Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua-driver): keep Windows update --apply from killing its own installer (#4398)

Francesco Bonacci93d0f7af24b1
diff --git a/.github/scripts/tests/test_cua_driver_release_wiring.py b/.github/scripts/tests/test_cua_driver_release_wiring.py
index d6c3f4fd64..c1de2e1d61 100644
--- a/.github/scripts/tests/test_cua_driver_release_wiring.py
+++ b/.github/scripts/tests/test_cua_driver_release_wiring.py
@@ -885,6 +885,7 @@ fi
windows = self.read(".github/workflows/e2e-rust-windows.yml")
self.assertIn('name: "Windows / installer and update smoke"', windows)
+ self.assertIn("update-apply-windows-e2e.ps1", windows)
self.assertIn("install-local.ps1 -NoAutoStart -NoPathUpdate", windows)
self.assertIn('CUA_DRIVER_LOCAL_HOME = Join-Path $env:RUNNER_TEMP', windows)
diff --git a/.github/workflows/ci-cua-driver-installer-compat.yml b/.github/workflows/ci-cua-driver-installer-compat.yml
index 48fc4fb174..c115020db4 100644
--- a/.github/workflows/ci-cua-driver-installer-compat.yml
+++ b/.github/workflows/ci-cua-driver-installer-compat.yml
@@ -48,7 +48,7 @@ jobs:
"repos/$GITHUB_REPOSITORY/pulls/$PR_NUMBER/files?per_page=100" \
--jq '.[].filename')
if ! grep -Eq \
- '^(\.github/release-state/cua-driver-rs-(published-version|withdrawn-versions)|\.github/scripts/verify_cua_driver_release_archives\.py|\.github/scripts/tests/test_verify_cua_driver_release_archives\.py|\.github/workflows/(cd-rust-cua-driver|ci-cua-driver-installer-compat)\.yml|libs/cua-driver/scripts/(_install-common|_install-rust|install)\.sh|libs/cua-driver/scripts/install\.ps1|release-please-config\.json)$' \
+ '^(\.github/release-state/cua-driver-rs-(published-version|withdrawn-versions)|\.github/scripts/verify_cua_driver_release_archives\.py|\.github/scripts/tests/test_verify_cua_driver_release_archives\.py|\.github/workflows/(cd-rust-cua-driver|ci-cua-driver-installer-compat)\.yml|libs/cua-driver/scripts/(_install-common|_install-rust|install)\.sh|libs/cua-driver/scripts/(_install-common\.psm1|install\.ps1)|release-please-config\.json)$' \
<<< "$CHANGED_FILES"; then
SHOULD_RUN=false
fi
diff --git a/.github/workflows/ci-test-scripts.yml b/.github/workflows/ci-test-scripts.yml
index 1e1fd49a36..99e7f6dc69 100644
--- a/.github/workflows/ci-test-scripts.yml
+++ b/.github/workflows/ci-test-scripts.yml
@@ -100,6 +100,9 @@ jobs:
- name: Test Windows release uninstall reporting
shell: powershell
run: '& ./libs/cua-driver/scripts/tests/uninstall-windows-regression.ps1'
+ - name: Test Windows installer daemon cleanup spares its launcher
+ shell: powershell
+ run: '& ./libs/cua-driver/scripts/tests/install-common-windows-regression.ps1'
test:
runs-on: ubuntu-latest
diff --git a/.github/workflows/e2e-rust-windows.yml b/.github/workflows/e2e-rust-windows.yml
index 3599649eb3..bdf5330163 100644
--- a/.github/workflows/e2e-rust-windows.yml
+++ b/.github/workflows/e2e-rust-windows.yml
@@ -270,6 +270,11 @@ jobs:
$env:USERPROFILE = $savedUserProfile
$env:LOCALAPPDATA = $savedLocalAppData
}
+ - name: Verify update --apply from the previous release
+ shell: pwsh
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: .\libs\cua-driver\scripts\tests\update-apply-windows-e2e.ps1 -EvidenceDir $env:RUNNER_TEMP
- name: Install into an isolated local namespace
shell: pwsh
env:
@@ -327,6 +332,8 @@ jobs:
${{ runner.temp }}/cua-driver-local-daemon.err.log
${{ runner.temp }}/cua-driver-release-install.txt
${{ runner.temp }}/cua-driver-release-reinstall.txt
+ ${{ runner.temp }}/cua-driver-update-from-install.txt
+ ${{ runner.temp }}/cua-driver-update-apply.txt
if-no-files-found: ignore
retention-days: 14
diff --git a/libs/cua-driver/scripts/_install-common.psm1 b/libs/cua-driver/scripts/_install-common.psm1
index d781ff5d08..d6f7febffb 100644
--- a/libs/cua-driver/scripts/_install-common.psm1
+++ b/libs/cua-driver/scripts/_install-common.psm1
@@ -1,13 +1,11 @@
-# _install-common.psm1 - shared helpers for install.ps1 + install-local.ps1.
+# _install-common.psm1 - daemon cleanup helpers for install.ps1.
#
-# Both scripts import this module to avoid drift in the daemon-kill logic.
-#
-# * install-local.ps1 runs from a checked-out repo, so it imports the
-# module from disk via $PSScriptRoot/_install-common.psm1.
-# * install.ps1 is fetched via `irm | iex` and has no file on disk
-# during execution. It uses Import-CuaDriverInstallModule (below)
-# which prefers the on-disk copy when available (dev / CI) and
-# falls back to fetching the .psm1 from GitHub raw.
+# install.ps1 is usually fetched via `irm | iex` (including by
+# `cua-driver update --apply`) and has no file on disk during execution.
+# It prefers the on-disk copy of this module when one sits next to it
+# (dev / CI) and otherwise fetches it from https://cua.ai/driver/.
+# install-local.ps1 manages the separate cua-driver-local identity and
+# keeps its own cleanup.
#
# Keep this module narrow on purpose - it's loaded over the network in
# the production install path, so every additional line is paid for in
@@ -18,6 +16,41 @@
Set-StrictMode -Version Latest
+# PIDs of this process and its live ancestors, nearest first.
+#
+# `cua-driver update --apply` launches the installer as a descendant of
+# cua-driver.exe and waits for its exit code. Cleanup must never stop any
+# of these processes: stopping the updater fails the update, and a tree
+# kill of it takes the installer down too (#2803, #4388). A recorded
+# parent PID can outlive its process and be reused, so a "parent" that was
+# created after its child ends the walk.
+function Get-CuaDriverAncestorProcessIds {
+ [CmdletBinding()]
+ param()
+ $ids = @([int]$PID)
+ try {
+ $child = Get-CimInstance -ClassName Win32_Process -Filter "ProcessId=$PID" -ErrorAction SilentlyContinue
+ while ($child) {
+ $parentId = [int]$child.ParentProcessId
+ if ($parentId -le 0 -or $ids -contains $parentId) { break }
+ $parent = Get-CimInstance -ClassName Win32_Process -Filter "ProcessId=$parentId" -ErrorAction SilentlyContinue
+ if (-not $parent) { break }
+ if ($parent.CreationDate -and $child.CreationDate -and $parent.CreationDate -gt $child.CreationDate) { break }
+ $ids += $parentId
+ $child = $parent
+ }
+ } catch {
+ # A broken WMI provider must not fail the install; keep what we found.
+ }
+ return $ids
+}
+
+function Get-CuaDriverProcesses {
+ param([int[]]$ExcludeIds = @())
+ return @(Get-Process -Name "cua-driver","cua-driver-uia" -ErrorAction SilentlyContinue |
+ Where-Object { $ExcludeIds -notcontains $_.Id })
+}
+
# Best-effort kill of any running cua-driver / cua-driver-uia processes
# so the next `cua-driver autostart kick` / `cua-driver mcp` starts the
# FRESH binary, not whatever's still in memory. Without this the
@@ -25,31 +58,50 @@ Set-StrictMode -Version Latest
# until the user reboots - which surfaces as "the bug I just fixed is
# still there" because the in-memory code is pre-fix.
#
+# This process and its ancestors are never stopped (see
+# Get-CuaDriverAncestorProcessIds). Every other process is stopped by
+# PID, never by image name, because an image-name tree kill also reaches
+# the updater that launched this installer.
+#
# Layers of escalation:
# 1. schtasks /End - terminates an autostart-task instance. Task
# Scheduler runs as SYSTEM so it can kill High-IL processes that
# a Medium-IL shell can't. /End on an instance the current user
# registered does NOT need admin.
-# 2. taskkill /F /IM - Medium-IL backstop for any process that
-# wasn't task-attached.
-# 3. Returns the surviving process list so callers can warn the user
+# 2. taskkill /F /T /PID - force-kills each remaining process and its
+# descendants. More permissive than Stop-Process across ILs.
+# 3. Stop-Process - catches anything taskkill missed, such as a
+# process that started meanwhile.
+# 4. Returns the surviving process list so callers can warn the user
# (these are the processes a Medium-IL shell genuinely can't reach
# - High-IL daemons whose parent wasn't `cua-driver-serve`).
+# Protected ancestors are not survivors: they are not stale daemons.
function Stop-CuaDriverDaemons {
[CmdletBinding()]
param()
+ $ancestorIds = @(Get-CuaDriverAncestorProcessIds)
$prevEAP = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
& schtasks.exe /End /TN "cua-driver-serve" 2>$null | Out-Null
Start-Sleep -Milliseconds 200
- & taskkill.exe /F /IM "cua-driver.exe" /T 2>$null | Out-Null
- & taskkill.exe /F /IM "cua-driver-uia.exe" /T 2>$null | Out-Null
+ foreach ($proc in (Get-CuaDriverProcesses -ExcludeIds $ancestorIds)) {
+ & taskkill.exe /F /T /PID $proc.Id 2>$null | Out-Null
+ }
+ foreach ($proc in (Get-CuaDriverProcesses -ExcludeIds $ancestorIds)) {
+ Stop-Process -Id $proc.Id -Force -ErrorAction SilentlyContinue
+ }
} finally {
$ErrorActionPreference = $prevEAP
}
+ $kept = @(Get-Process -Name "cua-driver","cua-driver-uia" -ErrorAction SilentlyContinue |
+ Where-Object { $ancestorIds -contains $_.Id })
+ if ($kept.Count -gt 0) {
+ $keptIds = ($kept | ForEach-Object { $_.Id }) -join ', '
+ Write-Host "Leaving the cua-driver process(es) that launched this installer running (pid: $keptIds)." -ForegroundColor DarkGray
+ }
Start-Sleep -Milliseconds 200
- return @(Get-Process -Name "cua-driver","cua-driver-uia" -ErrorAction SilentlyContinue)
+ return (Get-CuaDriverProcesses -ExcludeIds $ancestorIds)
}
# Probe whether `\\.\pipe\cua-driver` is currently accepting connections.
diff --git a/libs/cua-driver/scripts/install.ps1 b/libs/cua-driver/scripts/install.ps1
index ccc3c73648..e0ceaa2640 100644
--- a/libs/cua-driver/scripts/install.ps1
+++ b/libs/cua-driver/scripts/install.ps1
@@ -1263,22 +1263,6 @@ Write-Step "cua-driver-rs installer (Windows)"
Write-Step " install dir : $VisibleBinDir"
Write-Step " package home: $HomeDir"
-function Get-AncestorProcessIds {
- # PIDs of this process and its ancestors, so cleanup never kills the caller.
- # `cua-driver update --apply` runs the installer as a child of cua-driver.exe.
- $ids = @()
- $seen = @{}
- $currentPid = $PID
- while ($currentPid -and -not $seen.ContainsKey([int]$currentPid)) {
- $seen[[int]$currentPid] = $true
- $ids += $currentPid
- $proc = Get-CimInstance Win32_Process -Filter "ProcessId=$currentPid" -ErrorAction SilentlyContinue
- if (-not $proc -or -not $proc.ParentProcessId) { break }
- $currentPid = $proc.ParentProcessId
- }
- return $ids
-}
-
function Remove-LegacyInstall {
# Best-effort cleanup of v0.2.13-and-earlier install paths. Runs before
# any new install when default paths are in use (so users who override
@@ -1301,54 +1285,16 @@ function Remove-LegacyInstall {
Write-Step "detected legacy install layout (v0.2.13 or earlier); migrating to Cua\cua-driver"
- # 1. End the running daemon. Order matters:
- #
- # a. `schtasks /End` first — Task Scheduler runs as SYSTEM and can
- # terminate elevated (RunLevel=Highest, High IL) processes that a
- # Medium-IL Stop-Process from the user's shell cannot. This is
- # the case any time the legacy daemon was spawned via the
- # AtLogon trigger of the v0.2.13 autostart task on a non-RID-500
- # admin account (e.g. cuademo). Without this, Step 4 below fails
- # with "Access to the path 'cua-driver.exe' is denied" because
- # the legacy binary is held open by an unkillable elevated
- # process. Discovered during the cuademo v0.2.13 → v0.2.14
- # migration dogfood.
- # b. taskkill /F /IM as a backstop for any cua-driver process that
- # wasn't task-attached (manual `cua-driver serve`, legacy uia
- # worker, etc.). taskkill is more permissive than Stop-Process
- # for cross-IL termination.
- # c. Stop-Process last — catches anything taskkill missed.
- $prevEAP = $ErrorActionPreference
- $ErrorActionPreference = 'Continue'
- # Never kill the process tree we are running inside: when the installer is
- # launched by `cua-driver update --apply`, our own parent IS a cua-driver.exe,
- # and an unfiltered kill terminates the update mid-flight (the script dies
- # right after the step banner above). Both cleanup passes below skip these.
- $ancestorPids = @(Get-AncestorProcessIds)
- try {
- # Ends the running task instance. Returns non-zero when the task
- # isn't running or doesn't exist, both of which we swallow.
- & schtasks.exe /End /TN "cua-driver-serve" 2>$null | Out-Null
- Start-Sleep -Milliseconds 250
- # Force-kill via taskkill — handles High-IL processes that
- # Stop-Process can't touch from a Medium-IL caller.
- $selfFilters = @()
- foreach ($ancestorPid in $ancestorPids) {
- $selfFilters += '/FI'
- $selfFilters += "PID ne $ancestorPid"
- }
- & taskkill.exe /F /IM "cua-driver.exe" /T @selfFilters 2>$null | Out-Null
- & taskkill.exe /F /IM "cua-driver-uia.exe" /T @selfFilters 2>$null | Out-Null
- } finally {
- $ErrorActionPreference = $prevEAP
- }
- $procs = Get-Process -Name "cua-driver","cua-driver-uia" -ErrorAction SilentlyContinue
- if ($procs) {
- foreach ($p in $procs) {
- if ($ancestorPids -contains $p.Id) { continue }
- try { Stop-Process -Id $p.Id -Force -ErrorAction SilentlyContinue } catch {}
- }
- }
+ # 1. End the running daemon through the shared cleanup in
+ # _install-common.psm1. Its `schtasks /End` terminates elevated
+ # (RunLevel=Highest, High IL) daemons that a Medium-IL kill cannot.
+ # Without this, Step 4 below fails with "Access to the path
+ # 'cua-driver.exe' is denied" because the legacy binary is held open
+ # by an unkillable elevated process (found in the cuademo v0.2.13 ->
+ # v0.2.14 migration dogfood). It never stops this installer's own
+ # process tree: `cua-driver update --apply` launches the installer
+ # from a cua-driver.exe and waits for it (#2803).
+ $null = Stop-CuaDriverDaemons
Start-Sleep -Milliseconds 500
# 2. Unregister the autostart Scheduled Task if present. Idempotent —
diff --git a/libs/cua-driver/scripts/tests/install-common-windows-regression.ps1 b/libs/cua-driver/scripts/tests/install-common-windows-regression.ps1
new file mode 100644
index 0000000000..9207dac91e
--- /dev/null
+++ b/libs/cua-driver/scripts/tests/install-common-windows-regression.ps1
@@ -0,0 +1,152 @@
+# Real-process regression for the installer's shared daemon cleanup
+# (_install-common.psm1; #2803, #4388).
+#
+# `cua-driver update --apply` launches the installer from cua-driver.exe and
+# waits for its exit code. Like the shipped CLI, which runs finite commands in
+# a wrapped cua-driver.exe child, the stand-in updater is two cua-driver.exe
+# processes deep. It runs a Windows PowerShell "installer" that calls
+# Stop-CuaDriverDaemonsWithHealth, next to an unrelated cua-driver.exe daemon
+# with a child process and a cua-driver-uia.exe worker. Cleanup must stop the
+# daemon, its child, and the worker, report no survivors, and leave the
+# updater and installer running so the updater exits 0.
+#
+# The cleanup stops every cua-driver process on the machine and ends the
+# cua-driver-serve task. Run this only on a disposable machine such as CI.
+
+Set-StrictMode -Version Latest
+$ErrorActionPreference = 'Stop'
+
+function Assert-True {
+ param(
+ [Parameter(Mandatory = $true)][bool]$Condition,
+ [Parameter(Mandatory = $true)][string]$Message
+ )
+ if (-not $Condition) { throw $Message }
+}
+
+function Start-StandIn {
+ param([string]$Exe, [string]$Arguments = '')
+ $start = New-Object System.Diagnostics.ProcessStartInfo($Exe, $Arguments)
+ $start.UseShellExecute = $false
+ return [System.Diagnostics.Process]::Start($start)
+}
+
+$module = Join-Path (Split-Path -Parent $PSScriptRoot) '_install-common.psm1'
+$root = Join-Path ([System.IO.Path]::GetTempPath()) ('cua-driver-cleanup-' + [guid]::NewGuid().ToString('N'))
+New-Item -ItemType Directory -Path $root | Out-Null
+
+# One stand-in program, four modes:
+# (no arguments) idle, like a daemon
+# spawn <exe> start <exe>, then idle (a daemon with a child)
+# run <script> run <script> in Windows PowerShell, wait, and return its
+# exit code, as `cua-driver update --apply` does
+# wrap <args> run itself with <args>, wait, and return its exit code,
+# as the CLI's telemetry wrapper does
+$source = @'
+using System;
+using System.Diagnostics;
+using System.IO;
+using System.Threading;
+
+public static class StandIn {
+ static int RunAndWait(string file, string arguments) {
+ ProcessStartInfo start = new ProcessStartInfo(file, arguments);
+ start.UseShellExecute = false;
+ using (Process child = Process.Start(start)) {
+ child.WaitForExit();
+ return child.ExitCode;
+ }
+ }
+
+ public static int Main(string[] args) {
+ if (args.Length > 1 && args[0] == "wrap") {
+ string[] quoted = new string[args.Length - 1];
+ for (int i = 1; i < args.Length; i++) quoted[i - 1] = "\"" + args[i] + "\"";
+ return RunAndWait(Process.GetCurrentProcess().MainModule.FileName, string.Join(" ", quoted));
+ }
+ if (args.Length == 2 && args[0] == "run") {
+ string powershell = Path.Combine(Environment.SystemDirectory, @"WindowsPowerShell\v1.0\powershell.exe");
+ return RunAndWait(powershell,
+ "-NoProfile -NonInteractive -ExecutionPolicy Bypass -File \"" + args[1] + "\"");
+ }
+ if (args.Length == 2 && args[0] == "spawn") {
+ ProcessStartInfo start = new ProcessStartInfo(args[1]);
+ start.UseShellExecute = false;
+ Process.Start(start);
+ }
+ Thread.Sleep(Timeout.Infinite);
+ return 0;
+ }
+}
+'@
+
+$daemon = $null
+$worker = $null
+$updater = $null
+try {
+ $sourcePath = Join-Path $root 'StandIn.cs'
+ Set-Content -LiteralPath $sourcePath -Value $source -Encoding Ascii
+ $driverExe = Join-Path $root 'cua-driver.exe'
+ $csc = Join-Path $env:WINDIR 'Microsoft.NET\Framework64\v4.0.30319\csc.exe'
+ if (-not (Test-Path -LiteralPath $csc)) {
+ $csc = Join-Path $env:WINDIR 'Microsoft.NET\Framework\v4.0.30319\csc.exe'
+ }
+ & $csc /nologo /target:exe "/out:$driverExe" $sourcePath
+ if ($LASTEXITCODE -ne 0) { throw "csc failed with exit $LASTEXITCODE" }
+ $uiaExe = Join-Path $root 'cua-driver-uia.exe'
+ $childExe = Join-Path $root 'daemon-child.exe'
+ Copy-Item -LiteralPath $driverExe -Destination $uiaExe
+ Copy-Item -LiteralPath $driverExe -Destination $childExe
+
+ $resultPath = Join-Path $root 'cleanup-result.json'
+ $installerPath = Join-Path $root 'installer.ps1'
+ $installer = @"
+Set-StrictMode -Version Latest
+`$ErrorActionPreference = 'Stop'
+Import-Module -Name '$($module.Replace("'", "''"))' -Force
+`$result = Stop-CuaDriverDaemonsWithHealth
+@{
+ Survivors = @(`$result.Survivors | Where-Object { `$_ } | ForEach-Object { `$_.Id })
+ Stale = [bool]`$result.Stale
+} | ConvertTo-Json | Set-Content -LiteralPath '$($resultPath.Replace("'", "''"))'
+"@
+ Set-Content -LiteralPath $installerPath -Value $installer -Encoding UTF8
+
+ $daemon = Start-StandIn $driverExe "spawn `"$childExe`""
+ $worker = Start-StandIn $uiaExe
+ $daemonChild = $null
+ for ($attempt = 0; $attempt -lt 100 -and -not $daemonChild; $attempt++) {
+ $daemonChild = Get-CimInstance -ClassName Win32_Process `
+ -Filter "ParentProcessId=$($daemon.Id) AND Name='daemon-child.exe'" `
+ -ErrorAction SilentlyContinue
+ if (-not $daemonChild) { Start-Sleep -Milliseconds 100 }
+ }
+ Assert-True ($null -ne $daemonChild) 'daemon stand-in did not start its child'
+ $daemonChildId = [int]$daemonChild.ProcessId
+
+ $updater = Start-StandIn $driverExe "wrap run `"$installerPath`""
+ Assert-True ($updater.WaitForExit(120000)) 'updater stand-in did not exit within 120 seconds'
+
+ Assert-True ($updater.ExitCode -eq 0) `
+ "updater stand-in exited $($updater.ExitCode): cleanup stopped the process tree that launched the installer"
+ Assert-True (Test-Path -LiteralPath $resultPath) 'installer stand-in did not finish after cleanup'
+ $result = Get-Content -LiteralPath $resultPath -Raw | ConvertFrom-Json
+ Assert-True (@($result.Survivors).Count -eq 0) "cleanup reported survivors: $(@($result.Survivors) -join ', ')"
+ Assert-True (-not $result.Stale) 'cleanup reported a stale daemon'
+ Assert-True ($daemon.WaitForExit(5000)) 'unrelated cua-driver daemon was not stopped'
+ Assert-True ($worker.WaitForExit(5000)) 'cua-driver-uia worker was not stopped'
+ Assert-True ($null -eq (Get-Process -Id $daemonChildId -ErrorAction SilentlyContinue)) `
+ 'tree kill did not stop the daemon child process'
+
+ Write-Host 'Windows installer cleanup spared its launcher and stopped the other daemons.'
+}
+finally {
+ foreach ($process in @($daemon, $worker, $updater)) {
+ if ($process -and -not $process.HasExited) {
+ try { $process.Kill() } catch { }
+ }
+ }
+ Get-Process -Name 'daemon-child' -ErrorAction SilentlyContinue |
+ Stop-Process -Force -ErrorAction SilentlyContinue
+ Remove-Item -LiteralPath $root -Recurse -Force -ErrorAction SilentlyContinue
+}
diff --git a/libs/cua-driver/scripts/tests/install-windows-regression.ps1 b/libs/cua-driver/scripts/tests/install-windows-regression.ps1
index 4dd9a53a01..2f6ea07ee5 100644
--- a/libs/cua-driver/scripts/tests/install-windows-regression.ps1
+++ b/libs/cua-driver/scripts/tests/install-windows-regression.ps1
@@ -39,40 +39,18 @@ if ($parseErrors.Count -ne 0) {
throw "install.ps1 parse errors: $($parseErrors -join '; ')"
}
-Import-InstallerFunction -Ast $ast -Name "Get-AncestorProcessIds"
Import-InstallerFunction -Ast $ast -Name "Remove-LegacyInstall"
$script:Steps = @()
-$script:TaskkillCalls = @()
+$script:DaemonStops = 0
$script:ScheduledTaskCalls = @()
-$script:StoppedProcessIds = @()
-$script:Processes = @()
-$script:ParentByPid = @{}
function Write-Step { param($Message); $script:Steps += [string]$Message }
function Start-Sleep { [CmdletBinding()] param([int]$Milliseconds, [int]$Seconds) }
-function taskkill.exe { $script:TaskkillCalls += ,@($args); $global:LASTEXITCODE = 0 }
function schtasks.exe { $script:ScheduledTaskCalls += ,@($args); $global:LASTEXITCODE = 0 }
-function Get-CimInstance {
- [CmdletBinding()]
- param([string]$ClassName, [string]$Filter)
- $processId = [int]($Filter -replace '^ProcessId=', '')
- if (-not $script:ParentByPid.ContainsKey($processId)) { return $null }
- [pscustomobject]@{
- ProcessId = $processId
- ParentProcessId = $script:ParentByPid[$processId]
- }
-}
-function Get-Process {
- [CmdletBinding()]
- param([string[]]$Name)
- return $script:Processes
-}
-function Stop-Process {
- [CmdletBinding()]
- param([int]$Id, [switch]$Force)
- $script:StoppedProcessIds += $Id
-}
+# _install-common.psm1 owns daemon cleanup and its ancestor protection;
+# install-common-windows-regression.ps1 tests that with real processes.
+function Stop-CuaDriverDaemons { $script:DaemonStops++ }
$savedInstallDir = $env:CUA_DRIVER_RS_INSTALL_DIR
$savedHome = $env:CUA_DRIVER_RS_HOME
@@ -93,7 +71,7 @@ try {
Set-Content -LiteralPath (Join-Path $LegacyHomeDir ".telemetry_id") -Value "synthetic-test-id"
Remove-LegacyInstall
Assert-True ($script:Steps.Count -eq 0) "cache/telemetry-only home was detected as legacy"
- Assert-True ($script:TaskkillCalls.Count -eq 0) "cache/telemetry-only home triggered process cleanup"
+ Assert-True ($script:DaemonStops -eq 0) "cache/telemetry-only home triggered process cleanup"
Assert-True (Test-Path -LiteralPath $LegacyHomeDir) "cache/telemetry-only home was removed"
# Every supported on-disk legacy marker independently enters migration.
@@ -109,54 +87,15 @@ try {
New-Item -ItemType Directory -Force -Path (Join-Path $LegacyHomeDir $marker) | Out-Null
}
$script:Steps = @()
- $script:TaskkillCalls = @()
+ $script:DaemonStops = 0
$script:ScheduledTaskCalls = @()
- $script:Processes = @()
- $script:StoppedProcessIds = @()
- $script:ParentByPid = @{}
- $script:ParentByPid[[int]$PID] = 0
Remove-LegacyInstall
Assert-True ($script:Steps -contains "detected legacy install layout (v0.2.13 or earlier); migrating to Cua\cua-driver") `
"$marker was not detected as a legacy marker"
+ Assert-True ($script:DaemonStops -eq 1) "$marker migration did not stop daemons through the shared cleanup"
}
- # Model update --apply: PowerShell is a child of cua-driver.exe, which in
- # turn has another ancestor. Both must be excluded from taskkill and the
- # Stop-Process backstop, while an unrelated daemon must still be stopped.
- $HomeDir = Join-Path $root "process-tree\modern-home"
- $LegacyHomeDir = Join-Path $root "process-tree\profile\.cua-driver-rs"
- $LegacyVendorDir = Join-Path $root "process-tree\localappdata\Programs\trycua"
- $LegacyVisibleBinDir = Join-Path $LegacyVendorDir "cua-driver-rs\bin"
- New-Item -ItemType Directory -Force -Path (Join-Path $LegacyHomeDir "packages") | Out-Null
- $script:Steps = @()
- $script:TaskkillCalls = @()
- $script:ScheduledTaskCalls = @()
- $script:StoppedProcessIds = @()
- $script:ParentByPid = @{}
- $script:ParentByPid[[int]$PID] = 4100
- $script:ParentByPid[4100] = 4200
- $script:ParentByPid[4200] = 0
- $script:Processes = @(
- [pscustomobject]@{ Id = 4100; ProcessName = "cua-driver" },
- [pscustomobject]@{ Id = 4300; ProcessName = "cua-driver" }
- )
-
- $ancestors = @(Get-AncestorProcessIds)
- Assert-True (($ancestors -join ',') -eq "$PID,4100,4200") "ancestor discovery did not traverse the complete synthetic chain"
- Remove-LegacyInstall
-
- Assert-True ($script:TaskkillCalls.Count -eq 2) "expected taskkill calls for driver and UIA processes"
- foreach ($call in $script:TaskkillCalls) {
- $commandLine = $call -join ' '
- foreach ($protectedPid in @($PID, 4100, 4200)) {
- Assert-True ($commandLine -match "PID ne $protectedPid(?: |$)") `
- "taskkill did not exclude protected ancestor PID $protectedPid"
- }
- }
- Assert-True (-not ($script:StoppedProcessIds -contains 4100)) "Stop-Process targeted the cua-driver launcher"
- Assert-True ($script:StoppedProcessIds -contains 4300) "unrelated cua-driver daemon was not stopped"
-
- Write-Host "Windows installer legacy/update regression checks passed."
+ Write-Host "Windows installer legacy migration checks passed."
}
finally {
$env:CUA_DRIVER_RS_INSTALL_DIR = $savedInstallDir
diff --git a/libs/cua-driver/scripts/tests/update-apply-windows-e2e.ps1 b/libs/cua-driver/scripts/tests/update-apply-windows-e2e.ps1
new file mode 100644
index 0000000000..22b6814b93
--- /dev/null
+++ b/libs/cua-driver/scripts/tests/update-apply-windows-e2e.ps1
@@ -0,0 +1,186 @@
+# End-to-end `cua-driver update --apply` on Windows (#2803, #4388).
+#
+# Installs the previous published release with its autostart task, starts
+# that release's daemons, and runs its own `cua-driver update --apply`. The
+# shipped updater starts
+# powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "iwr -useb https://cua.ai/driver/install.ps1 | iex"
+# and waits for it. Windows resolves powershell.exe from the updater's own
+# directory first, so a stand-in placed there runs this checkout's
+# install.ps1 instead of the copy published from main. Release selection,
+# the process tree, the inherited environment, and exit-code propagation
+# all belong to the shipped updater.
+#
+# Needs an elevated interactive session and GH_TOKEN (release lookup). Run it
+# only on a disposable machine: it replaces the cua-driver-serve task, stops
+# every cua-driver process, and edits the User PATH (restored afterward).
+
+[CmdletBinding()]
+param(
+ [string]$EvidenceDir = [System.IO.Path]::GetTempPath()
+)
+
+Set-StrictMode -Version Latest
+$ErrorActionPreference = 'Stop'
+
+function Assert-True {
+ param(
+ [Parameter(Mandatory = $true)][bool]$Condition,
+ [Parameter(Mandatory = $true)][string]$Message
+ )
+ if (-not $Condition) { throw $Message }
+}
+
+function Invoke-Native {
+ param([string]$FilePath, [string[]]$Arguments)
+ $previous = $ErrorActionPreference
+ $ErrorActionPreference = 'Continue'
+ try {
+ $output = & $FilePath @Arguments 2>&1 | Out-String
+ $exitCode = $LASTEXITCODE
+ } finally {
+ $ErrorActionPreference = $previous
+ }
+ return [pscustomobject]@{ ExitCode = $exitCode; Output = $output }
+}
+
+$scriptsDir = Split-Path -Parent $PSScriptRoot
+$repoRoot = (Resolve-Path -LiteralPath (Join-Path $scriptsDir '..\..\..')).Path
+$installer = Join-Path $scriptsDir 'install.ps1'
+$windowsPowerShell = Join-Path $env:SystemRoot 'System32\WindowsPowerShell\v1.0\powershell.exe'
+$schtasks = Join-Path $env:SystemRoot 'System32\schtasks.exe'
+$taskName = 'cua-driver-serve'
+$oneLiner = 'iwr -useb https://cua.ai/driver/install.ps1 | iex'
+
+# Update from the newest published, non-withdrawn release below the newest.
+$withdrawn = @(Get-Content -LiteralPath (Join-Path $repoRoot '.github/release-state/cua-driver-rs-withdrawn-versions') |
+ ForEach-Object { ($_ -replace '#.*', '').Trim() } |
+ Where-Object { $_ })
+$tags = Invoke-Native 'gh' @('api', '--paginate', 'repos/trycua/cua/releases?per_page=100', '--jq', '.[] | select(.draft == false) | .tag_name')
+Assert-True ($tags.ExitCode -eq 0) "could not list releases: $($tags.Output)"
+$versions = @($tags.Output -split "`r?`n" |
+ Where-Object { $_ -match '^cua-driver-rs-v\d+\.\d+\.\d+$' } |
+ ForEach-Object { [version]($_ -replace '^cua-driver-rs-v', '') } |
+ Where-Object { $withdrawn -notcontains $_.ToString() } |
+ Sort-Object -Descending -Unique)
+Assert-True ($versions.Count -ge 2) 'need two published releases to test an update'
+$from = $versions[1].ToString()
+Write-Host "Updating from cua-driver $from"
+
+$testRoot = Join-Path ([System.IO.Path]::GetTempPath()) ('cua-driver-update-apply-' + [guid]::NewGuid().ToString('N'))
+$savedEnv = @{}
+foreach ($name in @('USERPROFILE', 'LOCALAPPDATA', 'CUA_DRIVER_RS_VERSION', 'CUA_DRIVER_RS_HOME',
+ 'CUA_DRIVER_RS_INSTALL_DIR', 'CUA_DRIVER_RS_TELEMETRY_ENABLED', 'CUA_TELEMETRY_ENABLED',
+ 'CUA_E2E_CANDIDATE_INSTALLER', 'CUA_E2E_UPDATER_ARGS')) {
+ $savedEnv[$name] = [Environment]::GetEnvironmentVariable($name)
+}
+$savedUserPath = [Environment]::GetEnvironmentVariable('Path', 'User')
+
+try {
+ $env:USERPROFILE = Join-Path $testRoot 'profile'
+ $env:LOCALAPPDATA = Join-Path $testRoot 'localappdata'
+ New-Item -ItemType Directory -Force -Path $env:USERPROFILE, $env:LOCALAPPDATA | Out-Null
+ foreach ($name in @('CUA_DRIVER_RS_VERSION', 'CUA_DRIVER_RS_HOME', 'CUA_DRIVER_RS_INSTALL_DIR')) {
+ [Environment]::SetEnvironmentVariable($name, $null)
+ }
+ $env:CUA_DRIVER_RS_TELEMETRY_ENABLED = 'false'
+ $env:CUA_TELEMETRY_ENABLED = 'false'
+
+ # 1. Install the previous release with its autostart task.
+ $install = Invoke-Native $windowsPowerShell @('-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', $installer,
+ '-Release', $from, '-NoPathUpdate')
+ $install.Output | Set-Content -LiteralPath (Join-Path $EvidenceDir 'cua-driver-update-from-install.txt')
+ Assert-True ($install.ExitCode -eq 0) "installing $from failed with exit $($install.ExitCode): $($install.Output)"
+ $binDir = Join-Path $env:LOCALAPPDATA 'Programs\Cua\cua-driver\bin'
+ $bin = Join-Path $binDir 'cua-driver.exe'
+ $before = Invoke-Native $bin @('--version')
+ Assert-True ($before.Output -match [regex]::Escape($from)) "installed binary is not $($from): $($before.Output)"
+ Assert-True ((Invoke-Native $schtasks @('/Query', '/TN', $taskName)).ExitCode -eq 0) "installing $from did not register $taskName"
+
+ # 2. Old daemons for the update to replace: the autostart task's daemon
+ # and a manually started one that no task owns.
+ Assert-True ((Invoke-Native $schtasks @('/Run', '/TN', $taskName)).ExitCode -eq 0) "could not start $taskName"
+ $socket = "\\.\pipe\cua-driver-update-e2e-$PID"
+ Start-Process -FilePath $bin -ArgumentList @('serve', '--socket', $socket) -WindowStyle Hidden | Out-Null
+ $oldDaemons = @()
+ for ($attempt = 0; $attempt -lt 60 -and $oldDaemons.Count -lt 2; $attempt++) {
+ Start-Sleep -Milliseconds 500
+ $oldDaemons = @(Get-CimInstance -ClassName Win32_Process -Filter "Name='cua-driver.exe'" |
+ Where-Object { $_.CommandLine -match '\sserve(\s|$)' } |
+ ForEach-Object { Get-Process -Id $_.ProcessId -ErrorAction SilentlyContinue })
+ }
+ Assert-True ($oldDaemons.Count -ge 2) "expected two $from daemons, found $($oldDaemons.Count)"
+
+ # 3. Stand-in powershell.exe in the updater's directory. It records the
+ # updater's arguments and runs this checkout's installer.
+ $standInSource = @'
+using System;
+using System.Diagnostics;
+using System.IO;
+
+public static class PowerShellStandIn {
+ public static int Main(string[] args) {
+ File.WriteAllLines(Environment.GetEnvironmentVariable("CUA_E2E_UPDATER_ARGS"), args);
+ string powershell = Path.Combine(Environment.SystemDirectory, @"WindowsPowerShell\v1.0\powershell.exe");
+ string installer = Environment.GetEnvironmentVariable("CUA_E2E_CANDIDATE_INSTALLER");
+ ProcessStartInfo start = new ProcessStartInfo(powershell,
+ "-NoProfile -ExecutionPolicy Bypass -File \"" + installer + "\"");
+ start.UseShellExecute = false;
+ using (Process child = Process.Start(start)) {
+ child.WaitForExit();
+ return child.ExitCode;
+ }
+ }
+}
+'@
+ $standInPath = Join-Path $testRoot 'PowerShellStandIn.cs'
+ Set-Content -LiteralPath $standInPath -Value $standInSource -Encoding Ascii
+ $csc = Join-Path $env:WINDIR 'Microsoft.NET\Framework64\v4.0.30319\csc.exe'
+ $compile = Invoke-Native $csc @('/nologo', '/target:exe', "/out:$(Join-Path $binDir 'powershell.exe')", $standInPath)
+ Assert-True ($compile.ExitCode -eq 0) "could not build the powershell.exe stand-in: $($compile.Output)"
+ $env:CUA_E2E_CANDIDATE_INSTALLER = $installer
+ $env:CUA_E2E_UPDATER_ARGS = Join-Path $testRoot 'updater-args.txt'
+
+ # 4. Run the shipped updater. Its release lookup is an unauthenticated
+ # GitHub API call, so retry only that failure, before anything installs.
+ for ($attempt = 1; $attempt -le 3; $attempt++) {
+ $update = Invoke-Native $bin @('update', '--apply')
+ if ($update.ExitCode -eq 0 -or $update.Output -notmatch 'Could not reach GitHub') { break }
+ Start-Sleep -Seconds 30
+ }
+ $update.Output | Set-Content -LiteralPath (Join-Path $EvidenceDir 'cua-driver-update-apply.txt')
+ Write-Host $update.Output
+ Assert-True ($update.ExitCode -eq 0) "cua-driver $from update --apply exited $($update.ExitCode)"
+
+ $updaterArgs = @(Get-Content -LiteralPath $env:CUA_E2E_UPDATER_ARGS)
+ Assert-True ($updaterArgs -contains $oneLiner) "the updater did not run the published installer one-liner: $($updaterArgs -join ' ')"
+ Assert-True ($update.Output -match 'New version available: (\S+)') 'the updater did not select a newer release'
+ $to = $Matches[1]
+ foreach ($expected in @(
+ "cua-driver-rs $to installed.",
+ 'Stopping any previous cua-driver processes',
+ 'Registering auto-start (cua-driver autostart enable)',
+ "Auto-start: 'cua-driver-serve' is registered at RunLevel=Highest.",
+ "Installed cua-driver $to.")) {
+ Assert-True ($update.Output.Contains($expected)) "update --apply output is missing: $expected"
+ }
+ $after = Invoke-Native $bin @('--version')
+ Assert-True ($after.Output -match [regex]::Escape($to)) "the updated binary is not $($to): $($after.Output)"
+ $action = (Get-ScheduledTask -TaskName $taskName -ErrorAction Stop).Actions | Select-Object -First 1
+ Assert-True ($action.Arguments -like "*$bin*") "$taskName does not launch $($bin): $($action.Arguments)"
+ foreach ($daemon in $oldDaemons) {
+ $daemon.Refresh()
+ Assert-True $daemon.HasExited "the $from daemon (pid $($daemon.Id)) is still running"
+ }
+
+ Write-Host "cua-driver $from update --apply installed $to, re-registered $taskName, and stopped the old daemons."
+}
+finally {
+ Invoke-Native $schtasks @('/End', '/TN', $taskName) | Out-Null
+ Invoke-Native $schtasks @('/Delete', '/TN', $taskName, '/F') | Out-Null
+ Get-Process -Name 'cua-driver', 'cua-driver-uia' -ErrorAction SilentlyContinue |
+ Stop-Process -Force -ErrorAction SilentlyContinue
+ [Environment]::SetEnvironmentVariable('Path', $savedUserPath, 'User')
+ foreach ($name in $savedEnv.Keys) {
+ [Environment]::SetEnvironmentVariable($name, $savedEnv[$name])
+ }
+}