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-sandbox): configure Fleet computer-server port (#2997)

r33drichards6ab8561dfabf
diff --git a/docs/superpowers/plans/2026-08-08-cua-sandbox-server-port.md b/docs/superpowers/plans/2026-08-08-cua-sandbox-server-port.md
new file mode 100644
index 0000000000..b9732cac1c
--- /dev/null
+++ b/docs/superpowers/plans/2026-08-08-cua-sandbox-server-port.md
@@ -0,0 +1,422 @@
+# Cua Sandbox Fleet Server Port Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Add `server_port` to the public asynchronous sandbox creation APIs so Fleet services, readiness probes, and server tunnels can target Linux port `5000` while preserving the existing Windows default of `8000`.
+
+**Architecture:** The public `Sandbox.create()` and `Sandbox.ephemeral()` methods forward one validated integer through `Sandbox._create()` into `FleetCloudTransport`. The transport owns all Fleet-specific use of the value: template service generation, readiness-probe generation, exposed-port deduplication, and server tunnel routing. Existing-pool connections remain unchanged because they consume the pool's stored template.
+
+**Tech Stack:** Python 3.11-3.13, `pytest`, `pytest-asyncio`, `ruff`, `cua-sandbox`, `cua-fleet`/UniFFI Fleet bindings.
+
+## Correction — August 9, 2026
+
+The attempted certification with pinned image
+`desktop-workspace@sha256:b9e74...` disproved the original image assumption.
+That image exposes cua-driver MCP on TCP `3000` and does not run the CUA
+computer-server on TCP `5000`. Positive live E2E remains blocked until a
+suitable image that serves the computer-server `/cmd` API is available.
+
+## Global Constraints
+
+- `server_port` defaults to exactly `8000`.
+- Valid values are integers from `1` through `65535`; booleans are invalid.
+- The option applies to Fleet-backed cloud creation and must not change legacy API-key or local runtime routing.
+- The selected port drives the Fleet `server` Service, readiness probe, and `forward_tunnel(server_port)` behavior.
+- `Image.expose(server_port)` must not create a duplicate `port-<server_port>` Service.
+- Do not infer ports from image names or registry references.
+- Preserve existing behavior for callers that omit `server_port`.
+
+---
+
+### Task 1: Make Fleet Transport Port-Aware
+
+**Files:**
+- Modify: `libs/python/cua-sandbox/tests/test_fleet_cloud_transport.py`
+- Modify: `libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py`
+
+**Interfaces:**
+- Consumes: `FleetCloudTransport(..., server_port: int = 8000)`.
+- Produces: `self._server_port`, port-aware `_template_request()`, and port-aware `forward_tunnel()`.
+
+- [ ] **Step 1: Write failing template and validation tests**
+
+Add these focused tests near `test_registry_image_becomes_typed_template_request`:
+
+```python
+import json
+
+
+def test_custom_server_port_configures_service_probe_and_exposed_port_deduplication():
+ request = FleetCloudTransport(
+ image=Image.from_registry("registry.example/workspace@sha256:abc")
+ .expose(5000)
+ .expose(3000),
+ name="demo",
+ server_port=5000,
+ )._template_request()
+
+ vm_template = request.spec.vm_template
+ assert [(service.name, service.target_port) for service in vm_template.services] == [
+ ("server", 5000),
+ ("port-3000", 3000),
+ ]
+ assert json.loads(vm_template.probes.to_json()) == {
+ "readinessProbe": {"tcpSocket": {"port": 5000}}
+ }
+
+
[email protected]("server_port", [True, False, 0, -1, 65536, 5000.0, "5000"])
+def test_rejects_invalid_server_port(server_port):
+ with pytest.raises(ValueError, match="server_port must be an integer between 1 and 65535"):
+ FleetCloudTransport(
+ image=Image.from_registry("registry.example/workspace:latest"),
+ name="demo",
+ server_port=server_port,
+ )
+```
+
+If the generated `PreservedJson` wrapper does not expose `to_json()`, use its existing public JSON accessor established by the installed `cua-fleet==0.1.8` binding; do not inspect private UniFFI handles.
+
+- [ ] **Step 2: Write the failing tunnel-routing test**
+
+Add beside `test_forward_tunnel_uses_named_service_url`:
+
+```python
+async def test_forward_tunnel_uses_server_service_for_custom_server_port():
+ transport = FleetCloudTransport(
+ image=Image.from_registry("example:latest"), name="demo", server_port=5000
+ )
+ transport._provisioned = True
+ transport._bound = Sandbox(
+ namespace="demo", claim="claim", name="sandbox", services=["server"]
+ )
+
+ class Client:
+ def service_url(self, sandbox, service):
+ assert service == "server"
+ return "https://run.cua.ai/api/svc/demo/sandbox-server/"
+
+ transport._sdk = Client()
+ tunnel = await transport.forward_tunnel(5000)
+ assert tunnel.url == "https://run.cua.ai/api/svc/demo/sandbox-server/"
+```
+
+- [ ] **Step 3: Run the focused tests and verify RED**
+
+Run:
+
+```bash
+cd libs/python/cua-sandbox
+.venv/bin/python -m pytest -q \
+ tests/test_fleet_cloud_transport.py::test_custom_server_port_configures_service_probe_and_exposed_port_deduplication \
+ tests/test_fleet_cloud_transport.py::test_rejects_invalid_server_port \
+ tests/test_fleet_cloud_transport.py::test_forward_tunnel_uses_server_service_for_custom_server_port
+```
+
+Expected: failures because `FleetCloudTransport.__init__()` does not accept `server_port`.
+
+- [ ] **Step 4: Implement minimal transport support**
+
+Update the constructor and template/tunnel code:
+
+```python
+def __init__(
+ self,
+ *,
+ image: Optional[Image],
+ name: str,
+ # existing arguments...
+ server_port: int = 8000,
+ replicas: int = 1,
+ services: Mapping[str, int] | None = None,
+) -> None:
+ if (
+ isinstance(server_port, bool)
+ or not isinstance(server_port, int)
+ or server_port < 1
+ or server_port > 65535
+ ):
+ raise ValueError("server_port must be an integer between 1 and 65535")
+ # existing validation...
+ self._server_port = server_port
+```
+
+Use the stored value everywhere the hardcoded server port currently appears:
+
+```python
+service = "server" if sandbox_port == self._server_port else f"port-{sandbox_port}"
+
+service_ports = self._services or {
+ "server": self._server_port,
+ **{
+ f"port-{port}": port
+ for port in self._image._ports
+ if port != self._server_port
+ },
+}
+
+PreservedJson.from_json(
+ json.dumps({"readinessProbe": {"tcpSocket": {"port": self._server_port}}})
+)
+```
+
+Do not change the named service passed to `wait_service_ready()` or `FleetTransport`; it remains `"server"`.
+
+- [ ] **Step 5: Run the Fleet transport tests and verify GREEN**
+
+Run:
+
+```bash
+cd libs/python/cua-sandbox
+.venv/bin/python -m pytest -q tests/test_fleet_cloud_transport.py
+```
+
+Expected: all Fleet transport tests pass.
+
+- [ ] **Step 6: Commit the transport behavior**
+
+```bash
+git add \
+ libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py \
+ libs/python/cua-sandbox/tests/test_fleet_cloud_transport.py
+git commit -m "fix(cua-sandbox): configure Fleet server port"
+```
+
+---
+
+### Task 2: Expose the Public Sandbox Argument
+
+**Files:**
+- Modify: `libs/python/cua-sandbox/tests/test_vm_cleanup.py`
+- Modify: `libs/python/cua-sandbox/cua_sandbox/sandbox.py`
+
+**Interfaces:**
+- Consumes: transport signature `FleetCloudTransport(..., server_port: int = 8000)` from Task 1.
+- Produces: `Sandbox.create(..., server_port: int = 8000)` and `Sandbox.ephemeral(..., server_port: int = 8000)`.
+
+- [ ] **Step 1: Write failing public forwarding tests**
+
+Add a focused test class before the existing ephemeral cleanup section. Patch `Sandbox._create()` so the tests exercise only the public wrappers:
+
+```python
+class TestFleetServerPortForwarding:
+ async def test_create_forwards_server_port(self):
+ sandbox = object()
+ with patch.object(Sandbox, "_create", AsyncMock(return_value=sandbox)) as create:
+ result = await Sandbox.create(
+ Image.from_registry("registry.example/workspace:latest"),
+ server_port=5000,
+ telemetry_enabled=False,
+ )
+
+ assert result is sandbox
+ assert create.await_args.kwargs["server_port"] == 5000
+
+ async def test_ephemeral_forwards_server_port(self):
+ sandbox = _make_sandbox(_make_cloud_transport(name="port-e2e"), ephemeral=True)
+ sandbox.destroy = AsyncMock()
+ with patch.object(Sandbox, "_create", AsyncMock(return_value=sandbox)) as create:
+ async with Sandbox.ephemeral(
+ Image.from_registry("registry.example/workspace:latest"),
+ server_port=5000,
+ telemetry_enabled=False,
+ ):
+ pass
+
+ assert create.await_args.kwargs["server_port"] == 5000
+```
+
+Also add a `_create()` seam test that patches `cua_sandbox.sandbox.FleetCloudTransport`, returns a fake connected transport, and asserts its constructor receives `server_port=5000`. This proves the value crosses the internal factory boundary rather than stopping at the public wrapper.
+
+- [ ] **Step 2: Run the forwarding tests and verify RED**
+
+Run:
+
+```bash
+cd libs/python/cua-sandbox
+.venv/bin/python -m pytest -q tests/test_vm_cleanup.py -k server_port
+```
+
+Expected: failures because the public methods and `_create()` do not accept or forward `server_port`.
+
+- [ ] **Step 3: Add the public and internal parameters**
+
+Add `server_port: int = 8000` to `Sandbox.create()`, `Sandbox.ephemeral()`, and `Sandbox._create()`. Forward it at each boundary:
+
+```python
+return await cls._create(
+ # existing arguments...
+ server_port=server_port,
+)
+```
+
+```python
+transport = FleetCloudTransport(
+ image=image,
+ name=name or _random_name(),
+ # existing arguments...
+ server_port=server_port,
+)
+```
+
+Validate at the start of `_create()` so invalid values fail before local, legacy-cloud, or Fleet provisioning can begin:
+
+```python
+if (
+ isinstance(server_port, bool)
+ or not isinstance(server_port, int)
+ or server_port < 1
+ or server_port > 65535
+):
+ raise ValueError("server_port must be an integer between 1 and 65535")
+```
+
+The value remains unused by local runtimes and legacy API-key cloud transports after validation.
+
+- [ ] **Step 4: Update constructor docstrings**
+
+Add this argument description to both public methods:
+
+```text
+server_port: Guest computer-server TCP port for Fleet cloud sandboxes.
+ Defaults to 8000. Set this when the guest image runs the CUA
+ computer-server /cmd API on a non-default port, for example 5000.
+```
+
+Update each method's example when useful, but do not change local-runtime examples to include a Fleet-only option.
+
+- [ ] **Step 5: Run public factory and transport tests**
+
+Run:
+
+```bash
+cd libs/python/cua-sandbox
+.venv/bin/python -m pytest -q \
+ tests/test_vm_cleanup.py \
+ tests/test_fleet_cloud_transport.py
+```
+
+Expected: all tests pass.
+
+- [ ] **Step 6: Commit the public API**
+
+```bash
+git add \
+ libs/python/cua-sandbox/cua_sandbox/sandbox.py \
+ libs/python/cua-sandbox/tests/test_vm_cleanup.py
+git commit -m "feat(cua-sandbox): expose Fleet server port"
+```
+
+---
+
+### Task 3: Document and Certify the Fix
+
+**Files:**
+- Modify: `libs/python/cua-sandbox/README.md`
+- Verify: `libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py`
+- Verify: `libs/python/cua-sandbox/cua_sandbox/sandbox.py`
+
+**Interfaces:**
+- Consumes: `Sandbox.create(..., server_port=5000)` and `Sandbox.ephemeral(..., server_port=5000)` from Task 2.
+- Produces: documented custom Linux image usage and release-ready E2E evidence once a suitable image is available.
+
+- [ ] **Step 1: Add a generic Linux README example**
+
+Update the Fleet cloud example to show the explicit image contract:
+
+```python
+async with Sandbox.ephemeral(
+ Image.from_registry("registry.example/linux-computer-server:latest"),
+ server_port=5000,
+) as sb:
+ await sb.shell.run("uname -a")
+```
+
+State that the image must serve the CUA computer-server `/cmd` API on the
+configured port and that Windows computer-server images continue to use the
+default port `8000`.
+
+- [ ] **Step 2: Run formatting and focused package tests**
+
+Run:
+
+```bash
+cd libs/python/cua-sandbox
+.venv/bin/python -m ruff check cua_sandbox tests
+.venv/bin/python -m ruff format --check cua_sandbox tests
+.venv/bin/python -m pytest -q \
+ tests/test_fleet_cloud_transport.py \
+ tests/test_vm_cleanup.py \
+ tests/test_fleet_builder_usage.py \
+ tests/test_fleet_sdk_packaging.py
+```
+
+Expected: zero lint errors, zero formatting diffs, all selected tests pass.
+
+- [ ] **Step 3: Run the complete cua-sandbox unit suite**
+
+Run:
+
+```bash
+cd libs/python/cua-sandbox
+.venv/bin/python -m pytest -q tests
+```
+
+Expected: all non-environment-gated tests pass; report any documented skips separately.
+
+- [ ] **Step 4: Commit documentation**
+
+```bash
+git add libs/python/cua-sandbox/README.md
+git commit -m "docs(cua-sandbox): document Linux Fleet server port"
+```
+
+- [ ] **Step 5: Run one live empty-namespace Linux E2E**
+
+This step remains blocked until a Linux image that serves the CUA
+computer-server `/cmd` API on TCP `5000` is available. Do not use the pinned
+`desktop-workspace@sha256:b9e74...` image: it exposes cua-driver MCP on `3000`
+and has no computer-server listener on `5000`.
+
+Once a suitable image is available, use a unique namespace and a user-scoped
+Fleet credential with this public API shape from the candidate commit:
+
+```python
+async with Sandbox.ephemeral(
+ Image.from_registry("<linux-computer-server-image>"),
+ name="pr-server-port-e2e-<timestamp>",
+ cpu=4,
+ memory_mb=4096,
+ server_port=5000,
+ time_to_start=900,
+ request_timeout=60,
+ telemetry_enabled=False,
+) as sandbox:
+ width, height = await sandbox.screen.size()
+ result = await sandbox.shell.run("uname -s")
+ assert width > 0 and height > 0
+ assert result.success
+```
+
+Verify with `kubectl` that namespace, template, pool, claim, sandbox, VMI, and pod are created in order. After context exit, verify the owned namespace and every child resource are gone. Do not revoke or alter any pre-existing managed credential; revoke only a temporary key minted for this E2E.
+
+- [ ] **Step 6: Review the final diff and PR metadata**
+
+Run:
+
+```bash
+git diff origin/main...HEAD --check
+git status --short
+git log --oneline origin/main..HEAD
+```
+
+Use PR title:
+
+```text
+feat(cua-sandbox): configure Fleet computer-server port
+```
+
+The PR body must link merged PR `#2979`, list exact test commands, call out that
+the default remains `8000`, and record that positive live `server_port=5000`
+E2E is blocked pending a suitable Linux computer-server image.
diff --git a/docs/superpowers/specs/2026-08-08-cua-sandbox-server-port-design.md b/docs/superpowers/specs/2026-08-08-cua-sandbox-server-port-design.md
new file mode 100644
index 0000000000..9b6db87d2c
--- /dev/null
+++ b/docs/superpowers/specs/2026-08-08-cua-sandbox-server-port-design.md
@@ -0,0 +1,90 @@
+# Cua Sandbox Fleet Server Port Design
+
+## Correction — August 9, 2026
+
+The attempted certification with pinned image
+`desktop-workspace@sha256:b9e74...` disproved the original image assumption.
+That image exposes cua-driver MCP on TCP `3000` and does not run the CUA
+computer-server on TCP `5000`. Positive live E2E remains blocked until a
+suitable image that serves the computer-server `/cmd` API is available.
+
+## Problem
+
+Fleet-backed `Sandbox.create()` and `Sandbox.ephemeral()` currently assume the
+guest computer server listens on TCP port `8000`. The transport uses that value
+for both the generated `server` Service and the VM readiness probe.
+
+Guest images may run the CUA computer-server on a non-default port such as
+`5000`, while Windows computer-server images retain the default `8000`. A
+single hardcoded port prevents callers from declaring those differing guest
+image contracts.
+
+## Public API
+
+Add an optional keyword argument to the asynchronous public constructors:
+
+```python
+await Sandbox.create(image, server_port=5000)
+
+async with Sandbox.ephemeral(image, server_port=5000) as sandbox:
+ ...
+```
+
+`server_port` defaults to `8000`, preserving existing behavior for Windows and
+all current callers that omit the argument. The existing synchronous context-manager
+facade is out of scope because it does not expose `Sandbox.create()` or
+`Sandbox.ephemeral()`.
+
+## Fleet Transport Behavior
+
+Pass `server_port` through `Sandbox._create()` into `FleetCloudTransport`.
+The transport stores the selected port and uses it consistently for:
+
+- the Fleet `server` Service `targetPort`;
+- the generated VM readiness probe TCP port; and
+- `forward_tunnel(server_port)`, which must route through the named `server` Service.
+
+Ports declared with `Image.expose()` remain additional Fleet services named
+`port-<port>`. If an exposed port equals `server_port`, do not create a duplicate
+additional service for that port.
+
+Connecting to an existing Fleet pool remains unchanged because the pool's
+template already defines its service target and readiness behavior.
+
+## Validation
+
+Reject invalid values before provisioning. `server_port` must be an integer in
+the TCP port range `1..65535`; booleans are not accepted as integers.
+
+This prevents malformed Fleet templates and gives callers a local, actionable
+error before any namespace or resource is created.
+
+## Tests
+
+Add focused regression coverage that first fails against the hardcoded-port
+implementation and then passes with the fix:
+
+1. `Sandbox.create()` and `Sandbox.ephemeral()` forward `server_port` to
+ `FleetCloudTransport`.
+2. `FleetCloudTransport` defaults to port `8000`.
+3. A custom port changes both `server.targetPort` and the readiness probe.
+4. An exposed port equal to `server_port` is not duplicated.
+5. Invalid ports fail before Fleet provisioning.
+
+Run the existing Fleet transport, sandbox creation, formatting, and packaging
+tests. Once a suitable Linux computer-server image is available, perform one
+live E2E using `server_port=5000`, verifying screen access and owned-namespace
+cleanup. The pinned `desktop-workspace@sha256:b9e74...` image is not suitable.
+
+## Documentation
+
+Document the optional argument in the public constructor docstrings and add a
+README example showing a generic Linux computer-server image contract:
+
+```python
+sandbox = await Sandbox.create(image, server_port=5000)
+```
+
+No image-name inference is added. The caller explicitly declares the port where
+the guest serves the CUA computer-server `/cmd` API, avoiding brittle
+registry-specific behavior.
diff --git a/libs/python/cua-sandbox/README.md b/libs/python/cua-sandbox/README.md
index 5df96557ce..a7dcaf6c92 100644
--- a/libs/python/cua-sandbox/README.md
+++ b/libs/python/cua-sandbox/README.md
@@ -182,7 +182,11 @@ cua.configure(
)
async with Sandbox.ephemeral(
- Image.from_registry("registry.example/desktop-workspace@sha256:...").expose(3000)
+ Image.from_registry("registry.example/linux-computer-server:latest"),
+ server_port=5000,
) as sb:
await sb.shell.run("uname -a")
```
+
+The image must run the CUA computer-server `/cmd` API on the configured `server_port`.
+Windows computer-server images continue to use the default port `8000`.
diff --git a/libs/python/cua-sandbox/cua_sandbox/sandbox.py b/libs/python/cua-sandbox/cua_sandbox/sandbox.py
index 783a04162b..639b703682 100644
--- a/libs/python/cua-sandbox/cua_sandbox/sandbox.py
+++ b/libs/python/cua-sandbox/cua_sandbox/sandbox.py
@@ -413,6 +413,7 @@ class Sandbox:
region: str = "us-east-1",
time_to_start: Optional[float] = None,
request_timeout: Optional[float] = None,
+ server_port: int = 8000,
telemetry_enabled: bool = True,
) -> "Sandbox":
"""Provision a new persistent sandbox and return it connected.
@@ -438,6 +439,10 @@ class Sandbox:
commands sent to the computer-server (default 30, cloud only).
Individual commands with a server-side timeout automatically
extend the client timeout to match.
+ server_port: Guest computer-server TCP port for Fleet cloud sandboxes.
+ Defaults to 8000. Set this when the guest image runs the CUA
+ computer-server ``/cmd`` API on a non-default port, for example
+ 5000.
telemetry_enabled: Set to False to disable telemetry for this instance.
Example::
@@ -460,6 +465,7 @@ class Sandbox:
region=region,
time_to_start=time_to_start,
request_timeout=request_timeout,
+ server_port=server_port,
telemetry_enabled=telemetry_enabled,
)
@@ -538,6 +544,7 @@ class Sandbox:
region: str = "us-east-1",
time_to_start: Optional[float] = None,
request_timeout: Optional[float] = None,
+ server_port: int = 8000,
telemetry_enabled: bool = True,
) -> AsyncIterator["Sandbox"]:
"""Create an ephemeral sandbox that is automatically destroyed on exit.
@@ -559,6 +566,10 @@ class Sandbox:
commands sent to the computer-server (default 30, cloud only).
Individual commands with a server-side timeout automatically
extend the client timeout to match.
+ server_port: Guest computer-server TCP port for Fleet cloud sandboxes.
+ Defaults to 8000. Set this when the guest image runs the CUA
+ computer-server ``/cmd`` API on a non-default port, for example
+ 5000.
Example::
@@ -579,6 +590,7 @@ class Sandbox:
region=region,
time_to_start=time_to_start,
request_timeout=request_timeout,
+ server_port=server_port,
telemetry_enabled=telemetry_enabled,
)
try:
@@ -1027,9 +1039,18 @@ class Sandbox:
region: str = "us-east-1",
time_to_start: Optional[float] = None,
request_timeout: Optional[float] = None,
+ server_port: int = 8000,
telemetry_enabled: bool = True,
) -> "Sandbox":
- """Internal workhorse — all public factories delegate here."""
+ """Internal factory that validates server_port before selecting a transport."""
+ if (
+ isinstance(server_port, bool)
+ or not isinstance(server_port, int)
+ or server_port < 1
+ or server_port > 65535
+ ):
+ raise ValueError("server_port must be an integer between 1 and 65535")
+
_t_start = time.monotonic()
if ephemeral is None:
ephemeral = bool(image)
@@ -1093,6 +1114,7 @@ class Sandbox:
region=region,
time_to_start=time_to_start,
request_timeout=request_timeout,
+ server_port=server_port,
)
sb = cls(
transport, name=name, _ephemeral=ephemeral, _telemetry_enabled=telemetry_enabled
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 824aede399..fc3eed6ef2 100644
--- a/libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py
+++ b/libs/python/cua-sandbox/cua_sandbox/transport/fleet_cloud.py
@@ -210,9 +210,17 @@ class FleetCloudTransport(FleetTransport):
region: str = "us-east-1",
time_to_start: Optional[float] = None,
request_timeout: Optional[float] = None,
+ server_port: int = 8000,
replicas: int = 1,
services: Mapping[str, int] | None = None,
) -> None:
+ if (
+ isinstance(server_port, bool)
+ or not isinstance(server_port, int)
+ or server_port < 1
+ or server_port > 65535
+ ):
+ raise ValueError("server_port must be an integer between 1 and 65535")
if disk_gb is not None:
raise ValueError("disk_gb is not supported by the Fleet cloud transport")
if region != "us-east-1":
@@ -238,6 +246,7 @@ class FleetCloudTransport(FleetTransport):
self._memory_mb = memory_mb
self._time_to_start = time_to_start if time_to_start is not None else 600.0
self._request_timeout = request_timeout or 30.0
+ self._server_port = server_port
self._replicas = replicas
self._services = dict(services) if services is not None else None
self._provisioned = False
@@ -304,7 +313,7 @@ class FleetCloudTransport(FleetTransport):
raise ValueError("Fleet services can only expose numeric TCP ports")
if not self._provisioned:
raise ValueError("Transport not connected")
- service = "server" if sandbox_port == 8000 else f"port-{sandbox_port}"
+ service = "server" if sandbox_port == self._server_port else f"port-{sandbox_port}"
from cua_sandbox.interfaces.tunnel import TunnelInfo
endpoint = self._sdk.service_url(self._bound, service)
@@ -404,10 +413,18 @@ class FleetCloudTransport(FleetTransport):
def _template_request(self) -> CreateTemplateRequest:
assert self._image is not None
- service_ports = self._services or {
- "server": 8000,
- **{f"port-{port}": port for port in self._image._ports if port != 8000},
- }
+ if self._services is not None:
+ service_ports = {
+ "server": self._server_port,
+ **{name: port for name, port in self._services.items() if name != "server"},
+ }
+ else:
+ service_ports = {
+ "server": self._server_port,
+ **{
+ f"port-{port}": port for port in self._image._ports if port != self._server_port
+ },
+ }
services = [
SandboxServiceBuilder()
.name(name)
@@ -422,7 +439,7 @@ class FleetCloudTransport(FleetTransport):
.image_pull_secret("ecr-credentials")
.probes(
PreservedJson.from_json(
- json.dumps({"readinessProbe": {"tcpSocket": {"port": 8000}}})
+ json.dumps({"readinessProbe": {"tcpSocket": {"port": self._server_port}}})
)
)
.services(services)
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 4342587242..4f6f9f94e2 100644
--- a/libs/python/cua-sandbox/tests/test_fleet_cloud_transport.py
+++ b/libs/python/cua-sandbox/tests/test_fleet_cloud_transport.py
@@ -1,3 +1,5 @@
+import json
+
import pytest
from cua_sandbox import Image
from cua_sandbox.transport import fleet_cloud
@@ -23,6 +25,67 @@ def test_registry_image_becomes_typed_template_request():
]
+def test_custom_server_port_configures_service_probe_and_exposed_port_deduplication():
+ request = FleetCloudTransport(
+ image=Image.from_registry("registry.example/workspace@sha256:abc")
+ .expose(5000)
+ .expose(3000),
+ name="demo",
+ server_port=5000,
+ )._template_request()
+
+ vm_template = request.spec.vm_template
+ assert [(service.name, service.target_port) for service in vm_template.services] == [
+ ("server", 5000),
+ ("port-3000", 3000),
+ ]
+ assert json.loads(vm_template.probes.to_json()) == {
+ "readinessProbe": {"tcpSocket": {"port": 5000}}
+ }
+
+
+def test_custom_services_include_configured_server_port():
+ request = FleetCloudTransport(
+ image=Image.from_registry("registry.example/workspace@sha256:abc"),
+ name="demo",
+ server_port=5000,
+ services={"metrics": 9000},
+ )._template_request()
+
+ assert [
+ (service.name, service.target_port) for service in request.spec.vm_template.services
+ ] == [
+ ("server", 5000),
+ ("metrics", 9000),
+ ]
+
+
+def test_custom_server_service_cannot_override_configured_server_port():
+ request = FleetCloudTransport(
+ image=Image.from_registry("registry.example/workspace@sha256:abc"),
+ name="demo",
+ server_port=5000,
+ services={"server": 9000, "metrics": 9001},
+ )._template_request()
+
+ assert [
+ (service.name, service.target_port) for service in request.spec.vm_template.services
+ ] == [
+ ("server", 5000),
+ ("metrics", 9001),
+ ]
+
+
[email protected]("server_port", [True, False, 0, -1, 65536, 5000.0, "5000"])
+def test_rejects_invalid_server_port(server_port):
+ with pytest.raises(ValueError, match="server_port must be an integer between 1 and 65535"):
+ FleetCloudTransport(
+ image=Image.from_registry("registry.example/workspace:latest"),
+ name="demo",
+ server_port=server_port,
+ )
+
+
def test_pool_request_only_references_the_template():
request = FleetCloudTransport(
image=Image.from_registry("registry.example/workspace@sha256:abc"),
@@ -480,6 +543,24 @@ async def test_forward_tunnel_uses_named_service_url():
assert tunnel.url == "https://run.cua.ai/api/svc/demo/sandbox-port-3000/"
+async def test_forward_tunnel_uses_server_service_for_custom_server_port():
+ transport = FleetCloudTransport(
+ image=Image.from_registry("example:latest"), name="demo", server_port=5000
+ )
+ transport._provisioned = True
+ transport._bound = Sandbox(namespace="demo", claim="claim", name="sandbox", services=["server"])
+
+ class Client:
+ def service_url(self, sandbox, service):
+ assert service == "server"
+ return "https://run.cua.ai/api/svc/demo/sandbox-server/"
+
+ transport._sdk = Client()
+ tunnel = await transport.forward_tunnel(5000)
+ assert tunnel.url == "https://run.cua.ai/api/svc/demo/sandbox-server/"
+
+
@pytest.mark.asyncio
async def test_snapshot_is_unsupported():
transport = FleetCloudTransport(image=Image.from_registry("example:latest"), name="demo")
diff --git a/libs/python/cua-sandbox/tests/test_vm_cleanup.py b/libs/python/cua-sandbox/tests/test_vm_cleanup.py
index 92a1e86ccd..ab1815f868 100644
--- a/libs/python/cua-sandbox/tests/test_vm_cleanup.py
+++ b/libs/python/cua-sandbox/tests/test_vm_cleanup.py
@@ -243,7 +243,135 @@ class TestDestroyResilience:
# ===================================================================
-# 3. ephemeral() integration — cleanup through the context manager
+# 3. Fleet server_port forwarding and validation
+# ===================================================================
+
+
+class TestFleetServerPortForwarding:
+ """Sandbox factories should pass server_port to Fleet and validate it early."""
+
+ @pytest.mark.parametrize("server_port", [1, 65535])
+ async def test_create_forwards_server_port(self, server_port):
+ sandbox = object()
+ with patch.object(Sandbox, "_create", AsyncMock(return_value=sandbox)) as create:
+ result = await Sandbox.create(
+ Image.from_registry("registry.example/workspace:latest"),
+ server_port=server_port,
+ telemetry_enabled=False,
+ )
+
+ assert result is sandbox
+ assert create.await_args.kwargs["server_port"] == server_port
+
+ async def test_create_forwards_default_server_port(self):
+ sandbox = object()
+ with patch.object(Sandbox, "_create", AsyncMock(return_value=sandbox)) as create:
+ result = await Sandbox.create(
+ Image.from_registry("registry.example/workspace:latest"),
+ telemetry_enabled=False,
+ )
+
+ assert result is sandbox
+ assert create.await_args.kwargs["server_port"] == 8000
+
+ async def test_ephemeral_forwards_server_port(self):
+ sandbox = _make_sandbox(_make_cloud_transport(name="port-e2e"), ephemeral=True)
+ sandbox.destroy = AsyncMock()
+ with patch.object(Sandbox, "_create", AsyncMock(return_value=sandbox)) as create:
+ async with Sandbox.ephemeral(
+ Image.from_registry("registry.example/workspace:latest"),
+ server_port=5000,
+ telemetry_enabled=False,
+ ):
+ pass
+
+ assert create.await_args.kwargs["server_port"] == 5000
+
+ async def test_create_passes_server_port_to_fleet_transport(self):
+ transport = _make_cloud_transport(name="port-fleet")
+ transport.connect = AsyncMock()
+
+ with (
+ patch(
+ "cua_sandbox.sandbox.FleetCloudTransport",
+ return_value=transport,
+ ) as fleet_transport,
+ patch.object(Sandbox, "_connect", AsyncMock()),
+ ):
+ await Sandbox._create(
+ image=Image.from_registry("registry.example/workspace:latest"),
+ server_port=5000,
+ telemetry_enabled=False,
+ )
+
+ assert fleet_transport.call_args.kwargs["server_port"] == 5000
+
+ async def test_existing_pool_does_not_pass_server_port_to_fleet_transport(self):
+ transport = _make_cloud_transport(name="existing-pool")
+
+ with (
+ patch.object(Sandbox, "_uses_fleet", return_value=True),
+ patch(
+ "cua_sandbox.sandbox.FleetCloudTransport",
+ return_value=transport,
+ ) as fleet_transport,
+ patch.object(Sandbox, "_connect", AsyncMock()),
+ ):
+ await Sandbox._create(
+ name="existing-pool",
+ server_port=5000,
+ telemetry_enabled=False,
+ )
+
+ assert "server_port" not in fleet_transport.call_args.kwargs
+
+ @pytest.mark.parametrize("server_port", [True, False, 0, -1, 65536, 5000.0, "5000"])
+ async def test_create_rejects_invalid_server_port_before_local_provisioning(self, server_port):
+ runtime = AsyncMock()
+
+ with pytest.raises(ValueError, match="server_port must be an integer between 1 and 65535"):
+ await Sandbox.create(
+ Image.from_registry("registry.example/workspace:latest"),
+ local=True,
+ runtime=runtime,
+ server_port=server_port,
+ telemetry_enabled=False,
+ )
+
+ runtime.start.assert_not_awaited()
+
+ @pytest.mark.parametrize("server_port", [True, False, 0, -1, 65536, 5000.0, "5000"])
+ async def test_invalid_server_port_rejects_before_legacy_cloud_provisioning(self, server_port):
+ with patch("cua_sandbox.sandbox._make_transport") as make_transport:
+ with pytest.raises(
+ ValueError, match="server_port must be an integer between 1 and 65535"
+ ):
+ await Sandbox._create(
+ image=Image.from_registry("registry.example/workspace:latest"),
+ api_key="sk-legacy",
+ server_port=server_port,
+ telemetry_enabled=False,
+ )
+
+ make_transport.assert_not_called()
+
+ @pytest.mark.parametrize("server_port", [True, False, 0, -1, 65536, 5000.0, "5000"])
+ async def test_invalid_server_port_rejects_before_fleet_provisioning(self, server_port):
+ with patch("cua_sandbox.sandbox.FleetCloudTransport") as fleet_transport:
+ with pytest.raises(
+ ValueError, match="server_port must be an integer between 1 and 65535"
+ ):
+ await Sandbox._create(
+ image=Image.from_registry("registry.example/workspace:latest"),
+ server_port=server_port,
+ telemetry_enabled=False,
+ )
+
+ fleet_transport.assert_not_called()
+
+
+# ===================================================================
+# 4. ephemeral() integration — cleanup through the context manager
# ===================================================================