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): request Windows runner breakaway only when the job allows it
chengzhi-c991062d477da
diff --git a/crates/host-core/Cargo.toml b/crates/host-core/Cargo.tomlindex b77102b9d..81fa0af42 100644--- a/crates/host-core/Cargo.toml+++ b/crates/host-core/Cargo.toml@@ -44,6 +44,7 @@ windows-sys = { version = "0.61.2", features = ["Win32_System_JobObjects","Win32_System_LibraryLoader","Win32_System_Registry",+ "Win32_System_Threading","Win32_UI_WindowsAndMessaging",] }diff --git a/crates/host-core/src/tools/mod.rs b/crates/host-core/src/tools/mod.rsindex a6bd3fc3e..f01a6381d 100644--- a/crates/host-core/src/tools/mod.rs+++ b/crates/host-core/src/tools/mod.rs@@ -45,16 +45,57 @@ pub const DEFAULT_BASH_TIMEOUT_MS: u64 = 60_000;pub const INTERNAL_TOOL_RUNNER_FLAG: &str = "--internal-tool-runner";// Windows inherits the parent process' Job Object unless the child is created// with CREATE_BREAKAWAY_FROM_JOB. The hidden runner is immediately assigned to-// its own kill-on-close job, so it must first leave any outer launcher job;-// otherwise terminating the runner job can terminate the whole Desktop tree.+// its own kill-on-close job, so leaving an outer launcher job keeps that job+// from becoming the runner's termination scope. The flag is only legal when the+// job the host is in grants JOB_OBJECT_LIMIT_BREAKAWAY_OK: `CreateProcess` fails+// the whole call with ERROR_ACCESS_DENIED otherwise.#[cfg(any(windows, test))]const WINDOWS_CREATE_NO_WINDOW: u32 = 0x0800_0000;#[cfg(any(windows, test))]const WINDOWS_CREATE_BREAKAWAY_FROM_JOB: u32 = 0x0100_0000;#[cfg(any(windows, test))]-const fn windows_tool_runner_creation_flags() -> u32 {- WINDOWS_CREATE_NO_WINDOW | WINDOWS_CREATE_BREAKAWAY_FROM_JOB+const fn windows_tool_runner_creation_flags(breakaway_allowed: bool) -> u32 {+ if breakaway_allowed {+ WINDOWS_CREATE_NO_WINDOW | WINDOWS_CREATE_BREAKAWAY_FROM_JOB+ } else {+ WINDOWS_CREATE_NO_WINDOW+ }+}++/// Whether the Job Object that contains this process grants breakaway.+///+/// Only the immediate job decides this; an ancestor in a nested chain that+/// withholds the grant leaves the child in that ancestor instead of failing the+/// call. A host that is not in a job never needs the flag, and one whose limits+/// cannot be read is treated as refusing it, because the host-owned job contains+/// the runner either way.+#[cfg(windows)]+fn windows_breakaway_allowed() -> bool {+ use windows_sys::Win32::System::JobObjects::{+ IsProcessInJob, JobObjectBasicLimitInformation, QueryInformationJobObject,+ JOBOBJECT_BASIC_LIMIT_INFORMATION, JOB_OBJECT_LIMIT_BREAKAWAY_OK,+ };+ use windows_sys::Win32::System::Threading::GetCurrentProcess;++ let mut in_job = 0;+ if unsafe { IsProcessInJob(GetCurrentProcess(), std::ptr::null_mut(), &mut in_job) } == 0+ || in_job == 0+ {+ return false;+ }+ let mut limits = JOBOBJECT_BASIC_LIMIT_INFORMATION::default();+ let mut returned = 0u32;+ let queried = unsafe {+ QueryInformationJobObject(+ std::ptr::null_mut(),+ JobObjectBasicLimitInformation,+ (&mut limits as *mut JOBOBJECT_BASIC_LIMIT_INFORMATION).cast(),+ std::mem::size_of::<JOBOBJECT_BASIC_LIMIT_INFORMATION>() as u32,+ &mut returned,+ )+ };+ queried != 0 && limits.LimitFlags & JOB_OBJECT_LIMIT_BREAKAWAY_OK != 0}const PIPE_DRAIN_TIMEOUT: Duration = Duration::from_millis(750);@@ -2635,7 +2676,9 @@ pub(crate) async fn spawn_tool_runner(#[cfg(unix)]command.process_group(0);#[cfg(windows)]- command.creation_flags(windows_tool_runner_creation_flags());+ command.creation_flags(windows_tool_runner_creation_flags(+ windows_breakaway_allowed(),+ ));let mut child = spawn_with_retries(&mut command).await?;let pid = child.id().unwrap_or_default();@@ -3338,16 +3381,72 @@ mod tests {}#[test]- fn windows_tool_runner_leaves_outer_job_before_owning_the_process_tree() {- assert_eq!(windows_tool_runner_creation_flags(), 0x0900_0000);- assert_ne!(- windows_tool_runner_creation_flags() & WINDOWS_CREATE_BREAKAWAY_FROM_JOB,- 0,+ fn windows_tool_runner_flags_follow_the_host_job_capability() {+ assert_eq!(+ windows_tool_runner_creation_flags(true),+ WINDOWS_CREATE_NO_WINDOW | WINDOWS_CREATE_BREAKAWAY_FROM_JOB,+ );+ // A job that withholds JOB_OBJECT_LIMIT_BREAKAWAY_OK rejects the+ // breakaway outright, so the flag must not be requested there.+ assert_eq!(+ windows_tool_runner_creation_flags(false),+ WINDOWS_CREATE_NO_WINDOW,+ );+ }++ #[cfg(windows)]+ #[tokio::test]+ async fn windows_bash_termination_does_not_reach_the_host_job() {+ // Whatever job the harness runs in, stopping a Bash command must stay+ // inside the job host-core created for it: a sibling in the harness job+ // must outlive the termination. That is the #1642 contract, where runner+ // cleanup took the Desktop tree with it. Under `cargo test` the harness+ // job withholds JOB_OBJECT_LIMIT_BREAKAWAY_OK, so this also covers the+ // fallback where the runner cannot leave that job.+ use std::os::windows::process::CommandExt;++ let mut sibling = std::process::Command::new("cmd")+ .args(["/c", "ping -n 60 127.0.0.1 >NUL"])+ .creation_flags(WINDOWS_CREATE_NO_WINDOW)+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn()+ .expect("host-job sibling must start");++ let dir = tempfile::tempdir().unwrap();+ let dialect = shell::catalog(None)+ .effective+ .and_then(|shell| shell::dialect_for_id(&shell.id))+ .unwrap_or("posix");+ let command = match dialect {+ "powershell" => "Start-Sleep -Seconds 30",+ "cmd" => "ping -n 31 127.0.0.1 >NUL",+ _ => "sleep 30",+ };+ let result = execute_tool(+ Some(dir.path()),+ None,+ "Bash",+ &serde_json::json!({ "command": command }),+ 1_000,+ )+ .await;+ // Without a real termination the sibling check below would be vacuous.+ assert_eq!(+ result.error_code.as_deref(),+ Some("TOOL_TIMEOUT"),+ "a command in a job without breakaway must still run: {:?}",+ result.content,);- assert_ne!(- windows_tool_runner_creation_flags() & WINDOWS_CREATE_NO_WINDOW,- 0,++ tokio::time::sleep(Duration::from_millis(500)).await;+ assert!(+ sibling.try_wait().unwrap().is_none(),+ "stopping a Bash command must not terminate the host's job",);+ let _ = sibling.kill();+ let _ = sibling.wait();}#[tokio::test]diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.mdindex c69885792..b1b1c7f67 100644--- a/docs/spec/03-runtime/03-tools-and-permissions.md+++ b/docs/spec/03-runtime/03-tools-and-permissions.md@@ -458,7 +458,7 @@ or executable path hash is accepted as shell identity.2. Unix: well-known locations (`/bin/bash`, `/usr/bin/bash`, `/usr/local/bin/bash`, Homebrew), then PATH3. Windows: `bash.exe` from Git for Windows — derived from the `git` on PATH, then standard install dirs, then PATH excluding the WSL launcher in `System32`-- Unix invokes `bash -lc` (login shell keeps profile PATH for Finder/Dock launches); Windows invokes `bash -c` with `CREATE_NO_WINDOW`. The hidden host-core runner that owns the command tree is created with both `CREATE_NO_WINDOW` and `CREATE_BREAKAWAY_FROM_JOB`, then assigned to its own kill-on-close Job Object. This keeps a launcher or policy Job around the Desktop process from becoming the runner's termination scope. If Windows refuses the breakaway, runner creation fails closed; the shell itself stays inside the host-owned job so timeout and abort still terminate the complete command tree.+- Unix invokes `bash -lc` (login shell keeps profile PATH for Finder/Dock launches); Windows invokes `bash -c` with `CREATE_NO_WINDOW`. The hidden host-core runner that owns the command tree is created with `CREATE_NO_WINDOW` and, only when the job that contains the host grants `JOB_OBJECT_LIMIT_BREAKAWAY_OK`, with `CREATE_BREAKAWAY_FROM_JOB`; it is then assigned to its own kill-on-close Job Object. Requesting the breakaway from the host's own job keeps a launcher or policy Job around the Desktop process from becoming the runner's termination scope. When that job withholds `JOB_OBJECT_LIMIT_BREAKAWAY_OK`, the flag is omitted and the runner joins the host-owned job as a nested job, because `CreateProcess` fails with `ERROR_ACCESS_DENIED` for a breakaway the job forbids; the shell itself stays inside the host-owned job either way, so timeout and abort still terminate the complete command tree.- On Unix, the Bash tool additionally probes the user's login shell for itsPATH — `$SHELL` (fallback `/bin/zsh` → `/bin/bash` → `/bin/sh`) with`-lic 'printf %s "$PATH"'`, 5s-bounded, cached per process — and injects itdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 89654cfdd..e27fb5ed1 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -7784,10 +7784,12 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.descendants, output events, audit, and turn state after the shutdown grace.- **Expected**: The process group/job tree is terminated, no descendant remains,no later output arrives, the turn returns `TURN_ABORTED`, and the workspace is- not rolled back automatically. On Windows, the hidden runner first breaks- away from any parent Job Object before entering its own kill-on-close job; a- denied breakaway fails the tool closed instead of allowing the Desktop tree- to become the termination scope.+ not rolled back automatically. On Windows, the hidden runner requests+ `CREATE_BREAKAWAY_FROM_JOB` only when the job that contains the host grants+ `JOB_OBJECT_LIMIT_BREAKAWAY_OK`, then enters its own kill-on-close job. A host+ job that withholds breakaway leaves the runner in a nested job instead of+ failing the tool closed; termination is still scoped to that job, so the+ Desktop tree never becomes the termination scope.- **Specs linked**: `03-runtime/03-tools-and-permissions.md`,`03-runtime/07-process-model.md`, `03-runtime/08-error-codes.md`,`03-runtime/16-tool-result-limits.md`, `05-security/01-security.md`, ADR 0054diff --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 821ffbdb4..0eab90abf 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@@ -365,7 +365,7 @@ tool/protocol 名称,请求中单独携带固定的 shell ID。2. Unix:众所周知的位置(`/bin/bash`、`/usr/bin/bash`、`/usr/local/bin/bash`、Homebrew),然后是 PATH3. Windows:来自 Git 的 Windows 的 `bash.exe` — 派生自 PATH 上的 `git`,然后是标准安装目录,然后是排除 `System32` 中的 WSL 启动器的 PATH-- Unix 调用 `bash -lc`(登录 shell 为 Finder/Dock 启动保留配置文件路径);Windows 使用 `CREATE_NO_WINDOW` 调用 `bash -c`。负责拥有命令树的隐藏 host-core runner 还会使用 `CREATE_BREAKAWAY_FROM_JOB` 创建,然后被分配到自己的 kill-on-close Job Object 中。这样,启动器或策略 Job 不会成为 Desktop 进程的终止范围。如果 Windows 拒绝 breakaway,runner 会安全失败而不启动命令;shell 本身仍留在 host 拥有的 job 中,因此超时和中止仍会终止完整的命令树。+- Unix 调用 `bash -lc`(登录 shell 为 Finder/Dock 启动保留配置文件路径);Windows 使用 `CREATE_NO_WINDOW` 调用 `bash -c`。负责拥有命令树的隐藏 host-core runner 会使用 `CREATE_NO_WINDOW` 创建,并且仅当宿主所在的 job 授予 `JOB_OBJECT_LIMIT_BREAKAWAY_OK` 时才加上 `CREATE_BREAKAWAY_FROM_JOB`,然后被分配到自己的 kill-on-close Job Object 中。按宿主自身 job 的能力请求 breakaway,使启动器或策略 Job 不会成为 Desktop 进程的终止范围。当该 job 未授予 `JOB_OBJECT_LIMIT_BREAKAWAY_OK` 时,`CreateProcess` 会以 `ERROR_ACCESS_DENIED` 拒绝该 breakaway,因此不再带上该标志,runner 改以嵌套 job 的形式加入 host 拥有的 job;无论哪种情况,shell 本身都留在这个 host 拥有的 job 中,所以超时和中止仍会终止完整的命令树。- 在 Unix 上,Bash 工具另外探测用户的登录 shell 以获取其信息路径 — `$SHELL`(回退 `/bin/zsh` → `/bin/bash` → `/bin/sh`)`-lic 'printf %s "$PATH"'`,5 秒范围内,每个进程缓存 — 并注入它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 09968e7ad..245d7868d 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@@ -4517,9 +4517,11 @@ eleven-tool-round desktop paths are verified by后代、输出事件、审核以及关闭宽限后的状态。- **预期**:进程 group/job 树终止,没有后代保留,没有后续输出到达,本轮返回 `TURN_ABORTED`,工作空间为- 不会自动回滚。在 Windows 上,隐藏 runner 会先脱离任何父 Job Object,- 再进入自己的 kill-on-close job;如果系统拒绝 breakaway,工具会安全失败,- 不会让 Desktop 进程树成为终止范围。+ 不会自动回滚。在 Windows 上,隐藏 runner 仅当宿主所在的 job 授予+ `JOB_OBJECT_LIMIT_BREAKAWAY_OK` 时才请求 `CREATE_BREAKAWAY_FROM_JOB`,+ 然后进入自己的 kill-on-close job;若宿主 job 未授予 breakaway,runner+ 改以嵌套 job 运行,而不是让工具安全失败;终止范围仍限定在该 job,+ 因此 Desktop 进程树不会成为终止范围。- **链接规格**:`03-runtime/03-tools-and-permissions.md`,`03-runtime/07-process-model.md`、`03-runtime/08-error-codes.md`、`03-runtime/16-tool-result-limits.md`、`05-security/01-security.md`、ADR 0054