Skip to content

armgit / cua

Public Imported from GitHub
0

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

feat(cua-cli): claim sandboxes from pre-created Fleet pools (#3020)

r33drichardse7fc154e08ba
diff --git a/.github/workflows/ci-py-cli-fleets-wif-smoke.yml b/.github/workflows/ci-py-cli-fleets-wif-smoke.yml
new file mode 100644
index 0000000000..acacd028c3
--- /dev/null
+++ b/.github/workflows/ci-py-cli-fleets-wif-smoke.yml
@@ -0,0 +1,60 @@
+name: "CI: cua-cli Fleets WIF smoke"
+
+on:
+ schedule:
+ - cron: "23 8 * * *"
+ workflow_dispatch:
+
+permissions:
+ contents: read
+ id-token: write
+
+concurrency:
+ group: cua-cli-fleets-wif-smoke
+ cancel-in-progress: false
+
+jobs:
+ smoke:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Check out Cua
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
+
+ - name: Set up uv
+ uses: astral-sh/setup-uv@d0cc045d04ccac9d8b7881df0226f9e82c39688e
+
+ - name: Install cua-cli from the locked dependency set
+ working-directory: libs/python/cua-cli
+ run: uv sync --frozen
+
+ - name: Claim, execute, and release a Fleet sandbox
+ working-directory: libs/python/cua-cli
+ shell: bash
+ run: |
+ set -euo pipefail
+ pool_name="cua-cli-wif-smoke"
+ claim_name="wif-smoke-$(tr -d '-' < /proc/sys/kernel/random/uuid | cut -c1-20)"
+ token="$(uv run cua wif-token github)"
+ export FLEETS_TOKEN="$token"
+
+ cleanup() {
+ status=$?
+ trap - EXIT
+ set +e
+ uv run cua sb delete "$claim_name" --force
+ delete_status=$?
+ uv run cua sb suspend "$pool_name"
+ suspend_status=$?
+ unset FLEETS_TOKEN token
+ if [ "$status" -eq 0 ] && [ "$delete_status" -ne 0 ]; then
+ status=$delete_status
+ fi
+ if [ "$status" -eq 0 ] && [ "$suspend_status" -ne 0 ]; then
+ status=$suspend_status
+ fi
+ exit "$status"
+ }
+ trap cleanup EXIT
+
+ uv run cua sb launch --name "$claim_name" --pool "$pool_name"
+ uv run cua sb exec "$claim_name" "uname -a && id && pwd"
diff --git a/.github/workflows/infra-fleets-wif-smoke.yml b/.github/workflows/infra-fleets-wif-smoke.yml
new file mode 100644
index 0000000000..2a20cc79d3
--- /dev/null
+++ b/.github/workflows/infra-fleets-wif-smoke.yml
@@ -0,0 +1,94 @@
+name: "Infra: Fleets WIF smoke pool"
+
+on:
+ workflow_dispatch:
+
+permissions:
+ contents: read
+ id-token: write
+
+concurrency:
+ group: fleets-wif-smoke-infra
+ cancel-in-progress: false
+
+env:
+ AWS_REGION: us-west-2
+ CYCLOPS_ENDPOINT: https://run.cua.ai
+ CYCLOPS_CLIENT_ID: ${{ secrets.FLEETS_TERRAFORM_CLIENT_ID }}
+ CYCLOPS_CLIENT_SECRET: ${{ secrets.FLEETS_TERRAFORM_CLIENT_SECRET }}
+ CYCLOPS_TOKEN_URL: ${{ secrets.FLEETS_TERRAFORM_TOKEN_URL }}
+ FLEETS_PROVIDER_COMMIT: d118faeafd288150d574c471a1038b3f3aef7c71
+ FLEETS_PROVIDER_VERSION: 1.0.0
+ TF_IN_AUTOMATION: "true"
+
+jobs:
+ apply:
+ runs-on: ubuntu-latest
+ steps:
+ - name: Check out Cua
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
+
+ - name: Configure AWS credentials
+ uses: aws-actions/configure-aws-credentials@v4
+ with:
+ role-to-assume: arn:aws:iam::296062593712:role/github-actions-cua-fleets-wif-smoke
+ aws-region: ${{ env.AWS_REGION }}
+
+ - name: Set up Go
+ uses: actions/setup-go@v5
+ with:
+ go-version: "1.25.8"
+ cache: false
+
+ - name: Set up Terraform
+ uses: hashicorp/setup-terraform@v3
+ with:
+ terraform_version: "1.11.4"
+
+ - name: Build the pinned Fleets provider
+ shell: bash
+ run: |
+ set -euo pipefail
+ provider_dir="$RUNNER_TEMP/terraform-provider-fleets"
+ sdk_parent="$RUNNER_TEMP/sdk-bindings"
+ mirror="$RUNNER_TEMP/terraform-plugins"
+ target="$mirror/registry.terraform.io/trycua/fleets/$FLEETS_PROVIDER_VERSION/$(go env GOOS)_$(go env GOARCH)"
+
+ git clone https://github.com/trycua/terraform-provider-fleets.git "$provider_dir"
+ git -C "$provider_dir" checkout "$FLEETS_PROVIDER_COMMIT"
+ mkdir -p "$sdk_parent" "$target"
+ ln -s "$GITHUB_WORKSPACE/libs/fleet/sdk-bindings/go-uniffi" "$sdk_parent/go-uniffi"
+
+ native_target="$RUNNER_TEMP/fleets-sdk-native"
+ cargo build --locked --manifest-path libs/fleet/Cargo.toml --package cyclops-sdk --target-dir "$native_target"
+ native_dir="$native_target/debug"
+ test -f "$native_dir/libcyclops_sdk.so"
+ export CGO_CFLAGS="-I$GITHUB_WORKSPACE/libs/fleet/sdk-bindings/go-uniffi/fleet_sdk -I$GITHUB_WORKSPACE/libs/fleet/sdk-bindings/go-uniffi/cyclops_sdk_schema"
+ export CGO_LDFLAGS="-L$native_dir -lcyclops_sdk -Wl,-rpath,$native_dir"
+ export LD_LIBRARY_PATH="$native_dir${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"
+
+ go -C "$provider_dir" build -o "$target/terraform-provider-fleets_v$FLEETS_PROVIDER_VERSION" .
+
+ cli_config="$RUNNER_TEMP/terraformrc-fleets"
+ cat > "$cli_config" <<CONFIG
+ provider_installation {
+ filesystem_mirror {
+ path = "$mirror"
+ include = ["registry.terraform.io/trycua/fleets"]
+ }
+
+ direct {
+ exclude = ["registry.terraform.io/trycua/fleets"]
+ }
+ }
+ CONFIG
+ echo "TF_CLI_CONFIG_FILE=$cli_config" >> "$GITHUB_ENV"
+ echo "LD_LIBRARY_PATH=$LD_LIBRARY_PATH" >> "$GITHUB_ENV"
+
+ - name: Apply pool and trust policy
+ working-directory: infra/fleets-wif-smoke
+ run: |
+ terraform init -input=false
+ terraform validate
+ terraform plan -input=false -out=tfplan
+ terraform apply -input=false -auto-approve tfplan
diff --git a/infra/fleets-wif-smoke/README.md b/infra/fleets-wif-smoke/README.md
new file mode 100644
index 0000000000..1a2e63cddf
--- /dev/null
+++ b/infra/fleets-wif-smoke/README.md
@@ -0,0 +1,13 @@
+# Cua CLI GitHub WIF smoke pool
+
+This stack keeps the `cua-cli-wif-smoke` Fleet pool and namespace available at zero replicas and authorizes GitHub Actions workflows from `trycua/cua` to claim it through GitHub WIF.
+
+Apply it with the manual `Infra: Fleets WIF smoke pool` workflow. The workflow builds `trycua/terraform-provider-fleets` at the pinned merged commit until `trycua/fleets` is published in the Terraform Registry.
+
+The apply job requires these protected repository or environment secrets from a Fleets user key:
+
+- `FLEETS_TERRAFORM_CLIENT_ID`
+- `FLEETS_TERRAFORM_CLIENT_SECRET`
+- `FLEETS_TERRAFORM_TOKEN_URL`
+
+The pool autoscaler is bounded from zero to one replica. The daily smoke workflow claims a UUID-suffixed sandbox, runs commands through `cua sb exec`, deletes the claim, and suspends the pool back to zero replicas.
diff --git a/infra/fleets-wif-smoke/main.tf b/infra/fleets-wif-smoke/main.tf
new file mode 100644
index 0000000000..c2c7891ba1
--- /dev/null
+++ b/infra/fleets-wif-smoke/main.tf
@@ -0,0 +1,52 @@
+terraform {
+ backend "s3" {
+ bucket = "cloud-terraform-state-bc8146107c2d77da"
+ key = "cua/fleets-wif-smoke/terraform.tfstate"
+ region = "us-west-2"
+ dynamodb_table = "cloud-terraform-lock-bc8146107c2d77da"
+ encrypt = true
+ }
+
+ required_providers {
+ fleets = {
+ source = "trycua/fleets"
+ version = "1.0.0"
+ }
+ }
+}
+
+provider "fleets" {
+ endpoint = "https://run.cua.ai"
+}
+
+resource "fleets_pool" "cua_cli_wif_smoke" {
+ name = "cua-cli-wif-smoke"
+ replicas = 0
+ cpu_cores = 4
+ memory = "8Gi"
+ container_disk_image = "296062593712.dkr.ecr.us-west-2.amazonaws.com/desktop-workspace:latest"
+ readiness_probe_json = jsonencode({ tcpSocket = { port = 8000 } })
+
+ autoscaling {
+ min_pool_size = 0
+ initial_pool_size = 0
+ max_pool_size = 1
+ }
+
+ service {
+ name = "server"
+ target_port = 8000
+ protocol = "TCP"
+ }
+}
+
+resource "fleets_github_trust_policy" "cua_cli_wif_smoke" {
+ name = "cua-cli-wif-smoke"
+ repository = "trycua/cua"
+
+ allowed_namespaces = [
+ fleets_pool.cua_cli_wif_smoke.name,
+ ]
+
+ enabled = true
+}
diff --git a/libs/python/cua-cli/cua_cli/commands/sandbox.py b/libs/python/cua-cli/cua_cli/commands/sandbox.py
index b57a76a2d6..29d83d0ee4 100644
--- a/libs/python/cua-cli/cua_cli/commands/sandbox.py
+++ b/libs/python/cua-cli/cua_cli/commands/sandbox.py
@@ -194,8 +194,14 @@ def register_parser(subparsers: argparse._SubParsersAction) -> None:
)
launch_parser.add_argument(
"image",
+ nargs="?",
help="Image to launch (e.g. macos, ubuntu:24.04, windows:11)",
)
+ launch_parser.add_argument(
+ "--pool",
+ default=None,
+ help="Claim the named pre-created Fleet pool",
+ )
launch_parser.add_argument(
"--local",
action="store_true",
@@ -421,10 +427,19 @@ def execute(args: argparse.Namespace) -> int:
def cmd_launch(args: argparse.Namespace) -> int:
"""Launch a new sandbox."""
+ image_arg = getattr(args, "image", None)
+ pool = getattr(args, "pool", None)
+ if bool(image_arg) == bool(pool):
+ print_error("Specify exactly one of IMAGE or --pool")
+ return 1
+ if pool and not getattr(args, "name", None):
+ print_error("--name is required with --pool")
+ return 1
+
async def _run() -> int:
from cua_sandbox import Sandbox
- image = _parse_image(args.image, vm=getattr(args, "vm", False))
+ image = _parse_image(image_arg, vm=getattr(args, "vm", False)) if image_arg else None
memory_mb = _parse_memory(args.memory) if args.memory else None
disk_gb = _parse_disk(args.disk) if args.disk else None
@@ -432,7 +447,9 @@ def cmd_launch(args: argparse.Namespace) -> int:
local = getattr(args, "local", False)
try:
- if local:
+ if pool:
+ sb = await Sandbox.create(pool=pool, name=args.name)
+ elif local:
sb = await Sandbox.create(
image,
local=True,
diff --git a/libs/python/cua-cli/tests/commands/test_sandbox.py b/libs/python/cua-cli/tests/commands/test_sandbox.py
index 7ec2b12d32..0d7a8e58d2 100644
--- a/libs/python/cua-cli/tests/commands/test_sandbox.py
+++ b/libs/python/cua-cli/tests/commands/test_sandbox.py
@@ -897,3 +897,65 @@ class TestCmdExec:
mock_sandbox.shell.run.assert_awaited_once_with("echo hello", timeout=120)
mock_sandbox.disconnect.assert_awaited_once_with()
assert capsys.readouterr().out == "hello\n"
+
+
+class TestPoolBackedLaunch:
+ def test_parser_accepts_pool_without_image(self):
+ parser = argparse.ArgumentParser()
+ subparsers = parser.add_subparsers()
+ sandbox.register_parser(subparsers)
+
+ args = parser.parse_args(
+ ["sb", "launch", "--name", "wif-smoke-123", "--pool", "cua-cli-wif-smoke"]
+ )
+
+ assert args.image is None
+ assert args.pool == "cua-cli-wif-smoke"
+ assert args.name == "wif-smoke-123"
+
+ def test_launch_rejects_image_and_pool(self, args_namespace):
+ args = args_namespace(
+ image="ubuntu:24.04",
+ pool="cua-cli-wif-smoke",
+ name="wif-smoke-123",
+ local=False,
+ vm=False,
+ cpu=None,
+ memory=None,
+ disk=None,
+ region=None,
+ json=False,
+ )
+
+ with patch.object(sandbox, "print_error") as mock_error:
+ result = sandbox.cmd_launch(args)
+
+ assert result == 1
+ mock_error.assert_called_once_with("Specify exactly one of IMAGE or --pool")
+
+ def test_launch_claims_named_sandbox_from_pool(self, args_namespace, monkeypatch):
+ monkeypatch.setenv("FLEETS_TOKEN", "github-token")
+ args = args_namespace(
+ image=None,
+ pool="cua-cli-wif-smoke",
+ name="wif-smoke-123",
+ local=False,
+ vm=False,
+ cpu=None,
+ memory=None,
+ disk=None,
+ region=None,
+ json=False,
+ )
+ claimed = SimpleNamespace(name="wif-smoke-123", disconnect=AsyncMock())
+ create = AsyncMock(return_value=claimed)
+ mock_sdk = MagicMock()
+ mock_sdk.Sandbox.create = create
+
+ with patch.dict("sys.modules", {"cua_sandbox": mock_sdk}):
+ with patch.object(sandbox, "print_success"):
+ result = sandbox.cmd_launch(args)
+
+ assert result == 0
+ create.assert_awaited_once_with(pool="cua-cli-wif-smoke", name="wif-smoke-123")
+ claimed.disconnect.assert_awaited_once()
diff --git a/libs/python/cua-sandbox/cua_sandbox/sandbox.py b/libs/python/cua-sandbox/cua_sandbox/sandbox.py
index 13505e9aee..e4a3db5524 100644
--- a/libs/python/cua-sandbox/cua_sandbox/sandbox.py
+++ b/libs/python/cua-sandbox/cua_sandbox/sandbox.py
@@ -402,9 +402,10 @@ class Sandbox:
@classmethod
async def create(
cls,
- image: Image,
+ image: Optional[Image] = None,
*,
name: Optional[str] = None,
+ pool: Optional[str] = None,
api_key: Optional[str] = None,
local: bool = False,
runtime: Optional["Runtime"] = None,
@@ -425,7 +426,8 @@ class Sandbox:
Args:
image: Image to run (e.g. ``Image.desktop("ubuntu")``).
- name: Optional name to assign to the sandbox.
+ name: Optional name to assign to the sandbox. Required with ``pool``.
+ pool: Pre-created Fleet pool to claim instead of creating from an image.
api_key: Legacy CUA API key. Providing one uses the legacy VM API;
Fleet cloud sandboxes use OAuth client credentials instead.
local: Use a local runtime instead of cloud.
@@ -453,9 +455,13 @@ class Sandbox:
print(sb.name) # save to reconnect later
await sb.disconnect()
"""
+ if (image is None) == (pool is None):
+ raise ValueError("Specify exactly one of image or pool")
+
return await cls._create(
image=image,
name=name,
+ pool=pool,
ephemeral=False,
api_key=api_key,
local=local,
@@ -1002,7 +1008,13 @@ class Sandbox:
await cloud_vm_action(name, "delete", api_key=api_key)
return
- await FleetCloudTransport.delete_sandbox(name)
+ from cua_sandbox import sandbox_state
+
+ state = sandbox_state.load(name)
+ pool_name = state.get("pool_name") if state else None
+ await FleetCloudTransport.delete_sandbox(name, pool_name=pool_name)
+ if pool_name:
+ sandbox_state.delete(name)
@classmethod
async def _delete_local(cls, name: str) -> None:
@@ -1044,6 +1056,7 @@ class Sandbox:
image: Optional[Image] = None,
runtime: Optional["Runtime"] = None,
name: Optional[str] = None,
+ pool: Optional[str] = None,
ephemeral: Optional[bool] = None,
cpu: Optional[int] = None,
memory_mb: Optional[int] = None,
@@ -1063,6 +1076,13 @@ class Sandbox:
):
raise ValueError("server_port must be an integer between 1 and 65535")
+ if image is not None and pool is not None:
+ raise ValueError("Specify exactly one of image or pool")
+ if pool and not name:
+ raise ValueError("Pool-backed sandboxes require a name")
+ if pool and local:
+ raise ValueError("Pool-backed sandboxes are cloud-only")
+
_t_start = time.monotonic()
if ephemeral is None:
ephemeral = bool(image)
@@ -1111,6 +1131,25 @@ class Sandbox:
_record_sandbox_create(sb, image=None, local=local, ephemeral=False, t_start=_t_start)
return sb
+ if pool:
+ transport = FleetCloudTransport(
+ image=None,
+ name=name,
+ pool_name=pool,
+ create_claim=True,
+ region=region,
+ time_to_start=time_to_start,
+ request_timeout=request_timeout,
+ server_port=server_port,
+ )
+ sb = cls(transport, name=name, _ephemeral=False, _telemetry_enabled=telemetry_enabled)
+ await sb._connect()
+ from cua_sandbox import sandbox_state
+
+ sandbox_state.save_fleet_claim(name, pool)
+ _record_sandbox_create(sb, image=None, local=False, ephemeral=False, t_start=_t_start)
+ return sb
+
if image and not runtime and local:
# local=True with no runtime → auto-select based on image type
runtime = _auto_runtime(image)
@@ -1243,9 +1282,14 @@ class Sandbox:
)
else:
if name and cls._uses_fleet(api_key) and not ws_url and not http_url:
+ from cua_sandbox import sandbox_state
+
+ state = sandbox_state.load(name)
+ pool_name = state.get("pool_name") if state else None
transport = FleetCloudTransport(
image=None,
name=name,
+ pool_name=pool_name,
cpu=cpu,
memory_mb=memory_mb,
disk_gb=disk_gb,
diff --git a/libs/python/cua-sandbox/cua_sandbox/sandbox_state.py b/libs/python/cua-sandbox/cua_sandbox/sandbox_state.py
index 5898ef9193..fef8ad2743 100644
--- a/libs/python/cua-sandbox/cua_sandbox/sandbox_state.py
+++ b/libs/python/cua-sandbox/cua_sandbox/sandbox_state.py
@@ -1,11 +1,10 @@
-"""Persistent state tracking for local sandboxes.
+"""Persistent state tracking for local sandboxes and Fleet claims.
-Each running local sandbox writes a JSON file at ~/.cua/sandboxes/{name}.json.
-This allows Sandbox.connect(name, local=True), Sandbox.list(local=True), etc.
-to work across Python process restarts.
+Each running local sandbox or named Fleet claim writes a JSON file at
+~/.cua/sandboxes/{name}.json. This lets later connect and delete commands route
+to the original runtime or pre-created Fleet pool across process restarts.
-State files are written by Sandbox.create() for local runtimes and deleted by
-Sandbox.delete(). Ephemeral sandboxes never write state files.
+Ephemeral sandboxes never write state files.
"""
from __future__ import annotations
@@ -103,3 +102,16 @@ def list_all() -> list[dict]:
except (json.JSONDecodeError, OSError):
pass
return result
+
+
+def save_fleet_claim(name: str, pool_name: str) -> None:
+ """Persist the pool association for a named Fleet claim."""
+ SANDBOX_STATE_DIR.mkdir(parents=True, exist_ok=True)
+ data: dict[str, Any] = {
+ "name": name,
+ "runtime_type": "fleet",
+ "pool_name": pool_name,
+ "status": "running",
+ "created_at": datetime.now(timezone.utc).isoformat(),
+ }
+ _state_path(name).write_text(json.dumps(data, indent=2))
diff --git a/libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py b/libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py
index bd700f30fa..bf138d7d3f 100644
--- a/libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py
+++ b/libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py
@@ -178,8 +178,8 @@ class _FleetClient:
async def get_pool(self, name: str) -> Any:
return await self._client.get_pool(name)
- async def get_claim(self, pool: Any) -> Any:
- expected = _claim_name(pool.metadata.name)
+ async def get_claim(self, pool: Any, name: str | None = None) -> Any:
+ expected = name or _claim_name(pool.metadata.name)
for claim in await self._client.list_claims(pool.metadata.namespace):
if claim.metadata.name == expected:
return claim
@@ -223,7 +223,7 @@ class _FleetClient:
class FleetCloudTransport(FleetTransport):
- """Provision and manage registry-image sandboxes through Fleet."""
+ """Provision image-backed pools or claim pre-created pools through Fleet."""
def __init__(
self,
@@ -237,6 +237,8 @@ class FleetCloudTransport(FleetTransport):
time_to_start: Optional[float] = None,
request_timeout: Optional[float] = None,
server_port: int = 8000,
+ pool_name: str | None = None,
+ create_claim: bool = False,
replicas: int = 1,
services: Mapping[str, int] | None = None,
) -> None:
@@ -268,6 +270,10 @@ class FleetCloudTransport(FleetTransport):
raise ValueError("services must map non-empty names to TCP ports")
self._image = image
self._name = name
+ self._explicit_pool = pool_name is not None
+ self._pool_name = pool_name or name
+ self._create_claim = create_claim
+ self._claim_name = name if pool_name else _claim_name(name)
self._cpu = cpu
self._memory_mb = memory_mb
self._time_to_start = time_to_start if time_to_start is not None else 600.0
@@ -276,7 +282,7 @@ class FleetCloudTransport(FleetTransport):
self._replicas = replicas
self._services = dict(services) if services is not None else None
self._provisioned = False
- self._owns_resources = image is not None
+ self._owns_resources = image is not None or create_claim
self._template: Any = None
self._pool: Any = None
self._claim: Any = None
@@ -293,7 +299,10 @@ class FleetCloudTransport(FleetTransport):
try:
if self._pool is None:
if self._image is None:
- self._pool = await self._sdk.get_pool(self._name)
+ self._pool = await self._sdk.get_pool(self._pool_name)
+ if self._create_claim:
+ self._pool = await self._sdk.set_pool_replicas(self._pool, 1)
+ self._pool = await self._sdk.wait_pool(self._pool)
else:
self._validate_image(self._image)
self._pool = await self._sdk.reconcile_pool(self._pool_request())
@@ -302,18 +311,18 @@ class FleetCloudTransport(FleetTransport):
)
self._pool = await self._sdk.wait_pool(self._pool)
if self._claim is None:
- if self._image is None:
- self._claim = await self._sdk.get_claim(self._pool)
+ if self._image is None and not self._create_claim:
+ self._claim = await self._get_claim()
else:
try:
self._claim = await self._sdk.create_claim(
CreateClaimRequest(
- pool=self._pool, spec=None, name=_claim_name(self._name)
+ pool=self._pool, spec=None, name=self._claim_name
)
)
except Exception as create_error:
try:
- self._claim = await self._sdk.get_claim(self._pool)
+ self._claim = await self._get_claim()
except Exception as lookup_error:
raise create_error from lookup_error
bound = await self._sdk.wait_claim(self._claim)
@@ -413,14 +422,23 @@ class FleetCloudTransport(FleetTransport):
await cls.resume_sandbox(name, time_to_start)
@classmethod
- async def delete_sandbox(cls, name: str) -> None:
+ async def delete_sandbox(cls, name: str, *, pool_name: str | None = None) -> None:
sdk = _FleetClient()
try:
- pool = await sdk.get_pool(name)
- await sdk.delete_claim(await sdk.get_claim(pool))
+ pool = await sdk.get_pool(pool_name or name)
+ if pool_name is not None:
+ claim = await sdk.get_claim(pool, name)
+ else:
+ claim = await sdk.get_claim(pool)
+ await sdk.delete_claim(claim)
finally:
await sdk.close()
+ async def _get_claim(self) -> Any:
+ if self._explicit_pool:
+ return await self._sdk.get_claim(self._pool, self._claim_name)
+ return await self._sdk.get_claim(self._pool)
+
def _template_request(self) -> CreateTemplateRequest:
assert self._image is not None
if self._services is not None:
@@ -464,21 +482,21 @@ class FleetCloudTransport(FleetTransport):
)
return (
CreateTemplateRequestBuilder()
- .namespace(self._name)
- .name(self._name)
+ .namespace(self._pool_name)
+ .name(self._pool_name)
.spec(template_spec)
.build()
)
def _pool_request(self) -> CreatePoolRequest:
- template_ref = SandboxTemplateRefBuilder().name(self._name).build()
+ template_ref = SandboxTemplateRefBuilder().name(self._pool_name).build()
pool_spec = (
OsGymSandboxWarmPoolSpecBuilder()
.replicas(self._replicas)
.sandbox_template_ref(template_ref)
.build()
)
- return CreatePoolRequestBuilder().namespace(self._name).spec(pool_spec).build()
+ return CreatePoolRequestBuilder().namespace(self._pool_name).spec(pool_spec).build()
@staticmethod
def _service_names(template: Any) -> list[str]:
diff --git a/libs/python/cua-sandbox/tests/test_cloud.py b/libs/python/cua-sandbox/tests/test_cloud.py
index 796eacc1bf..afea3ae331 100644
--- a/libs/python/cua-sandbox/tests/test_cloud.py
+++ b/libs/python/cua-sandbox/tests/test_cloud.py
@@ -207,3 +207,107 @@ async def test_cloud_invalid_api_key_errors():
sb = await Sandbox.connect(VM_NAME, api_key=reversed_key)
await sb.screenshot()
await sb.disconnect()
+
+
+async def test_pool_backed_create_persists_claim_pool_mapping(monkeypatch, tmp_path):
+ from cua_sandbox import sandbox_state
+
+ created = []
+ monkeypatch.setattr(sandbox_state, "SANDBOX_STATE_DIR", tmp_path)
+
+ class FleetTransport:
+ def __init__(self, **kwargs):
+ created.append(kwargs)
+ self.name = kwargs["name"]
+
+ async def connect(self):
+ return None
+
+ async def disconnect(self):
+ return None
+
+ monkeypatch.setattr(sandbox_module, "FleetCloudTransport", FleetTransport)
+
+ await Sandbox.create(pool="cua-cli-wif-smoke", name="wif-smoke-123")
+
+ assert created == [
+ {
+ "image": None,
+ "name": "wif-smoke-123",
+ "pool_name": "cua-cli-wif-smoke",
+ "create_claim": True,
+ "region": "us-east-1",
+ "time_to_start": None,
+ "request_timeout": None,
+ "server_port": 8000,
+ }
+ ]
+ assert sandbox_state.load("wif-smoke-123")["pool_name"] == "cua-cli-wif-smoke"
+
+
+async def test_pool_backed_connect_loads_claim_pool_mapping(monkeypatch, tmp_path):
+ from cua_sandbox import sandbox_state
+
+ created = []
+ monkeypatch.setattr(sandbox_state, "SANDBOX_STATE_DIR", tmp_path)
+ sandbox_state.save_fleet_claim("wif-smoke-123", "cua-cli-wif-smoke")
+ monkeypatch.setattr(Sandbox, "_uses_fleet", staticmethod(lambda api_key: True))
+
+ class FleetTransport:
+ def __init__(self, **kwargs):
+ created.append(kwargs)
+ self.name = kwargs["name"]
+
+ async def connect(self):
+ return None
+
+ async def disconnect(self):
+ return None
+
+ monkeypatch.setattr(sandbox_module, "FleetCloudTransport", FleetTransport)
+
+ await Sandbox.connect("wif-smoke-123")
+
+ assert created[0]["name"] == "wif-smoke-123"
+ assert created[0]["pool_name"] == "cua-cli-wif-smoke"
+
+
+async def test_pool_backed_delete_removes_mapping_only_after_success(monkeypatch, tmp_path):
+ from cua_sandbox import sandbox_state
+
+ calls = []
+ monkeypatch.setattr(sandbox_state, "SANDBOX_STATE_DIR", tmp_path)
+ sandbox_state.save_fleet_claim("wif-smoke-123", "cua-cli-wif-smoke")
+ monkeypatch.setattr(Sandbox, "_uses_fleet", staticmethod(lambda api_key: True))
+
+ class FleetTransport:
+ @classmethod
+ async def delete_sandbox(cls, name, *, pool_name=None):
+ calls.append((name, pool_name))
+
+ monkeypatch.setattr(sandbox_module, "FleetCloudTransport", FleetTransport)
+
+ await Sandbox.delete("wif-smoke-123")
+
+ assert calls == [("wif-smoke-123", "cua-cli-wif-smoke")]
+ assert sandbox_state.load("wif-smoke-123") is None
+
+
+async def test_pool_backed_delete_keeps_mapping_when_claim_delete_fails(monkeypatch, tmp_path):
+ from cua_sandbox import sandbox_state
+
+ monkeypatch.setattr(sandbox_state, "SANDBOX_STATE_DIR", tmp_path)
+ sandbox_state.save_fleet_claim("wif-smoke-123", "cua-cli-wif-smoke")
+ monkeypatch.setattr(Sandbox, "_uses_fleet", staticmethod(lambda api_key: True))
+
+ class FleetTransport:
+ @classmethod
+ async def delete_sandbox(cls, name, *, pool_name=None):
+ raise RuntimeError("claim delete failed")
+
+ monkeypatch.setattr(sandbox_module, "FleetCloudTransport", FleetTransport)
+
+ with pytest.raises(RuntimeError, match="claim delete failed"):
+ await Sandbox.delete("wif-smoke-123")
+
+ assert sandbox_state.load("wif-smoke-123")["pool_name"] == "cua-cli-wif-smoke"
diff --git a/libs/python/cua-sandbox/tests/test_fleet_cloud_transport.py b/libs/python/cua-sandbox/tests/test_fleet_cloud_transport.py
index 82a1bedc43..686fc050f5 100644
--- a/libs/python/cua-sandbox/tests/test_fleet_cloud_transport.py
+++ b/libs/python/cua-sandbox/tests/test_fleet_cloud_transport.py
@@ -732,3 +732,101 @@ async def test_snapshot_is_unsupported():
transport = FleetCloudTransport(image=Image.from_registry("example:latest"), name="demo")
with pytest.raises(NotImplementedError, match="Snapshots are not supported"):
await transport.create_snapshot()
+
+
+async def test_existing_pool_claim_uses_distinct_pool_and_sandbox_names(monkeypatch):
+ calls = []
+ pool = _pool("cua-cli-wif-smoke")
+ claim = SimpleNamespace(metadata=SimpleNamespace(name="wif-smoke-123"))
+ bound = _bound()
+
+ class Client:
+ async def get_pool(self, name):
+ calls.append(("get_pool", name))
+ return pool
+
+ async def set_pool_replicas(self, existing_pool, replicas):
+ calls.append(("set_pool_replicas", existing_pool.metadata.name, replicas))
+ return existing_pool
+
+ async def wait_pool(self, existing_pool):
+ calls.append(("wait_pool", existing_pool.metadata.name))
+ return existing_pool
+
+ async def create_claim(self, request):
+ calls.append(("create_claim", request.name, request.pool.metadata.name))
+ return claim
+
+ async def wait_claim(self, existing_claim):
+ calls.append(("wait_claim", existing_claim.metadata.name))
+ return bound
+
+ async def wait_service_ready(self, sandbox, service, time_to_start):
+ calls.append(("wait_service_ready", service))
+
+ monkeypatch.setattr(fleet_cloud, "_FleetClient", Client)
+
+ transport = FleetCloudTransport(
+ image=None,
+ name="wif-smoke-123",
+ pool_name="cua-cli-wif-smoke",
+ create_claim=True,
+ )
+ await transport.connect()
+
+ assert calls == [
+ ("get_pool", "cua-cli-wif-smoke"),
+ ("set_pool_replicas", "cua-cli-wif-smoke", 1),
+ ("wait_pool", "cua-cli-wif-smoke"),
+ ("create_claim", "wif-smoke-123", "cua-cli-wif-smoke"),
+ ("wait_claim", "wif-smoke-123"),
+ ("wait_service_ready", "server"),
+ ]
+
+
+async def test_existing_pool_claim_reconnect_and_delete_use_exact_claim_name(monkeypatch):
+ calls = []
+ pool = _pool("cua-cli-wif-smoke")
+ claim = SimpleNamespace(metadata=SimpleNamespace(name="wif-smoke-123"))
+ bound = _bound()
+
+ class Client:
+ async def get_pool(self, name):
+ calls.append(("get_pool", name))
+ return pool
+
+ async def get_claim(self, existing_pool, name=None):
+ calls.append(("get_claim", existing_pool.metadata.name, name))
+ return claim
+
+ async def wait_claim(self, existing_claim):
+ return bound
+
+ async def wait_service_ready(self, sandbox, service, time_to_start):
+ return None
+
+ async def delete_claim(self, existing_claim):
+ calls.append(("delete_claim", existing_claim.metadata.name))
+
+ async def close(self):
+ calls.append(("close",))
+
+ monkeypatch.setattr(fleet_cloud, "_FleetClient", Client)
+
+ await FleetCloudTransport(
+ image=None,
+ name="wif-smoke-123",
+ pool_name="cua-cli-wif-smoke",
+ ).connect()
+ await FleetCloudTransport.delete_sandbox("wif-smoke-123", pool_name="cua-cli-wif-smoke")
+
+ assert calls == [
+ ("get_pool", "cua-cli-wif-smoke"),
+ ("get_claim", "cua-cli-wif-smoke", "wif-smoke-123"),
+ ("get_pool", "cua-cli-wif-smoke"),
+ ("get_claim", "cua-cli-wif-smoke", "wif-smoke-123"),
+ ("delete_claim", "wif-smoke-123"),
+ ("close",),
+ ]