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 the Windows autostart task when an isolated install or failed registration would remove it (#4284)

Francesco Bonaccif7469d3fd6bd
diff --git a/libs/cua-driver/rust/crates/cua-driver/src/autostart.rs b/libs/cua-driver/rust/crates/cua-driver/src/autostart.rs
index 97f26af3b9..44bb78bf72 100644
--- a/libs/cua-driver/rust/crates/cua-driver/src/autostart.rs
+++ b/libs/cua-driver/rust/crates/cua-driver/src/autostart.rs
@@ -331,8 +331,11 @@ $action = New-ScheduledTaskAction `
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $user
$principal = New-ScheduledTaskPrincipal -UserId $user -LogonType Interactive -RunLevel Highest
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1) -ExecutionTimeLimit (New-TimeSpan -Hours 0)
-Unregister-ScheduledTask -TaskName $env:CUA_DRIVER_AS_TASK -Confirm:$false -ErrorAction SilentlyContinue
-Register-ScheduledTask -TaskName $env:CUA_DRIVER_AS_TASK -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Description "${env:CUA_DRIVER_AS_CLI}: serve daemon, auto-start at interactive logon, RunLevel=Highest for UWP/AppContainer support" | Out-Null
+# -Force replaces an existing task in one Task Scheduler call. Never
+# unregister first: if the new registration then failed (for example as
+# SYSTEM or without elevation), the machine would be left with no task
+# (#4090). A failed replacement keeps the existing task.
+Register-ScheduledTask -Force -TaskName $env:CUA_DRIVER_AS_TASK -Action $action -Trigger $trigger -Principal $principal -Settings $settings -Description "${env:CUA_DRIVER_AS_CLI}: serve daemon, auto-start at interactive logon, RunLevel=Highest for UWP/AppContainer support" | Out-Null
# The uiAccess worker (`cua-driver-uia.exe`) has no public client route and is
# not started by this task. The High-IL daemon is the supported path for
diff --git a/libs/cua-driver/scripts/install.ps1 b/libs/cua-driver/scripts/install.ps1
index e57774ec1f..998eab9fd3 100644
--- a/libs/cua-driver/scripts/install.ps1
+++ b/libs/cua-driver/scripts/install.ps1
@@ -98,6 +98,11 @@ param(
# `-NoAutoStart` is the explicit opt-out and takes precedence over
# the default-true `-AutoStart`.
if ($NoAutoStart) { $AutoStart = $false }
+# Whether the caller passed `-AutoStart` itself rather than relying on the
+# default. `irm | iex` runs have no bound parameters.
+$AutoStartRequested = [bool]$AutoStart -and
+ (Test-Path variable:PSBoundParameters) -and
+ $PSBoundParameters.ContainsKey('AutoStart')
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
@@ -1723,7 +1728,22 @@ $null = Repair-CuaDriverStaleDaemon
# task was registered (trycua/cua#3179).
$AutoStartRegistered = $false
-if ($AutoStart) {
+# An isolated install (CUA_DRIVER_RS_HOME or CUA_DRIVER_RS_INSTALL_DIR set)
+# must not register, re-register, or remove the machine's single autostart
+# task unless the caller explicitly passed -AutoStart (#4090). The legacy
+# cleanup above skips these installs for the same reason.
+$IsolatedInstall = [bool]($env:CUA_DRIVER_RS_INSTALL_DIR -or $env:CUA_DRIVER_RS_HOME)
+$SkipIsolatedAutostart = $IsolatedInstall -and -not $AutoStartRequested
+
+if ($SkipIsolatedAutostart) {
+ if ($AutoStart) {
+ Write-Host ""
+ Write-Host "Isolated install (CUA_DRIVER_RS_HOME/CUA_DRIVER_RS_INSTALL_DIR set) - leaving the autostart task unchanged." -ForegroundColor Yellow
+ Write-Host " The autostart task is shared by the whole machine. Pass -AutoStart explicitly to point it"
+ Write-Host " at this isolated binary, or pass -NoAutoStart to suppress this notice."
+ }
+}
+elseif ($AutoStart) {
Write-Host ""
Write-Host "Registering auto-start (cua-driver autostart enable)..." -ForegroundColor Cyan
try {
@@ -1742,7 +1762,8 @@ if ($AutoStart) {
# registered, re-register it against the fresh binary. Otherwise
# the task <Command> still points at the previous release dir + an
# older binary that may be missing the hidden-console wrapper (#1654)
- # or any later autostart-shape fix.
+ # or any later autostart-shape fix. Never reached by an isolated
+ # install, which must not touch the task owned by the default install.
$prevEAP = $ErrorActionPreference
$ErrorActionPreference = 'Continue'
try {
@@ -1784,7 +1805,12 @@ catch {
# Windows-specific autostart hint (kept inline; OS-natural location).
Write-Host ""
-if ($AutoStartRegistered) {
+if ($SkipIsolatedAutostart) {
+ Write-Host "Auto-start: unchanged for this isolated install (the task is shared by the whole machine)." -ForegroundColor Cyan
+ Write-Host " install.ps1 -AutoStart (point the task at this isolated binary)" -ForegroundColor Cyan
+ Write-Host " cua-driver autostart status (inspect)" -ForegroundColor Cyan
+}
+elseif ($AutoStartRegistered) {
Write-Host "Auto-start: 'cua-driver-serve' is registered at RunLevel=Highest." -ForegroundColor Cyan
Write-Host " cua-driver autostart status (inspect)" -ForegroundColor Cyan
Write-Host " cua-driver autostart disable (remove)" -ForegroundColor Cyan
diff --git a/libs/cua-driver/scripts/tests/test_install_autostart_summary.py b/libs/cua-driver/scripts/tests/test_install_autostart_summary.py
index f819955295..11e85ea7b8 100644
--- a/libs/cua-driver/scripts/tests/test_install_autostart_summary.py
+++ b/libs/cua-driver/scripts/tests/test_install_autostart_summary.py
@@ -51,7 +51,8 @@ def test_registered_summary_is_gated_on_the_registration_outcome(
assert len(matches) == 1, f"expected exactly one summary line, found {len(matches)}"
guard = _guard_for(lines, matches[0])
- assert guard == "if ($AutoStartRegistered) {", (
+ # An isolated install's own summary may come first (#4090).
+ assert guard in ("if ($AutoStartRegistered) {", "elseif ($AutoStartRegistered) {"), (
f"{installer.name} prints {summary!r} under {guard!r}; it must be gated on "
"the registration outcome, not on the -AutoStart request"
)
diff --git a/libs/cua-driver/scripts/tests/test_install_isolated_autostart.py b/libs/cua-driver/scripts/tests/test_install_isolated_autostart.py
new file mode 100644
index 0000000000..4da91246c1
--- /dev/null
+++ b/libs/cua-driver/scripts/tests/test_install_isolated_autostart.py
@@ -0,0 +1,89 @@
+"""An isolated Windows install must not touch the machine's autostart task (#4090).
+
+`install.ps1` with `CUA_DRIVER_RS_HOME` or `CUA_DRIVER_RS_INSTALL_DIR` set is an
+isolated install. It leaves the shared `cua-driver-serve` task alone unless the
+caller passes `-AutoStart` explicitly, and registration itself replaces an
+existing task in one Task Scheduler call instead of deleting it first.
+"""
+
+from __future__ import annotations
+
+import re
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+
+REPO_ROOT = Path(__file__).resolve().parents[4]
+INSTALL = REPO_ROOT / "libs/cua-driver/scripts/install.ps1"
+AUTOSTART = REPO_ROOT / "libs/cua-driver/rust/crates/cua-driver/src/autostart.rs"
+
+POWERSHELL = shutil.which("pwsh") or shutil.which("powershell")
+requires_powershell = pytest.mark.skipif(POWERSHELL is None, reason="requires PowerShell")
+
+
+def _register_script() -> str:
+ source = AUTOSTART.read_text(encoding="utf-8")
+ match = re.search(r'const REGISTER_PS: &str = r#"(.*?)"#;', source, re.S)
+ assert match, "REGISTER_PS not found in autostart.rs"
+ return match.group(1)
+
+
+def _install_source() -> str:
+ return INSTALL.read_text(encoding="utf-8-sig")
+
+
+def test_registration_replaces_the_task_without_unregistering_it_first() -> None:
+ script = _register_script()
+ assert "Unregister-ScheduledTask" not in script
+ assert "Register-ScheduledTask -Force" in script
+
+
+def test_isolated_install_skips_every_autostart_branch_unless_requested() -> None:
+ source = _install_source()
+ assert (
+ "$SkipIsolatedAutostart = $IsolatedInstall -and -not $AutoStartRequested" in source
+ )
+ # The skip must come first so neither registration nor the implicit
+ # "existing task detected - re-registering" branch runs.
+ chain = source.index("if ($SkipIsolatedAutostart) {")
+ assert source.index("elseif ($AutoStart) {", chain) < source.index(
+ "Existing 'cua-driver-serve' autostart task detected", chain
+ )
+
+
+def _autostart_request_probe() -> str:
+ """The installer's own parameter block and request detection, verbatim."""
+ source = _install_source()
+ start = source.index("[CmdletBinding()]")
+ end = source.index("$PSBoundParameters.ContainsKey('AutoStart')", start)
+ end = source.index("\n", end)
+ return source[start:end] + "\nWrite-Output ([bool]$AutoStartRequested)\n"
+
+
+@requires_powershell
+ ("arguments", "expected"),
+ [
+ ([], "False"),
+ (["-AutoStart"], "True"),
+ (["-AutoStart", "-NoAutoStart"], "False"),
+ (["-NoAutoStart"], "False"),
+ ],
+)
+def test_only_an_explicit_autostart_counts_as_a_request(
+ tmp_path: Path, arguments: list[str], expected: str
+) -> None:
+ probe = tmp_path / "probe.ps1"
+ probe.write_text(_autostart_request_probe(), encoding="utf-8")
+ result = subprocess.run(
+ [POWERSHELL, "-NoProfile", "-NonInteractive", "-File", str(probe), *arguments],
+ capture_output=True,
+ text=True,
+ timeout=60,
+ check=False,
+ )
+ assert result.returncode == 0, result.stderr
+ assert result.stdout.strip() == expected, result.stdout + result.stderr