Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
31w: on Windows, a killed kwnt.exe takes its docker and where helpers with it (#943)
Oleksandr Ivanchenkod2d645bf9d88
diff --git a/src/drivers/cli.rs b/src/drivers/cli.rsindex 19119275..ac3c0f49 100644--- a/src/drivers/cli.rs+++ b/src/drivers/cli.rs@@ -164,16 +164,14 @@ pub fn forget_cli_binaries() {fn find_cli_binary_uncached(name: &str) -> Option<String> {use std::os::windows::process::CommandExt;// `where` lists PATH hits with every PATHEXT extension; an .exe beats a .cmd shim- let on_path: Vec<String> = std::process::Command::new("where")- .arg(name)- .stdin(Stdio::null())- .stderr(Stdio::null())- .creation_flags(CREATE_NO_WINDOW)- .output()- .ok()- .filter(|o| o.status.success())- .map(|o| String::from_utf8_lossy(&o.stdout).lines().map(|l| l.trim().to_string()).filter(|l| !l.is_empty()).collect())- .unwrap_or_default();+ // held by kwnt's helper job, so it ends with kwnt.exe (stderr is captured and dropped)+ let on_path: Vec<String> = crate::helper_process::output_blocking(+ std::process::Command::new("where").arg(name).creation_flags(CREATE_NO_WINDOW),+ )+ .ok()+ .filter(|o| o.status.success())+ .map(|o| String::from_utf8_lossy(&o.stdout).lines().map(|l| l.trim().to_string()).filter(|l| !l.is_empty()).collect())+ .unwrap_or_default();let env = |k: &str| std::env::var_os(k).map(std::path::PathBuf::from);windows_cli_candidates(name, &on_path, env("USERPROFILE"), env("APPDATA")).into_iter()diff --git a/src/drivers/win_job.rs b/src/drivers/win_job.rsindex 0b1039f0..beb34449 100644--- a/src/drivers/win_job.rs+++ b/src/drivers/win_job.rs@@ -1,4 +1,5 @@-//! Windows only: one Job Object per bot turn, so Stop ends the whole process tree (plan decision 3).+//! Windows only: one Job Object per bot turn, so Stop ends the whole process tree (plan decision 3),+//! and one for kwnt's own helper commands, so they end with kwnt.exe ([`hold_helper`]).//!//! Windows has no process groups. Every process a job member starts joins the same job, so//! terminating the job ends the CLI or bot command, its children and their children. The job is@@ -20,22 +21,25 @@ unsafe impl Sync for Job {}impl Job {/// A new kill-on-close job holding `process` (a raw process handle), or None if Windows refused.pub(crate) fn holding(process: *mut c_void) -> Option<Self> {- // SAFETY: plain Win32 calls on handles this function owns or was given; the info struct- // lives on the stack for the duration of the call and its size is passed with it.- unsafe {- let handle = CreateJobObjectW(std::ptr::null(), std::ptr::null());- if handle.is_null() {- return None;- }- let job = Job(handle);- if !job.set_kill_on_close(true) {- return None;- }- if AssignProcessToJobObject(job.0, process as HANDLE) == 0 {- return None;- }- Some(job)+ let job = Self::kill_on_close()?;+ job.assign(process).then_some(job)+ }++ /// A new, empty kill-on-close job, or None if Windows refused.+ fn kill_on_close() -> Option<Self> {+ // SAFETY: a plain Win32 call; the handle it returns is owned by the Job from here on+ let handle = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };+ if handle.is_null() {+ return None;}+ let job = Job(handle);+ job.set_kill_on_close(true).then_some(job)+ }++ /// Puts `process` (a raw process handle) in the job. False if Windows refused.+ fn assign(&self, process: *mut c_void) -> bool {+ // SAFETY: a valid job handle owned by self and a process handle the caller holds+ unsafe { AssignProcessToJobObject(self.0, process as HANDLE) != 0 }}fn set_kill_on_close(&self, on: bool) -> bool {@@ -77,6 +81,20 @@ impl Drop for Job {}}+/// kwnt's own helper commands (docker, where): one kill-on-close job, made on first use and never+/// closed by kwnt. Its only handle closes when kwnt.exe exits, however it ends (Task Manager,+/// `Stop-Process -Force`, a crash), and Windows then ends every helper still in it. tokio's+/// `kill_on_drop` covers only an orderly exit. Bot turns are not here: each has its own job+/// ([`Job::holding`]), which Stop ends and [`Job::release`] can let go.+static HELPERS: std::sync::OnceLock<Option<Job>> = std::sync::OnceLock::new();++/// Puts a helper process kwnt just started in [`HELPERS`]. False if Windows refused (the helper+/// then runs as before, ended only by `kill_on_drop`). Works when kwnt itself is inside a job (the+/// desktop app, a CI runner): Windows 8 and later nest the new job under it.+pub(crate) fn hold_helper(process: *mut c_void) -> bool {+ HELPERS.get_or_init(Job::kill_on_close).as_ref().is_some_and(|job| job.assign(process))+}+/// Fallback when there is no job: `taskkill /T /F` ends `pid` and every process it started.pub(crate) fn taskkill_tree(pid: u32) {let _ = std::process::Command::new("taskkill")diff --git a/src/helper_process.rs b/src/helper_process.rsnew file mode 100644index 00000000..43da4b18--- /dev/null+++ b/src/helper_process.rs@@ -0,0 +1,94 @@+//! kwnt's own short helper commands (`docker`, `where`), run to the end like `Command::output`.+//!+//! On Windows each one is put in a kill-on-close Job Object that kwnt holds for its whole life+//! ([`crate::drivers::win_job::hold_helper`]), so a helper still running when kwnt.exe is killed+//! outright ends with it. Windows never ends or re-parents orphans, and tokio's `kill_on_drop`+//! doesn't run on a forced kill, so a `docker` stuck on a slow daemon would otherwise be left+//! behind with its console. On Mac and Linux these are plain `output()` and `status()`.++use std::io;+use std::process::{ExitStatus, Output};++/// `cmd.output().await`, with the helper held by kwnt's helper job on Windows. As with `output()`,+/// stdin is null and stdout and stderr are captured; `kill_on_drop` and the rest of `cmd` apply.+pub(crate) async fn output(cmd: &mut tokio::process::Command) -> io::Result<Output> {+ #[cfg(windows)]+ {+ use std::process::Stdio;+ let child = cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()?;+ if let Some(handle) = child.raw_handle() {+ crate::drivers::win_job::hold_helper(handle);+ }+ child.wait_with_output().await+ }+ #[cfg(not(windows))]+ {+ cmd.output().await+ }+}++/// `cmd.output()` (blocking), with the helper held by kwnt's helper job. As with `output()`, stdin+/// is null and stdout and stderr are captured. Windows only: its one caller is the `where` lookup.+#[cfg(windows)]+pub(crate) fn output_blocking(cmd: &mut std::process::Command) -> io::Result<Output> {+ use std::os::windows::io::AsRawHandle;+ use std::process::Stdio;+ let child = cmd.stdin(Stdio::null()).stdout(Stdio::piped()).stderr(Stdio::piped()).spawn()?;+ crate::drivers::win_job::hold_helper(child.as_raw_handle());+ child.wait_with_output()+}++/// `cmd.status()` (blocking), with the helper held by kwnt's helper job on Windows. The stdio+/// `cmd` sets is kept; unset, it is inherited, as with `status()`.+pub(crate) fn status_blocking(cmd: &mut std::process::Command) -> io::Result<ExitStatus> {+ #[cfg(windows)]+ {+ use std::os::windows::io::AsRawHandle;+ let mut child = cmd.spawn()?;+ crate::drivers::win_job::hold_helper(child.as_raw_handle());+ child.wait()+ }+ #[cfg(not(windows))]+ {+ cmd.status()+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn echo_hi() -> (&'static str, Vec<&'static str>) {+ if cfg!(windows) {+ ("cmd", vec!["/c", "echo hi& echo err 1>&2& exit /b 3"])+ } else {+ ("sh", vec!["-c", "echo hi; echo err >&2; exit 3"])+ }+ }++ #[tokio::test]+ async fn output_captures_stdout_stderr_and_the_exit_code() {+ let (program, args) = echo_hi();+ let out = output(tokio::process::Command::new(program).args(&args).kill_on_drop(true)).await.unwrap();+ assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "hi");+ assert_eq!(String::from_utf8_lossy(&out.stderr).trim(), "err");+ assert_eq!(out.status.code(), Some(3));+ }++ #[test]+ fn the_blocking_ones_match_output_and_status() {+ let (program, args) = echo_hi();+ #[cfg(windows)]+ {+ let out = output_blocking(std::process::Command::new(program).args(&args)).unwrap();+ assert_eq!(String::from_utf8_lossy(&out.stdout).trim(), "hi");+ assert_eq!(String::from_utf8_lossy(&out.stderr).trim(), "err");+ assert_eq!(out.status.code(), Some(3));+ }+ let status = status_blocking(+ std::process::Command::new(program).args(&args).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null()),+ )+ .unwrap();+ assert_eq!(status.code(), Some(3));+ }+}diff --git a/src/lib.rs b/src/lib.rsindex 7c5ff5c4..21b7ca39 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -9,6 +9,7 @@ pub mod documents;pub mod drivers;pub mod embedded;pub mod fsx;+pub(crate) mod helper_process;pub mod import;pub mod mcp;pub mod parallel;diff --git a/src/parallel/harness.rs b/src/parallel/harness.rsindex 02113b97..8b6ce863 100644--- a/src/parallel/harness.rs+++ b/src/parallel/harness.rs@@ -159,7 +159,8 @@ struct Out {}async fn docker(args: &[String], limit: Duration) -> Result<Out, String> {- let run = Command::new("docker").args(args).kill_on_drop(true).output();+ let mut cmd = Command::new("docker");+ let run = crate::helper_process::output(cmd.args(args).kill_on_drop(true));match timeout(limit, run).await {Err(_) => Err(format!("docker {} timed out", args.first().map(String::as_str).unwrap_or(""))),Ok(Err(e)) => Err(e.to_string()),diff --git a/src/sandbox/agent_vm/mod.rs b/src/sandbox/agent_vm/mod.rsindex c1a245ae..89bf204e 100644--- a/src/sandbox/agent_vm/mod.rs+++ b/src/sandbox/agent_vm/mod.rs@@ -576,12 +576,13 @@ impl AgentVm {/// Whether the image is in Docker already (blocking `docker image inspect`, a few ms).fn image_present_sync(&self) -> bool {- let ok = std::process::Command::new("docker")- .args(["image", "inspect", "--format", "{{.Id}}", &self.image()])- .stdout(std::process::Stdio::null())- .stderr(std::process::Stdio::null())- .status()- .is_ok_and(|s| s.success());+ let ok = crate::helper_process::status_blocking(+ std::process::Command::new("docker")+ .args(["image", "inspect", "--format", "{{.Id}}", &self.image()])+ .stdout(std::process::Stdio::null())+ .stderr(std::process::Stdio::null()),+ )+ .is_ok_and(|s| s.success());if ok {*self.image.lock().unwrap() = ImageState::Ready;}@@ -610,16 +611,13 @@ impl AgentVm {async fn start_container(&self, bot_id: &str, workdir: &Path, home: &Path, run_dir: &Path) -> Result<String, Refusal> {let name = Self::container_name(bot_id, workdir);let fail = |why: String| Refusal::new(codes::CONTAINER_FAILED, why);- let running = Command::new("docker")- .args(["inspect", "-f", "{{.State.Running}}", &name])- .kill_on_drop(true)- .output()+ let running = crate::helper_process::output(Command::new("docker").args(["inspect", "-f", "{{.State.Running}}", &name]).kill_on_drop(true)).await.is_ok_and(|o| String::from_utf8_lossy(&o.stdout).trim() == "true");if running {return Ok(name);}- let _ = Command::new("docker").args(["rm", "-f", &name]).kill_on_drop(true).output().await;+ let _ = crate::helper_process::output(Command::new("docker").args(["rm", "-f", &name]).kill_on_drop(true)).await;for d in [home, run_dir] {std::fs::create_dir_all(d).map_err(|e| fail(format!("Couldn't prepare the bot's computer folders: {e}")))?;set_private(d);@@ -628,10 +626,7 @@ impl AgentVm {prepare_ro_hooks(&ro_hooks).map_err(|e| fail(format!("Couldn't prepare the bot's computer folders: {e}")))?;let mounts = Mounts::new(workdir, home, run_dir, &ro_hooks)?;let args = run_args(&name, &self.root_label(), &mounts, &self.image(), host_ids(), self.limits.memory_mb);- let out = Command::new("docker")- .args(&args)- .kill_on_drop(true)- .output()+ let out = crate::helper_process::output(Command::new("docker").args(&args).kill_on_drop(true)).await.map_err(|e| fail(format!("Docker didn't start: {e}")))?;if !out.status.success() {@@ -666,7 +661,7 @@ impl AgentVm {}map.remove(container);}- match Command::new("docker").args(["rm", "-f", container]).kill_on_drop(true).output().await {+ match crate::helper_process::output(Command::new("docker").args(["rm", "-f", container]).kill_on_drop(true)).await {Ok(o) if o.status.success() => {}Ok(o) => tracing::warn!(container, error = %String::from_utf8_lossy(&o.stderr).trim(), "couldn't remove an agent container after its last turn"),Err(e) => tracing::warn!(container, error = %e, "couldn't remove an agent container after its last turn"),@@ -702,18 +697,19 @@ impl AgentVm {/// Removes this kwnt's agent containers whose name `pick` accepts.pub async fn remove_containers(&self, pick: impl Fn(&str) -> bool) {- let Ok(out) = Command::new("docker")- .args(["ps", "-a", "--filter", "label=kwnt.agent=1", "--filter"])- .arg(format!("label=kwnt.root={}", self.root_label()))- .args(["--format", "{{.Names}}"])- .kill_on_drop(true)- .output()- .await+ let Ok(out) = crate::helper_process::output(+ Command::new("docker")+ .args(["ps", "-a", "--filter", "label=kwnt.agent=1", "--filter"])+ .arg(format!("label=kwnt.root={}", self.root_label()))+ .args(["--format", "{{.Names}}"])+ .kill_on_drop(true),+ )+ .awaitelse {return;};for name in String::from_utf8_lossy(&out.stdout).lines().map(str::trim).filter(|n| n.starts_with("kwnt-agent-") && pick(n)) {- let _ = Command::new("docker").args(["rm", "-f", name]).kill_on_drop(true).output().await;+ let _ = crate::helper_process::output(Command::new("docker").args(["rm", "-f", name]).kill_on_drop(true)).await;}}}@@ -1175,7 +1171,7 @@ impl Drop for IsolatedTurn {let script = format!("p=$(cat {f} 2>/dev/null) && kill -TERM -- -$p 2>/dev/null; rm -f {f}", f = self.pid_file());if let Ok(rt) = tokio::runtime::Handle::try_current() {rt.spawn(async move {- let _ = Command::new("docker").args(["exec", &container, "sh", "-c", &script]).kill_on_drop(true).output().await;+ let _ = crate::helper_process::output(Command::new("docker").args(["exec", &container, "sh", "-c", &script]).kill_on_drop(true)).await;if last {vm.end_container(&container).await;}diff --git a/src/sandbox/browser_downloads.rs b/src/sandbox/browser_downloads.rsindex cb43a8d9..58e74b5d 100644--- a/src/sandbox/browser_downloads.rs+++ b/src/sandbox/browser_downloads.rs@@ -991,14 +991,18 @@ async fn copy_out_of_container(container: &str, staging: &Path, guid: &str) -> R/// pipe, so the file stayed empty and the whole download sat in memory instead. The child is/// killed if this future is dropped (the copy-out's time limit).async fn run_into_file(mut command: tokio::process::Command, file: std::fs::File) -> std::io::Result<std::process::Output> {- command+ let child = command.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::from(file)).stderr(std::process::Stdio::piped()).kill_on_drop(true)- .spawn()?- .wait_with_output()- .await+ .spawn()?;+ // held by kwnt's helper job, so the `docker exec` ends with kwnt.exe (Windows)+ #[cfg(windows)]+ if let Some(handle) = child.raw_handle() {+ crate::drivers::win_job::hold_helper(handle);+ }+ child.wait_with_output().await}/// A download finished inside kwant's browser container: copy it out into staging, land it indiff --git a/src/sandbox/manager.rs b/src/sandbox/manager.rsindex 58fb6244..1fa8be3a 100644--- a/src/sandbox/manager.rs+++ b/src/sandbox/manager.rs@@ -25,10 +25,7 @@ pub const EXECUTOR_IMAGE: &str = "kwnt-executor:v1";/// True when the image `tag` is already built.pub async fn image_exists(tag: &str) -> bool {- Command::new("docker")- .args(["image", "inspect", tag])- .kill_on_drop(true)- .output()+ crate::helper_process::output(Command::new("docker").args(["image", "inspect", tag]).kill_on_drop(true)).await.is_ok_and(|out| out.status.success())}@@ -50,7 +47,7 @@ pub async fn ensure_image(tag: &str, files: &[(&str, &str)], build_args: &[(&strfor (k, v) in build_args {cmd.arg("--build-arg").arg(format!("{k}={v}"));}- cmd.arg(&build).kill_on_drop(true).output().await+ crate::helper_process::output(cmd.arg(&build).kill_on_drop(true)).await}.await;let _ = tokio::fs::remove_dir_all(&build).await;@@ -109,7 +106,7 @@ impl SandboxManager {matches!(timeout(Duration::from_secs(3),- Command::new("docker").arg("version").kill_on_drop(true).output(),+ crate::helper_process::output(Command::new("docker").arg("version").kill_on_drop(true)),).await,Ok(Ok(output)) if output.status.success())@@ -133,10 +130,10 @@ impl SandboxManager {let mut lock = self.sandboxes.lock().await;if let Some(existing) = lock.get(team_id) {// Check if still running- let inspect = Command::new("docker")- .args(["inspect", "-f", "{{.State.Running}}", &existing.container_name])- .output()- .await;+ let inspect = crate::helper_process::output(+ Command::new("docker").args(["inspect", "-f", "{{.State.Running}}", &existing.container_name]),+ )+ .await;if let Ok(out) = inspect {if String::from_utf8_lossy(&out.stdout).trim() == "true" {return Ok(existing.clone());@@ -149,27 +146,25 @@ impl SandboxManager {let container_name = format!("kwnt-executor-{}-{}", safe_name, id_suffix);// Remove old container if exists- let _ = Command::new("docker").args(["rm", "-f", &container_name]).output().await;+ let _ = crate::helper_process::output(Command::new("docker").args(["rm", "-f", &container_name])).await;let ws_str = workspace_dir.to_string_lossy().to_string();ensure_executor_image().await?;- let run_res = Command::new("docker")- .args([- "run",- "-d",- "--name",- &container_name,- "--cpus=2.0",- "--memory=1536m",- "-v",- &format!("{}:/workspace:rw", ws_str),- "-w",- "/workspace",- EXECUTOR_IMAGE,- ])- .output()- .await- .map_err(|e| SandboxError::StartFailed(e.to_string()))?;+ let run_res = crate::helper_process::output(Command::new("docker").args([+ "run",+ "-d",+ "--name",+ &container_name,+ "--cpus=2.0",+ "--memory=1536m",+ "-v",+ &format!("{}:/workspace:rw", ws_str),+ "-w",+ "/workspace",+ EXECUTOR_IMAGE,+ ]))+ .await+ .map_err(|e| SandboxError::StartFailed(e.to_string()))?;if !run_res.status.success() {let err = String::from_utf8_lossy(&run_res.stderr);@@ -197,7 +192,7 @@ impl SandboxManager {let mut cmd = Command::new("docker");cmd.args(["exec", "-w", "/workspace", container_name, "bash", "-c", command_str]);- let output = timeout(Duration::from_secs(timeout_secs), cmd.output())+ let output = timeout(Duration::from_secs(timeout_secs), crate::helper_process::output(&mut cmd)).await.map_err(|_| SandboxError::Timeout)?.map_err(|e| SandboxError::ExecFailed(e.to_string()))?;@@ -227,10 +222,7 @@ impl SandboxManager {pub async fn stop_sandbox(&self, team_id: &str) -> Result<(), SandboxError> {let mut lock = self.sandboxes.lock().await;if let Some(active) = lock.remove(team_id) {- let _ = Command::new("docker")- .args(["rm", "-f", &active.container_name])- .output()- .await;+ let _ = crate::helper_process::output(Command::new("docker").args(["rm", "-f", &active.container_name])).await;}Ok(())}diff --git a/src/sandbox/service.rs b/src/sandbox/service.rsindex bf706014..87a18ca4 100644--- a/src/sandbox/service.rs+++ b/src/sandbox/service.rs@@ -346,8 +346,8 @@ impl BrowserService {}pub(crate) async fn docker(args: &[&str], seconds: u64) -> Result<String, BrowserError> {- let out = timeout(Duration::from_secs(seconds), Command::new("docker")- .args(args).kill_on_drop(true).output()).await+ let out = timeout(Duration::from_secs(seconds),+ crate::helper_process::output(Command::new("docker").args(args).kill_on_drop(true))).await.map_err(|_| BrowserError::Timeout)?.map_err(|e| BrowserError::Http(format!("docker: {e}")))?;// "docker:" marks it as Docker's failure, not the browser's (see [`outage`])diff --git a/tests/shell_stop_tree_test.rs b/tests/shell_stop_tree_test.rsindex ce7a26d4..09baeea9 100644--- a/tests/shell_stop_tree_test.rs+++ b/tests/shell_stop_tree_test.rs@@ -1,7 +1,7 @@//! Stop ends a bot command's whole process tree (Windows plan decision 3: a Job Object per turn;//! on Mac and Linux, the process group). The command starts a child bash that starts a grandchild;//! both keep appending to a file until they are gone. Runs on every OS; on windows-latest it is the-//! check that the Job Object holds the tree.+//! check that the Job Object holds the tree. The `killed_kwnt` test at the end is Windows only.use kwnt::tools::shell::execute_shell;use serde_json::json;use std::path::Path;@@ -42,3 +42,114 @@ async fn stop_ends_the_child_and_the_grandchild() {assert_eq!(size(&child), c, "the child kept running after Stop");assert_eq!(size(&grandchild), g, "the grandchild kept running after Stop");}++/// Windows only: kwnt.exe killed outright (Task Manager, `Stop-Process -Force`, a crash) takes its+/// own helper commands with it. Here the helper is the `docker ps` the browser-container reaper+/// runs at startup (serve.rs), the docker.exe that outlived kwnt.exe in the 0.9.33 release smoke.+/// A fake `docker.exe` keeps appending to a file for two minutes; once kwnt.exe is terminated, the+/// file must stop growing. No real Docker is needed.+///+/// The fake sits next to a copy of kwnt.exe, and that copy is the one started. Windows looks for a+/// program in the starting program's own folder first, then in System32, and only then on PATH.+/// GitHub's Windows runners put the real docker.exe in System32, so a fake that is only first on+/// PATH is never reached: kwnt.exe runs the real docker instead and the fake never writes.+#[cfg(windows)]+mod killed_kwnt {+ use super::size;+ use std::process::{Command, Stdio};+ use std::time::{Duration, Instant};+ use tempfile::tempdir;++ const FAKE_DOCKER: &str = r#"+use std::io::Write;+fn main() {+ let log = std::env::var_os("KWNT_TEST_FAKE_DOCKER_LOG").expect("KWNT_TEST_FAKE_DOCKER_LOG");+ let args: Vec<String> = std::env::args().skip(1).collect();+ for _ in 0..1200 {+ if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&log) {+ let _ = writeln!(f, "{} {}", std::process::id(), args.join(" "));+ }+ std::thread::sleep(std::time::Duration::from_millis(100));+ }+}+"#;++ #[test]+ fn a_killed_kwnt_takes_its_docker_helper_with_it() {+ let tmp = tempdir().unwrap();+ let (bin, data) = (tmp.path().join("bin"), tmp.path().join("data"));+ std::fs::create_dir_all(&bin).unwrap();+ std::fs::create_dir_all(&data).unwrap();+ let src = tmp.path().join("fake_docker.rs");+ std::fs::write(&src, FAKE_DOCKER).unwrap();+ let built = Command::new("rustc")+ .args(["--edition", "2021", "-o"])+ .arg(bin.join("docker.exe"))+ .arg(&src)+ .output()+ .expect("rustc runs");+ assert!(built.status.success(), "couldn't build the fake docker.exe: {}", String::from_utf8_lossy(&built.stderr));++ // kwnt.exe's own folder is searched before System32 (see above): run a copy from `bin`+ let exe = bin.join("kwnt.exe");+ std::fs::copy(env!("CARGO_BIN_EXE_kwnt"), &exe).expect("copy kwnt.exe next to the fake docker.exe");++ let log = tmp.path().join("docker.log");+ let port = std::net::TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port();+ let path = std::env::join_paths(+ std::iter::once(bin.clone()).chain(std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default())),+ )+ .unwrap();+ let (out, err) = (tmp.path().join("kwnt.out"), tmp.path().join("kwnt.err"));+ let mut kwnt = Command::new(&exe)+ .args(["serve", "--host", "127.0.0.1", "--port", &port.to_string(), "--no-laya"])+ .env("KWNT_DATA_DIR", &data)+ .env("PATH", &path)+ .env("KWNT_TEST_FAKE_DOCKER_LOG", &log)+ .stdin(Stdio::null())+ .stdout(std::fs::File::create(&out).unwrap())+ .stderr(std::fs::File::create(&err).unwrap())+ .spawn()+ .unwrap();++ // kwnt.exe is up and its docker helper is running: the file grows+ let started = Instant::now();+ while size(&log) == 0 && started.elapsed() < Duration::from_secs(90) {+ if let Ok(Some(status)) = kwnt.try_wait() {+ panic!("kwnt.exe exited ({status}) before it ran docker: {}", std::fs::read_to_string(&err).unwrap_or_default());+ }+ std::thread::sleep(Duration::from_millis(100));+ }+ if size(&log) == 0 {+ let _ = kwnt.kill();+ panic!(+ "kwnt.exe never ran the fake docker in 90 s.\nstdout: {}\nstderr: {}",+ std::fs::read_to_string(&out).unwrap_or_default(),+ std::fs::read_to_string(&err).unwrap_or_default()+ );+ }++ // Killed outright: TerminateProcess, so none of kwnt's own cleanup runs+ kwnt.kill().unwrap();+ kwnt.wait().unwrap();+ std::thread::sleep(Duration::from_secs(1));+ let before = size(&log);+ std::thread::sleep(Duration::from_secs(2));+ let after = size(&log);+ if after != before {+ // don't leave it running on the machine+ let lines = std::fs::read_to_string(&log).unwrap_or_default();+ let mut pids: Vec<&str> = lines.lines().filter_map(|l| l.split(' ').next()).collect();+ pids.sort_unstable();+ pids.dedup();+ for pid in &pids {+ let _ = Command::new("taskkill").args(["/F", "/PID", pid]).stdout(Stdio::null()).stderr(Stdio::null()).status();+ }+ panic!(+ "kwnt.exe's docker helper (pid {}) kept running after kwnt.exe was killed; it ran: {}",+ pids.join(", "),+ lines.lines().last().unwrap_or("")+ );+ }+ }+}