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(cua-driver): fall back to the releases API when the baked version has no assets
bluelikeness1be9c7ed0d9a
diff --git a/libs/cua-driver/scripts/_install-rust.sh b/libs/cua-driver/scripts/_install-rust.shindex 188511f949..406727b551 100644--- a/libs/cua-driver/scripts/_install-rust.sh+++ b/libs/cua-driver/scripts/_install-rust.sh@@ -508,34 +508,123 @@ done# The baked value is the common-case default: `curl ... | bash` against# `main` resolves the version locally with zero API calls, so an API# outage / rate limit / network blip can't break a default install. The-# API fallback only fires when this script is run from a branch where-# the baked line hasn't been updated yet (dev / pre-release checkouts).+# API is consulted only when the baked line is absent (dev / pre-release+# checkouts) or when the baked version turns out to have no downloadable+# asset — see the recovery at the download step below.## ~~~ BAKED_VERSION: auto-updated in the release PR — do not edit ~~~CUA_DRIVER_RS_BAKED_VERSION="0.14.0" # x-release-please-version# ~~~ END_BAKED_VERSION ~~~+# Run API requests with an optional token. Keep the header construction here+# (rather than in loggable command text) so neither GH_TOKEN nor GITHUB_TOKEN+# can appear in installer output. Release-asset downloads stay unauthenticated:+# the repository is public and curl may redirect them to another GitHub host.+# GH_TOKEN takes precedence, matching the GitHub CLI.+github_api_curl() {+ local token="${GH_TOKEN:-${GITHUB_TOKEN:-}}"+ if [[ -n "$token" ]]; then+ curl -H "Authorization: Bearer $token" "$@"+ else+ curl "$@"+ fi+}++# The authenticated releases endpoint can include drafts for maintainers.+# Associate each top-level tag_name with its following draft field before+# considering it. GitHub's REST response renders those top-level fields on+# separate lines in that order; nested author/assets objects have no tag_name.+extract_published_release_versions() {+ awk -v prefix="$TAG_PREFIX" '+ /"tag_name"[[:space:]]*:/ {+ tag = $0+ sub(/^.*"tag_name"[[:space:]]*:[[:space:]]*"/, "", tag)+ sub(/".*$/, "", tag)+ next+ }+ tag != "" && /"draft"[[:space:]]*:/ {+ if ($0 ~ /"draft"[[:space:]]*:[[:space:]]*false/) {+ version = tag+ if (index(version, prefix) == 1) {+ version = substr(version, length(prefix) + 1)+ if (version ~ /^[0-9]+\.[0-9]+\.[0-9]+$/) {+ print version+ }+ }+ }+ tag = ""+ }+ '+}++# Highest SemVer ${TAG_PREFIX}* version published on the repo, printed bare+# (no tag prefix) on stdout. Returns non-zero when the API is unreachable or+# has no matching tag; callers decide whether that is fatal, because this runs+# both as the primary resolver and as recovery for a bad baked version.+#+# per_page=100 (the API maximum): the repo interleaves lume, Python, and Swift+# releases with these. Walk up to ten pages so a busy repository cannot hide+# cua-driver-rs behind the first page, but keep the request count bounded.+resolve_latest_version_from_api() {+ local page page_json page_count page_versions+ local versions=""+ for ((page=1; page<=10; page++)); do+ page_json="$(github_api_curl -fsSL \+ "https://api.github.com/repos/$REPO/releases?per_page=100&page=$page")" || return 1++ # Extract only published exact stable x.y.z tags. Cua Driver's stable+ # tags are marked prerelease in GitHub metadata, so the tag syntax —+ # not the prerelease flag — decides semantic stability.+ page_versions="$(printf '%s' "$page_json" | extract_published_release_versions)" || true+ if [[ -n "$page_versions" ]]; then+ versions="${versions}${versions:+$'\n'}${page_versions}"+ fi++ page_count="$(+ printf '%s' "$page_json" \+ | awk '{ count += gsub(/"tag_name"[[:space:]]*:/, "&") } END { print count + 0 }'+ )"+ [[ "$page_count" =~ ^[0-9]+$ ]] || return 1+ if (( page_count < 100 )); then+ break+ fi+ done++ local version+ version="$(+ printf '%s\n' "$versions" \+ | sed '/^$/d' \+ | sort -t. -k1,1nr -k2,2nr -k3,3nr \+ | head -n 1+ )"+ [[ -n "$version" ]] || return 1+ printf '%s' "$version"+}++# Where VERSION came from. A missing asset is fatal for an explicit pin (the+# user named that version) but recoverable for the baked constant, which is+# routinely ahead of reality: merging the Release Please pull request bumps it+# on `main` and creates the tag, yet the release starts as an unpublished draft+# whose assets stay undownloadable until the CD build publishes it. cua.ai+# serves this script from `main`, so the public one-liner points at a version+# nobody can fetch for the length of every release build.if [[ -n "${CUA_DRIVER_RS_VERSION:-}" ]]; then+ VERSION_SOURCE="pin"TAG="${TAG_PREFIX}${CUA_DRIVER_RS_VERSION#v}"log "using version from CUA_DRIVER_RS_VERSION: $TAG"elif [[ -n "${CUA_DRIVER_RS_BAKED_VERSION:-}" ]]; then+ VERSION_SOURCE="baked"TAG="${TAG_PREFIX}${CUA_DRIVER_RS_BAKED_VERSION#v}"log "using baked release: $TAG"else+ VERSION_SOURCE="api"log "resolving latest $TAG_PREFIX* release via GitHub API"- # Pinned to the exact `cua-driver-rs-v*` prefix so this script can never- # accidentally pick up a Swift `cua-driver-v*` release.- TAG=$(curl -fsSL "https://api.github.com/repos/$REPO/releases?per_page=40" \- | grep -Eo '"tag_name":[[:space:]]*"'"${TAG_PREFIX}"'[^"]+"' \- | sed -E 's/.*"'"${TAG_PREFIX}"'([0-9]+[.][0-9]+[.][0-9]+)"/\1/' \- | sort -t. -k1,1nr -k2,2nr -k3,3nr \- | head -n 1 \- | sed -E 's/^/'"${TAG_PREFIX}"'/')- if [[ -z "$TAG" ]]; then+ if ! API_VERSION="$(resolve_latest_version_from_api)"; thenerr "no release matching ${TAG_PREFIX}* found on $REPO"err " (cua-driver-rs is a BETA-stage cross-platform port; releases may not be published yet.)"exit 1fi+ TAG="${TAG_PREFIX}${API_VERSION}"log "latest release: $TAG"fi@@ -569,17 +658,94 @@ version_is_at_least() {## Linux / Windows-via-WSL — use the bare-binary tarball. No bundle on# these platforms, no TCC, no need to unpack a directory.-case "$LABEL" in- darwin-*) TARBALL="cua-driver-rs-${VERSION}-darwin-universal.tar.gz" ;;- *) TARBALL="cua-driver-rs-${VERSION}-${LABEL}-binary.tar.gz" ;;-esac-URL="https://github.com/$REPO/releases/download/$TAG/$TARBALL"+release_tarball_name() {+ case "$LABEL" in+ darwin-*) printf 'cua-driver-rs-%s-darwin-universal.tar.gz' "$1" ;;+ *) printf 'cua-driver-rs-%s-%s-binary.tar.gz' "$1" "$LABEL" ;;+ esac+}-log "downloading $URL"-if ! curl -fsSL -o "$TMP_DIR/$TARBALL" "$URL"; then- err "download failed; try CUA_DRIVER_RS_VERSION=<version> to pin a specific release"- exit 1+# Fetches one release tarball into $TMP_DIR. A confirmed HTTP 404 returns 44;+# every other failure is retried at the same URL with bounded backoff, then+# returns 1. This distinction is load-bearing: only a missing baked asset may+# trigger release fallback. A timeout, TLS failure, rate limit, or server error+# must never silently install an older version.+download_release_tarball() {+ local version="$1" tarball url partial http_code curl_status attempt retryable+ tarball="$(release_tarball_name "$version")"+ url="https://github.com/$REPO/releases/download/${TAG_PREFIX}${version}/$tarball"+ partial="$TMP_DIR/$tarball.partial"+ log "downloading $url"+ for attempt in 1 2 3; do+ http_code=""+ curl_status=0+ http_code="$(+ curl -sSL -o "$partial" -w '%{http_code}' "$url"+ )" || curl_status=$?+ if (( curl_status == 0 )) && [[ "$http_code" =~ ^2[0-9][0-9]$ ]]; then+ mv "$partial" "$TMP_DIR/$tarball"+ return 0+ fi+ rm -f "$partial" 2>/dev/null || true+ if [[ "$http_code" == "404" ]]; then+ return 44+ fi+ retryable=0+ if (( curl_status != 0 )) \+ || [[ "$http_code" == "408" || "$http_code" == "429" ]] \+ || [[ "$http_code" =~ ^5[0-9][0-9]$ ]]; then+ retryable=1+ fi+ if (( retryable == 1 && attempt < 3 )); then+ err "download attempt $attempt failed (HTTP ${http_code:-unknown}, curl exit $curl_status); retrying the same release"+ sleep "$attempt"+ continue+ fi+ break+ done+ err "download failed after $attempt attempt(s) (HTTP ${http_code:-unknown}, curl exit $curl_status); refusing to fall back to an older release"+ return 1+}++DOWNLOAD_STATUS=0+download_release_tarball "$VERSION" || DOWNLOAD_STATUS=$?+if (( DOWNLOAD_STATUS != 0 )); then+ # Almost always the publish-lag window described at the baked constant: it+ # is already live on `main` while its release is still an unpublished draft.+ # Without this recovery the default `curl | bash` install fails outright for+ # the length of every release build, with no way through but a version pin.+ if [[ "$VERSION_SOURCE" != "baked" || "$DOWNLOAD_STATUS" != "44" ]]; then+ err "download failed; try CUA_DRIVER_RS_VERSION=<version> to pin a specific release"+ exit 1+ fi+ printf 'warning: baked release %s has no downloadable %s asset (HTTP 404); this is usually a temporary publish lag\n' \+ "$TAG" "$LABEL" >&2+ printf 'warning: temporarily falling back to the newest fully published release via the GitHub Releases API\n' >&2+ if ! API_VERSION="$(resolve_latest_version_from_api)"; then+ err "could not resolve any published ${TAG_PREFIX}* release to fall back to"+ err " try CUA_DRIVER_RS_VERSION=<version> to pin a specific release"+ exit 1+ fi+ if [[ "$API_VERSION" == "$VERSION" ]]; then+ # The API agrees this is the newest tag, so the tag exists but its+ # assets do not. Retrying the identical URL would just 404 again.+ err "${TAG_PREFIX}${API_VERSION} is the newest published release but is missing its ${LABEL} asset"+ err " try CUA_DRIVER_RS_VERSION=<version> to pin an older release"+ exit 1+ fi+ printf 'warning: falling back to %s%s\n' "$TAG_PREFIX" "$API_VERSION" >&2+ # Adopt the recovered release before anything downstream derives a path,+ # a stage directory, or a capability check from VERSION.+ VERSION="$API_VERSION"+ TAG="${TAG_PREFIX}${VERSION}"+ DOWNLOAD_STATUS=0+ download_release_tarball "$VERSION" || DOWNLOAD_STATUS=$?+ if (( DOWNLOAD_STATUS != 0 )); then+ err "download failed; try CUA_DRIVER_RS_VERSION=<version> to pin a specific release"+ exit 1+ fifi+TARBALL="$(release_tarball_name "$VERSION")"log "extracting"tar -xzf "$TMP_DIR/$TARBALL" -C "$TMP_DIR"diff --git a/libs/cua-driver/scripts/install.ps1 b/libs/cua-driver/scripts/install.ps1index 0a1405fff6..042955838b 100644--- a/libs/cua-driver/scripts/install.ps1+++ b/libs/cua-driver/scripts/install.ps1@@ -848,25 +848,53 @@ function Invoke-OldReleasesGc {# ---------- Release resolution ---------------------------------------------function Resolve-Version {- if ($env:CUA_DRIVER_RS_VERSION) {- $v = $env:CUA_DRIVER_RS_VERSION -replace '^v', ''- Write-Step "using version from `$env:CUA_DRIVER_RS_VERSION: $v"- return $v+# Version-resolution provenance for this run, set by Resolve-Version and read+# by the download path. The distinction matters when an asset is missing:+#+# 'env' / 'release-arg' — the user named an exact version. Installing some+# other version would silently defy an explicit instruction, so a+# missing asset must stay fatal.+# 'baked' — recoverable, and routinely wrong for a window on+# every release. Merging the Release Please pull request bumps the+# constant on `main` and creates the tag, but the release it creates is+# a *draft*: its assets only become downloadable when the CD workflow+# finishes building and publishes it. Since cua.ai serves this script+# from `main`, the public one-liner advertises a version nobody can+# download for the length of that build. Observed windows on+# cua-driver-rs releases range from ~12 minutes to ~3.5 hours. Falling+# back to the newest published release keeps installs working through it.+# 'api' — already the API's answer; nothing left to fall+# back to.+$Script:CuaDriverRsVersionSource = $null++function Get-GitHubApiHeaders {+ # GH_TOKEN matches the GitHub CLI's precedence. Keep the token in a header+ # object only; never include it in installer diagnostics.+ $token = $env:GH_TOKEN+ if (-not $token) { $token = $env:GITHUB_TOKEN }++ $headers = @{+ Accept = "application/vnd.github+json"+ "User-Agent" = "cua-driver-installer"}- if ($Release -ne "latest") {- $v = $Release -replace '^v', ''- Write-Step "using -Release $v"- return $v+ if ($token) {+ $headers["Authorization"] = "Bearer $token"}- # Baked-version fallback — set by the CD workflow after each release- # so the default `irm | iex` install path doesn't hit the GitHub API.- # See the BAKED_VERSION sentinel-block near the top of this file.- if ($Script:CuaDriverRsBakedVersion) {- $v = $Script:CuaDriverRsBakedVersion -replace '^v', ''- Write-Step "using baked release: $TagPrefix$v"- return $v+ return $headers+}++function Assert-StableVersion([string]$version, [string]$source) {+ if ($version -notmatch '^[0-9]+\.[0-9]+\.[0-9]+$') {+ Write-ErrorStep "$source must be an exact stable x.y.z version (got '$version')"+ exit 1}+}++function Get-LatestVersionFromApi {+ # Highest SemVer $TagPrefix* version published on the repo, or $null when+ # the API is unreachable or has no matching tag. Never exits: callers+ # decide whether a miss is fatal, because this runs both as the primary+ # resolver (fatal) and as a recovery step (advisory).Write-Step "resolving latest $TagPrefix* release via GitHub API"# Paginate the /releases endpoint until we've seen every release or# collected enough $TagPrefix* matches to be confident the latest is@@ -880,45 +908,213 @@ function Resolve-Version {# ever hold, but cheap insurance against an unbounded loop.# - stop early when a page comes back empty (we've exhausted the# list).- $matches = @()- for ($page = 1; $page -le 10; $page++) {- $uri = "https://api.github.com/repos/$Repo/releases?per_page=100&page=$page"- $batch = Invoke-RestMethod -Uri $uri -UseBasicParsing- if (-not $batch -or $batch.Count -eq 0) { break }- $matches += @($batch | Where-Object { $_.tag_name -like "$TagPrefix*" })- if ($batch.Count -lt 100) { break }- }- if (-not $matches -or $matches.Count -eq 0) {- Write-ErrorStep "no release matching $TagPrefix* found on $Repo"- exit 1+ #+ # $releaseMatches, not $matches: the latter is a PowerShell automatic+ # variable clobbered by every `-match` evaluation.+ $releaseMatches = @()+ try {+ for ($page = 1; $page -le 10; $page++) {+ $uri = "https://api.github.com/repos/$Repo/releases?per_page=100&page=$page"+ $batch = Invoke-RestMethod -Uri $uri -Headers (Get-GitHubApiHeaders) -UseBasicParsing+ if (-not $batch -or $batch.Count -eq 0) { break }+ $releaseMatches += @($batch | Where-Object {+ (-not $_.draft) -and+ ($_.tag_name -match "^$([regex]::Escape($TagPrefix))([0-9]+\.[0-9]+\.[0-9]+)$")+ })+ if ($batch.Count -lt 100) { break }+ }+ }+ catch {+ Write-WarningStep "GitHub Releases API query failed: $($_.Exception.Message)"+ return $null+ }+ if (-not $releaseMatches -or $releaseMatches.Count -eq 0) {+ return $null}# Sort by SemVer descending. [version] correctly orders dotted triples.- $latest = $matches | Sort-Object {+ $latest = $releaseMatches | Sort-Object {$v = $_.tag_name.Substring($TagPrefix.Length)try { [version]$v } catch { [version]"0.0.0" }} -Descending | Select-Object -First 1- $version = $latest.tag_name.Substring($TagPrefix.Length)Write-Step "latest release: $($latest.tag_name)"- return $version+ return $latest.tag_name.Substring($TagPrefix.Length)+}++function Resolve-Version {+ if ($env:CUA_DRIVER_RS_VERSION) {+ $v = $env:CUA_DRIVER_RS_VERSION -replace '^v', ''+ Assert-StableVersion $v 'CUA_DRIVER_RS_VERSION'+ Write-Step "using version from `$env:CUA_DRIVER_RS_VERSION: $v"+ $Script:CuaDriverRsVersionSource = 'env'+ return $v+ }+ if ($Release -ne "latest") {+ $v = $Release -replace '^v', ''+ Assert-StableVersion $v '-Release'+ Write-Step "using -Release $v"+ $Script:CuaDriverRsVersionSource = 'release-arg'+ return $v+ }+ # Baked-version fallback — set by the CD workflow after each release+ # so the default `irm | iex` install path doesn't hit the GitHub API.+ # See the BAKED_VERSION sentinel-block near the top of this file.+ if ($Script:CuaDriverRsBakedVersion) {+ $v = $Script:CuaDriverRsBakedVersion -replace '^v', ''+ Assert-StableVersion $v 'baked release'+ Write-Step "using baked release: $TagPrefix$v"+ $Script:CuaDriverRsVersionSource = 'baked'+ return $v+ }+ $v = Get-LatestVersionFromApi+ if (-not $v) {+ Write-ErrorStep "no release matching $TagPrefix* found on $Repo"+ exit 1+ }+ $Script:CuaDriverRsVersionSource = 'api'+ return $v}# ---------- Download + extract ---------------------------------------------function Get-ReleaseAsset([string]$version, [string]$archLabel, [string]$destDir) {+function Get-HttpStatusCode($exception) {+ if ($null -eq $exception) {+ return $null+ }+ try {+ $response = $exception.Response+ if ($null -eq $response) { return $null }+ return [int]$response.StatusCode+ }+ catch {+ return $null+ }+}++function Test-TransientDownloadFailure($statusCode) {+ # A missing status means the request failed below HTTP (DNS, connect,+ # timeout, TLS, etc.). Retry those plus standard transient HTTP statuses.+ if ($null -eq $statusCode) { return $true }+ return ($statusCode -eq 408 -or $statusCode -eq 429 -or $statusCode -ge 500)+}++function Get-ReleaseZip([string]$version, [string]$archLabel, [string]$destDir) {+ # Returns a structured result so a confirmed missing asset (HTTP 404) is+ # never confused with a transient network, server, or authentication+ # failure. Only the former may activate baked-version fallback.$zipName = "cua-driver-rs-$version-$archLabel.zip"$url = "https://github.com/$Repo/releases/download/$TagPrefix$version/$zipName"$zipPath = Join-Path $destDir $zipName+ $maxAttempts = 3Write-Step "downloading $url"- try {- Invoke-WebRequest -Uri $url -OutFile $zipPath -UseBasicParsing+ for ($attempt = 1; $attempt -le $maxAttempts; $attempt++) {+ try {+ Invoke-WebRequest -Uri $url -OutFile $zipPath -UseBasicParsing+ return @{+ ZipPath = $zipPath+ Missing = $false+ ErrorMessage = $null+ StatusCode = $null+ Attempts = $attempt+ }+ }+ catch {+ Remove-Item -LiteralPath $zipPath -Force -ErrorAction SilentlyContinue+ $statusCode = Get-HttpStatusCode $_.Exception+ if ($statusCode -eq 404) {+ return @{+ ZipPath = $null+ Missing = $true+ ErrorMessage = $null+ StatusCode = 404+ Attempts = $attempt+ }+ }+ $isTransient = Test-TransientDownloadFailure $statusCode+ if ($isTransient -and $attempt -lt $maxAttempts) {+ $delaySeconds = $attempt+ Write-WarningStep "download attempt $attempt of $maxAttempts failed; retrying the same release in $delaySeconds second(s): $($_.Exception.Message)"+ Start-Sleep -Seconds $delaySeconds+ continue+ }+ return @{+ ZipPath = $null+ Missing = $false+ ErrorMessage = $_.Exception.Message+ StatusCode = $statusCode+ Attempts = $attempt+ }+ }}- catch {- Write-ErrorStep "download failed: $($_.Exception.Message)"+}++function Get-ReleaseAsset([string]$version, [string]$archLabel, [string]$destDir) {+ # Returns @{ StageDir; Version }. Version can differ from the requested one+ # when a baked version had no downloadable asset and the API named a+ # different published release — so callers must re-read it rather than+ # assuming the version they passed in is what landed on disk.+ $resolvedVersion = $version+ $download = Get-ReleaseZip $resolvedVersion $archLabel $destDir+ $missingDetail = $null++ if ($download.ErrorMessage) {+ if (Test-TransientDownloadFailure $download.StatusCode) {+ Write-ErrorStep "download failed after $($download.Attempts) attempts for $TagPrefix$resolvedVersion ($archLabel): $($download.ErrorMessage)"+ }+ else {+ Write-ErrorStep "download failed for $TagPrefix$resolvedVersion ($archLabel) with HTTP $($download.StatusCode): $($download.ErrorMessage)"+ }+ Write-ErrorStep " The requested version was not changed. Check network access and GitHub credentials, then retry."+ exit 1+ }++ if ($download.Missing -and $Script:CuaDriverRsVersionSource -eq 'baked') {+ # Almost always the publish-lag window described above: the constant is+ # already live on `main` while its release is still an unpublished+ # draft. Without this recovery the default `irm | iex` install fails+ # outright for the length of every release build, with no way through+ # but an explicit version pin.+ $apiVersion = Get-LatestVersionFromApi+ if (-not $apiVersion) {+ $missingDetail = "no published fallback could be resolved"+ }+ elseif ($apiVersion -eq $resolvedVersion) {+ # The API agrees this is the newest tag, so the tag exists but its+ # assets do not. Retrying the identical URL would just 404 again.+ $missingDetail = "the API reports it as the latest published release, so there is no older version to select automatically"+ }+ else {+ Write-WarningStep "temporary fallback: baked release $TagPrefix$resolvedVersion is missing its $archLabel asset (HTTP 404); installing latest published release $TagPrefix$apiVersion instead"+ $resolvedVersion = $apiVersion+ $download = Get-ReleaseZip $resolvedVersion $archLabel $destDir+ if ($download.ErrorMessage) {+ if (Test-TransientDownloadFailure $download.StatusCode) {+ Write-ErrorStep "fallback download failed after $($download.Attempts) attempts for $TagPrefix$resolvedVersion ($archLabel): $($download.ErrorMessage)"+ }+ else {+ Write-ErrorStep "fallback download failed for $TagPrefix$resolvedVersion ($archLabel) with HTTP $($download.StatusCode): $($download.ErrorMessage)"+ }+ Write-ErrorStep " No further fallback was attempted. Check network access and GitHub credentials, then retry."+ exit 1+ }+ }+ }++ if ($download.Missing) {+ $message = "release asset for $TagPrefix$resolvedVersion ($archLabel) was not found (HTTP 404)"+ if ($missingDetail) { $message += "; $missingDetail" }+ Write-ErrorStep "$message."+ if ($Script:CuaDriverRsVersionSource -in @('env', 'release-arg')) {+ Write-ErrorStep " Explicit version pins are not eligible for fallback."+ }Write-ErrorStep " Try pinning a known-good version via `$env:CUA_DRIVER_RS_VERSION = '<x.y.z>'`."exit 1}+ $version = $resolvedVersion+ $zipPath = $download.ZipPath+ $zipName = Split-Path -Leaf $zipPath+Write-Step "extracting $zipName"$extractDir = Join-Path $destDir "extracted"if (Test-Path -LiteralPath $extractDir) {@@ -935,7 +1131,7 @@ function Get-ReleaseAsset([string]$version, [string]$archLabel, [string]$destDirGet-ChildItem $extractDir -Recurse | ForEach-Object { Write-Host " $($_.FullName)" }exit 1}- return $stageDir+ return @{ StageDir = $stageDir; Version = $version }}# ---------- Main -----------------------------------------------------------@@ -1100,28 +1296,45 @@ if (-not $skipDownload) {$tmpRoot = Join-Path (Get-CuaDriverTempDir) ("cua-driver-rs-install-" + [Guid]::NewGuid().ToString("N"))New-Item -ItemType Directory -Force -Path $tmpRoot | Out-Nulltry {- $stageDir = Get-ReleaseAsset $version $archLabel $tmpRoot- New-Item -ItemType Directory -Force -Path $versionedDir | Out-Null- Copy-Item -LiteralPath (Join-Path $stageDir $BinaryName) -Destination (Join-Path $versionedDir $BinaryName) -Force- $themeStage = Join-Path $stageDir $ThemeBinaryName- if (-not (Test-Path -LiteralPath $themeStage)) {- if ([version]$version -ge $CursorThemeRequiredFrom) {- throw "release archive is missing required $ThemeBinaryName"- }- Write-WarningStep "release $version predates $ThemeBinaryName; installing without custom cursor themes"- } else {- Copy-Item -LiteralPath $themeStage -Destination (Join-Path $versionedDir $ThemeBinaryName) -Force+ $asset = Get-ReleaseAsset $version $archLabel $tmpRoot+ # Get-ReleaseAsset may have recovered from a baked version with no+ # published assets by downloading a different one. Adopt what actually+ # landed before anything downstream derives a path or a capability+ # check from $version.+ if ($asset.Version -ne $version) {+ $version = $asset.Version+ $versionedDir = Join-Path $ReleasesDir "$version-$target"}- Write-Step "installed $versionedDir\$BinaryName (version $version, target $target)"- # Optional sibling: the reserved uiAccess worker- # (cua-driver-uia.exe). It started shipping with- # cua-driver-rs-v0.2.8 and is absent in earlier releases. Copy it when- # present for a future authenticated daemon-internal forwarding path;- # current autostart does not launch it. See #1602.- $uiaStage = Join-Path $stageDir 'cua-driver-uia.exe'- if (Test-Path -LiteralPath $uiaStage) {- Copy-Item -LiteralPath $uiaStage -Destination (Join-Path $versionedDir 'cua-driver-uia.exe') -Force- Write-Step "installed $versionedDir\cua-driver-uia.exe (uiAccess worker)"+ $stageDir = $asset.StageDir+ # A fallback can retarget us to a version that was already installed.+ # Re-check after adopting that version so we do not overwrite a+ # potentially running (and therefore locked) executable.+ if (Test-Path -LiteralPath (Join-Path $versionedDir $BinaryName)) {+ Write-Step "fallback release $version is already on disk at $versionedDir (skipping install copy)"+ }+ else {+ New-Item -ItemType Directory -Force -Path $versionedDir | Out-Null+ Copy-Item -LiteralPath (Join-Path $stageDir $BinaryName) -Destination (Join-Path $versionedDir $BinaryName) -Force+ $themeStage = Join-Path $stageDir $ThemeBinaryName+ if (-not (Test-Path -LiteralPath $themeStage)) {+ if ([version]$version -ge $CursorThemeRequiredFrom) {+ throw "release archive is missing required $ThemeBinaryName"+ }+ Write-WarningStep "release $version predates $ThemeBinaryName; installing without custom cursor themes"+ } else {+ Copy-Item -LiteralPath $themeStage -Destination (Join-Path $versionedDir $ThemeBinaryName) -Force+ }+ Write-Step "installed $versionedDir\$BinaryName (version $version, target $target)"+ # Optional sibling: the reserved uiAccess worker+ # (cua-driver-uia.exe). It started shipping with+ # cua-driver-rs-v0.2.8 and is absent in earlier releases. Copy it when+ # present for a future authenticated daemon-internal forwarding path;+ # current autostart does not launch it. See #1602.+ $uiaStage = Join-Path $stageDir 'cua-driver-uia.exe'+ if (Test-Path -LiteralPath $uiaStage) {+ Copy-Item -LiteralPath $uiaStage -Destination (Join-Path $versionedDir 'cua-driver-uia.exe') -Force+ Write-Step "installed $versionedDir\cua-driver-uia.exe (uiAccess worker)"+ }}}finally {diff --git a/libs/cua-driver/scripts/tests/test_install_version_fallback.py b/libs/cua-driver/scripts/tests/test_install_version_fallback.pynew file mode 100644index 0000000000..78b2a35a0e--- /dev/null+++ b/libs/cua-driver/scripts/tests/test_install_version_fallback.py@@ -0,0 +1,762 @@+"""Installer release-resolution guards.++Every release opens a window where the baked version constant points at assets+nobody can download yet. Merging the Release Please pull request bumps the+constant on `main` and creates the tag, but the release it creates is a draft;+its assets only become fetchable once the CD workflow finishes building and+publishes it. cua.ai serves both installers straight from `main`, so the public+one-liner advertises an undownloadable version for the length of that build --+observed windows on cua-driver-rs releases run from ~12 minutes to ~3.5 hours.++The baked value must therefore degrade to the GitHub Releases API rather than+fail the install. An explicit pin (CUA_DRIVER_RS_VERSION, -Release) is the+opposite case: the user named one version, so a missing asset must stay fatal+rather than silently installing a different one.++Version *agreement* across the checked-in sources is not tested here --+.github/scripts/validate_release_versions.py already owns that. It cannot cover+these invariants, because at merge time the release genuinely is unpublished.+"""++from __future__ import annotations++import json+import os+import re+import shutil+import subprocess+import textwrap+import threading+from contextlib import contextmanager+from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer+from pathlib import Path+from typing import Iterator++import pytest++# _install-rust.sh only ever runs on macOS and Linux, so the behavioral tests+# below are posix-only. Gating on os.name as well as bash's presence matters:+# on Windows, `bash.exe` is usually the WSL launcher, which resolves via+# shutil.which but cannot execute anything when no distro is installed.+requires_posix_bash = pytest.mark.skipif(+ os.name != "posix" or shutil.which("bash") is None,+ reason="requires a posix host with bash",+)+POWERSHELL = shutil.which("pwsh") or shutil.which("powershell")+requires_powershell = pytest.mark.skipif(+ POWERSHELL is None,+ reason="requires PowerShell",+)++REPO_ROOT = Path(__file__).resolve().parents[4]+SCRIPTS = REPO_ROOT / "libs/cua-driver/scripts"++WINDOWS_INSTALLER = SCRIPTS / "install.ps1"+UNIX_INSTALLER = SCRIPTS / "_install-rust.sh"+++def _windows_source() -> str:+ return WINDOWS_INSTALLER.read_text(encoding="utf-8-sig")+++def _unix_source() -> str:+ return UNIX_INSTALLER.read_text(encoding="utf-8")+++# ---------- Windows -------------------------------------------------------+++def _extract_powershell_function(source: str, name: str) -> str:+ start = source.index(f"function {name}")+ next_function = source.find("\nfunction ", start + 1)+ assert next_function != -1, f"could not locate the end of PowerShell function {name}"+ return source[start:next_function].strip()+++def _run_powershell(tmp_path: Path, body: str) -> subprocess.CompletedProcess[str]:+ script = tmp_path / "installer-harness.ps1"+ script.write_text(+ "$ErrorActionPreference = 'Stop'\n" + body,+ encoding="utf-8",+ )+ return subprocess.run(+ [str(POWERSHELL), "-NoProfile", "-NonInteractive", "-File", str(script)],+ capture_output=True,+ text=True,+ check=True,+ )+++@contextmanager+def _powershell_download_server(+ scenario: str,+) -> Iterator[tuple[str, list[str]]]:+ requests: list[str] = []++ class Handler(BaseHTTPRequestHandler):+ def do_GET(self) -> None:+ requests.append(self.path)+ if scenario == "network":+ self.connection.close()+ return+ status = {+ "missing": 404,+ "server": 503,+ "auth": 401,+ }[scenario]+ self.send_response(status)+ self.end_headers()++ def log_message(self, _format: str, *args: object) -> None:+ pass++ server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)+ thread = threading.Thread(target=server.serve_forever, daemon=True)+ thread.start()+ try:+ host, port = server.server_address+ yield f"http://{host}:{port}", requests+ finally:+ server.shutdown()+ server.server_close()+ thread.join()+++def test_windows_download_failure_is_recoverable_rather_than_fatal() -> None:+ """Get-ReleaseZip must report failure by returning, not by exiting.++ An `exit 1` inside the download helper makes any retry unreachable, which+ is precisely how the original defect became unrecoverable.+ """+ source = _windows_source()+ body = source[+ source.index("function Get-ReleaseZip") : source.index("function Get-ReleaseAsset")+ ]++ assert "Missing = $true" in body+ assert "ErrorMessage = $_.Exception.Message" in body+ assert "exit 1" not in body+++def test_windows_installer_falls_back_when_baked_release_is_unpublished() -> None:+ source = _windows_source()++ # The baked branch must record its provenance for the download path to key on.+ assert "$Script:CuaDriverRsVersionSource = 'baked'" in source++ fallback = source.index(+ "if ($download.Missing -and $Script:CuaDriverRsVersionSource -eq 'baked')"+ )+ # The recovery must consult the API and retry the download, in that order.+ api_call = source.index("$apiVersion = Get-LatestVersionFromApi", fallback)+ retry = source.index(+ "$download = Get-ReleaseZip $resolvedVersion $archLabel $destDir", api_call+ )+ fatal = source.index("if ($download.Missing) {", retry)+ assert fallback < api_call < retry < fatal+++def test_windows_installer_does_not_fall_back_for_an_explicit_version_pin() -> None:+ source = _windows_source()++ assert "$Script:CuaDriverRsVersionSource = 'env'" in source+ assert "$Script:CuaDriverRsVersionSource = 'release-arg'" in source+ # Exactly one fallback site, and it is gated on the baked provenance, so+ # neither pin route can reach it.+ assert source.count("$Script:CuaDriverRsVersionSource -eq 'baked'") == 1+++def test_windows_installer_adopts_the_version_that_actually_downloaded() -> None:+ """A fallback changes the install path and the cursor-theme capability check.++ Get-ReleaseAsset therefore returns the resolved version, and the caller must+ re-derive $versionedDir from it before staging anything.+ """+ source = _windows_source()++ assert "return @{ StageDir = $stageDir; Version = $version }" in source++ adopt = source.index("if ($asset.Version -ne $version) {")+ assert source.index("$version = $asset.Version", adopt) < source.index(+ "$versionedDir = Join-Path $ReleasesDir", adopt+ )+ # The retarget has to precede the directory creation that consumes it.+ assert adopt < source.index("New-Item -ItemType Directory -Force -Path $versionedDir", adopt)+++def test_windows_installer_rechecks_an_already_installed_fallback_before_copy() -> None:+ """A running fallback binary is locked on Windows and must not be overwritten."""+ source = _windows_source()+ adopt = source.index("if ($asset.Version -ne $version) {")+ recheck = source.index(+ "if (Test-Path -LiteralPath (Join-Path $versionedDir $BinaryName))", adopt+ )+ copy = source.index(+ "Copy-Item -LiteralPath (Join-Path $stageDir $BinaryName)", recheck+ )+ assert adopt < recheck < copy+++def test_windows_api_resolver_avoids_the_automatic_matches_variable() -> None:+ """$matches is clobbered by every `-match`; a local of that name is a trap."""+ source = _windows_source()+ body = source[+ source.index("function Get-LatestVersionFromApi") : source.index("function Resolve-Version")+ ]+ code = "\n".join(line for line in body.splitlines() if not line.lstrip().startswith("#"))++ assert "$releaseMatches" in code+ # Word-boundary match so $releaseMatches does not count as a hit.+ assert not re.search(r"\$matches\b", code)+++def test_windows_api_resolver_accepts_published_stable_tags_marked_prerelease() -> None:+ """Cua Driver releases use GitHub's prerelease flag despite stable x.y.z tags."""+ source = _windows_source()+ body = source[+ source.index("function Get-LatestVersionFromApi") : source.index(+ "function Resolve-Version"+ )+ ]+ assert "(-not $_.draft)" in body+ assert "(-not $_.prerelease)" not in body+ assert "[0-9]+\\.[0-9]+\\.[0-9]+" in body+++@requires_powershell+ ("scenario", "missing", "attempts", "has_error"),+ [+ ("missing", True, 1, False),+ ("server", False, 3, True),+ ("network", False, 3, True),+ ("auth", False, 1, True),+ ],+)+def test_windows_download_classifies_and_retries_failures_behaviorally(+ tmp_path: Path,+ scenario: str,+ missing: bool,+ attempts: int,+ has_error: bool,+) -> None:+ source = _windows_source()+ with _powershell_download_server(scenario) as (base_url, requests):+ functions = "\n\n".join(+ _extract_powershell_function(source, name)+ for name in (+ "Get-HttpStatusCode",+ "Test-TransientDownloadFailure",+ "Get-ReleaseZip",+ )+ )+ functions = functions.replace(+ "https://github.com/$Repo/releases/download/",+ f"{base_url}/",+ ).replace(+ "Start-Sleep -Seconds $delaySeconds",+ "$null = $delaySeconds",+ )+ result = _run_powershell(+ tmp_path,+ f"""+$Repo = 'trycua/cua'+$TagPrefix = 'cua-driver-rs-v'+function Write-Step {{ param([string]$Message) }}+function Write-WarningStep {{ param([string]$Message) }}++{functions}++$download = Get-ReleaseZip '1.2.3' 'windows-x86_64' '{tmp_path.as_posix()}'+[pscustomobject]@{{+ Missing = [bool]$download.Missing+ Attempts = [int]$download.Attempts+ HasError = [bool]$download.ErrorMessage+}} | ConvertTo-Json -Compress+""",+ )+ observed = json.loads(result.stdout)+ assert observed == {+ "Missing": missing,+ "Attempts": attempts,+ "HasError": has_error,+ }+ if scenario == "network":+ # Invoke-WebRequest has its own transport retry on a dropped socket;+ # the installer-level Attempts count must still remain bounded at three.+ assert len(requests) >= attempts+ else:+ assert len(requests) == attempts+++@requires_powershell+def test_windows_api_resolver_filters_drafts_but_accepts_stable_prereleases(+ tmp_path: Path,+) -> None:+ source = _windows_source()+ functions = "\n\n".join(+ _extract_powershell_function(source, name)+ for name in ("Get-GitHubApiHeaders", "Get-LatestVersionFromApi")+ )+ result = _run_powershell(+ tmp_path,+ f"""+$Repo = 'trycua/cua'+$TagPrefix = 'cua-driver-rs-v'+function Write-Step {{ param([string]$Message) }}+function Write-WarningStep {{ param([string]$Message) }}+function Invoke-RestMethod {{+ param(+ [string]$Uri,+ [hashtable]$Headers,+ [switch]$UseBasicParsing+ )+ @(+ [pscustomobject]@{{ tag_name = 'cua-driver-rs-v9.0.0'; draft = $true; prerelease = $false }}+ [pscustomobject]@{{ tag_name = 'cua-driver-rs-v1.20.3'; draft = $false; prerelease = $true }}+ [pscustomobject]@{{ tag_name = 'cua-driver-rs-v8.0.0-rc.1'; draft = $false; prerelease = $false }}+ )+}}++{functions}++Get-LatestVersionFromApi+""",+ )+ assert result.stdout.strip() == "1.20.3"+++# ---------- Unix ----------------------------------------------------------+++def test_unix_installer_falls_back_when_baked_release_is_unpublished() -> None:+ source = _unix_source()++ assert 'VERSION_SOURCE="baked"' in source++ fallback = source.index('download_release_tarball "$VERSION" || DOWNLOAD_STATUS=$?')+ guard = source.index(+ 'if [[ "$VERSION_SOURCE" != "baked" || "$DOWNLOAD_STATUS" != "44" ]]; then',+ fallback,+ )+ api_call = source.index('API_VERSION="$(resolve_latest_version_from_api)"', guard)+ adopt = source.index('VERSION="$API_VERSION"', api_call)+ retry = source.index('download_release_tarball "$VERSION" || DOWNLOAD_STATUS=$?', adopt)+ assert fallback < guard < api_call < adopt < retry+++def test_unix_installer_does_not_fall_back_for_an_explicit_version_pin() -> None:+ source = _unix_source()++ assert 'VERSION_SOURCE="pin"' in source+ # The non-baked route exits before reaching the API recovery below it,+ # including when its requested asset is a confirmed 404.+ guard = source.index(+ 'if [[ "$VERSION_SOURCE" != "baked" || "$DOWNLOAD_STATUS" != "44" ]]; then'+ )+ assert source.index("exit 1", guard) < source.index("resolve_latest_version_from_api", guard)+++def test_unix_installer_recomputes_the_tarball_after_a_fallback() -> None:+ """Every release-derived name must be computed after VERSION settles."""+ source = _unix_source()++ assert source.index('TARBALL="$(release_tarball_name "$VERSION")"') < source.index(+ 'tar -xzf "$TMP_DIR/$TARBALL"'+ )+ adopt = source.index('VERSION="$API_VERSION"')+ retag = source.index('TAG="${TAG_PREFIX}${VERSION}"', adopt)+ archive = source.index('TARBALL="$(release_tarball_name "$VERSION")"', retag)+ stage = source.index('STAGE="cua-driver-rs-${VERSION}-darwin-universal"', archive)+ assert adopt < retag < archive < stage+++def test_unix_api_resolver_queries_bounded_full_pages() -> None:+ """The repo interleaves lume/Python/Swift releases with these.++ A short page can contain no cua-driver-rs-v* tag at all and make a healthy+ repo look empty — which would turn the new fallback into a dead end.+ """+ source = _unix_source()+ assert "per_page=100" in source+ assert "page=$page" in source+ assert "page<=10" in source+ assert "per_page=40" not in source+++def _extract_shell_function(source: str, name: str) -> str:+ match = re.search(rf"^{re.escape(name)}\(\) \{{.*?^\}}", source, re.MULTILINE | re.DOTALL)+ assert match, f"could not locate shell function {name}()"+ return match.group(0)+++def _run_resolver(tmp_path: Path, releases_json: str, epilogue: str, strict: bool) -> str:+ """Runs the real resolver function with curl shadowed by a shell function.++ A function shim beats a PATH shim here: it needs no exec bit and no PATH+ entry, so the harness behaves the same whether the test host is Linux,+ macOS, or a Windows checkout whose drive letters would otherwise collide+ with the ':' PATH separator.+ """+ fixture = tmp_path / "releases.json"+ fixture.write_text(releases_json, encoding="utf-8")++ script = tmp_path / "run.sh"+ script.write_text(+ textwrap.dedent("""\+ set -{flags}uo pipefail+ REPO="trycua/cua"+ TAG_PREFIX="cua-driver-rs-v"+ curl() {{ cat "{fixture}"; }}+ {github_api_curl}+ {published_versions}+ {resolver}+ {epilogue}+ """).format(+ # `set -euo pipefail` when the resolver is expected to succeed;+ # `set -uo pipefail` when the test asserts on its non-zero return,+ # which -e would otherwise turn into an abort before the assertion.+ flags="e" if strict else "",+ fixture=fixture.as_posix(),+ github_api_curl=_extract_shell_function(_unix_source(), "github_api_curl"),+ published_versions=_extract_shell_function(+ _unix_source(), "extract_published_release_versions"+ ),+ resolver=_extract_shell_function(_unix_source(), "resolve_latest_version_from_api"),+ epilogue=epilogue,+ ),+ encoding="utf-8",+ )++ result = subprocess.run(["bash", script.as_posix()], capture_output=True, text=True, check=True)+ return result.stdout.strip()+++@requires_posix_bash+def test_unix_api_resolver_picks_the_highest_semver(tmp_path: Path) -> None:+ """Behavioral check on the grep/sed/sort pipeline, with curl stubbed.++ 0.9.1 sorts above 0.12.6 lexicographically, so this fails if the numeric+ sort keys regress. The unrelated cua-driver-v* and lume-v* tags must be+ filtered out entirely.+ """+ resolved = _run_resolver(+ tmp_path,+ """+ [+ {+ "tag_name": "cua-driver-v9.9.9",+ "draft": false+ },+ {+ "tag_name": "cua-driver-rs-v0.9.1",+ "draft": false+ },+ {+ "tag_name": "cua-driver-rs-v0.12.6",+ "draft": false+ },+ {+ "tag_name": "cua-driver-rs-v0.11.0",+ "draft": false+ },+ {+ "tag_name": "lume-v0.4.0",+ "draft": false+ }+ ]+ """,+ epilogue="resolve_latest_version_from_api",+ strict=True,+ )+ assert resolved == "0.12.6"+++@requires_posix_bash+def test_unix_api_resolver_fails_when_no_tag_matches(tmp_path: Path) -> None:+ """A miss must return non-zero so the caller can report it, not print junk."""+ resolved = _run_resolver(+ tmp_path,+ '[\n {\n "tag_name": "lume-v0.4.0",\n "draft": false\n }\n]',+ epilogue="if resolve_latest_version_from_api; then echo RESOLVED; else echo NOMATCH; fi",+ strict=False,+ )+ assert resolved == "NOMATCH"+++@requires_posix_bash+def test_unix_api_resolver_rejects_prerelease_and_malformed_tags(tmp_path: Path) -> None:+ resolved = _run_resolver(+ tmp_path,+ """+ [+ {+ "tag_name": "cua-driver-rs-v9.0.0-rc.1",+ "draft": false+ },+ {+ "tag_name": "cua-driver-rs-v8.0.0+build.1",+ "draft": false+ },+ {+ "tag_name": "cua-driver-rs-v7.0.0.1",+ "draft": false+ },+ {+ "tag_name": "cua-driver-rs-v6.0",+ "draft": false+ },+ {+ "tag_name": "cua-driver-rs-v5.4.3",+ "draft": false+ }+ ]+ """,+ epilogue="resolve_latest_version_from_api",+ strict=True,+ )+ assert resolved == "5.4.3"+++@requires_posix_bash+def test_unix_api_resolver_rejects_drafts_but_accepts_stable_prereleases(+ tmp_path: Path,+) -> None:+ resolved = _run_resolver(+ tmp_path,+ """+ [+ {+ "tag_name": "cua-driver-rs-v9.0.0",+ "draft": true,+ "prerelease": false+ },+ {+ "tag_name": "cua-driver-rs-v1.20.3",+ "draft": false,+ "prerelease": true+ }+ ]+ """,+ epilogue="resolve_latest_version_from_api",+ strict=True,+ )+ assert resolved == "1.20.3"+++@requires_posix_bash+def test_unix_api_resolver_paginates_and_sends_token_header(tmp_path: Path) -> None:+ calls = tmp_path / "calls"+ filler = ",\n".join(+ f' {{\n "tag_name": "lume-v1.0.{i}",\n "draft": false\n }}'+ for i in range(100)+ )+ page_one = tmp_path / "page-1.json"+ page_two = tmp_path / "page-2.json"+ page_one.write_text(f"[\n{filler}\n]", encoding="utf-8")+ page_two.write_text(+ (+ '[\n {\n "tag_name": "cua-driver-rs-v1.20.3",\n'+ ' "draft": false,\n "prerelease": true\n }\n]'+ ),+ encoding="utf-8",+ )+ script = tmp_path / "run-pages.sh"+ script.write_text(+ textwrap.dedent(+ f"""\+ set -euo pipefail+ REPO="trycua/cua"+ TAG_PREFIX="cua-driver-rs-v"+ GH_TOKEN="test-token"+ curl() {{+ printf '%s\\n' "$*" >> "{calls.as_posix()}"+ case "$*" in+ *"&page=1"*) cat "{page_one.as_posix()}" ;;+ *"&page=2"*) cat "{page_two.as_posix()}" ;;+ *) return 99 ;;+ esac+ }}+ {_extract_shell_function(_unix_source(), "github_api_curl")}+ {_extract_shell_function(_unix_source(), "extract_published_release_versions")}+ {_extract_shell_function(_unix_source(), "resolve_latest_version_from_api")}+ resolve_latest_version_from_api+ """+ ),+ encoding="utf-8",+ )+ result = subprocess.run(+ ["bash", script.as_posix()], capture_output=True, text=True, check=True+ )++ assert result.stdout == "1.20.3"+ call_lines = calls.read_text(encoding="utf-8").splitlines()+ assert len(call_lines) == 2+ assert all("Authorization: Bearer test-token" in line for line in call_lines)+ assert all("page=3" not in line for line in call_lines)+++def _run_download(tmp_path: Path, scenario: str, token_env: str = "") -> tuple[int, list[str], str]:+ """Run the real download helper with deterministic HTTP/curl behavior."""+ calls = tmp_path / "download-calls"+ script = tmp_path / "run-download.sh"+ script.write_text(+ textwrap.dedent(+ f"""\+ set -uo pipefail+ REPO="trycua/cua"+ TAG_PREFIX="cua-driver-rs-v"+ LABEL="linux-x86_64"+ TMP_DIR="{tmp_path.as_posix()}"+ {token_env}+ log() {{ printf '==> %s\\n' "$*"; }}+ err() {{ printf 'error: %s\\n' "$*" >&2; }}+ sleep() {{ :; }}+ curl() {{+ printf '%s\\n' "$*" >> "{calls.as_posix()}"+ local output="" previous="" arg+ for arg in "$@"; do+ if [[ "$previous" == "-o" ]]; then output="$arg"; fi+ previous="$arg"+ done+ case "{scenario}" in+ success)+ printf 'archive' > "$output"+ printf '200'+ return 0+ ;;+ missing)+ printf '404'+ return 0+ ;;+ transient)+ printf '503'+ return 0+ ;;+ auth)+ printf '401'+ return 0+ ;;+ network)+ printf '000'+ return 7+ ;;+ esac+ }}+ {_extract_shell_function(_unix_source(), "release_tarball_name")}+ {_extract_shell_function(_unix_source(), "download_release_tarball")}+ download_release_tarball "1.2.3"+ """+ ),+ encoding="utf-8",+ )+ result = subprocess.run(["bash", script.as_posix()], capture_output=True, text=True)+ call_lines = calls.read_text(encoding="utf-8").splitlines()+ return result.returncode, call_lines, result.stderr+++@requires_posix_bash+def test_unix_download_reports_confirmed_404_without_retry(tmp_path: Path) -> None:+ returncode, calls, _ = _run_download(tmp_path, "missing")+ assert returncode == 44+ assert len(calls) == 1+++@requires_posix_bash[email protected]("scenario", ["transient", "network"])+def test_unix_download_retries_transient_failure_without_fallback(+ tmp_path: Path, scenario: str+) -> None:+ returncode, calls, stderr = _run_download(tmp_path, scenario)+ assert returncode == 1+ assert len(calls) == 3+ assert "refusing to fall back to an older release" in stderr+++@requires_posix_bash+def test_unix_download_does_not_retry_auth_failure_or_fallback(tmp_path: Path) -> None:+ returncode, calls, stderr = _run_download(tmp_path, "auth")+ assert returncode == 1+ assert len(calls) == 1+ assert "HTTP 401" in stderr+ assert "refusing to fall back to an older release" in stderr+++@requires_posix_bash+def test_unix_public_asset_download_does_not_forward_api_token(tmp_path: Path) -> None:+ returncode, calls, stderr = _run_download(tmp_path, "success", 'GITHUB_TOKEN="api-token"')+ assert returncode == 0+ assert len(calls) == 1+ assert "Authorization:" not in calls[0]+ assert "api-token" not in stderr+++def _run_fallback_flow(+ tmp_path: Path, *, version_source: str, download_statuses: list[int]+) -> tuple[subprocess.CompletedProcess[str], list[str]]:+ """Execute the installer's real post-download fallback control flow."""+ source = _unix_source()+ start = source.index("DOWNLOAD_STATUS=0\n")+ end = source.index('TARBALL="$(release_tarball_name "$VERSION")"', start)+ flow = source[start:end]+ statuses = " ".join(str(status) for status in download_statuses)+ calls = tmp_path / "flow-calls"+ script = tmp_path / "run-flow.sh"+ script.write_text(+ textwrap.dedent(+ f"""\+ set -uo pipefail+ VERSION_SOURCE="{version_source}"+ VERSION="1.2.3"+ TAG_PREFIX="cua-driver-rs-v"+ TAG="${{TAG_PREFIX}}${{VERSION}}"+ LABEL="linux-x86_64"+ REPO="trycua/cua"+ DOWNLOAD_RESULTS=({statuses})+ DOWNLOAD_INDEX=0+ err() {{ printf 'error: %s\\n' "$*" >&2; }}+ download_release_tarball() {{+ printf 'download:%s\\n' "$1" >> "{calls.as_posix()}"+ local result="${{DOWNLOAD_RESULTS[$DOWNLOAD_INDEX]}}"+ DOWNLOAD_INDEX=$((DOWNLOAD_INDEX + 1))+ return "$result"+ }}+ resolve_latest_version_from_api() {{+ printf 'api\\n' >> "{calls.as_posix()}"+ printf '1.2.2'+ }}+ {flow}+ printf 'resolved:%s:%s\\n' "$VERSION" "$TAG"+ """+ ),+ encoding="utf-8",+ )+ result = subprocess.run(["bash", script.as_posix()], capture_output=True, text=True)+ call_lines = calls.read_text(encoding="utf-8").splitlines()+ return result, call_lines+++@requires_posix_bash+def test_unix_baked_404_falls_back_and_adopts_downloaded_version(tmp_path: Path) -> None:+ result, calls = _run_fallback_flow(+ tmp_path, version_source="baked", download_statuses=[44, 0]+ )+ assert result.returncode == 0+ assert calls == ["download:1.2.3", "api", "download:1.2.2"]+ assert result.stdout == "resolved:1.2.2:cua-driver-rs-v1.2.2\n"+ assert "temporary publish lag" in result.stderr+++@requires_posix_bash+ ("version_source", "download_status"),+ [("pin", 44), ("pin", 1), ("baked", 1)],+)+def test_unix_non_fallback_download_failure_makes_zero_api_calls(+ tmp_path: Path, version_source: str, download_status: int+) -> None:+ result, calls = _run_fallback_flow(+ tmp_path, version_source=version_source, download_statuses=[download_status]+ )+ assert result.returncode == 1+ assert calls == ["download:1.2.3"]