Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
fix(windows): uninstall and host remove leave no driver or driver.log behind (CUA-1749) (#5289)
Francesco Bonacci0b5bf4704caf
diff --git a/apps/cua-spaces-desktop/packaging/installer.nsh b/apps/cua-spaces-desktop/packaging/installer.nshindex 598fa8a391..d0fecba16b 100644--- a/apps/cua-spaces-desktop/packaging/installer.nsh+++ b/apps/cua-spaces-desktop/packaging/installer.nsh@@ -112,10 +112,26 @@ Var pidnsExec::Exec '"$SYSDIR\schtasks.exe" /Delete /TN "${CUA_HOST_TASK}" /F'Pop $0DeleteRegValue HKCU "Software\Microsoft\Windows\CurrentVersion\Run" "${CUA_HOST_RUN_NAME}"+ ; The driver, and the conhost/cmd.exe that runs it and holds driver.log+ ; open (`>> driver.log`), with their children: killing only the driver+ ; left cmd.exe writing the log, so driver.log outlived the folder (CUA-1749).${if} $IsPowerShellAvailable == 0- nsExec::Exec `"$SYSDIR\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -NonInteractive -C "Get-CimInstance -ClassName Win32_Process | ? {$$_.Path -and $$_.Path -like '*\host\bin\cua-spacesd.exe'} | % { Stop-Process -Id $$_.ProcessId -Force -ErrorAction SilentlyContinue }"`+ nsExec::Exec /TIMEOUT=30000 `"$SYSDIR\WindowsPowerShell\v1.0\powershell.exe" -NoProfile -NonInteractive -C "for ($$i = 0; $$i -lt 40; $$i++) { $$h = @(Get-CimInstance -ClassName Win32_Process | ? {$$_.ProcessId -ne $$PID -and (($$_.Path -and $$_.Path -like '*\host\bin\cua-spacesd.exe') -or ($$_.CommandLine -and ($$_.CommandLine -like '*\host\bin\cua-spacesd.exe*' -or $$_.CommandLine -like '*\host\driver.log*')))}); if (-not $$h) { break }; $$h | % { taskkill.exe /T /F /PID $$_.ProcessId 2>&1 | Out-Null }; Start-Sleep -Milliseconds 250 }"`Pop $0${endIf}- Sleep 500- RMDir /r "$PROFILE\.cua\host"+ !insertmacro removeHostFolder+!macroend++; ~/.cua/host, retried for up to 10 s: Windows releases a killed process's+; files (driver.log above all) a moment after it exits.+!macro removeHostFolder+ StrCpy $1 0+ ${Do}+ Sleep 500+ RMDir /r "$PROFILE\.cua\host"+ ${IfNot} ${FileExists} "$PROFILE\.cua\host\*.*"+ ${Break}+ ${EndIf}+ IntOp $1 $1 + 1+ ${LoopUntil} $1 >= 20!macroenddiff --git a/apps/cua-spaces-desktop/test/uninstall.test.ts b/apps/cua-spaces-desktop/test/uninstall.test.tsindex e591d251b5..ebc9011100 100644--- a/apps/cua-spaces-desktop/test/uninstall.test.ts+++ b/apps/cua-spaces-desktop/test/uninstall.test.ts@@ -73,7 +73,7 @@ describe("the Windows installer and uninstaller", () => {// Of the user's files, only the host service's own folder goes.const code = nsh.split("\n").filter((l) => !l.trim().startsWith(";")).join("\n");const home = code.split("\n").filter((l) => /[\\/]\.cua\b|\$APPDATA|\$PROFILE|RMDir \/r/.test(l)).map((l) => l.trim());- expect(home).toEqual(['RMDir /r "$PROFILE\\.cua\\host"']);+ expect(home).toEqual(['RMDir /r "$PROFILE\\.cua\\host"', '${IfNot} ${FileExists} "$PROFILE\\.cua\\host\\*.*"']);});it("turn off unattended access on uninstall, not on upgrade (CUA-1740)", () => {@@ -96,7 +96,41 @@ describe("the Windows installer and uninstaller", () => {expect(host).toContain('/Delete /TN "${CUA_HOST_TASK}" /F');expect(host).toContain('DeleteRegValue HKCU "Software\\Microsoft\\Windows\\CurrentVersion\\Run" "${CUA_HOST_RUN_NAME}"');expect(host).toContain("\\host\\bin\\cua-spacesd.exe");- expect(host.trim().split("\n").at(-1)!.trim()).toBe('RMDir /r "$PROFILE\\.cua\\host"');+ expect(host.trim().split("\n").at(-1)!.trim()).toBe("!insertmacro removeHostFolder");+ });++ it("leave no driver.log behind: stop the process tree that holds it, then remove ~/.cua/host until it is gone (CUA-1749)", () => {+ // cua-host runs the driver as `conhost --headless cmd.exe /d /c … cua-spacesd.exe … >> driver.log`:+ // cmd.exe holds the log open, so it and its children are killed by command line, not only the driver.+ const service = readFileSync(path.join(root, "../../libs/cua/crates/cua-host/src/service.rs"), "utf8");+ expect(service).toContain(`format!("{system_root}\\\\System32\\\\cmd.exe")`);+ const host = macro("removeHostService");+ const kill = host.split("\n").find((l) => l.includes("Win32_Process"))!;+ expect(kill).toContain("$$_.CommandLine -like '*\\host\\driver.log*'");+ expect(kill).toContain("$$_.CommandLine -like '*\\host\\bin\\cua-spacesd.exe*'");+ expect(kill).toContain("taskkill.exe /T /F /PID");+ expect(kill).toContain("$$_.ProcessId -ne $$PID");+ // Stopped and waited for (bounded) until none is left, before the folder goes.+ expect(kill).toMatch(/for \(\$\$i = 0; \$\$i -lt \d+;/);+ expect(kill).toContain("if (-not $$h) { break }");+ expect(kill).toContain("Start-Sleep");+ // Killed after the task is ended and deleted (so it cannot restart), before the folder goes.+ expect(host.indexOf("/Delete /TN")).toBeLessThan(host.indexOf(kill));+ expect(host.indexOf(kill)).toBeLessThan(host.indexOf("!insertmacro removeHostFolder"));++ // The folder is removed again until it is gone, bounded (Windows frees a killed process's files late).+ const folder = macro("removeHostFolder").trim().split("\n").map((l) => l.trim());+ expect(folder).toEqual([+ "StrCpy $1 0",+ "${Do}",+ "Sleep 500",+ 'RMDir /r "$PROFILE\\.cua\\host"',+ '${IfNot} ${FileExists} "$PROFILE\\.cua\\host\\*.*"',+ "${Break}",+ "${EndIf}",+ "IntOp $1 $1 + 1",+ "${LoopUntil} $1 >= 20",+ ]);});it("name the task and logon entry cua-host creates", () => {diff --git a/libs/cua/crates/cua-host/src/host.rs b/libs/cua/crates/cua-host/src/host.rsindex f393662fc7..560f9e2b7e 100644--- a/libs/cua/crates/cua-host/src/host.rs+++ b/libs/cua/crates/cua-host/src/host.rs@@ -1679,7 +1679,7 @@ impl Host {note(e);}self.manager_for_config(&config).uninstall()?;- std::fs::remove_dir_all(&self.paths.dir)?;+ remove_dir_retrying(&self.paths.dir).await?;match relay_error {Some(e) => Err(Error::Relay(format!("removed locally, but the relay could not be told: {e}"@@ -1751,6 +1751,23 @@ async fn install_driver(explicit: Option<&Path>, dest: &Path) -> Result<()> {driver::install_to(&source, dest).await}+/// `remove_dir_all`, retried for up to 5 s: Windows releases a stopped+/// driver's files (its exe, driver.log) a moment after it exits (CUA-1749).+async fn remove_dir_retrying(dir: &Path) -> std::io::Result<()> {+ let mut tries = 0;+ loop {+ match std::fs::remove_dir_all(dir) {+ Ok(()) => return Ok(()),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(()),+ Err(e) if tries >= 20 => return Err(e),+ Err(_) => {+ tries += 1;+ tokio::time::sleep(std::time::Duration::from_millis(250)).await;+ }+ }+ }+}+#[cfg(test)]mod tests {#[test]@@ -1892,4 +1909,16 @@ mod tests {0o600);}++ #[tokio::test]+ async fn remove_dir_retrying_removes_and_tolerates_missing() {+ let dir = tempfile::tempdir().unwrap();+ let host = dir.path().join("host");+ std::fs::create_dir_all(host.join("bin")).unwrap();+ std::fs::write(host.join("driver.log"), "x").unwrap();+ super::remove_dir_retrying(&host).await.unwrap();+ assert!(!host.exists());+ // Already gone (removed by another step): not an error.+ super::remove_dir_retrying(&host).await.unwrap();+ }}diff --git a/libs/cua/crates/cua-host/src/service.rs b/libs/cua/crates/cua-host/src/service.rsindex a2f83154b8..83fc9376b6 100644--- a/libs/cua/crates/cua-host/src/service.rs+++ b/libs/cua/crates/cua-host/src/service.rs@@ -913,12 +913,23 @@ impl ServiceManager for WindowsTask {Ok(())}fn uninstall(&self) -> Result<()> {+ let program = self.spec().ok().map(|s| s.program);if self.run_entry_installed() {let _ = self.stop();}self.remove_run_entry();let _ = run(Command::new("schtasks").args(["/End", "/TN", WINDOWS_TASK_NAME]));let _ = run(Command::new("schtasks").args(["/Delete", "/TN", WINDOWS_TASK_NAME, "/F"]));+ // `/End` stops only the task's own process (conhost): the cmd.exe+ // and the driver under it keep running, the driver still online and+ // cmd.exe holding driver.log open, so ~/.cua/host could not be+ // removed (CUA-1749).+ for pid in program+ .map(|p| windows_procs::pids_of(&p))+ .unwrap_or_default()+ {+ let _ = run(Command::new("taskkill").args(["/PID", &pid.to_string(), "/T", "/F"]));+ }let _ = std::fs::remove_file(&self.xml_path);remove_legacy_task();Ok(())