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: never ship a CLI that pins an unpublished cua-spacesd (#4473)
ddupontda46c4bc85bc
diff --git a/.github/scripts/check_spacesd_published.sh b/.github/scripts/check_spacesd_published.shnew file mode 100755index 0000000000..a74755fb1e--- /dev/null+++ b/.github/scripts/check_spacesd_published.sh@@ -0,0 +1,60 @@+#!/usr/bin/env bash+# Fails unless the cua-spacesd release the `cua` CLI bakes in+# (libs/cua-spacesd/VERSION, read by cua-host's driver.rs) is PUBLISHED on+# REPO with every artifact `cua host setup` downloads, each reachable+# anonymously, the way an end user's machine fetches it.+#+# Cua Spaces 0.3.0 shipped a CLI pinned to cua-spacesd 0.2.0, a release that+# stayed an empty draft, so "Set up for access" 404'd for everyone. Release+# workflows that bake the CLI (cd-cua-spaces.yml, cd-cua-sdk.yml) and the+# Release Please PR check run this before building anything.+#+# Usage: check_spacesd_published.sh [REPO] (default: $GITHUB_REPOSITORY,+# else trycua/cua). Needs `gh` (GH_TOKEN) and curl.+# A prerelease counts as published only off trycua/cua (staging publishes+# its cua-spacesd releases as prereleases).+set -euo pipefail++REPO="${1:-${GITHUB_REPOSITORY:-trycua/cua}}"+ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd)"+VERSION="$(tr -d '[:space:]' < "$ROOT/libs/cua-spacesd/VERSION")"+TAG="cua-spacesd-v$VERSION"++# cua-host's artifact_name(): cua-spacesd-<os>-<arch>.tar.gz plus the+# .sha256 it requires, for each platform cd-cua-spacesd.yml publishes.+ASSETS=()+for p in macos-aarch64 macos-x86_64 linux-x86_64 linux-aarch64 windows-x86_64; do+ ASSETS+=("cua-spacesd-$p.tar.gz" "cua-spacesd-$p.tar.gz.sha256")+done++fail() {+ echo "::error title=cua-spacesd $VERSION is not published::$*"+ echo "This build bakes cua-spacesd $VERSION (libs/cua-spacesd/VERSION) into the cua CLI," >&2+ echo "and \`cua host setup\` downloads it from https://github.com/$REPO/releases/tag/$TAG." >&2+ echo "Publish that release first (CD: cua-spacesd, or merge its Release Please PR)," >&2+ echo "or set libs/cua-spacesd/VERSION back to a published release." >&2+ exit 1+}++# The API answers 404 for a draft looked up by tag.+if ! json="$(gh api "repos/$REPO/releases/tags/$TAG" 2>/dev/null)"; then+ fail "$REPO has no published release $TAG (missing, or still a draft)"+fi+[ "$(jq -r .draft <<<"$json")" = false ] || fail "$TAG is still a draft"+if [ "$REPO" = trycua/cua ] && [ "$(jq -r .prerelease <<<"$json")" != false ]; then+ fail "$TAG is a prerelease; a release build must pin a full cua-spacesd release"+fi++missing=()+for name in "${ASSETS[@]}"; do+ url="$(jq -r --arg n "$name" '.assets[] | select(.name == $n) | .browser_download_url' <<<"$json")"+ if [ -z "$url" ]; then+ missing+=("$name (not attached)")+ elif ! curl -fsSIL --retry 3 --max-time 60 -o /dev/null "$url"; then+ missing+=("$name (not downloadable: $url)")+ fi+done+if [ ${#missing[@]} -gt 0 ]; then+ fail "$TAG lacks: ${missing[*]}"+fi+echo "cua-spacesd $VERSION is published on $REPO with all ${#ASSETS[@]} host-setup assets."diff --git a/.github/workflows/cd-cua-sdk.yml b/.github/workflows/cd-cua-sdk.ymlindex 295431bd25..2613aa54b1 100644--- a/.github/workflows/cd-cua-sdk.yml+++ b/.github/workflows/cd-cua-sdk.yml@@ -70,7 +70,18 @@ jobs:tag: ${{ steps.v.outputs.tag }}publish: ${{ steps.v.outputs.publish }}prerelease: ${{ steps.v.outputs.prerelease }}+ permissions:+ contents: readsteps:+ - uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4+ # The `cua` CLI bakes libs/cua-spacesd/VERSION and `cua host setup`+ # downloads that release: every job needs this one, so nothing builds+ # or publishes while the pinned cua-spacesd is unpublished (Cua Spaces+ # 0.3.0 shipped a CLI pinned to a draft).+ - name: Check the baked cua-spacesd release is published+ env:+ GH_TOKEN: ${{ github.token }}+ run: .github/scripts/check_spacesd_published.sh "$CUA_RELEASE_REPOSITORY"- id: vshell: bashrun: |diff --git a/.github/workflows/cd-cua-spaces.yml b/.github/workflows/cd-cua-spaces.ymlindex 11f16da3b3..a4e88bf086 100644--- a/.github/workflows/cd-cua-spaces.yml+++ b/.github/workflows/cd-cua-spaces.yml@@ -140,8 +140,28 @@ env:REQUIRE_SIGNING: ${{ github.repository == 'trycua/cua' && startsWith(github.ref, 'refs/tags/') }}jobs:+ # The bundled `cua` CLI bakes libs/cua-spacesd/VERSION and "Set up for+ # access" downloads that release: refuse to build an app whose pinned+ # cua-spacesd is not published (Cua Spaces 0.3.0 pinned a draft).+ spacesd-published:+ name: cua-spacesd pin is published+ runs-on: ubuntu-latest+ timeout-minutes: 10+ defaults:+ run:+ working-directory: .+ permissions:+ contents: read+ steps:+ - uses: actions/checkout@v4+ - name: Check the baked cua-spacesd release+ env:+ GH_TOKEN: ${{ github.token }}+ run: .github/scripts/check_spacesd_published.sh "$CUA_RELEASE_REPOSITORY"+build-macos:name: darwin-universal (SwiftUI)+ needs: spacesd-publishedruns-on: macos-26timeout-minutes: 180defaults:diff --git a/.github/workflows/ci-release-spacesd-pin.yml b/.github/workflows/ci-release-spacesd-pin.ymlnew file mode 100644index 0000000000..3b8a4e8f6a--- /dev/null+++ b/.github/workflows/ci-release-spacesd-pin.yml@@ -0,0 +1,53 @@+name: "CI: Release cua-spacesd pin"++# A Cua Spaces or cua SDK Release Please PR stays red while the cua-spacesd+# its `cua` CLI bakes (libs/cua-spacesd/VERSION) has no published release:+# merging it would cut a release whose "Set up for access" downloads a+# missing cua-spacesd (Cua Spaces 0.3.0 pinned an empty 0.2.0 draft). Publish+# cua-spacesd first, then re-run this check. cd-cua-spaces.yml and+# cd-cua-sdk.yml run the same check before building, so a tag pushed anyway+# still fails closed.++on:+ pull_request:+ types: [opened, synchronize, reopened, edited]+ paths:+ - .release-please-manifest.json+ - libs/cua-spacesd/VERSION++permissions:+ contents: read++jobs:+ spacesd-published:+ name: cua-spacesd pin is published+ if: startsWith(github.head_ref, 'release-please--branches--')+ runs-on: ubuntu-latest+ timeout-minutes: 10+ steps:+ - uses: actions/checkout@v4+ with:+ fetch-depth: 0+ ref: ${{ github.event.pull_request.head.sha }}+ - name: Does this PR release Cua Spaces or the cua SDK?+ id: scope+ env:+ BASE_SHA: ${{ github.event.pull_request.base.sha }}+ HEAD_SHA: ${{ github.event.pull_request.head.sha }}+ run: |+ set -euo pipefail+ bakes=false+ for key in apps/cua-spaces-macos libs/cua; do+ before="$(git show "$BASE_SHA:.release-please-manifest.json" | jq -r --arg k "$key" '.[$k] // ""')"+ after="$(git show "$HEAD_SHA:.release-please-manifest.json" | jq -r --arg k "$key" '.[$k] // ""')"+ if [ "$before" != "$after" ]; then+ echo "$key: $before -> $after"+ bakes=true+ fi+ done+ echo "bakes=$bakes" >> "$GITHUB_OUTPUT"+ - name: Check the baked cua-spacesd release+ if: steps.scope.outputs.bakes == 'true'+ env:+ GH_TOKEN: ${{ github.token }}+ run: .github/scripts/check_spacesd_published.sh "$GITHUB_REPOSITORY"diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostModel.swiftindex be58ca8d6a..e6014ba26f 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostModel.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostModel.swift@@ -104,6 +104,12 @@ public final class HostModel {public private(set) var form: AppHostFormState?public private(set) var busy = falsepublic private(set) var error: String?+ /// The last "Set up for access" failure, in plain words with the raw+ /// error as details. It stays while a retry runs (so Retry can show+ /// progress) and clears when setup succeeds or the form closes.+ public private(set) var setupFailure: HostSetupFailure?+ /// "Set up for access" (or Retry) is running.+ public var settingUp: Bool { formView?.busy == true }/// The signed-in account (relay mode joins as it).public var identity: String?/// The account's token for relay setup.@@ -139,16 +145,21 @@ public final class HostModel {public func openForm() {form = appHostFormInitial()error = nil+ setupFailure = nil}- public func closeForm() { form = nil }+ public func closeForm() {+ form = nil+ setupFailure = nil+ }public func send(_ action: AppHostFormAction) {guard let f = form else { return }form = appHostFormReduce(state: f, action: action)}- /// "Set up for access": host setup with the core's validated request.+ /// "Set up for access" (and Retry, which runs it again with the same+ /// choices): host setup with the core's validated request.public func submit() async {guard let host, let view = formView, view.canSubmit, let request = view.request else { return }send(.submit)@@ -156,9 +167,12 @@ public final class HostModel {let token: String? = request.mode == "relay" ? await accountToken?() : nillet status = try await host.setupRequest(request: request, accountToken: token)form = nil+ setupFailure = nilapply(status)} catch {- send(.failed(error: LiveSpacesBackend.words(error)))+ let raw = LiveSpacesBackend.words(error)+ setupFailure = HostSetupFailure.presenting(raw)+ send(.failed(error: raw))}}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostSetupFailure.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostSetupFailure.swiftnew file mode 100644index 0000000000..be5cf34a08--- /dev/null+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/HostSetupFailure.swift@@ -0,0 +1,92 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import Foundation++/// A failed "Set up for access", in words a person can act on: a short+/// title, one plain message (never a URL or a raw error), and the raw error+/// kept unchanged for the Details disclosure.+public struct HostSetupFailure: Equatable, Sendable {+ public enum Kind: Equatable, Sendable {+ /// The host service (cua-spacesd) could not be downloaded.+ case download+ /// No network, a timeout, or a server that could not be reached.+ case network+ /// No one is signed in at this Mac's screen (launchd's Aqua session).+ case guiSession+ /// The Cua account is signed out or its session expired.+ case signedOut+ case other+ }++ public let kind: Kind+ public let title: String+ public let message: String+ /// The raw error, as the setup reported it.+ public let details: String++ public static let retryLabel = "Retry"+ public static let retryingLabel = "Retrying\u{2026}"+ public static let detailsLabel = "Details"+ public static let copyLabel = "Copy"++ /// Maps the raw setup error to what the sheet shows.+ public static func presenting(_ raw: String) -> HostSetupFailure {+ let kind = classify(raw)+ let (title, message) = words(kind)+ return HostSetupFailure(kind: kind, title: title, message: message, details: raw)+ }++ static func classify(_ raw: String) -> Kind {+ let s = raw.lowercased()+ func any(_ needles: [String]) -> Bool { needles.contains { s.contains($0) } }+ func word(_ pattern: String) -> Bool {+ s.range(of: "\\b\(pattern)\\b", options: .regularExpression) != nil+ }++ let downloading = any(["download:", "download failed", "cua-spacesd"])+ let unavailable = word("404") || any(["not found", "no published", "not available", "unavailable"])+ if downloading && unavailable { return .download }++ if any([+ "timed out", "timeout", "offline", "not connected to the internet", "network is unreachable",+ "network unreachable", "connection refused", "connection reset", "connection closed",+ "could not resolve", "couldn't resolve", "failed to lookup", "dns error", "dns lookup",+ "error sending request", "host is unreachable", "no route to host", "tls handshake",+ ]) { return .network }++ if any(["aqua", "no gui session", "gui session", "not logged in at the console", "console user",+ "no console"]) { return .guiSession }++ if word("401") || any([+ "signed out", "not signed in", "sign in again", "please sign in", "unauthenticated", "unauthorized",+ "login required", "not logged in", "session expired", "token expired", "invalid token",+ "no account token", "missing account token",+ ]) { return .signedOut }++ if any(["download:", "download failed"]) { return .download }+ return .other+ }++ static func words(_ kind: Kind) -> (String, String) {+ switch kind {+ case .download:+ return ("Couldn\u{2019}t download the Cua host service",+ "The service this Mac needs to accept connections isn\u{2019}t available right now. "+ + "Check your internet connection and try again; if it keeps failing, update Cua Spaces.")+ case .network:+ return ("Couldn\u{2019}t connect",+ "Cua Spaces couldn\u{2019}t reach the internet. Check your connection and try again.")+ case .guiSession:+ return ("Sign in to this Mac first",+ "Setting up access needs someone signed in at this Mac\u{2019}s own screen, not only over "+ + "SSH or Screen Sharing. Sign in at the Mac, then try again.")+ case .signedOut:+ return ("Sign in to Cua",+ "Your Cua account isn\u{2019}t signed in on this Mac. Sign in, then try again.")+ case .other:+ return ("Couldn\u{2019}t set up this Mac for access",+ "Something went wrong. Try again, or open Details to see what happened.")+ }+ }+}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/OnboardingView.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/OnboardingView.swiftindex c5740908fe..c32bc366c7 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/OnboardingView.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/OnboardingView.swift@@ -216,8 +216,17 @@ public struct OnboardingView: View {}case .mode:if onboarding.showingHostForm {- HostFormView(host: onboarding.host, buttons: false)- .frame(height: 230)+ // A failed setup shows under the form, not inside its scroll.+ VStack(alignment: .leading, spacing: 8) {+ HostFormView(host: onboarding.host, buttons: false, showsFailure: false)+ .frame(height: 230)+ if let failure = onboarding.host.setupFailure {+ HostSetupFailureView(failure: failure, retrying: onboarding.host.settingUp) {+ Task { await onboarding.setUpHost() }+ }+ .padding(.horizontal, 20)+ }+ }} else {VStack(alignment: .leading, spacing: 10) {ForEach(v.choices, id: \.label) { choice indiff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/ThisMachineView.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/ThisMachineView.swiftindex 843cf38cfd..e89bb5c012 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/ThisMachineView.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Views/ThisMachineView.swift@@ -217,6 +217,9 @@ struct HostFormView: View {@Bindable var host: HostModel/// Draws Back and the submit button (onboarding draws its own).var buttons: Bool+ /// Shows a failed setup (and Retry) inside the form; onboarding draws+ /// it under the form instead.+ var showsFailure = truevar body: some View {if let v = host.formView {@@ -233,8 +236,10 @@ struct HostFormView: View {.foregroundStyle(.secondary).accessibilityIdentifier("host-advanced")ForEach(v.fields.filter(\.advanced), id: \.id) { field($0) }- if let error = v.error {- Text(error).foregroundStyle(.red).lineLimit(1).help(error)+ if showsFailure, let failure = host.setupFailure {+ HostSetupFailureView(failure: failure, retrying: v.busy) {+ Task { await host.submit() }+ }}}if buttons {@@ -282,3 +287,67 @@ struct HostFormView: View {}}}++/// A failed "Set up for access": a small warning symbol and a short title,+/// one secondary line saying what to do, Retry, and the raw error under a+/// collapsed Details (selectable, with Copy).+struct HostSetupFailureView: View {+ let failure: HostSetupFailure+ /// The retry is running: Retry shows progress and is disabled.+ let retrying: Bool+ let retry: () -> Void+ @State private var showDetails = false++ var body: some View {+ VStack(alignment: .leading, spacing: 6) {+ HStack(alignment: .firstTextBaseline, spacing: 6) {+ Image(systemName: "exclamationmark.triangle.fill")+ .symbolRenderingMode(.multicolor)+ .imageScale(.small)+ .accessibilityHidden(true)+ Text(failure.title).fontWeight(.medium)+ Spacer(minLength: 8)+ Button(action: retry) {+ HStack(spacing: 6) {+ if retrying { ProgressView().controlSize(.small) }+ Text(retrying ? HostSetupFailure.retryingLabel : HostSetupFailure.retryLabel)+ }+ }+ .controlSize(.small)+ .disabled(retrying)+ .accessibilityIdentifier("host-setup-retry")+ }+ Text(failure.message)+ .font(.callout)+ .foregroundStyle(.secondary)+ .fixedSize(horizontal: false, vertical: true)+ DisclosureGroup(HostSetupFailure.detailsLabel, isExpanded: $showDetails) {+ HStack(alignment: .top, spacing: 8) {+ // A long error scrolls instead of pushing the page.+ ScrollView {+ Text(failure.details)+ .font(.system(.caption, design: .monospaced))+ .foregroundStyle(.secondary)+ .textSelection(.enabled)+ .fixedSize(horizontal: false, vertical: true)+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ .frame(maxHeight: 80)+ Button(HostSetupFailure.copyLabel) {+ NSPasteboard.general.clearContents()+ NSPasteboard.general.setString(failure.details, forType: .string)+ }+ .buttonStyle(.borderless)+ .controlSize(.small)+ .accessibilityIdentifier("host-setup-copy-details")+ }+ .padding(.top, 2)+ }+ .font(.callout)+ .foregroundStyle(.secondary)+ .accessibilityIdentifier("host-setup-details")+ }+ .accessibilityElement(children: .contain)+ .accessibilityIdentifier("host-setup-failure")+ }+}diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostSetupFailureTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostSetupFailureTests.swiftnew file mode 100644index 0000000000..45f11672b9--- /dev/null+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/HostSetupFailureTests.swift@@ -0,0 +1,214 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++@testable import CuaSpacesMacKit+import CuaSDK+import CuaSpacesFFI+import Foundation+import Testing++@Suite("Host setup failure")+struct HostSetupFailureTests {+ static let missingRelease =+ "http: download: https://github.com/trycua/cua/releases/download/cua-spacesd-v0.2.0/"+ + "cua-spacesd-aarch64-apple-darwin.tar.gz: HTTP 404"++ @Test func aMissingReleaseIsADownloadFailureWithoutTheURL() {+ let f = HostSetupFailure.presenting(Self.missingRelease)+ #expect(f.kind == .download)+ #expect(f.title == "Couldn\u{2019}t download the Cua host service")+ #expect(f.message.contains("update Cua Spaces"))+ #expect(!f.message.contains("http"))+ #expect(!f.title.contains("http"))+ #expect(f.details == Self.missingRelease, "details stay raw")+ }++ @Test(arguments: [+ "cua-spacesd: no published release for this platform",+ "download: cua-spacesd v0.2.0 is not available",+ "Download failed: HTTP 404 Not Found",+ ])+ func releaseNotAvailableVariants(_ raw: String) {+ #expect(HostSetupFailure.presenting(raw).kind == .download)+ }++ @Test(arguments: [+ "error sending request for url (https://relay.cua.ai/v1/hosts): operation timed out",+ "The Internet connection appears to be offline.",+ "tcp connect error: Connection refused (os error 61)",+ "dns error: failed to lookup address information",+ "download: https://github.com/x: operation timed out",+ ])+ func networkFailures(_ raw: String) {+ let f = HostSetupFailure.presenting(raw)+ #expect(f.kind == .network)+ #expect(!f.message.contains("http"))+ }++ @Test(arguments: [+ "launchctl bootstrap gui/501: Bootstrap failed: 125: Domain does not support specified action (no Aqua session)",+ "no GUI session: sign in at the console",+ ])+ func guiSessionFailures(_ raw: String) {+ let f = HostSetupFailure.presenting(raw)+ #expect(f.kind == .guiSession)+ #expect(f.message.contains("Sign in at the Mac"))+ }++ @Test(arguments: [+ "relay: HTTP 401 Unauthorized",+ "not signed in: run `cua login`",+ "unauthenticated",+ ])+ func signedOutFailures(_ raw: String) {+ let f = HostSetupFailure.presenting(raw)+ #expect(f.kind == .signedOut)+ #expect(f.message.contains("Sign in"))+ }++ @Test func anythingElseIsGeneric() {+ let f = HostSetupFailure.presenting("launchctl bootstrap failed\nmore")+ #expect(f.kind == .other)+ #expect(f.title == "Couldn\u{2019}t set up this Mac for access")+ #expect(f.message == "Something went wrong. Try again, or open Details to see what happened.")+ #expect(f.details == "launchctl bootstrap failed\nmore")+ }++ @Test func aPortNumberIsNotAStatusCode() {+ #expect(HostSetupFailure.presenting("listen 0.0.0.0:14041 failed").kind == .other)+ }++ // MARK: - The model++ @MainActor func onboarding(_ host: HostRunning) -> OnboardingModel {+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent("cua-mac-tests-\(UUID().uuidString)")+ return OnboardingModel(statePath: dir.appendingPathComponent("onboarding.json").path, host: host)+ }++ @MainActor @Test func aFailedSetupKeepsTheRawErrorAsDetails() async {+ let host = FixtureHost()+ host.failSetup = Self.missingRelease + "\ncaused by: 404"+ let model = onboarding(host)+ model.host.openForm()+ await model.setUpHost()+ let failure = model.host.setupFailure+ #expect(failure?.kind == .download)+ #expect(failure?.details == Self.missingRelease + "\ncaused by: 404", "the whole error, every line")+ #expect(model.host.formView?.canSubmit == true, "Retry can run")+ #expect(!model.host.settingUp)+ #expect(model.showingHostForm)+ }++ @MainActor @Test func retryRunsTheSameChoiceAndClearsOnSuccess() async {+ let host = FixtureHost()+ host.failSetup = Self.missingRelease+ let model = onboarding(host)+ model.host.openForm()+ model.host.send(.setProfile(profile: "spare"))+ await model.setUpHost()+ #expect(model.host.setupFailure != nil)+ #expect(model.host.formView?.request?.profile == "spare", "the choice survives the failure")++ host.failSetup = nil+ await model.setUpHost()+ #expect(host.calls.count == 2)+ #expect(host.calls[0] == host.calls[1], "the retry sends the same request")+ #expect(model.host.setupFailure == nil)+ #expect(!model.showingHostForm)+ #expect(model.host.state?.configured == true)+ }++ @MainActor @Test func whileRetryingTheFailureStaysAndSetupIsBusy() async {+ let gate = GatedHost()+ let model = onboarding(gate)+ model.host.openForm()+ gate.fail = "no GUI session"+ await model.setUpHost()+ #expect(model.host.setupFailure?.kind == .guiSession)++ gate.fail = nil+ gate.hold = true+ let retry = Task { await model.setUpHost() }+ await gate.waitUntilCalled(times: 2)+ #expect(model.host.settingUp, "Retry shows progress and is disabled")+ #expect(model.host.formView?.canSubmit == false, "no second setup while one runs")+ #expect(model.host.setupFailure?.kind == .guiSession, "the failure stays while retrying")+ gate.release()+ await retry.value+ #expect(!model.host.settingUp)+ #expect(model.host.setupFailure == nil)+ }++ @MainActor @Test func closingTheFormClearsTheFailure() async {+ let host = FixtureHost()+ host.failSetup = "boom"+ let model = onboarding(host)+ model.host.openForm()+ await model.setUpHost()+ #expect(model.host.setupFailure != nil)+ model.host.closeForm()+ #expect(model.host.setupFailure == nil)+ model.host.openForm()+ #expect(model.host.setupFailure == nil)+ }+}++/// A host whose setup can fail or wait until released (no service, no+/// network: it wraps `FixtureHost`).+final class GatedHost: HostRunning, @unchecked Sendable {+ let inner = FixtureHost()+ var fail: String?+ var hold = false+ private var calls = 0+ private var held: CheckedContinuation<Void, Never>?+ private var callWaiters: [(Int, CheckedContinuation<Void, Never>)] = []+ private let lock = NSLock()++ func status() async throws -> HostStatus { try await inner.status() }++ func setupRequest(request: AppHostSetupRequest, accountToken: String?) async throws -> HostStatus {+ let (shouldHold, ready) = lock.withLock { () -> (Bool, [CheckedContinuation<Void, Never>]) in+ calls += 1+ let ready = callWaiters.filter { $0.0 <= calls }.map(\.1)+ callWaiters.removeAll { $0.0 <= calls }+ return (hold, ready)+ }+ ready.forEach { $0.resume() }+ if shouldHold { await withCheckedContinuation { c in lock.withLock { held = c } } }+ inner.failSetup = fail+ return try await inner.setupRequest(request: request, accountToken: accountToken)+ }++ func waitUntilCalled(times: Int) async {+ await withCheckedContinuation { c in+ let done = lock.withLock { () -> Bool in+ if calls >= times { return true }+ callWaiters.append((times, c))+ return false+ }+ if done { c.resume() }+ }+ }++ func release() {+ // The setup may not have parked yet: poll briefly for it.+ Task {+ while true {+ if let c = lock.withLock({ () -> CheckedContinuation<Void, Never>? in+ let c = held+ held = nil+ return c+ }) {+ c.resume()+ return+ }+ await Task.yield()+ }+ }+ }++ func stopSharing() async throws -> HostStatus { try await inner.stopSharing() }+ func startSharing() async throws -> HostStatus { try await inner.startSharing() }+ func remove() async throws { try await inner.remove() }+ func configure(change: HostSettingsChange) async throws -> HostStatus { try await inner.configure(change: change) }+}diff --git a/libs/cua-spacesd/README.md b/libs/cua-spacesd/README.mdindex 0f3e4e6a4d..301041253b 100644--- a/libs/cua-spacesd/README.md+++ b/libs/cua-spacesd/README.md@@ -179,6 +179,15 @@ bumps both. `packaging/release/package.sh` lists the assets and which installeruses each. `packaging/release/build-linux-docker.sh` reproduces the Linux joblocally in debian:11.+The `cua` CLI bakes `VERSION` and `cua host setup` downloads that release, so+publish cua-spacesd before releasing Cua Spaces or the cua SDK:+`cd-cua-spaces.yml`, `cd-cua-sdk.yml` and the Release Please PR check+(`ci-release-spacesd-pin.yml`) fail while the pinned release is missing, a+draft, or lacks a host-setup asset+(`.github/scripts/check_spacesd_published.sh`). An already-shipped CLI whose+pin is unavailable falls back to the newest published release on the same+major.minor, else the closest newer one on the same major.+## CratesThis workspace is server-only. Wire formats, codecs and clients live indiff --git a/libs/cua/crates/cua-host/src/driver.rs b/libs/cua/crates/cua-host/src/driver.rsindex 8730c1e49f..b002dc440a 100644--- a/libs/cua/crates/cua-host/src/driver.rs+++ b/libs/cua/crates/cua-host/src/driver.rs@@ -14,6 +14,14 @@//! version = $CUA_SPACESD_VERSION | the released driver version (libs/cua-spacesd/VERSION)//! os = linux | macos | windows, arch = x86_64 | aarch64//! ```+//!+//! When the base is the default (no `CUA_SPACESD_DOWNLOAD_BASE` or+//! `CUA_SPACESD_VERSION`) and the pinned release or its artifact is missing+//! (a release that never published, or is still a draft), [`install_to`]+//! falls back to the newest published, non-draft cua-spacesd release on the+//! same major.minor, else the closest newer one on the same major, and logs+//! that it did. The fallback artifact passes the same checksum check, against+//! the `.sha256` published in the release it actually uses.use crate::{Error, Result};use sha2::Digest as _;@@ -68,22 +76,40 @@ pub const RELEASE_REPOSITORY: &str = match option_env!("CUA_RELEASE_REPOSITORY")_ => "trycua/cua",};-/// Release download base (see the module docs).-pub fn download_base() -> String {- if let Some(b) = spacesd_env("DOWNLOAD_BASE")+/// `CUA_SPACESD_DOWNLOAD_BASE`, when set.+fn download_base_override() -> Option<String> {+ spacesd_env("DOWNLOAD_BASE").and_then(|v| v.into_string().ok()).filter(|v| !v.trim().is_empty())- {- return b.trim().trim_end_matches('/').to_string();- }- let version = spacesd_env("VERSION")+ .map(|b| b.trim().trim_end_matches('/').to_string())+}++/// `CUA_SPACESD_VERSION`, when set.+fn version_override() -> Option<String> {+ spacesd_env("VERSION").and_then(|v| v.into_string().ok()).filter(|v| !v.trim().is_empty())- .unwrap_or_else(|| SPACESD_VERSION.trim().to_string());- format!(- "https://github.com/{RELEASE_REPOSITORY}/releases/download/cua-spacesd-v{}",- version.trim_start_matches('v')- )+ .map(|v| v.trim().trim_start_matches('v').to_string())+}++/// `https://github.com/<repo>/releases/download/cua-spacesd-v<version>`.+fn release_base(version: &str) -> String {+ format!("https://github.com/{RELEASE_REPOSITORY}/releases/download/cua-spacesd-v{version}")+}++/// Release download base (see the module docs).+pub fn download_base() -> String {+ if let Some(b) = download_base_override() {+ return b;+ }+ let version = version_override().unwrap_or_else(|| SPACESD_VERSION.trim().to_string());+ release_base(&version)+}++/// The GitHub API listing of [`RELEASE_REPOSITORY`]'s releases (where the+/// fallback looks for a published cua-spacesd).+pub fn releases_api() -> String {+ format!("https://api.github.com/repos/{RELEASE_REPOSITORY}/releases")}/// Where the binary comes from.@@ -91,8 +117,20 @@ pub fn download_base() -> String {pub enum DriverSource {/// A local file.Local(PathBuf),- /// The release artifact (to download).+ /// An artifact URL to download as is (an explicit download base or+ /// version: no fallback).Download(String),+ /// The pinned cua-spacesd release built into this binary: `url` is its+ /// artifact; if that release is missing or unpublished, the newest+ /// compatible published release in `releases_api` is used instead.+ Release {+ /// The pinned version (`libs/cua-spacesd/VERSION`).+ version: String,+ /// The pinned release's artifact URL.+ url: String,+ /// The GitHub releases API listing to fall back on.+ releases_api: String,+ },}/// Resolves the source without touching the network.@@ -132,11 +170,15 @@ pub fn locate(explicit: Option<&Path>) -> Result<DriverSource> {}}}- Ok(DriverSource::Download(format!(- "{}/{}",- download_base(),- artifact_name()- )))+ let url = format!("{}/{}", download_base(), artifact_name());+ if download_base_override().is_some() || version_override().is_some() {+ return Ok(DriverSource::Download(url));+ }+ Ok(DriverSource::Release {+ version: SPACESD_VERSION.trim().to_string(),+ url,+ releases_api: releases_api(),+ })}/// Puts the driver at `dest` (copying a local binary or downloading and@@ -158,6 +200,15 @@ pub async fn install_to(source: &DriverSource, dest: &Path) -> Result<()> {let binary = extract_binary(&bytes)?;std::fs::write(&tmp, binary)?;}+ DriverSource::Release {+ version,+ url,+ releases_api,+ } => {+ let (_used, bytes) = download_release(version, url, releases_api).await?;+ let binary = extract_binary(&bytes)?;+ std::fs::write(&tmp, binary)?;+ }}#[cfg(unix)]{@@ -193,19 +244,39 @@ fn allowed_download_url(url: &url::Url) -> bool {}}-/// Downloads `url` and checks it against the published `<url>.sha256`.-/// Fails closed: a missing or mismatched checksum, a non-HTTPS URL, or a-/// redirect to one is an error.-pub async fn download_verified(url: &str) -> Result<Vec<u8>> {- let parsed = url::Url::parse(url).map_err(|e| Error::Download(format!("{url}: {e}")))?;- if !allowed_download_url(&parsed) {- return Err(Error::Download(format!(- "{url}: refusing a non-HTTPS download"- )));+/// Why a download failed: `missing` when the artifact or its checksum is+/// not there (HTTP 404/410: a release that never published or is still a+/// draft), which the release fallback treats as "try another release".+#[derive(Debug)]+struct FetchError {+ missing: bool,+ message: String,+}++impl FetchError {+ fn other(message: String) -> Self {+ Self {+ missing: false,+ message,+ }}- let http = reqwest::Client::builder()+}++impl From<FetchError> for Error {+ fn from(e: FetchError) -> Self {+ Error::Download(e.message)+ }+}++fn is_missing(status: reqwest::StatusCode) -> bool {+ status == reqwest::StatusCode::NOT_FOUND || status == reqwest::StatusCode::GONE+}++fn http_client(timeout: std::time::Duration) -> Result<reqwest::Client> {+ reqwest::Client::builder().connect_timeout(std::time::Duration::from_secs(15))- .timeout(std::time::Duration::from_secs(600))+ .timeout(timeout)+ .user_agent(concat!("cua-host/", env!("CARGO_PKG_VERSION"))).redirect(reqwest::redirect::Policy::custom(|attempt| {if attempt.previous().len() >= 10 {attempt.error("too many redirects")@@ -216,44 +287,68 @@ pub async fn download_verified(url: &str) -> Result<Vec<u8>> {}})).build()- .map_err(|e| Error::Download(e.to_string()))?;+ .map_err(|e| Error::Download(e.to_string()))+}++/// Downloads `url` and checks it against the published `<url>.sha256`.+/// Fails closed: a missing or mismatched checksum, a non-HTTPS URL, or a+/// redirect to one is an error.+pub async fn download_verified(url: &str) -> Result<Vec<u8>> {+ Ok(fetch_verified(url).await?)+}++async fn fetch_verified(url: &str) -> std::result::Result<Vec<u8>, FetchError> {+ let parsed = url::Url::parse(url).map_err(|e| FetchError::other(format!("{url}: {e}")))?;+ if !allowed_download_url(&parsed) {+ return Err(FetchError::other(format!(+ "{url}: refusing a non-HTTPS download"+ )));+ }+ let http = http_client(std::time::Duration::from_secs(600))+ .map_err(|e| FetchError::other(e.to_string()))?;let resp = http.get(url).send().await- .map_err(|e| Error::Download(format!("{url}: {e}")))?;+ .map_err(|e| FetchError::other(format!("{url}: {e}")))?;if !resp.status().is_success() {- return Err(Error::Download(format!("{url}: HTTP {}", resp.status())));+ return Err(FetchError {+ missing: is_missing(resp.status()),+ message: format!("{url}: HTTP {}", resp.status()),+ });}if resp.content_length().is_some_and(|n| n as usize > MAX_ARCHIVE_BYTES){- return Err(Error::Download(format!("{url}: archive too large")));+ return Err(FetchError::other(format!("{url}: archive too large")));}let bytes = resp.bytes().await- .map_err(|e| Error::Download(format!("{url}: {e}")))?;+ .map_err(|e| FetchError::other(format!("{url}: {e}")))?;if bytes.len() > MAX_ARCHIVE_BYTES {- return Err(Error::Download(format!("{url}: archive too large")));+ return Err(FetchError::other(format!("{url}: archive too large")));}let sum_url = format!("{url}.sha256");let r = http.get(&sum_url).send().await- .map_err(|e| Error::Download(format!("{sum_url}: {e}")))?;+ .map_err(|e| FetchError::other(format!("{sum_url}: {e}")))?;if !r.status().is_success() {- return Err(Error::Download(format!(- "{sum_url}: HTTP {} (a published checksum is required)",- r.status()- )));+ return Err(FetchError {+ missing: is_missing(r.status()),+ message: format!(+ "{sum_url}: HTTP {} (a published checksum is required)",+ r.status()+ ),+ });}let text = r.text().await- .map_err(|e| Error::Download(format!("{sum_url}: {e}")))?;+ .map_err(|e| FetchError::other(format!("{sum_url}: {e}")))?;let expected = text.split_whitespace().next()@@ -261,13 +356,184 @@ pub async fn download_verified(url: &str) -> Result<Vec<u8>> {.to_ascii_lowercase();let actual = hex::encode(sha2::Sha256::digest(&bytes));if expected.len() != 64 || expected != actual {- return Err(Error::Download(format!(+ return Err(FetchError::other(format!("{url}: sha256 mismatch (expected {expected}, got {actual})")));}Ok(bytes.to_vec())}+/// `major.minor.patch` (no prerelease or build suffix).+fn parse_version(v: &str) -> Option<(u64, u64, u64)> {+ let mut parts = v.trim().trim_start_matches('v').split('.');+ let major = parts.next()?.parse().ok()?;+ let minor = parts.next()?.parse().ok()?;+ let patch = parts.next()?.parse().ok()?;+ parts.next().is_none().then_some((major, minor, patch))+}++/// A published cua-spacesd release that carries this platform's artifact.+#[derive(Clone, Debug, PartialEq, Eq)]+struct Candidate {+ version: (u64, u64, u64),+ url: String,+}++impl Candidate {+ fn version_string(&self) -> String {+ let (a, b, c) = self.version;+ format!("{a}.{b}.{c}")+ }+}++/// The releases in a GitHub releases listing that may stand in for+/// `pinned`, best first: published (not draft, not prerelease)+/// `cua-spacesd-v<x.y.z>` releases other than `pinned` with both+/// `artifact` and `artifact.sha256` attached under the release's own tag.+/// Same major.minor first (newest patch first), then newer releases on the+/// same major (closest first).+fn fallback_candidates(+ listing: &serde_json::Value,+ pinned: (u64, u64, u64),+ artifact: &str,+) -> Vec<Candidate> {+ let mut same_minor = Vec::new();+ let mut newer = Vec::new();+ for release in listing.as_array().into_iter().flatten() {+ if release["draft"].as_bool() != Some(false)+ || release["prerelease"].as_bool() != Some(false)+ {+ continue;+ }+ let Some(tag) = release["tag_name"].as_str() else {+ continue;+ };+ let Some(version) = tag.strip_prefix("cua-spacesd-v").and_then(parse_version) else {+ continue;+ };+ if version == pinned {+ continue;+ }+ let asset_url = |name: &str| {+ release["assets"]+ .as_array()+ .into_iter()+ .flatten()+ .filter(|a| a["name"].as_str() == Some(name))+ .find_map(|a| a["browser_download_url"].as_str())+ .map(str::to_string)+ };+ let (Some(url), Some(sum)) = (+ asset_url(artifact),+ asset_url(&format!("{artifact}.sha256")),+ ) else {+ continue;+ };+ // Identity: the artifact and its checksum come from this release's+ // own tag (download_verified fetches `<url>.sha256`).+ let suffix = format!("/{tag}/{artifact}");+ if !url.ends_with(&suffix) || sum != format!("{url}.sha256") {+ continue;+ }+ let candidate = Candidate { version, url };+ if (version.0, version.1) == (pinned.0, pinned.1) {+ same_minor.push(candidate);+ } else if version.0 == pinned.0 && version > pinned {+ newer.push(candidate);+ }+ }+ same_minor.sort_by_key(|c| std::cmp::Reverse(c.version));+ newer.sort_by_key(|c| c.version);+ same_minor.extend(newer);+ same_minor+}++/// The error when neither the pinned release nor a compatible fallback is+/// available: a plain sentence first, the raw cause last.+fn unavailable(pinned: &str, detail: &str) -> Error {+ Error::Download(format!(+ "cua-spacesd {pinned} (the Cua host service this version of Cua needs) is not \+ available to download, and no compatible published release was found. Check \+ your internet connection and try again later, or update Cua. Details: {detail}"+ ))+}++/// Downloads the pinned release's artifact at `url`, else (when that+/// release or artifact is missing) the best compatible published release+/// from `releases_api`. Returns the version used and the verified archive.+async fn download_release(+ pinned: &str,+ url: &str,+ releases_api: &str,+) -> Result<(String, Vec<u8>)> {+ let pinned_err = match fetch_verified(url).await {+ Ok(bytes) => return Ok((pinned.to_string(), bytes)),+ Err(e) if e.missing => e.message,+ Err(e) => return Err(e.into()),+ };+ let Some(pinned_version) = parse_version(pinned) else {+ return Err(unavailable(pinned, &pinned_err));+ };+ tracing::warn!(+ pinned,+ error = %pinned_err,+ "cua-spacesd {pinned} is not published; looking for a compatible published release"+ );+ let listing = list_releases(releases_api)+ .await+ .map_err(|e| unavailable(pinned, &format!("{pinned_err}; listing releases: {e}")))?;+ let mut last = pinned_err;+ for candidate in fallback_candidates(&listing, pinned_version, &artifact_name()) {+ let used = candidate.version_string();+ match fetch_verified(&candidate.url).await {+ Ok(bytes) => {+ tracing::warn!(+ pinned,+ used = %used,+ url = %candidate.url,+ "cua-spacesd {pinned} is not published; using cua-spacesd {used} instead"+ );+ return Ok((used, bytes));+ }+ Err(e) if e.missing => last = e.message,+ Err(e) => return Err(e.into()),+ }+ }+ Err(unavailable(pinned, &last))+}++/// `GET <api>?per_page=100` (the first two pages): the releases listing.+async fn list_releases(api: &str) -> std::result::Result<serde_json::Value, String> {+ let parsed = url::Url::parse(api).map_err(|e| format!("{api}: {e}"))?;+ if !allowed_download_url(&parsed) {+ return Err(format!("{api}: refusing a non-HTTPS URL"));+ }+ let http = http_client(std::time::Duration::from_secs(30)).map_err(|e| e.to_string())?;+ let mut all = Vec::new();+ for page in 1..=2 {+ let resp = http+ .get(api)+ .query(&[("per_page", "100"), ("page", &page.to_string())])+ .header("Accept", "application/vnd.github+json")+ .send()+ .await+ .map_err(|e| format!("{api}: {e}"))?;+ if !resp.status().is_success() {+ return Err(format!("{api}: HTTP {}", resp.status()));+ }+ let body: serde_json::Value = resp.json().await.map_err(|e| format!("{api}: {e}"))?;+ let Some(items) = body.as_array() else {+ return Err(format!("{api}: not a release listing"));+ };+ let done = items.len() < 100;+ all.extend(items.iter().cloned());+ if done {+ break;+ }+ }+ Ok(serde_json::Value::Array(all))+}+/// Finds the driver binary in a `.tar.gz` (at the root or in a directory).pub fn extract_binary(archive: &[u8]) -> Result<Vec<u8>> {let gz = flate2::read::GzDecoder::new(archive);@@ -452,4 +718,224 @@ mod tests {.unwrap_err();assert!(missing.to_string().contains("404"), "{missing}");}++ /// A fake GitHub: `/releases` lists `releases` (tag, draft, prerelease,+ /// whether its artifact is attached, archive bytes, checksum override),+ /// and `/download/<tag>/<artifact>[.sha256]` serves the attached ones.+ struct FakeRelease {+ tag: &'static str,+ draft: bool,+ prerelease: bool,+ attached: bool,+ payload: &'static [u8],+ bad_sum: bool,+ }++ fn published(tag: &'static str, payload: &'static [u8]) -> FakeRelease {+ FakeRelease {+ tag,+ draft: false,+ prerelease: false,+ attached: true,+ payload,+ bad_sum: false,+ }+ }++ async fn fake_github(releases: Vec<FakeRelease>) -> String {+ use axum::{Json, Router, routing::get};+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let base = format!("http://{}", listener.local_addr().unwrap());+ let artifact = artifact_name();+ let mut listing = Vec::new();+ let mut app = Router::new();+ for r in releases {+ let mut assets = Vec::new();+ if r.attached && !r.draft {+ let archive = tar_gz(binary_name(), r.payload);+ let sum = if r.bad_sum {+ "0".repeat(64)+ } else {+ hex::encode(sha2::Sha256::digest(&archive))+ };+ let path = format!("/download/{}/{artifact}", r.tag);+ for (name, url) in [+ (artifact.clone(), format!("{base}{path}")),+ (format!("{artifact}.sha256"), format!("{base}{path}.sha256")),+ ] {+ assets.push(serde_json::json!({"name": name, "browser_download_url": url}));+ }+ let a = archive.clone();+ app = app+ .route(&path, get(move || async move { a.clone() }))+ .route(+ &format!("{path}.sha256"),+ get(move || async move { format!("{sum} x\n") }),+ );+ }+ listing.push(serde_json::json!({+ "tag_name": r.tag,+ "draft": r.draft,+ "prerelease": r.prerelease,+ "assets": assets,+ }));+ }+ let listing = serde_json::Value::Array(listing);+ app = app.route(+ "/releases",+ get(move || async move { Json(listing.clone()) }),+ );+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });+ base+ }++ fn pinned_url(base: &str, version: &str) -> String {+ format!("{base}/download/cua-spacesd-v{version}/{}", artifact_name())+ }++ async fn install_release(base: &str, version: &str) -> Result<(String, Vec<u8>)> {+ let (used, archive) = download_release(+ version,+ &pinned_url(base, version),+ &format!("{base}/releases"),+ )+ .await?;+ Ok((used, extract_binary(&archive)?))+ }++ #[tokio::test]+ async fn release_uses_the_pinned_version_when_published() {+ let base = fake_github(vec![+ published("cua-spacesd-v0.2.2", b"v0.2.2"),+ published("cua-spacesd-v0.2.0", b"v0.2.0"),+ ])+ .await;+ let (used, bin) = install_release(&base, "0.2.0").await.unwrap();+ assert_eq!((used.as_str(), bin.as_slice()), ("0.2.0", &b"v0.2.0"[..]));+ }++ #[tokio::test]+ async fn release_falls_back_to_the_newest_published_patch() {+ // The 0.3.0 incident: 0.2.0 stayed an empty draft.+ let base = fake_github(vec![+ FakeRelease {+ draft: true,+ ..published("cua-spacesd-v0.2.3", b"draft")+ },+ FakeRelease {+ prerelease: true,+ ..published("cua-spacesd-v0.2.4-rc.1", b"rc")+ },+ published("cua-spacesd-v0.3.0", b"v0.3.0"),+ published("cua-spacesd-v0.2.2", b"v0.2.2"),+ published("cua-spacesd-v0.2.1", b"v0.2.1"),+ published("cua-driver-v9.9.9", b"other"),+ FakeRelease {+ draft: true,+ ..published("cua-spacesd-v0.2.0", b"v0.2.0")+ },+ ])+ .await;+ let (used, bin) = install_release(&base, "0.2.0").await.unwrap();+ assert_eq!((used.as_str(), bin.as_slice()), ("0.2.2", &b"v0.2.2"[..]));+ }++ #[tokio::test]+ async fn release_falls_back_to_the_closest_newer_release_on_the_same_major() {+ let base = fake_github(vec![+ published("cua-spacesd-v1.0.0", b"v1.0.0"),+ published("cua-spacesd-v0.4.0", b"v0.4.0"),+ published("cua-spacesd-v0.3.1", b"v0.3.1"),+ published("cua-spacesd-v0.1.9", b"v0.1.9"),+ ])+ .await;+ let (used, bin) = install_release(&base, "0.2.0").await.unwrap();+ assert_eq!((used.as_str(), bin.as_slice()), ("0.3.1", &b"v0.3.1"[..]));+ }++ #[tokio::test]+ async fn release_fallback_still_verifies_the_checksum_of_the_release_it_uses() {+ let base = fake_github(vec![+ FakeRelease {+ bad_sum: true,+ ..published("cua-spacesd-v0.2.2", b"tampered")+ },+ published("cua-spacesd-v0.2.1", b"v0.2.1"),+ ])+ .await;+ let err = install_release(&base, "0.2.0").await.unwrap_err();+ assert!(err.to_string().contains("sha256 mismatch"), "{err}");+ }++ #[tokio::test]+ async fn release_with_nothing_published_is_a_plain_error() {+ let base = fake_github(vec![+ FakeRelease {+ draft: true,+ ..published("cua-spacesd-v0.2.0", b"v0.2.0")+ },+ published("cua-spacesd-v1.0.0", b"v1.0.0"),+ ])+ .await;+ let err = install_release(&base, "0.2.0")+ .await+ .unwrap_err()+ .to_string();+ assert!(+ err.starts_with("download: cua-spacesd 0.2.0 (the Cua host service"),+ "{err}"+ );+ assert!(err.contains("no compatible published release"), "{err}");+ // A dead releases API reads the same way.+ let err = download_release(+ "0.2.0",+ &pinned_url(&base, "0.2.0"),+ &format!("{base}/no-such-api"),+ )+ .await+ .unwrap_err()+ .to_string();+ assert!(err.contains("is not available to download"), "{err}");+ }++ #[tokio::test]+ async fn release_source_installs_through_install_to() {+ let base = fake_github(vec![published("cua-spacesd-v0.2.2", b"v0.2.2")]).await;+ let dir = tempfile::tempdir().unwrap();+ let dest = dir.path().join("bin").join(binary_name());+ install_to(+ &DriverSource::Release {+ version: "0.2.0".into(),+ url: pinned_url(&base, "0.2.0"),+ releases_api: format!("{base}/releases"),+ },+ &dest,+ )+ .await+ .unwrap();+ assert_eq!(std::fs::read(&dest).unwrap(), b"v0.2.2");+ }++ #[test]+ fn fallback_candidates_require_the_artifact_under_the_release_tag() {+ let a = artifact_name();+ let listing = serde_json::json!([+ {"tag_name": "cua-spacesd-v0.2.5", "draft": false, "prerelease": false, "assets": [+ {"name": a, "browser_download_url": format!("https://x/cua-spacesd-v0.2.9/{a}")},+ {"name": format!("{a}.sha256"), "browser_download_url": format!("https://x/cua-spacesd-v0.2.9/{a}.sha256")},+ ]},+ {"tag_name": "cua-spacesd-v0.2.4", "draft": false, "prerelease": false, "assets": [+ {"name": a, "browser_download_url": format!("https://x/cua-spacesd-v0.2.4/{a}")},+ ]},+ {"tag_name": "cua-spacesd-v0.2.3", "draft": false, "prerelease": false, "assets": [+ {"name": a, "browser_download_url": format!("https://x/cua-spacesd-v0.2.3/{a}")},+ {"name": format!("{a}.sha256"), "browser_download_url": format!("https://x/cua-spacesd-v0.2.3/{a}.sha256")},+ ]},+ ]);+ let got = fallback_candidates(&listing, (0, 2, 0), &a);+ assert_eq!(got.len(), 1, "{got:?}");+ assert_eq!(got[0].version_string(), "0.2.3");+ assert_eq!(parse_version("v0.2.0"), Some((0, 2, 0)));+ assert_eq!(parse_version("0.2.0-rc.1"), None);+ }}diff --git a/libs/cua/crates/cua-host/src/host.rs b/libs/cua/crates/cua-host/src/host.rsindex 2a7fa60ad3..7f8dbd98ed 100644--- a/libs/cua/crates/cua-host/src/host.rs+++ b/libs/cua/crates/cua-host/src/host.rs@@ -869,8 +869,12 @@ impl Host {}}let source = driver::locate(opts.driver_bin.as_deref())?;- if let DriverSource::Download(url) = &source {- tracing::info!(%url, "downloading cua-spacesd");+ match &source {+ DriverSource::Download(url) => tracing::info!(%url, "downloading cua-spacesd"),+ DriverSource::Release { version, url, .. } => {+ tracing::info!(%version, %url, "downloading cua-spacesd")+ }+ DriverSource::Local(_) => {}}driver::install_to(&source, &config.driver_bin).await?;write_json(&self.paths.config(), &config)?;