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
feat(cua-driver-rs): garbage-collect old install versions + concurrent-install lockfile (#1541)
Francesco Bonacci7581459d2fd9
diff --git a/.github/workflows/cd-rust-cua-driver.yml b/.github/workflows/cd-rust-cua-driver.ymlindex ac22aa4ffa..db86c91251 100644--- a/.github/workflows/cd-rust-cua-driver.yml+++ b/.github/workflows/cd-rust-cua-driver.yml@@ -371,6 +371,35 @@ jobs:with:path: artifacts+ # Bake the new version into the working-tree install scripts BEFORE+ # staging them for the release upload, so the per-tag release assets+ # carry version N's baked default — not version N-1's. The same sed+ # patterns run again later under `Bake version into install scripts+ # (commit + push)` to land the change on main; doing the in-tree+ # rewrite here is idempotent (sed on an already-baked file is a+ # no-op) and ensures the GitHub Release page and main-branch commit+ # stay in lockstep.+ - name: Bake version into install scripts (in-tree)+ if: startsWith(github.ref, 'refs/tags/cua-driver-rs-v')+ env:+ VERSION: ${{ steps.version.outputs.version }}+ run: |+ # GNU sed (ubuntu-latest). The Swift CD workflow runs on+ # macos-15 and uses the BSD form (`sed -i ''`).+ sed -i \+ "s/^CUA_DRIVER_RS_BAKED_VERSION=.*/CUA_DRIVER_RS_BAKED_VERSION=\"${VERSION}\"/" \+ libs/cua-driver-rs/scripts/install.sh++ # PowerShell line starts with `$Script:` — escape the `$` for+ # sed's BRE so it matches the literal dollar sign.+ sed -i \+ "s/^\\\$Script:CuaDriverRsBakedVersion = .*/\\\$Script:CuaDriverRsBakedVersion = \"${VERSION}\"/" \+ libs/cua-driver-rs/scripts/install.ps1++ echo "Baked version ${VERSION} into working-tree install scripts:"+ grep -E '^CUA_DRIVER_RS_BAKED_VERSION=' libs/cua-driver-rs/scripts/install.sh+ grep -E '^\$Script:CuaDriverRsBakedVersion = ' libs/cua-driver-rs/scripts/install.ps1+- name: Stage release filesrun: |mkdir -p release-upload@@ -383,6 +412,10 @@ jobs:# (prerelease excludes us from the /releases/latest/ endpoint).# The tag-pinned asset URLs below are a convenience for users who# want to audit the exact installer that shipped with a release.+ #+ # The freshly-baked scripts (rewritten in the prior step) are+ # what gets copied here, so the per-tag release assets carry the+ # current version's baked default — not the previous version's.cp libs/cua-driver-rs/scripts/install.sh release-upload/install.shcp libs/cua-driver-rs/scripts/install.ps1 release-upload/install.ps1echo "Release files:"@@ -509,7 +542,7 @@ jobs:owner: ${{ github.repository_owner }}repositories: ${{ github.event.repository.name }}- - name: Bake version into install scripts+ - name: Bake version into install scripts (commit + push)if: startsWith(github.ref, 'refs/tags/cua-driver-rs-v')env:VERSION: ${{ steps.version.outputs.version }}@@ -522,11 +555,16 @@ jobs:git fetch origin maingit checkout -B bake-version origin/main- # Replace the baked version line inside the sentinel block in- # both install.sh and install.ps1. The release job runs on- # ubuntu-latest, so this uses GNU sed syntax (`sed -i` with- # no empty-string arg) — the Swift CD workflow's bake step- # runs on macos-15 and uses the BSD form (`sed -i ''`).+ # Replay the same sed the earlier in-tree step ran against the+ # working tree — but here against origin/main, so the commit we+ # push back to main has the new baked version regardless of+ # whether the in-tree step ran (it's idempotent and the on-disk+ # working-tree edits got discarded by the checkout above).+ #+ # The release job runs on ubuntu-latest, so this uses GNU sed+ # syntax (`sed -i` with no empty-string arg) — the Swift CD+ # workflow's bake step runs on macos-15 and uses the BSD form+ # (`sed -i ''`).sed -i \"s/^CUA_DRIVER_RS_BAKED_VERSION=.*/CUA_DRIVER_RS_BAKED_VERSION=\"${VERSION}\"/" \libs/cua-driver-rs/scripts/install.shdiff --git a/docs/content/docs/cua-driver/guide/getting-started/installation.mdx b/docs/content/docs/cua-driver/guide/getting-started/installation.mdxindex 630c5d532a..86e70ac4e1 100644--- a/docs/content/docs/cua-driver/guide/getting-started/installation.mdx+++ b/docs/content/docs/cua-driver/guide/getting-started/installation.mdx@@ -71,7 +71,11 @@ The cross-platform Rust port ships its own one-liners. Pick the one for your sheirm https://raw.githubusercontent.com/trycua/cua/main/libs/cua-driver-rs/scripts/install.ps1 | iex```-The Windows installer auto-detects host architecture (x64 / arm64) via `[System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture` and downloads the matching `cua-driver-rs-<v>-windows-{x86_64,arm64}.zip` from GitHub Releases. It runs **without admin** and **without Developer Mode** — the install layout is wired with NTFS directory junctions, which any unprivileged user can create.+The Windows installer auto-detects host architecture (x64 / arm64) via `[System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture` and downloads the matching `cua-driver-rs-<v>-windows-{x86_64,arm64}.zip` from GitHub Releases.++It runs **without admin** and **without Developer Mode**.++The install layout is wired with NTFS directory junctions (`IO_REPARSE_TAG_MOUNT_POINT`), which any unprivileged user can create — no elevated symlink privilege required.#### Versioned-dirs install layout@@ -142,6 +146,7 @@ Clear `$env:CUA_DRIVER_RS_VERSION` and re-run to roll forward to the newest rele| `CUA_DRIVER_RS_INSTALL_DIR` | `~/.local/bin` | `%LOCALAPPDATA%\Programs\trycua\cua-driver-rs\bin` | The visible PATH-entry directory. On Windows this is itself a junction. || `CUA_DRIVER_RS_HOME` | `~/.cua-driver-rs` | `%USERPROFILE%\.cua-driver-rs` | Package home — holds `packages/releases/<v>/` and `packages/current`. || `CUA_DRIVER_RS_NO_MODIFY_PATH` *(Linux/macOS only)* | `0` | n/a — Windows installer never auto-edits PATH | Skip the rc-file PATH append. |+| `CUA_DRIVER_RS_KEEP_VERSIONS` *(Linux/Windows only)* | `5` | `5` | Keep the N most recent per-version release dirs after install (`0` disables GC). See the **Old-version cleanup** callout below for per-target and active-install invariants. |<Callout type="info">**How the installer picks a version.** Resolution order is:@@ -157,6 +162,59 @@ So an API outage, an unauthenticated-rate-limit (60 req/hr per IP), or a transie**Why macOS uses a different layout.** On macOS the install still drops `CuaDriverRs.app` into `/Applications` and symlinks `~/.local/bin/cua-driver` into the bundle. The `.app` placement is the anchor for both **TCC attribution** (cdhash + bundle id) and **LaunchServices** (`open -a CuaDriverRs`); symlinking the `.app` from `/Applications` to a versioned dir under `$CUA_DRIVER_RS_HOME` would break both. The asymmetry is intentional — rollback on macOS = reinstall an older release tag with `CUA_DRIVER_RS_VERSION=<x.y.z>`.</Callout>+<Callout type="info">+**Old-version cleanup (Linux / Windows).** Every install drops the binary into a fresh `packages/releases/<version>-<target>/` directory and retargets the `current` symlink/junction at it. To keep disk usage bounded, the installer prunes old per-version dirs after each install — by default it keeps the **5 most recent** per platform target, deleting the rest.++```bash+# Keep more (or fewer) versions on disk+CUA_DRIVER_RS_KEEP_VERSIONS=10 bash install.sh # keep 10 most recent+CUA_DRIVER_RS_KEEP_VERSIONS=0 bash install.sh # disable GC entirely+```++Two invariants worth knowing:++- **The active install is always preserved**, even if it would otherwise fall outside the keep window (e.g. you rolled back to an older version). Worst-case on-disk count is `keep + 1`.+- **Per-target filtering** — a multi-arch dev with both `aarch64-apple-darwin` and `x86_64-unknown-linux-gnu` directories under the same `$CUA_DRIVER_RS_HOME` (rare, but possible with shared/NFS homes) gets each target's history GC'd independently of the other.++The macOS install path is unaffected — `/Applications/CuaDriverRs.app` is an in-place replacement with no per-version accumulation.+</Callout>++<Callout type="info">+**Concurrent-install lockfile.** Running two installs at the same time — e.g. clicking the one-liner while a CI script is also installing, or two terminals racing — used to risk a partially-installed state if both hit the atomic `current` swap simultaneously. The installer now takes a process-level lock per `$CUA_DRIVER_RS_HOME` so the second install waits for the first to finish:++```+==> another cua-driver-rs install is already in progress (lock at+ ~/.cua-driver-rs/packages/.install.lock.d); waiting...+```++If you see this, the safe action is to let it block — it polls every 1 second and proceeds the moment the holding install finishes. The lock entry stamps the holder's pid, start time, and invocation args so you can confirm what's running:++```bash+cat ~/.cua-driver-rs/packages/.install.lock.d/info+# pid=43210+# started=2026-05-17T09:14:22Z+# argv=install.sh+```++```powershell+Get-Content $env:USERPROFILE\.cua-driver-rs\install.lock+# pid=43210+# started=2026-05-17T09:14:22.123Z+# invocation=install.ps1 -Release latest+```++**Stale-lock recovery.** If the holding process died without releasing (kill -9, host reboot mid-install, OOM), the lock would otherwise wedge every subsequent install. After **600 seconds** of waiting, the installer assumes the lock is stale, force-releases it with a loud `lock appears stale (>600s), forcing release` log, and proceeds. So even in the pathological case the worst recovery is a 10-minute wait, not a manual `rm -rf` on internal-looking paths.++Lock locations:++| Platform | Lock |+|---|---|+| Linux | `$CUA_DRIVER_RS_HOME/packages/.install.lock.d/` (mkdir-based mutex) |+| Windows | `$env:CUA_DRIVER_RS_HOME\install.lock` (`FileShare::None` mutex) |++Both primitives are unprivileged — no sudo, no admin elevation, no Developer Mode. The lock is released on every script exit path (success, error, Ctrl-C, `exit`).+</Callout>+### Verify it worked```bashdiff --git a/libs/cua-driver-rs/PARITY.md b/libs/cua-driver-rs/PARITY.mdindex d767fc68a2..cc8ad8118d 100644--- a/libs/cua-driver-rs/PARITY.md+++ b/libs/cua-driver-rs/PARITY.md@@ -1882,7 +1882,13 @@ interactive prompt path (TUI helper, GUI extra) can persist the"skip until next version" choice without re-implementing the cachelayer.-## Installer: version-resolution chain (`env > baked > API`)+## Installer: layout + lifecycle++This section covers the cross-platform Rust installer's runtime+behaviors: how it picks a version, where it lands files, and how it+keeps the on-disk state bounded across repeated upgrades.++### Version-resolution chain (`env > baked > API`)Both Rust installers (`scripts/install.sh`, `scripts/install.ps1`)resolve the release tag in the same priority order as the Swift@@ -1899,7 +1905,7 @@ resolve the release tag in the same priority order as the Swiftonly consulted when the env override is absent *and* the bakedline hasn't been updated yet (dev branches, pre-release checkouts).-### Why this exists+#### Why this existsThe Swift installer adopted this pattern after we hit two failuremodes the API-only chain couldn't dodge:@@ -1923,9 +1929,9 @@ valuable; `install.sh` keeps its single-page fetch for now, whichis a follow-up candidate once the baked default is shipped (it isfallback-only and not hit by the default curl-from-main path).-### Sentinel-block markers (kept byte-identical across both scripts)+#### Sentinel-block markers (kept byte-identical across both scripts)-```+```bash# ~~~ BAKED_VERSION: auto-updated by CD workflow after each release — do not edit ~~~CUA_DRIVER_RS_BAKED_VERSION="<version>"# ~~~ END_BAKED_VERSION ~~~@@ -1936,7 +1942,7 @@ The PowerShell variant swaps the bash assignment formarker comments. The CD step's `sed` patterns key on the assignmentline, not the markers, so the markers are a human cue only.-### CD wiring+#### CD wiring`.github/workflows/cd-rust-cua-driver.yml` runs a `Bake version intoinstall scripts` step at the end of the `release` job after each@@ -1959,3 +1965,187 @@ The commit author is `trycua-release[bot]` and the message is`chore(cua-driver-rs): bake version <V> into install scripts [skip ci]`(the `[skip ci]` suppresses the recursive CD trigger from thebake-push hitting `main`).++### Per-version release-dir GC (`CUA_DRIVER_RS_KEEP_VERSIONS`)++Each install drops the binary into a fresh+`$HOME_DIR/packages/releases/<version>-<target>/` directory and+retargets `current` at it. Old per-version dirs are kept on disk so+rollback is `ln -sfn` / junction-retarget away with no re-download.+Disk usage grows ~15 MB per upgrade, so the installer runs a+post-install GC pass to trim oldest dirs back to a configurable cap.++#### Defaults + override++- Default: **keep 5** most recent per-version dirs per target triple.+- Override: `CUA_DRIVER_RS_KEEP_VERSIONS=<N>` (env). `<N>` is any+ non-negative integer; `0` disables GC entirely (legacy behavior —+ retains every version forever). Non-integer or negative values fall+ back to the default with a `warning:` log.++#### Invariants++1. **Per-target** — only dirs whose name suffix matches the current+ platform's `${TARGET}` triple are eligible to prune. A multi-arch+ dev with both `aarch64-apple-darwin` and `x86_64-unknown-linux-gnu`+ under one `$HOME_DIR` (rare but possible — e.g. shared home over+ NFS) has each target's history GC'd independently.+2. **Active install is always preserved** — even if the dir that+ `current` resolves to is older than the keep window (e.g. user+ rolled back to an old version). Worst-case post-GC dir count is+ `keep + 1`; common-case is exactly `keep`.+3. **Runs after the atomic swap** — `prune_old_releases` (sh) /+ `Invoke-OldReleasesGc` (ps1) is invoked only after `current` has+ been retargeted at the new install, so the about-to-be-active+ version is never a deletion candidate.+4. **macOS path unchanged** — the macOS `/Applications/CuaDriverRs.app`+ install is an in-place replacement (no per-version directory+ accumulation), so the GC pass is a no-op there by construction+ (the Darwin branch never enters the versioned-dirs install path).++#### Implementation shape++- `install.sh` — `prune_old_releases` uses `ls -dt "$RELEASES_DIR"/*/`+ for mtime-sorted candidates, filters by `*-$TARGET`, skips the dir+ that `readlink "$CURRENT_LINK"` resolves to, and `xargs -0 rm -rf`s+ the excess past the keep window.+- `install.ps1` — `Invoke-OldReleasesGc` uses+ `Get-ChildItem -Directory | Where-Object Name -like "*-$target" |+ Sort-Object LastWriteTime -Descending`, resolves+ `Get-JunctionTarget $CurrentDir` to find and exempt the active+ install, and `Remove-Item -Recurse -Force`s the excess.++#### Verification recipes++**Linux** (pin three versions, observe GC):++```bash+# Install three pinned versions in sequence. Each one drops a new+# per-version dir under ~/.cua-driver-rs/packages/releases/ and+# retargets `current`.+CUA_DRIVER_RS_VERSION=0.1.4 bash install.sh+CUA_DRIVER_RS_VERSION=0.2.0 bash install.sh+CUA_DRIVER_RS_VERSION=0.2.1 bash install.sh+ls ~/.cua-driver-rs/packages/releases/+# → 0.1.4-…, 0.2.0-…, 0.2.1-… (3 dirs, GC saw ≤ default-5, no-op)++# Force keep=2 — GC trims to 2 newest, current always preserved.+CUA_DRIVER_RS_VERSION=0.2.1 CUA_DRIVER_RS_KEEP_VERSIONS=2 bash install.sh+ls ~/.cua-driver-rs/packages/releases/+# → 0.2.0-…, 0.2.1-… (0.1.4 pruned)++# keep=0 — GC disabled.+CUA_DRIVER_RS_VERSION=0.2.1 CUA_DRIVER_RS_KEEP_VERSIONS=0 bash install.sh+# (logs "version GC disabled", retains all on-disk dirs)+```++**Windows** (equivalent in PowerShell):++```powershell+$env:CUA_DRIVER_RS_VERSION = "0.1.4"; irm <url>/install.ps1 | iex+$env:CUA_DRIVER_RS_VERSION = "0.2.0"; irm <url>/install.ps1 | iex+$env:CUA_DRIVER_RS_VERSION = "0.2.1"; irm <url>/install.ps1 | iex+Get-ChildItem ~\.cua-driver-rs\packages\releases\+# → 3 dirs++$env:CUA_DRIVER_RS_KEEP_VERSIONS = "2"+$env:CUA_DRIVER_RS_VERSION = "0.2.1"; irm <url>/install.ps1 | iex+Get-ChildItem ~\.cua-driver-rs\packages\releases\+# → 2 dirs (0.1.4 pruned)+```++### Per-host concurrent-install lockfile++Two installs running at the same time (user clicks the one-liner while+a CI script is also installing; two terminals; cron-driven reinstall+racing a manual one) can race on the atomic `current` swap and leave+the visible binary pointing at a partially-populated release dir.+Serialize installs per `$HOME_DIR` with a process-level mutex.++#### Primitive++| Platform | Mutex |+|---|---|+| Linux (and Linux-via-WSL) | `mkdir $HOME_DIR/packages/.install.lock.d` — atomic on POSIX, no `flock` dependency. First install wins; concurrent attempts get `EEXIST` and poll. |+| Windows | `System.IO.FileStream` opened on `$HomeDir\install.lock` with `FileShare::None`. Windows kernel rejects a second open until the first handle closes, so the open call itself is the acquisition. |++Both primitives are unprivileged — no admin / sudo / Developer Mode.++#### Wait + stale-detection UX++- **Wait** — polls every 1s, prints `another cua-driver-rs install is+ already in progress (lock at <path>); waiting...` exactly once.+- **Stale threshold** — 600 seconds. Named constant in both scripts+ (`LOCK_STALE_AFTER_SECONDS` / `$Script:LockStaleAfterSeconds`), not+ a magic number, so future tuning is grep-able.+- **Force-release** — after `LOCK_STALE_AFTER_SECONDS` of waiting we+ log `lock appears stale (>600s), forcing release` and `rm -rf` /+ `Remove-Item` the lock entry, then retry. The alternative (hang+ forever) leaves users wedged with no obvious recovery path.++#### Lock-info stamp++After acquiring, the installer writes a tiny info blob into the lock+so a user investigating a stuck install can see who holds it:++```bash+$ cat ~/.cua-driver-rs/packages/.install.lock.d/info+pid=43210+started=2026-05-17T09:14:22Z+argv=install.sh+```++```powershell+PS> Get-Content $env:USERPROFILE\.cua-driver-rs\install.lock+pid=43210+started=2026-05-17T09:14:22.123Z+invocation=install.ps1 -Release latest+```++#### Release on every exit path++Both scripts release the lock unconditionally:++- `install.sh` — `trap cleanup_on_exit EXIT` plus per-signal traps+ for `INT` and `TERM` that release then re-raise so the exit code+ reflects the signal.+- `install.ps1` — top-level `try { ... } finally { Release-InstallLock }`+ wrapping the whole Main block. PowerShell's `finally` fires on+ normal exit, exceptions, `exit`, and `Ctrl-C` (pipeline-stop).++A half-finished install with a held lock would wedge every subsequent+install for the full 600s stale window, so the cleanup wiring is+non-optional.++#### Verification recipes++**Linux** — concurrent contention:++```bash+# Shell 1+bash install.sh # holds the lock, takes ~20s++# Shell 2 (kick off while shell 1 is still running)+bash install.sh+# → "another cua-driver-rs install is already in progress (lock at+# ~/.cua-driver-rs/packages/.install.lock.d); waiting..."+# (blocks until shell 1 finishes, then proceeds normally)+```++**Linux** — stale lock recovery:++```bash+# Simulate a dead holder.+mkdir ~/.cua-driver-rs/packages/.install.lock.d+echo "pid=99999" > ~/.cua-driver-rs/packages/.install.lock.d/info++bash install.sh+# → "another cua-driver-rs install is already in progress…; waiting..."+# (waits 600s, then:)+# → "lock appears stale (>600s), forcing release"+# (proceeds normally)+```++**Windows** — equivalent in two PowerShell windows. The stale-recovery+test in PowerShell is `New-Item -Path $env:USERPROFILE\.cua-driver-rs\install.lock`+plus `Remove-Item` to clear after; same 600s wait.diff --git a/libs/cua-driver-rs/scripts/install.ps1 b/libs/cua-driver-rs/scripts/install.ps1index 88699146d5..37b262b724 100644--- a/libs/cua-driver-rs/scripts/install.ps1+++ b/libs/cua-driver-rs/scripts/install.ps1@@ -37,6 +37,12 @@# (default %LOCALAPPDATA%\Programs\trycua\cua-driver-rs\bin)# $env:CUA_DRIVER_RS_HOME override the package home# (default %USERPROFILE%\.cua-driver-rs)+# $env:CUA_DRIVER_RS_KEEP_VERSIONS keep the N most recent per-version+# release dirs after install; older ones+# are deleted (default 5; set 0 to+# disable GC entirely). Per-target —+# multi-arch dirs are pruned+# independently of each other.## Param:# -Release release tag to install ("latest" or a bare version like "0.2.0").@@ -96,6 +102,19 @@ $PackagesDir = Join-Path $HomeDir "packages"$ReleasesDir = Join-Path $PackagesDir "releases"$CurrentDir = Join-Path $PackagesDir "current"+# Post-install GC: how many per-version release dirs to retain. Validated+# in Resolve-KeepVersions below; 0 means "never GC".+$Script:KeepVersionsDefault = 5++function Resolve-KeepVersions {+ $raw = $env:CUA_DRIVER_RS_KEEP_VERSIONS+ if (-not $raw) { return $Script:KeepVersionsDefault }+ $n = 0+ if ([int]::TryParse($raw, [ref]$n) -and $n -ge 0) { return $n }+ Write-WarningStep "CUA_DRIVER_RS_KEEP_VERSIONS=$raw is not a non-negative integer; falling back to $($Script:KeepVersionsDefault)"+ return $Script:KeepVersionsDefault+}+# ---------- Log helpers ----------------------------------------------------function Write-Step($message) {@@ -435,6 +454,213 @@ function Ensure-Junction([string]$linkPath, [string]$targetPath) {Write-Step "junction $linkPath -> $targetPath"}+# ---------- Concurrent-install lockfile -----------------------------------+#+# A second install kicked off while a first is still running can race+# on the junction retarget and leave a half-installed state. Serialize+# installs per $HomeDir with a process-level mutex.+#+# Primitive: System.IO.FileStream opened with FileShare::None. Windows+# kernel rejects a second open of the same file with sharing=None until+# the first handle is closed, so the open call itself is the mutex+# acquisition (no separate ACL trick or named-mutex registration needed,+# no admin rights, no per-process cleanup gymnastics — close = release).+#+# Stale-lock recovery: if the holder dies without closing the handle+# (process kill, host reboot mid-install), Windows reclaims the file+# handle automatically — but only when the *kernel* notices the process+# has exited. From another process's perspective the file is no longer+# locked once that happens, so a fresh FileStream open succeeds without+# any timeout dance.+#+# However if the prior process is somehow still alive but stuck (e.g.+# wedged on a network call), we still want to recover after a bounded+# wait. After $Script:LockStaleAfterSeconds the polling loop probes+# the lockfile by attempting an exclusive open against the same+# FileShare::None primitive: success means the previous holder really+# is gone (its FileStream handle was reclaimed) and the leftover file+# is safe to delete; IOException means the holder is alive but slow,+# and we keep waiting rather than corrupting an in-flight install.+# This is the Windows equivalent of the Linux mkdir-mutex's "force+# release" path, but guarded by a liveness check instead of a blind+# Remove-Item.++$Script:LockPollIntervalSeconds = 1+$Script:LockStaleAfterSeconds = 600+$Script:StandaloneRoot = $HomeDir+$Script:LockFilePath = Join-Path $Script:StandaloneRoot "install.lock"+$Script:LockStream = $null++function Release-InstallLock {+ if ($Script:LockStream) {+ try { $Script:LockStream.Close() } catch {}+ try { $Script:LockStream.Dispose() } catch {}+ $Script:LockStream = $null+ }+ # Best-effort delete of the lockfile so subsequent installs don't+ # see a stale-but-unlocked file (cosmetic — the FileShare::None+ # primitive doesn't care if the file exists).+ if (Test-Path -LiteralPath $Script:LockFilePath) {+ try { Remove-Item -LiteralPath $Script:LockFilePath -Force -ErrorAction SilentlyContinue } catch {}+ }+}++function Acquire-InstallLock {+ # Ensure parent dir exists before we try to open the file in it.+ if (-not (Test-Path -LiteralPath $Script:StandaloneRoot)) {+ New-Item -ItemType Directory -Force -Path $Script:StandaloneRoot | Out-Null+ }+ $waited = 0+ $announced = $false+ while ($true) {+ try {+ # Mode=OpenOrCreate so the first install creates the file+ # and subsequent installs reuse it. Access=ReadWrite so we+ # can stamp pid/timestamp info after acquiring. Share=None+ # is the actual mutex — second open returns IOException.+ $Script:LockStream = [System.IO.FileStream]::new(+ $Script:LockFilePath,+ [System.IO.FileMode]::OpenOrCreate,+ [System.IO.FileAccess]::ReadWrite,+ [System.IO.FileShare]::None)+ break+ }+ catch [System.IO.IOException] {+ if (-not $announced) {+ Write-Step "another cua-driver-rs install is already in progress (lock at $($Script:LockFilePath)); waiting..."+ $announced = $true+ }+ Start-Sleep -Seconds $Script:LockPollIntervalSeconds+ $waited += $Script:LockPollIntervalSeconds+ if ($waited -ge $Script:LockStaleAfterSeconds) {+ # Don't yank the lock from a live install. Probe the+ # file with the same Share=None primitive — if the open+ # succeeds, the previous holder's FileStream is really+ # gone (process exited, kernel reclaimed the handle)+ # and the lockfile is just a stale leftover safe to+ # delete. If it still throws IOException, the holder is+ # alive but slow (big download, wedged network); keep+ # waiting rather than corrupting an in-flight install.+ $probeStream = $null+ try {+ $probeStream = [System.IO.FileStream]::new(+ $Script:LockFilePath,+ [System.IO.FileMode]::Open,+ [System.IO.FileAccess]::ReadWrite,+ [System.IO.FileShare]::None)+ # Acquisition succeeded → previous holder is gone.+ # Close the probe so we can Remove-Item cleanly,+ # then fall through to the next loop iteration+ # which will reopen via the normal OpenOrCreate path+ # (and re-stamp the info blob).+ $probeStream.Close()+ $probeStream.Dispose()+ $probeStream = $null+ try { Remove-Item -LiteralPath $Script:LockFilePath -Force -ErrorAction SilentlyContinue } catch {}+ Write-WarningStep "previous install lock at $($Script:LockFilePath) appeared stale and was released"+ $waited = 0+ }+ catch [System.IO.IOException] {+ # Still locked by a live process. Reset waited so we+ # re-check after another full window rather than+ # spamming this branch every poll interval.+ Write-Step "lock at $($Script:LockFilePath) still held by a live process; continuing to wait"+ $waited = 0+ }+ finally {+ if ($probeStream) {+ try { $probeStream.Close() } catch {}+ try { $probeStream.Dispose() } catch {}+ }+ }+ }+ }+ }+ # Stamp pid + ISO timestamp + argv into the lockfile so a user+ # investigating a stuck install can see who holds it (Get-Content+ # $env:USERPROFILE\.cua-driver-rs\install.lock).+ try {+ $info = "pid=$PID`nstarted=$([DateTime]::UtcNow.ToString('o'))`ninvocation=install.ps1 -Release $Release`n"+ $bytes = [System.Text.Encoding]::UTF8.GetBytes($info)+ $Script:LockStream.SetLength(0)+ $Script:LockStream.Write($bytes, 0, $bytes.Length)+ $Script:LockStream.Flush()+ }+ catch {+ # Non-fatal — failing to stamp info doesn't affect the lock.+ }+}++# ---------- Per-version release dir GC ------------------------------------+#+# Prune per-version release dirs under $ReleasesDir for the current+# $target, keeping the N most recent (by LastWriteTime). The dir that+# the `current` junction resolves to is always preserved on top of the+# keep budget — so the worst-case post-GC count is keep + 1 (active+# fell outside the keep window, e.g. after a rollback), common case+# is exactly keep. Per-target filtering keeps a multi-arch dev's+# x86_64 and arm64 histories independent of each other.++function Invoke-OldReleasesGc {+ param(+ [string]$releasesDir,+ [string]$currentDir,+ [string]$target,+ [int]$keep+ )++ if ($keep -eq 0) {+ Write-Step "version GC disabled (`$env:CUA_DRIVER_RS_KEEP_VERSIONS=0)"+ return+ }+ if (-not (Test-Path -LiteralPath $releasesDir)) { return }++ # Resolve $currentDir's junction target so we can exempt it from the+ # prune list. Get-JunctionTarget returns $null on non-junction paths,+ # in which case nothing is exempted (still safe — we only prune the+ # excess past $keep newest).+ $currentTarget = $null+ if (Test-Path -LiteralPath $currentDir) {+ if (Test-IsJunction $currentDir) {+ $currentTarget = Get-JunctionTarget $currentDir+ if ($currentTarget) { $currentTarget = $currentTarget.TrimEnd('\') }+ }+ }++ # Filter to dirs whose name ends in "-$target". Sort newest-first.+ # Wrap in @(...) so a single-result match doesn't get unwrapped to a+ # bare object (PowerShell's classic foot-gun).+ $candidates = @(Get-ChildItem -LiteralPath $releasesDir -Directory -ErrorAction SilentlyContinue |+ Where-Object { $_.Name -like "*-$target" } |+ Sort-Object LastWriteTime -Descending)++ if ($candidates.Count -eq 0) { return }++ $toPrune = @()+ $kept = 0+ foreach ($cand in $candidates) {+ $isCurrent = ($currentTarget -and ($cand.FullName.TrimEnd('\') -ieq $currentTarget))+ if ($kept -lt $keep) {+ $kept += 1+ continue+ }+ if ($isCurrent) {+ # Active install fell outside the keep window — preserve+ # anyway (never delete the dir backing the active junction).+ continue+ }+ $toPrune += $cand+ }++ if ($toPrune.Count -eq 0) { return }++ Write-Step "pruning $($toPrune.Count) old release dir(s) (keeping $keep most recent for $target):"+ foreach ($d in $toPrune) {+ Write-Step " - $($d.Name)"+ Remove-Item -LiteralPath $d.FullName -Recurse -Force -ErrorAction SilentlyContinue+ }+}+# ---------- Release resolution --------------------------------------------function Resolve-Version {@@ -533,6 +759,13 @@ Write-Step "cua-driver-rs installer (Windows)"Write-Step " install dir : $VisibleBinDir"Write-Step " package home: $HomeDir"+# Serialize concurrent installs per $HomeDir. The lock is released in+# the finally below — covers normal exit, errors, and Ctrl-C (which+# triggers PowerShell's pipeline-stop = finally still runs).+Acquire-InstallLock++try {+$target = Get-TargetTriple$archLabel = Get-AssetArchLabel $targetWrite-Step " target : $target"@@ -569,6 +802,13 @@ if (-not $skipDownload) {Ensure-Junction $CurrentDir $versionedDirEnsure-Junction $VisibleBinDir $CurrentDir+# Post-install GC of old per-version release dirs. Runs AFTER the junction+# retarget above so the about-to-be-active version is never a deletion+# candidate (it's both the newest by mtime and exempted via the+# current-junction check inside Invoke-OldReleasesGc).+$keepVersions = Resolve-KeepVersions+Invoke-OldReleasesGc -releasesDir $ReleasesDir -currentDir $CurrentDir -target $target -keep $keepVersions+# ---------- Fire-and-forget install telemetry ping ------------------------## Same shape as the Linux install.sh path: invoke `cua-driver telemetry@@ -633,3 +873,11 @@ Write-Host ""Write-Host "WARNING — BETA: cua-driver-rs is a cross-platform Rust port of the Swift" -ForegroundColor YellowWrite-Host " cua-driver. Windows and Linux support is feature-complete; macOS" -ForegroundColor YellowWrite-Host " parity is in progress." -ForegroundColor Yellow++}+finally {+ # Always release the lock — success, error, Ctrl-C, or `exit` all+ # land here. A partial install + held lock would wedge every+ # subsequent install for the full $LockStaleAfterSeconds window.+ Release-InstallLock+}diff --git a/libs/cua-driver-rs/scripts/install.sh b/libs/cua-driver-rs/scripts/install.shindex 4ebea21ae4..eb99fbd842 100644--- a/libs/cua-driver-rs/scripts/install.sh+++ b/libs/cua-driver-rs/scripts/install.sh@@ -27,6 +27,12 @@# packages/releases/<v>-<target>/ and# packages/current/ on Linux/Windows.# CUA_DRIVER_RS_NO_MODIFY_PATH=1 same as --no-modify-path+# CUA_DRIVER_RS_KEEP_VERSIONS=N keep the N most recent per-version+# release dirs after install; older+# ones are deleted (default 5; set 0+# to disable GC entirely). Per-target+# — multi-arch dirs are pruned+# independently of each other.## On-disk layout (Linux; macOS keeps its .app-in-/Applications layout, see# below):@@ -42,8 +48,15 @@# dir, then rename(2)-swaps the `current` symlink to point at it. A# running daemon keeps its already-mmap'd binary open across the swap# (open file handles survive). Rollback: re-point `current` at any older-# entry under `releases/`. No auto-cleanup of old releases — that's the-# feature, not an oversight.+# entry under `releases/`.+#+# Post-install GC trims the per-target release dirs so disk usage stays+# bounded (each release dir is ~15 MB, so an indefinite series of+# upgrades grows without bound). The N most-recent dirs are kept (default+# 5, override via CUA_DRIVER_RS_KEEP_VERSIONS); the dir that `current`+# resolves to is always preserved even if its mtime would otherwise drop+# it off the list. GC runs after the atomic swap so the about-to-be-active+# version is never a deletion candidate.## ⚠️ This is a BETA release. The Rust port is feature-complete on Windows# and Linux; macOS parity with the Swift cua-driver is in progress. For@@ -58,6 +71,11 @@ TAG_PREFIX="cua-driver-rs-v"BIN_DIR="${CUA_DRIVER_RS_INSTALL_DIR:-${CUA_DRIVER_RS_BIN_DIR:-$HOME/.local/bin}}"HOME_DIR="${CUA_DRIVER_RS_HOME:-$HOME/.cua-driver-rs}"NO_MODIFY_PATH="${CUA_DRIVER_RS_NO_MODIFY_PATH:-0}"+# Post-install GC: how many per-version release dirs to retain. Validated+# below as a non-negative integer; 0 means "never GC". The dir that+# `current` resolves to is always preserved regardless of cutoff.+KEEP_VERSIONS_DEFAULT=5+KEEP_VERSIONS="${CUA_DRIVER_RS_KEEP_VERSIONS:-$KEEP_VERSIONS_DEFAULT}"# macOS-only: name and install location of the .app bundle that wraps# the bare binary so the TCC auto-relaunch path in `cua-driver-rs mcp`@@ -78,13 +96,220 @@ while [[ $# -gt 0 ]]; doesacdone+# Validate KEEP_VERSIONS up front so a typo (e.g. "five") falls back to+# the default instead of silently disabling GC. Accepts any non-negative+# integer; 0 is the documented "never GC" sentinel.+if ! [[ "$KEEP_VERSIONS" =~ ^[0-9]+$ ]]; then+ printf 'warning: CUA_DRIVER_RS_KEEP_VERSIONS=%s is not a non-negative integer; falling back to %d\n' \+ "$KEEP_VERSIONS" "$KEEP_VERSIONS_DEFAULT" >&2+ KEEP_VERSIONS="$KEEP_VERSIONS_DEFAULT"+fi+BIN_LINK="$BIN_DIR/$BINARY_NAME"TMP_DIR=$(mktemp -d)-trap 'rm -rf "$TMP_DIR"' EXITlog() { printf '==> %s\n' "$*"; }err() { printf 'error: %s\n' "$*" >&2; }+# --- Concurrent-install lockfile ---------------------------------------+#+# A second install kicked off while a first is still running can race+# on the atomic `current` symlink swap and produce a half-installed+# state (e.g. the symlink points at a dir whose binary the first install+# hasn't finished copying). Serialize installs per $HOME_DIR with a+# process-level mutex.+#+# Primitive: mkdir on POSIX is atomic. The first install to create+# $LOCK_DIR holds the lock; concurrent attempts get EEXIST and poll.+# Released via trap on every exit path (success, error, signal) so+# a half-finished install always frees the lock for the next one.+#+# Stale-lock recovery: if the holder dies without releasing (kill -9,+# OOM, host reboot mid-install), the lock dir sits around forever and+# every subsequent install hangs. After $LOCK_STALE_AFTER_SECONDS of+# waiting we probe the holder's liveness via `kill -0 <pid>` (the pid+# is stamped into $LOCK_INFO right after acquisition) — if the holder+# is alive we keep waiting (slow download / wedged network is not the+# same as a crashed install and we must not yank the lock out from+# under a live process), if it's dead we force-release with a loud log+# and proceed. The alternative (hang forever) leaves users in a+# permanently wedged state with no clear recovery path beyond `rm -rf`+# on an internal-looking dir.+LOCK_PACKAGES_DIR="$HOME_DIR/packages"+LOCK_DIR="$LOCK_PACKAGES_DIR/.install.lock.d"+LOCK_INFO="$LOCK_DIR/info"+LOCK_POLL_INTERVAL_SECONDS=1+LOCK_STALE_AFTER_SECONDS=600++LOCK_HELD=0+release_install_lock() {+ if (( LOCK_HELD == 1 )); then+ rm -rf "$LOCK_DIR" 2>/dev/null || true+ LOCK_HELD=0+ fi+}++# Combine TMP_DIR cleanup with lock release in a single trap so neither+# clobbers the other. INT/TERM also re-raise via $? so the user-visible+# exit code reflects the signal.+cleanup_on_exit() {+ rm -rf "$TMP_DIR" 2>/dev/null || true+ release_install_lock+}+trap cleanup_on_exit EXIT+trap 'cleanup_on_exit; trap - INT; kill -INT $$' INT+trap 'cleanup_on_exit; trap - TERM; kill -TERM $$' TERM++acquire_install_lock() {+ mkdir -p "$LOCK_PACKAGES_DIR"+ local waited=0+ while ! mkdir "$LOCK_DIR" 2>/dev/null; do+ if (( waited == 0 )); then+ log "another cua-driver-rs install is already in progress (lock at $LOCK_DIR); waiting..."+ fi+ sleep "$LOCK_POLL_INTERVAL_SECONDS"+ waited=$((waited + LOCK_POLL_INTERVAL_SECONDS))+ if (( waited >= LOCK_STALE_AFTER_SECONDS )); then+ # Don't yank the lock from a live install. Parse pid= from+ # the info file (written by the holder right after mkdir);+ # if that pid is still alive per kill -0, the holder is just+ # slow (big download, wedged network) — keep waiting. Only+ # reclaim when there's no live holder.+ #+ # Missing/unreadable info file → holder didn't get far enough+ # to stamp pid, so assume dead and reclaim. Unparseable pid+ # line → same. Either way we err on the side of progress+ # rather than hanging forever once the 600s window elapses.+ local holder_pid=""+ if [[ -r "$LOCK_INFO" ]]; then+ holder_pid=$(grep -E '^pid=' "$LOCK_INFO" 2>/dev/null | head -1 | cut -d= -f2)+ fi+ if [[ -n "$holder_pid" ]] && kill -0 "$holder_pid" 2>/dev/null; then+ log "lock at $LOCK_DIR still held by live pid $holder_pid; continuing to wait"+ # Reset waited so we re-check after another full window+ # rather than spamming this branch every poll interval.+ waited=0+ continue+ fi+ log "lock at $LOCK_DIR appears stale (>${LOCK_STALE_AFTER_SECONDS}s, no live holder); forcing release"+ rm -rf "$LOCK_DIR" 2>/dev/null || true+ waited=0+ fi+ done+ LOCK_HELD=1+ # Drop pid + ISO timestamp + invocation args into the lock dir so a+ # user investigating a stuck install can see who holds it (`cat+ # $HOME_DIR/packages/.install.lock.d/info`).+ {+ printf 'pid=%s\n' "$$"+ printf 'started=%s\n' "$(date -u +'%Y-%m-%dT%H:%M:%SZ' 2>/dev/null || date)"+ printf 'argv=%s\n' "$0 $*"+ } > "$LOCK_INFO" 2>/dev/null || true+}++acquire_install_lock "$@"++# Prune per-version release dirs under $RELEASES_DIR for the current+# $TARGET, keeping the N most recent (by mtime). The dir that the+# `current` symlink resolves to is always preserved — even if it's+# older than the cutoff — so we never delete the active install.+#+# Filtering is by target-triple suffix so a multi-arch dev with both+# (e.g.) aarch64-apple-darwin and x86_64-unknown-linux-gnu under the+# same $HOME_DIR keeps each target's history independently. Other-arch+# dirs are invisible to this prune pass.+#+# Args: $1 = releases dir, $2 = current symlink path, $3 = target triple,+# $4 = keep count (non-negative integer; 0 = skip).+prune_old_releases() {+ local releases_dir="$1" current_link="$2" target="$3" keep="$4"++ if [[ "$keep" == "0" ]]; then+ log "version GC disabled (CUA_DRIVER_RS_KEEP_VERSIONS=0)"+ return 0+ fi+ if [[ ! -d "$releases_dir" ]]; then+ return 0+ fi++ # Resolve the dir `current` points at so we can exempt it from the+ # prune candidates. `readlink -f` would canonicalize, but BSD readlink+ # (macOS — which doesn't reach here in production but is tested from+ # a dev shell) lacks -f, so use the more portable two-step.+ local current_target=""+ if [[ -L "$current_link" ]]; then+ local link_value+ link_value=$(readlink "$current_link" 2>/dev/null || true)+ if [[ -n "$link_value" ]]; then+ case "$link_value" in+ /*) current_target="$link_value" ;;+ *) current_target="$(dirname "$current_link")/$link_value" ;;+ esac+ fi+ fi++ # `ls -dt` sorts dirs by mtime, newest-first. The trailing slash on+ # the glob filters to dirs only. Skip if no matching dirs (the glob+ # would otherwise pass through literally under shopt -s nullglob being+ # off — guard with 2>/dev/null and an `|| true`).+ local candidates=()+ while IFS= read -r dir; do+ [[ -n "$dir" ]] || continue+ # Strip trailing slash for consistent comparison with $current_target.+ dir="${dir%/}"+ # Only consider dirs whose name ends in the current target triple.+ local base="${dir##*/}"+ case "$base" in+ *-"$target") candidates+=("$dir") ;;+ *) ;;+ esac+ done < <(ls -dt "$releases_dir"/*/ 2>/dev/null || true)++ if [[ ${#candidates[@]} -le "$keep" ]]; then+ return 0+ fi++ # Walk candidates newest-first. The first $keep are retained by mtime+ # (active install counts toward the budget in the common case where+ # the install just happened — it's the newest by mtime). The active+ # install is *additionally* preserved even if it would otherwise fall+ # outside the keep window (e.g. user rolled back to an old version),+ # so the worst-case post-GC count is $keep + 1, common case is exactly+ # $keep.+ local to_prune=()+ local kept=0+ local i+ for ((i=0; i<${#candidates[@]}; i++)); do+ local cand="${candidates[$i]}"+ local is_current=0+ if [[ -n "$current_target" && "${cand%/}" == "${current_target%/}" ]]; then+ is_current=1+ fi+ if (( kept < keep )); then+ kept=$((kept + 1))+ continue+ fi+ if (( is_current == 1 )); then+ # Active install fell outside the keep window — preserve+ # anyway (never delete the dir that's about to serve the+ # next `cua-driver` invocation).+ continue+ fi+ to_prune+=("$cand")+ done++ if [[ ${#to_prune[@]} -eq 0 ]]; then+ return 0+ fi++ log "pruning ${#to_prune[@]} old release dir(s) (keeping $keep most recent for $target):"+ local p+ for p in "${to_prune[@]}"; do+ log " - ${p##*/}"+ done+ printf '%s\0' "${to_prune[@]}" | xargs -0 rm -rf+}+# --- Resolve OS/arch ----------------------------------------------------OS=$(uname -s)@@ -343,6 +568,12 @@ elserm -f "$BIN_LINK"ln -s "$CURRENT_LINK/$BINARY_NAME" "$BIN_LINK"log "symlinked $BIN_LINK -> $CURRENT_LINK/$BINARY_NAME"++ # Post-install GC of old per-version release dirs. Runs AFTER the+ # atomic `current` swap above so the about-to-be-active version is+ # never a deletion candidate (it's both the newest by mtime and+ # exempted via the current-symlink check inside prune_old_releases).+ prune_old_releases "$RELEASES_DIR" "$CURRENT_LINK" "$TARGET" "$KEEP_VERSIONS"fi# --- Fire the one-shot install telemetry ping ---------------------------