diff --git a/.github/workflows/pytest.yml b/.github/workflows/pytest.yml new file mode 100644 index 000000000..2a0e126f6 --- /dev/null +++ b/.github/workflows/pytest.yml @@ -0,0 +1,27 @@ +name: Pytest + +on: + pull_request: + push: + branches: [main, develop] + +jobs: + pytest: + runs-on: ubuntu-latest + strategy: + matrix: + python-version: ["3.11", "3.12", "3.13"] + steps: + - uses: actions/checkout@v4 + with: + submodules: true + + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + + - name: Install uv + run: python -m pip install uv + + - name: Run unit tests + run: uv run --locked --extra sandbox --extra dev pytest tests/unit diff --git a/AGENTS.md b/AGENTS.md index 5f6368b2a..4babad770 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,10 +15,11 @@ Agent skills live in the `skills/` submodule (`droidrun/skills`). See [mobilerun/README.md](mobilerun/README.md) for the detailed package map, examples, and dependency diagram. -- `mobilerun/core/`: device, state, operator and resource interfaces. +- `mobilerun/core/`: operators, extensions, screen views, recording and account resources. +- `mobilerun-core` (separate package): native device actions, observation, lifecycle and action hooks. - `mobilerun/core/webhooks/`: organization webhook endpoints; commands in `mobilerun/cli/webhook/`. - LLM-backed agent execution is in the separate `mobilerun-agents` package (not yet publicly published). -- `mobilerun/clients/`: cloud, local and Portal service adapters. +- `mobilerun/clients/`: account service adapters and shared client helpers. - `mobilerun/models/`, `config/`, `errors/`, `logs/`, `utils/`: shared types and support. - `mobilerun/cli/`: command groups and shared CLI helpers. - `mobilerun/macro/`, `sandbox/`, `skills/`: independent framework features. @@ -26,11 +27,11 @@ examples, and dependency diagram. - `tests/unit/`: unit tests and opt-in real-world smoke tests. - `skills/`: git submodule; `hatch_build.py` bundles its files in the wheel. -Shared core must not import agents or feature packages. The intended boundaries -are checked in `tests/unit/architecture/test_layers.py`. The agent-required -dependency test (`tests/unit/test_agent_required_dependencies.py`) lives in the -separate `mobilerun-agents` repository. The CLI entry point has a special role; see the boundary tests for exceptions. -The v008 migration and legacy path resolver locate `mobilerun_agents` prompt assets without importing the add-on. +Shared core must not import agents or feature packages. The +[architecture tests](tests/unit/architecture/test_layers.py) enforce the public +`mobilerun_core` import boundary in production code and tests. They reject +imports from the retired framework device and state packages. See those tests +for the CLI entry point and fake-driver exceptions. ## Where code goes @@ -39,11 +40,9 @@ If yes, it belongs in an optional feature (`sandbox/`, `mcp/`, `macro/`, `skills/`); if not, put it in `core/` or a shared package. For example, `sandbox/` is removable; `core/webhooks/` is not, because the webhook CLI and sandbox both use it. In `mobilerun/`, `core/` holds domain -objects: devices, operators, state, credentials, proxies, numbers, mailboxes, -webhooks, workspace, and extensions. `models/`, `clients/`, `errors/`, `utils/`, -`config/`, and `logs/` supply shared building blocks. Phone behavior lives in -`core/devices/` and its components; account-wide resources live in their own -core folders or on `Workspace`. See the [topic map](mobilerun/core/README.md#topic-map). +interfaces that use a device, plus account resources. Native phone behavior lives +in `mobilerun-core`. Account resources live in their own core folders or on +`Workspace`. See the [topic map](mobilerun/core/README.md#topic-map). Features keep their own CLI, errors, models, settings, and utilities in their folders. Shared packages (including `cli/`) do not import features. Features do @@ -51,10 +50,10 @@ not import each other or the agent add-on. Core can use clients; clients do not import core or the root package. Register feature CLI groups via `mobilerun.cli` entry points in `pyproject.toml`. -Core subpackages (`core/credentials/`, `core/devices/`, `core/webhooks/`, …) +Core subpackages (`core/credentials/`, `core/screen/`, `core/webhooks/`, …) are part of core, not features: they never get their own `settings.py`, `utils.py`, `errors.py` or `models.py`. Their tunables go in -`config/settings.py`, helpers in `utils/`, errors in `errors/`, models in +`config/settings.py`, helpers in `utils//`, errors in `errors/`, models in `models/`. Domain constants that callers need (e.g. a default event type) are exported from the subpackage's `__init__.py`; backend limits stay private in the module that uses them. Only feature packages (`macro/`, `mcp/`, `skills/`, @@ -62,14 +61,16 @@ the module that uses them. Only feature packages (`macro/`, `mcp/`, `skills/`, | New code | Location | | --- | --- | -| Device error | `errors/device.py` | -| Macro error | `macro/errors.py` | -| Core tunable (e.g. webhook page size) | `config/settings.py` | -| Core helper (e.g. URL masking) | `utils/` (e.g. `utils/redaction.py`) | -| Core cloud adapter | `clients/cloud/.py` | -| Proxy CLI command | `cli/proxy/` | -| Webhook CLI command | `cli/webhook/` | -| Skills CLI | `skills/cli/` | +| Native device operation | `mobilerun-core` repository | +| Operator or prompt screen view | `mobilerun/core/operator/` or `mobilerun/core/screen/` | +| Action or screen recording | `mobilerun/core/runs/` | +| Macro error | `mobilerun/macro/errors.py` | +| Core tunable (e.g. webhook page size) | `mobilerun/config/settings.py` | +| Framework core helper (e.g. redaction) | `mobilerun/utils/` | +| Framework cloud account adapter | `mobilerun/clients/cloud/` | +| Proxy CLI command | `mobilerun/cli/proxy/` | +| Webhook CLI command | `mobilerun/cli/webhook/` | +| Skills CLI | `mobilerun/skills/cli/` | ## Setup @@ -130,28 +131,45 @@ security checks (`bandit -r mobilerun`, `safety scan`) and external docs updates ## Code rules -- Feature packages mirror the top-level layout with few files and no extra - subfolders beyond `cli/`. -- Keep config/settings modules declarative; put logic in role-named modules and - helpers in `utils.py`. -- Put tunable constants (URLs, timeouts, names) in the package's `settings.py`, - built like `mobilerun/config/settings.py`. +- Each folder contains one kind of file. Split distinct roles into subfolders + such as `cli/`, `clients/`, or `helpers/`. Put shared utilities in `utils//`. + Feature packages stay self-contained. +- Keep one behavior class per file. Related value types may share a file. + Do not put module-level functions beside classes except private helpers used + only by that file's base class. Use a classmethod for an instance builder. +- Use one interface per concept. Call it directly: no pass-through wrappers or + one-caller hops. Keep config/settings modules declarative. +- Pin Mobilerun-owned packages exactly; give third-party dependencies a lower + bound only. +- Put framework core tunables in `mobilerun/config/settings.py` and feature + tunables in the feature's `settings.py`. - Ship each feature or fix with unit tests using fakes, without devices or cost. - Do not add speculative functions: add code used by a caller or public API. -- Use type hints and explicit contracts. Device capabilities that are unavailable - raise `DeviceOperationNotSupported`; do not guess capabilities on our classes. +- Use type hints and explicit contracts. For device access, import only public + `mobilerun_core` APIs, not its driver packages or `adbutils`. Open handles with + `AsyncMobilerun`; use `AsyncDevice.from_driver()` for caller-owned drivers or + fakes. Check `device.supports(verb)` where needed. Use native errors from + `mobilerun_core.errors`, or `UnsupportedOperation` from `mobilerun_core`. +- Pass devices to operators per call and extensions to the operator constructor. + Do not attach an operator or an extension registry to a device. - In device action flows, use `await device.wait(seconds)` rather than - `asyncio.sleep`: recording captures device waits for macro replay. -- Use `async with` or `close()` for lifecycle cleanup. Release resources created + `asyncio.sleep`: recording captures device waits for macro replay. The screen + recorder's settle timer is host-only; an action hook must not call another + action on the same device. +- Use `async with` for core handles or `aclose()` when managing them manually. + Close framework resources through their own APIs. Release resources created in this run, not resources supplied by ID; preserve ownership on reuse. - Billing defaults to `paid`; `MOBILERUN_BILLING` changes the default and an explicit `billing=` argument overrides both. - Respect guards in `mobilerun/clients/cloud/billing.py`; `no_commerce` blocks + Respect guards in `mobilerun/clients/cloud/billing_policy.py`; `no_commerce` blocks purchases. - Never expose secret values in logs, exceptions or representations. Cloud tasks use vault references from `CloudCredentials`, not local credential values. - CLI commands should prompt for missing values when interactive, confirm paid or destructive actions, and support `--yes` and non-interactive operation. + Use the decorators in `mobilerun.cli.devices.base.device` so device commands + use core's approval gate. Do not approve unrelated operations. + Proxy replacement requires `--force` or interactive confirmation. - No compatibility layer: use the current public API and CLI command paths; agent code comes from the `mobilerun-agents` add-on. ## Documentation diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 000000000..e27e958de --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,85 @@ +# Changelog + +## 0.9.0 (unreleased) + +### Breaking / Removed + +The framework uses `mobilerun-core[local]==2.0.0`. Import native devices, values and errors from `mobilerun_core`; the framework no longer imports driver packages directly. + +| Before (framework) | Now | +| --- | --- | +| `Device`, `AndroidDevice`, `IOSDevice`, `CloudDevice`, `RemoteDevice` from `mobilerun`, `mobilerun.core` or `mobilerun.core.devices` | `AsyncDevice` and `AsyncMobilerun` from `mobilerun_core`. Use `await run.connect(...)` for an existing phone or remote session. | +| `DevicePool`, `DeviceWrapper` | No drop-in replacements. Manage core handles directly and loop over them instead of using a pool. | +| `RecordingDevice`, `StealthDevice` | Use `ActionRecording(device)` or `ScreenRecording(device)` from `mobilerun.core.runs` on the original device. Keep actions outside the recording scope to omit them. There is no stealth wrapper. | +| `DriverDevice(driver)` | `AsyncDevice.from_driver(driver)` for a caller-owned driver; declare supported verbs with `supported`. | +| `AndroidDevice(avd=...)` | `await run.start_emulator(avd, ...)`. | +| `device.close()` | `await device.aclose()` or an async context manager. The `AsyncMobilerun` context also closes its handles. | +| `device.input_text(...)`, `device.press_button(...)`, `device.press_key_code(...)` | `await device.type(...)`, `await device.key(name_or_code)`. Tap, swipe and drag are core verbs; `swipe` and `drag` use `ms=` and `wait` uses `seconds`. | +| `device.start_app(package, activity)`, `device.install_apk(path)`, `device.open_url(url)`, `InstallOptions`, `Workspace.install_app(app, device)` | Use `await device.start_app(app_id, activity=...)` and `await device.open_deep_link(url)`. Install a local artifact with `await device.install_app(Path(...))` or install from the cloud library on a cloud phone with `await device.install_app(CloudAppRef(...))`. Pass install options as keywords. | +| `device.push_file(path, dest)`, `device.pull_file(remote_path, local_path)` | `await device.push_file(source, device_path)` takes bytes or a local path and a full destination path. `await device.pull_file(device_path)` returns bytes. `list_files` returns core `FileEntry` values; `delete_file` is also a core verb. | +| Framework location, timezone, language and clipboard methods | Core `get/set_location`, `reset_location`, `get/set_timezone`, `get/set_locale` and `get/set_clipboard`. Use `locale`, not `language`. | +| `mobilerun.core.state`: `UIState`, `UIElement`, `StealthUIState`, `DeviceSnapshot`, `UIStateView`; `device.state.refresh()`, `device.screenshot()`, `device.tap_element(index)` | Use core `Observation` and `Element` via `await device.observe(screenshot=True)`. Use `await device.ui()` or `await device.screenshot_bytes()` for standalone reads. Core `tap_element` takes an `Element`. Use `ScreenProvider` for prompt text and `await device.tap_element(snapshot.element(index))` for indexed taps. There is no `StealthUIState` equivalent. | +| `mobilerun.core.state`: `StateProvider`, `AndroidStateProvider`, `IOSStateProvider`, `ScreenshotOnlyStateProvider`; factories `android_state_provider`, `ios_state_provider`, `screenshot_state_provider` and `StateProviderFactory` | Import the provider classes from `mobilerun_core`. Core selects the default provider. The framework provider factories are gone. | +| `StateProviderOptions`, `VisionResizePolicy`, state filters and formatters | Use `ScreenProvider`, `ScreenOptions` and `VisionResizePolicy` from `mobilerun.core.screen`. Import `ScreenView` and `ModelGeometry` from `mobilerun.models.screen`. | +| `mobilerun.models.Location`, `mobilerun.models.UIElement`; framework `ProxyStatus` imports from `mobilerun.models`, `mobilerun.models.proxy`, `mobilerun.core.proxy` or `mobilerun.interfaces` | Import `Location`, `Element` and `ProxyStatus` from `mobilerun_core`. | +| `mobilerun.models.DeviceFile`, `mobilerun.clients.cloud.files.list_device_files` | Use `await device.list_files(directory)` with core `FileEntry` values. `WorkspaceFile` still represents an account library file, not a device file. | +| `device.supported_operations`, `DeviceOperationNotSupported` for native calls, framework `NoFocusedInput` and `UnsupportedStateCapability` | Use `device.supports(verb)` and `device.capabilities`; handle core `UnsupportedOperation` and `mobilerun_core.errors.NoFocusedInput`. Protected input uses `await device.type_secret(Secret(value))` and requires verified editable focus. | +| `CredentialLookup`, `PlaceholderError`, `LocalCredentialsNotAllowed` | Removed. | +| `mobilerun.models.billing.Plan` | Use `mobilerun_core.CloudPlan` or its string literals. | +| Framework `DeviceNotReady`, `StateFetchFailed`, `ProxyNotActive` | No one-to-one exceptions. Use the core cloud handle's `wait_ready()`, native `observe()` with core errors, and `proxy_status()` for connected state. | +| `proxy.bind(device, force=True)` | Core binds with `await device.set_proxy(value, replace=True)` and exposes `proxy_status()` and `clear_proxy()` where supported. Framework products still handle catalogue, purchase and selection; `proxy.apply(replace=True)` uses a device supplied explicitly. | +| `mobilerun.interfaces.Proxy`; `ProxyTarget`, `CloudProxyTarget`, `AndroidProxyTarget` in `mobilerun.core.proxy.target` | Use `Proxy.status()` on a framework proxy configured with `device=`, or call the native `device.proxy_status()` directly. | +| `CloudProxy`, `ExistingCloudProxy`, `LocalProxy` | Removed. Pass a core `ConnectProxyRef` for an existing Connect proxy or `HttpProxy` for an HTTP proxy to `device.set_proxy(...)` on a supported backend. | +| `mobilerun.clients.cloud.apps`, `mobilerun.clients.cloud.files`, `mobilerun.clients.cloud.webhooks` | Use `Workspace` for account apps and files, and `CloudWebhooks` for organization webhooks. Use core device methods for on-device operations. | +| `Webhooks` protocol in `mobilerun.interfaces.webhooks` | Use `CloudWebhooks` from `mobilerun.core.webhooks` and `WebhookEndpoint` from `mobilerun.models`. | +| New `CloudDevice(...)` or `mobilerun.clients.cloud.devices.create(...)` | Use `await run.create_cloud(...)` with an explicit `ConnectProxyRef` and a core approval gate. Use `BillingPolicy.cloud_phone_plan(...)` to apply framework billing policy before provisioning. | +| `MOBILERUN_CLOUD_DEVICE_TYPE` | Pass `device_type=` explicitly when provisioning. | +| `devices.list_devices`, `devices.retrieve`, `devices.set_name` and old cloud lifecycle calls | `await run.list_cloud_devices()` for records; use `run.cloud_device(id)` to `refresh`, `wait_ready`, `rename`, `stop`, `resume`, `reboot`, `reset` or `terminate` without a UI connection. | +| Framework Portal ping, release lookup, setup and Android diagnostic adapters | Use `run.local` for `ping_portal()`, `latest_portal_release()`, setup and `diagnose_android()`. Portal recovery is explicit. | +| `mobilerun.clients.portal.state_fetch.fetch_state_with_retry`, `mobilerun.clients.portal.errors_text.ACCESSIBILITY_SERVICE_NOT_AVAILABLE` | Use native `device.observe()` and handle typed core Portal errors instead of matching error strings. | +| `mobilerun.core.runs.capture.FingerprintCapture`, `mobilerun.core.runs.session.RecordingSession` | Use `ActionRecording` or `ScreenRecording`. They install `device.use_action_hooks(before=..., after=...)`; `ScreenRecording` captures screen evidence. | +| Device extension registry and `mobilerun.core.extensions.registry.Binding`; `@action` and `@device_action` | Supply `extensions=[...]` to the operator and declare tools with `@function`. | +| `mobilerun.core.extensions.Action`, `ActionSet`, `ActionInfo`, `dispatch_guard`, `BillingRetry`, `iter_sensitive_values` | Use `Tool` and `operator.tools()` for the tool list. `ToolCallInfo` and `tool_dispatch_guard` cover tool dispatch. There is no public extension billing-retry or sensitive-value iterator. | +| `device.do(...)`, `device.expect(...)`, `Tasks.execute(...)`; `Credentials.type_field(...)` | Call `operator.do(device, ...)` or `operator.expect(device, ...)`. For credentials, pass `device=` to the provider and call `type_secret(name, package=..., field=...)`. | +| `mobilerun.utils.geometry`: `Bounds`, `rects_overlap`, `find_uncovered_point`, `find_clear_point` | Read native element bounds from `Element.bounds`; use core `device.tap_element(element)` for native targeting. No drop-in geometry helpers. | +| `mobilerun device action list`, `mobilerun device action call`, `mobilerun device action extensions` | Use explicit CLI commands such as `mobilerun device input tap` for native actions. Declare extension tools in Python; there is no generic CLI dispatcher. | +| Device CLI `DeviceTarget` and `base.options` | Use `@device_command`, `@cloud_command` or `@run_command` from `mobilerun.cli.devices.base.device` to inject a core handle. | +| Free functions in cloud account adapters | Bind `Proxies`, `Numbers`, `Mailboxes`, `Secrets`, `Tasks` and `ApiKeys` instances to the account and billing policy. For credential-free Connect results, use the helpers in `mobilerun.core.proxy`. | + +### Changed + +- An operator takes a device on every call: `await operator.do(device, instruction)` or `await operator.expect(device, condition)`. Choose the operator explicitly, including for hosted tasks. +- Pass extensions to the operator with `extensions=[...]`. Only methods declared with `@function` become tools. `to_atomic` can replace a method with named, zero-argument async tools. Pass `device=` to credentials for typing, use `number.attach(device)` / `number.detach()`, and call mailboxes directly. Hosted tasks receive vault references, not secret values. +- Vault provider provenance (`source`) is optional. Import `CredentialMetadata` from `mobilerun.models`. +- Record native calls on the original device through action hooks. Use `rec.extension_call(name, arguments)` for one explicit tool row instead of its nested device actions. The screen recorder settles on a host timer, not a replayable wait. +- Drive a recorded device from one task at a time and never call device actions from hooks. Concurrent actions can interleave, cancelled actions may not produce rows, and closing the device does not wait for in-flight actions. +- Recordings mask all plausible grouped codes from mailbox and SMS history, as written or compacted, and may also mask unrelated numbers. Polling behavior is unchanged. +- New run and macro rows use schema 2: `key(name_or_code)`, `wait(seconds)` and explicit `extension_call` rows. Existing unstamped JSONL runs and macros still load; portable actions are translated in memory without modifying the files. The older `macro.json` format still requires re-recording. +- Sensitive macro mismatches raise `MacroHandoffRefused` with a step index and phase but no screen or action data. +- Phones created by a run terminate on close unless `keep=True`. Automatic termination requires `plan="minute"`. Closing a phone connected by ID never terminates it. +- `Workspace.push_file` needs a full destination filename, not a directory. `Workspace.pull_file` uploads bytes read from the device to the account library. +- `Workspace.upload_app` delegates APK upload to `AsyncMobilerun.upload_app` without connecting a device and still returns a framework `App`. +- `mobilerun device screen ui` no longer repairs Portal automatically. A failed read does not restart Portal. +- Device CLI handlers now receive core device handles directly. `device app install`, `device file rm`, and `device settings location set` now require confirmation unless you pass `--yes`. Core also gates app uninstall and cloud lifecycle operations such as stop, reboot, and terminate. +- `mobilerun device cloud resume` requires `included` or `paid` billing for subscription phones and `paid` for all other strategies. Core still requires approval; `--yes` does not bypass billing policy. +- `mobilerun proxy bind` requires core approval even for the first bind and refuses non-interactive use without `--yes`. Replacing an active proxy additionally requires `--force` or interactive confirmation. `proxy buy` keeps its existing billing policy, including one paid retry after an approved billing upgrade. +- Device discovery and CLI selection use core `DeviceDescriptor` values. CLI JSON and the run file's `{platform, identifier}` shape are unchanged. + +### Added + +- `ScreenProvider` projects core observations into indexed, redacted prompt text with model-to-native coordinate mapping. +- `ActionRecording` stores actions, timestamps and outcomes. `ScreenRecording` adds before/after observations and stores screenshots at their original size. + +### Fixed + +- Screen recording saves either artifact if the other read fails. +- Number and mailbox payment recovery uses the existing resource ID: `PaymentRequired.resource_id` identifies the pending resource, and checkout timeouts report the ID for recovery in the dashboard without cancelling the resource. +- Framework cloud account errors are built from detached core error facts, preserving safe status, request ID and known error codes without retaining the original SDK response. +- Macro replay validates portable calls against core action schemas. Recorded element taps preserve the native tap point and atomic tool calls keep their validation aliases; cloud-only holds and app-data wipes remain unsupported. +- `mobilerun doctor` renders structured ADB and TCP facts, including the forwarded port and distinct missing-forward and unreachable-forward results. `mobilerun device list` includes offline and unauthorized Android devices. + +### Internal + +- Removed telephony SDK forwarders from `mobilerun.clients.cloud.devices`, the `mobilerun.cli.base.logging` module, and synchronous `confirm_action()` from `mobilerun.cli.base.safety`. +- Removed the unused `resize_image_to_max_side()` and `resize_image_to_max_side_with_grid()` image helpers and the sandbox `replace_document()` and `create_trigger()` adapters. +- Removed `skills_roots()`; use `skills_root()`. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index d169767f2..d2b6bea7a 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -51,9 +51,16 @@ Thank you for your interest in contributing to Mobilerun! This document provides 5. Open a Pull Request +## Device boundary + +- Implement native actions, observation and lifecycle in [mobilerun-core](https://github.com/droidrun/mobilerun-core). Use its public async API from this repository; do not import driver packages or `adbutils` directly. +- Keep operators, extensions, prompt screens, recording, macro replay and CLI wiring here. See the [package map](mobilerun/README.md) and [agent guide](AGENTS.md). +- Use `AsyncDevice.from_driver()` with a fake driver for framework unit tests. Test native behavior in the core repository. The [architecture tests](tests/unit/architecture/test_layers.py) enforce the public core import boundary in both framework code and tests. + ## Documentation - Update the README.md if you change functionality +- Update [CHANGELOG.md](CHANGELOG.md) with user-visible changes and migration steps - Add docstrings to new functions and classes - Update the documentation in [droidrun/mobilerun-docs](https://github.com/droidrun/mobilerun-docs) diff --git a/README.md b/README.md index b24b3c88d..41318f7bc 100644 --- a/README.md +++ b/README.md @@ -51,7 +51,9 @@ ## What is Mobilerun? -Mobilerun controls Android and iOS devices from Python or a CLI. Use direct device actions, record and replay macros, or delegate a task to an AI agent. Devices can be local or hosted in [Mobilerun Cloud](https://cloud.mobilerun.ai). +Use [mobilerun-core](https://github.com/droidrun/mobilerun-core) to connect to Android and iOS devices and run native actions. This framework adds a CLI, extensions, operators, recording and macro replay. Devices can be local or hosted in [Mobilerun Cloud](https://cloud.mobilerun.ai). See the [changelog](CHANGELOG.md) for migration details. + +The core backend split is in progress: cloud, local Android and local iOS use `AsyncCloudDevice`, `AsyncLocalAndroidDevice` and `AsyncLocalIOSDevice`, respectively, all subclasses of `AsyncDevice`; unknown drivers and fakes use plain `AsyncDevice`. ## Install @@ -82,12 +84,13 @@ Or use Python directly (replace the serial): ```python import asyncio -from mobilerun.core.devices import AndroidDevice +from mobilerun_core import AsyncMobilerun async def main(): - async with AndroidDevice("emulator-5554") as device: - await device.start_app("com.android.settings") - await device.press_button("home") + async with AsyncMobilerun() as run: + phone = await run.connect("emulator-5554", backend="local-android-adb") + await phone.start_app("com.android.settings") + await phone.key("home") asyncio.run(main()) ``` @@ -97,12 +100,11 @@ asyncio.run(main()) - **CLI and Python:** Inspect devices, run agent tasks, and build automation workflows. - **Android and iOS:** Drive Android with Portal, iPhones via mobilerun-ios, and iOS simulators with iOS Portal. - **Portal control:** Inspect UI trees and screenshots; launch apps, tap, swipe and type. -- **Vision:** Use `--vision` to include screenshots or `--vision-only` for screenshot-only control. -- **Reasoning:** Use `--reasoning` for manager–executor planning. -- **Tracing:** Inspect runs with Arize Phoenix, Langfuse, logs and saved trajectories. +- **Screens:** Use `ScreenProvider` for prompt-ready UI and optional screenshots. +- **Recording:** Capture action timings or add before/after screenshots and UI state. - **Structured output:** Return typed results from tasks. - **Webhooks:** Send [sandbox function results](mobilerun/sandbox/README.md#send-a-function-result-to-a-webhook) to an HTTPS receiver. -- **Custom tools:** The `mobilerun-agents` add-on supports custom agent actions. +- **Custom tools:** Declare extension methods with `@function` and pass the extensions to an operator. - **Docker:** The repository's [Dockerfile](Dockerfile) builds a container whose entrypoint is the Mobilerun CLI. ### Build the Docker image @@ -117,7 +119,7 @@ This refreshes the list of tracked skills before Docker builds the wheel without ### LLM providers -The configuration wizard supports OpenAI, Anthropic, Gemini, xAI, Ollama, MiniMax, ZAI and OpenAI-compatible endpoints such as OpenRouter, LM Studio and vLLM. The CLI also lists DeepSeek. Provider credentials and usage charges depend on your selection. Anthropic and DeepSeek support are provided by the required `mobilerun-agents` add-on; no provider extra is needed. +The `mobilerun-agents` add-on provides local LLM execution. Provider setup and usage charges depend on the add-on configuration. ## Easy examples @@ -126,48 +128,46 @@ The Python snippets below use an `async def` function. Run it with `asyncio.run( ### Local Android and iOS ```python -from mobilerun.core.devices import AndroidDevice, IOSDevice - -async def devices(): - async with AndroidDevice("emulator-5554") as android: - await android.press_button("home") - async with IOSDevice("http://localhost:8100") as ios: - await ios.press_button("home") +from mobilerun_core import AsyncMobilerun + +async def devices(ios_portal_url: str, ios_token: str | None = None): + async with AsyncMobilerun() as run: + android = await run.connect("emulator-5554", backend="local-android-adb") + await android.key("home") + ios = await run.connect( + backend="local-ios-http", url=ios_portal_url, token=ios_token + ) + await ios.screenshot_bytes() ``` Use the actual iOS Portal or mobilerun-ios URL for your setup. See [device setup](https://docs.mobilerun.ai/framework/guides/device-setup). ### Cloud phone and proxy -**Cost:** creating a cloud phone and using its proxy can incur charges. Authenticate with `mobilerun account login` or `MOBILERUN_API_KEY` first. +**Cost:** creating a cloud phone and using its proxy can incur charges. Set `MOBILERUN_API_KEY`, pass an existing Connect proxy ID, and supply a [gate](https://github.com/droidrun/mobilerun-core#-hitl-gate) that approves provisioning and cleanup. This example does not buy a proxy. ```python -from mobilerun.core.devices import CloudDevice -from mobilerun.core.proxy import CloudRotatingProxy - -async def cloud_phone(): - async with CloudDevice(name="demo", billing="paid", plan="minute", - proxy=CloudRotatingProxy(country="US")) as phone: - await phone.press_button("home") +from mobilerun_core import AsyncMobilerun, ConnectProxyRef, HitlGate + +from mobilerun.clients.cloud.devices import CloudPhones + +async def cloud_phone(proxy_id: str, gate: HitlGate): + async with AsyncMobilerun(hitl_gate=gate) as run: + phone = await CloudPhones(run, billing="paid").create( + name="demo", + plan="minute", + proxy=ConnectProxyRef(proxy_id), + ) + await phone.key("home") ``` -The context manager releases resources it creates; existing IDs are not automatically released. `keep=True` retains created resources. `MOBILERUN_BILLING` sets the default billing mode (`no_commerce` blocks purchases, `included` uses enforced included quotas); an explicit `billing=` argument overrides it, so the paid examples here still permit charges. +Closing a newly created phone terminates it unless `keep=True`. Automatic termination requires the `minute` plan. Phones connected by ID are borrowed; closing them does not terminate them. `MOBILERUN_BILLING` sets the default billing mode; the explicit `billing="paid"` above overrides it. ### Run an agent task -**Cost:** local agent tasks can consume LLM tokens; cloud tasks consume credits. - -```python -# Requires the unpublished mobilerun-agents add-on. -from mobilerun_agents import AgentOperator -from mobilerun.core.devices import AndroidDevice - -async def task(): - async with AndroidDevice("emulator-5554", operator=AgentOperator()) as device: - print(await device.do("Open Settings")) -``` +Pass the phone to a concrete operator with `await operator.do(phone, "Open Settings")` or `await operator.expect(phone, "Settings is open")`. Supply extensions when constructing the operator. Use `CloudTaskOperator` for hosted tasks (see [Structured output](#structured-output)) or `AgentOperator` from the separate `mobilerun-agents` add-on for local execution. -Configure an LLM first with `mobilerun agent llm configure`. `CloudDevice` uses a cloud task operator by default. +**Cost:** cloud tasks can consume credits; local agent tasks can consume LLM tokens. ### Record and replay a macro @@ -175,14 +175,17 @@ Record actions on a local emulator, then publish the replayable steps as a versi ```python from pathlib import Path -from mobilerun.core.devices import AndroidDevice, RecordingDevice +from mobilerun_core import AsyncMobilerun + +from mobilerun.core.runs import ActionRecording from mobilerun.macro import build_macro async def record() -> Path: - async with RecordingDevice(AndroidDevice("emulator-5554")) as recorded: - await recorded.press_button("home") - recorded.finish("succeeded") - assert recorded.run_dir is not None + async with AsyncMobilerun() as run: + phone = await run.connect("emulator-5554", backend="local-android-adb") + async with ActionRecording(phone) as recorded: + await phone.key("home") + recorded.finish("succeeded") return build_macro(recorded.run_dir / "steps.jsonl", "go-home") ``` @@ -190,50 +193,50 @@ Reset the emulator to its initial screen, then replay the path returned by `reco ```python from pathlib import Path -from mobilerun.core.devices import AndroidDevice +from mobilerun_core import AsyncMobilerun + from mobilerun.macro import MacroPlayer, load_macro async def replay(path: Path): - async with AndroidDevice("emulator-5554") as device: - await MacroPlayer(device).replay_macro(load_macro(path)) + async with AsyncMobilerun() as run: + phone = await run.connect("emulator-5554", backend="local-android-adb") + await MacroPlayer(phone).replay_macro(load_macro(path)) ``` +Use `ScreenRecording` if you also need before/after screenshots and UI state. Screenshots are not redacted. Recordings and macros use schema 2; re-record older macros. + ### Credentials and vault -Vault access uses your cloud account. Bind a provider to a device rather than putting secrets in a prompt. Cloud tasks require `CloudCredentials`; local credential providers are not sent to cloud tasks. +Vault access uses your cloud account. A provider only needs `device=` when it types on a phone. For hosted tasks that need credentials, pass `CloudCredentials` in the operator's `extensions=` list; the task gets vault references, not secret values. ```python from mobilerun.core.credentials import CloudCredentials -from mobilerun.core.devices import AndroidDevice async def credentials(): - async with AndroidDevice("emulator-5554") as device: - vault = CloudCredentials() - await vault.bind(device) - try: - print(await vault.list("com.example.demo")) - finally: - await vault.close() + vault = CloudCredentials(billing="no_commerce") + try: + return await vault.list("com.example.demo") + finally: + await vault.close() ``` See [vault_demo.py](tests/demos/vault_demo.py) for save, use and cleanup. -For a local agent, use a private YAML or JSON file with `FileCredentials` instead. The file must not be readable by other users (`chmod 600 secrets.yaml`). LLM use can incur provider charges. +For local typing, use a private YAML or JSON file with `FileCredentials`. The file must not be readable by other users (`chmod 600 secrets.yaml`). Supply a credential name from that file and focus an editable field on the unlocked device first. This example uses no LLM tokens. ```python -# Requires the unpublished mobilerun-agents add-on. -from mobilerun_agents import AgentOperator +from mobilerun_core import AsyncMobilerun + from mobilerun.core.credentials import FileCredentials -from mobilerun.core.devices import AndroidDevice -async def local_credentials(): - async with AndroidDevice("emulator-5554", operator=AgentOperator()) as device: - provider = FileCredentials("secrets.yaml") - await provider.bind(device) +async def local_credentials(credential_name: str): + async with AsyncMobilerun() as run: + phone = await run.connect("emulator-5554", backend="local-android-adb") + provider = FileCredentials("secrets.yaml", device=phone) try: - print(await device.do("Open Settings")) + await provider.type_secret(credential_name) finally: - await provider.unbind() + await provider.close() ``` See [credentials](mobilerun/core/credentials/README.md) for file format and provider details. Keep secrets out of prompts and version control. @@ -262,26 +265,33 @@ Save the one-time signing secret securely. Registration creates an endpoint but ### Structured output -**Cost:** the phone, proxy and cloud task can incur charges. +**Cost:** a hosted task and use of the cloud phone can incur charges. Set `MOBILERUN_API_KEY` and pass the ID of an existing ready cloud phone. ```python from pydantic import BaseModel -from mobilerun.core.devices import CloudDevice +from mobilerun_core import AsyncMobilerun + +from mobilerun.clients.cloud.client import cloud_client +from mobilerun.core.operator.cloud import CloudTaskOperator class AndroidVersion(BaseModel): version: str -async def structured(): - async with CloudDevice(name="version-demo", billing="paid", plan="minute") as phone: - result = await phone.do("Find the Android version", output=AndroidVersion) - print(result.output) +async def structured(device_id: str): + async with AsyncMobilerun() as run, cloud_client(billing="paid") as client: + phone = await run.connect(device_id, backend="cloud") + operator = CloudTaskOperator(client=client, billing="paid") + result = await operator.do(phone, "Find the Android version", output=AndroidVersion) + return result.output ``` From a source checkout, run `python -m tests.demos.task_demo` for the complete cloud lifecycle, task and structured-output example. Demos are excluded from the built wheel; see the [demo table](tests/demos/README.md) for prerequisites and costs. ## CLI overview -Run `mobilerun --help` or `mobilerun COMMAND --help`. Command groups include `device`, `agent`, `macro`, `account`, `credentials`, `number`, `mailbox`, `proxy`, `webhook`, `workspace`, `skills`, `mcp`, and `doctor`. `mobilerun device connect ` saves a default device; `mobilerun device disconnect` clears it. Old command aliases are unavailable; use `mobilerun account login`, `mobilerun device list`, and `mobilerun agent run`. See the [CLI guide](mobilerun/cli/README.md). +Run `mobilerun --help` or `mobilerun COMMAND --help`. The base CLI includes `device`, `macro`, `account`, `credentials`, `number`, `mailbox`, `proxy`, `task`, `webhook`, `workspace`, `skills`, `mcp`, and `doctor`. `mobilerun device connect ` saves a default device; `mobilerun device disconnect` clears it. The `agent` group requires the separate add-on. See the [CLI guide](mobilerun/cli/README.md). + +Cloud reboot, termination, metered resume, app uninstall, Android Portal setup or repair, and ADB network connect or disconnect require confirmation or `--yes`. Saving an already connected device as the default does not require confirmation. A first `mobilerun proxy bind` does not prompt for approval; replacing an active proxy requires `--force` or interactive confirmation. ## Skills for coding agents diff --git a/assets/examples/devices/android_basics.py b/assets/examples/devices/android_basics.py index cbc6396e6..cfeaa38c7 100644 --- a/assets/examples/devices/android_basics.py +++ b/assets/examples/devices/android_basics.py @@ -4,9 +4,10 @@ import asyncio from pathlib import Path -from mobilerun.config.settings import get_settings from mobilerun.core.devices import AndroidDevice +from mobilerun.config.settings import get_settings + async def run(serial: str | None = None, device: AndroidDevice | None = None) -> None: device = device or AndroidDevice(serial=serial or get_settings().android_serial) diff --git a/assets/examples/devices/custom_device.py b/assets/examples/devices/custom_device.py index 99f8bc518..45063b09a 100644 --- a/assets/examples/devices/custom_device.py +++ b/assets/examples/devices/custom_device.py @@ -4,9 +4,10 @@ import asyncio from pathlib import Path -from mobilerun.config.settings import get_settings from mobilerun.core.devices import AndroidDevice +from mobilerun.config.settings import get_settings + class MyAndroidDevice(AndroidDevice): async def screenshot_to(self, path: str) -> None: diff --git a/assets/examples/devices/recording_wrapper.py b/assets/examples/devices/recording_wrapper.py index 879a5cb23..35c6d93fd 100644 --- a/assets/examples/devices/recording_wrapper.py +++ b/assets/examples/devices/recording_wrapper.py @@ -3,9 +3,10 @@ import argparse import asyncio -from mobilerun.config.settings import get_settings from mobilerun.core.devices import AndroidDevice, RecordingDevice, StealthDevice +from mobilerun.config.settings import get_settings + async def run(serial: str | None = None, device: AndroidDevice | None = None) -> None: device = device or AndroidDevice(serial=serial or get_settings().android_serial) diff --git a/mobilerun/README.md b/mobilerun/README.md index aaf915787..38f6d735c 100644 --- a/mobilerun/README.md +++ b/mobilerun/README.md @@ -1,185 +1,54 @@ # mobilerun/ -Mobilerun connects device interfaces, execution operators, clients, and state providers. Its shared framework supports deterministic macros, sandbox apps, and coding-agent skills. LLM-backed execution and fallback require the separate `mobilerun-agents` add-on. It is not yet publicly published; there is no public pip or uv install command for it. - -Pause with `await device.wait(seconds)`, not `asyncio.sleep()`: RecordingDevice -records device waits so macro replay keeps the pause. - -See the [demos](../tests/demos/README.md) for source-checkout examples and costs. +The framework adds operators, extensions, prompt-ready screens, recording, macros and a CLI to the async device API in [mobilerun-core](https://github.com/droidrun/mobilerun-core). Use `AsyncMobilerun` to open an `AsyncDevice`. Pass that handle to the framework code that needs it. ## Package map | Folder | Purpose | | --- | --- | -| [addons/](addons/README.md) | Optional add-on discovery. | -| [core/](core/README.md) | Device, state, operator, and account-resource APIs. | -| [models/](models/) | Shared app, billing, credential and result value types; no IO or SDK. | -| [core/devices/](core/devices/README.md) | Device implementations. | -| [core/devices/base.py](core/devices/base.py) | Device protocol and shared mixin. | -| [core/devices/cloud.py](core/devices/cloud.py) | Cloud device, lifecycle, apps and task operator. | -| [core/devices/components/](core/devices/components/) | Driver, recording and stealth facades. | -| [core/phone_number/](core/phone_number/README.md) | Phone number interface and cloud implementation. | -| [core/mailbox/](core/mailbox/README.md) | Mailbox interface and cloud implementation. | -| [core/proxy/](core/proxy/README.md) | Proxy interface, Connect and SOCKS5 implementations. | -| [core/webhooks/](core/webhooks/README.md) | Organization webhook endpoint management. | -| [core/state/](core/state/README.md) | UI state providers and models. | -| [core/operator/](core/operator/README.md) | Operator interface. | -| [clients/](clients/README.md) | Shared service clients. | -| [clients/cloud/](clients/cloud/README.md) | Cloud account access. | -| [clients/portal/](clients/portal/README.md) | Portal client support. | -| [clients/local/](clients/local/README.md) | Functional local adapters and APK inspection. | -| [config/](config/README.md) | Shared configuration. | -| [core/credentials/](core/credentials/README.md) | Device-owned credential providers. | -| [utils/](utils/README.md) | Shared helpers. | -| [errors/](errors/README.md) | Shared errors. | -| [logs/](logs/README.md) | Shared logging. | -| [diagnostics/](diagnostics/README.md) | Diagnostics. | -| [assets/](assets/README.md) | Shared bundled assets. | -| [cli/](cli/README.md) | Root CLI and shared CLI helpers. | -| [cli/webhook/](cli/webhook/README.md) | Register, list, inspect, ping, and delete webhook endpoints. | -| [macro/](macro/README.md) | Recording and guarded replay. | -| [mcp/](mcp/README.md) | MCP configuration and installation. | -| [sandbox/](sandbox/README.md) | Sandbox apps and tasks. | -| [skills/](skills/README.md) | Bundled coding-agent skills. | -| `mobilerun-agents` (separate package) | Optional LLM agents, integrations and agent commands. | - -## Where code goes - -**Could someone delete this folder and still use the rest of Mobilerun?** -If yes, it belongs in an optional feature (`sandbox/`, -`mcp/`, `macro/`, `skills/`); if not, put it in `core/` or a shared package. -For example, `sandbox/` is removable; `core/webhooks/` is not, because the -webhook CLI and sandbox both use it. In `mobilerun/`, `core/` holds domain -objects: devices, operators, state, credentials, proxies, numbers, mailboxes, -webhooks, workspace, and extensions. `models/`, `clients/`, `errors/`, `utils/`, -`config/`, and `logs/` supply shared building blocks. Phone behavior lives in -`core/devices/` and its components; account-wide resources live in their own -core folders or on `Workspace`. See the [topic map](core/README.md#topic-map). - -| New code | Location | -| --- | --- | -| Device error | `errors/device.py` | -| Macro error | `macro/errors.py` | -| Proxy CLI command | `cli/proxy/` | -| Webhook CLI command | `cli/webhook/` | -| Skills CLI | `skills/cli/` | +| [core/](core/README.md) | Framework interfaces and account resources. | +| [core/operator/](core/operator/) | Operator interface and hosted task operator. | +| [core/extensions/](core/extensions/) | Standalone extensions and typed tool declarations. | +| [core/screen/](core/screen/) | Prompt view over native observations. | +| [core/runs/](core/runs/) | Hook-based recording and run artifacts. | +| [clients/](clients/) | Account service adapters; device access uses `mobilerun_core`. | +| [models/](models/) · [config/](config/) · [utils/](utils/) · [errors/](errors/) · [logs/](logs/) | Shared values, settings, helpers, errors and logging. | +| [diagnostics/](diagnostics/) · [assets/](assets/) | Doctor output and bundled assets. | +| [cli/](cli/) | Framework commands and shared CLI helpers. | +| [macro/](macro/) | Build and replay schema-2 macros. | +| [mcp/](mcp/) · [sandbox/](sandbox/) · [skills/](skills/) | MCP setup, sandbox apps and coding-agent skills. | +| [addons/](addons/) | Discover installed add-ons. | +| `__main__.py`, `version.py` | Module CLI entry point and package/plugin version. | +| `mobilerun-agents` (separate package) | Local LLM operators, integrations and agent commands. | ## Dependency direction -Name new cloud phones explicitly: `CloudDevice(name="signup-check", billing="paid")`. -Creation options are explicit keywords, not arbitrary SDK passthrough; they are -rejected with an existing device ID. Use `await phone.rename("new-name")` there. -`phone.name` is a read-only cache refreshed by `await phone.info()` or rename. -See [cloud creation options](core/devices/cloud.py). - -**Design rule:** Optional resources that work independently bind themselves to a -device. Behavior that only makes sense on a phone lives on the phone. - -| Rule | What belongs here | Where each thing goes | -| --- | --- | --- | -| On the phone | Proxy selection/switching; operator selection/execution | `core/devices/cloud.py`, `core/proxy/`, `core/operator/` | -| Binds itself | Phone numbers, mailboxes, credential providers | `core/phone_number/`, `core/mailbox/`, `core/credentials/` | -| Organization-scoped | Webhook endpoints; no device binding | `core/webhooks/` | -| Shared values | App, Billing/Plan, Credential, task/expectation results | `models/`; no SDK, IO or lifecycle | - -Use `await number.bind(phone)`, `await mailbox.bind(device)` and -`await provider.bind(device)`. Numbers/mailboxes and providers unbind with -`await x.unbind()`. Device resource state is read-only, -including the ordered `device.credentials` tuple (first-bound wins). Devices do -not accept `credentials=`. Mailbox binding is local association only and works on -local typing devices too. Number binding requires a telephony-capable cloud phone. - -Cloud phones always require a proxy; `CloudDevice()` defaults to `CloudRotatingProxy`. -Pass `CloudRotatingProxy`, `CloudFixedProxy` or `CloudSocks5Proxy` explicitly to choose one. -Proxies are extensions: bind one with `await proxy.bind(phone)`. Replace an active -proxy with `await replacement.bind(phone, force=True)`. Operators support constructor and -per-call selection; they are separate from proxy binding. +Arrows point from an importer to its dependencies. ```text -Each arrow points from the importer to a dependency it may import. - -sandbox/, mcp/, macro/, skills/ -> core/, clients/, shared packages -core/ -> clients/, shared packages -cli/ -> core/, clients/, shared packages - -Shared packages: models/, config/, utils/, errors/, logs/ -The root CLI loads feature commands only via mobilerun.cli entry points. -No feature imports another feature or the mobilerun-agents add-on. +mobilerun-agents → framework interfaces +framework features and CLI → core/, clients/, shared packages +framework core/ → clients/, shared packages +framework device access → mobilerun_core public async API +framework account services → mobilerun SDK via cloud adapters ``` -Shared packages do not import features. Clients do not import core or the root package. Features keep their own CLI, errors, models, settings, and utilities. They may use `cli/base/` and `cli/devices/base/`, but not other shared CLI modules. - -## Operators - -A device provides actions and state; an operator decides how to execute an instruction. `CloudDevice` defaults to `CloudTaskOperator`. Pass `MacroOperator` for strict replay. The `mobilerun-agents` add-on provides `AgentOperator` for LLM execution and `AgentMacroOperator` for agent fallback on divergence. Pass an operator to the device or override it per `device.do()` call. - -## Quickstart - -Start or reuse a local AVD with `await AndroidDevice(avd="AVD_NAME")`; see -[device lifecycle](core/devices/README.md#platforms-and-wrappers). +Use only the public `mobilerun_core` API for device access. The [architecture tests](../tests/unit/architecture/test_layers.py) reject private core imports, direct ADB imports and imports from the retired framework device and state packages. Clients do not import framework core or the root package. Shared packages do not import features. Features do not import one another or the agent add-on. The root CLI loads feature commands via `mobilerun.cli` entry points; features can use `cli/base/` and `cli/devices/base/`. -This example requires the unpublished `mobilerun-agents` add-on, an Android device and agent credentials. Running it may consume LLM tokens. For an example using only the base package, see the [device quickstart](../README.md#60-second-quickstart). +## Quick example -```python -import asyncio -from mobilerun.core.devices import AndroidDevice -from mobilerun_agents import AgentOperator # provided by mobilerun-agents - -async def main(): - async with AndroidDevice("emulator-5554", operator=AgentOperator()) as device: - result = await device.do("Open Settings") - print(result) -asyncio.run(main()) -``` - -### Cloud quickstart - -With cloud API credentials configured (this creates a billable phone): +Project the native state of a connected device into a prompt view. No LLM is called. ```python -from pydantic import BaseModel -from mobilerun import CloudDevice -from mobilerun.models import Billing, Plan - -class Screen(BaseModel): - description: str - -async def cloud_example(): - cloud = await CloudDevice(name="Quickstart", billing=Billing.PAID, plan=Plan.MINUTE) - try: - result = await cloud.do("Describe the current screen", output=Screen) - return result.output - finally: - await cloud.close() -``` +from mobilerun_core import AsyncMobilerun -Secrets cannot be sent through the public cloud. Create them in the Mobilerun -vault with `CloudCredentials().save(...)`, then attach `CloudCredentials()` to -the cloud device (`await CloudCredentials().bind(cloud)`). Cloud tasks use -vault references, not secret values; local credential providers are rejected -before API calls. A local `AgentOperator` driving a cloud phone remains allowed -to use local credentials. +from mobilerun.core.screen import ScreenProvider -### Cloud webhooks - -With cloud API credentials configured, list your organization's webhook endpoints without creating resources: - -```python -from mobilerun.core.webhooks import CloudWebhooks - -async def webhook_example(): - for endpoint in await CloudWebhooks(billing="no_commerce").list(): - print(endpoint.id, endpoint.state) +async def show_screen(serial: str): + async with AsyncMobilerun() as run: + phone = await run.connect(serial, backend="local-android-adb") + snapshot = await ScreenProvider(phone).observe() + print(snapshot.formatted_text) ``` -Use a registered endpoint ID to [deliver sandbox function results](sandbox/README.md#send-a-function-result-to-a-webhook). Deploying and running that flow can incur charges. - -## CLI device selection - -For a local example that records `steps.jsonl`, builds a versioned macro, and -loads it for replay, see [Record and replay a macro](../README.md#record-and-replay-a-macro). - -DEVICE is optional: run `mobilerun device connect ` to save a default, or choose from discovered devices. An explicit DEVICE takes precedence, followed by the saved `device.serial` and discovery. Run `mobilerun device disconnect` to clear the default. Python device APIs remain explicit. - -There is no legacy import compatibility layer. With the add-on installed, -import agent code from `mobilerun_agents` directly. +Use `await device.wait(seconds)` for pauses that should be recorded and replayed. Use the [root examples](../README.md#easy-examples) for cloud creation, recording and macros, or the [topic map](core/README.md#topic-map) to find a framework API. diff --git a/mobilerun/__init__.py b/mobilerun/__init__.py index 7befc6db3..27018fa80 100644 --- a/mobilerun/__init__.py +++ b/mobilerun/__init__.py @@ -4,12 +4,6 @@ from typing import TYPE_CHECKING, Any if TYPE_CHECKING: - from mobilerun.core import ( - AndroidDevice as AndroidDevice, - ) - from mobilerun.core import ( - CloudDevice as CloudDevice, - ) from mobilerun.core import ( CloudFixedProxy as CloudFixedProxy, ) @@ -19,27 +13,6 @@ from mobilerun.core import ( CloudSocks5Proxy as CloudSocks5Proxy, ) - from mobilerun.core import ( - Device as Device, - ) - from mobilerun.core import ( - DevicePool as DevicePool, - ) - from mobilerun.core import ( - IOSDevice as IOSDevice, - ) - from mobilerun.core import ( - LocalProxy as LocalProxy, - ) - from mobilerun.core import ( - RecordingDevice as RecordingDevice, - ) - from mobilerun.core import ( - RemoteDevice as RemoteDevice, - ) - from mobilerun.core import ( - StealthDevice as StealthDevice, - ) from mobilerun.core import ( Workspace as Workspace, ) @@ -53,12 +26,7 @@ from mobilerun.config.user_config import ( MobileConfig as MobileConfig, ) -from mobilerun.config.user_config import ( - TelemetryConfig as TelemetryConfig, -) -from mobilerun.config.user_config import ( - TracingConfig as TracingConfig, -) +from mobilerun.version import PLUGIN_API_VERSION as PLUGIN_API_VERSION from mobilerun.version import __version__ as __version__ _EAGER_EXPORTS = ( @@ -66,24 +34,14 @@ "DeviceConfig", "LoggingConfig", "MobileConfig", - "TelemetryConfig", - "TracingConfig", + "PLUGIN_API_VERSION", ) _CORE_EXPORTS = ( - "Device", - "AndroidDevice", - "CloudDevice", - "IOSDevice", - "RemoteDevice", - "DevicePool", - "RecordingDevice", - "StealthDevice", "Workspace", "CloudFixedProxy", "CloudRotatingProxy", "CloudSocks5Proxy", - "LocalProxy", ) __all__ = [*_EAGER_EXPORTS, *_CORE_EXPORTS] diff --git a/mobilerun/addons/README.md b/mobilerun/addons/README.md index 46773ad4e..9a245b496 100644 --- a/mobilerun/addons/README.md +++ b/mobilerun/addons/README.md @@ -3,10 +3,16 @@ The base package discovers add-ons using installed distribution entry points. Discovery reads metadata without importing the add-on. First-party macro, mcp, and skills commands use the same mechanism in the `mobilerun` distribution. -Sandbox currently has no CLI group. +Sandbox registers its CLI group through the same entry-point mechanism. ## Write a plugin +Declare `mobilerun>=0.9.0` as a dependency. The base exposes the integer +`PLUGIN_API_VERSION` (currently `1`) in `mobilerun.version` and as +`mobilerun.PLUGIN_API_VERSION`. It increases on every breaking change to what an +add-on may import or implement. Add-ons can assert the supported integer at +import time. + Declare entry points in your add-on's `pyproject.toml`: ```toml @@ -14,21 +20,30 @@ Declare entry points in your add-on's `pyproject.toml`: example = "example_plugin.cli:command" [project.entry-points."mobilerun.operators"] +inventory = "example_plugin.operators:InventoryOperator" + +[project.entry-points."mobilerun.macro_handoff"] agent_macro = "example_plugin.replay:handoff" ``` - `mobilerun.cli`: each value resolves to a `click.Command` or `click.Group`. Its name appears in root help. The implementation is imported when invoked, not when help is listed. -- `mobilerun.operators`: `agent_macro` resolves to a **plain callable**, not a +- `mobilerun.operators`: each value resolves to a concrete `Operator` subclass + constructible with `extensions=` alone. Accept and forward that argument to + `Operator.__init__` (or inherit its constructor). Register a class, not a + factory or an instance. See [operator plugins](../core/operator/README.md#installed-operators). +- `mobilerun.macro_handoff`: `agent_macro` resolves to a **plain callable**, not a Click-decorated callback. The base invokes it with keyword arguments - `provider: str | None`, `model: str | None`, `path: str` (the pinned JSONL version), a resolved - `target: DeviceTarget`, `delay: float`, `start_from: int`, + `provider: str | None`, `model: str | None`, `path: str` (the pinned JSONL + version), `target: str | None` (the requested device), `device_kind: str | None`, + `tcp: bool | None`, `base_url: str | None`, `delay: float`, `start_from: int`, `max_steps: int | None`, `debug: bool`, `dry_run: bool`, - `state_timeout: float`, `state_threshold: float`, and - `config_path: str | None`. It owns configuration and replay. Do not reparse - device flags: `target` is already resolved. The callable loads only when a - replay requests agent fallback. + `state_timeout: float`, `state_threshold: float`, + `config_path: str | None`, and `yes: bool` (explicit paid-SMS consent). It + owns configuration and replay. Forward the parsed options to `run_replay`; + it resolves the target and opens the core connection. Replay only loads the + callable when agent fallback is requested. Built-in command and alias names win over add-on CLI names. For duplicate plugin names, a single entry from the `mobilerun` distribution wins over third-party entries. Other ambiguous duplicates are skipped with a @@ -50,15 +65,21 @@ def test_handoff(monkeypatch): calls = [] monkeypatch.setattr(replay, "run_replay", lambda *a, **kw: calls.append((a, kw))) # Also replace the configuration loader with a fake. - ep = next(ep for ep in entry_points(group="mobilerun.operators") + ep = next(ep for ep in entry_points(group="mobilerun.macro_handoff") if ep.name == "agent_macro") ep.load()(provider=None, model=None, path="/macros/routine/v1.jsonl", target=object(), delay=0.0, start_from=1, max_steps=None, debug=False, dry_run=False, state_timeout=1.0, state_threshold=0.5, - config_path=None) + config_path=None, yes=False) assert calls[0][1]["path"] == "/macros/routine/v1.jsonl" ``` The `mobilerun/cli/plugins/` package contains the top-level CLI for this core-side concern; `mobilerun/addons/` owns discovery and shared contracts. + +| File | Purpose | +| --- | --- | +| `plugins.py` | Discover and load installed entry points. | +| `settings.py` | Entry-point groups, built-in metadata and plugin defaults. | + See the [package map](../README.md) and [CLI](../cli/README.md). diff --git a/mobilerun/cli/README.md b/mobilerun/cli/README.md index 1ee6789f2..e2d8ef32c 100644 --- a/mobilerun/cli/README.md +++ b/mobilerun/cli/README.md @@ -21,7 +21,6 @@ mobilerun ├── credentials: delete, list, path, save, update ├── device │ ├── list, connect, disconnect, ping, setup -│ ├── action: call, extensions, list │ ├── app: install, list, open, start, stop, uninstall │ ├── cloud: reboot, resume, status, stop, terminate │ ├── file: list, pull, push, rm @@ -47,7 +46,7 @@ Overwriting an existing credential requires an interactive confirmation. Even in `paid` mode, the CLI asks before buying a proxy (`proxy buy`), creating a number or mailbox that may rent (`number create`, `mailbox create`), sending SMS -(`number send`, `device action call sms.send`), or resuming a metered device +(`number send`), or resuming a metered device (`device cloud resume`). Explicit `--plan included` skips paid confirmation because it cannot rent. If billing must escalate to `paid`, the retry prompt is the only one. The prompt defaults to No, which cancels with exit status 1. diff --git a/mobilerun/cli/app.py b/mobilerun/cli/app.py index a558727da..978cd0b73 100644 --- a/mobilerun/cli/app.py +++ b/mobilerun/cli/app.py @@ -11,14 +11,12 @@ from mobilerun import __version__ from mobilerun.addons import plugins -from mobilerun.addons.settings import ( - CLI_ENTRY_POINT_GROUP, - CLI_PLUGIN_HELP, - OPERATOR_ENTRY_POINT_GROUP, -) -from mobilerun.cli.base.logging import cli_handler +from mobilerun.addons.settings import CLI_ENTRY_POINT_GROUP, CLI_PLUGIN_HELP from mobilerun.cli.base.menu import MenuGroup from mobilerun.cli.base.prompts import SelectChoice +from mobilerun.logs.handlers import CLILogHandler, configure_logging + +_log_handler: CLILogHandler | None = None _COMMANDS = { "credentials": ( @@ -38,6 +36,7 @@ ), "proxy": ("mobilerun.cli.proxy.group", "proxy", "Manage Connect proxies."), "webhook": ("mobilerun.cli.webhook.group", "webhook", "Manage webhook endpoints."), + "task": ("mobilerun.cli.task.group", "task", "Check or stop cloud tasks."), "number": ( "mobilerun.cli.phone_number.group", "number", @@ -63,8 +62,31 @@ _REMOVABLE_FEATURES = frozenset({"sandbox", "mcp", "macro", "skills"}) +# Approved compatibility exception: diagnose the old command without forwarding it. +@click.command( + "run", + hidden=True, + add_help_option=False, + context_settings={"ignore_unknown_options": True, "allow_extra_args": True}, +) +def _retired_run() -> None: + raise click.UsageError( + "`mobilerun run` moved to `mobilerun agent run`. " + "Install the mobilerun-agents add-on (see README: Agent add-on)." + ) + + +MACRO_HANDOFF_ENTRY_POINT_GROUP = "mobilerun.macro_handoff" + + def _run_agent_macro(provider: str | None, model: str | None, **options: Any) -> None: - handoff = plugins.load(OPERATOR_ENTRY_POINT_GROUP, "agent_macro") + try: + handoff = plugins.load(MACRO_HANDOFF_ENTRY_POINT_GROUP, "agent_macro") + except plugins.MissingPlugin as error: + raise plugins.MissingPlugin( + f"{error.format_message()} " + "Install the mobilerun-agents add-on (see README: Agent add-on)." + ) from None if not callable(handoff): raise click.ClickException( "Invalid agent macro plugin; reinstall the mobilerun-agents add-on." @@ -191,6 +213,8 @@ def get_command(self, ctx: click.Context, cmd_name: str) -> click.Command | None target = _COMMANDS.get(cmd_name) if target is None: if cmd_name not in self._plugin_commands(ctx): + if cmd_name == "run": + return _retired_run if cmd_name == "agent": return cast( click.Command, plugins.load(CLI_ENTRY_POINT_GROUP, cmd_name) @@ -236,10 +260,10 @@ def _print_version(ctx: click.Context, param: click.Parameter, value: bool) -> N ) def cli(debug: bool) -> None: """Mobilerun - Control your mobile devices through LLM agents.""" + global _log_handler + if _log_handler is None: + _log_handler = CLILogHandler() logger = logging.getLogger("mobilerun") - handler = cli_handler() - from mobilerun.logs.handlers import configure_logging - - configure_logging(debug, handler) + configure_logging(debug, _log_handler) logger.setLevel(logging.DEBUG if debug else logging.INFO) logger.propagate = False diff --git a/mobilerun/cli/auth/README.md b/mobilerun/cli/auth/README.md index 1ae86404e..8e0b963ec 100644 --- a/mobilerun/cli/auth/README.md +++ b/mobilerun/cli/auth/README.md @@ -8,4 +8,14 @@ CLI auth commands and helpers. mobilerun account status ``` +`mobilerun account login --api-key` validates the supplied key through the +bound cloud adapter before saving it locally. + +| File | Purpose | +| --- | --- | +| `group.py` | Register the account commands. | +| `login.py` | Authenticate and save a login. | +| `logout.py` | Remove the saved login. | +| `status.py` | Show the active login source. | + See [CLI overview](../README.md). diff --git a/mobilerun/cli/auth/login.py b/mobilerun/cli/auth/login.py index 35bffe455..ace9c3401 100644 --- a/mobilerun/cli/auth/login.py +++ b/mobilerun/cli/auth/login.py @@ -12,11 +12,11 @@ from mobilerun.cli.base import render from mobilerun.cli.base.billing import billing_option from mobilerun.cli.base.run import coro -from mobilerun.clients.cloud import api_keys as cloud -from mobilerun.clients.cloud import device_flow as deviceauth -from mobilerun.clients.local import login_store as credentials +from mobilerun.clients.cloud.api_keys import ApiKeys +from mobilerun.clients.cloud.device_flow import DeviceAuthorization +from mobilerun.clients.local.login_store import LoginStore from mobilerun.config.settings import get_settings -from mobilerun.errors import CloudAPIError, InvalidAPIKeyError +from mobilerun.errors import CloudAPIError, DeviceAuthError, InvalidAPIKeyError from mobilerun.errors.base import MobilerunError from mobilerun.models.billing import Billing @@ -59,10 +59,10 @@ async def login( "--api-key cannot be combined with --client-id or --auth-url" ) try: - await cloud.validate_api_key(api_key, billing=Billing(billing)) + await ApiKeys(api_key=api_key, billing=Billing(billing)).validate() except (CloudAPIError, InvalidAPIKeyError) as exc: raise click.ClickException(str(exc)) from exc - path = credentials.save_credentials( + path = LoginStore.from_settings().save( { "api_key": api_key, "auth_type": "api_key", @@ -74,11 +74,10 @@ async def login( return auth_url = auth_url or get_settings().MOBILERUN_AUTH_URL + auth = DeviceAuthorization(auth_url, billing=Billing(billing)) try: - code = await deviceauth.request_code( - auth_url, client_id, billing=Billing(billing) - ) + code = await auth.request_code(client_id) except MobilerunError as e: raise click.ClickException(f"request device code: {e}") from e @@ -97,21 +96,21 @@ async def login( ) try: - token = await deviceauth.poll_token( - auth_url, client_id, code, billing=Billing(billing) - ) - except (deviceauth.DeviceAuthError, CloudAPIError) as e: + token = await auth.poll_token(client_id, code) + except (DeviceAuthError, CloudAPIError) as e: raise click.ClickException(f"authorization failed: {e}") from e except KeyboardInterrupt: raise click.ClickException("login cancelled") from None - path = credentials.save_token(token, auth_url) + path = LoginStore.from_settings().save( + {"access_token": token, "auth_url": auth_url} + ) email = None try: - info = await deviceauth.fetch_session(auth_url, token, billing=Billing(billing)) + info = await auth.fetch_session(token) if info: email = info.get("user", {}).get("email") - except (deviceauth.DeviceAuthError, CloudAPIError, ValueError): + except (DeviceAuthError, CloudAPIError, ValueError): logger.warning("Could not retrieve the account name for this session.") who = f" as {email}" if email else "" render.success(f"Logged in{who}.") diff --git a/mobilerun/cli/auth/logout.py b/mobilerun/cli/auth/logout.py index 9317c2d5b..4799e4cdc 100644 --- a/mobilerun/cli/auth/logout.py +++ b/mobilerun/cli/auth/logout.py @@ -3,14 +3,14 @@ import click from mobilerun.cli.base import render -from mobilerun.clients.local import login_store as credentials +from mobilerun.clients.local.login_store import LoginStore from mobilerun.config.env import get_secrets, secret_value @click.command() def logout() -> None: """Remove the saved Mobilerun cloud login.""" - if credentials.clear_credentials(): + if LoginStore.from_settings().clear(): render.success("Logged out.") else: render.warn("Not logged in.") diff --git a/mobilerun/cli/auth/status.py b/mobilerun/cli/auth/status.py index b7b00305b..c783f4e9e 100644 --- a/mobilerun/cli/auth/status.py +++ b/mobilerun/cli/auth/status.py @@ -8,8 +8,8 @@ from mobilerun.cli.base import render from mobilerun.cli.base.billing import billing_option from mobilerun.cli.base.run import coro -from mobilerun.clients.cloud import device_flow as deviceauth -from mobilerun.clients.local import login_store as credentials +from mobilerun.clients.cloud.device_flow import DeviceAuthorization +from mobilerun.clients.local.login_store import LoginStore from mobilerun.config.env import get_secrets, secret_value from mobilerun.config.settings import get_settings from mobilerun.errors.base import MobilerunError @@ -42,7 +42,7 @@ async def whoami(billing: str, as_json: bool) -> None: ] ) return - creds = credentials.load_credentials() + creds = LoginStore.from_settings().load() api_key = (creds or {}).get("api_key") if api_key: if as_json: @@ -55,7 +55,9 @@ async def whoami(billing: str, as_json: bool) -> None: if not token: raise click.ClickException("Not logged in (run `mobilerun account login`).") try: - info = await deviceauth.fetch_session(auth_url, token, billing=Billing(billing)) + info = await DeviceAuthorization( + auth_url, billing=Billing(billing) + ).fetch_session(token) except MobilerunError as e: raise click.ClickException(f"session check failed: {e}") from e if info is None: diff --git a/mobilerun/cli/base/README.md b/mobilerun/cli/base/README.md index da359dadf..ef73cba1d 100644 --- a/mobilerun/cli/base/README.md +++ b/mobilerun/cli/base/README.md @@ -6,4 +6,12 @@ CLI base commands and helpers. mobilerun completion --help ``` +| Files | Purpose | +| --- | --- | +| `menu.py`, `prompts.py`, `choices.py` | Menus and interactive selection. | +| `billing.py`, `checkout.py`, `safety.py` | Billing, checkout and confirmation. | +| `errors.py`, `handling.py`, `render.py` | Safe errors, exit behavior and output. | +| `cleanup.py`, `run.py` | Cleanup reporting and async entry points. | +| `completion.py` | Shell completion. | + See [CLI overview](../README.md). diff --git a/mobilerun/cli/base/billing.py b/mobilerun/cli/base/billing.py index 17dc2df80..942c160a1 100644 --- a/mobilerun/cli/base/billing.py +++ b/mobilerun/cli/base/billing.py @@ -3,18 +3,17 @@ import sys from collections.abc import Awaitable, Callable from contextlib import redirect_stdout -from typing import Any, TypeVar +from typing import Any, TypeVar, overload import click -from mobilerun.clients.cloud.billing import ( - billing_prompt_is_interactive, - with_billing_retry, -) +from mobilerun.clients.cloud.billing_policy import BillingPolicy from mobilerun.config.settings import get_settings from mobilerun.errors.base import MobilerunError from mobilerun.errors.cloud import BillingRequired from mobilerun.models.billing import Billing +from mobilerun.utils.billing.retry import with_billing_retry +from mobilerun.utils.terminal import can_prompt F = TypeVar("F", bound=Callable[..., Any]) T = TypeVar("T") @@ -50,7 +49,7 @@ async def prompt(error: BillingRequired) -> bool: def require_consent_possible(*, yes: bool) -> None: """Refuse early when consent was not given and no terminal can ask for it.""" - if not yes and not billing_prompt_is_interactive(): + if not yes and not can_prompt(sys.stderr): raise BillingConsentError( "Refusing to proceed without confirmation; pass --yes." ) @@ -72,17 +71,40 @@ async def _confirm(message: str) -> bool: return True -def billing_option(function: F) -> F: - return click.option( +@overload +def billing_option(function: F) -> F: ... + + +@overload +def billing_option(*, minimum: Billing, operation: str) -> Callable[[F], F]: ... + + +def billing_option( + function: F | None = None, + *, + minimum: Billing | None = None, + operation: str = "Cloud request", +) -> F | Callable[[F], F]: + def preflight(ctx: click.Context, param: click.Parameter, value: str) -> Billing: + if ctx.resilient_parsing or minimum is None: + return Billing(value) + try: + return BillingPolicy(value).require(minimum, operation) + except BillingRequired as exc: + raise click.ClickException(str(exc)) from None + + decorate = click.option( "--billing", type=click.Choice([mode.value for mode in Billing]), default=lambda: get_settings().MOBILERUN_BILLING.value, show_default="MOBILERUN_BILLING", + callback=preflight if minimum is not None else None, help=( "Billing mode: no_commerce blocks purchases; included allows included resources; " "paid allows paid resources. Default: MOBILERUN_BILLING (paid)." ), - )(function) + ) + return decorate if function is None else decorate(function) def creation_warning(billing: str) -> str: diff --git a/mobilerun/cli/base/choices.py b/mobilerun/cli/base/choices.py index 5eddc96df..eeeb3b9be 100644 --- a/mobilerun/cli/base/choices.py +++ b/mobilerun/cli/base/choices.py @@ -3,41 +3,43 @@ import asyncio import click -from async_adbutils import adb +from mobilerun_core import AsyncMobilerun from mobilerun.cli.base.prompts import SelectChoice -from mobilerun.clients.cloud.devices import list_devices -from mobilerun.clients.cloud.mailboxes import list_mailboxes -from mobilerun.clients.cloud.numbers import list_numbers -from mobilerun.clients.cloud.proxies import list_proxies +from mobilerun.clients.cloud.mailboxes import Mailboxes +from mobilerun.clients.cloud.numbers import Numbers +from mobilerun.clients.cloud.proxies import Proxies from mobilerun.models.billing import Billing -def connected_devices(ctx: click.Context) -> list[SelectChoice]: - return [SelectChoice(item.serial, item.serial) for item in asyncio.run(adb.list())] +def cloud_devices(ctx: click.Context) -> list[SelectChoice]: + from mobilerun.cli.devices.base.selection import open_client + async def fetch() -> list[SelectChoice]: + async with open_client(base_url=ctx.params.get("base_url"), cloud=True) as run: + return await cloud_device_choices(run) -def cloud_devices(ctx: click.Context) -> list[SelectChoice]: - items = asyncio.run( - list_devices(billing=Billing.NO_COMMERCE, base_url=ctx.params.get("base_url")) - ) - items.sort(key=lambda item: str(item.state).lower() not in {"running", "ready"}) + return asyncio.run(fetch()) + + +async def cloud_device_choices(run: AsyncMobilerun) -> list[SelectChoice]: + """Read and order cloud phone choices using a caller-owned core client.""" + items = await run.list_cloud_devices() return [ SelectChoice( - str(item.id), - str(item.name or item.id), - " · ".join( - str(value) - for value in (item.state, getattr(item, "country", None)) - if value - ), + item.device_id, + item.name or item.device_id, + " · ".join(value for value in (item.state, item.country) if value), + ) + for item in sorted( + items, + key=lambda item: (item.state or "").lower() not in {"running", "ready"}, ) - for item in items ] def mailboxes(ctx: click.Context) -> list[SelectChoice]: - items = asyncio.run(list_mailboxes(billing=Billing.NO_COMMERCE)) + items = asyncio.run(Mailboxes(billing=Billing.NO_COMMERCE).list()) items.sort(key=lambda item: getattr(item, "status", None) != "active") return [ SelectChoice( @@ -48,7 +50,7 @@ def mailboxes(ctx: click.Context) -> list[SelectChoice]: def numbers(ctx: click.Context) -> list[SelectChoice]: - items = asyncio.run(list_numbers(billing=Billing.NO_COMMERCE)) + items = asyncio.run(Numbers(billing=Billing.NO_COMMERCE).list()) items.sort( key=lambda item: getattr(item, "state", None) not in {"active", "cancel_scheduled"} @@ -65,12 +67,11 @@ def numbers(ctx: click.Context) -> list[SelectChoice]: def proxies(ctx: click.Context) -> list[SelectChoice]: async def fetch() -> list[SelectChoice]: + resource = Proxies(billing=Billing.NO_COMMERCE) page = 1 items = [] while True: - response = await list_proxies( - billing=Billing.NO_COMMERCE, page=page, page_size=100 - ) + response = await resource.list(page=page, page_size=100) items.extend(response.items) if not response.pagination.has_next: items.sort(key=lambda item: getattr(item, "status", None) != "active") diff --git a/mobilerun/cli/base/completion.py b/mobilerun/cli/base/completion.py index ccf759c27..95df8f0d3 100644 --- a/mobilerun/cli/base/completion.py +++ b/mobilerun/cli/base/completion.py @@ -16,10 +16,6 @@ _SHELLS = ("zsh", "bash", "fish") -def _stdout_is_tty() -> bool: - return sys.stdout.isatty() - - def _bash_version() -> tuple[int, int]: configured = os.environ.get("SHELL", "") bash = configured if Path(configured).name == "bash" else shutil.which("bash") @@ -77,7 +73,7 @@ def _completion_script(shell: str) -> str: ) def completion(shell: str | None, print_script: bool, yes: bool) -> None: """Install completion for SHELL, or print it when output is redirected.""" - tty = _stdout_is_tty() + tty = sys.stdout.isatty() if shell is None: detected = Path(os.environ.get("SHELL", "")).name if detected in _SHELLS: diff --git a/mobilerun/cli/base/errors.py b/mobilerun/cli/base/errors.py index 0714bb842..6eca31914 100644 --- a/mobilerun/cli/base/errors.py +++ b/mobilerun/cli/base/errors.py @@ -4,11 +4,48 @@ import traceback import click +from mobilerun_core import ( + ActionHookError, + ActionHooksAlreadyInstalledError, + AppArtifactError, + AppOperationError, + CloudLifecycleError, + DeviceDisconnectedError, + EmulatorError, + FileOperationError, + FocusUnknown, + HitlDenied, + NoFocusedInput, + PortalError, + ProxyOperationError, + SecretInputRejected, + StaleElement, + UnsupportedOperation, +) from mobilerun.cli.base import render from mobilerun.errors.base import MobilerunError from mobilerun.errors.cloud import CloudAuthRequired +_CORE_ERRORS = ( + ActionHookError, + ActionHooksAlreadyInstalledError, + AppArtifactError, + AppOperationError, + CloudLifecycleError, + DeviceDisconnectedError, + EmulatorError, + FileOperationError, + FocusUnknown, + HitlDenied, + NoFocusedInput, + PortalError, + ProxyOperationError, + SecretInputRejected, + StaleElement, + UnsupportedOperation, +) + def _line(value: object) -> str: text = re.sub(r"\x1b\[[0-?]*[ -/]*[@-~]", "", str(value)) @@ -26,13 +63,14 @@ def safe_error_message(error: BaseException) -> str: and error.name and error.name.split(".")[0] in {"anthropic", "langfuse", "openinference"} ): - extra = "anthropic" if error.name.split(".")[0] == "anthropic" else "langfuse" - return f"Optional dependency missing. Install with: pip install 'mobilerun-agents[{extra}]'" + return "Optional dependency missing; install the mobilerun-agents add-on." if isinstance(error, TimeoutError) and not isinstance(error, MobilerunError): return _line(error) or "Timed out" if isinstance(error, ExceptionGroup): return _line(error.message) - if isinstance(error, (MobilerunError, click.ClickException)): + if isinstance(error, DeviceDisconnectedError): + return "Device disconnected. Reconnect before retrying." + if isinstance(error, (MobilerunError, click.ClickException, *_CORE_ERRORS)): return _line(error) return "unexpected failure (use --debug for details)" @@ -51,8 +89,8 @@ def render_error(error: BaseException, debug: bool = False) -> None: notes = getattr(cause, "__notes__", []) label = f"{_line(notes[0])}: " if notes else "" message = ( - _line(cause) - if isinstance(cause, MobilerunError) + safe_error_message(cause) + if isinstance(cause, (MobilerunError, *_CORE_ERRORS)) else "Unexpected error (use --debug for details)" ) render.error(f"{label}{message}") diff --git a/mobilerun/cli/base/logging.py b/mobilerun/cli/base/logging.py deleted file mode 100644 index 186f482e3..000000000 --- a/mobilerun/cli/base/logging.py +++ /dev/null @@ -1,17 +0,0 @@ -"""Track the CLI's installed log handler across command groups.""" - -from mobilerun.logs.handlers import CLILogHandler - -_handler: CLILogHandler | None = None - - -def remember_cli_handler(handler: CLILogHandler) -> None: - global _handler - _handler = handler - - -def cli_handler() -> CLILogHandler: - global _handler - if _handler is None: - _handler = CLILogHandler() - return _handler diff --git a/mobilerun/cli/base/safety.py b/mobilerun/cli/base/safety.py index 3ce082c76..44c1a70c4 100644 --- a/mobilerun/cli/base/safety.py +++ b/mobilerun/cli/base/safety.py @@ -6,36 +6,7 @@ import click from mobilerun.cli.base import menu -from mobilerun.cli.base.prompts import confirm_prompt, confirm_prompt_async - - -def _prepare_confirmation( - action: str, billing: str, warning: str, yes: bool, interactive: bool -) -> bool: - if interactive: - chargeable = action in { - "send SMS", - "reboot cloud phone", - } - click.echo( - f"Billing: {billing}. {warning}" - if chargeable and billing == "paid" - else warning - ) - return not yes - elif not yes: - raise click.ClickException( - f"Refusing to {action} without confirmation; pass --yes." - ) - return False - - -def confirm_action(action: str, billing: str, warning: str, *, yes: bool) -> None: - """Require --yes in automation, or an affirmative interactive confirmation.""" - if _prepare_confirmation( - action, billing, warning, yes, menu.is_interactive() - ) and not confirm_prompt("Continue?", default=False): - click.get_current_context().exit(0) +from mobilerun.cli.base.prompts import confirm_prompt_async async def confirm_action_async( @@ -44,7 +15,18 @@ async def confirm_action_async( """Detect the original streams before optionally routing prompts to stderr.""" interactive = menu.is_interactive() with redirect_stdout(sys.stderr) if err else nullcontext(): - if _prepare_confirmation( - action, billing, warning, yes, interactive - ) and not await confirm_prompt_async("Continue?", default=False): + if not interactive: + if not yes: + raise click.ClickException( + f"Refusing to {action} without confirmation; pass --yes." + ) + return + + chargeable = action in {"send SMS", "reboot cloud phone"} + click.echo( + f"Billing: {billing}. {warning}" + if chargeable and billing == "paid" + else warning + ) + if not yes and not await confirm_prompt_async("Continue?", default=False): click.get_current_context().exit(0) diff --git a/mobilerun/cli/credentials/README.md b/mobilerun/cli/credentials/README.md index 584bdd9a7..d0b8535c5 100644 --- a/mobilerun/cli/credentials/README.md +++ b/mobilerun/cli/credentials/README.md @@ -29,6 +29,9 @@ mapping supported field names to string values. Prompts hide input. Save confirm before modifying an existing credential; deletion also requires confirmation unless `--yes` is supplied. Interactive update and delete can select missing identifiers. Protect any secret input files and remove them when no longer needed. +Listing and editing do not require a phone. Interactive save can suggest apps +from the configured local Android phone through a borrowed core connection; +otherwise choose a package manually. `credentials path` shows the resolved local file and whether it exists. Its JSON output also reports whether the path source is `env` or `default`. Relative diff --git a/mobilerun/cli/credentials/group.py b/mobilerun/cli/credentials/group.py index c40745059..c6841e63d 100644 --- a/mobilerun/cli/credentials/group.py +++ b/mobilerun/cli/credentials/group.py @@ -91,29 +91,32 @@ def _resolve(package, name, field=None, *, need_field=False, local=False): return package, name, field -def _installed_packages(): - async def fetch(): - from mobilerun.cli.devices.base.selection import connect_target +def _installed_packages() -> list[str]: + async def fetch() -> list[str]: + from mobilerun_core import AsyncMobilerun + from mobilerun.config.loader import ConfigLoader - config = ConfigLoader.load(None) - serial = config.device.serial + config = ConfigLoader.load(None).device + serial = config.serial if not serial: return [] - device = await connect_target(serial, config=config, allow_auto_setup=False) - try: - apps = await device.list_apps() - return [ - package - for item in apps - if ( - package := item.get("package") - or item.get("package_name") - or item.get("packageName") + async with AsyncMobilerun() as run: + if serial.lower().startswith(("http://", "https://")): + token = config.resolve_auth_token("android") + if not token: + return [] + device = await run.connect( + backend="local-android-http", url=serial, token=token ) - ] - finally: - await device.close() + else: + device = await run.connect( + serial, + backend="local-android-adb", + use_tcp=config.use_tcp, + portal_mode=config.portal_mode, + ) + return [item.identity.app_id for item in await device.list_apps()] try: return asyncio.run(asyncio.wait_for(fetch(), timeout=1.5)) diff --git a/mobilerun/cli/devices/README.md b/mobilerun/cli/devices/README.md index 6be82cd8c..993672b11 100644 --- a/mobilerun/cli/devices/README.md +++ b/mobilerun/cli/devices/README.md @@ -17,11 +17,18 @@ cloud devices are discovered without creating a device. A single match is used automatically; multiple matches prompt on a terminal and require an explicit ID in non-interactive use. Cloud devices that are not ready are marked in the picker. +`mobilerun device list` (including `--json`) shows ADB states such as `offline` +and `unauthorized`. Listing does not require approval. These devices are marked +as not ready in the `connect` picker and are excluded from automatic command +target selection. + Run `mobilerun device connect` to choose a default from a picker, pass a known device ID, or provide a network address such as `host:5555`. The picker also offers an address-entry option for devices not yet discovered. Run `mobilerun device disconnect` to clear the default; network defaults are also disconnected from ADB. Pass a network address to disconnect that device alone. +Changing an ADB network connection requires confirmation or `--yes`. +Choosing an existing ID or clearing a non-network default doesn't need approval. ## Environment controls @@ -41,22 +48,23 @@ mobilerun device app open https://example.com All commands use the normal device selection and accept `[DEVICE]` or `--device`. Clipboard get and set are cloud-only. -Support varies by backend; see [environment, credentials and proxies](../../core/devices/README.md#environment-credentials-and-proxies). +Support varies by backend; devices are provided by `AsyncDevice` / `AsyncMobilerun` from `mobilerun_core`. Emulators retain their last fixed location; reset is unsupported, so set a new one instead. Reading location is supported on cloud devices; local Android, iOS and remote devices report it as unsupported. The cloud API returns coordinates without a mocked-status flag. ## Command tree Top-level commands: `list`, `connect`, `disconnect`, `ping`, `setup`. -Subgroups: `app`, `file`, `input`, `screen`, `settings`, `action`, `cloud`. +Subgroups: `app`, `file`, `input`, `screen`, `settings`, `cloud`. Package directories mirror these groups, with the group entry in `__init__.py`. Each selected command accepts `[DEVICE]` or `--device/-d`; conflicting values fail. | Path | Purpose | | --- | --- | | `group.py`, `list.py`, `connect.py`, `disconnect.py`, `ping.py`, `setup.py` | Root device commands | -| [base/](base/README.md) | Shared selection and device options | -| [action/](action/README.md), [app/](app/README.md), [cloud/](cloud/README.md) | Actions, apps and cloud lifecycle | +| [base/](base/README.md) | Shared Click plumbing and core client ownership | +| [utils/](utils/README.md) | Target routing, safe labels, approval, and prompts | +| [app/](app/README.md), [cloud/](cloud/README.md) | Apps and cloud lifecycle | | [file/](file/README.md), [input/](input/README.md), [screen/](screen/README.md), [settings/](settings/README.md) | File transfer, input, screen and environment controls | See the [CLI overview](../README.md). @@ -75,6 +83,8 @@ The old flat commands are no longer registered. Use their grouped replacements: | `device apps` | `device app list` | | `device start` | `device app start` | -`mobilerun doctor` diagnoses without installing/updating Portal or enabling -accessibility. Use `mobilerun doctor --fix` to permit repairs. Failed checks exit 1; -warnings alone do not fail. +`mobilerun doctor [SERIAL]` diagnoses without installing/updating Portal or enabling +accessibility. A missing TCP forward is a warning; an existing forward that +cannot reach Portal is a failure. Failed checks exit 1; warnings alone do not +fail. Use `mobilerun doctor SERIAL --fix` to request repairs. Like +`mobilerun device setup SERIAL`, repairs require confirmation or `--yes`. diff --git a/mobilerun/cli/devices/action/README.md b/mobilerun/cli/devices/action/README.md deleted file mode 100644 index 10989afd0..000000000 --- a/mobilerun/cli/devices/action/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# Device actions - -`mobilerun device action list --json` describes public callable actions. -`call ACTION --arg key=value` validates and converts schema arguments, then invokes -the action. Interactive calls can choose an action or enter its name manually. -`extensions --json` lists bound extensions and their current context. - -Sending through a bound CloudPhoneNumber uses that extension's billing mode. -Sending SMS may incur charges and requires confirmation, even in `paid` mode. -If the send must retry as `paid`, it asks only once. Use `--yes` to confirm -without prompting; it is required in non-interactive shells. - -```sh -mobilerun device action list --json -``` diff --git a/mobilerun/cli/devices/action/__init__.py b/mobilerun/cli/devices/action/__init__.py deleted file mode 100644 index 5e8b54094..000000000 --- a/mobilerun/cli/devices/action/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -import click - -from mobilerun.cli.base.menu import MenuGroup - -from .call import call -from .extensions import extensions -from .list import actions - - -@click.group(cls=MenuGroup) -def action(): - """Inspect and invoke device and extension actions.""" - - -for command in (actions, call, extensions): - action.add_command(command) diff --git a/mobilerun/cli/devices/action/call.py b/mobilerun/cli/devices/action/call.py deleted file mode 100644 index ff08209b6..000000000 --- a/mobilerun/cli/devices/action/call.py +++ /dev/null @@ -1,141 +0,0 @@ -"""Inspect and invoke actions on a selected device's extensions.""" - -import json -from collections.abc import Mapping -from functools import partial -from typing import Any - -import click - -from mobilerun.cli.base.billing import confirm_paid_action, invoke_with_billing -from mobilerun.cli.base.menu import is_interactive -from mobilerun.cli.base.prompts import SelectChoice -from mobilerun.cli.base.prompts import text_prompt_async as text_prompt -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command -from mobilerun.cli.devices.base.pickers import choose_value_async as choose_value -from mobilerun.config.settings import get_settings -from mobilerun.core.devices import Device -from mobilerun.core.extensions import Action, BillingRetry -from mobilerun.errors.base import MobilerunError -from mobilerun.models.billing import Billing -from mobilerun.models.context import JSONValue - - -def _convert(value: str, schema: Mapping[str, Any], name: str) -> JSONValue: - types = [schema.get("type")] - types.extend(item.get("type") for item in schema.get("anyOf", [])) - if "string" in types or types == [None]: - return value - try: - parsed: JSONValue = json.loads(value) - except json.JSONDecodeError: - raise click.ClickException(f"Invalid value for {name}") from None - return parsed - - -async def _arguments(action: Action, supplied: tuple[str, ...]) -> dict[str, JSONValue]: - properties: Mapping[str, Any] = action.input_schema.get("properties", {}) - values: dict[str, str] = {} - for item in supplied: - key, separator, value = item.partition("=") - if not separator or not key or key not in properties or key in values: - raise click.ClickException("Arguments must be unique known key=value pairs") - values[key] = value - for name in action.input_schema.get("required", []): - if name not in values: - if not is_interactive(): - raise click.ClickException(f"Missing required argument: {name}") - values[name] = await text_prompt( - name, secret=name in action.sensitive_parameters - ) - return { - name: _convert(value, properties[name], name) for name, value in values.items() - } - - -async def _billing_policy( - device: Device, entry: Action, *, yes: bool -) -> BillingRetry | None: - owner = device.extensions.get(entry.owner) - is_sms_send = entry.name == "sms.send" or ( - entry.name.endswith(".send") - and owner is not None - and owner.role == "phone_number" - ) - if entry.supports_billing_retry: - return partial( - invoke_with_billing, - yes=yes, - confirm_paid="Send SMS" if is_sms_send else None, - ) - - # Unmarked SMS providers cannot safely be retried; require consent up front. - if not is_sms_send: - return None - billing = get_settings().MOBILERUN_BILLING - if billing is not Billing.PAID: - raise click.ClickException( - "Sending SMS may incur charges; set MOBILERUN_BILLING=paid." - ) - await confirm_paid_action("Send SMS", yes=yes) - return None - - -@click.command("call") -@click.argument("action", required=False) -@click.option( - "--arg", - "arguments", - multiple=True, - help="Action argument as key=value (repeatable).", -) -@click.option("--json", "json_output", is_flag=True, help="Output JSON.") -@click.option( - "--yes", "-y", is_flag=True, help="Confirm chargeable actions without prompting." -) -@device_command -@coro -async def call( - action: str | None, - arguments: tuple[str, ...], - json_output: bool, - yes: bool, - target: DeviceTarget, -) -> None: - """Call an action on the selected device.""" - try: - async with target.open() as device: - assert device is not None # @device_command requires a device. - selected = await choose_value( - action, - "action", - ( - [ - SelectChoice(entry.name, entry.name, entry.description) - for entry in device.actions.list(audience="cli") - ] - if action is None and is_interactive() - else [] - ), - ) - entry = device.actions.get(selected) - if not entry.public: - raise click.ClickException(f"Action {selected} is restricted") - billing_retry = await _billing_policy(device, entry, yes=yes) - result = await device.actions.call( - selected, - await _arguments(entry, arguments), - audience="cli", - billing_retry=billing_retry, - ) - serialized = entry.serialize(result) - click.echo( - json.dumps(serialized, ensure_ascii=False) - if json_output or not isinstance(serialized, str) - else serialized - ) - except click.ClickException: - raise - except MobilerunError as exc: - raise click.ClickException(" ".join(str(exc).splitlines())) from exc diff --git a/mobilerun/cli/devices/action/extensions.py b/mobilerun/cli/devices/action/extensions.py deleted file mode 100644 index 4e29dc1de..000000000 --- a/mobilerun/cli/devices/action/extensions.py +++ /dev/null @@ -1,52 +0,0 @@ -import json -from dataclasses import asdict - -import click - -from mobilerun.cli.base import render -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command - - -@click.command("extensions") -@click.option("--json", "json_output", is_flag=True, help="Output JSON.") -@device_command -@coro -async def extensions(json_output: bool, target: DeviceTarget) -> None: - """List bound extensions and their context.""" - async with target.open() as device: - entries = [] - for name, extension in device.extensions.items(): - entries.append( - { - "name": name, - "kind": type(extension).__name__, - "exclusive": extension.exclusive, - "context": [asdict(item) for item in await extension.context()], - } - ) - if json_output: - click.echo(json.dumps(entries, ensure_ascii=False)) - else: - if not entries: - render.empty("extensions") - return - render.heading(len(entries), "extension") - for entry in entries: - render.table( - [ - [ - entry["name"], - render.secondary(entry["kind"]), - render.secondary( - f"exclusive: {entry['exclusive']}" - if entry["exclusive"] - else "" - ), - ] - ] - ) - render.kv( - (f" {item['kind']}", json.dumps(item["data"], ensure_ascii=False)) - for item in entry["context"] - ) diff --git a/mobilerun/cli/devices/action/list.py b/mobilerun/cli/devices/action/list.py deleted file mode 100644 index 9c3aeeddd..000000000 --- a/mobilerun/cli/devices/action/list.py +++ /dev/null @@ -1,42 +0,0 @@ -import json - -import click - -from mobilerun.cli.base import render -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command - - -@click.command("list") -@click.option("--json", "json_output", is_flag=True, help="Output JSON.") -@device_command -@coro -async def actions(json_output: bool, target: DeviceTarget) -> None: - """List callable device and extension actions.""" - async with target.open() as device: - entries = device.actions.list(audience="cli") - if json_output: - click.echo( - json.dumps( - [ - { - "name": entry.name, - "description": entry.description, - "input_schema": entry.input_schema, - } - for entry in entries - ], - ensure_ascii=False, - ) - ) - else: - if not entries: - render.empty("actions") - else: - render.heading(len(entries), "action") - render.table( - [ - [entry.name, render.secondary(entry.description)] - for entry in entries - ] - ) diff --git a/mobilerun/cli/devices/app/README.md b/mobilerun/cli/devices/app/README.md index 4cae7be62..29207b4ba 100644 --- a/mobilerun/cli/devices/app/README.md +++ b/mobilerun/cli/devices/app/README.md @@ -4,7 +4,19 @@ `open` opens URLs and deep links. Start, stop and uninstall offer installed-app choices when no package is supplied in an interactive terminal, with manual entry. Every command accepts `[DEVICE]` or `--device/-d`. +Install accepts an APK path or `--app-id` for workspace apps on a cloud phone. +Install and uninstall ask for approval in a terminal. For automation, pass `--yes`. +`list --json` uses `app_id` for both Android package names and iOS bundle IDs. ```sh mobilerun device app list emulator-5554 +mobilerun device app install ./example.apk emulator-5554 --yes ``` + +| Files | Purpose | +| --- | --- | +| `install.py`, `uninstall.py` | Install and remove apps | +| `list.py` | List installed apps as a table or JSON | +| `start.py`, `stop.py`, `open.py` | Launch or stop an app, or open a URL | + +See [device commands](../README.md) for shared target options. diff --git a/mobilerun/cli/devices/app/install.py b/mobilerun/cli/devices/app/install.py index cd54e9eae..50787d9bf 100644 --- a/mobilerun/cli/devices/app/install.py +++ b/mobilerun/cli/devices/app/install.py @@ -1,9 +1,14 @@ import click +from mobilerun_core import AppIdentity, AsyncDevice from mobilerun.cli.base import render -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command -from mobilerun.cli.devices.base.source import SourceCommand, source_option +from mobilerun.cli.devices.base.commands.source import SourceCommand +from mobilerun.cli.devices.base.device import device_command +from mobilerun.cli.devices.utils.labels import display_label +from mobilerun.cli.devices.utils.prompts.source import ( + select_source_async, + source_arguments, +) from mobilerun.core.workspace import Workspace @@ -12,33 +17,35 @@ @click.option("--app-id", help="Install a workspace app by ID.") @click.option("--reinstall", is_flag=True, help="Replace an existing installation") @click.option("--grant/--no-grant", default=True, help="Grant runtime permissions") -@source_option("apk", "app_id", apps=True) +@source_arguments("apk", "app_id") @device_command -@coro async def install( apk: str | None, app_id: str | None, reinstall: bool, grant: bool, - target: DeviceTarget, + device: AsyncDevice, ) -> None: """Install an app on a device.""" - if app_id and target.kind == "android": + apk, app_id = await select_source_async(apk, app_id, apps=True) + if app_id and device.info().backend != "cloud": raise click.UsageError( - "Workspace app IDs cannot be installed on local Android devices. " + "Workspace app IDs require a cloud device. " "Pass a local APK path instead of --app-id." ) - click.echo(f"Installing on {target}…", err=True) - async with target.open() as device: - if app_id: - app = await Workspace.get_app(app_id) - result = await device.install_app( - app, reinstall=reinstall, grant_permissions=grant - ) - else: - assert apk is not None - result = await device.install_apk( - apk, reinstall=reinstall, grant_permissions=grant - ) - detail = f"{result.package} {result.version}" if result is not None else apk - render.success(f"{target}: Installed {detail}") + label = display_label(device.device_id) + source: str | AppIdentity + if app_id: + app = await Workspace().get_app(app_id) + source = app.identity + elif apk is not None: + source = apk + else: + raise click.UsageError("Provide a local APK path or --app-id.") + click.echo(f"Installing on {label}…", err=True) + result = await device.install_app( + source, reinstall=reinstall, grant_permissions=grant + ) + identity = result.identity + version = f" {identity.version_name}" if identity.version_name else "" + render.success(f"{label}: Installed {identity.app_id}{version}") diff --git a/mobilerun/cli/devices/app/list.py b/mobilerun/cli/devices/app/list.py index 390c24fe1..8fe3cdfec 100644 --- a/mobilerun/cli/devices/app/list.py +++ b/mobilerun/cli/devices/app/list.py @@ -1,45 +1,52 @@ import json import click +from mobilerun_core import AsyncDevice from mobilerun.cli.base import render -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command +from mobilerun.cli.devices.base.device import device_command @click.command("list") @click.option("--system/--no-system", default=False, help="Include system apps") @click.option("--json", "as_json", is_flag=True, help="Output JSON.") @device_command -@coro async def apps( system: bool, as_json: bool, - target: DeviceTarget, + device: AsyncDevice, ) -> None: """List installed apps.""" - async with target.open() as device: - app_list = await device.list_apps(include_system=system) - if as_json: - click.echo(json.dumps(app_list, ensure_ascii=False)) - return - if not app_list: - render.empty("apps") - return - render.heading(len(app_list), "app") - rows = [] - for app in app_list: - label = app.get("label") or "" - package = ( - app.get("package") - or app.get("package_name") - or app.get("packageName") - or "" - ) - rows.append( - [ - label or package, - render.secondary(package if label and label != package else ""), - ] - ) - render.table(rows) + app_list = await device.list_apps(include_system_apps=system) + if as_json: + json_rows = [ + { + key: value + for key, value in { + "app_id": app.identity.app_id, + "label": app.name, + "version_name": app.identity.version_name, + "version_code": app.identity.version_code, + "is_system_app": app.is_system_app, + }.items() + if value is not None + } + for app in app_list + ] + click.echo(json.dumps(json_rows, ensure_ascii=False)) + return + if not app_list: + render.empty("apps") + return + render.heading(len(app_list), "app") + rows = [] + for app in app_list: + label = app.name + package = app.identity.app_id + rows.append( + [ + label or package, + render.secondary(package if label and label != package else ""), + ] + ) + render.table(rows) diff --git a/mobilerun/cli/devices/app/open.py b/mobilerun/cli/devices/app/open.py index 727322a31..41b0d5aed 100644 --- a/mobilerun/cli/devices/app/open.py +++ b/mobilerun/cli/devices/app/open.py @@ -1,17 +1,17 @@ import click +from mobilerun_core import AsyncDevice from mobilerun.cli.base import render -from mobilerun.cli.base.menu import PromptingArgument -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command +from mobilerun.cli.devices.base.device import device_command +from mobilerun.cli.devices.utils.labels import display_label +from mobilerun.cli.devices.utils.prompts.pickers import require_text @click.command("open") -@click.argument("url", cls=PromptingArgument) +@click.argument("url", required=False) @device_command -@coro -async def open_url(url: str, target: DeviceTarget) -> None: +async def open_url(url: str | None, device: AsyncDevice) -> None: """Open a URL or deep link.""" - async with target.open() as device: - await device.open_url(url) - render.success(f"Opened {url} on {target}") + url = await require_text(url, "URL") + await device.open_deep_link(url) + render.success(f"Opened {url} on {display_label(device.device_id)}") diff --git a/mobilerun/cli/devices/app/start.py b/mobilerun/cli/devices/app/start.py index a02527f6b..fe7fac02c 100644 --- a/mobilerun/cli/devices/app/start.py +++ b/mobilerun/cli/devices/app/start.py @@ -1,21 +1,20 @@ import click +from mobilerun_core import AsyncDevice from mobilerun.cli.base import render -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command -from mobilerun.cli.devices.base.pickers import choose_app +from mobilerun.cli.devices.base.device import device_command +from mobilerun.cli.devices.utils.labels import display_label +from mobilerun.cli.devices.utils.prompts.pickers import choose_app @click.command() @click.argument("package", required=False) @device_command -@coro async def start( package: str | None, - target: DeviceTarget, + device: AsyncDevice, ) -> None: """Launch an app by package name.""" - async with target.open() as device: - package = await choose_app(device, package) - await device.start_app(package) - render.success(f"{target}: Started {package}") + package = await choose_app(device, package) + await device.start_app(package) + render.success(f"{display_label(device.device_id)}: Started {package}") diff --git a/mobilerun/cli/devices/app/stop.py b/mobilerun/cli/devices/app/stop.py index 0ce7bb760..a789ea06b 100644 --- a/mobilerun/cli/devices/app/stop.py +++ b/mobilerun/cli/devices/app/stop.py @@ -1,18 +1,17 @@ import click +from mobilerun_core import AsyncDevice from mobilerun.cli.base import render -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command -from mobilerun.cli.devices.base.pickers import choose_app +from mobilerun.cli.devices.base.device import device_command +from mobilerun.cli.devices.utils.labels import display_label +from mobilerun.cli.devices.utils.prompts.pickers import choose_app @click.command() @click.argument("package", required=False) @device_command -@coro -async def stop(package: str | None, target: DeviceTarget) -> None: +async def stop(package: str | None, device: AsyncDevice) -> None: """Stop an installed app.""" - async with target.open() as device: - package = await choose_app(device, package) - await device.stop_app(package) - render.success(f"Stopped {package} on {target}") + package = await choose_app(device, package) + await device.stop_app(package) + render.success(f"Stopped {package} on {display_label(device.device_id)}") diff --git a/mobilerun/cli/devices/app/uninstall.py b/mobilerun/cli/devices/app/uninstall.py index 81cf61d47..ffd8cfe50 100644 --- a/mobilerun/cli/devices/app/uninstall.py +++ b/mobilerun/cli/devices/app/uninstall.py @@ -1,41 +1,17 @@ import click +from mobilerun_core import AsyncDevice from mobilerun.cli.base import render -from mobilerun.cli.base.run import coro -from mobilerun.cli.base.safety import confirm_action_async -from mobilerun.cli.devices.base.options import DeviceTarget, device_command -from mobilerun.cli.devices.base.pickers import choose_app +from mobilerun.cli.devices.base.device import device_command +from mobilerun.cli.devices.utils.labels import display_label +from mobilerun.cli.devices.utils.prompts.pickers import choose_app @click.command() @click.argument("package", required=False) -@click.option("--yes", "-y", is_flag=True, help="Confirm uninstall without prompting.") @device_command -@coro -async def uninstall( - package: str | None, - yes: bool, - target: DeviceTarget, -) -> None: +async def uninstall(package: str | None, device: AsyncDevice) -> None: """Uninstall an app by package name.""" - confirmed = package is not None - if confirmed: - await confirm_action_async( - f"uninstall {package}", - "no_commerce", - f"Uninstall {package} from {target}; app data will be deleted.", - yes=yes, - ) - async with target.open() as device: - package = await choose_app(device, package) - if not confirmed: - await confirm_action_async( - f"uninstall {package}", - "no_commerce", - f"Uninstall {package} from {target}; app data will be deleted.", - yes=yes, - ) - result = await device.uninstall_app(package) - if isinstance(result, str) and result.lower().startswith(("failure", "error")): - raise click.ClickException(f"{target}: {result}") - render.success(f"Uninstalled {package} from {target}") + package = await choose_app(device, package) + await device.uninstall_app(package) + render.success(f"Uninstalled {package} from {display_label(device.device_id)}") diff --git a/mobilerun/cli/devices/base/README.md b/mobilerun/cli/devices/base/README.md index 7df173c79..a89c39c1b 100644 --- a/mobilerun/cli/devices/base/README.md +++ b/mobilerun/cli/devices/base/README.md @@ -1,16 +1,41 @@ # Device CLI base -Shared device selection and options. +Decorate async Click handlers directly. `@device_command` injects a connected +`AsyncDevice` as `device`. It resolves `[DEVICE]` or `--device/-d`, then +`ANDROID_SERIAL`, then the saved default. Without a target, it offers a picker +in a terminal and otherwise asks for `--device`. Core owns the connection and +closes it after the command; it does not stop or delete the phone. -`@device_command` adds `[DEVICE]`, `--device/-d`, configuration, device-kind and -transport options. Command handlers receive one `DeviceTarget`; use -`async with target.open() as device:` to connect and guarantee cleanup. -Optional targets can represent no device (doctor). Lifecycle commands validate a -cloud-only target and use the cloud client directly rather than opening a phone. +```python +import click +from mobilerun_core import AsyncDevice +from mobilerun.cli.devices.base.device import device_command +from mobilerun.cli.devices.utils.prompts.pickers import choose_app -Direct commands do not auto-install Portal. Agent run and macro replay explicitly -preserve their configured auto-setup behavior with `allow_auto_setup=True`. - -```sh -mobilerun device ping emulator-5554 +@click.command() +@click.argument("package", required=False) +@device_command +async def start(package: str | None, device: AsyncDevice) -> None: + await device.start_app(await choose_app(device, package)) ``` + +For operands that should prompt **after** device selection, set `required=False` +in Click and use an async prompt helper in the handler. Use +`display_label(device.device_id)` for terminal output to hide URL paths and +credentials. Device-kind flags are `-a/-i/-c/-v`; `--base-url` sets the cloud API +URL. Android ADB transport preferences come from config when Android is selected +explicitly or from the picker. + +`@cloud_command` injects a `CloudDeviceHandle` as `device`, without connecting +to the phone. `@run_command` injects only `run: AsyncMobilerun` for commands that +use `run.local` or need to resolve their own inputs. All three decorators supply +`--yes/-y`. Core's approval gate asks in a terminal, denies non-interactively +without `--yes`, and never prints raw operation details. + +| File | Role | +| --- | --- | +| `device.py` | Click decorators that inject core handles | +| `selection.py` | Own a core client for one command | +| [commands/](commands/README.md) | Click command classes for argument parsing and preflight | + +See [device CLI utilities](../utils/README.md) for target routing, prompts, and labels. diff --git a/mobilerun/cli/devices/base/commands/README.md b/mobilerun/cli/devices/base/commands/README.md new file mode 100644 index 000000000..1c8ef66ad --- /dev/null +++ b/mobilerun/cli/devices/base/commands/README.md @@ -0,0 +1,12 @@ +# Device Click command classes + +Customize parsing or preflight before a device handler runs. For example, +`device cloud rename -d ID "New name"` binds the positional argument to the name. + +| File | Purpose | +| --- | --- | +| `rename.py` | Bind the phone name when `--device` supplies the ID | +| `resume.py` | Reject blocked billing before looking up a phone | +| `source.py` | Treat the lone positional as the device when an app or file ID supplies the transfer source | + +See [device command decorators](../README.md). diff --git a/mobilerun/cli/devices/base/commands/__init__.py b/mobilerun/cli/devices/base/commands/__init__.py new file mode 100644 index 000000000..37ca1c76a --- /dev/null +++ b/mobilerun/cli/devices/base/commands/__init__.py @@ -0,0 +1 @@ +"""Click command subclasses for device-specific parsing and validation.""" diff --git a/mobilerun/cli/devices/base/commands/rename.py b/mobilerun/cli/devices/base/commands/rename.py new file mode 100644 index 000000000..28f1ceb4c --- /dev/null +++ b/mobilerun/cli/devices/base/commands/rename.py @@ -0,0 +1,18 @@ +"""Click argument handling for cloud device rename.""" + +from typing import Any + +import click + + +class RenameCommand(click.Command): + def invoke(self, ctx: click.Context) -> Any: + """With -d, bind a single positional to NAME, not DEVICE.""" + params = ctx.params + if ( + params["device_option"] + and params["device_arg"] is not None + and params["name"] is None + ): + params["name"], params["device_arg"] = params["device_arg"], None + return super().invoke(ctx) diff --git a/mobilerun/cli/devices/base/commands/source.py b/mobilerun/cli/devices/base/commands/source.py new file mode 100644 index 000000000..ba24f199f --- /dev/null +++ b/mobilerun/cli/devices/base/commands/source.py @@ -0,0 +1,35 @@ +"""Click parsing for workspace-backed app and file transfers.""" + +import click + + +class SourceCommand(click.Command): + """Treat the lone positional argument as DEVICE when an ID is supplied.""" + + def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]: + source_flag = "--app-id" if self.name == "install" else "--file-id" + if any(arg == source_flag or arg.startswith(source_flag + "=") for arg in args): + takes_value = { + source_flag, + "--dest", + "--device", + "-d", + "--config", + "--base-url", + } + positions: list[int] = [] + skip = False + for index, arg in enumerate(args): + if skip: + skip = False + elif arg in takes_value: + skip = True + elif not arg.startswith("-"): + positions.append(index) + explicit_device = any( + arg in {"--device", "-d"} or arg.startswith("--device=") for arg in args + ) + if len(positions) == 1 and not explicit_device: + index = positions[0] + args = [*args[:index], "--device", args[index], *args[index + 1 :]] + return super().parse_args(ctx, args) diff --git a/mobilerun/cli/devices/base/default.py b/mobilerun/cli/devices/base/default.py deleted file mode 100644 index 5fb242f5a..000000000 --- a/mobilerun/cli/devices/base/default.py +++ /dev/null @@ -1,29 +0,0 @@ -"""Read and update the saved default without discarding other config keys.""" - -from pathlib import Path - -import yaml - -from mobilerun.config.loader import ConfigLoader -from mobilerun.config.settings import get_settings - - -def save_default_device(serial: str | None, *, config_path: str | None = None) -> None: - ConfigLoader.load(config_path) - if config_path: - path = Path(config_path) - else: - configured_path = get_settings().MOBILERUN_CONFIG - path = ( - Path(configured_path) - if configured_path and Path(configured_path).exists() - else ConfigLoader.get_user_config_path() - ) - with path.open(encoding="utf-8") as stream: - data = yaml.safe_load(stream) - device = data.setdefault("device", {}) - if serial is None: - device.pop("serial", None) - else: - device["serial"] = serial - ConfigLoader._save_dict(data, path) diff --git a/mobilerun/cli/devices/base/device.py b/mobilerun/cli/devices/base/device.py new file mode 100644 index 000000000..23652d90e --- /dev/null +++ b/mobilerun/cli/devices/base/device.py @@ -0,0 +1,98 @@ +"""Inject core handles into async device CLI commands.""" + +from collections.abc import Callable, Coroutine +from functools import update_wrapper +from typing import Any, Literal + +import click +from mobilerun_core import AsyncDevice, CloudDeviceHandle + +from mobilerun.cli.base.menu import is_interactive +from mobilerun.cli.base.run import coro +from mobilerun.cli.devices.base.selection import open_client +from mobilerun.cli.devices.utils.approval import cli_hitl_gate +from mobilerun.cli.devices.utils.connection.default import device_target +from mobilerun.cli.devices.utils.connection.device import connect_device, pick_device +from mobilerun.config.loader import ConfigLoader + +Handler = Callable[..., Coroutine[Any, Any, None]] +Command = Callable[..., None] +_KIND_FLAGS = ("android", "ios", "cloud", "remote") + + +def _command(handler: Handler, *, mode: Literal["device", "cloud", "run"]) -> Command: + @coro + async def invoke(*, base_url: str | None, yes: bool, **kwargs: Any) -> None: + if mode == "run": + async with open_client( + base_url=base_url, hitl_gate=cli_hitl_gate(yes=yes) + ) as run: + await handler(run=run, **kwargs) + return + + arg, flag = kwargs.pop("device_arg"), kwargs.pop("device_option") + if arg and flag and arg != flag: + raise click.UsageError( + "DEVICE and --device refer to different devices; choose one." + ) + kinds = [kind for kind in _KIND_FLAGS if kwargs.pop(f"device_{kind}", False)] + if len(kinds) > 1: + raise click.UsageError("Choose at most one device type flag.") + kind = "cloud" if mode == "cloud" else next(iter(kinds), None) + config = ConfigLoader.load(kwargs.pop("device_config")).device + identifier, kind = device_target(arg or flag, config, kind) + if not identifier and not is_interactive(): + raise click.UsageError( + "Pass DEVICE or --device, or set a default with `mobilerun device connect`." + ) + + async with open_client( + base_url=base_url, cloud=kind == "cloud", hitl_gate=cli_hitl_gate(yes=yes) + ) as run: + discovered = None + if not identifier: + selection = await pick_device(run, kind) + identifier, discovered = selection.device_id, selection.backend + device: CloudDeviceHandle | AsyncDevice + if mode == "cloud": + device = run.cloud_device(identifier) + else: + device = await connect_device(run, identifier, kind, config, discovered) + await handler(device=device, **kwargs) + + # Click reads the handler's help, name, and parameters from its wrapper. + command = update_wrapper(invoke, handler) + if mode != "run": + command = click.argument("device_arg", required=False, metavar="[DEVICE]")( + command + ) + command = click.option("--device", "-d", "device_option", help="Device to use")( + command + ) + command = click.option( + "--config", "device_config", type=click.Path(exists=True, dir_okay=False) + )(command) + if mode == "device": + for short, kind in zip("aicv", _KIND_FLAGS, strict=True): + command = click.option( + f"-{short}", f"--{kind}", f"device_{kind}", is_flag=True + )(command) + command = click.option("--base-url", help="Cloud API base URL")(command) + return click.option( + "--yes", "-y", is_flag=True, help="Approve this command without prompting." + )(command) + + +def device_command(handler: Handler) -> Command: + """Inject a connected core AsyncDevice as ``device``.""" + return _command(handler, mode="device") + + +def cloud_command(handler: Handler) -> Command: + """Inject a borrowed core CloudDeviceHandle as ``device``.""" + return _command(handler, mode="cloud") + + +def run_command(handler: Handler) -> Command: + """Inject a core AsyncMobilerun as ``run``, without choosing a device.""" + return _command(handler, mode="run") diff --git a/mobilerun/cli/devices/base/discovery.py b/mobilerun/cli/devices/base/discovery.py deleted file mode 100644 index 82a157db2..000000000 --- a/mobilerun/cli/devices/base/discovery.py +++ /dev/null @@ -1,92 +0,0 @@ -"""Discover existing local and cloud devices without creating resources.""" - -import logging -from dataclasses import dataclass -from typing import Literal - -import click -from async_adbutils import adb - -from mobilerun.clients.cloud.devices import list_devices -from mobilerun.clients.local.login_store import resolve_cloud_api_key -from mobilerun.errors.base import CredentialError, MobilerunError -from mobilerun.models.billing import Billing - -logger = logging.getLogger(__name__) - - -@dataclass(frozen=True) -class DiscoveredDevice: - id: str - source: Literal["local", "cloud"] - name: str | None - state: str | None - type: str | None - - @property - def ready(self) -> bool: - return self.state == ("device" if self.source == "local" else "ready") - - -async def discover_devices( - *, - cloud: bool = True, - local: bool = True, - base_url: str | None = None, - billing: Billing | None = None, - strict: bool = False, -) -> list[DiscoveredDevice]: - """List local and cloud devices; strict mode raises cloud errors.""" - devices: list[DiscoveredDevice] = [] - if local: - try: - local_devices = await adb.list() - except Exception: - logger.warning("Local device discovery failed; use --debug for details.") - logger.debug("Local discovery failure", exc_info=True) - else: - devices.extend( - DiscoveredDevice(device.serial, "local", None, device.state, None) - for device in local_devices - ) - if cloud: - try: - api_key = resolve_cloud_api_key() - except CredentialError as exc: - if strict: - raise click.ClickException(str(exc)) from exc - click.echo(f"Warning: {exc}", err=True) - return devices - if not api_key and strict: - raise click.ClickException( - "No cloud API key found. Set MOBILERUN_API_KEY or run `mobilerun account login`." - ) - if api_key: - try: - items = await list_devices( - api_key=api_key, - base_url=base_url, - billing=billing or Billing.NO_COMMERCE, - ) - except Exception as exc: - if strict: - if not isinstance(exc, MobilerunError): - raise click.ClickException( - "Error listing cloud devices: offline or unavailable (use --debug for details)." - ) from exc - raise click.ClickException( - f"Error listing cloud devices: {exc}" - ) from exc - reason = ( - str(exc) - if isinstance(exc, MobilerunError) - else "use --debug for details" - ) - click.echo(f"Warning: Error listing cloud devices: {reason}", err=True) - logger.debug("Cloud discovery failure", exc_info=True) - else: - devices.extend( - DiscoveredDevice(item.id, "cloud", item.name, item.state, item.type) - for item in items - ) - return devices diff --git a/mobilerun/cli/devices/base/options.py b/mobilerun/cli/devices/base/options.py deleted file mode 100644 index 7e3c230c3..000000000 --- a/mobilerun/cli/devices/base/options.py +++ /dev/null @@ -1,444 +0,0 @@ -from __future__ import annotations - -import asyncio -import os -from collections.abc import AsyncIterator, Callable -from contextlib import asynccontextmanager -from dataclasses import dataclass -from functools import partial, wraps -from typing import TYPE_CHECKING, Any, overload - -import click - -from mobilerun.cli.base.menu import PromptingParameter, is_interactive -from mobilerun.cli.base.prompts import SelectChoice, confirm_prompt, select_prompt -from mobilerun.cli.devices.base.default import save_default_device -from mobilerun.cli.devices.base.discovery import DiscoveredDevice, discover_devices -from mobilerun.cli.devices.base.selection import detect_device_kind -from mobilerun.config.loader import ConfigLoader -from mobilerun.config.user_config import MobileConfig - -if TYPE_CHECKING: - from mobilerun.core.devices.base import Device - - -@dataclass(frozen=True) -class DeviceTarget: - """A resolved CLI target; opening it always releases the connection.""" - - identifier: str | None - kind: str | None - config: MobileConfig - tcp: bool | None = None - base_url: str | None = None - allow_auto_setup: bool = False - - def __str__(self) -> str: - return self.identifier or "no device" - - @asynccontextmanager - async def open(self) -> AsyncIterator[Device | None]: - from mobilerun.cli.devices.base.selection import connect_target - - if self.identifier is None: - yield None - return - device = await connect_target( - self.identifier, - kind=self.kind, - config=self.config, - tcp=self.tcp, - base_url=self.base_url, - allow_auto_setup=self.allow_auto_setup, - ) - try: - yield device - finally: - await device.close() - - -def device_command( - f: Callable[..., Any] | None = None, - *, - optional: bool = False, - base_url_name: str = "base_url", - cloud_only: bool = False, - allow_auto_setup: bool = False, -) -> Callable[..., Any]: - """Add device controls and inject exactly one DeviceTarget parameter.""" - if f is None: - return lambda command: device_command( - command, - optional=optional, - base_url_name=base_url_name, - cloud_only=cloud_only, - allow_auto_setup=allow_auto_setup, - ) - - @wraps(f) - def invoke(*args: Any, **kwargs: Any) -> Any: - identifier = kwargs.pop("target") - android = kwargs.pop("android") - ios = kwargs.pop("ios") - cloud = kwargs.pop("cloud") - remote = kwargs.pop("visual_remote") - tcp = kwargs.pop("tcp") - base_url = kwargs.pop(base_url_name) - kind = ( - selected_device_kind(identifier, android, ios, cloud, remote, tcp, base_url) - if identifier is not None - else None - ) - if ( - identifier is None - and not kwargs.get("dry_run") - and (android or ios or cloud or remote or tcp is not None or base_url) - ): - raise click.UsageError("Device type and transport options require DEVICE.") - if cloud_only and kind != "cloud": - raise click.UsageError("This command requires a cloud device ID.") - config = click.get_current_context().meta["device_config"] - kwargs["target"] = DeviceTarget( - identifier, - kind, - config, - ( - tcp - if tcp is not None - else (config.device.use_tcp if kind == "android" else None) - ), - base_url, - allow_auto_setup, - ) - return f(*args, **kwargs) - - return device_options( - invoke, optional=optional, base_url_name=base_url_name, cloud_only=cloud_only - ) - - -def choose_device( - devices: list[DiscoveredDevice], *, save: Callable[[str], None] | None = None -) -> str: - if not devices: - raise click.ClickException( - "No devices found. Plug in a phone, run `mobilerun device setup`, " - "or `mobilerun account login` for cloud devices." - ) - if len(devices) == 1: - device = devices[0] - click.echo( - f"Using {device.id}" + (f" ({device.name})" if device.name else ""), - err=True, - ) - return device.id - if not is_interactive(): - candidates = ", ".join(f"{device.id} ({device.source})" for device in devices) - raise click.ClickException( - f"Devices found: {candidates}. Pass a device explicitly " - "or run `mobilerun device connect `." - ) - choices = [] - for device in devices: - label = device.id - if device.name: - label += f" ({device.name})" - if device.state: - label += f" [{device.state}]" - label += f" {device.source}" - if not device.ready: - label += " (not ready)" - choices.append(SelectChoice(device.id, label)) - try: - target = select_prompt("Select a device", choices) - if target is None: - click.get_current_context().exit(0) - if save and confirm_prompt(f"Save {target} as default device?", default=False): - save(target) - except (KeyboardInterrupt, click.Abort, EOFError): - click.get_current_context().exit(130) - return target - - -@overload -def device_options( - f: Callable[..., Any], - *, - optional: bool = False, - base_url_name: str = "base_url", - cloud_only: bool = False, -) -> Callable[..., Any]: ... - - -@overload -def device_options( - f: None = None, - *, - optional: bool = False, - base_url_name: str = "base_url", - cloud_only: bool = False, -) -> Callable[[Callable[..., Any]], Callable[..., Any]]: ... - - -def device_options( - f: Callable[..., Any] | None = None, - *, - optional: bool = False, - base_url_name: str = "base_url", - cloud_only: bool = False, -) -> Callable[..., Any]: - """Add target options: DEVICE, explicit config, env, saved config, discovery.""" - if f is None: - return lambda command: device_options( - command, - optional=optional, - base_url_name=base_url_name, - cloud_only=cloud_only, - ) - original = f - is_device_command = f.__module__.startswith("mobilerun.cli.devices.") - - def resolve( - ctx: click.Context, target: str | None, kwargs: dict[str, Any] - ) -> str | None: - path = kwargs.get("config_path", kwargs.get("config")) - config = ConfigLoader.load(path) - ctx.meta["device_config"] = config - explicit = target or kwargs.get("device_target") - if target and kwargs.get("device_target") and target != kwargs["device_target"]: - raise click.UsageError( - "DEVICE and --device refer to different devices; choose one." - ) - if explicit: - return explicit - if kwargs.get("dry_run"): - return None - if cloud_only: - from mobilerun.cli.base.choices import cloud_devices - from mobilerun.cli.devices.base.pickers import choose_value - - saved = config.device.serial - if ( - saved - and not saved.lower().startswith(("http://", "https://")) - and detect_device_kind(saved) == "cloud" - ): - return saved - choices = [] - if is_interactive(): - try: - choices = list(cloud_devices(ctx)) - except Exception: - click.echo( - "Could not load cloud devices; enter an ID manually.", err=True - ) - return choose_value(None, "cloud device", choices) - saved = config.device.serial - requested = [ - kind - for kind in ("android", "ios", "cloud", "visual_remote") - if kwargs.get(kind) - ] - if len(requested) > 1: - raise click.UsageError("Choose at most one device type flag.") - kind = requested[0] if requested else None - env_serial = os.environ.get("ANDROID_SERIAL", "").strip() - if env_serial and kind in (None, "android"): - local_devices = asyncio.run(discover_devices(cloud=False)) - if not any(item.id == env_serial and item.ready for item in local_devices): - raise click.ClickException( - f"ANDROID_SERIAL {env_serial} is not available." - ) - ctx.meta["android_env_serial"] = env_serial - return env_serial - if saved and kind and _infer_device_kind(saved, config) != kind: - saved = None - if saved and saved.lower().startswith(("http://", "https://")): - return saved - if ( - not saved - and (kind or getattr(config.device, "platform", "android")) == "ios" - ): - from mobilerun_core_local.driver.ios import discover_ios_device - - return asyncio.run(discover_ios_device()) - if kind == "visual_remote": - raise click.UsageError("Pass a remote device URL with --remote.") - devices = asyncio.run( - discover_devices( - local=kind != "cloud", - cloud=kind != "android", - base_url=kwargs.get(base_url_name), - ) - ) - devices = [item for item in devices if item.source != "local" or item.ready] - if saved: - if not any(device.id == saved for device in devices): - raise click.ClickException( - f"Default device {saved} is not available. Run `mobilerun device connect` " - "to pick another or `mobilerun device disconnect` to clear it." - ) - return saved - if optional and not devices: - return None - save = ( - partial(save_default_device, config_path=path) - if path - else save_default_device - ) - return choose_device(devices, save=save) - - def target_callback( - ctx: click.Context, param: click.Parameter, value: str | None - ) -> str | None: - # Only pick early when a required command argument would prompt first. - # Explicit kind options are eager too, so Click processes them before DEVICE. - if ( - not is_device_command - or ctx.resilient_parsing - or not is_interactive() - or not any( - isinstance(p, PromptingParameter) and p.required - for p in ctx.command.params - ) - ): - return value - return resolve(ctx, value, ctx.params) - - @wraps(original) - def with_config(*args: Any, **kwargs: Any) -> Any: - ctx = click.get_current_context() - target = kwargs.get("target") - if target and kwargs.get("device_target") and target != kwargs["device_target"]: - raise click.UsageError( - "DEVICE and --device refer to different devices; choose one." - ) - if "device_config" not in ctx.meta: - target = resolve(ctx, target, kwargs) - kwargs["target"] = target - kwargs.pop("device_target", None) - if is_device_command: - kwargs.pop("config_path", None) - return original(*args, **kwargs) - - decorated: Callable[..., Any] = with_config - decorated = click.argument( - "target", - required=False, - default=None, - metavar="[DEVICE]", - is_eager=is_device_command, - callback=target_callback, - )(decorated) - decorated = click.option( - "--device", - "-d", - "device_target", - default=None, - is_eager=True, - help="Device to use", - )(decorated) - if is_device_command: - decorated = click.option( - "--config", - "config_path", - is_eager=True, - type=click.Path(exists=True, dir_okay=False), - help="Use a specific configuration file", - )(decorated) - for option in ( - click.option( - "--base-url", - base_url_name, - is_eager=True, - default=None, - help="Cloud API base URL (cloud only)", - ), - click.option( - "--tcp/--no-tcp", default=None, help="Use TCP communication (Android only)" - ), - click.option( - "-v", - "--remote", - "visual_remote", - is_eager=True, - is_flag=True, - help="Interpret DEVICE as a remote device URL", - ), - click.option( - "-c", - "--cloud", - is_eager=True, - is_flag=True, - help="Interpret DEVICE as a cloud device id", - ), - click.option( - "-i", - "--ios", - is_eager=True, - is_flag=True, - help="Interpret DEVICE as an iOS URL", - ), - click.option( - "-a", - "--android", - is_eager=True, - is_flag=True, - help="Interpret DEVICE as Android (including Portal HTTP URLs)", - ), - ): - decorated = option(decorated) - return decorated - - -def _infer_device_kind(target: str, config: MobileConfig | None) -> str: - """Use configured transport for a known URL; otherwise infer from the ID.""" - if ( - config - and target.lower().startswith(("http://", "https://")) - and (config.device.serial == target or config.device.platform == "ios") - ): - return ( - "visual_remote" - if (config.device.control_backend or "").lower() == "visual-remote" - else config.device.platform - ) - return detect_device_kind(target) - - -def selected_device_kind( - target: str | None, - android: bool, - ios: bool, - cloud: bool, - visual_remote: bool, - tcp: bool | None, - base_url: str | None, -) -> str: - if target is None: - raise click.UsageError("Missing argument 'DEVICE'") - flags = [ - ("android", android), - ("ios", ios), - ("cloud", cloud), - ("visual_remote", visual_remote), - ] - selected = [kind for kind, enabled in flags if enabled] - if len(selected) > 1: - raise click.UsageError("Choose at most one device type flag.") - ctx = click.get_current_context(silent=True) - config = ctx.meta.get("device_config") if ctx else None - try: - if selected: - kind = selected[0] - elif ctx and ctx.meta.get("android_env_serial") == target: - kind = "android" - else: - kind = _infer_device_kind(target, config) - except ValueError as exc: - raise click.UsageError(str(exc)) from exc - if tcp is not None and kind != "android": - raise click.UsageError("--tcp/--no-tcp may only be used with Android.") - if base_url is not None and kind != "cloud": - raise click.UsageError("--base-url may only be used with cloud.") - return kind diff --git a/mobilerun/cli/devices/base/selection.py b/mobilerun/cli/devices/base/selection.py index 0e7f934b4..bf10590a7 100644 --- a/mobilerun/cli/devices/base/selection.py +++ b/mobilerun/cli/devices/base/selection.py @@ -1,111 +1,36 @@ -"""Construct devices for direct CLI actions.""" +"""Own a core client for the lifetime of one CLI command.""" -import uuid +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager -from async_adbutils import adb -from mobilerun_core_local.driver.android.portal import ensure_portal_ready +from mobilerun_core import AsyncMobilerun -from mobilerun.clients.portal.http import ( - create_android_portal_http_driver, - is_portal_http_url, -) -from mobilerun.clients.portal.setup import portal_version_kwargs -from mobilerun.config.loader import ConfigLoader -from mobilerun.config.user_config import MobileConfig -from mobilerun.core.devices import ( - AndroidDevice, - Device, - IOSDevice, - RemoteDevice, -) -from mobilerun.core.devices.components.wrapper import DriverDevice -from mobilerun.core.state.options import android_state_provider +from mobilerun.cli.devices.utils.approval import AsyncHitlGate, cli_hitl_gate +from mobilerun.clients.local.login_store import LoginStore +from mobilerun.config.settings import get_settings +from mobilerun.errors.base import CredentialError +from mobilerun.errors.cloud import CloudAuthRequired -def detect_device_kind(target: str) -> str: - """Infer a device type from an unambiguous positional target.""" - if target.lower().startswith(("http://", "https://")): - raise ValueError( - "URL target: add -i/--ios, -a/--android (Portal HTTP) or -v/--remote" - ) - try: - uuid.UUID(target) - except (ValueError, AttributeError): - return "android" - return "cloud" - - -async def connect_target( - target: str, - kind: str | None = None, - tcp: bool | None = None, +@asynccontextmanager +async def open_client( + *, base_url: str | None = None, - config: MobileConfig | None = None, - allow_auto_setup: bool = True, -) -> Device: - """Build and connect the explicitly selected device.""" - kind = kind or detect_device_kind(target) - if kind not in {"android", "ios", "cloud", "visual_remote"}: - raise ValueError(f"Unknown device type: {kind}") - if tcp is not None and kind != "android": - raise ValueError("--tcp/--no-tcp may only be used with Android.") - if base_url is not None and kind != "cloud": - raise ValueError("--base-url may only be used with cloud.") - device: Device - if kind == "android": - if is_portal_http_url(target): - token = (config or ConfigLoader.load(None)).device.resolve_auth_token( - "android" - ) - driver = create_android_portal_http_driver(target, token) - - async def close_portal_client() -> None: - if driver._client is not None: - await driver._client.aclose() - driver._client = None - - device = DriverDevice( - driver, - state_provider_factory=android_state_provider, - close=close_portal_client, - ) - else: - if ( - allow_auto_setup - and config is not None - and config.device.auto_setup - and config.device.portal_mode != "disabled" - ): - await ensure_portal_ready( - await adb.device(serial=target), - debug=config.logging.debug, - **portal_version_kwargs(ensure_portal_ready), - ) - if config is None: - device = AndroidDevice(serial=target, use_tcp=tcp) - else: - device = AndroidDevice( - serial=target, use_tcp=tcp, portal_mode=config.device.portal_mode - ) - elif kind == "ios": - token = config.device.resolve_auth_token("ios") if config is not None else None - device = IOSDevice(target, token=token) - elif kind == "cloud": - # lazy: the cloud driver is an optional dependency. - from mobilerun.core.devices.cloud import CloudDevice - - device = CloudDevice(device_id=target, base_url=base_url) - else: - if config is None: - device = RemoteDevice(url=target) - else: - device = RemoteDevice(url=target, device_id=config.device.device_id) + cloud: bool = False, + hitl_gate: AsyncHitlGate | None = None, +) -> AsyncIterator[AsyncMobilerun]: + """Own one command's core client, without requiring login for local work.""" try: - await device.connect() - except BaseException as exc: - try: - await device.close() - except BaseException as cleanup_error: - exc.add_note(f"Device cleanup failed: {type(cleanup_error).__name__}") - raise - return device + key = LoginStore.from_settings().resolve_api_key() + except CredentialError: + if cloud: + raise + key = None + if cloud and not key: + raise CloudAuthRequired("No cloud API key found.") + async with AsyncMobilerun( + bearer=key, + base_url=base_url or get_settings().MOBILERUN_CLOUD_BASE_URL, + hitl_gate=cli_hitl_gate() if hitl_gate is None else hitl_gate, + ) as run: + yield run diff --git a/mobilerun/cli/devices/base/source.py b/mobilerun/cli/devices/base/source.py deleted file mode 100644 index a0d69ea3a..000000000 --- a/mobilerun/cli/devices/base/source.py +++ /dev/null @@ -1,102 +0,0 @@ -"""Shared source selection for device transfer commands.""" - -import asyncio -from collections.abc import Callable -from functools import wraps -from typing import Any - -import click - -from mobilerun.cli.base.menu import is_interactive -from mobilerun.cli.base.prompts import SelectChoice, select_prompt, text_prompt -from mobilerun.core.workspace import Workspace - - -class SourceCommand(click.Command): - """Treat the lone positional argument as DEVICE when an ID is supplied.""" - - def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]: - source_flag = "--app-id" if self.name == "install" else "--file-id" - if any(arg == source_flag or arg.startswith(source_flag + "=") for arg in args): - takes_value = { - source_flag, - "--dest", - "--device", - "-d", - "--config", - "--base-url", - } - positions: list[int] = [] - skip = False - for index, arg in enumerate(args): - if skip: - skip = False - elif arg in takes_value: - skip = True - elif not arg.startswith("-"): - positions.append(index) - explicit_device = any( - arg in {"--device", "-d"} or arg.startswith("--device=") for arg in args - ) - if len(positions) == 1 and not explicit_device: - index = positions[0] - args = [*args[:index], "--device", args[index], *args[index + 1 :]] - return super().parse_args(ctx, args) - - -def select_source( - local: str | None, resource_id: str | None, *, apps: bool -) -> tuple[str | None, str | None]: - """Require exactly one source, offering a local path or workspace picker in a TTY.""" - if local and resource_id: - raise click.UsageError("Pass either a local path or a workspace ID, not both.") - if not local and not resource_id and is_interactive(): - choice = select_prompt( - "Choose a source", - [ - SelectChoice("local", "Local file"), - SelectChoice("workspace", "Workspace"), - ], - ) - if choice == "local": - local = text_prompt("Local path").strip() - if local: - local = str( - click.Path(exists=True, dir_okay=False).convert(local, None, None) - ) - elif choice == "workspace": - if apps: - choices = [ - SelectChoice(item.id, item.name or item.package, item.id) - for item in asyncio.run(Workspace.list_apps()) - if item.id is not None - ] - else: - choices = [ - SelectChoice(item.id, item.name, item.id) - for item in asyncio.run(Workspace.list_files()) - ] - if not choices: - raise click.ClickException("No workspace items found.") - resource_id = select_prompt("Select a workspace item", choices) - else: - raise click.Abort() - if not local and not resource_id: - raise click.UsageError("Provide a local path or a workspace ID.") - return local, resource_id - - -def source_option( - local_name: str, id_name: str, *, apps: bool -) -> Callable[[Callable[..., Any]], Callable[..., Any]]: - def decorate(func: Callable[..., Any]) -> Callable[..., Any]: - @wraps(func) - def wrapper(*args: Any, **kwargs: Any) -> Any: - kwargs[local_name], kwargs[id_name] = select_source( - kwargs[local_name], kwargs[id_name], apps=apps - ) - return func(*args, **kwargs) - - return wrapper - - return decorate diff --git a/mobilerun/cli/devices/cloud/README.md b/mobilerun/cli/devices/cloud/README.md index e5f240100..80421519e 100644 --- a/mobilerun/cli/devices/cloud/README.md +++ b/mobilerun/cli/devices/cloud/README.md @@ -1,18 +1,28 @@ # Cloud device lifecycle `mobilerun device cloud` exposes status, resume, stop, reboot, rename and terminate for an -existing cloud phone. These operations call the billing-aware SDK boundary without -opening a device connection, so stopped phones can be resumed or inspected. -Terminate permanently deletes the phone and requires confirmation (`--yes` in -automation). Missing IDs offer the cloud-device picker on a terminal. +existing cloud phone. These operations use a core lifecycle handle without +attaching to the phone, so stopped phones can be resumed or inspected. +Core asks for one confirmation for every change (`--yes` in automation). Status +is read-only. Terminate permanently deletes the phone and its data. +Missing IDs offer the cloud-device picker on a terminal. -`resume` checks the phone's reported billing strategy once. It does not ask for -confirmation when the strategy is `subscription`. A minute, auto, or unknown -strategy requires confirmation even in `paid` mode. In a restricted mode it -asks once before retrying with `paid`. Use `--yes` to confirm without prompting; -it is required for a potentially metered resume in non-interactive shells. +`resume` rejects `no_commerce` before device selection. It reads the billing +strategy once so core can warn about possible charges for minute, auto or unknown +plans. Under `included` or `paid` billing, approval authorizes that one resume, +including any charges. `--yes` does not override `no_commerce`. ```sh mobilerun device cloud status -mobilerun device cloud rename DEVICE "My phone" +mobilerun device cloud rename DEVICE "My phone" --yes ``` + +| File | Purpose | +| --- | --- | +| `status.py` | Read status as a table or allowlisted JSON. | +| `stop.py`, `resume.py`, `reboot.py` | Control the phone's power state. | +| `rename.py` | Change the phone's display name. | +| `terminate.py` | Permanently delete a phone and its data. | + +See [device selection](../base/README.md) for target and client ownership and +[Click command classes](../base/commands/README.md) for parsing and preflight. diff --git a/mobilerun/cli/devices/cloud/__init__.py b/mobilerun/cli/devices/cloud/__init__.py index 0729d7a5b..933b92481 100644 --- a/mobilerun/cli/devices/cloud/__init__.py +++ b/mobilerun/cli/devices/cloud/__init__.py @@ -11,7 +11,7 @@ @click.group(cls=MenuGroup) -def cloud(): +def cloud() -> None: """Manage cloud phone lifecycle without connecting to the phone.""" diff --git a/mobilerun/cli/devices/cloud/reboot.py b/mobilerun/cli/devices/cloud/reboot.py index a7ab6bc3b..12b9cd5bd 100644 --- a/mobilerun/cli/devices/cloud/reboot.py +++ b/mobilerun/cli/devices/cloud/reboot.py @@ -1,25 +1,14 @@ import click +from mobilerun_core import CloudDeviceHandle from mobilerun.cli.base import render -from mobilerun.cli.base.billing import creation_warning -from mobilerun.cli.base.run import coro -from mobilerun.cli.base.safety import confirm_action_async -from mobilerun.cli.devices.base.options import DeviceTarget, device_command -from mobilerun.clients.cloud import devices -from mobilerun.clients.cloud.client import cloud_client -from mobilerun.config.settings import get_settings +from mobilerun.cli.devices.base.device import cloud_command +from mobilerun.cli.devices.utils.labels import display_label @click.command() -@click.option("--yes", "-y", is_flag=True, help="Confirm cloud phone charges.") -@device_command(cloud_only=True) -@coro -async def reboot(target: DeviceTarget, yes: bool) -> None: +@cloud_command +async def reboot(device: CloudDeviceHandle) -> None: """Reboot a cloud phone.""" - billing = get_settings().MOBILERUN_BILLING - await confirm_action_async( - "reboot cloud phone", billing.value, creation_warning(billing.value), yes=yes - ) - async with cloud_client(base_url=target.base_url, billing=billing) as client: - await devices.reboot(target.identifier, billing=billing, client=client) - render.success(f"Rebooted {target}") + await device.reboot() + render.success(f"Rebooted {display_label(device.device_id)}") diff --git a/mobilerun/cli/devices/cloud/rename.py b/mobilerun/cli/devices/cloud/rename.py index 9231781dc..5771f275f 100644 --- a/mobilerun/cli/devices/cloud/rename.py +++ b/mobilerun/cli/devices/cloud/rename.py @@ -1,54 +1,29 @@ """Rename an existing cloud phone without opening a device connection.""" import json -from typing import Any import click +from mobilerun_core import CloudDeviceHandle from mobilerun.cli.base import render -from mobilerun.cli.base.menu import is_interactive -from mobilerun.cli.base.prompts import text_prompt_async -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command -from mobilerun.clients.cloud import devices -from mobilerun.clients.cloud.client import cloud_client -from mobilerun.config.settings import get_settings +from mobilerun.cli.devices.base.commands.rename import RenameCommand +from mobilerun.cli.devices.base.device import cloud_command +from mobilerun.cli.devices.utils.labels import display_label +from mobilerun.cli.devices.utils.prompts.pickers import require_text -class _RenameCommand(click.Command): - def invoke(self, ctx: click.Context) -> Any: - """With -d, bind a single positional to NAME, not DEVICE.""" - params = ctx.params - if ( - params["device_target"] - and params["target"] is not None - and params["name"] is None - ): - params["name"], params["target"] = params["target"], None - return super().invoke(ctx) - - -@click.command(cls=_RenameCommand) +@click.command(cls=RenameCommand) @click.option("--json", "as_json", is_flag=True) -@device_command(cloud_only=True) +@cloud_command @click.argument("name", required=False) -@coro -async def rename(target: DeviceTarget, name: str | None, as_json: bool) -> None: +async def rename(device: CloudDeviceHandle, name: str | None, as_json: bool) -> None: """Rename a cloud phone.""" - if name is None: - if not is_interactive(): - raise click.UsageError("Missing argument 'NAME'.") - name = await text_prompt_async("Name") - if not name or not name.strip(): - click.echo("Cancelled.", err=True) - return - name = name.strip() + name = (await require_text(name, "Name")).strip() if not name: raise click.UsageError("NAME must not be empty.") - billing = get_settings().MOBILERUN_BILLING - async with cloud_client(base_url=target.base_url, billing=billing) as client: - await devices.set_name(target.identifier, name, billing=billing, client=client) + await device.rename(name) + label = display_label(device.device_id) if as_json: - click.echo(json.dumps({"id": target.identifier, "name": name})) + click.echo(json.dumps({"id": label, "name": name})) else: - render.success(f"Renamed {target} to {name}") + render.success(f"Renamed {label} to {name}") diff --git a/mobilerun/cli/devices/cloud/resume.py b/mobilerun/cli/devices/cloud/resume.py index 401d63368..7a3114fa4 100644 --- a/mobilerun/cli/devices/cloud/resume.py +++ b/mobilerun/cli/devices/cloud/resume.py @@ -1,35 +1,23 @@ -from typing import cast - import click +from mobilerun_core import CloudDeviceHandle from mobilerun.cli.base import render -from mobilerun.cli.base.billing import billing_option, invoke_with_billing -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command -from mobilerun.clients.cloud import devices -from mobilerun.clients.cloud.client import cloud_client +from mobilerun.cli.base.billing import billing_option +from mobilerun.cli.devices.base.device import cloud_command +from mobilerun.cli.devices.utils.labels import display_label +from mobilerun.clients.cloud.billing_policy import BillingPolicy from mobilerun.models.billing import Billing @click.command() -@click.option( - "--yes", "-y", is_flag=True, help="Confirm metered resume without prompting." -) -@billing_option -@device_command(cloud_only=True) -@coro -async def resume(target: DeviceTarget, yes: bool, billing: str) -> None: +@billing_option(minimum=Billing.INCLUDED, operation="Resume cloud phone") +@cloud_command +async def resume(device: CloudDeviceHandle, billing: Billing) -> None: """Resume a stopped cloud phone.""" - device_id = cast(str, target.identifier) # @device_command requires a cloud ID. - mode = Billing(billing) - async with cloud_client(base_url=target.base_url, billing=mode) as client: - operation, needs_paid = await devices._prepare_resume( - device_id, billing=mode, client=client - ) - await invoke_with_billing( - operation, - mode, - yes=yes, - confirm_paid="Resume cloud phone" if needs_paid else None, - ) - render.success(f"Resumed {target}") + record = await device.refresh() + minimum = ( + Billing.INCLUDED if record.billing_strategy == "subscription" else Billing.PAID + ) + BillingPolicy(billing).require(minimum, "Resume cloud phone") + await device.resume() + render.success(f"Resumed {display_label(device.device_id)}") diff --git a/mobilerun/cli/devices/cloud/status.py b/mobilerun/cli/devices/cloud/status.py index ffc5404d6..47838a199 100644 --- a/mobilerun/cli/devices/cloud/status.py +++ b/mobilerun/cli/devices/cloud/status.py @@ -1,44 +1,44 @@ +import json + import click +from mobilerun_core import CloudDeviceHandle from mobilerun.cli.base import render -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command -from mobilerun.clients.cloud import devices -from mobilerun.clients.cloud.client import cloud_client -from mobilerun.config.settings import get_settings +from mobilerun.cli.devices.base.device import cloud_command +from mobilerun.cli.devices.utils.labels import display_label @click.command() @click.option("--json", "as_json", is_flag=True) -@device_command(cloud_only=True) -@coro -async def status(target: DeviceTarget, as_json: bool) -> None: +@cloud_command +async def status(device: CloudDeviceHandle, as_json: bool) -> None: """Print cloud phone status.""" - billing = get_settings().MOBILERUN_BILLING - async with cloud_client(base_url=target.base_url, billing=billing) as client: - info = await devices.retrieve(target.identifier, billing=billing, client=client) + info = await device.refresh() if as_json: click.echo( - info.model_dump_json( - include={ - "id", - "name", - "platform", - "type", - "state", - "stop_reason", - "billing_strategy", - } + json.dumps( + { + "id": info.device_id, + "name": info.name, + "platform": info.platform, + "state": info.state, + "type": info.device_type, + "billing_strategy": info.billing_strategy, + "stop_reason": info.stop_reason, + }, + ensure_ascii=False, + separators=(",", ":"), ) ) else: - name = getattr(info, "name", None) + name = info.name + label = display_label(device.device_id) render.table( [ [ - name or str(target), + name or label, render.status(info.state), - render.secondary(str(target)) if name else "", + render.secondary(label) if name else "", ] ] ) diff --git a/mobilerun/cli/devices/cloud/stop.py b/mobilerun/cli/devices/cloud/stop.py index 966eb1c04..2e23537e8 100644 --- a/mobilerun/cli/devices/cloud/stop.py +++ b/mobilerun/cli/devices/cloud/stop.py @@ -1,19 +1,14 @@ import click +from mobilerun_core import CloudDeviceHandle from mobilerun.cli.base import render -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command -from mobilerun.clients.cloud import devices -from mobilerun.clients.cloud.client import cloud_client -from mobilerun.config.settings import get_settings +from mobilerun.cli.devices.base.device import cloud_command +from mobilerun.cli.devices.utils.labels import display_label @click.command() -@device_command(cloud_only=True) -@coro -async def stop(target: DeviceTarget) -> None: +@cloud_command +async def stop(device: CloudDeviceHandle) -> None: """Stop a cloud phone without deleting it.""" - billing = get_settings().MOBILERUN_BILLING - async with cloud_client(base_url=target.base_url, billing=billing) as client: - await devices.stop(target.identifier, billing=billing, client=client) - render.success(f"Stopped {target}") + await device.stop() + render.success(f"Stopped {display_label(device.device_id)}") diff --git a/mobilerun/cli/devices/cloud/terminate.py b/mobilerun/cli/devices/cloud/terminate.py index 1ef9fcd20..1ee71fc56 100644 --- a/mobilerun/cli/devices/cloud/terminate.py +++ b/mobilerun/cli/devices/cloud/terminate.py @@ -1,27 +1,18 @@ import click +from mobilerun_core import CloudDeviceHandle from mobilerun.cli.base import render -from mobilerun.cli.base.run import coro -from mobilerun.cli.base.safety import confirm_action_async -from mobilerun.cli.devices.base.options import DeviceTarget, device_command -from mobilerun.clients.cloud import devices -from mobilerun.clients.cloud.client import cloud_client -from mobilerun.config.settings import get_settings +from mobilerun.cli.base.menu import is_interactive +from mobilerun.cli.devices.base.device import cloud_command +from mobilerun.cli.devices.utils.labels import display_label @click.command() -@click.option("--yes", "-y", is_flag=True, help="Confirm permanent phone deletion.") -@device_command(cloud_only=True) -@coro -async def terminate(target: DeviceTarget, yes: bool) -> None: +@cloud_command +async def terminate(device: CloudDeviceHandle) -> None: """Permanently delete a cloud phone and its data.""" - billing = get_settings().MOBILERUN_BILLING - await confirm_action_async( - "terminate cloud phone", - billing.value, - f"Permanently delete {target} and its data.", - yes=yes, - ) - async with cloud_client(base_url=target.base_url, billing=billing) as client: - await devices.terminate(target.identifier, billing=billing, client=client) - render.success(f"Terminated {target}") + label = display_label(device.device_id) + if is_interactive(): + render.warn(f"This permanently deletes {label} and its data.") + await device.terminate() + render.success(f"Terminated {label}") diff --git a/mobilerun/cli/devices/connect.py b/mobilerun/cli/devices/connect.py index b5bda8b72..6a96eb99f 100644 --- a/mobilerun/cli/devices/connect.py +++ b/mobilerun/cli/devices/connect.py @@ -1,38 +1,37 @@ """Choose a default device, optionally connecting an ADB network address.""" -import re -import uuid - import click -from async_adbutils import adb +from mobilerun_core import AsyncMobilerun, HitlDenied from mobilerun.cli.base import render +from mobilerun.cli.base.errors import safe_error_message from mobilerun.cli.base.menu import is_interactive from mobilerun.cli.base.prompts import SelectChoice from mobilerun.cli.base.prompts import select_prompt_async as select_prompt from mobilerun.cli.base.prompts import text_prompt_async as text_prompt -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.default import save_default_device -from mobilerun.cli.devices.base.discovery import discover_devices -from mobilerun.errors.base import MobilerunError +from mobilerun.cli.devices.base.device import run_command +from mobilerun.cli.devices.utils.connection.default import save_default_device +from mobilerun.cli.devices.utils.connection.discovery import discover_devices +from mobilerun.cli.devices.utils.labels import display_label +from mobilerun.cli.devices.utils.targets import adb_tcp_address, classify_target @click.command(short_help="Choose default device") @click.argument("target", required=False) -@coro -async def connect(target: str | None) -> None: +@run_command +async def connect(target: str | None, run: AsyncMobilerun) -> None: """Choose the device Mobilerun uses by default (picker, ID, or host:port for network devices).""" if target is None and not is_interactive(): raise click.ClickException("Pass a device id or host:port.") - devices = await discover_devices() + devices = await discover_devices(run=run) if target is None: choices = [ SelectChoice( - device.id, - f"{device.id}" + device.device_id, + display_label(device.device_id) + (f" ({device.name})" if device.name else "") + (f" [{device.state}]" if device.state else "") - + f" {device.source}" + + (" cloud" if device.backend == "cloud" else " local") + (" (not ready)" if not device.ready else ""), ) for device in devices @@ -48,25 +47,22 @@ async def connect(target: str | None) -> None: target = await text_prompt("Device address (host[:port])") except (KeyboardInterrupt, click.Abort, EOFError): click.get_current_context().exit(130) - if not any(device.id == target for device in devices): - try: - uuid.UUID(target) - except ValueError: - is_id = False - else: - is_id = True - if is_id or not re.fullmatch( - r"(?:[A-Za-z0-9][A-Za-z0-9.-]*|\[[0-9A-Fa-f:]+\])(?::[0-9]{1,5})?", target - ): - raise click.ClickException(f"Device {target} is not available.") + if not any(device.device_id == target for device in devices): + address = adb_tcp_address(target, default_port=5555) + if address is None or classify_target(target) == "cloud": + raise click.ClickException( + f"Device {display_label(target)} is not available." + ) try: - response = await adb.connect(target) - except MobilerunError as exc: - raise click.ClickException(f"Failed to connect to {target}: {exc}") from exc - prefixes = ("connected to ", "already connected to ") - prefix = next((item for item in prefixes if response.startswith(item)), None) - if prefix is None: - raise click.ClickException(f"Failed to connect to {target}: {response}") - target = response[len(prefix) :].strip() + result = await run.local.connect_android(address) + except HitlDenied: + raise + except Exception as exc: + raise click.ClickException( + f"Failed to connect to {target}: {safe_error_message(exc)}" + ) from exc + if not result.success: + raise click.ClickException(f"Failed to connect to {target}") + target = result.facts.get("transport_serial", result.serial) save_default_device(target) - render.success(f"Connected {target} (default device)") + render.success(f"Connected {display_label(target)} (default device)") diff --git a/mobilerun/cli/devices/disconnect.py b/mobilerun/cli/devices/disconnect.py index 5efc40a30..37e79edf2 100644 --- a/mobilerun/cli/devices/disconnect.py +++ b/mobilerun/cli/devices/disconnect.py @@ -1,21 +1,21 @@ """Clear the default device or disconnect a specific ADB TCP device.""" -import re - import click -from async_adbutils import adb +from mobilerun_core import AsyncMobilerun, HitlDenied from mobilerun.cli.base import render -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.default import save_default_device +from mobilerun.cli.base.errors import safe_error_message +from mobilerun.cli.devices.base.device import run_command +from mobilerun.cli.devices.utils.connection.default import save_default_device +from mobilerun.cli.devices.utils.labels import display_label +from mobilerun.cli.devices.utils.targets import adb_tcp_address from mobilerun.config.loader import ConfigLoader -from mobilerun.errors.base import MobilerunError @click.command() @click.argument("target", required=False) -@coro -async def disconnect(target: str | None) -> None: +@run_command +async def disconnect(target: str | None, run: AsyncMobilerun) -> None: """Clear the default, or disconnect a specific network device.""" default = ConfigLoader.load(None).device.serial if target is None: @@ -23,21 +23,21 @@ async def disconnect(target: str | None) -> None: click.echo("No default device.") return target = default - is_tcp = ( - re.fullmatch( - r"(?:[A-Za-z0-9][A-Za-z0-9.-]*|\[[0-9A-Fa-f:]+\]):[0-9]{1,5}", target - ) - is not None - ) - if target != default and not is_tcp: - raise click.ClickException(f"{target} is not a TCP device address.") - if is_tcp: + address = adb_tcp_address(target) + label = display_label(target) + if target != default and address is None: + raise click.ClickException(f"{label} is not a TCP device address.") + if address is not None: try: - response = await adb.disconnect(target, raise_error=True) - except MobilerunError as exc: - raise click.ClickException(f"Failed to disconnect {target}: {exc}") from exc - if not response or not response.startswith("disconnected "): - raise click.ClickException(f"Failed to disconnect {target}: {response}") + result = await run.local.disconnect_android(address) + except HitlDenied: + raise + except Exception as exc: + raise click.ClickException( + f"Failed to disconnect {label}: {safe_error_message(exc)}" + ) from exc + if not result.success: + raise click.ClickException(f"Failed to disconnect {label}") if target == default: save_default_device(None) - render.success(f"Disconnected {target}") + render.success(f"Disconnected {label}") diff --git a/mobilerun/cli/devices/file/README.md b/mobilerun/cli/devices/file/README.md index 796443f60..5242bd0ac 100644 --- a/mobilerun/cli/devices/file/README.md +++ b/mobilerun/cli/devices/file/README.md @@ -3,7 +3,20 @@ `mobilerun device file list` lists a directory. `push` accepts a local file or `--file-id` from the workspace. `pull` downloads a device file and `rm` deletes one after confirmation. Transfer progress goes to stderr; paths and JSON stay on stdout. +`--dest` names a device directory; without it, uploads go to `/sdcard/Download` +or, for images and videos, `/sdcard/DCIM/Camera`. Local ADB uploads also scan +images and videos. The CLI selects the device before asking for a missing path +or source. Pass `--yes` to approve `rm` without a prompt; scripts must pass it +explicitly. ```sh mobilerun device file list /sdcard emulator-5554 ``` + +| Files | Purpose | +| --- | --- | +| `list.py` | List device files as a table or JSON | +| `push.py`, `pull.py` | Transfer files to or from a device | +| `rm.py` | Confirm and delete a device file | + +See [device commands](../README.md) for shared target options. diff --git a/mobilerun/cli/devices/file/list.py b/mobilerun/cli/devices/file/list.py index 073ce1ce8..afb540fd5 100644 --- a/mobilerun/cli/devices/file/list.py +++ b/mobilerun/cli/devices/file/list.py @@ -2,26 +2,23 @@ from dataclasses import asdict import click +from mobilerun_core import AsyncDevice from mobilerun.cli.base import render -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command +from mobilerun.cli.devices.base.device import device_command @click.command("list") @click.argument("directory", required=False, default="/sdcard/Download") @click.option("--json", "as_json", is_flag=True) @device_command -@coro -async def list_command(directory: str, as_json: bool, target: DeviceTarget) -> None: +async def list_command(directory: str, as_json: bool, device: AsyncDevice) -> None: """List files on a device.""" - async with target.open() as device: - entries = await device.list_files(directory) - if as_json: - click.echo(json.dumps([asdict(entry) for entry in entries], default=str)) - else: - if not entries: - render.empty("files") - else: - render.heading(len(entries), "file") - render.table([[entry.path] for entry in entries]) + entries = await device.list_files(directory) + if as_json: + click.echo(json.dumps([asdict(entry) for entry in entries], default=str)) + elif not entries: + render.empty("files") + else: + render.heading(len(entries), "file") + render.table([[entry.path] for entry in entries]) diff --git a/mobilerun/cli/devices/file/pull.py b/mobilerun/cli/devices/file/pull.py index 423318445..49de4f0c2 100644 --- a/mobilerun/cli/devices/file/pull.py +++ b/mobilerun/cli/devices/file/pull.py @@ -1,19 +1,24 @@ +import asyncio +import posixpath from pathlib import Path import click +from mobilerun_core import AsyncDevice -from mobilerun.cli.base.menu import PromptingArgument -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command +from mobilerun.cli.devices.base.device import device_command +from mobilerun.cli.devices.utils.labels import display_label +from mobilerun.cli.devices.utils.prompts.pickers import require_text @click.command("pull") -@click.argument("remote", cls=PromptingArgument) +@click.argument("remote", required=False) @click.argument("local", required=False, default=".", type=click.Path(path_type=Path)) @device_command -@coro -async def pull(remote: str, local: Path, target: DeviceTarget) -> None: +async def pull(remote: str | None, local: Path, device: AsyncDevice) -> None: """Pull a file from a device.""" - click.echo(f"Pulling from {target}…", err=True) - async with target.open() as device: - click.echo(await device.pull_file(remote, local)) + remote = await require_text(remote, "remote") + click.echo(f"Pulling from {display_label(device.device_id)}…", err=True) + data = await device.pull_file(remote) + destination = local / posixpath.basename(remote) if local.is_dir() else local + await asyncio.to_thread(destination.write_bytes, data) + click.echo(destination) diff --git a/mobilerun/cli/devices/file/push.py b/mobilerun/cli/devices/file/push.py index 94bbea69c..fb9a0b137 100644 --- a/mobilerun/cli/devices/file/push.py +++ b/mobilerun/cli/devices/file/push.py @@ -1,32 +1,53 @@ +import mimetypes +import posixpath +from pathlib import Path + import click +from mobilerun_core import AsyncDevice -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command -from mobilerun.cli.devices.base.source import SourceCommand, source_option +from mobilerun.cli.devices.base.commands.source import SourceCommand +from mobilerun.cli.devices.base.device import device_command +from mobilerun.cli.devices.utils.labels import display_label +from mobilerun.cli.devices.utils.prompts.source import ( + select_source_async, + source_arguments, +) from mobilerun.core.workspace import Workspace +_MEDIA_DIR = "/sdcard/DCIM/Camera" +_DOWNLOAD_DIR = "/sdcard/Download" + @click.command("push", cls=SourceCommand) @click.argument("path", required=False, type=click.Path(exists=True, dir_okay=False)) @click.option("--dest") @click.option("--file-id", help="Push a workspace file by ID.") -@source_option("path", "file_id", apps=False) +@source_arguments("path", "file_id") @device_command -@coro async def push( - path: str | None, file_id: str | None, dest: str | None, target: DeviceTarget + path: str | None, file_id: str | None, dest: str | None, device: AsyncDevice ) -> None: """Push a local or workspace file to a device.""" + path, file_id = await select_source_async(path, file_id, apps=False) item = None + workspace = Workspace() if file_id: - items = await Workspace.list_files() + items = await workspace.list_files() item = next((item for item in items if item.id == file_id), None) if item is None: raise click.ClickException("Workspace file not found") - click.echo(f"Pushing to {target}…", err=True) - async with target.open() as device: - if file_id: - result = await Workspace.push_file(item, device, dest) - else: - result = await device.push_file(path, dest) - click.echo(result.path) + name = Path(item.name).name + else: + assert path is not None + name = Path(path).name + mime = mimetypes.guess_type(name)[0] or "" + media = mime.startswith(("image/", "video/")) + device_path = posixpath.join(dest or (_MEDIA_DIR if media else _DOWNLOAD_DIR), name) + scan_media = media and device.info().backend == "local-android-adb" + click.echo(f"Pushing to {display_label(device.device_id)}…", err=True) + if item is not None: + await workspace.push_file(item, device, device_path, scan_media=scan_media) + else: + assert path is not None + await device.push_file(path, device_path, scan_media=scan_media) + click.echo(device_path) diff --git a/mobilerun/cli/devices/file/rm.py b/mobilerun/cli/devices/file/rm.py index 7d13cec72..dd9c7040f 100644 --- a/mobilerun/cli/devices/file/rm.py +++ b/mobilerun/cli/devices/file/rm.py @@ -1,22 +1,17 @@ import click +from mobilerun_core import AsyncDevice from mobilerun.cli.base import render -from mobilerun.cli.base.menu import PromptingArgument -from mobilerun.cli.base.run import coro -from mobilerun.cli.base.safety import confirm_action_async -from mobilerun.cli.devices.base.options import DeviceTarget, device_command +from mobilerun.cli.devices.base.device import device_command +from mobilerun.cli.devices.utils.labels import display_label +from mobilerun.cli.devices.utils.prompts.pickers import require_text @click.command("rm") -@click.argument("remote", cls=PromptingArgument) -@click.option("--yes", "-y", is_flag=True) +@click.argument("remote", required=False) @device_command -@coro -async def rm(remote: str, yes: bool, target: DeviceTarget) -> None: +async def rm(remote: str | None, device: AsyncDevice) -> None: """Delete a file from a device.""" - await confirm_action_async( - "delete device file", "no_commerce", f"Delete {remote}.", yes=yes - ) - async with target.open() as device: - await device.delete_file(remote) - render.success(f"Deleted {remote} from {target}") + remote = await require_text(remote, "remote") + await device.delete_file(remote) + render.success(f"Deleted {remote} from {display_label(device.device_id)}") diff --git a/mobilerun/cli/devices/group.py b/mobilerun/cli/devices/group.py index 71374d248..e60cf7a9c 100644 --- a/mobilerun/cli/devices/group.py +++ b/mobilerun/cli/devices/group.py @@ -3,7 +3,6 @@ import click from mobilerun.cli.base.menu import MenuGroup -from mobilerun.cli.devices.action import action from mobilerun.cli.devices.app import app from mobilerun.cli.devices.cloud import cloud from mobilerun.cli.devices.connect import connect @@ -33,7 +32,6 @@ def device() -> None: input, screen, settings, - action, cloud, ): device.add_command(command) diff --git a/mobilerun/cli/devices/input/README.md b/mobilerun/cli/devices/input/README.md index 46f764449..e99510276 100644 --- a/mobilerun/cli/devices/input/README.md +++ b/mobilerun/cli/devices/input/README.md @@ -5,8 +5,19 @@ Clipboard commands are cloud-only. `clipboard get` prints clipboard text; `clipboard set TEXT` acknowledges without printing the text. Bare clipboard opens its menu on a terminal or shows help. +The CLI selects the device before prompting for missing input. Use `--device` +when supplying a device without all positional operands. +`long-press` uses a one-second swipe in place and is not available on iOS. + ```sh mobilerun device input tap 200 200 emulator-5554 mobilerun device input clipboard get "$CLOUD_DEVICE_ID" mobilerun device input clipboard set "hello" "$CLOUD_DEVICE_ID" ``` + +| Files | Purpose | +| --- | --- | +| `tap.py`, `long_press.py`, `swipe.py` | Coordinate input | +| [`../utils/coordinates.py`](../utils/coordinates.py) | Prompt for and validate a missing coordinate | +| `press.py`, `type.py` | System keys and text entry | +| [`clipboard/`](clipboard/README.md) | Cloud clipboard commands | diff --git a/mobilerun/cli/devices/input/clipboard/README.md b/mobilerun/cli/devices/input/clipboard/README.md index fc12b1fce..d504cb0d7 100644 --- a/mobilerun/cli/devices/input/clipboard/README.md +++ b/mobilerun/cli/devices/input/clipboard/README.md @@ -2,9 +2,16 @@ On a cloud device, get clipboard text on stdout or set text without echoing the supplied value. If the selected target is not a cloud device, both commands -report that a cloud device ID is required and exit without connecting. +report that a cloud device ID is required and exit without accessing its +clipboard. `set` prompts for missing text after selecting the device. Bare invocation presents the get/set menu; both `-h` and `--help` show help. +The commands borrow a core async device through the [shared target selector](../../base/README.md). ```sh mobilerun device input clipboard get "$CLOUD_DEVICE_ID" ``` + +| File | Purpose | +| --- | --- | +| `get.py` | Read and print clipboard text | +| `set.py` | Set clipboard text and acknowledge success | diff --git a/mobilerun/cli/devices/input/clipboard/get.py b/mobilerun/cli/devices/input/clipboard/get.py index be7b416e3..87b4ef0dd 100644 --- a/mobilerun/cli/devices/input/clipboard/get.py +++ b/mobilerun/cli/devices/input/clipboard/get.py @@ -1,17 +1,13 @@ import click +from mobilerun_core import AsyncDevice -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command +from mobilerun.cli.devices.base.device import device_command @click.command("get") @device_command -@coro -async def clipboard_get(target: DeviceTarget) -> None: +async def clipboard_get(device: AsyncDevice) -> None: """Print clipboard text from a cloud device.""" - if target.kind != "cloud": + if device.info().backend != "cloud": raise click.UsageError("Clipboard commands require a cloud device ID.") - async with target.open() as device: - if device is None: - raise click.UsageError("Missing argument 'DEVICE'.") - click.echo(await device.get_clipboard()) + click.echo(await device.get_clipboard()) diff --git a/mobilerun/cli/devices/input/clipboard/set.py b/mobilerun/cli/devices/input/clipboard/set.py index 2dfaf800e..759c4245e 100644 --- a/mobilerun/cli/devices/input/clipboard/set.py +++ b/mobilerun/cli/devices/input/clipboard/set.py @@ -1,21 +1,19 @@ import click +from mobilerun_core import AsyncDevice from mobilerun.cli.base import render -from mobilerun.cli.base.menu import PromptingArgument -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command +from mobilerun.cli.devices.base.device import device_command +from mobilerun.cli.devices.utils.labels import display_label +from mobilerun.cli.devices.utils.prompts.pickers import require_text @click.command("set") -@click.argument("text", cls=PromptingArgument) +@click.argument("text", required=False) @device_command -@coro -async def clipboard_set(text: str, target: DeviceTarget) -> None: +async def clipboard_set(text: str | None, device: AsyncDevice) -> None: """Set clipboard text on a cloud device.""" - if target.kind != "cloud": + if device.info().backend != "cloud": raise click.UsageError("Clipboard commands require a cloud device ID.") - async with target.open() as device: - if device is None: - raise click.UsageError("Missing argument 'DEVICE'.") - await device.set_clipboard(text) - render.success(f"Clipboard set on {target}") + text = await require_text(text, "text") + await device.set_clipboard(text) + render.success(f"Clipboard set on {display_label(device.device_id)}") diff --git a/mobilerun/cli/devices/input/long_press.py b/mobilerun/cli/devices/input/long_press.py index 65d7ccba5..4d26066d8 100644 --- a/mobilerun/cli/devices/input/long_press.py +++ b/mobilerun/cli/devices/input/long_press.py @@ -1,24 +1,21 @@ import click +from mobilerun_core import AsyncDevice from mobilerun.cli.base import render -from mobilerun.cli.base.menu import PromptingArgument -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command +from mobilerun.cli.devices.base.device import device_command +from mobilerun.cli.devices.utils.coordinates import require_coordinate +from mobilerun.cli.devices.utils.labels import display_label @click.command("long-press") -@click.argument("x", type=int, cls=PromptingArgument, prompt_label="X coordinate") -@click.argument("y", type=int, cls=PromptingArgument, prompt_label="Y coordinate") +@click.argument("x", type=int, required=False) +@click.argument("y", type=int, required=False) @device_command -@coro -async def long_press( - x: int, - y: int, - target: DeviceTarget, -) -> None: +async def long_press(x: int | None, y: int | None, device: AsyncDevice) -> None: """Long press at screen coordinates.""" - if target.kind == "ios": + if device.info().platform == "ios": raise click.ClickException("long-press is not supported on iOS") - async with target.open() as device: - await device.swipe(x, y, x, y, 1000) - render.success(f"{target}: Long pressed ({x}, {y})") + x = await require_coordinate(x, "X coordinate") + y = await require_coordinate(y, "Y coordinate") + await device.swipe(x, y, x, y, ms=1000) + render.success(f"{display_label(device.device_id)}: Long pressed ({x}, {y})") diff --git a/mobilerun/cli/devices/input/press.py b/mobilerun/cli/devices/input/press.py index 1683bf154..fa4de052f 100644 --- a/mobilerun/cli/devices/input/press.py +++ b/mobilerun/cli/devices/input/press.py @@ -1,24 +1,31 @@ import click +from mobilerun_core import AsyncDevice from mobilerun.cli.base import render -from mobilerun.cli.base.menu import ChoiceArgument -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command +from mobilerun.cli.base.menu import is_interactive +from mobilerun.cli.base.prompts import SelectChoice, select_prompt_async +from mobilerun.cli.devices.base.device import device_command +from mobilerun.cli.devices.utils.labels import display_label + +_BUTTONS = ("back", "home", "enter") @click.command() @click.argument( "button", - cls=ChoiceArgument, - type=click.Choice(["back", "home", "enter"], case_sensitive=False), + required=False, + type=click.Choice(_BUTTONS, case_sensitive=False), ) @device_command -@coro -async def press( - button: str, - target: DeviceTarget, -) -> None: +async def press(button: str | None, device: AsyncDevice) -> None: """Press a system button.""" - async with target.open() as device: - await device.press_button(button) - render.success(f"{target}: Pressed {button}") + if button is None: + if not is_interactive(): + raise click.UsageError("Missing argument 'BUTTON'.") + button = await select_prompt_async( + "Button", [SelectChoice(key, key) for key in _BUTTONS] + ) + if button is None: + raise click.exceptions.Exit(0) + await device.key(button) + render.success(f"{display_label(device.device_id)}: Pressed {button}") diff --git a/mobilerun/cli/devices/input/swipe.py b/mobilerun/cli/devices/input/swipe.py index a03d93b40..a022f9f37 100644 --- a/mobilerun/cli/devices/input/swipe.py +++ b/mobilerun/cli/devices/input/swipe.py @@ -1,38 +1,35 @@ import click +from mobilerun_core import AsyncDevice from mobilerun.cli.base import render -from mobilerun.cli.base.menu import PromptingArgument -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command +from mobilerun.cli.devices.base.device import device_command +from mobilerun.cli.devices.utils.coordinates import require_coordinate +from mobilerun.cli.devices.utils.labels import display_label @click.command("swipe") -@click.argument( - "x1", type=int, cls=PromptingArgument, prompt_label="X coordinate (start)" -) -@click.argument( - "y1", type=int, cls=PromptingArgument, prompt_label="Y coordinate (start)" -) -@click.argument( - "x2", type=int, cls=PromptingArgument, prompt_label="X coordinate (end)" -) -@click.argument( - "y2", type=int, cls=PromptingArgument, prompt_label="Y coordinate (end)" -) +@click.argument("x1", type=int, required=False) +@click.argument("y1", type=int, required=False) +@click.argument("x2", type=int, required=False) +@click.argument("y2", type=int, required=False) @click.option( "--duration", type=float, default=1.0, show_default=True, help="Duration in seconds" ) @device_command -@coro async def swipe_cmd( - x1: int, - y1: int, - x2: int, - y2: int, + x1: int | None, + y1: int | None, + x2: int | None, + y2: int | None, duration: float, - target: DeviceTarget, + device: AsyncDevice, ) -> None: """Swipe from (x1, y1) to (x2, y2).""" - async with target.open() as device: - await device.swipe(x1, y1, x2, y2, duration_ms=int(duration * 1000)) - render.success(f"{target}: Swiped ({x1}, {y1}) -> ({x2}, {y2})") + x1 = await require_coordinate(x1, "X coordinate (start)") + y1 = await require_coordinate(y1, "Y coordinate (start)") + x2 = await require_coordinate(x2, "X coordinate (end)") + y2 = await require_coordinate(y2, "Y coordinate (end)") + await device.swipe(x1, y1, x2, y2, ms=int(duration * 1000)) + render.success( + f"{display_label(device.device_id)}: Swiped ({x1}, {y1}) -> ({x2}, {y2})" + ) diff --git a/mobilerun/cli/devices/input/tap.py b/mobilerun/cli/devices/input/tap.py index f7df726cf..72afa946c 100644 --- a/mobilerun/cli/devices/input/tap.py +++ b/mobilerun/cli/devices/input/tap.py @@ -1,22 +1,19 @@ import click +from mobilerun_core import AsyncDevice from mobilerun.cli.base import render -from mobilerun.cli.base.menu import PromptingArgument -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command +from mobilerun.cli.devices.base.device import device_command +from mobilerun.cli.devices.utils.coordinates import require_coordinate +from mobilerun.cli.devices.utils.labels import display_label @click.command() -@click.argument("x", type=int, cls=PromptingArgument, prompt_label="X coordinate") -@click.argument("y", type=int, cls=PromptingArgument, prompt_label="Y coordinate") +@click.argument("x", type=int, required=False) +@click.argument("y", type=int, required=False) @device_command -@coro -async def tap( - x: int, - y: int, - target: DeviceTarget, -) -> None: +async def tap(x: int | None, y: int | None, device: AsyncDevice) -> None: """Tap at screen coordinates.""" - async with target.open() as device: - await device.tap(x, y) - render.success(f"{target}: Tapped ({x}, {y})") + x = await require_coordinate(x, "X coordinate") + y = await require_coordinate(y, "Y coordinate") + await device.tap(x, y) + render.success(f"{display_label(device.device_id)}: Tapped ({x}, {y})") diff --git a/mobilerun/cli/devices/input/type.py b/mobilerun/cli/devices/input/type.py index 033b6d0d9..a59d5968d 100644 --- a/mobilerun/cli/devices/input/type.py +++ b/mobilerun/cli/devices/input/type.py @@ -1,24 +1,19 @@ import click +from mobilerun_core import AsyncDevice from mobilerun.cli.base import render -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command +from mobilerun.cli.devices.base.device import device_command +from mobilerun.cli.devices.utils.labels import display_label +from mobilerun.cli.devices.utils.prompts.pickers import require_text @click.command("type") -@click.argument("text") +@click.argument("text", required=False) @click.option("--clear", is_flag=True, default=False, help="Clear field before typing") @device_command -@coro -async def type_text( - text: str, - clear: bool, - target: DeviceTarget, -) -> None: +async def type_text(text: str | None, clear: bool, device: AsyncDevice) -> None: """Type text into the currently focused field. Use 'tap' first to focus.""" - async with target.open() as device: - success = await device.input_text(text, clear) - if success: - render.success(f"{target}: Typed text") - else: - raise click.ClickException("Failed to type text") + text = await require_text(text, "text") + if not await device.type(text, clear=clear): + raise click.ClickException("Failed to type text") + render.success(f"{display_label(device.device_id)}: Typed text") diff --git a/mobilerun/cli/devices/list.py b/mobilerun/cli/devices/list.py index 1c6133534..66f2e8bb4 100644 --- a/mobilerun/cli/devices/list.py +++ b/mobilerun/cli/devices/list.py @@ -5,29 +5,9 @@ from mobilerun.cli.base import render from mobilerun.cli.base.billing import billing_option from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.discovery import DiscoveredDevice, discover_devices +from mobilerun.cli.devices.utils.connection.discovery import discover_devices from mobilerun.config.loader import ConfigLoader from mobilerun.config.settings import get_settings -from mobilerun.errors.base import MobilerunError -from mobilerun.models.billing import Billing - - -def _render_cloud(items: list[DiscoveredDevice], default: str | None = None) -> None: - if not items: - render.empty("cloud devices") - return - render.heading(len(items), "cloud device") - rows = [] - for item in items: - rows.append( - [ - ("★ " if item.id == default else "") + (item.name or item.id), - render.secondary(item.id) if item.name else "", - render.status(item.state), - render.secondary(item.type), - ] - ) - render.table(rows) @click.command("list") @@ -45,30 +25,19 @@ def _render_cloud(items: list[DiscoveredDevice], default: str | None = None) -> async def devices( cloud: bool, base_url: str | None, billing: str, as_json: bool ) -> None: - """List connected local devices and authenticated cloud devices.""" - if cloud: - items = await discover_devices( - local=False, - cloud=True, - base_url=base_url, - billing=Billing(billing), - strict=True, - ) - else: - try: - items = await discover_devices(base_url=base_url, billing=Billing(billing)) - except MobilerunError as exc: - raise click.ClickException(f"Error listing local devices: {exc}") from exc + """List local Android inventory and authenticated cloud devices.""" + # Keep the CLI option; core listings are read-only in either billing mode. + items = await discover_devices(local=not cloud, base_url=base_url, strict=cloud) default = ConfigLoader.load(None).device.serial if as_json: payload = [ { - "id": item.id, - "source": item.source, - "default": item.id == default, + "id": item.device_id, + "source": "cloud" if item.backend == "cloud" else "local", + "default": item.device_id == default, **( - {"name": item.name, "state": item.state, "type": item.type} - if item.source == "cloud" + {"name": item.name, "state": item.state, "type": item.device_type} + if item.backend == "cloud" else {"state": item.state} ), } @@ -76,8 +45,8 @@ async def devices( ] click.echo(json.dumps(payload, ensure_ascii=False)) return - local_items = [item for item in items if item.source == "local"] - cloud_items = [item for item in items if item.source == "cloud"] + local_items = [item for item in items if item.backend != "cloud"] + cloud_items = [item for item in items if item.backend == "cloud"] if not cloud: if local_items: render.heading(len(local_items), "local device") @@ -85,7 +54,7 @@ async def devices( [ [ render.secondary( - ("★ " if item.id == default else "") + item.id + ("★ " if item.device_id == default else "") + item.device_id ), render.secondary(item.state), ] @@ -97,4 +66,19 @@ async def devices( if cloud or cloud_items: if not cloud: click.echo() - _render_cloud(cloud_items, default) + if not cloud_items: + render.empty("cloud devices") + return + render.heading(len(cloud_items), "cloud device") + render.table( + [ + [ + ("★ " if item.device_id == default else "") + + (item.name or item.device_id), + render.secondary(item.device_id) if item.name else "", + render.status(item.state), + render.secondary(item.device_type), + ] + for item in cloud_items + ] + ) diff --git a/mobilerun/cli/devices/ping.py b/mobilerun/cli/devices/ping.py index c6e53adf2..e5ecc51fb 100644 --- a/mobilerun/cli/devices/ping.py +++ b/mobilerun/cli/devices/ping.py @@ -1,63 +1,70 @@ +"""Read Android Portal reachability through core.""" + import click -from async_adbutils import adb -from mobilerun_core_local.driver.android.portal import ( - ping_portal, - ping_portal_content, - ping_portal_tcp, -) +from mobilerun_core import AsyncMobilerun, PortalError, PortalUnavailable from mobilerun.cli.base import render from mobilerun.cli.base.errors import render_error -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command -from mobilerun.clients.portal.http import ( - create_android_portal_http_driver, - is_portal_http_url, -) +from mobilerun.cli.devices.base.device import run_command +from mobilerun.cli.devices.utils.labels import display_label +from mobilerun.cli.devices.utils.targets import classify_target, serial_or_option +from mobilerun.config.loader import ConfigLoader @click.command() +@click.argument("serial", metavar="[DEVICE]", required=False, envvar="ANDROID_SERIAL") +@click.option("--device", "-d", "device_option") +@click.option("--tcp/--no-tcp", default=None, help="Use TCP for Android ADB.") +@click.option("--config", type=click.Path(exists=True, dir_okay=False)) @click.option("--debug/--no-debug", default=None, help="Enable verbose debug logging") -@device_command -@coro +@run_command async def ping( - target: DeviceTarget, + run: AsyncMobilerun, + serial: str | None, + device_option: str | None, + tcp: bool | None, + config: str | None, debug: bool | None, ) -> None: """Ping a device to check if it is ready and accessible.""" - # Handle None defaults - debug_mode = debug if debug is not None else False - config = click.get_current_context().meta["device_config"] - use_tcp_mode = target.tcp - if target.kind != "android": + serial = serial_or_option(serial, device_option) + settings = ConfigLoader.load(config).device + serial = serial or settings.serial + if not serial: + raise click.UsageError("Pass DEVICE or --device.") + kind = classify_target(serial) + if kind == "cloud": raise click.ClickException( "device ping currently supports Android targets only." ) - + http = kind == "http" + token = settings.resolve_auth_token("android") if http else None + if http and not token: + raise click.ClickException( + "Android Portal HTTP needs the Portal auth token. Set " + "MOBILERUN_DEVICE_TOKEN or device.auth_token." + ) + target = display_label(serial) try: - if is_portal_http_url(target.identifier): - token = config.device.resolve_auth_token("android") - driver = create_android_portal_http_driver(target.identifier, token) - try: - await driver.connect() - await driver.get_ui_tree() - finally: - await driver.close() - render.success(f"{target}: Portal HTTP is reachable.") - return - - device_obj = await adb.device(target.identifier) - if not device_obj: - raise click.ClickException(f"{target}: device not found") - - await ping_portal(device_obj, debug_mode) - - if use_tcp_mode: - await ping_portal_tcp(device_obj, debug_mode) + if http: + status = await run.local.ping_portal(url=serial, token=token) else: - await ping_portal_content(device_obj, debug_mode) + status = await run.local.ping_portal( + serial, tcp=settings.use_tcp if tcp is None else tcp + ) + except PortalUnavailable: + reason = "Portal HTTP is not reachable." if http else "device not found" + raise click.ClickException(f"{target}: {reason}") from None + except PortalError: + raise click.ClickException(f"{target}: Portal check failed.") from None + except Exception as exc: + render_error(exc, debug=bool(debug)) + raise click.exceptions.Exit(1) from exc + label = "Portal HTTP" if status.transport == "http" else "Portal" + if not status.reachable: + raise click.ClickException(f"{label} is not reachable.") + if status.transport == "http": + render.success("Portal HTTP is reachable.") + else: render.success(f"{target}: Portal is accessible.") - except Exception as e: - render_error(e, debug=debug_mode) - raise click.exceptions.Exit(1) from e diff --git a/mobilerun/cli/devices/screen/README.md b/mobilerun/cli/devices/screen/README.md index bc394a3e0..356dbe84c 100644 --- a/mobilerun/cli/devices/screen/README.md +++ b/mobilerun/cli/devices/screen/README.md @@ -2,8 +2,15 @@ `mobilerun device screen screenshot` saves a PNG and prints its path. `ui` prints the accessibility tree; `ui --raw` preserves its original indentation. -Both use the shared target selector and release their device connection afterward. +Both use a connected core device and release its connection afterward. For a +visual remote, `ui` reports that only screenshots are available. ```sh mobilerun device screen screenshot emulator-5554 +mobilerun device screen ui emulator-5554 --raw ``` + +| File | Purpose | +| --- | --- | +| `screenshot.py` | Save core screenshot bytes to a temporary PNG | +| `ui.py` | Format a core observation as an indexed tree with native input bounds | diff --git a/mobilerun/cli/devices/screen/screenshot.py b/mobilerun/cli/devices/screen/screenshot.py index 6c9d962d1..711311189 100644 --- a/mobilerun/cli/devices/screen/screenshot.py +++ b/mobilerun/cli/devices/screen/screenshot.py @@ -2,23 +2,19 @@ import tempfile import click +from mobilerun_core import AsyncDevice -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command +from mobilerun.cli.devices.base.device import device_command @click.command() @device_command -@coro -async def screenshot( - target: DeviceTarget, -) -> None: +async def screenshot(device: AsyncDevice) -> None: """Take a screenshot and print the saved file path to stdout.""" - async with target.open() as device: - png_bytes = await device.screenshot() - fd, path = tempfile.mkstemp(prefix="mobilerun_", suffix=".png") - try: - os.write(fd, png_bytes) - finally: - os.close(fd) - click.echo(path) + png_bytes = await device.screenshot_bytes() + fd, path = tempfile.mkstemp(prefix="mobilerun_", suffix=".png") + try: + os.write(fd, png_bytes) + finally: + os.close(fd) + click.echo(path) diff --git a/mobilerun/cli/devices/screen/ui.py b/mobilerun/cli/devices/screen/ui.py index 15438285c..cb29193ac 100644 --- a/mobilerun/cli/devices/screen/ui.py +++ b/mobilerun/cli/devices/screen/ui.py @@ -1,34 +1,26 @@ import click +from mobilerun_core import AsyncDevice -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command -from mobilerun.core.state.filters import ConciseFilter -from mobilerun.core.state.options import StateProviderOptions +from mobilerun.cli.devices.base.device import device_command +from mobilerun.core.screen import ScreenOptions, ScreenProvider from mobilerun.logs.progress import log_progress_to_stderr @click.command() @click.option("--raw", is_flag=True, help="Print the unmodified tree.") @device_command -@coro -async def ui( - raw: bool, - target: DeviceTarget, -) -> None: +async def ui(raw: bool, device: AsyncDevice) -> None: """Print the UI accessibility tree with element bounds for targeting.""" - from mobilerun.core.state.ios import IOSStateProvider - log_progress_to_stderr() - async with target.open() as device: - provider = device._create_state_provider( - StateProviderOptions(tree_filter=ConciseFilter()) - ) - state = ( - await provider.get_state(strict=True) - if isinstance(provider, IOSStateProvider) - else await provider.get_state() - ) - tree = state.formatted_text - click.echo(tree if raw else "\n".join(f" {line}" for line in tree.split("\n"))) - if state.phone_state: - click.echo(f"\nPhone state: {state.phone_state}") + provider = ScreenProvider(device, options=ScreenOptions(detail="concise")) + screen = (await provider.observe()).ui + tree = screen.formatted_text + click.echo(tree if raw else "\n".join(f" {line}" for line in tree.split("\n"))) + phone_state = screen.phone_state + if device.info().backend == "visual-remote": + phone_state = { + "observationMode": "screenshot_only", + "accessibilityTree": False, + } + if phone_state: + click.echo(f"\nPhone state: {phone_state}") diff --git a/mobilerun/cli/devices/settings/README.md b/mobilerun/cli/devices/settings/README.md index cd61d0acf..97623e830 100644 --- a/mobilerun/cli/devices/settings/README.md +++ b/mobilerun/cli/devices/settings/README.md @@ -1,10 +1,19 @@ # Device settings `mobilerun device settings` contains `location get/set/reset`, `language get/set` -and `timezone get/set`. Language and timezone getters use the cloud SDK; backends -without support report an unsupported operation. Successful mutations acknowledge -the selected device. Location get accepts `--json`. +and `timezone get/set`. Commands use `mobilerun_core.AsyncDevice`. Reads do not +require approval. Core asks for approval before set or reset; pass `--yes` to +approve without a prompt. In a terminal, omitted setting values are prompted for +after device selection. Use `--device` to name the device when omitting values. +Unsupported backends report an error. Location get accepts `--json`. ```sh -mobilerun device settings location set 52.52 13.40 emulator-5554 +mobilerun device settings location set 52.52 13.40 emulator-5554 --yes ``` + +| Files | Purpose | +| --- | --- | +| `__init__.py` | Register the settings group. | +| [language/](language/) | Read or set the locale. | +| [location/](location/) | Read, set, or reset location. | +| [timezone/](timezone/) | Read or set the timezone. | diff --git a/mobilerun/cli/devices/settings/language/README.md b/mobilerun/cli/devices/settings/language/README.md index 44bfc5d25..f3c75ee92 100644 --- a/mobilerun/cli/devices/settings/language/README.md +++ b/mobilerun/cli/devices/settings/language/README.md @@ -2,7 +2,16 @@ Get the cloud phone's BCP-47 locale or set a locale such as `de-DE`. Other backends report unsupported operations explicitly. Both commands accept shared target flags. +`set` asks for approval unless you pass `--yes`. ```sh mobilerun device settings language get ``` + +| Files | Purpose | +| --- | --- | +| `__init__.py` | Register the language group. | +| `get.py` | Print the locale from core. | +| `set.py` | Change the locale through core. | + +See [device settings](../README.md). diff --git a/mobilerun/cli/devices/settings/language/get.py b/mobilerun/cli/devices/settings/language/get.py index c65dbc159..03ec9eb32 100644 --- a/mobilerun/cli/devices/settings/language/get.py +++ b/mobilerun/cli/devices/settings/language/get.py @@ -1,14 +1,12 @@ import click +from mobilerun_core import AsyncDevice from mobilerun.cli.base import render -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command +from mobilerun.cli.devices.base.device import device_command @click.command("get") @device_command -@coro -async def language_get(target: DeviceTarget) -> None: +async def language_get(device: AsyncDevice) -> None: """Print the device language.""" - async with target.open() as device: - render.kv([("Language", await device.get_language())]) + render.kv([("Language", await device.get_locale())]) diff --git a/mobilerun/cli/devices/settings/language/set.py b/mobilerun/cli/devices/settings/language/set.py index 5a8b2d605..023e0ebb8 100644 --- a/mobilerun/cli/devices/settings/language/set.py +++ b/mobilerun/cli/devices/settings/language/set.py @@ -1,17 +1,17 @@ import click +from mobilerun_core import AsyncDevice from mobilerun.cli.base import render -from mobilerun.cli.base.menu import PromptingArgument -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command +from mobilerun.cli.devices.base.device import device_command +from mobilerun.cli.devices.utils.labels import display_label +from mobilerun.cli.devices.utils.prompts.pickers import require_text @click.command("set") -@click.argument("locale", cls=PromptingArgument) +@click.argument("locale", required=False) @device_command -@coro -async def language_set(locale: str, target: DeviceTarget) -> None: +async def language_set(locale: str | None, device: AsyncDevice) -> None: """Set a locale such as de-DE.""" - async with target.open() as device: - await device.set_language(locale) - render.success(f"Language set to {locale} on {target}") + locale = await require_text(locale, "Locale") + await device.set_locale(locale) + render.success(f"Language set to {locale} on {display_label(device.device_id)}") diff --git a/mobilerun/cli/devices/settings/location/README.md b/mobilerun/cli/devices/settings/location/README.md index a9d5fb4f4..216edebc6 100644 --- a/mobilerun/cli/devices/settings/location/README.md +++ b/mobilerun/cli/devices/settings/location/README.md @@ -1,8 +1,17 @@ # Location commands Get cloud coordinates as text or JSON, set latitude/longitude on supported devices, -or reset the simulated cloud location. Mutations acknowledge the selected target. +or reset the simulated cloud location. `set` and `reset` ask for approval unless +you pass `--yes`. Both acknowledge the selected device on success. ```sh mobilerun device settings location set 52.52 13.40 emulator-5554 ``` + +| Files | Purpose | +| --- | --- | +| `__init__.py` | Register the location group. | +| `get.py` | Print coordinates or JSON. | +| `set.py`, `reset.py` | Change or reset location through core. | + +See [device settings](../README.md). diff --git a/mobilerun/cli/devices/settings/location/get.py b/mobilerun/cli/devices/settings/location/get.py index 021e994f4..1683354d1 100644 --- a/mobilerun/cli/devices/settings/location/get.py +++ b/mobilerun/cli/devices/settings/location/get.py @@ -1,32 +1,30 @@ import json import click +from mobilerun_core import AsyncDevice from mobilerun.cli.base import render -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command +from mobilerun.cli.devices.base.device import device_command @click.command("get") @click.option("--json", "as_json", is_flag=True) @device_command -@coro -async def location_get(as_json: bool, target: DeviceTarget) -> None: +async def location_get(as_json: bool, device: AsyncDevice) -> None: """Print the device location.""" - async with target.open() as device: - result = await device.get_location() - if as_json: - click.echo( - json.dumps( - None - if result is None - else { - "latitude": result.latitude, - "longitude": result.longitude, - } - ) + result = await device.get_location() + if as_json: + click.echo( + json.dumps( + None + if result is None + else { + "latitude": result.latitude, + "longitude": result.longitude, + } ) - elif result is None: - render.kv([("Location", "Not available")]) - else: - render.kv([("Location", f"{result.latitude:.4f}, {result.longitude:.4f}")]) + ) + elif result is None: + render.kv([("Location", "Not available")]) + else: + render.kv([("Location", f"{result.latitude:.4f}, {result.longitude:.4f}")]) diff --git a/mobilerun/cli/devices/settings/location/reset.py b/mobilerun/cli/devices/settings/location/reset.py index 5cf44eb90..78056460c 100644 --- a/mobilerun/cli/devices/settings/location/reset.py +++ b/mobilerun/cli/devices/settings/location/reset.py @@ -1,15 +1,14 @@ import click +from mobilerun_core import AsyncDevice from mobilerun.cli.base import render -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command +from mobilerun.cli.devices.base.device import device_command +from mobilerun.cli.devices.utils.labels import display_label @click.command("reset") @device_command -@coro -async def location_reset(target: DeviceTarget) -> None: +async def location_reset(device: AsyncDevice) -> None: """Reset the device location.""" - async with target.open() as device: - await device.reset_location() - render.success(f"Location reset on {target}") + await device.reset_location() + render.success(f"Location reset on {display_label(device.device_id)}") diff --git a/mobilerun/cli/devices/settings/location/set.py b/mobilerun/cli/devices/settings/location/set.py index c0e3ec33e..bc2f6bbae 100644 --- a/mobilerun/cli/devices/settings/location/set.py +++ b/mobilerun/cli/devices/settings/location/set.py @@ -1,18 +1,27 @@ import click +from mobilerun_core import AsyncDevice from mobilerun.cli.base import render -from mobilerun.cli.base.menu import PromptingArgument -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command +from mobilerun.cli.devices.base.device import device_command +from mobilerun.cli.devices.utils.labels import display_label +from mobilerun.cli.devices.utils.prompts.pickers import require_text @click.command("set") -@click.argument("latitude", type=float, cls=PromptingArgument) -@click.argument("longitude", type=float, cls=PromptingArgument) +@click.argument("latitude", type=float, required=False) +@click.argument("longitude", type=float, required=False) @device_command -@coro -async def location_set(latitude: float, longitude: float, target: DeviceTarget) -> None: +async def location_set( + latitude: float | None, longitude: float | None, device: AsyncDevice +) -> None: """Set latitude and longitude.""" - async with target.open() as device: - await device.set_location(latitude, longitude) - render.success(f"Location set to {latitude}, {longitude} on {target}") + if latitude is None: + latitude = click.FLOAT.convert(await require_text(None, "Latitude"), None, None) + if longitude is None: + longitude = click.FLOAT.convert( + await require_text(None, "Longitude"), None, None + ) + await device.set_location(latitude, longitude) + render.success( + f"Location set to {latitude}, {longitude} on {display_label(device.device_id)}" + ) diff --git a/mobilerun/cli/devices/settings/timezone/README.md b/mobilerun/cli/devices/settings/timezone/README.md index 32dc62bf8..5e3ab1cda 100644 --- a/mobilerun/cli/devices/settings/timezone/README.md +++ b/mobilerun/cli/devices/settings/timezone/README.md @@ -1,8 +1,17 @@ # Timezone commands Get the cloud phone's IANA timezone, or set a valid timezone on supported backends. -Use `Europe/Berlin`, for example. Mutations report the value and selected device. +Use `Europe/Berlin`, for example. `set` asks for approval unless you pass `--yes` and +reports the value and selected device on success. ```sh mobilerun device settings timezone get ``` + +| Files | Purpose | +| --- | --- | +| `__init__.py` | Register the timezone group. | +| `get.py` | Print the timezone from core. | +| `set.py` | Change the timezone through core. | + +See [device settings](../README.md). diff --git a/mobilerun/cli/devices/settings/timezone/get.py b/mobilerun/cli/devices/settings/timezone/get.py index 2811ab3f8..549ed996e 100644 --- a/mobilerun/cli/devices/settings/timezone/get.py +++ b/mobilerun/cli/devices/settings/timezone/get.py @@ -1,15 +1,13 @@ import click +from mobilerun_core import AsyncDevice from mobilerun.cli.base import render -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command +from mobilerun.cli.devices.base.device import device_command @click.command("get") @device_command -@coro -async def timezone_get(target: DeviceTarget) -> None: +async def timezone_get(device: AsyncDevice) -> None: """Print the IANA timezone.""" - async with target.open() as device: - value = await device.get_timezone() - render.kv([("Timezone", value if value is not None else "Not available")]) + value = await device.get_timezone() + render.kv([("Timezone", value if value is not None else "Not available")]) diff --git a/mobilerun/cli/devices/settings/timezone/set.py b/mobilerun/cli/devices/settings/timezone/set.py index c20231af3..f71ce37b8 100644 --- a/mobilerun/cli/devices/settings/timezone/set.py +++ b/mobilerun/cli/devices/settings/timezone/set.py @@ -1,17 +1,17 @@ import click +from mobilerun_core import AsyncDevice from mobilerun.cli.base import render -from mobilerun.cli.base.menu import PromptingArgument -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command +from mobilerun.cli.devices.base.device import device_command +from mobilerun.cli.devices.utils.labels import display_label +from mobilerun.cli.devices.utils.prompts.pickers import require_text @click.command("set") -@click.argument("timezone", cls=PromptingArgument) +@click.argument("timezone", required=False) @device_command -@coro -async def timezone_set(timezone: str, target: DeviceTarget) -> None: +async def timezone_set(timezone: str | None, device: AsyncDevice) -> None: """Set the IANA timezone.""" - async with target.open() as device: - await device.set_timezone(timezone) - render.success(f"Timezone set to {timezone} on {target}") + timezone = await require_text(timezone, "Timezone") + await device.set_timezone(timezone) + render.success(f"Timezone set to {timezone} on {display_label(device.device_id)}") diff --git a/mobilerun/cli/devices/setup.py b/mobilerun/cli/devices/setup.py index a7943b8b3..41a2a0c4d 100644 --- a/mobilerun/cli/devices/setup.py +++ b/mobilerun/cli/devices/setup.py @@ -1,122 +1,75 @@ -import traceback +"""Install and enable Android Portal using core's approval gate.""" import click -from async_adbutils import adb -from mobilerun_core_local.driver.android.portal import PORTAL_PACKAGE_NAME -from rich.console import Console +from mobilerun_core import AsyncMobilerun, HitlDenied +from mobilerun.cli.base import render from mobilerun.cli.base.errors import render_error -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command -from mobilerun.clients.portal.install import install_portal -from mobilerun.errors import DeviceNotFound, PortalApkNotFound, PortalInstallFailed - -console = Console() +from mobilerun.cli.devices.base.device import run_command +from mobilerun.cli.devices.utils.targets import classify_target, serial_or_option +from mobilerun.config.loader import ConfigLoader +from mobilerun.version import __version__ @click.command() -@click.option( - "--path", - help="Path to the Mobilerun Portal APK to install on the device. If not provided, the latest portal apk version will be downloaded and installed.", - default=None, -) -@click.option( - "--portal-version", - "-pv", - help="Specific Portal version to install (e.g., 0.4.7)", - default=None, -) +@click.argument("serial", metavar="[DEVICE]", required=False, envvar="ANDROID_SERIAL") +@click.option("--device", "-d", "device_option") +@click.option("--config", type=click.Path(exists=True, dir_okay=False)) +@click.option("--path", help="Path to a local Mobilerun Portal APK.") +@click.option("--portal-version", "-pv", help="Specific Portal version to install.") @click.option( "--latest", is_flag=True, - help="Install latest Portal instead of compatible version", - default=False, -) -@click.option( - "--debug", is_flag=True, help="Enable verbose debug logging", default=False + help="Install latest Portal instead of compatible version.", ) -@device_command -@coro +@click.option("--debug", is_flag=True, help="Enable verbose debug logging") +@run_command async def setup( - target: DeviceTarget, + run: AsyncMobilerun, + serial: str | None, + device_option: str | None, + config: str | None, path: str | None, portal_version: str | None, latest: bool, debug: bool, ) -> None: - """Install and enable the Mobilerun Portal on a device.""" - if target.kind != "android": - raise click.ClickException( - "device setup currently supports Android targets only." + """Install and enable the Mobilerun Portal on an Android device over ADB.""" + if sum((path is not None, portal_version is not None, latest)) > 1: + raise click.UsageError( + "Choose at most one of --path, --portal-version, or --latest." ) + serial = ( + serial_or_option(serial, device_option) + or ConfigLoader.load(config).device.serial + ) + if not serial or classify_target(serial) != "android": + raise click.ClickException("device setup requires an Android ADB serial.") try: - device_obj = await adb.device(target.identifier) - if not device_obj: - raise DeviceNotFound(f"Could not get device object for {target}") - - if path: - console.print(f"[bold blue]Using provided APK:[/] {path}") - elif latest: - console.print("[bold blue]Downloading latest Portal APK...[/]") - - result = await install_portal( - device_obj, + result = await run.local.setup_portal( + serial, + client_version=__version__, apk_path=path, - version=portal_version, + portal_version=portal_version, latest=latest, - debug=debug, ) - if result.apk_source: - console.print( - f"[bold blue]Step 1/2: Installing APK:[/] {result.apk_source}" - ) - console.print("[bold green]Installation successful![/]") - console.print("[bold blue]Step 2/2: Enabling accessibility service[/]") - if result.accessibility_enabled: - console.print("[green]Accessibility service enabled successfully![/]") - console.print( - "\n[bold green]Setup complete![/] The Mobilerun Portal is now installed and ready to use." - ) - elif result.needs_manual_accessibility: - console.print( - f"[yellow]Could not automatically enable accessibility service: {result.accessibility_error or 'the service did not respond in time'}[/]" - ) - console.print( - "[yellow]Opening accessibility settings for manual configuration...[/]" - ) - console.print( - "\n[yellow]Please complete the following steps on your device:[/]" - ) - console.print( - f"1. Find [bold]{PORTAL_PACKAGE_NAME}[/] in the accessibility services list" - ) - console.print("2. Tap on the service name") - console.print("3. Toggle the switch to [bold]ON[/] to enable the service") - console.print("4. Accept any permission dialogs that appear") - console.print( - "\n[bold green]APK installation complete![/] Please manually enable the accessibility service using the steps above." - ) - except (PortalApkNotFound, PortalInstallFailed, DeviceNotFound) as exc: - if isinstance(exc, PortalApkNotFound): - console.print(f"[bold red]Error:[/] {exc}") - elif isinstance(exc, PortalInstallFailed): - if not (path or portal_version or latest) and str(exc) == "Setup failed": - console.print( - "[bold red]Setup failed.[/] Run 'mobilerun doctor' for diagnostics." - ) - else: - if exc.apk_path: - console.print( - f"[bold blue]Step 1/2: Installing APK:[/] {exc.apk_path}" - ) - console.print(f"[bold red]Installation failed:[/] {exc}") - else: - console.print(f"[bold red]Error:[/] {exc}") - if debug: - traceback.print_exc() - raise click.exceptions.Exit(1) from exc + except HitlDenied as exc: + raise click.ClickException(exc.reason or "Portal setup denied.") from exc except Exception as exc: render_error(exc, debug=debug) raise click.exceptions.Exit(1) from exc - if not result.installed or not result.accessibility_enabled: + + if result.success: + render.success( + "Setup complete! The Mobilerun Portal is now installed and ready to use." + ) + elif result.facts.get("manual_needed"): + package = result.facts.get("package", "Mobilerun Portal") + render.warn( + f"APK installation complete! Please manually enable {package} in Android accessibility settings." + ) raise click.exceptions.Exit(1) + else: + raise click.ClickException( + "Setup failed. Run 'mobilerun doctor' for diagnostics." + ) diff --git a/mobilerun/cli/devices/utils/README.md b/mobilerun/cli/devices/utils/README.md new file mode 100644 index 000000000..44af64ba5 --- /dev/null +++ b/mobilerun/cli/devices/utils/README.md @@ -0,0 +1,15 @@ +# Device CLI utilities + +Shared device command helpers. For example, `display_label()` shows a Portal +URL's origin without its credentials, path, query, or fragment. + +| File or folder | Purpose | +| --- | --- | +| `approval.py` | Ask for core mutation approval, or deny non-interactively without `--yes` | +| `coordinates.py` | Prompt for a coordinate when omitted | +| `labels.py` | Format a device ID safely for display | +| `targets.py` | Classify device targets and validate ADB addresses | +| [connection/](connection/README.md) | Discover and connect to devices; save the default | +| [prompts/](prompts/README.md) | Ask for command operands and transfer sources | + +See the [device commands](../README.md). diff --git a/mobilerun/cli/devices/utils/__init__.py b/mobilerun/cli/devices/utils/__init__.py new file mode 100644 index 000000000..635b7bd85 --- /dev/null +++ b/mobilerun/cli/devices/utils/__init__.py @@ -0,0 +1 @@ +"""Shared device CLI utilities.""" diff --git a/mobilerun/cli/devices/utils/approval.py b/mobilerun/cli/devices/utils/approval.py new file mode 100644 index 000000000..9d3debd60 --- /dev/null +++ b/mobilerun/cli/devices/utils/approval.py @@ -0,0 +1,36 @@ +"""Core mutation approval for interactive and automated CLI commands.""" + +from collections.abc import Awaitable, Callable +from typing import Any + +from mobilerun_core import HitlDenied + +from mobilerun.cli.base.menu import is_interactive +from mobilerun.cli.base.prompts import confirm_prompt_async + +AsyncHitlGate = Callable[[str, dict[str, Any]], Awaitable[bool]] + + +def cli_hitl_gate(*, yes: bool = False) -> AsyncHitlGate: + """Ask before core mutations without printing arbitrary request arguments.""" + + async def approve(action: str, args: dict[str, Any]) -> bool: + if yes: + return True + label = action.replace(".", " ").replace("_", " ") + if not is_interactive(): + raise HitlDenied( + action, f"{label} requires interactive approval; pass --yes" + ) + warning = ( + " (charges may apply)" + if action == "device.create_cloud" or args.get("may_be_charged") is True + else "" + ) + if action == "device.uninstall_app": + warning = " (app data will be deleted)" + if not await confirm_prompt_async(f"Approve {label}{warning}?", default=False): + raise HitlDenied(action, "not approved") + return True + + return approve diff --git a/mobilerun/cli/devices/utils/connection/README.md b/mobilerun/cli/devices/utils/connection/README.md new file mode 100644 index 000000000..f41668b2f --- /dev/null +++ b/mobilerun/cli/devices/utils/connection/README.md @@ -0,0 +1,13 @@ +# Device discovery and connection + +`discover_devices()` fetches descriptors for listings and pickers without +connecting or creating resources. Pickers can include configured Portal +routes. They retain the selected backend when connecting. + +| File | Purpose | +| --- | --- | +| `default.py` | Resolve explicit, environment, and saved targets; save or clear the default | +| `device.py` | Pick a device and connect using its backend | +| `discovery.py` | List Android ADB and authenticated cloud inventory | + +See [device CLI utilities](../README.md). diff --git a/mobilerun/cli/devices/utils/connection/__init__.py b/mobilerun/cli/devices/utils/connection/__init__.py new file mode 100644 index 000000000..1ebe02c07 --- /dev/null +++ b/mobilerun/cli/devices/utils/connection/__init__.py @@ -0,0 +1 @@ +"""Device inventory and connection helpers.""" diff --git a/mobilerun/cli/devices/utils/connection/default.py b/mobilerun/cli/devices/utils/connection/default.py new file mode 100644 index 000000000..29235007a --- /dev/null +++ b/mobilerun/cli/devices/utils/connection/default.py @@ -0,0 +1,24 @@ +"""Read and update the saved default without discarding other config keys.""" + +import os + +from mobilerun.config.loader import ConfigLoader +from mobilerun.config.user_config import DeviceConfig + + +def device_target( + explicit: str | None, config: DeviceConfig, kind: str | None = None +) -> tuple[str | None, str | None]: + """Resolve a target before interactive discovery, retaining an Android env hint.""" + if explicit: + return explicit, kind + if kind in (None, "android") and ( + serial := os.environ.get("ANDROID_SERIAL", "").strip() + ): + return serial, "android" + return config.serial, kind + + +def save_default_device(serial: str | None) -> None: + """Persist the selected device without replacing other settings.""" + ConfigLoader.update(lambda config: setattr(config.device, "serial", serial)) diff --git a/mobilerun/cli/devices/utils/connection/device.py b/mobilerun/cli/devices/utils/connection/device.py new file mode 100644 index 000000000..08f7dc653 --- /dev/null +++ b/mobilerun/cli/devices/utils/connection/device.py @@ -0,0 +1,112 @@ +"""Choose a ready device and attach core to the selected target.""" + +import click +from mobilerun_core import AsyncDevice, AsyncMobilerun, BackendKind, DeviceDescriptor + +from mobilerun.cli.base.prompts import SelectChoice, select_prompt_async +from mobilerun.cli.devices.utils.connection.discovery import discover_devices +from mobilerun.cli.devices.utils.labels import display_label +from mobilerun.cli.devices.utils.targets import classify_target +from mobilerun.config.user_config import DeviceConfig + +_ANDROID = {"local-android-adb", "local-android-http"} + + +async def pick_device(run: AsyncMobilerun, kind: str | None) -> DeviceDescriptor: + """Select an existing device, preserving its backend.""" + if kind == "remote": + raise click.UsageError("Pass a URL with --remote.") + entries = [] + for info in await discover_devices( + run=run, + local=kind != "cloud", + cloud=kind in (None, "cloud"), + include_portal=True, + strict=kind == "cloud", + ): + backend = info.backend + if ( + backend in ("cloud", "local-android-adb") + and not info.ready + and kind != "cloud" + ): + continue + if kind == "ios" and backend != "local-ios-http": + continue + if kind == "android" and backend not in _ANDROID: + continue + entries.append(info) + if kind is None: + # Preserve the order of core's combined inventory. + entries.sort(key=lambda info: info.backend != "cloud") + if not entries: + raise click.ClickException( + "No devices found. Pass a DEVICE or run `mobilerun device setup`." + ) + if len(entries) == 1: + click.echo(f"Using {display_label(entries[0].device_id)}", err=True) + return entries[0] + # Index choices so equal public IDs (e.g. two backends on one host) stay distinct. + choices = [ + SelectChoice( + str(i), f"{display_label(info.device_id)} ({info.name or info.backend})" + ) + for i, info in enumerate(entries) + ] + try: + picked = await select_prompt_async("Select a device", choices) + except (KeyboardInterrupt, EOFError): + raise click.exceptions.Exit(130) from None + if picked is None: + raise click.exceptions.Exit(0) + return entries[int(picked)] + + +async def connect_device( + run: AsyncMobilerun, + identifier: str, + kind: str | None, + config: DeviceConfig, + discovered: BackendKind | None, +) -> AsyncDevice: + """Connect using the selected backend and applicable device config.""" + target_kind = classify_target(identifier) + is_url = target_kind == "http" + if kind is None and discovered is None and is_url and identifier == config.serial: + kind = ( + "remote" if config.control_backend == "visual-remote" else config.platform + ) + backend = discovered + if kind == "remote": + return await run.connect( + config.device_id, backend="visual-remote", url=identifier + ) + if kind == "ios": + backend = "local-ios-http" + elif kind == "android" and backend is None: + backend = "local-android-http" if is_url else "local-android-adb" + elif kind == "cloud": + backend = "cloud" + elif backend is None and target_kind == "android": + backend = "local-android-adb" + if backend in ("local-ios-http", "local-android-http"): + platform = "ios" if backend == "local-ios-http" else "android" + # The public ID of a discovered Portal endpoint omits dial credentials. + # Discovery reads core's configured URL; let core read the same URL back. + return await run.connect( + backend=backend, + url=None if discovered else identifier, + token=config.resolve_auth_token(platform), + ) + if backend == "local-android-adb": + return await run.connect( + identifier, + backend=backend, + portal_mode=config.portal_mode, + use_tcp=config.use_tcp, + ) + if is_url and backend is None: + raise click.UsageError( + "URL target: add --ios, --android (Portal HTTP), or --remote." + ) + return await run.connect(identifier, backend=backend) diff --git a/mobilerun/cli/devices/utils/connection/discovery.py b/mobilerun/cli/devices/utils/connection/discovery.py new file mode 100644 index 000000000..a3bdebf59 --- /dev/null +++ b/mobilerun/cli/devices/utils/connection/discovery.py @@ -0,0 +1,86 @@ +"""Discover existing local and cloud devices without creating resources.""" + +import logging +from contextlib import nullcontext + +import click +from mobilerun_core import AsyncMobilerun, CloudLifecycleError, DeviceDescriptor + +from mobilerun.cli.base.errors import safe_error_message +from mobilerun.cli.devices.base.selection import open_client +from mobilerun.clients.local.login_store import LoginStore +from mobilerun.errors.base import CredentialError + +logger = logging.getLogger(__name__) + + +async def discover_devices( + *, + local: bool = True, + cloud: bool = True, + include_portal: bool = False, + base_url: str | None = None, + strict: bool = False, + run: AsyncMobilerun | None = None, +) -> list[DeviceDescriptor]: + """Fetch descriptors without dialing devices; strict mode raises cloud errors.""" + devices: list[DeviceDescriptor] = [] + async with ( + nullcontext(run) if run is not None else open_client(base_url=base_url) + ) as owner: + if local: + try: + if include_portal: + # Core exposes configured Portal routes alongside ready ADB + # devices; raw ADB inventory includes offline transports. + handles = await owner.list_devices(scope="local") + inventory = [handle.info() for handle in handles] + else: + inventory = await owner.local.list_android_devices() + except Exception: + logger.warning("Local inventory unavailable.") + else: + devices.extend( + item + for item in inventory + if item.backend != "local-android-adb" + or ( + "://" not in item.device_id + and not item.device_id.startswith("//") + ) + ) + if not cloud: + return devices + try: + api_key = LoginStore.from_settings().resolve_api_key() + except CredentialError as exc: + if strict: + raise click.ClickException(str(exc)) from exc + click.echo(f"Warning: {exc}", err=True) + return devices + if not api_key and strict: + raise click.ClickException( + "No cloud API key found. Set MOBILERUN_API_KEY or run `mobilerun account login`." + ) + if api_key: + try: + items = await owner.list_cloud_devices() + except Exception as exc: + if strict: + if not isinstance(exc, CloudLifecycleError): + raise click.ClickException( + "Error listing cloud devices: offline or unavailable (use --debug for details)." + ) from exc + raise click.ClickException( + f"Error listing cloud devices: {safe_error_message(exc)}" + ) from exc + reason = ( + safe_error_message(exc) + if isinstance(exc, CloudLifecycleError) + else "use --debug for details" + ) + click.echo(f"Warning: Error listing cloud devices: {reason}", err=True) + logger.debug("Cloud discovery failure", exc_info=True) + else: + devices.extend(items) + return devices diff --git a/mobilerun/cli/devices/utils/coordinates.py b/mobilerun/cli/devices/utils/coordinates.py new file mode 100644 index 000000000..f8f2411fb --- /dev/null +++ b/mobilerun/cli/devices/utils/coordinates.py @@ -0,0 +1,10 @@ +import click + +from mobilerun.cli.devices.utils.prompts.pickers import require_text + + +async def require_coordinate(value: int | None, label: str) -> int: + """Read a missing coordinate after selecting the device.""" + if value is not None: + return value + return int(click.INT.convert(await require_text(None, label), None, None)) diff --git a/mobilerun/cli/devices/utils/labels.py b/mobilerun/cli/devices/utils/labels.py new file mode 100644 index 000000000..dbf240fb2 --- /dev/null +++ b/mobilerun/cli/devices/utils/labels.py @@ -0,0 +1,21 @@ +"""Device labels safe for terminal output.""" + +from urllib.parse import urlsplit + + +def display_label(identifier: str | None) -> str: + """Show a URL's origin without credentials, path, query, or fragment.""" + if identifier is None: + return "unknown device" + if "://" not in identifier and not identifier.startswith("//"): + return identifier + try: + parts = urlsplit(identifier) + except ValueError: + return "remote device" + host = parts.netloc.rsplit("@", 1)[-1] + return ( + f"{parts.scheme + ':' if parts.scheme else ''}//{host}" + if host + else "remote device" + ) diff --git a/mobilerun/cli/devices/utils/prompts/README.md b/mobilerun/cli/devices/utils/prompts/README.md new file mode 100644 index 000000000..6cdc1278a --- /dev/null +++ b/mobilerun/cli/devices/utils/prompts/README.md @@ -0,0 +1,11 @@ +# Device prompts + +Ask for missing command operands after selecting a device. For example, +`choose_app()` offers installed apps or manual package entry in a terminal. + +| File | Purpose | +| --- | --- | +| `pickers.py` | Choose a value or installed app; request required text | +| `source.py` | Choose a local file or workspace resource for a transfer | + +See [device CLI utilities](../README.md). diff --git a/mobilerun/cli/devices/utils/prompts/__init__.py b/mobilerun/cli/devices/utils/prompts/__init__.py new file mode 100644 index 000000000..a7f5cc5bb --- /dev/null +++ b/mobilerun/cli/devices/utils/prompts/__init__.py @@ -0,0 +1 @@ +"""Prompts for device command arguments.""" diff --git a/mobilerun/cli/devices/base/pickers.py b/mobilerun/cli/devices/utils/prompts/pickers.py similarity index 69% rename from mobilerun/cli/devices/base/pickers.py rename to mobilerun/cli/devices/utils/prompts/pickers.py index 2398d7c75..87f1933a6 100644 --- a/mobilerun/cli/devices/base/pickers.py +++ b/mobilerun/cli/devices/utils/prompts/pickers.py @@ -1,30 +1,16 @@ """Device-scoped choices, fetched only after opening the selected device.""" import click +from mobilerun_core import AsyncDevice from mobilerun.cli.base.menu import is_interactive from mobilerun.cli.base.prompts import ( SelectChoice, - select_prompt, select_prompt_async, - text_prompt, text_prompt_async, ) -def choose_value(value: str | None, label: str, choices: list[SelectChoice]) -> str: - if value is not None: - return value - if not is_interactive(): - raise click.UsageError(f"Missing argument '{label.upper()}'.") - selected = select_prompt( - label, [*choices, SelectChoice("__manual__", "Enter manually…")] - ) - if selected is None: - raise click.exceptions.Exit(0) - return text_prompt(label) if selected == "__manual__" else selected - - async def choose_value_async( value: str | None, label: str, choices: list[SelectChoice] ) -> str: @@ -40,7 +26,7 @@ async def choose_value_async( return await text_prompt_async(label) if selected == "__manual__" else selected -async def choose_app(device, package: str | None) -> str: +async def choose_app(device: AsyncDevice, package: str | None) -> str: if package is not None or not is_interactive(): return await choose_value_async(package, "package", []) try: @@ -48,9 +34,19 @@ async def choose_app(device, package: str | None) -> str: except Exception: click.echo("Could not load installed apps; enter a package manually.", err=True) return await choose_value_async(None, "package", []) - choices = [] - for app in apps: - key = app.get("package") or app.get("package_name") or app.get("packageName") - if key: - choices.append(SelectChoice(key, app.get("label") or key, key)) + choices = [ + SelectChoice(app.identity.app_id, app.name, app.identity.app_id) for app in apps + ] return await choose_value_async(None, "package", choices) + + +async def require_text(value: str | None, label: str) -> str: + """Prompt for omitted required text after the command selects a device.""" + if value is not None: + return value + if not is_interactive(): + raise click.UsageError(f"Missing argument '{label.upper()}'.") + value = (await text_prompt_async(label)).strip() + if not value: + raise click.exceptions.Exit(0) + return value diff --git a/mobilerun/cli/devices/utils/prompts/source.py b/mobilerun/cli/devices/utils/prompts/source.py new file mode 100644 index 000000000..03f51b64d --- /dev/null +++ b/mobilerun/cli/devices/utils/prompts/source.py @@ -0,0 +1,80 @@ +"""Shared source selection for device transfer commands.""" + +from collections.abc import Callable +from functools import wraps +from typing import Any + +import click + +from mobilerun.cli.base.menu import is_interactive +from mobilerun.cli.base.prompts import ( + SelectChoice, + select_prompt_async, + text_prompt_async, +) +from mobilerun.core.workspace import Workspace + + +def source_arguments( + path: str, reference: str +) -> Callable[[Callable[..., None]], Callable[..., None]]: + """Validate the explicit source before a device command opens its connection.""" + + def decorate(command: Callable[..., None]) -> Callable[..., None]: + @wraps(command) + def invoke(**kwargs: Any) -> None: + local, resource_id = kwargs[path], kwargs[reference] + if local and resource_id: + raise click.UsageError( + "Pass either a local path or a workspace ID, not both." + ) + if not local and not resource_id and not is_interactive(): + raise click.UsageError("Provide a local path or a workspace ID.") + command(**kwargs) + + return invoke + + return decorate + + +async def select_source_async( + local: str | None, resource_id: str | None, *, apps: bool +) -> tuple[str | None, str | None]: + """Prompt for a missing source after explicit arguments have been validated.""" + if not local and not resource_id: + choice = await select_prompt_async( + "Choose a source", + [ + SelectChoice("local", "Local file"), + SelectChoice("workspace", "Workspace"), + ], + ) + if choice == "local": + local = (await text_prompt_async("Local path")).strip() + if local: + local = str( + click.Path(exists=True, dir_okay=False).convert(local, None, None) + ) + elif choice == "workspace": + if apps: + choices = [ + SelectChoice( + item.resource_id, + item.name or item.identity.app_id, + item.resource_id, + ) + for item in await Workspace().list_apps() + ] + else: + choices = [ + SelectChoice(item.id, item.name, item.id) + for item in await Workspace().list_files() + ] + if not choices: + raise click.ClickException("No workspace items found.") + resource_id = await select_prompt_async("Select a workspace item", choices) + else: + raise click.Abort() + if not local and not resource_id: + raise click.UsageError("Provide a local path or a workspace ID.") + return local, resource_id diff --git a/mobilerun/cli/devices/utils/targets.py b/mobilerun/cli/devices/utils/targets.py new file mode 100644 index 000000000..16952e6da --- /dev/null +++ b/mobilerun/cli/devices/utils/targets.py @@ -0,0 +1,45 @@ +"""Device target routing and ADB network address rules.""" + +import re +from typing import Literal +from uuid import UUID + +import click +from click.core import ParameterSource + +_ADB_ADDRESS = r"(?:[A-Za-z0-9][A-Za-z0-9.-]*|\[[0-9A-Fa-f:]+\])" +_ADB_PORT = r":[0-9]{1,5}" + + +def classify_target(target: str) -> Literal["http", "android", "cloud"]: + """Distinguish HTTP endpoints, cloud UUIDs and Android serials.""" + if target.lower().startswith(("http://", "https://")): + return "http" + try: + UUID(target) + except ValueError: + return "android" + return "cloud" + + +def adb_tcp_address(target: str, *, default_port: int | None = None) -> str | None: + """Return a host:port address, allowing a bare host only with a default port.""" + if re.fullmatch(_ADB_ADDRESS + _ADB_PORT, target): + return target + if default_port is not None and re.fullmatch(_ADB_ADDRESS, target): + return f"{target}:{default_port}" + return None + + +def serial_or_option(serial: str | None, device_option: str | None) -> str | None: + """Prefer an explicit option over an environment serial, but reject conflicting arguments.""" + if ( + device_option + and serial != device_option + and click.get_current_context().get_parameter_source("serial") + is ParameterSource.COMMANDLINE + ): + raise click.UsageError( + "DEVICE and --device refer to different devices; choose one." + ) + return device_option or serial diff --git a/mobilerun/cli/doctor.py b/mobilerun/cli/doctor.py index 261b562e7..c9f3b545f 100644 --- a/mobilerun/cli/doctor.py +++ b/mobilerun/cli/doctor.py @@ -1,41 +1,28 @@ -import asyncio +"""CLI rendering and repair policy for core Android diagnostics.""" + +from collections.abc import Sequence import click -from async_adbutils import AdbDevice -from mobilerun_core_local.driver.android.portal import ( - PORTAL_PACKAGE_NAME, - check_portal_accessibility, - enable_portal_accessibility, -) +from mobilerun_core import AsyncMobilerun, DiagnosticResult, HitlDenied, LocalDevices from mobilerun.cli.base import render from mobilerun.cli.base.errors import render_error from mobilerun.cli.base.menu import is_interactive from mobilerun.cli.base.prompts import SelectChoice, select_prompt -from mobilerun.cli.base.run import coro -from mobilerun.cli.devices.base.options import DeviceTarget, device_command -from mobilerun.clients.portal.http import is_portal_http_url -from mobilerun.clients.portal.install import install_portal +from mobilerun.cli.devices.base.device import run_command +from mobilerun.cli.devices.utils.targets import classify_target from mobilerun.diagnostics.checks import ( - ReadyTcp, - check_accessibility, - check_adb, check_config, - check_content_provider, - check_device, - check_keyboard, - check_portal_installed, - check_portal_state, - check_portal_version, - check_screenshot, check_sdk_version, - check_tcp, + device_result, + portal_version_result, ) from mobilerun.diagnostics.results import CheckResult, Status +from mobilerun.version import __version__ class DoctorCommand(click.Command): - def parse_args(self, ctx, args): + def parse_args(self, ctx: click.Context, args: list[str]) -> list[str]: if not args and not ctx.resilient_parsing and is_interactive(): selected = select_prompt( "Doctor", @@ -52,33 +39,42 @@ def parse_args(self, ctx, args): @click.command(cls=DoctorCommand) +@click.argument("serial", metavar="[DEVICE]", required=False) @click.option("--debug/--no-debug", default=None, help="Enable verbose debug output") @click.option( "--fix", is_flag=True, help="Repair Portal installation and accessibility." ) -@device_command(optional=True) -@coro +@run_command async def doctor( - target: DeviceTarget, + run: AsyncMobilerun, + serial: str | None, debug: bool | None, fix: bool, ) -> None: """Check system health and diagnose issues.""" - serial = target.identifier if serial is None: render.warn( - "No device given: skipping device checks (use --android SERIAL ...)" + "No device given: skipping device checks (use `mobilerun doctor SERIAL`)." ) else: - if target.kind == "android" and is_portal_http_url(serial): + kind = classify_target(serial) + if kind == "http": render.warn( "doctor: device checks for Portal HTTP targets aren't supported yet; ran local checks" ) serial = None - elif target.kind != "android": + elif kind == "cloud": render.warn("doctor: device checks support Android only; ran local checks") serial = None - await run_doctor(serial, debug if debug is not None else False, fix=fix) + try: + await run_doctor(run.local, serial, bool(debug), fix=fix) + except HitlDenied as exc: + raise click.ClickException(exc.reason or "Portal repair denied.") from exc + except click.exceptions.Exit: + raise + except Exception as exc: + render_error(exc, debug=bool(debug)) + raise click.exceptions.Exit(1) from exc def _print_result(result: CheckResult, debug: bool = False) -> None: @@ -92,175 +88,141 @@ def _print_result(result: CheckResult, debug: bool = False) -> None: render.kv([(" Detail", result.detail)]) -# ── Auto-fix Functions ─────────────────────────────────────────── - - -async def fix_enable_accessibility(device: AdbDevice, debug: bool) -> bool: - """Enable accessibility service. Returns True on success.""" - render.kv([("Action", "Enabling accessibility service")]) - try: - await enable_portal_accessibility(device) - # Verify - enabled = await check_portal_accessibility(device, debug=debug) - if enabled: - render.success("Accessibility enabled") - return True - else: - render.warn("Auto-enable may have failed; opening settings") - await device.shell("am start -a android.settings.ACCESSIBILITY_SETTINGS") - render.warn(f"Please enable {PORTAL_PACKAGE_NAME} manually") - return False - except Exception as e: - render_error(e, debug=debug) - try: - await device.shell("am start -a android.settings.ACCESSIBILITY_SETTINGS") - render.warn(f"Please enable {PORTAL_PACKAGE_NAME} manually") - except Exception: - pass - return False - - -# ── Orchestrator ───────────────────────────────────────────────── - - async def run_doctor( + local: LocalDevices, device_serial: str | None = None, debug: bool = False, *, fix: bool = False, ) -> None: - """Run all doctor checks and auto-fix where possible.""" - debug = debug or False - + """Report core diagnostics and request repairs only when explicitly asked.""" render.kv([("Mobilerun Doctor", "system health")]) - results: list[CheckResult] = [] - # 1. SDK Version - r = await check_sdk_version(debug) - _print_result(r, debug) - results.append(r) - - # 2. Config - r_config, config = await check_config(debug) - _print_result(r_config, debug) - results.append(r_config) - - # 3. ADB - r = await check_adb(debug) - _print_result(r, debug) - results.append(r) - if r.status == Status.FAIL: - _print_summary(results) - return - - if device_serial is None: + def record(result: CheckResult) -> None: + _print_result(result, debug) + results.append(result) + + async def diagnose( + *names: str, allow_changes: bool = False + ) -> dict[str, DiagnosticResult]: + checks = await local.diagnose_android( + device_serial, + client_version=__version__, + checks=names, + allow_changes=allow_changes, + ) + if "ADB" not in names: + failure = next( + ( + check + for check in checks + if check.check == "ADB" and check.status == "fail" + ), + None, + ) + if failure is not None: + record(device_result(failure, device_serial)) + _print_summary(results) + return {check.check: check for check in checks} + + def record_probes( + names: Sequence[str], diagnostics: dict[str, DiagnosticResult] + ) -> None: + tcp_check = diagnostics.get("TCP Mode") + for name in names: + check = diagnostics.get(name) + if check is None: + continue + if name in ("State (tcp)", "Screenshot (tcp)") and ( + tcp_check is None or tcp_check.status != "pass" + ): + continue + if name.startswith("Screenshot"): + state = diagnostics.get(name.replace("Screenshot", "State", 1)) + if state is None or state.status != "pass": + continue + record(device_result(check, device_serial)) + + record(await check_sdk_version()) + record(await check_config()) + preflight = ( + await diagnose("ADB", "Device", "Portal Installed") + if device_serial + else await diagnose("ADB") + ) + adb = device_result(preflight["ADB"], device_serial) + record(adb) + if adb.status is Status.FAIL or device_serial is None: _print_summary(results) return - # 5. Device - r_device, device = await check_device(device_serial, debug) - _print_result(r_device, debug) - results.append(r_device) - if device is None: + device = device_result(preflight["Device"], device_serial) + record(device) + if device.status is Status.FAIL: render.warn("Skipping device-dependent checks (no device)") _print_summary(results) return - # 6. Portal Installed - r_portal, is_installed = await check_portal_installed(device, debug) - _print_result(r_portal, debug) - if not is_installed and fix: - # Auto-fix: run setup - await install_portal(device, debug=debug) - render.success( - "Setup complete! The Mobilerun Portal is now installed and ready to use." + installed = preflight["Portal Installed"] + if installed.facts.get("installed") is False and fix: + _print_result(device_result(installed, device_serial), debug) + setup = await local.setup_portal(device_serial, client_version=__version__) + if setup.success: + render.success( + "Setup complete! The Mobilerun Portal is now installed and ready to use." + ) + installed = (await diagnose("Portal Installed")).get( + "Portal Installed", installed ) - # Re-check - r_portal, is_installed = await check_portal_installed(device, debug) - if not is_installed: - results.append(r_portal) - _print_summary(results) - return - results.append(r_portal) - if not is_installed: + record(device_result(installed, device_serial)) + if installed.status != "pass": _print_summary(results) return - # 7. Portal Version - r_version, installed_ver, _, _ = await check_portal_version(device, debug) - _print_result(r_version, debug) - if fix and r_version.status == Status.WARN and installed_ver: - # Auto-fix: run setup to install compatible version - render.kv([("Action", "Updating portal")]) - await install_portal(device, debug=debug, in_place=True) - render.success( - "Setup complete! The Mobilerun Portal is now installed and ready to use." - ) - # Wait for portal service to initialize after install - render.kv([("Action", "Waiting for portal to start")]) - await asyncio.sleep(3) - # Re-check - r_version, _, _, _ = await check_portal_version(device, debug) - if r_version.status == Status.PASS: - render.success("Portal updated") - else: - render.warn("Update may not have resolved the version mismatch") - results.append(r_version) - - # 8. Accessibility - r_a11y, a11y_enabled = await check_accessibility(device, debug) - if not a11y_enabled: - _print_result(r_a11y, debug) - # Auto-fix: enable accessibility - success = await fix_enable_accessibility(device, debug) if fix else False - if success: - r_a11y = CheckResult("Accessibility", Status.PASS, "enabled (auto-fixed)") - _print_result(r_a11y, debug) + maintenance = await diagnose("Portal Version", "Accessibility") + if version_check := maintenance.get("Portal Version"): + version, older = await portal_version_result(local, version_check) + if fix and older: + _print_result(version, debug) + render.kv([("Action", "Updating portal")]) + setup = await local.setup_portal( + device_serial, client_version=__version__, uninstall=False + ) + refreshed = await diagnose("Portal Version", "Accessibility") + if new_version := refreshed.get("Portal Version"): + version, _ = await portal_version_result(local, new_version) + maintenance.update(refreshed) + if setup.success and version.status is Status.PASS: + render.success("Portal updated") + else: + render.warn("Update may not have resolved the version mismatch") + record(version) + if accessibility_check := maintenance.get("Accessibility"): + accessibility = device_result(accessibility_check, device_serial) + if fix and accessibility.status is Status.FAIL: + _print_result(accessibility, debug) + render.kv([("Action", "Enabling accessibility service")]) + enabled = await local.enable_portal_accessibility(device_serial) + if enabled: + accessibility = CheckResult( + "Accessibility", Status.PASS, "enabled (auto-fixed)" + ) + else: + render.warn( + "Please enable Mobilerun Portal manually in Android accessibility settings" + ) + record(accessibility) + + content = ("Content Provider", "State (content)", "Screenshot (content)") + tcp = ("TCP Mode", "State (tcp)", "Screenshot (tcp)") + if fix: + record_probes(content, await diagnose(*content)) + record_probes(tcp, await diagnose(*tcp, allow_changes=True)) + record_probes(("Keyboard",), await diagnose("Keyboard")) else: - _print_result(r_a11y, debug) - results.append(r_a11y) - - # 9. Content Provider — connectivity, state, screenshot - r = await check_content_provider(device, debug) - _print_result(r, debug) - results.append(r) - - r_cp_state, cp_portal = await check_portal_state(device, debug) - r_cp_state.name = "State (content)" - _print_result(r_cp_state, debug) - results.append(r_cp_state) - - if cp_portal and r_cp_state.status == Status.PASS: - r = await check_screenshot(cp_portal, debug) - r.name = "Screenshot (content)" - _print_result(r, debug) - results.append(r) - - # 10. TCP — connectivity, state, screenshot - r = await check_tcp(device, debug, fix=fix) - _print_result(r, debug) - results.append(r) - - if isinstance(r, ReadyTcp): - r_tcp_state, tcp_portal = await check_portal_state( - device, debug, tcp_portal=r.portal - ) - r_tcp_state.name = "State (tcp)" - _print_result(r_tcp_state, debug) - results.append(r_tcp_state) - - if tcp_portal and r_tcp_state.status == Status.PASS: - r = await check_screenshot(tcp_portal, debug) - r.name = "Screenshot (tcp)" - _print_result(r, debug) - results.append(r) - - # 12. Keyboard - r = await check_keyboard(device, debug) - _print_result(r, debug) - results.append(r) - + names = (*content, *tcp, "Keyboard") + record_probes(names, await diagnose(*names)) _print_summary(results) diff --git a/mobilerun/cli/mailbox/README.md b/mobilerun/cli/mailbox/README.md index 9e40272be..35954f763 100644 --- a/mobilerun/cli/mailbox/README.md +++ b/mobilerun/cli/mailbox/README.md @@ -23,7 +23,8 @@ MAILBOX` waits for a verification code. Create, status and release support `--js `mailbox messages MAILBOX` lists received emails, and `--json` returns the full message summaries. The API reports whether a message contains an OTP, but its -history response does not include the code itself. +history response does not include the code itself. Both commands operate on the +mailbox ID without connecting a phone. ## Files diff --git a/mobilerun/cli/mailbox/group.py b/mobilerun/cli/mailbox/group.py index b45bb5c25..bd2e9e8e9 100644 --- a/mobilerun/cli/mailbox/group.py +++ b/mobilerun/cli/mailbox/group.py @@ -14,10 +14,9 @@ from mobilerun.cli.base.cleanup import cleanup from mobilerun.cli.base.menu import MenuGroup, PromptingArgument from mobilerun.cli.base.run import coro -from mobilerun.clients.cloud import mailboxes as cloud_mailboxes -from mobilerun.clients.cloud.mailboxes import list_mailboxes +from mobilerun.clients.cloud.mailboxes import Mailboxes +from mobilerun.core.extensions import ToolInvocationError from mobilerun.core.mailbox import CloudMailbox as Mailbox -from mobilerun.errors import ExtensionActionError from mobilerun.errors.base import MobilerunError from mobilerun.models.billing import Billing @@ -35,7 +34,7 @@ def mailbox() -> None: @billing_option @coro async def mailbox_messages(mailbox_id: str, as_json: bool, billing: str) -> None: - items = await cloud_mailboxes.messages(mailbox_id, billing=Billing(billing)) + items = await Mailbox(mailbox_id, billing=Billing(billing)).messages() entries = [item.model_dump(mode="json") for item in items] if as_json: click.echo(json.dumps(entries, ensure_ascii=False)) @@ -65,7 +64,7 @@ async def mailbox_messages(mailbox_id: str, as_json: bool, billing: str) -> None @billing_option @coro async def mailbox_status(mailbox_id: str, as_json: bool, billing: str) -> None: - data = (await cloud_mailboxes.retrieve(mailbox_id, billing=Billing(billing))).data + data = (await Mailboxes(billing=Billing(billing)).retrieve(mailbox_id)).data entry = {"id": data.id, "status": data.status, "address": data.address} if as_json: click.echo(json.dumps(entry)) @@ -86,7 +85,7 @@ async def mailbox_status(mailbox_id: str, as_json: bool, billing: str) -> None: @billing_option @coro async def mailbox_list(billing: str, as_json: bool) -> None: - items = await list_mailboxes(billing=Billing(billing)) + items = await Mailboxes(billing=Billing(billing)).list() entries = [ {"id": item.id, "address": item.address, "status": item.status} for item in items @@ -145,7 +144,7 @@ async def mailbox_create( confirm_paid=None if plan == "included" else "Create mailbox", ) try: - data = (await cloud_mailboxes.retrieve(item.id, billing=mode)).data + data = (await Mailboxes(billing=mode).retrieve(item.id)).data except Exception as exc: reason = str(exc) if isinstance(exc, MobilerunError) else type(exc).__name__ click.echo(f"{item.id} created; details unavailable ({reason})", err=True) @@ -229,17 +228,8 @@ async def mailbox_code( code = await Mailbox(mailbox_id, billing=Billing(billing)).wait_for_code( sender=sender, timeout=timeout ) - except (TimeoutError, ExtensionActionError) as exc: - if isinstance(exc, ExtensionActionError) and exc.cause_type != "TimeoutError": - raise - try: - data = ( - await cloud_mailboxes.retrieve(mailbox_id, billing=Billing(billing)) - ).data - address = data.address or mailbox_id - except Exception: - address = mailbox_id + except (TimeoutError, ToolInvocationError): raise click.ClickException( - f"Timed out waiting for email on {address} after {timeout:g}s (sender: {sender or 'any'}). Retry with a longer --timeout." - ) from exc + "Could not read an email verification code. Check the mailbox and sender, or use a longer --timeout." + ) from None click.echo(code) diff --git a/mobilerun/cli/phone_number/README.md b/mobilerun/cli/phone_number/README.md index 5947ceac9..e33d1ad65 100644 --- a/mobilerun/cli/phone_number/README.md +++ b/mobilerun/cli/phone_number/README.md @@ -44,3 +44,5 @@ for a verification code. Create, status, release, messages and countries support See the [CLI overview](../README.md). `number release ID...` and `number unbind ID...` accept multiple IDs, confirm once, and return arrays of per-ID results with `--json`. Use `--yes` in automation. +`number bind` and `number unbind` change the server attachment without opening a +phone UI connection. `number bind` won't displace a different number. diff --git a/mobilerun/cli/phone_number/group.py b/mobilerun/cli/phone_number/group.py index 0e8241cbf..4dc07a5ca 100644 --- a/mobilerun/cli/phone_number/group.py +++ b/mobilerun/cli/phone_number/group.py @@ -24,20 +24,20 @@ select_prompt_async as select_prompt, ) from mobilerun.cli.base.run import coro -from mobilerun.clients.cloud import devices -from mobilerun.clients.cloud import numbers as cloud_numbers -from mobilerun.clients.cloud.billing import billing_prompt_is_interactive from mobilerun.clients.cloud.client import cloud_client -from mobilerun.clients.cloud.numbers import list_numbers +from mobilerun.clients.cloud.numbers import Numbers from mobilerun.config.settings import get_settings +from mobilerun.core.extensions import ToolInvocationError from mobilerun.core.phone_number import CloudPhoneNumber as PhoneNumber from mobilerun.errors import ( CloudAuthenticationError, CloudPermissionDenied, - ExtensionActionError, + ExtensionNotSupported, ) from mobilerun.errors.base import MobilerunError +from mobilerun.errors.cloud import NumberAttachmentConflict from mobilerun.models.billing import Billing +from mobilerun.utils.terminal import can_prompt @click.group(cls=MenuGroup) @@ -85,7 +85,7 @@ async def lookup(country: str) -> int: @billing_option @coro async def number_messages(number_id: str, as_json: bool, billing: str) -> None: - items = await cloud_numbers.messages(number_id, billing=Billing(billing)) + items = await Numbers(billing=billing).messages(number_id) entries = [item.model_dump(mode="json") for item in items] if as_json: click.echo(json.dumps(entries, ensure_ascii=False)) @@ -114,7 +114,7 @@ async def number_messages(number_id: str, as_json: bool, billing: str) -> None: @billing_option @coro async def number_countries(as_json: bool, billing: str) -> None: - result = await cloud_numbers.countries(billing=Billing(billing)) + result = await Numbers(billing=billing).countries() entries = [item.model_dump(mode="json") for item in result.data.items] if as_json: click.echo(json.dumps(entries, ensure_ascii=False)) @@ -147,12 +147,12 @@ async def number_send( number_id: str, to: str, text: str, yes: bool, billing: str ) -> None: await invoke_with_billing( - lambda mode: cloud_numbers.send(number_id, to, text, billing=mode), + lambda mode: PhoneNumber(number_id, billing=mode).send(to, text), Billing(billing), yes=yes, confirm_paid="Send SMS", ) - render.success(f"Sent SMS from {number_id} to {to}") + render.success(f"Sent SMS from {number_id}") @number.command("status", help="Show a number's lifecycle state and binding.") @@ -161,7 +161,7 @@ async def number_send( @billing_option @coro async def number_status(number_id: str, as_json: bool, billing: str) -> None: - data = (await cloud_numbers.retrieve(number_id, billing=Billing(billing))).data + data = (await Numbers(billing=billing).retrieve(number_id)).data entry = { "id": data.id, "status": data.state, @@ -188,7 +188,7 @@ async def number_status(number_id: str, as_json: bool, billing: str) -> None: @billing_option @coro async def number_list(billing: str, as_json: bool) -> None: - items = await list_numbers(billing=Billing(billing)) + items = await Numbers(billing=billing).list() entries = [ { "id": item.id, @@ -245,10 +245,9 @@ async def number_create( as_json: bool, ) -> None: # With --json the picker draws on stderr, so stdout carries only the result. - picker_is_interactive = billing_prompt_is_interactive if as_json else is_interactive - if not country and picker_is_interactive(): + if not country and (can_prompt(sys.stderr) if as_json else is_interactive()): # Show countries and included quota first: they decide whether this costs. - available = await cloud_numbers.countries(billing=Billing(billing)) + available = await Numbers(billing=billing).countries() in_stock = [item for item in available.data.items if item.in_stock] remaining = await _included_counts([item.country for item in in_stock], billing) choices = [ @@ -287,7 +286,7 @@ async def number_create( confirm_paid=None if plan == "included" else "Create number", ) try: - data = (await cloud_numbers.retrieve(item.id, billing=mode)).data + data = (await Numbers(billing=mode).retrieve(item.id)).data except Exception as exc: reason = str(exc) if isinstance(exc, MobilerunError) else type(exc).__name__ click.echo(f"{item.id} created; details unavailable ({reason})", err=True) @@ -312,7 +311,7 @@ async def number_create( @coro async def number_included(country: str | None, as_json: bool, billing: str) -> None: if country is None: - countries = (await cloud_numbers.countries(billing=Billing(billing))).data.items + countries = (await Numbers(billing=billing).countries()).data.items counts = await _included_counts([item.country for item in countries], billing) entries = [ {"country": item.country, "remaining": count} @@ -386,15 +385,12 @@ async def number_bind( ) -> None: mode = Billing(billing) async with cloud_client(billing=mode) as client: - info = await devices.capabilities(device_id, billing=mode, client=client) - if not info.capabilities.telephony: - raise click.ClickException("This device does not support cloud telephony") - current = await devices.number(device_id, billing=mode, client=client) - if current.binding is not None: - raise click.ClickException( - f"Device {device_id} already has a phone number; unbind it first." - ) - await devices.bind_number(device_id, number_id, billing=mode, client=client) + try: + await PhoneNumber( + number_id, billing=mode, client=client + ).attach_to_cloud_phone(device_id) + except (ExtensionNotSupported, NumberAttachmentConflict) as exc: + raise click.ClickException(str(exc)) from None if as_json: click.echo( json.dumps( @@ -426,16 +422,13 @@ async def number_bind( async def number_unbind( number_id: tuple[str, ...], as_json: bool, billing: str, yes: bool ) -> None: - async def unbind(item_id: str) -> str: + async def detach(item_id: str) -> str: mode = Billing(billing) async with cloud_client(billing=mode) as client: - result = await cloud_numbers.retrieve(item_id, billing=mode, client=client) - binding = result.data.device_binding - if binding is None: + if not await PhoneNumber(item_id, billing=mode, client=client).detach(): raise click.ClickException( f"Number {item_id} is not bound to a device." ) - await devices.unbind_number(binding.device_id, billing=mode, client=client) return "unbound" await cleanup( @@ -445,7 +438,7 @@ async def unbind(item_id: str) -> str: billing=billing, yes=yes, as_json=as_json, - operation=unbind, + operation=detach, ) @@ -468,17 +461,8 @@ async def number_sms( code = await PhoneNumber(number_id, billing=Billing(billing)).wait_for_code( sender=sender, timeout=timeout ) - except (TimeoutError, ExtensionActionError) as exc: - if isinstance(exc, ExtensionActionError) and exc.cause_type != "TimeoutError": - raise - try: - data = ( - await cloud_numbers.retrieve(number_id, billing=Billing(billing)) - ).data - address = data.phone_number or number_id - except Exception: - address = number_id + except (TimeoutError, ToolInvocationError): raise click.ClickException( - f"Timed out waiting for SMS on {address} after {timeout:g}s (sender: {sender or 'any'}). Retry with a longer --timeout." - ) from exc + "Could not read an SMS verification code. Check the number and sender, or use a longer --timeout." + ) from None click.echo(code) diff --git a/mobilerun/cli/plugins/group.py b/mobilerun/cli/plugins/group.py index 7d5109976..ddad13af9 100644 --- a/mobilerun/cli/plugins/group.py +++ b/mobilerun/cli/plugins/group.py @@ -7,6 +7,7 @@ from mobilerun.addons import plugins as registry from mobilerun.addons.settings import CLI_ENTRY_POINT_GROUP, OPERATOR_ENTRY_POINT_GROUP from mobilerun.cli.base.menu import MenuGroup +from mobilerun.core.operator.helpers.plugins import load_operator_entry @click.group(cls=MenuGroup) @@ -19,11 +20,18 @@ def plugins() -> None: @click.option("--json", "as_json", is_flag=True, help="Output machine-readable JSON.") def list_plugins(check: bool, as_json: bool) -> None: """List installed plugin entry points and their distributions.""" - from mobilerun.cli.app import reserved_command_names + from mobilerun.cli.app import ( + MACRO_HANDOFF_ENTRY_POINT_GROUP, + reserved_command_names, + ) reserved = reserved_command_names() rows = [] - for group in (CLI_ENTRY_POINT_GROUP, OPERATOR_ENTRY_POINT_GROUP): + for group in ( + CLI_ENTRY_POINT_GROUP, + OPERATOR_ENTRY_POINT_GROUP, + MACRO_HANDOFF_ENTRY_POINT_GROUP, + ): entries = sorted( registry.installed_entries(group), key=lambda ep: (ep.name, str(ep.value)), @@ -37,12 +45,13 @@ def list_plugins(check: bool, as_json: bool) -> None: status = "shadowed" elif check: try: - value = entry.load() - valid = ( - isinstance(value, click.Command) - if group == CLI_ENTRY_POINT_GROUP - else callable(value) - ) + if group == OPERATOR_ENTRY_POINT_GROUP: + load_operator_entry(entry) + valid = True + elif group == CLI_ENTRY_POINT_GROUP: + valid = isinstance(entry.load(), click.Command) + else: + valid = callable(entry.load()) status = "ok" if valid else "broken" except Exception: status = "broken" diff --git a/mobilerun/cli/proxy/README.md b/mobilerun/cli/proxy/README.md index 81b8bc790..6c5eadcc1 100644 --- a/mobilerun/cli/proxy/README.md +++ b/mobilerun/cli/proxy/README.md @@ -1,24 +1,31 @@ # proxy/ -CLI proxy commands and helpers. - -`proxy release ID` requires confirmation and releases provisioning; phones -using the proxy lose it. Pass `--yes` for automation and `--json` for JSON output. -`proxy buy` and `proxy bind` also support `--json`. Checkout and binding -progress are written to stderr. - -Proxy purchases can incur charges. `proxy buy` asks for confirmation before -purchasing in `paid` mode or retrying once with `paid` from a restricted mode. -Pass `--yes` to confirm without prompting; non-interactive purchases require it. +Manage account-level Connect products and bind a selected Connect ID to a cloud +phone. `proxy status ID` describes an account product, not a phone's binding. ```sh -mobilerun proxy list --json -mobilerun proxy list --included mobilerun proxy list --included --json +mobilerun proxy status PROXY_ID +mobilerun proxy bind PROXY_ID DEVICE_ID --yes +mobilerun proxy bind PROXY_ID DEVICE_ID --force --yes ``` -Choose `included` in the interactive `mobilerun proxy` menu, or run `mobilerun -proxy list --included`. Both show only existing proxies billed as included, not -remaining plan quota. The table displays billing mode when known. +`bind` selects the cloud phone first, then asks for a proxy if you left out its +ID. Core asks for approval even for the first bind (`--yes` in automation). +If the phone already has an active proxy, also confirm replacement +interactively or pass `--force`. +`--yes` alone never authorizes replacement. Closing the CLI's borrowed connection +leaves the phone and its proxy configured. + +`proxy buy --country de` **can incur charges** and requires consent. If +`--billing no_commerce` blocks a purchase, confirming the upgrade or passing +`--yes` authorizes one retry with paid billing. +`proxy release ID...` requires consent and can disconnect phones using those +proxies. Buy, bind, list, status and release support `--json`; progress goes to +stderr. `proxy included` is the menu shortcut for `proxy list --included`. + +| File | Purpose | +| --- | --- | +| `group.py` | Connect account commands and explicit device binding | -`proxy release ID...` accepts multiple IDs; `--json` returns an array of per-ID results, including failures. +See the [proxy extension](../../core/proxy/README.md). diff --git a/mobilerun/cli/proxy/group.py b/mobilerun/cli/proxy/group.py index b53489cd3..af4643045 100644 --- a/mobilerun/cli/proxy/group.py +++ b/mobilerun/cli/proxy/group.py @@ -2,27 +2,31 @@ import json import sys +from collections.abc import Awaitable from contextlib import redirect_stdout import click +from mobilerun_core import AsyncDevice, ConnectProxyRef, ProxyAlreadyConfigured from mobilerun.cli.base import menu, render from mobilerun.cli.base.billing import billing_option, invoke_with_billing from mobilerun.cli.base.checkout import complete_checkout -from mobilerun.cli.base.choices import cloud_devices, proxies +from mobilerun.cli.base.choices import proxies from mobilerun.cli.base.cleanup import cleanup from mobilerun.cli.base.menu import MenuGroup, PromptingArgument -from mobilerun.cli.base.prompts import confirm_prompt_async +from mobilerun.cli.base.prompts import SelectChoice, confirm_prompt_async from mobilerun.cli.base.run import coro -from mobilerun.clients.cloud.proxies import ( - buy_proxy, - cancel_proxy, - get_proxy, - list_proxies, +from mobilerun.cli.devices.base.device import device_command +from mobilerun.cli.devices.utils.labels import display_label +from mobilerun.cli.devices.utils.prompts.pickers import choose_value_async +from mobilerun.core.proxy import ( + get_connect_proxy, + list_connect_proxies, + purchase_connect_proxy, + release_connect_proxy, ) -from mobilerun.core.devices.cloud import CloudDevice -from mobilerun.core.proxy import CloudFixedProxy, UnmanagedProxyConflict from mobilerun.models.billing import Billing +from mobilerun.models.proxy import ProxyProduct, ProxyProductType @click.group(cls=MenuGroup) @@ -42,7 +46,7 @@ async def proxy_release( proxy_id: tuple[str, ...], yes: bool, as_json: bool, billing: str ) -> None: async def release(item_id: str) -> str: - await cancel_proxy(item_id, billing=Billing(billing)) + await release_connect_proxy(item_id, billing=Billing(billing)) return "released" await cleanup( @@ -61,58 +65,70 @@ async def release(item_id: str) -> str: ) -@proxy.command("bind", help="Bind an existing Connect proxy to a cloud phone.") -@click.option("--json", "as_json", is_flag=True) -@click.argument("proxy_id", cls=PromptingArgument, choices=proxies) -@click.argument( - "device_id", - cls=PromptingArgument, - prompt_label="Cloud device ID", - choices=cloud_devices, +class _BindCommand(click.Command): + def invoke(self, ctx: click.Context) -> object: + ctx.params["device_cloud"] = True + return super().invoke(ctx) + + +@proxy.command( + "bind", cls=_BindCommand, help="Bind an existing Connect proxy to a cloud phone." ) +@click.option("--json", "as_json", is_flag=True) +@click.argument("proxy_id", required=False) @click.option( "--force", is_flag=True, help="Explicitly replace the phone's current proxy." ) @billing_option -@coro +@device_command async def proxy_bind( - proxy_id: str, device_id: str, force: bool, billing: str, as_json: bool + proxy_id: str | None, device: AsyncDevice, force: bool, billing: str, as_json: bool ) -> None: - phone = CloudDevice(device_id=device_id, billing=Billing(billing)) - extension = CloudFixedProxy(proxy_id) - try: - click.echo(f"Binding proxy {proxy_id} to {device_id}…", err=True) - click.echo("Waiting for connection…", err=True) + # Binding an existing ID never buys capacity under any billing mode. + choices = [] + if proxy_id is None and menu.is_interactive(): try: - await extension.bind(phone, force=force) - except UnmanagedProxyConflict as exc: - if force or not menu.is_interactive(): - raise click.ClickException( - str(exc).replace("force=True", "--force") - ) from exc - with redirect_stdout(sys.stderr): - replace = await confirm_prompt_async( - f"{device_id} already has an active proxy. Replace it?", - default=False, + entries = [item async for item in list_connect_proxies()] + except Exception: + click.echo("Could not load proxies; enter a proxy ID manually.", err=True) + else: + entries.sort(key=lambda item: item.status != "active") + choices = [ + SelectChoice( + item.ref.id, item.ref.id, f"{item.country} · {item.status}" ) - if not replace: - click.echo("Cancelled.", err=True) - return - await extension.bind(phone, force=True) - status = await extension.status() - state = "connected" if status.connected else "disconnected" - if as_json: - click.echo( - json.dumps({"id": proxy_id, "status": state, "device_id": device_id}) + for item in entries + ] + proxy_id = await choose_value_async(proxy_id, "proxy ID", choices) + ref = ConnectProxyRef(proxy_id) + device_id = display_label(device.device_id) + click.echo(f"Binding proxy {proxy_id} to {device_id}…", err=True) + try: + await device.set_proxy(ref, replace=force) + except ProxyAlreadyConfigured: + if force or not menu.is_interactive(): + raise click.ClickException( + "This phone already has an active proxy; use --force to replace it." + ) from None + with redirect_stdout(sys.stderr): + replace = await confirm_prompt_async( + f"{device_id} already has an active proxy. Replace it?", + default=False, ) - elif status.connected: - render.success(f"Bound proxy {proxy_id} to {device_id}") - else: - render.warn(f"Proxy {proxy_id} is disconnected on {device_id}") - finally: - # Detach the local relationship while leaving the cloud phone's - # required proxy configured on the server. - await phone.close() + if not replace: + click.echo("Cancelled.", err=True) + return + await device.set_proxy(ref, replace=True) + status = await device.proxy_status() + state = "connected" if status.connected else "disconnected" + if as_json: + click.echo( + json.dumps({"id": proxy_id, "status": state, "device_id": device_id}) + ) + elif status.connected: + render.success(f"Bound proxy {proxy_id} to {device_id}") + else: + render.warn(f"Proxy {proxy_id} is disconnected on {device_id}") @proxy.command("list", help="List Connect proxies.") @@ -121,22 +137,18 @@ async def proxy_bind( @billing_option @coro async def proxy_list(billing: str, as_json: bool, included: bool) -> None: - page = 1 - entries = [] - while True: - result = await list_proxies( - billing=Billing(billing), page=page, page_size=100, included_only=included + entries = [ + item + async for item in list_connect_proxies( + billing=Billing(billing), included_only=included ) - entries.extend(result.items) - if not result.pagination.has_next: - break - page += 1 + ] if as_json: click.echo( json.dumps( [ { - "id": item.id, + "id": item.ref.id, "country": item.country, "status": item.status, "type": item.type, @@ -156,7 +168,7 @@ async def proxy_list(billing: str, as_json: bool, included: bool) -> None: render.table( [ [ - render.secondary(item.id), + render.secondary(item.ref.id), render.secondary(item.country), render.status(item.status), render.secondary(item.type), @@ -182,12 +194,12 @@ def proxy_included(ctx: click.Context, billing: str, as_json: bool) -> None: @billing_option @coro async def proxy_status(proxy_id: str, billing: str, as_json: bool) -> None: - result = await get_proxy(proxy_id, billing=Billing(billing)) + result = await get_connect_proxy(proxy_id, billing=Billing(billing)) if as_json: click.echo( json.dumps( { - "id": result.id, + "id": result.ref.id, "country": result.country, "status": result.status, "type": result.type, @@ -222,13 +234,13 @@ async def proxy_status(proxy_id: str, billing: str, as_json: bool) -> None: "proxy_type", type=click.Choice(["residential", "dedicated_residential", "mobile"]), default="residential", - help="Proxy network type. Use dedicated_residential for a fixed IP; pass the printed ID to CloudFixedProxy.", + help="Proxy network type. Use dedicated_residential for a fixed IP.", ) @billing_option @coro async def proxy_buy( country: str, - proxy_type: str, + proxy_type: ProxyProductType, billing: str, yes: bool, payment_timeout: float, @@ -236,23 +248,26 @@ async def proxy_buy( ) -> None: if proxy_type not in ("residential", "dedicated_residential", "mobile"): raise click.BadParameter("Invalid proxy type", param_hint="--type") - result, _ = await invoke_with_billing( - lambda mode: complete_checkout( - buy_proxy( + + def purchase(mode: Billing) -> Awaitable[ProxyProduct]: + return complete_checkout( + purchase_connect_proxy( country, - type=proxy_type, + proxy_type=proxy_type, billing=mode, checkout="browser", payment_timeout=payment_timeout, ) - ), - Billing(billing), - yes=yes, - confirm_paid="Buy Connect proxy", + ) + + result, _ = await invoke_with_billing( + purchase, Billing(billing), yes=yes, confirm_paid="Buy Connect proxy" ) if as_json: click.echo( - json.dumps({"id": result.id, "status": result.status, "country": country}) + json.dumps( + {"id": result.ref.id, "status": result.status, "country": country} + ) ) else: - render.success(f"Bought proxy {result.id} ({country})") + render.success(f"Bought proxy {result.ref.id} ({country})") diff --git a/mobilerun/cli/task/README.md b/mobilerun/cli/task/README.md new file mode 100644 index 000000000..4af1c5342 --- /dev/null +++ b/mobilerun/cli/task/README.md @@ -0,0 +1,22 @@ +# Cloud task CLI + +Inspect and stop existing Mobilerun Cloud tasks without the agent add-on. +Sign in with `mobilerun account login` or set `MOBILERUN_API_KEY` first. + +```sh +mobilerun task status TASK_ID --json +mobilerun task stop TASK_ID +mobilerun task stop TASK_ID --yes --json +``` + +`status` shows the current state and available results. `stop` asks for +confirmation in a terminal and requires `--yes` in automation. It reports +whether a stop was requested or the task was already finished. Both commands +support `--json` and do not make purchases. + +| File | Purpose | +| --- | --- | +| `__init__.py` | CLI package marker. | +| `group.py` | Command group, confirmation, and task output. | + +The commands use the bound `Tasks` adapter from the [cloud clients](../../clients/cloud/) and [CLI helpers](../base/). diff --git a/mobilerun/cli/task/__init__.py b/mobilerun/cli/task/__init__.py new file mode 100644 index 000000000..4892430e8 --- /dev/null +++ b/mobilerun/cli/task/__init__.py @@ -0,0 +1 @@ +"""Cloud task CLI commands.""" diff --git a/mobilerun/cli/task/group.py b/mobilerun/cli/task/group.py new file mode 100644 index 000000000..e64dcab8c --- /dev/null +++ b/mobilerun/cli/task/group.py @@ -0,0 +1,96 @@ +"""Inspect and stop existing Mobilerun Cloud tasks.""" + +import json +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager + +import click + +from mobilerun.cli.base import render +from mobilerun.cli.base.menu import MenuGroup +from mobilerun.cli.base.run import coro +from mobilerun.cli.base.safety import confirm_action_async +from mobilerun.clients.cloud import client as connection +from mobilerun.clients.cloud.tasks import Tasks +from mobilerun.errors.cloud import ( + CloudAPIError, + CloudAuthRequired, + CloudResourceNotFound, +) +from mobilerun.models.billing import Billing + + +@click.group(cls=MenuGroup) +def task() -> None: + """Inspect and stop cloud tasks.""" + + +@asynccontextmanager +async def _task_errors(task_id: str) -> AsyncIterator[None]: + try: + yield + except CloudResourceNotFound: + raise click.ClickException(f"Task not found: {task_id}") from None + except CloudAuthRequired: + raise click.ClickException( + "Not logged in (run `mobilerun account login`)." + ) from None + except CloudAPIError as exc: + # Transport errors are sanitized; do not show their raw SDK causes. + raise click.ClickException(str(exc)) from None + + +@task.command() +@click.argument("task_id") +@click.option("--json", "as_json", is_flag=True, help="Output JSON.") +@coro +async def status(task_id: str, as_json: bool) -> None: + """Show the current state and available results for TASK_ID.""" + async with _task_errors(task_id): + result = await Tasks(billing=Billing.NO_COMMERCE).status(task_id) + data = result.model_dump(mode="json", exclude_none=True) + if as_json: + click.echo(json.dumps(data)) + else: + render.kv( + ( + key.replace("_", " ").capitalize(), + ( + render.status(value) + if key in ("status", "state") + else render.relative_time(value) if key.endswith("_at") else value + ), + ) + for key, value in data.items() + ) + + +@task.command() +@click.argument("task_id") +@click.option("--yes", is_flag=True, help="Stop without prompting.") +@click.option("--json", "as_json", is_flag=True, help="Output JSON.") +@coro +async def stop(task_id: str, yes: bool, as_json: bool) -> None: + """Stop TASK_ID if it is still running.""" + await confirm_action_async( + "stop the task", "no commerce", "This stops the task.", yes=yes, err=as_json + ) + async with ( + _task_errors(task_id), + connection.cloud_client(billing=Billing.NO_COMMERCE) as client, + ): + tasks = Tasks(client=client, billing=Billing.NO_COMMERCE) + state = await tasks.status(task_id) + if state.status in {"completed", "failed", "cancelled"}: + if as_json: + click.echo(json.dumps({"task_id": task_id, "status": state.status})) + else: + click.echo(f"Task {task_id} is already finished ({state.status}).") + return + result = await tasks.stop(task_id) + if not result.cancelled: + raise click.ClickException(f"Task {task_id} was not stopped; check its status.") + if as_json: + click.echo(json.dumps({"task_id": task_id, "cancelled": True})) + else: + render.success(f"Stop requested for task {task_id}") diff --git a/mobilerun/cli/webhook/group.py b/mobilerun/cli/webhook/group.py index 4aa3029e3..a60cb4335 100644 --- a/mobilerun/cli/webhook/group.py +++ b/mobilerun/cli/webhook/group.py @@ -15,10 +15,10 @@ from mobilerun.core.webhooks import ( DEFAULT_WEBHOOK_EVENT, CloudWebhooks, - WebhookEndpoint, validate_webhook_url, ) from mobilerun.errors.cloud import CloudConflict, CloudValidationError +from mobilerun.models import WebhookEndpoint from mobilerun.utils.redaction import mask_url diff --git a/mobilerun/cli/workspace/README.md b/mobilerun/cli/workspace/README.md index a2c7bc6f2..43e900f9c 100644 --- a/mobilerun/cli/workspace/README.md +++ b/mobilerun/cli/workspace/README.md @@ -17,3 +17,7 @@ files. File download and removal, and app upload and removal, also accept `--jso Progress and confirmations are written to stderr. `workspace files rm ID...` (also `remove`) and `workspace apps remove ID...` accept multiple IDs and return arrays of per-ID results with `--json`. + +| File | Purpose | +| --- | --- | +| `group.py` | Workspace app and file commands. | diff --git a/mobilerun/cli/workspace/group.py b/mobilerun/cli/workspace/group.py index 9666eaef2..9a70738e0 100644 --- a/mobilerun/cli/workspace/group.py +++ b/mobilerun/cli/workspace/group.py @@ -19,15 +19,16 @@ def file_choices(ctx: click.Context) -> list[SelectChoice]: return [ SelectChoice(item.id, item.name, item.id) - for item in asyncio.run(Workspace.list_files()) + for item in asyncio.run(Workspace().list_files()) ] def app_choices(ctx: click.Context) -> list[SelectChoice]: return [ - SelectChoice(item.id, item.name or item.package, item.id) - for item in asyncio.run(Workspace.list_apps()) - if item.id is not None + SelectChoice( + item.resource_id, item.name or item.identity.app_id, item.resource_id + ) + for item in asyncio.run(Workspace().list_apps()) ] @@ -53,7 +54,7 @@ async def upload_files(paths: tuple[str, ...], as_json: bool) -> None: for path in paths: click.echo(f"Uploading {path}…", err=True) try: - item = await Workspace.upload_file(path) + item = await Workspace().upload_file(path) except (click.Abort, click.exceptions.Exit): raise except Exception as exc: @@ -78,7 +79,7 @@ async def upload_files(paths: tuple[str, ...], as_json: bool) -> None: @coro async def list_files(as_json: bool) -> None: """List workspace files.""" - items = await Workspace.list_files() + items = await Workspace().list_files() if as_json: click.echo(json.dumps([asdict(item) for item in items], default=str)) else: @@ -102,7 +103,7 @@ async def list_files(as_json: bool) -> None: async def download_file(file_id: str, dest: str, as_json: bool) -> None: """Download a workspace file.""" click.echo(f"Downloading {file_id}…", err=True) - path = await Workspace.download_file(file_id, dest) + path = await Workspace().download_file(file_id, dest) click.echo( json.dumps({"id": file_id, "status": "downloaded", "path": str(path)}) if as_json @@ -121,7 +122,7 @@ async def delete_file(file_id: tuple[str, ...], yes: bool, as_json: bool) -> Non """Delete workspace files.""" async def remove(item_id: str) -> str: - await Workspace.delete_file(item_id) + await Workspace().delete_file(item_id) return "deleted" await cleanup( @@ -154,9 +155,24 @@ def apps() -> None: @coro async def list_apps(as_json: bool) -> None: """List workspace apps.""" - items = await Workspace.list_apps() + items = await Workspace().list_apps() if as_json: - click.echo(json.dumps([asdict(item) for item in items], default=str)) + click.echo( + json.dumps( + [ + { + "id": item.resource_id, + "name": item.name, + "package": item.identity.app_id, + "version": item.identity.version_name or "", + "version_code": item.identity.version_code, + "path": item.path, + } + for item in items + ], + default=str, + ) + ) else: if not items: render.empty( @@ -168,9 +184,9 @@ async def list_apps(as_json: bool) -> None: render.table( [ [ - item.name or item.package, - render.secondary(item.package if item.name else ""), - render.secondary(item.id), + item.name or item.identity.app_id, + render.secondary(item.identity.app_id if item.name else ""), + render.secondary(item.resource_id), ] for item in items ] @@ -186,21 +202,26 @@ async def list_apps(as_json: bool) -> None: async def upload_app(apk: str, as_json: bool) -> None: """Upload an APK to the workspace.""" click.echo(f"Uploading {apk}…", err=True) - item = await Workspace.upload_app(apk) + item = await Workspace().upload_app(apk) if as_json: click.echo( json.dumps( { - "id": item.id, + "id": item.resource_id, "status": "uploaded", "name": item.name, - "package": item.package, + "package": item.identity.app_id, } ) ) else: - render.success(f"Uploaded {item.name or item.package}") - render.kv([("Package", item.package), ("App ID", render.secondary(item.id))]) + render.success(f"Uploaded {item.name or item.identity.app_id}") + render.kv( + [ + ("Package", item.identity.app_id), + ("App ID", render.secondary(item.resource_id)), + ] + ) @apps.command("remove") @@ -214,7 +235,7 @@ async def delete_app(app_id: tuple[str, ...], yes: bool, as_json: bool) -> None: """Delete apps from the workspace.""" async def remove(item_id: str) -> str: - await Workspace.delete_app(item_id) + await Workspace().delete_app(item_id) return "deleted" await cleanup( diff --git a/mobilerun/clients/README.md b/mobilerun/clients/README.md index 473d22875..e13bdad10 100644 --- a/mobilerun/clients/README.md +++ b/mobilerun/clients/README.md @@ -1,20 +1,27 @@ # clients/ -**Purpose:** Functional SDK and Portal transport boundaries. +**Purpose:** Framework service and account adapters. **What belongs here / what doesn't:** Put service calls and response handling here, not CLI printing or core, agent, and feature imports. **Contents:** -- `__init__.py` — Package marker. -- `cloud/` — Cloud authentication and account access. -- `local/` — Function-only local helpers, APK metadata and shared code waiting. -- `portal/` — Portal setup, HTTP, and state retrieval. +| Path | Purpose | +| --- | --- | +| `__init__.py` | Package marker. | +| `cloud/` | Cloud authentication and account access. | +| `local/` | Private login persistence and APK metadata inspection. | **Examples:** -Use [devices](../core/devices/README.md) for the public API. Cloud, local and Portal clients are lower-level transport helpers. +Use `AsyncDevice` / `AsyncMobilerun` from `mobilerun_core` for the public device API, including Portal setup and transport. + +```python +from mobilerun.clients.cloud.api_keys import ApiKeys + +keys = ApiKeys(billing="no_commerce") +``` **Depends on / used by:** Uses shared configuration, errors, and external clients; used by core, CLI, and features. -See [cloud](cloud/README.md), [local](local/README.md), and [Portal](portal/README.md). +See [cloud](cloud/README.md) and [local](local/README.md). diff --git a/mobilerun/clients/cloud/README.md b/mobilerun/clients/cloud/README.md index 93e046d01..e1ebb5b3d 100644 --- a/mobilerun/clients/cloud/README.md +++ b/mobilerun/clients/cloud/README.md @@ -1,70 +1,96 @@ # cloud/ -**Purpose:** The only SDK boundary for cloud services, including billing policy. +**Purpose:** Cloud adapters for framework-owned account resources, authentication and signed transfers. `mobilerun-core` owns native phone operations and lifecycle. **What belongs here / what doesn't:** Put cloud account access and OAuth flows here, not CLI presentation. **Contents:** - `__init__.py` — Package marker. -- `api_keys.py` — API key validation. -- `device_flow.py` — OAuth device authorization flow. -- `client.py` — Shared AsyncMobilerun factory. -- `billing.py` — Shared fail-closed commerce guard. -- `checkout.py`, `payments.py` — Checkout presentation and payment polling. -- `errors.py` — Sanitized cloud API errors. -- `devices.py`, `numbers.py`, `mailboxes.py`, `proxies.py` — Resource operations. -- `secrets.py` — Credential-vault SDK operations; core owns caching and package policy. -- `webhooks.py` — Endpoint registration, lookup, listing, deletion, and signed test delivery for [CloudWebhooks](../../core/webhooks/README.md). -- `tasks.py` — Task calls, streaming, status and artifact SDK access. -- `apps.py` — APK upload, reuse and retrieval. +- `api_keys.py` — `ApiKeys` validates account API keys. +- `billing_policy.py` — `BillingPolicy` authorizes operations and translates SDK billing options. +- `client.py` — Shared factory for a caller-owned account SDK client. +- `device_flow.py` — `DeviceAuthorization` requests codes, polls for tokens and reads sessions outside the account SDK. +- `errors.py` — `CloudErrorMapper` translates core error facts into framework errors. +- `mailboxes.py` — `Mailboxes` manages account mailboxes and messages. +- `numbers.py` — `Numbers` manages phone numbers and SMS. +- `payments.py` — `PaymentFlow` polls checkout and activation without presentation or automatic deletion. +- `proxies.py` — `Proxies` manages account Connect proxies. +- `resource.py` — `CloudResource` binds billing and connection settings and owns the SDK error boundary. +- `secrets.py` — `Vault` manages credentials; core owns caching and package policy. +- `signed_http.py` — `SignedHTTP` owns raw transfer clients and suppresses sensitive diagnostics. +- `tasks.py` — `Tasks` submits jobs and retrieves progress, status and artifacts. **Examples:** ```python +from mobilerun.clients.cloud.numbers import Numbers from mobilerun.models import Billing -billing = Billing.NO_COMMERCE +numbers = Numbers(billing=Billing.NO_COMMERCE) +countries = await numbers.countries() +owned_numbers = await numbers.list() ``` -**Depends on / used by:** Uses shared configuration and HTTP dependencies; used by cloud devices and authentication commands. +**Depends on / used by:** Uses shared configuration, the core async factory and the account SDK; used by framework extensions and CLI commands. + +## Cloud phones + +Pass a caller-owned `mobilerun_core.AsyncMobilerun` with an approval gate and a +preselected `ConnectProxyRef`. The adapter never buys a proxy, changes `keep`, +substitutes a minute plan, or bypasses core approval. + +```python +from mobilerun.clients.cloud.billing_policy import BillingPolicy +from mobilerun_core import ConnectProxyRef + +# Can incur per-minute charges. The factory's HITL gate must approve creation. +plan = BillingPolicy.cloud_phone_plan("minute") +phone = await run.create_cloud(proxy=ConnectProxyRef(id=proxy_id), plan=plan) +async with phone: + await phone.observe() +``` + +Core terminates the phone on close unless you pass `keep=True`. Only +`plan="minute"` supports `keep=False`. To use the included `subscription` default +or the paid `auto` default, pass `keep=True`. Connecting to an existing ID never +transfers phone ownership. Use `run.list_cloud_devices()` for discovery and +`run.cloud_device(id)` for status (`refresh()`), readiness, stop, resume, reboot, +reset, rename and termination without a UI connection. + +Use the core `AsyncDevice` for phone app installation, device file transfers, +and device proxy settings. Use [Workspace](../../core/WORKSPACE.md) for account +apps and files, and [CloudWebhooks](../../core/webhooks/README.md) for endpoints. ## App library -`upload_app(path, billing=Billing.NO_COMMERCE)` inspects an APK with Android build-tools `aapt`, hashes it, -reuses an available matching package and version, or uploads it to the cloud -library. Install Android SDK build-tools and set `ANDROID_HOME`/`ANDROID_SDK_ROOT` -or put `aapt` on `PATH`. The helper accepts optional `api_key` and `base_url`; -otherwise it uses the usual cloud credential resolution. Existing matching -versions are reused without creating app storage. +`Workspace().upload_app(path)` uses core to inspect an APK with Android build-tools `aapt`, +hashes it, and uploads it to the cloud library. Install Android SDK build-tools +and set `ANDROID_HOME`/`ANDROID_SDK_ROOT` or put `aapt` on `PATH`. ```python -from mobilerun.clients.cloud.apps import upload_app -from mobilerun.models import Billing +from mobilerun import Workspace -app = await upload_app("counter.apk", billing=Billing.NO_COMMERCE) +app = await Workspace().upload_app("counter.apk") ``` ## Billing -Every public client function requires keyword-only `billing: Billing`, without a -default. Enum values and their strings work; `None` does not. Each boundary declares -its minimum with `@requires(Billing.X)`. A call that can cost more declares it on -the same line with `paid_if=`, a function of the bound arguments (a metered phone -plan, a rented number or mailbox, a new Connect proxy by country); the guard never -infers a rule from a module or function name. Missing billing raises `TypeError`, an -invalid mode raises `BillingError`, and a lower mode raises `BillingRequired` +Account SDK calls require explicit billing. Pass it when constructing the adapter +or using the standalone SDK factory. Enum values and their strings work; `None` +does not. Each operation declares its minimum explicitly, and renting a number +or mailbox requires `PAID`. Missing billing raises `TypeError`, an invalid mode +raises `BillingError`, and a lower mode raises `BillingRequired` with `needed`, `given`, and `operation`, all before transport. The order is -`NO_COMMERCE < INCLUDED < PAID`. Import enums from `mobilerun.models` (clients) -or `mobilerun.core.devices` (application code). +`NO_COMMERCE < INCLUDED < PAID`. Import billing enums from `mobilerun.models`. -Core resources snapshot `MOBILERUN_BILLING` (default `paid`) at construction unless -`billing=` is explicit, and pass that mode on every client call. Cloud CLI commands accept -`--billing no_commerce|included|paid`, defaulting to that setting. +`BillingPolicy.cloud_phone_plan()` resolves `MOBILERUN_BILLING` (default `paid`) +unless given explicit `billing`. Call it before core phone creation to block +`no_commerce` and select a permitted plan. For a single operation whose guard runs before side effects, call `await with_billing_retry(operation, billing, yes=False)` from -`mobilerun.clients.cloud.billing`. The callback receives the mode for each attempt; +`mobilerun.utils.billing.retry`. The callback receives the mode for each attempt; the helper returns `(result, effective_billing)`. It prompts on a terminal only if the guard rejects the requested mode. `yes=True` authorizes one retry with the mode required by the guard without a prompt. Only a retry with `PAID` can charge. @@ -74,25 +100,19 @@ before hitting a billing guard. | Function | Minimum mode | | --- | --- | -| `client._cloud_client` | `NO_COMMERCE` | -| `api_keys.validate_api_key` | `NO_COMMERCE` | -| `device_flow.request_code`, `poll_token`, `fetch_session` | `NO_COMMERCE` | -| `devices.create` | `INCLUDED`; `PAID` for `AUTO`/`MINUTE` or a country Connect proxy | -| `devices.resume` | `NO_COMMERCE` for subscription-billed phones; `PAID` otherwise | -| `devices.list_devices`, `retrieve`, `wait_ready`, `terminate`, `stop`, `reboot`, `reset`, `number`, `bind_number`, `unbind_number` | `NO_COMMERCE` | -| `numbers.create`, `mailboxes.create` | `INCLUDED` | -| `numbers.list_numbers`, `retrieve`, `delete`, `countries`, `capacity`, `messages` | `NO_COMMERCE` | -| `numbers.send` | `PAID` | -| `mailboxes.list_mailboxes`, `retrieve`, `delete`, `capacity`, `messages`, `otp` | `NO_COMMERCE` | -| `proxies.connect_device` | `NO_COMMERCE` for an existing Connect ID or SOCKS5; `PAID` for country Connect | -| `proxies.buy_proxy` | `PAID` | -| `proxies.disconnect_device`, `device_status`, `list_proxies`, `get_proxy` | `NO_COMMERCE` | -| `secrets.list_secrets`, `list_package`, `create_package`, `save`, `create_field`, `update`, `delete` | `NO_COMMERCE` | -| `webhooks.register_webhook`, `list_webhooks`, `get_webhook`, `ping_webhook`, `delete_webhook` | `NO_COMMERCE` | -| `apps.get_app`, `upload_app`, `list_installs`, `install`, `uninstall` | `NO_COMMERCE` | -| `files.upload_file`, `list_files`, `download_file`, `delete_file`, `push_device_file`, `list_device_files`, `download_device_file`, `delete_device_file` | `NO_COMMERCE` | -| `tasks.run` | `INCLUDED` (consumes task credits) | -| `tasks.progress`, `status`, `stop`, `trajectory`, `screenshots` | `NO_COMMERCE` | +| `client.cloud_client` | `NO_COMMERCE` | +| `ApiKeys.validate` | `NO_COMMERCE` | +| `DeviceAuthorization.request_code`, `poll_token`, `fetch_session` | `NO_COMMERCE` | +| `BillingPolicy.cloud_phone_plan` | `INCLUDED`; `PAID` for explicit `auto` or `minute` | +| `Numbers.create`, `Mailboxes.create` | `INCLUDED`; `PAID` for `plan="rent"` | +| `Numbers.list`, `retrieve`, `delete`, `countries`, `capacity`, `messages` | `NO_COMMERCE` | +| `Numbers.send` | `PAID` | +| `Mailboxes.list`, `retrieve`, `delete`, `capacity`, `messages`, `otp` | `NO_COMMERCE` | +| `Proxies.buy` | `PAID` | +| `Proxies.list`, `retrieve`, `cancel` | `NO_COMMERCE` | +| `Vault.list`, `list_package`, `create_package`, `save`, `create_field`, `update`, `delete`, `delete_field` | `NO_COMMERCE` | +| `Tasks.run` | `INCLUDED` (consumes task credits) | +| `Tasks.progress`, `status`, `stop`, `trajectory`, `screenshots` | `NO_COMMERCE` | | Mode | Phones | Numbers / mailboxes | Connect proxy | | --- | --- | --- | --- | @@ -100,19 +120,12 @@ before hitting a billing guard. | `included` | `subscription`, no fallback | `included_only` | Blocked: no SDK-enforced included-only mode | | `paid` (default) | Any plan; default `auto` | `included` (paid fallback) | Allowed | -Existing IDs never trigger a purchase. A Connect proxy ID can be attached without -buying a proxy; selecting a Connect country may purchase one and is guarded. -`proxies.list_proxies(included_only=True, billing=Billing.NO_COMMERCE)` filters -each page to proxies billed as included. Pagination still describes the unfiltered +An existing Connect proxy ID can be attached through core without buying a proxy. +`Mailboxes` and `Proxies` take billing and optional connection settings at +construction. They never close an SDK client supplied by the caller. +`await Proxies(billing=Billing.NO_COMMERCE).list(included_only=True)` filters +one page to proxies billed as included. Pagination still describes the unfiltered inventory, so a filtered page can be empty even when more pages are available. -The old allow-paid setting and resource create classmethods are removed. - -App uploads and installs require the explicit mode, but permit `NO_COMMERCE`. - -```python -app = await device.install_apk("counter.apk") -await device.start_app(app.package) -await device.uninstall_app(app.package) -``` +Checkout presentation lives in [utils/checkout](../../utils/checkout/README.md). -See [clients](../README.md) and [cloud devices](../../core/devices/README.md). +See [clients](../README.md). diff --git a/mobilerun/clients/cloud/api_keys.py b/mobilerun/clients/cloud/api_keys.py index 958bb04eb..88d69fdb2 100644 --- a/mobilerun/clients/cloud/api_keys.py +++ b/mobilerun/clients/cloud/api_keys.py @@ -1,30 +1,26 @@ """Cloud API key validation.""" -from mobilerun_sdk import APIError - -from mobilerun.clients.cloud.billing import requires -from mobilerun.clients.cloud.client import cloud_client -from mobilerun.clients.cloud.errors import cloud_error +from mobilerun.clients.cloud.resource import CloudResource from mobilerun.config.settings import get_settings from mobilerun.errors import InvalidAPIKeyError from mobilerun.models.billing import Billing -@requires(Billing.NO_COMMERCE) -async def validate_api_key(api_key: str, *, billing: Billing) -> None: - """Validate access to the devices endpoint.""" - if not api_key: - raise InvalidAPIKeyError("Invalid API key") - settings = get_settings() - base = settings.MOBILERUN_CLOUD_BASE_URL.rstrip("/") - if not base.endswith("/v1"): - base += "/v1" - try: - async with cloud_client( - billing=billing, api_key=api_key, base_url=base - ) as client: - await client.devices.list( - page_size=1, timeout=settings.MOBILERUN_CLOUD_API_TIMEOUT +class ApiKeys(CloudResource): + """Validate an explicitly supplied cloud API key.""" + + def __init__(self, *, api_key: str, billing: Billing | str) -> None: + base = get_settings().MOBILERUN_CLOUD_BASE_URL.rstrip("/") + if not base.endswith("/v1"): + base += "/v1" + super().__init__(billing=billing, api_key=api_key, base_url=base) + + async def validate(self) -> None: + """Validate access to the devices endpoint with the login timeout.""" + if not self._api_key: + self._billing.require(Billing.NO_COMMERCE, "Validate cloud API key") + raise InvalidAPIKeyError("Invalid API key") + async with self._request("Validate cloud API key", Billing.NO_COMMERCE) as sdk: + await sdk.devices.list( + page_size=1, timeout=get_settings().MOBILERUN_CLOUD_API_TIMEOUT ) - except APIError as exc: - raise cloud_error(exc, "Validate cloud API key") from exc diff --git a/mobilerun/clients/cloud/apps.py b/mobilerun/clients/cloud/apps.py deleted file mode 100644 index e7294653c..000000000 --- a/mobilerun/clients/cloud/apps.py +++ /dev/null @@ -1,191 +0,0 @@ -"""Upload Android packages and install cloud apps; neither is billable.""" - -import asyncio -import hashlib -from collections.abc import AsyncIterator -from pathlib import Path -from typing import TypedDict, Unpack - -import httpx -from mobilerun_sdk import APIError, AsyncMobilerun -from mobilerun_sdk.types.app_list_response import Item -from mobilerun_sdk.types.app_retrieve_response import AppRetrieveResponse -from mobilerun_sdk.types.devices.app_list_installs_response import ( - AppListInstallsResponse, -) - -from mobilerun.clients.cloud.billing import requires -from mobilerun.clients.cloud.client import cloud_client -from mobilerun.clients.cloud.errors import cloud_error -from mobilerun.clients.cloud.signed_http import _signed_client -from mobilerun.clients.local.apk import inspect_apk -from mobilerun.models.apps import App -from mobilerun.models.billing import Billing - -InstallParams = TypedDict( - "InstallParams", - { - "bundle_id": str, - "package_name": str, - "background": bool, - "country": str, - "version_code": int, - "x_device_display_id": int, - }, - total=False, -) -UninstallParams = TypedDict("UninstallParams", {"device_id": str}) - - -@requires(Billing.NO_COMMERCE) -async def get_app( - client: AsyncMobilerun, app_id: str, *, billing: Billing -) -> AppRetrieveResponse: - """Retrieve an app library entry.""" - try: - return await client.apps.retrieve(app_id) - except APIError as exc: - raise cloud_error(exc, "Retrieve cloud app") from exc - - -async def _items(client: AsyncMobilerun) -> AsyncIterator[Item]: - """Iterate every app library page.""" - page = 1 - try: - while True: - result = await client.apps.list(page=page, page_size=100) - for item in result.items: - yield item - if not result.pagination.has_next: - break - page += 1 - except APIError as exc: - raise cloud_error(exc, "List cloud apps") from exc - - -@requires(Billing.NO_COMMERCE) -async def list_apps(client: AsyncMobilerun, *, billing: Billing) -> list[App]: - return [ - App( - item.bundle_id, - item.version.version_name or "", - item.display_name, - id=item.id, - version_code=item.version.version_code, - ) - async for item in _items(client) - ] - - -@requires(Billing.NO_COMMERCE) -async def delete_app(client: AsyncMobilerun, app_id: str, *, billing: Billing) -> None: - try: - await client.apps.delete(app_id) - except APIError as exc: - raise cloud_error(exc, "Delete workspace app") from exc - - -@requires(Billing.NO_COMMERCE) -async def upload_app( - path: str | Path, - *, - billing: Billing, - api_key: str | None = None, - base_url: str | None = None, -) -> App: - """Upload an APK; version metadata alone cannot verify identical content.""" - path = Path(path) - - def prepare(): - metadata = inspect_apk(path) - content = path.read_bytes() - return metadata, content, hashlib.sha256(content).hexdigest() - - (package, code, version, name), content, digest = await asyncio.to_thread(prepare) - async with cloud_client(api_key, base_url, billing=billing) as client: - try: - signed = await client.apps.create_signed_upload_url( - bundle_id=package, - display_name=name, - version_code=code, - version_name=version, - platform="android", - files=[ - { - "file_name": path.name, - "content_type": "application/vnd.android.package-archive", - "sha256": digest, - } - ], - ) - except APIError as exc: - raise cloud_error(exc, "Prepare cloud app upload") from exc - try: - url = next( - entry.r2_upload_url - for entry in signed.r2_upload_urls - if entry.file_name == path.name - ) - async with _signed_client(httpx.AsyncClient()) as http: - response = await http.put( - url, - content=content, - headers={"Content-Type": "application/vnd.android.package-archive"}, - timeout=None, - ) - response.raise_for_status() - await client.apps.confirm_upload(signed.version_id) - except BaseException as exc: - try: - await client.apps.mark_failed(signed.version_id) - except APIError: - pass - if isinstance(exc, (APIError, httpx.HTTPError, httpx.InvalidURL)): - raise cloud_error(exc, "Upload cloud app") from None - raise - return App( - package, version, name, id=signed.app_id, version_code=code, path=path - ) - - -@requires(Billing.NO_COMMERCE) -async def list_installs( - client: AsyncMobilerun, device_id: str, *, billing: Billing -) -> AppListInstallsResponse: - """Poll app installations.""" - try: - return await client.devices.apps.list_installs(device_id) - except APIError as exc: - raise cloud_error(exc, "List phone app installs", device=True) from exc - - -@requires(Billing.NO_COMMERCE) -async def install( - client: AsyncMobilerun, - device_id: str, - *, - billing: Billing, - **params: Unpack[InstallParams], -) -> None: - """Install an app on an existing phone.""" - try: - return await client.devices.apps.install(device_id, **params) - except APIError as exc: - raise cloud_error(exc, "Install phone app", device=True) from exc - - -@requires(Billing.NO_COMMERCE) -async def uninstall( - client: AsyncMobilerun, - package: str, - *, - billing: Billing, - **params: Unpack[UninstallParams], -) -> None: - """Uninstall an app from a phone.""" - try: - # The deployed endpoint requires a JSON body even though the generated - # SDK describes DELETE as bodyless. An empty object has no side effects. - return await client.devices.apps.delete(package, extra_body={}, **params) - except APIError as exc: - raise cloud_error(exc, "Uninstall phone app", device=True) from exc diff --git a/mobilerun/clients/cloud/billing.py b/mobilerun/clients/cloud/billing.py deleted file mode 100644 index 73211c90a..000000000 --- a/mobilerun/clients/cloud/billing.py +++ /dev/null @@ -1,174 +0,0 @@ -"""One opt-in policy for every billable cloud resource.""" - -import sys -from collections.abc import Awaitable, Callable, Mapping -from functools import wraps -from inspect import signature -from typing import Any, ParamSpec, TypeVar - -from mobilerun.errors.cloud import BillingError, BillingRequired -from mobilerun.models.billing import Billing, Plan, ResourcePlan -from mobilerun.utils.terminal import can_prompt - -P = ParamSpec("P") -R = TypeVar("R") - - -def billing_prompt_is_interactive() -> bool: - """Return whether a billing prompt can use terminal stdin and stderr.""" - return can_prompt(sys.stderr) - - -async def _confirm_billing(error: BillingRequired) -> bool: - from prompt_toolkit import PromptSession - from prompt_toolkit.output import create_output - - session: PromptSession[str] = PromptSession(output=create_output(stdout=sys.stderr)) - try: - answer = await session.prompt_async(f"{error.confirmation} [y/N] ") - except EOFError: - return False - return answer.strip().casefold() in {"y", "yes"} - - -async def with_billing_retry( - operation: Callable[[Billing], Awaitable[R]], - billing: Billing | str, - *, - yes: bool = False, - prompt: Callable[[BillingRequired], Awaitable[bool]] = _confirm_billing, - is_interactive: Callable[[], bool] | None = None, -) -> tuple[R, Billing]: - """Retry one operation whose billing checks run before any side effects. - - Pass a callback accepting the mode for this attempt. Return the result and - the effective mode. Without consent or a terminal on stdin and stderr, - re-raise BillingRequired. - """ - - mode = Billing(billing) - try: - return await operation(mode), mode - except BillingRequired as error: - if mode is Billing.PAID or error.given is not mode or error.needed is mode: - raise - needed = error.needed - if yes is not True: - interactive = ( - billing_prompt_is_interactive() - if is_interactive is None - else is_interactive() - ) - if not interactive or not await prompt(error): - raise - return await operation(needed), needed - - -def buys_connect_proxy(proxy: object) -> bool: - """Return whether a proxy spec orders a new Connect proxy by country.""" - connect = proxy.get("connect") if isinstance(proxy, Mapping) else None - return isinstance(connect, Mapping) and bool(connect.get("country")) - - -def rents_resource(arguments: Mapping[str, Any]) -> bool: - """Return whether a number or mailbox call asks for a rented resource.""" - plan = arguments.get("plan") - return plan is not None and ResourcePlan(plan) is ResourcePlan.RENT - - -def requires( - minimum: Billing, - *, - operation: str | None = None, - paid_if: Callable[[Mapping[str, Any]], bool] | None = None, -) -> Callable[[Callable[P, R]], Callable[P, R]]: - """Declare and enforce a boundary's minimum commerce mode before any work. - - ``paid_if`` receives the bound arguments and returns whether this call needs - paid billing. Declare it on the function it guards: the guard never infers - a rule from a module or function name. - """ - - def decorate(function: Callable[P, R]) -> Callable[P, R]: - sig = signature(function) - - @wraps(function) - def guarded(*args: P.args, **kwargs: P.kwargs) -> R: - bound = sig.bind(*args, **kwargs) - given = bound.arguments["billing"] - needed = minimum - try: - if paid_if is not None and paid_if(bound.arguments): - needed = Billing.PAID - mode = Billing(given) - except (ValueError, TypeError) as exc: - error = BillingError( - operation=function.__name__, - code="invalid_billing", - required_billing=needed.value, - detail=given, - ) - raise error from exc - if list(Billing).index(mode) < list(Billing).index(needed): - raise BillingRequired( - needed=needed, given=mode, operation=operation or function.__name__ - ) - bound.arguments["billing"] = mode - return function(*bound.args, **bound.kwargs) - - return guarded - - return decorate - - -async def _billing_preference( - resource: str, - billing: Billing, - *, - plan: Plan | ResourcePlan | str | None = None, -) -> str: - """Map authorized commerce to the SDK's resource-specific preferences.""" - mode = Billing(billing) - if resource in {"numbers", "mailboxes"}: - resource_plan = ResourcePlan.AUTO if plan is None else ResourcePlan(plan) - if resource_plan is ResourcePlan.RENT: - return "rent" - if resource_plan is ResourcePlan.INCLUDED: - return "included_only" - return "included_only" if mode is Billing.INCLUDED else "included" - if resource == "cloud phones": - return Plan( - plan or (Plan.SUBSCRIPTION if mode is Billing.INCLUDED else Plan.AUTO) - ).value - return "auto" - - -async def _validate_create_params( - params: Mapping[str, object], - *, - allow_proxy: bool = False, - allow_connect: bool = False, -) -> None: - """Prevent extra fields from overriding commerce policy.""" - - def forbidden(key: object) -> bool: - return isinstance(key, str) and key.replace("_", "").lower().startswith( - ("billing", "proxy", "connect") - ) - - extra = params.get("extra_body") or {} - query = params.get("extra_query") or {} - pending = [extra, query] - while pending: - value = pending.pop() - if isinstance(value, Mapping): - if any(forbidden(key) for key in value): - raise BillingError(code="billing_override") - pending.extend(value.values()) - elif isinstance(value, (list, tuple)): - pending.extend(value) - allowed = ({"proxy"} if allow_proxy else set()) | ( - {"connect"} if allow_connect else set() - ) - if any(forbidden(key) and key not in allowed for key in params): - raise BillingError(code="billing_override") diff --git a/mobilerun/clients/cloud/billing_policy.py b/mobilerun/clients/cloud/billing_policy.py new file mode 100644 index 000000000..f6d8449f9 --- /dev/null +++ b/mobilerun/clients/cloud/billing_policy.py @@ -0,0 +1,128 @@ +"""Commerce authorization for cloud account resources.""" + +from __future__ import annotations + +from collections.abc import Callable, Mapping +from functools import wraps +from inspect import signature +from typing import TYPE_CHECKING, Literal, ParamSpec, TypeVar, get_args + +from mobilerun.errors.cloud import BillingError, BillingRequired +from mobilerun.models.billing import Billing, ResourcePlan + +if TYPE_CHECKING: + from mobilerun_core import CloudPlan + +P = ParamSpec("P") +R = TypeVar("R") + + +class BillingPolicy: + """Authorize commerce before opening an SDK client or issuing a request.""" + + def __init__(self, billing: Billing | str) -> None: + self._billing = billing + + @classmethod + def cloud_phone_plan( + cls, plan: CloudPlan | None = None, *, billing: Billing | str | None = None + ) -> CloudPlan: + """Authorize a creation plan before passing it to the core factory.""" + from mobilerun_core import CloudPlan + + from mobilerun.config.settings import get_settings + + if plan is not None and ( + not isinstance(plan, str) or plan not in get_args(CloudPlan) + ): + raise ValueError("plan must be auto, subscription or minute") + mode = billing if billing is not None else get_settings().MOBILERUN_BILLING + minimum = Billing.INCLUDED if plan in {None, "subscription"} else Billing.PAID + authorized = cls(mode).require(minimum, "Create cloud phone") + return ( + plan + if plan is not None + else ("auto" if authorized is Billing.PAID else "subscription") + ) + + def require( + self, + minimum: Billing, + operation: str, + *, + plan: ResourcePlan | str | None = None, + invalid_operation: str | None = None, + ) -> Billing: + """Check the minimum mode and return the normalized mode.""" + try: + if plan is not None and ResourcePlan(plan) is ResourcePlan.RENT: + minimum = Billing.PAID + mode = Billing(self._billing) + except (ValueError, TypeError) as exc: + raise BillingError( + operation=invalid_operation or operation, + code="invalid_billing", + required_billing=minimum.value, + detail=self._billing, + ) from exc + if list(Billing).index(mode) < list(Billing).index(minimum): + raise BillingRequired(needed=minimum, given=mode, operation=operation) + return mode + + def resource_preference( + self, plan: ResourcePlan | str | None = None + ) -> Literal["included", "included_only", "rent"]: + """Translate a number or mailbox plan to the SDK billing preference.""" + resource_plan = ResourcePlan.AUTO if plan is None else ResourcePlan(plan) + if resource_plan is ResourcePlan.RENT: + return "rent" + if ( + resource_plan is ResourcePlan.INCLUDED + or Billing(self._billing) is Billing.INCLUDED + ): + return "included_only" + return "included" + + @classmethod + def guard( + cls, minimum: Billing, *, operation: str | None = None + ) -> Callable[[Callable[P, R]], Callable[P, R]]: + """Authorize unbound sandbox entry points before creating their coroutine.""" + + def decorate(function: Callable[P, R]) -> Callable[P, R]: + sig = signature(function) + + @wraps(function) + def guarded(*args: P.args, **kwargs: P.kwargs) -> R: + bound = sig.bind(*args, **kwargs) + bound.arguments["billing"] = cls(bound.arguments["billing"]).require( + minimum, + operation or function.__name__, + invalid_operation=function.__name__, + ) + return function(*bound.args, **bound.kwargs) + + return guarded + + return decorate + + @staticmethod + def validate_create_params(params: Mapping[str, object]) -> None: + """Prevent extra fields from overriding commerce policy.""" + + def forbidden(key: object) -> bool: + return isinstance(key, str) and key.replace("_", "").lower().startswith( + ("billing", "proxy", "connect") + ) + + pending = [params.get("extra_body") or {}, params.get("extra_query") or {}] + while pending: + value = pending.pop() + if isinstance(value, Mapping): + if any(forbidden(key) for key in value): + raise BillingError(code="billing_override") + pending.extend(value.values()) + elif isinstance(value, (list, tuple)): + pending.extend(value) + if any(forbidden(key) for key in params): + raise BillingError(code="billing_override") diff --git a/mobilerun/clients/cloud/client.py b/mobilerun/clients/cloud/client.py index 34011456b..26f1cba98 100644 --- a/mobilerun/clients/cloud/client.py +++ b/mobilerun/clients/cloud/client.py @@ -1,30 +1,14 @@ """Shared SDK client factory.""" -from collections.abc import Awaitable -from typing import TypeVar +from mobilerun_sdk import AsyncMobilerun -import httpx -from mobilerun_sdk import APIError, AsyncMobilerun - -from mobilerun.clients.cloud.billing import requires -from mobilerun.clients.cloud.errors import cloud_error -from mobilerun.clients.local.login_store import resolve_cloud_api_key +from mobilerun.clients.cloud.billing_policy import BillingPolicy +from mobilerun.clients.local.login_store import LoginStore from mobilerun.config.settings import get_settings from mobilerun.errors.cloud import CloudAuthRequired from mobilerun.models.billing import Billing -T = TypeVar("T") - - -async def _device_request(request: Awaitable[T]) -> T: - """Translate transport failures without leaking the SDK into core.""" - try: - return await request - except (APIError, httpx.HTTPError) as exc: - raise cloud_error(exc, "Cloud phone request", device=True) from exc - -@requires(Billing.NO_COMMERCE) def cloud_client( api_key: str | None = None, base_url: str | None = None, @@ -32,7 +16,10 @@ def cloud_client( billing: Billing | str, ) -> AsyncMobilerun: """Construct a client; callers own its lifetime.""" - key = api_key if api_key is not None else resolve_cloud_api_key() + BillingPolicy(billing).require(Billing.NO_COMMERCE, "cloud_client") + key = ( + api_key if api_key is not None else LoginStore.from_settings().resolve_api_key() + ) if not key: raise CloudAuthRequired(code="credentials_required") return AsyncMobilerun( diff --git a/mobilerun/clients/cloud/device_flow.py b/mobilerun/clients/cloud/device_flow.py index e62c417d9..e1998f3f7 100644 --- a/mobilerun/clients/cloud/device_flow.py +++ b/mobilerun/clients/cloud/device_flow.py @@ -1,163 +1,152 @@ -"""OAuth 2.0 Device Authorization Grant (RFC 8628) client for Mobilerun. - -Python port of the mobilerun-ios ``pkg/deviceauth`` flow: request a device -code, poll the better-auth token endpoint until the user approves, and return -the session access token. Transport + storage only — callers handle UI. -""" +"""OAuth device authorization and session lookup, without the account SDK.""" from __future__ import annotations import asyncio import time -from dataclasses import dataclass -from typing import Optional, TypedDict, Unpack +from dataclasses import dataclass, field +from typing import Any import httpx -from mobilerun.clients.cloud.billing import requires -from mobilerun.clients.cloud.errors import cloud_error +from mobilerun.clients.cloud.billing_policy import BillingPolicy +from mobilerun.clients.cloud.errors import CloudErrorMapper from mobilerun.config.settings import get_settings from mobilerun.errors import CloudAPIError, DeviceAuthError from mobilerun.models.billing import Billing +from mobilerun.utils.network.quiet import quiet_transport_logs @dataclass class CodeResponse: """Values returned by the OAuth device authorization flow.""" - device_code: str - user_code: str + device_code: str = field(repr=False) + user_code: str = field(repr=False) verification_uri: str - verification_uri_complete: str + verification_uri_complete: str = field(repr=False) expires_in: int interval: int -_RequestOptions = TypedDict( - "_RequestOptions", - {"json": dict[str, str], "headers": dict[str, str], "timeout": float}, - total=False, -) - - -_GRANT_TYPE_DEVICE_CODE = "urn:ietf:params:oauth:grant-type:device_code" - - -async def _request( - method: str, url: str, **kwargs: Unpack[_RequestOptions] -) -> httpx.Response: - """Make an authentication request without exposing its URL.""" - try: - async with httpx.AsyncClient() as client: - return await client.request(method, url, **kwargs) - except httpx.HTTPError as exc: - raise cloud_error(exc, "Contact authentication service") from exc - - -@requires(Billing.NO_COMMERCE) -async def request_code( - auth_url: str, client_id: str, *, billing: Billing -) -> CodeResponse: - """Request OAuth device and user codes.""" - resp = await _request( - "POST", - auth_url.rstrip("/") + "/device/code", - json={"client_id": client_id, "scope": "openid profile email"}, - headers={"Accept": "application/json"}, - timeout=get_settings().MOBILERUN_DEVICE_AUTH_REQUEST_TIMEOUT, - ) - if not (200 <= resp.status_code < 300): +class DeviceAuthorization: + """Bind an auth server and use a short-lived, unaffiliated HTTP client.""" + + def __init__(self, auth_url: str, *, billing: Billing | str) -> None: + self._url = auth_url.rstrip("/") + self._billing = BillingPolicy(billing) + + async def _request( + self, + method: str, + endpoint: str, + operation: str, + *, + body: dict[str, str] | None = None, + token: str | None = None, + polling: bool = False, + ) -> dict[str, Any] | None: + headers = {"Accept": "application/json"} + if token is not None: + headers["Authorization"] = f"Bearer {token}" + failure: CloudAPIError try: - resp.raise_for_status() - except httpx.HTTPStatusError as exc: - raise cloud_error(exc, "Request device code") from exc - d = resp.json() - return CodeResponse( - device_code=d["device_code"], - user_code=d["user_code"], - verification_uri=d.get("verification_uri", ""), - verification_uri_complete=d.get("verification_uri_complete", ""), - expires_in=int(d.get("expires_in", 0)), - interval=int(d.get("interval", 5)), - ) - - -async def _exchange(auth_url: str, client_id: str, device_code: str) -> str: - """Exchange an approved device code for a token.""" - resp = await _request( - "POST", - auth_url.rstrip("/") + "/device/token", - json={ - "grant_type": _GRANT_TYPE_DEVICE_CODE, - "device_code": device_code, - "client_id": client_id, - }, - headers={"Accept": "application/json"}, - timeout=get_settings().MOBILERUN_DEVICE_AUTH_REQUEST_TIMEOUT, - ) - if 200 <= resp.status_code < 300: - token = resp.json().get("access_token") - if not token: - raise CloudAPIError(operation="Exchange device code", code="missing_token") - return token - try: - err = resp.json() - code = err.get("error") - except Exception: - code = None - allowed = {"authorization_pending", "slow_down", "access_denied", "expired_token"} - if code in allowed and resp.status_code == 400: - raise DeviceAuthError(code) - try: - resp.raise_for_status() - except httpx.HTTPStatusError as exc: - raise cloud_error(exc, "Exchange device code") from exc - raise CloudAPIError(operation="Exchange device code", code="auth_failed") - - -@requires(Billing.NO_COMMERCE) -async def poll_token( - auth_url: str, client_id: str, code: CodeResponse, *, billing: Billing -) -> str: - """Poll for approval and return the access token. - - Handles ``authorization_pending`` and ``slow_down`` internally. Raises - ``DeviceAuthError`` on terminal errors (access_denied, expired_token, ...). - """ - interval = max( - float(code.interval), get_settings().MOBILERUN_DEVICE_AUTH_MIN_POLL_INTERVAL - ) - deadline = time.monotonic() + code.expires_in - - while True: - await asyncio.sleep(interval) + with quiet_transport_logs(): + async with httpx.AsyncClient() as client: + response = await client.request( + method, + self._url + endpoint, + json=body, + headers=headers, + timeout=get_settings().MOBILERUN_DEVICE_AUTH_REQUEST_TIMEOUT, + ) + if polling and response.status_code == 400: + try: + payload = response.json() + except ValueError: + payload = None + code = payload.get("error") if isinstance(payload, dict) else None + if isinstance(code, str) and code in { + "authorization_pending", + "slow_down", + "access_denied", + "expired_token", + }: + raise DeviceAuthError(code) + response.raise_for_status() + payload = response.json() + if payload is None or isinstance(payload, dict): + return payload + failure = CloudAPIError(operation=operation, code="auth_failed") + except (httpx.HTTPError, httpx.InvalidURL) as exc: + failure = CloudErrorMapper.from_exception(exc, operation) + except ValueError: + failure = CloudAPIError(operation=operation, code="auth_failed") + # Do not attach the URL, response body, or authorization headers. + raise failure from None + + async def request_code(self, client_id: str) -> CodeResponse: + """Request OAuth device and user codes.""" + operation = "Request device code" + self._billing.require(Billing.NO_COMMERCE, operation) + data = await self._request( + "POST", + "/device/code", + operation, + body={"client_id": client_id, "scope": "openid profile email"}, + ) try: - return await _exchange(auth_url, client_id, code.device_code) - except DeviceAuthError as e: - if e.code == "authorization_pending": - pass - elif e.code == "slow_down": - interval += get_settings().MOBILERUN_DEVICE_AUTH_SLOW_DOWN_BUMP + if data is not None: + return CodeResponse( + device_code=data["device_code"], + user_code=data["user_code"], + verification_uri=data.get("verification_uri", ""), + verification_uri_complete=data.get("verification_uri_complete", ""), + expires_in=int(data.get("expires_in", 0)), + interval=int(data.get("interval", 5)), + ) + except (KeyError, TypeError, ValueError, OverflowError): + pass + raise CloudAPIError(operation=operation, code="auth_failed") + + async def poll_token(self, client_id: str, code: CodeResponse) -> str: + """Poll for approval; raise on denial or expiration.""" + operation = "Exchange device code" + self._billing.require(Billing.NO_COMMERCE, operation) + settings = get_settings() + interval = max( + float(code.interval), settings.MOBILERUN_DEVICE_AUTH_MIN_POLL_INTERVAL + ) + deadline = time.monotonic() + code.expires_in + while True: + await asyncio.sleep(interval) + try: + data = await self._request( + "POST", + "/device/token", + operation, + polling=True, + body={ + "grant_type": "urn:ietf:params:oauth:grant-type:device_code", + "device_code": code.device_code, + "client_id": client_id, + }, + ) + except DeviceAuthError as exc: + if exc.code == "slow_down": + interval += settings.MOBILERUN_DEVICE_AUTH_SLOW_DOWN_BUMP + elif exc.code != "authorization_pending": + raise else: - raise - if time.monotonic() > deadline: - raise DeviceAuthError("expired_token", "device code expired") - - -@requires(Billing.NO_COMMERCE) -async def fetch_session( - auth_url: str, token: str, *, billing: Billing -) -> Optional[dict]: - """Retrieve the session; None means no active session.""" - resp = await _request( - "GET", - auth_url.rstrip("/") + "/get-session", - headers={"Accept": "application/json", "Authorization": f"Bearer {token}"}, - timeout=get_settings().MOBILERUN_DEVICE_AUTH_REQUEST_TIMEOUT, - ) - if not (200 <= resp.status_code < 300): - try: - resp.raise_for_status() - except httpx.HTTPStatusError as exc: - raise cloud_error(exc, "Retrieve authentication session") from exc - return resp.json() # better-auth returns null when there's no session + token = data.get("access_token") if data is not None else None + if not isinstance(token, str) or not token: + raise CloudAPIError(operation=operation, code="missing_token") + return token + if time.monotonic() > deadline: + raise DeviceAuthError("expired_token", "device code expired") + + async def fetch_session(self, token: str) -> dict[str, Any] | None: + """Retrieve the session; None means no active session.""" + operation = "Retrieve authentication session" + self._billing.require(Billing.NO_COMMERCE, operation) + return await self._request("GET", "/get-session", operation, token=token) diff --git a/mobilerun/clients/cloud/devices.py b/mobilerun/clients/cloud/devices.py deleted file mode 100644 index 7a6bd46be..000000000 --- a/mobilerun/clients/cloud/devices.py +++ /dev/null @@ -1,429 +0,0 @@ -"""Functional cloud device SDK boundaries.""" - -from collections.abc import Awaitable, Callable, Mapping -from contextlib import nullcontext -from datetime import datetime -from typing import Any, Literal, TypedDict, Unpack, cast - -import httpx -from mobilerun_sdk import APIError, AsyncMobilerun -from mobilerun_sdk._types import Body, Headers, NotGiven, Query, SequenceNotStr -from mobilerun_sdk.types import ( - DeviceCreateResponse, - DeviceRetrieveCapabilitiesResponse, - DeviceRetrieveResponse, - DeviceSetNameResponse, - DeviceWaitReadyResponse, -) -from mobilerun_sdk.types.device_create_params import DeviceCreateParams, Proxy -from mobilerun_sdk.types.device_list_response import Item as DeviceItem -from mobilerun_sdk.types.devices import ( - LanguageGetResponse, - NumberBindResponse, - NumberRetrieveResponse, - NumberUnbindResponse, - TimezoneGetResponse, -) -from mobilerun_sdk.types.shared.location import Location as DeviceLocation -from mobilerun_sdk.types.shared_params import DeviceCarrier, DeviceIdentifiers, Location - -from mobilerun.clients.cloud.billing import ( - _billing_preference, - _validate_create_params, - buys_connect_proxy, - requires, -) -from mobilerun.clients.cloud.client import cloud_client -from mobilerun.clients.cloud.errors import cloud_error -from mobilerun.models.billing import Billing, Plan -from mobilerun.utils.redaction import secret_scope - -DeviceCreateOptions = TypedDict( - "DeviceCreateOptions", - { - "query_country": str, - "device_type": Literal["android_cloud_phone", "ios_phone", "device_slot"], - "profile_id": str, - "template": str, - "android_version": int, - "apps": SequenceNotStr[str] | None, - "files": SequenceNotStr[str] | None, - "name": str, - "locale": str, - "timezone": str, - "body_country": str, - "carrier": DeviceCarrier, - "identifiers": DeviceIdentifiers, - "location": Location, - "extra_headers": Headers | None, - "extra_query": Query | None, - "extra_body": Body | None, - "timeout": float | httpx.Timeout | None | NotGiven, - "idempotency_key": str | None, - }, - total=False, -) - -RequestOptions = TypedDict( - "RequestOptions", - { - "extra_headers": Headers | None, - "extra_query": Query | None, - "extra_body": Body | None, - "timeout": float | httpx.Timeout | None | NotGiven, - "idempotency_key": str | None, - }, - total=False, -) -ReadOptions = TypedDict( - "ReadOptions", - { - "extra_headers": Headers | None, - "extra_query": Query | None, - "extra_body": Body | None, - "timeout": float | httpx.Timeout | None | NotGiven, - }, - total=False, -) -TerminateOptions = TypedDict( - "TerminateOptions", - { - "previous_device_id": str, - "terminate_at": str | datetime, - "extra_headers": Headers | None, - "extra_query": Query | None, - "extra_body": Body | None, - "timeout": float | httpx.Timeout | None | NotGiven, - "idempotency_key": str | None, - }, - total=False, -) -ResetOptions = TypedDict( - "ResetOptions", - { - "mode": Literal["full", "identity"], - "preserve": list[Literal["proxy", "location", "locale", "timezone"]] | None, - "extra_headers": Headers | None, - "extra_query": Query | None, - "extra_body": Body | None, - "timeout": float | httpx.Timeout | None | NotGiven, - "idempotency_key": str | None, - }, - total=False, -) - - -def _create_needs_paid(arguments: Mapping[str, Any]) -> bool: - """A metered plan or a new Connect proxy costs money.""" - plan = arguments.get("plan") - metered = plan is not None and Plan(plan) in (Plan.AUTO, Plan.MINUTE) - return metered or buys_connect_proxy(arguments.get("proxy")) - - -@requires(Billing.INCLUDED, paid_if=_create_needs_paid) -async def create( - *, - billing: Billing, - plan: Plan | str | None = None, - proxy: Proxy | None = None, - client: AsyncMobilerun | None = None, - api_key: str | None = None, - base_url: str | None = None, - **params: Unpack[DeviceCreateOptions], -) -> DeviceCreateResponse: - """Create a cloud phone, optionally with a Connect proxy.""" - await _validate_create_params(params, allow_proxy=True) - if proxy is None: - raise ValueError("A proxy is required to create a cloud phone") - if proxy is not None: - connect = proxy.get("connect") - socks = proxy.get("socks5") - valid_connect = isinstance(connect, dict) and bool( - connect.get("id") or connect.get("country") - ) - valid_socks = isinstance(socks, dict) and bool( - socks.get("host") and socks.get("port") - ) - if not (valid_connect or valid_socks): - raise ValueError("Pass a valid Connect or SOCKS5 proxy, or omit proxy") - _create_params = cast(DeviceCreateParams, params) - if proxy is not None: - _create_params["proxy"] = proxy - _create_params["billing"] = cast( - Literal["auto", "subscription", "minute"], - await _billing_preference("cloud phones", billing, plan=plan), - ) - async with ( - nullcontext(client) - if client is not None - else cloud_client(api_key, base_url, billing=billing) - ) as sdk: - socks = proxy.get("socks5") or {} - with secret_scope(socks.get("password", "")): - try: - return await sdk.devices.create(**_create_params) - except APIError as exc: - raise cloud_error(exc, "Create cloud phone", device=True) from exc - - -@requires(Billing.NO_COMMERCE) -async def list_devices( - *, - billing: Billing, - client: AsyncMobilerun | None = None, - api_key: str | None = None, - base_url: str | None = None, -) -> list[DeviceItem]: - """List every device page.""" - async with ( - nullcontext(client) - if client is not None - else cloud_client(api_key, base_url, billing=billing) - ) as sdk: - items, page = [], 1 - try: - while True: - response = await sdk.devices.list(page=page, page_size=100) - items.extend(cast(list[DeviceItem], response.items)) - if not response.pagination.has_next: - return items - page += 1 - except APIError as exc: - raise cloud_error(exc, "List cloud phones") from exc - - -@requires(Billing.NO_COMMERCE) -async def capabilities( - device_id: str, - *, - billing: Billing, - client: AsyncMobilerun | None = None, - api_key: str | None = None, - base_url: str | None = None, -) -> DeviceRetrieveCapabilitiesResponse: - """Retrieve a cloud phone's supported capabilities.""" - async with ( - nullcontext(client) - if client is not None - else cloud_client(api_key, base_url, billing=billing) - ) as sdk: - try: - return await sdk.devices.retrieve_capabilities(device_id) - except APIError as exc: - raise cloud_error( - exc, "Retrieve cloud phone capabilities", device=True - ) from exc - - -@requires(Billing.NO_COMMERCE) -async def set_name( - device_id: str, name: str, *, billing: Billing, client: AsyncMobilerun -) -> DeviceSetNameResponse: - """Set a cloud phone's display name and return its updated info.""" - try: - return await client.devices.set_name(device_id, name=name) - except APIError as exc: - raise cloud_error(exc, "Rename cloud phone", device=True) from exc - - -@requires(Billing.NO_COMMERCE) -async def retrieve( - device_id: str, *, billing: Billing, client: AsyncMobilerun -) -> DeviceRetrieveResponse: - """Retrieve a cloud phone.""" - try: - return await client.devices.retrieve(device_id) - except APIError as exc: - raise cloud_error(exc, "Retrieve cloud phone", device=True) from exc - - -@requires(Billing.NO_COMMERCE) -async def wait_ready( - device_id: str, - *, - billing: Billing, - client: AsyncMobilerun, - **params: Unpack[ReadOptions], -) -> DeviceWaitReadyResponse: - """Wait for phone readiness using SDK polling.""" - try: - return await client.devices.wait_ready(device_id, **params) - except APIError as exc: - raise cloud_error(exc, "Wait for cloud phone", device=True) from exc - - -@requires(Billing.NO_COMMERCE) -async def terminate( - device_id: str, - *, - billing: Billing, - client: AsyncMobilerun, - **params: Unpack[TerminateOptions], -) -> None: - """Terminate a cloud phone.""" - try: - return await client.devices.terminate(device_id, **params) - except APIError as exc: - raise cloud_error(exc, "Terminate cloud phone", device=True) from exc - - -@requires(Billing.NO_COMMERCE) -async def resume( - device_id: str, - *, - billing: Billing, - client: AsyncMobilerun, - **params: Unpack[RequestOptions], -) -> None: - """Resume an existing phone without starting minute billing unless authorized.""" - if billing is Billing.PAID: - return await _resume(device_id, client=client, **params) - operation, _ = await _prepare_resume( - device_id, billing=billing, client=client, **params - ) - return await operation(billing) - - -@requires(Billing.PAID, operation="Resume cloud phone") -def _require_paid_resume(*, billing: Billing) -> None: - """Reject restricted billing before a potentially metered resume.""" - - -async def _prepare_resume( - device_id: str, - *, - billing: Billing, - client: AsyncMobilerun, - **params: Unpack[RequestOptions], -) -> tuple[Callable[[Billing], Awaitable[None]], bool]: - """Resolve the billing strategy once, outside any retry of the mutation.""" - needs_paid = ( - await retrieve(device_id, billing=billing, client=client) - ).billing_strategy != Plan.SUBSCRIPTION - - async def resume_prepared(mode: Billing) -> None: - if needs_paid: - _require_paid_resume(billing=mode) - return await _resume(device_id, client=client, **params) - - return resume_prepared, needs_paid - - -async def _resume( - device_id: str, *, client: AsyncMobilerun, **params: Unpack[RequestOptions] -) -> None: - try: - return await client.devices.resume(device_id, **params) - except APIError as exc: - raise cloud_error(exc, "Resume cloud phone", device=True) from exc - - -@requires(Billing.NO_COMMERCE) -async def stop( - device_id: str, - *, - billing: Billing, - client: AsyncMobilerun, - **params: Unpack[RequestOptions], -) -> None: - """Stop a cloud phone.""" - try: - return await client.devices.stop(device_id, **params) - except APIError as exc: - raise cloud_error(exc, "Stop cloud phone", device=True) from exc - - -@requires(Billing.NO_COMMERCE) -async def reboot( - device_id: str, - *, - billing: Billing, - client: AsyncMobilerun, - **params: Unpack[RequestOptions], -) -> None: - """Reboot a cloud phone.""" - try: - return await client.devices.reboot(device_id, **params) - except APIError as exc: - raise cloud_error(exc, "Reboot cloud phone", device=True) from exc - - -@requires(Billing.NO_COMMERCE) -async def reset( - device_id: str, - *, - billing: Billing, - client: AsyncMobilerun, - **params: Unpack[ResetOptions], -) -> None: - """Reset a cloud phone.""" - try: - return await client.devices.reset(device_id, **params) - except APIError as exc: - raise cloud_error(exc, "Reset cloud phone", device=True) from exc - - -@requires(Billing.NO_COMMERCE) -async def get_location( - device_id: str, *, billing: Billing, client: AsyncMobilerun -) -> DeviceLocation | None: - """Retrieve the simulated GPS location of a cloud phone.""" - try: - return await client.devices.location.get(device_id) - except APIError as exc: - raise cloud_error(exc, "Retrieve cloud phone location", device=True) from exc - - -@requires(Billing.NO_COMMERCE) -async def number( - device_id: str, *, billing: Billing, client: AsyncMobilerun -) -> NumberRetrieveResponse: - """Retrieve the bound number.""" - try: - return await client.devices.number.retrieve(device_id) - except APIError as exc: - raise cloud_error(exc, "Retrieve phone number binding", device=True) from exc - - -@requires(Billing.NO_COMMERCE) -async def get_language( - device_id: str, *, billing: Billing, client: AsyncMobilerun -) -> LanguageGetResponse: - """Retrieve the phone's BCP-47 locale.""" - try: - return await client.devices.language.get(device_id) - except APIError as exc: - raise cloud_error(exc, "Retrieve cloud phone language", device=True) from exc - - -@requires(Billing.NO_COMMERCE) -async def get_timezone( - device_id: str, *, billing: Billing, client: AsyncMobilerun -) -> TimezoneGetResponse: - """Retrieve the phone's IANA timezone.""" - try: - return await client.devices.timezone.get(device_id) - except APIError as exc: - raise cloud_error(exc, "Retrieve cloud phone timezone", device=True) from exc - - -@requires(Billing.NO_COMMERCE) -async def bind_number( - device_id: str, number_id: str, *, billing: Billing, client: AsyncMobilerun -) -> NumberBindResponse: - """Bind an existing number.""" - try: - return await client.devices.number.bind(device_id, number_id=number_id) - except APIError as exc: - raise cloud_error(exc, "Bind phone number", device=True) from exc - - -@requires(Billing.NO_COMMERCE) -async def unbind_number( - device_id: str, *, billing: Billing, client: AsyncMobilerun -) -> NumberUnbindResponse: - """Unbind a number.""" - try: - return await client.devices.number.unbind(device_id) - except APIError as exc: - raise cloud_error(exc, "Unbind phone number", device=True) from exc diff --git a/mobilerun/clients/cloud/errors.py b/mobilerun/clients/cloud/errors.py index 12a5b76f9..a90474b61 100644 --- a/mobilerun/clients/cloud/errors.py +++ b/mobilerun/clients/cloud/errors.py @@ -1,6 +1,6 @@ -"""Sanitized cloud transport errors; never include server text or URLs.""" +"""Translate detached transport facts to framework errors.""" -import httpx +from mobilerun_core import CloudErrorFacts, cloud_error_facts from mobilerun.errors import ( CloudAPIError, @@ -19,69 +19,79 @@ from mobilerun.errors.cloud import NumberNotCancellable -def cloud_error( - exc: BaseException, operation: str, *, device: bool = False -) -> CloudAPIError: - """Build a safe public error from transport metadata, not response content.""" - # SDK and httpx exception classes expose different optional metadata fields. - status = getattr(exc, "status_code", None) - response = getattr(exc, "response", None) - if status is None and response is not None: - status = response.status_code - request_id = getattr(exc, "request_id", None) - if not request_id and response is not None: - request_id = response.headers.get("x-request-id") - kind = CloudAPIError - code = "request_failed" - if status == 401: - kind = CloudAuthenticationError - elif status == 403: - kind = CloudPermissionDenied - elif status == 404: - kind = CloudDeviceNotFound if device else CloudResourceNotFound - elif status == 409: - kind = CloudConflict - body = getattr(exc, "body", None) - if ( - operation == "Release number" - and isinstance(body, dict) - and body.get("code") == "not_cancellable" - ): - kind = NumberNotCancellable - elif status in {400, 422}: - kind = CloudValidationError - body = getattr(exc, "body", None) - detail = body.get("detail", []) if isinstance(body, dict) else [] - if isinstance(detail, list) and any( - isinstance(item, dict) - and isinstance(item.get("loc"), (list, tuple)) - and "deviceId" in item["loc"] - for item in detail - ): - kind = InvalidCloudDeviceId - if status == 422 and isinstance(body, dict): - if ( - operation == "Create number" - and body.get("code") == "unsupported_country" - ): - code = "unsupported_number_country" - elif ( - operation == "Create cloud phone" - and body.get("code") == "DEVICE_TYPE_UNAVAILABLE" - ): - code = "device_type_unavailable" - elif status == 429: - kind = CloudRateLimited - elif type(status) is int and status >= 500: - kind = CloudServiceUnavailable - elif ( - isinstance(exc, (TimeoutError, httpx.TimeoutException)) - or type(exc).__name__ == "APITimeoutError" - ): - kind = CloudTimeout - elif ( - isinstance(exc, httpx.RequestError) - or type(exc).__name__ == "APIConnectionError" - ): - kind = CloudConnectionError - return kind(operation=operation, status=status, request_id=request_id, code=code) +class CloudErrorMapper: + """Build safe errors using status and operation-specific known codes.""" + + _statuses: dict[int, type[CloudAPIError]] = { + 400: CloudValidationError, + 401: CloudAuthenticationError, + 403: CloudPermissionDenied, + 404: CloudResourceNotFound, + 409: CloudConflict, + 422: CloudValidationError, + 429: CloudRateLimited, + } + _transport: dict[str, type[CloudAPIError]] = { + "timeout": CloudTimeout, + "connection": CloudConnectionError, + } + _operations: dict[tuple[str, int, str], tuple[type[CloudAPIError], str]] = { + ("Release number", 409, "not_cancellable"): ( + NumberNotCancellable, + "request_failed", + ), + ("Create number", 409, "included_capacity_unavailable"): ( + CloudConflict, + "included_number_capacity", + ), + ("Create mailbox", 409, "included_capacity_unavailable"): ( + CloudConflict, + "included_mailbox_capacity", + ), + ("Create number", 409, "purchase_in_progress"): ( + CloudConflict, + "purchase_in_progress", + ), + ("Create number", 422, "unsupported_country"): ( + CloudValidationError, + "unsupported_number_country", + ), + ("Create cloud phone", 422, "DEVICE_TYPE_UNAVAILABLE"): ( + CloudValidationError, + "device_type_unavailable", + ), + } + + @classmethod + def from_facts( + cls, facts: CloudErrorFacts, operation: str, *, device: bool = False + ) -> CloudAPIError: + """Build an error without retaining payload or URL in its fields.""" + status = facts.status_code + kind, code = CloudAPIError, "request_failed" + if status is not None: + kind = cls._statuses.get(status, CloudAPIError) + if status >= 500: + kind = CloudServiceUnavailable + elif status == 404 and device: + kind = CloudDeviceNotFound + elif status in {400, 422} and facts.invalid_device_id: + kind = InvalidCloudDeviceId + if facts.code is not None: + known = cls._operations.get((operation, status, facts.code)) + if known is not None: + if kind is not InvalidCloudDeviceId: + kind = known[0] + code = known[1] + if kind is CloudAPIError: + kind = cls._transport.get(facts.kind, CloudAPIError) + return kind( + operation=operation, status=status, request_id=facts.request_id, code=code + ) + + @classmethod + def from_exception( + cls, exc: BaseException, operation: str, *, device: bool = False + ) -> CloudAPIError: + """Detach transport facts before building a safe framework error.""" + return cls.from_facts(cloud_error_facts(exc), operation, device=device) diff --git a/mobilerun/clients/cloud/files.py b/mobilerun/clients/cloud/files.py deleted file mode 100644 index aad43c31e..000000000 --- a/mobilerun/clients/cloud/files.py +++ /dev/null @@ -1,152 +0,0 @@ -"""Cloud workspace file transport.""" - -import mimetypes -import posixpath -from pathlib import Path - -import httpx -from mobilerun_sdk import APIError, AsyncMobilerun -from mobilerun_sdk.types.file_confirm_response import FileConfirmResponse -from mobilerun_sdk.types.file_list_response import File - -from mobilerun.clients.cloud.billing import requires -from mobilerun.clients.cloud.errors import cloud_error -from mobilerun.clients.cloud.signed_http import _signed_client, _signed_transfer_logs -from mobilerun.models import Billing, DeviceFile, WorkspaceFile - - -def _file(item: File | FileConfirmResponse) -> WorkspaceFile: - return WorkspaceFile( - item.file_id, - item.filename, - item.mime_type, - int(item.size_bytes), - item.created_at, - ) - - -@requires(Billing.NO_COMMERCE) -async def upload_file( - client: AsyncMobilerun, path: str | Path, *, billing: Billing -) -> WorkspaceFile: - path = Path(path) - content = path.read_bytes() - mime_type = mimetypes.guess_type(path.name)[0] or "application/octet-stream" - try: - signed = await client.files.upload_url( - filename=path.name, - mime_type=mime_type, - size_bytes=len(content), - zone="user", - ) - except APIError as exc: - raise cloud_error(exc, "Prepare file upload") from exc - try: - async with _signed_client(httpx.AsyncClient()) as http: - response = await http.put( - signed.put_url, - content=content, - headers={"Content-Type": mime_type}, - timeout=None, - ) - response.raise_for_status() - return _file(await client.files.confirm(signed.file_id)) - except BaseException as exc: - try: - await client.files.cancel_pending(signed.file_id) - except Exception: - pass - if isinstance(exc, (APIError, httpx.HTTPError, httpx.InvalidURL)): - raise cloud_error(exc, "Upload file") from None - raise - - -@requires(Billing.NO_COMMERCE) -async def list_files( - client: AsyncMobilerun, *, billing: Billing -) -> list[WorkspaceFile]: - try: - result = await client.files.list(zone="user") - return [_file(item) for item in result.files] - except APIError as exc: - raise cloud_error(exc, "List files") from exc - - -@requires(Billing.NO_COMMERCE) -async def download_file( - client: AsyncMobilerun, file_id: str, *, billing: Billing -) -> bytes: - try: - with _signed_transfer_logs(): - response = await client.files.with_raw_response.download(file_id) - return await response.read() - except (APIError, httpx.HTTPError) as exc: - raise cloud_error(exc, "Download file") from None - - -@requires(Billing.NO_COMMERCE) -async def delete_file( - client: AsyncMobilerun, file_id: str, *, billing: Billing -) -> None: - try: - await client.files.delete(file_id) - except APIError as exc: - raise cloud_error(exc, "Delete file") from exc - - -@requires(Billing.NO_COMMERCE) -async def push_device_file( - client: AsyncMobilerun, - device_id: str, - path: Path, - directory: str, - *, - billing: Billing, -) -> None: - try: - await client.devices.files.upload(device_id, path=directory, file=path) - except APIError as exc: - raise cloud_error(exc, "Upload device file", device=True) from exc - - -@requires(Billing.NO_COMMERCE) -async def list_device_files( - client: AsyncMobilerun, device_id: str, directory: str, *, billing: Billing -) -> list[DeviceFile]: - try: - result = await client.devices.files.list(device_id, path=directory) - return [ - DeviceFile( - posixpath.join(directory, item.name), - item.name, - item.size, - item.modified_at, - ) - for item in result.files or [] - ] - except APIError as exc: - raise cloud_error(exc, "List device files", device=True) from exc - - -@requires(Billing.NO_COMMERCE) -async def download_device_file( - client: AsyncMobilerun, device_id: str, remote_path: str, *, billing: Billing -) -> bytes: - try: - with _signed_transfer_logs(): - response = await client.devices.files.with_raw_response.download( - device_id, path=remote_path - ) - return await response.read() - except (APIError, httpx.HTTPError) as exc: - raise cloud_error(exc, "Download device file", device=True) from None - - -@requires(Billing.NO_COMMERCE) -async def delete_device_file( - client: AsyncMobilerun, device_id: str, remote_path: str, *, billing: Billing -) -> None: - try: - await client.devices.files.delete(device_id, path=remote_path) - except APIError as exc: - raise cloud_error(exc, "Delete device file", device=True) from exc diff --git a/mobilerun/clients/cloud/mailboxes.py b/mobilerun/clients/cloud/mailboxes.py index 2ef4135b7..318e8f39d 100644 --- a/mobilerun/clients/cloud/mailboxes.py +++ b/mobilerun/clients/cloud/mailboxes.py @@ -1,275 +1,148 @@ -"""Functional mailbox SDK boundaries.""" +"""SDK operations for cloud mailboxes and their messages.""" -from contextlib import nullcontext -from typing import Literal, Unpack, cast +from __future__ import annotations -from mobilerun_sdk import APIError, APIStatusError, AsyncMobilerun, NotFoundError +import builtins +from typing import Unpack + +from mobilerun_sdk import AsyncMobilerun, omit from mobilerun_sdk.types.mailbox_capacity_response import MailboxCapacityResponse -from mobilerun_sdk.types.mailbox_create_params import MailboxCreateParams +from mobilerun_sdk.types.mailbox_create_params import ( + MailboxCreateParams as MailboxCreateParams, +) from mobilerun_sdk.types.mailbox_create_response import MailboxCreateResponse -from mobilerun_sdk.types.mailbox_delete_response import MailboxDeleteResponse +from mobilerun_sdk.types.mailbox_delete_response import ( + MailboxDeleteResponse as MailboxDeleteResponse, +) from mobilerun_sdk.types.mailbox_list_response import Item from mobilerun_sdk.types.mailbox_otp_params import MailboxOtpParams from mobilerun_sdk.types.mailbox_otp_response import MailboxOtpResponse from mobilerun_sdk.types.mailbox_retrieve_response import MailboxRetrieveResponse from mobilerun_sdk.types.mailboxes.message_list_response import Item as MessageItem -from mobilerun.clients.cloud.billing import ( - _billing_preference, - _validate_create_params, - rents_resource, - requires, -) -from mobilerun.clients.cloud.checkout import CheckoutMode, checkout_callback -from mobilerun.clients.cloud.client import cloud_client -from mobilerun.clients.cloud.errors import cloud_error -from mobilerun.clients.cloud.payments import ( - CheckoutCallback, - PaymentAdapter, - wait_for_payment, - wait_until_active, +from mobilerun.clients.cloud.payments import PaymentFlow +from mobilerun.clients.cloud.resource import CloudResource +from mobilerun.errors import ( + CloudConflict, + CloudResourceNotFound, + IncludedCapacityUnavailable, ) -from mobilerun.errors import IncludedCapacityUnavailable from mobilerun.models.billing import Billing, ResourcePlan -from mobilerun.models.checkout import PaymentSnapshot - - -@requires(Billing.INCLUDED, operation="Create mailbox", paid_if=rents_resource) -async def create( - *, - billing: Billing, - plan: ResourcePlan | str | None = None, - client: AsyncMobilerun | None = None, - api_key: str | None = None, - base_url: str | None = None, - keep: bool = False, - on_checkout: CheckoutCallback | None = None, - checkout: CheckoutMode = "error", - payment_timeout: float = 600, - **params: Unpack[MailboxCreateParams], -) -> MailboxCreateResponse: - """Provision a mailbox.""" - on_checkout = checkout_callback(checkout, on_checkout) - await _validate_create_params(params) - unknown = params.keys() - MailboxCreateParams.__annotations__.keys() - if unknown: - raise TypeError(f"Unexpected create options: {', '.join(sorted(unknown))}") - params["billing_preference"] = cast( - Literal["included", "included_only", "rent"], - await _billing_preference("mailboxes", billing, plan=plan), - ) - async with ( - nullcontext(client) - if client is not None - else cloud_client(api_key, base_url, billing=billing) - ) as sdk: - try: - response = await sdk.mailboxes.create(**params) - - if response.data.status == "awaiting_payment": - - async def payment_state() -> PaymentSnapshot: - data = (await sdk.mailboxes.retrieve(response.data.id)).data - return PaymentSnapshot( - data.status, data.checkout_url, data.checkout_expires_at - ) - - async def resume(timeout: float) -> MailboxRetrieveResponse: - async def fetch() -> PaymentSnapshot: - data = ( - await retrieve( - response.data.id, - billing=Billing.NO_COMMERCE, - client=client, - api_key=api_key, - base_url=base_url, - ) - ).data +from mobilerun.models.checkout import CheckoutCallback, PaymentSnapshot +from mobilerun.utils.checkout.presentation import CheckoutMode, checkout_callback + + +class Mailboxes(CloudResource): + """Operate on the mailboxes of one cloud account.""" + + async def create( + self, + *, + plan: ResourcePlan | str | None = None, + on_checkout: CheckoutCallback | None = None, + checkout: CheckoutMode = "error", + payment_timeout: float = 600, + **params: Unpack[MailboxCreateParams], + ) -> MailboxCreateResponse: + """Provision a mailbox or hand off checkout for the new mailbox.""" + mode = self._billing.require( + Billing.INCLUDED, "Create mailbox", plan=plan, invalid_operation="create" + ) + on_checkout = checkout_callback(checkout, on_checkout) + self._billing.validate_create_params(params) + unknown = params.keys() - MailboxCreateParams.__annotations__.keys() + if unknown: + raise TypeError(f"Unexpected create options: {', '.join(sorted(unknown))}") + params["billing_preference"] = self._billing.resource_preference(plan) + async with self._client(mode) as sdk: + try: + with self._errors("Create mailbox"): + response = await sdk.mailboxes.create(**params) + data = response.data + if data.status != "awaiting_payment": + return response + mailbox_id = data.id + + async def fetch(client: AsyncMobilerun) -> PaymentSnapshot: + state = (await client.mailboxes.retrieve(mailbox_id)).data return PaymentSnapshot( - data.status, data.checkout_url, data.checkout_expires_at + state.status, state.checkout_url, state.checkout_expires_at ) - adapter = PaymentAdapter( - "mailbox", - response.data.id, - fetch, - lambda: sdk.mailboxes.delete(response.data.id), - ) - await wait_until_active(adapter, timeout=timeout) - return await retrieve( - response.data.id, - billing=Billing.NO_COMMERCE, - client=client, - api_key=api_key, - base_url=base_url, + async def resume(timeout: float) -> MailboxRetrieveResponse: + async with self._client(Billing.NO_COMMERCE) as client: + with self._errors("Retrieve mailbox"): + await PaymentFlow( + "mailbox", mailbox_id, lambda: fetch(client) + ).wait_until_active(timeout=timeout) + return await client.mailboxes.retrieve(mailbox_id) + + await PaymentFlow( + "mailbox", mailbox_id, lambda: fetch(sdk) + ).wait_for_payment( + PaymentSnapshot( + data.status, data.checkout_url, data.checkout_expires_at + ), + resume=resume, + on_checkout=on_checkout, + timeout=payment_timeout, ) - - await wait_for_payment( - PaymentAdapter( - "mailbox", - response.data.id, - payment_state, - lambda: sdk.mailboxes.delete(response.data.id), - ), - PaymentSnapshot( - response.data.status, - response.data.checkout_url, - response.data.checkout_expires_at, - ), - resume=resume, - on_checkout=on_checkout, - timeout=payment_timeout, - ) + except CloudConflict as exc: + if exc.code == "included_mailbox_capacity": + raise IncludedCapacityUnavailable("mailbox") from None + raise return response - except APIError as exc: - body = getattr(exc, "body", None) - if ( - isinstance(exc, APIStatusError) - and exc.status_code == 409 - and isinstance(body, dict) - and body.get("code") == "included_capacity_unavailable" - ): - raise IncludedCapacityUnavailable("mailbox") from None - raise cloud_error(exc, "Create mailbox") from exc - -@requires(Billing.NO_COMMERCE) -async def list_mailboxes( - *, - billing: Billing, - client: AsyncMobilerun | None = None, - api_key: str | None = None, - base_url: str | None = None, -) -> list[Item]: - """List every mailbox page.""" - async with ( - nullcontext(client) - if client is not None - else cloud_client(api_key, base_url, billing=billing) - ) as sdk: - items, page = [], 1 - try: + async def list(self) -> builtins.list[Item]: + """List every mailbox page.""" + async with self._request("List mailboxes", Billing.NO_COMMERCE) as sdk: + items, page = [], 1 while True: response = await sdk.mailboxes.list(page=page, page_size=100) items.extend(response.items) if not response.pagination.has_next: return items page += 1 - except APIError as exc: - raise cloud_error(exc, "List mailboxes") from exc - -@requires(Billing.NO_COMMERCE) -async def retrieve( - mailbox_id: str, - *, - billing: Billing, - client: AsyncMobilerun | None = None, - api_key: str | None = None, - base_url: str | None = None, -) -> MailboxRetrieveResponse: - """Retrieve a mailbox.""" - async with ( - nullcontext(client) - if client is not None - else cloud_client(api_key, base_url, billing=billing) - ) as sdk: - try: + async def retrieve(self, mailbox_id: str) -> MailboxRetrieveResponse: + """Retrieve a mailbox.""" + async with self._request("Retrieve mailbox", Billing.NO_COMMERCE) as sdk: return await sdk.mailboxes.retrieve(mailbox_id) - except APIError as exc: - raise cloud_error(exc, "Retrieve mailbox") from exc - -@requires(Billing.NO_COMMERCE) -async def delete( - mailbox_id: str, - *, - billing: Billing, - client: AsyncMobilerun | None = None, - api_key: str | None = None, - base_url: str | None = None, -) -> MailboxDeleteResponse: - """Release a mailbox.""" - async with ( - nullcontext(client) - if client is not None - else cloud_client(api_key, base_url, billing=billing) - ) as sdk: - try: + async def delete(self, mailbox_id: str) -> MailboxDeleteResponse: + """Release a mailbox.""" + async with self._request("Release mailbox", Billing.NO_COMMERCE) as sdk: return await sdk.mailboxes.delete(mailbox_id) - except APIError as exc: - raise cloud_error(exc, "Release mailbox") from exc - -@requires(Billing.NO_COMMERCE) -async def capacity( - *, - billing: Billing, - client: AsyncMobilerun | None = None, - api_key: str | None = None, - base_url: str | None = None, -) -> MailboxCapacityResponse: - """Retrieve mailbox capacity.""" - async with ( - nullcontext(client) - if client is not None - else cloud_client(api_key, base_url, billing=billing) - ) as sdk: - try: + async def capacity(self) -> MailboxCapacityResponse: + """Retrieve mailbox capacity.""" + async with self._request( + "Retrieve mailbox capacity", Billing.NO_COMMERCE + ) as sdk: return await sdk.mailboxes.capacity() - except APIError as exc: - raise cloud_error(exc, "Retrieve mailbox capacity") from exc - -@requires(Billing.NO_COMMERCE) -async def otp( - mailbox_id: str, - *, - billing: Billing, - client: AsyncMobilerun | None = None, - api_key: str | None = None, - base_url: str | None = None, - **params: Unpack[MailboxOtpParams], -) -> MailboxOtpResponse | None: - """Retrieve an OTP; no matching message returns None.""" - async with ( - nullcontext(client) - if client is not None - else cloud_client(api_key, base_url, billing=billing) - ) as sdk: + async def otp( + self, mailbox_id: str, **params: Unpack[MailboxOtpParams] + ) -> MailboxOtpResponse | None: + """Retrieve an OTP; no matching message returns None.""" try: - return await sdk.mailboxes.otp(mailbox_id, **params) - except NotFoundError: + async with self._request( + "Retrieve mailbox OTP", Billing.NO_COMMERCE + ) as sdk: + return await sdk.mailboxes.otp(mailbox_id, **params) + except CloudResourceNotFound: return None - except APIError as exc: - raise cloud_error(exc, "Retrieve mailbox OTP") from exc - -@requires(Billing.NO_COMMERCE) -async def messages( - mailbox_id: str, - *, - billing: Billing, - client: AsyncMobilerun | None = None, - api_key: str | None = None, - base_url: str | None = None, -) -> list[MessageItem]: - """List all mailbox message pages.""" - async with ( - nullcontext(client) - if client is not None - else cloud_client(api_key, base_url, billing=billing) - ) as sdk: - items: list[MessageItem] = [] - cursor = None - try: + async def messages(self, mailbox_id: str) -> builtins.list[MessageItem]: + """List all mailbox message pages.""" + async with self._request("List mailbox messages", Billing.NO_COMMERCE) as sdk: + items: list[MessageItem] = [] + cursor = None while True: response = await sdk.mailboxes.messages.list( - mailbox_id, **({"cursor": cursor} if cursor else {}) + mailbox_id, cursor=cursor or omit ) items.extend(response.items) cursor = response.next_cursor if not cursor: return items - except APIError as exc: - raise cloud_error(exc, "List mailbox messages") from exc diff --git a/mobilerun/clients/cloud/numbers.py b/mobilerun/clients/cloud/numbers.py index 175e5bc0d..fa63dac0b 100644 --- a/mobilerun/clients/cloud/numbers.py +++ b/mobilerun/clients/cloud/numbers.py @@ -1,11 +1,13 @@ -"""Functional number SDK boundaries.""" +"""SDK operations for cloud phone numbers and their messages.""" -from contextlib import nullcontext +from __future__ import annotations + +import builtins from datetime import datetime from typing import Literal, TypedDict, Unpack, cast import httpx -from mobilerun_sdk import APIError, APIStatusError, AsyncMobilerun +from mobilerun_sdk import AsyncMobilerun from mobilerun_sdk._types import Body, Headers, NotGiven, Query from mobilerun_sdk.types import ( NumberCapacityResponse, @@ -16,347 +18,223 @@ ) from mobilerun_sdk.types.number_create_params import NumberCreateParams from mobilerun_sdk.types.number_list_response import Item as NumberItem -from mobilerun_sdk.types.numbers import MessageSendResponse +from mobilerun_sdk.types.numbers import MessageSendResponse as MessageSendResponse from mobilerun_sdk.types.numbers.message_list_response import Item as MessageItem -from mobilerun.clients.cloud.billing import ( - _billing_preference, - _validate_create_params, - rents_resource, - requires, -) -from mobilerun.clients.cloud.checkout import CheckoutMode, checkout_callback -from mobilerun.clients.cloud.client import cloud_client -from mobilerun.clients.cloud.errors import cloud_error -from mobilerun.clients.cloud.payments import ( - CheckoutCallback, - PaymentAdapter, - wait_for_payment, - wait_until_active, -) +from mobilerun.clients.cloud.payments import PaymentFlow +from mobilerun.clients.cloud.resource import CloudResource from mobilerun.errors import ( + CloudAPIError, CloudConflict, IncludedCapacityUnavailable, PurchaseInProgress, ) from mobilerun.models.billing import Billing, ResourcePlan -from mobilerun.models.checkout import Checkout, PaymentSnapshot +from mobilerun.models.checkout import Checkout, CheckoutCallback, PaymentSnapshot +from mobilerun.utils.checkout.presentation import CheckoutMode, checkout_callback from mobilerun.utils.timestamps import to_api_timestamp -NumberCreateOptions = TypedDict( - "NumberCreateOptions", - { - "country": str, - "label": str | None, - "extra_headers": Headers | None, - "extra_query": Query | None, - "extra_body": Body | None, - "timeout": float | httpx.Timeout | None | NotGiven, - "idempotency_key": str | None, - }, - total=False, -) - - -MessageOptions = TypedDict( - "MessageOptions", - { - "direction": Literal["all", "inbound", "outbound"], - "since": str | datetime, - "extra_headers": Headers | None, - "extra_query": Query | None, - "extra_body": Body | None, - "timeout": float | httpx.Timeout | None | NotGiven, - }, - total=False, -) - - -@requires(Billing.INCLUDED, operation="Create number", paid_if=rents_resource) -async def create( - *, - billing: Billing, - plan: ResourcePlan | str | None = None, - client: AsyncMobilerun | None = None, - api_key: str | None = None, - base_url: str | None = None, - keep: bool = False, - on_checkout: CheckoutCallback | None = None, - checkout: CheckoutMode = "error", - payment_timeout: float = 600, - **params: Unpack[NumberCreateOptions], -) -> NumberCreateResponse: - """Provision a phone number.""" - on_checkout = checkout_callback(checkout, on_checkout) - await _validate_create_params(params) - unknown = params.keys() - NumberCreateOptions.__annotations__.keys() - if unknown: - raise TypeError(f"Unexpected create options: {', '.join(sorted(unknown))}") - _create_params = cast(NumberCreateParams, params) - _create_params["billing_preference"] = cast( - Literal["included", "included_only", "rent"], - await _billing_preference("numbers", billing, plan=plan), - ) - async with ( - nullcontext(client) - if client is not None - else cloud_client(api_key, base_url, billing=billing) - ) as sdk: - try: - response = await sdk.numbers.create(**_create_params) - async def payment_state() -> PaymentSnapshot: - data = (await sdk.numbers.retrieve(response.data.number_id)).data - return PaymentSnapshot(data.state, data.checkout_url) - - async def resume(timeout: float) -> NumberRetrieveResponse: - async def fetch() -> PaymentSnapshot: - data = ( - await retrieve( - response.data.number_id, - billing=Billing.NO_COMMERCE, - client=client, - api_key=api_key, - base_url=base_url, - ) - ).data - return PaymentSnapshot(data.state, data.checkout_url) - - adapter = PaymentAdapter( - "phone number", - response.data.number_id, - fetch, - lambda: sdk.numbers.delete(response.data.number_id), - ) - await wait_until_active(adapter, timeout=timeout) - return await retrieve( - response.data.number_id, - billing=Billing.NO_COMMERCE, - client=client, - api_key=api_key, - base_url=base_url, - ) +class NumberCreateOptions(TypedDict, total=False): + country: str + label: str | None + extra_headers: Headers | None + extra_query: Query | None + extra_body: Body | None + timeout: float | httpx.Timeout | None | NotGiven + idempotency_key: str | None + + +class MessageOptions(TypedDict, total=False): + direction: Literal["all", "inbound", "outbound"] + since: str | datetime + extra_headers: Headers | None + extra_query: Query | None + extra_body: Body | None + timeout: float | httpx.Timeout | None | NotGiven + + +class Numbers(CloudResource): + """Operate on the phone numbers of one cloud account.""" + + async def create( + self, + *, + plan: ResourcePlan | str | None = None, + on_checkout: CheckoutCallback | None = None, + checkout: CheckoutMode = "error", + payment_timeout: float = 600, + **params: Unpack[NumberCreateOptions], + ) -> NumberCreateResponse: + """Provision a number or expose checkout without buying a duplicate.""" + mode = self._billing.require( + Billing.INCLUDED, "Create number", plan=plan, invalid_operation="create" + ) + on_checkout = checkout_callback(checkout, on_checkout) + self._billing.validate_create_params(params) + unknown = params.keys() - NumberCreateOptions.__annotations__.keys() + if unknown: + raise TypeError(f"Unexpected create options: {', '.join(sorted(unknown))}") + purchase = cast(NumberCreateParams, params) + purchase["billing_preference"] = self._billing.resource_preference(plan) + async with self._client(mode) as sdk: + try: + with self._errors("Create number"): + response = await sdk.numbers.create(**purchase) + await self._wait_for_purchase( + sdk, response, on_checkout, payment_timeout + ) + except CloudConflict as exc: + if exc.code == "included_number_capacity": + raise IncludedCapacityUnavailable( + "number", country=params.get("country") + ) from None + if exc.code != "purchase_in_progress": + raise + conflict = await self._pending_purchase(sdk, exc, purchase, mode) + raise conflict from None + return response - await wait_for_payment( - PaymentAdapter( - "phone number", - response.data.number_id, - payment_state, - lambda: sdk.numbers.delete(response.data.number_id), - ), - PaymentSnapshot(response.data.state, response.data.checkout_url), - resume=resume, - on_checkout=on_checkout, - timeout=payment_timeout, + async def _pending_purchase( + self, + sdk: AsyncMobilerun, + conflict: CloudConflict, + params: NumberCreateParams, + mode: Billing, + ) -> CloudConflict: + # The listing cannot verify idempotency or opaque request overrides. + pending: list[NumberItem] = [] + if ( + mode is Billing.PAID + and params.get("billing_preference") != "included_only" + and params.get("idempotency_key") is None + and not any( + params.get(key) + for key in ("extra_body", "extra_query", "extra_headers") ) - return response - except APIError as exc: - body = getattr(exc, "body", None) - if ( - isinstance(exc, APIStatusError) - and exc.status_code == 409 - and isinstance(body, dict) - and body.get("code") == "included_capacity_unavailable" - ): - raise IncludedCapacityUnavailable( - "number", country=params.get("country") - ) from None - if ( - isinstance(exc, APIStatusError) - and exc.status_code == 409 - and isinstance(body, dict) - and body.get("code") == "purchase_in_progress" - ): - conflict = CloudConflict( + ): + try: + with self._errors("List numbers"): + pending = [ + item + for item in await self._list_pages(sdk) + if item.state in {"awaiting_payment", "provisioning"} + ] + except CloudAPIError: + # If lookup fails, keep the original purchase conflict. + return CloudConflict( operation="Create number", status=409, - request_id=exc.response.headers.get("x-request-id"), - ) - conflict.add_note( - "Another number purchase is pending. Check it in the dashboard; checkout was not resumed." + request_id=conflict.request_id, ) - # The listing cannot verify idempotency or opaque request overrides. - if ( - billing is not Billing.PAID - or _create_params["billing_preference"] == "included_only" - or params.get("idempotency_key") is not None - or params.get("extra_body") - or params.get("extra_query") - or params.get("extra_headers") - ): - raise conflict from None - pending = [] - page = 1 - try: - while True: - result = await sdk.numbers.list(page=page, page_size=100) - pending.extend( - item - for item in result.items - if item.state in ("awaiting_payment", "provisioning") - ) - if not result.pagination.has_next: - break - page += 1 - except APIError: - raise cloud_error(exc, "Create number") from None - if len(pending) == 1: - item = pending[0] - country = params.get("country") - label = params.get("label") - # Only awaiting_payment represents a paid checkout. A - # provisioning number could instead be an included slot. - if ( - item.state != "awaiting_payment" - or ( - country is not None - and (item.country_code or "").upper() != country.upper() - ) - or label != item.label - ): - raise conflict from None - pending_checkout = ( - Checkout(item.checkout_url, None, "phone number", item.id) - if item.checkout_url - else None - ) - raise PurchaseInProgress(item.id, pending_checkout) from None - raise conflict from None - raise cloud_error(exc, "Create number") from exc + if len(pending) == 1: + item = pending[0] + country = params.get("country") + # Provisioning may represent an included slot, not a paid checkout. + if ( + item.state == "awaiting_payment" + and ( + country is None + or (item.country_code or "").upper() == country.upper() + ) + and params.get("label") == item.label + ): + checkout = ( + Checkout(item.checkout_url, None, "phone number", item.id) + if item.checkout_url + else None + ) + return PurchaseInProgress(item.id, checkout) + failure = CloudConflict( + operation="Create number", status=409, request_id=conflict.request_id + ) + failure.add_note( + "Another number purchase is pending. Check it in the dashboard; checkout was not resumed." + ) + return failure + + async def _wait_for_purchase( + self, + sdk: AsyncMobilerun, + response: NumberCreateResponse, + on_checkout: CheckoutCallback | None, + timeout: float, + ) -> None: + number_id = response.data.number_id + + async def fetch(client: AsyncMobilerun) -> PaymentSnapshot: + data = (await client.numbers.retrieve(number_id)).data + return PaymentSnapshot(data.state, data.checkout_url) + + async def resume(timeout: float) -> NumberRetrieveResponse: + # The original create may have closed its client before the caller resumes. + async with self._request("Retrieve number", Billing.NO_COMMERCE) as client: + await PaymentFlow( + "phone number", number_id, lambda: fetch(client) + ).wait_until_active(timeout=timeout) + return await client.numbers.retrieve(number_id) + + await PaymentFlow( + "phone number", number_id, lambda: fetch(sdk) + ).wait_for_payment( + PaymentSnapshot(response.data.state, response.data.checkout_url), + resume=resume, + on_checkout=on_checkout, + timeout=timeout, + ) -@requires(Billing.NO_COMMERCE) -async def list_numbers( - *, - billing: Billing, - client: AsyncMobilerun | None = None, - api_key: str | None = None, - base_url: str | None = None, -) -> list[NumberItem]: - """List every number page.""" - async with ( - nullcontext(client) - if client is not None - else cloud_client(api_key, base_url, billing=billing) - ) as sdk: + @staticmethod + async def _list_pages(sdk: AsyncMobilerun) -> builtins.list[NumberItem]: items, page = [], 1 - try: - while True: - response = await sdk.numbers.list(page=page, page_size=100) - items.extend(response.items) - if not response.pagination.has_next: - return items - page += 1 - except APIError as exc: - raise cloud_error(exc, "List numbers") from exc - - -@requires(Billing.NO_COMMERCE) -async def retrieve( - number_id: str, - *, - billing: Billing, - client: AsyncMobilerun | None = None, - api_key: str | None = None, - base_url: str | None = None, -) -> NumberRetrieveResponse: - """Retrieve a number.""" - async with ( - nullcontext(client) - if client is not None - else cloud_client(api_key, base_url, billing=billing) - ) as sdk: - try: + while True: + response = await sdk.numbers.list(page=page, page_size=100) + items.extend(response.items) + if not response.pagination.has_next: + return items + page += 1 + + async def list(self) -> builtins.list[NumberItem]: + """List every number page.""" + async with self._request("List numbers", Billing.NO_COMMERCE) as sdk: + return await self._list_pages(sdk) + + async def retrieve(self, number_id: str) -> NumberRetrieveResponse: + """Retrieve a number.""" + async with self._request("Retrieve number", Billing.NO_COMMERCE) as sdk: return await sdk.numbers.retrieve(number_id) - except APIError as exc: - raise cloud_error(exc, "Retrieve number") from exc - -@requires(Billing.NO_COMMERCE) -async def delete( - number_id: str, - *, - billing: Billing, - client: AsyncMobilerun | None = None, - api_key: str | None = None, - base_url: str | None = None, -) -> NumberDeleteResponse: - """Release a number.""" - async with ( - nullcontext(client) - if client is not None - else cloud_client(api_key, base_url, billing=billing) - ) as sdk: - try: + async def delete(self, number_id: str) -> NumberDeleteResponse: + """Release a number.""" + async with self._request("Release number", Billing.NO_COMMERCE) as sdk: return await sdk.numbers.delete(number_id) - except APIError as exc: - raise cloud_error(exc, "Release number") from exc - -@requires(Billing.NO_COMMERCE) -async def countries( - *, - billing: Billing, - client: AsyncMobilerun | None = None, - api_key: str | None = None, - base_url: str | None = None, -) -> NumberCountriesResponse: - """List number countries.""" - async with ( - nullcontext(client) - if client is not None - else cloud_client(api_key, base_url, billing=billing) - ) as sdk: - try: + async def countries(self) -> NumberCountriesResponse: + """List number countries.""" + async with self._request("List number countries", Billing.NO_COMMERCE) as sdk: return await sdk.numbers.countries() - except APIError as exc: - raise cloud_error(exc, "List number countries") from exc - -@requires(Billing.NO_COMMERCE) -async def capacity( - country: str, - *, - billing: Billing, - client: AsyncMobilerun | None = None, - api_key: str | None = None, - base_url: str | None = None, -) -> NumberCapacityResponse: - """Retrieve number capacity.""" - async with ( - nullcontext(client) - if client is not None - else cloud_client(api_key, base_url, billing=billing) - ) as sdk: - try: + async def capacity(self, country: str) -> NumberCapacityResponse: + """Retrieve number capacity.""" + async with self._request( + "Retrieve number capacity", Billing.NO_COMMERCE + ) as sdk: return await sdk.numbers.capacity(country=country) - except APIError as exc: - raise cloud_error(exc, "Retrieve number capacity") from exc - -@requires(Billing.NO_COMMERCE) -async def messages( - number_id: str, - *, - billing: Billing, - after: str | datetime | None = None, - client: AsyncMobilerun | None = None, - api_key: str | None = None, - base_url: str | None = None, - **params: Unpack[MessageOptions], -) -> list[MessageItem]: - """List every SMS message page.""" - if after is not None: - params["since"] = ( - to_api_timestamp(after) if isinstance(after, datetime) else after - ) - async with ( - nullcontext(client) - if client is not None - else cloud_client(api_key, base_url, billing=billing) - ) as sdk: - items, page = [], 1 - try: + async def messages( + self, + number_id: str, + *, + after: str | datetime | None = None, + **params: Unpack[MessageOptions], + ) -> builtins.list[MessageItem]: + """List every SMS message page.""" + if after is not None: + params["since"] = ( + to_api_timestamp(after) if isinstance(after, datetime) else after + ) + async with self._request("List SMS messages", Billing.NO_COMMERCE) as sdk: + items, page = [], 1 while True: response = await sdk.numbers.messages.list( number_id, page=page, page_size=100, **params @@ -365,28 +243,8 @@ async def messages( if not response.pagination.has_next: return items page += 1 - except APIError as exc: - raise cloud_error(exc, "List SMS messages") from exc - -@requires(Billing.PAID, operation="Send SMS") -async def send( - number_id: str, - to: str, - text: str, - *, - billing: Billing, - client: AsyncMobilerun | None = None, - api_key: str | None = None, - base_url: str | None = None, -) -> MessageSendResponse: - """Send an SMS using an existing number.""" - async with ( - nullcontext(client) - if client is not None - else cloud_client(api_key, base_url, billing=billing) - ) as sdk: - try: + async def send(self, number_id: str, to: str, text: str) -> MessageSendResponse: + """Send an SMS using an existing number.""" + async with self._request("Send SMS", Billing.PAID) as sdk: return await sdk.numbers.messages.send(number_id, to=to, body=text) - except APIError as exc: - raise cloud_error(exc, "Send SMS") from exc diff --git a/mobilerun/clients/cloud/payments.py b/mobilerun/clients/cloud/payments.py index 8ab6e43ee..16bf8ecd6 100644 --- a/mobilerun/clients/cloud/payments.py +++ b/mobilerun/clients/cloud/payments.py @@ -7,134 +7,109 @@ from typing import TypeVar from mobilerun.errors import CloudAPIError, PaymentRequired -from mobilerun.models.checkout import Checkout, PaymentSnapshot +from mobilerun.models.checkout import Checkout, CheckoutCallback, PaymentSnapshot T = TypeVar("T") -CheckoutCallback = Callable[[Checkout], Awaitable[None] | None] @dataclass(frozen=True) -class PaymentAdapter: +class PaymentFlow: + """Wait for checkout and activation through resource-specific operations.""" + resource: str resource_id: str retrieve: Callable[[], Awaitable[PaymentSnapshot]] - cancel: Callable[[], Awaitable[object]] | None = None awaiting: frozenset[str] = frozenset({"awaiting_payment", "pending_payment"}) preparing: frozenset[str] = frozenset() active: frozenset[str] = frozenset({"active"}) provisioning: frozenset[str] = frozenset({"provisioning"}) + async def wait_until_active(self, *, timeout: float = 600) -> PaymentSnapshot: + """Wait for payment and provisioning without changing ownership.""" + loop = asyncio.get_running_loop() + deadline = loop.time() + timeout + attempt = 0 + try: + if timeout <= 0: + raise TimeoutError + async with asyncio.timeout(timeout): + while True: + state = await self.retrieve() + if state.status in self.active: + return state + if ( + state.status + not in self.awaiting | self.preparing | self.provisioning + ): + raise CloudAPIError(code="payment_failed", status=state.status) + remaining = deadline - loop.time() + if remaining <= 0: + raise TimeoutError + await asyncio.sleep(min((1, 2, 3, 5)[min(attempt, 3)], remaining)) + attempt += 1 + except TimeoutError as exc: + raise TimeoutError( + f"Timed out waiting for {self.resource} {self.resource_id}; check the dashboard." + ) from exc -async def wait_until_active( - adapter: PaymentAdapter, *, timeout: float = 600 -) -> PaymentSnapshot: - """Wait for payment and provisioning without changing resource ownership.""" - loop = asyncio.get_running_loop() - deadline = loop.time() + timeout - attempt = 0 - try: - if timeout <= 0: - raise TimeoutError - async with asyncio.timeout(timeout): + async def wait_for_payment( + self, + initial: PaymentSnapshot, + *, + resume: Callable[[float], Awaitable[T]], + on_checkout: CheckoutCallback | None = None, + timeout: float = 600, + checkout_timeout: float = 30, + ) -> PaymentSnapshot: + """Find checkout and hand it to the caller, or raise a resumable error.""" + if initial.status not in self.awaiting | self.preparing: + return initial + state = initial + loop = asyncio.get_running_loop() + deadline = loop.time() + checkout_timeout + attempt = 0 + try: while True: - state = await adapter.retrieve() - if state.status in adapter.active: + if state.status in self.awaiting and state.url: + checkout = Checkout( + state.url, state.expires_at, self.resource, self.resource_id + ) + if on_checkout is None: + raise PaymentRequired(checkout, resume) + async with asyncio.timeout(timeout): + result = on_checkout(checkout) + if inspect.isawaitable(result): + await result + return await self.wait_until_active(timeout=timeout) + if state.status in self.active or ( + initial.status in self.preparing + and state.status in self.provisioning + ): return state if ( state.status - not in adapter.awaiting | adapter.preparing | adapter.provisioning + not in self.awaiting | self.preparing | self.provisioning ): - error = CloudAPIError(code="payment_failed", status=state.status) - raise error + raise CloudAPIError(code="checkout_missing", status=state.status) remaining = deadline - loop.time() if remaining <= 0: - break - await asyncio.sleep(min((1, 2, 3, 5)[min(attempt, 3)], remaining)) + raise TimeoutError + async with asyncio.timeout(remaining): + await asyncio.sleep(min((1, 2, 3, 5)[min(attempt, 3)], remaining)) + state = await self.retrieve() attempt += 1 - except TimeoutError as exc: - raise TimeoutError( - f"Timed out waiting for {adapter.resource} {adapter.resource_id}; check the dashboard." - ) from exc - raise TimeoutError( - f"Timed out waiting for {adapter.resource} {adapter.resource_id}; check the dashboard." - ) - - -async def wait_for_payment( - adapter: PaymentAdapter, - initial: PaymentSnapshot, - *, - resume: Callable[[float], Awaitable[T]], - on_checkout: CheckoutCallback | None = None, - timeout: float = 600, - checkout_timeout: float = 30, -) -> PaymentSnapshot: - """Find checkout and hand presentation to the caller, or expose resumable error.""" - if initial.status not in adapter.awaiting | adapter.preparing: - return initial - state = initial - loop = asyncio.get_running_loop() - deadline = loop.time() + checkout_timeout - attempt = 0 - try: - while True: - if state.status in adapter.awaiting and state.url: - checkout = Checkout( - state.url, state.expires_at, adapter.resource, adapter.resource_id - ) - if on_checkout is None: - raise PaymentRequired(checkout, resume) - async with asyncio.timeout(timeout): - try: - result = on_checkout(checkout) - if inspect.isawaitable(result): - await result - except TimeoutError: - raise # The outer timeout handler cancels once. - except Exception as exc: - if adapter.cancel is not None: - try: - await adapter.cancel() - except Exception as cleanup_error: - exc.add_note( - f"Could not cancel {adapter.resource} {adapter.resource_id}: {cleanup_error}; check the dashboard." - ) - raise - return await wait_until_active(adapter, timeout=timeout) - if state.status in adapter.active or ( - initial.status in adapter.preparing - and state.status in adapter.provisioning - ): - return state - if ( - state.status - not in adapter.awaiting | adapter.preparing | adapter.provisioning - ): - error = CloudAPIError(code="checkout_missing", status=state.status) - raise error - remaining = deadline - loop.time() - if remaining <= 0: - raise TimeoutError - async with asyncio.timeout(remaining): - await asyncio.sleep(min((1, 2, 3, 5)[min(attempt, 3)], remaining)) - state = await adapter.retrieve() - attempt += 1 - except (TimeoutError, asyncio.CancelledError, KeyboardInterrupt) as exc: - if on_checkout is not None and adapter.cancel is not None: - try: - await adapter.cancel() - exc.add_note( - f"Cancelled pending {adapter.resource} {adapter.resource_id}." - ) - except Exception as cleanup_error: + except (TimeoutError, asyncio.CancelledError, KeyboardInterrupt) as exc: + if isinstance(exc, TimeoutError): + raise TimeoutError( + f"Timed out waiting for {self.resource} {self.resource_id}; check the dashboard." + ) from exc + exc.add_note(f"Check {self.resource} {self.resource_id} in the dashboard.") + raise + except Exception as exc: + if not isinstance(exc, PaymentRequired): + # The APIs cannot atomically cancel only an unpaid checkout. + # Even an awaiting-payment snapshot can lag a successful charge. exc.add_note( - f"Could not cancel {adapter.resource} {adapter.resource_id}: {cleanup_error}; check the dashboard." + f"Check {self.resource} {self.resource_id} in the dashboard." ) - if isinstance(exc, TimeoutError): - error = TimeoutError( - f"Timed out waiting for {adapter.resource} {adapter.resource_id}; check the dashboard." - ) - for note in exc.__notes__ if hasattr(exc, "__notes__") else (): - error.add_note(note) - raise error from exc - raise + raise diff --git a/mobilerun/clients/cloud/proxies.py b/mobilerun/clients/cloud/proxies.py index 57a8e7d39..94cb0566e 100644 --- a/mobilerun/clients/cloud/proxies.py +++ b/mobilerun/clients/cloud/proxies.py @@ -1,236 +1,108 @@ -"""Mobilerun Connect proxy management.""" +"""SDK operations for Mobilerun Connect proxies.""" from typing import Literal, TypedDict, Unpack -from mobilerun_sdk import APIError, APIStatusError +from mobilerun_sdk import AsyncMobilerun from mobilerun_sdk.types.connect.proxy_buy_response import ProxyBuyResponse from mobilerun_sdk.types.connect.proxy_list_params import ProxyListParams from mobilerun_sdk.types.connect.proxy_list_response import ProxyListResponse from mobilerun_sdk.types.connect.proxy_retrieve_response import ProxyRetrieveResponse -from mobilerun_sdk.types.devices.proxy_connect_params import ProxyConnectParams -from mobilerun_sdk.types.devices.proxy_status_response import ProxyStatusResponse -from mobilerun.clients.cloud.billing import ( - _validate_create_params, - buys_connect_proxy, - requires, -) -from mobilerun.clients.cloud.checkout import CheckoutMode, checkout_callback -from mobilerun.clients.cloud.client import cloud_client -from mobilerun.clients.cloud.errors import cloud_error -from mobilerun.clients.cloud.payments import ( - CheckoutCallback, - PaymentAdapter, - wait_for_payment, - wait_until_active, -) -from mobilerun.errors.cloud import CloudConflict -from mobilerun.errors.device import DeviceOperationNotSupported +from mobilerun.clients.cloud.payments import PaymentFlow +from mobilerun.clients.cloud.resource import CloudResource from mobilerun.models.billing import Billing -from mobilerun.models.checkout import PaymentSnapshot -from mobilerun.utils.redaction import secret_scope - -BuyParams = TypedDict("BuyParams", {"name": str}, total=False) - - -@requires( - Billing.NO_COMMERCE, - paid_if=lambda arguments: buys_connect_proxy(arguments["params"]), -) -async def connect_device( - device_id: str, - params: ProxyConnectParams, - *, - billing: Billing, - api_key: str | None = None, - base_url: str | None = None, -) -> None: - """Connect a proxy, purchasing capacity when requested.""" - await _validate_create_params(params, allow_connect=True) - async with cloud_client(api_key, base_url, billing=billing) as client: - socks = params.get("socks5") or {} - with secret_scope(socks.get("password", ""), params.get("password", "")): - try: - return await client.devices.proxy.connect(device_id, **params) - except APIError as exc: - raise cloud_error(exc, "Connect phone proxy", device=True) from exc - - -@requires(Billing.NO_COMMERCE) -async def disconnect_device( - device_id: str, - *, - billing: Billing, - api_key: str | None = None, - base_url: str | None = None, -) -> None: - """Disconnect a phone proxy.""" - async with cloud_client(api_key, base_url, billing=billing) as client: - try: - return await client.with_options(max_retries=0).devices.proxy.disconnect( - device_id +from mobilerun.models.checkout import CheckoutCallback, PaymentSnapshot +from mobilerun.utils.checkout.presentation import CheckoutMode, checkout_callback + + +class BuyParams(TypedDict, total=False): + name: str + + +class Proxies(CloudResource): + """Operate on the Connect proxies of one cloud account.""" + + async def list( + self, *, included_only: bool = False, **params: Unpack[ProxyListParams] + ) -> ProxyListResponse: + """List one proxy page, optionally filtering items without changing pagination.""" + async with self._request("List proxies", Billing.NO_COMMERCE) as sdk: + response = await sdk.connect.proxies.list(**params) + if included_only: + return response.model_copy( + update={ + "items": [ + item + for item in response.items + if item.billing_mode == "included" + ] + } ) - except APIError as exc: - if isinstance(exc, APIStatusError) and exc.status_code == 409: - raise CloudConflict( - operation="Disconnect phone proxy", - status=409, - code="proxy_disconnect", - ) from exc - raise cloud_error(exc, "Disconnect phone proxy", device=True) from exc - - -@requires(Billing.NO_COMMERCE) -async def device_status( - device_id: str, - *, - billing: Billing, - api_key: str | None = None, - base_url: str | None = None, -) -> ProxyStatusResponse: - """Retrieve a phone proxy's status.""" - async with cloud_client(api_key, base_url, billing=billing) as client: - try: - return await client.devices.proxy.status(device_id) - except APIError as exc: - if ( - isinstance(exc, APIStatusError) - and exc.status_code in {400, 422} - and isinstance(exc.body, dict) - and exc.body.get("code") == "DEVICE_TOOL_UNSUPPORTED" - ): - raise DeviceOperationNotSupported( - "This device does not support proxy status" - ) from None - raise cloud_error(exc, "Retrieve phone proxy status", device=True) from exc - - -@requires(Billing.NO_COMMERCE) -async def list_proxies( - *, - billing: Billing, - included_only: bool = False, - api_key: str | None = None, - base_url: str | None = None, - **params: Unpack[ProxyListParams], -) -> ProxyListResponse: - """List a proxy page, optionally filtering items while retaining SDK pagination.""" - async with cloud_client(api_key, base_url, billing=billing) as client: - try: - response = await client.connect.proxies.list(**params) - except APIError as exc: - raise cloud_error(exc, "List proxies") from exc - if included_only: - return response.model_copy( - update={ - "items": [ - item for item in response.items if item.billing_mode == "included" - ] - } + return response + + async def retrieve(self, id: str) -> ProxyRetrieveResponse: + """Retrieve a proxy.""" + async with self._request("Retrieve proxy", Billing.NO_COMMERCE) as sdk: + return await sdk.connect.proxies.retrieve(id) + + async def cancel(self, id: str) -> None: + """Cancel a Connect proxy and release its provisioning.""" + async with self._request("Release proxy", Billing.NO_COMMERCE) as sdk: + await sdk.connect.proxies.cancel(id) + + async def buy( + self, + country: str, + *, + type: Literal["dedicated_residential", "residential", "mobile"] = "residential", + on_checkout: CheckoutCallback | None = None, + checkout: CheckoutMode = "error", + payment_timeout: float = 600, + **params: Unpack[BuyParams], + ) -> ProxyBuyResponse: + """Purchase Connect proxy capacity or hand off checkout for the new proxy.""" + mode = self._billing.require( + Billing.PAID, "Buy Connect proxy", invalid_operation="buy_proxy" ) - return response - - -@requires(Billing.NO_COMMERCE) -async def get_proxy( - id: str, - *, - billing: Billing, - api_key: str | None = None, - base_url: str | None = None, -) -> ProxyRetrieveResponse: - """Retrieve a proxy.""" - async with cloud_client(api_key, base_url, billing=billing) as client: - try: - return await client.connect.proxies.retrieve(id) - except APIError as exc: - raise cloud_error(exc, "Retrieve proxy") from exc - - -@requires(Billing.NO_COMMERCE) -async def cancel_proxy( - id: str, - *, - billing: Billing, - api_key: str | None = None, - base_url: str | None = None, -) -> None: - """Cancel a Connect proxy and release its provisioning.""" - async with cloud_client(api_key, base_url, billing=billing) as client: - try: - await client.connect.proxies.cancel(id) - except APIError as exc: - raise cloud_error(exc, "Release proxy") from exc - - -@requires(Billing.PAID, operation="Buy Connect proxy") -async def buy_proxy( - country: str, - *, - type: Literal["dedicated_residential", "residential", "mobile"] = "residential", - billing: Billing, - api_key: str | None = None, - base_url: str | None = None, - keep: bool = False, - on_checkout: CheckoutCallback | None = None, - checkout: CheckoutMode = "error", - payment_timeout: float = 600, - **params: Unpack[BuyParams], -) -> ProxyBuyResponse: - """Purchase Connect proxy capacity.""" - on_checkout = checkout_callback(checkout, on_checkout) - await _validate_create_params(params) - unknown = params.keys() - BuyParams.__annotations__.keys() - if unknown: - raise TypeError(f"Unexpected purchase options: {', '.join(sorted(unknown))}") - async with cloud_client(api_key, base_url, billing=billing) as client: - try: - response = await client.connect.proxies.buy( - country=country, type=type, **params + on_checkout = checkout_callback(checkout, on_checkout) + self._billing.validate_create_params(params) + unknown = params.keys() - BuyParams.__annotations__.keys() + if unknown: + raise TypeError( + f"Unexpected purchase options: {', '.join(sorted(unknown))}" ) + async with self._client(mode) as sdk: + with self._errors("Buy Connect proxy"): + response = await sdk.connect.proxies.buy( + country=country, type=type, **params + ) + proxy_id = response.id + preparing = frozenset({"checking"}) - async def payment_state() -> PaymentSnapshot: - data = await client.connect.proxies.retrieve(response.id) - return PaymentSnapshot(data.status, data.payment_url) - - async def resume(timeout: float) -> ProxyRetrieveResponse: - async def fetch() -> PaymentSnapshot: - data = await get_proxy( - response.id, - billing=Billing.NO_COMMERCE, - api_key=api_key, - base_url=base_url, - ) + async def fetch(client: AsyncMobilerun) -> PaymentSnapshot: + data = await client.connect.proxies.retrieve(proxy_id) return PaymentSnapshot(data.status, data.payment_url) - adapter = PaymentAdapter( + async def resume(timeout: float) -> ProxyRetrieveResponse: + async with self._client(Billing.NO_COMMERCE) as client: + with self._errors("Retrieve proxy"): + await PaymentFlow( + "Connect proxy", + proxy_id, + lambda: fetch(client), + preparing=preparing, + ).wait_until_active(timeout=timeout) + return await client.connect.proxies.retrieve(proxy_id) + + await PaymentFlow( "Connect proxy", - response.id, - fetch, - lambda: client.connect.proxies.cancel(response.id), - preparing=frozenset({"checking"}), - ) - await wait_until_active(adapter, timeout=timeout) - return await get_proxy( - response.id, - billing=Billing.NO_COMMERCE, - api_key=api_key, - base_url=base_url, + proxy_id, + lambda: fetch(sdk), + preparing=preparing, + ).wait_for_payment( + PaymentSnapshot(response.status, response.payment_url), + resume=resume, + on_checkout=on_checkout, + timeout=payment_timeout, ) - - await wait_for_payment( - PaymentAdapter( - "Connect proxy", - response.id, - payment_state, - lambda: client.connect.proxies.cancel(response.id), - preparing=frozenset({"checking"}), - ), - PaymentSnapshot(response.status, response.payment_url), - resume=resume, - on_checkout=on_checkout, - timeout=payment_timeout, - ) - return response - except APIError as exc: - raise cloud_error(exc, "Buy Connect proxy") from exc + return response diff --git a/mobilerun/clients/cloud/resource.py b/mobilerun/clients/cloud/resource.py new file mode 100644 index 000000000..20aa1c5dd --- /dev/null +++ b/mobilerun/clients/cloud/resource.py @@ -0,0 +1,87 @@ +"""Connection ownership and the SDK error boundary for account resources.""" + +from __future__ import annotations + +from collections.abc import AsyncIterator, Iterator +from contextlib import asynccontextmanager, contextmanager, nullcontext +from dataclasses import replace +from typing import TYPE_CHECKING + +from mobilerun.clients.cloud.billing_policy import BillingPolicy +from mobilerun.models.billing import Billing + +if TYPE_CHECKING: + from mobilerun_sdk import AsyncMobilerun + + +class CloudResource: + """Bind authorization and connection settings once; never close a borrowed SDK.""" + + def __init__( + self, + *, + billing: Billing | str, + client: AsyncMobilerun | None = None, + api_key: str | None = None, + base_url: str | None = None, + ) -> None: + self._billing = BillingPolicy(billing) + self._sdk = client + self._api_key = api_key + self._base_url = base_url + + @asynccontextmanager + async def _client(self, billing: Billing) -> AsyncIterator[AsyncMobilerun]: + from mobilerun.clients.cloud import client as connection + + async with ( + nullcontext(self._sdk) + if self._sdk is not None + else connection.cloud_client(self._api_key, self._base_url, billing=billing) + ) as sdk: + yield sdk + + @staticmethod + @contextmanager + def _errors(operation: str) -> Iterator[None]: + import httpx + from mobilerun_core import cloud_error_facts + from mobilerun_sdk import APIError, APIStatusError + + from mobilerun.clients.cloud.errors import CloudErrorMapper + + try: + yield + except (APIError, httpx.HTTPError, httpx.InvalidURL) as exc: + facts = cloud_error_facts(exc) + # Core does not recognize account-only purchase codes. Retain only + # these known values; never carry the response body into the mapper. + if ( + facts.status_code == 409 + and isinstance(exc, APIStatusError) + and isinstance(exc.body, dict) + ): + code = exc.body.get("code") + if type(code) is str and code in { + "included_capacity_unavailable", + "purchase_in_progress", + }: + facts = replace(facts, code=code) + failure = CloudErrorMapper.from_facts(facts, operation) + else: + return + try: + raise failure from None + finally: + # contextlib throws the original into this generator, so Python + # can still set its implicit context outside the except block. + failure.__context__ = None + + @asynccontextmanager + async def _request( + self, operation: str, minimum: Billing + ) -> AsyncIterator[AsyncMobilerun]: + mode = self._billing.require(minimum, operation) + async with self._client(mode) as sdk: + with self._errors(operation): + yield sdk diff --git a/mobilerun/clients/cloud/secrets.py b/mobilerun/clients/cloud/secrets.py index 64273b590..0ecb7a0c7 100644 --- a/mobilerun/clients/cloud/secrets.py +++ b/mobilerun/clients/cloud/secrets.py @@ -1,8 +1,10 @@ -"""Functional vault SDK boundaries; package and cache policy belongs to core.""" +"""Bound vault SDK operations; package and cache policy belongs to core.""" +import builtins +from collections.abc import Iterator +from contextlib import contextmanager from typing import Literal -from mobilerun_sdk import APIError, AsyncMobilerun from mobilerun_sdk.types.credential_list_response import Item from mobilerun_sdk.types.credentials.package_create_response import ( PackageCreateResponse, @@ -24,8 +26,8 @@ FieldUpdateResponse, ) -from mobilerun.clients.cloud.billing import requires -from mobilerun.clients.cloud.errors import cloud_error +from mobilerun.clients.cloud.resource import CloudResource +from mobilerun.errors import CloudAPIError from mobilerun.models.billing import Billing from mobilerun.utils.redaction import secret_scope @@ -40,134 +42,90 @@ ] -@requires(Billing.NO_COMMERCE) -async def list_secrets(client: AsyncMobilerun, *, billing: Billing) -> list[Item]: - """List all credential pages.""" - items, page = [], 1 - try: - while True: - response = await client.credentials.list(page=page) - items.extend(response.items) - if not response.pagination.has_next: - return items - page += 1 - except APIError as exc: - raise cloud_error(exc, "List vault credentials") from exc - - -@requires(Billing.NO_COMMERCE) -async def list_package( - client: AsyncMobilerun, package: str, *, billing: Billing -) -> list[Data]: - """List credentials in one package.""" - try: - return (await client.credentials.packages.list(package)).data - except APIError as exc: - raise cloud_error(exc, "List vault package") from exc - - -@requires(Billing.NO_COMMERCE) -async def create_package( - client: AsyncMobilerun, package: str, *, billing: Billing -) -> PackageCreateResponse: - """Create a vault package.""" - try: - return await client.credentials.packages.create(package_name=package) - except APIError as exc: - raise cloud_error(exc, "Create vault package") from exc - - -@requires(Billing.NO_COMMERCE) -async def save( - client: AsyncMobilerun, - package: str, - name: str, - fields: dict[FieldType, str], - *, - billing: Billing, -) -> CredentialCreateResponse: - """Save a credential in an existing package.""" - with secret_scope(*fields.values()): - try: - return await client.credentials.packages.credentials.create( - package, - credential_name=name, - fields=[ - {"field_type": key, "value": value} for key, value in fields.items() - ], - ) - except APIError as exc: - error = cloud_error(exc, "Save vault credential") - raise error from None - - -@requires(Billing.NO_COMMERCE) -async def create_field( - client: AsyncMobilerun, - package: str, - name: str, - field: FieldType, - value: str, - *, - billing: Billing, -) -> FieldCreateResponse: - """Add a credential field.""" - with secret_scope(value): - try: - return await client.credentials.packages.credentials.fields.create( - name, - package_name=package, - field_type=field, - value=value, - ) - except APIError as exc: - error = cloud_error(exc, "Create vault field") - raise error from None - - -@requires(Billing.NO_COMMERCE) -async def update( - client: AsyncMobilerun, - package: str, - name: str, - field: FieldType, - value: str, - *, - billing: Billing, -) -> FieldUpdateResponse: - """Update a credential field.""" - with secret_scope(value): - try: - return await client.credentials.packages.credentials.fields.update( - field, - package_name=package, - credential_name=name, - value=value, +class Vault(CloudResource): + """Operate on the credential vault of one cloud account.""" + + @staticmethod + @contextmanager + def _secret_write(*values: str) -> Iterator[None]: + with secret_scope(*values): + try: + yield + except CloudAPIError as error: + # The shared boundary mapped the error; its raw SDK cause can echo values. + error.__cause__ = error.__context__ = None + raise + + async def list(self) -> list[Item]: + """List all credential pages.""" + async with self._request("List vault credentials", Billing.NO_COMMERCE) as sdk: + items, page = [], 1 + while True: + response = await sdk.credentials.list(page=page) + items.extend(response.items) + if not response.pagination.has_next: + return items + page += 1 + + async def list_package(self, package: str) -> builtins.list[Data]: + """List credentials in one package.""" + async with self._request("List vault package", Billing.NO_COMMERCE) as sdk: + return (await sdk.credentials.packages.list(package)).data + + async def create_package(self, package: str) -> PackageCreateResponse: + """Create a vault package.""" + async with self._request("Create vault package", Billing.NO_COMMERCE) as sdk: + return await sdk.credentials.packages.create(package_name=package) + + async def save( + self, package: str, name: str, fields: dict[FieldType, str] + ) -> CredentialCreateResponse: + """Save a credential in an existing package.""" + with self._secret_write(*fields.values()): + async with self._request( + "Save vault credential", Billing.NO_COMMERCE + ) as sdk: + return await sdk.credentials.packages.credentials.create( + package, + credential_name=name, + fields=[ + {"field_type": key, "value": value} + for key, value in fields.items() + ], + ) + + async def create_field( + self, package: str, name: str, field: FieldType, value: str + ) -> FieldCreateResponse: + """Add a credential field.""" + with self._secret_write(value): + async with self._request("Create vault field", Billing.NO_COMMERCE) as sdk: + return await sdk.credentials.packages.credentials.fields.create( + name, package_name=package, field_type=field, value=value + ) + + async def update( + self, package: str, name: str, field: FieldType, value: str + ) -> FieldUpdateResponse: + """Update a credential field.""" + with self._secret_write(value): + async with self._request("Update vault field", Billing.NO_COMMERCE) as sdk: + return await sdk.credentials.packages.credentials.fields.update( + field, package_name=package, credential_name=name, value=value + ) + + async def delete(self, package: str, name: str) -> CredentialDeleteResponse: + """Delete a credential.""" + async with self._request("Delete vault credential", Billing.NO_COMMERCE) as sdk: + return await sdk.credentials.packages.credentials.delete( + name, package_name=package ) - except APIError as exc: - error = cloud_error(exc, "Update vault field") - raise error from None - -@requires(Billing.NO_COMMERCE) -async def delete( - client: AsyncMobilerun, - package: str, - name: str, - field: FieldType | None = None, - *, - billing: Billing, -) -> CredentialDeleteResponse | FieldDeleteResponse: - """Delete a credential or field.""" - try: - if field is None: - return await client.credentials.packages.credentials.delete( - name, package_name=package + async def delete_field( + self, package: str, name: str, field: FieldType + ) -> FieldDeleteResponse: + """Delete one credential field.""" + async with self._request("Delete vault credential", Billing.NO_COMMERCE) as sdk: + return await sdk.credentials.packages.credentials.fields.delete( + field, package_name=package, credential_name=name ) - return await client.credentials.packages.credentials.fields.delete( - field, - package_name=package, - credential_name=name, - ) - except APIError as exc: - raise cloud_error(exc, "Delete vault credential") from exc diff --git a/mobilerun/clients/cloud/signed_http.py b/mobilerun/clients/cloud/signed_http.py index 541937a92..992ccb581 100644 --- a/mobilerun/clients/cloud/signed_http.py +++ b/mobilerun/clients/cloud/signed_http.py @@ -1,43 +1,20 @@ -"""Keep transport diagnostics for signed transfers out of application logs.""" +"""Owned HTTPX clients for signed transfers, separate from the account SDK.""" -import logging -from collections.abc import AsyncIterator, Iterator -from contextlib import asynccontextmanager, contextmanager -from contextvars import ContextVar +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager import httpx -_signed_transfer = ContextVar("mobilerun_signed_transfer", default=False) +from mobilerun.utils.network.quiet import quiet_transport_logs -def _allow_transport_log(record: logging.LogRecord) -> bool: - return not _signed_transfer.get() +class SignedHTTP: + """Keep signed URLs out of transport logs for the lifetime of a transfer.""" - -@contextmanager -def _signed_transfer_logs() -> Iterator[None]: - """Silence only this task, including redirect URLs and httpcore header traces.""" - for logger in ( - "httpx", - "mobilerun_sdk._base_client", - "httpcore.http11", - "httpcore.http2", - "httpcore.connection", - "httpcore.proxy", - "httpcore.socks", - ): - # addFilter is idempotent. Leave it installed for concurrent transfers. - logging.getLogger(logger).addFilter(_allow_transport_log) - token = _signed_transfer.set(True) - try: - yield - finally: - _signed_transfer.reset(token) - - -@asynccontextmanager -async def _signed_client(client: httpx.AsyncClient) -> AsyncIterator[httpx.AsyncClient]: - """Open and close an owned transfer client without logging signed URLs.""" - with _signed_transfer_logs(): - async with client as opened: - yield opened + @staticmethod + @asynccontextmanager + async def open(client: httpx.AsyncClient) -> AsyncIterator[httpx.AsyncClient]: + """Open and close the owned transfer client in a quiet task scope.""" + with quiet_transport_logs(): + async with client as opened: + yield opened diff --git a/mobilerun/clients/cloud/tasks.py b/mobilerun/clients/cloud/tasks.py index e1c898500..daf710725 100644 --- a/mobilerun/clients/cloud/tasks.py +++ b/mobilerun/clients/cloud/tasks.py @@ -1,12 +1,10 @@ -"""Functional cloud task SDK boundaries, including streaming and polling.""" +"""Bound SDK operations for cloud tasks.""" -import asyncio -import logging -from collections.abc import AsyncIterator, Callable, Iterable -from typing import Literal, Required, TypedDict, TypeVar, Unpack +from collections.abc import AsyncGenerator, Iterable +from typing import Literal, Required, TypedDict, Unpack import httpx -from mobilerun_sdk import APIError, AsyncMobilerun +from mobilerun_sdk import APIStatusError from mobilerun_sdk._types import Body, Headers, NotGiven, Query, SequenceNotStr from mobilerun_sdk.types import ( TaskGetStatusResponse, @@ -14,21 +12,13 @@ TaskRunResponse, TaskStopResponse, ) -from mobilerun_sdk.types.task_run_params import Credential +from mobilerun_sdk.types.task_run_params import Credential as Credential from mobilerun_sdk.types.tasks import ScreenshotListResponse -from pydantic import BaseModel, ValidationError -from mobilerun.clients.cloud.billing import requires -from mobilerun.clients.cloud.errors import cloud_error -from mobilerun.config.settings import get_settings -from mobilerun.errors import CloudTaskTimeout -from mobilerun.logs.actions import action_line, cloud_progress -from mobilerun.logs.actions import logger as action_logger +from mobilerun.clients.cloud.errors import CloudErrorMapper +from mobilerun.clients.cloud.resource import CloudResource from mobilerun.models.billing import Billing -from mobilerun.models.results import ExecutionResult -T = TypeVar("T", bound=BaseModel) -logger = logging.getLogger(__name__) TaskRunOptions = TypedDict( "TaskRunOptions", { @@ -74,224 +64,64 @@ ) -@requires(Billing.INCLUDED) -async def run( - client: AsyncMobilerun, *, billing: Billing, **params: Unpack[TaskRunOptions] -) -> TaskRunResponse: - """Run a task on an existing phone.""" - try: - return await client.tasks.run(**params) - except APIError as exc: - body = exc.body - detail = body.get("detail", "") if isinstance(body, dict) else "" - device = ( - isinstance(detail, str) - and "device" in detail.lower() - and "not found" in detail.lower() - ) - raise cloud_error(exc, "Run cloud task", device=device) from exc +class Tasks(CloudResource): + """Operate on the cloud tasks of one account.""" - -@requires(Billing.NO_COMMERCE) -async def progress( - client: AsyncMobilerun, task_id: str, *, billing: Billing -) -> AsyncIterator[str]: - """Yield SSE lines with transport failures mapped.""" - try: - async with client.tasks.with_streaming_response.attach( - task_id, timeout=None - ) as stream: - async for line in stream.iter_lines(): - yield line - except (APIError, httpx.HTTPError) as exc: - raise cloud_error(exc, "Stream cloud task progress") from exc - - -@requires(Billing.NO_COMMERCE) -async def status( - client: AsyncMobilerun, task_id: str, *, billing: Billing -) -> TaskGetStatusResponse: - """Poll a cloud task's status.""" - try: - return await client.tasks.get_status(task_id) - except APIError as exc: - raise cloud_error(exc, "Poll cloud task") from exc - - -@requires(Billing.NO_COMMERCE) -async def stop( - client: AsyncMobilerun, task_id: str, *, billing: Billing -) -> TaskStopResponse: - """Cancel a running cloud task.""" - try: - return await client.tasks.stop(task_id) - except APIError as exc: - raise cloud_error(exc, "Stop cloud task") from exc - - -@requires(Billing.NO_COMMERCE) -async def trajectory( - client: AsyncMobilerun, task_id: str, *, billing: Billing -) -> TaskGetTrajectoryResponse: - """Retrieve a task trajectory.""" - try: - return await client.tasks.get_trajectory(task_id) - except APIError as exc: - raise cloud_error(exc, "Retrieve cloud task trajectory") from exc - - -@requires(Billing.NO_COMMERCE) -async def screenshots( - client: AsyncMobilerun, - task_id: str, - *, - billing: Billing, - **params: Unpack[RequestOptions], -) -> ScreenshotListResponse: - """Retrieve task screenshots.""" - try: - return await client.tasks.screenshots.list(task_id, **params) - except APIError as exc: - raise cloud_error(exc, "Retrieve cloud task screenshots") from exc - - -async def _progress( - client: AsyncMobilerun, - task_id: str, - device_id: str | None = None, - *, - billing: Billing, -) -> None: - step_count = 0 - # SDK 6 attach() parses to None; its streaming response exposes SSE lines. - async for line in progress(client, task_id, billing=billing): - if line.startswith("data:"): - parsed = cloud_progress(line[5:].strip()) - if parsed: - action, step = parsed - step_count += 1 - action_logger.info( - "%s", - action_line( - str(device_id)[:8] if device_id else "unknown", - "task", - step or step_count, - action, - ), - ) - - -async def _stop( - client: AsyncMobilerun, task_id: str, *, billing: Billing -) -> asyncio.CancelledError | None: - if task_id == "unknown": - return None - - async def stop_with_timeout() -> None: - try: - async with asyncio.timeout( - get_settings().MOBILERUN_CLOUD_TASK_STOP_TIMEOUT_SECONDS - ): - await stop(client, task_id, billing=billing) - except (Exception, asyncio.CancelledError): - # Best effort: cleanup must not mask the caller's outcome. - logger.warning("Could not stop cloud task %s", task_id) - - # Keep waiting for the bounded stop even if the caller is cancelled again. - cleanup = asyncio.create_task(stop_with_timeout()) - cancellation = None - while not cleanup.done(): - try: - await asyncio.shield(cleanup) - except asyncio.CancelledError as exc: - cancellation = exc - return cancellation - - -@requires(Billing.INCLUDED) -async def run_task( - client: AsyncMobilerun, - *, - device_id: str, - task: str, - billing: Billing, - output: type[T] | None = None, - max_steps: int | None = None, - timeout: float | None = None, - poll_interval: float | None = None, - on_task_started: Callable[[str], None] | None = None, - credentials: Iterable[Credential] | None = None, -) -> ExecutionResult: - """Run a cloud task and return pure result data, including its task_id.""" - settings = get_settings() - timeout = ( - settings.MOBILERUN_CLOUD_TASK_TIMEOUT_SECONDS if timeout is None else timeout - ) - poll_interval = ( - settings.MOBILERUN_CLOUD_TASK_POLL_INTERVAL_SECONDS - if poll_interval is None - else poll_interval - ) - params: TaskRunOptions = {"device_id": device_id, "task": task} - if output is not None: - params["output_schema"] = output.model_json_schema() - if max_steps is not None: - params["max_steps"] = max_steps - if credentials is not None: - params["credentials"] = credentials - task_id = "unknown" - deadline = asyncio.timeout(timeout) - try: - async with deadline: - response = await run(client, billing=billing, **params) - task_id = response.id - if on_task_started is not None: - on_task_started(task_id) + async def run(self, **params: Unpack[TaskRunOptions]) -> TaskRunResponse: + """Run a task on an existing phone.""" + operation = "Run cloud task" + async with self._request(operation, Billing.INCLUDED) as sdk: try: - await _progress(client, task_id, device_id, billing=billing) - except Exception: - # Progress is optional; status is authoritative. Cancellation - # (including the enclosing deadline) still propagates. - logger.warning("Cloud task progress unavailable; polling status") - while True: - state = await status(client, task_id, billing=billing) - if state.status in {"completed", "failed", "cancelled"}: - success = bool(state.succeeded) - answer = state.message - parsed_output = None - if output is not None and state.output is not None: - try: - parsed_output = output.model_validate(state.output) - except ValidationError as exc: - success = False - answer = str(exc) - result_type = ( - ExecutionResult[output] - if output is not None - else ExecutionResult - ) - return result_type( - success=success, - answer=answer, - output=parsed_output, - steps=state.steps, - task_id=task_id, - device="CloudDevice", + return await sdk.tasks.run(**params) + except APIStatusError as exc: + body = exc.body + detail = body.get("detail") if isinstance(body, dict) else None + if ( + exc.status_code == 404 + and isinstance(detail, str) + and "device" in detail.lower() + and "not found" in detail.lower() + ): + failure = CloudErrorMapper.from_exception( + exc, operation, device=True ) - await asyncio.sleep(poll_interval) - except TimeoutError as exc: - # A request timeout does not mean the overall wait deadline expired. - if not deadline.expired(): - raise - cancellation = await _stop(client, task_id, billing=billing) - if cancellation is not None: - raise cancellation from None - raise CloudTaskTimeout( - operation="Run cloud task", - code="task_timeout", - resource_id=task_id, - timeout=timeout, - ) from exc - except (asyncio.CancelledError, KeyboardInterrupt): - await _stop(client, task_id, billing=billing) - raise + else: + raise + raise failure from None + + async def progress(self, task_id: str) -> AsyncGenerator[str, None]: + """Yield SSE lines with transport failures mapped.""" + operation = "Stream cloud task progress" + async with self._request(operation, Billing.NO_COMMERCE) as sdk: + # SDK attach() parses to None; its streaming response exposes SSE lines. + async with sdk.tasks.with_streaming_response.attach( + task_id, timeout=None + ) as stream: + async for line in stream.iter_lines(): + yield line + + async def status(self, task_id: str) -> TaskGetStatusResponse: + """Poll a cloud task's status.""" + async with self._request("Poll cloud task", Billing.NO_COMMERCE) as sdk: + return await sdk.tasks.get_status(task_id) + + async def stop(self, task_id: str) -> TaskStopResponse: + """Cancel a running cloud task.""" + async with self._request("Stop cloud task", Billing.NO_COMMERCE) as sdk: + return await sdk.tasks.stop(task_id) + + async def trajectory(self, task_id: str) -> TaskGetTrajectoryResponse: + """Retrieve a task trajectory.""" + async with self._request( + "Retrieve cloud task trajectory", Billing.NO_COMMERCE + ) as sdk: + return await sdk.tasks.get_trajectory(task_id) + + async def screenshots( + self, task_id: str, **params: Unpack[RequestOptions] + ) -> ScreenshotListResponse: + """Retrieve task screenshots.""" + async with self._request( + "Retrieve cloud task screenshots", Billing.NO_COMMERCE + ) as sdk: + return await sdk.tasks.screenshots.list(task_id, **params) diff --git a/mobilerun/clients/cloud/webhooks.py b/mobilerun/clients/cloud/webhooks.py deleted file mode 100644 index 78ab1c524..000000000 --- a/mobilerun/clients/cloud/webhooks.py +++ /dev/null @@ -1,186 +0,0 @@ -"""Guarded webhook API calls. Endpoint management does not purchase resources.""" - -import asyncio -import re -from collections.abc import Awaitable, Sequence -from typing import TypeVar - -import httpx -from mobilerun_sdk import APIError, APIStatusError -from mobilerun_sdk.types.webhook_create_response import Data as Created -from mobilerun_sdk.types.webhook_list_response import Item -from mobilerun_sdk.types.webhook_retrieve_response import Data as Retrieved -from pydantic import SecretStr - -from mobilerun.clients.cloud.billing import requires -from mobilerun.clients.cloud.client import cloud_client -from mobilerun.clients.cloud.errors import cloud_error -from mobilerun.errors.cloud import ( - CloudConflict, - CloudResourceNotFound, - CloudTimeout, - CloudValidationError, -) -from mobilerun.models.billing import Billing -from mobilerun.models.webhooks import WebhookEndpoint -from mobilerun.utils.redaction import secret_scope - -T = TypeVar("T") - - -def _registration_error(body: object) -> CloudValidationError: - # Match only known service messages (endpoints.service.ts and lib/url.ts). - # Never render the response text, even if it starts with a recognized reason. - message = body.get("message") if isinstance(body, dict) else None - reasons = { - "eventTypes contains an unknown or non-webhook-deliverable type": "The filter contains an unknown or non-webhook-deliverable event type.", - "url is not a valid absolute URL": "The destination is not a valid absolute URL.", - "url scheme must be http or https": "The destination needs an HTTPS URL.", - "url must not contain userinfo (user:pass@…)": "Remove the username or password from the URL.", - "url must not contain a fragment (#…)": "Remove the URL fragment.", - } - reason = "The service rejected this registration; unrecognized details were withheld for privacy." - if isinstance(message, str): - if re.fullmatch(r"endpoint limit reached \([0-9]+ per org\)", message): - reason = "The organization has reached its webhook endpoint limit." - else: - reason = reasons.get(message, reason) - return CloudValidationError( - f"Register webhook failed (HTTP 400). {reason}", - operation="Register webhook", - status=400, - ) - - -async def _request(request: Awaitable[T], operation: str) -> T: - try: - return await request - except (APIError, httpx.HTTPError) as exc: - error = cloud_error(exc, operation) - if ( - operation == "Register webhook" - and isinstance(exc, APIStatusError) - and exc.status_code == 400 - ): - error = _registration_error(exc.body) - elif ( - operation == "Register webhook" - and isinstance(exc, APIStatusError) - and isinstance(exc.body, dict) - ): - code = exc.body.get("code") - if ( - exc.status_code == 409 - and code == "conflict" - and exc.body.get("message") == "a webhook for this URL already exists" - ): - error = CloudConflict( - operation=operation, status=409, code="webhook_duplicate_url" - ) - elif exc.status_code == 409 and code == "idempotency_request_in_progress": - error = CloudConflict( - operation=operation, - status=409, - code="webhook_registration_in_progress", - ) - elif ( - exc.status_code == 404 - and code == "not_found" - and exc.response.headers.get("Idempotent-Replayed") == "true" - ): - error = CloudResourceNotFound( - operation=operation, status=404, code="webhook_replay_deleted" - ) - # Drop the raw response and request (which can contain the URL or secret). - raise error from None - - -def _endpoint( - data: Created | Retrieved | Item, secret: str | None = None -) -> WebhookEndpoint: - return WebhookEndpoint( - data.id, - data.kind, - SecretStr(data.url) if data.url else None, - data.state, - data.health, - tuple(data.event_types), - SecretStr(secret) if secret else None, - ) - - -@requires(Billing.NO_COMMERCE) -async def register_webhook( - url: str, - event_types: Sequence[str], - idempotency_key: str | None, - *, - billing: Billing, -) -> WebhookEndpoint: - """Create an HTTP endpoint; never adopt an existing URL on conflict.""" - with secret_scope(url): - async with cloud_client(billing=billing) as client: - data = ( - await _request( - client.webhooks.create( - url=url, - event_types=list(event_types), - idempotency_key=idempotency_key, - ), - "Register webhook", - ) - ).data - return _endpoint(data, data.secret) - - -@requires(Billing.NO_COMMERCE) -async def list_webhooks(page_size: int, *, billing: Billing) -> list[WebhookEndpoint]: - """Read all pages within one SDK client lifetime.""" - endpoints: list[WebhookEndpoint] = [] - async with cloud_client(billing=billing) as client: - page = 1 - while True: - response = await _request( - client.webhooks.list(page=page, page_size=page_size), "List webhooks" - ) - endpoints.extend(_endpoint(item) for item in response.items) - if not response.pagination.has_next: - return endpoints - page += 1 - - -@requires(Billing.NO_COMMERCE) -async def get_webhook(endpoint_id: str, *, billing: Billing) -> WebhookEndpoint: - """Read one endpoint; the service never returns its signing secret here.""" - async with cloud_client(billing=billing) as client: - return _endpoint( - (await _request(client.webhooks.retrieve(endpoint_id), "Get webhook")).data - ) - - -@requires(Billing.NO_COMMERCE) -async def ping_webhook( - endpoint_id: str, timeout: float, *, billing: Billing -) -> tuple[bool, int | None]: - """Read the synchronous test result; receiver error strings may contain secrets.""" - async with cloud_client(billing=billing) as client: - try: - async with asyncio.timeout(timeout): - data = ( - await _request( - client.with_options(max_retries=0).webhooks.test_delivery( - endpoint_id - ), - "Ping webhook", - ) - ).data - except TimeoutError: - raise CloudTimeout(operation="Ping webhook") from None - return data.success, int(data.status_code) if data.status_code is not None else None - - -@requires(Billing.NO_COMMERCE) -async def delete_webhook(endpoint_id: str, *, billing: Billing) -> None: - """Delete the explicitly selected endpoint.""" - async with cloud_client(billing=billing) as client: - await _request(client.webhooks.delete(endpoint_id), "Delete webhook") diff --git a/mobilerun/clients/local/README.md b/mobilerun/clients/local/README.md index a5a80e893..1844d6b79 100644 --- a/mobilerun/clients/local/README.md +++ b/mobilerun/clients/local/README.md @@ -1,8 +1,20 @@ # Local clients -Function-only helpers for local machine operations: emulator processes, login -file persistence, credential lookup and APK inspection. These helpers do not depend on core or -cloud clients. Resource ownership and cleanup belong to core resource/device -implementations, not these transport helpers. +Local machine adapters do not depend on core or cloud clients. `LoginStore` +binds a login path and uses private, atomic writes. `inspect_apk` reads APK +metadata using Android build-tools. -See [clients](../README.md) and [local devices](../../core/devices/README.md). +```python +from mobilerun.clients.local.login_store import LoginStore + +login = LoginStore.from_settings() +signed_in = login.resolve_api_key() is not None +``` + +| File | Purpose | +| --- | --- | +| `__init__.py` | Package marker | +| `apk.py` | APK metadata inspection | +| `login_store.py` | Login persistence and credential lookup | + +Devices are provided by `AsyncDevice` / `AsyncMobilerun` from `mobilerun_core`. See [clients](../README.md). diff --git a/mobilerun/clients/local/emulator.py b/mobilerun/clients/local/emulator.py deleted file mode 100644 index 5857ae1cd..000000000 --- a/mobilerun/clients/local/emulator.py +++ /dev/null @@ -1,128 +0,0 @@ -"""Android emulator process and ADB helpers.""" - -import asyncio -from pathlib import Path - -from mobilerun.config.settings import get_settings - -_processes: dict[str, asyncio.subprocess.Process] = {} - - -def emulator_binary() -> str: - sdk = get_settings().ANDROID_HOME or get_settings().ANDROID_SDK_ROOT - return str(Path(sdk or Path.home() / "Library/Android/sdk") / "emulator/emulator") - - -async def _command(*args: str) -> str: - process = await asyncio.create_subprocess_exec( - *args, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE - ) - try: - stdout, stderr = await process.communicate() - except asyncio.CancelledError: - process.kill() - await process.wait() - raise - if process.returncode: - raise RuntimeError(stderr.decode(errors="replace").strip()) - return stdout.decode(errors="replace") - - -async def list_avds() -> list[str]: - return (await _command(emulator_binary(), "-list-avds")).splitlines() - - -async def find_running(name: str) -> str | None: - output = await _command("adb", "devices") - for line in output.splitlines()[1:]: - parts = line.split() - if len(parts) < 2 or not parts[0].startswith("emulator-"): - continue - try: - result = await _command("adb", "-s", parts[0], "emu", "avd", "name") - except RuntimeError: - result = "" - if not result.strip(): - try: - result = await _command( - "adb", "-s", parts[0], "shell", "getprop", "ro.boot.qemu.avd_name" - ) - except RuntimeError: - continue - if result.splitlines() and result.splitlines()[0].strip() == name: - return parts[0] - return None - - -async def start_avd(name: str, headless: bool = False) -> str: - """Let the emulator allocate its console port and report it over a socket.""" - loop = asyncio.get_running_loop() - reported = loop.create_future() - - async def receive( - reader: asyncio.StreamReader, writer: asyncio.StreamWriter - ) -> None: - try: - value = (await reader.read(32)).decode().strip() - if not reported.done(): - reported.set_result(value) - finally: - writer.close() - await writer.wait_closed() - - server = await asyncio.start_server(receive, "127.0.0.1", 0) - port = server.sockets[0].getsockname()[1] - process = None - try: - args = [emulator_binary(), "-avd", name, "-report-console", f"tcp:{port}"] - if headless: - args.append("-no-window") - process = await asyncio.create_subprocess_exec( - *args, stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.DEVNULL - ) - value = await asyncio.wait_for(reported, timeout=30) - if not value.isdigit() or not 0 < int(value) < 65536: - raise RuntimeError("Emulator reported an invalid console port") - serial = f"emulator-{value}" - _processes[serial] = process - return serial - except BaseException: - if process is not None and process.returncode is None: - process.kill() - await process.wait() - raise - finally: - server.close() - await server.wait_closed() - - -async def wait_boot(serial: str, timeout: float = 300) -> None: - async def wait() -> None: - await _command("adb", "-s", serial, "wait-for-device") - while ( - await _command( - "adb", "-s", serial, "shell", "getprop", "sys.boot_completed" - ) - ).strip() != "1": - await asyncio.sleep(1) - - try: - await asyncio.wait_for(wait(), timeout) - except asyncio.TimeoutError as exc: - raise TimeoutError( - f"Emulator {serial} did not boot within {timeout} seconds" - ) from exc - - -async def stop(serial: str) -> None: - process = _processes.get(serial) - try: - await _command("adb", "-s", serial, "emu", "kill") - except Exception: - if process is None: - raise - if process is not None: - if process.returncode is None: - process.kill() - await process.wait() - _processes.pop(serial, None) diff --git a/mobilerun/clients/local/login_store.py b/mobilerun/clients/local/login_store.py index cf6cb09ab..a2e16b96d 100644 --- a/mobilerun/clients/local/login_store.py +++ b/mobilerun/clients/local/login_store.py @@ -1,112 +1,83 @@ -"""Private cloud credential persistence.""" +"""Private cloud credential persistence on this machine.""" import json import os -import re -import tempfile +from collections.abc import Mapping from pathlib import Path -from typing import Optional +from typing import Self from mobilerun.config.env import get_secrets, secret_value from mobilerun.config.settings import get_settings from mobilerun.errors.credentials import CredentialFormatError, CredentialReadError +from mobilerun.utils.credentials.private import private_credential_writer -def credential_path() -> Path: - return get_settings().mobilerun_cloud_credential_path +class LoginStore: + """Read, replace or clear the login file at one path.""" + def __init__(self, path: Path) -> None: + self.path = path -def _chmod_private(path: Path, mode: int) -> None: - if os.name != "nt": - os.chmod(path, mode) + @classmethod + def from_settings(cls) -> Self: + """Use the currently configured cloud login path.""" + return cls(get_settings().mobilerun_cloud_credential_path) + def save(self, credentials: Mapping[str, str]) -> Path: + """Atomically replace saved cloud credentials with a private file.""" + path = self.path + path.parent.mkdir(parents=True, exist_ok=True) + if os.name != "nt": + os.chmod(path.parent, 0o700) + with private_credential_writer(path) as handle: + json.dump(dict(credentials), handle) + return path -def save_token(token: str, auth_url: str) -> Path: - """Persist the session token to the credentials dir.""" - return save_credentials({"access_token": token, "auth_url": auth_url}) - - -def save_credentials(credentials: dict) -> Path: - """Atomically replace saved cloud credentials with a private file.""" - path = credential_path() - path.parent.mkdir(parents=True, exist_ok=True) - _chmod_private(path.parent, 0o700) - - payload = json.dumps(credentials) - fd, tmp_name = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) - tmp_path = Path(tmp_name) - try: - with os.fdopen(fd, "w") as handle: - handle.write(payload) - _chmod_private(tmp_path, 0o600) - os.replace(tmp_path, path) - _chmod_private(path, 0o600) - except Exception: + def load(self) -> dict[str, str] | None: + """Load the saved login or return None if it has not been created.""" try: - tmp_path.unlink() + text = self.path.read_text(encoding="utf-8") except FileNotFoundError: + return None + except UnicodeError: + raise CredentialFormatError( + "Cloud credentials must be UTF-8 JSON; run `mobilerun account login` again." + ) from None + except OSError: + raise CredentialReadError( + "Cannot read cloud credentials; check file permissions." + ) from None + try: + data = json.loads(text) + if isinstance(data, dict) and all( + key not in data or isinstance(data[key], str) + for key in ( + "api_key", + "access_token", + "auth_url", + "auth_type", + "saved_at", + ) + ): + return data + except ValueError: pass - raise - return path - - -def load_credentials() -> Optional[dict]: - path = credential_path() - try: - text = path.read_text() - except FileNotFoundError: - return None - except UnicodeError as exc: - raise CredentialFormatError( - "Cloud credentials must be UTF-8 JSON; run `mobilerun account login` again." - ) from exc - except OSError as exc: - raise CredentialReadError( - "Cannot read cloud credentials; check file permissions." - ) from exc - try: - data = json.loads(text) - if not isinstance(data, dict) or any( - key in data and not isinstance(data[key], str) - for key in ("api_key", "access_token", "auth_url", "auth_type", "saved_at") - ): - raise ValueError("Expected a credential object containing string fields") - return data - except (ValueError, UnicodeError) as exc: raise CredentialFormatError( "Invalid cloud credentials; run `mobilerun account login` again." - ) from exc - + ) -def clear_credentials() -> bool: - """Delete the saved login. Returns True if a file was removed.""" - path = credential_path() - if path.exists(): - path.unlink() + def clear(self) -> bool: + """Remove the saved login and report whether it existed.""" + try: + self.path.unlink() + except FileNotFoundError: + return False return True - return False - - -# Cloud device ids are UUIDs (RFC 4122); ADB serials never are. Used to -# auto-route `-d ` to the cloud driver when the user didn't pass `--cloud`. -_CLOUD_DEVICE_ID_RE = re.compile( - r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$", - re.IGNORECASE, -) - - -def looks_like_cloud_device_id(value: Optional[str]) -> bool: - return bool(value and _CLOUD_DEVICE_ID_RE.match(value)) - - -def resolve_cloud_api_key() -> Optional[str]: - """Resolve the Mobilerun cloud API key for ``--cloud`` commands. - Order: the ``MOBILERUN_API_KEY`` env var, then the credential persisted by - ``mobilerun account login`` (``/credentials/mobilerun-cloud.json``). - """ - env_key = secret_value(get_secrets().MOBILERUN_API_KEY) - if env_key: - return env_key - data = load_credentials() - return (data.get("api_key") or data.get("access_token")) if data else None + def resolve_api_key(self) -> str | None: + """Prefer the environment API key over a saved key or session token.""" + env_key = secret_value(get_secrets().MOBILERUN_API_KEY) + if env_key: + return env_key + data = self.load() + return (data.get("api_key") or data.get("access_token")) if data else None diff --git a/mobilerun/clients/portal/README.md b/mobilerun/clients/portal/README.md deleted file mode 100644 index 4ea2e747a..000000000 --- a/mobilerun/clients/portal/README.md +++ /dev/null @@ -1,31 +0,0 @@ -# portal/ - -**Purpose:** Portal companion-app setup and state access. - -**What belongs here / what doesn't:** Put Portal service operations here, not CLI presentation or feature logic. - -**Contents:** - -- `__init__.py` — Public Portal types. -- `errors_text.py` — Portal error text constants. -- `http.py` — Portal HTTP URL and driver helpers. -- `install.py` — Portal installation and service readiness. -- `releases.py` — Latest Portal release lookup. -- `setup.py` — Portal setup argument helpers. -- `state_fetch.py` — State-fetch retries and driver recovery. - -**Examples:** - -```python -from mobilerun.clients.portal.http import is_portal_http_url - -is_http = is_portal_http_url("http://localhost:8080") -``` - -**Depends on / used by:** Uses shared configuration, errors, and drivers; used by device setup and state providers. - -## CLI device selection - -DEVICE is optional: run `mobilerun device connect ` to save a default, or choose from discovered devices. An explicit DEVICE takes precedence, followed by the saved `device.serial` and discovery. Run `mobilerun device disconnect` to clear the default. Python device APIs remain explicit. - -See [clients](../README.md) and [devices](../../core/devices/README.md). diff --git a/mobilerun/clients/portal/__init__.py b/mobilerun/clients/portal/__init__.py deleted file mode 100644 index 46d78131f..000000000 --- a/mobilerun/clients/portal/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Portal companion-app operations and shared types.""" diff --git a/mobilerun/clients/portal/discovery.py b/mobilerun/clients/portal/discovery.py deleted file mode 100644 index f9612842d..000000000 --- a/mobilerun/clients/portal/discovery.py +++ /dev/null @@ -1,23 +0,0 @@ -"""Discover a single local device for interactive CLI use.""" - -from async_adbutils import adb -from mobilerun_core_local.driver.ios import discover_ios_device as discover_ios_device - -from mobilerun.errors import DeviceNotFound - - -async def find_android_serial() -> str: - devices = await adb.list() - online = [device.serial for device in devices if device.state == "device"] - if len(online) == 1: - return online[0] - if not online: - message = "No connected Android device found." - not_ready = [f"{device.serial} ({device.state})" for device in devices] - if not_ready: - message += f" Not ready: {', '.join(not_ready)}." - raise DeviceNotFound(message) - raise DeviceNotFound( - f"Several devices connected: {', '.join(online)}. " - "Pass DEVICE or run `mobilerun device connect `." - ) diff --git a/mobilerun/clients/portal/errors_text.py b/mobilerun/clients/portal/errors_text.py deleted file mode 100644 index 43300a163..000000000 --- a/mobilerun/clients/portal/errors_text.py +++ /dev/null @@ -1,3 +0,0 @@ -"""Public text constants for Portal-reported errors.""" - -ACCESSIBILITY_SERVICE_NOT_AVAILABLE = "Accessibility service not available" diff --git a/mobilerun/clients/portal/http.py b/mobilerun/clients/portal/http.py deleted file mode 100644 index d2c19bb94..000000000 --- a/mobilerun/clients/portal/http.py +++ /dev/null @@ -1,20 +0,0 @@ -"""Portal HTTP URL helpers.""" - -from mobilerun_core_local.driver.android import AndroidPortalHttpDriver - - -def create_android_portal_http_driver( - url: str, token: str | None -) -> AndroidPortalHttpDriver: - """Return an unconnected Portal HTTP driver, without ADB.""" - if not token: - raise ValueError( - "Android Portal HTTP needs the Portal auth token. Copy it from the " - "Portal app and set MOBILERUN_DEVICE_TOKEN or device.auth_token." - ) - return AndroidPortalHttpDriver(url, token) - - -def is_portal_http_url(device: str | None) -> bool: - """True when ``device`` is a Portal HTTP base URL rather than an ADB serial.""" - return bool(device) and device.lower().startswith(("http://", "https://")) diff --git a/mobilerun/clients/portal/install.py b/mobilerun/clients/portal/install.py deleted file mode 100644 index c58c4ab74..000000000 --- a/mobilerun/clients/portal/install.py +++ /dev/null @@ -1,117 +0,0 @@ -import asyncio -import logging -import os -from contextlib import nullcontext -from dataclasses import dataclass -from typing import cast - -from async_adbutils import AdbDevice -from mobilerun_core_local.driver.android.portal import ( - DOWNLOAD_BASE, - PORTAL_PACKAGE_NAME, - check_portal_accessibility, - download_portal_apk, - download_versioned_portal_apk, - enable_portal_accessibility, - portal_content_uri, - setup_portal, -) - -from mobilerun.clients.portal.setup import portal_version_kwargs -from mobilerun.errors import PortalApkNotFound, PortalInstallFailed - -logger = logging.getLogger(__name__) - - -@dataclass(frozen=True) -class PortalSetupResult: - installed: bool - accessibility_enabled: bool - needs_manual_accessibility: bool - apk_source: str | None = None - accessibility_error: str | None = None - - -async def wait_for_portal_service( - device_obj: AdbDevice, timeout: float = 30.0, interval: float = 1.0 -) -> bool: - """Wait until Portal's accessibility service responds.""" - uri = portal_content_uri(PORTAL_PACKAGE_NAME, "ping") - loop = asyncio.get_running_loop() - deadline = loop.time() + timeout - while loop.time() < deadline: - try: - result = cast(str, await device_obj.shell(f"content query --uri {uri}")) - if '"status":"success"' in result: - return True - if not await check_portal_accessibility(device_obj): - await enable_portal_accessibility(device_obj) - except (OSError, RuntimeError): - logger.warning("Portal service probe failed; retrying.") - await asyncio.sleep(interval) - return False - - -async def install_portal( - device_obj: AdbDevice, - *, - apk_path: str | None = None, - version: str | None = None, - latest: bool = False, - in_place: bool = False, - debug: bool = False, - wait_timeout: float = 30.0, -) -> PortalSetupResult: - """Install Portal and enable its accessibility service without rendering output.""" - if apk_path: - apk_context = nullcontext(apk_path) - elif version: - normalized = f"v{version.lstrip('v')}" - apk_context = download_versioned_portal_apk(normalized, DOWNLOAD_BASE, debug) - elif latest: - apk_context = download_portal_apk(debug) - else: - success = await setup_portal( - device_obj, debug, **portal_version_kwargs(setup_portal, in_place=in_place) - ) - if not success: - raise PortalInstallFailed("Setup failed") - try: - enabled = await wait_for_portal_service(device_obj, timeout=wait_timeout) - except Exception: - enabled = False - if not enabled: - await device_obj.shell( - "am start -a android.settings.ACCESSIBILITY_SETTINGS" - ) - return PortalSetupResult(True, enabled, not enabled) - - with apk_context as downloaded_path: - if not os.path.exists(downloaded_path): - raise PortalApkNotFound(f"APK file not found at {downloaded_path}") - try: - await device_obj.install( - downloaded_path, - nolaunch=True, - uninstall=True, - flags=["-g"], - silent=not debug, - ) - except Exception as exc: - raise PortalInstallFailed(str(exc), apk_path=downloaded_path) from exc - - accessibility_error = None - try: - await enable_portal_accessibility(device_obj) - enabled = await wait_for_portal_service(device_obj, timeout=wait_timeout) - if not enabled: - raise RuntimeError("the service did not respond in time") - except Exception as exc: - accessibility_error = str(exc) - await device_obj.shell( - "am start -a android.settings.ACCESSIBILITY_SETTINGS" - ) - enabled = False - return PortalSetupResult( - True, enabled, not enabled, downloaded_path, accessibility_error - ) diff --git a/mobilerun/clients/portal/releases.py b/mobilerun/clients/portal/releases.py deleted file mode 100644 index fd6062c02..000000000 --- a/mobilerun/clients/portal/releases.py +++ /dev/null @@ -1,22 +0,0 @@ -import requests -from mobilerun_core_local.driver.android.portal import GITHUB_API_HOSTS, REPO - - -def get_latest_portal_version() -> str | None: - """Fetch latest portal release version from GitHub.""" - for host in GITHUB_API_HOSTS: - try: - url = f"{host}/repos/{REPO}/releases/latest" - resp = requests.get(url, timeout=10) - if resp.status_code == 200: - data = resp.json() - if "release" in data: - tag = data["release"].get( - "tag", data["release"].get("tag_name", "") - ) - else: - tag = data.get("tag_name", "") - return tag.lstrip("v").strip() if tag else None - except Exception: - continue - return None diff --git a/mobilerun/clients/portal/setup.py b/mobilerun/clients/portal/setup.py deleted file mode 100644 index 21e2f2d16..000000000 --- a/mobilerun/clients/portal/setup.py +++ /dev/null @@ -1,22 +0,0 @@ -"""Portal auto-setup helpers.""" - -import inspect -from typing import Any, Callable - -from mobilerun.version import __version__ - - -def portal_version_kwargs( - setup_fn: Callable[..., Any], *, in_place: bool = False -) -> dict[str, Any]: - """Key the Portal version map by mobilerun's version when core-local allows it. - - With in_place, also ask for an update that keeps Portal's data. - """ - params = inspect.signature(setup_fn).parameters - kwargs: dict[str, Any] = {} - if "version" in params: - kwargs["version"] = __version__ - if in_place and "uninstall" in params: - kwargs["uninstall"] = False - return kwargs diff --git a/mobilerun/clients/portal/state_fetch.py b/mobilerun/clients/portal/state_fetch.py deleted file mode 100644 index dc4c87d24..000000000 --- a/mobilerun/clients/portal/state_fetch.py +++ /dev/null @@ -1,143 +0,0 @@ -"""Portal-specific state retrieval, retries, and driver recovery.""" - -import asyncio -import logging -import time -from typing import Any, Awaitable, Callable, Dict, List, Optional - -import httpx -from mobilerun_core_local.driver.base import DeviceDisconnectedError - -from mobilerun.clients.portal.errors_text import ( - ACCESSIBILITY_SERVICE_NOT_AVAILABLE as _A11Y_SERVICE_NOT_AVAILABLE, -) -from mobilerun.config.settings import get_settings -from mobilerun.errors import StateFetchFailed - -logger = logging.getLogger("mobilerun") - - -def _is_timeout(error: BaseException) -> bool: - """True for device-side read timeouts; exclude connect and pool timeouts.""" - return isinstance(error, (TimeoutError, httpx.ReadTimeout)) - - -async def _fetch_with_notice( - fetch: Callable[[], Awaitable[Dict[str, Any]]], notice: bool, notice_after: float -) -> Dict[str, Any]: - """Await ``fetch``, logging once when it exceeds the configured notice delay.""" - if not notice: - return await fetch() - task = asyncio.ensure_future(fetch()) - try: - done, _ = await asyncio.wait({task}, timeout=notice_after) - except BaseException: - task.cancel() - raise - if not done: - logger.info("Waiting for the UI state from the device...") - return await task - - -async def fetch_state_with_retry( - fetch: Callable[[], Awaitable[Dict[str, Any]]], - recovery: Optional[Callable[[], Awaitable[None]]] = None, - max_retries: Optional[int] = None, - retry_delays: Optional[List[float]] = None, - recovery_after: Optional[int] = None, -) -> Dict[str, Any]: - """Fetch Portal state with configured retries, backoff, and recovery.""" - configured = get_settings() - max_retries = ( - max_retries - if max_retries is not None - else configured.MOBILERUN_STATE_MAX_RETRIES - ) - recovery_after = ( - recovery_after - if recovery_after is not None - else configured.MOBILERUN_STATE_RECOVERY_AFTER_ATTEMPT - ) - max_timeout_attempts = configured.MOBILERUN_STATE_MAX_TIMEOUT_ATTEMPTS - slow_fetch_notice_s = configured.MOBILERUN_STATE_SLOW_FETCH_NOTICE_S - delays = ( - retry_delays - if retry_delays is not None - else configured.MOBILERUN_STATE_RETRY_DELAYS - ) - last_error: Optional[Exception] = None - recovery_attempted = False - slow_notice_logged = False - timeouts = 0 - attempts = 0 - is_debug = logger.isEnabledFor(logging.DEBUG) - - for attempt in range(max_retries): - try: - attempts = attempt + 1 - logger.debug(f"Getting state (attempt {attempts}/{max_retries})") - t0 = time.monotonic() - try: - combined_data = await _fetch_with_notice( - fetch, not slow_notice_logged, slow_fetch_notice_s - ) - finally: - if time.monotonic() - t0 >= slow_fetch_notice_s: - slow_notice_logged = True - if is_debug: - elapsed = (time.monotonic() - t0) * 1000 - logger.debug(f"State fetched in {elapsed:.0f}ms") - if "error" in combined_data: - portal_error = combined_data["error"] - if ( - isinstance(portal_error, str) - and _A11Y_SERVICE_NOT_AVAILABLE in portal_error - ): - raise Exception(_A11Y_SERVICE_NOT_AVAILABLE) - raise Exception("Portal returned an error") - required_keys = ["a11y_tree", "phone_state", "device_context"] - missing = [key for key in required_keys if key not in combined_data] - if missing: - raise Exception(f"Missing data in state: {', '.join(missing)}") - return combined_data - except DeviceDisconnectedError: - raise - except Exception as exc: - last_error = exc - timed_out = _is_timeout(exc) - if timed_out: - timeouts += 1 - is_last = attempt >= max_retries - 1 or timeouts >= max_timeout_attempts - delay = delays[attempt] if attempt < len(delays) else delays[-1] - err_desc = str(exc) or type(exc).__name__ - suffix = f" (retrying in {delay:.0f}s)" if not is_last else "" - logger.warning( - f"get_state attempt {attempt + 1} failed: {err_desc}{suffix}" - ) - service_gone = _A11Y_SERVICE_NOT_AVAILABLE in err_desc - if ( - not recovery_attempted - and recovery is not None - and (attempt + 1 >= recovery_after or service_gone or timed_out) - and not is_last - ): - recovery_attempted = True - if service_gone: - logger.info( - "Portal accessibility service is off, re-enabling it..." - ) - else: - logger.info("State retrieval failing, attempting recovery...") - try: - await recovery() - logger.info("Recovery action completed") - except Exception as recovery_error: - logger.warning(f"Recovery action failed: {recovery_error}") - if is_last: - break - await asyncio.sleep(delay) - - last_desc = str(last_error) or type(last_error).__name__ - error_msg = f"Failed to get state after {attempts} attempts: {last_desc}" - logger.error(error_msg) - raise StateFetchFailed(error_msg) from last_error diff --git a/mobilerun/config/README.md b/mobilerun/config/README.md index 059eaf939..cbf809f22 100644 --- a/mobilerun/config/README.md +++ b/mobilerun/config/README.md @@ -10,7 +10,8 @@ Runtime settings, user configuration loading, migrations, and secrets access. | --- | --- | | `__init__.py` | Package marker | | `env.py` | Environment-backed secrets access | -| `loader.py` | Typed YAML config files and shared `config.yaml` migrations | +| `file.py` | Generic typed YAML persistence and migration lifecycle | +| `loader.py` | Shared `config.yaml` loading and migrations | | [migrations/](migrations/README.md) | Versioned configuration migrations | | `settings.py` | Runtime settings | | `user_config.py` | Shared user configuration models | @@ -32,6 +33,29 @@ explicit or environment path is an error. With no user `config.yaml`, the loader writes defaults. It can also migrate an existing file and write a backup. See [migrations](migrations/README.md). +`config.yaml` models `device`, `logging.debug`, `logging.level`, and +`credentials`, with `_version` tracking the file schema. The base neither +interprets nor validates other top-level keys or other `logging` entries. It +carries their parsed YAML values through migrations, updates, and saves; +formatting and comments are not preserved on rewrite. An explicit save keeps +unmodeled values from both the loaded snapshot and the destination, preferring +the destination's values for those keys. Use `update()` to lock edits. +The `mobilerun-agents` add-on owns its own settings file and legacy import. + +### Saved CLI device + +`device.serial` stores the default target: an Android serial, a cloud phone ID, +or a URL. An explicit CLI target takes precedence. For a saved URL, `device.platform` +helps select Android or iOS Portal; `device.control_backend: visual-remote` +selects the visual backend and `device.device_id` supplies its ID (default `auto`). + +For Android ADB, `device.use_tcp` defaults to `false`, `device.portal_mode` +defaults to `auto` (`required` and `disabled` are also accepted), and +`device.auto_setup` defaults to `true`. Auto-setup only runs for commands that +allow it and when Portal is not disabled. For Portal HTTP, the CLI passes +`MOBILERUN_DEVICE_TOKEN` or the saved `device.auth_token` for the matching platform +to core, in that order. Android Portal HTTP requires a token. + **Depends on / used by:** Uses configuration libraries and shared utilities; used across the framework. ## Subclass for your own file @@ -46,7 +70,7 @@ from typing import Any from pydantic import BaseModel -from mobilerun.config.loader import ConfigFile +from mobilerun.config.file import ConfigFile class AgentSettings(BaseModel): @@ -98,16 +122,14 @@ case-sensitive environment names. | Section | Environment variables | | --- | --- | | Paths | `MOBILERUN_USER_CONFIG_DIR`, `MOBILERUN_CONFIG`, `MOBILERUN_CREDENTIALS_FILE`, `MOBILERUN_MACRO_DIRECTORY` (macro list; defaults to `/macros`), `MOBILERUN_LOG_LEVEL` | -| Devices | `MOBILERUN_PORTAL_REMOTE_PORT` (default `8080`), `MOBILERUN_ANDROID_DEVICE_TYPE` (AVD name; unset by default), `MOBILERUN_CLOUD_DEVICE_TYPE` (default `android_cloud_phone`) | | Run recording | `MOBILERUN_RUNS_DIR` (unset or empty: `/runs`, resolved by `get_settings().runs_dir`), `MOBILERUN_RUN_SETTLE_SECONDS` (default `0.25`, full capture only) | -| Cloud | `MOBILERUN_BILLING` (`paid` by default; `included` / `no_commerce` restrict charges), `MOBILERUN_CLOUD_PROXY_COUNTRY` (default `us`), `MOBILERUN_CLOUD_PROXY_SMART_IP`, `MOBILERUN_CLOUD_BASE_URL`, `MOBILERUN_CLOUD_API_TIMEOUT`, `MOBILERUN_CLOUD_NUMBER_READY_TIMEOUT_SECONDS`, `MOBILERUN_CLOUD_APP_INSTALL_TIMEOUT_SECONDS`, `MOBILERUN_CLOUD_TASK_TIMEOUT_SECONDS`, `MOBILERUN_CLOUD_TASK_POLL_INTERVAL_SECONDS` | +| Cloud | `MOBILERUN_BILLING` (`paid` by default; `included` / `no_commerce` restrict charges), `MOBILERUN_CLOUD_PROXY_COUNTRY` (default `us`), `MOBILERUN_CLOUD_PROXY_SMART_IP`, `MOBILERUN_CLOUD_BASE_URL`, `MOBILERUN_CLOUD_API_TIMEOUT`, `MOBILERUN_CLOUD_NUMBER_READY_TIMEOUT_SECONDS`, `MOBILERUN_CLOUD_TASK_TIMEOUT_SECONDS`, `MOBILERUN_CLOUD_TASK_POLL_INTERVAL_SECONDS` | | Cloud webhooks | `MOBILERUN_WEBHOOK_PAGE_SIZE` (default `100`, from `1` to `100`), `MOBILERUN_WEBHOOK_PING_TIMEOUT` (default `15` seconds, greater than `0` and at most `60`) | -| Device auth | `MOBILERUN_AUTH_URL`, `MOBILERUN_DEVICE_AUTH_REQUEST_TIMEOUT`, `MOBILERUN_DEVICE_AUTH_MIN_POLL_INTERVAL`, `MOBILERUN_DEVICE_AUTH_SLOW_DOWN_BUMP` | -| UI state | `MOBILERUN_STATE_RETRY_DELAYS`, `MOBILERUN_STATE_MAX_RETRIES`, `MOBILERUN_STATE_RECOVERY_AFTER_ATTEMPT`, `MOBILERUN_STATE_MAX_TIMEOUT_ATTEMPTS`, `MOBILERUN_STATE_SLOW_FETCH_NOTICE_S` | -| Screenshots | `MOBILERUN_MODEL_SCREENSHOT_MAX_SIDE` | +| Account login (OAuth device flow) | `MOBILERUN_AUTH_URL`, `MOBILERUN_DEVICE_AUTH_REQUEST_TIMEOUT`, `MOBILERUN_DEVICE_AUTH_MIN_POLL_INTERVAL`, `MOBILERUN_DEVICE_AUTH_SLOW_DOWN_BUMP` | +| Screen presentation | `MOBILERUN_MODEL_SCREENSHOT_MAX_SIDE`, `MOBILERUN_SCREEN_CONCISE_MIN_ELEMENT_SIZE`, `MOBILERUN_SCREEN_DETAILED_MIN_VISIBILITY` | -Capture level is selected on `RecordingDevice`, not globally. Screenshots in -`capture="full"` are not redacted; use `capture="actions"` for sensitive flows. +Choose `ActionRecording` for actions only or `ScreenRecording` for actions with +UI state and screenshots. Screenshots are stored as taken, without redaction. `MOBILERUN_AGENTS` overrides the agent registry as a JSON object. Each agent has `skills` and `mcp` user/project path pairs and can supply an `mcp_format` override. Hints can use `{server_name}`. Set an unsupported integration to `null`. MCP-specific environment settings are documented in [mcp/](../mcp/README.md). @@ -121,7 +143,7 @@ Phoenix tracing settings are owned by the optional `mobilerun-agents` package. names exactly. Both fields default to `None` and are masked in representations: - `MOBILERUN_API_KEY` — Cloud API credential. -- `MOBILERUN_DEVICE_TOKEN` — Device authentication token. +- `MOBILERUN_DEVICE_TOKEN` — Portal HTTP authentication token override. Provider and tracing credentials live in `AgentSecrets` under the `mobilerun-agents` package, not in the base configuration package. diff --git a/mobilerun/config/file.py b/mobilerun/config/file.py new file mode 100644 index 000000000..5813c4432 --- /dev/null +++ b/mobilerun/config/file.py @@ -0,0 +1,217 @@ +"""Persistence and migration lifecycle for one typed YAML file.""" + +from __future__ import annotations + +import os +import stat +from abc import ABC, abstractmethod +from collections.abc import Callable, Iterator +from contextlib import contextmanager +from contextvars import ContextVar +from pathlib import Path +from tempfile import NamedTemporaryFile +from typing import Any, ClassVar, Generic, TypeVar + +import yaml # type: ignore[import-untyped, unused-ignore] +from filelock import FileLock + +from mobilerun.config.settings import get_settings +from mobilerun.errors.base import ConfigError + +T = TypeVar("T") + + +class ConfigFile(ABC, Generic[T]): + """Subclass to store a typed model in one YAML file in the user config directory.""" + + CONFIG_FILE: ClassVar[str] + config_type: type[T] + WRITE_DEFAULTS: ClassVar[bool] = False + USE_ENV_PATH: ClassVar[bool] = False + CONFIG_VERSION: ClassVar[int | None] = None + _invalid_config_error: ClassVar[type[ConfigError] | None] = None + _override: ContextVar[T | None] + + def __init_subclass__(cls) -> None: + super().__init_subclass__() + cls._override = ContextVar(f"{cls.__qualname__}.override", default=None) + + @classmethod + @abstractmethod + def from_dict(cls, data: dict[str, Any]) -> T: + """Build and validate a model from the parsed mapping.""" + + @classmethod + @abstractmethod + def to_dict(cls, config: T) -> dict[str, Any]: + """Serialize a model to a YAML-ready mapping, validating it if needed.""" + + @classmethod + def parse_yaml(cls, text: str) -> object: + """Parse YAML text, treating an empty document as an empty mapping.""" + data = yaml.safe_load(text) + return {} if data is None else data + + @classmethod + def migrate_dict(cls, data: dict[str, Any]) -> dict[str, Any]: + """Upgrade a versioned mapping before validation and set its new _version.""" + return data + + @classmethod + def get_user_config_dir(cls) -> Path: + return get_settings().MOBILERUN_USER_CONFIG_DIR + + @classmethod + def get_user_config_path(cls) -> Path: + return cls.get_user_config_dir() / cls.CONFIG_FILE + + @classmethod + @contextmanager + def override(cls, config: T) -> Iterator[None]: + """Temporarily return this model from load() for this class and context.""" + token = cls._override.set(config) + try: + yield + finally: + cls._override.reset(token) + + @classmethod + def load(cls, config_path: str | None = None) -> T: + """Resolve an explicit path, contextual override, opt-in env path, or user file.""" + if config_path: + return cls._load_user_config(Path(config_path)) + + if config_path is None and (config := cls._override.get()) is not None: + return config + + if cls.USE_ENV_PATH: + env_config = get_settings().MOBILERUN_CONFIG + if env_config and env_config.strip(): + return cls._load_user_config(Path(env_config)) + + user_config_path = cls.get_user_config_path() + + if user_config_path.exists(): + return cls._load_user_config(user_config_path) + + config = cls.config_type() + if cls.WRITE_DEFAULTS: + cls.save(config) + return config + + @classmethod + def _load_user_config( + cls, user_config_path: Path, *, edit: Callable[[T], None] | None = None + ) -> T: + old_version = None + try: + user_config_path = user_config_path.resolve() + original = user_config_path.read_bytes() + user_dict = cls.parse_yaml(original.decode("utf-8")) + if not isinstance(user_dict, dict): + raise ValueError("config must be a mapping") + if cls.CONFIG_VERSION is not None: + old_version = user_dict.get("_version", 1) + if type(old_version) is not int or old_version < 1: + raise ValueError("_version must be a positive integer") + user_dict["_version"] = old_version + user_dict = cls.migrate_dict(user_dict) + config = cls.from_dict(user_dict) + except ( + OSError, + UnicodeError, + yaml.YAMLError, + ValueError, + TypeError, + AttributeError, + ) as exc: + if cls._invalid_config_error is None: + raise + raise cls._invalid_config_error( + f"Invalid config at {user_config_path}: {exc}" + ) from exc + + # Do not publish a migration if the caller's edit fails. + if edit is not None: + edit(config) + if old_version is not None and user_dict.get("_version", 0) > old_version: + backup = user_config_path.with_name( + f"{user_config_path.name}.v{old_version}.bak" + ) + cls._save_backup(backup, original) + if edit is None: + cls._save_dict(user_dict, user_config_path) + + return config + + @staticmethod + def _save_backup(backup: Path, original: bytes) -> None: + # Publish a complete, private backup without replacing an older one. + target = NamedTemporaryFile(dir=backup.parent, delete=False) + try: + with target: + target.write(original) + target.flush() + os.fsync(target.fileno()) + try: + os.link(target.name, backup) + except FileExistsError: + if not stat.S_ISREG(backup.lstat().st_mode): + raise FileExistsError( + f"Migration backup must be a regular file, not a link or special file: {backup}" + ) from None + if backup.read_bytes() != original: + raise + finally: + Path(target.name).unlink(missing_ok=True) + + @classmethod + def update(cls, edit: Callable[[T], None]) -> Path: + """Edit the configured user file under an interprocess lock.""" + env_path = get_settings().MOBILERUN_CONFIG if cls.USE_ENV_PATH else None + configured = bool(env_path and env_path.strip()) + path = Path(env_path) if env_path and configured else cls.get_user_config_path() + with cls._lock(path.resolve()): + if configured or path.exists(): + config = cls._load_user_config(path, edit=edit) + else: + config = cls.config_type() + edit(config) + return cls._save_config(config, path) + + @classmethod + def save(cls, config: T) -> Path: + """Atomically replace the user file; prefer update for read-modify-write.""" + path = cls.get_user_config_path() + with cls._lock(path): + return cls._save_config(config, path) + + @staticmethod + def _lock(path: Path) -> FileLock: + path.parent.mkdir(parents=True, exist_ok=True) + return FileLock(f"{path}.lock") + + @classmethod + def _save_config(cls, config: T, path: Path) -> Path: + config_dict = cls.to_dict(config) + if cls.CONFIG_VERSION is not None: + config_dict["_version"] = cls.CONFIG_VERSION + return cls._save_dict(config_dict, path) + + @classmethod + def _save_dict(cls, config_dict: dict[str, Any], path: Path) -> Path: + """Save config dict to path.""" + destination = path.resolve() + destination.parent.mkdir(parents=True, exist_ok=True) + f = NamedTemporaryFile( + mode="w", encoding="utf-8", dir=destination.parent, delete=False + ) + try: + with f: + yaml.dump(config_dict, f, default_flow_style=False, sort_keys=False) + f.flush() + os.fsync(f.fileno()) + os.replace(f.name, destination) + finally: + Path(f.name).unlink(missing_ok=True) + return path diff --git a/mobilerun/config/loader.py b/mobilerun/config/loader.py index dfeb93716..28219f7ea 100644 --- a/mobilerun/config/loader.py +++ b/mobilerun/config/loader.py @@ -1,231 +1,19 @@ -"""Typed YAML configuration files and the shared Mobilerun configuration.""" +"""The shared Mobilerun config.yaml file.""" -from __future__ import annotations - -import os -import stat -from abc import ABC, abstractmethod -from collections.abc import Callable, Iterator -from contextlib import contextmanager -from contextvars import ContextVar +from dataclasses import asdict from pathlib import Path -from tempfile import NamedTemporaryFile -from typing import Any, ClassVar, Generic, TypeVar +from typing import Any import yaml -from filelock import FileLock -from mobilerun.config.settings import get_settings -from mobilerun.errors.base import ConfigError +from mobilerun.errors.config import OutdatedConfigError as _OutdatedConfigError +from .file import ConfigFile as _ConfigFile from .migrations import CURRENT_VERSION, migrate from .user_config import MobileConfig -class OutdatedConfigError(ConfigError): - """Raised when user config is unreadable or invalid.""" - - pass - - -T = TypeVar("T") - - -class ConfigFile(ABC, Generic[T]): - """Subclass to store a typed model in one YAML file in the user config directory.""" - - CONFIG_FILE: ClassVar[str] - config_type: type[T] - WRITE_DEFAULTS: ClassVar[bool] = False - USE_ENV_PATH: ClassVar[bool] = False - CONFIG_VERSION: ClassVar[int | None] = None - _invalid_config_error: ClassVar[type[ConfigError] | None] = None - _override: ContextVar[T | None] - - def __init_subclass__(cls) -> None: - super().__init_subclass__() - cls._override = ContextVar(f"{cls.__qualname__}.override", default=None) - - @classmethod - @abstractmethod - def from_dict(cls, data: dict[str, Any]) -> T: - """Build and validate a model from the parsed mapping.""" - - @classmethod - @abstractmethod - def to_dict(cls, config: T) -> dict[str, Any]: - """Serialize a model to a YAML-ready mapping, validating it if needed.""" - - @classmethod - def parse_yaml(cls, text: str) -> object: - """Parse YAML text, treating an empty document as an empty mapping.""" - data = yaml.safe_load(text) - return {} if data is None else data - - @classmethod - def migrate_dict(cls, data: dict[str, Any]) -> dict[str, Any]: - """Upgrade a versioned mapping before validation and set its new _version.""" - return data - - @classmethod - def get_user_config_dir(cls) -> Path: - return get_settings().MOBILERUN_USER_CONFIG_DIR - - @classmethod - def get_user_config_path(cls) -> Path: - return cls.get_user_config_dir() / cls.CONFIG_FILE - - @classmethod - @contextmanager - def override(cls, config: T) -> Iterator[None]: - """Temporarily return this model from load() for this class and context.""" - token = cls._override.set(config) - try: - yield - finally: - cls._override.reset(token) - - @classmethod - def load(cls, config_path: str | None = None) -> T: - """Resolve an explicit path, contextual override, opt-in env path, or user file.""" - if config_path: - return cls._load_user_config(Path(config_path)) - - if config_path is None and (config := cls._override.get()) is not None: - return config - - if cls.USE_ENV_PATH: - env_config = get_settings().MOBILERUN_CONFIG - if env_config and env_config.strip(): - return cls._load_user_config(Path(env_config)) - - user_config_path = cls.get_user_config_path() - - if user_config_path.exists(): - return cls._load_user_config(user_config_path) - - config = cls.config_type() - if cls.WRITE_DEFAULTS: - cls.save(config) - return config - - @classmethod - def _load_user_config( - cls, user_config_path: Path, *, edit: Callable[[T], None] | None = None - ) -> T: - old_version = None - try: - user_config_path = user_config_path.resolve() - original = user_config_path.read_bytes() - user_dict = cls.parse_yaml(original.decode("utf-8")) - if not isinstance(user_dict, dict): - raise ValueError("config must be a mapping") - if cls.CONFIG_VERSION is not None: - old_version = user_dict.get("_version", 1) - if type(old_version) is not int or old_version < 1: - raise ValueError("_version must be a positive integer") - user_dict["_version"] = old_version - user_dict = cls.migrate_dict(user_dict) - config = cls.from_dict(user_dict) - except ( - OSError, - UnicodeError, - yaml.YAMLError, - ValueError, - TypeError, - AttributeError, - ) as exc: - if cls._invalid_config_error is None: - raise - raise cls._invalid_config_error( - f"Invalid config at {user_config_path}: {exc}" - ) from exc - - # Do not publish a migration if the caller's edit fails. - if edit is not None: - edit(config) - if old_version is not None and user_dict.get("_version", 0) > old_version: - backup = user_config_path.with_name( - f"{user_config_path.name}.v{old_version}.bak" - ) - cls._save_backup(backup, original) - if edit is None: - cls._save_dict(user_dict, user_config_path) - - return config - - @staticmethod - def _save_backup(backup: Path, original: bytes) -> None: - # Publish a complete, private backup without replacing an older one. - target = NamedTemporaryFile(dir=backup.parent, delete=False) - try: - with target: - target.write(original) - target.flush() - os.fsync(target.fileno()) - try: - os.link(target.name, backup) - except FileExistsError: - if not stat.S_ISREG(backup.lstat().st_mode): - raise FileExistsError( - f"Migration backup must be a regular file, not a link or special file: {backup}" - ) from None - if backup.read_bytes() != original: - raise - finally: - Path(target.name).unlink(missing_ok=True) - - @classmethod - def update(cls, edit: Callable[[T], None]) -> Path: - """Read, edit in place, and save the user file under an interprocess lock.""" - path = cls.get_user_config_path() - with cls._lock(path): - if path.exists(): - config = cls._load_user_config(path, edit=edit) - else: - config = cls.config_type() - edit(config) - return cls._save_config(config, path) - - @classmethod - def save(cls, config: T) -> Path: - """Atomically replace the user file; prefer update for read-modify-write.""" - path = cls.get_user_config_path() - with cls._lock(path): - return cls._save_config(config, path) - - @staticmethod - def _lock(path: Path) -> FileLock: - path.parent.mkdir(parents=True, exist_ok=True) - return FileLock(f"{path}.lock") - - @classmethod - def _save_config(cls, config: T, path: Path) -> Path: - config_dict = cls.to_dict(config) - if cls.CONFIG_VERSION is not None: - config_dict["_version"] = cls.CONFIG_VERSION - return cls._save_dict(config_dict, path) - - @classmethod - def _save_dict(cls, config_dict: dict[str, Any], path: Path) -> Path: - """Save config dict to path.""" - destination = path.resolve() - destination.parent.mkdir(parents=True, exist_ok=True) - f = NamedTemporaryFile( - mode="w", encoding="utf-8", dir=destination.parent, delete=False - ) - try: - with f: - yaml.dump(config_dict, f, default_flow_style=False, sort_keys=False) - f.flush() - os.fsync(f.fileno()) - os.replace(f.name, destination) - finally: - Path(f.name).unlink(missing_ok=True) - return path - - -class ConfigLoader(ConfigFile[MobileConfig]): +class ConfigLoader(_ConfigFile[MobileConfig]): """The shared config.yaml file and its Mobilerun migrations.""" APP_NAME = "droidrun" @@ -234,7 +22,7 @@ class ConfigLoader(ConfigFile[MobileConfig]): WRITE_DEFAULTS = True USE_ENV_PATH = True CONFIG_VERSION = CURRENT_VERSION - _invalid_config_error = OutdatedConfigError + _invalid_config_error = _OutdatedConfigError @classmethod def from_dict(cls, data: dict[str, Any]) -> MobileConfig: @@ -251,9 +39,30 @@ def parse_yaml(cls, text: str) -> object: @classmethod def migrate_dict(cls, data: dict[str, Any]) -> dict[str, Any]: - return migrate(data, for_storage=True) + return migrate(data) @classmethod def save(cls, config: MobileConfig) -> Path: - """Replace config.yaml without creating a lock file; use update to lock edits.""" - return cls._save_config(config, cls.get_user_config_path()) + """Save config.yaml, retaining unmodeled keys already on disk.""" + path = cls.get_user_config_path() + data = cls.to_dict(config) + if path.exists(): + existing = cls.parse_yaml(path.read_text(encoding="utf-8")) + if not isinstance(existing, dict): + raise _OutdatedConfigError( + f"Invalid config at {path}: config must be a mapping" + ) + logging = existing.get("logging") + data = { + **data, + **existing, + "device": data["device"], + "logging": { + **data["logging"], + **(logging if isinstance(logging, dict) else {}), + **asdict(config.logging), + }, + "credentials": data["credentials"], + } + data["_version"] = cls.CONFIG_VERSION + return cls._save_dict(data, path) diff --git a/mobilerun/config/migrations/README.md b/mobilerun/config/migrations/README.md index 523f58af7..2150839fb 100644 --- a/mobilerun/config/migrations/README.md +++ b/mobilerun/config/migrations/README.md @@ -16,17 +16,16 @@ print(config["_version"]) `migrate` transforms the supplied mapping; the config loader handles any file backup and persistence. See [configuration](../README.md). +The current schema is v008. Only v003 changes base settings. Earlier versions +gain `device.auto_setup: true` when unset; versions v002 and v004–v008 do not +transform any values. Unmodeled data stays in the original file for other +consumers to migrate independently. + ## Files | Path | Purpose | | --- | --- | | `__init__.py`, `runner.py` | Export, discover and run migrations | -| `v002_add_code_exec.py` | Rename codeact config and add codeact flag | | `v003_add_auto_setup.py` | Add device auto-setup | -| `v004_remove_deprecated_agents.py` | Remove deprecated agent configs and rename prompt paths | -| `v005_remove_external_agents.py` | Remove legacy external agent configs | -| `v006_disabled_tools_default_sentinel.py` | Use the disabled-tools default sentinel | -| `v007_manager_prompt_auto.py` | Select manager prompt automatically | -| `v008_bundled_assets.py` | Relocate bundled asset references | **Depends on / used by:** Uses Python import machinery; called by the configuration loader. diff --git a/mobilerun/config/migrations/runner.py b/mobilerun/config/migrations/runner.py index ec780e118..ea7dd045a 100644 --- a/mobilerun/config/migrations/runner.py +++ b/mobilerun/config/migrations/runner.py @@ -23,8 +23,8 @@ def get_migrations() -> List: return sorted(migrations, key=lambda m: m.VERSION) -def migrate(config: Dict[str, Any], *, for_storage: bool = False) -> Dict[str, Any]: - """Upgrade config, omitting cwd-dependent path resolution for stored data.""" +def migrate(config: Dict[str, Any]) -> Dict[str, Any]: + """Apply base migrations and advance over versions without base changes.""" version = config.get("_version", 0) if version >= CURRENT_VERSION: @@ -34,8 +34,8 @@ def migrate(config: Dict[str, Any], *, for_storage: bool = False) -> Dict[str, A for migration in migrations: if migration.VERSION > version: - if not (for_storage and getattr(migration, "READ_TIME_ONLY", False)): - config = migration.migrate(config) - config["_version"] = migration.VERSION + config = migration.migrate(config) + + config["_version"] = CURRENT_VERSION return config diff --git a/mobilerun/config/migrations/v002_add_code_exec.py b/mobilerun/config/migrations/v002_add_code_exec.py deleted file mode 100644 index 95ea20a39..000000000 --- a/mobilerun/config/migrations/v002_add_code_exec.py +++ /dev/null @@ -1,43 +0,0 @@ -"""Migration v2: Rename codeact config to fast_agent, add codeact flag.""" - -from typing import Any, Dict - -VERSION = 2 - -_OLD_SYSTEM_PROMPT = "config/prompts/codeact/system.jinja2" -_OLD_USER_PROMPT = "config/prompts/codeact/user.jinja2" -_NEW_SYSTEM_PROMPT = "config/prompts/codeact/tools_system.jinja2" -_NEW_USER_PROMPT = "config/prompts/codeact/tools_user.jinja2" - - -def migrate(config: Dict[str, Any]) -> Dict[str, Any]: - """Rename agent.codeact -> agent.fast_agent and llm_profiles.codeact -> fast_agent.""" - agent = config.get("agent", {}) - - # Rename agent.codeact -> agent.fast_agent - if "codeact" in agent and "fast_agent" not in agent: - agent["fast_agent"] = agent.pop("codeact") - - fast_agent = agent.setdefault("fast_agent", {}) - - fast_agent.setdefault("codeact", False) - fast_agent.setdefault("parallel_tools", True) - - # Remove safe_execution and execution_timeout (now in top-level safe_execution) - fast_agent.pop("safe_execution", None) - fast_agent.pop("execution_timeout", None) - - # Update prompt paths if still at old defaults - if fast_agent.get("system_prompt") == _OLD_SYSTEM_PROMPT: - fast_agent["system_prompt"] = _NEW_SYSTEM_PROMPT - if fast_agent.get("user_prompt") == _OLD_USER_PROMPT: - fast_agent["user_prompt"] = _NEW_USER_PROMPT - - config["agent"] = agent - - # Rename llm_profiles.codeact -> llm_profiles.fast_agent - profiles = config.get("llm_profiles", {}) - if "codeact" in profiles and "fast_agent" not in profiles: - profiles["fast_agent"] = profiles.pop("codeact") - - return config diff --git a/mobilerun/config/migrations/v003_add_auto_setup.py b/mobilerun/config/migrations/v003_add_auto_setup.py index 4c038b36b..d867fd25a 100644 --- a/mobilerun/config/migrations/v003_add_auto_setup.py +++ b/mobilerun/config/migrations/v003_add_auto_setup.py @@ -7,6 +7,8 @@ def migrate(config: Dict[str, Any]) -> Dict[str, Any]: """Add auto_setup to device config (defaults to True).""" - device = config.setdefault("device", {}) + # Do not mutate aliases to the original device mapping elsewhere in the file. + device = config.get("device", {}).copy() device.setdefault("auto_setup", True) + config["device"] = device return config diff --git a/mobilerun/config/migrations/v004_remove_deprecated_agents.py b/mobilerun/config/migrations/v004_remove_deprecated_agents.py deleted file mode 100644 index 697714a5a..000000000 --- a/mobilerun/config/migrations/v004_remove_deprecated_agents.py +++ /dev/null @@ -1,41 +0,0 @@ -"""Migration v4: Remove deprecated agent configs and rename prompt paths.""" - -from typing import Any, Dict - -VERSION = 4 - -_OLD_SYSTEM_PROMPT = "config/prompts/codeact/tools_system.jinja2" -_OLD_USER_PROMPT = "config/prompts/codeact/tools_user.jinja2" -_NEW_SYSTEM_PROMPT = "config/prompts/fast_agent/system.jinja2" -_NEW_USER_PROMPT = "config/prompts/fast_agent/user.jinja2" - - -def migrate(config: Dict[str, Any]) -> Dict[str, Any]: - """Strip removed agent configs and update prompt paths.""" - agent = config.get("agent", {}) - - fast_agent = agent.get("fast_agent", {}) - - # Remove deprecated fields from fast_agent - fast_agent.pop("codeact", None) - fast_agent.pop("safe_execution", None) - fast_agent.pop("execution_timeout", None) - - # Update prompt paths from legacy codeact directory - if fast_agent.get("system_prompt") == _OLD_SYSTEM_PROMPT: - fast_agent["system_prompt"] = _NEW_SYSTEM_PROMPT - if fast_agent.get("user_prompt") == _OLD_USER_PROMPT: - fast_agent["user_prompt"] = _NEW_USER_PROMPT - - # Remove scripter section - agent.pop("scripter", None) - - # Remove top-level safe_execution - config.pop("safe_execution", None) - - # Remove deprecated LLM profiles - profiles = config.get("llm_profiles", {}) - profiles.pop("text_manipulator", None) - profiles.pop("scripter", None) - - return config diff --git a/mobilerun/config/migrations/v005_remove_external_agents.py b/mobilerun/config/migrations/v005_remove_external_agents.py deleted file mode 100644 index 6981ccc28..000000000 --- a/mobilerun/config/migrations/v005_remove_external_agents.py +++ /dev/null @@ -1,15 +0,0 @@ -"""Migration v5: Remove legacy external agent example configs.""" - -from typing import Any, Dict - -VERSION = 5 - - -def migrate(config: Dict[str, Any]) -> Dict[str, Any]: - """Remove legacy mai_ui and autoglm example entries from external_agents.""" - external_agents = config.get("external_agents", {}) - if isinstance(external_agents, dict): - external_agents.pop("mai_ui", None) - external_agents.pop("autoglm", None) - - return config diff --git a/mobilerun/config/migrations/v006_disabled_tools_default_sentinel.py b/mobilerun/config/migrations/v006_disabled_tools_default_sentinel.py deleted file mode 100644 index f0438332b..000000000 --- a/mobilerun/config/migrations/v006_disabled_tools_default_sentinel.py +++ /dev/null @@ -1,33 +0,0 @@ -"""Migration v6: Treat default-shaped ``tools.disabled_tools`` as the sentinel. - -Older generated configs (v5) shipped the literal default list -``[click_at, click_area, long_press_at]``. The schema now uses ``None`` as the -"use framework default" sentinel — an explicit list is honored verbatim and -disables the vision auto-unmask for ``click_at`` (and raises in -screenshot-only modes when coordinate tools are listed). - -This migration only converts the **exact** default list to ``None``. Supersets -like ``[click_at, click_area, long_press_at, wait]`` are intentionally left -untouched so non-vision runs continue disabling the coordinate tools the user -expected. ``_effective_disabled_tools`` gives those legacy supersets a -graceful path through screenshot-only modes (coord tools are stripped with a -warning instead of raising ValueError). -""" - -from typing import Any, Dict - -VERSION = 6 - -_OLD_DEFAULT = {"click_at", "click_area", "long_press_at"} - - -def migrate(config: Dict[str, Any]) -> Dict[str, Any]: - tools = config.get("tools") - if not isinstance(tools, dict): - return config - - disabled = tools.get("disabled_tools") - if isinstance(disabled, list) and set(disabled) == _OLD_DEFAULT: - tools["disabled_tools"] = None - - return config diff --git a/mobilerun/config/migrations/v007_manager_prompt_auto.py b/mobilerun/config/migrations/v007_manager_prompt_auto.py deleted file mode 100644 index 6f3047723..000000000 --- a/mobilerun/config/migrations/v007_manager_prompt_auto.py +++ /dev/null @@ -1,29 +0,0 @@ -"""Migration v7: use automatic manager prompt selection by default. - -Configs produced before v7 stored the bundled stateful manager prompt as an -explicit path. That pin prevents ``stateless: true`` from selecting the bundled -stateless prompt. Convert only that exact former default to ``None``. Any other -path remains an intentional override; an intentional pin to the former default -can be restored after migration. -""" - -from typing import Any, Dict - -VERSION = 7 - -_OLD_DEFAULT_MANAGER_SYSTEM_PROMPT = "config/prompts/manager/system.jinja2" - - -def migrate(config: Dict[str, Any]) -> Dict[str, Any]: - agent = config.get("agent") - if not isinstance(agent, dict): - return config - - manager = agent.get("manager") - if not isinstance(manager, dict): - return config - - if manager.get("system_prompt") == _OLD_DEFAULT_MANAGER_SYSTEM_PROMPT: - manager["system_prompt"] = None - - return config diff --git a/mobilerun/config/migrations/v008_bundled_assets.py b/mobilerun/config/migrations/v008_bundled_assets.py deleted file mode 100644 index b418393b1..000000000 --- a/mobilerun/config/migrations/v008_bundled_assets.py +++ /dev/null @@ -1,37 +0,0 @@ -"""Migration v8: relocate references to prompts bundled in the base package. - -Leave add-on-only prompts under ``config/prompts`` so PathResolver can still -find them in the add-on. -""" - -from pathlib import Path -from typing import Any - -from mobilerun.utils.paths import PathResolver - -VERSION = 8 -# CWD is a property of the reader, not of the shared config file. -READ_TIME_ONLY = True - - -def migrate(config: dict[str, Any]) -> dict[str, Any]: - """Resolve legacy prompt paths for an in-memory config only.""" - agent = config.get("agent") - if not isinstance(agent, dict): - return config - for section in agent.values(): - if not isinstance(section, dict): - continue - for key in ("system_prompt", "user_prompt"): - value = section.get(key) - if not isinstance(value, str): - continue - path = Path(value) - if path.parts[:2] != ("config", "prompts") or ".." in path.parts: - continue - asset = Path("assets", *path.parts[1:]) - if (PathResolver.get_project_root() / asset).exists() and ( - PathResolver.resolve(path) == PathResolver.resolve(asset) - ): - section[key] = str(asset) - return config diff --git a/mobilerun/config/settings.py b/mobilerun/config/settings.py index 52de7e42f..e0d1f32a3 100644 --- a/mobilerun/config/settings.py +++ b/mobilerun/config/settings.py @@ -12,14 +12,6 @@ _APP_NAME = "droidrun" # Preserve the existing user configuration directory. -def _user_config_dir() -> Path: - return Path(platformdirs.user_config_dir(_APP_NAME)) - - -def _smoke_apk() -> str: - return str(Path(platformdirs.user_cache_dir(_APP_NAME)) / "smoke" / "counter.apk") - - class AgentPaths(BaseModel): """User and project paths for each agent integration.""" @@ -29,30 +21,40 @@ class AgentPaths(BaseModel): mcp_format: dict[str, object] | None = None -def _agents() -> dict[str, AgentPaths]: - return { - "claude-code": AgentPaths( - skills=(".claude/skills", ".claude/skills"), - mcp=(".claude.json", ".mcp.json"), - ), - "codex": AgentPaths( - skills=(".agents/skills", ".agents/skills"), - mcp=(".codex/config.toml", ".codex/config.toml"), - ), - "opencode": AgentPaths( - skills=(".config/opencode/skills", ".opencode/skills"), - mcp=(".config/opencode/opencode.json", "opencode.json"), - ), - "cursor": AgentPaths( - skills=(".cursor/skills", ".cursor/skills"), - mcp=(".cursor/mcp.json", ".cursor/mcp.json"), - ), - } - - class Settings(BaseSettings): """Shared runtime settings, read from the environment on every get_settings() call.""" + @staticmethod + def _default_config_dir() -> Path: + return Path(platformdirs.user_config_dir(_APP_NAME)) + + @staticmethod + def _default_smoke_apk() -> str: + return str( + Path(platformdirs.user_cache_dir(_APP_NAME)) / "smoke" / "counter.apk" + ) + + @staticmethod + def _default_agents() -> dict[str, AgentPaths]: + return { + "claude-code": AgentPaths( + skills=(".claude/skills", ".claude/skills"), + mcp=(".claude.json", ".mcp.json"), + ), + "codex": AgentPaths( + skills=(".agents/skills", ".agents/skills"), + mcp=(".codex/config.toml", ".codex/config.toml"), + ), + "opencode": AgentPaths( + skills=(".config/opencode/skills", ".opencode/skills"), + mcp=(".config/opencode/opencode.json", "opencode.json"), + ), + "cursor": AgentPaths( + skills=(".cursor/skills", ".cursor/skills"), + mcp=(".cursor/mcp.json", ".cursor/mcp.json"), + ), + } + model_config = SettingsConfigDict( case_sensitive=True, extra="ignore", @@ -63,7 +65,7 @@ class Settings(BaseSettings): # ── Paths / user config - MOBILERUN_USER_CONFIG_DIR: Path = Field(default_factory=_user_config_dir) + MOBILERUN_USER_CONFIG_DIR: Path = Field(default_factory=_default_config_dir) """User configuration directory.""" MOBILERUN_CONFIG: str | None = None @@ -75,16 +77,14 @@ class Settings(BaseSettings): MOBILERUN_LOG_LEVEL: Literal["quiet", "normal", "verbose", "debug"] | None = None """Log level.""" - MOBILERUN_PORTAL_REMOTE_PORT: int = Field(8080, ge=1, le=65535) - """Portal remote port.""" - MOBILERUN_AGENTS: dict[str, AgentPaths] = Field(default_factory=_agents) + MOBILERUN_AGENTS: dict[str, AgentPaths] = Field(default_factory=_default_agents) """Skill and MCP configuration paths by agent.""" ANDROID_HOME: str | None = None """Android SDK location.""" ANDROID_SDK_ROOT: str | None = None """Android SDK root directory.""" - MOBILERUN_SMOKE_APK: str = Field(default_factory=_smoke_apk) + MOBILERUN_SMOKE_APK: str = Field(default_factory=_default_smoke_apk) """Demo APK to install. Defaults to smoke/counter.apk in the user cache.""" # ── Devices @@ -92,9 +92,6 @@ class Settings(BaseSettings): MOBILERUN_ANDROID_DEVICE_TYPE: str | None = None """Android device type.""" - MOBILERUN_CLOUD_DEVICE_TYPE: str = "android_cloud_phone" - """Cloud device type.""" - # ── Run recording MOBILERUN_RUNS_DIR: Path | None = None @@ -125,9 +122,6 @@ class Settings(BaseSettings): MOBILERUN_CLOUD_NUMBER_READY_TIMEOUT_SECONDS: float = Field(600.0, gt=0) """Max seconds to wait for a new cloud number to become active.""" - MOBILERUN_CLOUD_APP_INSTALL_TIMEOUT_SECONDS: float = Field(180.0, gt=0) - """Cloud app install timeout seconds.""" - MOBILERUN_CLOUD_TASK_TIMEOUT_SECONDS: float = 1800.0 """Cloud task timeout seconds.""" @@ -157,28 +151,17 @@ class Settings(BaseSettings): MOBILERUN_DEVICE_AUTH_SLOW_DOWN_BUMP: float = 5.0 """Device auth slow down bump.""" - # ── UI state and retries - - MOBILERUN_STATE_RETRY_DELAYS: list[float] = [1.0, 2.0, 3.0, 5.0, 8.0, 10.0] - """State retry delays.""" - - MOBILERUN_STATE_MAX_RETRIES: int = 7 - """State max retries.""" - - MOBILERUN_STATE_RECOVERY_AFTER_ATTEMPT: int = 5 - """State recovery after attempt.""" - - MOBILERUN_STATE_MAX_TIMEOUT_ATTEMPTS: int = 2 - """State max timeout attempts.""" - - MOBILERUN_STATE_SLOW_FETCH_NOTICE_S: float = 3.0 - """State slow fetch notice s.""" - # ── Model screenshots MOBILERUN_MODEL_SCREENSHOT_MAX_SIDE: int = 2048 """Model screenshot max side.""" + MOBILERUN_SCREEN_CONCISE_MIN_ELEMENT_SIZE: int = 5 + """Minimum width and height for elements included in concise screen output.""" + + MOBILERUN_SCREEN_DETAILED_MIN_VISIBILITY: float = 0.1 + """Minimum visible fraction for elements included in detailed screen output.""" + @field_validator("MOBILERUN_AUTH_URL", "MOBILERUN_CLOUD_BASE_URL", mode="before") @classmethod def _empty_url_uses_default(cls, value: str, info): diff --git a/mobilerun/config/user_config.py b/mobilerun/config/user_config.py index ba2c62dc1..4af0bf94b 100644 --- a/mobilerun/config/user_config.py +++ b/mobilerun/config/user_config.py @@ -1,7 +1,7 @@ -"""Shared configuration; agent-owned sections are preserved as opaque data.""" +"""Base configuration with opaque pass-through for unmodeled YAML.""" from copy import deepcopy -from dataclasses import asdict, dataclass, field +from dataclasses import asdict, dataclass, field, fields from os import PathLike from typing import Any, Literal, Self @@ -13,6 +13,15 @@ @dataclass class DeviceConfig: + """Saved CLI target and transport preferences for connecting through core. + + ``serial`` is the saved target (serial, cloud ID, or URL). ``device_id`` + is the ID passed when connecting to a visual-remote URL. ``use_tcp``, + ``portal_mode``, and ``auto_setup`` control Android ADB connections. + ``platform`` helps classify a saved URL and scopes the stored Portal token; + ``control_backend="visual-remote"`` selects the visual transport. + """ + serial: str | None = None control_backend: str | None = None device_id: str = "auto" @@ -23,7 +32,7 @@ class DeviceConfig: auth_token: str | None = None def resolve_auth_token(self, platform: str | None = None) -> str | None: - """Use the environment override or the selected platform's saved token.""" + """Use the Portal token override, then the matching platform's saved token.""" configured = ( self.auth_token if platform is None or platform.lower() == self.platform.lower() @@ -32,79 +41,60 @@ def resolve_auth_token(self, platform: str | None = None) -> str | None: return secret_value(get_secrets().MOBILERUN_DEVICE_TOKEN) or configured -@dataclass -class TelemetryConfig: - enabled: bool = True - - -@dataclass -class TracingConfig: - enabled: bool = False - provider: str = "phoenix" - langfuse_screenshots: bool = False - langfuse_secret_key: str = "" - langfuse_public_key: str = "" - langfuse_host: str = "" - langfuse_user_id: str = "anonymous" - langfuse_session_id: str = "" - - @dataclass class LoggingConfig: debug: bool = False level: Literal["quiet", "normal", "verbose", "debug"] = "normal" - save_trajectory: str = "none" - trajectory_path: str = "trajectories" - rich_text: bool = False - trajectory_gifs: bool = True @dataclass class MobileConfig: - """Device settings plus lossless data for optional agent consumers.""" + """Device, logging and credential settings for the base framework.""" device: DeviceConfig = field(default_factory=DeviceConfig) - telemetry: TelemetryConfig = field(default_factory=TelemetryConfig) - tracing: TracingConfig = field(default_factory=TracingConfig) logging: LoggingConfig = field(default_factory=LoggingConfig) - agent: dict = field(default_factory=lambda: {"streaming": True}) - llm_profiles: dict = field(default_factory=dict) - tools: dict = field(default_factory=dict) credentials: dict = field(default_factory=dict) - external_agents: dict = field(default_factory=dict) - mcp: dict = field(default_factory=dict) + _unmodeled: dict[str, Any] = field(default_factory=dict, init=False, repr=False) def to_dict(self) -> dict[str, Any]: - return asdict(self) + extras = deepcopy(self._unmodeled) + return { + **extras, + "device": asdict(self.device), + "logging": {**extras.get("logging", {}), **asdict(self.logging)}, + "credentials": deepcopy(self.credentials), + } @classmethod def from_dict(cls, data: dict[str, Any]) -> Self: data = deepcopy(data) if "_version" in data and data["_version"] < CURRENT_VERSION: data = migrate(data) - shared = { - name: kind(**(data.get(name) or {})) - for name, kind in ( - ("device", DeviceConfig), - ("telemetry", TelemetryConfig), - ("tracing", TracingConfig), - ("logging", LoggingConfig), - ) + data.pop("_version", None) + device = DeviceConfig(**(data.pop("device", None) or {})) + logging = data.pop("logging", None) or {} + if not isinstance(logging, dict): + raise ValueError("logging must be a mapping") + logging_fields = {entry.name for entry in fields(LoggingConfig)} + known_logging = { + key: value for key, value in logging.items() if key in logging_fields + } + credentials = data.pop("credentials", None) or {} + if not isinstance(credentials, dict): + raise ValueError("credentials must be a mapping") + config = cls( + device=device, + logging=LoggingConfig(**known_logging), + credentials=credentials, + ) + unknown_logging = { + key: value for key, value in logging.items() if key not in logging_fields } - raw = {} - for name in ( - "agent", - "llm_profiles", - "tools", - "credentials", - "external_agents", - "mcp", - ): - value = data.get(name) or {} - if not isinstance(value, dict): - raise ValueError(f"{name} must be a mapping") - raw[name] = value - return cls(**shared, **raw) + if unknown_logging: + data["logging"] = unknown_logging + # A YAML alias can point into a modeled section that callers edit. + config._unmodeled = deepcopy(data) + return config @classmethod def from_yaml(cls, path: str | PathLike[str]) -> Self: diff --git a/mobilerun/core/README.md b/mobilerun/core/README.md index 3086ef036..53a611d54 100644 --- a/mobilerun/core/README.md +++ b/mobilerun/core/README.md @@ -1,53 +1,44 @@ -# core/ - -**Could someone delete this folder and still use the rest of Mobilerun?** -If yes, it belongs in an optional feature (`sandbox/`, -`mcp/`, `macro/`, `skills/`); if not, put it in `core/` or a shared package. -For example, `sandbox/` is removable; `core/webhooks/` is not, because the -webhook CLI and sandbox both use it. In `mobilerun/`, `core/` holds domain -objects: devices, operators, state, credentials, proxies, numbers, mailboxes, -webhooks, workspace, and extensions. `models/`, `clients/`, `errors/`, `utils/`, -`config/`, and `logs/` supply shared building blocks. Phone behavior lives in -`core/devices/` and its components; account-wide resources live in their own -core folders or on `Workspace`. +# Framework core + +This package holds interfaces that use devices, not device implementations. Native actions, observation, lifecycle and capability errors belong to [mobilerun-core](https://github.com/droidrun/mobilerun-core). Framework code receives a `mobilerun_core.AsyncDevice` when it needs a phone. ## Topic map -Apps and files each have two entry points: `Workspace` manages the account -library, while `Device` methods act on one phone. For example, -`Workspace.delete_app()` removes a library entry; `device.uninstall_app()` does not. -`—` means there is no dedicated shared model or cloud adapter for that topic. - -| Topic | User-facing API | Domain code | Model | Cloud API | -| --- | --- | --- | --- | --- | -| Devices | `Device`, `CloudDevice`, `AndroidDevice`, `IOSDevice`, `RemoteDevice`, `DevicePool` | [devices/](devices/) | [Plan](../models/billing.py) | [devices.py](../clients/cloud/devices.py) | -| Apps | `Workspace.upload_app()`, `Workspace.list_apps()`, `device.install_app()`, `device.uninstall_app()` | [workspace.py](workspace.py), [cloud_apps.py](devices/components/cloud_apps.py), [base.py](devices/base.py) | [App](../models/apps.py) | [apps.py](../clients/cloud/apps.py) | -| Files | `Workspace.upload_file()`, `Workspace.list_files()`, `device.push_file()`, `device.pull_file()` | [workspace.py](workspace.py), [device files](devices/components/files.py) | [WorkspaceFile, DeviceFile](../models/files.py) | [files.py](../clients/cloud/files.py) | -| Settings/environment | `device.get_location()`, `device.set_location()`, language and timezone methods | [environment.py](devices/components/environment.py) | [Location](../models/location.py) | [devices.py](../clients/cloud/devices.py) | -| Proxies | `CloudRotatingProxy`, `CloudFixedProxy`, `CloudSocks5Proxy`, `LocalProxy`; `proxy.bind(device)` | [proxy/](proxy/) | [ProxyStatus](../models/proxy.py) | [proxies.py](../clients/cloud/proxies.py) | -| Numbers | `CloudPhoneNumber`, `device.number` | [phone_number/](phone_number/) | — | [numbers.py](../clients/cloud/numbers.py) | -| Mailboxes | `CloudMailbox`, `device.mailbox` | [mailbox/](mailbox/) | — | [mailboxes.py](../clients/cloud/mailboxes.py) | -| Credentials | `CloudCredentials`, `EnvCredentials`, `FileCredentials`, `DictCredentials` | [credentials/](credentials/) | [Credential](../models/credentials.py) | [secrets.py](../clients/cloud/secrets.py) | -| Webhooks | `CloudWebhooks` | [webhooks/](webhooks/) | [WebhookEndpoint](../models/webhooks.py) | [webhooks.py](../clients/cloud/webhooks.py) | -| Operators/tasks | `device.do()`, `device.expect()`, `Operator` | [operator/](operator/) | [ExecutionResult, ExpectationResult](../models/results.py), [CloudTaskInputs](../models/cloud_task.py) | [tasks.py](../clients/cloud/tasks.py) | -| State | `device.state`, `StateProvider`, `UIState` | [state/](state/) | [UIElement](../models/ui.py) | — | -| Runs and recording | `RecordingDevice`, `RunWriter`, `recording_scope()` | [devices/recording.py](devices/recording.py), [runs/](runs/README.md) | [RunRecord, RunStep, Fingerprint](../models/recording.py) | — | -| Extensions | `Extension.bind()`, `device.extensions`, `device.actions` | [extensions/](extensions/) | [ContextItem](../models/context.py) | — | - -`RecordingDevice` writes each run under `runs//`: `run.json` contains the -`RunRecord` metadata and terminal status, while `steps.jsonl` contains one -`RunStep` per dispatched action, including outcomes and optional `Fingerprint` -screen evidence. `core/runs/RunWriter` creates and appends these artifacts. - -**Examples:** - -Use an existing `device`. +| Topic | Public API | Framework code | +| --- | --- | --- | +| Operators | `operator.do(device, instruction)`, `operator.expect(device, condition)` | [operator/](operator/) | +| Extensions | `Extension`, `@function(name=…, description=…, to_atomic=…)` | [extensions/](extensions/) | +| Credentials | `CloudCredentials`, `EnvCredentials`, `FileCredentials`, `DictCredentials`; pass `device=` to the provider, then `await credentials.type_secret(name, field="password")` | [credentials/](credentials/) | +| Mailboxes | `CloudMailbox`; no device required | [mailbox/](mailbox/) | +| Phone numbers | `CloudPhoneNumber`; explicit `await number.attach(device)` and `await number.detach()` | [phone_number/](phone_number/) | +| Proxy products | `CloudRotatingProxy`, `CloudFixedProxy`, `CloudSocks5Proxy`; pass core `ConnectProxyRef` or `HttpProxy` directly to `device.set_proxy(...)` for borrowed proxies | [proxy/](proxy/) | +| Prompt screens | `ScreenProvider(device).observe()`; formats native UI and maps model coordinates | [screen/](screen/) | +| Recording | `ActionRecording(device)`, `ScreenRecording(device)` | [runs/](runs/) | +| Workspace | `Workspace` manages the account app and file libraries and transfers artifacts to or from a device | [workspace.py](workspace.py), [Workspace guide](WORKSPACE.md) | +| Webhooks | `CloudWebhooks`; organization-scoped | [webhooks/](webhooks/) | + +Use `Workspace.delete_app()` to delete a library entry and `device.uninstall_app()` to remove the app from one phone. Give `Workspace.push_file(file, device, device_path)` a full destination filename, not just a directory. + +`Operator.do(device, instruction, ...)` runs a task. `CredentialProvider.type_secret(name, *, package=None, field=None)` uses the device already bound to the provider. `mobilerun.models.CredentialMetadata` includes optional provider provenance (`source`). + +## Operators and tools + +Choose a concrete operator and give it its extensions explicitly. The operator borrows them; the caller owns their cleanup. Only methods declared with `@function` become tools. Optional `to_atomic` receives the bound method and replaces it with named, zero-argument async tools. ```python -state = await device.state.refresh() -print(state.formatted_text) +from mobilerun.core.extensions import Extension, function +from mobilerun.core.operator import Operator + +class Fixture(Extension): + @function(name="label", description="Return the QA fixture label.") + async def label(self) -> str: + return "signup" + +tools = Operator(extensions=[Fixture(name="fixture")]).tools() ``` -**Depends on / used by:** Uses clients and other shared packages; used by devices and features. +The base `Operator` can compile tools but does not execute tasks. Use `CloudTaskOperator` for hosted tasks, `MacroOperator` for deterministic replay, or the separate `mobilerun-agents` add-on for local LLM execution. Hosted tasks can cost credits; local LLM calls can cost tokens. + +## Recording -See [devices](devices/README.md), [state](state/README.md), [webhooks](webhooks/README.md), and [Workspace](WORKSPACE.md). +Recorders install scoped core action hooks without replacing or closing the device. `ActionRecording` writes actions, timestamps and outcomes. `ScreenRecording` also captures before/after screenshots and UI state. Screenshots are stored as taken. Run metadata goes to `run.json`; action rows go to `steps.jsonl`. Use `rec.extension_call(name, arguments)` around an extension tool dispatch if you want a single extension row instead of its nested device actions. diff --git a/mobilerun/core/WORKSPACE.md b/mobilerun/core/WORKSPACE.md index 94a1a685e..ce2450315 100644 --- a/mobilerun/core/WORKSPACE.md +++ b/mobilerun/core/WORKSPACE.md @@ -1,36 +1,62 @@ # Workspace assets `Workspace` manages account-wide files and apps, independently of a phone. -Every operation is a classmethod; no configured instance is needed. +Create a `Workspace` to bind the account and billing settings once. Operations +that transfer to or from a phone take a `mobilerun_core.AsyncDevice`. ## Quick example These operations use a cloud account; uploaded storage or other resources may incur charges. ```python +from pathlib import Path + from mobilerun import Workspace -file = await Workspace.upload_file("photo.jpg") -files = await Workspace.list_files() -path = await Workspace.download_file(file.id, ".") -await Workspace.push_file(file, device, "/sdcard/Download") -await Workspace.delete_file(file.id) - -app = await Workspace.upload_app("counter.apk") -apps = await Workspace.list_apps() -app = await Workspace.get_app(app.id) -await device.install_app(app) -await Workspace.delete_app(app.id) +# Use an existing core AsyncDevice as `device`. +workspace = Workspace() +file = await workspace.upload_file("photo.jpg") +files = await workspace.list_files() +path = await workspace.download_file(file.id, ".") +await workspace.push_file(file, device, "/sdcard/Download/photo.jpg") +# Set scan_media=True for Android media indexing after the push. +copy = await workspace.pull_file(device, "/sdcard/Download/photo.jpg") +await workspace.delete_file(file.id) + +app = await workspace.upload_app("counter.apk") +apps = await workspace.list_apps() +installed = await device.install_app(app.identity) +await device.install_app(Path("counter.apk")) # or install a local APK +await workspace.delete_app(app.resource_id) ``` -Methods accept keyword `api_key=`, `base_url=`, and `billing=` overrides. Defaults -use `MOBILERUN_API_KEY`, then saved login, and `Billing.NO_COMMERCE`. Each operation -owns and closes its client. `push_file` selects the source workspace through -these options; the destination device retains its own account and billing. -Temporary local transfer files are removed even when the destination fails. +Use `app.resource_id` for workspace operations. `app.identity.app_id` is the +Android package name or iOS bundle ID used on the device. + +The constructor accepts `api_key=`, `base_url=`, and `billing=` overrides. +Defaults use `MOBILERUN_API_KEY`, then saved login, and `Billing.NO_COMMERCE`. +Each operation owns and closes its client unless you pass a borrowed `client=` +to the constructor. These options select the source +workspace for `push_file` and the destination workspace for `pull_file`. They +do not change the device's credentials. + +`push_file` requires a full device path, including the filename, and returns +`None`. `pull_file` uploads bytes under the device path's basename and returns +the new account `WorkspaceFile`. The temporary upload file is removed even if +the upload fails. Use `device.list_files(directory)` to get core `FileEntry` +values from the phone. + +`device.install_app` returns core's `InstalledApp`. Use `AppIdentity` to select +a package and optional version from the cloud device's own app library; this +does not transfer an app between accounts. For a local Android backend, use a +local APK instead. Downloads accept an existing directory or a file path. A string ending in `/` creates a directory. Uploaded app deletion removes files and metadata; it does not uninstall the app from a phone. Deletions cannot be undone. -See [devices](devices/README.md) and [cloud clients](../clients/cloud/README.md). +| File | Purpose | +| --- | --- | +| [workspace.py](workspace.py) | Account app and file operations and transfers through `AsyncDevice`. | + +See [core topics](README.md) and [cloud clients](../clients/cloud/README.md). diff --git a/mobilerun/core/__init__.py b/mobilerun/core/__init__.py index bf676f4b1..b409a65bc 100644 --- a/mobilerun/core/__init__.py +++ b/mobilerun/core/__init__.py @@ -4,45 +4,24 @@ from typing import TYPE_CHECKING, Any if TYPE_CHECKING: - from mobilerun.core.devices import ( - AndroidDevice, - CloudDevice, - Device, - DevicePool, - IOSDevice, - RecordingDevice, - RemoteDevice, - StealthDevice, - ) from mobilerun.core.proxy import ( CloudFixedProxy, CloudRotatingProxy, CloudSocks5Proxy, - LocalProxy, ) from mobilerun.core.workspace import Workspace __all__ = [ - "Device", - "AndroidDevice", - "CloudDevice", - "IOSDevice", - "RemoteDevice", - "DevicePool", - "RecordingDevice", - "StealthDevice", "Workspace", "CloudFixedProxy", "CloudRotatingProxy", "CloudSocks5Proxy", - "LocalProxy", ] _EXPORT_MODULES = { - **{name: "mobilerun.core.devices" for name in __all__[:8]}, "Workspace": "mobilerun.core.workspace", - **{name: "mobilerun.core.proxy" for name in __all__[9:]}, + **{name: "mobilerun.core.proxy" for name in __all__ if name != "Workspace"}, } diff --git a/mobilerun/core/credentials/README.md b/mobilerun/core/credentials/README.md index c20acb008..afc91fa27 100644 --- a/mobilerun/core/credentials/README.md +++ b/mobilerun/core/credentials/README.md @@ -1,109 +1,71 @@ -# Device credentials +# Credential extensions -`base.py` defines `CredentialProvider`; `dict.py`, `env.py`, `file.py` and -`cloud.py` implement it. The shared `Credential` value type lives in -`mobilerun/models/credentials.py` and is exported by this package. - -Credential vaults are extensions. Bind each vault with `await vault.bind(device)` -and detach it with `await vault.unbind()`. Give multiple vaults distinct `name=` -values. Metadata contains package names, credential names and field names, never -values. `type_field` types the value through the device's secret-safe path and -returns `None`. - -Before replay, a host can set `vault.policies` to a tuple of `CredentialPolicy` -objects. For example, `CredentialPolicy("card", field="number", package="app", -requires_approval=True, mask_from_start=True)` prevents unattended typing and -masks the field in macro state guards from the first observation. A recorded -`protected` marker also prevents replay even if the bound vault has no policy. -Base replay never asks for or infers approval. `mask_card_numbers=True` masks -Luhn-valid card numbers in normalized macro snapshots without resolving any -vault fields. Ordinary fields are resolved only when typed. Masking does not -change the raw device, screenshots or a caller's own state provider. - -Credential input relies on `mobilerun.utils.redaction.secret_scope` to redact -exact values and their escaped forms in logs. For values made only of digits and -supported separators, with at least four digits (such as PINs and expiries), it -also masks the same digits separated by spaces, hyphens, periods, or slashes. -Alphanumeric secrets are literal-only. -It does not mask a numeric substring inside a longer date or joined ID: `12/27` -matches `expires 12 / 27.` but not `2026/12/27`. Other reformattings are not covered. - -Before typing, the device refreshes its state and checks for a focused editable -field. If Android's focus summary does not show one, typing is allowed only when -the keyboard is visible and a fresh app tree reports exactly one enabled, focused -node in the foreground app's primary window. The node must report editability or, -if that flag is absent, have an editable widget class. When a compact snapshot -omits window IDs, the fallback requires an unambiguous foreground app tree. -Degraded snapshots and the separate keyboard tree cannot authorize the fallback. -Providers that cannot report focus and editability, including -screenshot-only providers, reject secret input with `DeviceOperationNotSupported`. - -The focus check and secret typing share a task-reentrant input-operation lock on -the root device. Taps, swipes, keys, app changes, ordinary typing and other -focus-changing operations through that root, its wrappers, pools or action catalog -wait until secret input finishes. Wrapper delegation takes the same lock reentrantly. - -**Residual risk:** the app or OS can still change focus on its own between the -check and typing. The backend has no atomic "type into this expected field" API. -This lock prevents competing Mobilerun operations, not autonomous app/OS changes -or input from another client/process. +List credential metadata, type a stored value into a focused field, or pass +vault references to a cloud task. Providers borrow an optional core +`AsyncDevice`; they never connect to or close it. ## Quick example -Run inside an async function after focusing an editable field. - -```python -from mobilerun.core.credentials import DictCredentials -from mobilerun.core.devices import AndroidDevice - -async with AndroidDevice("emulator-5554") as device: - vault = DictCredentials({"com.example.app": {"work": {"password": "example-only"}}}) - await vault.bind(device) - await vault.type_field("com.example.app", "password", name="work") -``` - -Flat mappings and YAML/JSON files automatically become unbound credentials with -one `password` field. `MOBILERUN_SECRET_GMAIL_PASSWORD` becomes name -`GMAIL_PASSWORD` with a password field. A custom prefix is supported. - -The full YAML/JSON format is package → credential name → fields: - -```yaml -com.google.android.gm: - work: - email: example@example.com - password: example-only -``` - -Fields match the Cloud vault: `email`, `username`, `password`, `api_token`, -`phone_number`, `two_factor_secret`, `backup_codes`. Package `None` means a -credential is not app-bound. `list(package=None)` lists metadata for all credentials. - -Cloud credentials use the same API-key resolution as CloudDevice, including -`mobilerun account login`, unless `api_key=` is explicit. They paginate the vault, -include Mobilerun and 1Password entries, and cache per instance. Call -`await provider.close()` when done. No service authentication storage is changed. - -Replace `{{secret:…}}` input with `await vault.type_field(package, field, name)`. - -Cloud tasks send only vault references, never secret values. Create credentials in the cloud vault before running a cloud task. Local credentials can be used by a local operator, including on a cloud phone. -Use the vault to manage fields directly (values are never shown in credential -representations): - ```python -from mobilerun.core.credentials import CloudCredentials +from mobilerun.core.credentials import FileCredentials +from mobilerun.core.extensions import compile_tools -vault = CloudCredentials() +# `phone` is a connected core AsyncDevice with a focused editable field. +vault = FileCredentials("credentials.yaml", device=phone) try: - await vault.save("com.example.app", "work", {"username": "example", "password": "example-only"}) - await vault.update("com.example.app", "work", "password", "new-example") - await vault.delete("com.example.app", "work", "username") # one field - await vault.delete("com.example.app", "work") # entire credential + await vault.type_secret("github") + tools = compile_tools([vault]) # e.g. vault.type_secret_github() finally: await vault.close() ``` -`save` creates missing packages and credentials and updates or adds supplied -fields on existing credentials. Writes invalidate the instance cache. - -See [devices](../devices/README.md) and [extensions](../extensions/README.md). +Pass the same vault in `Operator(extensions=[vault])`. Tools expose metadata and +zero-argument secret-typing aliases, not values or account write operations. +Unique names keep their existing alias, such as `vault.type_secret_login`. +If the same name appears in multiple packages, each entry gets an alias: +`vault.type_secret__encoded_p_n`, or +`vault.type_secret__encoded_u_n` for an entry without a package. +Each hex component encodes the public name as UTF-8 bytes. The description +shows the original package and name. Record a packaged alias as the canonical +`vault.type_secret` call with the `name` and `package` arguments for replay. + +Tool compilation is synchronous: for a cloud vault, `await vault.list()` first +to populate the cached inventory, then compile. Re-list and recompile after +mutating the vault. A cloud task needs neither local tools nor a device on the +vault: `cloud_task_inputs()` returns package/name references only. +`CloudCredentials` owns its SDK client; the bound `Vault` adapter borrows it +for requests. Close the provider when finished. + +Local files must be private (`chmod 600 credentials.yaml` on POSIX). Flat +YAML/JSON dictionaries map a name to a password. Nested dictionaries map app +package → credential name → fields. `Credential.from_mapping()` converts both +forms to credential records. `EnvCredentials` uses a flat mapping from variables +with the `MOBILERUN_SECRET_` prefix by default. + +`type_secret(name, *, package=None, field=None)` selects the password or sole +field by default. Specify `package` for duplicate names and `field` for another +field. `vault.device` exposes the bound handle read-only, or `None` if unbound. +Missing `device=` raises `CredentialDeviceRequired`; listing still works. +Core checks fresh editable focus and types once without humanization. Direct +Python calls preserve `NoFocusedInput`, `FocusUnknown`, and +`SecretInputRejected`; no retry is attempted. An app or OS can still change +focus between the check and the write. + +`CredentialPolicy` preserves host approval and pre-mask rules. The typing scope +masks logging during the operation. Direct typing registers the value in all +active recordings in the current task context so later action arguments are +masked. Use `CredentialMasks.scope(redactor=recorder.redactor)` from +`mobilerun.utils.credentials.masking` when you also need normalized snapshot +masks for replay. This does not redact screenshot pixels. + +## Files + +| File | Purpose | +| --- | --- | +| `base.py` | Metadata, atomic tool expansion and protected input | +| `dict.py`, `env.py`, `file.py` | Local stores; files use atomic private writes | +| `cloud.py` | Cached Cloud and 1Password vault entries and cloud-task references | + +See [credential models](../../models/credentials.py), +[credential utilities](../../utils/credentials/README.md), +[extensions](../extensions/README.md) and [credential CLI](../../cli/credentials/README.md). diff --git a/mobilerun/core/credentials/__init__.py b/mobilerun/core/credentials/__init__.py index 0a7b8a264..e60be8212 100644 --- a/mobilerun/core/credentials/__init__.py +++ b/mobilerun/core/credentials/__init__.py @@ -1,17 +1,16 @@ -"""Device-owned credential providers. Importing these never loads agents.""" +"""Credential extensions with optional protected input on a core device.""" -from mobilerun.core.credentials.base import ( - CredentialProvider, -) +from mobilerun.core.credentials.base import CredentialProvider from mobilerun.core.credentials.cloud import CloudCredentials from mobilerun.core.credentials.dict import DictCredentials from mobilerun.core.credentials.env import EnvCredentials from mobilerun.core.credentials.file import FileCredentials -from mobilerun.core.credentials.policy import CredentialPolicy -from mobilerun.models.credentials import Credential +from mobilerun.errors.credentials import CredentialDeviceRequired +from mobilerun.models.credentials import Credential, CredentialPolicy __all__ = [ "Credential", + "CredentialDeviceRequired", "CredentialPolicy", "CredentialProvider", "DictCredentials", diff --git a/mobilerun/core/credentials/base.py b/mobilerun/core/credentials/base.py index 5d284bc6f..9f4e594b3 100644 --- a/mobilerun/core/credentials/base.py +++ b/mobilerun/core/credentials/base.py @@ -3,28 +3,99 @@ from __future__ import annotations from abc import ABC, abstractmethod -from collections.abc import Mapping -from typing import TYPE_CHECKING, cast +from collections import defaultdict +from collections.abc import Awaitable, Callable, Iterable +from re import fullmatch +from typing import cast -from mobilerun.core.credentials.masking import CredentialMasks, current_masks -from mobilerun.core.credentials.policy import CredentialPolicy -from mobilerun.core.extensions import Extension, action, device_action -from mobilerun.errors import ( +from mobilerun_core import AsyncDevice, Secret + +from mobilerun.core.extensions import Extension, bind_atomic, function +from mobilerun.errors import CredentialError +from mobilerun.errors.credentials import ( + CredentialDeviceRequired, CredentialFieldNotFound, - ExtensionActionError, + CredentialReadError, ) -from mobilerun.errors.credentials import CredentialFormatError from mobilerun.models.context import ContextItem, JSONValue -from mobilerun.models.credentials import Credential, CredentialMetadata +from mobilerun.models.credentials import ( + Credential, + CredentialMetadata, + CredentialPolicy, +) +from mobilerun.utils.credentials.masking import CredentialMasks +from mobilerun.utils.redaction import remember_scoped_secrets, secret_scope + + +def _secret_tools( + bound: Callable[..., Awaitable[None]], +) -> Iterable[Callable[[], Awaitable[None]]]: + vault = cast(CredentialProvider, getattr(bound, "__self__", None)) + + def encode(value: str) -> str: + return value.encode("utf-8", errors="surrogatepass").hex() + + def alias( + name: str, package: str | None, *, qualified: bool + ) -> Callable[[], Awaitable[None]]: + arguments: dict[str, JSONValue] = {"name": name} + if qualified: + if package is None: + arguments["unscoped"] = True + else: + arguments["package"] = package + + async def invoke() -> None: + await bound(**arguments) + + if qualified: + # The legacy `_encoded_` suffixes contain only hex digits after the prefix. + scope = "u" if package is None else "p" + encode(package) + suffix = f"_encoded_{scope}_n{encode(name)}" + location = " without a package" if package is None else f" in {package!r}" + else: + suffix = ( + name + if fullmatch(r"[A-Za-z0-9_]+", name) + and not name.startswith("_encoded_") + else "_encoded_" + encode(name) + ) + location = "" + invoke.__name__ = f"type_secret_{suffix}" + invoke.__doc__ = ( + f"Type the {name!r} credential{location} into the focused field." + ) + return bind_atomic(invoke, arguments) -if TYPE_CHECKING: - from mobilerun.core.devices.base import Device + packages_by_name: dict[str, set[str | None]] = defaultdict(set) + for name, package in vault._known_entries(): + packages_by_name[name].add(package) + return tuple( + alias(name, package, qualified=len(packages) > 1) + for name, packages in sorted(packages_by_name.items()) + for package in sorted(packages, key=lambda item: (item is not None, item or "")) + ) class CredentialProvider(Extension, ABC): default_name = "vault" policies: tuple[CredentialPolicy, ...] = () + def __init__( + self, *, device: AsyncDevice | None = None, name: str | None = None + ) -> None: + super().__init__(name=name) + self._target = device + + @property + def device(self) -> AsyncDevice | None: + """The device bound to this vault for protected typing, if any.""" + return self._target + + @abstractmethod + def _known_entries(self) -> Iterable[tuple[str, str | None]]: + """Return public (name, package) pairs already available without I/O.""" + def requires_approval( self, package: str | None, field: str, name: str | None ) -> bool: @@ -52,15 +123,6 @@ async def prepare_masks(self, masks: CredentialMasks) -> None: for credential in matches: masks.register(credential.name, credential.fields[policy.field]) - @abstractmethod - async def _find( - self, - package: str | None = None, - field: str = "password", - name: str | None = None, - ) -> Credential | None: - """Return the first matching credential, or None.""" - @abstractmethod async def _list_credentials(self, package: str | None = None) -> list[Credential]: """Read credentials internally.""" @@ -73,31 +135,80 @@ async def _credential_metadata( for item in await self._list_credentials(package) ] - @action() + @function async def list(self, package: str | None = None) -> list[CredentialMetadata]: """List available credential names and fields without their values.""" return await self._credential_metadata(package) - @device_action() - async def type_field( - self, device: Device, package: str | None, field: str, name: str | None = None + @function(name="type_secret", to_atomic=_secret_tools) + async def _type_secret_tool( + self, + name: str, + *, + package: str | None = None, + field: str | None = None, + unscoped: bool = False, + ) -> None: + """Type a stored credential into the focused field.""" + if unscoped: + if package is not None: + raise CredentialFieldNotFound("An unscoped credential has no package") + await self._type_matching_secret(name, package, field, unscoped=True) + else: + await self.type_secret(name, package=package, field=field) + + async def type_secret( + self, name: str, *, package: str | None = None, field: str | None = None + ) -> None: + """Type a password or sole field, or select a field explicitly.""" + await self._type_matching_secret(name, package, field) + + async def _type_matching_secret( + self, + name: str, + package: str | None, + field: str | None, + *, + unscoped: bool = False, ) -> None: - """Type a credential field directly into the bound device.""" - if self.requires_approval(package, field, name): - raise ExtensionActionError("Credential input requires host approval") + device = self._target + if device is None: + raise CredentialDeviceRequired("Pass device= when constructing the vault") + matches: list[Credential] | None try: - credential = await self._find(package, field, name) + matches = [ + item + for item in await self._list_credentials(package) + if item.name == name + and (not unscoped or item.package is None) + and (field is None or field in item.fields) + ] except Exception: - # The resolver can include a value in its exception before the device - # has registered it for redaction. Never forward that traceback. - raise ExtensionActionError("Credential lookup failed") from None - if credential is None: - raise CredentialFieldNotFound("Credential field not found") - masks = current_masks.get() + # Resolver errors may contain values before they could be registered. + matches = None + if matches is None: + raise CredentialReadError("Credential lookup failed") from None + if len(matches) != 1: + raise CredentialFieldNotFound( + "Credential not found or ambiguous; specify its package and field" + ) + credential = matches[0] + if field is None: + if "password" in credential.fields: + field = "password" + elif len(credential.fields) == 1: + field = next(iter(credential.fields)) + else: + raise CredentialFieldNotFound("Specify the credential field to type") + if self.requires_approval(package, field, credential.name): + raise CredentialError("Credential input requires host approval") + value = credential.fields[field] + masks = CredentialMasks.current.get() if masks is not None: - masks.register(credential.name, credential.fields[field]) - if not await device._input_secret(credential.fields[field]): - raise ExtensionActionError("Device rejected credential input") + masks.register(credential.name, value) + remember_scoped_secrets(value) + with secret_scope(value): + await device.type_secret(Secret(value)) async def context(self) -> tuple[ContextItem, ...]: return ( @@ -107,25 +218,3 @@ async def context(self) -> tuple[ContextItem, ...]: {"credentials": cast(JSONValue, await self._credential_metadata())}, ), ) - - -def normalize(mapping: Mapping[str, object]) -> list[Credential]: - """Convert flat names or package → name → fields into one model.""" - result = [] - for key, value in mapping.items(): - if isinstance(value, str): - result.append(Credential(None, key, {"password": value})) - elif isinstance(value, dict): - for name, fields in value.items(): - if not isinstance(fields, dict) or not all( - isinstance(v, str) for v in fields.values() - ): - raise CredentialFormatError( - "Credential fields must map field types to strings" - ) - result.append(Credential(key, name, fields.copy())) - else: - raise CredentialFormatError( - "Credentials must be strings or package mappings" - ) - return result diff --git a/mobilerun/core/credentials/cloud.py b/mobilerun/core/credentials/cloud.py index 233fd0bf5..ac52b2d33 100644 --- a/mobilerun/core/credentials/cloud.py +++ b/mobilerun/core/credentials/cloud.py @@ -4,57 +4,25 @@ import asyncio from collections.abc import Awaitable, Iterable -from contextlib import ExitStack -from typing import Any, cast, get_args +from typing import cast, get_args + +from mobilerun_core import AsyncDevice -from mobilerun.clients.cloud import secrets from mobilerun.clients.cloud.client import cloud_client +from mobilerun.clients.cloud.secrets import FieldType, Vault from mobilerun.config.settings import get_settings from mobilerun.core.credentials.dict import DictCredentials -from mobilerun.core.extensions import action from mobilerun.errors.base import is_value_safe from mobilerun.errors.cloud import CloudConflict, CloudResourceNotFound from mobilerun.models.billing import Billing from mobilerun.models.cloud_task import CloudCredentialReference, CloudTaskInputs -from mobilerun.models.credentials import Credential -from mobilerun.utils.redaction import _redact_secrets, secret_scope +from mobilerun.models.credentials import Credential, CredentialMetadata +from mobilerun.utils.redaction import redact, secret_scope -FIELD_ORDER = get_args(secrets.FieldType) +FIELD_ORDER = get_args(FieldType) FIELD_TYPES = frozenset(FIELD_ORDER) -async def _write_secret_values( - operation: Awaitable[object], values: Iterable[str] -) -> None: - with ExitStack() as stack: - for value in values: - stack.enter_context(secret_scope(value)) - try: - await operation - return - except Exception as exc: - message = _redact_secrets(str(exc)) - if is_value_safe(exc) and message == str(exc): - sanitized = exc - sanitized.__cause__ = sanitized.__context__ = None - sanitized.__notes__ = [] - else: - try: - sanitized = type(exc)(message) - except Exception: - sanitized = RuntimeError(message) - raise sanitized from None - - -def _validate_field(field: str) -> secrets.FieldType: - if field not in FIELD_TYPES: - raise ValueError( - f"Invalid credential field type {field!r}; expected one of: {', '.join(sorted(FIELD_TYPES))}" - ) - # The membership check above validates the external string against the SDK union. - return cast(secrets.FieldType, field) - - class CloudCredentials(DictCredentials): cloud_native = True @@ -77,27 +45,67 @@ def __init__( api_key: str | None = None, base_url: str | None = None, *, + device: AsyncDevice | None = None, billing: Billing | str | None = None, name: str | None = None, ) -> None: - super().__init__({}, name=name) + super().__init__({}, device=device, name=name) self._billing = Billing( get_settings().MOBILERUN_BILLING if billing is None else billing ) self._client = cloud_client(api_key, base_url, billing=self._billing) + self._vault = Vault(client=self._client, billing=self._billing) self._loaded = False self._package_cache = {} self._package_names: dict[str, str] = {} self._sources: dict[tuple[str, str], str] = {} self._lock = asyncio.Lock() + @staticmethod + async def _write_secret_values( + operation: Awaitable[object], values: Iterable[str] + ) -> None: + with secret_scope(*values): + try: + await operation + return + except Exception as exc: + message = redact(str(exc)) + if is_value_safe(exc) and message == str(exc): + sanitized = exc + sanitized.__cause__ = sanitized.__context__ = None + sanitized.__notes__ = [] + else: + try: + sanitized = type(exc)(message) + except Exception: + sanitized = RuntimeError(message) + raise sanitized from None + + @staticmethod + def _validate_field(field: str) -> FieldType: + if field not in FIELD_TYPES: + raise ValueError( + f"Invalid credential field type {field!r}; expected one of: {', '.join(sorted(FIELD_TYPES))}" + ) + # Membership validates the external string against the SDK union. + return cast(FieldType, field) + + def _invalidate_cache(self) -> None: + self._loaded = False + self._credentials = [] + self._package_cache.clear() + async def _list_credentials(self, package: str | None = None) -> list[Credential]: async with self._lock: if package is not None: if "." in package: self._package_names[package.replace(".", "-")] = package if package not in self._package_cache: - response = await self._list_package(package) + try: + response = await self._vault.list_package(package) + except CloudResourceNotFound: + response = [] for item in response: if ( getattr(item, "source", None) == "onepassword" @@ -117,42 +125,41 @@ async def _list_credentials(self, package: str | None = None) -> list[Credential ] return list(self._package_cache[package]) if not self._loaded: - response = await secrets.list_secrets( - self._client, billing=self._billing - ) + items = await self._vault.list() self._sources = { ( item.package_name.replace(".", "-"), item.credential_name, ): "1password" - for item in response + for item in items if getattr(item, "source", None) == "onepassword" or getattr(getattr(item, "link", None), "provider", None) == "onepassword" } - items = [ + self._credentials = [ Credential( item.package_name, item.credential_name, {entry.field_type: entry.value for entry in item.fields}, ) - for item in response + for item in items ] - self._credentials = items self._loaded = True return await super()._list_credentials(package) - @action() - async def list(self, package: str | None = None) -> list[dict]: - """List vault metadata without secret values.""" - return await self._credential_metadata(package) + def _known_entries(self) -> Iterable[tuple[str, str | None]]: + yield from super()._known_entries() + for credentials in self._package_cache.values(): + yield from ((item.name, item.package) for item in credentials) - async def _credential_metadata(self, package: str | None = None) -> list[dict]: + async def _credential_metadata( + self, package: str | None = None + ) -> list[CredentialMetadata]: items = await self._list_credentials(package) - result = [] + result: list[CredentialMetadata] = [] for item in items: slug = (item.package or "").replace(".", "-") - entry = { + entry: CredentialMetadata = { "package": self._package_names.get(slug, item.package), "name": item.name, "fields": list(item.fields), @@ -165,104 +172,63 @@ async def _credential_metadata(self, package: str | None = None) -> list[dict]: async def save(self, package: str, name: str, fields: dict[str, str]) -> None: if "." in package: self._package_names[package.replace(".", "-")] = package - validated_fields: dict[secrets.FieldType, str] = { - _validate_field(field): value for field, value in fields.items() + validated_fields: dict[FieldType, str] = { + self._validate_field(field): value for field, value in fields.items() } async with self._lock: try: + try: + items = await self._vault.list_package(package) + except CloudResourceNotFound: + try: + await self._vault.create_package(package) + except CloudConflict: + pass + items = [] existing = next( - ( - item - for item in await self._list_package(package) - if item.credential_name == name - ), - None, + (item for item in items if item.credential_name == name), None ) if existing is None: - try: - await secrets.list_package( - self._client, package, billing=self._billing - ) - except CloudResourceNotFound: - try: - await secrets.create_package( - self._client, package, billing=self._billing - ) - except CloudConflict: - pass - await _write_secret_values( - secrets.save( - self._client, - package, - name, - validated_fields, - billing=self._billing, - ), + await self._write_secret_values( + self._vault.save(package, name, validated_fields), validated_fields.values(), ) else: existing_fields = {item.field_type for item in existing.fields} for field, value in validated_fields.items(): operation = ( - secrets.update + self._vault.update if field in existing_fields - else secrets.create_field + else self._vault.create_field ) - await _write_secret_values( - operation( - self._client, - package, - name, - field, - value, - billing=self._billing, - ), + await self._write_secret_values( + operation(package, name, field, value), (value,), ) finally: - self._loaded = False - self._credentials = [] - self._package_cache.clear() + self._invalidate_cache() async def update(self, package: str, name: str, field: str, value: str) -> None: - validated_field = _validate_field(field) + validated_field = self._validate_field(field) async with self._lock: try: - await _write_secret_values( - secrets.update( - self._client, - package, - name, - validated_field, - value, - billing=self._billing, - ), + await self._write_secret_values( + self._vault.update(package, name, validated_field, value), (value,), ) finally: - self._loaded = False - self._credentials = [] - self._package_cache.clear() + self._invalidate_cache() async def delete(self, package: str, name: str, field: str | None = None) -> None: - validated_field = _validate_field(field) if field is not None else None + validated_field = self._validate_field(field) if field is not None else None async with self._lock: try: - await secrets.delete( - self._client, package, name, validated_field, billing=self._billing - ) + if validated_field is None: + await self._vault.delete(package, name) + else: + await self._vault.delete_field(package, name, validated_field) finally: - self._loaded = False - self._credentials = [] - self._package_cache.clear() + self._invalidate_cache() async def on_close(self) -> None: await self._client.close() - - async def _list_package(self, package: str) -> list[Any]: - try: - return await secrets.list_package( - self._client, package, billing=self._billing - ) - except CloudResourceNotFound: - return [] diff --git a/mobilerun/core/credentials/dict.py b/mobilerun/core/credentials/dict.py index c8386fab7..4c1d2bcf6 100644 --- a/mobilerun/core/credentials/dict.py +++ b/mobilerun/core/credentials/dict.py @@ -1,17 +1,26 @@ """In-memory credentials using the shared mapping normalizer.""" -from collections.abc import Mapping +from collections.abc import Iterable, Mapping -from mobilerun.core.credentials.base import CredentialProvider, normalize +from mobilerun_core import AsyncDevice + +from mobilerun.core.credentials.base import CredentialProvider from mobilerun.models.credentials import Credential class DictCredentials(CredentialProvider): def __init__( - self, mapping: Mapping[str, object], *, name: str | None = None + self, + mapping: Mapping[str, object] | Mapping[str | None, object], + *, + device: AsyncDevice | None = None, + name: str | None = None, ) -> None: - super().__init__(name=name) - self._credentials = normalize(mapping) + super().__init__(device=device, name=name) + self._credentials = Credential.from_mapping(mapping) + + def _known_entries(self) -> Iterable[tuple[str, str | None]]: + return ((item.name, item.package) for item in self._credentials) async def _list_credentials(self, package: str | None = None) -> list[Credential]: return [ @@ -19,18 +28,3 @@ async def _list_credentials(self, package: str | None = None) -> list[Credential for item in self._credentials if package is None or item.package == package ] - - async def _find( - self, - package: str | None = None, - field: str = "password", - name: str | None = None, - ) -> Credential | None: - return next( - ( - item - for item in await self._list_credentials(package) - if field in item.fields and (name is None or item.name == name) - ), - None, - ) diff --git a/mobilerun/core/credentials/env.py b/mobilerun/core/credentials/env.py index 67385f554..352c33222 100644 --- a/mobilerun/core/credentials/env.py +++ b/mobilerun/core/credentials/env.py @@ -2,12 +2,18 @@ import os # The vault deliberately enumerates an arbitrary caller-specified prefix. +from mobilerun_core import AsyncDevice + from mobilerun.core.credentials.dict import DictCredentials class EnvCredentials(DictCredentials): def __init__( - self, prefix: str = "MOBILERUN_SECRET_", *, name: str | None = None + self, + prefix: str = "MOBILERUN_SECRET_", + *, + device: AsyncDevice | None = None, + name: str | None = None, ) -> None: super().__init__( { @@ -15,5 +21,6 @@ def __init__( for key, value in os.environ.items() if key.startswith(prefix) }, + device=device, name=name, ) diff --git a/mobilerun/core/credentials/file.py b/mobilerun/core/credentials/file.py index 0002898b1..fb4900cfc 100644 --- a/mobilerun/core/credentials/file.py +++ b/mobilerun/core/credentials/file.py @@ -3,9 +3,9 @@ import os import shlex import stat -import tempfile -import uuid +from collections.abc import Iterator from contextlib import contextmanager +from typing import Any try: import fcntl @@ -14,84 +14,27 @@ from pathlib import Path import yaml +from mobilerun_core import AsyncDevice -from mobilerun.core.credentials.base import normalize from mobilerun.core.credentials.dict import DictCredentials - - -def _windows_private_temp(parent: Path) -> tuple[int, str]: - """Create a new file with a protected owner-only DACL, never an inherited ACL.""" - import ctypes as c - import msvcrt - from ctypes import wintypes as w - - class SecurityAttributes(c.Structure): - _fields_ = [("length", w.DWORD), ("descriptor", w.LPVOID), ("inherit", w.BOOL)] - - kernel = c.WinDLL("kernel32", use_last_error=True) - security = c.WinDLL("advapi32", use_last_error=True) - convert = security.ConvertStringSecurityDescriptorToSecurityDescriptorW - convert.argtypes = [w.LPCWSTR, w.DWORD, c.POINTER(w.LPVOID), c.POINTER(w.DWORD)] - convert.restype = w.BOOL - create = kernel.CreateFileW - create.argtypes = [ - w.LPCWSTR, - w.DWORD, - w.DWORD, - c.POINTER(SecurityAttributes), - w.DWORD, - w.DWORD, - w.HANDLE, - ] - create.restype = w.HANDLE - volume = kernel.GetVolumeInformationByHandleW - volume.argtypes = [ - w.HANDLE, - w.LPWSTR, - w.DWORD, - c.POINTER(w.DWORD), - c.POINTER(w.DWORD), - c.POINTER(w.DWORD), - w.LPWSTR, - w.DWORD, - ] - volume.restype = w.BOOL - descriptor = w.LPVOID() - path = str(parent / f".credentials-{uuid.uuid4().hex}") - # P = protected (no inherited ACEs); FA = full access; OW = owner rights. - if not convert("D:P(A;;FA;;;OW)", 1, c.byref(descriptor), None): - raise c.WinError(c.get_last_error()) - try: - attributes = SecurityAttributes(c.sizeof(SecurityAttributes), descriptor, False) - # GENERIC_READ | GENERIC_WRITE, no sharing, CREATE_NEW, FILE_ATTRIBUTE_NORMAL. - handle = create(path, 0xC0000000, 0, c.byref(attributes), 1, 0x80, None) - if handle == w.HANDLE(-1).value: - raise c.WinError(c.get_last_error()) - finally: - kernel.LocalFree(descriptor) - try: - flags = w.DWORD() - if not volume(handle, None, 0, None, None, c.byref(flags), None, 0): - raise c.WinError(c.get_last_error()) - if not flags.value & 0x8: # FILE_PERSISTENT_ACLS (e.g. not FAT/exFAT) - raise PermissionError( - "Credentials require a volume supporting private DACLs" - ) - return msvcrt.open_osfhandle(handle, os.O_WRONLY | os.O_BINARY), path - except BaseException: - kernel.CloseHandle(w.HANDLE(handle)) - os.unlink(path) - raise +from mobilerun.models.credentials import Credential +from mobilerun.utils.credentials.private import private_credential_writer class FileCredentials(DictCredentials): """Atomically replace the credential file with a new owner-only file.""" - def __init__(self, path: str | Path, *, name: str | None = None) -> None: + def __init__( + self, + path: str | Path, + *, + device: AsyncDevice | None = None, + name: str | None = None, + ) -> None: self.path = Path(path).expanduser() - super().__init__(self._read(), name=name) + super().__init__(self._read(), device=device, name=name) - def _read(self): + def _read(self) -> dict[str | None, Any]: try: fd = os.open(self.path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)) except FileNotFoundError: @@ -107,14 +50,22 @@ def _read(self): try: data = yaml.safe_load(stream) or {} except yaml.YAMLError: - raise ValueError("Invalid credentials file format") from None - if not isinstance(data, dict): - raise ValueError("Credentials file must contain a mapping") - normalize(data) + pass + else: + if not isinstance(data, dict): + raise ValueError("Credentials file must contain a mapping") + return data + raise ValueError("Invalid credentials file format") from None + + def _read_for_edit(self, package: str | None, name: str) -> dict[str | None, Any]: + data = self._read() + Credential.from_mapping(data) + if package is None and isinstance(data.get(name), str): + data.setdefault(None, {})[name] = {"password": data.pop(name)} return data @contextmanager - def _locked(self): + def _locked(self) -> Iterator[None]: self.path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) lock_path = self.path.with_name(self.path.name + ".lock") fd = os.open( @@ -129,37 +80,17 @@ def _locked(self): fcntl.flock(fd, fcntl.LOCK_UN) os.close(fd) - def _write(self, data): - normalized = normalize(data) - missing = [] - parent = self.path.parent - while not parent.exists(): - missing.append(parent) - parent = parent.parent - for directory in reversed(missing): - directory.mkdir(mode=0o700, exist_ok=True) - if os.name == "nt": - fd, path = _windows_private_temp(self.path.parent) - else: - fd, path = tempfile.mkstemp(prefix=".credentials-", dir=self.path.parent) - try: - with os.fdopen(fd, "w", encoding="utf-8") as stream: - if os.name != "nt": - os.fchmod(stream.fileno(), 0o600) - yaml.safe_dump(data, stream, sort_keys=False) - os.replace(path, self.path) - finally: - if os.path.exists(path): - os.unlink(path) + def _write(self, data: dict[str | None, Any]) -> None: + normalized = Credential.from_mapping(data) + with private_credential_writer(self.path) as stream: + yaml.safe_dump(data, stream, sort_keys=False) self._credentials = normalized async def save( self, package: str | None, name: str, fields: dict[str, str] ) -> None: with self._locked(): - data = self._read() - if package is None and isinstance(data.get(name), str): - data.setdefault(None, {})[name] = {"password": data.pop(name)} + data = self._read_for_edit(package, name) entries = data.setdefault(package, {}) if not isinstance(entries, dict): raise ValueError("Package conflicts with a flat credential") @@ -170,9 +101,7 @@ async def update( self, package: str | None, name: str, field: str, value: str ) -> None: with self._locked(): - data = self._read() - if package is None and isinstance(data.get(name), str): - data.setdefault(None, {})[name] = {"password": data.pop(name)} + data = self._read_for_edit(package, name) if ( package not in data or name not in data[package] @@ -186,9 +115,7 @@ async def delete( self, package: str | None, name: str, field: str | None = None ) -> None: with self._locked(): - data = self._read() - if package is None and isinstance(data.get(name), str): - data.setdefault(None, {})[name] = {"password": data.pop(name)} + data = self._read_for_edit(package, name) if package not in data or name not in data[package]: raise ValueError("Credential not found") if field is None: diff --git a/mobilerun/core/credentials/policy.py b/mobilerun/core/credentials/policy.py deleted file mode 100644 index 57d7eef1b..000000000 --- a/mobilerun/core/credentials/policy.py +++ /dev/null @@ -1,23 +0,0 @@ -"""Host-owned credential policies. Macro data cannot relax these rules.""" - -from dataclasses import dataclass - - -@dataclass(frozen=True) -class CredentialPolicy: - """Policy for a named field (optionally limited to one package).""" - - name: str - field: str = "password" - package: str | None = None - requires_approval: bool = False - mask_from_start: bool = False - mask_card_numbers: bool = False - - def matches(self, package: str | None, field: str, name: str | None) -> bool: - # A partial selector must not bypass a protected field it could match. - return ( - (name is None or self.name == name) - and self.field == field - and (package is None or self.package is None or self.package == package) - ) diff --git a/mobilerun/core/devices/README.md b/mobilerun/core/devices/README.md deleted file mode 100644 index 2a2b109e5..000000000 --- a/mobilerun/core/devices/README.md +++ /dev/null @@ -1,259 +0,0 @@ -# Devices - -`Device` is the common action interface. Construct a platform device, then call -`connect()`, await it, or use an async context. These all perform the same -idempotent setup. Context exit calls `close()`. - -```python -from mobilerun import AndroidDevice, RecordingDevice -from mobilerun.core.state import StateProviderOptions - -async with AndroidDevice("emulator-5554", state_options=StateProviderOptions(vision=True)) as phone: - device = RecordingDevice(phone) - state = await device.state.refresh() - print(state.formatted_text) - assert device.state.current is state - await device.tap_element(0) - await device.wait(1) - device.finish("succeeded") - print(device.run_dir / "steps.jsonl") -``` - -## Quick example - -Connect a local Android device or running emulator. Run this inside an async function. - -```python -from pathlib import Path -from mobilerun import AndroidDevice - -async with AndroidDevice("emulator-5554") as phone: - await phone.tap(200, 400) - await phone.input_text("hello") - await phone.swipe(200, 700, 200, 300, duration_ms=500) - Path("screen.png").write_bytes(await phone.screenshot()) - print((await phone.state.refresh()).formatted_text) -``` - -See [state](../state/README.md), [credentials](../credentials/README.md), -[proxies](../proxy/README.md), and [Workspace](../WORKSPACE.md). - -## State and operators - -`device.state` is a controller with only `refresh()`, `current`, and -`capabilities`. `refresh()` returns a `UIState`; `current` is that cached snapshot -and raises `DeviceNotReady` until the first refresh. Read elements, text, and -coordinate helpers from the snapshot, not from the controller. - -Configure state at construction using `state_options=`, a `state_provider=` -instance, or a `state_provider_factory=(device, options) -> StateProvider`. -An instance and factory are mutually exclusive. Built-in providers and factories -are lazily bound to the outer wrapper so observations see its behavior. An -explicit provider instance is reused as supplied. - -```python -from mobilerun import AndroidDevice -# Requires the unpublished mobilerun-agents add-on. -from mobilerun_agents import AgentOperator - -device = AndroidDevice("emulator-5554", operator=AgentOperator()) -await device.connect() -await device.do("Open Settings") -await device.expect("Settings is visible") -# Override only this operation: -await device.do("Read the battery level", operator=AgentOperator()) -``` - -Providers, operators, raw trees/time, coordinate calibration, recovery, unwrap, -and backend handles are internal machinery. There are no runtime attach methods -or compatibility aliases. Advanced raw-driver composition lives in -`components/wrapper.py`, not the root exports. - -## Platforms and wrappers - -- `AndroidDevice(serial)` uses a connected ADB phone or emulator. -- `await AndroidDevice(avd="Pixel_API_35", headless=True)` starts or reuses an - emulator. Only an emulator started by that instance is stopped on close; - `keep=True` retains it. `timeout=` controls boot wait. -- `CloudDevice(device_id=...)` uses an existing phone. Awaiting a device without - an ID creates one and can incur charges. `keep=True` retains created phones. -- `IOSDevice(url, token=...)` detects the Portal protocol once during connect. - Legacy Portal uses the iOS text-tree provider; Portal HTTP uses the Android - tree provider with point-space coordinates. -- `RemoteDevice(url=...)` uses screenshot-only state by default. -- `RecordingDevice(device)` writes dispatched actions and outcomes to `steps.jsonl` - under a private run directory. The run starts on demand; `start_run()` can - reserve it earlier, and `finish(status, failed_step=None)` finalizes metadata - without closing the device. Actions can continue after `finish()`, but they - are not recorded. `step_index` is the last persisted row. Use - `with recorder.collect_steps() as ids:` for rows committed in the block by - this task and tasks it spawns. Tasks created outside the block are excluded. -- `StealthDevice(device)` applies humanized interaction behavior and vetoes - recording in either wrapper order. Check `device.recording_allowed()` before - using `device.recording_device()` to reuse a caller-owned recorder. - -`capture="full"` (default) records before/after fingerprints, redacted UI and -context JSON, and unredacted screenshots. Use `capture="actions"` to skip -all automatic observations, especially for sensitive flows. Explicit -`capture_fingerprint(fresh=True)` still works on demand when supported. -See [runs](../runs/README.md) for settings and scoped recording policy. - -Wrappers explicitly delegate operations and private hooks. They do not forward -unknown attributes. `do()` and `expect()` execute against the outer wrapper. -Keep a typed platform handle for platform-only operations, such as cloud rename. -`device.supported_operations` describes backend operations; presence of a method does -not guarantee backend support. Unsupported actions raise -`DeviceOperationNotSupported`. `supported_buttons` lists button names. - -Focus-changing input operations share one lock on the root device, including -calls through wrappers, pools and action catalogs. Secret input holds it across -the focused-field precheck and raw typing. Base methods, subclass overrides and -device mixins are instrumented automatically. Wrapper delegation is reentrant -only within the same asyncio task; child tasks wait like any competing operation. -Direct driver access and autonomous app/OS focus changes are outside this lock. - -## Installed apps versus workspace apps - -```python -from mobilerun import Workspace - -app = await Workspace.upload_app("counter.apk") -await cloud_device.install_app(app) -await cloud_device.install_app(await Workspace.get_app("app-id")) -await cloud_device.uninstall_app(app.package) -await Workspace.delete_app(app.id) # deletes uploaded files/metadata, not an install - -local_app = await local_device.install_apk("counter.apk", reinstall=True) -await local_device.start_app(local_app.package) -apps = await local_device.list_apps() # user apps only -all_apps = await local_device.list_apps(include_system=True) -``` - -`install_apk(path)` and `install_app(App)` stay separate. Cloud path installation -uploads using the destination device's credentials. Cloud installs wait for -success and the requested version to appear; pass `timeout=` or set -`MOBILERUN_CLOUD_APP_INSTALL_TIMEOUT_SECONDS` (default 180). -Local Android verifies the installed package. Portal HTTP and local iOS may not -support installation/uninstallation. - -## Files and pools - -```python -from mobilerun import DevicePool, Workspace - -file = await Workspace.upload_file("photo.jpg") -await Workspace.push_file(file, device, "/sdcard/Download") -await device.push_file("local.txt") -files = await device.list_files("/sdcard/Download") -await device.pull_file(files[0].path, "downloaded.txt") - -async with DevicePool([first, second], concurrency=2) as pool: - states = await pool.state.refresh() - await pool.start_app("com.android.settings") -``` - -Pool results preserve device order. Package methods broadcast a single package -string. For different packages, iterate `pool.devices` explicitly. Pull files -from members individually with distinct local destinations; pools have no -`pull_file` method. Pools do not expose cloud lifecycle methods. - -Android image/video pushes default to `/sdcard/DCIM/Camera` and trigger a media -scan; other files default to `/sdcard/Download`. Cloud uploads do not expose -media scanning. Local iOS and remote devices may not support files. - -## Environment, credentials, and proxies - -| Value | Definition | -| --- | --- | -| `Location` | `mobilerun.models.location` — device latitude and longitude. | - -Location, timezone, URL, language, and clipboard operations are declared on -`Device` and delegated by wrappers and pools. Cloud implements these through its -API. Android emulator location uses `adb emu geo fix`; Android timezone and URL -use shell commands. Unsupported backend combinations fail explicitly. - -```python -location = await device.get_location() # Cloud: latitude/longitude, or None -locations = await pool.get_location() # One result per device, in order -await device.set_language("de-DE") -locale = await device.get_language() # Cloud BCP-47 locale -timezone = await device.get_timezone() # Cloud IANA timezone, or None -await device.set_clipboard("hello") -text = await device.get_clipboard() -await device.open_url("https://example.com") -``` - -Reading location is unsupported on local Android, iOS and remote devices. The -cloud API does not expose a mocked-status flag. - -Bind credentials and communications from the resource side: -`await provider.bind(device)`, `await number.bind(device)`, and -`await mailbox.bind(device)`. Credentials are a read-only tuple. -`device.number` and `device.mailbox` return typed resources; unavailable resources -raise `DeviceOperationNotSupported`. An `AgentOperator` from the optional `mobilerun-agents` package can use local -credentials on a cloud phone; a `CloudTaskOperator` requires cloud vault references. -Only reference names, never secret values, are sent to public cloud tasks. - -Cloud credentials resolve from `MOBILERUN_API_KEY`, then saved login. There is no -legacy environment fallback. Device billing follows settings; Workspace defaults -to `Billing.NO_COMMERCE`. Creation and lifecycle operations can incur charges or -delete data. - -Creating a cloud phone and rotating proxy can incur charges. - -```python -from mobilerun import CloudDevice -from mobilerun.core.proxy import CloudRotatingProxy - -proxy = CloudRotatingProxy(country="DE") -async with CloudDevice(country="DE", proxy=proxy, - name="signup-check", billing="paid", plan="minute") as phone: - await phone.info() - await phone.rename("signup-complete") - status = await proxy.status() -``` - -Cloud creation requires a proxy. Omission selects configured rotating-proxy -defaults; `None` is invalid. `CloudFixedProxy` reuses purchased capacity; -`CloudSocks5Proxy` uses external credentials. Android supports `LocalProxy`. - -| Class | Where it works | What it does | -| --- | --- | --- | -| `CloudRotatingProxy` | Cloud phones | Uses rotating residential Connect capacity | -| `CloudFixedProxy` | Cloud phones | Reuses a purchased Connect proxy | -| `CloudSocks5Proxy` | Cloud phones | Uses your own SOCKS5 server | -| `LocalProxy` | Local Android | Sets a plain HTTP proxy without authentication | -Proxies are extensions: `await proxy.bind(device)` and `await proxy.status()`. -`phone.proxy` returns the extension object; retain the original handle for static -typing. There is no typed lookup API. Cloud creation publishes the -exact supplied/default proxy instance without a second provisioning call. Cloud -phones reject standalone proxy unbind: use `await replacement.bind(phone, -force=True)` to switch. Local proxies may be unbound normally. Closing a borrowed -cloud phone detaches the local extension without disconnecting its server proxy. -Keep passwords in the environment or a vault. - -Connecting an existing cloud phone adopts its remote proxy without SDK mutations: -known Connect IDs become `CloudFixedProxy`; connected but unidentified proxies -become typed `ExistingCloudProxy` observations. Both expose `status()` and require -`force=True` replacement. If the phone is disconnected, no extension is published; -`phone.proxy` raises an error suggesting `await proxy.bind(phone)`. Nothing is -automatically provisioned. Failed/ cancelled binds and failed rollbacks read remote -status before re-raising, so the registry reflects the actual active proxy. Only -unreadable remote state leaves a binding uncertain and blocks ordinary actions. - -Creation-only options include `name`, `country`, `locale`, `timezone`, -`android_version`, `apps`, `template`, `proxy`, `device_type`, and `plan`. -Do not combine `template` with `android_version` or `apps`. Existing IDs reject -creation options. `phone.name` is a read-only response cache; `info()` refreshes -it. Existing IDs are never automatically terminated. Cloud-only lifecycle -methods include `resume`, `stop`, `wait_ready`, `reboot`, `reset`, and `terminate`. - -For iOS portal authentication, pass credentials using `token=` rather than embedding them in the URL. - -### Migrating placeholder input - -Placeholder expansion has been removed. Replace `{{secret:…}}` with -`await vault.type_field(package, field, name)` after binding the vault. Replace -`{{code:sms}}` with `code = await sms.wait_for_code()` followed by -`await device.input_text(code)`. Codes are ordinary values; credential values -are typed directly by the vault and are not returned. diff --git a/mobilerun/core/devices/__init__.py b/mobilerun/core/devices/__init__.py deleted file mode 100644 index f85282daf..000000000 --- a/mobilerun/core/devices/__init__.py +++ /dev/null @@ -1,53 +0,0 @@ -"""Device actions and explicit behavioral wrappers.""" - -from importlib import import_module -from typing import TYPE_CHECKING, Any - -if TYPE_CHECKING: - from mobilerun.core.devices.android import AndroidDevice - from mobilerun.core.devices.base import Device - from mobilerun.core.devices.cloud import CloudDevice - from mobilerun.core.devices.ios import IOSDevice - from mobilerun.core.devices.pool import DevicePool - from mobilerun.core.devices.recording import RecordingDevice - from mobilerun.core.devices.remote import RemoteDevice - from mobilerun.core.devices.stealth import StealthDevice - -__all__ = [ - "Device", - "AndroidDevice", - "CloudDevice", - "IOSDevice", - "RemoteDevice", - "DevicePool", - "RecordingDevice", - "StealthDevice", -] - - -_EXPORT_MODULES = dict( - zip( - __all__, - ( - "base", - "android", - "cloud", - "ios", - "remote", - "pool", - "recording", - "stealth", - ), - strict=True, - ) -) - - -def __getattr__(name: str) -> Any: - if name in _EXPORT_MODULES: - return getattr(import_module(f"{__name__}.{_EXPORT_MODULES[name]}"), name) - raise AttributeError(f"module {__name__!r} has no attribute {name!r}") - - -def __dir__() -> list[str]: - return sorted(set(globals()) | set(__all__)) diff --git a/mobilerun/core/devices/android.py b/mobilerun/core/devices/android.py deleted file mode 100644 index ce1d7bb3a..000000000 --- a/mobilerun/core/devices/android.py +++ /dev/null @@ -1,404 +0,0 @@ -"""Android device interface.""" - -import asyncio -import logging -import shlex -from collections.abc import Awaitable, Callable -from pathlib import Path -from typing import Any, Unpack - -from async_adbutils import AdbDevice -from mobilerun_core_local.driver.android import AndroidDriver -from mobilerun_core_local.transport.android.portal_client import PortalClient - -from mobilerun.clients.local import emulator -from mobilerun.clients.local.apk import inspect_apk -from mobilerun.config.settings import get_settings -from mobilerun.core.devices.base import Device, InstallOptions -from mobilerun.core.devices.components import environment -from mobilerun.core.devices.components import files as device_files -from mobilerun.core.devices.components.identifiers import _sanitize_identifier -from mobilerun.core.devices.components.raw import _backend_operation, _BackendIO -from mobilerun.core.operator import Operator -from mobilerun.core.proxy import LocalProxy, ProxyStatus -from mobilerun.core.proxy.target import AndroidProxyTarget -from mobilerun.core.state.base import StateProvider -from mobilerun.core.state.options import ( - StateProviderFactory, - StateProviderOptions, - android_state_provider, -) -from mobilerun.errors import DeviceOperationNotSupported -from mobilerun.models.apps import App -from mobilerun.models.files import DeviceFile - - -class AndroidDevice(_BackendIO, Device): - """Android device backed by the local Android driver.""" - - # Local file operations. - async def push_file(self, path: str | Path, dest: str | None = None) -> DeviceFile: - return await device_files.android_push_file(self, path, dest) - - async def list_files(self, directory: str) -> list[DeviceFile]: - return await device_files.android_list_files(self, directory) - - async def pull_file(self, remote_path: str, local_path: str | Path) -> Path: - return await device_files.android_pull_file(self, remote_path, local_path) - - async def delete_file(self, remote_path: str) -> None: - await device_files.android_delete_file(self, remote_path) - - # Local environment controls. - async def set_location(self, latitude: float, longitude: float) -> None: - await environment.android_set_location(self, latitude, longitude) - - async def reset_location(self) -> None: - raise DeviceOperationNotSupported( - "reset_location is unsupported on local Android; emulators keep the last fixed location; set a new one instead" - ) - - async def set_timezone(self, timezone: str) -> None: - environment.validate_timezone(timezone) - await environment.android_shell( - self, f"cmd alarm set-timezone {shlex.quote(timezone)}" - ) - - async def open_url(self, url: str) -> None: - await environment.android_shell( - self, f"am start -a android.intent.action.VIEW -d {shlex.quote(url)}" - ) - - _backend = AndroidDriver - - @property - def platform(self) -> str: - return self._driver.platform - - @property - def supported_operations(self) -> set[str]: - return self._driver.supported | {"http_proxy", "open_url"} - - @property - def supported_buttons(self) -> set[str]: - return self._driver.supported_buttons - - @property - def _io_driver(self) -> AndroidDriver: - if self._pending_avd: - raise RuntimeError( - "Await AndroidDevice(avd=...) or use async with before using it" - ) - self._driver._serial = self._serial - return self._driver - - @property - def _adb_device(self) -> AdbDevice | None: - return self._driver.device - - @_adb_device.setter - def _adb_device(self, value: AdbDevice | None) -> None: - self._driver.device = value - - @property - def _portal(self) -> PortalClient | None: - return self._driver.portal - - @_portal.setter - def _portal(self, value: PortalClient | None) -> None: - self._driver.portal = value - - @property - def _portal_keyboard_available(self) -> bool: - return self._driver._portal_keyboard_available - - @_portal_keyboard_available.setter - def _portal_keyboard_available(self, value: bool) -> None: - self._driver._portal_keyboard_available = value - - @property - def identifier(self) -> str | None: - return _sanitize_identifier(self._serial) - - @property - def _state_recovery(self) -> Callable[[], Awaitable[None]] | None: - if self._driver._portal_mode == "disabled": - return None - return self._recover_portal - - async def _recover_portal(self) -> None: - from mobilerun_core_local.driver.android.portal import ( - PORTAL_PACKAGE_NAME, - portal_a11y_service, - portal_content_uri, - setup_keyboard, - ) - - device = self._adb_device - portal = self._portal - if device is None or portal is None: - return - logger = logging.getLogger("mobilerun") - a11y = portal_a11y_service(PORTAL_PACKAGE_NAME) - read = await device.shell2( - "settings get secure enabled_accessibility_services", rstrip=True - ) - current = read.output - if read.returncode or not isinstance(current, str): - raise RuntimeError("Could not read Android accessibility services") - services = [] if current in ("", "null") else current.split(":") - if a11y not in services: - services.append(a11y) - await device.shell( - f"settings put secure enabled_accessibility_services {shlex.quote(':'.join(services))}" - ) - await device.shell("settings put secure accessibility_enabled 1") - if portal.tcp_available: - toggle_uri = portal_content_uri(PORTAL_PACKAGE_NAME, "toggle_socket_server") - try: - await device.shell( - f"content insert --uri {shlex.quote(toggle_uri)} --bind enabled:b:false" - ) - await asyncio.sleep(0.3) - await device.shell( - f"content insert --uri {shlex.quote(toggle_uri)} --bind enabled:b:true" - ) - new_token = await portal._fetch_auth_token() - if new_token: - portal._auth_token = new_token - except Exception as exc: - logger.debug("TCP server restart failed: %s", exc) - if self._portal_keyboard_available: - try: - await setup_keyboard(device) - except Exception as exc: - logger.debug("Portal keyboard restore failed: %s", exc) - await asyncio.sleep(1.5) - - async def _swipe_humanized( - self, x1: int, y1: int, x2: int, y2: int, duration_ms: float = 1000 - ) -> None: - from mobilerun_core_local.driver.stealth import generate_curved_path - - await self._ensure_connected() - device = self._adb_device - if device is None: - raise RuntimeError("Android device is not connected") - points = generate_curved_path(x1, y1, x2, y2) - x, y = points[0] - await device.shell(f"input motionevent DOWN {x} {y}") - for x, y in points[1:]: - await asyncio.sleep(duration_ms / 1000 / len(points)) - await device.shell(f"input motionevent MOVE {x} {y}") - x, y = points[-1] - await device.shell(f"input motionevent UP {x} {y}") - - def __init__( - self, - serial: str | None = None, - *, - avd: str | None = None, - headless: bool = False, - timeout: float = 300, - keep: bool = False, - state_provider: StateProvider | None = None, - state_provider_factory: StateProviderFactory | None = None, - state_options: StateProviderOptions | None = None, - operator: Operator | None = None, - **kwargs: Any, - ) -> None: - if serial is not None and avd is not None: - raise ValueError("Pass a serial or avd, not both") - if "credentials" in kwargs: - raise TypeError("Use await provider.bind(device), not credentials=...") - self._avd = avd - self._headless = headless - self._boot_timeout = timeout - self._keep = keep - self._started_emulator = False - self._pending_avd = avd is not None - self._emulator_lock = asyncio.Lock() - self._serial = serial - self._driver = AndroidDriver(serial, **kwargs) - super().__init__( - state_provider=state_provider, - operator=operator, - state_options=state_options, - state_provider_factory=state_provider_factory, - ) - - async def close(self) -> None: - async with self._closing_extensions(), self._emulator_lock: - if self._adb_device: - from mobilerun_core_local.driver.android.portal import ( - PORTAL_PACKAGE_NAME, - portal_ime_id, - ) - - try: - await self._adb_device.shell( - f"ime disable {shlex.quote(portal_ime_id(PORTAL_PACKAGE_NAME))}" - ) - except Exception: - pass - if self._started_emulator and not self._keep: - await self.terminate() - - async def _ensure_connected(self) -> None: - if self._pending_avd: - raise RuntimeError( - "Await AndroidDevice(avd=...) or use async with before using it" - ) - await super()._ensure_connected() - - @_backend_operation - async def _input_text_raw( - self, text: str, clear: bool = False, stealth: bool = False, wpm: int = 0 - ) -> bool: - # ADB's typed backend only accepts text/clear; humanization is a wrapper. - return await self._driver.input_text(text, clear) - - async def install_apk( - self, path: str | Path, **kwargs: Unpack[InstallOptions] - ) -> App: - path = Path(path) - package, code, version, name = await asyncio.to_thread(inspect_apk, path) - return await self.install_app( - App(package, version, name, version_code=code, path=path), **kwargs - ) - - @_backend_operation - async def install_app(self, app: App, **kwargs: Unpack[InstallOptions]) -> App: - if app.path is None: - raise ValueError("This app has no local APK; use install_apk with a path") - await self._io_driver.install_app(str(app.path), **kwargs) - device = self._adb_device - if device is None: - raise RuntimeError("Android device is not connected") - result = await device.shell( - f"pm path {shlex.quote(app.package)}", encoding="utf-8" - ) - if not isinstance(result, str): - raise RuntimeError("ADB returned a non-text package list") - if not any(line.startswith("package:") for line in result.splitlines()): - raise RuntimeError(f"App {app.package} is not installed after adb install") - return app - - async def start_app(self, package: str, activity: str | None = None) -> str: - return await super().start_app(package, activity) - - async def stop_app(self, package: str) -> str: - return await super().stop_app(package) - - async def uninstall_app(self, package: str) -> str: - return await super().uninstall_app(package) - - @property - def _proxy_target(self) -> AndroidProxyTarget: - return AndroidProxyTarget( - self._set_http_proxy, self._proxy_status, self._disconnect_proxy - ) - - async def _set_http_proxy(self, host: str, port: int) -> ProxyStatus: - address = LocalProxy(host, port) - await self._ensure_connected() - device = self._adb_device - if device is None: - raise RuntimeError("Android device is not connected") - await device.shell( - f"settings put global http_proxy {shlex.quote(str(address))}" - ) - return await self._proxy_status() - - async def _proxy_status(self) -> ProxyStatus: - await self._ensure_connected() - device = self._adb_device - if device is None: - raise RuntimeError("Android device is not connected") - result = await device.shell("settings get global http_proxy", encoding="utf-8") - if not isinstance(result, str): - raise RuntimeError("ADB returned a non-text proxy setting") - address = result.strip() - connected = address not in ("", "null", ":0", "0.0.0.0:0") - return ProxyStatus(connected, address if connected else None) - - async def _disconnect_proxy(self) -> None: - await self._ensure_connected() - device = self._adb_device - if device is None: - raise RuntimeError("Android device is not connected") - await device.shell("settings put global http_proxy :0") - - async def connect(self) -> None: - async with self._emulator_lock: - if self._extension_state.closing: - raise RuntimeError("Android device is closed") - if self._pending_avd: - await self._boot() - try: - await self._ensure_connected() - except BaseException as exc: - if self._started_emulator and not self._keep: - try: - await self.terminate() - except Exception as cleanup_error: - exc.add_note( - f"Could not stop started emulator: {cleanup_error}" - ) - raise - - async def _boot(self) -> None: - """Reuse or start an AVD; only a newly started emulator is owned.""" - name = ( - self._avd - if self._avd is not None - else get_settings().MOBILERUN_ANDROID_DEVICE_TYPE - ) - if not name: - available = await emulator.list_avds() - raise ValueError( - f"Set MOBILERUN_ANDROID_DEVICE_TYPE or pass device_type; available AVDs: {', '.join(available) or 'none'}" - ) - serial = await emulator.find_running(name) - started = serial is None - if started: - available = await emulator.list_avds() - if name not in available: - raise ValueError( - f"Unknown AVD {name!r}; available AVDs: {', '.join(available) or 'none'}" - ) - serial = await emulator.start_avd(name, headless=self._headless) - try: - await emulator.wait_boot(serial, timeout=self._boot_timeout) - except BaseException as exc: - if started: - try: - await emulator.stop(serial) - except Exception as cleanup_error: - exc.add_note( - f"Could not stop started emulator {serial}: {cleanup_error}" - ) - raise - self._serial = serial - self._started_emulator = started - self._pending_avd = False - - async def terminate(self) -> None: - """Stop only an emulator started by this instance.""" - if not self._started_emulator: - raise ValueError( - "Cannot terminate an emulator not started by this device or a physical device" - ) - serial = self._serial - if serial is None: - raise RuntimeError("Started emulator has no serial") - await emulator.stop(serial) - self._started_emulator = False - - def _create_state_provider( - self, - options: StateProviderOptions | None = None, - *, - device: Device | None = None, - ) -> StateProvider: - return android_state_provider(device or self, options or StateProviderOptions()) diff --git a/mobilerun/core/devices/base.py b/mobilerun/core/devices/base.py deleted file mode 100644 index 419b238a5..000000000 --- a/mobilerun/core/devices/base.py +++ /dev/null @@ -1,669 +0,0 @@ -"""Common functionality for framework device implementations.""" - -from __future__ import annotations - -import asyncio -from collections.abc import ( - AsyncIterator, - Awaitable, - Callable, - Generator, - Iterable, - Mapping, -) -from contextlib import asynccontextmanager -from pathlib import Path -from types import TracebackType -from typing import ( - TYPE_CHECKING, - Any, - Self, - SupportsIndex, - TypedDict, - TypeVar, - Unpack, - cast, -) - -from pydantic import BaseModel - -from mobilerun.core.devices.components.input_lock import ( - InputOperationLock, - serialize_inputs, -) -from mobilerun.core.extensions import Action, ActionSet, Extension -from mobilerun.core.extensions.actions import Audience, BillingRetry, Declaration -from mobilerun.core.extensions.base import _ExtensionAccess, _redact_bound_arguments -from mobilerun.core.extensions.registry import ExtensionView, Registry -from mobilerun.core.operator import Operator -from mobilerun.core.proxy.target import ProxyTarget -from mobilerun.core.runs import recording_scope -from mobilerun.core.state.base import StateProvider -from mobilerun.core.state.options import StateProviderFactory, StateProviderOptions -from mobilerun.core.state.view import UIStateView -from mobilerun.errors import ( - DeviceOperationNotSupported, - ExpectationFailed, - ExpectationInconclusive, - NoFocusedInput, -) -from mobilerun.models.apps import App -from mobilerun.models.context import ContextItem, JSONValue -from mobilerun.models.files import DeviceFile -from mobilerun.models.location import Location -from mobilerun.models.results import ( - ExecutionResult, - ExpectationResult, - ExpectationVerdict, -) -from mobilerun.utils.prompts import PromptLoader, load_prompt_text -from mobilerun.utils.redaction import _redact_secrets, secret_scope - -T = TypeVar("T", bound=BaseModel) - - -class InstallOptions(TypedDict, total=False): - timeout: float - reinstall: bool - grant_permissions: bool - - -if TYPE_CHECKING: - from mobilerun.clients.cloud.client import AsyncMobilerun - from mobilerun.core.devices.recording import RecordingDevice - from mobilerun.core.mailbox.base import Mailbox - from mobilerun.core.phone_number.base import PhoneNumber - - -def _unwrap_device(device: Device) -> Device: - """Find the innermost framework device, not its underlying driver.""" - return device._unwrap() - - -class _UnrecordedActions(ActionSet): - """Preserve the invoking facade's veto for calls bound to sibling facades.""" - - async def call( - self, - name: str, - arguments: Mapping[str, JSONValue], - *, - audience: Audience = "python", - timeout: float | None = None, - billing_retry: BillingRetry | None = None, - ) -> object: - with recording_scope(enabled=False): - return await super().call( - name, - arguments, - audience=audience, - timeout=timeout, - billing_retry=billing_retry, - ) - - -@serialize_inputs -class Device: - """Shared UI-state access for framework devices.""" - - def __init_subclass__(cls, **kwargs: Any) -> None: - super().__init_subclass__(**kwargs) - serialize_inputs(cls) - - def _number_cloud_client(self) -> AsyncMobilerun | None: - """Cloud client for device-scoped resource operations, when available.""" - return None - - @property - def _extension_state(self) -> Registry: - return self._unwrap().__dict__["_extensions"] - - @property - def extensions(self) -> Mapping[str, Extension]: - return ExtensionView(self._extension_state, self) - - def __getattr__(self, name: str) -> Extension: - root = self._unwrap() - registry = root.__dict__.get("_extensions") - if registry is not None and name in registry.view: - return self._extension_access(registry.view[name]) - if name == "proxy" and self.cloud_id is not None: - raise AttributeError( - "Cloud phone has no active proxy; await proxy.bind(phone) to configure one without automatic provisioning" - ) - raise AttributeError( - f"{type(self).__name__} has no extension or attribute '{name}'" - ) - - def __copy__(self) -> Self: - raise TypeError( - "Devices cannot be copied or pickled; retain the original handle" - ) - - def __deepcopy__(self, memo: dict[int, Any]) -> Self: - raise TypeError( - "Devices cannot be copied or pickled; retain the original handle" - ) - - def __reduce_ex__(self, protocol: SupportsIndex) -> Any: - raise TypeError( - "Devices cannot be copied or pickled; retain the original handle" - ) - - async def unbind_extension(self, name: str) -> None: - extension = self.extensions.get(name) - if extension is None: - raise LookupError(f"No extension named '{name}'") - await extension.unbind() - - @property - def actions(self) -> ActionSet: - catalog = ActionSet if self.recording_allowed() else _UnrecordedActions - return catalog(self, facade=self) - - def _extension_access(self, extension: Extension) -> Extension: - bound = extension._binding - if bound is not None and ( - self.recording_device() is not bound.facade.recording_device() - or self.recording_allowed() != bound.facade.recording_allowed() - ): - return cast(Extension, _ExtensionAccess(extension, self)) - return extension - - def _action_entries(self) -> tuple[Action, ...]: - operations = { - "tap": self.tap, - "swipe": self.swipe, - "drag": self.drag, - "input_text": self.input_text, - "press_button": self.press_button, - "press_key_code": self.press_key_code, - "start_app": self.start_app, - "stop_app": self.stop_app, - "open_url": self.open_url, - "wait": self.wait, - } - entries = [ - Action.compile( - "device", - name, - method, - Declaration(), - description=f"Device {name.replace('_', ' ')}", - ) - for name, method in operations.items() - if name in self.supported_operations or name == "wait" - ] - for extension in self.extensions.values(): - entries.extend(extension._action_entries()) - return tuple(entries) - - def known_codes_redactor(self) -> Callable[[str], str]: - """Return a live text redactor for verification codes learned by this device.""" - return self._extension_state.known_codes.redact - - def register_sensitive_values(self, values: Iterable[str]) -> None: - """Mask exact dispatched values for this device session without storing them on disk.""" - self._extension_state.known_codes.remember_sensitive(values) - - async def context(self) -> tuple[ContextItem, ...]: - items = [] - with recording_scope(enabled=self.recording_allowed()): - for extension in tuple(self.extensions.values()): - items.extend(await extension.context()) - return tuple(items) - - @property - def cloud_id(self) -> str | None: - return None - - async def _close_extensions(self) -> None: - registry = self._extension_state - async with registry.lock: - registry.closing = True - bindings = tuple(registry.bindings.values()) - errors = [] - for binding in reversed(bindings): - try: - if binding.owned: - await binding.extension.close() - else: - await binding.extension.unbind() - except Exception as exc: - errors.append(exc) - if errors: - raise ExceptionGroup("Could not close extensions", errors) - - @asynccontextmanager - async def _closing_extensions(self) -> AsyncIterator[None]: - error = None - try: - await self._close_extensions() - except BaseException as exc: - error = exc - try: - yield - finally: - if error is not None: - raise error - - # File operations default to unsupported on backends without file access. - async def push_file(self, path: str | Path, dest: str | None = None) -> DeviceFile: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support push_file" - ) - - async def list_files(self, directory: str) -> list[DeviceFile]: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support list_files" - ) - - async def pull_file(self, remote_path: str, local_path: str | Path) -> Path: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support pull_file" - ) - - async def delete_file(self, remote_path: str) -> None: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support delete_file" - ) - - # Device environment controls; unsupported backends fail explicitly. - async def get_location(self) -> Location | None: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support get_location" - ) - - async def set_location(self, latitude: float, longitude: float) -> None: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support set_location" - ) - - async def reset_location(self) -> None: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support reset_location" - ) - - async def set_timezone(self, timezone: str) -> None: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support set_timezone" - ) - - async def get_timezone(self) -> str | None: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support get_timezone" - ) - - async def get_language(self) -> str: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support get_language" - ) - - async def open_url(self, url: str) -> None: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support open_url" - ) - - async def set_language(self, locale: str) -> None: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support set_language" - ) - - async def set_clipboard(self, text: str) -> None: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support set_clipboard" - ) - - async def get_clipboard(self) -> str: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support get_clipboard" - ) - - @property - def _is_cloud(self) -> bool: - return False - - @property - def identifier(self) -> str | None: - """Stable log metadata; never a repr containing connection secrets.""" - return None - - async def install_apk( - self, path: str | Path, **kwargs: Unpack[InstallOptions] - ) -> App: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support install_apk" - ) - - async def install_app(self, app: App, **kwargs: Unpack[InstallOptions]) -> App: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support install_app" - ) - - @property - def _proxy_target(self) -> ProxyTarget: - return ProxyTarget() - - async def _swipe_humanized( - self, x1: int, y1: int, x2: int, y2: int, duration_ms: float = 1000 - ) -> None: - await self.swipe(x1, y1, x2, y2, duration_ms) - - def _unwrap(self) -> Device: - return self - - def recording_device(self) -> RecordingDevice[Any] | None: - """Find a recording wrapper in this facade's chain, if present.""" - return None - - def recording_allowed(self) -> bool: - """Whether this facade permits recording, independently of task policy.""" - return True - - @property - def _state_recovery(self) -> Callable[[], Awaitable[None]] | None: - return None - - async def _input_coordinate_size( - self, screenshot_width: int, screenshot_height: int - ) -> tuple[int, int]: - return screenshot_width, screenshot_height - - def __await__(self) -> Generator[Any, None, Self]: - async def ready() -> Self: - await self.connect() - return self - - return ready().__await__() - - async def close(self) -> None: - """Release resources owned by this device, if any.""" - await self._close_extensions() - - async def __aenter__(self) -> Self: - await self.connect() - return self - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc: BaseException | None, - tb: TracebackType | None, - ) -> None: - await self.close() - - def __init__( - self, - *args: Any, - state_provider: StateProvider | None = None, - state_provider_factory: StateProviderFactory | None = None, - state_options: StateProviderOptions | None = None, - operator: Operator | None = None, - **kwargs: Any, - ) -> None: - if "credentials" in kwargs: - raise TypeError("Use await provider.bind(device), not credentials=...") - super().__init__(*args, **kwargs) - self._extensions = Registry() - self._input_operations = InputOperationLock() - self._operator: Operator | None = operator - if operator is not None: - operator.check(self) - if state_provider is not None and state_provider_factory is not None: - raise TypeError("Pass state_provider or state_provider_factory, not both") - self._state_provider_factory = state_provider_factory - self._default_provider_options = state_options or StateProviderOptions() - self._ui_state_view = UIStateView(self, self._build_default_state_provider) - self._state_provider_override: StateProvider | None = None - if state_provider is not None: - self._set_state_provider(state_provider) - - def _set_state_provider(self, state_provider: StateProvider | None) -> None: - """Attach a provider; passing None restores the lazy built-in default.""" - self._state_provider_override = state_provider - self._ui_state_view._attach(state_provider) - - def _set_state_provider_factory( - self, factory: Callable[[Device], StateProvider] - ) -> None: - self._ui_state_view._attach_factory(factory) - - async def input_text( - self, text: str, clear: bool = False, stealth: bool = False, wpm: int = 0 - ) -> bool: - return await self._input_text_raw(text, clear, stealth, wpm) - - async def _input_text_raw( - self, text: str, clear: bool = False, stealth: bool = False, wpm: int = 0 - ) -> bool: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support input_text" - ) - - async def _input_secret(self, value: str) -> bool: - with secret_scope(value): - _redact_bound_arguments(self) - try: - state = await self.state.refresh() - phone_state = state.phone_state - if ( - not isinstance(phone_state, dict) - or "focusedElement" not in phone_state - or not isinstance(phone_state.get("isEditable"), bool) - ): - raise DeviceOperationNotSupported( - "Secret input requires a state provider that reports focused editable fields" - ) - focused = phone_state["focusedElement"] - focused_editable = ( - isinstance(focused, dict) - and bool(focused) - and phone_state["isEditable"] is True - ) - if not focused_editable and not ( - phone_state.get("keyboardVisible") is True - and getattr(state, "_has_single_focused_app_node", False) is True - ): - raise NoFocusedInput( - "No text field is focused; tap the field before typing a credential" - ) - self._extension_state.sensitive_ui = True - if value: - self._extension_state.known_codes.observed_secrets.add(value) - return await self._input_text_raw(value) - except Exception as exc: - message = _redact_secrets(str(exc)) - try: - sanitized = type(exc)(message) - except Exception: - sanitized = RuntimeError(message) - raise sanitized from None - - async def wait(self, seconds: float) -> None: - """Pause; unlike a plain sleep, wrappers can record this operation.""" - await asyncio.sleep(seconds) - - @property - def number(self) -> PhoneNumber: - return cast("PhoneNumber", self._resource_lookup("sms", "phone_number")) - - @property - def mailbox(self) -> Mailbox: - return cast("Mailbox", self._resource_lookup("email", "mailbox")) - - def _resource_lookup(self, name: str, role: str) -> Extension: - default = self.extensions.get(name) - if default is not None and default.role == role: - return default - matches = [item for item in self.extensions.values() if item.role == role] - if len(matches) == 1: - return matches[0] - if not matches: - raise DeviceOperationNotSupported(f"No {name} extension is bound") - raise DeviceOperationNotSupported( - f"Multiple {name} extensions are bound; select one by name" - ) - - def _default_operator(self) -> Operator | None: - return None - - async def do( - self, - instruction: str, - *, - output: type[T] | None = None, - max_steps: int | None = None, - operator: Operator | None = None, - timeout: float | None = None, - ) -> ExecutionResult[T]: - selected = operator if operator is not None else self._operator - if selected is None: - selected = self._default_operator() - if selected is None: - selected = Operator() - selected.check(self) - kwargs: dict[str, Any] = {"output": output, "max_steps": max_steps} - if timeout is not None: - kwargs["timeout"] = timeout - return await selected.execute(self, instruction, **kwargs) - - async def expect( - self, - condition: str, - *, - operator: Operator | None = None, - timeout: float | None = None, - ) -> ExpectationResult: - kwargs: dict[str, Any] = {} - if operator is not None: - operator.check(self) - kwargs["operator"] = operator - if timeout is not None: - kwargs["timeout"] = timeout - instruction = PromptLoader.render_template( - load_prompt_text("devices/expect.jinja2"), {"condition": condition} - ) - task = await self.do(instruction, output=ExpectationVerdict, **kwargs) - if not task.success or task.output is None: - raise ExpectationInconclusive(condition, task) - result = ExpectationResult( - passed=task.output.passed, - condition=condition, - reason=task.output.reason, - task=task, - ) - if not result.passed: - raise ExpectationFailed(result) - return result - - def _create_state_provider( - self, - options: StateProviderOptions | None = None, - *, - device: Device | None = None, - ) -> StateProvider: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support _create_state_provider" - ) - - def _build_default_state_provider(self) -> StateProvider: - if self._state_provider_factory is not None: - return self._state_provider_factory(self, self._default_provider_options) - return self._create_state_provider(self._default_provider_options) - - def _reset_state_provider( - self, options: StateProviderOptions | None = None - ) -> None: - """Set options for a fresh lazy default provider, replacing any override.""" - self._default_provider_options = options or StateProviderOptions() - self._ui_state_view._reset_default() - - @property - def state(self) -> UIStateView: - return self._ui_state_view - - async def tap_element(self, index: int) -> None: - self.state._require("element_index") - x, y = self.state.current.get_element_coords(index) - return await self.tap(x, y) - - # Concrete backends implement the raw I/O surface. - @property - def platform(self) -> str: - return "" - - @property - def supported_operations(self) -> set[str]: - return set() - - @property - def supported_buttons(self) -> set[str]: - return set() - - async def connect(self) -> None: - await self._ensure_connected() - - async def _ensure_connected(self) -> None: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support _ensure_connected" - ) - - async def screenshot(self, hide_overlay: bool = True) -> bytes: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support screenshot" - ) - - async def tap(self, x: int, y: int) -> None: - raise DeviceOperationNotSupported(f"{type(self).__name__} doesn't support tap") - - async def swipe( - self, x1: int, y1: int, x2: int, y2: int, duration_ms: float = 1000 - ) -> None: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support swipe" - ) - - async def start_app(self, package: str, activity: str | None = None) -> str: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support start_app" - ) - - async def stop_app(self, package: str) -> str: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support stop_app" - ) - - async def uninstall_app(self, package: str) -> str: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support uninstall_app" - ) - - async def list_apps(self, include_system: bool = False) -> list[dict[str, str]]: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support list_apps" - ) - - async def press_button(self, button: str) -> None: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support press_button" - ) - - async def press_key_code(self, key_code: int) -> None: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support press_key_code" - ) - - async def drag( - self, x1: int, y1: int, x2: int, y2: int, duration: float = 3.0 - ) -> None: - raise DeviceOperationNotSupported(f"{type(self).__name__} doesn't support drag") - - async def _get_ui_tree(self) -> dict[str, Any]: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support _get_ui_tree" - ) - - async def _get_date(self) -> str: - raise DeviceOperationNotSupported( - f"{type(self).__name__} doesn't support _get_date" - ) diff --git a/mobilerun/core/devices/cloud.py b/mobilerun/core/devices/cloud.py deleted file mode 100644 index a2c650aa7..000000000 --- a/mobilerun/core/devices/cloud.py +++ /dev/null @@ -1,407 +0,0 @@ -"""Cloud device driver facade; lifecycle, apps and operator live alongside it.""" - -import asyncio -from collections.abc import Awaitable, Callable -from pathlib import Path -from typing import Any, TypeVar, cast - -from mobilerun_core_local.driver.cloud import CloudDriver - -from mobilerun.clients.cloud import proxies -from mobilerun.clients.cloud.client import _device_request -from mobilerun.clients.cloud.proxies import ProxyConnectParams -from mobilerun.clients.local.login_store import resolve_cloud_api_key -from mobilerun.config.settings import get_settings -from mobilerun.core.devices.base import Device -from mobilerun.core.devices.components import environment -from mobilerun.core.devices.components import files as device_files -from mobilerun.core.devices.components.cloud_apps import _CloudApps -from mobilerun.core.devices.components.cloud_lifecycle import _create_params -from mobilerun.core.devices.components.raw import _BackendIO -from mobilerun.core.operator.cloud import CloudTaskOperator -from mobilerun.core.proxy import CloudRotatingProxy, ProxyStatus -from mobilerun.core.proxy.base import CloudProxy -from mobilerun.core.proxy.target import CloudProxyTarget -from mobilerun.core.state.base import StateProvider -from mobilerun.core.state.options import ( - StateProviderFactory, - StateProviderOptions, - android_state_provider, -) -from mobilerun.errors import CloudAuthRequired, ExtensionConflict, ProxyNotActive -from mobilerun.errors.cloud import CloudAPIError -from mobilerun.errors.device import DeviceOperationNotSupported -from mobilerun.models.billing import Billing, Plan -from mobilerun.models.files import DeviceFile -from mobilerun.models.location import Location - -_UNSET = object() -_DEFAULT_PROXY = cast(CloudProxy, _UNSET) -T = TypeVar("T") - - -class CloudDevice(_CloudApps, _BackendIO, Device): - """Cloud device backed by the cloud driver.""" - - # Cloud device file operations. - async def push_file(self, path: str | Path, dest: str | None = None) -> DeviceFile: - return await device_files.cloud_push_file(self, path, dest) - - async def list_files(self, directory: str) -> list[DeviceFile]: - return await device_files.cloud_list_files(self, directory) - - async def pull_file(self, remote_path: str, local_path: str | Path) -> Path: - return await device_files.cloud_pull_file(self, remote_path, local_path) - - async def delete_file(self, remote_path: str) -> None: - await device_files.cloud_delete_file(self, remote_path) - - # Cloud environment controls. - async def get_location(self) -> Location | None: - return await environment.cloud_get_location(self) - - async def set_location(self, latitude: float, longitude: float) -> None: - await environment.cloud_set_location(self, latitude, longitude) - - async def reset_location(self) -> None: - await environment.cloud_reset_location(self) - - async def set_language(self, locale: str) -> None: - await environment.cloud_set_language(self, locale) - - async def get_language(self) -> str: - return await environment.cloud_get_language(self) - - async def get_timezone(self) -> str | None: - return await environment.cloud_get_timezone(self) - - async def set_timezone(self, timezone: str) -> None: - await environment.cloud_set_timezone(self, timezone) - - async def set_clipboard(self, text: str) -> None: - await environment.cloud_set_clipboard(self, text) - - async def get_clipboard(self) -> str: - return await environment.cloud_get_clipboard(self) - - async def open_url(self, url: str) -> None: - await environment.cloud_open_url(self, url) - - _backend = CloudDriver - - @property - def platform(self) -> str: - return self._driver.platform - - @property - def supported_operations(self) -> set[str]: - return ( - self._driver.supported - | {"stop_app", "open_url"} - | ({"proxy_switch"} if self._cloud_proxy is not False else set()) - | ({"cloud_telephony"} if self._cloud_telephony else set()) - ) - - @property - def cloud_id(self) -> str | None: - return self.device_id - - @property - def supported_buttons(self) -> set[str]: - return self._driver.supported_buttons - - @property - def _io_driver(self) -> CloudDriver: - # Raw I/O sees only an initialized id and the current clients (also when - # tests or embedding applications replace a client). - self._driver.device_id = self._require_device_id() - self._driver._client = self._client - self._driver._write_client = self._write_client - return self._driver - - @property - def _is_cloud(self) -> bool: - return True - - @property - def identifier(self) -> str | None: - return self.device_id - - def __init__( - self, - device_id: str | None = None, - api_key: str | None = None, - base_url: str | None = None, - *args: Any, - state_provider: StateProvider | None = None, - state_provider_factory: StateProviderFactory | None = None, - state_options: StateProviderOptions | None = None, - device_type: str | None = None, - keep: bool = False, - billing: Billing | str | None = None, - plan: Plan | str | None = None, - name: Any = _UNSET, - country: Any = _UNSET, - locale: Any = _UNSET, - timezone: Any = _UNSET, - android_version: Any = _UNSET, - apps: Any = _UNSET, - template: Any = _UNSET, - proxy: CloudProxy = _DEFAULT_PROXY, - **kwargs: Any, - ) -> None: - if "number" in kwargs: - raise TypeError("Use await number.bind(phone), not CloudDevice(number=...)") - if "credentials" in kwargs: - raise TypeError("Use await provider.bind(phone), not credentials=...") - driver_names = {"operator", "display_id", "user_id", "owner_id", "stealth"} - unknown = kwargs.keys() - driver_names - if unknown: - raise TypeError( - f"unexpected CloudDevice keyword argument(s): {', '.join(sorted(unknown))}" - ) - creation = { - key: value - for key, value in { - "name": name, - "country": country, - "locale": locale, - "timezone": timezone, - "android_version": android_version, - "apps": apps, - "template": template, - "proxy": proxy, - }.items() - if value is not _UNSET - } - if device_id is not None and ( - creation or device_type is not None or plan is not None - ): - raise TypeError("Creation options are only used when creating a phone") - api_key = resolve_cloud_api_key() if api_key is None else api_key - if not api_key: - raise CloudAuthRequired(code="credentials_required") - base_url = ( - get_settings().MOBILERUN_CLOUD_BASE_URL if base_url is None else base_url - ) - if device_id is None and "proxy" not in creation: - creation["proxy"] = CloudRotatingProxy._from_settings() - self._create_options = _create_params(creation) if device_id is None else {} - self._name = None - self._device_type = None - if device_type is not None: - if device_type not in ("android_cloud_phone", "ios_phone", "device_slot"): - raise ValueError(f"Invalid cloud device type: {device_type}") - self._device_type = device_type - self._keep = keep - self._owned = False - self._billing = Billing( - get_settings().MOBILERUN_BILLING if billing is None else billing - ) - self._plan = plan - self._ready = device_id is not None - self._number_loaded = False - self._cloud_telephony = False - self._cloud_proxy = None - self._task_started_callback: Callable[[str], None] | None = None - self._connect_lock = asyncio.Lock() - operator = kwargs.pop("operator", None) - self.device_id = device_id - self._driver = CloudDriver( - device_id or "", - *args, - api_key=api_key, - base_url=base_url, - **kwargs, - ) - self._client = self._driver._client - self._write_client = self._driver._write_client - self._driver._call = self._call - super().__init__( - state_provider=state_provider, - operator=operator, - state_options=state_options, - state_provider_factory=state_provider_factory, - ) - self._creation_proxy: CloudProxy | None = ( - creation["proxy"] if device_id is None else None - ) - self._creation_proxy_published = False - self._remote_proxy_loaded = False - self._owned_client = self._client - - async def connect(self) -> None: - proxy = self._creation_proxy - if proxy is None or self._creation_proxy_published: - await super().connect() - if proxy is None and self._cloud_proxy is not False: - from mobilerun.core.proxy.adoption import _adopt_remote_proxy - - async with self._extension_state.lock: - bindings = tuple( - binding - for binding in self._extension_state.bindings.values() - if binding.extension.exclusive == "proxy" - ) - uncertain = any(binding.uncertain for binding in bindings) - if not self._remote_proxy_loaded or uncertain: - if not bindings or uncertain: - try: - await _adopt_remote_proxy(self) - except DeviceOperationNotSupported: - if self._cloud_proxy is not None: - raise - self._cloud_proxy = False - return - self._remote_proxy_loaded = True - return - from mobilerun.core.extensions.registry import Binding - - async with proxy._lifecycle_lock: - async with self._extension_state.lock: - if self._creation_proxy_published: - await super().connect() - return - if proxy._binding is not None or proxy._closed: - raise ExtensionConflict("Creation proxy is already bound or closed") - if self._extension_state.closing: - raise ExtensionConflict("Cloud phone is closing") - proxy._check_name(self) - proxy._action_entries() - await super().connect() - # Creation applied the exact supplied proxy. Do not issue a - # second provisioning or switching request. - await proxy.check_bind(self) - binding = Binding(proxy, self, False) - self._extension_state.bindings[proxy.name] = binding - proxy._binding = binding - self._creation_proxy_published = True - - @property - def name(self) -> str | None: - """Server display name from the last info/create/rename response, or None.""" - return self._name - - async def _call(self, coro: Awaitable[T]) -> T: - return await _device_request(coro) - - def _create_state_provider( - self, - options: StateProviderOptions | None = None, - *, - device: Device | None = None, - ) -> StateProvider: - return android_state_provider(device or self, options or StateProviderOptions()) - - def _default_operator(self) -> CloudTaskOperator: - return CloudTaskOperator(billing=self._billing) - - @property - def _proxy_target(self) -> CloudProxyTarget: - return CloudProxyTarget( - self._connect_proxy, - self._proxy_status, - self._disconnect_proxy, - resolve_reference=self._resolve_proxy_reference, - ) - - async def _resolve_proxy_reference(self, reference: str) -> str | None: - try: - resolved = await proxies.get_proxy( - reference, - billing=self._billing, - api_key=self._client.api_key, - base_url=str(self._client.base_url), - ) - except CloudAPIError: - # Status is authoritative about connection, even when this account - # cannot resolve the reference to reusable Connect credentials. - return None - return resolved.id - - async def _proxy_status(self) -> ProxyStatus: - await self._ensure_connected() - response = await proxies.device_status( - self._require_device_id(), - billing=self._billing, - api_key=self._client.api_key, - base_url=str(self._client.base_url), - ) - return ProxyStatus(response.connected, response.name, response.protocol) - - async def _connect_proxy(self, params: ProxyConnectParams) -> ProxyStatus: - await self._ensure_connected() - await proxies.connect_device( - self._require_device_id(), - params, - billing=self._billing, - api_key=self._client.api_key, - base_url=str(self._client.base_url), - ) - info = await self.info() - if info.state != "ready": - await self.wait_ready() - status = await self._proxy_status() - if not status.connected: - raise ProxyNotActive("The cloud phone has no active proxy after switching") - return status - - async def _disconnect_proxy(self) -> None: - await self._ensure_connected() - await proxies.disconnect_device( - self._require_device_id(), - billing=self._billing, - api_key=self._client.api_key, - base_url=str(self._client.base_url), - ) - - async def tap(self, x: int, y: int) -> None: - await self._ensure_connected() - return await super().tap(x, y) - - async def swipe( - self, x1: int, y1: int, x2: int, y2: int, duration_ms: float = 1000 - ) -> None: - await self._ensure_connected() - return await super().swipe(x1, y1, x2, y2, duration_ms) - - async def _input_text_raw( - self, text: str, clear: bool = False, stealth: bool = False, wpm: int = 0 - ) -> bool: - await self._ensure_connected() - return await super()._input_text_raw(text, clear, stealth, wpm) - - async def press_button(self, button: str) -> None: - await self._ensure_connected() - return await super().press_button(button) - - async def start_app(self, package: str, activity: str | None = None) -> str: - await self._ensure_connected() - return await super().start_app(package, activity) - - async def stop_app(self, package: str) -> str: - await self._ensure_connected() - await _device_request( - self._write_client.devices.apps.stop( - package, - device_id=self._require_device_id(), - x_device_display_id=self._driver.display_id, - ) - ) - return f"Stopped {package}" - - async def list_apps(self, include_system: bool = False) -> list[dict[str, Any]]: - await self._ensure_connected() - return await super().list_apps(include_system) - - async def screenshot(self, hide_overlay: bool = True) -> bytes: - await self._ensure_connected() - return await super().screenshot(hide_overlay) - - async def _get_ui_tree(self) -> dict[str, Any]: - await self._ensure_connected() - return await super()._get_ui_tree() - - async def _get_date(self) -> str: - await self._ensure_connected() - return await super()._get_date() diff --git a/mobilerun/core/devices/components/README.md b/mobilerun/core/devices/components/README.md deleted file mode 100644 index 0cf9499a6..000000000 --- a/mobilerun/core/devices/components/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# Device components - -Internal cloud app, cloud lifecycle, and shared wrapper implementations. -Public device classes live in the parent package. - -See [devices](../README.md) for public APIs. diff --git a/mobilerun/core/devices/components/__init__.py b/mobilerun/core/devices/components/__init__.py deleted file mode 100644 index b71f90d9d..000000000 --- a/mobilerun/core/devices/components/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""Internal device components.""" diff --git a/mobilerun/core/devices/components/cloud_apps.py b/mobilerun/core/devices/components/cloud_apps.py deleted file mode 100644 index c1489da77..000000000 --- a/mobilerun/core/devices/components/cloud_apps.py +++ /dev/null @@ -1,143 +0,0 @@ -"""Cloud app installation and bounded completion checks.""" - -import asyncio -import logging -from pathlib import Path -from typing import Any, Unpack - -from mobilerun.clients.cloud import apps -from mobilerun.clients.cloud.apps import upload_app -from mobilerun.clients.cloud.client import AsyncMobilerun -from mobilerun.config.settings import get_settings -from mobilerun.core.devices.base import InstallOptions -from mobilerun.core.devices.components.cloud_lifecycle import _CloudLifecycle -from mobilerun.errors import DeviceOperationNotSupported -from mobilerun.models.apps import App -from mobilerun.models.billing import Billing - -logger = logging.getLogger(__name__) - - -class _CloudApps(_CloudLifecycle): - _client: AsyncMobilerun - _billing: Billing - device_id: str | None - - async def install_apk( - self, path: str | Path, **kwargs: Unpack[InstallOptions] - ) -> App: - await self._ensure_connected() - self._install_timeout(dict(kwargs)) - app = await upload_app( - path, - billing=self._billing, - api_key=self._client.api_key, - base_url=str(self._client.base_url), - ) - return await self.install_app(app, **kwargs) - - @staticmethod - def _install_timeout(kwargs: dict[str, Any]) -> float: - timeout = kwargs.pop("timeout", None) - if timeout is None: - timeout = get_settings().MOBILERUN_CLOUD_APP_INSTALL_TIMEOUT_SECONDS - if timeout <= 0: - raise ValueError("Cloud app install timeout must be positive") - if kwargs.pop("reinstall", False): - raise DeviceOperationNotSupported( - "Cloud app installs do not support the reinstall option" - ) - if not kwargs.pop("grant_permissions", True): - raise DeviceOperationNotSupported( - "Cloud app installs do not support changing permission grants" - ) - if kwargs: - raise TypeError(f"Unsupported cloud install options: {', '.join(kwargs)}") - return timeout - - async def install_app(self, app: App, **kwargs: Unpack[InstallOptions]) -> App: - await self._ensure_connected() - timeout = self._install_timeout(dict(kwargs)) - if not app.id: - if app.path is None: - raise ValueError( - "This app has no local APK or cloud id; use install_apk with a path" - ) - app = await upload_app( - app.path, - billing=self._billing, - api_key=self._client.api_key, - base_url=str(self._client.base_url), - ) - params: dict[str, Any] = {"package_name": app.package} - if app.version_code is not None: - params["version_code"] = app.version_code - try: - async with asyncio.timeout(timeout): - previous = await apps.list_installs( - self._client, self._require_device_id(), billing=self._billing - ) - previous_starts = { - item.started_at - for item in (previous.installs or []) - if item.app_id == app.package - } - await apps.install( - self._client, - self._require_device_id(), - background=True, - billing=self._billing, - **params, - ) - while True: - result = await apps.list_installs( - self._client, self._require_device_id(), billing=self._billing - ) - attempts = [ - item - for item in (result.installs or []) - if item.app_id == app.package - and item.started_at not in previous_starts - ] - if attempts: - attempt = max(attempts, key=lambda item: item.started_at) - logger.info("Installing %s: %s", app.package, attempt.status) - if attempt.status == "failed": - raise RuntimeError( - f"App install failed for {app.package}: {attempt.error_class or 'unknown error'}" - ) - if attempt.status == "succeeded": - installed_apps = await self.list_apps(include_system=True) - if any( - item.get("package_name") == app.package - and ( - ( - app.version_code is not None - and item.get("version_code") == app.version_code - ) - or ( - app.version_code is None - and ( - not app.version - or item.get("version_name") == app.version - ) - ) - ) - for item in installed_apps - ): - return app - await asyncio.sleep(0.5) - except TimeoutError as exc: - raise TimeoutError( - f"App install timed out for {app.package} after {timeout}s" - ) from exc - - async def uninstall_app(self, package: str) -> str: - await self._ensure_connected() - await apps.uninstall( - self._client, - package, - billing=self._billing, - device_id=self._require_device_id(), - ) - return f"Uninstalled {package}" diff --git a/mobilerun/core/devices/components/cloud_lifecycle.py b/mobilerun/core/devices/components/cloud_lifecycle.py deleted file mode 100644 index a6a23e9e1..000000000 --- a/mobilerun/core/devices/components/cloud_lifecycle.py +++ /dev/null @@ -1,258 +0,0 @@ -"""Cloud phone creation, resource ownership and lifecycle.""" - -from __future__ import annotations - -import asyncio -import logging -from types import TracebackType -from typing import Any, Literal, Self - -from mobilerun.clients.cloud import devices -from mobilerun.clients.cloud.client import AsyncMobilerun -from mobilerun.config.settings import get_settings -from mobilerun.core.devices.base import Device -from mobilerun.core.phone_number.cloud import CloudPhoneNumber, _BorrowedNumberBinding -from mobilerun.core.proxy import CloudRotatingProxy -from mobilerun.models.billing import Billing, Plan - -logger = logging.getLogger(__name__) - - -def _create_params(params: dict[str, Any]) -> dict[str, Any]: - params = dict(params) - if "country" in params: - params["body_country"] = params.pop("country") - proxy = params.pop("proxy", CloudRotatingProxy._from_settings()) - if proxy is None: - raise ValueError("A proxy is required to create a cloud phone") - params["proxy"] = proxy._parameters() - return params - - -class _CloudLifecycle(Device): - device_id: str | None - _keep: bool - _ready: bool - _owned: bool - _number_loaded: bool - _client: AsyncMobilerun - _owned_client: AsyncMobilerun | None - _billing: Billing - _plan: Plan | str | None - _device_type: Literal["android_cloud_phone", "ios_phone", "device_slot"] | None - _connect_lock: asyncio.Lock - _create_options: dict[str, Any] - _cloud_telephony: bool - _cloud_proxy: bool | None - - @property - def _cloud_client(self) -> AsyncMobilerun: - return self._client - - def _number_cloud_client(self) -> AsyncMobilerun: - return self._client - - def _require_device_id(self) -> str: - if self.device_id is None: - raise RuntimeError("Await CloudDevice(...) before using a new cloud phone") - return self.device_id - - @property - def _keep_policy(self) -> bool: - return self._keep - - async def _ensure_connected(self) -> None: - if not self._ready: - raise RuntimeError( - "Await CloudDevice(...) or use async with before using a new cloud phone" - ) - - async def _load_number(self) -> None: - response = await devices.number( - self._require_device_id(), billing=self._billing, client=self._client - ) - binding = response.binding - if binding: - number = CloudPhoneNumber( - binding.number_id, client=self._client, billing=self._billing - ) - number._device_id = self.device_id - number._phone_number = binding.phone_number - number._binding_loaded = True - async with self._extension_state.lock: - number._check_name(self) - number._action_entries() - adopted = _BorrowedNumberBinding(number, self, False) - self._extension_state.bindings[number.name] = adopted - number._binding = adopted - self._number_loaded = True - - async def connect(self) -> None: - async with self._connect_lock: - if self._ready: - info = await devices.capabilities( - self._require_device_id(), - billing=self._billing, - client=self._client, - ) - self._cloud_telephony = bool(info.capabilities.telephony) - self._cloud_proxy = info.capabilities.proxy - if not self._number_loaded: - if self._cloud_telephony: - await self._load_number() - else: - self._number_loaded = True - return - if self.device_id is None: - device_type = ( - self._device_type - if self._device_type is not None - else get_settings().MOBILERUN_CLOUD_DEVICE_TYPE - ) - if device_type not in ( - "android_cloud_phone", - "ios_phone", - "device_slot", - ): - raise ValueError(f"Invalid cloud device type: {device_type}") - plan_options = {"plan": self._plan} if self._plan is not None else {} - created = await devices.create( - client=self._client, - billing=self._billing, - device_type=device_type, - **plan_options, - **self._create_options, - ) - self.device_id = created.id - self._name = created.name - self._owned = True - logger.info("Created cloud device %s", self.device_id) - try: - await devices.wait_ready( - self.device_id, billing=self._billing, client=self._client - ) - info = await devices.capabilities( - self.device_id, billing=self._billing, client=self._client - ) - self._cloud_telephony = bool(info.capabilities.telephony) - self._cloud_proxy = info.capabilities.proxy - # Newly created phones cannot have a binding: creation has no number option. - self._number_loaded = True - except BaseException: - if self._owned and not self._keep: - await devices.terminate( - self.device_id, billing=self._billing, client=self._client - ) - self._owned = False - self.device_id = None - raise - self._ready = True - - async def _close_resources(self) -> None: - pass - - async def close(self) -> None: - async with self._closing_extensions(): - try: - await self._close_resources() - finally: - try: - async with self._connect_lock: - if self._owned and not self._keep: - await devices.terminate( - self._require_device_id(), - billing=self._billing, - client=self._client, - ) - self._owned = False - finally: - if not self._owned or self._keep: - client = self._owned_client - self._owned_client = None - if client is not None: - await client.close() - - async def __aenter__(self) -> Self: - return await self - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc: BaseException | None, - tb: TracebackType | None, - ) -> None: - await self.close() - - async def info(self) -> Any: - await self._ensure_connected() - info = await devices.retrieve( - self._require_device_id(), billing=self._billing, client=self._client - ) - self._name = info.name - return info - - async def rename(self, name: str) -> Any: - """Set the server display name and refresh the read-only name cache.""" - await self._ensure_connected() - info = await devices.set_name( - self._require_device_id(), name, billing=self._billing, client=self._client - ) - self._name = info.name - return info - - async def resume(self, **params: Any) -> Any: - await self._ensure_connected() - return await devices.resume( - self._require_device_id(), - billing=self._billing, - client=self._client, - **params, - ) - - async def stop(self, **params: Any) -> Any: - await self._ensure_connected() - return await devices.stop( - self._require_device_id(), - billing=self._billing, - client=self._client, - **params, - ) - - async def terminate(self, **params: Any) -> Any: - await self._ensure_connected() - await self._close_resources() - result = await devices.terminate( - self._require_device_id(), - billing=self._billing, - client=self._client, - **params, - ) - self._owned = False - return result - - async def wait_ready(self, **params: Any) -> Any: - await self._ensure_connected() - return await devices.wait_ready( - self._require_device_id(), - billing=self._billing, - client=self._client, - **params, - ) - - async def reboot(self, **params: Any) -> Any: - await self._ensure_connected() - return await devices.reboot( - self._require_device_id(), - billing=self._billing, - client=self._client, - **params, - ) - - async def reset(self, **params: Any) -> Any: - await self._ensure_connected() - return await devices.reset( - self._require_device_id(), - billing=self._billing, - client=self._client, - **params, - ) diff --git a/mobilerun/core/devices/components/environment.py b/mobilerun/core/devices/components/environment.py deleted file mode 100644 index 4a076c94a..000000000 --- a/mobilerun/core/devices/components/environment.py +++ /dev/null @@ -1,152 +0,0 @@ -"""Environment controls for cloud-backed devices.""" - -import asyncio -import re -from typing import TYPE_CHECKING -from zoneinfo import ZoneInfo, ZoneInfoNotFoundError - -from mobilerun.clients.cloud import devices as cloud_devices -from mobilerun.errors import DeviceOperationNotSupported -from mobilerun.models.location import Location - -if TYPE_CHECKING: - from mobilerun.core.devices.android import AndroidDevice - from mobilerun.core.devices.cloud import CloudDevice - - -def validate_timezone(timezone: str) -> None: - try: - ZoneInfo(timezone) - except (ZoneInfoNotFoundError, ValueError) as exc: - raise ValueError(f"Invalid IANA timezone: {timezone}") from exc - - -def validate_locale(locale: str) -> None: - if not re.fullmatch( - r"[A-Za-z]{2,3}(?:-[A-Za-z]{4})?(?:-(?:[A-Za-z]{2}|[0-9]{3}))?", locale - ): - raise ValueError(f"Invalid locale: {locale}") - - -async def cloud_get_location(device: "CloudDevice") -> Location | None: - await device._ensure_connected() - result = await cloud_devices.get_location( - device._require_device_id(), billing=device._billing, client=device._client - ) - return ( - None - if result is None - else Location(latitude=result.latitude, longitude=result.longitude) - ) - - -async def cloud_set_location( - device: "CloudDevice", latitude: float, longitude: float -) -> None: - if not (-90 <= latitude <= 90 and -180 <= longitude <= 180): - raise ValueError("Invalid latitude or longitude") - await device._ensure_connected() - await device._call( - device._write_client.devices.location.set( - device._require_device_id(), latitude=latitude, longitude=longitude - ) - ) - - -async def cloud_reset_location(device: "CloudDevice") -> None: - await device._ensure_connected() - await device._call( - device._write_client.devices.location.reset(device._require_device_id()) - ) - - -async def cloud_set_language(device: "CloudDevice", locale: str) -> None: - validate_locale(locale) - await device._ensure_connected() - await device._call( - device._write_client.devices.language.set( - device._require_device_id(), locale=locale - ) - ) - - -async def cloud_get_language(device: "CloudDevice") -> str: - await device._ensure_connected() - result = await cloud_devices.get_language( - device._require_device_id(), billing=device._billing, client=device._client - ) - return result.locale - - -async def cloud_get_timezone(device: "CloudDevice") -> str | None: - await device._ensure_connected() - result = await cloud_devices.get_timezone( - device._require_device_id(), billing=device._billing, client=device._client - ) - return result.timezone - - -async def cloud_set_timezone(device: "CloudDevice", timezone: str) -> None: - validate_timezone(timezone) - await device._ensure_connected() - await device._call( - device._write_client.devices.timezone.set( - device._require_device_id(), timezone=timezone - ) - ) - - -async def cloud_set_clipboard(device: "CloudDevice", text: str) -> None: - await device._ensure_connected() - await device._call( - device._write_client.devices.clipboard.set( - device._require_device_id(), text=text - ) - ) - - -async def cloud_get_clipboard(device: "CloudDevice") -> str: - await device._ensure_connected() - response = await device._call( - device._client.devices.clipboard.get(device._require_device_id()) - ) - return response.text - - -async def cloud_open_url(device: "CloudDevice", url: str) -> None: - await device._ensure_connected() - await device._call( - device._write_client.devices.deep_link.execute_deep_link( - device._require_device_id(), deep_link=url - ) - ) - - -async def android_shell(device: "AndroidDevice", command: str) -> None: - await device._ensure_connected() - adb = device._adb_device - if adb is None: - raise RuntimeError("Android device is not connected") - result = await adb.shell2(command) - if result.returncode: - raise DeviceOperationNotSupported(f"Android command failed: {result.output}") - - -async def android_set_location( - device: "AndroidDevice", latitude: float, longitude: float -) -> None: - if not (-90 <= latitude <= 90 and -180 <= longitude <= 180): - raise ValueError("Invalid latitude or longitude") - await device._ensure_connected() - adb = device._adb_device - if adb is None: - raise RuntimeError("Android device is not connected") - if not adb.serial.startswith("emulator-"): - raise DeviceOperationNotSupported( - "set_location on a physical Android device needs a mock-location app; supported on emulators and cloud phones" - ) - result = await asyncio.to_thread( - adb.adb_output, "emu", "geo", "fix", str(longitude), str(latitude) - ) - if result is None or "KO" in result: - raise DeviceOperationNotSupported(f"Emulator rejected location: {result}") diff --git a/mobilerun/core/devices/components/files.py b/mobilerun/core/devices/components/files.py deleted file mode 100644 index 77788d6c5..000000000 --- a/mobilerun/core/devices/components/files.py +++ /dev/null @@ -1,133 +0,0 @@ -"""File operations for Android devices.""" - -import mimetypes -import posixpath -import shlex -from pathlib import Path -from typing import TYPE_CHECKING - -from mobilerun.clients.cloud import files as cloud_files -from mobilerun.models.files import DeviceFile - -if TYPE_CHECKING: - from mobilerun.core.devices.android import AndroidDevice - from mobilerun.core.devices.cloud import CloudDevice - - -def destination(path: Path, dest: str | None) -> tuple[str, bool]: - mime = mimetypes.guess_type(path.name)[0] or "" - media = mime.startswith(("image/", "video/")) - return dest or ("/sdcard/DCIM/Camera" if media else "/sdcard/Download"), media - - -async def android_push_file( - device: "AndroidDevice", path: str | Path, dest: str | None = None -) -> DeviceFile: - path = Path(path) - directory, media = destination(path, dest) - remote = posixpath.join(directory, path.name) - await device._ensure_connected() - adb = device._adb_device - if adb is None: - raise RuntimeError("Android device is not connected") - await adb.sync.push(path, remote) - if media: - result = await adb.shell2( - "am broadcast -a android.intent.action.MEDIA_SCANNER_SCAN_FILE -d " - + shlex.quote("file://" + remote) - ) - if result.returncode: - raise RuntimeError(f"Media scan failed: {result.output}") - return DeviceFile(remote, path.name, path.stat().st_size, None) - - -async def android_list_files( - device: "AndroidDevice", directory: str -) -> list[DeviceFile]: - await device._ensure_connected() - adb = device._adb_device - if adb is None: - raise RuntimeError("Android device is not connected") - return [ - DeviceFile( - posixpath.join(directory, item.path), item.path, item.size, item.mtime - ) - async for item in adb.sync.iter_directory(directory) - if item.path not in {".", ".."} - ] - - -async def android_pull_file( - device: "AndroidDevice", remote_path: str, local_path: str | Path -) -> Path: - await device._ensure_connected() - adb = device._adb_device - if adb is None: - raise RuntimeError("Android device is not connected") - destination = Path(local_path) - if destination.is_dir(): - destination = destination / posixpath.basename(remote_path) - await adb.sync.pull(remote_path, destination) - return destination - - -async def android_delete_file(device: "AndroidDevice", remote_path: str) -> None: - await device._ensure_connected() - adb = device._adb_device - if adb is None: - raise RuntimeError("Android device is not connected") - result = await adb.shell2("rm -- " + shlex.quote(remote_path)) - if result.returncode: - raise RuntimeError(f"File deletion failed: {result.output}") - - -async def cloud_push_file( - device: "CloudDevice", path: str | Path, dest: str | None -) -> DeviceFile: - path = Path(path) - directory, _ = destination(path, dest) - await device._ensure_connected() - await cloud_files.push_device_file( - device._write_client, - device._require_device_id(), - path, - directory, - billing=device._billing, - ) - return DeviceFile( - posixpath.join(directory, path.name), path.name, path.stat().st_size, None - ) - - -async def cloud_list_files(device: "CloudDevice", directory: str) -> list[DeviceFile]: - await device._ensure_connected() - return await cloud_files.list_device_files( - device._client, device._require_device_id(), directory, billing=device._billing - ) - - -async def cloud_pull_file( - device: "CloudDevice", remote_path: str, local_path: str | Path -) -> Path: - await device._ensure_connected() - data = await cloud_files.download_device_file( - device._client, - device._require_device_id(), - remote_path, - billing=device._billing, - ) - path = Path(local_path) - if path.is_dir(): - path = path / posixpath.basename(remote_path) - path.write_bytes(data) - return path - - -async def cloud_delete_file(device: "CloudDevice", remote_path: str) -> None: - await device._ensure_connected() - await cloud_files.delete_device_file( - device._write_client, - device._require_device_id(), - remote_path, - billing=device._billing, - ) diff --git a/mobilerun/core/devices/components/identifiers.py b/mobilerun/core/devices/components/identifiers.py deleted file mode 100644 index cddb48536..000000000 --- a/mobilerun/core/devices/components/identifiers.py +++ /dev/null @@ -1,43 +0,0 @@ -"""Connection identifiers safe to include in action logs.""" - -import logging -import re -from urllib.parse import urlsplit, urlunsplit - - -def _sanitize_identifier(identifier: str | None) -> str | None: - """Keep ordinary device IDs; remove credentials and URL metadata.""" - if identifier is None or "://" not in identifier: - return identifier - try: - parts = urlsplit(identifier) - return urlunsplit( - (parts.scheme, parts.netloc.rsplit("@", 1)[-1], parts.path, "", "") - ) - except ValueError: - # Malformed URLs must not fall back to logging the original secret. - return "invalid-url" - - -_URL = re.compile(r"[a-zA-Z][a-zA-Z0-9+.-]*://[^\s\"'<>]+") - - -def _sanitize_urls(text: str) -> str: - return _URL.sub(lambda match: _sanitize_identifier(match.group()) or "", text) - - -class _URLRedactionFilter(logging.Filter): - _mobilerun_url_redaction = True - - def filter(self, record: logging.LogRecord) -> bool: - # Format first so URLs split between message and arguments are covered too. - record.msg = _sanitize_urls(record.getMessage()) - record.args = () - return True - - -_backend_logger = logging.getLogger("mobilerun_core_local") -if not any( - getattr(item, "_mobilerun_url_redaction", False) for item in _backend_logger.filters -): - _backend_logger.addFilter(_URLRedactionFilter()) diff --git a/mobilerun/core/devices/components/input_lock.py b/mobilerun/core/devices/components/input_lock.py deleted file mode 100644 index bf5901aa1..000000000 --- a/mobilerun/core/devices/components/input_lock.py +++ /dev/null @@ -1,81 +0,0 @@ -"""Task-reentrant root-device serialization for focus-changing operations.""" - -from __future__ import annotations - -import asyncio -import inspect -from collections.abc import AsyncIterator, Awaitable, Callable -from contextlib import asynccontextmanager -from functools import wraps -from typing import TYPE_CHECKING, Any, Concatenate, ParamSpec, TypeVar - -if TYPE_CHECKING: - from mobilerun.core.devices.base import Device - -D = TypeVar("D", bound="Device") -P = ParamSpec("P") -R = TypeVar("R") - -_INPUT_OPERATIONS = frozenset( - { - "tap", - "swipe", - "drag", - "press_button", - "press_key_code", - "input_text", - "start_app", - "stop_app", - "open_url", - "tap_element", - "_input_secret", - "_input_text_raw", - "_swipe_humanized", - "install_app", - "install_apk", - "uninstall_app", - "set_language", - } -) - - -class InputOperationLock: - def __init__(self) -> None: - self._lock = asyncio.Lock() - self._owner: asyncio.Task[Any] | None = None - - @asynccontextmanager - async def hold(self) -> AsyncIterator[None]: - task = asyncio.current_task() - if task is not None and self._owner is task: - yield - return - async with self._lock: - self._owner = task - try: - yield - finally: - self._owner = None - - -def _serialize_input( - fn: Callable[Concatenate[D, P], Awaitable[R]], -) -> Callable[Concatenate[D, P], Awaitable[R]]: - @wraps(fn) - async def invoke(self: D, *args: P.args, **kwargs: P.kwargs) -> R: - async with self._unwrap()._input_operations.hold(): - return await fn(self, *args, **kwargs) - - invoke.__dict__["_serialized_input"] = True - return invoke - - -def serialize_inputs(cls: type[D]) -> type[D]: - """Instrument base methods, overrides and inherited device mixins alike.""" - for name in _INPUT_OPERATIONS: - method = getattr(cls, name, None) - if inspect.iscoroutinefunction(method) and not getattr( - method, "_serialized_input", False - ): - setattr(cls, name, _serialize_input(method)) - return cls diff --git a/mobilerun/core/devices/components/raw.py b/mobilerun/core/devices/components/raw.py deleted file mode 100644 index 3aea1388f..000000000 --- a/mobilerun/core/devices/components/raw.py +++ /dev/null @@ -1,138 +0,0 @@ -"""Explicit raw I/O delegation for framework-owned backend compositions. - -The backend is chosen at construction, never inferred from an instance. -Framework input semantics stay in Device; raw text always bypasses expansion. -""" - -from __future__ import annotations - -import asyncio -from collections.abc import Callable, Coroutine -from functools import wraps -from types import CoroutineType -from typing import Any, Concatenate, ParamSpec, TypeVar - -from mobilerun_core_local.driver.base import DeviceDriver, PlatformUnsupportedError - -from mobilerun.errors import DeviceOperationNotSupported - -P = ParamSpec("P") -R = TypeVar("R") -B = TypeVar("B", bound="_BackendIO") - - -def _translate_unsupported( - operation: Callable[P, Coroutine[Any, Any, R]], -) -> Callable[P, CoroutineType[Any, Any, R]]: - """Translate only the raw driver's declared unsupported-operation errors.""" - - @wraps(operation) - async def invoke(*args: P.args, **kwargs: P.kwargs) -> R: - try: - return await operation(*args, **kwargs) - except (NotImplementedError, PlatformUnsupportedError) as exc: - raise DeviceOperationNotSupported( - str(exc) or f"{operation.__name__} is unsupported" - ) from exc - - return invoke - - -def _backend_operation( - operation: Callable[Concatenate[B, P], Coroutine[Any, Any, R]], -) -> Callable[Concatenate[B, P], CoroutineType[Any, Any, R]]: - translated = _translate_unsupported(operation) - - @wraps(operation) - async def invoke(self: B, *args: P.args, **kwargs: P.kwargs) -> R: - await self._ensure_connected() - return await translated(self, *args, **kwargs) - - return invoke - - -class _BackendIO: - _backend: type[DeviceDriver] - - def __init__(self, *args: Any, **kwargs: Any) -> None: - self._backend_connect_lock = asyncio.Lock() - super().__init__(*args, **kwargs) - - @property - def _io_driver(self) -> DeviceDriver: - raise DeviceOperationNotSupported("No raw backend is configured") - - @_translate_unsupported - async def connect(self) -> None: - await self._ensure_connected() - - @_translate_unsupported - async def _ensure_connected(self) -> None: - async with self._backend_connect_lock: - await self._io_driver.ensure_connected() - - @_backend_operation - async def tap(self, x: int, y: int) -> None: - await self._io_driver.tap(x, y) - - @_backend_operation - async def swipe( - self, x1: int, y1: int, x2: int, y2: int, duration_ms: float = 1000 - ) -> None: - await self._io_driver.swipe(x1, y1, x2, y2, duration_ms) - - @_backend_operation - async def _input_text_raw( - self, text: str, clear: bool = False, stealth: bool = False, wpm: int = 0 - ) -> bool: - return await self._io_driver.input_text(text, clear, stealth, wpm) - - @_backend_operation - async def press_button(self, button: str) -> None: - await self._io_driver.press_button(button) - - @_backend_operation - async def press_key_code(self, key_code: int) -> None: - await self._io_driver.press_key_code(key_code) - - @_backend_operation - async def drag( - self, x1: int, y1: int, x2: int, y2: int, duration: float = 3.0 - ) -> None: - await self._io_driver.drag(x1, y1, x2, y2, duration) - - @_backend_operation - async def start_app(self, package: str, activity: str | None = None) -> str: - return await self._io_driver.start_app(package, activity) - - @_backend_operation - async def stop_app(self, package: str) -> str: - return await self._io_driver.stop_app(package) - - @_backend_operation - async def uninstall_app(self, package: str) -> str: - return await self._io_driver.uninstall_app(package) - - @_backend_operation - async def list_apps(self, include_system: bool = False) -> list[dict[str, str]]: - return await self._io_driver.get_apps(include_system) - - @_backend_operation - async def screenshot(self, hide_overlay: bool = True) -> bytes: - return await self._io_driver.screenshot(hide_overlay) - - @_backend_operation - async def _input_coordinate_size( - self, screenshot_width: int, screenshot_height: int - ) -> tuple[int, int]: - return await self._io_driver.input_coordinate_size( - screenshot_width, screenshot_height - ) - - @_backend_operation - async def _get_ui_tree(self) -> dict[str, Any]: - return await self._io_driver.get_ui_tree() - - @_backend_operation - async def _get_date(self) -> str: - return await self._io_driver.get_date() diff --git a/mobilerun/core/devices/components/wrapper.py b/mobilerun/core/devices/components/wrapper.py deleted file mode 100644 index f53381781..000000000 --- a/mobilerun/core/devices/components/wrapper.py +++ /dev/null @@ -1,445 +0,0 @@ -"""Explicit framework wrapper delegation and the raw-driver boundary.""" - -from __future__ import annotations - -import asyncio -from collections.abc import Awaitable, Callable -from pathlib import Path -from typing import TYPE_CHECKING, Any, Generic, TypeVar, Unpack, cast - -from mobilerun_core_local.driver.base import DeviceDriver, PlatformUnsupportedError -from pydantic import BaseModel - -from mobilerun.core.devices.base import Device, InstallOptions -from mobilerun.core.devices.components.identifiers import _sanitize_identifier -from mobilerun.core.devices.components.raw import _translate_unsupported -from mobilerun.core.operator import Operator -from mobilerun.core.proxy.target import ProxyTarget -from mobilerun.core.runs import recording_scope -from mobilerun.core.state.base import StateProvider -from mobilerun.core.state.options import StateProviderFactory, StateProviderOptions -from mobilerun.errors import DeviceOperationNotSupported -from mobilerun.models.apps import App -from mobilerun.models.files import DeviceFile -from mobilerun.models.location import Location -from mobilerun.models.results import ExecutionResult, ExpectationResult - -T = TypeVar("T", bound=BaseModel) -D = TypeVar("D", bound=Device) -R = TypeVar("R") - -if TYPE_CHECKING: - from mobilerun.core.devices.recording import RecordingDevice - from mobilerun.core.mailbox.base import Mailbox - from mobilerun.core.phone_number.base import PhoneNumber - - -class DeviceWrapper(Device, Generic[D]): - """A framework-only wrapper. Unknown attributes are never forwarded.""" - - # File operations follow the wrapped device. - async def push_file(self, path: str | Path, dest: str | None = None) -> DeviceFile: - return await self._inner.push_file(path, dest) - - async def list_files(self, directory: str) -> list[DeviceFile]: - return await self._inner.list_files(directory) - - async def pull_file(self, remote_path: str, local_path: str | Path) -> Path: - return await self._inner.pull_file(remote_path, local_path) - - async def delete_file(self, remote_path: str) -> None: - await self._inner.delete_file(remote_path) - - # Environment controls follow the wrapped device. - async def get_location(self) -> Location | None: - return await self._inner.get_location() - - async def get_language(self) -> str: - return await self._inner.get_language() - - async def get_timezone(self) -> str | None: - return await self._inner.get_timezone() - - async def set_location(self, latitude: float, longitude: float) -> None: - await self._inner.set_location(latitude, longitude) - - async def reset_location(self) -> None: - await self._inner.reset_location() - - async def set_timezone(self, timezone: str) -> None: - await self._inner.set_timezone(timezone) - - async def open_url(self, url: str) -> None: - await self._delegate_action(self._inner.open_url(url)) - - async def set_language(self, locale: str) -> None: - await self._inner.set_language(locale) - - async def set_clipboard(self, text: str) -> None: - await self._inner.set_clipboard(text) - - async def get_clipboard(self) -> str: - return await self._inner.get_clipboard() - - def __init__( - self, - device: D, - *, - state_provider: StateProvider | None = None, - state_provider_factory: StateProviderFactory | None = None, - state_options: StateProviderOptions | None = None, - operator: Operator | None = None, - ) -> None: - self._inner: D = device - if state_provider is not None and state_provider_factory is not None: - raise TypeError("Pass state_provider or state_provider_factory, not both") - if state_provider is None and state_provider_factory is None: - state_provider = device._state_provider_override - # Rebuild lazy providers against the OUTER wrapper, not its raw inner IO. - factory = state_provider_factory or device._state_provider_factory - options = state_options or device._default_provider_options - super().__init__( - state_provider=state_provider, - state_provider_factory=factory if state_provider is None else None, - state_options=options, - operator=operator if operator is not None else device._operator, - ) - - def _unwrap(self) -> Device: - inner = self.__dict__.get("_inner") - if inner is None: - raise AttributeError("Device wrapper is not initialized") - return inner._unwrap() - - @property - def platform(self) -> str: - return self._inner.platform - - @property - def supported_operations(self) -> set[str]: - return self._inner.supported_operations - - @property - def cloud_id(self) -> str | None: - return self._inner.cloud_id - - @property - def supported_buttons(self) -> set[str]: - return self._inner.supported_buttons - - @property - def _is_cloud(self) -> bool: - return self._inner._is_cloud - - @property - def identifier(self) -> str | None: - return self._inner.identifier - - async def close(self) -> None: - await self._inner.close() - - async def connect(self) -> None: - await self._inner.connect() - - async def _ensure_connected(self) -> None: - await self._inner._ensure_connected() - - @property - def number(self) -> PhoneNumber: - return cast("PhoneNumber", self._resource_lookup("sms", "phone_number")) - - @property - def mailbox(self) -> Mailbox: - return cast("Mailbox", self._resource_lookup("email", "mailbox")) - - @property - def _proxy_target(self) -> ProxyTarget: - return self._inner._proxy_target - - def _default_operator(self) -> Operator | None: - return self._inner._default_operator() - - async def do( - self, - instruction: str, - *, - output: type[T] | None = None, - max_steps: int | None = None, - operator: Operator | None = None, - timeout: float | None = None, - ) -> ExecutionResult[T]: - return await Device.do( - self, - instruction, - output=output, - max_steps=max_steps, - operator=operator, - timeout=timeout, - ) - - async def expect( - self, - condition: str, - *, - operator: Operator | None = None, - timeout: float | None = None, - ) -> ExpectationResult: - return await Device.expect(self, condition, operator=operator, timeout=timeout) - - def recording_device(self) -> RecordingDevice[Any] | None: - return self._inner.recording_device() - - def recording_allowed(self) -> bool: - return self._inner.recording_allowed() - - async def _delegate_action(self, operation: Awaitable[R]) -> R: - with recording_scope(enabled=self.recording_allowed()): - return await operation - - @property - def _state_recovery(self) -> Callable[[], Awaitable[None]] | None: - return self._inner._state_recovery - - def _create_state_provider( - self, - options: StateProviderOptions | None = None, - *, - device: Device | None = None, - ) -> StateProvider: - return self._inner._create_state_provider(options, device=device or self) - - async def _input_coordinate_size( - self, screenshot_width: int, screenshot_height: int - ) -> tuple[int, int]: - return await self._inner._input_coordinate_size( - screenshot_width, screenshot_height - ) - - async def input_text( - self, text: str, clear: bool = False, stealth: bool = False, wpm: int = 0 - ) -> bool: - return await self._delegate_action( - self._inner.input_text(text, clear, stealth, wpm) - ) - - async def _input_text_raw( - self, text: str, clear: bool = False, stealth: bool = False, wpm: int = 0 - ) -> bool: - return await self._delegate_action( - self._inner._input_text_raw(text, clear, stealth, wpm) - ) - - async def wait(self, seconds: float) -> None: - await self._delegate_action(self._inner.wait(seconds)) - - async def tap(self, x: int, y: int) -> None: - await self._delegate_action(self._inner.tap(x, y)) - - async def swipe( - self, x1: int, y1: int, x2: int, y2: int, duration_ms: float = 1000 - ) -> None: - await self._delegate_action(self._inner.swipe(x1, y1, x2, y2, duration_ms)) - - async def drag( - self, x1: int, y1: int, x2: int, y2: int, duration: float = 3.0 - ) -> None: - await self._delegate_action(self._inner.drag(x1, y1, x2, y2, duration)) - - async def press_button(self, button: str) -> None: - await self._delegate_action(self._inner.press_button(button)) - - async def press_key_code(self, key_code: int) -> None: - await self._delegate_action(self._inner.press_key_code(key_code)) - - async def install_apk( - self, path: str | Path, **kwargs: Unpack[InstallOptions] - ) -> App: - return await self._inner.install_apk(path, **kwargs) - - async def install_app(self, app: App, **kwargs: Unpack[InstallOptions]) -> App: - return await self._inner.install_app(app, **kwargs) - - async def _swipe_humanized( - self, x1: int, y1: int, x2: int, y2: int, duration_ms: float = 1000 - ) -> None: - await self._delegate_action( - self._inner._swipe_humanized(x1, y1, x2, y2, duration_ms) - ) - - async def start_app(self, package: str, activity: str | None = None) -> str: - return await self._delegate_action(self._inner.start_app(package, activity)) - - async def stop_app(self, package: str) -> str: - return await self._delegate_action(self._inner.stop_app(package)) - - async def uninstall_app(self, package: str) -> str: - return await self._inner.uninstall_app(package) - - async def list_apps(self, include_system: bool = False) -> list[dict[str, str]]: - return await self._inner.list_apps(include_system) - - async def screenshot(self, hide_overlay: bool = True) -> bytes: - return await self._inner.screenshot(hide_overlay) - - async def _get_ui_tree(self) -> dict[str, Any]: - return await self._inner._get_ui_tree() - - async def _get_date(self) -> str: - return await self._inner._get_date() - - -class DriverDevice(Device): - """Adapt a raw driver with an explicitly paired provider and lifecycle.""" - - def __init__( - self, - driver: DeviceDriver, - *, - state_provider_factory: StateProviderFactory, - initialize: Callable[[], Awaitable[None]] | None = None, - close: Callable[[], Awaitable[None]] | None = None, - identifier: str | None = None, - ) -> None: - self._driver = driver - self._identifier = _sanitize_identifier(identifier) - self._initialize_driver = initialize - self._connected = False - self._connect_lock = asyncio.Lock() - self._close_driver = close - super().__init__(state_provider_factory=state_provider_factory) - - @property - def platform(self) -> str: - return self._driver.platform - - @property - def identifier(self) -> str | None: - return self._identifier - - @property - def supported_operations(self) -> set[str]: - return self._driver.supported - - @property - def supported_buttons(self) -> set[str]: - return self._driver.supported_buttons - - @_translate_unsupported - async def connect(self) -> None: - async with self._connect_lock: - if not self._connected: - if self._initialize_driver is not None: - await self._initialize_driver() - else: - await self._driver.connect() - self._connected = True - - async def close(self) -> None: - async with self._closing_extensions(): - if self._close_driver is not None: - await self._close_driver() - - def _create_state_provider( - self, - options: StateProviderOptions | None = None, - *, - device: Device | None = None, - ) -> StateProvider: - assert self._state_provider_factory is not None - return self._state_provider_factory( - device or self, options or StateProviderOptions() - ) - - @_translate_unsupported - async def _ensure_connected(self) -> None: - await self.connect() - - @_translate_unsupported - async def _input_text_raw( - self, text: str, clear: bool = False, stealth: bool = False, wpm: int = 0 - ) -> bool: - return await self._driver.input_text( - text, clear=clear, stealth=stealth, wpm=wpm - ) - - @_translate_unsupported - async def tap(self, x: int, y: int) -> None: - await self._driver.tap(x, y) - - @_translate_unsupported - async def swipe( - self, x1: int, y1: int, x2: int, y2: int, duration_ms: float = 1000 - ) -> None: - await self._driver.swipe(x1, y1, x2, y2, duration_ms) - - @_translate_unsupported - async def drag( - self, x1: int, y1: int, x2: int, y2: int, duration: float = 3.0 - ) -> None: - await self._driver.drag(x1, y1, x2, y2, duration) - - @_translate_unsupported - async def press_button(self, button: str) -> None: - await self._driver.press_button(button) - - @_translate_unsupported - async def press_key_code(self, key_code: int) -> None: - await self._driver.press_key_code(key_code) - - @_translate_unsupported - async def install_apk( - self, path: str | Path, **kwargs: Unpack[InstallOptions] - ) -> App: - try: - await self._driver.install_app(str(path), **kwargs) - except PlatformUnsupportedError as exc: - raise DeviceOperationNotSupported(str(exc)) from exc - from mobilerun.clients.local.apk import inspect_apk - - package, code, version, name = await asyncio.to_thread(inspect_apk, Path(path)) - return App(package, version, name, version_code=code, path=Path(path)) - - async def install_app(self, app: App, **kwargs: Unpack[InstallOptions]) -> App: - if app.path is None: - raise ValueError("This app has no local APK; use install_apk with a path") - await self.install_apk(app.path, **kwargs) - return app - - @_translate_unsupported - async def start_app(self, package: str, activity: str | None = None) -> str: - return await self._driver.start_app(package, activity) - - @_translate_unsupported - async def stop_app(self, package: str) -> str: - return await self._driver.stop_app(package) - - @_translate_unsupported - async def uninstall_app(self, package: str) -> str: - try: - return await self._driver.uninstall_app(package) - except PlatformUnsupportedError as exc: - raise DeviceOperationNotSupported(str(exc)) from exc - - @_translate_unsupported - async def list_apps(self, include_system: bool = False) -> list[dict[str, str]]: - return await self._driver.get_apps(include_system) - - @_translate_unsupported - async def screenshot(self, hide_overlay: bool = True) -> bytes: - return await self._driver.screenshot(hide_overlay) - - @_translate_unsupported - async def _input_coordinate_size( - self, screenshot_width: int, screenshot_height: int - ) -> tuple[int, int]: - return await self._driver.input_coordinate_size( - screenshot_width, screenshot_height - ) - - @_translate_unsupported - async def _get_ui_tree(self) -> dict[str, Any]: - return await self._driver.get_ui_tree() - - @_translate_unsupported - async def _get_date(self) -> str: - return await self._driver.get_date() diff --git a/mobilerun/core/devices/ios.py b/mobilerun/core/devices/ios.py deleted file mode 100644 index c528bc044..000000000 --- a/mobilerun/core/devices/ios.py +++ /dev/null @@ -1,128 +0,0 @@ -"""iOS devices, detecting the portal protocol once during connection.""" - -import asyncio - -import httpx -from mobilerun_core_local.driver.ios import ( - IOSPortalDriver, - IOSPortalHttpDriver, - detect_ios_portal_kind, -) - -from mobilerun.core.devices.base import Device -from mobilerun.core.devices.components.identifiers import _sanitize_identifier -from mobilerun.core.devices.components.raw import _BackendIO -from mobilerun.core.operator import Operator -from mobilerun.core.state.base import StateProvider -from mobilerun.core.state.options import ( - StateProviderFactory, - StateProviderOptions, - android_state_provider, - ios_state_provider, -) -from mobilerun.errors import DeviceNotReady, DeviceOperationNotSupported - - -class _DetectionTransport(httpx.AsyncBaseTransport): - def __init__(self, transport: httpx.AsyncBaseTransport) -> None: - self._transport = transport - - async def handle_async_request(self, request: httpx.Request) -> httpx.Response: - return await self._transport.handle_async_request(request) - - async def aclose(self) -> None: - pass # Detection must not close the device-owned transport. - - -class IOSDevice(_BackendIO, Device): - async def uninstall_app(self, package: str) -> str: - raise DeviceOperationNotSupported("iOS does not support uninstall") - - def __init__( - self, - url: str, - bundle_identifiers: list[str] | None = None, - *, - token: str | None = None, - transport: httpx.AsyncBaseTransport | None = None, - state_provider: StateProvider | None = None, - state_provider_factory: StateProviderFactory | None = None, - state_options: StateProviderOptions | None = None, - operator: Operator | None = None, - ) -> None: - self._url = url - self._token = token - self._transport = transport - self._bundle_identifiers = bundle_identifiers - self._driver: IOSPortalDriver | IOSPortalHttpDriver | None = None - self._portal_http = False - self._connect_lock = asyncio.Lock() - super().__init__( - state_provider=state_provider, - state_provider_factory=state_provider_factory, - state_options=state_options, - operator=operator, - ) - - @property - def _io_driver(self) -> IOSPortalDriver | IOSPortalHttpDriver: - if self._driver is None: - raise DeviceNotReady("Connect IOSDevice or use async with before using it") - return self._driver - - @property - def platform(self) -> str: - return "ios" - - @property - def identifier(self) -> str | None: - return _sanitize_identifier(self._url) - - @property - def supported_operations(self) -> set[str]: - return self._io_driver.supported - - @property - def supported_buttons(self) -> set[str]: - return self._io_driver.supported_buttons - - async def connect(self) -> None: - async with self._connect_lock: - if self._driver is None: - detection = ( - _DetectionTransport(self._transport) - if self._transport is not None - else None - ) - kind = await detect_ios_portal_kind( - self._url, token=self._token, transport=detection - ) - self._portal_http = kind == "portal-http" - if self._portal_http: - self._driver = IOSPortalHttpDriver( - self._url, self._token, transport=self._transport - ) - else: - self._driver = IOSPortalDriver( - self._url, self._bundle_identifiers, transport=self._transport - ) - await self._ensure_connected() - - def _create_state_provider( - self, - options: StateProviderOptions | None = None, - *, - device: Device | None = None, - ) -> StateProvider: - if self._driver is None: - raise DeviceNotReady( - "Connect IOSDevice before resolving its state provider" - ) - factory = android_state_provider if self._portal_http else ios_state_provider - return factory(device or self, options or StateProviderOptions()) - - async def close(self) -> None: - async with self._closing_extensions(): - if self._driver is not None and self._driver._client is not None: - await self._driver._client.aclose() - self._driver._client = None diff --git a/mobilerun/core/devices/pool.py b/mobilerun/core/devices/pool.py deleted file mode 100644 index c8d4a8885..000000000 --- a/mobilerun/core/devices/pool.py +++ /dev/null @@ -1,390 +0,0 @@ -"""Concurrent, ordered operations across a group of devices.""" - -from __future__ import annotations - -import asyncio -from collections.abc import Awaitable, Callable, Iterator, Mapping -from pathlib import Path -from types import TracebackType -from typing import TYPE_CHECKING, Any, Self, TypeVar, Unpack - -from pydantic import BaseModel - -from mobilerun.core.devices.base import Device, InstallOptions -from mobilerun.core.extensions import Action, Extension -from mobilerun.core.extensions.actions import Audience -from mobilerun.core.state.ui_state import UIState -from mobilerun.models.apps import App -from mobilerun.models.context import ContextItem, JSONValue -from mobilerun.models.files import DeviceFile -from mobilerun.models.location import Location -from mobilerun.models.results import ExecutionResult, ExpectationResult - -if TYPE_CHECKING: - from mobilerun.core.mailbox.base import Mailbox - from mobilerun.core.phone_number.base import PhoneNumber - -T = TypeVar("T", bound=BaseModel) -R = TypeVar("R") - - -class _PoolActions: - def __init__(self, pool: DevicePool) -> None: - self._pool = pool - - def list(self, *, audience: Audience = "python") -> list[tuple[Action, ...]]: - return [device.actions.list(audience=audience) for device in self._pool.devices] - - async def call( - self, - name: str, - arguments: Mapping[str, JSONValue], - *, - audience: Audience = "python", - timeout: float | None = None, - ) -> list[object]: - schemas = [] - for device in self._pool.devices: - entry = device.actions.get(name) - if audience != "python" and not entry.public: - raise PermissionError(f"Action {name} is restricted") - entry.validate(arguments) - schemas.append(entry.input_schema) - if schemas and any(schema != schemas[0] for schema in schemas): - raise ValueError(f"Pool action {name} has incompatible schemas") - return await self._pool._broadcast( - name, - lambda device, _: device.actions.call( - name, arguments, audience=audience, timeout=timeout - ), - ) - - -class _PoolState: - def __init__(self, pool: DevicePool) -> None: - self._pool = pool - - async def refresh(self) -> list[UIState]: - return await self._pool._broadcast( - "state.refresh", lambda device, _: device.state.refresh() - ) - - -class DevicePool: - """Broadcast device operations concurrently, collecting results in device order.""" - - @property - def actions(self) -> _PoolActions: - return _PoolActions(self) - - async def context(self) -> list[tuple[ContextItem, ...]]: - return await self._broadcast("context", lambda device, _: device.context()) - - async def bind_each( - self, - factory: Callable[[Device], Extension], - *, - force: bool = False, - close_on_device_close: bool = False, - ) -> list[Extension]: - extensions = [factory(device) for device in self.devices] - if len({id(extension) for extension in extensions}) != len(extensions): - raise ValueError("Pool binding requires separate extension instances") - return await self._broadcast( - "bind", - lambda device, index: extensions[index].bind( - device, force=force, close_on_device_close=close_on_device_close - ), - ) - - async def unbind_extension(self, name: str) -> list[None]: - return await self._broadcast( - "unbind_extension", lambda device, _: device.unbind_extension(name) - ) - - # File operations are broadcast in device order. - async def push_file( - self, path: str | Path, dest: str | None = None - ) -> list[DeviceFile]: - return await self._broadcast( - "push_file", lambda device, _: device.push_file(path, dest) - ) - - async def list_files(self, directory: str) -> list[list[DeviceFile]]: - return await self._broadcast( - "list_files", lambda device, _: device.list_files(directory) - ) - - async def delete_file(self, remote_path: str) -> list[None]: - return await self._broadcast( - "delete_file", lambda device, _: device.delete_file(remote_path) - ) - - # Environment controls are broadcast in device order. - async def get_language(self) -> list[str]: - return await self._broadcast( - "get_language", lambda device, _: device.get_language() - ) - - async def get_timezone(self) -> list[str | None]: - return await self._broadcast( - "get_timezone", lambda device, _: device.get_timezone() - ) - - async def get_location(self) -> list[Location | None]: - return await self._broadcast( - "get_location", lambda device, _: device.get_location() - ) - - async def set_location(self, latitude: float, longitude: float) -> list[None]: - return await self._broadcast( - "set_location", lambda device, _: device.set_location(latitude, longitude) - ) - - async def reset_location(self) -> list[None]: - return await self._broadcast( - "reset_location", lambda device, _: device.reset_location() - ) - - async def set_timezone(self, timezone: str) -> list[None]: - return await self._broadcast( - "set_timezone", lambda device, _: device.set_timezone(timezone) - ) - - async def open_url(self, url: str) -> list[None]: - return await self._broadcast("open_url", lambda device, _: device.open_url(url)) - - @property - def number(self) -> list[PhoneNumber]: - return [device.number for device in self.devices] - - @property - def mailbox(self) -> list[Mailbox]: - return [device.mailbox for device in self.devices] - - def __init__( - self, devices: list[Device], *, concurrency: int | None = None - ) -> None: - if not devices: - raise ValueError("DevicePool requires at least one device") - if concurrency is not None and ( - not isinstance(concurrency, int) or concurrency < 1 - ): - raise ValueError("concurrency must be a positive integer") - for device in devices: - operator = device._operator - if operator is not None: - operator.check(device) - self.devices = tuple(devices) - self.state = _PoolState(self) - self._semaphore = asyncio.Semaphore(concurrency) if concurrency else None - - def __len__(self) -> int: - return len(self.devices) - - def __iter__(self) -> Iterator[Device]: - return iter(self.devices) - - @property - def platform(self) -> list[str]: - return [device.platform for device in self.devices] - - @property - def supported_operations(self) -> list[set[str]]: - return [device.supported_operations for device in self.devices] - - @property - def extensions(self) -> list[Mapping[str, Extension]]: - return [device.extensions for device in self.devices] - - @property - def supported_buttons(self) -> list[set[str]]: - return [device.supported_buttons for device in self.devices] - - async def _broadcast( - self, name: str, call: Callable[[Device, int], Awaitable[R]] - ) -> list[R]: - errors: dict[int, Exception] = {} - - async def invoke(device: Device, index: int) -> list[R]: - try: - if self._semaphore is None: - return [await call(device, index)] - async with self._semaphore: - return [await call(device, index)] - except Exception as exc: - exc.add_note(f"device {index}: {type(device).__name__}") - errors[index] = exc - return [] - - outcomes = await asyncio.gather( - *(invoke(device, index) for index, device in enumerate(self.devices)) - ) - if errors: - raise ExceptionGroup( - f"{len(errors)} of {len(self)} devices failed: {name}", - [errors[index] for index in sorted(errors)], - ) - return [value for outcome in outcomes for value in outcome] - - async def __aenter__(self) -> Self: - try: - await self.connect() - except BaseException as exc: - try: - await self.close() - except Exception as cleanup_error: - exc.add_note(f"Pool cleanup failed: {cleanup_error}") - raise - return self - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc: BaseException | None, - tb: TracebackType | None, - ) -> None: - try: - await self.close() - except Exception as cleanup_error: - if exc is None: - raise - exc.add_note(f"Pool cleanup failed: {cleanup_error}") - - async def close(self) -> list[None]: - return await self._broadcast("close", lambda device, _: device.close()) - - async def connect(self) -> list[None]: - return await self._broadcast("connect", lambda device, _: device.connect()) - - async def screenshot(self, hide_overlay: bool = True) -> list[bytes]: - return await self._broadcast( - "screenshot", lambda device, _: device.screenshot(hide_overlay=hide_overlay) - ) - - async def tap(self, x: int, y: int) -> list[None]: - return await self._broadcast("tap", lambda device, _: device.tap(x, y)) - - async def swipe( - self, x1: int, y1: int, x2: int, y2: int, duration_ms: float = 1000 - ) -> list[None]: - return await self._broadcast( - "swipe", - lambda device, _: device.swipe(x1, y1, x2, y2, duration_ms=duration_ms), - ) - - async def drag( - self, x1: int, y1: int, x2: int, y2: int, duration: float = 3.0 - ) -> list[None]: - return await self._broadcast( - "drag", lambda device, _: device.drag(x1, y1, x2, y2, duration=duration) - ) - - async def input_text( - self, text: str, clear: bool = False, stealth: bool = False, wpm: int = 0 - ) -> list[bool]: - return await self._broadcast( - "input_text", - lambda device, _: device.input_text( - text, clear=clear, stealth=stealth, wpm=wpm - ), - ) - - async def press_button(self, button: str) -> list[None]: - return await self._broadcast( - "press_button", lambda device, _: device.press_button(button) - ) - - async def wait(self, seconds: float) -> list[None]: - return await self._broadcast("wait", lambda device, _: device.wait(seconds)) - - async def press_key_code(self, key_code: int) -> list[None]: - return await self._broadcast( - "press_key_code", lambda device, _: device.press_key_code(key_code) - ) - - async def start_app(self, package: str, activity: str | None = None) -> list[str]: - return await self._broadcast( - "start_app", - lambda device, _: device.start_app(package, activity=activity), - ) - - async def stop_app(self, package: str) -> list[str]: - return await self._broadcast( - "stop_app", lambda device, _: device.stop_app(package) - ) - - async def install_apk( - self, path: str | Path, **kwargs: Unpack[InstallOptions] - ) -> list[App]: - return await self._broadcast( - "install_apk", lambda device, _: device.install_apk(path, **kwargs) - ) - - async def install_app( - self, app: App, **kwargs: Unpack[InstallOptions] - ) -> list[App]: - return await self._broadcast( - "install_app", lambda device, _: device.install_app(app, **kwargs) - ) - - async def uninstall_app(self, package: str) -> list[str]: - return await self._broadcast( - "uninstall_app", lambda device, _: device.uninstall_app(package) - ) - - async def list_apps( - self, include_system: bool = False - ) -> list[list[dict[str, str]]]: - return await self._broadcast( - "list_apps", - lambda device, _: device.list_apps(include_system=include_system), - ) - - async def tap_element(self, index: int) -> list[None]: - return await self._broadcast( - "tap_element", lambda device, _: device.tap_element(index) - ) - - async def set_language(self, locale: str) -> list[None]: - return await self._broadcast( - "set_language", lambda device, _: device.set_language(locale) - ) - - async def set_clipboard(self, text: str) -> list[None]: - return await self._broadcast( - "set_clipboard", lambda device, _: device.set_clipboard(text) - ) - - async def get_clipboard(self) -> list[str]: - return await self._broadcast( - "get_clipboard", lambda device, _: device.get_clipboard() - ) - - async def do( - self, - instruction: str, - *, - output: type[T] | None = None, - max_steps: int | None = None, - operator: Any = None, - timeout: float | None = None, - ) -> list[ExecutionResult[T]]: - kwargs = {"output": output, "max_steps": max_steps, "operator": operator} - if timeout is not None: - kwargs["timeout"] = timeout - return await self._broadcast( - "do", lambda device, _: device.do(instruction, **kwargs) - ) - - async def expect( - self, condition: str, *, operator: Any = None, timeout: float | None = None - ) -> list[ExpectationResult]: - kwargs = {} - if operator is not None: - kwargs["operator"] = operator - if timeout is not None: - kwargs["timeout"] = timeout - return await self._broadcast( - "expect", lambda device, _: device.expect(condition, **kwargs) - ) diff --git a/mobilerun/core/devices/recording.py b/mobilerun/core/devices/recording.py deleted file mode 100644 index b1b63c644..000000000 --- a/mobilerun/core/devices/recording.py +++ /dev/null @@ -1,225 +0,0 @@ -"""Explicit device wrapper for recording dispatched actions.""" - -from __future__ import annotations - -from collections.abc import Awaitable, Callable -from contextlib import AbstractContextManager -from functools import partial -from pathlib import Path -from types import TracebackType -from typing import Any, Literal, TypeVar - -from pydantic import JsonValue - -from mobilerun.config.settings import get_settings -from mobilerun.core.devices.base import Device -from mobilerun.core.devices.components.wrapper import DeviceWrapper -from mobilerun.core.extensions.base import _inside_bound_action -from mobilerun.core.operator import Operator -from mobilerun.core.runs import recording_policy -from mobilerun.core.runs.capture import FingerprintCapture -from mobilerun.core.runs.session import RecordingSession -from mobilerun.core.state.base import StateProvider -from mobilerun.core.state.options import StateProviderFactory, StateProviderOptions -from mobilerun.models import Actor, Fingerprint, RunKind, RunStatus -from mobilerun.utils.redaction import _active_secrets, _redact_secrets - -D = TypeVar("D", bound=Device) -R = TypeVar("R") - - -class RecordingDevice(DeviceWrapper[D]): - """Record one outcome for each dispatched primitive or outer extension call.""" - - def __init__( - self, - device: D, - *, - kind: RunKind = "recording", - source_macro: str | None = None, - by: Actor = "script", - runs_dir: Path | None = None, - capture: Literal["full", "actions"] = "full", - state_provider: StateProvider | None = None, - state_provider_factory: StateProviderFactory | None = None, - state_options: StateProviderOptions | None = None, - operator: Operator | None = None, - ) -> None: - super().__init__( - device, - state_provider=state_provider, - state_provider_factory=state_provider_factory, - state_options=state_options, - operator=operator, - ) - settings = get_settings() - self._owner = device.recording_device() or self - evidence = FingerprintCapture( - self, - device, - capture == "full", - settings.MOBILERUN_RUN_SETTLE_SECONDS, - ) - self._session = RecordingSession( - self, - evidence, - runs_dir if runs_dir is not None else settings.runs_dir, - kind=kind, - source_macro=source_macro, - by=by, - observe_extensions=self._owner is self, - ) - - def recording_device(self) -> RecordingDevice[Any]: - return self._owner - - @property - def run_dir(self) -> Path | None: - return self._owner._session.writer.started_dir - - @property - def step_index(self) -> int: - return self._owner._session.writer.step_index - - def collect_steps(self) -> AbstractContextManager[list[int]]: - """Collect committed rows from this scope and tasks spawned in it.""" - return self._owner._session.writer.collect_steps() - - def start_run(self) -> Path | None: - return self._owner._session.start() if self.recording_allowed() else None - - def finish(self, status: RunStatus, failed_step: int | None = None) -> None: - self._session.finish(status, failed_step) - - async def close(self) -> None: - try: - self.finish("cancelled") - except BaseException as error: - try: - await self._inner.close() - except BaseException: - error.add_note("The wrapped device also failed to close") - raise - await self._inner.close() - - async def __aexit__( - self, - exc_type: type[BaseException] | None, - exc: BaseException | None, - tb: TracebackType | None, - ) -> None: - try: - await self.close() - except Exception: - if exc is None: - raise - exc.add_note("Recording/device cleanup also failed") - - async def capture_fingerprint(self, *, fresh: bool = False) -> Fingerprint | None: - if not self.recording_allowed() or not recording_policy()[0]: - return None - return await self._owner._session.capture.capture(fresh=fresh) - - async def _dispatch( - self, operation: Callable[[], Awaitable[R]], action: str, **args: JsonValue - ) -> R: - if self._owner is not self or _inside_bound_action(self): - return await operation() - return await self._session.dispatch(operation, action, args) - - async def tap(self, x: int, y: int) -> None: - await self._dispatch(partial(self._inner.tap, x, y), "tap", x=x, y=y) - - async def swipe( - self, x1: int, y1: int, x2: int, y2: int, duration_ms: float = 1000 - ) -> None: - op = partial(self._inner.swipe, x1, y1, x2, y2, duration_ms) - await self._gesture(op, "swipe", (x1, y1, x2, y2), duration_ms=duration_ms) - - async def _swipe_humanized( - self, x1: int, y1: int, x2: int, y2: int, duration_ms: float = 1000 - ) -> None: - op = partial(self._inner._swipe_humanized, x1, y1, x2, y2, duration_ms) - await self._gesture(op, "swipe", (x1, y1, x2, y2), duration_ms=duration_ms) - - async def drag( - self, x1: int, y1: int, x2: int, y2: int, duration: float = 3.0 - ) -> None: - op = partial(self._inner.drag, x1, y1, x2, y2, duration) - await self._gesture(op, "drag", (x1, y1, x2, y2), duration=duration) - - async def _gesture( - self, - operation: Callable[[], Awaitable[None]], - action: str, - points: tuple[int, int, int, int], - **duration: JsonValue, - ) -> None: - args = dict(zip(("start_x", "start_y", "end_x", "end_y"), points, strict=True)) - await self._dispatch(operation, action, **args, **duration) - - async def input_text( - self, text: str, clear: bool = False, stealth: bool = False, wpm: int = 0 - ) -> bool: - sensitive = bool( - _active_secrets.get() - ) or self._extension_state.matches_sensitive_argument(text) - if sensitive: - self._extension_state.sensitive_ui = True - if _redact_secrets(text) != text: - self._extension_state.known_codes.observed_secrets.add(text) - op = partial(self._inner.input_text, text, clear, stealth, wpm) - return await self._text(op, "***" if sensitive else text, clear, stealth, wpm) - - async def _input_text_raw( - self, text: str, clear: bool = False, stealth: bool = False, wpm: int = 0 - ) -> bool: - if not _active_secrets.get(): - return await super()._input_text_raw(text, clear, stealth, wpm) - op = partial(self._inner._input_text_raw, text, clear, stealth, wpm) - return await self._text(op, "***", clear, stealth, wpm) - - async def _text( - self, - operation: Callable[[], Awaitable[bool]], - text: str, - clear: bool, - stealth: bool, - wpm: int, - ) -> bool: - return await self._dispatch( - operation, "input_text", text=text, clear=clear, stealth=stealth, wpm=wpm - ) - - async def press_button(self, button: str) -> None: - await self._dispatch( - partial(self._inner.press_button, button), "button_press", button=button - ) - - async def start_app(self, package: str, activity: str | None = None) -> str: - return await self._dispatch( - partial(self._inner.start_app, package, activity), - "start_app", - package=package, - activity=activity, - ) - - async def open_url(self, url: str) -> None: - await self._dispatch(partial(self._inner.open_url, url), "open_url", url=url) - - async def stop_app(self, package: str) -> str: - return await self._dispatch( - partial(self._inner.stop_app, package), "stop_app", package=package - ) - - async def press_key_code(self, key_code: int) -> None: - await self._dispatch( - partial(self._inner.press_key_code, key_code), - "press_key_code", - key_code=key_code, - ) - - async def wait(self, seconds: float) -> None: - await self._dispatch( - partial(self._inner.wait, seconds), "wait", duration=seconds - ) diff --git a/mobilerun/core/devices/remote.py b/mobilerun/core/devices/remote.py deleted file mode 100644 index 02f0245e0..000000000 --- a/mobilerun/core/devices/remote.py +++ /dev/null @@ -1,103 +0,0 @@ -"""Visual remote device interface.""" - -from typing import Any - -from mobilerun_core_local.driver.visual_remote import VisualRemoteDriver - -from mobilerun.core.devices.base import Device -from mobilerun.core.devices.components.identifiers import _sanitize_identifier -from mobilerun.core.devices.components.raw import _BackendIO -from mobilerun.core.operator import Operator -from mobilerun.core.state.base import StateProvider -from mobilerun.core.state.options import ( - StateProviderFactory, - StateProviderOptions, - screenshot_state_provider, -) -from mobilerun.errors import DeviceOperationNotSupported - - -class RemoteDevice(_BackendIO, Device): - """Device backed by a visual remote driver.""" - - _backend = VisualRemoteDriver - - async def list_apps(self, include_system: bool = False) -> list[dict[str, str]]: - raise DeviceOperationNotSupported( - "Visual remote does not expose an app inventory" - ) - - async def _get_date(self) -> str: - raise DeviceOperationNotSupported("Visual remote does not expose device time") - - async def _get_ui_tree(self) -> dict[str, Any]: - raise DeviceOperationNotSupported("Visual remote does not expose a UI tree") - - async def start_app(self, package: str, activity: str | None = None) -> str: - await self._ensure_connected() - if "start_app" not in self.supported_operations: - raise DeviceOperationNotSupported( - "This visual remote server does not support app launch" - ) - return await super().start_app(package, activity) - - @property - def platform(self) -> str: - return self._driver.platform - - def __init__( - self, - *args: Any, - state_provider: StateProvider | None = None, - state_options: StateProviderOptions | None = None, - state_provider_factory: StateProviderFactory | None = None, - operator: Operator | None = None, - **kwargs: Any, - ) -> None: - self._driver = VisualRemoteDriver(*args, **kwargs) - super().__init__( - state_provider=state_provider, - operator=operator, - state_options=state_options, - state_provider_factory=state_provider_factory, - ) - - @property - def _io_driver(self) -> VisualRemoteDriver: - return self._driver - - @property - def supported_operations(self) -> set[str]: - return self._driver.supported - - @property - def supported_buttons(self) -> set[str]: - return self._driver.supported_buttons - - @property - def _remote_identifier(self) -> str | None: - return _sanitize_identifier(self._driver.device_id or self._driver.url) - - @property - def _url(self) -> str: - return self._driver.url - - @property - def identifier(self) -> str | None: - return self._remote_identifier - - def _create_state_provider( - self, - options: StateProviderOptions | None = None, - *, - device: Device | None = None, - ) -> StateProvider: - return screenshot_state_provider( - device or self, options or StateProviderOptions() - ) - - async def close(self) -> None: - async with self._closing_extensions(): - if self._driver._client is not None: - await self._driver._client.aclose() - self._driver._client = None diff --git a/mobilerun/core/devices/stealth.py b/mobilerun/core/devices/stealth.py deleted file mode 100644 index 81ae23e03..000000000 --- a/mobilerun/core/devices/stealth.py +++ /dev/null @@ -1,41 +0,0 @@ -"""Humanized input over the explicit framework device contract.""" - -import random -from typing import TypeVar - -from mobilerun.core.devices.base import Device -from mobilerun.core.devices.components.wrapper import DeviceWrapper -from mobilerun.core.runs import recording_scope - -D = TypeVar("D", bound=Device) - - -class StealthDevice(DeviceWrapper[D]): - def recording_allowed(self) -> bool: - """Stealth vetoes run evidence across the entire wrapper chain.""" - return False - - async def input_text( - self, text: str, clear: bool = False, stealth: bool = False, wpm: int = 0 - ) -> bool: - with recording_scope(enabled=False): - if "{{" in text or "}}" in text: - return await self._inner.input_text(text, clear, stealth, wpm) - words = text.split(" ") - for i, word in enumerate(words): - if not await self._inner.input_text( - word, clear and i == 0, stealth, wpm - ): - return False - if i < len(words) - 1: - if not await self._inner.input_text(" ", False, stealth, wpm): - return False - await self._inner.wait(random.uniform(0.1, 0.3)) - return True - - async def swipe( - self, x1: int, y1: int, x2: int, y2: int, duration_ms: float = 1000 - ) -> None: - await self._delegate_action( - self._inner._swipe_humanized(x1, y1, x2, y2, duration_ms) - ) diff --git a/mobilerun/core/extensions/README.md b/mobilerun/core/extensions/README.md index 8fa1a2fba..bb4f612d4 100644 --- a/mobilerun/core/extensions/README.md +++ b/mobilerun/core/extensions/README.md @@ -1,161 +1,72 @@ # Extensions -An extension is a standalone resource with typed async `@action` methods and -public `ContextItem` metadata. Bind explicitly with `await extension.bind(device)`. -The device owns only the shared registry; the extension owns compatibility checks. - -Repository test helpers live in `tests/support`: `MemoryDevice` in `devices.py` -and `check_extension_contract` in `extensions.py`. The contract checker covers -binding invariants and safe standalone/device-action probes. These helpers are -internal to the repository and are not shipped in the package. - -`check_bind` calls `super()` and returns conflicts with the same `exclusive` key. -Conflicts fail before backend calls. `force=True` unbinds conflicts without closing -or releasing them; compatibility and unrelated name collisions still fail. -Device cleanup unbinds borrowed extensions and closes extensions bound with -`close_on_device_close=True`, before closing its transport. - -Use the original typed handle. There is no typed `Device.get` API. Dynamic -`device.name` resolves only registered names; unknown names raise AttributeError. -Discover actions through `device.actions` and public metadata through -`await device.context()`. Action arguments/results are schema-validated. Secret -values must never be returned or included in context. - -## Quick example: standalone and device actions - -`@action` runs bound or unbound, through direct typed calls or the extension's -`actions.call(...)` catalog. Use it for vault listings, mailbox codes, and number -messages. `@device_action` always requires a binding and injects the bound facade -before the body runs: - -```python -from mobilerun.core.devices import Device -from mobilerun.core.extensions import Extension, action, device_action - -class Example(Extension): - @action - async def available(self) -> bool: - """Read standalone resource metadata.""" - return True - - @device_action - async def write(self, device: Device, text: str) -> None: - """Type through the bound recording/stealth facade.""" - await device.input_text(text) - -# await example.write("hello") # device is injected, never passed by the caller -``` - -The first parameter after `self` must be `device: Device`. It is hidden from -the typed public signature, runtime signature, and input schema. Unbound calls -raise `ExtensionNotBound("'example.write' needs a bound device; await example.bind(device) first")` -before executing the body. Listings expose `requires_device: bool`, even unbound. -Both decorators support bare or configured forms (`@action()`, -`@device_action(public=False, sensitive_parameters=frozenset({"text"}))`). -Overrides inherit the original decorator unless explicitly redecorated. - -For a cloud operation that checks billing before any side effects, use -`@action(billing_retry=_send_with_billing)`, where the handler accepts -`(self, policy: BillingRetry, /, ...)` followed by the ordinary action arguments. -The policy is bound to this handler only, never serialized or recorded. -Callers may pass it to `actions.call(..., billing_retry=policy)` only for entries -with `supports_billing_retry=True`. Pass the callback only the guarded operation -and its starting billing mode; keep validation and the action lock around both -attempts. With no policy, run once at the action's configured mode. A replacement -method must opt in explicitly; it never inherits retry support from the old body. - -Bound actions still reject uncertain bindings and draining devices. Unbound -actions retain serialization, validation, safe error wrapping, and nested-call -rules. Local proxy status requires a device; cloud proxy status returns a -disconnected status when unbound and queries remote status when bound. - -## Server-side cloud task contract - -`Extension.cloud_native: ClassVar[bool] = False` declares whether a server-side -cloud task can use an extension. Third-party extensions default to false. -Cloud proxies opt in because their configuration is already device state on the -server. CloudMailbox remains false: the task API has no mailbox input. +An extension exposes typed async methods and public `ContextItem` metadata. +Operators borrow explicit extension instances. Only `@function` methods become +tools; calling an undecorated method remains ordinary Python. ```python -from mobilerun.models import CloudCredentialReference, CloudTaskInputs - -async def cloud_task_inputs(self) -> CloudTaskInputs: - return CloudTaskInputs( - credential_references=(CloudCredentialReference("com.example", "login"),) - ) +from mobilerun.core.extensions import Extension, function +from mobilerun.core.operator import Operator + +def fixed_choice(lookup): + async def inbox() -> str: + """Return the inbox label.""" + return await lookup("inbox") + + return (inbox,) + +class Labels(Extension): + @function(to_atomic=fixed_choice) + async def lookup(self, name: str) -> str: + """Return the requested label.""" + return name.upper() + +labels = Labels(name="labels") +(inbox,) = Operator(extensions=[labels]).tools() +assert inbox.name == "labels.inbox" +assert await inbox.invoke({}) == "INBOX" +assert await labels.lookup("archive") == "ARCHIVE" ``` -The default implementation returns `CloudTaskInputs()`. Both models are frozen; -references contain only `package` and `name` strings, never credential values. -The cloud task operator merges references from all bound `cloud_native` extensions, -deduplicating names per package. Non-native extensions are not asked for inputs. -No concrete extension-class checks or vault-specific Extension hooks are needed. - -Action failures remain safely converted to `ExtensionActionError`; there is no -`propagate_exceptions` option. The exception is public `MobilerunError` subclasses -that explicitly declare `value_safe: ClassVar[bool] = True`: actions re-raise them -unchanged so callers can catch typed failures such as `CredentialFieldNotFound`. -Opt in only when every message (including subclass messages) contains no values. -All other failures stay wrapped without backend details. -Wrapped failures expose `ExtensionActionError.cause_type` and include the exception -type plus a value-free category in the message. Timeouts include a finite, -nonnegative numeric `timeout` argument in seconds only when it is not sensitive. -Framework errors without an underlying cause leave `cause_type` empty. - -By default, wrapped errors suppress exception chaining. With the `mobilerun` logger -at DEBUG, nonsensitive actions retain the original cause for diagnostics. Sensitive -actions and their nested calls never attach unsafe backend causes, even at DEBUG. -Opted-in value-safe typed errors retain their identity and attributes. Their -implicit contexts and unsafe explicit causes are stripped, including at DEBUG; -only acyclic value-safe explicit causes survive. Cloud errors opt in per instance -only when constructed with keyword diagnostic fields, not legacy free-text messages. -Backend exceptions from bind/unbind hooks propagate -unchanged. Do not return secrets in action results, context, or cloud task inputs. - -Cross-extension nested action calls are rejected before acquiring another action -lock. Same-extension nested actions remain supported. Sensitive parameters cannot -have defaults; exported schemas remove defaults, examples, and constants from their -parameter schemas and reachable definitions. Failed or cancelled detach hooks -leave uncertain bindings until read-back reconciles the actual proxy state. -Devices and wrappers explicitly reject copying and pickling. - -`close()` marks the extension closing before waiting for in-flight actions, then -releases its resource under the action lock. New and queued actions fail with the -value-safe `ExtensionClosed`; an already-running action can finish same-extension -nested work. Refused detach validation and cancellation before mutation leave the -handle usable. Once detach/cleanup mutation begins, failed or cancelled cleanup -stays closing and can be retried with `close()`. - -Sensitive action values are registered in the shared secret-redaction context -while the body and observers run, including nested sensitive calls. Exported -sensitive schemas also remove `enum` and `pattern` values from reachable definitions; -runtime validation keeps the original constraints. - -When a recorder observes a bound action, it brackets dispatch after argument and -binding validation. It writes one outcome for the outer action, including a -`False` return or exception code, not extra rows for primitives or same-extension -actions it calls. Direct calls through a device or its action catalog use that -facade's recording policy, including calls through `device.extensions[name]`. -Calls on the original extension handle use its bound device. Sensitive -arguments are replaced with `***`; results and exception -messages are not persisted. `wait_for_code()` values are tracked in memory so -later actions and logs can mask the code. Verification reads such as `messages()` -also register codes. `device.known_codes_redactor()` returns a live text redactor -for that device and its facades. Full recording screenshots are not redacted. -Register additional exact sensitive values before dispatch with -`device.register_sensitive_values(values)`. The device and its facades retain -them in memory for recording, live observation, and log redaction. - -Use `with dispatch_guard(predicate):` to authorize declared actions before -execution, including nested extension actions and actions on unrecorded -devices. The predicate receives `ActionInfo` and denies dispatch by raising. -Nested scopes add checks rather than replace them. `supports_billing_retry` -identifies actions with a declared billing retry path, not permission to spend; -cloud billing policy remains enforced at the client boundary. - -Extensions can declare `role: ClassVar[str | None]` (default `None`). The built-in -mailbox and phone-number bases declare `mailbox` and `phone_number`. Device resource -shortcuts select by role, preferring the default `email`/`sms` name, then a unique -match; they never check concrete extension classes. - -See [credentials](../credentials/README.md), [proxies](../proxy/README.md), and [devices](../devices/README.md). +- `@function` and `@function(...)` preserve the typed Python call. `name` and + `description` default to the method name and its first docstring paragraph + (empty without a docstring). +- Tool parameters must be typed and callable by keyword; the result must be + annotated. `Tool.invoke()` validates strict JSON inputs and returns a + JSON-safe result. Use `Tool.validate_arguments(arguments)` for the same strict + validation and typed defaults without dispatch (for example, macro preflight). + Sensitive fields are omitted from the returned model's `repr()` and `str()`. + The model still contains the real values; do not log or serialize it. Direct + Python calls return the original typed result. +- A synchronous `to_atomic` factory receives the bound method once per compile + and returns an ordered iterable of named, zero-parameter async functions. + These replace the parent in `Operator.tools()`; an empty iterable hides it. + Use `compile_tools(extensions, expand_atomics=False)` for canonical replay. + For a zero-argument alias that calls its parent with fixed arguments, return + `bind_atomic(alias, {"name": "inbox"})` from the factory (`bind_atomic` is in + `mobilerun.core.extensions`). The compiler validates the declaration + against the parent tool. `Tool.bound_arguments` exposes a read-only JSON + snapshot of the supplied input keys, including validation aliases, with no + defaults added and sensitive parameters replaced by `"***"`. It is `None` for + canonical tools and aliases without a declared binding; `Tool.is_atomic` + distinguishes aliases even when they reuse the parent's name. + Duplicate canonical names, duplicate visible names, and invalid expansions + raise `ToolCompilationError`. +- Put only public references in alias names, docstrings, and closures. Declare + sensitive inputs with `sensitive_parameters=("parameter",)`, without + defaults or Pydantic field aliases (`alias`, `validation_alias`, or + `serialization_alias`). Atomic tools inherit the parent's sensitivity metadata. + Use `tool_dispatch_guard` for value-free authorization before alias and + canonical dispatch, including typed calls; it does not grant spending permission. + +| File | Purpose | +| --- | --- | +| `functions.py` | `@function` declarations and `bind_atomic` | +| `tool.py` | Tool descriptor and validated invocation | +| `helpers/compiler.py` | Ordered tool discovery, schemas, and atomic expansion | +| `base.py` | Extension name, context, and lifecycle | + +Call `await extension.close()` to release resources owned by the extension. +An extension that needs a phone receives it explicitly; the operator does not +attach or close borrowed extensions. See [operators](../operator/README.md) for +composition and context. diff --git a/mobilerun/core/extensions/__init__.py b/mobilerun/core/extensions/__init__.py index 44de4e054..0fdd9c4e1 100644 --- a/mobilerun/core/extensions/__init__.py +++ b/mobilerun/core/extensions/__init__.py @@ -1,25 +1,27 @@ -"""Typed standalone extensions: bind explicitly; discover actions and context.""" +"""Standalone extensions and their declared tools.""" -from .actions import ( - Action, - ActionInfo, - ActionSet, - BillingRetry, - action, - device_action, - dispatch_guard, - iter_sensitive_values, +from mobilerun.errors.tools import ( + ToolArgumentsError, + ToolCompilationError, + ToolInvocationError, ) +from mobilerun.models.tool_call import ToolCallInfo +from mobilerun.utils.tools.dispatch import tool_dispatch_guard + from .base import Extension +from .functions import bind_atomic, function +from .helpers.compiler import compile_tools +from .tool import Tool __all__ = [ - "Action", - "ActionInfo", - "ActionSet", - "BillingRetry", "Extension", - "action", - "device_action", - "dispatch_guard", - "iter_sensitive_values", + "Tool", + "ToolArgumentsError", + "ToolCallInfo", + "ToolCompilationError", + "ToolInvocationError", + "bind_atomic", + "compile_tools", + "function", + "tool_dispatch_guard", ] diff --git a/mobilerun/core/extensions/actions.py b/mobilerun/core/extensions/actions.py deleted file mode 100644 index c8cdb5f26..000000000 --- a/mobilerun/core/extensions/actions.py +++ /dev/null @@ -1,427 +0,0 @@ -"""Typed async action declarations and consumer-independent catalogs.""" - -from __future__ import annotations - -import asyncio -import inspect -from collections.abc import Awaitable, Callable, Iterator, Mapping -from contextlib import contextmanager -from contextvars import ContextVar -from dataclasses import dataclass, field, fields, is_dataclass -from enum import Enum -from functools import wraps -from typing import ( - TYPE_CHECKING, - Any, - Concatenate, - Literal, - ParamSpec, - Protocol, - TypeVar, - cast, - get_type_hints, - overload, -) - -from pydantic import BaseModel, ConfigDict, TypeAdapter, ValidationError, create_model - -from mobilerun.core.extensions.registry import invoking_facade -from mobilerun.errors.operators import ExtensionActionError -from mobilerun.models.billing import Billing -from mobilerun.models.context import JSONValue - -if TYPE_CHECKING: - from mobilerun.core.devices.base import Device - from mobilerun.core.extensions.base import Extension - -P = ParamSpec("P") -R = TypeVar("R") -S = TypeVar("S") -Audience = Literal["python", "operator", "cli"] - - -@dataclass(frozen=True) -class ActionInfo: - """Value-free metadata supplied to pre-dispatch authorization guards.""" - - extension_role: str | None - extension_name: str | None - action_name: str - supports_billing_retry: bool - - -_dispatch_guards: ContextVar[tuple[Callable[[ActionInfo], None], ...]] = ContextVar( - "extension_dispatch_guards", default=() -) - - -@contextmanager -def dispatch_guard(predicate: Callable[[ActionInfo], None]) -> Iterator[None]: - """Authorize each declared action before dispatch; nested guards accumulate.""" - token = _dispatch_guards.set((*_dispatch_guards.get(), predicate)) - try: - yield - finally: - _dispatch_guards.reset(token) - - -def _authorize_dispatch(info: ActionInfo) -> None: - for predicate in _dispatch_guards.get(): - predicate(info) - - -class BillingRetry(Protocol): - """Run a preflight-guarded operation, retrying only with authorized billing.""" - - def __call__( - self, operation: Callable[[Billing], Awaitable[R]], billing: Billing, / - ) -> Awaitable[tuple[R, Billing]]: ... - - -@dataclass(frozen=True) -class Declaration: - public: bool = True - sensitive_parameters: frozenset[str] = frozenset() - requires_device: bool = False - - -_RetryHandler = Callable[Concatenate[S, BillingRetry, P], Awaitable[R]] -_RetryCall = Callable[[BillingRetry, dict[str, Any]], Awaitable[object]] - - -@overload -def action( - fn: Callable[P, Awaitable[R]], - *, - public: bool = True, - sensitive_parameters: frozenset[str] = frozenset(), -) -> Callable[P, Awaitable[R]]: ... - - -@overload -def action( - *, public: bool = True, sensitive_parameters: frozenset[str] = frozenset() -) -> Callable[[Callable[P, Awaitable[R]]], Callable[P, Awaitable[R]]]: ... - - -@overload -def action( - *, - public: bool = True, - sensitive_parameters: frozenset[str] = frozenset(), - billing_retry: _RetryHandler[S, P, R], -) -> Callable[ - [Callable[Concatenate[S, P], Awaitable[R]]], - Callable[Concatenate[S, P], Awaitable[R]], -]: ... - - -def action( - fn: Callable[..., Any] | None = None, - *, - public: bool = True, - sensitive_parameters: frozenset[str] = frozenset(), - billing_retry: Callable[..., Awaitable[Any]] | None = None, -) -> Any: - """Declare a documented async extension method; direct calls stay typed.""" - decorate = _decorate( - Declaration(public, frozenset(sensitive_parameters)), - billing_retry=billing_retry, - ) - return decorate if fn is None else decorate(fn) - - -@overload -def device_action( - fn: Callable[Concatenate[S, Device, P], Awaitable[R]], - *, - public: bool = True, - sensitive_parameters: frozenset[str] = frozenset(), -) -> Callable[Concatenate[S, P], Awaitable[R]]: ... - - -@overload -def device_action( - *, public: bool = True, sensitive_parameters: frozenset[str] = frozenset() -) -> Callable[ - [Callable[Concatenate[S, Device, P], Awaitable[R]]], - Callable[Concatenate[S, P], Awaitable[R]], -]: ... - - -def device_action( - fn: Callable[..., Any] | None = None, - *, - public: bool = True, - sensitive_parameters: frozenset[str] = frozenset(), -) -> Any: - """Require and inject the bound facade, hiding it from public arguments.""" - decorate = _decorate(Declaration(public, frozenset(sensitive_parameters), True)) - return decorate if fn is None else decorate(fn) - - -def _decorate( - declaration: Declaration, - *, - billing_retry: Callable[..., Awaitable[Any]] | None = None, -) -> Callable[[Callable[..., Any]], Callable[..., Any]]: - - def decorate(fn: Callable[..., Any]) -> Callable[..., Any]: - if not inspect.iscoroutinefunction(fn): - raise TypeError("Actions must be async methods") - if not inspect.getdoc(fn): - raise TypeError("Actions require a docstring") - signature = inspect.signature(fn) - for name, parameter in signature.parameters.items(): - if ( - name in declaration.sensitive_parameters - and parameter.default is not parameter.empty - ): - raise TypeError("Sensitive action parameters cannot declare a default") - - if declaration.requires_device: - parameters = list(signature.parameters.values()) - if ( - len(parameters) < 2 - or parameters[1].name != "device" - or not ( - parameters[1].annotation == "Device" - or parameters[1].annotation is _device_type() - ) - or parameters[1].kind - not in ( - inspect.Parameter.POSITIONAL_ONLY, - inspect.Parameter.POSITIONAL_OR_KEYWORD, - ) - ): - raise TypeError( - "Device actions require device: Device immediately after self" - ) - signature = signature.replace(parameters=[parameters[0], *parameters[2:]]) - - @wraps(fn) - async def invoke(*args: Any, **kwargs: Any) -> Any: - extension = cast("Extension", args[0]) - return await extension._invoke_action(fn, args, kwargs) - - invoke.__dict__["_extension_action"] = declaration - if billing_retry is not None: - - async def retry_call( - extension: Extension, policy: BillingRetry, arguments: dict[str, Any] - ) -> object: - @wraps(fn) - async def authorized(owner: Extension, /, **validated: Any) -> object: - return await billing_retry(owner, policy, **validated) - - return await extension._invoke_action( - authorized, (extension,), arguments - ) - - # wraps() copies metadata; only this exact wrapper grants consent handling. - invoke.__dict__["_billing_handler"] = (invoke, retry_call) - invoke.__dict__["__signature__"] = signature - return invoke - - return decorate - - -def _device_type() -> type: - # Lazy import avoids the Device -> Extension -> actions import cycle. - from mobilerun.core.devices.base import Device - - return Device - - -@dataclass(frozen=True) -class Action: - name: str - owner: str - description: str - input_schema: Mapping[str, Any] - output_schema: Mapping[str, Any] - public: bool - sensitive_parameters: frozenset[str] - requires_device: bool - _call: Callable[..., Awaitable[Any]] = field(repr=False, compare=False) - _arguments: type = field(repr=False, compare=False) - _returns: TypeAdapter[Any] = field(repr=False, compare=False) - _retry_call: _RetryCall | None = field(default=None, repr=False, compare=False) - - @property - def supports_billing_retry(self) -> bool: - return self._retry_call is not None - - @classmethod - def compile( - cls, - owner: str, - name: str, - fn: Callable[..., Awaitable[Any]], - declaration: Declaration, - *, - description: str | None = None, - retry_call: _RetryCall | None = None, - ) -> Action: - signature = inspect.signature(fn) - raw = inspect.unwrap(fn) - hints = get_type_hints( - raw, - globalns={**raw.__globals__, "Device": _device_type()}, - include_extras=True, - ) - fields: dict[str, Any] = {} - for parameter in signature.parameters.values(): - if parameter.name == "self": - continue - if parameter.kind in ( - parameter.POSITIONAL_ONLY, - parameter.VAR_POSITIONAL, - parameter.VAR_KEYWORD, - ): - raise TypeError(f"Action {name} has an unsupported parameter interface") - if parameter.name not in hints: - raise TypeError(f"Action {name} requires typed parameters") - default = ... if parameter.default is parameter.empty else parameter.default - fields[parameter.name] = (hints[parameter.name], default) - if "return" not in hints: - raise TypeError(f"Action {name} requires a return annotation") - if not declaration.sensitive_parameters <= fields.keys(): - raise TypeError(f"Action {name} declares an unknown sensitive parameter") - arguments = create_model( - f"{owner}_{name}_Arguments", - __config__=ConfigDict(extra="forbid"), - **fields, - ) - returns = TypeAdapter(hints["return"]) - input_schema = arguments.model_json_schema() - _sanitize_sensitive_schema(input_schema, declaration.sensitive_parameters) - return cls( - f"{owner}.{name}", - owner, - description or inspect.getdoc(fn) or name, - input_schema, - returns.json_schema(), - declaration.public, - declaration.sensitive_parameters, - declaration.requires_device, - fn, - arguments, - returns, - retry_call, - ) - - def validate(self, arguments: Mapping[str, Any]) -> dict[str, Any]: - try: - model = self._arguments.model_validate(dict(arguments)) - return {name: model.__dict__[name] for name in type(model).model_fields} - except ValidationError: - raise ExtensionActionError(f"Invalid arguments for {self.name}") from None - - def validate_result(self, result: object) -> object: - try: - return self._returns.validate_python(result) - except ValidationError: - raise ExtensionActionError(f"Invalid result from {self.name}") from None - - def serialize(self, result: object) -> JSONValue: - return cast(JSONValue, self._returns.dump_python(result, mode="json")) - - -def iter_sensitive_values(value: object) -> Iterator[str]: - """Yield scalar strings from nested values, including mapping keys.""" - if isinstance(value, Enum): - yield from iter_sensitive_values(value.value) - elif isinstance(value, BaseModel): - yield from iter_sensitive_values(value.model_dump()) - elif is_dataclass(value) and not isinstance(value, type): - for item in fields(value): - yield from iter_sensitive_values(getattr(value, item.name)) - elif isinstance(value, Mapping): - for key, item in value.items(): - yield from iter_sensitive_values(key) - yield from iter_sensitive_values(item) - elif isinstance(value, (list, tuple, set, frozenset)): - for item in value: - yield from iter_sensitive_values(item) - elif value is not None: - yield str(value) - - -def _sanitize_sensitive_schema(schema: dict[str, Any], names: frozenset[str]) -> None: - definitions = schema.get("$defs", {}) - visited: set[str] = set() - - def scrub(node: Any) -> None: - if isinstance(node, dict): - for key in ("default", "examples", "example", "const", "enum", "pattern"): - node.pop(key, None) - reference = node.get("$ref") - if isinstance(reference, str) and reference.startswith("#/$defs/"): - name = reference.removeprefix("#/$defs/") - if name not in visited and name in definitions: - visited.add(name) - scrub(definitions[name]) - for child in node.values(): - scrub(child) - elif isinstance(node, list): - for child in node: - scrub(child) - - for name in names: - scrub(schema.get("properties", {}).get(name, {})) - - -class ActionSet: - """A live catalog; stale callers still validate current binding state.""" - - def __init__( - self, source: Device | Extension, *, facade: Device | None = None - ) -> None: - self._source = source - self._facade = facade - - def list(self, *, audience: Audience = "python") -> tuple[Action, ...]: - return tuple( - entry - for entry in self._source._action_entries() - if audience == "python" or entry.public - ) - - def get(self, name: str) -> Action: - for entry in self.list(): - if entry.name == name: - return entry - raise ExtensionActionError(f"Unknown action: {name}") - - async def call( - self, - name: str, - arguments: Mapping[str, JSONValue], - *, - audience: Audience = "python", - timeout: float | None = None, - billing_retry: BillingRetry | None = None, - ) -> object: - """Invoke a validated action, optionally providing billing consent policy.""" - entry = self.get(name) - if audience != "python" and not entry.public: - raise ExtensionActionError(f"Action {name} is restricted") - validated = entry.validate(arguments) - if entry.owner == "device": - _authorize_dispatch(ActionInfo(None, None, name.partition(".")[2], False)) - token = invoking_facade.set(self._facade) if self._facade is not None else None - try: - async with asyncio.timeout(timeout): - if billing_retry is not None: - if entry._retry_call is None: - raise ExtensionActionError( - f"Action {name} does not support billing retry" - ) - return entry.validate_result( - await entry._retry_call(billing_retry, validated) - ) - return entry.validate_result(await entry._call(**validated)) - finally: - if token is not None: - invoking_facade.reset(token) diff --git a/mobilerun/core/extensions/base.py b/mobilerun/core/extensions/base.py index ddac3ccc2..d38a572e1 100644 --- a/mobilerun/core/extensions/base.py +++ b/mobilerun/core/extensions/base.py @@ -1,637 +1,47 @@ -"""Extension-owned checks and atomic local relationship transitions.""" +"""Names, context and resource ownership for standalone extensions.""" from __future__ import annotations import asyncio -import inspect -import logging import re -from collections.abc import ( - AsyncGenerator, - Awaitable, - Callable, - Generator, - Iterator, - Sequence, -) -from contextlib import AsyncExitStack, ExitStack, contextmanager, nullcontext -from contextvars import ContextVar -from functools import partial, wraps -from typing import TYPE_CHECKING, Any, ClassVar, Self, cast +from collections.abc import Sequence +from typing import ClassVar -from pydantic import BaseModel - -from mobilerun.core.extensions.actions import ( - Action, - ActionInfo, - ActionSet, - Declaration, - _authorize_dispatch, - action, - device_action, -) -from mobilerun.core.extensions.registry import ActionOutcome, Binding, invoking_facade -from mobilerun.errors.base import CloudError, MobilerunError, is_value_safe -from mobilerun.errors.operators import ( - ExtensionActionError, - ExtensionClosed, - ExtensionConflict, - ExtensionNotBound, -) from mobilerun.models.cloud_task import CloudTaskInputs from mobilerun.models.context import ContextItem -from mobilerun.utils.codes import verification_read_codes -from mobilerun.utils.redaction import mask_step_args - -if TYPE_CHECKING: - from mobilerun.core.devices.base import Device - -_active: ContextVar[Extension | None] = ContextVar("extension_action", default=None) -_sensitive_action: ContextVar[bool] = ContextVar( - "sensitive_extension_action", default=False -) -_observed_outcome: ContextVar[ActionOutcome | None] = ContextVar( - "observed_extension_outcome", default=None -) - - -def _inside_bound_action(device: Device) -> bool: - """Whether a named action is executing on this device or a sibling facade.""" - active = _active.get() - bound = active.device if active is not None else None - return bound is not None and bound._extension_state is device._extension_state - - -def _redact_bound_arguments(device: Device) -> None: - outcome = _observed_outcome.get() - if outcome is not None and _inside_bound_action(device): - outcome.redact_arguments() - - -class _ExtensionAccess: - """Retain the invoking device for actions reached through a facade.""" - - def __init__(self, extension: Extension, facade: Device) -> None: - self._extension = extension - self._facade = facade - - @property - def __class__(self) -> type[Extension]: - return type(self._extension) - - @property - def actions(self) -> ActionSet: - return ActionSet(self._extension, facade=self._facade) - - @contextmanager - def _invocation(self) -> Iterator[None]: - from mobilerun.core.runs import recording_scope - - token = invoking_facade.set(self._facade) - try: - with recording_scope(enabled=self._facade.recording_allowed()): - yield - finally: - invoking_facade.reset(token) - - def __getattr__(self, name: str) -> Any: - if name.startswith("_"): - return getattr(self._extension, name) - with self._invocation(): - member = getattr(self._extension, name) - if not callable(member): - return member - - if inspect.iscoroutinefunction(member): - - @wraps(member) - async def invoke(*args: Any, **kwargs: Any) -> Any: - with self._invocation(): - return self._wrap_lazy(await member(*args, **kwargs)) - - return invoke - - @wraps(member) - def call(*args: Any, **kwargs: Any) -> Any: - with self._invocation(): - result = member(*args, **kwargs) - if inspect.isawaitable(result): - - async def await_result() -> Any: - with self._invocation(): - return self._wrap_lazy(await result) - - return await_result() - return self._wrap_lazy(result) - - return call - - def _wrap_lazy(self, result: Any) -> Any: - if inspect.isasyncgen(result): - return self._iterate_async(result) - if inspect.isgenerator(result): - return self._iterate(result) - return result - - def _iterate(self, iterator: Generator[Any, Any, Any]) -> Generator[Any, Any, Any]: - advance: Callable[[], Any] = partial(next, iterator) - try: - while True: - with self._invocation(): - item = advance() - try: - value = yield item - except GeneratorExit: - raise - except BaseException as error: - advance = partial(iterator.throw, error) - else: - advance = partial(iterator.send, value) - except StopIteration as stop: - return stop.value - finally: - with self._invocation(): - iterator.close() - - async def _iterate_async( - self, iterator: AsyncGenerator[Any, Any] - ) -> AsyncGenerator[Any, Any]: - advance: Callable[[], Awaitable[Any]] = iterator.__anext__ - try: - while True: - with self._invocation(): - item = await advance() - try: - value = yield item - except GeneratorExit: - raise - except BaseException as error: - advance = partial(iterator.athrow, error) - else: - advance = partial(iterator.asend, value) - except StopAsyncIteration: - return - finally: - with self._invocation(): - await iterator.aclose() - - -def _sanitize_safe_chain(error: MobilerunError) -> None: - """Keep safe explicit causes only; discard implicit backend contexts.""" - seen: set[int] = set() - current: BaseException = error - while True: - seen.add(id(current)) - # Notes are free-text provider data, including on otherwise safe causes. - current.__notes__ = [] - current.__context__ = None - current.__suppress_context__ = True - cause = current.__cause__ - if ( - not isinstance(cause, MobilerunError) - or not is_value_safe(cause) - or id(cause) in seen - ): - current.__cause__ = None - return - current = cause class Extension: - """Standalone resource linked through one shared binding coordinator.""" + """A standalone resource that can contribute tools and context to operators.""" default_name: ClassVar[str] = "extension" - exclusive: ClassVar[str | None] = None cloud_native: ClassVar[bool] = False - role: ClassVar[str | None] = None - _declarations: ClassVar[dict[str, Declaration]] = {} - - def __init_subclass__(cls, **kwargs: Any) -> None: - super().__init_subclass__(**kwargs) - declarations: dict[str, Declaration] = {} - for base in reversed(cls.__mro__[1:]): - declarations.update(vars(base).get("_declarations", {})) - for name, member in vars(cls).items(): - if inspect.isfunction(member) and "_extension_action" in member.__dict__: - declarations[name] = member.__dict__["_extension_action"] - elif inspect.isfunction(member) and name in declarations: - declaration = declarations[name] - setattr( - cls, - name, - (device_action if declaration.requires_device else action)( - public=declaration.public, - sensitive_parameters=declaration.sensitive_parameters, - )(member), - ) - cls._declarations = declarations def __init__(self, *, name: str | None = None) -> None: self._name = self.default_name if name is None else name if not re.fullmatch(r"[a-z][a-z0-9_]{0,31}", self._name): raise ValueError("Extension names must match [a-z][a-z0-9_]{0,31}") - self._binding: Binding | None = None self._lifecycle_lock = asyncio.Lock() - self._action_lock = asyncio.Lock() self._closed = False - self._closing = False - self._close_mutation_started = False @property def name(self) -> str: return self._name - @property - def device(self) -> Device | None: - if self._binding is None: - return None - if self._binding.uncertain: - raise ExtensionNotBound(f"Extension '{self.name}' binding is uncertain") - return self._binding.facade - - @property - def actions(self) -> ActionSet: - return ActionSet(self) - - def _action_entries(self) -> tuple[Action, ...]: - entries = [] - for name, declaration in self._declarations.items(): - member = inspect.getattr_static(type(self), name) - target, retry = getattr(member, "_billing_handler", (None, None)) - entries.append( - Action.compile( - self.name, - name, - member.__get__(self), - declaration, - retry_call=retry.__get__(self) if target is member else None, - ) - ) - return tuple(entries) - - async def check_bind(self, device: Device) -> Sequence[Extension]: - return tuple( - other - for other in device._extension_state.view.values() - if self.exclusive is not None - and other.exclusive == self.exclusive - and other is not self - ) - - async def on_bind(self, device: Device) -> None: - """Perform backend linking; no local registry mutation.""" - - async def on_unbind(self, device: Device) -> None: - """Remove backend linking; no local registry mutation.""" - - async def _check_unbind(self, device: Device) -> None: - """Reject a detach before starting a potentially mutating hook.""" - - async def on_close(self) -> None: - """Release only resources owned by this extension.""" - async def context(self) -> Sequence[ContextItem]: + """Return public metadata for an operator.""" return () async def cloud_task_inputs(self) -> CloudTaskInputs: """Contribute server-side task references, never secret values.""" return CloudTaskInputs() - def _can_switch(self, device: Device) -> bool: - return False - - async def _reconcile_bind_failure( - self, device: Device, failure: BaseException - ) -> None: - """Resource-specific read-back after an ambiguous backend mutation.""" - - def _matches_remote(self, observed: object) -> bool: - """Whether a remote binding observation identifies this resource.""" - return False - - def _observe_remote_binding(self, device: Device, observed: object | None) -> None: - """Update resource-owned backend state after binding read-back.""" - - def _check_name(self, device: Device, conflicts: Sequence[Extension] = ()) -> None: - occupied = device._extension_state.view.get(self.name) - if ( - self.name == "device" - or any(self.name in vars(base) for base in type(device).__mro__) - or self.name in vars(device) - ): - raise ExtensionConflict(f"Extension name '{self.name}' is reserved") - if occupied is not None and occupied not in conflicts: - raise ExtensionConflict(f"Extension name '{self.name}' is already bound") - - async def bind( - self, - device: Device, - *, - close_on_device_close: bool = False, - force: bool = False, - ) -> Self: - if _active.get() is not None: - raise ExtensionConflict("Binding cannot change inside an extension action") - async with self._lifecycle_lock: - registry = device._extension_state - async with registry.lock: - if self._closed or self._closing or registry.closing: - raise ExtensionConflict( - "Cannot bind a closed extension or closing device" - ) - if self._binding is not None: - if self._binding.facade._unwrap() is device._unwrap(): - if self._binding.uncertain: - raise ExtensionConflict( - "Binding is uncertain; unbind it first" - ) - return self - raise ExtensionConflict( - f"Extension '{self.name}' is already bound to another device" - ) - conflicts = tuple(await self.check_bind(device)) - self._check_name(device, conflicts) - if conflicts and not force: - old = conflicts[0] - raise ExtensionConflict( - f"{device.identifier or 'device'} already has {self.exclusive} '{old.name}'; unbind it first" - ) - self._action_entries() - removed: list[Binding] = [] - registry.force = force - registry.switching = bool( - conflicts and force and self._can_switch(device) - ) - detaching: Binding | None = None - try: - for old in conflicts: - async with old._action_lock: - binding = registry.bindings[old.name] - await old._check_unbind(binding.facade) - detaching = binding - await old.on_unbind(binding.facade) - registry.bindings.pop(old.name) - # Keep the relationship until the transition settles: - # concurrent close/unbind must wait for this registry - # lock rather than release a rollback resource early. - binding.uncertain = True - removed.append(binding) - detaching = None - await self.on_bind(device) - except BaseException as failure: - registry.switching = False - if detaching is not None: - detaching.uncertain = True - for binding in removed: - try: - async with binding.extension._action_lock: - await binding.extension.on_bind(binding.facade) - binding.uncertain = False - except BaseException: - binding.uncertain = True - failure.add_note( - f"Could not restore extension '{binding.extension.name}'; checking remote state" - ) - registry.bindings[binding.extension.name] = binding - binding.extension._binding = binding - if detaching is not None: - await detaching.extension._finish_reconciliation( - device, failure - ) - for binding in removed: - # A successful restore response does not prove remote - # truth. Read back through each restored resource's hook. - await binding.extension._finish_reconciliation( - binding.facade, failure - ) - if detaching is None and not removed: - await self._finish_reconciliation(device, failure) - raise failure - finally: - registry.force = False - registry.switching = False - binding = Binding(self, device, close_on_device_close) - for previous in removed: - previous.extension._binding = None - registry.bindings[self.name] = binding - self._binding = binding - return self - - async def unbind(self) -> None: - if _active.get() is not None: - raise ExtensionConflict("Binding cannot change inside an extension action") - async with self._lifecycle_lock: - await self._unbind_locked() - - async def _finish_reconciliation( - self, device: Device, failure: BaseException - ) -> None: - # Hold the registry lock until read-back finishes, including repeated - # cancellation, so no competing transition observes stale certainty. - reconciliation = asyncio.create_task( - self._reconcile_bind_failure(device, failure) - ) - while not reconciliation.done(): - try: - await asyncio.shield(reconciliation) - except asyncio.CancelledError: - continue - reconciliation.result() - - async def _unbind_locked(self, *, for_close: bool = False) -> None: - if self._binding is None: - return - binding = self._binding - registry = binding.facade._extension_state - async with registry.lock: - if self._binding is not binding: - return # A concurrent force transition already detached us. - async with self._action_lock: - await self._check_unbind(binding.facade) - try: - if for_close: - self._close_mutation_started = True - await self.on_unbind(binding.facade) - except BaseException as failure: - binding.uncertain = True - await self._finish_reconciliation(binding.facade, failure) - raise - registry.bindings.pop(self.name) - self._binding = None - async def close(self) -> None: - if _active.get() is not None: - raise ExtensionConflict("Binding cannot change inside an extension action") - try: - async with self._lifecycle_lock: - if self._closed: - return - if not self._closing and self._binding is not None: - binding = self._binding - async with binding.facade._extension_state.lock: - if self._binding is binding: - await self._check_unbind(binding.facade) - self._closing = True - await self._unbind_locked(for_close=True) - async with self._action_lock: - self._close_mutation_started = True - await self.on_close() - self._closed = True - except BaseException: - if not self._close_mutation_started: - self._closing = False - raise - - async def _invoke_action( - self, - fn: Callable[..., Awaitable[Any]], - args: tuple[Any, ...], - kwargs: dict[str, Any], - ) -> object: - active = _active.get() - if active is not None and active is not self: - raise ExtensionActionError( - "Cross-extension nested action calls are not allowed" - ) - nested = active is self - if self._closed or (self._closing and not nested): - raise ExtensionClosed(f"Extension '{self.name}' is closing or closed") - entry = self.actions.get(f"{self.name}.{fn.__name__}") - - def device_for_call() -> Device | None: - if self._closed or (self._closing and not nested): - raise ExtensionClosed(f"Extension '{self.name}' is closing or closed") - device = self.device - if device is not None and device._extension_state.closing: - raise ExtensionNotBound("Device is closing") - if device is None and entry.requires_device: - raise ExtensionNotBound( - f"'{entry.name}' needs a bound device; await {self.name}.bind(device) first" - ) - return device - - from mobilerun.core.extensions.actions import iter_sensitive_values - from mobilerun.core.runs import recording_scope - from mobilerun.utils.redaction import secret_scope + """Run cleanup once after a successful close.""" + async with self._lifecycle_lock: + if not self._closed: + await self.on_close() + self._closed = True - lock = nullcontext() if nested else self._action_lock - async with lock, AsyncExitStack() as dispatch_scope: - device = device_for_call() - facade = invoking_facade.get() - if device is not None and ( - facade is None or facade._extension_state is not device._extension_state - ): - facade = device - if facade is not None and not facade.recording_allowed(): - dispatch_scope.enter_context(recording_scope(enabled=False)) - values = inspect.signature(entry._call).bind(*args[1:], **kwargs) - values.apply_defaults() - arguments = { - key: value for key, value in values.arguments.items() if key != "self" - } - validated = entry.validate(arguments) - _authorize_dispatch( - ActionInfo( - self.role, self.name, fn.__name__, entry.supports_billing_retry - ) - ) - token = _active.set(self) - sensitivity_token = _sensitive_action.set( - _sensitive_action.get() or bool(entry.sensitive_parameters) - ) - outcome = ActionOutcome() - outcome_token = _observed_outcome.set(outcome) if not nested else None - try: - with ExitStack() as secrets: - for key in entry.sensitive_parameters: - for value in iter_sensitive_values(validated[key]): - secrets.enter_context(secret_scope(value)) - async with AsyncExitStack() as stack: - if device is not None: - registry = device._extension_state - if entry.sensitive_parameters: - registry.sensitive_ui = True - if nested: - _redact_bound_arguments(device) - recorder = ( - facade.recording_device() - if facade is not None and facade.recording_allowed() - else None - ) - observe = ( - registry.observers.get(recorder) - if recorder is not None and not nested - else None - ) - if observe is not None: - model = cast(type[BaseModel], entry._arguments) - safe = model.model_construct(**validated).model_dump( - mode="json", exclude=set(entry.sensitive_parameters) - ) - safe.update( - dict.fromkeys(entry.sensitive_parameters, "***") - ) - safe = mask_step_args( - safe, - contains_code=registry.matches_sensitive_argument, - ) - outcome.arguments = safe - await stack.enter_async_context( - observe(facade or device, entry.name, safe, outcome) - ) - try: - result = entry.validate_result( - await fn(self, device, **validated) - if entry.requires_device - else await fn(self, **validated) - ) - except BaseException as error: - outcome.error = type(error).__name__ - raise - if result is False: - outcome.error = "returned_false" - if device is not None: - device._extension_state.remember_verification_codes( - *verification_read_codes(self.role, fn.__name__, result) - ) - return result - except Exception as error: - if isinstance(error, MobilerunError) and is_value_safe(error): - _sanitize_safe_chain(error) - raise - cause_type = type(error).__name__ - category = "unexpected failure" - if isinstance(error, TimeoutError): - category = "timed out" - timeout = validated.get("timeout") - if ( - "timeout" not in entry.sensitive_parameters - and timeout is not None - and type(timeout) in (int, float) - and 0 <= timeout < float("inf") - ): - seconds = ( - str(timeout) if type(timeout) is int else f"{timeout:g}" - ) - category += f" after {seconds}s" - elif isinstance(error, CloudError): - category = "cloud request failed" - elif isinstance(error, ConnectionError): - category = "connection failed" - wrapped = ExtensionActionError( - f"Action {entry.name} failed: {cause_type} ({category})", - cause_type=cause_type, - ) - if ( - logging.getLogger("mobilerun").isEnabledFor(logging.DEBUG) - and not _sensitive_action.get() - # A rejected safe-rendering claim is not a debug escape hatch. - and not isinstance(error, CloudError) - ): - raise wrapped from error - raise wrapped from None - finally: - if outcome_token is not None: - _observed_outcome.reset(outcome_token) - _sensitive_action.reset(sensitivity_token) - _active.reset(token) + async def on_close(self) -> None: + """Release only resources owned by this extension.""" diff --git a/mobilerun/core/extensions/functions.py b/mobilerun/core/extensions/functions.py new file mode 100644 index 000000000..3b1784e59 --- /dev/null +++ b/mobilerun/core/extensions/functions.py @@ -0,0 +1,136 @@ +"""Declare async extension functions and authorize typed dispatch.""" + +from __future__ import annotations + +import inspect +import re +from collections.abc import Awaitable, Callable, Iterable, Mapping, Sequence +from dataclasses import dataclass, field +from functools import wraps +from typing import Any, ParamSpec, TypeAlias, TypeVar, overload + +from mobilerun.core.extensions.base import Extension +from mobilerun.errors.tools import ToolInvocationError +from mobilerun.models.context import JSONValue +from mobilerun.models.tool_call import ToolCallInfo +from mobilerun.utils.tools.dispatch import authorize_tool +from mobilerun.utils.tools.redaction import tool_secret_scope + +P = ParamSpec("P") +R = TypeVar("R") +AtomicFactory: TypeAlias = Callable[ + [Callable[..., Awaitable[Any]]], Iterable[Callable[[], Awaitable[Any]]] +] + + +@dataclass(frozen=True) +class FunctionDeclaration: + name: str + description: str + to_atomic: AtomicFactory | None = field(repr=False) + sensitive_parameters: frozenset[str] + + +def function_name(method: Callable[..., Any], name: str | None = None) -> str: + candidate = method.__name__ if name is None else name + if not isinstance(candidate, str) or not re.fullmatch( + r"[A-Za-z_][A-Za-z0-9_]*", candidate + ): + raise ValueError("Tool names must be ASCII identifiers") + return candidate + + +def function_description(method: Callable[..., Any]) -> str: + lines: list[str] = [] + for line in (inspect.getdoc(method) or "").splitlines(): + if not line.strip(): + break + lines.append(line.strip()) + return " ".join(lines) + + +def get_function_declaration(method: object) -> FunctionDeclaration | None: + metadata = getattr(method, "__mobilerun_function__", None) + return metadata if isinstance(metadata, FunctionDeclaration) else None + + +def bind_atomic( + alias: Callable[[], Awaitable[R]], arguments: Mapping[str, JSONValue] +) -> Callable[[], Awaitable[R]]: + """Declare the canonical JSON arguments used by a zero-argument alias.""" + + @wraps(alias) + async def declared() -> R: + return await alias() + + declared.__dict__["__mobilerun_atomic_binding__"] = (alias, dict(arguments)) + return declared + + +@overload +def function(fn: Callable[P, Awaitable[R]], /) -> Callable[P, Awaitable[R]]: ... + + +@overload +def function( + *, + name: str | None = None, + description: str | None = None, + to_atomic: AtomicFactory | None = None, + sensitive_parameters: Sequence[str] = (), +) -> Callable[[Callable[P, Awaitable[R]]], Callable[P, Awaitable[R]]]: ... + + +def function( + fn: Callable[P, Awaitable[R]] | None = None, + /, + *, + name: str | None = None, + description: str | None = None, + to_atomic: AtomicFactory | None = None, + sensitive_parameters: Sequence[str] = (), +) -> ( + Callable[P, Awaitable[R]] + | Callable[[Callable[P, Awaitable[R]]], Callable[P, Awaitable[R]]] +): + """Expose an async method, optionally replacing its tool with atomic aliases.""" + + def decorate(method: Callable[P, Awaitable[R]]) -> Callable[P, Awaitable[R]]: + if not inspect.iscoroutinefunction(method): + raise TypeError("Tool functions must be async") + signature = inspect.signature(method) + sensitive = frozenset(sensitive_parameters) + if sensitive - signature.parameters.keys(): + raise TypeError("Unknown sensitive tool parameter") + if any( + signature.parameters[key].default is not inspect.Parameter.empty + for key in sensitive + ): + raise TypeError("Sensitive tool parameters cannot declare a default") + declaration = FunctionDeclaration( + function_name(method, name), + function_description(method) if description is None else description, + to_atomic, + sensitive, + ) + + @wraps(method) + async def guarded(*args: P.args, **kwargs: P.kwargs) -> R: + bound = signature.bind(*args, **kwargs) + receiver = next(iter(bound.arguments.values()), None) + label = declaration.name + if isinstance(receiver, Extension): + label = f"{receiver.name}.{declaration.name}" + authorize_tool(ToolCallInfo(label, label, sensitive)) + try: + with tool_secret_scope(bound.arguments, sensitive): + return await method(*args, **kwargs) + except Exception: + pass + # Raise outside the handler so raw provider errors are not chained. + raise ToolInvocationError(f"Tool '{label}' failed") from None + + guarded.__dict__["__mobilerun_function__"] = declaration + return guarded + + return decorate if fn is None else decorate(fn) diff --git a/mobilerun/core/extensions/helpers/compiler.py b/mobilerun/core/extensions/helpers/compiler.py new file mode 100644 index 000000000..6029b099c --- /dev/null +++ b/mobilerun/core/extensions/helpers/compiler.py @@ -0,0 +1,217 @@ +"""Compile ordered tool descriptors from explicitly decorated extensions.""" + +from __future__ import annotations + +import inspect +import json +import re +from collections.abc import Awaitable, Callable, Iterable, Mapping, Sequence, Set +from contextlib import ExitStack +from dataclasses import replace +from typing import TYPE_CHECKING, Any, get_type_hints + +from pydantic import ConfigDict, Field, TypeAdapter, create_model + +from mobilerun.core.extensions.functions import ( + FunctionDeclaration, + function_description, + function_name, + get_function_declaration, +) +from mobilerun.core.extensions.tool import Tool +from mobilerun.errors.tools import ToolCompilationError +from mobilerun.utils.redaction import mask_step_args + +if TYPE_CHECKING: + from mobilerun.core.extensions.base import Extension + + +def _sanitize_sensitive_schema(schema: dict[str, Any], names: frozenset[str]) -> None: + """Remove sensitive examples, defaults and constraints from exposed schemas.""" + definitions = schema.get("$defs", {}) + visited: set[str] = set() + + def scrub(node: Any) -> None: + if isinstance(node, dict): + for key in ("default", "examples", "example", "const", "enum", "pattern"): + node.pop(key, None) + reference = node.get("$ref") + if isinstance(reference, str) and reference.startswith("#/$defs/"): + name = reference.removeprefix("#/$defs/") + if name not in visited and name in definitions: + visited.add(name) + scrub(definitions[name]) + for child in node.values(): + scrub(child) + elif isinstance(node, list): + for child in node: + scrub(child) + + for name in names: + scrub(schema.get("properties", {}).get(name, {})) + + +def _build_tool( + call: Callable[..., Awaitable[Any]], + declaration: FunctionDeclaration, + name: str, + canonical_name: str, + sensitive_parameters: frozenset[str], + *, + atomic: bool = False, +) -> Tool: + fields: dict[str, Any] = {} + annotations = get_type_hints(inspect.unwrap(call), include_extras=True) + for key, parameter in inspect.signature(call).parameters.items(): + if parameter.kind not in ( + inspect.Parameter.POSITIONAL_OR_KEYWORD, + inspect.Parameter.KEYWORD_ONLY, + ): + raise TypeError("Tool parameters must be callable by keyword") + default = ( + ... if parameter.default is inspect.Parameter.empty else parameter.default + ) + fields[key] = ( + annotations[key], + Field(default, repr=False) if key in sensitive_parameters else default, + ) + arguments = create_model( + name, + __config__=ConfigDict( + extra="forbid", hide_input_in_errors=True, validate_default=True + ), + **fields, + ) + for key, model_field in arguments.model_fields.items(): + if key in sensitive_parameters and any( + alias is not None + for alias in ( + model_field.alias, + model_field.validation_alias, + model_field.serialization_alias, + ) + ): + raise TypeError("Sensitive tool parameters cannot use aliases") + returns = TypeAdapter(annotations["return"]) + input_schema = arguments.model_json_schema() + _sanitize_sensitive_schema(input_schema, sensitive_parameters) + return Tool( + name, + canonical_name, + declaration.description, + input_schema, + returns.json_schema(mode="serialization"), + sensitive_parameters, + arguments, + returns, + call, + atomic, + ) + + +def _tools_for_function( + bound: Callable[..., Awaitable[Any]], + extension_name: str, + declaration: FunctionDeclaration, + expand_atomics: bool, +) -> Iterable[Tool]: + canonical_name = f"{extension_name}.{declaration.name}" + factory = declaration.to_atomic if expand_atomics else None + issue = "Invalid atomic expansion" if factory is not None else "Invalid tool" + try: + parent = _build_tool( + bound, + declaration, + canonical_name, + canonical_name, + declaration.sensitive_parameters, + ) + if factory is None: + return (parent,) + aliases = factory(bound) + if inspect.iscoroutine(aliases): + aliases.close() + raise TypeError("Atomic factories must be synchronous") + if isinstance(aliases, (str, bytes, Mapping, Set)): + raise TypeError("Atomic factories must return an ordered iterable") + tools = [] + for alias in aliases: + if ( + not inspect.iscoroutinefunction(alias) + or inspect.signature(alias).parameters + ): + raise TypeError( + "Atomic tools must be async functions without parameters" + ) + metadata = get_function_declaration(alias) + if metadata is None: + metadata = FunctionDeclaration( + function_name(alias), function_description(alias), None, frozenset() + ) + if metadata.to_atomic is not None: + raise TypeError("An atomic tool cannot expand recursively") + name = f"{extension_name}.{metadata.name}" + binding = getattr(alias, "__mobilerun_atomic_binding__", None) + tool = _build_tool( + alias if binding is None else binding[0], + metadata, + name, + canonical_name, + declaration.sensitive_parameters, + atomic=True, + ) + if binding is not None: + arguments = binding[1] + with ExitStack() as scope: + parent.validate_arguments(arguments, scope=scope) + values = { + key: "***" if key in parent.sensitive_parameters else value + for key, value in arguments.items() + } + bound_json = json.dumps(mask_step_args(values), allow_nan=False) + tool = replace(tool, _bound_json=bound_json) + tools.append(tool) + return tools + except Exception: + pass + raise ToolCompilationError(f"{issue} for '{canonical_name}'") from None + + +def compile_tools( + extensions: Sequence[Extension], *, expand_atomics: bool = True +) -> tuple[Tool, ...]: + """Compile in extension and declaration order; replay can use canonical names.""" + compiled: list[Tool] = [] + owners: dict[str, str] = {} + canonical_owners: dict[str, str] = {} + for extension in extensions: + extension_name = extension.name + if not re.fullmatch(r"[a-z][a-z0-9_]{0,31}", extension_name): + raise ToolCompilationError("Invalid extension namespace") + attributes: dict[str, object] = {} + for cls in reversed(type(extension).__mro__): + attributes.update(vars(cls)) + for attribute, method in attributes.items(): + if not inspect.isfunction(method): + continue + declaration = get_function_declaration(method) + if declaration is None: + continue + bound = method.__get__(extension) + owner = f"{type(extension).__qualname__}.{attribute}" + canonical_name = f"{extension_name}.{declaration.name}" + if canonical_name in canonical_owners: + raise ToolCompilationError( + f"Duplicate tool '{canonical_name}' from {canonical_owners[canonical_name]} and {owner}" + ) + canonical_owners[canonical_name] = owner + for tool in _tools_for_function( + bound, extension_name, declaration, expand_atomics + ): + if tool.name in owners: + raise ToolCompilationError( + f"Duplicate tool '{tool.name}' from {owners[tool.name]} and {owner}" + ) + owners[tool.name] = owner + compiled.append(tool) + return tuple(compiled) diff --git a/mobilerun/core/extensions/registry.py b/mobilerun/core/extensions/registry.py deleted file mode 100644 index edb6b17f1..000000000 --- a/mobilerun/core/extensions/registry.py +++ /dev/null @@ -1,113 +0,0 @@ -"""One root registry and lock, shared by device facades.""" - -from __future__ import annotations - -import asyncio -from collections.abc import Callable, Iterator, Mapping -from contextlib import AbstractAsyncContextManager -from contextvars import ContextVar -from dataclasses import dataclass -from typing import TYPE_CHECKING - -from pydantic import JsonValue - -from mobilerun.utils.redaction import KnownCodes, mask_step_args - -if TYPE_CHECKING: - from mobilerun.core.devices.base import Device - from mobilerun.core.extensions.base import Extension - -invoking_facade: ContextVar[Device | None] = ContextVar( - "extension_invoking_facade", default=None -) - - -@dataclass -class Binding: - extension: Extension - facade: Device - owned: bool - uncertain: bool = False - - -@dataclass -class ActionOutcome: - """Dispatch outcome shared by observers while the secret scopes are active.""" - - error: str | None = None - arguments: dict[str, JsonValue] | None = None - - def redact_arguments(self) -> None: - """Redact aliases discovered in a nested secret scope before it exits.""" - if self.arguments is not None: - safe = mask_step_args(self.arguments) - self.arguments.clear() - self.arguments.update(safe) - - -def redact_action_value( - value: JsonValue, *, contains_code: Callable[[str], bool] | None = None -) -> JsonValue: - """Mask a structured value for existing extension evidence consumers.""" - return mask_step_args({"value": value}, contains_code=contains_code).get( - "value", "***" - ) - - -ActionObserver = Callable[ - ["Device", str, dict[str, JsonValue], ActionOutcome], - AbstractAsyncContextManager[None], -] - - -class ExtensionView(Mapping[str, "Extension"]): - def __init__(self, registry: Registry, facade: Device | None = None) -> None: - self._registry = registry - self._facade = facade - - def __getitem__(self, name: str) -> Extension: - extension = self._registry.bindings[name].extension - return ( - self._facade._extension_access(extension) - if self._facade is not None - else extension - ) - - def __iter__(self) -> Iterator[str]: - return iter(self._registry.bindings) - - def __len__(self) -> int: - return len(self._registry.bindings) - - -class Registry: - def __init__(self) -> None: - self.lock = asyncio.Lock() - self.bindings: dict[str, Binding] = {} - self.view = ExtensionView(self) - self.closing = False - self.observers: dict[Device, ActionObserver] = {} - self.sensitive_ui = False - self.known_codes = KnownCodes() - self.switching = False - self.force = False - - def remember_verification_codes(self, *codes: str) -> None: - if codes: - self.known_codes.remember(*codes) - self.sensitive_ui = True - - def contains_verification_code(self, text: str) -> bool: - return self.known_codes.redact(text) != text - - def matches_sensitive_argument(self, text: str) -> bool: - return ( - text in self.known_codes.sensitive_values - or self.contains_verification_code(text) - ) - - def contains_sensitive_text(self, text: str) -> bool: - return ( - self.contains_verification_code(text) - or self.known_codes.redact_sensitive_text(text) != text - ) diff --git a/mobilerun/core/extensions/tool.py b/mobilerun/core/extensions/tool.py new file mode 100644 index 000000000..b32c46f4f --- /dev/null +++ b/mobilerun/core/extensions/tool.py @@ -0,0 +1,103 @@ +"""Validated tool invocation and its JSON schema descriptor.""" + +from __future__ import annotations + +import json +from collections.abc import Awaitable, Callable, Mapping +from contextlib import ExitStack, nullcontext +from dataclasses import dataclass, field +from types import MappingProxyType +from typing import Any, cast + +from pydantic import BaseModel, TypeAdapter + +from mobilerun.errors.tools import ToolArgumentsError, ToolInvocationError +from mobilerun.models.context import JSONValue +from mobilerun.models.tool_call import ToolCallInfo +from mobilerun.utils.tools.dispatch import authorize_tool +from mobilerun.utils.tools.redaction import tool_secret_scope + + +@dataclass(frozen=True) +class Tool: + """A callable tool with JSON schemas and value-free call metadata.""" + + name: str + canonical_name: str + description: str = field(repr=False) + input_schema: dict[str, Any] = field(repr=False) + output_schema: dict[str, Any] = field(repr=False) + sensitive_parameters: frozenset[str] + _arguments: type[BaseModel] = field(repr=False) + _returns: TypeAdapter[Any] = field(repr=False) + _call: Callable[..., Awaitable[Any]] = field(repr=False) + _atomic: bool = field(repr=False) + _bound_json: str | None = field(default=None, repr=False) + + @property + def is_atomic(self) -> bool: + """Whether this is an expanded alias, even if its name matches its parent.""" + return self._atomic + + @property + def bound_arguments(self) -> Mapping[str, JSONValue] | None: + """Read-only snapshot of validated, masked wire arguments for an alias.""" + return ( + None + if self._bound_json is None + else MappingProxyType(json.loads(self._bound_json)) + ) + + async def invoke(self, arguments: Mapping[str, object]) -> JSONValue: + """Validate JSON arguments, call once, and return a JSON-safe result.""" + with ExitStack() as scope: + parsed = self.validate_arguments(arguments, scope=scope) + return self._serialize(await self._invoke(parsed)) + + def validate_arguments( + self, arguments: Mapping[str, object], *, scope: ExitStack | None = None + ) -> BaseModel: + """Validate JSON inputs without dispatch and return their typed values. + + If supplied, keep input redaction active until the caller exits ``scope``. + Sensitive fields are omitted from repr and str, but the model still + contains their actual validated values; do not log it. + """ + try: + if not isinstance(arguments, Mapping) or any( + not isinstance(key, str) for key in arguments + ): + raise TypeError("Expected an object with string keys") + with ExitStack() if scope is None else nullcontext(scope) as stack: + stack.enter_context( + tool_secret_scope(arguments, self.sensitive_parameters) + ) + return self._arguments.model_validate_json( + json.dumps(dict(arguments), allow_nan=False), strict=True + ) + except Exception: + pass + raise ToolArgumentsError(f"Invalid arguments for '{self.name}'") from None + + async def _invoke(self, parsed: BaseModel) -> object: + if not self._atomic: + return await self._call(**dict(parsed)) + authorize_tool( + ToolCallInfo(self.name, self.canonical_name, self.sensitive_parameters) + ) + try: + return await self._call() + except Exception: + pass + raise ToolInvocationError(f"Tool '{self.name}' failed") from None + + def _serialize(self, result: object) -> JSONValue: + try: + validated = self._returns.validate_python(result, strict=True) + return cast( + JSONValue, + json.loads(self._returns.dump_json(validated, warnings="error")), + ) + except Exception: + pass + raise ToolInvocationError(f"Invalid result from '{self.name}'") from None diff --git a/mobilerun/core/mailbox/README.md b/mobilerun/core/mailbox/README.md index d403d18cb..8074a4501 100644 --- a/mobilerun/core/mailbox/README.md +++ b/mobilerun/core/mailbox/README.md @@ -2,17 +2,18 @@ ## Quick example -A cloud mailbox receives email and extracts codes. +A cloud mailbox receives email and extracts codes without a phone. Creating a mailbox may incur charges. This waits for an email sent to its address. ```python +from mobilerun.core.extensions import compile_tools from mobilerun.core.mailbox import CloudMailbox async with CloudMailbox(billing="paid") as mailbox: print(mailbox.address) code = await mailbox.wait_for_code(timeout=60) - print(code) + tools = compile_tools([mailbox]) # email.messages, email.wait_for_code ``` See [phone numbers](../phone_number/README.md) and [extensions](../extensions/README.md). @@ -32,17 +33,28 @@ timeout names the resource and asks you to check the dashboard. `Mailbox` defines address and code waiting. Await `CloudMailbox(billing=...)` to create an owned mailbox, or pass an id to retrieve one. `keep=True` retains it. +Closing an existing mailbox handle does not release that mailbox. For raw SDK +responses without handle ownership, use the [bound Mailboxes adapter](../../clients/cloud/README.md). -There is no server mailbox binding API. `await mailbox.bind(device)` and -`await mailbox.unbind()` attach and detach a local extension. -This works on cloud and local typing devices, including through wrappers. -`phone.mailbox` is read-only. Code polling shares the SMS timeout helper. +Pass `extensions=[mailbox]` to a local operator to use the same tools. The +caller owns the mailbox and must close it. A closed handle cannot be reopened or +used for backend operations. `messages()` and `wait_for_code()` register code +candidates with recordings active in the current task context so later action +arguments are masked. Treat return values as live results; don't print or store +verification codes. Cloud task inputs are unchanged. ### Included quota and billing plan `await CloudMailbox.included_available()` returns remaining included mailboxes; -it is a snapshot, not a reservation. Create with `plan="included"` to avoid +it returns `None` for unlimited capacity and is a snapshot, not a reservation. +Create with `plan="included"` to avoid renting, default `plan="auto"` to use included quota first (renting only when billing is paid), or `plan="rent"` to always rent with `billing="paid"`. Unlike cloud phone `plan="auto"`, resource `auto` also accepts included billing. Import `ResourcePlan` from `mobilerun.models` for enum values. + +| File | Purpose | +| --- | --- | +| `base.py` | Shared resource contract | +| `cloud.py` | Cloud lifecycle and email tools | +| `__init__.py` | Public exports | diff --git a/mobilerun/core/mailbox/base.py b/mobilerun/core/mailbox/base.py index 949dc5930..7c9e84a00 100644 --- a/mobilerun/core/mailbox/base.py +++ b/mobilerun/core/mailbox/base.py @@ -8,7 +8,6 @@ class Mailbox(Extension, ABC): - role = "mailbox" default_name = "email" @property diff --git a/mobilerun/core/mailbox/cloud.py b/mobilerun/core/mailbox/cloud.py index d2f5e3ed9..5bd55bc4e 100644 --- a/mobilerun/core/mailbox/cloud.py +++ b/mobilerun/core/mailbox/cloud.py @@ -1,28 +1,31 @@ -"""Cloud mailbox lifecycle and local-only device attachment.""" +"""Device-free cloud mailbox lifecycle and verification reads.""" from __future__ import annotations import asyncio +import builtins from collections.abc import Generator from datetime import datetime, timezone from types import TracebackType from typing import Any, Self -from mobilerun.clients.cloud import mailboxes -from mobilerun.clients.cloud.checkout import CheckoutMode, checkout_callback -from mobilerun.clients.cloud.payments import ( - CheckoutCallback, - PaymentAdapter, - wait_for_payment, +from mobilerun.clients.cloud.mailboxes import ( + MailboxCreateParams, + MailboxDeleteResponse, + Mailboxes, + MessageItem, ) +from mobilerun.clients.cloud.payments import PaymentFlow from mobilerun.config.settings import get_settings -from mobilerun.core.extensions import action +from mobilerun.core.extensions import function from mobilerun.core.mailbox.base import Mailbox -from mobilerun.errors import PaymentRequired +from mobilerun.errors import ExtensionClosed, PaymentRequired from mobilerun.models.billing import Billing, ResourcePlan -from mobilerun.models.checkout import PaymentSnapshot +from mobilerun.models.checkout import CheckoutCallback, PaymentSnapshot from mobilerun.models.context import ContextItem -from mobilerun.utils.codes import wait_for_code +from mobilerun.utils.checkout.presentation import CheckoutMode, checkout_callback +from mobilerun.utils.codes import verification_read_codes, wait_for_code +from mobilerun.utils.redaction import remember_scoped_secrets from mobilerun.utils.timestamps import to_api_timestamp @@ -51,20 +54,23 @@ def __init__( if mailbox_id == "": raise ValueError("Resource id must not be empty") self._id = mailbox_id - self._billing = Billing( - get_settings().MOBILERUN_BILLING if billing is None else billing + self._mailboxes = Mailboxes( + billing=Billing( + get_settings().MOBILERUN_BILLING if billing is None else billing + ), + **connection, ) if plan is not None: ResourcePlan(plan) self._plan = plan - self._connection = connection self._label = label self._keep = keep self._on_checkout = checkout_callback(checkout, on_checkout) self._payment_timeout = payment_timeout self._ready_timeout = ready_timeout self._owned = False - self._address = None + self._resource_closed = False + self._address: str | None = None self._lock = asyncio.Lock() @property @@ -82,52 +88,39 @@ def __await__(self) -> Generator[Any, None, Self]: async def _ready(self) -> Self: async with self._lock: + self._ensure_open() if self._id is None: - params: dict[str, Any] = ( - {"label": self._label} if self._label is not None else {} - ) + params: MailboxCreateParams = {} + if self._label is not None: + params["label"] = self._label try: - response = await mailboxes.create( - billing=self._billing, - **({"plan": self._plan} if self._plan is not None else {}), - **( - { - "on_checkout": self._on_checkout, - "payment_timeout": self._payment_timeout, - } - if self._on_checkout is not None - else {} - ), - **({"keep": True} if self._keep else {}), - **self._connection, + created = await self._mailboxes.create( + plan=self._plan, + on_checkout=self._on_checkout, + payment_timeout=self._payment_timeout, **params, ) except PaymentRequired as exc: self._id = exc.checkout.resource_id self._owned = True raise PaymentRequired(exc.checkout, self.wait_until_paid) from exc - self._id = response.data.id + self._id = created.data.id self._owned = True - if self._on_checkout is not None and response.data.status in ( - "awaiting_payment", - "pending_payment", - ): - response = await mailboxes.retrieve( - self.id, billing=self._billing, **self._connection - ) - else: - response = await mailboxes.retrieve( - self.id, billing=self._billing, **self._connection + response = ( + await self._mailboxes.retrieve(self.id) + if self._on_checkout is not None + and created.data.status in ("awaiting_payment", "pending_payment") + else created ) + else: + response = await self._mailboxes.retrieve(self.id) self._address = response.data.address if response.data.status in ("awaiting_payment", "pending_payment"): - await wait_for_payment( - PaymentAdapter( - "mailbox", - self.id, - self._payment_state, - self.release if self._owned else None, - ), + await PaymentFlow( + "mailbox", + self.id, + self._payment_state, + ).wait_for_payment( PaymentSnapshot( response.data.status, response.data.checkout_url, @@ -148,12 +141,10 @@ async def _wait_ready(self, *, timeout: float | None = None) -> None: self._ready_timeout if timeout is None else timeout ): while True: - data = ( - await mailboxes.retrieve( - self.id, billing=self._billing, **self._connection - ) - ).data - self._address = data.address + async with self._lock: + self._ensure_open() + data = (await self._mailboxes.retrieve(self.id)).data + self._address = data.address if data.status == "active" and data.address: return if data.status not in ( @@ -172,13 +163,14 @@ async def _wait_ready(self, *, timeout: float | None = None) -> None: ) from None async def _payment_state(self) -> PaymentSnapshot: - data = ( - await mailboxes.retrieve(self.id, billing=self._billing, **self._connection) - ).data - self._address = data.address + async with self._lock: + self._ensure_open() + data = (await self._mailboxes.retrieve(self.id)).data + self._address = data.address return PaymentSnapshot(data.status, data.checkout_url, data.checkout_expires_at) async def wait_until_paid(self, timeout: float = 600) -> Self: + self._ensure_open() await self._wait_ready(timeout=timeout) return self @@ -196,29 +188,40 @@ async def __aexit__( @classmethod async def included_available( cls, *, billing: Billing | str | None = None, **connection: Any - ) -> int: - """Return a capacity snapshot, not a reservation.""" + ) -> int | None: + """Return a capacity snapshot (None if unlimited), not a reservation.""" billing = Billing( get_settings().MOBILERUN_BILLING if billing is None else billing ) - data = (await mailboxes.capacity(billing=billing, **connection)).data + data = (await Mailboxes(billing=billing, **connection).capacity()).data return 0 if data.status == "not_included" else data.remaining @classmethod async def list( cls, *, billing: Billing | str | None = None, **connection: Any - ) -> list[Self]: + ) -> builtins.list[Self]: billing = Billing( get_settings().MOBILERUN_BILLING if billing is None else billing ) result = [] - for item in await mailboxes.list_mailboxes(billing=billing, **connection): + for item in await Mailboxes(billing=billing, **connection).list(): mailbox = cls(item.id, billing=billing, **connection) mailbox._address = item.address result.append(mailbox) return result - @action() + @function + async def messages(self) -> builtins.list[MessageItem]: + """List email message history for this mailbox.""" + async with self._lock: + self._ensure_open() + history = await self._mailboxes.messages(self.id) + remember_scoped_secrets( + *verification_read_codes("mailbox", "messages", history) + ) + return history + + @function async def wait_for_code( self, *, @@ -227,33 +230,41 @@ async def wait_for_code( after: datetime | None = None, ) -> str: """Wait for a verification code sent to this mailbox.""" - params = { - "after": to_api_timestamp(after or datetime.now(timezone.utc)), - "min_length": 4, - "max_length": 8, - } + since = to_api_timestamp(after or datetime.now(timezone.utc)) async def fetch(sender: str | None) -> str | None: - query = {**params, **({"sender": sender} if sender is not None else {})} - response = await mailboxes.otp( - self.id, billing=self._billing, **self._connection, **query + response = await self._mailboxes.otp( + self.id, + after=since, + min_length=4, + max_length=8, + **({"sender": sender} if sender is not None else {}), ) return response.data.code if response and response.data else None - return await wait_for_code(fetch, timeout=timeout, sender=sender) + async with self._lock: + self._ensure_open() + code = await wait_for_code(fetch, timeout=timeout, sender=sender) + remember_scoped_secrets(code) + return code + + def _ensure_open(self) -> None: + if self._resource_closed: + raise ExtensionClosed("Mailbox is closed") async def context(self) -> tuple[ContextItem, ...]: return (ContextItem(self.name, "mailbox", {"address": self.address}),) - async def release(self) -> Any: - await self.unbind() - result = await mailboxes.delete( - self.id, billing=self._billing, **self._connection - ) - self._owned = False - return result + async def release(self) -> MailboxDeleteResponse: + async with self._lock: + self._ensure_open() + result = await self._mailboxes.delete(self.id) + self._owned = False + return result async def on_close(self) -> None: - if self._owned and not self._keep: - await mailboxes.delete(self.id, billing=self._billing, **self._connection) - self._owned = False + async with self._lock: + if self._owned and not self._keep: + await self._mailboxes.delete(self.id) + self._owned = False + self._resource_closed = True diff --git a/mobilerun/core/operator/README.md b/mobilerun/core/operator/README.md index 36c862ca8..096e262ce 100644 --- a/mobilerun/core/operator/README.md +++ b/mobilerun/core/operator/README.md @@ -1,26 +1,64 @@ # operator/ -**Purpose:** The contract for operators that execute device tasks. +**Purpose:** Execute tasks on a `mobilerun_core.AsyncDevice` with caller-owned extensions. **What belongs here / what doesn't:** Put the operator interface here, not concrete agent implementations. **Contents:** -- `__init__.py` — Operator export. -- `base.py` — Abstract operator interface. +| File | Purpose | +| --- | --- | +| `__init__.py` | Operator and plugin loader exports. | +| `base.py` | Operator interface, borrowed extensions, tool compilation and context. | +| `cloud.py` | Server-side task operator. | +| `helpers/plugins.py` | Lazy loader for installed operator classes. | **Examples:** ```python -from mobilerun.core.operator import Operator +from mobilerun.core.operator.cloud import CloudTaskOperator -# Implement Operator to supply task execution to a device. +# Given a core cloud phone, SDK client, and cloud credentials: +operator = CloudTaskOperator(client=client, extensions=[vault], billing="included") +result = await operator.do(phone, "Open the inventory screen", max_steps=10) +verdict = await operator.expect(phone, "Inventory is visible", timeout=30) ``` -**Depends on / used by:** Uses shared task result types; used by device implementations and operators. +Cloud tasks may consume included quota or credits. The operator borrows the SDK +client and extensions; the caller closes both. The operator streams progress, +polls for the result and attempts to stop the task on cancellation or timeout +through its bound `Tasks` adapter. Cloud tasks use only reference +inputs from supplied cloud-native extensions. Other extensions raise +`OperatorNotSupported` before any task is submitted. An optional +`on_task_started(task_id)` callback receives the submitted task ID. -Operators may override `check(device)` to reject incompatible devices at pairing. -`CloudTaskOperator` requires a cloud client. For local LLM execution, install -`mobilerun-agents` and use its `AgentOperator`. +Use `operator.do(phone, instruction, output=..., timeout=...)` for tasks and +`operator.expect(phone, condition, timeout=...)` for a structured verdict. +For a negative verdict or a missing verdict, `expect()` raises +`ExpectationFailed` or `ExpectationInconclusive`, respectively. -See [devices](../devices/README.md) and the separate `mobilerun-agents` package. +Implementers override `_execute(device, ...)` and can override `check(device)` +to reject incompatible pairings before execution. Local implementations can use +`operator.tools()` to compile [declared extension functions](../extensions/README.md) +and `await operator.context()` to collect extension context in caller-provided +order. Cloud submission does not compile tools. For local LLM execution, use +`AgentOperator` from the separate `mobilerun-agents` package. + +## Installed operators + +Register a concrete `Operator` subclass under `mobilerun.operators`. The class +must accept `extensions=` without any other required arguments. The loader +imports only the selected entry and does not construct it: + +```python +from mobilerun.core.operator import load_operator + +operator_type = load_operator("inventory") +operator = operator_type(extensions=[vault, mailbox]) +``` + +Unknown names, invalid entries, and failed imports raise `OperatorPluginError` +from `mobilerun.errors.operator_plugins`. An unknown name lists available +operators; import failures retain the original exception as their cause. +See [add-on registration](../../addons/README.md#write-a-plugin) and +`mobilerun plugins list --check` to inspect installed entries. diff --git a/mobilerun/core/operator/__init__.py b/mobilerun/core/operator/__init__.py index 4b3ea04bd..5de5c298c 100644 --- a/mobilerun/core/operator/__init__.py +++ b/mobilerun/core/operator/__init__.py @@ -1,5 +1,6 @@ """Device operator interface.""" from .base import Operator +from .helpers.plugins import load_operator -__all__ = ["Operator"] +__all__ = ["Operator", "load_operator"] diff --git a/mobilerun/core/operator/base.py b/mobilerun/core/operator/base.py index 741d8ef64..7b6364e18 100644 --- a/mobilerun/core/operator/base.py +++ b/mobilerun/core/operator/base.py @@ -1,34 +1,103 @@ """Base interface for device operators.""" from abc import ABC -from typing import TYPE_CHECKING, TypeVar +from collections.abc import Sequence +from typing import TypeVar +from mobilerun_core import AsyncDevice from pydantic import BaseModel -from mobilerun.errors import OperatorNotAvailable -from mobilerun.models.results import ExecutionResult - -if TYPE_CHECKING: - from mobilerun.core.devices.base import Device +from mobilerun.core.extensions import Extension, Tool, compile_tools +from mobilerun.errors import ( + ExpectationFailed, + ExpectationInconclusive, + OperatorNotAvailable, +) +from mobilerun.models.context import ContextItem +from mobilerun.models.results import ( + ExecutionResult, + ExpectationResult, + ExpectationVerdict, +) +from mobilerun.utils.prompts import PromptLoader, load_prompt_text T = TypeVar("T", bound=BaseModel) class Operator(ABC): # noqa: B024 - the base implementation deliberately raises - def check(self, device: "Device") -> None: # noqa: B027 + """Execute tasks on a caller-supplied device with borrowed extensions.""" + + def __init__(self, *, extensions: Sequence[Extension] = ()) -> None: + self._extensions = tuple(extensions) + + @property + def extensions(self) -> tuple[Extension, ...]: + """Borrowed extension instances, in caller-provided order.""" + return self._extensions + + def tools(self) -> tuple[Tool, ...]: + """Compile operator-visible tools; expand atomics once per call.""" + return compile_tools(self.extensions) + + async def context(self) -> tuple[ContextItem, ...]: + """Collect extension context without changing resource ownership.""" + items: list[ContextItem] = [] + for extension in self.extensions: + items.extend(await extension.context()) + return tuple(items) + + async def do( + self, + device: AsyncDevice, + instruction: str, + *, + output: type[T] | None = None, + max_steps: int | None = None, + timeout: float | None = None, + ) -> ExecutionResult[T]: + """Validate the device pairing and execute an instruction.""" + self.check(device) + return await self._execute( + device, instruction, output=output, max_steps=max_steps, timeout=timeout + ) + + async def expect( + self, device: AsyncDevice, condition: str, *, timeout: float | None = None + ) -> ExpectationResult: + """Verify a condition, distinguishing a negative verdict from no verdict.""" + instruction = PromptLoader.render_template( + load_prompt_text("devices/expect.jinja2"), {"condition": condition} + ) + task = await self.do( + device, instruction, output=ExpectationVerdict, timeout=timeout + ) + if not task.success or task.output is None: + raise ExpectationInconclusive(condition, task) + result = ExpectationResult( + passed=task.output.passed, + condition=condition, + reason=task.output.reason, + task=task, + ) + if not result.passed: + raise ExpectationFailed(result) + return result + + def check(self, device: AsyncDevice) -> None: # noqa: B027 """Validate a pairing before use.""" - async def execute( + async def _execute( self, - device: "Device", + device: AsyncDevice, instruction: str, *, output: type[T] | None = None, max_steps: int | None = None, timeout: float | None = None, ) -> ExecutionResult[T]: + """Implementation hook for subclasses; callers should use ``do``.""" raise OperatorNotAvailable( - f"No operator for {type(device).__name__}. Pass operator=..., " + f"No operator implementation for {type(device).__name__}. Choose a concrete operator, " "e.g. AgentOperator() from the mobilerun-agents add-on " "(from mobilerun_agents import AgentOperator)." ) diff --git a/mobilerun/core/operator/cloud.py b/mobilerun/core/operator/cloud.py index 9a3be244a..ccd341d43 100644 --- a/mobilerun/core/operator/cloud.py +++ b/mobilerun/core/operator/cloud.py @@ -2,85 +2,197 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any, TypeVar, cast +import asyncio +import logging +from collections.abc import Callable, Sequence +from contextlib import aclosing +from typing import TypeVar, cast -from pydantic import BaseModel +from mobilerun_core import AsyncDevice +from pydantic import BaseModel, ValidationError -from mobilerun.models.results import ExecutionResult - -if TYPE_CHECKING: - from mobilerun.core.devices.base import Device - from mobilerun.core.devices.cloud import CloudDevice - - -from mobilerun.clients.cloud.tasks import run_task +from mobilerun.clients.cloud.client import AsyncMobilerun +from mobilerun.clients.cloud.tasks import Credential, TaskRunOptions, Tasks from mobilerun.config.settings import get_settings -from mobilerun.core.operator import Operator -from mobilerun.errors import OperatorNotSupported +from mobilerun.core.extensions import Extension +from mobilerun.errors import CloudTaskTimeout, OperatorNotSupported +from mobilerun.logs.actions import action_line, cloud_progress +from mobilerun.logs.actions import logger as action_logger from mobilerun.models.billing import Billing +from mobilerun.models.results import ExecutionResult + +from .base import Operator T = TypeVar("T", bound=BaseModel) +logger = logging.getLogger(__name__) class CloudTaskOperator(Operator): - def __init__(self, *, billing: Billing | str | None = None) -> None: + """Submit tasks through a borrowed SDK client for an existing cloud phone.""" + + def __init__( + self, + *, + client: AsyncMobilerun, + billing: Billing | str | None = None, + extensions: Sequence[Extension] = (), + on_task_started: Callable[[str], None] | None = None, + ) -> None: + super().__init__(extensions=extensions) + self._on_task_started = on_task_started self._billing = Billing( get_settings().MOBILERUN_BILLING if billing is None else billing ) + self._tasks = Tasks(client=client, billing=self._billing) - def check(self, device: Device) -> None: - if not device._is_cloud: - kind = type(device).__name__ - inner = device._unwrap() - if inner is not device: - kind = f"{kind}({type(inner).__name__})" + def check(self, device: AsyncDevice) -> None: + if device.info().backend != "cloud": raise OperatorNotSupported( - f"{kind} ({device.identifier or 'unidentified'}) is not a cloud device. Use an operator from mobilerun-agents for local LLM tasks." + "The supplied device is not a cloud device. " + "Use an operator from mobilerun-agents for local LLM tasks." ) local = [ extension.name - for extension in device.extensions.values() + for extension in self.extensions if not extension.cloud_native ] if local: raise OperatorNotSupported( - f"This device has local extensions ({', '.join(local)}) that cloud tasks can't use; use an operator from mobilerun-agents or unbind them" + f"Cloud tasks cannot use non-cloud-native extensions: {', '.join(local)}. " + "Omit them or use an operator from mobilerun-agents." ) - async def execute( + async def _execute( self, - device: Device, + device: AsyncDevice, instruction: str, *, output: type[T] | None = None, max_steps: int | None = None, timeout: float | None = None, ) -> ExecutionResult[T]: - self.check(device) references: dict[str, set[str]] = {} - extensions = tuple(device.extensions.values()) - for extension in extensions: - if extension.cloud_native: - inputs = await extension.cloud_task_inputs() - for reference in inputs.credential_references: - references.setdefault(reference.package, set()).add(reference.name) - await device._ensure_connected() - cloud = cast("CloudDevice", device._unwrap()) - params: dict[str, Any] = { - "device_id": cloud.device_id, - "task": instruction, - "output": output, - "max_steps": max_steps, - } - if timeout is not None: - params["timeout"] = timeout - if references: - params["credentials"] = [ - {"package_name": package, "credential_names": sorted(names)} - for package, names in references.items() - ] - if cloud._task_started_callback is not None: - params["on_task_started"] = cloud._task_started_callback - outcome = await run_task(cloud._cloud_client, billing=self._billing, **params) - outcome.device = type(device).__name__ - return outcome + for extension in self.extensions: + inputs = await extension.cloud_task_inputs() + for reference in inputs.credential_references: + references.setdefault(reference.package, set()).add(reference.name) + credentials: list[Credential] = [ + {"package_name": package, "credential_names": sorted(names)} + for package, names in references.items() + ] + params: TaskRunOptions = {"device_id": device.device_id, "task": instruction} + if output is not None: + params["output_schema"] = output.model_json_schema() + if max_steps is not None: + params["max_steps"] = max_steps + if credentials: + params["credentials"] = credentials + + settings = get_settings() + timeout = ( + settings.MOBILERUN_CLOUD_TASK_TIMEOUT_SECONDS + if timeout is None + else timeout + ) + task_id = "unknown" + deadline = asyncio.timeout(timeout) + try: + async with deadline: + response = await self._tasks.run(**params) + task_id = response.id + if self._on_task_started is not None: + self._on_task_started(task_id) + try: + step_count = 0 + async with aclosing(self._tasks.progress(task_id)) as lines: + async for line in lines: + if line.startswith("data:") and ( + parsed := cloud_progress(line[5:].strip()) + ): + action, step = parsed + step_count += 1 + action_logger.info( + "%s", + action_line( + device.device_id[:8] or "unknown", + "task", + step or step_count, + action, + ), + ) + except Exception: + # Streaming is optional; status is authoritative. + logger.warning("Cloud task progress unavailable; polling status") + while True: + state = await self._tasks.status(task_id) + if state.status in {"completed", "failed", "cancelled"}: + break + await asyncio.sleep( + settings.MOBILERUN_CLOUD_TASK_POLL_INTERVAL_SECONDS + ) + + success = bool(state.succeeded) + answer = state.message + parsed_output = None + if output is not None and state.output is not None: + try: + parsed_output = output.model_validate(state.output) + except ValidationError as exc: + success = False + answer = str(exc) + result_type: type[ExecutionResult[T]] = ( + cast( + type[ExecutionResult[T]], + ExecutionResult.__class_getitem__(output), + ) + if output is not None + else ExecutionResult + ) + return result_type( + success=success, + answer=answer, + output=parsed_output, + steps=state.steps, + task_id=task_id, + device=type(device).__name__, + ) + except (TimeoutError, asyncio.CancelledError, KeyboardInterrupt) as exc: + # A request timeout does not mean the overall wait deadline expired. + timed_out = isinstance(exc, TimeoutError) + if timed_out and not deadline.expired(): + raise + cancellation = await self._stop(task_id) + if not timed_out: + raise + if cancellation is not None: + raise cancellation from None + raise CloudTaskTimeout( + operation="Run cloud task", + code="task_timeout", + resource_id=task_id, + timeout=timeout, + ) from exc + + async def _stop(self, task_id: str) -> asyncio.CancelledError | None: + if task_id == "unknown": + return None + + async def stop_with_timeout() -> None: + try: + async with asyncio.timeout( + get_settings().MOBILERUN_CLOUD_TASK_STOP_TIMEOUT_SECONDS + ): + await self._tasks.stop(task_id) + except (Exception, asyncio.CancelledError): + # Best effort: cleanup must not mask the caller's outcome. + logger.warning("Could not stop cloud task %s", task_id) + + # Keep waiting for the bounded stop even if the caller is cancelled again. + cleanup = asyncio.create_task(stop_with_timeout()) + cancellation = None + while not cleanup.done(): + try: + await asyncio.shield(cleanup) + except asyncio.CancelledError as exc: + cancellation = exc + return cancellation diff --git a/mobilerun/core/operator/helpers/plugins.py b/mobilerun/core/operator/helpers/plugins.py new file mode 100644 index 000000000..b6c512ed4 --- /dev/null +++ b/mobilerun/core/operator/helpers/plugins.py @@ -0,0 +1,45 @@ +"""Discover and validate installed operator classes without instantiating them.""" + +from importlib.metadata import EntryPoint +from inspect import isabstract, signature + +from mobilerun.addons.plugins import discover, distribution_name +from mobilerun.addons.settings import OPERATOR_ENTRY_POINT_GROUP +from mobilerun.core.operator.base import Operator +from mobilerun.errors.operator_plugins import OperatorPluginError + + +def load_operator(name: str) -> type[Operator]: + """Resolve one installed operator by name, importing only its entry point.""" + entries = discover(OPERATOR_ENTRY_POINT_GROUP) + entry = entries.get(name) + if entry is None: + available = ", ".join(entries) or "none" + raise OperatorPluginError( + f"Unknown operator {name!r}. Available operators: {available}." + ) + return load_operator_entry(entry) + + +def load_operator_entry(entry: EntryPoint) -> type[Operator]: + """Validate a selected operator entry, as used by plugin diagnostics.""" + label = f"Operator plugin {entry.name!r} from {distribution_name(entry)!r}" + try: + operator = entry.load() + except Exception as error: + raise OperatorPluginError(f"{label} failed to load.") from error + + if ( + not isinstance(operator, type) + or not issubclass(operator, Operator) + or operator is Operator + or isabstract(operator) + ): + raise OperatorPluginError(f"{label} must export a concrete Operator subclass.") + try: + signature(operator).bind(extensions=()) + except (TypeError, ValueError): + raise OperatorPluginError( + f"{label} must be constructible with extensions= alone." + ) from None + return operator diff --git a/mobilerun/core/phone_number/README.md b/mobilerun/core/phone_number/README.md index 313171b23..83b8f0c26 100644 --- a/mobilerun/core/phone_number/README.md +++ b/mobilerun/core/phone_number/README.md @@ -1,6 +1,6 @@ # Phone numbers -A cloud number receives SMS and can bind to a compatible cloud phone. +A cloud number receives SMS and can attach to a compatible cloud phone. ## Quick example @@ -10,12 +10,11 @@ Creating a number may incur charges. This waits for an SMS sent to the new numbe from mobilerun.core.phone_number import CloudPhoneNumber async with CloudPhoneNumber(country="US", billing="paid") as number: - print(number.phone_number) + await number.attach(phone) # phone is a mobilerun_core.AsyncDevice code = await number.wait_for_code(timeout=60) - print(code) ``` -See [devices](../devices/README.md) and [mailboxes](../mailbox/README.md). +See [mailboxes](../mailbox/README.md) and [extensions](../extensions/README.md). ## Number readiness @@ -51,30 +50,27 @@ SMS are separate operations with different timeouts. when awaited, or retrieves an existing number by id. Creation accepts `billing`, `country` and `keep`. -Use `await number.bind(phone)` and `await number.unbind()`. These are the only -binding operations. `phone.number` is read-only. Local devices reject binding -before making requests. Cloud phones must support telephony. -Await an existing `CloudDevice(id)` to fetch/cache its -server-side number binding. Use `wait_for_code()` to retrieve a code explicitly. - -Every `Device` declares the read-only `number` property. A local device or a -cloud phone without a bound number raises `DeviceOperationNotSupported` with -support/attachment guidance. After binding, use the typed resource directly: - -```python -code = await device.number.wait_for_code(sender="Example", timeout=60) -messages = await device.number.messages() -await device.number.send("+15555550123", "Test message") -``` - -Sending may incur charges. The typed call uses the number's configured billing -mode without prompting. The device-action CLI can authorize a retry of the -preflight-guarded send without changing that configured mode. - -Wrappers delegate `number`; `DevicePool.number` returns resources in device order. - -Owned numbers bound to an owned phone are unbound and released when the phone -closes, unless the phone or number has `keep=True`. +Use `await number.attach(phone)` and `await number.detach()`. Connect never +adopts a number. `attach` requires a cloud phone with telephony; it uses the +number's configured cloud account, not private state from the phone handle. +For control-plane-only operations, `attach_to_cloud_phone(device_id)` uses the +cloud ID without opening a UI connection. Both reject a different number +already on the phone with `NumberAttachmentConflict` unless `replace=True`. +Replacement is not atomic. After an interrupted or ambiguous request, check +the phone's state before retrying. `detach()` returns whether it removed a link. + +The caller closes the number. Close detaches a link made by this handle and +releases a number purchased by this handle (unless `keep=True`). It neither +detaches a pre-existing link nor releases a number supplied by ID. A closed +handle cannot be reopened or used for backend operations. + +Pass `extensions=[number]` to a local operator to expose `sms.messages` and +`sms.wait_for_code`. Neither read needs an attached phone. `messages()` and +`wait_for_code()` register code candidates with recordings active in the current +task context so later action arguments are masked. Don't print or store +verification codes. `send(to, text)` is +a typed Python/CLI operation, not an operator tool; it may incur charges and +uses the number's billing mode. ### Included quota and billing plan @@ -86,3 +82,9 @@ rents only with `billing="paid"`; `plan="rent"` always rents and requires paid billing. Unlike a cloud phone's explicit `plan="auto"`, resource `auto` also works with `billing="included"`. Import `ResourcePlan` from `mobilerun.models` to use enum values instead of strings. + +| File | Purpose | +| --- | --- | +| `base.py` | Shared resource contract | +| `cloud.py` | Cloud lifecycle, attachment and SMS tools | +| `__init__.py` | Public exports | diff --git a/mobilerun/core/phone_number/base.py b/mobilerun/core/phone_number/base.py index 9e633f13e..aa289a941 100644 --- a/mobilerun/core/phone_number/base.py +++ b/mobilerun/core/phone_number/base.py @@ -8,9 +8,7 @@ class PhoneNumber(Extension, ABC): - role = "phone_number" default_name = "sms" - exclusive = "phone_number" @property @abstractmethod diff --git a/mobilerun/core/phone_number/cloud.py b/mobilerun/core/phone_number/cloud.py index fbd324f70..4438b54c5 100644 --- a/mobilerun/core/phone_number/cloud.py +++ b/mobilerun/core/phone_number/cloud.py @@ -1,58 +1,45 @@ -"""Owned cloud numbers, with resource-side binding only.""" +"""Cloud number lifetime, explicit phone attachment and SMS.""" from __future__ import annotations import asyncio import inspect import logging -from collections.abc import Generator -from dataclasses import dataclass +from collections.abc import Awaitable, Generator from datetime import datetime, timezone from types import TracebackType -from typing import Any, Self, cast - -from mobilerun.clients.cloud import devices, numbers -from mobilerun.clients.cloud.checkout import CheckoutMode, checkout_callback -from mobilerun.clients.cloud.client import AsyncMobilerun -from mobilerun.clients.cloud.payments import ( - CheckoutCallback, - PaymentAdapter, - wait_for_payment, - wait_until_active, -) +from typing import Any, Self, TypeVar + +from mobilerun_core import AsyncDevice +from mobilerun_sdk import APIError + +from mobilerun.clients.cloud.errors import CloudErrorMapper +from mobilerun.clients.cloud.numbers import MessageItem, MessageSendResponse, Numbers +from mobilerun.clients.cloud.payments import PaymentFlow from mobilerun.config.settings import get_settings -from mobilerun.core.devices.base import Device -from mobilerun.core.extensions import BillingRetry, Extension, action -from mobilerun.core.extensions.registry import Binding +from mobilerun.core.extensions import function from mobilerun.core.phone_number.base import PhoneNumber from mobilerun.errors import ( CloudError, + ExtensionClosed, ExtensionNotSupported, PaymentRequired, PurchaseInProgress, ) +from mobilerun.errors.cloud import CloudAPIError, NumberAttachmentConflict from mobilerun.models.billing import Billing, ResourcePlan -from mobilerun.models.checkout import PaymentSnapshot +from mobilerun.models.checkout import CheckoutCallback, PaymentSnapshot from mobilerun.models.context import ContextItem -from mobilerun.utils.codes import extract_code, wait_for_code +from mobilerun.utils.checkout.presentation import CheckoutMode, checkout_callback +from mobilerun.utils.codes import extract_code, verification_read_codes, wait_for_code +from mobilerun.utils.redaction import remember_scoped_secrets, secret_scope from mobilerun.utils.timestamps import to_api_timestamp logger = logging.getLogger(__name__) - - -@dataclass(frozen=True) -class _ObservedNumberBinding: - number_id: str - phone_number: str | None - - -class _BorrowedNumberBinding(Binding): - """An existing server relationship discovered, not made, by this handle.""" +_T = TypeVar("_T") class CloudPhoneNumber(PhoneNumber): - cloud_native = True - def __init__( self, number_id: str | None = None, @@ -83,7 +70,7 @@ def __init__( if plan is not None: ResourcePlan(plan) self._plan = plan - self._connection = connection + self._numbers = Numbers(billing=self._billing, **connection) self._params: dict[str, Any] = { key: value for key, value in {"country": country, "label": label}.items() @@ -96,7 +83,8 @@ def __init__( self.resumed_existing = False self._phone_number = None self._device_id = None - self._binding_loaded = False + self._attached_device_id: str | None = None + self._resource_closed = False self._lock = asyncio.Lock() @property @@ -118,21 +106,13 @@ def __await__(self) -> Generator[Any, None, Self]: async def _ready(self) -> Self: async with self._lock: + self._ensure_open() if self._id is None: try: - response = await numbers.create( - billing=self._billing, - **({"plan": self._plan} if self._plan is not None else {}), - **( - { - "on_checkout": self._on_checkout, - "payment_timeout": self._payment_timeout, - } - if self._on_checkout is not None - else {} - ), - **({"keep": True} if self._keep else {}), - **self._connection, + response = await self._numbers.create( + plan=self._plan, + on_checkout=self._on_checkout, + payment_timeout=self._payment_timeout, **self._params, ) except PurchaseInProgress as exc: @@ -155,31 +135,22 @@ async def _ready(self) -> Self: self._owned = True self._phone_number = None if self._on_checkout is not None and data.state == "awaiting_payment": - ready = ( - await numbers.retrieve( - self.id, billing=self._billing, **self._connection - ) - ).data + ready = (await self._numbers.retrieve(self.id)).data self._phone_number = ready.phone_number data = ready self._device_id = None else: - response = await numbers.retrieve( - self.id, billing=self._billing, **self._connection - ) + response = await self._numbers.retrieve(self.id) data = response.data self._phone_number = data.phone_number binding = data.device_binding self._device_id = binding.device_id if binding else None - self._binding_loaded = True if data.state == "awaiting_payment": - await wait_for_payment( - PaymentAdapter( - "phone number", - self.id, - self._payment_state, - self.release if self._owned else None, - ), + await PaymentFlow( + "phone number", + self.id, + self._payment_state, + ).wait_for_payment( PaymentSnapshot(data.state, data.checkout_url), resume=self.wait_until_paid, on_checkout=self._on_checkout, @@ -188,17 +159,16 @@ async def _ready(self) -> Self: return self async def _payment_state(self) -> PaymentSnapshot: - data = ( - await numbers.retrieve(self.id, billing=self._billing, **self._connection) - ).data + self._ensure_open() + data = (await self._numbers.retrieve(self.id)).data self._phone_number = data.phone_number return PaymentSnapshot(data.state, data.checkout_url) async def wait_until_paid(self, timeout: float = 600) -> Self: - await wait_until_active( - PaymentAdapter("phone number", self.id, self._payment_state), - timeout=timeout, - ) + self._ensure_open() + await PaymentFlow( + "phone number", self.id, self._payment_state + ).wait_until_active(timeout=timeout) return self async def __aenter__(self) -> Self: @@ -206,6 +176,7 @@ async def __aenter__(self) -> Self: async def wait_ready(self, *, timeout: float | None = None) -> Self: """Wait for GET number data.state=active; payment is never automated.""" + self._ensure_open() timeout = ( get_settings().MOBILERUN_CLOUD_NUMBER_READY_TIMEOUT_SECONDS if timeout is None @@ -219,14 +190,13 @@ async def wait_ready(self, *, timeout: float | None = None) -> Self: try: async with asyncio.timeout(timeout): while True: - data = ( - await numbers.retrieve( - self.id, billing=self._billing, **self._connection - ) - ).data + async with self._lock: + self._ensure_open() + data = (await self._numbers.retrieve(self.id)).data state = data.state - snapshot = await wait_for_payment( - PaymentAdapter("phone number", self.id, self._payment_state), + snapshot = await PaymentFlow( + "phone number", self.id, self._payment_state + ).wait_for_payment( PaymentSnapshot(data.state, data.checkout_url), resume=self.wait_until_paid, ) @@ -265,7 +235,7 @@ async def included_available( billing = Billing( get_settings().MOBILERUN_BILLING if billing is None else billing ) - data = (await numbers.capacity(country, billing=billing, **connection)).data + data = (await Numbers(billing=billing, **connection).capacity(country)).data return 0 if data.status == "not_included" else data.remaining @classmethod @@ -276,47 +246,46 @@ async def list( get_settings().MOBILERUN_BILLING if billing is None else billing ) result = [] - for item in await numbers.list_numbers(billing=billing, **connection): + for item in await Numbers(billing=billing, **connection).list(): number = cls(item.id, billing=billing, **connection) number._phone_number = item.phone_number binding = item.device_binding number._device_id = binding.device_id if binding else None - number._binding_loaded = True result.append(number) return result - @action() - async def messages( - self, *, after: datetime | None = None - ) -> list[numbers.MessageItem]: + @function + async def messages(self, *, after: datetime | None = None) -> list[MessageItem]: """List inbound messages received by this number.""" - return await numbers.messages( + async with self._lock: + self._ensure_open() + history = await self._incoming_messages(after) + remember_scoped_secrets( + *verification_read_codes("phone_number", "messages", history) + ) + return history + + async def _incoming_messages(self, after: datetime | None) -> list[MessageItem]: + return await self._numbers.messages( self.id, - billing=self._billing, after=to_api_timestamp(after) if after is not None else None, direction="inbound", - **self._connection, ) - async def _send_with_billing( - self, policy: BillingRetry | None, /, to: str, text: str - ) -> numbers.MessageSendResponse: - async def send_with_mode(mode: Billing) -> numbers.MessageSendResponse: - return await numbers.send( - self.id, to, text, billing=mode, **self._connection - ) - - if policy is None: - return await send_with_mode(self._billing) - result, _ = await policy(send_with_mode, self._billing) - return result - - @action(billing_retry=_send_with_billing) - async def send(self, to: str, text: str) -> numbers.MessageSendResponse: + async def send(self, to: str, text: str) -> MessageSendResponse: """Send an SMS message to a phone number.""" - return await self._send_with_billing(None, to, text) - - @action() + async with self._lock: + self._ensure_open() + with secret_scope(to, text): + try: + return await self._numbers.send(self.id, to, text) + except CloudAPIError as exc: + failure = exc + # Preserve billing and cloud error types, without the SDK error body. + failure.__context__ = None + raise failure.with_traceback(None) from None + + @function async def wait_for_code( self, *, @@ -328,7 +297,7 @@ async def wait_for_code( after = after if after is not None else datetime.now(timezone.utc) async def fetch(sender: str | None) -> str | None: - for message in await self.messages(after=after): + for message in await self._incoming_messages(after): if sender and not any( sender.casefold() in (value or "").casefold() for value in (message.detected_sender, message.peer_number) @@ -339,142 +308,143 @@ async def fetch(sender: str | None) -> str | None: return code return None - return await wait_for_code(fetch, timeout=timeout, sender=sender) + async with self._lock: + self._ensure_open() + code = await wait_for_code(fetch, timeout=timeout, sender=sender) + remember_scoped_secrets(code) + return code - async def check_bind(self, device: Device) -> tuple[Extension, ...]: - if ( - device.cloud_id is None - or "cloud_telephony" not in device.supported_operations - ): - raise ExtensionNotSupported("This device does not support cloud telephony") - return tuple(await super().check_bind(device)) + def _ensure_open(self) -> None: + if self._resource_closed: + raise ExtensionClosed("Phone number is closed") - async def on_bind(self, device: Device) -> None: - if device.cloud_id is None: - raise ExtensionNotSupported("This device does not support cloud telephony") - client = cast( - AsyncMobilerun, - device._unwrap()._number_cloud_client() or self._connection.get("client"), - ) - await devices.bind_number( - device.cloud_id, self.id, billing=self._billing, client=client - ) - self._device_id = device.cloud_id - self._binding_loaded = True - - async def on_unbind(self, device: Device) -> None: - if isinstance(self._binding, _BorrowedNumberBinding) and ( - device._extension_state.closing or self._closing - ): - return # Device cleanup must leave a pre-existing server binding intact. - if device.cloud_id is None: + @staticmethod + async def _telephony_request(request: Awaitable[_T], operation: str) -> _T: + try: + return await request + except APIError as exc: + failure = CloudErrorMapper.from_exception(exc, operation, device=True) + raise failure from None + + async def attach(self, device: AsyncDevice, *, replace: bool = False) -> None: + """Attach to a core cloud device using its public identity.""" + info = device.info() + if info.backend != "cloud" or not info.device_id: raise ExtensionNotSupported("This device does not support cloud telephony") - client = cast( - AsyncMobilerun, - device._unwrap()._number_cloud_client() or self._connection.get("client"), - ) - await devices.unbind_number( - device.cloud_id, billing=self._billing, client=client - ) - self._device_id = None - - def _matches_remote(self, observed: object) -> bool: - return ( - isinstance(observed, _ObservedNumberBinding) - and self.id == observed.number_id - ) + await self.attach_to_cloud_phone(info.device_id, replace=replace) - def _observe_remote_binding(self, device: Device, observed: object | None) -> None: - self._device_id = device.cloud_id if observed is not None else None - if observed is not None: - if not isinstance(observed, _ObservedNumberBinding): - raise TypeError("Unexpected phone number binding observation") - self._phone_number = observed.phone_number - self._binding_loaded = True - - async def _reconcile_bind_failure( - self, device: Device, failure: BaseException + async def attach_to_cloud_phone( + self, device_id: str, *, replace: bool = False ) -> None: - registry = device._extension_state - previous = [ - binding - for binding in registry.bindings.values() - if binding.extension.exclusive == self.exclusive - ] - try: - if device.cloud_id is None: - raise RuntimeError("Missing cloud device ID") - client = cast( - AsyncMobilerun, - device._unwrap()._number_cloud_client() - or self._connection.get("client"), - ) - async with asyncio.timeout(10): - response = await devices.number( - device.cloud_id, billing=self._billing, client=client - ) - binding_data = response.binding - observed = ( - _ObservedNumberBinding( - binding_data.number_id, binding_data.phone_number - ) - if binding_data is not None - else None - ) - selected = None - if observed: - selected = next( - (b for b in previous if b.extension._matches_remote(observed)), - None, + """Attach by cloud ID without opening a UI transport (e.g. in the CLI).""" + async with self._lock: + self._ensure_open() + number_id = self.id + async with self._numbers._client(Billing.NO_COMMERCE) as client: + info = await self._telephony_request( + client.devices.retrieve_capabilities(device_id), + "Retrieve cloud phone capabilities", ) - if selected is None: - number = ( - self - if self.id == observed.number_id - else CloudPhoneNumber( - observed.number_id, - billing=self._billing, - name=self.name, - **self._connection, + if not info.capabilities.telephony: + raise ExtensionNotSupported( + "This device does not support cloud telephony" + ) + number = client.devices.number + current = ( + await self._telephony_request( + number.retrieve(device_id), "Retrieve phone number binding" + ) + ).binding + if current is not None: + if current.number_id == number_id: + self._device_id = device_id + self._phone_number = current.phone_number + return # Observing a link does not claim ownership of it. + if not replace: + raise NumberAttachmentConflict( + operation="Bind phone number", status=409 ) + await self._telephony_request( + number.unbind(device_id), "Unbind phone number" ) - number._check_name(device, tuple(b.extension for b in previous)) - kind = Binding if number is self else _BorrowedNumberBinding - selected = kind(number, device, False) - selected.extension._observe_remote_binding(device, observed) - selected.uncertain = False - for binding in previous: - registry.bindings.pop(binding.extension.name, None) - binding.extension._binding = None - if binding is not selected: - binding.extension._observe_remote_binding(device, None) - if selected is not None: - registry.bindings[selected.extension.name] = selected - selected.extension._binding = selected - except (Exception, asyncio.CancelledError): - if not previous: - binding = Binding(self, device, False, uncertain=True) - registry.bindings[self.name] = binding - self._binding = binding - else: - for binding in previous: - binding.uncertain = True - failure.add_note( - "Remote phone number binding could not be reconciled; binding is uncertain." - ) + try: + result = await self._telephony_request( + number.bind(device_id, number_id=number_id), "Bind phone number" + ) + except CloudAPIError as exc: + # The SDK has no atomic replace. Compensate only after a definite + # rejection, and only if the displaced slot is still empty. + if current is not None and exc.status in {400, 404, 409, 422}: + try: + if ( + await self._telephony_request( + number.retrieve(device_id), + "Retrieve phone number binding", + ) + ).binding is None: + await self._telephony_request( + number.bind(device_id, number_id=current.number_id), + "Bind phone number", + ) + except Exception: + exc.add_note( + "The previous number could not be restored; check the phone's current attachment." + ) + raise + self._device_id = self._attached_device_id = device_id + if result.binding is not None: + self._phone_number = result.binding.phone_number + + async def detach(self) -> bool: + """Detach this number if currently attached; return whether a link was removed.""" + async with self._lock: + self._ensure_open() + return await self._detach(self._attached_device_id, lookup=True) + + async def _detach(self, device_id: str | None, *, lookup: bool) -> bool: + async with self._numbers._client(Billing.NO_COMMERCE) as client: + if device_id is None and lookup: + data = ( + await Numbers(billing=self._billing, client=client).retrieve( + self.id + ) + ).data + if data.device_binding is not None: + device_id = data.device_binding.device_id + if device_id is not None: + number = client.devices.number + current = ( + await self._telephony_request( + number.retrieve(device_id), "Retrieve phone number binding" + ) + ).binding + if current is not None and current.number_id == self.id: + # Do not retry this write automatically if the response is lost. + self._attached_device_id = self._device_id = None + await self._telephony_request( + number.unbind(device_id), "Unbind phone number" + ) + return True + self._attached_device_id = self._device_id = None + return False async def context(self) -> tuple[ContextItem, ...]: return (ContextItem(self.name, "phone_number", {"number": self.phone_number}),) async def release(self) -> Any: - await self.unbind() - result = await numbers.delete( - self.id, billing=self._billing, **self._connection - ) - self._owned = False - return result + async with self._lock: + self._ensure_open() + if self._attached_device_id is not None: + await self._detach(self._attached_device_id, lookup=False) + result = await self._numbers.delete(self.id) + self._owned = False + return result async def on_close(self) -> None: - if self._owned and not self._keep: - await numbers.delete(self.id, billing=self._billing, **self._connection) - self._owned = False + async with self._lock: + if self._attached_device_id is not None: + await self._detach(self._attached_device_id, lookup=False) + if self._owned and not self._keep: + await self._numbers.delete(self.id) + self._owned = False + self._resource_closed = True diff --git a/mobilerun/core/proxy/README.md b/mobilerun/core/proxy/README.md index e0c8b1fb7..a3adadea5 100644 --- a/mobilerun/core/proxy/README.md +++ b/mobilerun/core/proxy/README.md @@ -1,126 +1,70 @@ -# Proxy extensions +# Proxy products -Proxies are standalone extensions, not device settings methods: - -## Quick example - -With an existing connected Android device `android`: +The framework chooses and buys proxy products. `mobilerun_core` validates, +applies, and verifies proxy bindings on one phone. Nothing is adopted or +applied automatically when a phone connects. ```python -from mobilerun.core.proxy import LocalProxy - -proxy = LocalProxy("localhost", 8080) -await proxy.bind(android) -assert android.proxy is proxy -status = await proxy.status() -await proxy.unbind() -assert proxy.device is None -``` - -The default extension name is `proxy`; `phone.proxy` returns the proxy object -itself. Keep the original handle for static typing; there is no typed lookup API. -The device's registry is read-only and shared through wrappers. - -| Class | Compatibility | Exclusive kind | -| --- | --- | --- | -| `CloudRotatingProxy(country, smart_ip=True)` | Cloud device | `proxy` | -| `CloudFixedProxy(id)` | Cloud device | `proxy` | -| `CloudSocks5Proxy(host, port, user, password)` | Cloud device | `proxy` | -| `ExistingCloudProxy()` | Observes an active, unidentified cloud proxy | `proxy` | -| `LocalProxy(host, port)` | Local Android with `http_proxy` support | `proxy` | +from mobilerun_core import ConnectProxyRef -All cloud variants inherit the shared `CloudProxy` base. Compatibility is checked -by the extension using declared device facts, never concrete device class tests. -Credentials are excluded from repr, context and action results. `status()` is a -public typed action returning `ProxyStatus(connected, name, protocol)`. +from mobilerun.core.proxy import CloudFixedProxy -## Conflicts and switching +# `run` is an AsyncMobilerun with an appropriate approval gate. +phone = await run.create_cloud(proxy=ConnectProxyRef("my-connect-id"), plan="minute") -An unmanaged active cloud proxy raises `mobilerun.errors.UnmanagedProxyConflict`, -a subclass of `ExtensionConflict`, unless the bind explicitly uses `force=True`. -It is also re-exported from `mobilerun.core.proxy`. +# Wrap only when you want the extension tools. +selected = CloudFixedProxy(ConnectProxyRef("another-connect-id"), device=phone) +await selected.apply(replace=True) +status = await selected.status() +``` -Binding a second proxy raises `ExtensionConflict`, naming the bound extension, -**before any SDK mutation**. There is no automatic replacement. For local devices, -unbind the old proxy before binding another, or explicitly force replacement: +Give an extension its phone with `device=` before passing it to an operator. +`compile_tools([selected])` exposes `proxy.apply`, `proxy.clear` and +`proxy.status`. The direct Python methods preserve core's typed errors; +compiled tool calls use the framework's generic tool-error boundary. +Cloud phones support Connect IDs and SOCKS5 for live binding; Android ADB +supports HTTP and is the only backend that supports clearing. The current core +factory accepts only Connect IDs for cloud creation. ```python -await replacement.bind(device, force=True) -``` +from mobilerun_core import ConnectProxyRef, HttpProxy -Force only replaces same-kind exclusivity conflicts. Compatibility failures, -unrelated name collisions and SDK errors still raise. It unbinds the old extension -without closing or releasing it, even if device cleanup previously owned it. - -Cloud phones require a proxy. New cloud-device creation uses the supplied typed -`CloudProxy`, or configured rotating defaults, and publishes that exact instance -as a bound extension after creation. No second provisioning request is made. -Passing `None` is invalid. Unbinding the only cloud proxy is rejected: switch with -`new_proxy.bind(phone, force=True)` instead. Closing a borrowed cloud device removes -the local relationship but leaves its required server proxy configured. - -An unmanaged active cloud proxy also requires explicit `force=True` takeover. -Cloud-to-cloud replacement uses one API switching call where supported, not a -disconnect followed by connect. On failure, the coordinator attempts to restore -the old proxy. A failed initial bind or any rollback triggers read-only status -reconciliation **before the original error or cancellation is raised**. The registry -then reflects the remotely active proxy, not the requested configuration. Failed -handles are detached; observing a proxy does not grant ownership of its capacity. -Reconciliation survives repeated caller cancellation and has a 10-second bound. -If status cannot be read, a relationship remains marked uncertain, ordinary actions -fail clearly, and the original error includes a diagnostic note. Reconnect or bind -another proxy with `force=True` to recover. An API error is not a guarantee of -network rollback: some backends disconnect the old proxy before the new one fails. - -After a successful restore, a positive identity match preserves the original -handle and ownership metadata. Policy for an empty remote name: a connected proxy -with no identity also preserves the successfully restored handle. A different, -nonempty but unresolvable reference is not a match: it becomes `ExistingCloudProxy`. - -## Existing cloud phones: read-only adoption - -`await CloudDevice(existing_id)` reads remote proxy status and publishes an -extension without provisioning, switching, disconnecting, or purchasing anything: - -- A `mrc:` name becomes `CloudFixedProxy(id)`. Other nonempty references are - resolved with a read-only Connect lookup when possible. -- Connected but unidentified (including an empty name) becomes - `ExistingCloudProxy`, a typed **existing proxy (unknown)** observation. Its - `status()` action works, but it contains no reusable credentials and cannot be - used to create a cloud phone or reapply an unidentified configuration. -- Disconnected means **no proxy extension**. Connect does not silently repair the - phone. Accessing `phone.proxy` raises an `AttributeError` explaining that there is - no active proxy and suggesting `await proxy.bind(phone)`. - -Both known and unknown observations are exclusive `"proxy"` extensions. They reject -standalone unbind on a cloud phone; replace them with -`await replacement.bind(phone, force=True)`. A failed status read raises instead of -claiming that the phone is disconnected. Successful repeated connects reuse the -observation; reconnecting an uncertain binding reads status again. - -The API resolves an existing Connect proxy ID to credentials; it does not establish -a demonstrated exclusive cross-device lease. Separate handles for the same ID may -therefore work on different devices. Backend errors are surfaced, not invented. - -## CLI and creation - -```console -mobilerun proxy bind PROXY_ID DEVICE_ID --force -mobilerun proxy buy --country US --type dedicated_residential --billing paid -``` +from mobilerun.core.proxy import CloudRotatingProxy, list_connect_proxies -`bind` references an existing ID and does not purchase proxy capacity. Country-based -rotating proxies may provision capacity and require the existing billing approval. -Only rotating proxies expose smart-IP settings. Configured defaults use -`MOBILERUN_CLOUD_PROXY_COUNTRY` and `MOBILERUN_CLOUD_PROXY_SMART_IP`. +async for entry in list_connect_proxies(included_only=True): + print(entry.ref.id, entry.status) # no endpoint or credentials -`buy_proxy` checkout, timeout and cancellation behavior is unchanged. Without a -checkout callback, `PaymentRequired` can be resumed without cancelling on timeout. -Callbacks use typed checkout details. By default (`checkout="error"`) the library -never prints or opens a browser; `checkout="print"` / `checkout="browser"` opt in. +rotating = await CloudRotatingProxy.select("de") # reuse, never buy +status = await phone.proxy_status() +if status.connected and status.protocol == "socks5" and status.reference: + configured = ConnectProxyRef(status.reference) -Breaking change: `Device.set_proxy`, `clear_proxy`, and `proxy_status` are removed, -including wrapper and pool variants. Pools bind separate extension instances via -`bind_each`; `pool.actions.call("proxy.status", {})` broadcasts explicitly. +await local_android.set_proxy(HttpProxy("proxy.example", 8080)) +``` -See [devices](../devices/README.md) and [extensions](../extensions/README.md). +An unidentified active proxy has no reusable Connect reference. +Country selection only reuses an active +residential proxy; it does not request Smart IP or provision implicitly. +`CloudSocks5Proxy.from_url(...)` accepts a SOCKS5 URL with optional percent-encoded +userinfo; the resolved core value holds credentials as `Secret`. + +`CloudFixedProxy.purchase(...)` and `CloudRotatingProxy.purchase(...)` **can +incur charges**. A successfully returned product owns the purchase; call its +`close()` to release it. Close never clears a phone or releases a borrowed ID. +Use `purchase_connect_proxy(...)` for a persistent purchase and +`release_connect_proxy(id)` for explicit release. The purchase result carries a +`ref` you can pass to `device.set_proxy()` without rebuilding it. `no_commerce` +blocks purchases. + +For raw SDK responses and individual catalogue pages, use the +[bound Proxies adapter](../../clients/cloud/README.md). Prefer the account +functions above when you only need product details without credentials. + +| File | Purpose | +| --- | --- | +| `base.py` | Core value conversion and three device tools | +| `account.py` | Safe Connect catalogue, purchase, status and release | +| `cloud_fixed.py`, `cloud_rotating.py` | Select Connect capacity; explicit owned purchase | +| `cloud_socks5.py` | Bring your own SOCKS5 endpoint | + +See [proxy CLI](../../cli/proxy/README.md) and [extensions](../extensions/README.md). diff --git a/mobilerun/core/proxy/__init__.py b/mobilerun/core/proxy/__init__.py index 0a9de24eb..17b2fdfb4 100644 --- a/mobilerun/core/proxy/__init__.py +++ b/mobilerun/core/proxy/__init__.py @@ -1,20 +1,23 @@ -from mobilerun.models.proxy import ProxyStatus +"""Select, buy, and use proxy products with core phones.""" -from .base import CloudProxy, Proxy, UnmanagedProxyConflict +from .account import ( + get_connect_proxy, + list_connect_proxies, + purchase_connect_proxy, + release_connect_proxy, +) +from .base import Proxy from .cloud_fixed import CloudFixedProxy from .cloud_rotating import CloudRotatingProxy from .cloud_socks5 import CloudSocks5Proxy -from .existing import ExistingCloudProxy -from .local import LocalProxy __all__ = [ "Proxy", - "CloudProxy", - "ExistingCloudProxy", - "LocalProxy", "CloudRotatingProxy", "CloudFixedProxy", "CloudSocks5Proxy", - "ProxyStatus", - "UnmanagedProxyConflict", + "get_connect_proxy", + "list_connect_proxies", + "purchase_connect_proxy", + "release_connect_proxy", ] diff --git a/mobilerun/core/proxy/account.py b/mobilerun/core/proxy/account.py new file mode 100644 index 000000000..49e650a0e --- /dev/null +++ b/mobilerun/core/proxy/account.py @@ -0,0 +1,151 @@ +"""Account-level Connect catalogue and commerce; no phone operations.""" + +from collections.abc import AsyncIterator, Awaitable +from typing import Protocol, TypedDict, TypeVar + +from mobilerun_core import ConnectProxyRef + +from mobilerun.clients.cloud.proxies import BuyParams, Proxies +from mobilerun.config.settings import get_settings +from mobilerun.errors.cloud import CloudAPIError, PaymentRequired +from mobilerun.models.billing import Billing +from mobilerun.models.checkout import CheckoutCallback +from mobilerun.models.proxy import ProxyProduct, ProxyProductType +from mobilerun.utils.checkout.presentation import CheckoutMode +from mobilerun.utils.redaction import mask_url + +T = TypeVar("T") + + +class _CatalogueFilters(TypedDict, total=False): + country: str + type: list[ProxyProductType] + + +class _AccountRow(Protocol): + @property + def id(self) -> str: ... + @property + def name(self) -> str: ... + @property + def country(self) -> str: ... + @property + def status(self) -> str: ... + @property + def type(self) -> ProxyProductType: ... + @property + def billing_mode(self) -> str | None: ... + + +def _product(row: _AccountRow) -> ProxyProduct: + # SDK retrieve/buy results contain credentials. Publish no endpoint, user, + # password, or checkout URL in the account product. + label = mask_url(row.name) if "://" in row.name else row.name + return ProxyProduct( + ConnectProxyRef(row.id), + label, + row.country, + row.status, + row.type, + row.billing_mode, + ) + + +async def _account_call(operation: Awaitable[T]) -> T: + try: + return await operation + except CloudAPIError as error: + # The adapter's public message is sanitized, but its SDK cause can + # contain an entire proxy response. Do not expose that chain at this boundary. + safe = error + safe.__context__ = None + raise safe.with_traceback(None) from None + + +async def list_connect_proxies( + *, + billing: Billing | str = Billing.NO_COMMERCE, + included_only: bool = False, + country: str | None = None, + proxy_type: ProxyProductType | None = None, +) -> AsyncIterator[ProxyProduct]: + """Stream credential-free account products across all catalogue pages.""" + filters: _CatalogueFilters = {} + if country is not None: + filters["country"] = country + if proxy_type is not None: + filters["type"] = [proxy_type] + + proxies = Proxies(billing=Billing(billing)) + page = 1 + while True: + result = await _account_call( + proxies.list( + included_only=included_only, + page=page, + page_size=100, + **filters, + ) + ) + for row in result.items: + yield _product(row) + if not result.pagination.has_next: + return + page += 1 + + +async def get_connect_proxy( + id: str, *, billing: Billing | str = Billing.NO_COMMERCE +) -> ProxyProduct: + """Read account product status, not the proxy status of a phone.""" + ref = ConnectProxyRef(id) + return _product( + await _account_call(Proxies(billing=Billing(billing)).retrieve(ref.id)) + ) + + +async def release_connect_proxy( + id: str, *, billing: Billing | str = Billing.NO_COMMERCE +) -> None: + """Explicitly release an account proxy, including a caller-supplied ID.""" + ref = ConnectProxyRef(id) + await _account_call(Proxies(billing=Billing(billing)).cancel(ref.id)) + + +async def purchase_connect_proxy( + country: str, + *, + proxy_type: ProxyProductType = "residential", + product_name: str | None = None, + billing: Billing | str | None = None, + checkout: CheckoutMode = "error", + payment_timeout: float = 600, + on_checkout: CheckoutCallback | None = None, +) -> ProxyProduct: + """Buy a persistent account proxy (may charge); release it explicitly.""" + mode = get_settings().MOBILERUN_BILLING if billing is None else Billing(billing) + if product_name is not None and "://" in product_name: + raise ValueError("Use a display name, not a URL, for the proxy product") + params: BuyParams = {} + if product_name is not None: + params["name"] = product_name + try: + result = await _account_call( + Proxies(billing=mode).buy( + country, + type=proxy_type, + checkout=checkout, + payment_timeout=payment_timeout, + on_checkout=on_checkout, + **params, + ) + ) + except PaymentRequired as error: + pending = error + else: + return _product(result) + + async def resume(timeout: float) -> ProxyProduct: + return _product(await _account_call(pending.wait_until_paid(timeout))) + + raise PaymentRequired(pending.checkout, resume) diff --git a/mobilerun/core/proxy/adoption.py b/mobilerun/core/proxy/adoption.py deleted file mode 100644 index 8373642b9..000000000 --- a/mobilerun/core/proxy/adoption.py +++ /dev/null @@ -1,75 +0,0 @@ -"""Read-only remote observation; callers hold the shared registry lock.""" - -from __future__ import annotations - -import asyncio -from typing import TYPE_CHECKING - -from mobilerun.core.extensions.registry import Binding -from mobilerun.core.proxy.cloud_fixed import CloudFixedProxy -from mobilerun.core.proxy.existing import ExistingCloudProxy -from mobilerun.models.proxy import ProxyStatus - -if TYPE_CHECKING: - from mobilerun.core.devices.base import Device - from mobilerun.core.proxy.base import CloudProxy - -_READBACK_TIMEOUT = 10.0 - - -async def _proxy_id(device: Device, status: ProxyStatus) -> str | None: - reference = status.name or "" - if reference.startswith("mrc:"): - return reference[4:].strip() or None - if not reference: - return None - return await device._proxy_target._resolve_reference(reference) - - -async def _adopt_remote_proxy( - device: Device, *, name: str = "proxy", restored: CloudProxy | None = None -) -> None: - deadline = asyncio.get_running_loop().time() + _READBACK_TIMEOUT - async with asyncio.timeout_at(deadline): - status = await device._proxy_target.status() - registry = device._extension_state - previous = tuple( - binding - for binding in registry.bindings.values() - if binding.extension.exclusive == "proxy" - ) - observed: CloudProxy | None = None - if status.connected: - try: - async with asyncio.timeout_at(deadline): - proxy_id = await _proxy_id(device, status) - except Exception: - # A failed identity read does not invalidate a successful status - # read: the proxy is known active, only its identity is unknown. - proxy_id = None - if restored is not None: - applied = restored._last_applied_status - reference = (applied.name or "").removeprefix("mrc:") if applied else "" - observed_reference = (status.name or "").removeprefix("mrc:") - if not status.name or ( - reference and reference in (proxy_id, observed_reference) - ): - # The restore hook succeeded and read-back has no contradictory - # identity. Retain the user's handle and all binding metadata. - return - observed = ( - CloudFixedProxy(proxy_id, name=name) - if proxy_id is not None - else ExistingCloudProxy(name=name) - ) - observed._check_name(device, tuple(binding.extension for binding in previous)) - observed._action_entries() - # Publish only after status/identity reads and validation succeeded. Never - # invoke bind/unbind hooks: observation must not switch the remote proxy. - for binding in previous: - registry.bindings.pop(binding.extension.name) - binding.extension._binding = None - if observed is not None: - binding = Binding(observed, device, False) - registry.bindings[observed.name] = binding - observed._binding = binding diff --git a/mobilerun/core/proxy/base.py b/mobilerun/core/proxy/base.py index dbc350dd4..d8fc9fcb2 100644 --- a/mobilerun/core/proxy/base.py +++ b/mobilerun/core/proxy/base.py @@ -1,133 +1,91 @@ -"""Standalone proxy extensions; compatibility belongs to the extension.""" - -from __future__ import annotations - -import asyncio -from collections.abc import Sequence -from typing import TYPE_CHECKING - -from mobilerun.core.extensions import Extension, action, device_action -from mobilerun.core.proxy.target import ProxyTarget -from mobilerun.errors import ( - ExtensionConflict, - ExtensionNotSupported, - UnmanagedProxyConflict, +"""Framework proxy products and their explicit device tools.""" + +from collections.abc import Awaitable, Callable, Sequence +from functools import wraps +from typing import Concatenate, Generic, ParamSpec, TypeVar + +from mobilerun_core import ( + AsyncDevice, + ConnectProxyRef, + HttpProxy, + ProxyStatus, + Socks5Proxy, ) + +from mobilerun.core.extensions import Extension, function from mobilerun.models.context import ContextItem -from mobilerun.models.proxy import ProxyStatus +from mobilerun.utils.redaction import secret_scope -if TYPE_CHECKING: - from mobilerun.core.devices.base import Device +P = TypeVar("P", bound=ConnectProxyRef | HttpProxy | Socks5Proxy, covariant=True) +_Receiver = TypeVar("_Receiver", bound=Extension) +_Args = ParamSpec("_Args") +_Result = TypeVar("_Result") -class Proxy(Extension): - default_name = "proxy" - exclusive = "proxy" - _last_applied_status: ProxyStatus | None = None - - async def on_bind(self, device: Device) -> None: - self._last_applied_status = await self._apply(device._proxy_target) - - async def on_unbind(self, device: Device) -> None: - await device._proxy_target.disconnect() - - def _mark_uncertain(self, device: Device, failure: BaseException) -> None: - from mobilerun.core.extensions.registry import Binding - - registry = device._extension_state - previous = [ - binding - for binding in registry.bindings.values() - if binding.extension.exclusive == "proxy" - ] - if not previous: - binding = Binding(self, device, False, uncertain=True) - registry.bindings[self.name] = binding - self._binding = binding - else: - for binding in previous: - binding.uncertain = True - failure.add_note( - "Remote proxy status could not be reconciled; binding is uncertain. Reconnect or bind another proxy with force=True to recover." - ) +def _device_tool( + method: Callable[Concatenate[_Receiver, _Args], Awaitable[_Result]], +) -> Callable[Concatenate[_Receiver, _Args], Awaitable[_Result]]: + """Expose the public method's signature, but resolve overrides at dispatch.""" - @device_action - async def status(self, device: Device) -> ProxyStatus: - """Return current device proxy connection state without credentials.""" - return await device._proxy_target.status() + @wraps(method) + async def dispatch( + self: _Receiver, /, *args: _Args.args, **kwargs: _Args.kwargs + ) -> _Result: + return await getattr(self, method.__name__)(*args, **kwargs) - async def context(self) -> Sequence[ContextItem]: - return (ContextItem(self.name, "proxy", {"kind": self.exclusive}),) + return function(dispatch) - async def _apply(self, target: ProxyTarget) -> ProxyStatus: - raise NotImplementedError - def _parameters(self) -> dict[str, object]: - raise NotImplementedError +class Proxy(Extension, Generic[P]): + """A selected proxy product, optionally used with an explicitly supplied phone.""" + default_name = "proxy" -class CloudProxy(Proxy): - """Shared type for cloud-device creation and cloud-only proxy checks.""" + def __init__( + self, value: P, *, device: AsyncDevice | None = None, name: str | None = None + ) -> None: + super().__init__(name=name) + self._phone = device + self._value = value + + def as_device_proxy(self) -> P: + """Return the core value without connecting a phone or buying capacity.""" + return self._value + + def _require_phone(self) -> AsyncDevice: + if self._phone is None: + raise ValueError( + "Pass device= when creating a proxy extension to use its phone tools" + ) + return self._phone + + async def apply(self, *, replace: bool = False) -> None: + """Apply this proxy to the selected phone; replacement must be explicit.""" + value = self.as_device_proxy() + phone = self._require_phone() + if isinstance(value, Socks5Proxy): + with secret_scope( + *( + secret.reveal() + for secret in (value.user, value.password) + if secret is not None + ) + ): + await phone.set_proxy(value, replace=replace) + else: + await phone.set_proxy(value, replace=replace) - cloud_native = True + async def clear(self) -> None: + """Clear the selected phone's proxy; Android ADB only.""" + await self._require_phone().clear_proxy() - @action async def status(self) -> ProxyStatus: - """Return remote status when attached, or disconnected when unbound.""" - device = self.device - return ( - ProxyStatus(False) - if device is None - else await device._proxy_target.status() - ) - - def _can_switch(self, device: Device) -> bool: - return "proxy_switch" in device.supported_operations - - async def _reconcile_bind_failure( - self, device: Device, failure: BaseException - ) -> None: - if isinstance(failure, UnmanagedProxyConflict): - # on_bind refused before applying anything; there is no remote - # mutation to reconcile and the incoming extension remains unbound. - return - from mobilerun.core.proxy.adoption import _adopt_remote_proxy - - try: - restored = ( - self - if self._binding is not None and not self._binding.uncertain - else None - ) - await _adopt_remote_proxy(device, name=self.name, restored=restored) - except (Exception, asyncio.CancelledError): - self._mark_uncertain(device, failure) - - async def check_bind(self, device: Device) -> Sequence[Extension]: - conflicts = await super().check_bind(device) - if device.cloud_id is None: - raise ExtensionNotSupported("Cloud proxies require a cloud device") - return conflicts - - async def on_bind(self, device: Device) -> None: - state = device._extension_state - status = await device._proxy_target.status() - if status.connected and not state.force: - raise UnmanagedProxyConflict( - "Device has an unmanaged active proxy; use force=True to take over" - ) - await super().on_bind(device) - - async def _check_unbind(self, device: Device) -> None: - state = device._extension_state - if state.switching: - return # The incoming cloud proxy replaces upstream in one SDK call. - if not state.closing: - raise ExtensionConflict( - "cloud phones need a proxy; bind another one with force=True to switch" - ) + """Read the selected phone's proxy status without credentials.""" + return await self._require_phone().proxy_status() - async def on_unbind(self, device: Device) -> None: - await self._check_unbind(device) - # Closing a borrowed cloud phone must not leave it proxy-less. Closing - # the relationship leaves its server configuration intact. + _apply_tool = _device_tool(apply) + _clear_tool = _device_tool(clear) + _status_tool = _device_tool(status) + + async def context(self) -> Sequence[ContextItem]: + return (ContextItem(self.name, "proxy", {"product": type(self).__name__}),) diff --git a/mobilerun/core/proxy/cloud_fixed.py b/mobilerun/core/proxy/cloud_fixed.py index 999808faf..4fb454ea9 100644 --- a/mobilerun/core/proxy/cloud_fixed.py +++ b/mobilerun/core/proxy/cloud_fixed.py @@ -1,19 +1,67 @@ -"""Select an existing purchased Mobilerun Connect proxy.""" +"""Select or buy Mobilerun Connect proxy capacity.""" -from mobilerun.core.proxy.base import CloudProxy -from mobilerun.core.proxy.target import ProxyTarget -from mobilerun.models.proxy import ProxyStatus +from typing import ClassVar, Self +from mobilerun_core import AsyncDevice, ConnectProxyRef -class CloudFixedProxy(CloudProxy): - def __init__(self, id: str, *, name: str | None = None) -> None: - super().__init__(name=name) - if not id: - raise ValueError("An existing proxy id is required") - self.id = id +from mobilerun.core.proxy.account import purchase_connect_proxy, release_connect_proxy +from mobilerun.core.proxy.base import Proxy +from mobilerun.models.billing import Billing +from mobilerun.models.checkout import CheckoutCallback +from mobilerun.models.proxy import ProxyProductType +from mobilerun.utils.checkout.presentation import CheckoutMode - def _parameters(self) -> dict[str, object]: - return {"connect": {"id": self.id}} - async def _apply(self, target: ProxyTarget) -> ProxyStatus: - return await target.connect_fixed(id=self.id) +class CloudFixedProxy(Proxy[ConnectProxyRef]): + """Use a known Connect ID rather than an implicit country-based purchase.""" + + _purchase_type: ClassVar[ProxyProductType] = "dedicated_residential" + + def __init__( + self, + ref: ConnectProxyRef, + *, + device: AsyncDevice | None = None, + name: str | None = None, + ) -> None: + super().__init__(ref, device=device, name=name) + self._owned = False + + @property + def id(self) -> str: + """The Connect proxy ID, not a credential.""" + return self.as_device_proxy().id + + @classmethod + async def purchase( + cls, + country: str, + *, + device: AsyncDevice | None = None, + name: str | None = None, + product_name: str | None = None, + billing: Billing | str | None = None, + checkout: CheckoutMode = "error", + payment_timeout: float = 600, + on_checkout: CheckoutCallback | None = None, + ) -> Self: + """Buy a proxy (may charge); close releases it. Pass a name for the extension, if any.""" + # Validate the extension name before the paid request. + proxy = cls(ConnectProxyRef("pending"), name=name, device=device) + bought = await purchase_connect_proxy( + country, + proxy_type=cls._purchase_type, + product_name=product_name, + billing=billing, + checkout=checkout, + payment_timeout=payment_timeout, + on_checkout=on_checkout, + ) + proxy._value = bought.ref + proxy._owned = True + return proxy + + async def on_close(self) -> None: + if self._owned: + await release_connect_proxy(self.id, billing=Billing.NO_COMMERCE) + self._owned = False diff --git a/mobilerun/core/proxy/cloud_rotating.py b/mobilerun/core/proxy/cloud_rotating.py index 75081720f..08009e164 100644 --- a/mobilerun/core/proxy/cloud_rotating.py +++ b/mobilerun/core/proxy/cloud_rotating.py @@ -1,38 +1,42 @@ -"""Rotating residential Mobilerun Connect proxy selection.""" +"""Choose existing rotating residential Connect capacity.""" -from typing import Self +from typing import ClassVar, Self -from mobilerun.config.settings import get_settings -from mobilerun.core.proxy.base import CloudProxy -from mobilerun.core.proxy.target import ProxyTarget -from mobilerun.models.proxy import ProxyStatus +from mobilerun_core import AsyncDevice +from mobilerun.core.proxy.account import list_connect_proxies +from mobilerun.core.proxy.cloud_fixed import CloudFixedProxy +from mobilerun.models.billing import Billing +from mobilerun.models.proxy import ProxyProductType -class CloudRotatingProxy(CloudProxy): - def __init__( - self, country: str, smart_ip: bool = True, *, name: str | None = None - ) -> None: - super().__init__(name=name) - if not country: - raise ValueError("A country is required for a rotating proxy") - self.country = country - self.smart_ip = smart_ip - @classmethod - def _from_settings(cls) -> Self: - settings = get_settings() - return cls( - country=settings.MOBILERUN_CLOUD_PROXY_COUNTRY, - smart_ip=settings.MOBILERUN_CLOUD_PROXY_SMART_IP, - ) +class CloudRotatingProxy(CloudFixedProxy): + """Choose a residential proxy by country, without making a purchase.""" - def _parameters(self) -> dict[str, object]: - return { - "connect": {"country": self.country}, - "smart_ip": self.smart_ip, - } + _purchase_type: ClassVar[ProxyProductType] = "residential" - async def _apply(self, target: ProxyTarget) -> ProxyStatus: - return await target.connect_rotating( - country=self.country, smart_ip=self.smart_ip + @classmethod + async def select( + cls, + country: str, + *, + device: AsyncDevice | None = None, + name: str | None = None, + billing: Billing | str = Billing.NO_COMMERCE, + ) -> Self: + """Select the first active residential proxy in this country.""" + country = country.strip().lower() + if len(country) != 2 or not country.isascii() or not country.isalpha(): + raise ValueError("Expected a two-letter proxy country code") + async for item in list_connect_proxies( + country=country, proxy_type="residential", billing=billing + ): + if ( + item.status == "active" + and item.type == "residential" + and item.country.lower() == country + ): + return cls(item.ref, device=device, name=name) + raise LookupError( + "No active residential Connect proxy found in the requested country" ) diff --git a/mobilerun/core/proxy/cloud_socks5.py b/mobilerun/core/proxy/cloud_socks5.py index 835f939a4..a63d0c262 100644 --- a/mobilerun/core/proxy/cloud_socks5.py +++ b/mobilerun/core/proxy/cloud_socks5.py @@ -1,11 +1,14 @@ -"""SOCKS5 parameters; repr never exposes the password.""" +"""Bring your own SOCKS5 endpoint without exposing its credentials.""" -from mobilerun.core.proxy.base import CloudProxy -from mobilerun.core.proxy.target import ProxyTarget -from mobilerun.models.proxy import ProxyStatus +from typing import Self +from urllib.parse import unquote, urlsplit +from mobilerun_core import AsyncDevice, Secret, Socks5Proxy -class CloudSocks5Proxy(CloudProxy): +from mobilerun.core.proxy.base import Proxy + + +class CloudSocks5Proxy(Proxy[Socks5Proxy]): def __init__( self, host: str, @@ -13,30 +16,41 @@ def __init__( user: str | None = None, password: str | None = None, *, + device: AsyncDevice | None = None, name: str | None = None, ) -> None: - super().__init__(name=name) - self.host = host - self.port = port - self.user = user - self.password = password - - def _parameters(self) -> dict[str, object]: - result: dict[str, object] = { - "socks5": { - key: value - for key, value in { - "host": self.host, - "port": self.port, - "user": self.user, - "password": self.password, - }.items() - if value is not None - } - } - return result - - async def _apply(self, target: ProxyTarget) -> ProxyStatus: - return await target.connect_socks5( - self.host, self.port, self.user, self.password + value = Socks5Proxy( + host, + port, + user=Secret(user) if user is not None else None, + password=Secret(password) if password is not None else None, ) + super().__init__(value, device=device, name=name) + + @classmethod + def from_url( + cls, url: str, *, device: AsyncDevice | None = None, name: str | None = None + ) -> Self: + """Parse a SOCKS5 URL, including optional percent-encoded credentials.""" + try: + parts = urlsplit(url) + host, port = parts.hostname, parts.port + if ( + parts.scheme == "socks5" + and host + and port + and parts.path in ("", "/") + and not parts.query + and not parts.fragment + ): + return cls( + host, + port, + unquote(parts.username) if parts.username is not None else None, + unquote(parts.password) if parts.password is not None else None, + device=device, + name=name, + ) + except ValueError: + pass + raise ValueError("Invalid SOCKS5 proxy URL") diff --git a/mobilerun/core/proxy/existing.py b/mobilerun/core/proxy/existing.py deleted file mode 100644 index e69d7887a..000000000 --- a/mobilerun/core/proxy/existing.py +++ /dev/null @@ -1,45 +0,0 @@ -"""Read-only representation of an active but unidentified cloud proxy.""" - -from __future__ import annotations - -from collections.abc import Sequence -from typing import TYPE_CHECKING - -from mobilerun.core.proxy.base import CloudProxy -from mobilerun.core.proxy.target import ProxyTarget -from mobilerun.errors import ExtensionConflict -from mobilerun.models.context import ContextItem -from mobilerun.models.proxy import ProxyStatus - -if TYPE_CHECKING: - from mobilerun.core.devices.base import Device - - -class ExistingCloudProxy(CloudProxy): - """An observed existing proxy, not credentials or provisionable capacity.""" - - async def on_bind(self, device: Device) -> None: - from mobilerun.core.proxy.adoption import _proxy_id - - status = await device._proxy_target.status() - if not status.connected or await _proxy_id(device, status) is not None: - raise ExtensionConflict( - "The unidentified existing proxy is no longer active" - ) - - async def _apply(self, target: ProxyTarget) -> ProxyStatus: - raise ExtensionConflict( - "An unidentified existing proxy cannot be provisioned or restored" - ) - - def _parameters(self) -> dict[str, object]: - raise ExtensionConflict( - "An unidentified existing proxy cannot be used for cloud creation" - ) - - async def context(self) -> Sequence[ContextItem]: - return ( - ContextItem( - self.name, "proxy", {"description": "existing proxy (unknown)"} - ), - ) diff --git a/mobilerun/core/proxy/local.py b/mobilerun/core/proxy/local.py deleted file mode 100644 index aa9a87329..000000000 --- a/mobilerun/core/proxy/local.py +++ /dev/null @@ -1,94 +0,0 @@ -"""Validated host and port for device HTTP proxies.""" - -from __future__ import annotations - -import asyncio -import ipaddress -import re -from collections.abc import Sequence -from typing import TYPE_CHECKING - -from mobilerun.core.extensions import Extension -from mobilerun.core.proxy.base import Proxy -from mobilerun.core.proxy.target import ProxyTarget -from mobilerun.errors import DeviceOperationNotSupported, ExtensionNotSupported -from mobilerun.models.proxy import ProxyStatus - -if TYPE_CHECKING: - from mobilerun.core.devices.base import Device - - -class LocalProxy(Proxy): - async def _reconcile_bind_failure( - self, device: Device, failure: BaseException - ) -> None: - from mobilerun.core.extensions.registry import Binding - - try: - async with asyncio.timeout(10): - status = await device._proxy_target.status() - observed = None - if status.connected: - host, _, port = (status.name or "").rpartition(":") - observed = LocalProxy(host.strip("[]"), int(port), name=self.name) - registry = device._extension_state - previous = tuple( - binding - for binding in registry.bindings.values() - if binding.extension.exclusive == "proxy" - ) - for binding in previous: - registry.bindings.pop(binding.extension.name) - binding.extension._binding = None - if observed is not None: - binding = Binding(observed, device, False) - registry.bindings[observed.name] = binding - observed._binding = binding - except (Exception, asyncio.CancelledError): - self._mark_uncertain(device, failure) - - def __init__(self, host: str, port: int, *, name: str | None = None) -> None: - super().__init__(name=name) - self.host = host - self.port = port - try: - ipaddress.ip_address(self.host) - except ValueError: - hostname = self.host.removesuffix(".") - if ( - len(hostname) > 253 - or not hostname - or not all( - re.fullmatch( - r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?", label - ) - for label in hostname.split(".") - ) - ): - raise ValueError("Invalid proxy host") from None - if not 1 <= self.port <= 65535: - raise ValueError("Invalid proxy port") - - async def check_bind(self, device: Device) -> Sequence[Extension]: - conflicts = await super().check_bind(device) - if ( - device.cloud_id is not None - or device.platform.lower() != "android" - or "http_proxy" not in device.supported_operations - ): - raise ExtensionNotSupported( - "LocalProxy requires local Android http_proxy support" - ) - return conflicts - - def __str__(self) -> str: - host = f"[{self.host}]" if ":" in self.host else self.host - return f"{host}:{self.port}" - - def _parameters(self) -> dict[str, object]: - raise DeviceOperationNotSupported( - "HTTP proxies aren't supported on cloud devices; use CloudRotatingProxy, CloudFixedProxy or CloudSocks5Proxy" - ) - - async def _apply(self, target: ProxyTarget) -> ProxyStatus: - return await target.set_http_proxy(self.host, self.port) diff --git a/mobilerun/core/proxy/target.py b/mobilerun/core/proxy/target.py deleted file mode 100644 index 80d92a658..000000000 --- a/mobilerun/core/proxy/target.py +++ /dev/null @@ -1,140 +0,0 @@ -"""Typed proxy application boundary, independent of device implementations.""" - -from __future__ import annotations - -from collections.abc import Awaitable, Callable -from typing import TYPE_CHECKING - -if TYPE_CHECKING: - from mobilerun.clients.cloud.proxies import ProxyConnectParams - -from mobilerun.errors import DeviceOperationNotSupported -from mobilerun.models.proxy import ProxyStatus - - -class ProxyTarget: - async def _resolve_reference(self, reference: str) -> str | None: - return None - - async def status(self) -> ProxyStatus: - raise DeviceOperationNotSupported("Proxy status is unsupported") - - async def disconnect(self) -> None: - raise DeviceOperationNotSupported("Proxy disconnect is unsupported") - - async def connect_rotating(self, *, country: str, smart_ip: bool) -> ProxyStatus: - raise DeviceOperationNotSupported( - "CloudRotatingProxy isn't supported on this device" - ) - - async def connect_fixed(self, *, id: str) -> ProxyStatus: - raise DeviceOperationNotSupported( - "CloudFixedProxy isn't supported on this device" - ) - - async def connect_socks5( - self, - host: str, - port: int, - user: str | None, - password: str | None, - ) -> ProxyStatus: - raise DeviceOperationNotSupported( - "CloudSocks5Proxy isn't supported on this device" - ) - - async def set_http_proxy(self, host: str, port: int) -> ProxyStatus: - raise DeviceOperationNotSupported("LocalProxy isn't supported on this device") - - -class CloudProxyTarget(ProxyTarget): - def __init__( - self, - connect: Callable[[ProxyConnectParams], Awaitable[ProxyStatus]], - status: Callable[[], Awaitable[ProxyStatus]] | None = None, - disconnect: Callable[[], Awaitable[None]] | None = None, - *, - resolve_reference: Callable[[str], Awaitable[str | None]] | None = None, - ) -> None: - self._connect = connect - self._status = status - self._disconnect = disconnect - self._resolve = resolve_reference - - async def _resolve_reference(self, reference: str) -> str | None: - if self._resolve is None: - return None - return await self._resolve(reference) - - async def status(self) -> ProxyStatus: - if self._status is None: - return await super().status() - return await self._status() - - async def disconnect(self) -> None: - if self._disconnect is None: - return await super().disconnect() - await self._disconnect() - - async def connect_rotating(self, *, country: str, smart_ip: bool) -> ProxyStatus: - return await self._connect( - {"connect": {"country": country}, "smart_ip": smart_ip} - ) - - async def connect_fixed(self, *, id: str) -> ProxyStatus: - return await self._connect({"connect": {"id": id}}) - - async def set_http_proxy(self, host: str, port: int) -> ProxyStatus: - raise DeviceOperationNotSupported( - "HTTP proxies aren't supported on cloud devices; use CloudRotatingProxy, CloudFixedProxy or CloudSocks5Proxy" - ) - - async def connect_socks5( - self, - host: str, - port: int, - user: str | None, - password: str | None, - ) -> ProxyStatus: - params: ProxyConnectParams = {"socks5": {"host": host, "port": port}} - if user is not None: - params["socks5"]["user"] = user - if password is not None: - params["socks5"]["password"] = password - return await self._connect(params) - - -class AndroidProxyTarget(ProxyTarget): - def __init__( - self, - set_http: Callable[[str, int], Awaitable[ProxyStatus]], - status: Callable[[], Awaitable[ProxyStatus]] | None = None, - disconnect: Callable[[], Awaitable[None]] | None = None, - ) -> None: - self._set_http = set_http - self._status = status - self._disconnect = disconnect - - async def status(self) -> ProxyStatus: - if self._status is None: - return await super().status() - return await self._status() - - async def disconnect(self) -> None: - if self._disconnect is None: - return await super().disconnect() - await self._disconnect() - - async def connect_rotating(self, *, country: str, smart_ip: bool) -> ProxyStatus: - raise DeviceOperationNotSupported("Android local supports only LocalProxy") - - async def connect_fixed(self, *, id: str) -> ProxyStatus: - raise DeviceOperationNotSupported("Android local supports only LocalProxy") - - async def connect_socks5( - self, host: str, port: int, user: str | None, password: str | None - ) -> ProxyStatus: - raise DeviceOperationNotSupported("Android local supports only LocalProxy") - - async def set_http_proxy(self, host: str, port: int) -> ProxyStatus: - return await self._set_http(host, port) diff --git a/mobilerun/core/runs/README.md b/mobilerun/core/runs/README.md index 26bbc78c4..b2a885c1c 100644 --- a/mobilerun/core/runs/README.md +++ b/mobilerun/core/runs/README.md @@ -1,59 +1,86 @@ # runs/ -Store device-action outcomes independently of macros or agents. The writer -manages lazy creation, status and step attribution. Callers appending `RunStep` -directly must redact their own arguments and evidence. +Record an existing core phone without wrapping its device methods or taking +ownership of its connection. ```python -from datetime import datetime, timezone from pathlib import Path -from uuid import uuid4 - -from mobilerun.core.runs import RunWriter -from mobilerun.models import DeviceInfo, RunRecord, RunStep - -now = datetime.now(timezone.utc) -writer = RunWriter( - RunRecord( - run_id=uuid4().hex, kind="recording", started_at=now, - device=DeviceInfo(platform="android", identifier="local"), - ), - Path("runs"), -) -writer.append(RunStep(i=1, started_at=now, finished_at=now, action="tap", - args={"x": 10, "y": 20}, ok=True, by="script")) -writer.finish("succeeded") + +from mobilerun.core.runs import ActionRecording, ScreenRecording + +async with ActionRecording(phone, runs_dir=Path("runs")) as rec: + await phone.tap(10, 20) + rec.finish("succeeded") + +async with ScreenRecording(phone, runs_dir=Path("runs")) as rec: + await phone.key("home") + rec.finish("succeeded") ``` -`run_dir` is the prospective path. It is created on the first append, or -explicitly by `start()` when another evidence sink needs it first. Finishing -an unused writer creates no files. Each append flushes one JSONL row before -advancing `step_index`; `finish()` replaces `run.json` atomically. No resume or -crash durability is provided. After an append I/O failure, do not rerun the -device action or append again. The writer may still finalize a started run. - -Use `recording_scope(enabled=False)` to suppress recording in the current task, -or `recording_scope(by="agent")` to override the actor. `recording_policy()` -returns the effective `(enabled, actor_override)`. A nested scope cannot lift -suppression from an outer scope. - -`collect_steps()` includes committed rows from the current context and tasks -spawned inside the block. Await those tasks before leaving the block. Nested -blocks see their own rows and contribute them to enclosing blocks. - -Each step has UTC action start and finish times, excluding evidence capture. -`RecordingDevice(capture="full")` (the default) stores structural before/after -fingerprints, redacted UI and context JSON, and PNG files when available. -Snapshots live under `screens/..*`; a step can reference the -previous step's after files as its before state. `capture="actions"` skips -all automatic screen observation and stores only the action and outcome data. -**Screenshots are not redacted. Use `capture="actions"` for sensitive flows.** +`ActionRecording` installs exclusive core action hooks and writes action rows. +`ScreenRecording` adds fresh UI state and original PNG bytes before +and after each action; ordinary reads generate no rows. Its async +`checkpoint()` returns a structural fingerprint when available, without writing +a row. The action-only checkpoint is a no-op. Post-action capture uses an +unrecorded host timer set by `MOBILERUN_RUN_SETTLE_SECONDS` (`0` disables it). + +Drive each device from only one task at a time while recording. Core does not +queue actions; concurrent actions can interleave. Hooks must not call device +actions, which would trigger the hooks again. Unhooked reads such as `observe()` +and `screenshot_bytes()` are fine. + +Use `rec.device` to access the same phone and `rec.run_dir` for the prospective +artifact path. The run starts on the first write or on `rec.start_run()`. +`finish(status)` finalizes the run and stops writing. Exit removes the hooks but +does not close the phone. Await actions before finishing or closing the device; +closing does not wait for in-flight actions. A cancelled action may not produce +a row. Unfinished runs that have started become `failed` on an uncaught error +or `cancelled` on cancellation or normal exit without an explicit status. + +To create a custom mode, subclass `ActionRecording` and override +`async def after_action(self, device, event)`. Call `await +super().after_action(device, event)` to keep standard rows. A post-hook error +can mean the action already happened. Do not retry it. For a custom sink +failure, catch core's `ActionHookError` and finalize with `rec.finish("failed")`. + +Operators and add-ons can use `async with rec.extension_call(name, args) as +outcome` around a validated, authorized tool invocation. Call +`outcome.set_result(value)`; only literal `False` is kept, not the response +payload. Nested actions on this recorder's phone are grouped into the tool row. +Await all spawned work before leaving the scope and do not interleave unrelated +phone actions with it. Mask declared sensitive parameters before passing args +and register newly learned values with `rec.redactor` before the scope exits. + +`recording_scope(enabled=False)` suppresses rows in the current task and its +children. A nested scope cannot lift an ancestor's veto. `recording_scope(by="agent")` +overrides attribution. `rec.collect_steps()` collects committed row indices from +the current context and children awaited within it. + +Each row has `schema_version: 2`, `i`, `action`, `args`, UTC `started_at` and +`finished_at`, `ok`, `result`, `error`, `by`, `before`, `after`, `note`, `target`, +and `screens`. `action` and argument names follow core's public signatures. +Successful element taps are recorded as coordinate taps at the native point +that was tapped, so macros replay that point. Errors are names, not exception +messages. Opaque action arguments, including `set_clipboard(value)`, are masked. +Mailbox and phone-number verification readers register their codes with each +recording active in the reader's task context. Later actions mask matching +arguments as `***`; macro building skips those rows. +Old runs must be re-recorded for macro building. Screen evidence is linked as +`screens/..{json,png}`. JSON is redacted, but **PNGs may contain +credentials or codes**. Use action-only recording when capturing pixels is not +appropriate. | File | Purpose | | --- | --- | -| `writer.py` | Append action rows, publish metadata and collect committed step IDs | -| `session.py` | Coordinate dispatch, extension observation and capture | -| `capture.py` | Observe, redact and reuse before/after screen evidence | +| `recording.py` | Action hooks and extension recording scopes | +| `outcome.py` | Capture literal tool failure without keeping the tool response | +| `screen.py` | Screen recording and checkpoints | +| `evidence.py` | Capture and write normalized, redacted native UI evidence and original PNGs | +| `writer.py` | Append JSONL rows, publish run metadata and collect committed step IDs | +| `helpers/policy.py` | Task-local recording vetoes and attribution | | `__init__.py` | Public run API | -See [run values](../../models/recording.py) and [run settings](../../config/README.md#settings-overview). +`RunWriter` also accepts caller-built rows. Those callers must redact values +themselves. Each append advances `step_index` only after the row is written; +`finish()` atomically replaces `run.json`. Runs cannot be resumed and are not +crash-durable. See [run values](../../models/recording.py). diff --git a/mobilerun/core/runs/__init__.py b/mobilerun/core/runs/__init__.py index cd3e67ec6..02f2e585c 100644 --- a/mobilerun/core/runs/__init__.py +++ b/mobilerun/core/runs/__init__.py @@ -1,5 +1,17 @@ -"""Shared disk-backed recording and task-local recording policy.""" +"""Scoped device recording, screen evidence and task-local recording policy.""" -from .writer import RunWriter, recording_policy, recording_scope +from mobilerun.utils.screen.fingerprint import observation_fingerprint -__all__ = ["RunWriter", "recording_policy", "recording_scope"] +from .helpers.policy import recording_policy, recording_scope +from .recording import ActionRecording +from .screen import ScreenRecording +from .writer import RunWriter + +__all__ = [ + "ActionRecording", + "ScreenRecording", + "RunWriter", + "observation_fingerprint", + "recording_policy", + "recording_scope", +] diff --git a/mobilerun/core/runs/capture.py b/mobilerun/core/runs/capture.py deleted file mode 100644 index d894230fe..000000000 --- a/mobilerun/core/runs/capture.py +++ /dev/null @@ -1,141 +0,0 @@ -"""Optional structural observations around a recorded device action.""" - -from __future__ import annotations - -import json -from contextlib import suppress -from datetime import UTC, datetime -from pathlib import Path -from typing import TYPE_CHECKING, Literal - -from mobilerun.core.state.screenshot import ScreenshotOnlyStateProvider -from mobilerun.core.state.snapshot import DeviceSnapshot -from mobilerun.models import Fingerprint -from mobilerun.utils.redaction import _redact_secrets - -from .writer import recording_scope - -if TYPE_CHECKING: - from mobilerun.core.devices.base import Device - from mobilerun.core.state.ui_state import UIState - - -class FingerprintCapture: - """Reuse the latest observation until an action or explicit refresh invalidates it.""" - - def __init__( - self, device: Device, inner: Device, full: bool, settle_seconds: float - ) -> None: - self._device = device - self._inner = inner - self._full = full - self._settle_seconds = settle_seconds - self._invalidated = False - self._last_current: UIState | None = None - self._snapshot: DeviceSnapshot | None = None - self._saved: ( - tuple[DeviceSnapshot, bool, dict[Literal["json", "png"], str]] | None - ) = None - - def invalidate(self) -> None: - self._invalidated = True - - async def capture(self, *, fresh: bool = False) -> Fingerprint | None: - return self.fingerprint(await self._sample(fresh=fresh)) - - async def sample(self, *, fresh: bool = False) -> DeviceSnapshot | None: - return await self._sample(fresh=fresh) if self._full else None - - async def _sample(self, *, fresh: bool) -> DeviceSnapshot | None: - with recording_scope(enabled=False): - return await self._sample_unrecorded(fresh=fresh) - - async def _sample_unrecorded(self, *, fresh: bool) -> DeviceSnapshot | None: - current = self._device.state._current or self._inner.state._current - if ( - not fresh - and not self._invalidated - and current is self._last_current - and self._snapshot is not None - ): - return self._snapshot - try: - self._snapshot = None - if fresh or self._invalidated or current is None: - provider = self._device.state._resolved_provider - if isinstance(provider, ScreenshotOnlyStateProvider) and not self._full: - return None - state = await provider.get_final_state() - else: - state = current - self._invalidated = False - self._last_current = current - self._snapshot = ( - await DeviceSnapshot._from_ui( - self._device, state, screenshot=True, redact=False - ) - if self._full - else DeviceSnapshot(datetime.now(UTC), state) - ) - return self._snapshot - except Exception: - self.invalidate() - return None - - async def after(self, *, cancelled: bool) -> DeviceSnapshot | None: - self.invalidate() - if cancelled or not self._full: - return None - if self._settle_seconds: - with suppress(Exception), recording_scope(enabled=False): - await self._inner.wait(self._settle_seconds) - return await self.sample(fresh=True) - - def fingerprint(self, snapshot: DeviceSnapshot | None) -> Fingerprint | None: - if snapshot is None or DeviceSnapshot.is_sensitive(self._device): - return None - fingerprint = snapshot.fingerprint - contains_code = self._device._extension_state.contains_sensitive_text - if any( - _redact_secrets(value) != value or contains_code(value) - for value in (fingerprint.app, fingerprint.activity, *fingerprint.elements) - if value is not None - ): - return None - return ( - fingerprint - if fingerprint.app or fingerprint.activity or fingerprint.elements - else None - ) - - def save( - self, - run_dir: Path, - index: int, - phase: Literal["before", "after"], - snapshot: DeviceSnapshot | None, - ) -> dict[Literal["json", "png"], str] | None: - """Persist redacted evidence, referring to the previous after files when safe.""" - if snapshot is None: - return None - sensitive = DeviceSnapshot.is_sensitive(self._device) - if ( - self._saved is not None - and self._saved[0] is snapshot - and self._saved[1] == sensitive - ): - return self._saved[2] - files: dict[Literal["json", "png"], str] = {} - stem = f"screens/{index}.{phase}" - with suppress(OSError, ValueError, TypeError): - (run_dir / "screens").mkdir(mode=0o700, exist_ok=True) - (run_dir / f"{stem}.json").write_text( - json.dumps(snapshot.to_json_data(device=self._device), allow_nan=False), - encoding="utf-8", - ) - files["json"] = f"{stem}.json" - if snapshot.screenshot is not None: - (run_dir / f"{stem}.png").write_bytes(snapshot.screenshot) - files["png"] = f"{stem}.png" - self._saved = (snapshot, sensitive, files) if files else None - return files or None diff --git a/mobilerun/core/runs/evidence.py b/mobilerun/core/runs/evidence.py new file mode 100644 index 000000000..5e8669bd9 --- /dev/null +++ b/mobilerun/core/runs/evidence.py @@ -0,0 +1,109 @@ +"""Capture and redact native observations without dispatching phone actions.""" + +from __future__ import annotations + +import json +from contextlib import suppress +from dataclasses import dataclass, field, replace +from datetime import UTC, datetime +from io import BytesIO +from pathlib import Path +from typing import Literal, cast +from uuid import uuid4 + +from mobilerun_core import AsyncDevice, FocusEvidence, Observation, ScreenGeometry +from PIL import Image +from pydantic import JsonValue + +from mobilerun.models import Fingerprint +from mobilerun.utils.json.redaction import safe_json +from mobilerun.utils.redaction import Redactor, mask_secure_ui +from mobilerun.utils.screen.fingerprint import observation_fingerprint +from mobilerun.utils.screen.observation import observation_ui + +Phase = Literal["before", "after"] +ScreenFiles = dict[Literal["json", "png"], str] + + +@dataclass(frozen=True) +class ScreenSample: + """Two independent reads; unsupported UI does not suppress a screenshot.""" + + observation: Observation | None = field(repr=False) + state_captured: bool + + @classmethod + async def capture(cls, device: AsyncDevice) -> ScreenSample: + at = datetime.now(UTC) + observation = None + with suppress(Exception): + if device.supports("observe_tree"): + observation = await device.observe(screenshot=False) + state_captured = observation is not None + screenshot = None + with suppress(Exception): + screenshot = await device.screenshot_bytes() + if screenshot is not None: + size = None + with suppress( + OSError, SyntaxError, ValueError, Image.DecompressionBombError + ): + with Image.open(BytesIO(screenshot)) as image: + size = image.size + if observation is None: + observation = Observation( + timestamp=at, + source_format=device.observation_format, + focused_app=None, + focused_input=None, + focus_evidence=FocusEvidence.UNKNOWN, + elements=None, + geometry=ScreenGeometry(screenshot_size=size, input_size=None), + screenshot=screenshot, + device_id=device.observation_device_id, + observation_id=uuid4().hex, + ) + else: + observation = replace( + observation, + screenshot=screenshot, + geometry=replace(observation.geometry, screenshot_size=size), + ) + return cls(observation, state_captured) + + def fingerprint(self, redactor: Redactor) -> Fingerprint | None: + if self.observation is None: + return None + return observation_fingerprint(self.observation, redactor=redactor) + + def save( + self, run_dir: Path, index: int, phase: Phase, redactor: Redactor + ) -> ScreenFiles: + """Write files before publishing their row links; keep PNG bytes unchanged.""" + files: ScreenFiles = {} + observation = self.observation + if observation is None: + return files + stem = f"screens/{index}.{phase}" + (run_dir / "screens").mkdir(mode=0o700, exist_ok=True) + if self.state_captured: + ui: JsonValue = "***" + if not redactor.sensitive_ui: + ui = safe_json( + mask_secure_ui( + observation_ui(observation), + raw_state=cast(JsonValue, observation.raw_state), + ), + redactor, + ) + files["json"] = f"{stem}.json" + (run_dir / files["json"]).write_text( + json.dumps( + {"at": observation.timestamp.isoformat(), "ui": ui}, allow_nan=False + ), + encoding="utf-8", + ) + if observation.screenshot is not None: + files["png"] = f"{stem}.png" + (run_dir / files["png"]).write_bytes(observation.screenshot) + return files diff --git a/mobilerun/core/runs/helpers/policy.py b/mobilerun/core/runs/helpers/policy.py new file mode 100644 index 000000000..365bbba22 --- /dev/null +++ b/mobilerun/core/runs/helpers/policy.py @@ -0,0 +1,29 @@ +"""Task-local recording veto and actor attribution.""" + +from collections.abc import Iterator +from contextlib import contextmanager +from contextvars import ContextVar + +from mobilerun.models import Actor + +_policy: ContextVar[tuple[bool, Actor | None]] = ContextVar( + "run_recording_policy", default=(True, None) +) + + +def recording_policy() -> tuple[bool, Actor | None]: + """Read (enabled, actor override) for the current task.""" + return _policy.get() + + +@contextmanager +def recording_scope(*, enabled: bool = True, by: Actor | None = None) -> Iterator[None]: + """Override the actor or suppress recording without lifting a parent veto.""" + parent_enabled, parent_actor = _policy.get() + token = _policy.set( + (parent_enabled and enabled, by if by is not None else parent_actor) + ) + try: + yield + finally: + _policy.reset(token) diff --git a/mobilerun/core/runs/outcome.py b/mobilerun/core/runs/outcome.py new file mode 100644 index 000000000..e515ea4e7 --- /dev/null +++ b/mobilerun/core/runs/outcome.py @@ -0,0 +1,14 @@ +"""Result capture for an extension recording scope.""" + +from dataclasses import dataclass + + +@dataclass +class ExtensionOutcome: + """Communicate a tool's outcome without retaining its response payload.""" + + returned_false: bool = False + + def set_result(self, result: object) -> None: + """Treat literal False as a failed tool call; never store other values.""" + self.returned_false = result is False diff --git a/mobilerun/core/runs/recording.py b/mobilerun/core/runs/recording.py new file mode 100644 index 000000000..71c041c40 --- /dev/null +++ b/mobilerun/core/runs/recording.py @@ -0,0 +1,339 @@ +"""Scoped recording modes built on native async action hooks.""" + +from __future__ import annotations + +import asyncio +from collections.abc import AsyncIterator, Mapping +from contextlib import ( + AbstractAsyncContextManager, + AbstractContextManager, + ExitStack, + asynccontextmanager, +) +from contextvars import ContextVar +from dataclasses import dataclass, replace +from datetime import UTC, datetime +from pathlib import Path +from types import TracebackType +from typing import Self +from uuid import uuid4 + +from mobilerun_core import Action, ActionCall, ActionEvent, AsyncDevice +from pydantic import JsonValue + +from mobilerun.config.settings import get_settings +from mobilerun.models import ( + Actor, + DeviceInfo, + Fingerprint, + RunKind, + RunRecord, + RunStatus, + RunStep, +) +from mobilerun.utils.json.redaction import safe_json +from mobilerun.utils.redaction import Redactor, redact, secret_scope + +from .evidence import Phase, ScreenFiles, ScreenSample +from .helpers.policy import recording_policy +from .outcome import ExtensionOutcome +from .writer import RunWriter + +_OPAQUE_ARGS: Mapping[str, frozenset[str]] = { + "type_secret": frozenset({"secret"}), + "set_clipboard": frozenset({"value"}), + "set_proxy": frozenset({"proxy"}), + "install_app": frozenset({"source"}), + "push_file": frozenset({"source", "device_path"}), + "delete_file": frozenset({"device_path"}), + "tap_element": frozenset({"element"}), + "open_deep_link": frozenset({"deep_link"}), +} + + +@dataclass +class _ExtensionScope: + active: bool = True + + +class ActionRecording: + """Record action timings and outcomes on an existing, caller-owned device.""" + + def __init__( + self, + device: AsyncDevice, + *, + runs_dir: Path | None = None, + kind: RunKind = "recording", + source_macro: str | None = None, + by: Actor = "script", + redactor: Redactor | None = None, + ) -> None: + self.device = device + self.redactor = redactor if redactor is not None else Redactor() + self._by = by + self._start: datetime | None = None + self._run_id = uuid4().hex + self._runs_dir = runs_dir if runs_dir is not None else get_settings().runs_dir + self._hooks: AbstractAsyncContextManager[None] | None = None + self._secrets = ExitStack() + self._finished = False + self._faulted = False + self._extension: ContextVar[_ExtensionScope | None] = ContextVar( + "recording_extension_call", default=None + ) + + def record() -> RunRecord: + info = device.info() + return RunRecord( + schema_version=2, + run_id=self._run_id, + kind=kind, + source_macro=( + self._safe_text(source_macro) if source_macro is not None else None + ), + device=DeviceInfo( + platform=self._safe_text(info.platform), + identifier=self._safe_text(info.device_id), + ), + started_at=self._start or datetime.now(UTC), + ) + + self._writer = RunWriter(record, self._runs_dir) + + def _safe_text(self, value: object) -> str: + return ( + redact(self.redactor.redact(value)) if isinstance(value, str) else "unknown" + ) + + async def __aenter__(self) -> Self: + if self._finished: + raise RuntimeError("A finished recording cannot be reopened") + hooks = self.device.use_action_hooks( + before=self.before_action, after=self.after_action + ) + with ExitStack() as secrets: + secrets.enter_context(secret_scope(redactor=self.redactor, recording=True)) + await hooks.__aenter__() + self._secrets = secrets.pop_all() + self._hooks = hooks + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + with self._secrets: + try: + if self._hooks is not None: + try: + await self._hooks.__aexit__(exc_type, exc, tb) + finally: + self._hooks = None + finally: + status: RunStatus = "cancelled" + if exc is not None and not isinstance(exc, asyncio.CancelledError): + status = "failed" + try: + self.finish(status) + except Exception: + if exc is None: + raise + exc.add_note("Recording cleanup also failed.") + + @property + def run_dir(self) -> Path: + """The artifact path, even before the first recorded action.""" + return self._runs_dir / self._run_id + + @property + def step_index(self) -> int: + """Index of the last committed row, or zero.""" + return self._writer.step_index + + def collect_steps(self) -> AbstractContextManager[list[int]]: + """Collect rows committed within this scope and its child tasks.""" + return self._writer.collect_steps() + + def start_run(self) -> Path | None: + """Publish an empty run for another sink; a recording veto still applies.""" + if self._allowed(): + return self._writer.start() + return None + + def finish(self, status: RunStatus, failed_step: int | None = None) -> None: + """Finalize the run; the context exit detaches the hooks.""" + if status == "running": + raise ValueError("A finished run requires a terminal status") + if not self._finished: + if status == "failed" and not self._faulted and self._allowed(): + self._writer.start() + self._writer.finish( + "failed" if self._faulted else status, failed_step=failed_step + ) + self._finished = True + + async def checkpoint(self) -> Fingerprint | None: + """No-op in action mode; screen mode returns a fresh structural guard.""" + return None + + def _allowed(self) -> bool: + return self._hooks is not None and not self._finished and recording_policy()[0] + + def _in_extension(self) -> bool: + scope = self._extension.get() + return scope is not None and scope.active + + async def before_action(self, device: AsyncDevice, call: ActionCall) -> None: + """Reject new actions on a faulted writer before they dispatch.""" + if self._allowed() and self._faulted: + raise RuntimeError("Recording sink failed; finish the run") + + async def after_action(self, device: AsyncDevice, event: ActionEvent) -> None: + """Persist one native outcome. Override and call super to add a custom mode.""" + if self._hooks is None or self._finished: + return + action = event.action + opaque = _OPAQUE_ARGS.get(action.name, frozenset()) + args = { + name: "***" if name in opaque else safe_json(value, self.redactor) + for name, value in action.arguments.items() + } + if action.name == "type_secret" or any( + args.get(key) == "***" for key in ("text", "value") + ): + self.redactor.mark_sensitive() + if not self._allowed() or self._in_extension(): + return + await self._write( + replace(event, action=Action(action.name, args, action.scope)), + self._before_sample(), + ) + + def _before_sample(self) -> ScreenSample | None: + return None + + async def _sample(self, *, after: bool = False) -> ScreenSample | None: + return None + + async def _write( + self, + event: ActionEvent, + before: ScreenSample | None, + ) -> None: + try: + after = ( + None + if isinstance(event.exception, asyncio.CancelledError) + else await self._sample(after=True) + ) + if not self._allowed(): + return + error = ( + type(event.exception).__name__ if event.exception is not None else None + ) + if event.result is False and error is None: + error = "returned_false" + action = event.action + if action.name == "tap_element" and error is None: + match event.result: + case (x, y) if type(x) is int and type(y) is int: + action = Action("tap", {"x": x, "y": y}, "device") + result: JsonValue = None + if type(event.result) is bool or ( + action.name == "start_app" and type(event.result) is str + ): + result = safe_json(event.result, self.redactor) + self._start = self._start or event.started_at + run_dir = self._writer.start() + index = self.step_index + 1 + screens: dict[Phase, ScreenFiles] = {} + if before is not None and ( + files := before.save(run_dir, index, "before", self.redactor) + ): + screens["before"] = files + if after is not None and ( + files := after.save(run_dir, index, "after", self.redactor) + ): + screens["after"] = files + self._writer.append( + RunStep( + schema_version=2, + i=index, + started_at=event.started_at, + finished_at=event.finished_at, + action=action, + ok=error is None, + error=self._safe_text(error) if error is not None else None, + result=result, + before=( + before.fingerprint(self.redactor) + if before is not None + else None + ), + after=( + after.fingerprint(self.redactor) if after is not None else None + ), + by=recording_policy()[1] or self._by, + screens=screens or None, + ) + ) + except Exception: + self._faulted = True + else: + return + # Core chains ordinary hook exceptions. Do not expose the original I/O error, + # filesystem paths, inputs, or sink exception messages to that chain. + raise RuntimeError("Recording sink failed") + + @asynccontextmanager + async def extension_call( + self, name: str, arguments: Mapping[str, JsonValue] + ) -> AsyncIterator[ExtensionOutcome]: + """Group one authorized, validated tool call; await all its child work inside. + + Pass only replayable arguments with declared sensitive fields already masked. + Register newly learned values on ``redactor`` before leaving the scope. + """ + outcome = ExtensionOutcome() + if not self._allowed() or self._in_extension(): + yield outcome + return + if self._faulted: + raise RuntimeError("Recording sink failed; finish the run") + projected = safe_json(dict(arguments), self.redactor) + before = await self._sample() + started = datetime.now(UTC) + scope = _ExtensionScope() + token = self._extension.set(scope) + failure: BaseException | None = None + try: + yield outcome + except BaseException as error: + failure = error + raise + finally: + finished = datetime.now(UTC) + scope.active = False + self._extension.reset(token) + if self._allowed(): + result = False if outcome.returned_false and failure is None else None + try: + action = Action( + "extension_call", + { + "name": self._safe_text(name), + "arguments": safe_json(projected, self.redactor), + }, + "extension", + ) + await self._write( + ActionEvent(action, started, finished, result, failure), + before, + ) + except BaseException: + if failure is None: + raise + failure.add_note("Writing the recorded tool outcome also failed.") diff --git a/mobilerun/core/runs/screen.py b/mobilerun/core/runs/screen.py new file mode 100644 index 000000000..93732b0dd --- /dev/null +++ b/mobilerun/core/runs/screen.py @@ -0,0 +1,45 @@ +"""Record screen evidence alongside native actions.""" + +import asyncio + +from mobilerun_core import ActionCall, ActionEvent, AsyncDevice + +from mobilerun.config.settings import get_settings +from mobilerun.models import Fingerprint + +from .evidence import ScreenSample +from .recording import ActionRecording + + +class ScreenRecording(ActionRecording): + """Add fresh UI and original PNG evidence before and after each action.""" + + _before: ScreenSample | None = None + + async def checkpoint(self) -> Fingerprint | None: + """Read a structural guard without creating a row or writing files.""" + sample = await self._sample() if self._allowed() else None + return sample.fingerprint(self.redactor) if sample is not None else None + + async def before_action(self, device: AsyncDevice, call: ActionCall) -> None: + """Read pre-action evidence from the same device outside its transport lock.""" + await super().before_action(device, call) + self._before = None + if self._allowed() and not self._in_extension(): + self._before = await self._sample() + + async def after_action(self, device: AsyncDevice, event: ActionEvent) -> None: + """Read and save post-action evidence unless dispatch was cancelled.""" + try: + await super().after_action(device, event) + finally: + self._before = None + + def _before_sample(self) -> ScreenSample | None: + return self._before + + async def _sample(self, *, after: bool = False) -> ScreenSample: + # Settling is recorder-only: a host timer avoids recording another action. + if after and (settle := get_settings().MOBILERUN_RUN_SETTLE_SECONDS): + await asyncio.sleep(settle) + return await ScreenSample.capture(self.device) diff --git a/mobilerun/core/runs/session.py b/mobilerun/core/runs/session.py deleted file mode 100644 index 6e0f35699..000000000 --- a/mobilerun/core/runs/session.py +++ /dev/null @@ -1,181 +0,0 @@ -"""Coordinate action observation, screen evidence, and a run's row writer.""" - -from __future__ import annotations - -from collections.abc import AsyncIterator, Awaitable, Callable -from contextlib import AbstractAsyncContextManager, asynccontextmanager -from datetime import UTC, datetime -from pathlib import Path -from typing import TYPE_CHECKING, Literal, TypeVar -from uuid import uuid4 - -from pydantic import JsonValue - -from mobilerun.core.extensions.registry import ActionOutcome -from mobilerun.models import Actor, DeviceInfo, RunKind, RunRecord, RunStatus, RunStep -from mobilerun.utils.redaction import _redact_secrets, mask_step_args - -from .writer import RunWriter, recording_policy - -if TYPE_CHECKING: - from mobilerun.core.devices.base import Device - from mobilerun.core.runs.capture import FingerprintCapture - -R = TypeVar("R") - - -class RecordingSession: - def __init__( - self, - device: Device, - capture: FingerprintCapture, - runs_dir: Path, - *, - kind: RunKind, - source_macro: str | None, - by: Actor, - observe_extensions: bool, - ) -> None: - self._device = device - self.capture = capture - self._by = by - self._accepting = True - self._observing = observe_extensions - - def record() -> RunRecord: - redact = device.known_codes_redactor() - return RunRecord( - run_id=uuid4().hex, - kind=kind, - source_macro=( - redact(_redact_secrets(source_macro)) - if source_macro is not None - else None - ), - device=DeviceInfo( - platform=device.platform, - identifier=redact(_redact_secrets(device.identifier or "unknown")), - ), - started_at=datetime.now(UTC), - ) - - self.writer = RunWriter(record, runs_dir) - if self._observing: - device._extension_state.observers[device] = self._observe_extension - - def start(self) -> Path | None: - if ( - self._accepting - and self._device.recording_allowed() - and recording_policy()[0] - ): - return self.writer.start() - return None - - def finish(self, status: RunStatus, failed_step: int | None = None) -> None: - if status == "running": - raise ValueError("A finished run requires a terminal status") - if not self._accepting: - return - self._accepting = False - try: - self.writer.finish(status, failed_step=failed_step) - finally: - if self._observing: - self._device._extension_state.observers.pop(self._device, None) - - def _observe_extension( - self, - facade: Device, - name: str, - args: dict[str, JsonValue], - outcome: ActionOutcome, - ) -> AbstractAsyncContextManager[None]: - return self._observe( - "extension_call", - {"name": name, "arguments": args}, - outcome, - allowed=facade.recording_allowed(), - ) - - @asynccontextmanager - async def _observe( - self, - action: str, - args: dict[str, JsonValue], - outcome: ActionOutcome, - *, - allowed: bool = True, - ) -> AsyncIterator[None]: - enabled, actor = recording_policy() - if not allowed or not enabled or not self._device.recording_allowed(): - self.capture.invalidate() - run_dir = self.start() if allowed else None - if run_dir is None: - yield - return - before = await self.capture.sample() - started_at = datetime.now(UTC) - try: - yield - finally: - finished_at = datetime.now(UTC) - if self._accepting: - after = await self.capture.after( - cancelled=outcome.error == "CancelledError" - ) - if self._accepting: - try: - i = self.writer.step_index + 1 - screens: dict[ - Literal["before", "after"], - dict[Literal["json", "png"], str], - ] = {} - if before_files := self.capture.save( - run_dir, i, "before", before - ): - screens["before"] = before_files - if after_files := self.capture.save(run_dir, i, "after", after): - screens["after"] = after_files - self.writer.append( - RunStep( - i=i, - started_at=started_at, - finished_at=finished_at, - action=action, - args=mask_step_args( - args, - contains_code=self._device._extension_state.matches_sensitive_argument, - ), - ok=outcome.error is None, - error=( - _redact_secrets(outcome.error) - if outcome.error is not None - else None - ), - before=self.capture.fingerprint(before), - after=self.capture.fingerprint(after), - by=actor or self._by, - screens=screens or None, - ) - ) - except Exception: - if outcome.error is None: - raise # Preserve a prior device exception. - - async def dispatch( - self, - operation: Callable[[], Awaitable[R]], - action: str, - args: dict[str, JsonValue], - ) -> R: - outcome = ActionOutcome() - async with self._observe(action, args, outcome): - try: - result = await operation() - except BaseException as error: - outcome.error = type(error).__name__ - raise - if result is False: - outcome.error = "returned_false" - return result diff --git a/mobilerun/core/runs/writer.py b/mobilerun/core/runs/writer.py index e7599d83f..a39a0037f 100644 --- a/mobilerun/core/runs/writer.py +++ b/mobilerun/core/runs/writer.py @@ -12,29 +12,7 @@ from pathlib import Path from tempfile import NamedTemporaryFile -from mobilerun.models import Actor, RunRecord, RunStatus, RunStep - -_policy: ContextVar[tuple[bool, Actor | None]] = ContextVar( - "run_recording_policy", default=(True, None) -) - - -def recording_policy() -> tuple[bool, Actor | None]: - """Read (enabled, actor override) for the current task.""" - return _policy.get() - - -@contextmanager -def recording_scope(*, enabled: bool = True, by: Actor | None = None) -> Iterator[None]: - """Override the actor or suppress recording without lifting a parent veto.""" - parent_enabled, parent_actor = recording_policy() - token = _policy.set( - (parent_enabled and enabled, by if by is not None else parent_actor) - ) - try: - yield - finally: - _policy.reset(token) +from mobilerun.models import RunRecord, RunStatus, RunStep @dataclass @@ -127,12 +105,22 @@ def append(self, step: RunStep) -> None: step = RunStep.model_validate(step) if step.i != self.step_index + 1: raise ValueError("Run steps must be appended in consecutive 1-based order") - row = json.dumps(step.model_dump(mode="json"), allow_nan=False) + "\n" + row = (json.dumps(step.model_dump(mode="json"), allow_nan=False) + "\n").encode( + "utf-8" + ) path = self.start() / "steps.jsonl" try: - with os.fdopen(os.open(path, os.O_APPEND | os.O_WRONLY), "ab") as file: - file.write(row.encode("utf-8")) - file.flush() + fd = os.open(path, os.O_APPEND | os.O_WRONLY) + try: + checkpoint = os.fstat(fd).st_size + try: + if os.write(fd, row) != len(row): + raise OSError("Incomplete recording row") + except OSError: + os.ftruncate(fd, checkpoint) + raise + finally: + os.close(fd) except OSError: self._write_failed = True raise diff --git a/mobilerun/core/screen/README.md b/mobilerun/core/screen/README.md new file mode 100644 index 000000000..6ed6e18a1 --- /dev/null +++ b/mobilerun/core/screen/README.md @@ -0,0 +1,42 @@ +# Screen + +`ScreenProvider` turns a core phone's native observation into a model prompt, +optional resized screenshot, and observation-relative action targets. Keep one +view per run. It leaves `device.state_provider` installed as-is; core still +selects the provider, validates targets, and asks for approval. Reads never +perform Portal recovery. + +```python +from mobilerun.core.screen import ScreenOptions, ScreenProvider + +async def step(phone, choose, redactor): + screen = ScreenProvider(phone, options=ScreenOptions(normalized=True), redactor=redactor) + state = await screen.observe(screenshot=True) + choice = await choose(state.ui.formatted_text, state.screenshot) + if isinstance(choice, int): + await phone.tap_element(state.element(choice)) + else: + await phone.tap(*state.ui.geometry.to_device(*choice)) +``` + +Pass the snapshot the model actually saw, not `screen.current` after another +read. Indices start at 1 for Portal-style trees and 0 for legacy XCTest, as +before. `state.element(index)` returns a native target for core; +`state.ui.element(index)` returns only a [prompt row](../../models/screen/README.md). +The screenshot is resized, not privacy-redacted. A tree and screenshot are +successive reads, not one atomic frame. Reuse the run's `Redactor` for known +codes and persistence taint. CLI code can use `ScreenOptions(detail="concise")` +and `observe(screenshot=False)`; recording should use native observations and +unmodified screenshot bytes, not this view. + +The projected iOS phone state displays `Home Screen` instead of a clock label +when the observation identifies SpringBoard. This does not change the native +observation. + +| File | Role | +| --- | --- | +| `provider.py` | Read, project, and cache the latest successful view | +| `options.py` | Prompt, coordinate and model resize options | +| `filters.py` | Concise/detailed Portal pruning and legacy XCTest prioritization | +| `formatter.py` | Indexed and screenshot-only prompts | +| `snapshot.py` | Live targets, safe JSON, and native structural fingerprint | diff --git a/mobilerun/core/screen/__init__.py b/mobilerun/core/screen/__init__.py new file mode 100644 index 000000000..5dd1660cb --- /dev/null +++ b/mobilerun/core/screen/__init__.py @@ -0,0 +1,7 @@ +"""Model-facing screen views over the core async device.""" + +from .options import ScreenOptions, VisionResizePolicy +from .provider import ScreenProvider +from .snapshot import ScreenSnapshot + +__all__ = ["ScreenOptions", "ScreenProvider", "ScreenSnapshot", "VisionResizePolicy"] diff --git a/mobilerun/core/screen/filters.py b/mobilerun/core/screen/filters.py new file mode 100644 index 000000000..733275be5 --- /dev/null +++ b/mobilerun/core/screen/filters.py @@ -0,0 +1,123 @@ +"""Concise and detailed presentation pruning, independent of tap safety.""" + +from collections.abc import Sequence + +from mobilerun_core import Element + +from mobilerun.config.settings import get_settings +from mobilerun.utils.screen.labels import element_label + +_IOS_LAYOUT = { + "Window", + "Window (Main)", + "ScrollView", + "CollectionView", + "Table", + "Toolbar", + "TabBar", + "StatusBar", + "PageIndicator", +} +_IOS_ACTIONABLE = { + "Icon", + "Button", + "SearchField", + "TextField", + "SecureTextField", + "TextView", + "Cell", + "StaticText", + "Image", + "Switch", +} + + +def legacy_elements(elements: Sequence[Element]) -> list[Element]: + """Skip layout noise and duplicates, then prioritize labeled controls.""" + seen: set[tuple[str | None, str, tuple[int, ...]]] = set() + kept: list[Element] = [] + for node in elements: + if node.bounds is None or node.class_name in _IOS_LAYOUT: + continue + left, top, right, bottom = node.bounds + if right <= left or bottom <= top: + continue + label = element_label(node, legacy_ios=True) + if node.class_name == "Other" and not (label or node.value): + continue + signature = (node.class_name, label, tuple(map(int, node.bounds))) + if signature not in seen: + seen.add(signature) + kept.append(node) + return sorted( + kept, + key=lambda node: not ( + node.class_name in _IOS_ACTIONABLE and element_label(node, legacy_ios=True) + ), + ) + + +def filter_elements( + elements: Sequence[Element], + input_size: tuple[int, int] | None, + *, + concise: bool, +) -> list[Element]: + """Retain the original preorder and native identity after prompt pruning.""" + kept: set[tuple[int, ...]] = set() + if concise: + minimum = get_settings().MOBILERUN_SCREEN_CONCISE_MIN_ELEMENT_SIZE + # ConciseFilter pruned an entire branch when its parent failed. + for element in elements: + if element.parent_id is not None and element.parent_id not in kept: + continue + if element.bounds is not None: + left, top, right, bottom = element.bounds + intersects = ( + right > 0 + and bottom > 0 + and ( + input_size is None + or (left < input_size[0] and top < input_size[1]) + ) + ) + if intersects and right - left > minimum and bottom - top > minimum: + kept.add(element.node_id) + else: + minimum_visibility = get_settings().MOBILERUN_SCREEN_DETAILED_MIN_VISIBILITY + # DetailedFilter kept parents of retained children, except Gboard branches. + keyboard: set[tuple[int, ...]] = set() + for element in elements: + if element.parent_id in keyboard or (element.resource_id or "").startswith( + "com.google.android.inputmethod.latin:id/" + ): + keyboard.add(element.node_id) + for element in reversed(elements): + if element.node_id in keyboard: + continue + if any(child in kept for child in element.child_ids) or _visible( + element, input_size, minimum_visibility + ): + kept.add(element.node_id) + return [element for element in elements if element.node_id in kept] + + +def _visible( + element: Element, input_size: tuple[int, int] | None, minimum_visibility: float +) -> bool: + """Port DetailedFilter's 10% visibility rule without guessing a viewport.""" + if element.bounds is None: + return False + left, top, right, bottom = element.bounds + if right <= left or bottom <= top: + return False + if input_size is None: + return True + width, height = input_size + if left <= 0 and top <= 0 and right >= width and bottom >= height: + return True + area = (right - left) * (bottom - top) + visible = max(0, min(right, width) - max(left, 0)) * max( + 0, min(bottom, height) - max(top, 0) + ) + return visible / area >= minimum_visibility diff --git a/mobilerun/core/screen/formatter.py b/mobilerun/core/screen/formatter.py new file mode 100644 index 000000000..d993fe92b --- /dev/null +++ b/mobilerun/core/screen/formatter.py @@ -0,0 +1,86 @@ +"""Render model-facing screen elements in the established indexed syntax.""" + +from pydantic import JsonValue + +from mobilerun.models.screen import ScreenView +from mobilerun.utils.prompts import load_prompt_text + +_SCREENSHOT_GUIDANCE = load_prompt_text("state/screenshot_only_guidance.md") + + +def format_screen(view: ScreenView, *, legacy_ios: bool) -> str: + """Render typed bounds as text only at the prompt boundary.""" + geometry = view.geometry + note = " (normalized [0-1000])" if geometry.normalized else "" + if legacy_ios: + lines = [ + f"Current UI elements{note}:", + "'index. className: text - bounds(x1,y1,x2,y2)':", + ] + else: + lines = ["**Current Phone State:**"] + app = view.phone_state.get("currentApp") + package = view.phone_state.get("packageName") + if app and package: + lines.append(f"• **App:** {app} ({package})") + elif app or package: + lines.append(f"• **App:** {app or package}") + keyboard: JsonValue = view.phone_state.get( + "keyboardVisible", view.phone_state.get("isEditable") + ) + lines.extend( + [ + f"• **Keyboard:** {'Visible' if keyboard is True else 'Hidden'}", + f"• **Focused Element:** '{view.focused_text}'", + "", + f"Current Clickable UI elements{note}:", + "'index. className: resourceId; checkedState, text - bounds(x1,y1,x2,y2)':", + ] + ) + + for row in view.elements: + parts = [f"{row.index}."] + short_class = row.class_name.rsplit(".", 1)[-1] + if view.opaque: + parts.append("***") + elif legacy_ios: + parts.append(f"{short_class or 'Unknown'}:") + if row.label: + parts.append(row.label) + else: + if short_class: + parts.append(f"{short_class}:") + if details := [ + f'"{value}"' for value in (row.resource_id, row.label) if value + ]: + parts.append(", ".join(details)) + if row.checked is not None: + parts.append(f"; isChecked={row.checked}") + if (bounds := geometry.project_bounds(row.bounds)) is not None: + parts.append(f"- ({','.join(map(str, bounds))})") + lines.append(" ".join(parts)) + if not view.elements: + lines.append("No UI elements found") + return "\n".join(lines) + + +def format_screenshot_only(size: tuple[int, int] | None, normalized: bool) -> str: + """Explain how to target a screen without indexed elements.""" + title = "Screenshot-only mode is active. There is no accessibility tree or element index list." + if size is None: + return title + " No screenshot was requested." + if normalized: + return ( + f"{title} Inspect the screenshot and use coordinate actions in normalized coordinates: " + "both axes run from 0 to 1000 across the screenshot, whatever the image size, so " + "(0,0) is top-left, (500,500) is the center and (1000,1000) is bottom-right. " + f"{_SCREENSHOT_GUIDANCE}" + ) + width, height = size + return ( + f"{title} Inspect the screenshot and use coordinate actions in the screenshot pixel " + "coordinates shown to the model. The screenshot includes a coordinate grid for visual " + "reference; use the underlying screenshot pixel coordinates, not grid-cell numbers. " + f"The screenshot shown to the model is {width}x{height}; (0,0) is top-left and " + f"({width - 1},{height - 1}) is bottom-right. {_SCREENSHOT_GUIDANCE}" + ) diff --git a/mobilerun/core/screen/options.py b/mobilerun/core/screen/options.py new file mode 100644 index 000000000..ff1c5c15c --- /dev/null +++ b/mobilerun/core/screen/options.py @@ -0,0 +1,19 @@ +"""Presentation options; native provider selection stays with the device.""" + +from dataclasses import dataclass +from typing import Literal, Protocol + + +class VisionResizePolicy(Protocol): + """The active vision model's effective input dimensions.""" + + def effective_dims(self, width: int, height: int) -> tuple[int, int]: ... + + +@dataclass(frozen=True) +class ScreenOptions: + """Prompt detail, coordinate protocol, and optional model resize policy.""" + + detail: Literal["concise", "detailed"] = "detailed" + normalized: bool = False + vision_resize_policy: VisionResizePolicy | None = None diff --git a/mobilerun/core/screen/provider.py b/mobilerun/core/screen/provider.py new file mode 100644 index 000000000..38298617a --- /dev/null +++ b/mobilerun/core/screen/provider.py @@ -0,0 +1,302 @@ +"""A run-local view over the core provider selected by an async device.""" + +from __future__ import annotations + +import asyncio +import re +from typing import cast + +from mobilerun_core import AsyncDevice, Observation +from pydantic import JsonValue + +from mobilerun.config.settings import get_settings +from mobilerun.models.screen import ModelGeometry, ProjectedElement, ScreenView +from mobilerun.utils.images import fit_dimensions_to_max_side +from mobilerun.utils.prompts import load_prompt_text +from mobilerun.utils.redaction import Redactor, mask_secure_ui +from mobilerun.utils.screen.fingerprint import observation_fingerprint +from mobilerun.utils.screen.labels import element_label + +from .filters import filter_elements, legacy_elements +from .formatter import format_screen, format_screenshot_only +from .options import ScreenOptions +from .snapshot import ScreenSnapshot + +_NORMALIZED_NOTE = load_prompt_text("state/normalized_state_note.md") +_IOS_SPRINGBOARD = "com.apple.springboard" +_IOS_CLOCK = re.compile(r"\d{1,2}:\d{2}") + + +class ScreenProvider: + """Project observations without replacing the device's read-only provider.""" + + def __init__( + self, + device: AsyncDevice, + *, + options: ScreenOptions | None = None, + redactor: Redactor | None = None, + ) -> None: + self._device = device + self._options = options if options is not None else ScreenOptions() + self._redactor = redactor if redactor is not None else Redactor() + self._current: ScreenSnapshot | None = None + + @property + def current(self) -> ScreenSnapshot | None: + """Last successfully projected observation, or None before the first read.""" + return self._current + + async def observe(self, *, screenshot: bool | None = None) -> ScreenSnapshot: + """Read once; default to an image only for a screenshot-only provider.""" + if screenshot is None: + screenshot = not self._device.state_provider.tree_supported + observation = await self._device.observe(screenshot=screenshot) + state = await asyncio.to_thread(self._project, observation) + self._current = state + return state + + def _project(self, observation: Observation) -> ScreenSnapshot: + input_size = observation.geometry.input_size + if input_size is not None and min(input_size) <= 0: + input_size = None + normalized = self._options.normalized and input_size is not None + image = observation.screenshot + model_size = None + if image is not None: + pixel_size = observation.geometry.screenshot_size + if pixel_size is None or min(pixel_size) <= 0: + raise ValueError( + "Observation has a screenshot without pixel dimensions" + ) + policy = self._options.vision_resize_policy + model_size = ( + policy.effective_dims(*pixel_size) + if policy is not None + else fit_dimensions_to_max_side( + pixel_size[0], + pixel_size[1], + get_settings().MOBILERUN_MODEL_SCREENSHOT_MAX_SIDE, + ) + ) + if min(model_size) <= 0: + raise ValueError("Vision policy returned invalid screenshot dimensions") + + native_elements = observation.elements or () + legacy_ios = observation.source_format == "ios-legacy" + targets = ( + legacy_elements(native_elements) + if legacy_ios + else filter_elements( + native_elements, input_size, concise=self._options.detail == "concise" + ) + ) + first_index = 0 if legacy_ios else 1 + indices = { + node.node_id: index for index, node in enumerate(targets, first_index) + } + focus = observation.focused_input + focused_index = indices.get(focus.node_id) if focus is not None else None + geometry = ModelGeometry( + input_size=input_size, model_size=model_size, normalized=normalized + ) + rows = tuple( + ProjectedElement.from_element( + node, + index=index, + parent_index=( + indices.get(node.parent_id) if node.parent_id is not None else None + ), + legacy_ios=legacy_ios, + label=element_label(node, legacy_ios=legacy_ios), + ) + for index, node in enumerate(targets, first_index) + ) + phone = observation.phone_state + phone_state: dict[str, JsonValue] = {} + if phone is not None: + current_app, package_name = phone.current_app, phone.package_name + if self._device.info().platform == "ios": + raw_tree = (observation.raw_state or {}).get("raw_a11y_tree") + if package_name == _IOS_SPRINGBOARD or ( + isinstance(raw_tree, str) and "Home screen icons" in raw_tree + ): + package_name = _IOS_SPRINGBOARD + if not current_app or _IOS_CLOCK.fullmatch(current_app): + current_app = "Home Screen" + phone_state = { + key: value + for key, value in ( + ("currentApp", current_app), + ("packageName", package_name), + ("activityName", phone.activity_name), + ("keyboardVisible", phone.keyboard_visible), + ("isEditable", phone.editable), + ) + if value is not None + } + focused = observation.focused_text or "" + + # The raw scan covers secure nodes filtered out of the prompt and native + # flags (e.g. Android inputType) not yet present on core's Element. + # Raw data is never copied into the snapshot. + unmasked: dict[str, JsonValue] = { + "elements": [row.model_dump(mode="json") for row in rows] + } + masked = mask_secure_ui( + unmasked, + retain_targeting=True, + raw_state=cast(JsonValue, observation.raw_state), + ) + secure = masked is not unmasked or any( + node.password is True for node in native_elements + ) + if secure or self._redactor.sensitive_ui: + image = None + model_size = None + geometry = geometry.model_copy(update={"model_size": None}) + if secure: + phone_state = {} + focused = "***" + if self._redactor.sensitive_ui: + # Opaque values cannot be checked against candidate text. Keep only + # targeting geometry in memory; ScreenView serialization hides it all. + rows = tuple( + ProjectedElement( + index=row.index, + bounds=row.bounds, + clickable=row.clickable, + enabled=row.enabled, + visible=row.visible, + long_clickable=row.long_clickable, + parent_index=row.parent_index, + ) + for row in rows + ) + phone_state = {} + focused = "***" + focused_index = None + else: + # Masking a secure row removes its metadata. A missing flag must not + # turn a known non-target into a target of unknown reachability. + denied = ( + { + row.index: { + key: False + for key in ("clickable", "enabled", "visible") + if getattr(row, key) is False + } + for row in rows + } + if secure + else {} + ) + clean_rows = cast( + list[dict[str, JsonValue]], + self._redactor.redact_json(masked["elements"]), + ) + rows = tuple( + ProjectedElement.model_validate( + { + key: value + for key, value in row.items() + if ( + key != "bounds" + or value is None + or ( + isinstance(value, list) + and all(type(part) is int for part in value) + ) + ) + and (key not in _TYPED_SCALARS or value != "***") + } + | ( + {"label": "***", "password": True} + if row.get("isPassword") is True + else {} + ) + | denied.get(cast(int, row["index"]), {}) + ) + for row in clean_rows + if type(row.get("index")) is int + ) + clean_geometry = cast( + dict[str, JsonValue], + self._redactor.redact_json(geometry.model_dump(mode="json")), + ) + geometry = ModelGeometry( + input_size=( + input_size + if clean_geometry["input_size"] + == (list(input_size) if input_size else None) + else None + ), + model_size=( + model_size + if clean_geometry["model_size"] + == (list(model_size) if model_size else None) + else None + ), + normalized=clean_geometry["normalized"] is True, + ) + if not any(row.index == focused_index for row in rows): + focused_index = None + phone_state = cast( + dict[str, JsonValue], self._redactor.redact_json(phone_state) + ) + ui = ScreenView( + elements=rows, + phone_state=phone_state, + focused_text=self._redactor.redact(focused), + focused_index=focused_index, + geometry=geometry, + ) + redactor = self._redactor + ui._mask_projection = lambda data: redactor.sensitive_ui or ( + data is not None and redactor.redact_json(data) != data + ) + + if not observation.tree_present: + formatted = format_screenshot_only(model_size, normalized) + else: + formatted = format_screen(ui, legacy_ios=legacy_ios) + if normalized and image is not None: + formatted += f"\n\n{_NORMALIZED_NOTE}" + elif model_size is not None and input_size is not None: + width, height = model_size + formatted += ( + f"\n\nAll coordinates in this device state are in the {width}x{height} " + "screenshot shown to you, which carries a labeled coordinate grid." + ) + return ScreenSnapshot( + at=observation.timestamp, + ui=ui.model_copy( + update={"formatted_text": self._redactor.redact(formatted)} + ), + _pixels=image, + _targets=tuple(targets), + _first_index=first_index, + _redactor=self._redactor, + _fingerprint=( + None + if secure or ui.opaque + else observation_fingerprint( + observation, redactor=self._redactor, include_scope=False + ) + ), + ) + + +_TYPED_SCALARS = frozenset( + { + "clickable", + "enabled", + "visible", + "long_clickable", + "editable", + "password", + "checked", + "parent_index", + "legacy_ios", + } +) diff --git a/mobilerun/core/screen/snapshot.py b/mobilerun/core/screen/snapshot.py new file mode 100644 index 000000000..e9107a734 --- /dev/null +++ b/mobilerun/core/screen/snapshot.py @@ -0,0 +1,69 @@ +"""Live screen evidence pinned to one native observation.""" + +from dataclasses import dataclass, field +from datetime import UTC, datetime +from typing import cast + +from mobilerun_core import Element +from pydantic import JsonValue + +from mobilerun.models.recording import Fingerprint +from mobilerun.models.screen import ScreenView +from mobilerun.utils.images import resize_image_to_dimensions_with_grid +from mobilerun.utils.redaction import Redactor +from mobilerun.utils.screen.fingerprint import unmasked_fingerprint + + +@dataclass(frozen=True, repr=False) +class ScreenSnapshot: + """A model projection, with live-only pixels and pinned native targets.""" + + at: datetime + ui: ScreenView + _pixels: bytes | None = field(repr=False) + _targets: tuple[Element, ...] = field(repr=False) + _first_index: int = field(repr=False) + _fingerprint: Fingerprint | None = field(repr=False) + _redactor: Redactor = field(repr=False) + + @property + def screenshot(self) -> bytes | None: + """Return the default model image, never unredacted evidence.""" + return self.render_screenshot() + + def render_screenshot( + self, *, size: tuple[int, int] | None = None, normalized: bool | None = None + ) -> bytes | None: + """Resize original pixels and draw the grid only in the final coordinate space.""" + size = size or self.ui.geometry.model_size + if self._pixels is None or size is None or self.ui.opaque: + return None + if normalized is None: + normalized = self.ui.geometry.normalized + return resize_image_to_dimensions_with_grid( + self._pixels, + *size, + divisions=0 if normalized or self.ui.geometry.input_size is None else 10, + ) + + def element(self, index: int) -> Element: + """Return the exact core target behind a prompt index; never log its values.""" + offset = index - self._first_index + if not 0 <= offset < len(self._targets): + raise ValueError(f"No element at screen index {index}") + return self._targets[offset] + + @property + def fingerprint(self) -> Fingerprint | None: + """Return the native observation fingerprint unless it has protected keys.""" + if self.ui.opaque or self._fingerprint is None: + return None + return unmasked_fingerprint( + self._fingerprint, + lambda value: "***" in value or self._redactor.redact(value) != value, + ) + + def to_json_data(self) -> dict[str, JsonValue]: + """Export redacted model data, never native targets or screenshot bytes.""" + ui = "***" if self.ui.opaque else self.ui.model_dump(mode="json") + return {"at": self.at.astimezone(UTC).isoformat(), "ui": cast(JsonValue, ui)} diff --git a/mobilerun/core/state/README.md b/mobilerun/core/state/README.md deleted file mode 100644 index 733d26524..000000000 --- a/mobilerun/core/state/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# state/ - -**Purpose:** UI state models and platform-specific state providers. - -**What belongs here / what doesn't:** Put state fetching, element parsing, filtering, and formatting here, not feature logic. - -**Contents:** - -- `__init__.py` — Public models and provider exports. -- `android.py` — Android state provider. -- `base.py` — Provider interface and screenshot resizing helpers. -- `elements.py` — UI element model. -- `filters/` — UI tree filters. -- `formatters/` — UI tree formatters. -- `ios.py` — iOS state provider. -- `options.py` — Typed options, vision policy and provider factories. -- `screenshot.py` — Screenshot-only provider. -- `stealth.py` — Randomized coordinate resolution. -- `ui_state.py` — Parsed UI state and element resolution. -- `view.py` — Device-facing cached state view. - -**Examples:** - -Run in an async function with an existing `device`. - -```python -state = await device.state.refresh() -print(state.formatted_text) -assert device.state.current is state -``` - -`StateProvider` declares all consumed capability flags, including -`use_normalized` and `requires_active_contract_for_coords`. The public state -controller exposes only `refresh()`, `current`, and `capabilities`. Read snapshot -fields and coordinate methods from the returned `UIState` or -`device.state.current`. No snapshot fields are forwarded by the controller. -Configure devices with `state_options=`, a `state_provider=` instance, or a -`state_provider_factory=(device, options) -> StateProvider`. An instance and -factory are mutually exclusive. Provider selection and coordinate plumbing are -private framework hooks. - -**Depends on / used by:** Uses shared packages and platform drivers; used by devices and features. - -See [devices](../devices/README.md), [filters](filters/README.md), and [formatters](formatters/README.md). diff --git a/mobilerun/core/state/__init__.py b/mobilerun/core/state/__init__.py deleted file mode 100644 index 854b58413..000000000 --- a/mobilerun/core/state/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -"""UI state and provider abstractions for Mobilerun.""" - -from mobilerun.core.state.android import AndroidStateProvider -from mobilerun.core.state.base import StateProvider -from mobilerun.core.state.ios import IOSStateProvider -from mobilerun.core.state.options import ( - StateProviderFactory, - StateProviderOptions, - VisionResizePolicy, -) -from mobilerun.core.state.screenshot import ScreenshotOnlyStateProvider -from mobilerun.core.state.stealth import StealthUIState -from mobilerun.core.state.ui_state import UIState -from mobilerun.models.ui import UIElement - -__all__ = [ - "UIState", - "UIElement", - "StealthUIState", - "StateProvider", - "StateProviderOptions", - "StateProviderFactory", - "VisionResizePolicy", - "AndroidStateProvider", - "IOSStateProvider", - "ScreenshotOnlyStateProvider", -] diff --git a/mobilerun/core/state/android.py b/mobilerun/core/state/android.py deleted file mode 100644 index 24a374004..000000000 --- a/mobilerun/core/state/android.py +++ /dev/null @@ -1,278 +0,0 @@ -"""StateProvider — orchestrates fetching and parsing device state. - -Fetches raw data from a ``DeviceDriver``, applies tree filters/formatters, -and produces a ``UIState`` snapshot. -""" - -from __future__ import annotations - -import asyncio -from copy import copy, deepcopy -from typing import TYPE_CHECKING, Any, Optional - -from mobilerun.clients.portal.state_fetch import fetch_state_with_retry -from mobilerun.config.settings import get_settings -from mobilerun.core.state.base import StateProvider -from mobilerun.core.state.stealth import StealthUIState -from mobilerun.core.state.ui_state import UIState -from mobilerun.utils.images import ( - fit_dimensions_to_max_side, -) -from mobilerun.utils.prompts import load_prompt_text - -NORMALIZED_STATE_NOTE = load_prompt_text("state/normalized_state_note.md") - -if TYPE_CHECKING: - from mobilerun.core.devices.base import Device - from mobilerun.core.state.filters import TreeFilter - from mobilerun.core.state.formatters import TreeFormatter - from mobilerun.core.state.options import VisionResizePolicy - - -def _has_single_focused_app_node(tree: dict[str, Any] | None, package: str) -> bool: - """Find a single enabled, editable focus in the primary app window.""" - if not tree or tree.get("packageName") != package: - return False - window = tree.get("windowId") - if window is None: - # Portal appends additional window roots as direct children. On compact - # snapshots, a resource-identified leaf is not another window branch; - # multiple other branches cannot reliably be assigned to one window. - branches = [ - child - for child in tree.get("children") or [] - if child.get("packageName") in (package, None, "") - and (child.get("children") or not child.get("resourceId")) - ] - if len(branches) > 1 or any( - not child.get("resourceId") - and child.get("className") == tree.get("className") - for child in branches - ): - return False - elif type(window) is not int or window < 0: - return False - pending = [tree] - focused = None - while pending: - node = pending.pop() - node_window = node.get("windowId") - if type(node_window) is int and node_window >= 0 and node_window != window: - # Portal may append additional window roots under the primary root. - if window is None and node.get("packageName") in (package, None, ""): - return False - continue - if ( - node.get("isFocused") is True - and node.get("isEnabled") is True - and node.get("packageName") == package - ): - if ( - focused is not None - or node_window != window - or type(node_window) is not type(window) - ): - return False - focused = node - pending.extend(node.get("children") or []) - if focused is None: - return False - if "isEditable" in focused: - return focused["isEditable"] is True - class_name = focused.get("className") - return isinstance(class_name, str) and ( - class_name.endswith("EditText") - or class_name.rsplit(".", 1)[-1] == "AutoCompleteTextView" - ) - - -class AndroidStateProvider(StateProvider): - """Fetches state from an Android device via ``driver._get_ui_tree()``. - - Includes retry logic with exponential backoff and mid-retry recovery - (accessibility service restart) for robustness against intermittent - Portal/a11y failures. - """ - - capabilities = {"element_index", "convert_point"} - - def __init__( - self, - driver: "Device", - tree_filter: "TreeFilter", - tree_formatter: "TreeFormatter", - use_normalized: bool = False, - stealth: bool = False, - ui_cls: "type[UIState] | None" = None, - vision_enabled: bool = False, - vision_resize_policy: VisionResizePolicy | None = None, - ) -> None: - super().__init__(driver) - self.tree_filter = tree_filter - self.tree_formatter = tree_formatter - self.use_normalized = use_normalized - self._ui_cls = ui_cls or (StealthUIState if stealth else UIState) - self.vision_enabled = vision_enabled - # Resolves the exact screenshot dims the active vision model grounds on - # (duck-typed: needs ``effective_dims(w, h)``). None → legacy 2048 cap. - self.vision_resize_policy = vision_resize_policy - # Exact model-facing screenshot dims for the current state (set per - # get_state); read by _resize_model_screenshot_with_grid. - self.model_screenshot_width: Optional[int] = None - self.model_screenshot_height: Optional[int] = None - # Model coordinates reach device pixels either 1:1, through the vision - # contract's scaling, or through normalized [0-1000] conversion. - self.screenshot_matches_input_coords = True - # Normalized [0-1000] coordinates are scale-invariant, so the - # deterministic-space contract is only needed for pixel coordinates. - # Re-evaluated per get_state: the flag must describe the CURRENT - # state's contract — if screen bounds are unavailable for a state, - # resizing that step's screenshot would desynchronize the model's - # space from convert_point. - self._vision_contract_intent = vision_enabled and not use_normalized - self.resize_model_screenshot = self._vision_contract_intent - # Hybrid vision exposes click_at when a coordinate contract is - # expected, but individual states can still arrive with missing or - # zero screen bounds. Refuse coordinate actions for those snapshots - # instead of mapping model coordinates against a wrong screen size. - self.requires_active_contract_for_coords = vision_enabled - - async def get_state(self) -> UIState: - combined_data = await fetch_state_with_retry( - fetch=self._device._get_ui_tree, - recovery=self._device._state_recovery, - ) - return await self._state_from_data_async(combined_data) - - async def get_final_state(self) -> UIState: - """Finalization must not restart accessibility after a failed read.""" - combined_data = await self._device._get_ui_tree() - return await self._state_from_data_async(combined_data) - - async def _state_from_data_async(self, combined_data: dict) -> UIState: - # Workers may outlive cancellation. Only their per-call copies may change. - processor = copy(self) - processor.tree_filter = deepcopy(self.tree_filter) - processor.tree_formatter = deepcopy(self.tree_formatter) - processor.vision_resize_policy = deepcopy(self.vision_resize_policy) - - def process() -> tuple[UIState, bool]: - state = processor._state_from_data(combined_data) - return state, processor.resize_model_screenshot - - state, resize = await asyncio.to_thread(process) - # Publish together on the loop only when processing completed successfully. - self.resize_model_screenshot = resize - self.model_screenshot_width = state.model_screenshot_width - self.model_screenshot_height = state.model_screenshot_height - self.tree_formatter.screen_width = state.screen_width - self.tree_formatter.screen_height = state.screen_height - self.tree_formatter.use_normalized = state.use_normalized - self.tree_formatter.display_scale_x = state.coordinate_scale_x - self.tree_formatter.display_scale_y = state.coordinate_scale_y - return state - - def _state_from_data(self, combined_data: dict) -> UIState: - - device_context = combined_data["device_context"] - screen_bounds = device_context.get("screen_bounds", {}) - screen_width = screen_bounds.get("width") - screen_height = screen_bounds.get("height") - - raw_tree = combined_data["a11y_tree"] - raw_phone_state = combined_data["phone_state"] - package = raw_phone_state.get("packageName") - focused = raw_phone_state.get("focusedElement") - editable = raw_phone_state.get("isEditable") - # Inspect only the raw app tree, not the separate ime_tree. Filters - # and formatters can omit nodes or discard their focus metadata. - has_single_focused_app_node = ( - combined_data.get("degraded", False) is False - and "focusedElement" in raw_phone_state - and isinstance(editable, bool) - and not (editable and isinstance(focused, dict) and focused) - and raw_phone_state.get("keyboardVisible") is True - and isinstance(package, str) - and bool(package) - and _has_single_focused_app_node(raw_tree, package) - ) - filtered = self.tree_filter.filter(raw_tree, device_context) - - coordinate_scale_x = 1.0 - coordinate_scale_y = 1.0 - display_width = None - display_height = None - if self._vision_contract_intent and screen_width and screen_height: - if self.vision_resize_policy is not None: - display_width, display_height = ( - self.vision_resize_policy.effective_dims( - screen_width, screen_height - ) - ) - else: - display_width, display_height = fit_dimensions_to_max_side( - screen_width, - screen_height, - get_settings().MOBILERUN_MODEL_SCREENSHOT_MAX_SIDE, - ) - coordinate_scale_x = screen_width / display_width - coordinate_scale_y = screen_height / display_height - if self._vision_contract_intent: - # Keep agent-side resizing paired with the contract this state - # actually declares (screen bounds can be missing for a state). - self.resize_model_screenshot = bool(display_width and display_height) - # Exact dims the model-facing screenshot must match for this state. - self.model_screenshot_width = display_width - self.model_screenshot_height = display_height - - self.tree_formatter.screen_width = screen_width - self.tree_formatter.screen_height = screen_height - self.tree_formatter.use_normalized = self.use_normalized - # Model-facing bounds text is emitted in the display space the model - # actually sees; tap bounds in ``elements`` stay native device pixels. - self.tree_formatter.display_scale_x = coordinate_scale_x - self.tree_formatter.display_scale_y = coordinate_scale_y - - formatted_text, focused_text, elements, phone_state = ( - self.tree_formatter.format(filtered, raw_phone_state) - ) - - if ( - self.use_normalized - and self.vision_enabled - and screen_width - and screen_height - ): - formatted_text += f"\n\n{NORMALIZED_STATE_NOTE}" - if display_width and display_height: - scaled_note = ( - f" — the {screen_width}x{screen_height} device screen scaled down" - if (display_width, display_height) != (screen_width, screen_height) - else "" - ) - formatted_text += ( - f"\n\nAll coordinates in this device state (element bounds above, " - f"and any x/y you provide to coordinate actions) are in a " - f"{display_width}x{display_height} coordinate space{scaled_note}. " - f"When a screenshot is provided it matches this " - f"{display_width}x{display_height} space and carries a labeled " - f"coordinate grid for reference." - ) - - state = self._ui_cls( - elements=elements, - formatted_text=formatted_text, - focused_text=focused_text, - phone_state=phone_state, - screen_width=screen_width, - screen_height=screen_height, - use_normalized=self.use_normalized, - coordinate_scale_x=coordinate_scale_x, - coordinate_scale_y=coordinate_scale_y, - coordinate_contract_active=bool(display_width and display_height) - or bool(self.use_normalized and screen_width and screen_height), - model_screenshot_width=display_width, - model_screenshot_height=display_height, - ) - state._has_single_focused_app_node = has_single_focused_app_node - return state diff --git a/mobilerun/core/state/base.py b/mobilerun/core/state/base.py deleted file mode 100644 index e1fa27c11..000000000 --- a/mobilerun/core/state/base.py +++ /dev/null @@ -1,121 +0,0 @@ -"""StateProvider — orchestrates fetching and parsing device state. - -Fetches raw data from a ``DeviceDriver``, applies tree filters/formatters, -and produces a ``UIState`` snapshot. -""" - -from __future__ import annotations - -import asyncio -from dataclasses import dataclass -from typing import TYPE_CHECKING - -from mobilerun.config.settings import get_settings -from mobilerun.core.state.ui_state import UIState -from mobilerun.utils.images import ( - resize_image_to_dimensions_with_grid, - resize_image_to_max_side_with_grid, -) - -if TYPE_CHECKING: - from mobilerun.core.devices.base import Device - - -class StateProvider: - """Base class — subclass to support different platforms.""" - - capabilities: set[str] = set() - use_normalized: bool = False - requires_active_contract_for_coords: bool = False - # True when coordinates a model derives from the screenshot map to the - # driver's tap input space — either directly (Android: screenshot and - # input coords are both device pixels) or via ``convert_point`` scaling - # (the vision coordinate contract; iOS sets this only when the contract - # is active, since its screenshots are physical pixels while taps use - # XCTest points). Gates the click_at auto-unmask with vision. - screenshot_matches_input_coords: bool = False - # True when the screenshot attached to LLM messages must first be resized - # (with a labeled coordinate grid) into the deterministic coordinate space - # the provider declared in ``formatted_text`` and compensates for via - # ``coordinate_scale_x/y``. Vision-model output spaces are otherwise - # model-dependent: a raw native screenshot is downscaled inside the LLM - # provider's API and different models answer in different spaces. - resize_model_screenshot: bool = False - requires_coordinate_tools: bool = False - model_screenshot_width: int | None = None - model_screenshot_height: int | None = None - model_screenshot_grid: bool = True - - def __init__(self, driver: "Device") -> None: - self._device = driver - - async def get_state(self) -> UIState: - raise NotImplementedError - - async def get_final_state(self) -> UIState: - """Read the final observation; subclasses may make this narrower.""" - return await self.get_state() - - -def _should_resize_model_screenshot(state_provider: StateProvider) -> bool: - """True when screenshots attached to LLM messages must be resized (with - the labeled grid) into the coordinate space the provider declared. - - Falls back to the legacy ``requires_coordinate_tools`` contract: injected - screenshot-only providers that predate ``resize_model_screenshot`` are - still treated as screenshot-coordinate mode by the tool registry, prompts, - and validation, so they must keep receiving resized screenshots too. - """ - return bool( - state_provider.resize_model_screenshot - or state_provider.requires_coordinate_tools - ) - - -def _resize_model_screenshot_with_grid( - state_provider: StateProvider | _ScreenshotGeometry, screenshot: bytes -) -> bytes: - """Resize a screenshot to the exact model-facing dims the provider declared. - - The provider stores ``model_screenshot_width/height`` (resolved from the - active vision model's effective image size) on each ``get_state``. Resizing - to those exact dims keeps the image the model grounds on equal to the - declared coordinate space. Falls back to the legacy max-side resize when no - dims are available (e.g. injected screenshot-only providers).""" - width = state_provider.model_screenshot_width - height = state_provider.model_screenshot_height - # A pixel grid contradicts a normalized coordinate contract. - divisions = 10 if state_provider.model_screenshot_grid else 0 - if width and height: - return resize_image_to_dimensions_with_grid( - screenshot, width, height, divisions=divisions - ) - return resize_image_to_max_side_with_grid( - screenshot, - get_settings().MOBILERUN_MODEL_SCREENSHOT_MAX_SIDE, - divisions=divisions, - ) - - -async def _resize_model_screenshot_async( - state_provider: StateProvider, screenshot: bytes -) -> bytes: - """Resize when required, snapshotting model geometry before offloading.""" - if not _should_resize_model_screenshot(state_provider): - return screenshot - - geometry = _ScreenshotGeometry( - model_screenshot_width=state_provider.model_screenshot_width, - model_screenshot_height=state_provider.model_screenshot_height, - model_screenshot_grid=state_provider.model_screenshot_grid, - ) - return await asyncio.to_thread( - _resize_model_screenshot_with_grid, geometry, screenshot - ) - - -@dataclass(frozen=True) -class _ScreenshotGeometry: - model_screenshot_width: int | None - model_screenshot_height: int | None - model_screenshot_grid: bool = True diff --git a/mobilerun/core/state/elements.py b/mobilerun/core/state/elements.py deleted file mode 100644 index 9e6a44280..000000000 --- a/mobilerun/core/state/elements.py +++ /dev/null @@ -1,8 +0,0 @@ -"""Typed representation of elements emitted by the UI tree formatters.""" - -from mobilerun.utils.geometry import Bounds - - -def _parse_bounds(value: str) -> Bounds: - left, top, right, bottom = map(int, value.split(",")) - return left, top, right, bottom diff --git a/mobilerun/core/state/filters/README.md b/mobilerun/core/state/filters/README.md deleted file mode 100644 index 8e85c5f22..000000000 --- a/mobilerun/core/state/filters/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# core/state/filters/ - -Filters accessibility trees before state formatting. - -Keep tree-filter strategies here; rendering belongs in `core/state/formatters/`. - -## Files - -- `__init__.py` — Exports `TreeFilter`, `ConciseFilter`, `DetailedFilter`, `get_filter`. -- `base.py` — `TreeFilter` — base interface for accessibility tree filters. -- `concise_filter.py` — `ConciseFilter` — concise filtering - all logic self-contained. -- `detailed_filter.py` — `DetailedFilter` — detailed filtering - all logic self-contained. -- `factory.py` — `get_filter` — ui tree filter factory. - -**Depends on / used by:** Uses the tree-filter interface; used by Android and iOS state providers and device defaults. - -See [state](../README.md) and [formatters](../formatters/README.md). diff --git a/mobilerun/core/state/filters/__init__.py b/mobilerun/core/state/filters/__init__.py deleted file mode 100644 index 8cbc0f59e..000000000 --- a/mobilerun/core/state/filters/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -"""Filter exports.""" - -from .base import TreeFilter -from .concise_filter import ConciseFilter -from .detailed_filter import DetailedFilter -from .factory import get_filter - -__all__ = ["TreeFilter", "ConciseFilter", "DetailedFilter", "get_filter"] diff --git a/mobilerun/core/state/filters/base.py b/mobilerun/core/state/filters/base.py deleted file mode 100644 index 251744cdd..000000000 --- a/mobilerun/core/state/filters/base.py +++ /dev/null @@ -1,20 +0,0 @@ -"""Base interface for accessibility tree filters.""" - -from abc import ABC, abstractmethod -from typing import Any, Dict, Optional - - -class TreeFilter(ABC): - """Interface for filtering accessibility trees.""" - - @abstractmethod - def filter( - self, a11y_tree: Dict[str, Any], device_context: Dict[str, Any] - ) -> Optional[Dict[str, Any]]: - """Filter tree and return filtered tree with hierarchy preserved.""" - pass - - @abstractmethod - def get_name(self) -> str: - """Return filter name.""" - pass diff --git a/mobilerun/core/state/filters/concise_filter.py b/mobilerun/core/state/filters/concise_filter.py deleted file mode 100644 index 8cb4e7831..000000000 --- a/mobilerun/core/state/filters/concise_filter.py +++ /dev/null @@ -1,68 +0,0 @@ -"""Concise filtering - all logic self-contained.""" - -from typing import Any, Dict, Optional - -from .base import TreeFilter - - -class ConciseFilter(TreeFilter): - """Concise tree filtering (formerly Mobilerun).""" - - def filter( - self, a11y_tree: Dict[str, Any], device_context: Dict[str, Any] - ) -> Optional[Dict[str, Any]]: - """Filter using concise logic.""" - screen_bounds = device_context.get("screen_bounds", {}) - filtering_params = device_context.get("filtering_params", {}) - - return self._filter_node(a11y_tree, screen_bounds, filtering_params) - - def _filter_node( - self, - node: Dict[str, Any], - screen_bounds: Dict[str, int], - filtering_params: Dict[str, Any], - ) -> Optional[Dict[str, Any]]: - """Recursively filter node.""" - min_size = filtering_params.get("min_element_size", 5) - screen_width = screen_bounds.get("width", 1080) - screen_height = screen_bounds.get("height", 2400) - - if not self._intersects_screen(node, screen_width, screen_height): - return None - if not self._min_size(node, min_size): - return None - - filtered_children = [] - for child in node.get("children") or []: - filtered_child = self._filter_node(child, screen_bounds, filtering_params) - if filtered_child: - filtered_children.append(filtered_child) - - return {**node, "children": filtered_children} - - @staticmethod - def _intersects_screen( - node: Dict[str, Any], screen_width: int, screen_height: int - ) -> bool: - """Check if element intersects screen bounds.""" - bounds = node.get("boundsInScreen", {}) - left = bounds.get("left", 0) - top = bounds.get("top", 0) - right = bounds.get("right", 0) - bottom = bounds.get("bottom", 0) - return not ( - right <= 0 or bottom <= 0 or left >= screen_width or top >= screen_height - ) - - @staticmethod - def _min_size(node: Dict[str, Any], min_size: int) -> bool: - """Check if element meets minimum size.""" - bounds = node.get("boundsInScreen", {}) - w = bounds.get("right", 0) - bounds.get("left", 0) - h = bounds.get("bottom", 0) - bounds.get("top", 0) - return w > min_size and h > min_size - - def get_name(self) -> str: - """Return filter name.""" - return "concise" diff --git a/mobilerun/core/state/filters/detailed_filter.py b/mobilerun/core/state/filters/detailed_filter.py deleted file mode 100644 index 5b596e076..000000000 --- a/mobilerun/core/state/filters/detailed_filter.py +++ /dev/null @@ -1,160 +0,0 @@ -"""Detailed filtering - all logic self-contained.""" - -from typing import Any, Dict, Optional - -from .base import TreeFilter - - -class DetailedFilter(TreeFilter): - """Detailed tree filtering with 10% visibility rule.""" - - def __init__( - self, - visibility_threshold: float = 0.1, - filter_keyboard: bool = True, - clip_bounds: bool = False, - ) -> None: - self.visibility_threshold = visibility_threshold - self.filter_keyboard = filter_keyboard - self.clip_bounds = clip_bounds - - def filter( - self, a11y_tree: Dict[str, Any], device_context: Dict[str, Any] - ) -> Optional[Dict[str, Any]]: - """Filter using detailed logic.""" - screen_bounds = device_context.get("screen_bounds", {}) - screen_width = screen_bounds.get("width", 1080) - screen_height = screen_bounds.get("height", 2400) - - filtered_tree = a11y_tree - - if self.clip_bounds: - filtered_tree = self._clip_tree_bounds( - filtered_tree, screen_width, screen_height - ) - - if self.filter_keyboard: - filtered_tree = self._filter_keyboard_elements(filtered_tree) - if filtered_tree is None: - return None - - filtered_tree = self._filter_out_of_bounds( - filtered_tree, screen_width, screen_height - ) - - return filtered_tree - - @staticmethod - def _get_visible_percentage( - bounds: Dict[str, int], screen_width: int, screen_height: int - ) -> float: - """Calculate what percentage of element is visible on screen.""" - left = bounds.get("left", 0) - top = bounds.get("top", 0) - right = bounds.get("right", 0) - bottom = bounds.get("bottom", 0) - - width = right - left - height = bottom - top - - if width == 0 and height == 0: - return 0.0 - - overflow = ( - left <= 0 and top <= 0 and right >= screen_width and bottom >= screen_height - ) - if overflow: - return 1.0 - - visible_x = max(0, min(right, screen_width) - max(left, 0)) - visible_y = max(0, min(bottom, screen_height) - max(top, 0)) - - visible_area = visible_x * visible_y - total_area = width * height - - return visible_area / total_area if total_area > 0 else 0.0 - - @staticmethod - def _clip_bounds_to_screen( - bounds: Dict[str, int], screen_width: int, screen_height: int - ) -> Dict[str, int]: - """Clip element bounds to screen boundaries.""" - return { - "left": max(bounds.get("left", 0), 0), - "top": max(bounds.get("top", 0), 0), - "right": min(bounds.get("right", 0), screen_width), - "bottom": min(bounds.get("bottom", 0), screen_height), - } - - @classmethod - def _clip_tree_bounds( - cls, node: Dict[str, Any], screen_width: int, screen_height: int - ) -> Dict[str, Any]: - """Recursively clip all bounds in tree to screen.""" - if "boundsInScreen" in node: - node = {**node} - node["boundsInScreen"] = cls._clip_bounds_to_screen( - node["boundsInScreen"], screen_width, screen_height - ) - - if "children" in node: - node["children"] = [ - cls._clip_tree_bounds(child, screen_width, screen_height) - for child in node.get("children") or [] - ] - - return node - - @staticmethod - def _should_filter_keyboard(node: Dict[str, Any]) -> bool: - """Check if element is from Google keyboard.""" - resource_id = node.get("resourceId", "") - return resource_id.startswith("com.google.android.inputmethod.latin:id/") - - @classmethod - def _filter_keyboard_elements( - cls, node: Dict[str, Any] - ) -> Optional[Dict[str, Any]]: - """Recursively remove keyboard elements from tree.""" - filtered_children = [] - for child in node.get("children") or []: - filtered_child = cls._filter_keyboard_elements(child) - if filtered_child is not None: - filtered_children.append(filtered_child) - - if cls._should_filter_keyboard(node): - return None - - return {**node, "children": filtered_children} - - def _filter_out_of_bounds( - self, node: Dict[str, Any], screen_width: int, screen_height: int - ) -> Optional[Dict[str, Any]]: - """Filter tree by visibility with parent preservation.""" - if node.get("ignoreBoundsFiltering") == "true": - return node - - filtered_children = [] - for child in node.get("children") or []: - filtered_child = self._filter_out_of_bounds( - child, screen_width, screen_height - ) - if filtered_child is not None: - filtered_children.append(filtered_child) - - bounds = node.get("boundsInScreen") - if bounds is None: - visible_percentage = 0.0 - else: - visible_percentage = self._get_visible_percentage( - bounds, screen_width, screen_height - ) - - if visible_percentage < self.visibility_threshold and not filtered_children: - return None - - return {**node, "children": filtered_children} - - def get_name(self) -> str: - """Return filter name.""" - return "detailed" diff --git a/mobilerun/core/state/filters/factory.py b/mobilerun/core/state/filters/factory.py deleted file mode 100644 index d889cea26..000000000 --- a/mobilerun/core/state/filters/factory.py +++ /dev/null @@ -1,21 +0,0 @@ -"""UI tree filter factory.""" - -from typing import Any - -from .base import TreeFilter -from .concise_filter import ConciseFilter -from .detailed_filter import DetailedFilter - - -def get_filter(name: str, **kwargs: Any) -> TreeFilter: - """Factory to get filter by name.""" - filters = { - "concise": ConciseFilter, - "detailed": DetailedFilter, - } - - filter_class = filters.get(name.lower()) - if filter_class is None: - raise ValueError(f"Unknown filter: {name}. Available: {list(filters.keys())}") - - return filter_class(**kwargs) diff --git a/mobilerun/core/state/formatters/README.md b/mobilerun/core/state/formatters/README.md deleted file mode 100644 index b43d1ad93..000000000 --- a/mobilerun/core/state/formatters/README.md +++ /dev/null @@ -1,15 +0,0 @@ -# core/state/formatters/ - -Formats filtered UI trees with indexed elements. - -Keep tree-to-text formatters here; filtering belongs in `core/state/filters/`. - -## Files - -- `__init__.py` — Exports `TreeFormatter`, `IndexedFormatter`. -- `base.py` — `TreeFormatter` — base interface for tree formatters. -- `indexed_formatter.py` — `IndexedFormatter` — indexed formatter - standard mobilerun format. - -**Depends on / used by:** Uses coordinate and geometry utilities; used by Android and iOS state providers and device defaults. - -See [state](../README.md) and [filters](../filters/README.md). diff --git a/mobilerun/core/state/formatters/__init__.py b/mobilerun/core/state/formatters/__init__.py deleted file mode 100644 index 9b82748eb..000000000 --- a/mobilerun/core/state/formatters/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -"""Formatter exports.""" - -from .base import TreeFormatter -from .indexed_formatter import IndexedFormatter - -__all__ = ["TreeFormatter", "IndexedFormatter"] diff --git a/mobilerun/core/state/formatters/base.py b/mobilerun/core/state/formatters/base.py deleted file mode 100644 index 51095ecb6..000000000 --- a/mobilerun/core/state/formatters/base.py +++ /dev/null @@ -1,33 +0,0 @@ -"""Base interface for tree formatters.""" - -from abc import ABC, abstractmethod -from typing import Any, Dict, List, Optional, Tuple - - -class TreeFormatter(ABC): - """Interface for formatting filtered trees.""" - - screen_width: int | None = None - screen_height: int | None = None - use_normalized: bool = False - display_scale_x: float = 1.0 - display_scale_y: float = 1.0 - - @abstractmethod - def format( - self, filtered_tree: Optional[Dict[str, Any]], phone_state: Dict[str, Any] - ) -> Tuple[str, str, List[Dict[str, Any]], Dict[str, Any]]: - """Format filtered tree to standard output format. - - Args: - filtered_tree: Filtered accessibility tree (or None) - phone_state: Raw phone state dictionary - - Returns: - Tuple of: - - formatted_text (str): Complete formatted device state for prompts - - focused_text (str): Text content of focused element (empty if none) - - a11y_tree (List[Dict]): Flattened/Processed accessibility tree with indices - - phone_state (Dict): Raw phone state dict - """ - pass diff --git a/mobilerun/core/state/formatters/indexed_formatter.py b/mobilerun/core/state/formatters/indexed_formatter.py deleted file mode 100644 index eea8ac24a..000000000 --- a/mobilerun/core/state/formatters/indexed_formatter.py +++ /dev/null @@ -1,273 +0,0 @@ -"""Indexed formatter - Standard Mobilerun format.""" - -from typing import Any, Dict, List, Optional, Tuple - -from mobilerun.core.state.elements import _parse_bounds -from mobilerun.utils.coordinates import bounds_to_normalized -from mobilerun.utils.geometry import rects_overlap -from mobilerun.utils.redaction import is_secure_ui_node - -from .base import TreeFormatter - - -class IndexedFormatter(TreeFormatter): - """Format tree in the standard Mobilerun format.""" - - def __init__(self) -> None: - self.screen_width: Optional[int] = None - self.screen_height: Optional[int] = None - self.use_normalized: bool = False - # Native-pixels-per-displayed-pixel of the screenshot shown to the - # model. When != 1.0, the bounds in the model-facing text are emitted - # in display space while ``bounds`` (used for real taps) stay native. - self.display_scale_x: float = 1.0 - self.display_scale_y: float = 1.0 - - def format( - self, filtered_tree: Optional[Dict[str, Any]], phone_state: Dict[str, Any] - ) -> Tuple[str, str, List[Dict[str, Any]], Dict[str, Any]]: - """Format device state with indices and hierarchy.""" - focused_text = self._get_focused_text(phone_state) - - if filtered_tree is None: - a11y_tree = [] - else: - a11y_tree = self._flatten_with_index(filtered_tree, [1]) - - phone_state_text = self._format_phone_state(phone_state) - ui_elements_text = self._format_ui_elements_text(a11y_tree) - - formatted_text = f"{phone_state_text}\n\n{ui_elements_text}" - - return (formatted_text, focused_text, a11y_tree, phone_state) - - @staticmethod - def _get_focused_text(phone_state: Dict[str, Any]) -> str: - """Extract focused element text.""" - focused_element = phone_state.get("focusedElement") - if focused_element: - return focused_element.get("text", "") - return "" - - @staticmethod - def _format_phone_state(phone_state: Dict[str, Any]) -> str: - """Format phone state.""" - if isinstance(phone_state, dict) and "error" not in phone_state: - current_app = phone_state.get("currentApp", "") - package_name = phone_state.get("packageName", "") - focused_element = phone_state.get("focusedElement") - is_editable = phone_state.get("isEditable", False) - - if focused_element and focused_element.get("text"): - focused_desc = f"'{focused_element.get('text', '')}'" - else: - focused_desc = "''" - - # Build app line — skip package if empty, skip whole line if both empty - if current_app and package_name: - app_line = f"• **App:** {current_app} ({package_name})" - elif current_app: - app_line = f"• **App:** {current_app}" - elif package_name: - app_line = f"• **App:** {package_name}" - else: - app_line = "" - - lines = ["**Current Phone State:**"] - if app_line: - lines.append(app_line) - lines.append(f"• **Keyboard:** {'Visible' if is_editable else 'Hidden'}") - lines.append(f"• **Focused Element:** {focused_desc}") - - phone_state_text = "\n".join(lines) - else: - if isinstance(phone_state, dict) and "error" in phone_state: - phone_state_text = f"📱 **Phone State Error:** {phone_state.get('message', 'Unknown error')}" - else: - phone_state_text = f"📱 **Phone State:** {phone_state}" - - return phone_state_text - - def _format_ui_elements_text(self, a11y_tree: List[Dict[str, Any]]) -> str: - """Format UI elements text.""" - # Label only bounds that were actually normalized. - normalized = self.use_normalized and self.screen_width and self.screen_height - coord_note = " (normalized [0-1000])" if normalized else "" - schema = ( - "'index. className: resourceId; checkedState, text - bounds(x1,y1,x2,y2)'" - ) - if a11y_tree: - formatted_ui = IndexedFormatter._format_ui_elements(a11y_tree) - ui_elements_text = ( - f"Current Clickable UI elements{coord_note}:\n{schema}:\n{formatted_ui}" - ) - else: - ui_elements_text = f"Current Clickable UI elements{coord_note}:\n{schema}:\nNo UI elements found" - return ui_elements_text - - @staticmethod - def _format_ui_elements(ui_data: List[Dict[str, Any]], level: int = 0) -> str: - """Format UI elements.""" - if not ui_data: - return "" - - formatted_lines = [] - indent = " " * level - - elements = ui_data if isinstance(ui_data, list) else [ui_data] - - for element in elements: - if not isinstance(element, dict): - continue - - index = element.get("index", "") - class_name = element.get("className", "") - resource_id = element.get("resourceId", "") - text = element.get("text", "") - # Model-facing text shows display-space or normalized bounds; - # "bounds" (native pixels) drive real taps. - bounds = element.get("displayBounds") or element.get("bounds", "") - checkedState = element.get("checkedState", "") - children = element.get("children") or [] - - line_parts = [] - if index != "": - line_parts.append(f"{index}.") - if class_name: - line_parts.append(class_name + ":") - - details = [] - if resource_id: - details.append(f'"{resource_id}"') - if text: - details.append(f'"{text}"') - - if details: - line_parts.append(", ".join(details)) - - if checkedState: - line_parts.append(f"; {checkedState}") - - if bounds: - line_parts.append(f"- ({bounds})") - - formatted_line = f"{indent}{' '.join(line_parts)}" - formatted_lines.append(formatted_line) - - if children: - child_formatted = IndexedFormatter._format_ui_elements( - children, level + 1 - ) - if child_formatted: - formatted_lines.append(child_formatted) - - return "\n".join(formatted_lines) - - def _flatten_with_index( - self, node: Dict[str, Any], counter: List[int] - ) -> List[Dict[str, Any]]: - """Recursively flatten tree with index assignment.""" - results = [] - - formatted = self._format_node(node, counter[0]) - results.append(formatted) - counter[0] += 1 - - siblings = [] - for child in node.get("children") or []: - descendants = self._flatten_with_index(child, counter) - siblings.append((child, descendants[0])) - results.extend(descendants) - - self._add_tap_blockers(siblings) - - return results - - @staticmethod - def _add_tap_blockers( - siblings: List[Tuple[Dict[str, Any], Dict[str, Any]]], - ) -> None: - """Retain proven sibling touch obstructions before discarding hierarchy. - - Android drawingOrder is relative to siblings, not a global z-index. - Portal can append other windows as children, so windowId must match. - Missing or tied order is insufficient evidence to change existing taps. - """ - for raw, formatted in siblings: - order = raw.get("drawingOrder") - window = raw.get("windowId") - if not isinstance(order, int) or not isinstance(window, int) or window < 0: - continue - bounds = _parse_bounds(formatted["bounds"]) - blockers = [] - for other, candidate in siblings: - other_order = other.get("drawingOrder") - if ( - other.get("windowId") != window - or not isinstance(other_order, int) - or other_order <= order - or other.get("isVisibleToUser") is False - or not (other.get("isClickable") or other.get("isLongClickable")) - ): - continue - candidate_bounds = _parse_bounds(candidate["bounds"]) - if rects_overlap(bounds, candidate_bounds): - blockers.append(candidate["bounds"]) - if blockers: - formatted["tapBlockers"] = blockers - - def _format_node(self, node: Dict[str, Any], index: int) -> Dict[str, Any]: - """Format single node to Mobilerun format.""" - bounds = node.get("boundsInScreen", {}) - bounds_str = f"{bounds.get('left', 0)},{bounds.get('top', 0)},{bounds.get('right', 0)},{bounds.get('bottom', 0)}" - - display_bounds_str = None - if self.use_normalized and self.screen_width and self.screen_height: - display_bounds_str = bounds_to_normalized( - bounds_str, self.screen_width, self.screen_height - ) - elif self.display_scale_x != 1.0 or self.display_scale_y != 1.0: - display_bounds_str = ",".join( - str(round(value / scale)) - for value, scale in zip( - (int(part) for part in bounds_str.split(",")), - ( - self.display_scale_x, - self.display_scale_y, - self.display_scale_x, - self.display_scale_y, - ), - strict=True, - ) - ) - - text = ( - node.get("text") - or node.get("contentDescription") - or node.get("resourceId") - or node.get("className", "") - ) - - class_name = node.get("className", "") - short_class = class_name.split(".")[-1] if class_name else "" - - checked_state = "" - if node.get("isCheckable"): - checked_state = ( - "isChecked=True" if node.get("isChecked") else "isChecked=False" - ) - - formatted = { - "index": index, - "resourceId": node.get("resourceId", ""), - "className": short_class, - "checkedState": checked_state, - "text": text, - "bounds": bounds_str, - "children": [], - } - if display_bounds_str is not None: - formatted["displayBounds"] = display_bounds_str - if is_secure_ui_node(node): - formatted["isPassword"] = True - return formatted diff --git a/mobilerun/core/state/ios.py b/mobilerun/core/state/ios.py deleted file mode 100644 index 7feec9f90..000000000 --- a/mobilerun/core/state/ios.py +++ /dev/null @@ -1,435 +0,0 @@ -"""IOSStateProvider — builds UIState from iOS portal accessibility data. - -Parses the raw text-based accessibility tree returned by the iOS portal -into structured elements compatible with UIState. - -Known limitations: -- Normalized coordinates untested on real iOS devices -- No filter/formatter pipeline (iOS UIState still formats from raw a11y text) -""" - -from __future__ import annotations - -import logging -import re -from typing import TYPE_CHECKING, Any, Dict, List, Optional - -from mobilerun_core_local.driver.base import DeviceDisconnectedError - -if TYPE_CHECKING: - from mobilerun.core.devices.base import Device - from mobilerun.core.state.options import VisionResizePolicy - -from mobilerun.config.settings import get_settings -from mobilerun.core.state.base import StateProvider -from mobilerun.core.state.ui_state import UIState -from mobilerun.utils.coordinates import bounds_to_normalized -from mobilerun.utils.images import ( - fit_dimensions_to_max_side, - image_dimensions, -) -from mobilerun.utils.prompts import load_prompt_text - -NORMALIZED_STATE_NOTE = load_prompt_text("state/normalized_state_note.md") - -logger = logging.getLogger("mobilerun") - -# Element types to skip — layout containers that add noise without useful info. -# Everything else is kept (buttons, cells, text, icons, images, etc.) -_SKIP_TYPES = { - "Window", - "Window (Main)", - "ScrollView", - "CollectionView", - "Table", - "Toolbar", - "TabBar", - "StatusBar", - "PageIndicator", -} - -_COORD_RE = re.compile(r"\{\{([0-9.]+),\s*([0-9.]+)\},\s*\{([0-9.]+),\s*([0-9.]+)\}\}") -_ELEMENT_TYPE_RE = re.compile(r"\s*(.+?),") -_LABEL_RE = re.compile(r"label:\s*'([^']*)'") -_IDENTIFIER_RE = re.compile(r"identifier:\s*'([^']*)'") -_PLACEHOLDER_RE = re.compile(r"placeholderValue:\s*'([^']*)'") -_VALUE_RE = re.compile(r"value:\s*([^,}]+)") -_CLOCK_RE = re.compile(r"^\d{1,2}:\d{2}$") - - -class IOSStateProvider(StateProvider): - """Produces ``UIState`` from an iOS device's accessibility tree.""" - - capabilities = {"element_index", "convert_point"} - - def __init__( - self, - driver: Device, - use_normalized: bool = False, - vision_enabled: bool = False, - vision_resize_policy: VisionResizePolicy | None = None, - ) -> None: - super().__init__(driver) - self.use_normalized = use_normalized - self.vision_enabled = vision_enabled - # Resolves the exact screenshot dims the active vision model grounds on - # (duck-typed: needs ``effective_dims(w, h)``). None → legacy 2048 cap. - self.vision_resize_policy = vision_resize_policy - self.model_screenshot_width: Optional[int] = None - self.model_screenshot_height: Optional[int] = None - # iOS screenshots are physical pixels while taps/bounds are points, so - # without the contract a vision model answers in image space and taps - # land wrong. Normalized [0-1000] coordinates are scale-invariant and - # opt out, mirroring AndroidStateProvider. - # - # The flag is re-evaluated on every get_state: it must describe the - # CURRENT state's contract, because the agents resize the screenshot - # they captured based on it. If the contract could not be established - # for a state (screenshot probe failed), resizing that step's image - # would desynchronize the model's space from convert_point. - self._vision_contract_intent = vision_enabled and not use_normalized - self.resize_model_screenshot = self._vision_contract_intent - # Without the contract, iOS screenshots (physical pixels) do not map - # to tap input (points), so coordinate tools stay masked. With the - # contract active, or in normalized mode, convert_point maps the - # model's coordinates to points, making click_at safe to auto-enable. - self.screenshot_matches_input_coords = ( - self._vision_contract_intent or use_normalized - ) - # Coordinate actions are only safe while the contract is active (iOS - # taps use points, not screenshot pixels). Action-time guards refuse - # them on a state without it. See - # actions._require_active_coordinate_contract. - self.requires_active_contract_for_coords = vision_enabled - - async def get_state(self, *, strict: bool = False) -> UIState: - """Read the UI tree, allowing agent fallback unless strict is requested.""" - try: - raw = await self._device._get_ui_tree() - except DeviceDisconnectedError: - raise - except Exception as e: - if strict: - raise - logger.warning(f"iOS state retrieval failed, returning empty state: {e}") - # No contract for this state — agents must not resize the - # screenshot they attach alongside it. - if self._vision_contract_intent: - self.resize_model_screenshot = False - self.model_screenshot_width = None - self.model_screenshot_height = None - return UIState( - elements=[], - formatted_text="No UI elements available — device may be loading.", - focused_text="", - phone_state={}, - screen_width=390, - screen_height=844, - use_normalized=self.use_normalized, - ) - - a11y_tree = raw.get("a11y_tree", "") - a11y_text = ( - a11y_tree if isinstance(a11y_tree, str) else raw.get("raw_a11y_tree", "") - ) - phone_state = dict(raw.get("phone_state", {}) or {}) - device_context = raw.get("device_context", {}) - - elements = _parse_a11y_tree(a11y_text) - phone_state = _normalize_phone_state(phone_state, a11y_text) - - # Screen size from device_context (points — the tap input space) - screen_bounds = device_context.get("screen_bounds", {}) - screen_width = int(screen_bounds.get("width", 390)) - screen_height = int(screen_bounds.get("height", 844)) - - # Normalized coordinates need the real screen size, not the defaults. - normalized_ready = bool( - self.use_normalized - and screen_bounds.get("width") - and screen_bounds.get("height") - ) - - # Vision coordinate contract: the screenshot agents attach is resized - # (with a labeled grid) into a display space derived from the actual - # physical-pixel screenshot; the portal reports only points, so the - # physical dimensions must be measured from real bytes (the device - # scale factor varies, 2x/3x). - coordinate_scale_x = 1.0 - coordinate_scale_y = 1.0 - display_width = None - display_height = None - if self._vision_contract_intent and screen_width and screen_height: - try: - screenshot = await self._device.screenshot() - shot_width, shot_height = image_dimensions(screenshot) - if self.vision_resize_policy is not None: - display_width, display_height = ( - self.vision_resize_policy.effective_dims( - shot_width, shot_height - ) - ) - else: - display_width, display_height = fit_dimensions_to_max_side( - shot_width, - shot_height, - get_settings().MOBILERUN_MODEL_SCREENSHOT_MAX_SIDE, - ) - # convert_point maps model output back to POINTS, not pixels - coordinate_scale_x = screen_width / display_width - coordinate_scale_y = screen_height / display_height - except Exception as e: - logger.warning( - f"iOS vision coordinate contract disabled for this state " - f"(screenshot probe failed): {e}" - ) - display_width = None - display_height = None - coordinate_scale_x = 1.0 - coordinate_scale_y = 1.0 - if self._vision_contract_intent: - # Keep agent-side resizing paired with the contract this state - # actually declares. - self.resize_model_screenshot = bool(display_width and display_height) - # Exact dims the model-facing screenshot must match for this state. - self.model_screenshot_width = display_width - self.model_screenshot_height = display_height - - if display_width and display_height: - # Model-facing bounds in display space; "bounds" (points) keep - # driving element taps. - for element in elements: - left, top, right, bottom = ( - int(part) for part in element["bounds"].split(",") - ) - element["displayBounds"] = ",".join( - str(round(value / scale)) - for value, scale in zip( - (left, top, right, bottom), - ( - coordinate_scale_x, - coordinate_scale_y, - coordinate_scale_x, - coordinate_scale_y, - ), - strict=True, - ) - ) - elif normalized_ready: - # Model-facing bounds in 0-1000; "bounds" (points) keep driving taps. - for element in elements: - element["displayBounds"] = bounds_to_normalized( - element["bounds"], screen_width, screen_height - ) - - formatted_text = _format_elements( - elements, screen_width, screen_height, normalized=normalized_ready - ) - if normalized_ready and self.vision_enabled: - formatted_text += f"\n\n{NORMALIZED_STATE_NOTE}" - - if display_width and display_height: - formatted_text += ( - f"\n\nAll coordinates in this device state (element bounds above, " - f"and any x/y you provide to coordinate actions) are in a " - f"{display_width}x{display_height} coordinate space — the device " - f"screen scaled to the screenshot shown to you. " - f"When a screenshot is provided it matches this " - f"{display_width}x{display_height} space and carries a labeled " - f"coordinate grid for reference." - ) - - # Extract focused text from phone_state - focused_element = phone_state.get("focusedElement") - focused_text = "" - if focused_element and isinstance(focused_element, dict): - focused_text = focused_element.get("text", "") - - return UIState( - elements=elements, - formatted_text=formatted_text, - focused_text=focused_text, - phone_state=phone_state, - screen_width=screen_width, - screen_height=screen_height, - use_normalized=self.use_normalized, - coordinate_scale_x=coordinate_scale_x, - coordinate_scale_y=coordinate_scale_y, - coordinate_contract_active=bool(display_width and display_height) - or normalized_ready, - model_screenshot_width=display_width, - model_screenshot_height=display_height, - ) - - -# --------------------------------------------------------------------------- -# Parsing -# --------------------------------------------------------------------------- - - -def _parse_a11y_tree(a11y_text: str) -> List[Dict[str, Any]]: - """Parse iOS accessibility tree text into structured elements. - - Moved verbatim from ``IOSTools._parse_ios_accessibility_tree``. - """ - elements: List[Dict[str, Any]] = [] - element_index = 0 - - seen_signatures: set[tuple[str, str, str]] = set() - - for line in a11y_text.strip().split("\n"): - stripped = line.strip() - if ( - not stripped - or stripped.startswith("Attributes:") - or stripped.startswith("Element subtree:") - or stripped.startswith("Path to element:") - or stripped.startswith("Query chain:") - ): - continue - - coord_match = _COORD_RE.search(line) - if not coord_match: - continue - - x, y, width, height = map(float, coord_match.groups()) - - # Skip elements with no tappable area - if width == 0 or height == 0: - continue - - # Element type - type_match = _ELEMENT_TYPE_RE.match(line) - element_type = type_match.group(1).strip() if type_match else "Unknown" - element_type = re.sub(r"^[→\s]+", "", element_type) - - # Skip layout containers that add noise without useful info - if element_type in _SKIP_TYPES: - continue - - # Extract properties - label_m = _LABEL_RE.search(line) - label = label_m.group(1) if label_m else "" - ident_m = _IDENTIFIER_RE.search(line) - identifier = ident_m.group(1) if ident_m else "" - ph_m = _PLACEHOLDER_RE.search(line) - placeholder = ph_m.group(1) if ph_m else "" - val_m = _VALUE_RE.search(line) - value = val_m.group(1).strip() if val_m else "" - - text = label or identifier or placeholder or "" - - # Bounds in "left,top,right,bottom" format — compatible with UIState - bounds_str = f"{int(x)},{int(y)},{int(x + width)},{int(y + height)}" - - # Filter noisy wrapper nodes that duplicate a more useful action target. - signature = (element_type, text, bounds_str) - if element_type == "Other" and not ( - label or identifier or placeholder or value - ): - continue - if signature in seen_signatures: - continue - seen_signatures.add(signature) - - elements.append( - { - "index": element_index, - "type": element_type, - "className": element_type, - "text": text, - "label": label, - "identifier": identifier, - "placeholder": placeholder, - "value": value, - "bounds": bounds_str, - "rect": f"{x},{y},{width},{height}", - "children": [], - } - ) - element_index += 1 - - return _prioritize_actionable_elements(elements) - - -def _normalize_phone_state( - phone_state: Dict[str, Any], a11y_text: str -) -> Dict[str, Any]: - package_name = phone_state.get("packageName", "") or "" - current_app = phone_state.get("currentApp", "") or "" - - is_home = ( - package_name == "com.apple.springboard" or "Home screen icons" in a11y_text - ) - if is_home: - phone_state["packageName"] = "com.apple.springboard" - if not current_app or _CLOCK_RE.match(current_app): - phone_state["currentApp"] = "Home Screen" - elif current_app and _CLOCK_RE.match(current_app): - phone_state["currentApp"] = "" - - return phone_state - - -def _prioritize_actionable_elements( - elements: List[Dict[str, Any]], -) -> List[Dict[str, Any]]: - actionable_types = { - "Icon", - "Button", - "SearchField", - "TextField", - "SecureTextField", - "TextView", - "Cell", - "StaticText", - "Image", - "Switch", - } - - def sort_key(el: Dict[str, Any]) -> tuple[int, int]: - class_name = el.get("className", "") - text = el.get("text", "") - actionable_rank = 0 if class_name in actionable_types and text else 1 - return (actionable_rank, el.get("index", 0)) - - ordered = sorted(elements, key=sort_key) - for i, el in enumerate(ordered): - el["index"] = i - return ordered - - -# --------------------------------------------------------------------------- -# Formatting for agent prompt -# --------------------------------------------------------------------------- - - -def _format_elements( - elements: List[Dict[str, Any]], - screen_width: int, - screen_height: int, - normalized: bool = False, -) -> str: - """Build the text representation shown to the agent.""" - coord_note = " (normalized [0-1000])" if normalized else "" - schema = "'index. className: text - bounds(x1,y1,x2,y2)'" - if not elements: - return f"Current UI elements{coord_note}:\n{schema}:\nNo UI elements found" - - lines = [f"Current UI elements{coord_note}:\n{schema}:"] - for el in elements: - idx = el.get("index", 0) - cls = el.get("className", "Unknown") - text = el.get("text", "") - # Model-facing text shows display-space or normalized bounds; - # "bounds" (points) drive real taps. - bounds = el.get("displayBounds") or el.get("bounds", "") - - parts = [f"{idx}. {cls}:"] - if text: - parts.append(text) - if bounds: - parts.append(f"- ({bounds})") - lines.append(" ".join(parts)) - - return "\n".join(lines) diff --git a/mobilerun/core/state/options.py b/mobilerun/core/state/options.py deleted file mode 100644 index fc3b29e87..000000000 --- a/mobilerun/core/state/options.py +++ /dev/null @@ -1,74 +0,0 @@ -"""Typed construction options shared by device state-provider factories.""" - -from __future__ import annotations - -from collections.abc import Callable -from dataclasses import dataclass -from typing import TYPE_CHECKING, Protocol - -from mobilerun.core.state.filters import TreeFilter - -if TYPE_CHECKING: - from mobilerun.core.devices.base import Device - from mobilerun.core.state.base import StateProvider - - -class VisionResizePolicy(Protocol): - def effective_dims(self, width: int, height: int) -> tuple[int, int]: ... - - -@dataclass(frozen=True) -class StateProviderOptions: - vision: bool = False - normalized: bool = False - stealth: bool = False - vision_resize_policy: VisionResizePolicy | None = None - tree_filter: TreeFilter | None = None - - -StateProviderFactory = Callable[["Device", StateProviderOptions], "StateProvider"] - - -def android_state_provider( - device: Device, options: StateProviderOptions -) -> StateProvider: - from mobilerun.core.state.android import AndroidStateProvider - from mobilerun.core.state.filters import ConciseFilter, DetailedFilter - from mobilerun.core.state.formatters import IndexedFormatter - - return AndroidStateProvider( - device, - tree_filter=( - options.tree_filter - if options.tree_filter is not None - else (ConciseFilter() if options.vision else DetailedFilter()) - ), - tree_formatter=IndexedFormatter(), - vision_enabled=options.vision, - use_normalized=options.normalized, - stealth=options.stealth, - vision_resize_policy=options.vision_resize_policy, - ) - - -def ios_state_provider(device: Device, options: StateProviderOptions) -> StateProvider: - from mobilerun.core.state.ios import IOSStateProvider - - return IOSStateProvider( - device, - vision_enabled=options.vision, - use_normalized=options.normalized, - vision_resize_policy=options.vision_resize_policy, - ) - - -def screenshot_state_provider( - device: Device, options: StateProviderOptions -) -> StateProvider: - from mobilerun.core.state.screenshot import ScreenshotOnlyStateProvider - - return ScreenshotOnlyStateProvider( - device, - vision_resize_policy=options.vision_resize_policy, - use_normalized=options.normalized, - ) diff --git a/mobilerun/core/state/screenshot.py b/mobilerun/core/state/screenshot.py deleted file mode 100644 index 4efa701be..000000000 --- a/mobilerun/core/state/screenshot.py +++ /dev/null @@ -1,113 +0,0 @@ -"""Screenshot-only state provider for visual control backends.""" - -from __future__ import annotations - -from typing import TYPE_CHECKING, Optional - -from mobilerun.config.settings import get_settings -from mobilerun.core.state.base import StateProvider -from mobilerun.core.state.ui_state import UIState -from mobilerun.utils.images import ( - fit_dimensions_to_max_side, - image_dimensions, -) -from mobilerun.utils.prompts import load_prompt_text - -if TYPE_CHECKING: - from mobilerun.core.devices.base import Device - from mobilerun.core.state.options import VisionResizePolicy - - -class ScreenshotOnlyStateProvider(StateProvider): - """Build UI state from screenshots without reading an accessibility tree.""" - - capabilities = {"convert_point", "direct_text_input"} - requires_coordinate_tools = True - resize_model_screenshot = True - - _guidance = load_prompt_text("state/screenshot_only_guidance.md") - - def __init__( - self, - driver: "Device", - vision_resize_policy: VisionResizePolicy | None = None, - use_normalized: bool = False, - ) -> None: - super().__init__(driver) - # Resolves the exact screenshot dims the active vision model grounds on - # (duck-typed: needs ``effective_dims(w, h)``). None → legacy 2048 cap. - self.vision_resize_policy = vision_resize_policy - # Normalized mode declares a 0-1000 grid instead of screenshot pixels. - self.use_normalized = use_normalized - self.model_screenshot_grid = not use_normalized - self.model_screenshot_width: Optional[int] = None - self.model_screenshot_height: Optional[int] = None - - async def get_state(self) -> UIState: - screenshot = await self._device.screenshot() - native_width, native_height = image_dimensions(screenshot) - input_width, input_height = await self._device._input_coordinate_size( - native_width, native_height - ) - if self.vision_resize_policy is not None: - screen_width, screen_height = self.vision_resize_policy.effective_dims( - native_width, native_height - ) - else: - screen_width, screen_height = fit_dimensions_to_max_side( - native_width, - native_height, - get_settings().MOBILERUN_MODEL_SCREENSHOT_MAX_SIDE, - ) - self.model_screenshot_width = screen_width - self.model_screenshot_height = screen_height - phone_state = { - "observationMode": "screenshot_only", - "accessibilityTree": False, - } - - if self.use_normalized: - return UIState( - elements=[], - formatted_text=( - "Screenshot-only mode is active. There is no accessibility " - "tree or element index list. Inspect the screenshot and use " - "coordinate actions in normalized coordinates: both axes run " - "from 0 to 1000 across the screenshot, whatever the image " - "size, so (0,0) is top-left, (500,500) is the center and " - f"(1000,1000) is bottom-right. {self._guidance}" - ), - focused_text="", - phone_state=phone_state, - screen_width=input_width, - screen_height=input_height, - use_normalized=True, - model_screenshot_width=screen_width, - model_screenshot_height=screen_height, - ) - - max_x = max(screen_width - 1, 0) - max_y = max(screen_height - 1, 0) - return UIState( - elements=[], - formatted_text=( - "Screenshot-only mode is active. There is no accessibility tree " - "or element index list. Inspect the screenshot and use coordinate " - "actions in the screenshot pixel coordinates shown to the model. " - "The screenshot includes a coordinate grid for visual reference; " - "use the underlying screenshot pixel coordinates, not grid-cell " - "numbers. " - f"The screenshot shown to the model is {screen_width}x{screen_height}; " - "(0,0) is top-left and " - f"({max_x},{max_y}) is bottom-right. {self._guidance}" - ), - focused_text="", - phone_state=phone_state, - screen_width=screen_width, - screen_height=screen_height, - use_normalized=False, - coordinate_scale_x=input_width / screen_width, - coordinate_scale_y=input_height / screen_height, - model_screenshot_width=screen_width, - model_screenshot_height=screen_height, - ) diff --git a/mobilerun/core/state/snapshot.py b/mobilerun/core/state/snapshot.py deleted file mode 100644 index 262a73315..000000000 --- a/mobilerun/core/state/snapshot.py +++ /dev/null @@ -1,169 +0,0 @@ -"""One observed device state, with value-safe serialization for evidence sinks.""" - -from __future__ import annotations - -from copy import copy -from dataclasses import dataclass, field -from datetime import UTC, datetime -from typing import TYPE_CHECKING - -from pydantic import JsonValue - -from mobilerun.core.credentials.masking import current_masks -from mobilerun.core.state.formatters.indexed_formatter import IndexedFormatter -from mobilerun.errors import DeviceOperationNotSupported -from mobilerun.models import Fingerprint -from mobilerun.models.context import ContextItem -from mobilerun.utils.redaction import _active_secrets, mask_secure_ui, mask_step_args -from mobilerun.utils.screen_fingerprint import screen_fingerprint - -if TYPE_CHECKING: - from mobilerun.core.devices.base import Device - from mobilerun.core.state.ui_state import UIState - -_UI_FIELDS = ( - "elements", - "formatted_text", - "focused_text", - "phone_state", - "screen_width", - "screen_height", - "use_normalized", - "coordinate_scale_x", - "coordinate_scale_y", - "coordinate_contract_active", - "model_screenshot_width", - "model_screenshot_height", -) - - -@dataclass -class DeviceSnapshot: - """A UI observation and public extension context; PNG bytes stay out of JSON.""" - - at: datetime - ui: UIState = field(repr=False) - screenshot: bytes | None = field(default=None, repr=False) - context: list[ContextItem] = field(default_factory=list, repr=False) - - @classmethod - async def observe( - cls, device: Device, *, screenshot: bool = False, redact: bool = True - ) -> DeviceSnapshot: - """Refresh live UI and context, optionally taking an unredacted screenshot.""" - from mobilerun.core.runs import recording_scope - - with recording_scope(enabled=False): - return await cls._from_ui( - device, - await device.state.refresh(), - screenshot=screenshot, - redact=redact, - ) - - @classmethod - async def _from_ui( - cls, device: Device, ui: UIState, *, screenshot: bool, redact: bool - ) -> DeviceSnapshot: - at = datetime.now(UTC) - context = list(await device.context()) - result = cls(at, ui, context=context) - if screenshot: - try: - image = await device.screenshot() - except DeviceOperationNotSupported: - pass - else: - result.screenshot = image or None - if not redact: - return result - safe_ui = copy(ui) - masked = result._ui_payload(device, live=True) - for name, value in masked.items(): - setattr(safe_ui, name, value) - return cls(at, safe_ui, result.screenshot, result._context_payload(device)) - - @staticmethod - def is_sensitive(device: Device) -> bool: - masks = current_masks.get() - return bool( - device._extension_state.sensitive_ui - or _active_secrets.get() - or (masks and masks.active) - ) - - @property - def fingerprint(self) -> Fingerprint: - payload: dict[str, JsonValue] = { - "phone_state": self.ui.phone_state, - "elements": [*self.ui.elements], - } - safe = mask_secure_ui(payload) - return screen_fingerprint(safe if safe is payload else {}) - - def _ui_payload( - self, device: Device | None, *, live: bool = False - ) -> dict[str, JsonValue]: - ui = {name: getattr(self.ui, name) for name in _UI_FIELDS} - rerender = False - sensitive = device is not None and self.is_sensitive(device) - if not live and sensitive: - # A secret may have passed through a scope that already exited. - # IDs and app/activity can be supplied dynamically, so omit them too. - ui.update( - elements=[], phone_state={}, formatted_text="***", focused_text="***" - ) - else: - secure = mask_secure_ui(ui, retain_targeting=live) - rerender = live and (sensitive or secure is not ui) - ui = secure - safe = mask_step_args( - ui, - contains_code=( - device._extension_state.contains_sensitive_text - if device is not None - else None - ), - ) - if live and (rerender or safe != ui): - formatter = IndexedFormatter() - formatter.screen_width = self.ui.screen_width - formatter.screen_height = self.ui.screen_height - formatter.use_normalized = self.ui.use_normalized - elements = safe.get("elements") - if isinstance(elements, list): - safe["formatted_text"] = formatter._format_ui_elements_text( - [node for node in elements if isinstance(node, dict)] - ) - return safe - - def _context_payload(self, device: Device | None) -> list[ContextItem]: - if device is not None and self.is_sensitive(device): - return [] - contains_code = ( - device._extension_state.contains_sensitive_text - if device is not None - else None - ) - items = [] - for item in self.context: - safe = mask_step_args( - {"source": item.source, "kind": item.kind, "data": dict(item.data)}, - contains_code=contains_code, - ) - if isinstance(safe["data"], dict): - items.append( - ContextItem(str(safe["source"]), str(safe["kind"]), safe["data"]) - ) - return items - - def to_json_data(self, *, device: Device | None = None) -> dict[str, JsonValue]: - """Serialize redacted UI fields and context; supply the device for taint checks.""" - return { - "at": self.at.astimezone(UTC).isoformat(), - "ui": self._ui_payload(device), - "device_context": [ - {"source": item.source, "kind": item.kind, "data": dict(item.data)} - for item in self._context_payload(device) - ], - } diff --git a/mobilerun/core/state/stealth.py b/mobilerun/core/state/stealth.py deleted file mode 100644 index 2ce99def8..000000000 --- a/mobilerun/core/state/stealth.py +++ /dev/null @@ -1,104 +0,0 @@ -"""StealthUIState — randomized coordinate resolution for human-like taps. - -Overrides ``UIState.get_element_coords()`` and ``get_clear_point()`` -to return randomized positions within element bounds, avoiding the -predictable dead-center taps that betray automation. -""" - -from __future__ import annotations - -import random -from typing import Tuple - -from mobilerun.core.state.ui_state import UIState - - -class StealthUIState(UIState): - """UIState variant that randomizes tap coordinates within element bounds.""" - - def get_element_coords(self, index: int) -> Tuple[int, int]: - """Return a randomized point within the safe zone of element *index*. - - The safe zone is the inner 40% of the element (20% inset from each - edge), ensuring taps land clearly inside the element. - - Raises ``ValueError`` when the element is missing or has no bounds. - """ - element = self._find_by_index(self.elements, index) - - if element is None: - indices = sorted(self._collect_indices(self.elements)) - indices_str = ", ".join(str(i) for i in indices[:20]) - if len(indices) > 20: - indices_str += f"... and {len(indices) - 20} more" - raise ValueError( - f"No element found with index {index}. Available indices: {indices_str}" - ) - - bounds_str = element.get("bounds") - if not bounds_str: - text = element.get("text", "No text") - cls = element.get("className", "Unknown class") - etype = element.get("type", "unknown") - raise ValueError( - f"Element with index {index} ('{text}', {cls}, type: {etype}) " - f"has no bounds and cannot be tapped" - ) - - try: - left, top, right, bottom = map(int, bounds_str.split(",")) - except ValueError as e: - raise ValueError( - f"Invalid bounds format for element with index {index}: {bounds_str}" - ) from e - - center_x = (left + right) // 2 - center_y = (top + bottom) // 2 - - width = right - left - height = bottom - top - - # Safe zone: inner 40% (20% inset from each edge) - safe_zone = 0.4 - x_range = max(5, int(width * safe_zone)) - y_range = max(5, int(height * safe_zone)) - - x = center_x + random.randint(-x_range // 2, x_range // 2) - y = center_y + random.randint(-y_range // 2, y_range // 2) - - # Clamp to stay within bounds - x = max(left + 2, min(x, right - 2)) - y = max(top + 2, min(y, bottom - 2)) - - return self._avoid_tap_blockers(element, (x, y)) - - def get_clear_point(self, index: int) -> Tuple[int, int]: - """Find a clear tap point for *index*, then randomize around it. - - Uses the parent overlap-avoidance logic, then adds jitter within - a 20% radius of the element dimensions. - """ - # Get the overlap-free center from parent - cx, cy = super().get_clear_point(index) - - element = self._find_by_index(self.elements, index) - if element is None: - raise ValueError(f"No element found with index {index}") - bounds_str = element.get("bounds", "") - if not bounds_str: - return cx, cy - - left, top, right, bottom = map(int, bounds_str.split(",")) - width = right - left - height = bottom - top - - x_range = max(5, int(width * 0.2)) - y_range = max(5, int(height * 0.2)) - - x = cx + random.randint(-x_range // 2, x_range // 2) - y = cy + random.randint(-y_range // 2, y_range // 2) - - x = max(left + 2, min(x, right - 2)) - y = max(top + 2, min(y, bottom - 2)) - - return x, y diff --git a/mobilerun/core/state/ui_state.py b/mobilerun/core/state/ui_state.py deleted file mode 100644 index 2a3e1e848..000000000 --- a/mobilerun/core/state/ui_state.py +++ /dev/null @@ -1,223 +0,0 @@ -"""UIState — parsed UI elements with element resolution and coordinate conversion. - -Replaces ``clickable_elements_cache``, ``_extract_element_coordinates_by_index``, -and the scattered ``find_element_by_index`` local functions from ``adb.py``. -""" - -from __future__ import annotations - -from typing import Any, Dict, List, Optional, Tuple - -from mobilerun.core.state.elements import _parse_bounds -from mobilerun.utils.coordinates import NORMALIZED_MAX -from mobilerun.utils.geometry import ( - find_clear_point, - find_uncovered_point, - rects_overlap, -) - - -class UIState: - """Holds parsed UI elements for a single device state snapshot.""" - - def __init__( - self, - elements: List[Dict[str, Any]], - formatted_text: str, - focused_text: str, - phone_state: Dict[str, Any], - screen_width: int, - screen_height: int, - use_normalized: bool = False, - coordinate_scale_x: float = 1.0, - coordinate_scale_y: float = 1.0, - coordinate_contract_active: bool = False, - model_screenshot_width: Optional[int] = None, - model_screenshot_height: Optional[int] = None, - ) -> None: - self.elements = elements - self.formatted_text = formatted_text - self.focused_text = focused_text - self.phone_state = phone_state - self._has_single_focused_app_node: bool = False - self.screen_width = screen_width - self.screen_height = screen_height - self.use_normalized = use_normalized - self.coordinate_scale_x = coordinate_scale_x - self.coordinate_scale_y = coordinate_scale_y - # Exact pixel size the model-facing screenshot must be resized to so the - # image the model grounds on matches this snapshot's declared coordinate - # space (== convert_point basis). None means "no contract / native". - self.model_screenshot_width = model_screenshot_width - self.model_screenshot_height = model_screenshot_height - # Whether a coordinate contract (resized+grid screenshot with declared - # display space, or normalized 0-1000 with a real screen size) is - # active for this snapshot. Action-time - # coordinate guards read it from here so they match the space this - # snapshot's convert_point uses. - self.coordinate_contract_active = coordinate_contract_active - - # -- element lookup ------------------------------------------------------ - - def get_element(self, index: int) -> Optional[Dict[str, Any]]: - """Recursively find an element by its index.""" - return self._find_by_index(self.elements, index) - - def get_element_coords(self, index: int) -> Tuple[int, int]: - """Return the centre, avoiding known touchable sibling obstructions. - - Raises ``ValueError`` when the element is missing or has no bounds. - """ - element = self._find_by_index(self.elements, index) - - if element is None: - indices = sorted(self._collect_indices(self.elements)) - indices_str = ", ".join(str(i) for i in indices[:20]) - if len(indices) > 20: - indices_str += f"... and {len(indices) - 20} more" - raise ValueError( - f"No element found with index {index}. Available indices: {indices_str}" - ) - - bounds_str = element.get("bounds") - if not bounds_str: - text = element.get("text", "No text") - cls = element.get("className", "Unknown class") - etype = element.get("type", "unknown") - raise ValueError( - f"Element with index {index} ('{text}', {cls}, type: {etype}) " - f"has no bounds and cannot be tapped" - ) - - try: - left, top, right, bottom = map(int, bounds_str.split(",")) - except ValueError as e: - raise ValueError( - f"Invalid bounds format for element with index {index}: {bounds_str}" - ) from e - - return self._avoid_tap_blockers( - element, ((left + right) // 2, (top + bottom) // 2) - ) - - def _avoid_tap_blockers( - self, element: Dict[str, Any], point: Tuple[int, int] - ) -> Tuple[int, int]: - """Keep a preferred point unless the formatter identified an obstruction.""" - blockers = [_parse_bounds(bounds) for bounds in element.get("tapBlockers", [])] - x, y = point - if not any( - left <= x < right and top <= y < bottom - for left, top, right, bottom in blockers - ): - return point - left, top, right, bottom = map(int, element["bounds"].split(",")) - if self.screen_width and self.screen_height: - left, top = max(0, left), max(0, top) - right = min(self.screen_width, right) - bottom = min(self.screen_height, bottom) - clear = find_uncovered_point((left, top, right, bottom), blockers) - if clear is None: - raise ValueError(f"No clear tap point for element {element.get('index')}") - return clear - - def get_element_info(self, index: int) -> Dict[str, Any]: - """Return a dict with common element fields for display.""" - element = self.get_element(index) - if element is None: - return {} - - info: Dict[str, Any] = { - "text": element.get("text", "No text"), - "className": element.get("className", "Unknown class"), - "type": element.get("type", "unknown"), - } - - children = element.get("children") or [] - if children: - child_texts = [c.get("text") for c in children if c.get("text")] - if child_texts: - info["child_texts"] = child_texts - - return info - - def get_clear_point(self, index: int) -> Tuple[int, int]: - """Find a tap point for *index* that avoids overlapping elements. - - Falls back to the centre if no clear point exists. - """ - element = self._find_by_index(self.elements, index) - if element is None: - raise ValueError(f"No element found with index {index}") - - bounds_str = element.get("bounds") - if not bounds_str: - raise ValueError(f"Element {index} has no bounds") - - target_bounds = _parse_bounds(bounds_str) - - all_elements = self._collect_all(self.elements) - blockers = [] - for el in all_elements: - el_idx = el.get("index") - el_bounds_str = el.get("bounds") - if el_idx is not None and el_idx > index and el_bounds_str: - el_bounds = _parse_bounds(el_bounds_str) - if rects_overlap(target_bounds, el_bounds): - blockers.append(el_bounds) - - point = find_clear_point(target_bounds, blockers) - if point is None: - raise ValueError( - f"Element {index} is fully obscured by overlapping elements" - ) - return point - - def convert_point(self, x: int | float, y: int | float) -> Tuple[int, int]: - """Convert point to absolute pixels if normalized mode is active.""" - if self.use_normalized: - abs_x = int(x * self.screen_width / NORMALIZED_MAX) - abs_y = int(y * self.screen_height / NORMALIZED_MAX) - # 1000 maps to one past the last pixel; keep it on screen. - if x == NORMALIZED_MAX: - abs_x = max(self.screen_width - 1, 0) - if y == NORMALIZED_MAX: - abs_y = max(self.screen_height - 1, 0) - return abs_x, abs_y - return ( - int(round(x * self.coordinate_scale_x)), - int(round(y * self.coordinate_scale_y)), - ) - - # -- internal helpers ---------------------------------------------------- - - @staticmethod - def _find_by_index( - elements: List[Dict[str, Any]], target: int - ) -> Optional[Dict[str, Any]]: - for item in elements: - if item.get("index") == target: - return item - child = UIState._find_by_index(item.get("children") or [], target) - if child is not None: - return child - return None - - @staticmethod - def _collect_indices(elements: List[Dict[str, Any]]) -> List[int]: - indices: List[int] = [] - for item in elements: - if item.get("index") is not None: - indices.append(item["index"]) - indices.extend(UIState._collect_indices(item.get("children") or [])) - return indices - - @staticmethod - def _collect_all( - elements: List[Dict[str, Any]], - ) -> List[Dict[str, Any]]: - result: List[Dict[str, Any]] = [] - for item in elements: - result.append(item) - result.extend(UIState._collect_all(item.get("children") or [])) - return result diff --git a/mobilerun/core/state/view.py b/mobilerun/core/state/view.py deleted file mode 100644 index b2b9bcf17..000000000 --- a/mobilerun/core/state/view.py +++ /dev/null @@ -1,77 +0,0 @@ -"""A small controller for a cached observation, not a second snapshot model.""" - -from __future__ import annotations - -from collections.abc import Callable -from typing import TYPE_CHECKING - -from mobilerun.core.state.base import StateProvider -from mobilerun.core.state.ui_state import UIState -from mobilerun.errors import DeviceNotReady, UnsupportedStateCapability - -if TYPE_CHECKING: - from mobilerun.core.devices.base import Device - - -class UIStateView: - def __init__( - self, - device: Device, - default_provider: Callable[[], StateProvider] | None = None, - ) -> None: - self._device = device - self._default_provider = default_provider - self._factory: Callable[[Device], StateProvider] | None = None - self._provider: StateProvider | None = None - self._current: UIState | None = None - - def _attach(self, provider: StateProvider | None) -> None: - if callable(provider): - raise TypeError( - "Pass a StateProvider instance; use state_provider_factory= for factories" - ) - self._factory = None - self._provider = provider - self._current = None - - def _attach_factory(self, factory: Callable[[Device], StateProvider]) -> None: - self._factory = factory - self._provider = None - self._current = None - - @property - def _resolved_provider(self) -> StateProvider: - if self._provider is None: - if self._factory is not None: - self._provider = self._factory(self._device) - elif self._default_provider is not None: - self._provider = self._default_provider() - else: - raise DeviceNotReady("No state provider is configured") - return self._provider - - def _reset_default(self) -> None: - self._attach(None) - - @property - def capabilities(self) -> set[str]: - return set(self._resolved_provider.capabilities) - - @property - def current(self) -> UIState: - if self._current is None: - raise DeviceNotReady( - "UI state has not been refreshed; call await device.state.refresh()" - ) - return self._current - - def _require(self, capability: str) -> None: - if capability not in self.capabilities: - raise UnsupportedStateCapability(self._resolved_provider, capability) - - async def refresh(self) -> UIState: - self._current = await self._resolved_provider.get_state() - return self._current - - async def _final(self) -> UIState: - return await self._resolved_provider.get_final_state() diff --git a/mobilerun/core/webhooks/README.md b/mobilerun/core/webhooks/README.md index ae379f465..7575374c3 100644 --- a/mobilerun/core/webhooks/README.md +++ b/mobilerun/core/webhooks/README.md @@ -42,13 +42,15 @@ reading them in plaintext requires `.get_secret_value()`. | File | Purpose | | --- | --- | | `__init__.py` | Public API, including `DEFAULT_WEBHOOK_EVENT` | -| `cloud.py` | Endpoint operations, validation, and URL lookup | +| `cloud.py` | Endpoint operations and URL lookup | +| `helpers/requests.py` | Value-safe translation of webhook SDK errors | + +Local URL validation lives in [`utils/webhooks/urls.py`](../../utils/webhooks/urls.py). Set `MOBILERUN_WEBHOOK_PAGE_SIZE` and `MOBILERUN_WEBHOOK_PING_TIMEOUT` via [shared settings](../../config/README.md#settings-overview). `ping` uses the SDK’s `webhooks.test_delivery(id)` (`POST /webhooks/{id}/test`). The service signs and attempts delivery before returning the outcome and HTTP status, so there is no need to poll delivery history. Receiver error text is not returned. The SDK also exposes `deliveries.list_for_webhook` and `deliveries.retrieve_attempts` for history. See the [backend implementation](https://github.com/droidrun/webhooks-api/blob/94783f57f4c7c4e7c014ae3fcaf91c0b39396e09/src/modules/endpoints/service/endpoints.service.ts#L495-L530). -See the [cloud SDK adapter](../../clients/cloud/webhooks.py), -[endpoint model](../../models/webhooks.py), [webhook CLI](../../cli/webhook/README.md), +See the [endpoint model](../../models/webhooks.py), [webhook CLI](../../cli/webhook/README.md), and [sandbox result delivery](../../sandbox/README.md#send-a-function-result-to-a-webhook). diff --git a/mobilerun/core/webhooks/__init__.py b/mobilerun/core/webhooks/__init__.py index 60196f1e4..2b366d7ae 100644 --- a/mobilerun/core/webhooks/__init__.py +++ b/mobilerun/core/webhooks/__init__.py @@ -1,12 +1,11 @@ """Webhook endpoint management for the Mobilerun cloud account.""" -from mobilerun.models.webhooks import WebhookEndpoint +from mobilerun.utils.webhooks.urls import validate_webhook_url -from .cloud import DEFAULT_WEBHOOK_EVENT, CloudWebhooks, validate_webhook_url +from .cloud import DEFAULT_WEBHOOK_EVENT, CloudWebhooks __all__ = [ "DEFAULT_WEBHOOK_EVENT", "CloudWebhooks", - "WebhookEndpoint", "validate_webhook_url", ] diff --git a/mobilerun/core/webhooks/cloud.py b/mobilerun/core/webhooks/cloud.py index f1585f9ed..959a8d09f 100644 --- a/mobilerun/core/webhooks/cloud.py +++ b/mobilerun/core/webhooks/cloud.py @@ -1,74 +1,25 @@ """Manage organization webhook endpoints using the configured cloud account.""" +import asyncio from collections.abc import Sequence from uuid import UUID -from pydantic import HttpUrl +from mobilerun_sdk.types.webhook_create_response import Data as Created +from mobilerun_sdk.types.webhook_list_response import Item +from mobilerun_sdk.types.webhook_retrieve_response import Data as Retrieved +from pydantic import SecretStr -from mobilerun.clients.cloud import webhooks +from mobilerun.clients.cloud.client import cloud_client from mobilerun.config.settings import get_settings -from mobilerun.errors.cloud import CloudValidationError +from mobilerun.errors.cloud import CloudTimeout, CloudValidationError from mobilerun.models.billing import Billing from mobilerun.models.webhooks import WebhookEndpoint +from mobilerun.utils.redaction import secret_scope +from mobilerun.utils.webhooks.urls import validate_webhook_url -DEFAULT_WEBHOOK_EVENT = "workflow.step.emit" -_WEBHOOK_URL_MAX_LENGTH = 2048 - - -def _validate_webhook_url_length(value: str) -> None: - if len(value) > _WEBHOOK_URL_MAX_LENGTH: - raise CloudValidationError( - f"Webhook URL exceeds {_WEBHOOK_URL_MAX_LENGTH} characters." - ) +from .helpers.requests import request_webhook - -def validate_webhook_url(value: str) -> str: - """Return the canonical HTTPS registration URL or raise a value-safe error.""" - if not isinstance(value, str): - raise CloudValidationError("Webhook URL must be a string.") - _validate_webhook_url_length(value) - if any( - c.isspace() or ord(c) < 32 or 127 <= ord(c) <= 159 or c == "\\" for c in value - ): - raise CloudValidationError( - "Remove whitespace, control characters and backslashes from the URL." - ) - if not value.lower().startswith("https://"): - raise CloudValidationError("Webhook URL must start with https://.") - parsed = None - if value[8:9] not in ("", "/", "?", "#"): - try: - parsed = HttpUrl(value) - except ValueError: - pass # Do not chain the parser error: it contains the caller's URL. - if parsed is None: - raise CloudValidationError( - "Webhook URL needs a valid hostname and port (if specified)." - ) - if parsed.username is not None or parsed.password is not None: - raise CloudValidationError( - "Remove the username or password from the webhook URL." - ) - if parsed.fragment is not None: - raise CloudValidationError("Remove the fragment (#…) from the webhook URL.") - # webhooks-api's normalizeUrl removes trailing slashes only from the path. - base, separator, query = str(parsed).partition("?") - if parsed.path and parsed.path != "/": - base = base.rstrip("/") - if not parsed.path.rstrip("/"): - base += "/" - canonical = base + separator + query - _validate_webhook_url_length(canonical) - return canonical - - -def _id(value: str) -> str: - if isinstance(value, str): - try: - return str(UUID(value)) - except ValueError: - pass - raise CloudValidationError("Expected a webhook endpoint UUID") +DEFAULT_WEBHOOK_EVENT = "workflow.step.emit" class CloudWebhooks: @@ -91,29 +42,62 @@ async def register( """Register a new HTTPS destination. An explicit empty filter subscribes to all events.""" if isinstance(event_types, (str, bytes)): raise CloudValidationError("Expected a sequence of webhook event types") - return await webhooks.register_webhook( - validate_webhook_url(url), - event_types, - idempotency_key, - billing=self._billing, - ) + url = validate_webhook_url(url) + with secret_scope(url): + async with cloud_client(billing=self._billing) as client: + response = await request_webhook( + client.webhooks.create( + url=url, + event_types=list(event_types), + idempotency_key=idempotency_key, + ), + "Register webhook", + ) + return self._endpoint(response.data, response.data.secret) async def get(self, endpoint_id: str) -> WebhookEndpoint: """Get endpoint metadata by UUID.""" - return await webhooks.get_webhook(_id(endpoint_id), billing=self._billing) + endpoint_id = self._endpoint_id(endpoint_id) + async with cloud_client(billing=self._billing) as client: + response = await request_webhook( + client.webhooks.retrieve(endpoint_id), "Get webhook" + ) + return self._endpoint(response.data) async def list(self) -> list[WebhookEndpoint]: """List all endpoint kinds and states visible to the account.""" - return await webhooks.list_webhooks( - get_settings().MOBILERUN_WEBHOOK_PAGE_SIZE, billing=self._billing - ) + page_size = get_settings().MOBILERUN_WEBHOOK_PAGE_SIZE + endpoints: list[WebhookEndpoint] = [] + async with cloud_client(billing=self._billing) as client: + page = 1 + while True: + response = await request_webhook( + client.webhooks.list(page=page, page_size=page_size), + "List webhooks", + ) + endpoints.extend(self._endpoint(item) for item in response.items) + if not response.pagination.has_next: + return endpoints + page += 1 async def ping(self, endpoint_id: str) -> tuple[bool, int | None]: """Send one service-signed test. Return success and receiver HTTP status.""" - return await webhooks.ping_webhook( - _id(endpoint_id), - get_settings().MOBILERUN_WEBHOOK_PING_TIMEOUT, - billing=self._billing, + endpoint_id = self._endpoint_id(endpoint_id) + timeout = get_settings().MOBILERUN_WEBHOOK_PING_TIMEOUT + async with cloud_client(billing=self._billing) as client: + try: + async with asyncio.timeout(timeout): + response = await request_webhook( + client.with_options(max_retries=0).webhooks.test_delivery( + endpoint_id + ), + "Ping webhook", + ) + except TimeoutError: + raise CloudTimeout(operation="Ping webhook") from None + data = response.data + return data.success, ( + int(data.status_code) if data.status_code is not None else None ) async def find_by_url(self, url: str) -> WebhookEndpoint | None: @@ -133,4 +117,29 @@ async def find_by_url(self, url: str) -> WebhookEndpoint | None: async def delete(self, endpoint_id: str) -> None: """Delete by UUID. Callers must decide whether they own or may delete it.""" - await webhooks.delete_webhook(_id(endpoint_id), billing=self._billing) + endpoint_id = self._endpoint_id(endpoint_id) + async with cloud_client(billing=self._billing) as client: + await request_webhook(client.webhooks.delete(endpoint_id), "Delete webhook") + + @staticmethod + def _endpoint( + data: Created | Retrieved | Item, secret: str | None = None + ) -> WebhookEndpoint: + return WebhookEndpoint( + data.id, + data.kind, + SecretStr(data.url) if data.url else None, + data.state, + data.health, + tuple(data.event_types), + SecretStr(secret) if secret else None, + ) + + @staticmethod + def _endpoint_id(value: str) -> str: + if isinstance(value, str): + try: + return str(UUID(value)) + except ValueError: + pass + raise CloudValidationError("Expected a webhook endpoint UUID") diff --git a/mobilerun/core/webhooks/helpers/requests.py b/mobilerun/core/webhooks/helpers/requests.py new file mode 100644 index 000000000..ec6e5aeb1 --- /dev/null +++ b/mobilerun/core/webhooks/helpers/requests.py @@ -0,0 +1,79 @@ +"""Translate webhook SDK failures without displaying request or response data.""" + +import re +from collections.abc import Awaitable +from typing import TypeVar + +import httpx +from mobilerun_sdk import APIError, APIStatusError + +from mobilerun.clients.cloud.errors import CloudErrorMapper +from mobilerun.errors.cloud import ( + CloudConflict, + CloudResourceNotFound, + CloudValidationError, +) + +T = TypeVar("T") + + +def _registration_error(body: object) -> CloudValidationError: + # Match only known service messages. Never render untrusted response text. + message = body.get("message") if isinstance(body, dict) else None + reasons = { + "eventTypes contains an unknown or non-webhook-deliverable type": "The filter contains an unknown or non-webhook-deliverable event type.", + "url is not a valid absolute URL": "The destination is not a valid absolute URL.", + "url scheme must be http or https": "The destination needs an HTTPS URL.", + "url must not contain userinfo (user:pass@…)": "Remove the username or password from the URL.", + "url must not contain a fragment (#…)": "Remove the URL fragment.", + } + reason = "The service rejected this registration; unrecognized details were withheld for privacy." + if isinstance(message, str): + if re.fullmatch(r"endpoint limit reached \([0-9]+ per org\)", message): + reason = "The organization has reached its webhook endpoint limit." + else: + reason = reasons.get(message, reason) + return CloudValidationError( + f"Register webhook failed (HTTP 400). {reason}", + operation="Register webhook", + status=400, + ) + + +async def request_webhook(request: Awaitable[T], operation: str) -> T: + try: + return await request + except (APIError, httpx.HTTPError) as exc: + error = CloudErrorMapper.from_exception(exc, operation) + if operation == "Register webhook" and isinstance(exc, APIStatusError): + if exc.status_code == 400: + error = _registration_error(exc.body) + elif isinstance(exc.body, dict): + code = exc.body.get("code") + if ( + exc.status_code == 409 + and code == "conflict" + and exc.body.get("message") + == "a webhook for this URL already exists" + ): + error = CloudConflict( + operation=operation, status=409, code="webhook_duplicate_url" + ) + elif ( + exc.status_code == 409 and code == "idempotency_request_in_progress" + ): + error = CloudConflict( + operation=operation, + status=409, + code="webhook_registration_in_progress", + ) + elif ( + exc.status_code == 404 + and code == "not_found" + and exc.response.headers.get("Idempotent-Replayed") == "true" + ): + error = CloudResourceNotFound( + operation=operation, status=404, code="webhook_replay_deleted" + ) + # Drop the raw response and request (which can contain the URL or secret). + raise error from None diff --git a/mobilerun/core/workspace.py b/mobilerun/core/workspace.py index 474629816..80c2bc27d 100644 --- a/mobilerun/core/workspace.py +++ b/mobilerun/core/workspace.py @@ -2,68 +2,110 @@ from __future__ import annotations -from pathlib import Path +import mimetypes +from pathlib import Path, PurePosixPath from tempfile import TemporaryDirectory from typing import TYPE_CHECKING -from mobilerun.models import App, Billing, DeviceFile, WorkspaceFile +from mobilerun.clients.cloud.resource import CloudResource +from mobilerun.models import App, Billing, WorkspaceFile if TYPE_CHECKING: - from mobilerun.core.devices.base import Device + from mobilerun_core import AsyncDevice + from mobilerun_sdk import AsyncMobilerun + from mobilerun_sdk.types.file_confirm_response import FileConfirmResponse + from mobilerun_sdk.types.file_list_response import File -class Workspace: - """Manage assets in an account, independently of any particular device. +class Workspace(CloudResource): + """Manage account assets independently of any particular device. Credentials default to MOBILERUN_API_KEY, then saved login. Overrides select - the source workspace; a destination device keeps its own account and billing. + the workspace account; devices keep their own credentials. """ - @classmethod - async def upload_file( - cls, - path: str | Path, + def __init__( + self, *, api_key: str | None = None, base_url: str | None = None, - billing: Billing = Billing.NO_COMMERCE, - ) -> WorkspaceFile: - # Defer cloud SDK imports until a Workspace operation runs. - from mobilerun.clients.cloud import files as cloud_files - from mobilerun.clients.cloud.client import cloud_client - - async with cloud_client(api_key, base_url, billing=billing) as client: - return await cloud_files.upload_file(client, path, billing=billing) - - @classmethod - async def list_files( - cls, - *, - api_key: str | None = None, - base_url: str | None = None, - billing: Billing = Billing.NO_COMMERCE, - ) -> list[WorkspaceFile]: - from mobilerun.clients.cloud import files as cloud_files - from mobilerun.clients.cloud.client import cloud_client - - async with cloud_client(api_key, base_url, billing=billing) as client: - return await cloud_files.list_files(client, billing=billing) - - @classmethod - async def download_file( - cls, - file_id: str, - dest: str | Path = ".", - *, - api_key: str | None = None, - base_url: str | None = None, - billing: Billing = Billing.NO_COMMERCE, - ) -> Path: - from mobilerun.clients.cloud import files as cloud_files - from mobilerun.clients.cloud.client import cloud_client + billing: Billing | str = Billing.NO_COMMERCE, + client: AsyncMobilerun | None = None, + ) -> None: + super().__init__( + billing=billing, api_key=api_key, base_url=base_url, client=client + ) + + @staticmethod + def _file(item: File | FileConfirmResponse) -> WorkspaceFile: + return WorkspaceFile( + item.file_id, + item.filename, + item.mime_type, + int(item.size_bytes), + item.created_at, + ) - async with cloud_client(api_key, base_url, billing=billing) as client: - items = await cloud_files.list_files(client, billing=billing) + async def _list_files(self, client: AsyncMobilerun) -> list[WorkspaceFile]: + with self._errors("List files"): + result = await client.files.list(zone="user") + return [self._file(item) for item in result.files] + + async def _download_file(self, client: AsyncMobilerun, file_id: str) -> bytes: + from mobilerun.utils.network.quiet import quiet_transport_logs + + with self._errors("Download file"): + with quiet_transport_logs("mobilerun_sdk._base_client"): + response = await client.files.with_raw_response.download(file_id) + return await response.read() + + async def upload_file(self, path: str | Path) -> WorkspaceFile: + """Upload a file through a signed URL and confirm successful storage.""" + import httpx + + from mobilerun.clients.cloud.signed_http import SignedHTTP + + billing = self._billing.require(Billing.NO_COMMERCE, "Prepare file upload") + path = Path(path) + content = path.read_bytes() + mime_type = mimetypes.guess_type(path.name)[0] or "application/octet-stream" + async with self._client(billing) as client: + with self._errors("Prepare file upload"): + signed = await client.files.upload_url( + filename=path.name, + mime_type=mime_type, + size_bytes=len(content), + zone="user", + ) + with self._errors("Upload file"): + try: + async with SignedHTTP.open(httpx.AsyncClient()) as http: + response = await http.put( + signed.put_url, + content=content, + headers={"Content-Type": mime_type}, + timeout=None, + ) + response.raise_for_status() + return self._file(await client.files.confirm(signed.file_id)) + except BaseException: + try: + await client.files.cancel_pending(signed.file_id) + except Exception: + pass + raise + + async def list_files(self) -> list[WorkspaceFile]: + """List files belonging to this workspace.""" + billing = self._billing.require(Billing.NO_COMMERCE, "List files") + async with self._client(billing) as client: + return await self._list_files(client) + + async def download_file(self, file_id: str, dest: str | Path = ".") -> Path: + """Download a workspace file, resolving its name for directory targets.""" + billing = self._billing.require(Billing.NO_COMMERCE, "Download file") + async with self._client(billing) as client: + items = await self._list_files(client) item = next((item for item in items if item.id == file_id), None) if item is None: raise FileNotFoundError(f"Workspace file not found: {file_id}") @@ -71,103 +113,120 @@ async def download_file( if destination.is_dir() or str(dest).endswith("/"): destination.mkdir(parents=True, exist_ok=True) destination /= Path(item.name).name - data = await cloud_files.download_file(client, file_id, billing=billing) - destination.write_bytes(data) - return destination - - @classmethod - async def delete_file( - cls, - file_id: str, - *, - api_key: str | None = None, - base_url: str | None = None, - billing: Billing = Billing.NO_COMMERCE, - ) -> None: - from mobilerun.clients.cloud import files as cloud_files - from mobilerun.clients.cloud.client import cloud_client + data = await self._download_file(client, file_id) + destination.write_bytes(data) + return destination - async with cloud_client(api_key, base_url, billing=billing) as client: - await cloud_files.delete_file(client, file_id, billing=billing) + async def delete_file(self, file_id: str) -> None: + """Delete a workspace file.""" + async with self._request("Delete file", Billing.NO_COMMERCE) as client: + await client.files.delete(file_id) - @classmethod async def push_file( - cls, + self, file: WorkspaceFile, - device: Device, - dest: str | None = None, + device: AsyncDevice, + device_path: str, *, - api_key: str | None = None, - base_url: str | None = None, - billing: Billing = Billing.NO_COMMERCE, - ) -> DeviceFile: - from mobilerun.clients.cloud import files as cloud_files - from mobilerun.clients.cloud.client import cloud_client - - async with cloud_client(api_key, base_url, billing=billing) as client: - data = await cloud_files.download_file(client, file.id, billing=billing) + scan_media: bool = False, + ) -> None: + """Download a workspace file and write it to a full path on the device.""" + billing = self._billing.require(Billing.NO_COMMERCE, "Download file") + async with self._client(billing) as client: + data = await self._download_file(client, file.id) + if scan_media: + await device.push_file(data, device_path, scan_media=True) + else: + await device.push_file(data, device_path) + + async def pull_file(self, device: AsyncDevice, device_path: str) -> WorkspaceFile: + """Read a device file and upload it to the workspace using its basename.""" + name = PurePosixPath(device_path).name + if ( + not name + or name == ".." + or Path(name).name != name + or device_path.endswith(("/", "/.")) + ): + raise ValueError("Pass a full device file path, including its filename") + self._billing.require(Billing.NO_COMMERCE, "Prepare file upload") + data = await device.pull_file(device_path) with TemporaryDirectory() as directory: - path = Path(directory) / Path(file.name).name + path = Path(directory) / name path.write_bytes(data) - return await device.push_file(path, dest) - - @classmethod - async def upload_app( - cls, - path: str | Path, - *, - api_key: str | None = None, - base_url: str | None = None, - billing: Billing = Billing.NO_COMMERCE, - ) -> App: - from mobilerun.clients.cloud import apps as cloud_apps - - return await cloud_apps.upload_app( - path, api_key=api_key, base_url=base_url, billing=billing - ) - - @classmethod - async def list_apps( - cls, - *, - api_key: str | None = None, - base_url: str | None = None, - billing: Billing = Billing.NO_COMMERCE, - ) -> list[App]: - from mobilerun.clients.cloud import apps as cloud_apps - from mobilerun.clients.cloud.client import cloud_client - - async with cloud_client(api_key, base_url, billing=billing) as client: - return await cloud_apps.list_apps(client, billing=billing) - - @classmethod - async def get_app( - cls, - app_id: str, - *, - api_key: str | None = None, - base_url: str | None = None, - billing: Billing = Billing.NO_COMMERCE, - ) -> App: - from mobilerun.clients.cloud import apps as cloud_apps - from mobilerun.clients.cloud.client import cloud_client - - async with cloud_client(api_key, base_url, billing=billing) as client: - result = await cloud_apps.get_app(client, app_id, billing=billing) - return App(result.data.bundle_id, "", result.data.display_name, id=app_id) - - @classmethod - async def delete_app( - cls, - app_id: str, - *, - api_key: str | None = None, - base_url: str | None = None, - billing: Billing = Billing.NO_COMMERCE, - ) -> None: + return await self.upload_file(path) + + async def upload_app(self, path: str | Path) -> App: + """Upload an APK to the account app library without connecting a device.""" + from dataclasses import replace + + from mobilerun_core import AsyncMobilerun + from mobilerun_core.errors import AppOperationError, CloudRequestError + + from mobilerun.clients.cloud.errors import CloudErrorMapper + from mobilerun.utils.network.quiet import quiet_transport_logs + + billing = self._billing.require(Billing.NO_COMMERCE, "Prepare cloud app upload") + try: + async with self._client(billing) as client, AsyncMobilerun() as core: + with quiet_transport_logs("mobilerun_sdk._base_client"): + uploaded = await core.upload_app(path, client=client) + except CloudRequestError as exc: + failure = CloudErrorMapper.from_exception(exc, "Upload cloud app") + except AppOperationError as exc: + if not isinstance(exc.__cause__, CloudRequestError): + raise + failure = CloudErrorMapper.from_exception(exc.__cause__, "Upload cloud app") + else: + return App( + replace( + uploaded.identity, + version_name=uploaded.identity.version_name or None, + ), + uploaded.name, + resource_id=uploaded.resource_id, + path=Path(path), + ) + raise failure from None + + async def list_apps(self) -> list[App]: + """List all workspace apps.""" + from mobilerun_core import AppIdentity + + apps: list[App] = [] + async with self._request("List cloud apps", Billing.NO_COMMERCE) as client: + page = 1 + while True: + result = await client.apps.list(page=page, page_size=100) + apps.extend( + App( + AppIdentity( + item.bundle_id, + item.version.version_code, + item.version.version_name or None, + ), + item.display_name, + resource_id=item.id, + ) + for item in result.items + ) + if not result.pagination.has_next: + return apps + page += 1 + + async def get_app(self, resource_id: str) -> App: + """Look up a workspace app by its resource ID.""" + from mobilerun_core import AppIdentity + + async with self._request("Retrieve cloud app", Billing.NO_COMMERCE) as client: + result = await client.apps.retrieve(resource_id) + return App( + AppIdentity(result.data.bundle_id), + result.data.display_name, + resource_id, + ) + + async def delete_app(self, resource_id: str) -> None: """Delete an uploaded app and its files/metadata, not a phone install.""" - from mobilerun.clients.cloud import apps as cloud_apps - from mobilerun.clients.cloud.client import cloud_client - - async with cloud_client(api_key, base_url, billing=billing) as client: - await cloud_apps.delete_app(client, app_id, billing=billing) + async with self._request("Delete workspace app", Billing.NO_COMMERCE) as client: + await client.apps.delete(resource_id) diff --git a/mobilerun/diagnostics/README.md b/mobilerun/diagnostics/README.md index c3bf248d7..7dda921bf 100644 --- a/mobilerun/diagnostics/README.md +++ b/mobilerun/diagnostics/README.md @@ -1,35 +1,26 @@ -# diagnostics/ +# Diagnostics -Reusable health checks and typed diagnostic results for the CLI doctor. - -**What belongs here / what doesn't:** Put reusable environment and device checks here, not CLI command wiring. - -## Contents - -| Path | Purpose | -| --- | --- | -| `__init__.py` | Package marker | -| `checks.py` | SDK, config, device, and Portal checks | -| `results.py` | Check result and status types | -| `versions.py` | SDK and Portal version helpers | - -## Quick example +Framework SDK and configuration checks, plus rendering of core's Android +`DiagnosticResult` and `PortalRelease` values. Core owns ADB and Portal probes. ```sh -mobilerun doctor +mobilerun doctor emulator-5554 +mobilerun doctor emulator-5554 --fix --yes ``` -Use `mobilerun doctor --fix` only when you want it to repair Portal installation -and accessibility settings. Cloud device use can incur charges. +The first command does not modify the device. `--fix` can install Portal, +change accessibility settings, or configure TCP. Interactive use prompts for +approval. Use `--yes` only if those changes are intended for the selected device. +Direct Portal HTTP targets get host checks only; use `device ping URL` +for a read-only HTTP reachability check. +Doctor shows the ADB executable path in debug output and distinguishes a +missing executable from an ADB server error. A working TCP forward shows +`localhost:PORT`; a missing forward warns, while a broken one fails the check. -For a typed result in Python: - -```python -from mobilerun.diagnostics.results import CheckResult, Status - -result = CheckResult(name="config", status=Status.PASS, message="Ready") -``` - -See the [CLI overview](../cli/README.md). +| File | Purpose | +| --- | --- | +| `checks.py` | Check framework version/config and format core diagnostic facts. | +| `results.py` | Status and message used by the CLI renderer. | +| `versions.py` | Look up the latest framework release and compare SDK versions. | -**Depends on / used by:** Uses shared config, clients, and device dependencies; used by the doctor command. +See [CLI overview](../cli/README.md). diff --git a/mobilerun/diagnostics/checks.py b/mobilerun/diagnostics/checks.py index f5bb805f0..111da333b 100644 --- a/mobilerun/diagnostics/checks.py +++ b/mobilerun/diagnostics/checks.py @@ -1,37 +1,20 @@ +"""Map framework and core health checks to human-readable doctor results.""" + import asyncio -import base64 -import json -import re -import shutil -from typing import Any -import httpx -from async_adbutils import AdbDevice, adb -from mobilerun_core_local.driver.android.portal import ( - PORTAL_PACKAGE_NAME, - check_portal_accessibility, - get_compatible_portal_version, - portal_content_uri, - portal_ime_id, -) -from mobilerun_core_local.transport.android.portal_client import PortalClient +from mobilerun_core import DiagnosticResult, LocalDevices, PortalError, PortalRelease -from mobilerun import __version__ -from mobilerun.clients.portal.releases import get_latest_portal_version -from mobilerun.config.loader import ConfigLoader, OutdatedConfigError -from mobilerun.config.settings import get_settings +from mobilerun.config.loader import ConfigLoader from mobilerun.diagnostics.results import CheckResult, Status -from mobilerun.diagnostics.versions import ( - get_latest_sdk_version, - parse_portal_version, - parse_version_tuple, -) +from mobilerun.diagnostics.versions import get_latest_sdk_version, parse_version_tuple +from mobilerun.errors.config import OutdatedConfigError +from mobilerun.version import __version__ -async def check_sdk_version(debug: bool) -> CheckResult: +async def check_sdk_version() -> CheckResult: """Check Mobilerun SDK version against latest GitHub release.""" current = __version__ - latest = get_latest_sdk_version() + latest = await asyncio.to_thread(get_latest_sdk_version) if latest is None: return CheckResult( @@ -55,536 +38,159 @@ async def check_sdk_version(debug: bool) -> CheckResult: return CheckResult("SDK Version", Status.PASS, f"{current} (up to date)") -async def check_config(debug: bool) -> tuple[CheckResult, Any]: - """Check config file exists and loads.""" +async def check_config() -> CheckResult: + """Check that the user configuration can be loaded.""" config_path = ConfigLoader.get_user_config_path() - - if not config_path.exists(): - # Will be created on first load - try: - config = ConfigLoader.load() - return ( - CheckResult( - "Config", - Status.PASS, - f"{config_path} (created)", - ), - config, - ) - except Exception as e: - return ( - CheckResult( - "Config", - Status.FAIL, - "failed to create default config", - detail=str(e), - ), - None, - ) - + exists = config_path.exists() try: - config = ConfigLoader.load() - return CheckResult("Config", Status.PASS, str(config_path)), config + ConfigLoader.load() except OutdatedConfigError: - return ( - CheckResult( - "Config", - Status.FAIL, - f"{config_path} (outdated, missing _version)", - detail="See: assets/examples/config_example.yaml in the mobilerun repo", - ), - None, - ) - except Exception as e: - return ( - CheckResult( - "Config", - Status.FAIL, - f"failed to load: {e}", - detail=str(config_path), - ), - None, - ) - - -async def check_adb(debug: bool) -> CheckResult: - """Check ADB is available and list devices.""" - adb_path = shutil.which("adb") - if not adb_path: return CheckResult( - "ADB", + "Config", Status.FAIL, - "adb not found in PATH", - detail="Install Android SDK Platform Tools", - ) - - try: - devices = await adb.list() - count = len(devices) - return CheckResult( - "ADB", - Status.PASS, - f"found, {count} device(s)", - detail=adb_path, - ) - except Exception as e: - return CheckResult( - "ADB", - Status.FAIL, - f"adb found but server error: {e}", - detail=adb_path, - ) - - -async def check_device( - serial: str | None, debug: bool -) -> tuple[CheckResult, AdbDevice | None]: - """Check device connection.""" - try: - device = await adb.device(serial) if serial is not None else await adb.device() - state = await device.get_state() - if state == "device": - return ( - CheckResult( - "Device", - Status.PASS, - f"{device.serial} (online)", - ), - device, - ) - else: - return ( - CheckResult( - "Device", - Status.FAIL, - f"{device.serial} (state: {state})", - ), - None, - ) - except Exception as e: - msg = str(e) - if "no devices" in msg.lower() or "not found" in msg.lower(): - return CheckResult("Device", Status.FAIL, "no device connected"), None - return CheckResult("Device", Status.FAIL, str(e)), None - - -async def check_portal_installed( - device: AdbDevice, debug: bool -) -> tuple[CheckResult, bool]: - """Check if Portal APK is installed. Returns (result, is_installed).""" - try: - packages = await device.list_packages() - if PORTAL_PACKAGE_NAME in packages: - return CheckResult("Portal", Status.PASS, "installed"), True - else: - return CheckResult("Portal", Status.FAIL, "not installed"), False - except Exception as e: - return CheckResult("Portal", Status.FAIL, f"error: {e}"), False - - -async def check_portal_version( - device: AdbDevice, debug: bool -) -> tuple[CheckResult, str | None, str | None, str | None]: - """Check portal version and compatibility. Returns (result, installed_ver, expected_ver, download_base).""" - # Get installed version - installed = None - try: - output = await device.shell( - f"content query --uri {portal_content_uri(PORTAL_PACKAGE_NAME, 'version')}" + f"{config_path} (outdated, missing _version)", + detail="See: assets/examples/config_example.yaml in the mobilerun repo", ) - if not isinstance(output, str): - raise ValueError("ADB shell returned non-text output") - if "result=" in output: - json_str = output.split("result=", 1)[1].strip() - data = json.loads(json_str) - if data.get("status") == "success": - installed = data.get("result") or data.get("data") except Exception: - pass - - if not installed: - return ( - CheckResult( - "Portal Version", - Status.WARN, - "could not read version", - ), - None, - None, - None, + message = ( + "failed to load config" if exists else "failed to create default config" ) - - # Get latest portal version from GitHub - latest_portal = get_latest_portal_version() - - # Get expected (compatible) version from version mapping - expected, download_base, mapping_fetched = get_compatible_portal_version( - __version__, debug + return CheckResult("Config", Status.FAIL, message, detail=str(config_path)) + return CheckResult( + "Config", Status.PASS, f"{config_path}" + (" (created)" if not exists else "") ) - installed_t = parse_portal_version(installed) - # Build message parts - parts = [f"v{installed}"] - - if expected: - expected_t = parse_portal_version(expected) - if installed_t != expected_t: - parts.append(f"expected {expected}") - - if latest_portal: - latest_t = parse_portal_version(latest_portal) - if installed_t < latest_t: - parts.append(f"latest: {latest_portal}") - - msg = " → ".join(parts[:1]) + ( - " (" + ", ".join(parts[1:]) + ")" if len(parts) > 1 else "" - ) - - # Determine status - if expected: - expected_t = parse_portal_version(expected) - if installed_t < expected_t: - return ( - CheckResult("Portal Version", Status.WARN, msg), - installed, - expected, - download_base, - ) - if installed_t > expected_t: - # Auto-setup keeps a newer Portal too. - return ( - CheckResult( - "Portal Version", - Status.PASS, - f"v{installed} (newer than {expected}, pinned for mobilerun {__version__})", - ), - installed, - expected, - download_base, - ) - # The pinned Portal is correct even when a newer release exists. +async def portal_version_result( + local: LocalDevices, result: DiagnosticResult +) -> tuple[CheckResult, bool]: + """Render compatibility and return whether a known older install needs repair.""" + name = result.check + installed = result.facts.get("installed") + expected = result.facts.get("compatible") + if not isinstance(installed, str): return ( - CheckResult( - "Portal Version", - Status.PASS, - f"v{installed} (pinned for mobilerun {__version__})", - ), - installed, - expected, - download_base, + CheckResult(name, Status.WARN, "could not read version", result.detail), + False, ) - - if latest_portal: - latest_t = parse_portal_version(latest_portal) - if installed_t < latest_t: - # Outdated but no specific compatible version required — warn - return ( - CheckResult( - "Portal Version", - Status.WARN, - msg, - detail="pip install --upgrade mobilerun, then mobilerun device setup", - ), - installed, - expected, - download_base, - ) - - if not mapping_fetched and not latest_portal: + current = f"v{installed}" + if result.status == "pass" and isinstance(expected, str): + newer = PortalRelease(installed, None).update_available(expected) + qualifier = f"newer than {expected}, " if newer else "" return ( CheckResult( - "Portal Version", - Status.WARN, - f"v{installed} (could not check latest)", + name, + Status.PASS, + f"{current} ({qualifier}pinned for mobilerun {__version__})", ), - installed, - None, - None, + False, ) - return ( - CheckResult( - "Portal Version", - Status.PASS, - f"v{installed} (up to date)", - ), - installed, - expected, - download_base, - ) - - -async def check_accessibility( - device: AdbDevice, debug: bool -) -> tuple[CheckResult, bool]: - """Check accessibility service. Returns (result, is_enabled).""" + pinned = isinstance(expected, str) and bool(result.facts.get("mapping_fetched")) + older = pinned and PortalRelease(expected, None).update_available(installed) is True + hints = [f"expected {expected}"] if older else [] try: - enabled = await check_portal_accessibility(device, debug=debug) - if enabled: - return CheckResult("Accessibility", Status.PASS, "enabled"), True - else: - return CheckResult("Accessibility", Status.FAIL, "not enabled"), False - except Exception as e: - return CheckResult("Accessibility", Status.FAIL, str(e)), False - - -async def check_content_provider(device: AdbDevice, debug: bool) -> CheckResult: - """Check content provider connectivity.""" - try: - state = await device.shell( - f"content query --uri {portal_content_uri(PORTAL_PACKAGE_NAME, 'state')}" + release = await local.latest_portal_release() + except PortalError: + release = None + if release is not None and release.update_available(installed): + hints.append(f"latest: {release.version}") + if hints: + detail = ( + "" + if older + else "pip install --upgrade mobilerun, then mobilerun device setup" ) - if not isinstance(state, str): - raise ValueError("ADB shell returned non-text output") - if "Row: 0 result=" in state: - return CheckResult("Content Provider", Status.PASS, "reachable") - else: - return CheckResult( - "Content Provider", - Status.FAIL, - "invalid response", - detail=state[:100] if debug else "", - ) - except Exception as e: - return CheckResult("Content Provider", Status.FAIL, f"unreachable: {e}") - - -class ForwardedPortal: - """Probe the pinged forward directly, without ADB repair or fallback.""" - - def __init__(self, port: int, headers: dict[str, str]): - self.url = f"http://localhost:{port}" - self.headers = headers - - async def _get(self, path: str) -> httpx.Response: - async with httpx.AsyncClient() as client: - response = await client.get( - self.url + path, headers=self.headers, timeout=10 - ) - response.raise_for_status() - return response - - async def get_state(self) -> dict: - data = (await self._get("/state_full")).json() - if data.get("status") == "error": - raise ValueError("Portal state request failed") - state = data.get("result", data.get("data", data)) - return json.loads(state) if isinstance(state, str) else state - - async def take_screenshot(self, *, hide_overlay: bool) -> bytes: - response = await self._get( - "/screenshot" if hide_overlay else "/screenshot?hideOverlay=false" + return ( + CheckResult(name, Status.WARN, f"{current} ({', '.join(hints)})", detail), + older, ) - if response.headers.get("content-type", "").startswith( - "image/" - ) or response.content.startswith(b"\x89PNG"): - return response.content - data = response.json() - if data.get("status") == "error": - raise ValueError("Portal screenshot request failed") - return base64.b64decode(data.get("result", data.get("data"))) - - -class ReadyTcp(CheckResult): - """Successful ping and the exact endpoint to use for subsequent checks.""" + if release is not None and release.update_available(installed) is False: + return CheckResult(name, Status.PASS, f"{current} (up to date)"), False + return CheckResult(name, Status.WARN, f"{current} (could not check latest)"), False - def __init__(self, port: int, headers: dict[str, str], detail: str): - super().__init__("TCP Mode", Status.PASS, f"localhost:{port}", detail) - self.portal = ForwardedPortal(port, headers) - -async def check_tcp( - device: AdbDevice, debug: bool, *, fix: bool = False -) -> CheckResult: - """Check existing TCP wiring; configure server/forwarding only with fix.""" - - steps = [] - - # Step 1: Enable socket server via content provider - if fix: - try: - toggle_uri = portal_content_uri(PORTAL_PACKAGE_NAME, "toggle_socket_server") - await device.shell( - f"content insert --uri {toggle_uri} --bind enabled:b:true" - ) - steps.append("server enabled") - except Exception as e: - return CheckResult( - "TCP Mode", Status.FAIL, "failed to enable socket server", detail=str(e) - ) - await asyncio.sleep(1) - - # Step 2: Fetch auth token via content provider - auth_headers: dict[str, str] = {} - try: - portal = PortalClient(device, prefer_tcp=False) - token = await portal._fetch_auth_token() - if token: - auth_headers["Authorization"] = f"Bearer {token}" - steps.append("auth token ok") - else: - steps.append("no auth token") - except Exception as e: - steps.append(f"auth token failed: {e}") - - # Step 3: Set up port forward - local_port = None - try: - # Check for existing forward first - forwards = [] - async for fwd in device.forward_list(): - forwards.append(fwd) - for fwd in forwards: - if ( - fwd.serial == device.serial - and fwd.remote == f"tcp:{get_settings().MOBILERUN_PORTAL_REMOTE_PORT}" - ): - match = re.search(r"tcp:(\d+)", fwd.local) - if match: - local_port = int(match.group(1)) - steps.append(f"reusing forward :{local_port}") - break - - if local_port is None: - if not fix: - return CheckResult( - "TCP Mode", - Status.WARN, - "no existing port forward; use doctor --fix to configure TCP", - ) - local_port = await device.forward_port( - get_settings().MOBILERUN_PORTAL_REMOTE_PORT - ) - steps.append(f"forwarded :{local_port}") - except Exception as e: - return CheckResult( - "TCP Mode", - Status.FAIL, - "port forward failed", - detail=str(e), - ) - - # Step 4: Test connection with auth - try: - async with httpx.AsyncClient() as client: - resp = await client.get( - f"http://localhost:{local_port}/ping", - headers=auth_headers, - timeout=5, +def device_result(result: DiagnosticResult, serial: str | None) -> CheckResult: + """Translate sanitized core facts without using ADB or HTTP directly.""" + name, status, facts, detail = ( + result.check, + Status(result.status), + result.facts, + result.detail, + ) + passed = status is Status.PASS + if name == "ADB": + path = facts.get("executable_path") + detail = path if isinstance(path, str) else "" + if passed: + message = f"found, {facts.get('count', 0)} device(s)" + elif facts.get("failure") == "missing_executable": + message, detail = ( + "adb not found in PATH", + "Install Android SDK Platform Tools", ) - if resp.status_code == 200: - steps.append("ping ok") - return ReadyTcp(local_port, auth_headers, ", ".join(steps)) - else: - return CheckResult( - "TCP Mode", - Status.FAIL, - f"ping returned {resp.status_code}", - detail=", ".join(steps), - ) - except Exception as e: - return CheckResult( - "TCP Mode", - Status.FAIL, - f"ping failed: {e}", - detail=", ".join(steps), - ) - - -async def check_portal_state( - device: AdbDevice, debug: bool, *, tcp_portal: ForwardedPortal | None = None -) -> tuple[CheckResult, Any]: - """Fetch full state and verify a11y_tree, phone_state, device_context are present.""" - try: - portal: PortalClient | ForwardedPortal - if tcp_portal is None: - portal = PortalClient(device, prefer_tcp=False) - await portal.connect() - method = "content_provider" else: - portal = tcp_portal - method = "tcp" - - state = await portal.get_state() - - if isinstance(state, dict) and state.get("error"): - return ( - CheckResult( - "Portal State", - Status.FAIL, - f"error: {state.get('message', state.get('error'))}", - ), - portal, - ) - - required = ("a11y_tree", "phone_state", "device_context") - present = [k for k in required if k in state] - missing = [k for k in required if k not in state] - - if missing: - return ( - CheckResult( - "Portal State", - Status.FAIL, - f"missing: {', '.join(missing)}", - detail=f"present: {', '.join(present)} (via {method})", - ), - portal, - ) + message = "adb found but server error" + elif name == "Device": + state = facts.get("state") + if passed: + message = f"{serial} (online)" + elif state in ("unauthorized", "offline"): + message = f"{serial} (state: {state})" else: - return ( - CheckResult( - "Portal State", - Status.PASS, - f"a11y_tree, phone_state, device_context (via {method})", - ), - portal, - ) - except Exception as e: - return CheckResult("Portal State", Status.FAIL, str(e)), None - - -async def check_screenshot(portal: Any, debug: bool) -> CheckResult: - """Take a test screenshot to verify the full capture pipeline.""" - try: - data = await portal.take_screenshot(hide_overlay=True) - if data and len(data) > 0: - size_kb = len(data) / 1024 - return CheckResult( - "Screenshot", - Status.PASS, - f"ok ({size_kb:.0f} KB)", - ) + message = "no device connected" + elif name == "Portal Installed": + name = "Portal" + message = ( + "installed" + if passed + else ("could not check installation" if detail else "not installed") + ) + elif name == "Accessibility": + message = "enabled" if passed else "not enabled" + elif name == "Content Provider": + message = "reachable" if passed else "invalid response" + elif name == "TCP Mode": + port = facts.get("forward_port") + failure = facts.get("failure") + detail = "" + if passed: + message = f"localhost:{port}" if isinstance(port, int) else "reachable" + elif failure == "no_forward" and status is Status.WARN: + message = "no existing port forward; use doctor --fix to configure TCP" + elif failure == "bad_status": + status = Status.FAIL + http_status = facts.get("http_status") + message = ( + f"ping returned {http_status}" + if isinstance(http_status, int) + else "ping returned an unexpected status" + ) + elif failure == "unreachable": + status = Status.FAIL + message = "ping failed" else: - return CheckResult( - "Screenshot", - Status.FAIL, - "empty response", - ) - except Exception as e: - return CheckResult( - "Screenshot", - Status.FAIL, - f"capture failed: {e}", - ) - - -async def check_keyboard(device: AdbDevice, debug: bool) -> CheckResult: - """Check if Mobilerun keyboard IME is available.""" - try: - output = await device.shell("ime list -s") - if not isinstance(output, str): - raise ValueError("ADB shell returned non-text output") - ime_id = portal_ime_id(PORTAL_PACKAGE_NAME) - if ime_id in output: - return CheckResult("Keyboard", Status.PASS, "available") + message = "could not configure or reach TCP" + elif name.startswith("State ("): + method = "tcp" if name == "State (tcp)" else "content_provider" + missing = facts.get("missing_keys", ()) + if passed: + message = f"a11y_tree, phone_state, device_context (via {method})" + elif missing: + message = f"missing: {', '.join(missing)}" else: - return CheckResult( - "Keyboard", - Status.WARN, - "not listed", - detail="Will be set up automatically when needed", - ) - except Exception as e: - return CheckResult("Keyboard", Status.WARN, f"could not check: {e}") + message = "invalid response" + elif name.startswith("Screenshot ("): + size = facts.get("bytes", 0) + message = f"ok ({size / 1024:.0f} KB)" if passed else "capture failed" + elif name == "Keyboard": + message = ( + "available" + if passed + else ("could not check keyboard" if detail else "not listed") + ) + if not passed and not detail: + detail = "Will be set up automatically when needed" + else: + message = result.status + return CheckResult(name, status, message, detail) diff --git a/mobilerun/diagnostics/versions.py b/mobilerun/diagnostics/versions.py index 9847fb4ca..60423ee39 100644 --- a/mobilerun/diagnostics/versions.py +++ b/mobilerun/diagnostics/versions.py @@ -1,8 +1,6 @@ -import re from typing import TypeAlias import requests -from mobilerun_core_local.driver.android.portal import GITHUB_API_HOSTS VersionTuple: TypeAlias = tuple[int, ...] @@ -19,30 +17,16 @@ def parse_version_tuple(version_str: str) -> VersionTuple: return tuple(parts) -def parse_portal_version(version_str: str) -> VersionTuple: - """Like parse_version_tuple, but '0.7.26-dev' reads as 0.7.26.""" - cleaned = version_str.lstrip("v").strip() - parts = [] - for p in cleaned.split("."): - match = re.match(r"\d+", p) - parts.append(int(match.group()) if match else 0) - return tuple(parts) - - def get_latest_sdk_version() -> str | None: - for host in GITHUB_API_HOSTS: - try: - url = f"{host}/repos/droidrun/mobilerun/releases/latest" - resp = requests.get(url, timeout=10) - if resp.status_code == 200: - data = resp.json() - if "release" in data: - tag = data["release"].get( - "tag", data["release"].get("tag_name", "") - ) - else: - tag = data.get("tag_name", "") - return tag.lstrip("v") - except Exception: - continue - return None + """Return the latest framework GitHub release tag, if available.""" + try: + response = requests.get( + "https://api.github.com/repos/droidrun/mobilerun/releases/latest", + timeout=10, + ) + response.raise_for_status() + data = response.json() + tag = data.get("tag_name") if isinstance(data, dict) else None + return tag.removeprefix("v") if isinstance(tag, str) and tag else None + except (requests.RequestException, ValueError): + return None diff --git a/mobilerun/errors/README.md b/mobilerun/errors/README.md index 8b5145be7..29cb5c37c 100644 --- a/mobilerun/errors/README.md +++ b/mobilerun/errors/README.md @@ -1,8 +1,8 @@ # errors/ -Core's errors. Feature packages keep their own errors inside their folder. - -Shared exception types for device, cloud, credentials, and other framework failures. +Shared exceptions for account resources, credentials, operators, and other +framework failures. Feature packages keep their own errors. Catch native phone +failures such as `UnsupportedOperation` from `mobilerun_core.errors`. **What belongs here / what doesn't:** Put reusable error definitions here, not recovery workflows or CLI output. @@ -12,22 +12,23 @@ Shared exception types for device, cloud, credentials, and other framework failu | --- | --- | | `__init__.py`, `base.py` | Public exports and shared error hierarchy | | `cloud.py` | Cloud API, authentication, billing and proxy failures | +| `config.py` | Config loading and schema failures | | `credentials.py` | Credential lookup, file and policy failures | -| `device.py` | Device authentication, selection, Portal and state failures | -| `operators.py` | Operator, extension, expectation and placeholder failures | +| `device.py` | OAuth device-flow login errors (account authentication) | +| `operators.py` | Operator, extension and expectation failures | +| `operator_plugins.py`, `tools.py` | Operator plugin and tool failures | ## Quick example ```python -from mobilerun.errors import CloudError, CredentialError, DeviceError, MobilerunError +from mobilerun_core import AsyncDevice +from mobilerun_core.errors import UnsupportedOperation -def run_safely(operation): +async def read_locale(phone: AsyncDevice) -> str | None: try: - return operation() - except (CloudError, CredentialError, DeviceError) as exc: - print(f"Operation failed: {type(exc).__name__}") - except MobilerunError as exc: - print(f"Other Mobilerun error: {type(exc).__name__}") + return await phone.get_locale() + except UnsupportedOperation: + return None ``` See [diagnostics](../diagnostics/README.md). @@ -43,18 +44,13 @@ operation labels, validated HTTP status codes and support request IDs. Raw `status`, `detail` and other diagnostic attributes remain available for inspection; they are not arbitrary message text. Do not put credentials in reference fields. -Legacy positional messages remain accepted for compatibility, but set instance -`value_safe=False`. An extension action wraps them instead of passing their text -through. Use `code` for the supported fixed remediation templates. - -When an action propagates a safe typed error, it retains the same error object and -attributes but removes implicit contexts and unsafe explicit causes. Only acyclic, -value-safe explicit causes remain. This applies at INFO and DEBUG, including -sensitive and nested action scopes. All notes are removed from every retained -exception: free-text notes do not inherit the error's safety classification. +Positional messages set instance `value_safe=False`. Use `code` for the +supported fixed remediation templates. An extension tool failure reports the +tool name without carrying a provider error message or cause. Direct service +calls do not pass through the tool boundary. Stock cloud errors render a private, write-once message rather than mutable -`.args`. The action boundary revalidates rendering and rejects changed `.args`. +`.args`. `is_value_safe` revalidates rendering and rejects changed `.args`. Every unaudited class in a cloud error's MRO must contain only plain constants (strings, numbers, booleans, `None`, or recursively constant tuples/frozensets) and standard class bookkeeping. Methods and descriptors are rejected by default, @@ -66,7 +62,3 @@ Classes with additional behavior must each deliberately declare behavior, and a child opt-in does not audit an unsafe parent or mixin. Even opted-in subclasses must render the stored message exactly. This is an explicit author promise, not an automatic audit of custom code. -Rejected rendering contracts are wrapped without a cause, including at DEBUG. - -Direct client calls outside an action retain -their original transport chains for diagnostics. diff --git a/mobilerun/errors/__init__.py b/mobilerun/errors/__init__.py index 18bda3b0b..5d4dde9a8 100644 --- a/mobilerun/errors/__init__.py +++ b/mobilerun/errors/__init__.py @@ -29,7 +29,6 @@ InvalidAPIKeyError, InvalidCloudDeviceId, PaymentRequired, - ProxyNotActive, PurchaseInProgress, ) from .credentials import ( @@ -37,40 +36,20 @@ CredentialFormatError, CredentialNotFoundError, CredentialReadError, - LocalCredentialsNotAllowed, -) -from .device import ( - DeviceAuthError, - DeviceNotFound, - DeviceNotReady, - DeviceOperationNotSupported, - NoFocusedInput, - PortalApkNotFound, - PortalInstallFailed, - StateFetchFailed, - UnsupportedStateCapability, ) +from .device import DeviceAuthError from .operators import ( ExpectationFailed, ExpectationInconclusive, - ExtensionActionError, ExtensionClosed, - ExtensionConflict, - ExtensionNotBound, ExtensionNotSupported, OperatorNotAvailable, OperatorNotSupported, - PlaceholderError, - UnmanagedProxyConflict, ) __all__ = [ - "ExtensionActionError", "ExtensionClosed", - "ExtensionConflict", - "ExtensionNotBound", "ExtensionNotSupported", - "UnmanagedProxyConflict", "MobilerunError", "AgentError", "CloudError", @@ -82,7 +61,6 @@ "BillingRequired", "IncludedCapacityUnavailable", "PaymentRequired", - "ProxyNotActive", "CloudAuthenticationError", "CloudConflict", "CloudConnectionError", @@ -96,26 +74,16 @@ "CredentialNotFoundError", "CredentialFieldNotFound", "PurchaseInProgress", - "NoFocusedInput", "CredentialFormatError", - "DeviceNotReady", - "PlaceholderError", "CloudAPIError", "CloudAuthRequired", "CloudDeviceNotFound", "CloudTaskTimeout", "DeviceAuthError", - "DeviceNotFound", - "DeviceOperationNotSupported", "ExpectationFailed", "ExpectationInconclusive", "InvalidAPIKeyError", "InvalidCloudDeviceId", - "LocalCredentialsNotAllowed", "OperatorNotAvailable", "OperatorNotSupported", - "PortalApkNotFound", - "PortalInstallFailed", - "StateFetchFailed", - "UnsupportedStateCapability", ] diff --git a/mobilerun/errors/base.py b/mobilerun/errors/base.py index 01389d99e..31a86d719 100644 --- a/mobilerun/errors/base.py +++ b/mobilerun/errors/base.py @@ -59,7 +59,6 @@ "List SMS messages", "List cloud apps", "List cloud phones", - "List device files", "List files", "List mailboxes", "List number countries", @@ -148,7 +147,6 @@ "list_webhooks", "register_webhook", "delete_webhook", - "list_device_files", "list_devices", "list_files", "list_installs", diff --git a/mobilerun/errors/cloud.py b/mobilerun/errors/cloud.py index 8c7213057..275652e58 100644 --- a/mobilerun/errors/cloud.py +++ b/mobilerun/errors/cloud.py @@ -47,6 +47,14 @@ class NumberNotCancellable(CloudConflict): ) +class NumberAttachmentConflict(CloudConflict): + """The target cloud phone already has a different number.""" + + _hint: ClassVar[str] = ( + "This cloud phone already has a number; detach it or pass replace=True." + ) + + class CloudValidationError(CloudAPIError): """The cloud rejected invalid parameters.""" @@ -62,7 +70,7 @@ class CloudRateLimited(CloudAPIError): class CloudServiceUnavailable(CloudAPIError): """The cloud service is temporarily unavailable.""" - _hint: ClassVar[str] = "Retry later or contact support with the request id." + _hint: ClassVar[str] = "Retry later or contact support." class CloudConnectionError(CloudAPIError): @@ -187,7 +195,3 @@ def __init__(self, resource_id: str, checkout: Checkout | None) -> None: code="purchase_in_progress", resource_id=resource_id, ) - - -class ProxyNotActive(CloudError): - """The cloud phone has no active proxy after a switch.""" diff --git a/mobilerun/errors/config.py b/mobilerun/errors/config.py new file mode 100644 index 000000000..f04abe7d6 --- /dev/null +++ b/mobilerun/errors/config.py @@ -0,0 +1,7 @@ +"""Configuration-file errors.""" + +from .base import ConfigError + + +class OutdatedConfigError(ConfigError): + """Raised when user config is unreadable or invalid.""" diff --git a/mobilerun/errors/credentials.py b/mobilerun/errors/credentials.py index a1552e597..bc4f2c947 100644 --- a/mobilerun/errors/credentials.py +++ b/mobilerun/errors/credentials.py @@ -13,13 +13,13 @@ class CredentialFieldNotFound(CredentialNotFoundError): """Raised when a requested credential field cannot be found.""" +class CredentialDeviceRequired(CredentialError): + """Protected typing requires an explicit device on the credential provider.""" + + class CredentialReadError(CredentialError): """A credential file cannot be read.""" class CredentialFormatError(CredentialError, ValueError): """A credential file is malformed.""" - - -class LocalCredentialsNotAllowed(CredentialError, ValueError): - """A public cloud task was given a local credential provider.""" diff --git a/mobilerun/errors/device.py b/mobilerun/errors/device.py index 2d82ce73f..992c1c2cc 100644 --- a/mobilerun/errors/device.py +++ b/mobilerun/errors/device.py @@ -1,4 +1,4 @@ -"""Device, Portal, and state errors.""" +"""OAuth device-flow login errors.""" from mobilerun.errors.base import DeviceError @@ -10,47 +10,3 @@ def __init__(self, code: str, description: str = "") -> None: self.code = code self.description = description super().__init__(f"{code}: {description}" if description else code) - - -class DeviceNotFound(DeviceError, RuntimeError): - """The requested Android device could not be obtained.""" - - -class DeviceNotReady(DeviceError, RuntimeError): - pass - - -class DeviceOperationNotSupported(DeviceError, RuntimeError): - """The selected device cannot perform the requested operation.""" - - value_safe = True - - -class NoFocusedInput(DeviceError): - """No editable text field is focused.""" - - value_safe = True - - -class PortalApkNotFound(DeviceError, FileNotFoundError): - """A requested Portal APK does not exist.""" - - -class PortalInstallFailed(DeviceError, RuntimeError): - """Installing the Portal APK failed.""" - - def __init__(self, message: str, *, apk_path: str | None = None) -> None: - self.apk_path = apk_path - super().__init__(message) - - -class UnsupportedStateCapability(DeviceError, RuntimeError): - def __init__(self, provider: object, capability: str) -> None: - provider_name = type(provider).__name__ - super().__init__( - f"State provider {provider_name} does not support capability '{capability}'" - ) - - -class StateFetchFailed(DeviceError): - """Fetching device state failed after all retry attempts.""" diff --git a/mobilerun/errors/operator_plugins.py b/mobilerun/errors/operator_plugins.py new file mode 100644 index 000000000..67aa2795e --- /dev/null +++ b/mobilerun/errors/operator_plugins.py @@ -0,0 +1,7 @@ +"""Errors raised when resolving installed operator plugins.""" + +from mobilerun.errors.base import OperatorError + + +class OperatorPluginError(OperatorError): + """An operator entry point is missing, broken, or invalid.""" diff --git a/mobilerun/errors/operators.py b/mobilerun/errors/operators.py index bf6c4ec56..9ec689fe9 100644 --- a/mobilerun/errors/operators.py +++ b/mobilerun/errors/operators.py @@ -1,6 +1,6 @@ """Operator, extension, and expectation errors.""" -from mobilerun.errors.base import CredentialError, DeviceError, OperatorError +from mobilerun.errors.base import DeviceError, OperatorError from mobilerun.models.results import ( ExecutionResult, ExpectationResult, @@ -8,38 +8,12 @@ ) -class ExtensionConflict(DeviceError): - """A name or exclusive binding is already occupied.""" - - value_safe = True - - -class UnmanagedProxyConflict(ExtensionConflict): - """An active unmanaged cloud proxy requires explicit replacement.""" - - class ExtensionNotSupported(DeviceError): """Declared device facts do not satisfy an extension.""" value_safe = True -class ExtensionNotBound(DeviceError): - """The extension is detached, closing, or uncertain.""" - - value_safe = True - - -class ExtensionActionError(DeviceError): - """An action failed without exposing arguments or provider responses.""" - - value_safe = True - - def __init__(self, message: str, *, cause_type: str = "") -> None: - super().__init__(message) - self.cause_type = cause_type - - class ExtensionClosed(DeviceError): """The extension is shutting down or has already released its resource.""" @@ -71,7 +45,3 @@ def __init__( super().__init__( "Could not determine whether the expectation holds: no structured verdict" ) - - -class PlaceholderError(CredentialError, ValueError): - pass diff --git a/mobilerun/errors/tools.py b/mobilerun/errors/tools.py new file mode 100644 index 000000000..872ee34df --- /dev/null +++ b/mobilerun/errors/tools.py @@ -0,0 +1,21 @@ +"""Safe errors at the extension tool boundary.""" + +from mobilerun.errors.base import OperatorError + + +class ToolCompilationError(OperatorError): + """An invalid declaration, expansion, or duplicate tool name.""" + + value_safe = True + + +class ToolArgumentsError(OperatorError): + """A tool was not called because its inputs failed validation.""" + + value_safe = True + + +class ToolInvocationError(OperatorError): + """A tool call failed or returned an invalid result; do not retry blindly.""" + + value_safe = True diff --git a/mobilerun/logs/README.md b/mobilerun/logs/README.md index 303337d93..5de37e390 100644 --- a/mobilerun/logs/README.md +++ b/mobilerun/logs/README.md @@ -9,7 +9,7 @@ Shared logging handlers, action logging, and progress output. | Path | Purpose | | --- | --- | | `__init__.py` | Package marker | -| `actions.py` | Action logging helpers | +| `actions.py` | Safe summaries for core hooks, recorded rows and cloud task progress | | `handlers.py` | Logging setup and CLI/TUI handlers | | `progress.py` | Progress output to stderr | @@ -24,6 +24,31 @@ configure_logging(debug=True, handler=CLILogHandler()) This replaces handlers on the `mobilerun` logger and sets its level to DEBUG. See [configuration](../config/README.md) and [CLI commands](../cli/README.md). +A core `AsyncDevice` does not log its actions by default. Use the formatter +with a hook, or with a schema-2 recording's `step.action` and `step.args`: + +```python +import logging + +from mobilerun_core import ActionEvent, AsyncDevice + +from mobilerun.logs.actions import format_action + +async def report(_phone: AsyncDevice, event: ActionEvent) -> None: + summary = format_action(event.name, event.arguments) + if summary is not None: + logging.getLogger("mobilerun.actions").info("%s", summary) + +async def tap_with_logging(phone: AsyncDevice) -> None: + async with phone.use_action_hooks(after=report): + await phone.tap(10, 20) # tap (10, 20) +``` + +Both `type` and `type_secret` render as `type `. The formatter +never prints hook results, exceptions, element contents or extension arguments. +Core allows one hook pair per phone; use a single hook scope, not a second +installer alongside an active [recording](../core/runs/README.md). + Agent logging supports `quiet`, `normal` (default), `verbose`, and `debug`. Set `logging.level` in the configuration file or `MOBILERUN_LOG_LEVEL` in the environment. For `agent run`, `--quiet`, `--verbose`, `--debug`, and diff --git a/mobilerun/logs/actions.py b/mobilerun/logs/actions.py index 68ec89aef..3d8b7ca24 100644 --- a/mobilerun/logs/actions.py +++ b/mobilerun/logs/actions.py @@ -1,163 +1,91 @@ -"""Safe, concise summaries of agent device actions.""" - -from __future__ import annotations +"""Value-safe summaries of device actions and cloud task progress.""" import json import logging -import re -from collections.abc import Iterator -from contextlib import contextmanager -from contextvars import ContextVar -from dataclasses import dataclass -from typing import Any, Protocol +from collections.abc import Mapping from mobilerun.logs.handlers import VERBOSE - -class ActionUI(Protocol): - def get_element(self, index: int) -> dict[str, Any] | None: ... - - -class ActionState(Protocol): - @property - def step_number(self) -> int: ... - - -class ActionDevice(Protocol): - @property - def identifier(self) -> str | None: ... - - -class ActionContext(Protocol): - @property - def driver(self) -> ActionDevice: ... - - @property - def ui(self) -> ActionUI | None: ... - - @property - def shared_state(self) -> ActionState: ... - - logger = logging.getLogger("mobilerun.actions") - -@dataclass -class ActionCounter: - count: int = 0 - - -_action_counter: ContextVar[ActionCounter | None] = ContextVar( - "action_counter", default=None -) - - -@contextmanager -def action_counting() -> Iterator[ActionCounter]: - """Track action numbering independently for each asynchronous agent run.""" - counter = ActionCounter() - token = _action_counter.set(counter) - try: - yield counter - finally: - _action_counter.reset(token) - - +_TYPING_SUMMARY = "type " _ACTIONS = { + "tap": "tap", + "tap_element": "tap element", + "swipe": "swipe", + "drag": "drag", + "type": _TYPING_SUMMARY, + "type_secret": _TYPING_SUMMARY, + "key": "button", + "wait": "wait", + "start_app": "open app", + "stop_app": "stop app", + "install_app": "install app", + "uninstall_app": "uninstall app", + "open_deep_link": "open deep link", + "push_file": "push file", + "delete_file": "delete file", + "set_location": "set location", + "reset_location": "reset location", + "set_timezone": "set timezone", + "set_locale": "set locale", + "set_clipboard": "set clipboard ", + "set_proxy": "set proxy", + "clear_proxy": "clear proxy", + "recover_portal": "recover Portal", + "disable_portal_keyboard": "disable Portal keyboard", + "extension_call": "extension call", +} + +# The task service emits agent tool names, not just native device verbs. +_TASK_ALIASES = { "click": "tap", "click_at": "tap", "click_area": "tap", - "tap": "tap", - "long_press": "long press", - "long_press_at": "long press", - "swipe": "swipe", - "system_button": "button", - "press_button": "button", + "system_button": "key", + "press_button": "key", "type_text": "type", "type_text_direct": "type", - "type_secret": "type", "input_text": "type", - "open_app": "open app", - "open_bundle_id": "open app", - "start_app": "open app", - "wait": "wait", + "open_app": "start_app", + "open_bundle_id": "start_app", +} +_TASK_ONLY_ACTIONS = { + "long_press": "long press", + "long_press_at": "long press", "complete": "done", } +_SENSITIVE_FIELDS = {"text", "password", "secret", "token", "credential"} -def format_action(name: str, args: object, ui: ActionUI | None = None) -> str | None: - verb = _ACTIONS.get(name) - if verb is None: - return None - args = args if isinstance(args, dict) else {} - parts = [verb] - index = args.get("index") - if type(index) is int: - element = ui.get_element(index) if ui is not None else None - if isinstance(element, dict): - class_name = element.get("className") - resource_id = element.get("resourceId") - class_name = ( - class_name.rsplit(".", 1)[-1] if isinstance(class_name, str) else "" - ) - resource_id = ( - resource_id.rsplit("/", 1)[-1] if isinstance(resource_id, str) else "" - ) - if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]{0,63}", class_name): - class_name = "" - if not re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]{0,63}", resource_id): - resource_id = "" - target = class_name + (f"[{resource_id}]" if resource_id else "") - if target: - parts.append(target) - parts.append(f"#{index}") - elif all(type(args.get(k)) in (int, float) for k in ("x", "y")): - parts.append(f"({args['x']}, {args['y']})") - elif ( - isinstance(args.get("coordinate"), list) - and len(args["coordinate"]) == 2 - and all(type(v) in (int, float) for v in args["coordinate"]) - ): - parts.append(f"({args['coordinate'][0]}, {args['coordinate'][1]})") - if verb == "type" or any( - k in args for k in ("text", "password", "secret", "token", "credential") - ): - parts.append("") - if verb == "button" and args.get("button") in ("home", "back", "enter"): - parts.append(args["button"]) - return " ".join(parts) +def _point(x: object, y: object) -> str | None: + if type(x) in (int, float) and type(y) in (int, float): + return f"({x}, {y})" + return None -def action_line(device: object, source: str, step: int, action: str) -> str: - label = str(device or "unknown") +def format_action(name: str, args: Mapping[str, object]) -> str | None: + """Summarize a core hook or recording row without rendering opaque values.""" + summary = _ACTIONS.get(name) + if name == "tap": + point = _point(args.get("x"), args.get("y")) + if point is not None: + return f"tap {point}" + if name == "key": + key = args.get("name_or_code") + if type(key) is str and key in ("home", "back", "enter"): + return f"button {key}" + return summary + + +def action_line(device: str | None, source: str, step: int, action: str) -> str: + """Format a line from a safe device label and preformatted action summary.""" + label = device or "unknown" if source == "agent" and not logger.isEnabledFor(VERBOSE): return f"{label} · step {step} {action}" return f"{label:<13} · {source:<5} · step {step} {action}" -def agent_line(ctx: ActionContext | None, name: str, args: object) -> str | None: - # Older callers may provide a partial context instead of an ActionContext. - try: - driver = ctx.driver if ctx is not None else None - except AttributeError: - driver = None - label = driver.identifier if driver is not None else None - try: - step = (ctx.shared_state.step_number if ctx is not None else 0) or 1 - except AttributeError: - step = 1 - try: - ui = ctx.ui if ctx is not None else None - except AttributeError: - ui = None - action = format_action(name, args, ui) - counter = _action_counter.get() - if action and name != "complete" and counter is not None: - counter.count += 1 - step = counter.count - return action_line(label, "agent", step, action) if action else None - - def cloud_progress(data: str | bytes | bytearray) -> tuple[str, int | None] | None: """Return a safe action summary and step, or None for non-action events.""" try: @@ -171,8 +99,30 @@ def cloud_progress(data: str | bytes | bytearray) -> tuple[str, int | None] | No if isinstance(action, dict): args = action.get("args", action.get("parameters", args)) action = action.get("name", action.get("type")) - summary = format_action(action, args) if isinstance(action, str) else None - step = payload.get("step_number", payload.get("step")) - return ( - (summary, step if type(step) is int and step > 0 else None) if summary else None + if not isinstance(action, str): + return None + args = args if isinstance(args, dict) else {} + name = _TASK_ALIASES.get(action, action) + summary = _TASK_ONLY_ACTIONS.get(name) or format_action( + name, + ( + {"name_or_code": args.get("button")} + if name == "key" and action != "key" + else args + ), ) + if summary is None: + return None + if name in {"tap", "long_press", "long_press_at"}: + index, coordinate = args.get("index"), args.get("coordinate") + target = ( + f"#{index}" if type(index) is int else _point(args.get("x"), args.get("y")) + ) + if target is None and isinstance(coordinate, list) and len(coordinate) == 2: + target = _point(*coordinate) + if target is not None: + summary = f"{_TASK_ONLY_ACTIONS.get(name, 'tap')} {target}" + if _SENSITIVE_FIELDS.intersection(args) and not summary.endswith(""): + summary += " " + step = payload.get("step_number", payload.get("step")) + return summary, step if type(step) is int and step > 0 else None diff --git a/mobilerun/macro/README.md b/mobilerun/macro/README.md index 21d37516c..396ddb982 100644 --- a/mobilerun/macro/README.md +++ b/mobilerun/macro/README.md @@ -1,27 +1,42 @@ # Macros +`__main__.py` invokes the macro CLI for `python -m mobilerun.macro`. + Build a replayable macro from a device [run](../core/runs/README.md). Each -successful selected action becomes a JSONL row with its original step ID, -arguments, and any before/after screen guards. Failed actions and actions -with masked arguments are omitted. Run timestamps, actors, errors, and -screenshots are not part of the macro. +successful selected action becomes a JSONL row stamped `schema_version: 2`, +with its original step ID, core arguments, the time the action was recorded +(`started_at`), and any before/after screen guards. The timestamp is for +reading only: replay ignores it and keeps its own delay. Finish times, actors, +results, errors, and evidence files are not part of the macro. Failed actions and successful actions outside the replay vocabulary are +omitted; unknown actions in saved macros still fail replay validation. +Opaque/redacted actions are omitted, except a bare secret +mask is retained so replay cannot silently skip the credential entry. Review +omissions before replaying a routine. Build with `step_ids=` to select only the +actions you intend to replay. ```python from pathlib import Path -from mobilerun.macro import MacroPlayer, build_macro, load_macro +from mobilerun_core import AsyncDevice + +from mobilerun.macro import MacroOperator, build_macro path = build_macro(Path("/path/to/run/steps.jsonl"), "open-settings") -async def replay(device): - player = MacroPlayer(device) - await player.replay_macro(load_macro(path)) +async def replay(device: AsyncDevice): + return await MacroOperator().do(device, str(path)) ``` Names and directories load the latest numeric version. Pass an exact file to pin a version. For example, `open-settings` can load `v10.jsonl` while `macros/open-settings/v9.jsonl` still pins version 9. Publishing never replaces -an existing version. Legacy v2 `macro.json` files are not supported. +an existing version. Unstamped JSONL runs and macros from the previous release +still load. Portable actions are translated in memory without rewriting the +files. Older `macro.json` recordings still require re-recording. + +```json +{"schema_version":2,"i":3,"action":"swipe","args":{"x1":10,"y1":20,"x2":90,"y2":20,"ms":300}} +``` By default the macro store is `/macros`. Set `MOBILERUN_MACRO_DIRECTORY` to change it, or use `mobilerun macro path` to @@ -33,18 +48,34 @@ corresponding `MOBILERUN_MACRO_*` settings. The player uses recorded coordinates, even if an element moves. It does not open, wrap, or close the device. A step with no guard skips that check; a present guard requires screen evidence. `MacroMismatch` identifies the -original row and failing phase (`before`, `action`, or `after`). A mismatch -during masked credential replay stops without handing off the device. +original row and failing phase (`before`, `action`, or `after`). If credential +masks are active or the player or its recorder has seen sensitive input, replay +raises `MacroHandoffRefused` instead. This `MacroError` carries only the +original `step_index` and `phase`, not the row or observed screen. + +Replay validates the entire file, including rows outside the requested slice, +before observing or acting on the phone. Only `tap`, `swipe`, `drag`, `type`, +`key`, `start_app`, `stop_app`, and `wait` are executable native verbs. Tools +are resolved by canonical name from `MacroOperator(extensions=[...])`. For +example, record `vault.type_secret` with `{"name":"login"}` as an extension +call and supply the corresponding credentials extension constructed with the +exact device handle used for replay. A missing or different handle is rejected +before any steps run. The row keeps the name, not the value. A bare `type_secret` +row is masked and has no lookup reference; re-record it using the extension. +Protected credentials and masked literal arguments do not execute. -Credentials come only from providers bound to the supplied device. Replay -checks the selected steps before dispatch; protected credentials and masked -literals are not replayed. The [CLI](cli/README.md) also asks for consent -before device selection if the steps may send SMS. Cloud use can incur charges. +`run_replay()` and the agent replay handoff ask for consent if the selected +rows may send paid SMS. In Python, pass `yes=True` for unattended replay; +without it, replay refuses before opening the device if it cannot prompt. +The [CLI](cli/README.md) (`--yes` or `-y`) checks before device selection and +uses the same pinned rows for replay. A dry run never prompts. Consent does +not override billing restrictions. If you use `MacroPlayer` or an operator +directly, you are responsible for obtaining consent before replaying paid actions. | File | Responsibility | | --- | --- | | `builder.py`, `models.py` | Build, version and load typed macro rows | -| `player.py`, `errors.py` | Guarded replay and phase-specific failures | +| `replay_actions.py`, `player.py`, `errors.py` | Allow-list, preflight, guarded replay, and failures | | `operator.py` | Run a macro through the shared device operator interface | | `settings.py`, `utils.py` | Replay defaults, fingerprint matching and logging | | `cli/` | List and replay macros from the terminal | diff --git a/mobilerun/macro/__init__.py b/mobilerun/macro/__init__.py index 78a11cdad..ef80852da 100644 --- a/mobilerun/macro/__init__.py +++ b/mobilerun/macro/__init__.py @@ -1,14 +1,25 @@ """Build versioned macros from runs and replay them with screen guards.""" from mobilerun.macro.builder import build_macro, load_macro, resolve_macro_path -from mobilerun.macro.errors import MacroError, MacroMismatch +from mobilerun.macro.errors import ( + MacroError, + MacroHandoffRefused, + MacroMismatch, + MacroPreflightError, + MacroSecretError, + OlderMacroError, +) from mobilerun.macro.models import MacroStep from mobilerun.macro.operator import MacroOperator from mobilerun.macro.player import MacroPlayer __all__ = [ "MacroError", + "MacroHandoffRefused", "MacroMismatch", + "MacroPreflightError", + "MacroSecretError", + "OlderMacroError", "MacroOperator", "MacroPlayer", "MacroStep", diff --git a/mobilerun/macro/builder.py b/mobilerun/macro/builder.py index bf6f59c3f..681c57f63 100644 --- a/mobilerun/macro/builder.py +++ b/mobilerun/macro/builder.py @@ -1,26 +1,53 @@ """Build and read versioned macro JSONL files.""" +import json import os import re from collections.abc import Collection from contextvars import ContextVar from pathlib import Path from tempfile import NamedTemporaryFile -from typing import TypeVar +from typing import Any, TypeVar -from pydantic import BaseModel, ValidationError +from pydantic import BaseModel -from mobilerun.macro.errors import MacroError +from mobilerun.macro.errors import MacroError, OlderMacroError from mobilerun.macro.models import MacroStep +from mobilerun.macro.replay_actions import is_replay_action, validate_action from mobilerun.macro.settings import get_macro_settings from mobilerun.macro.utils import has_masked_arguments from mobilerun.models import RunStep _NAME = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]*") _VERSION = re.compile(r"v([1-9][0-9]*)\.jsonl") -_UNSUPPORTED = ( - "Unsupported macro schema. Build a macro from a current run's steps.jsonl." -) +_LEGACY_RENAMES = { + "button_press": ("key", {"button": "name_or_code"}), + "press_key_code": ("key", {"key_code": "name_or_code"}), + "swipe": ( + "swipe", + { + "start_x": "x1", + "start_y": "y1", + "end_x": "x2", + "end_y": "y2", + "duration_ms": "ms", + }, + ), + "drag": ( + "drag", + { + "start_x": "x1", + "start_y": "y1", + "end_x": "x2", + "end_y": "y2", + "duration": "ms", + }, + ), + "wait": ("wait", {"duration": "seconds"}), + "input_text": ("type", {"stealth": "humanize"}), + "start_app": ("start_app", {"package": "app_id"}), + "stop_app": ("stop_app", {"package": "app_id"}), +} _Row = TypeVar("_Row", bound=BaseModel) _replay_snapshot: ContextVar[tuple[Path, list[MacroStep]] | None] = ContextVar( "macro_replay_snapshot", default=None @@ -57,7 +84,7 @@ def resolve_macro_path(target: str | Path) -> Path: if versions: return versions[max(versions)].absolute() if (path / "macro.json").is_file(): - raise MacroError(_UNSUPPORTED) + raise OlderMacroError() raise MacroError("No macro versions found in the directory") if not path.is_file(): raise MacroError("Macro file or directory not found") @@ -70,16 +97,55 @@ def _read_rows(path: Path, model: type[_Row]) -> list[_Row]: with path.open(encoding="utf-8") as file: for line_number, line in enumerate(file, 1): try: - rows.append(model.model_validate_json(line)) - except ValidationError: - raise MacroError( - f"{_UNSUPPORTED} Invalid JSONL row {line_number}." - ) from None + raw = json.loads(line) + if isinstance(raw, dict): + if "schema_version" not in raw: + if "macro_schema_version" in raw: + raise OlderMacroError() + _migrate_legacy_row(raw) + elif ( + type(raw["schema_version"]) is not int + or raw["schema_version"] != 2 + ): + raise OlderMacroError() + rows.append(model.model_validate(raw)) + except (ValueError, RecursionError, OverflowError): + raise MacroError(f"Invalid JSONL row {line_number}.") from None except (OSError, UnicodeError): raise MacroError("Could not read macro evidence") from None return rows +def _migrate_legacy_row(row: dict[str, Any]) -> None: + """Normalize the previous unstamped JSONL dialect without changing the file.""" + row["schema_version"] = 2 + name, args = row.get("action"), row.get("args") + if not isinstance(name, str) or not isinstance(args, dict): + return # Let the row model reject malformed evidence. + if name in _LEGACY_RENAMES: + row["action"], renamed = _LEGACY_RENAMES[name] + for old, new in renamed.items(): + if old in args: + if new in args: + raise ValueError("Duplicate legacy action argument") + args[new] = args.pop(old) + if name == "drag" and type(args.get("ms")) in (float, int): + args["ms"] *= 1000 # HEAD recorded drag duration in seconds. + if name == "input_text": + if args.get("humanize") is False: + args.pop("humanize") + if type(args.get("wpm")) is int and args["wpm"] == 0: + args.pop("wpm") + elif name == "extension_call" and args.get("name") == "vault.type_field": + values = args.get("arguments") + if ( + isinstance(values, dict) + and isinstance(values.get("name"), str) + and not values.get("protected", False) + ): + args["name"] = "vault.type_secret" + + def build_macro( steps_path: Path, name: str, @@ -92,22 +158,20 @@ def build_macro( if type(after_version) is not int or after_version < 0: raise MacroError("after_version must be a nonnegative integer") rows = [ - MacroStep( - i=row.i, - action=row.action, - args=row.args, - before=row.before, - after=row.after, - note=row.note, - target=row.target, - ) + MacroStep.from_run_step(row) for row in _read_rows(steps_path, RunStep) if row.ok + and is_replay_action(row.action.name) and (step_ids is None or row.i in step_ids) - and not has_masked_arguments(row.args) + and ( + row.action.name == "type_secret" + or not has_masked_arguments(row.action.arguments) + ) ] if not rows: raise MacroError("No replayable steps to build a macro") + for step in rows: + validate_action(step) temporary: Path | None = None try: diff --git a/mobilerun/macro/cli/README.md b/mobilerun/macro/cli/README.md index a4fd7d3be..7e11f9855 100644 --- a/mobilerun/macro/cli/README.md +++ b/mobilerun/macro/cli/README.md @@ -15,7 +15,14 @@ selects a one-based row position, while preview and mismatch output show the original recorded step ID. `--dry-run` previews the selected actions without a device and omits private arguments and screen evidence. Live replay asks for consent before selecting a device if the selected steps may send SMS; use -`--yes` only to approve those potential charges. +`--yes` to skip the consent prompt. If enabled in the device config, Android +Portal auto-setup runs before connection and also requires confirmation or +`--yes`. This flag does not approve gated actions recorded in the macro. The +CLI passes an opened core `AsyncDevice` to the macro operator. +Local credentials come from the selected config; Python callers of `run_replay` +can also supply `extensions=`. Strict replay denies gated core actions after +attachment. A handoff can supply a scoped `hitl_gate=` separately from SMS +consent. Files must use row schema 2. See [recording and replay](../README.md). Cloud devices can incur charges. @@ -23,9 +30,10 @@ Keep Click commands here; recording and playback implementations live in `macro/ ## Files -- `__init__.py` — Exports `macro`. -- `group.py` — `macro` — macro commands. -- `list.py` — `list` — list recorded macros. -- `replay.py` — `replay_options`, `replay`, `run_replay` — replay a recorded macro strictly, without agent dependencies. +| File | Purpose | +| --- | --- | +| `__init__.py`, `group.py` | Expose the macro command group. | +| `list.py` | List recorded macros. | +| `replay.py` | Parse options and replay a macro without agent dependencies. | **Depends on / used by:** Uses `macro`, `cli.base`, device selection, configuration and credentials; registered by the main CLI. diff --git a/mobilerun/macro/cli/replay.py b/mobilerun/macro/cli/replay.py index 8066dc4c5..4174188b6 100644 --- a/mobilerun/macro/cli/replay.py +++ b/mobilerun/macro/cli/replay.py @@ -1,30 +1,47 @@ """Replay a recorded macro strictly, without agent dependencies.""" import asyncio -from collections.abc import Callable +from collections.abc import Callable, Sequence +from contextvars import ContextVar +from dataclasses import replace from functools import wraps -from typing import Any, TypedDict, TypeVar, Unpack +from pathlib import Path +from typing import Any, NotRequired, TypedDict, TypeVar, Unpack, cast import click from mobilerun.cli.base import render from mobilerun.cli.base.billing import confirm_paid_action -from mobilerun.cli.devices.base.options import DeviceTarget, device_command +from mobilerun.cli.base.menu import is_interactive +from mobilerun.cli.devices.base.selection import open_client +from mobilerun.cli.devices.utils.approval import AsyncHitlGate, cli_hitl_gate +from mobilerun.cli.devices.utils.connection.default import device_target +from mobilerun.cli.devices.utils.connection.device import connect_device, pick_device +from mobilerun.cli.devices.utils.targets import classify_target from mobilerun.config.loader import ConfigLoader from mobilerun.config.settings import get_settings from mobilerun.core.credentials import DictCredentials, FileCredentials +from mobilerun.core.extensions import Extension from mobilerun.macro import MacroOperator, MacroStep, load_macro, resolve_macro_path from mobilerun.macro.builder import _replay_snapshot +from mobilerun.macro.replay_actions import validate_action from mobilerun.macro.settings import get_macro_settings from mobilerun.macro.utils import configure_macro_logging from mobilerun.models.results import ExecutionResult +from mobilerun.version import __version__ F = TypeVar("F", bound=Callable[..., Any]) +_replay_confirmation: ContextVar[ + tuple[tuple[Path, list[MacroStep]], int, int | None] | None +] = ContextVar("macro_replay_confirmation", default=None) class ReplayOptions(TypedDict): path: str - target: DeviceTarget + target: str | None + device_kind: NotRequired[str | None] + tcp: NotRequired[bool | None] + base_url: NotRequired[str | None] delay: float start_from: int max_steps: int | None @@ -33,12 +50,29 @@ class ReplayOptions(TypedDict): state_timeout: float state_threshold: float config_path: str | None + yes: NotRequired[bool] def replay_options(command: F) -> F: - """Shared replay controls for strict and agent-macro commands.""" + """Add replay controls and confirm paid SMS before resolving a device target.""" options = [ click.argument("path", metavar="MACRO"), + click.argument("target", metavar="[DEVICE]", required=False), + click.option("--device", "-d", "device_option", help="Device to use."), + *( + click.option(f"-{short}", f"--{kind}", is_flag=True) + for short, kind in zip( + "aicv", ("android", "ios", "cloud", "remote"), strict=True + ) + ), + click.option("--tcp/--no-tcp", default=None, help="Use TCP for Android ADB."), + click.option("--base-url", help="Cloud API base URL."), + click.option( + "--yes", + "-y", + is_flag=True, + help="Approve possible SMS charges and Portal setup without prompting.", + ), click.option( "--delay", "-t", @@ -73,63 +107,85 @@ def replay_options(command: F) -> F: click.option( "--config", "config_path", default=None, help="Config file for credentials" ), - device_command(allow_auto_setup=True), ] for option in reversed(options): command = option(command) - return command + + @wraps(command) + def invoke(**options: Any) -> Any: + path = resolve_macro_path(options["path"]) + steps = load_macro(path) + snapshot = (path, steps) + start_from, max_steps = options["start_from"], options["max_steps"] + confirmation = None + if not options["dry_run"]: + for step in steps: + validate_action(step) + confirm_replay_sms( + _selected_actions(steps, start_from, max_steps), yes=options["yes"] + ) + confirmation = (snapshot, start_from, max_steps) + + target, device_option = options["target"], options.pop("device_option") + if target and device_option and target != device_option: + raise click.UsageError( + "DEVICE and --device refer to different devices; choose one." + ) + kinds = [ + kind for kind in ("android", "ios", "cloud", "remote") if options.pop(kind) + ] + if len(kinds) > 1: + raise click.UsageError("Choose at most one device type flag.") + options["target"] = target or device_option + options["device_kind"] = next(iter(kinds), None) + + # Pass the checked rows, not a fresh read of the file after device selection. + options["path"] = str(path) + snapshot_token = _replay_snapshot.set(snapshot) + confirmation_token = _replay_confirmation.set(confirmation) + try: + return command(**options) + finally: + _replay_confirmation.reset(confirmation_token) + _replay_snapshot.reset(snapshot_token) + + return cast(F, invoke) def _selected_actions( steps: list[MacroStep], start_from: int, max_steps: int | None ) -> list[MacroStep]: """Read the same step range as the player, with a one-based CLI start.""" + if start_from < 1 or (max_steps is not None and max_steps < 0): + raise ValueError( + "start_from must be at least 1 and max_steps cannot be negative" + ) end = None if max_steps is None else start_from - 1 + max_steps return steps[start_from - 1 : end] -def _preflight_before_target(command: Callable[..., None]) -> Callable[..., None]: - """Check the recording before the device-command wrapper can discover a target.""" - - @wraps(command) - def invoke(*, yes: bool, **options: Any) -> None: - path = resolve_macro_path(options["path"]) - steps = load_macro(path) - if not (options["dry_run"] or yes): - count = 0 - for step in _selected_actions( - steps, options["start_from"], options["max_steps"] - ): - if step.action != "extension_call": - continue - name = step.args.get("name") - # Extension roles are not recorded; a named .send may be SMS. - if isinstance(name, str): - owner, _, method = name.rpartition(".") - if owner and method == "send": - count += 1 - if count: - asyncio.run(confirm_paid_action(f"Send {count} SMS", yes=False)) - - # Play what was checked, even if the file changes while the device opens. - options["path"] = str(path) - token = _replay_snapshot.set((path, steps)) - try: - return command(**options) - finally: - _replay_snapshot.reset(token) - - return invoke +def confirm_replay_sms(steps: Sequence[MacroStep], *, yes: bool) -> None: + """Ask for consent if any of the selected steps may send paid SMS.""" + if yes is True: + return + count = 0 + for step in steps: + if step.action.scope != "extension": + continue + name = step.action.arguments.get("name") + # Extension roles are not recorded; a named .send may be SMS. + if isinstance(name, str): + owner, _, method = name.rpartition(".") + if owner and method == "send": + count += 1 + if count: + asyncio.run(confirm_paid_action(f"Send {count} SMS", yes=False)) @click.command(short_help="Replay strictly") @click.option("--on-mismatch", type=click.Choice(["stop", "agent"]), default="stop") @click.option("--provider", default=None) @click.option("--model", default=None) -@click.option( - "--yes", "-y", is_flag=True, help="Confirm possible SMS charges without prompting." -) -@_preflight_before_target @replay_options def replay( on_mismatch: str, @@ -153,21 +209,21 @@ def replay( def _action_summary(step: MacroStep) -> str: """Preview the operation without displaying snapshots or free-form payloads.""" - kind = step.action - if kind in {"type_secret", "input_text", "extension_call", "open_url"}: + kind = step.action.name + if kind in {"type_secret", "type", "extension_call"}: return f"{kind} [redacted]" fields = { "tap": ("x", "y"), - "swipe": ("start_x", "start_y", "end_x", "end_y", "duration_ms"), - "drag": ("start_x", "start_y", "end_x", "end_y", "duration", "duration_ms"), - "wait": ("duration",), - "press_key_code": ("key_code",), + "swipe": ("x1", "y1", "x2", "y2", "ms"), + "drag": ("x1", "y1", "x2", "y2", "ms"), + "wait": ("seconds",), + "key": ("name_or_code",), } - if kind not in fields and kind not in {"start_app", "stop_app", "button_press"}: + if kind not in fields and kind not in {"start_app", "stop_app"}: return "unknown" parts = [kind] for key in fields.get(kind, ()): - value = step.args.get(key) + value = step.action.arguments.get(key) if isinstance(value, (int, float)): parts.append(f"{key}={str(value)[:24]}") return " ".join(parts) @@ -177,7 +233,7 @@ def run_replay( operator_type: Callable[..., MacroOperator], *, path: str, - target: DeviceTarget, + target: str | None, delay: float, start_from: int, max_steps: int | None, @@ -186,42 +242,108 @@ def run_replay( state_timeout: float, state_threshold: float, config_path: str | None, + yes: bool = False, + device_kind: str | None = None, + tcp: bool | None = None, + base_url: str | None = None, + extensions: Sequence[Extension] = (), + hitl_gate: AsyncHitlGate | None = None, **operator_options: object, ) -> None: + """Replay pinned rows after getting consent for any selected paid SMS sends.""" + if "macro_file" in operator_options: + raise ValueError("Use path, not macro_file, to select a recording") configure_macro_logging(debug) snapshot = _replay_snapshot.get() - if snapshot is not None and str(snapshot[0]) == path: - resolved, steps = snapshot - else: + if snapshot is None or str(snapshot[0]) != path: resolved = resolve_macro_path(path) - steps = load_macro(resolved) + snapshot = (resolved, load_macro(resolved)) + resolved, steps = snapshot + selected = _selected_actions(steps, start_from, max_steps) if dry_run: - for step in _selected_actions(steps, start_from, max_steps): + for step in selected: click.echo(f"{step.i}: {_action_summary(step)}") return + for step in steps: + validate_action(step) + confirmation = _replay_confirmation.get() + if not ( + confirmation is not None + and confirmation[0] is snapshot + and confirmation[1:] == (start_from, max_steps) + ): + confirm_replay_sms(selected, yes=yes) config = ConfigLoader.load(config_path) - operator = operator_type( - start_from_step=start_from - 1, - delay_between_actions=delay, - state_timeout=state_timeout, - state_threshold=state_threshold, - **operator_options, - ) + settings = config.device if tcp is None else replace(config.device, use_tcp=tcp) + identifier, kind = device_target(target, settings, device_kind) + if not identifier and not is_interactive(): + raise click.UsageError( + "Pass DEVICE or --device, or set a default with `mobilerun device connect`." + ) async def execute() -> ExecutionResult[Any]: - async with target.open() as device: + approve_setup = cli_hitl_gate(yes=yes) + setup_serial: str | None = None + + async def gate(action: str, args: dict[str, Any]) -> bool: + if setup_serial is not None: + return ( + action == "local.ensure_portal_ready" + and args.get("serial") == setup_serial + and await approve_setup(action, args) + ) + return hitl_gate is not None and await hitl_gate(action, args) + + async with open_client(base_url=base_url, hitl_gate=gate) as run: + if identifier: + selected_id, backend = identifier, None + else: + selected = await pick_device(run, kind) + selected_id, backend = selected.device_id, selected.backend + target_kind = classify_target(selected_id) + android_adb = target_kind != "http" and ( + backend == "local-android-adb" + or (backend is None and (kind or target_kind) == "android") + ) + if ( + android_adb + and settings.auto_setup + and settings.portal_mode != "disabled" + ): + setup_serial = selected_id + try: + await run.local.ensure_portal_ready( + selected_id, client_version=__version__ + ) + finally: + setup_serial = None + device = await connect_device( + run, selected_id, "android" if android_adb else kind, settings, backend + ) + supplied = list(extensions) configured = config.credentials if configured.get("enabled"): - await FileCredentials( - configured.get( - "file_path", str(get_settings().local_credentials_path) + supplied.append( + FileCredentials( + configured.get( + "file_path", str(get_settings().local_credentials_path) + ), + device=device, ) - ).bind(device) + ) elif configured and "enabled" not in configured: - await DictCredentials(configured).bind(device) - return await operator.execute(device, str(resolved), max_steps=max_steps) + supplied.append(DictCredentials(configured, device=device)) + operator = operator_type( + start_from_step=start_from - 1, + delay_between_actions=delay, + state_timeout=state_timeout, + state_threshold=state_threshold, + extensions=supplied, + **operator_options, + ) + return await operator.do(device, str(resolved), max_steps=max_steps) - token = _replay_snapshot.set((resolved, steps)) + token = _replay_snapshot.set(snapshot) try: result = asyncio.run(execute()) finally: diff --git a/mobilerun/macro/errors.py b/mobilerun/macro/errors.py index 91dc49f64..6ef2fff96 100644 --- a/mobilerun/macro/errors.py +++ b/mobilerun/macro/errors.py @@ -13,6 +13,34 @@ class MacroError(MobilerunError): """Base error for macro operations.""" +class OlderMacroError(MacroError): + """A stored run or macro does not use the current row schema.""" + + def __init__(self) -> None: + super().__init__("recorded with an older Mobilerun; re-record it") + + +class MacroPreflightError(MacroError): + """The file cannot be replayed as supplied; no action was dispatched.""" + + +class MacroSecretError(MacroPreflightError): + """Replay cannot resolve a safe credential reference.""" + + +class MacroHandoffRefused(MacroError): + """Replay stopped at a mismatch without exposing sensitive evidence.""" + + value_safe = True + + def __init__(self, step_index: int, phase: MismatchPhase) -> None: + self.step_index = step_index + self.phase = phase + super().__init__( + f"Macro mismatch at step {step_index} ({phase}) with sensitive input; handoff refused" + ) + + class MacroMismatch(MacroError, RuntimeError): """Replay stopped at a guard or action for an original macro row.""" diff --git a/mobilerun/macro/models.py b/mobilerun/macro/models.py index ad2940d8e..462c57fbb 100644 --- a/mobilerun/macro/models.py +++ b/mobilerun/macro/models.py @@ -1,19 +1,33 @@ """Persisted replay steps derived from run evidence.""" -from pydantic import BaseModel, ConfigDict, Field, JsonValue +from typing import Literal -from mobilerun.models import Fingerprint +from mobilerun_core import Action +from pydantic import Field +from mobilerun.models.recording import Fingerprint, RecordedAction, RunStep -class MacroStep(BaseModel): - """One deterministic action with its original index and optional guards.""" - model_config = ConfigDict(extra="forbid", frozen=True, hide_input_in_errors=True) +class MacroStep(RecordedAction): + """One deterministic action with its original index and optional guards.""" + schema_version: Literal[2] i: int = Field(ge=1, strict=True) - action: str = Field(min_length=1) - args: dict[str, JsonValue] = Field(repr=False) + action: Action = Field(repr=False) before: Fingerprint | None = None after: Fingerprint | None = None note: str | None = Field(default=None, repr=False) target: str | None = Field(default=None, repr=False) + + @classmethod + def from_run_step(cls, row: RunStep) -> "MacroStep": + """Carry replay inputs and guards forward, without run-only evidence.""" + return cls( + schema_version=row.schema_version, + i=row.i, + action=row.action, + before=row.before, + after=row.after, + note=row.note, + target=row.target, + ) diff --git a/mobilerun/macro/operator.py b/mobilerun/macro/operator.py index 68685f4da..30083d306 100644 --- a/mobilerun/macro/operator.py +++ b/mobilerun/macro/operator.py @@ -1,20 +1,20 @@ """Strict macro execution on caller-owned devices.""" import asyncio +from collections.abc import Sequence from pathlib import Path -from typing import TYPE_CHECKING, Any, TypedDict, TypeVar, Unpack +from typing import Any, TypedDict, TypeVar, Unpack +from mobilerun_core import AsyncDevice from pydantic import BaseModel +from mobilerun.core.extensions import Extension from mobilerun.core.operator import Operator from mobilerun.macro.builder import load_macro from mobilerun.macro.models import MacroStep from mobilerun.macro.player import MacroPlayer from mobilerun.models.results import ExecutionResult -if TYPE_CHECKING: - from mobilerun.core.devices import Device - T = TypeVar("T", bound=BaseModel) @@ -31,15 +31,17 @@ def __init__( macro_file: str | Path | None = None, *, start_from_step: int = 0, + extensions: Sequence[Extension] = (), **player_options: Unpack[PlayerOptions], ) -> None: + super().__init__(extensions=extensions) self.macro_file = macro_file self.start_from_step = start_from_step self.player_options = player_options - async def execute( + async def _execute( self, - device: "Device", + device: AsyncDevice, instruction: str, *, output: type[T] | None = None, @@ -48,7 +50,7 @@ async def execute( ) -> ExecutionResult[T]: if output is not None: raise ValueError("Strict macro replay does not produce structured output") - player = MacroPlayer(device, **self.player_options) + player = MacroPlayer(device, extensions=self.extensions, **self.player_options) steps = load_macro(self.macro_file or instruction) async with asyncio.timeout(timeout): return await self._execute_macro(player, device, steps, max_steps=max_steps) @@ -56,7 +58,7 @@ async def execute( async def _execute_macro( self, player: MacroPlayer, - device: "Device", + device: AsyncDevice, steps: list[MacroStep], *, max_steps: int | None = None, diff --git a/mobilerun/macro/player.py b/mobilerun/macro/player.py index 282a88730..9e045dcc9 100644 --- a/mobilerun/macro/player.py +++ b/mobilerun/macro/player.py @@ -1,55 +1,76 @@ -"""Deterministic, guarded replay on a caller-owned device.""" +"""Deterministic, guarded replay on a caller-owned core device.""" import asyncio import logging import time -from collections.abc import Awaitable, Iterator, Sequence -from contextlib import contextmanager +from collections.abc import Iterator, Sequence +from contextlib import ExitStack, contextmanager from contextvars import ContextVar from dataclasses import dataclass, field -from typing import Any +from typing import cast + +from mobilerun_core import AsyncDevice, DeviceDisconnectedError +from pydantic import JsonValue from mobilerun.core.credentials import CredentialProvider -from mobilerun.core.credentials.masking import CredentialMasks, masking_scope -from mobilerun.core.devices import Device -from mobilerun.core.state.base import StateProvider -from mobilerun.errors.base import DeviceError -from mobilerun.macro.errors import MacroError, MacroMismatch, MismatchPhase +from mobilerun.core.extensions import Extension, Tool, compile_tools +from mobilerun.core.runs import ActionRecording, observation_fingerprint +from mobilerun.errors.tools import ToolArgumentsError, ToolCompilationError +from mobilerun.macro.errors import ( + MacroError, + MacroHandoffRefused, + MacroMismatch, + MacroPreflightError, + MacroSecretError, + MismatchPhase, +) from mobilerun.macro.models import MacroStep +from mobilerun.macro.replay_actions import ExtensionCall, MaskedSecret, validate_action from mobilerun.macro.settings import get_macro_settings -from mobilerun.macro.utils import ( - capture_fingerprint, - compare_states, - has_masked_arguments, -) +from mobilerun.macro.utils import compare_states from mobilerun.models import Fingerprint +from mobilerun.utils.credentials.masking import CredentialMasks +from mobilerun.utils.redaction import Redactor, mask_step_args logger = logging.getLogger("mobilerun-macro") -_OBSERVATION_ERRORS = (DeviceError, OSError, NotImplementedError) -_Credential = tuple[CredentialProvider, str | None, str, str | None] - @dataclass class _ReplayMasks: masks: CredentialMasks + redactor: Redactor prepared: bool = False lock: asyncio.Lock = field(default_factory=asyncio.Lock) +@dataclass(frozen=True) +class _PreparedAction: + step: MacroStep + arguments: dict[str, object] = field(repr=False) + tool: Tool | None = None + credential: bool = False + + class MacroPlayer: """Replay steps without constructing, recording or closing the device.""" def __init__( self, - device: Device | None = None, + device: AsyncDevice, delay_between_actions: float | None = None, state_timeout: float | None = None, state_threshold: float | None = None, state_poll_interval: float | None = None, + *, + extensions: Sequence[Extension] = (), + recorder: ActionRecording | None = None, ) -> None: + if recorder is not None and recorder.device is not device: + raise ValueError("Macro recorder belongs to a different device") settings = get_macro_settings() - self.driver = device + self.device = device + self.extensions = tuple(extensions) + self._recorder = recorder self.delay_between_actions = ( settings.MOBILERUN_MACRO_DELAY if delay_between_actions is None @@ -70,7 +91,6 @@ def __init__( if state_poll_interval is None else state_poll_interval ) - self.state_provider: StateProvider | None = None self.executed_steps = 0 self._tainted = False self._replay_masks: ContextVar[_ReplayMasks | None] = ContextVar( @@ -79,8 +99,10 @@ def __init__( @property def tainted(self) -> bool: - """Whether this player may have dispatched sensitive input; sticky.""" - return self._tainted + """Whether the player or its recorder has seen sensitive input; sticky.""" + return self._tainted or ( + self._recorder is not None and self._recorder.redactor.sensitive_ui + ) @contextmanager def replay_scope(self) -> Iterator[None]: @@ -94,42 +116,23 @@ def _mask_scope(self) -> Iterator[_ReplayMasks]: if existing is not None: yield existing return - with masking_scope() as masks: - state = _ReplayMasks(masks) + redactor = self._recorder.redactor if self._recorder is not None else Redactor() + with CredentialMasks.scope(redactor=redactor) as masks: + state = _ReplayMasks(masks, redactor) token = self._replay_masks.set(state) try: yield state finally: self._replay_masks.reset(token) - def _device(self) -> Device: - if self.driver is None: - raise MacroError("MacroPlayer requires a Device") - return self.driver - async def get_current_fingerprint(self) -> Fingerprint | None: - """Read the best available structural screen evidence, without UI text.""" - driver = self._device() - if self.state_provider is not None: - try: - observed = capture_fingerprint(await self.state_provider.get_state()) - except _OBSERVATION_ERRORS: - pass - else: - if observed is not None: - return observed - view = driver.state - if view is not None: - try: - observed = capture_fingerprint(await view.refresh()) - except _OBSERVATION_ERRORS: - pass - else: - if observed is not None: - return observed + """Read the same structural guard as the screen recorder.""" + state = self._replay_masks.get() try: - return capture_fingerprint(await driver._get_ui_tree()) - except _OBSERVATION_ERRORS: + return observation_fingerprint( + await self.device.observe(), redactor=state.redactor if state else None + ) + except (DeviceDisconnectedError, OSError, NotImplementedError): return None async def _wait_for_guard( @@ -146,133 +149,129 @@ async def _wait_for_guard( # Engine polling is not an authored device wait. await asyncio.sleep(min(remaining, self.state_poll_interval)) - def _preflight(self, step: MacroStep) -> _Credential | None: - """Validate credential and redaction constraints before device observation.""" - args: dict[str, Any] = step.args - if has_masked_arguments(args): - raise MacroError("Cannot replay redacted action arguments") - driver = self._device() - if step.action not in {"extension_call", "type_secret"}: - return None - if args.get("protected", False) is not False: - raise MacroError("Protected credential replay requires host approval") - if step.action == "extension_call": - qualified = args.get("name") - arguments = args.get("arguments") - if not isinstance(qualified, str) or not isinstance(arguments, dict): - raise MacroError("Invalid extension_call action") - owner, dot, method = qualified.partition(".") - if not owner or not dot or not method: - raise MacroError("Invalid extension_call action") - bound = driver.extensions.get(owner) - if bound is None: - raise MacroError("Extension is not bound for macro replay") - entry = driver.actions.get(qualified) - if entry.sensitive_parameters & arguments.keys(): - raise MacroError("Cannot replay sensitive extension arguments") - if method != "type_field" or not isinstance(bound, CredentialProvider): - return None - vault = bound - else: - arguments = args - default_vault = driver.extensions.get("vault") - if isinstance(default_vault, CredentialProvider): - vault = default_vault - else: - candidates = [ - v - for v in driver.extensions.values() - if isinstance(v, CredentialProvider) - ] - if len(candidates) != 1: - raise MacroError("Bind one vault to replay a secret action") - vault = candidates[0] - package, name = arguments.get("package"), arguments.get("name") - field = arguments.get("field", "password") - if not any(isinstance(v, str) and v.strip() for v in (package, name)): - raise MacroError("Credential action requires a package or name") + async def _preflight(self, steps: Sequence[MacroStep]) -> list[_PreparedAction]: + parsed = [(step, validate_action(step)) for step in steps] + tools: dict[str, Tool] = {} + if any(isinstance(args, ExtensionCall) for _, args in parsed): + try: + tools = { + tool.canonical_name: tool + for tool in compile_tools(self.extensions, expand_atomics=False) + } + except ToolCompilationError: + raise MacroPreflightError( + "Could not compile macro extensions" + ) from None + vaults = { + f"{extension.name}.type_secret": extension + for extension in self.extensions + if isinstance(extension, CredentialProvider) + } + prepared = [] + for step, args in parsed: + if isinstance(args, MaskedSecret): + raise MacroSecretError( + f"No credential reference for masked secret at step {step.i}; " + "re-record it using a credentials extension" + ) + if not isinstance(args, ExtensionCall): + prepared.append(_PreparedAction(step, dict(args))) + continue + tool = tools.get(args.name) + if tool is None: + error = ( + MacroSecretError + if args.name.endswith(".type_secret") + else MacroPreflightError + ) + raise error(f"Extension tool is unavailable at step {step.i}") + if tool.sensitive_parameters & args.arguments.keys(): + raise MacroPreflightError( + f"Cannot replay sensitive extension arguments at step {step.i}" + ) + try: + with ExitStack() as scope: + values = dict(tool.validate_arguments(args.arguments, scope=scope)) + except ToolArgumentsError: + raise MacroPreflightError( + f"Invalid extension arguments at step {step.i}" + ) from None + vault = vaults.get(args.name) + if vault is not None: + if vault.device is not self.device: + raise MacroSecretError( + f"Credential provider must use the same device at step {step.i}" + ) + await self._validate_credential(vault, values, step.i) + prepared.append( + _PreparedAction( + step, dict(args.arguments), tool, credential=vault is not None + ) + ) + return prepared + + @staticmethod + async def _validate_credential( + vault: CredentialProvider, values: dict[str, object], index: int + ) -> None: + name, package, field_name = ( + values.get("name"), + values.get("package"), + values.get("field"), + ) + unscoped = values.get("unscoped") is True if ( - (package is not None and not isinstance(package, str)) - or (name is not None and not isinstance(name, str)) - or not isinstance(field, str) - or not field.strip() + not isinstance(name, str) + or not name.strip() + or (package is not None and not isinstance(package, str)) + or (field_name is not None and not isinstance(field_name, str)) + or (unscoped and package is not None) ): - raise MacroError("Invalid credential reference") - if vault.requires_approval(package, field, name): - raise MacroError("Protected credential replay requires host approval") - return vault, package, field, name - - async def _prepare_masks(self, masks: CredentialMasks) -> None: + raise MacroSecretError(f"Invalid credential reference at step {index}") try: - for extension in self._device().extensions.values(): - if isinstance(extension, CredentialProvider): - await extension.prepare_masks(masks) - return + metadata = await vault.list(package) except Exception: - pass - # Provider exceptions can contain values; don't attach their traceback. - raise MacroError("Could not prepare credential masking") + metadata = None + if metadata is not None: + match_package = unscoped or package is not None + matches = [ + item + for item in metadata + if item["name"] == name + and (not match_package or item["package"] == package) + and (field_name is None or field_name in item["fields"]) + ] + if len(matches) == 1: + fields = matches[0]["fields"] + if field_name is None: + field_name = ( + "password" + if "password" in fields + else (fields[0] if len(fields) == 1 else None) + ) + if field_name is not None: + if vault.requires_approval(package, field_name, name): + raise MacroSecretError( + "Protected credential replay requires host approval" + ) + return + # Resolver errors can include values: do not attach an exception chain. + raise MacroSecretError(f"Could not resolve the credential at step {index}") - async def _prepare_once(self, state: _ReplayMasks) -> CredentialMasks: + async def _prepare_once(self, state: _ReplayMasks) -> None: async with state.lock: - if not state.prepared: - await self._prepare_masks(state.masks) + if state.prepared: + return + try: + for extension in self.extensions: + if isinstance(extension, CredentialProvider): + await extension.prepare_masks(state.masks) + except Exception: + state.prepared = False + else: state.prepared = True - return state.masks - - async def _dispatch( - self, step: MacroStep, credential: _Credential | None - ) -> object: - driver = self._device() - args: dict[str, Any] = step.args - operation: Awaitable[object] - match step.action: - case "tap": - operation = driver.tap(args["x"], args["y"]) - case "swipe": - operation = driver.swipe( - args["start_x"], - args["start_y"], - args["end_x"], - args["end_y"], - args["duration_ms"], - ) - case "drag": - operation = driver.drag( - args["start_x"], - args["start_y"], - args["end_x"], - args["end_y"], - args["duration"], - ) - case "input_text": - options = { - key: args[key] for key in ("clear", "stealth", "wpm") if key in args - } - operation = driver.input_text(args["text"], **options) - case "start_app": - operation = driver.start_app(args["package"], args.get("activity")) - case "stop_app": - operation = driver.stop_app(args["package"]) - case "open_url": - operation = driver.open_url(args["url"]) - case "press_key_code": - operation = driver.press_key_code(args["key_code"]) - case "button_press": - operation = driver.press_button(args["button"]) - case "wait": - operation = driver.wait(args["duration"]) - case "extension_call": - operation = driver.actions.call( - args["name"], args["arguments"], audience="operator" - ) - case "type_secret": - assert credential is not None - vault, package, field, name = credential - operation = vault.type_field(package, field, name) - case _: - raise MacroError("Unknown macro action") - return await operation + return + raise MacroSecretError("Could not prepare credential masking") def _stop( self, @@ -282,32 +281,49 @@ def _stop( masks: CredentialMasks, ) -> MacroMismatch: if masks.active or self.tainted: - # A repair add-on must not be handed a device with visible credentials. - raise MacroError( - f"Macro mismatch at step {step.i} ({phase}) during credential replay; handoff refused" - ) + # A repair add-on must not be handed a device with visible secrets. + raise MacroHandoffRefused(step.i, phase) return MacroMismatch(step, phase, observed) - async def _play_step( - self, step: MacroStep, credential: _Credential | None, masks: CredentialMasks - ) -> None: + async def _play_step(self, action: _PreparedAction, masks: CredentialMasks) -> None: + step = action.step before = None if step.before is not None: matched, before = await self._wait_for_guard(step.before) if not matched: raise self._stop(step, "before", before, masks) + if action.credential: + self._tainted = True try: - try: - ok = await self._dispatch(step, credential) is not False - finally: - if masks.active: - self._tainted = True - except MacroError: - raise + if action.tool is not None: + if self._recorder is None: + result = await action.tool.invoke(action.arguments) + else: + # Preflight validated these source JSON arguments. Keep omitted defaults omitted. + arguments = mask_step_args( + cast(dict[str, JsonValue], action.arguments) + ) + async with self._recorder.extension_call( + action.tool.canonical_name, arguments + ) as outcome: + try: + result = await action.tool.invoke(action.arguments) + outcome.set_result(result) + finally: + if action.credential or masks.active: + self._recorder.redactor.mark_sensitive() + else: + # Only names admitted by the closed argument-model table reach here. + result = await getattr(self.device, step.action.name)( + **action.arguments + ) except Exception: - # Never attach backend exception text or a credential traceback. - ok = False - if not ok: + # Backend error text and credential tracebacks are not replay evidence. + result = False + finally: + if masks.active: + self._tainted = True + if result is False: raise self._stop(step, "action", before, masks) if step.after is not None: matched, after = await self._wait_for_guard(step.after) @@ -316,11 +332,11 @@ async def _play_step( self.executed_steps += 1 async def play_step(self, step: MacroStep) -> None: - """Check the before guard, dispatch the action, then check the after guard.""" - credential = self._preflight(step) + """Preflight one standalone step, then play it with its guards.""" + (action,) = await self._preflight([step]) with self._mask_scope() as state: - masks = await self._prepare_once(state) - await self._play_step(step, credential, masks) + await self._prepare_once(state) + await self._play_step(action, state.masks) async def replay_macro( self, @@ -328,23 +344,20 @@ async def replay_macro( start_from_step: int = 0, max_steps: int | None = None, ) -> bool: - """Replay selected rows; the zero-based offset is a position, not an ID.""" + """Preflight the entire file, then replay the requested positional slice.""" self.executed_steps = 0 if start_from_step < 0 or (max_steps is not None and max_steps < 0): raise MacroError("Step limits must not be negative") end = None if max_steps is None else start_from_step + max_steps - selected = steps[start_from_step:end] - credentials = [self._preflight(step) for step in selected] + selected = (await self._preflight(steps))[start_from_step:end] if not selected: return True with self._mask_scope() as state: - masks = await self._prepare_once(state) - for index, (step, credential) in enumerate( - zip(selected, credentials, strict=True) - ): + await self._prepare_once(state) + for index, action in enumerate(selected): if index: # Only explicit macro waits are recorded as device actions. await asyncio.sleep(self.delay_between_actions) - logger.info("Replaying macro step %s", step.i) - await self._play_step(step, credential, masks) + logger.info("Replaying macro step %s", action.step.i) + await self._play_step(action, state.masks) return True diff --git a/mobilerun/macro/replay_actions.py b/mobilerun/macro/replay_actions.py new file mode 100644 index 000000000..554e91c60 --- /dev/null +++ b/mobilerun/macro/replay_actions.py @@ -0,0 +1,76 @@ +"""Closed replay vocabulary and value-safe validation of persisted arguments.""" + +from typing import Literal + +from mobilerun_core import AsyncDevice +from pydantic import BaseModel, ConfigDict, Field, JsonValue, ValidationError + +from mobilerun.macro.errors import MacroPreflightError +from mobilerun.macro.models import MacroStep +from mobilerun.macro.utils import has_masked_arguments + + +class _Args(BaseModel): + model_config = ConfigDict( + extra="forbid", strict=True, allow_inf_nan=False, hide_input_in_errors=True + ) + + +class MaskedSecret(_Args): + secret: Literal["***"] + clear: bool = False + + +class ExtensionCall(_Args): + name: str = Field(pattern=r"^[a-z][a-z0-9_]{0,31}\.[A-Za-z_][A-Za-z0-9_]*$") + arguments: dict[str, JsonValue] + + +# Only portable control actions. Opaque links, files, proxies and maintenance +# remain run evidence. Matching core method names are dispatched by the player. +_NATIVE = AsyncDevice.native_actions() +_ARGUMENT_MODELS: dict[str, type[BaseModel]] = { + **{ + name: _NATIVE[name].arguments + for name in ( + "tap", + "swipe", + "drag", + "type", + "key", + "start_app", + "stop_app", + "wait", + ) + }, + "type_secret": MaskedSecret, + "extension_call": ExtensionCall, +} + + +def is_replay_action(name: str) -> bool: + """Whether this action name belongs to the macro replay vocabulary.""" + return name in _ARGUMENT_MODELS + + +def validate_action(step: MacroStep) -> BaseModel: + """Check one action's vocabulary and exact JSON argument names/types.""" + name, inputs = step.action.name, step.action.arguments + model = _ARGUMENT_MODELS.get(name) + if model is None: + raise MacroPreflightError(f"Unknown macro action at step {step.i}") + if model is not MaskedSecret and has_masked_arguments(inputs): + raise MacroPreflightError(f"Cannot replay redacted arguments at step {step.i}") + try: + arguments = model.model_validate(inputs) + except ValidationError: + pass + else: + # Default-only options can be in the recording. Do not replay a + # cloud-only gesture or allow this portable action to erase app data. + if not ( + (name == "swipe" and inputs.get("hold_ms", 0) != 0) + or (name == "stop_app" and inputs.get("clear_data", False)) + ): + return arguments + raise MacroPreflightError(f"Invalid macro arguments at step {step.i}") diff --git a/mobilerun/macro/utils.py b/mobilerun/macro/utils.py index d90dd91e9..c68242c18 100644 --- a/mobilerun/macro/utils.py +++ b/mobilerun/macro/utils.py @@ -1,45 +1,10 @@ """Fingerprint matching, replay argument checks, and CLI logging.""" import logging -from collections.abc import Mapping -from mobilerun.core.credentials.masking import current_masks -from mobilerun.core.state.ui_state import UIState from mobilerun.macro.settings import get_macro_settings from mobilerun.models import Fingerprint -from mobilerun.utils.redaction import _redact_secrets -from mobilerun.utils.screen_fingerprint import fingerprint_matches, screen_fingerprint - - -def capture_fingerprint( - state: UIState | Mapping[str, object] | None, -) -> Fingerprint | None: - """Normalize either a state-provider view or a raw device dump.""" - if state is None: - return None - if not isinstance(state, Mapping): - state = {"phone_state": state.phone_state, "elements": state.elements} - observed = screen_fingerprint(state) - masks = current_masks.get() - if masks is not None and masks.active: - masked = masks.snapshot( - { - "phone_state": {"app": observed.app, "activity": observed.activity}, - "nodes": [{"id": key} for key in observed.elements], - } - ) - observed = Fingerprint( - app=masked["phone_state"]["app"], - activity=masked["phone_state"]["activity"], - elements=tuple(node["id"] for node in masked["nodes"]), - ) - if any( - _redact_secrets(value) != value - for value in (observed.app, observed.activity, *observed.elements) - if value is not None - ): - return None - return observed if observed.app or observed.activity or observed.elements else None +from mobilerun.utils.screen.fingerprint import fingerprint_matches def compare_states( diff --git a/mobilerun/mcp/cli/README.md b/mobilerun/mcp/cli/README.md index 01baefff4..5226894dd 100644 --- a/mobilerun/mcp/cli/README.md +++ b/mobilerun/mcp/cli/README.md @@ -1,3 +1,13 @@ # MCP CLI Click commands for installing, listing, and removing the public Mobilerun MCP server. Installation logic lives in `mobilerun.mcp.installer`. + +```sh +mobilerun mcp list --help +``` + +| File | Purpose | +| --- | --- | +| `group.py` | Register MCP install, list and remove commands. | + +See [MCP overview](../README.md). diff --git a/mobilerun/models/README.md b/mobilerun/models/README.md index ed3c882f6..70c31c36e 100644 --- a/mobilerun/models/README.md +++ b/mobilerun/models/README.md @@ -1,23 +1,23 @@ # models/ -Core's models. Feature packages keep their own models inside their folder. - -Defines transport-independent values for apps, billing, credentials and task results. - -Keep shared value types here; device lifecycle and API calls belong in `core/` and `clients/`. +Shared framework values for account resources, billing, credentials, tasks and recordings. +Feature packages keep their own models. Get phone values such as `Element`, +`Observation`, `InstalledApp`, `FileEntry`, `Location` and `ProxyStatus` from +`mobilerun_core`, not from framework models. ## Files -- `__init__.py` — Exports shared value types, including `Location`, `App`, `Billing`, `Credential`, and task results. -- `apps.py` — `App` — application value type shared by devices and clients. -- `billing.py` — `Billing`, `Plan` — billing modes shared by configuration and core resources. -- `credentials.py` — `Credential`, `CredentialMetadata` — value-safe credential data and metadata. -- `checkout.py` — `Checkout` and `PaymentSnapshot` — checkout and payment values. -- `location.py` — `Location` — latitude and longitude reported by a device. -- `proxy.py` — `ProxyStatus` — proxy connection status. -- `recording.py` — `RunRecord`, `RunStep`, and `Fingerprint` — validated run metadata, action outcomes, and screen evidence. `RecordingDevice` writes `runs//run.json` and append-only `runs//steps.jsonl` through [`RunWriter`](../core/runs/README.md). -- `ui.py` — `UIElement` — UI snapshot element data. -- `results.py` — `ExecutionResult`, `ExpectationVerdict`, `ExpectationResult` — typed task results, independent of execution and transport. +| File | Purpose | +| --- | --- | +| `apps.py`, `files.py` | Account library apps and files, not phone-side values. | +| `billing.py`, `checkout.py` | Account billing, allocation plans and payment state. For cloud phone plans use `mobilerun_core.CloudPlan`. | +| `cloud_task.py`, `context.py`, `results.py` | Cloud task inputs and references, extension context and typed results. | +| `credentials.py` | Credential records, public metadata and host masking/approval rules. | +| `proxy.py` | Account proxy product metadata. | +| `recording.py` | [Run metadata, actions and evidence](../core/runs/README.md) using schema 2. | +| `screen/` | [Model-facing screen values](screen/README.md); core owns native observations. | +| `tool_call.py` | Extension call metadata. | +| `webhooks.py` | Endpoint metadata with masked URLs and signing secrets. | ```python from mobilerun.models import Billing @@ -27,4 +27,4 @@ billing = Billing.INCLUDED See [configuration](../config/README.md). -**Depends on / used by:** Python dataclasses, enums and Pydantic; used by device, cloud-client and agent code. +**Depends on / used by:** Python dataclasses, enums and Pydantic; used by cloud clients, recording and agent code. diff --git a/mobilerun/models/__init__.py b/mobilerun/models/__init__.py index 8ca351cd9..ee7289d0c 100644 --- a/mobilerun/models/__init__.py +++ b/mobilerun/models/__init__.py @@ -1,38 +1,54 @@ """Shared value types. No clients, SDK access, or resource lifecycle.""" +from typing import TYPE_CHECKING + from .apps import App -from .billing import Billing, Plan, ResourcePlan +from .billing import Billing, ResourcePlan from .checkout import Checkout, PaymentSnapshot from .cloud_task import CloudCredentialReference, CloudTaskInputs from .credentials import Credential, CredentialMetadata -from .files import DeviceFile, WorkspaceFile -from .location import Location -from .proxy import ProxyStatus -from .recording import ( - Actor, - DeviceInfo, - Fingerprint, - RunKind, - RunRecord, - RunStatus, - RunStep, -) +from .files import WorkspaceFile from .results import ExecutionResult, ExpectationResult, ExpectationVerdict -from .ui import UIElement +from .webhooks import WebhookEndpoint + +if TYPE_CHECKING: + from .recording import ( + Actor, + DeviceInfo, + Fingerprint, + RunKind, + RunRecord, + RunStatus, + RunStep, + ) + + +def __getattr__(name: str) -> object: + # Recording models depend on core; other value types do not. + if name in { + "Actor", + "DeviceInfo", + "Fingerprint", + "RunKind", + "RunRecord", + "RunStatus", + "RunStep", + }: + from . import recording + + return getattr(recording, name) + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + __all__ = [ "App", "Billing", - "Plan", "ResourcePlan", "Credential", "Checkout", "CloudCredentialReference", "CloudTaskInputs", - "DeviceFile", "WorkspaceFile", - "Location", - "ProxyStatus", "Actor", "DeviceInfo", "Fingerprint", @@ -41,9 +57,9 @@ "RunStatus", "RunStep", "CredentialMetadata", - "UIElement", "PaymentSnapshot", "ExecutionResult", "ExpectationResult", "ExpectationVerdict", + "WebhookEndpoint", ] diff --git a/mobilerun/models/apps.py b/mobilerun/models/apps.py index 5d5755e5d..24a257b5f 100644 --- a/mobilerun/models/apps.py +++ b/mobilerun/models/apps.py @@ -1,14 +1,20 @@ -"""Application value type shared by devices and clients.""" +"""Application metadata in the framework's workspace library.""" + +from __future__ import annotations from dataclasses import dataclass from pathlib import Path +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from mobilerun_core import AppIdentity @dataclass(frozen=True) class App: - package: str - version: str + """Workspace library entry with a resource ID distinct from the platform ID.""" + + identity: AppIdentity name: str - id: str | None = None - version_code: int | None = None + resource_id: str path: Path | None = None diff --git a/mobilerun/models/billing.py b/mobilerun/models/billing.py index bdd2a4a8b..2011627e9 100644 --- a/mobilerun/models/billing.py +++ b/mobilerun/models/billing.py @@ -17,16 +17,3 @@ class ResourcePlan(StrEnum): AUTO = "auto" INCLUDED = "included" RENT = "rent" - - -class Plan(StrEnum): - """Cloud phone billing plans. - - AUTO uses a subscription first, then falls back to minutes. - MINUTE uses per-minute balance only; exhaustion raises MINUTE_BALANCE_EXHAUSTED. - SUBSCRIPTION uses a subscription slot only, never minutes. - """ - - AUTO = "auto" - MINUTE = "minute" - SUBSCRIPTION = "subscription" diff --git a/mobilerun/models/checkout.py b/mobilerun/models/checkout.py index 5f8754786..8c66e4d38 100644 --- a/mobilerun/models/checkout.py +++ b/mobilerun/models/checkout.py @@ -1,5 +1,6 @@ """Public checkout details for a pending cloud resource.""" +from collections.abc import Awaitable, Callable from dataclasses import dataclass from datetime import datetime @@ -12,6 +13,9 @@ class Checkout: resource_id: str +CheckoutCallback = Callable[[Checkout], Awaitable[None] | None] + + @dataclass(frozen=True) class PaymentSnapshot: status: str diff --git a/mobilerun/models/credentials.py b/mobilerun/models/credentials.py index 1de6aed5e..39f9d808e 100644 --- a/mobilerun/models/credentials.py +++ b/mobilerun/models/credentials.py @@ -1,11 +1,21 @@ -"""Value-safe credential data.""" - -from __future__ import annotations +"""Value-safe credential data and host-owned policies.""" +from collections.abc import Mapping from dataclasses import dataclass, field -from typing import Protocol +from typing import Self + +from typing_extensions import NotRequired, TypedDict + +from mobilerun.errors.credentials import CredentialFormatError + -from typing_extensions import TypedDict +class CredentialMetadata(TypedDict): + """Public metadata with optional vault-provider provenance.""" + + package: str | None + name: str + fields: list[str] + source: NotRequired[str] @dataclass @@ -14,22 +24,51 @@ class Credential: name: str fields: dict[str, str] = field(repr=False) + @classmethod + def from_mapping( + cls, mapping: Mapping[str, object] | Mapping[str | None, object] + ) -> list[Self]: + """Convert flat names or package → name → fields into records.""" + result: list[Self] = [] + for key, value in mapping.items(): + if isinstance(value, str) and isinstance(key, str): + result.append(cls(None, key, {"password": value})) + elif isinstance(value, dict): + for name, fields in value.items(): + if ( + not isinstance(name, str) + or not isinstance(fields, dict) + or not all(isinstance(v, str) for v in fields.values()) + ): + raise CredentialFormatError( + "Credential fields must map field types to strings" + ) + result.append(cls(key, name, fields.copy())) + else: + raise CredentialFormatError( + "Credentials must be strings or package mappings" + ) + return result + def __repr__(self) -> str: return f"Credential(package={self.package!r}, name={self.name!r}, fields={list(self.fields)!r})" -class CredentialLookup(Protocol): - """Minimal lookup contract consumed by shared credential clients.""" - - async def find( - self, - package: str | None = None, - field: str = "password", - name: str | None = None, - ) -> Credential | None: ... - +@dataclass(frozen=True) +class CredentialPolicy: + """Host-owned policy for a named field, optionally limited to one package.""" -class CredentialMetadata(TypedDict): - package: str | None name: str - fields: list[str] + field: str = "password" + package: str | None = None + requires_approval: bool = False + mask_from_start: bool = False + mask_card_numbers: bool = False + + def matches(self, package: str | None, field: str, name: str | None) -> bool: + # A partial selector must not bypass a protected field it could match. + return ( + (name is None or self.name == name) + and self.field == field + and (package is None or self.package is None or self.package == package) + ) diff --git a/mobilerun/models/files.py b/mobilerun/models/files.py index 0c36b5286..35f130f5f 100644 --- a/mobilerun/models/files.py +++ b/mobilerun/models/files.py @@ -1,4 +1,4 @@ -"""File value types shared by workspace and device operations.""" +"""Workspace file metadata.""" from dataclasses import dataclass from datetime import datetime @@ -11,11 +11,3 @@ class WorkspaceFile: mime_type: str size_bytes: int created_at: datetime - - -@dataclass(frozen=True) -class DeviceFile: - path: str - name: str - size_bytes: int | None - modified_at: datetime | None diff --git a/mobilerun/models/location.py b/mobilerun/models/location.py deleted file mode 100644 index ea68e0cf4..000000000 --- a/mobilerun/models/location.py +++ /dev/null @@ -1,10 +0,0 @@ -"""Location reported by a device.""" - -from pydantic import BaseModel - - -class Location(BaseModel): - """Coordinates reported by the device's location service.""" - - latitude: float - longitude: float diff --git a/mobilerun/models/proxy.py b/mobilerun/models/proxy.py index 497d6835c..a385ebdc2 100644 --- a/mobilerun/models/proxy.py +++ b/mobilerun/models/proxy.py @@ -1,10 +1,20 @@ -"""Proxy value types.""" +"""Account product metadata; device proxy values belong to mobilerun-core.""" from dataclasses import dataclass +from typing import Literal, TypeAlias + +from mobilerun_core import ConnectProxyRef + +ProxyProductType: TypeAlias = Literal["dedicated_residential", "residential", "mobile"] @dataclass(frozen=True) -class ProxyStatus: - connected: bool - name: str | None = None - protocol: str | None = None +class ProxyProduct: + """Credential-free account catalogue entry, not a device proxy value.""" + + ref: ConnectProxyRef + name: str + country: str + status: str + type: ProxyProductType + billing_mode: str | None diff --git a/mobilerun/models/recording.py b/mobilerun/models/recording.py index 7728477c4..61bd116fe 100644 --- a/mobilerun/models/recording.py +++ b/mobilerun/models/recording.py @@ -1,8 +1,9 @@ """Shared metadata, action outcomes, and screen evidence for recorded runs.""" from datetime import datetime, timezone -from typing import Annotated, Literal +from typing import Annotated, Any, Literal +from mobilerun_core import Action from pydantic import ( AfterValidator, AwareDatetime, @@ -10,6 +11,10 @@ ConfigDict, Field, JsonValue, + SerializerFunctionWrapHandler, + TypeAdapter, + model_serializer, + model_validator, ) RunKind = Literal["recording", "macro_replay", "agent"] @@ -34,8 +39,64 @@ class _RunValue(BaseModel): ) +_ACTION_NAME: TypeAdapter[str] = TypeAdapter(Annotated[str, Field(min_length=1)]) +_ACTION_ARGUMENTS = TypeAdapter(dict[str, JsonValue]) +_ACTION_STARTED_AT: TypeAdapter[datetime | None] = TypeAdapter(_UtcDatetime | None) + + +class RecordedAction(_RunValue): + """Shared schema-2 action encoding for run and macro rows. + + The action's timestamp is the row's ``started_at``; rows without one load as None. + """ + + @model_validator(mode="before") + @classmethod + def decode_action(cls, value: Any) -> Any: + if not isinstance(value, dict): + return value + fields = dict(value) + raw = fields.get("action") + started_at = fields.get("started_at") + if "started_at" not in cls.model_fields: + fields.pop("started_at", None) + if isinstance(raw, Action): + name, arguments = raw.name, raw.arguments + started_at = started_at or raw.started_at + elif isinstance(raw, str) and "args" in fields: + name, arguments = raw, fields.pop("args") + else: + raise ValueError("Expected an Action or flat schema-2 action and args") + name = _ACTION_NAME.validate_python(name) + scope = "extension" if name == "extension_call" else "device" + if isinstance(raw, Action) and raw.scope != scope: + raise ValueError("Action scope cannot be represented in schema 2") + fields["action"] = Action( + name, + _ACTION_ARGUMENTS.validate_python(arguments), + scope, + _ACTION_STARTED_AT.validate_python(started_at), + ) + return fields + + @model_serializer(mode="wrap") + def encode_action(self, handler: SerializerFunctionWrapHandler) -> dict[str, Any]: + flat = {} + for key, value in handler(self).items(): + if key != "action": + flat[key] = value + else: + if "name" in value: + flat["action"] = value["name"] + if "arguments" in value: + flat["args"] = value["arguments"] + if value.get("started_at") is not None: + flat.setdefault("started_at", value["started_at"]) + return flat + + class DeviceInfo(_RunValue): - """Identity of the device being recorded.""" + """Version-2 run file identity, not the live device descriptor.""" platform: str identifier: str @@ -52,6 +113,7 @@ class Fingerprint(_RunValue): class RunRecord(_RunValue): """Metadata and lifecycle status for one recording directory.""" + schema_version: Literal[2] run_id: str = Field(pattern=r"^[a-zA-Z0-9][a-zA-Z0-9_.-]*$") kind: RunKind source_macro: str | None = None @@ -62,15 +124,16 @@ class RunRecord(_RunValue): failed_step: _StepIndex | None = None -class RunStep(_RunValue): +class RunStep(RecordedAction): """One dispatched action, including unsuccessful outcomes.""" + schema_version: Literal[2] i: _StepIndex started_at: _UtcDatetime finished_at: _UtcDatetime - action: str = Field(min_length=1) - args: dict[str, JsonValue] + action: Action = Field(repr=False) ok: bool = Field(strict=True) + result: JsonValue = None error: str | None = None before: Fingerprint | None = None after: Fingerprint | None = None diff --git a/mobilerun/models/results.py b/mobilerun/models/results.py index 21b080b6c..2fea96ec4 100644 --- a/mobilerun/models/results.py +++ b/mobilerun/models/results.py @@ -8,6 +8,8 @@ class ExecutionResult(BaseModel, Generic[T]): + """Result of running a task on a device.""" + success: bool answer: str | None = None output: T | None = None diff --git a/mobilerun/models/screen/README.md b/mobilerun/models/screen/README.md new file mode 100644 index 000000000..b8df0a816 --- /dev/null +++ b/mobilerun/models/screen/README.md @@ -0,0 +1,20 @@ +# Screen models + +`ScreenView` is the prompt projection shared by live observations and agent +history. Its `ProjectedElement` rows carry input-unit bounds and reported UI +flags. `ModelGeometry` translates model coordinates back to native input. + +```python +from mobilerun.models.screen import ModelGeometry + +geometry = ModelGeometry(input_size=(1080, 2400), normalized=True) +assert geometry.to_device(500, 500) == (540, 1200) +``` + +| File | Role | +| --- | --- | +| `view.py` | Prompt text, projected rows, focus and privacy-aware serialization | +| `element.py` | A typed prompt row, not a native action target | +| `geometry.py` | Model-to-input geometry and rounding | + +See [the screen provider](../../core/screen/README.md) for live target dispatch. diff --git a/mobilerun/models/screen/__init__.py b/mobilerun/models/screen/__init__.py new file mode 100644 index 000000000..2607a15be --- /dev/null +++ b/mobilerun/models/screen/__init__.py @@ -0,0 +1,7 @@ +"""Model-facing screen data, without native device targets.""" + +from .element import ProjectedElement +from .geometry import ModelGeometry +from .view import ScreenView + +__all__ = ["ModelGeometry", "ProjectedElement", "ScreenView"] diff --git a/mobilerun/models/screen/element.py b/mobilerun/models/screen/element.py new file mode 100644 index 000000000..5dfcebcae --- /dev/null +++ b/mobilerun/models/screen/element.py @@ -0,0 +1,66 @@ +"""A model-facing element without any native identities.""" + +from typing import Self + +from mobilerun_core import Element +from pydantic import BaseModel, ConfigDict, Field + +from .geometry import Bounds + + +class ProjectedElement(BaseModel): + """A prompt row, never a native dispatch target. Bounds are in input units.""" + + model_config = ConfigDict(frozen=True, hide_input_in_errors=True) + index: int + label: str = Field(default="", repr=False) + class_name: str = Field(default="", repr=False) + resource_id: str = Field(default="", repr=False) + description: str = Field(default="", repr=False) + hint: str = Field(default="", repr=False) + value: str = Field(default="", repr=False) + bounds: Bounds | None = Field(default=None, repr=False) + clickable: bool | None = None + enabled: bool | None = None + visible: bool | None = None + long_clickable: bool | None = None + editable: bool | None = None + password: bool | None = None + checked: bool | None = None + parent_index: int | None = None + legacy_ios: bool = False + + @classmethod + def from_element( + cls, + node: Element, + *, + index: int, + parent_index: int | None, + legacy_ios: bool, + label: str, + ) -> Self: + """Project a native element into a prompt row without its native identity.""" + bounds = None + if node.bounds is not None: + left, top, right, bottom = node.bounds + bounds = (int(left), int(top), int(right), int(bottom)) + return cls( + index=index, + parent_index=parent_index, + legacy_ios=legacy_ios, + bounds=bounds, + label=label, + class_name=node.class_name or "", + resource_id=node.resource_id or "", + description=node.content_description or "", + hint=node.hint or node.placeholder or "", + value=node.value or "", + clickable=node.clickable, + enabled=node.enabled, + visible=node.visible, + long_clickable=node.long_clickable, + editable=node.editable, + password=node.password, + checked=bool(node.checked) if node.checkable else None, + ) diff --git a/mobilerun/models/screen/geometry.py b/mobilerun/models/screen/geometry.py new file mode 100644 index 000000000..87fae7bb1 --- /dev/null +++ b/mobilerun/models/screen/geometry.py @@ -0,0 +1,66 @@ +"""Display and input coordinate mapping.""" + +from math import inf, isfinite, nextafter +from typing import ClassVar + +from pydantic import BaseModel, ConfigDict + +Bounds = tuple[int, int, int, int] +Size = tuple[int, int] + + +class ModelGeometry(BaseModel): + """The coordinate space shown to a model and its corresponding input space.""" + + NORMALIZED_MAX: ClassVar[int] = 1000 + model_config = ConfigDict(frozen=True) + input_size: Size | None = None + model_size: Size | None = None + normalized: bool = False + + def _sizes(self) -> tuple[Size, Size]: + if self.input_size is None or min(self.input_size) <= 0: + raise ValueError("Screen input dimensions are unavailable") + model = ( + (self.NORMALIZED_MAX, self.NORMALIZED_MAX) + if self.normalized + else self.model_size or self.input_size + ) + return self.input_size, model + + def to_device(self, x: float, y: float) -> tuple[int, int]: + """Convert a model point to device coordinates, rejecting out-of-screen input.""" + (width, height), (cols, rows) = self._sizes() + if not (0 <= x <= cols and 0 <= y <= rows) or ( + not self.normalized and (x >= cols or y >= rows) + ): + raise ValueError("Point is outside the model coordinate space") + if self.normalized: + # Undo float roundoff at pixel boundaries without rounding arbitrary points up. + return min(width - 1, int(nextafter(x * width / cols, inf))), min( + height - 1, int(nextafter(y * height / rows, inf)) + ) + return min(width - 1, round(x * width / cols)), min( + height - 1, round(y * height / rows) + ) + + def from_device(self, x: float, y: float) -> tuple[float, float]: + """Convert an in-screen native point without rounding.""" + (width, height), (cols, rows) = self._sizes() + if not (isfinite(x) and isfinite(y) and 0 <= x < width and 0 <= y < height): + raise ValueError("Point is outside the device coordinate space") + return x * cols / width, y * rows / height + + def project_bounds(self, bounds: Bounds | None) -> Bounds | None: + """Scale half-open bounds for display, including off-screen edges.""" + if bounds is None or self.input_size is None: + return bounds + (width, height), (cols, rows) = self._sizes() + left, top, right, bottom = bounds + quantize = int if self.normalized else round + return ( + quantize(left * cols / width), + quantize(top * rows / height), + quantize(right * cols / width), + quantize(bottom * rows / height), + ) diff --git a/mobilerun/models/screen/view.py b/mobilerun/models/screen/view.py new file mode 100644 index 000000000..57928837c --- /dev/null +++ b/mobilerun/models/screen/view.py @@ -0,0 +1,55 @@ +"""Typed model-facing screen data, independent of native action targets.""" + +from collections.abc import Callable +from typing import Any + +from pydantic import ( + BaseModel, + ConfigDict, + Field, + JsonValue, + PrivateAttr, + SerializationInfo, + SerializerFunctionWrapHandler, + model_serializer, +) +from pydantic_core import to_jsonable_python + +from .element import ProjectedElement +from .geometry import ModelGeometry + + +class ScreenView(BaseModel): + """Sanitized prompt evidence, without screenshots or native handles.""" + + model_config = ConfigDict(frozen=True, hide_input_in_errors=True) + formatted_text: str = Field(default="", repr=False) + focused_text: str = Field(default="", repr=False) + phone_state: dict[str, JsonValue] = Field(default_factory=dict, repr=False) + elements: tuple[ProjectedElement, ...] = Field(default=(), repr=False) + focused_index: int | None = Field(default=None, repr=False) + geometry: ModelGeometry = Field(default_factory=ModelGeometry, repr=False) + _mask_projection: Callable[[JsonValue], bool] | None = PrivateAttr(default=None) + + def element(self, index: int) -> ProjectedElement | None: + """Find a prompt row by its displayed index.""" + return next((row for row in self.elements if row.index == index), None) + + @property + def opaque(self) -> bool: + """An opaque credential may be present even without a known literal.""" + return self._mask_projection is not None and self._mask_projection(None) + + @model_serializer(mode="wrap") + def _serialize( + self, handler: SerializerFunctionWrapHandler, info: SerializationInfo + ) -> dict[str, Any]: + if not self.opaque: + data = handler(self) + if self._mask_projection is None: + return data + if not self._mask_projection(to_jsonable_python(data)): + return data + return ScreenView(formatted_text="***", focused_text="***").model_dump( + mode=info.mode + ) diff --git a/mobilerun/models/tool_call.py b/mobilerun/models/tool_call.py new file mode 100644 index 000000000..4ac97a68e --- /dev/null +++ b/mobilerun/models/tool_call.py @@ -0,0 +1,10 @@ +"""Value-free metadata sent to tool dispatch guards.""" + +from dataclasses import dataclass + + +@dataclass(frozen=True) +class ToolCallInfo: + name: str + canonical_name: str + sensitive_parameters: frozenset[str] diff --git a/mobilerun/models/ui.py b/mobilerun/models/ui.py deleted file mode 100644 index a17dfb5b9..000000000 --- a/mobilerun/models/ui.py +++ /dev/null @@ -1,17 +0,0 @@ -"""UI snapshot value types.""" - -from typing import TypedDict - - -class UIElement(TypedDict, total=False): - """Element data exposed by UI state snapshots.""" - - index: int - text: str - className: str - resourceId: str - bounds: str - checkedState: str - displayBounds: str - tapBlockers: list[str] - children: list["UIElement"] diff --git a/mobilerun/models/webhooks.py b/mobilerun/models/webhooks.py index 6627234a9..9935f96f4 100644 --- a/mobilerun/models/webhooks.py +++ b/mobilerun/models/webhooks.py @@ -8,7 +8,7 @@ @dataclass(frozen=True) class WebhookEndpoint: - """A destination, not proof of ownership. A signing secret is returned only on creation.""" + """Endpoint metadata; the signing secret is returned only on creation.""" id: str kind: Literal["http", "integration"] diff --git a/mobilerun/sandbox/README.md b/mobilerun/sandbox/README.md index e5702fd7d..93072de28 100644 --- a/mobilerun/sandbox/README.md +++ b/mobilerun/sandbox/README.md @@ -330,16 +330,16 @@ to identify resources and verify ownership before changing or deleting them. | File | Responsibility | | --- | --- | | [`__init__.py`](__init__.py), [`_runtime.py`](_runtime.py) | Public API and lazy worker-runtime exports | -| [`app.py`](app.py) | Cloud decorator and synchronous `deploy`, `Remote`, and `Run` APIs | -| [`packaging.py`](packaging.py) | Static declaration parsing, extraction, and local inspection | -| [`deployment.py`](deployment.py) | Async first deploy, redeploy, and workflow cutover | +| [`app.py`](app.py), [`handles/`](handles/) | Synchronous deploy entry point, cloud decorator, and remote/run handles | +| [`packaging.py`](packaging.py), [`helpers/`](helpers/) | Packaging, source extraction, and local contract inspection | +| [`deployment.py`](deployment.py), [`deployments/`](deployments/) | Async deploy entry point; initial staging, cutover planning, execution, and recovery | | [`receipts.py`](receipts.py) | Account scope, the local receipt store, and deploy checkpoints | | [`documents.py`](documents.py) | Workflow document building and comparison | | [`flows.py`](flows.py) | Remote function and flow lookup, ownership checks, webhook checks, and enable/disable | | [`execution.py`](execution.py) | Endpoint runs, run polling, results, and logs | | [`cleanup.py`](cleanup.py) | Removal of resources recorded in a receipt | | [`billing.py`](billing.py) | Paid-mode check shared by deploy, run, and activation | -| [`clients.py`](clients.py) | Sandbox's async SDK adapter; uses shared [cloud client and billing helpers](../clients/cloud/README.md), closes clients it creates, and leaves injected clients caller-owned | +| [`clients/`](clients/) | Resource-scoped async SDK transport; owns only the clients it creates | | [`models.py`](models.py), [`errors.py`](errors.py), [`settings.py`](settings.py) | Declarations, receipts, errors, and defaults | | [`cli/`](cli/) | Removable `mobilerun sandbox` command group | diff --git a/mobilerun/sandbox/__init__.py b/mobilerun/sandbox/__init__.py index b4271335c..65954ec90 100644 --- a/mobilerun/sandbox/__init__.py +++ b/mobilerun/sandbox/__init__.py @@ -40,11 +40,20 @@ ) +_HANDLE_EXPORTS = { + "cloud": (".handles.cloud", "cloud"), + "deploy": (".app", "deploy"), + "Remote": (".handles.remote", "Remote"), + "Run": (".handles.run", "Run"), + "routine": (".helpers.routine", "routine"), +} + + def __getattr__(name: str) -> Any: - if name in ("cloud", "deploy", "Remote", "Run"): - return getattr(import_module(".app", __name__), name) + if name in _HANDLE_EXPORTS: + module, attribute = _HANDLE_EXPORTS[name] + return getattr(import_module(module, __name__), attribute) if name in ( - "routine", "DeploymentReceipt", "Endpoint", "OwnershipReceipt", diff --git a/mobilerun/sandbox/app.py b/mobilerun/sandbox/app.py index ab5c11a06..b9df84d11 100644 --- a/mobilerun/sandbox/app.py +++ b/mobilerun/sandbox/app.py @@ -1,486 +1,16 @@ -"""Cloud declarations and lazy synchronous handles for deployed functions.""" +"""Synchronous deployment entry point.""" -from __future__ import annotations - -import asyncio -import inspect -import json -import time -from collections.abc import Callable, Coroutine, Mapping -from copy import deepcopy -from datetime import datetime -from functools import partial from pathlib import Path -from typing import Any, TypeVar, get_args, get_origin, get_type_hints - -from pydantic import AliasChoices, AliasPath, BaseModel, TypeAdapter, ValidationError -from pydantic_core import ErrorType, InitErrorDetails, PydanticCustomError -from mobilerun.clients.cloud.billing import with_billing_retry from mobilerun.models.billing import Billing +from mobilerun.utils.billing.retry import with_billing_retry from . import deployment as _deployment -from . import execution as _execution -from . import flows as _flows -from .billing import check_deploy_billing -from .errors import SandboxDeclarationError, SandboxDeploymentError, SandboxRunError -from .models import ( - FILES_RETURN_ERROR, - CloudDeclaration, - DeploymentReceipt, - Endpoint, - resolve_billing, - validate_device, -) +from .billing import check_deploy_billing, resolve_billing +from .helpers.declaration_values import validate_device +from .helpers.sync import run_sync +from .models import DeploymentReceipt from .packaging import package -from .settings import get_sandbox_settings - -JSON = dict[str, Any] -F = TypeVar("F", bound=Callable[..., Any]) -T = TypeVar("T") -_BUILTIN_ERROR_CODES = frozenset(get_args(ErrorType)) - - -def _sync(operation: Callable[[], Coroutine[Any, Any, T]]) -> T: - """Reject a running loop before constructing the coroutine.""" - try: - asyncio.get_running_loop() - except RuntimeError: - pass - else: - raise RuntimeError( - "The synchronous sandbox API cannot run inside an active event loop" - ) - return asyncio.run(operation()) - - -def _write_alias(container: Any, path: list[str | int], value: Any) -> None: - key, *rest = path - if isinstance(key, str) and isinstance(container, dict): - pass - elif isinstance(key, int) and key >= 0 and isinstance(container, list): - if key >= len(container): - container.extend([None] * (key + 1 - len(container))) - else: - raise ValueError("Unsupported or conflicting alias path") - if not rest: - container[key] = value - return - if isinstance(container, dict): - child = container.get(key) - else: - child = container[key] - if child is None: - child = {} if isinstance(rest[0], str) else [] - container[key] = child - _write_alias(child, rest, value) - - -def _validation_keys(value: Any, dumped: Any) -> Any: - """Shape dumped model fields according to their validation aliases.""" - if isinstance(value, BaseModel) and isinstance(dumped, dict): - fields = type(value).model_fields - result = {key: entry for key, entry in dumped.items() if key not in fields} - for name, field in fields.items(): - if name not in dumped: - continue - alias = field.validation_alias - if isinstance(alias, AliasChoices): - alias = alias.choices[0] - path = ( - alias.path - if isinstance(alias, AliasPath) - else [name if alias is None else alias] - ) - _write_alias( - result, path, _validation_keys(getattr(value, name), dumped[name]) - ) - return result - if ( - isinstance(value, (list, tuple)) - and isinstance(dumped, list) - and len(value) == len(dumped) - ): - return [ - _validation_keys(child, entry) - for child, entry in zip(value, dumped, strict=True) - ] - if isinstance(value, dict) and isinstance(dumped, dict): - return { - key: _validation_keys(value.get(key), entry) - for key, entry in dumped.items() - } - return dumped - - -def _safe_location( - model: Any, location: tuple[str | int, ...], *, extra_field: bool -) -> tuple[str | int, ...]: - """Keep declared model fields and sequence indices; unknown path segments are data.""" - result: list[str | int] = [] - for part in location: - origin, args = get_origin(model), get_args(model) - safe: str | int = "" - child = None - if ( - isinstance(model, type) - and issubclass(model, BaseModel) - and not model.__pydantic_root_model__ - ): - # An alias path or ambiguous alias may point to a different shape. - fields = model.model_fields - if isinstance(part, str) and all( - f.validation_alias is None or isinstance(f.validation_alias, str) - for f in fields.values() - ): - matches = [ - f - for name, f in fields.items() - if part in (name, f.validation_alias) - ] - if len(matches) == 1: - safe, child = part, matches[0].annotation - elif origin is list and isinstance(part, int) and part >= 0: - safe, child = part, args[0] if args else None - elif origin is tuple and isinstance(part, int) and part >= 0: - safe = part - child = ( - args[0] - if args[-1:] == (Ellipsis,) - else args[part] if part < len(args) else None - ) - elif origin is dict and len(args) == 2: - child = args[1] - result.append(safe) - model = child - if extra_field and result: - result[-1] = "" - return tuple(result) - - -def _validate_typed(validate: Callable[[Any], T], value: Any, model: Any) -> T: - """Preserve validation locations and types, never values or validator messages.""" - try: - return validate(value) - except ValidationError as exc: - errors: list[InitErrorDetails] = [] - for error in exc.errors( - include_input=False, include_context=False, include_url=False - ): - code = error["type"] if error["type"] in _BUILTIN_ERROR_CODES else "invalid" - errors.append( - { - "type": PydanticCustomError(code, code), - "loc": _safe_location( - model, - error["loc"], - extra_field=error["type"] == "extra_forbidden", - ), - "input": None, - } - ) - # Raise outside the handler so the original exception is not retained as context. - raise ValidationError.from_exception_data( - "Sandbox validation", errors, hide_input=True - ) - - -def _validation_payload(value: BaseModel) -> JSON: - message = "Sandbox input could not round-trip through its model's JSON validation" - try: - payload = _validation_keys( - value, value.model_dump(mode="json", by_alias=False, round_trip=True) - ) - if isinstance(payload, dict): - # Match the worker's JSON validation, including strict model types. - rendered = json.dumps(payload, allow_nan=False) - if type(value).model_validate_json(rendered) == value: - return payload - except (TypeError, ValueError, OverflowError, RecursionError): - raise SandboxDeclarationError(message) from None - raise SandboxDeclarationError(message) - - -class Remote: - """A named function handle; lookup itself does not contact the cloud.""" - - def __init__( - self, - name: str, - input_type: type[BaseModel] | None = None, - output_type: type[BaseModel] | None = None, - *, - billing: Billing | str | None = None, - ) -> None: - self.name = name - self.input_type = input_type - self.output_type = output_type - self._billing = resolve_billing(billing) - - def _mode(self, billing: Billing | str | None) -> Billing: - return self._billing if billing is None else resolve_billing(billing) - - @property - def _description(self) -> JSON: - return _sync(partial(_flows.describe_remote, self.name, billing=self._billing)) - - @property - def function_id(self) -> str: - return self._description["function_id"] - - @property - def version(self) -> int: - return self._description["version"] - - @property - def flow_id(self) -> str: - flow_id = self._description.get("flow_id") - if flow_id is None: - raise SandboxDeploymentError( - "Sandbox flow not found", missing_deployment=True - ) - return flow_id - - @property - def endpoint(self) -> Endpoint: - endpoint = self._description.get("endpoint") - if endpoint is None: - raise SandboxDeploymentError( - "Sandbox endpoint not found", missing_deployment=True - ) - return Endpoint(**endpoint) - - def fire( - self, - input: Mapping[str, Any] | BaseModel | None = None, - *, - billing: Billing | str | None = None, - **values: Any, - ) -> Run: - """Enqueue a run without waiting for execution to start.""" - if input is not None and values: - raise TypeError("Pass either input= or keyword payload values, not both") - if input is None: - data: Mapping[str, Any] | BaseModel = values - elif not isinstance(input, (BaseModel, Mapping)): - raise TypeError("input must be a mapping or a pydantic BaseModel") - else: - data = input - if self.input_type is not None and not isinstance(data, self.input_type): - if isinstance(data, BaseModel): - data = _validation_payload(data) - data = _validate_typed( - self.input_type.model_validate, data, self.input_type - ) - payload = ( - _validation_payload(data) if isinstance(data, BaseModel) else dict(data) - ) - fired, mode = _sync( - partial( - with_billing_retry, - lambda attempt: _execution.fire_remote( - self.name, payload, billing=attempt - ), - self._mode(billing), - ) - ) - run = Run(self, invocation_id=fired["invocation_id"]) - run._billing = mode - return run - - def __call__( - self, - input: Mapping[str, Any] | BaseModel | None = None, - *, - billing: Billing | str | None = None, - **values: Any, - ) -> Any: - return self.fire(input=input, billing=billing, **values).result() - - def runs( - self, limit: int = 10, *, billing: Billing | str | None = None - ) -> list[Run]: - """Read recent executions, newest first.""" - if limit <= 0: - return [] - mode = self._mode(billing) - rows = _sync(partial(_execution.recent_runs, self.name, limit, billing=mode)) - runs = [] - for row in rows: - run = Run(self, execution_id=row["id"], snapshot=row) - run._billing = mode - runs.append(run) - return runs - - def enable( - self, *, billing: Billing | str | None = None, yes: bool = False - ) -> JSON: - """Enable this owned flow.""" - result, _ = _sync( - partial( - with_billing_retry, - lambda attempt: _flows.set_enabled(self.name, True, billing=attempt), - self._mode(billing), - yes=yes, - ) - ) - return result - - def disable(self, *, billing: Billing | str | None = None) -> JSON: - """Pause this owned flow until enabled again.""" - return _sync( - partial(_flows.set_enabled, self.name, False, billing=self._mode(billing)) - ) - - -class Run: - """A run keyed by invocation or execution ID.""" - - def __init__( - self, - remote: Remote, - *, - invocation_id: str | None = None, - execution_id: str | None = None, - snapshot: JSON | None = None, - ) -> None: - self.remote = remote - self._snapshot = deepcopy(snapshot) if snapshot is not None else {} - self.invocation_id = invocation_id or self._snapshot.get("invocationId") - self._id = execution_id or self._snapshot.get("id") - self._billing = remote._billing - - @property - def id(self) -> str: - if self._id is None: - if self.invocation_id is None: - raise SandboxRunError("Provide an invocation or execution ID") - self._id = _sync( - partial( - _execution.resolve_execution, - self.remote.name, - self.invocation_id, - deadline=time.monotonic() - + get_sandbox_settings().MOBILERUN_SANDBOX_RUN_TIMEOUT, - billing=self._billing, - ) - ) - return self._id - - @property - def status(self) -> str: - self._snapshot = _sync( - partial(_execution.execution_snapshot, self.id, billing=self._billing) - ) - return self._snapshot["status"] - - @property - def started_at(self) -> str | None: - return self._snapshot.get("startedAt") - - @property - def ended_at(self) -> str | None: - return self._snapshot.get("finishedAt") - - @property - def duration(self) -> float | None: - start, end = self.started_at, self.ended_at - if not start or not end: - return None - return ( - datetime.fromisoformat(end) - datetime.fromisoformat(start) - ).total_seconds() - - @property - def snapshot(self) -> JSON: - return deepcopy(self._snapshot) - - def result(self, timeout: float | None = None) -> Any: - """Wait for completion and validate the function result when typed.""" - if timeout is None: - timeout = get_sandbox_settings().MOBILERUN_SANDBOX_RUN_TIMEOUT - self._snapshot = _sync( - partial( - _execution.wait_result, - self.remote.name, - invocation_id=self.invocation_id, - execution_id=self._id, - timeout=timeout, - billing=self._billing, - ) - ) - self._id = self._snapshot["id"] - # The orchestration helper validates the execution and function steps. - step = next( - step - for step in self._snapshot["result"]["steps"] - if isinstance(step, dict) and step.get("uses") == "functions.run" - ) - value = step["body"]["result"] - output_type = self.remote.output_type - return ( - _validate_typed( - TypeAdapter(output_type).validate_json, json.dumps(value), output_type - ) - if output_type is not None - else deepcopy(value) - ) - - def logs(self) -> str: - """Return execution logs through the cloud boundary.""" - return _sync(partial(_execution.execution_logs, self.id, billing=self._billing)) - - -class Cloud: - """Register local scripts or look up an untyped remote by deployment name.""" - - def __call__( - self, - name: str, - schedule: str | None = None, - device: str | None = None, - endpoint: bool | None = None, - webhook: str | None = None, - *, - files: dict[str, str] | None = None, - files_folder: str | None = None, - ) -> Callable[[F], F]: - CloudDeclaration( - name, - schedule=schedule, - device=device, - endpoint=endpoint, - webhook=webhook, - files=files, - files_folder=files_folder, - ).validate() - has_files = bool(files) - - def decorate(func: F) -> F: - from ._runtime import EntryPointError, script - - hints = get_type_hints(func) if has_files else None - if hints is not None: - output = hints.get("return") - if not isinstance(output, type) or not issubclass(output, BaseModel): - raise SandboxDeclarationError(FILES_RETURN_ERROR) - try: - script(func) - except EntryPointError as exc: - raise SandboxDeclarationError(str(exc)) from exc - if hints is None: - hints = get_type_hints(func) - first = next(iter(inspect.signature(func).parameters)) - func.remote = Remote(name, hints[first], hints.get("return")) # type: ignore[attr-defined] - return func - - return decorate - - def __getitem__(self, name: str) -> Remote: - return Remote(name) - - -cloud = Cloud() def deploy( @@ -507,4 +37,4 @@ async def deploy_inspected() -> DeploymentReceipt: artifact=artifact, ) - return _sync(deploy_inspected) + return run_sync(deploy_inspected) diff --git a/mobilerun/sandbox/billing.py b/mobilerun/sandbox/billing.py index 2b53fcd2a..4fbb9a2c7 100644 --- a/mobilerun/sandbox/billing.py +++ b/mobilerun/sandbox/billing.py @@ -1,14 +1,22 @@ """Billing checks shared by sandbox deploy, run and activation.""" -from mobilerun.clients.cloud.billing import requires +from mobilerun.clients.cloud.billing_policy import BillingPolicy +from mobilerun.config.settings import get_settings from mobilerun.models.billing import Billing -@requires(Billing.PAID, operation="Sandbox deployment, endpoint run, or activation") def require_paid(*, billing: Billing) -> None: """Check commerce authorization before creating local or remote resources.""" + BillingPolicy(billing).require( + Billing.PAID, "Sandbox deployment, endpoint run, or activation" + ) async def check_deploy_billing(billing: Billing) -> None: """Let interactive callers retry authorization without retrying inspection or deploy.""" require_paid(billing=billing) + + +def resolve_billing(billing: Billing | str | None) -> Billing: + """Resolve explicit billing before the shared environment default.""" + return Billing(billing) if billing is not None else get_settings().MOBILERUN_BILLING diff --git a/mobilerun/sandbox/cleanup.py b/mobilerun/sandbox/cleanup.py index 9fec3de22..40bb324fd 100644 --- a/mobilerun/sandbox/cleanup.py +++ b/mobilerun/sandbox/cleanup.py @@ -3,9 +3,10 @@ from mobilerun.models.billing import Billing from . import clients +from .billing import resolve_billing from .errors import SandboxDeploymentConflict, SandboxDeploymentError from .flows import delete_verified, get_flow, require_unshared, valid_id -from .models import OwnershipReceipt, resolve_billing +from .models import OwnershipReceipt from .receipts import ( ReceiptStore, checkpoint, diff --git a/mobilerun/sandbox/cli/README.md b/mobilerun/sandbox/cli/README.md index e42ea8143..aaf242cda 100644 --- a/mobilerun/sandbox/cli/README.md +++ b/mobilerun/sandbox/cli/README.md @@ -28,4 +28,7 @@ See the [sandbox guide](../README.md) for setup, billing, and examples. | --- | --- | | `__init__.py` | Sandbox CLI package marker. | | `group.py` | Click command group and local `path` command. | -| `commands.py` | Cloud command options, prompts, and output. | +| `deploy.py`, `fire.py` | Deploy scripts and invoke an endpoint. | +| `list.py`, `runs.py` | List functions and executions. | +| `activation.py` | Confirm and batch enable or disable owned flows. | +| `helpers/` | Shared options, prompts, and billing messages. | diff --git a/mobilerun/sandbox/cli/activation.py b/mobilerun/sandbox/cli/activation.py new file mode 100644 index 000000000..68e16ac33 --- /dev/null +++ b/mobilerun/sandbox/cli/activation.py @@ -0,0 +1,106 @@ +"""Enable and disable owned sandbox flows.""" + +import json + +import click + +from mobilerun.cli.base import render +from mobilerun.cli.base.billing import invoke_with_billing +from mobilerun.cli.base.errors import safe_error_message +from mobilerun.cli.base.run import coro +from mobilerun.cli.base.safety import confirm_action_async +from mobilerun.errors.cloud import BillingRequired +from mobilerun.models.billing import Billing + +from ..billing import resolve_billing +from ..errors import TargetedBillingRequired +from .helpers.deployment_argument import DeploymentArgument +from .helpers.options import billing_option, json_option, yes_option + + +async def _set_enabled( + names: tuple[str, ...], enabled: bool, billing: str | None, yes: bool, as_json: bool +) -> None: + from mobilerun.sandbox.billing import require_paid + from mobilerun.sandbox.flows import set_enabled + + mode = resolve_billing(billing) + verb = "Enable" if enabled else "Disable" + names = tuple(dict.fromkeys(names)) + targets = ", ".join(map(repr, names)) + warning = f"{verb} {targets}. Billing: {mode}." + if enabled: + summary = f"Enable sandbox flows {targets}" + + async def authorize(attempt: Billing) -> None: + try: + require_paid(billing=attempt) + except BillingRequired as exc: + raise TargetedBillingRequired(exc, summary) from exc + + _, mode = await invoke_with_billing( + authorize, mode, yes=yes, confirm_paid=summary + ) + else: + try: + await confirm_action_async( + "disable sandbox flows", mode, warning, yes=yes, err=True + ) + except click.exceptions.Exit as exc: + if as_json and exc.exit_code == 0: + click.echo("[]") + raise + + results = [] + for name in names: + try: + await set_enabled(name, enabled, billing=mode) + except (BillingRequired, click.Abort, click.exceptions.Exit): + raise + except Exception as exc: + status = "failed" + render.error(f"{name!r}: {safe_error_message(exc)}") + else: + status = "enabled" if enabled else "disabled" + if not as_json: + render.success(f"{name!r}: {status}") + results.append({"name": name, "status": status}) + if as_json: + click.echo(json.dumps(results)) + if any(item["status"] == "failed" for item in results): + click.get_current_context().exit(1) + + +@click.command("enable") +@click.argument( + "name", + cls=DeploymentArgument, + nargs=-1, + required=True, + metavar="NAME...", + requires_consent=True, +) +@billing_option +@yes_option +@json_option +@coro +async def enable_command( + name: tuple[str, ...], billing: str | None, yes: bool, as_json: bool +) -> None: + """Enable one or more owned sandbox flows.""" + await _set_enabled(name, True, billing, yes, as_json) + + +@click.command("disable") +@click.argument( + "name", cls=DeploymentArgument, nargs=-1, required=True, metavar="NAME..." +) +@billing_option +@yes_option +@json_option +@coro +async def disable_command( + name: tuple[str, ...], billing: str | None, yes: bool, as_json: bool +) -> None: + """Disable one or more owned sandbox flows.""" + await _set_enabled(name, False, billing, yes, as_json) diff --git a/mobilerun/sandbox/cli/commands.py b/mobilerun/sandbox/cli/commands.py deleted file mode 100644 index 706ddd343..000000000 --- a/mobilerun/sandbox/cli/commands.py +++ /dev/null @@ -1,515 +0,0 @@ -"""Sandbox operations with explicit CLI authorization.""" - -import asyncio -import json -import shlex -import sys -from contextlib import nullcontext, redirect_stdout -from datetime import datetime -from pathlib import Path -from typing import TYPE_CHECKING, Any - -import click - -from mobilerun.cli.base import menu, render -from mobilerun.cli.base.billing import invoke_with_billing, require_consent_possible -from mobilerun.cli.base.errors import safe_error_message -from mobilerun.cli.base.prompts import SelectChoice, select_prompt_async -from mobilerun.cli.base.run import coro -from mobilerun.cli.base.safety import confirm_action_async -from mobilerun.errors.cloud import BillingRequired -from mobilerun.models.billing import Billing - -if TYPE_CHECKING: - from mobilerun.sandbox.models import DeploymentReceipt - - -class _TargetedBillingRequired(BillingRequired): - def __init__(self, error: BillingRequired, target_summary: str) -> None: - super().__init__( - needed=error.needed, given=error.given, operation=error.operation - ) - self.target_summary = target_summary - - @property - def confirmation(self) -> str: - return f"{self.target_summary}. {super().confirmation}" - - -_billing_option = click.option( - "--billing", - type=click.Choice([mode.value for mode in Billing]), - help="Billing mode.", -) -_json_option = click.option("--json", "as_json", is_flag=True, help="Output JSON.") -_yes_option = click.option( - "--yes", is_flag=True, help="Confirm the action without prompting." -) -_source_file = click.Path(exists=True, dir_okay=False, readable=True, path_type=Path) - - -class _StderrArgument(menu.PromptingArgument): - """Keep required text prompts off stdout, including in JSON mode.""" - - def process_value(self, ctx: click.Context, value: Any) -> Any: - if ( - self.value_is_missing(value) - and not ctx.resilient_parsing - and menu.is_interactive() - ): - try: - with redirect_stdout(sys.stderr): - value = menu.text_prompt(self.prompt_label).strip() - except (KeyboardInterrupt, click.Abort, EOFError): - ctx.exit(130) - if not value: - click.echo("Cancelled.", err=True) - ctx.exit(0) - return super().process_value(ctx, value) - - -def _resolve_mode(billing: str | None) -> Billing: - from mobilerun.sandbox.models import resolve_billing - - return resolve_billing(billing) - - -def _deployment_choices(ctx: click.Context) -> list[SelectChoice]: - from mobilerun.sandbox.flows import list_deployments - - mode = _resolve_mode(ctx.params.get("billing")) - records = asyncio.run(list_deployments(billing=mode)) - choices = [] - for item in records: - name = item.get("name") - if not isinstance(name, str) or not name: - continue - latest = item.get("latestVersion", {}) - version = latest.get("version", "—") - status = render.status(latest.get("status")).plain - function_id = item["id"] - short_id = f"{function_id[:8]}…" if len(function_id) > 8 else function_id - choices.append( - SelectChoice(name, f"{name} · {short_id} · {version} · {status}") - ) - return choices - - -class _DeploymentArgument(menu.PromptingArgument): - """Select deployed names without the generic argument's free-text fallback.""" - - def __init__( - self, *args: Any, requires_consent: bool = False, **kwargs: Any - ) -> None: - super().__init__(*args, **kwargs) - self.requires_consent = requires_consent - - def process_value(self, ctx: click.Context, value: Any) -> Any: - if ( - not self.value_is_missing(value) - or ctx.resilient_parsing - or not menu.is_interactive() - ): - return super().process_value(ctx, value) - - batch = self.nargs == -1 - if self.requires_consent: - # Click processes explicitly supplied options before omitted arguments. - # Refuse before the remote lookup when billing consent cannot be asked. - require_consent_possible(yes=ctx.params.get("yes", False)) - choices = _deployment_choices(ctx) - try: - with redirect_stdout(sys.stderr): - if not choices: - click.echo("No deployed sandbox functions found.") - elif batch: - value = tuple( - menu.multi_select_prompt("Select sandbox functions", choices) - or () - ) - else: - value = menu.select_prompt("Name", choices) - except (KeyboardInterrupt, click.Abort, EOFError): - ctx.exit(130) - if not choices or not value: - if choices: - click.echo("Cancelled.", err=True) - if batch and ctx.params.get("as_json"): - click.echo("[]") - ctx.exit(0) - return super().process_value(ctx, value) - - -_name_argument = click.argument("name", cls=_DeploymentArgument) -_names_argument = click.argument( - "name", cls=_DeploymentArgument, nargs=-1, required=True, metavar="NAME..." -) - - -async def _pick_device(*, as_json: bool, yes: bool) -> tuple[str | None, bool]: - from mobilerun.cli.devices.base.discovery import discover_devices - - if not menu.is_interactive(): - raise click.UsageError( - "Pass --device ID or --device-free for a scheduled deployment." - ) - require_consent_possible(yes=yes) - devices = await discover_devices(local=False, strict=True) - # Disjoint choice values keep the device-free option distinct from device IDs. - cloud = {f"device:{item.id}": item for item in devices if item.source == "cloud"} - choices = [ - SelectChoice( - value, item.name or item.id, f"{item.id} · {item.state or 'unknown'}" - ) - for value, item in cloud.items() - ] - choices.append(SelectChoice("device-free", "Device-free")) - with redirect_stdout(sys.stderr) if as_json else nullcontext(): - selected = await select_prompt_async("Choose a cloud device", choices) - if selected is None: - click.echo("Cancelled.", err=True) - click.get_current_context().exit(0) - return (None, True) if selected == "device-free" else (cloud[selected].id, False) - - -def _sample_value(schema: dict[str, Any]) -> Any: - """Illustrate the shape without publishing literal defaults or examples.""" - for key in ("anyOf", "oneOf"): - if schema.get(key): - return _sample_value(schema[key][0]) - kind = schema.get("type") - if kind == "object" or "properties" in schema: - properties = schema.get("properties", {}) - return { - key: _sample_value(properties.get(key, {})) - for key in schema.get("required", []) - } - return ( - {"string": "", "integer": 0, "number": 0, "boolean": False, "array": []}.get( - kind - ) - if isinstance(kind, str) - else None - ) - - -def _endpoint_contract(receipt: "DeploymentReceipt", schema: dict[str, Any]) -> None: - endpoint = receipt.endpoint - if endpoint is None: - return - base_url = endpoint.url.rsplit("/triggers/", 1)[0] - sample = _sample_value(schema) or {} - click.echo( - f"Endpoint: POST {endpoint.url}\n" - "Authorization: Bearer (use MOBILERUN_API_KEY)\n" - "Idempotency-Key: (optional)\n" - "Content-Type: application/json\n" - f"Example body: {json.dumps({'payload': sample})}\n" - "HTTP 202 returns invocationId, enqueuedCount, and deduplicated, not the result.\n" - f"Poll GET {base_url}/executions?flowId={receipt.flow_id}&invocationId=;\n" - f"then GET {base_url}/executions/ for result.steps[].body.result.\n" - f"List recent runs: mobilerun sandbox runs {shlex.quote(receipt.name)}" - ) - - -@click.command("deploy") -@click.argument("file", cls=_StderrArgument, prompt_label="File", type=_source_file) -@click.option("--device", metavar="ID", help="Use an existing cloud device.") -@click.option("--device-free", is_flag=True, help="Deploy without a device.") -@_billing_option -@_yes_option -@_json_option -@coro -async def deploy_command( - file: Path, - device: str | None, - device_free: bool, - billing: str | None, - yes: bool, - as_json: bool, -) -> None: - """Deploy a cloud function as an endpoint by default.""" - from mobilerun.sandbox.billing import check_deploy_billing - from mobilerun.sandbox.deployment import deploy_file - from mobilerun.sandbox.packaging import package, read_declaration - - if device is not None and device_free: - raise click.UsageError("Choose either --device or --device-free, not both.") - if device is not None and not device.strip(): - raise click.UsageError("--device requires a nonempty ID.") - try: - source = file.read_text(encoding="utf-8") - except (OSError, UnicodeError) as exc: - raise click.ClickException(f"Cannot read source: {file}") from exc - declaration = read_declaration(file, source=source) - if not device_free and device is None: - device = declaration.device - if device is None and declaration.schedule is not None: - device, device_free = await _pick_device(as_json=as_json, yes=yes) - - target = f"device {device!r}" if device is not None else "device-free" - summary = f"Deploy {declaration.name!r} ({target})" - if declaration.schedule is not None: - summary += f" on schedule {declaration.schedule!r}" - - async def authorize(attempt: Billing) -> None: - try: - await check_deploy_billing(attempt) - except BillingRequired as exc: - raise _TargetedBillingRequired(exc, summary) from exc - - _, mode = await invoke_with_billing( - authorize, _resolve_mode(billing), yes=yes, confirm_paid=summary - ) - artifact = package(file, source=source) - - receipt = await deploy_file( - file, - device=device, - device_free=device_free, - billing=mode, - artifact=artifact, - ) - if as_json: - click.echo(json.dumps(receipt.to_dict())) - else: - render.success(f"{receipt.name} v{receipt.version}: {receipt.status}") - fields = [("Function", receipt.function_id)] - if receipt.flow_id: - fields.append(("Flow", receipt.flow_id)) - render.kv(fields) - _endpoint_contract(receipt, artifact.input_schema) - for warning in receipt.warnings: - render.warn(warning) - - -@click.command("list") -@_billing_option -@_json_option -@coro -async def list_command(billing: str | None, as_json: bool) -> None: - """List deployed sandbox functions.""" - from mobilerun.sandbox.flows import list_deployments - - records = await list_deployments(billing=_resolve_mode(billing)) - if as_json: - click.echo(json.dumps(records)) - elif not records: - render.empty( - "sandbox functions", "Run `mobilerun sandbox deploy FILE` to deploy one." - ) - else: - render.heading(len(records), "sandbox function") - render.table( - ( - item.get("name"), - item["id"], - latest.get("version"), - render.status(latest.get("status")), - ) - for item in records - for latest in [item.get("latestVersion", {})] - ) - - -def _invalid_constant(value: str) -> None: - raise ValueError("Non-finite JSON number") - - -def _payload(input_json: str | None, input_file: Path | None) -> dict[str, Any]: - if input_json is not None and input_file is not None: - raise click.UsageError("Choose either --input or --input-file, not both.") - if input_file is not None: - try: - input_json = input_file.read_text(encoding="utf-8") - except (OSError, UnicodeError) as exc: - raise click.UsageError("Cannot read --input-file as UTF-8.") from exc - if input_json is None: - return {} - message = "Sandbox input must be a valid JSON object." - try: - payload = json.loads(input_json, parse_constant=_invalid_constant) - if not isinstance(payload, dict): - raise ValueError - # Python also decodes overflowing exponents as infinity. - json.dumps(payload, allow_nan=False) - except (ValueError, RecursionError) as exc: - raise click.UsageError(message) from exc - return payload - - -@click.command("fire") -@click.argument("name", cls=_DeploymentArgument, requires_consent=True) -@click.option("--input", "input_json", metavar="JSON", help="Input as a JSON object.") -@click.option( - "--input-file", - type=_source_file, - metavar="FILE", - help="Read input from a JSON file.", -) -@_billing_option -@_yes_option -@_json_option -@coro -async def fire_command( - name: str, - input_json: str | None, - input_file: Path | None, - billing: str | None, - yes: bool, - as_json: bool, -) -> None: - """Trigger a sandbox run without waiting for its result.""" - from mobilerun.sandbox.execution import fire_remote - - mode = _resolve_mode(billing) - payload = _payload(input_json, input_file) - result, _ = await invoke_with_billing( - lambda attempt: fire_remote(name, payload, billing=attempt), - mode, - yes=yes, - confirm_paid=f"Fire sandbox endpoint {name!r}", - ) - invocation_id = result["invocation_id"] - if as_json: - click.echo(json.dumps({"invocation_id": invocation_id})) - else: - render.success(f"Fired invocation {invocation_id}") - - -def _run_summary(record: dict[str, Any]) -> dict[str, Any]: - summary = { - key: record[key] - for key in ("id", "status", "startedAt", "finishedAt", "invocationId", "flowId") - if key in record and (record[key] is None or isinstance(record[key], str)) - } - start, end = summary.get("startedAt"), summary.get("finishedAt") - if start and end: - try: - summary["duration"] = ( - datetime.fromisoformat(end) - datetime.fromisoformat(start) - ).total_seconds() - except (ValueError, TypeError): - pass - return summary - - -@click.command("runs") -@_name_argument -@click.option( - "--limit", - type=click.IntRange(min=1), - default=10, - show_default=True, - help="Maximum runs.", -) -@_billing_option -@_json_option -@coro -async def runs_command( - name: str, limit: int, billing: str | None, as_json: bool -) -> None: - """List recent runs of a sandbox function.""" - from mobilerun.sandbox.execution import recent_runs - - records = await recent_runs(name, limit, billing=_resolve_mode(billing)) - if as_json: - click.echo(json.dumps([_run_summary(record) for record in records])) - elif not records: - render.empty("sandbox runs") - else: - render.heading(len(records), "sandbox run") - render.table( - ( - item["id"], - render.status(item.get("status")), - render.relative_time(item.get("startedAt")), - ) - for item in records - ) - - -async def _set_enabled( - names: tuple[str, ...], enabled: bool, billing: str | None, yes: bool, as_json: bool -) -> None: - from mobilerun.sandbox.billing import require_paid - from mobilerun.sandbox.flows import set_enabled - - mode = _resolve_mode(billing) - verb = "Enable" if enabled else "Disable" - names = tuple(dict.fromkeys(names)) - targets = ", ".join(map(repr, names)) - warning = f"{verb} {targets}. Billing: {mode}." - if enabled: - summary = f"Enable sandbox flows {targets}" - - async def authorize(attempt: Billing) -> None: - try: - require_paid(billing=attempt) - except BillingRequired as exc: - raise _TargetedBillingRequired(exc, summary) from exc - - _, mode = await invoke_with_billing( - authorize, mode, yes=yes, confirm_paid=summary - ) - else: - try: - await confirm_action_async( - "disable sandbox flows", mode, warning, yes=yes, err=True - ) - except click.exceptions.Exit as exc: - if as_json and exc.exit_code == 0: - click.echo("[]") - raise - - results = [] - for name in names: - try: - await set_enabled(name, enabled, billing=mode) - except (BillingRequired, click.Abort, click.exceptions.Exit): - raise - except Exception as exc: - status = "failed" - render.error(f"{name!r}: {safe_error_message(exc)}") - else: - status = "enabled" if enabled else "disabled" - if not as_json: - render.success(f"{name!r}: {status}") - results.append({"name": name, "status": status}) - if as_json: - click.echo(json.dumps(results)) - if any(item["status"] == "failed" for item in results): - click.get_current_context().exit(1) - - -@click.command("enable") -@click.argument( - "name", - cls=_DeploymentArgument, - nargs=-1, - required=True, - metavar="NAME...", - requires_consent=True, -) -@_billing_option -@_yes_option -@_json_option -@coro -async def enable_command( - name: tuple[str, ...], billing: str | None, yes: bool, as_json: bool -) -> None: - """Enable one or more owned sandbox flows.""" - await _set_enabled(name, True, billing, yes, as_json) - - -@click.command("disable") -@_names_argument -@_billing_option -@_yes_option -@_json_option -@coro -async def disable_command( - name: tuple[str, ...], billing: str | None, yes: bool, as_json: bool -) -> None: - """Disable one or more owned sandbox flows.""" - await _set_enabled(name, False, billing, yes, as_json) diff --git a/mobilerun/sandbox/cli/deploy.py b/mobilerun/sandbox/cli/deploy.py new file mode 100644 index 000000000..1c209bceb --- /dev/null +++ b/mobilerun/sandbox/cli/deploy.py @@ -0,0 +1,170 @@ +"""Deploy a sandbox function from a script.""" + +import json +import shlex +import sys +from contextlib import nullcontext, redirect_stdout +from pathlib import Path +from typing import TYPE_CHECKING, Any + +import click + +from mobilerun.cli.base import menu, render +from mobilerun.cli.base.billing import invoke_with_billing, require_consent_possible +from mobilerun.cli.base.prompts import SelectChoice, select_prompt_async +from mobilerun.cli.base.run import coro +from mobilerun.errors.cloud import BillingRequired +from mobilerun.models.billing import Billing + +from ..billing import resolve_billing +from ..errors import TargetedBillingRequired +from .helpers.options import billing_option, json_option, source_file, yes_option +from .helpers.stderr_argument import StderrArgument + +if TYPE_CHECKING: + from ..models import DeploymentReceipt + + +async def _pick_device(*, as_json: bool, yes: bool) -> tuple[str | None, bool]: + from mobilerun.cli.devices.utils.connection.discovery import discover_devices + + if not menu.is_interactive(): + raise click.UsageError( + "Pass --device ID or --device-free for a scheduled deployment." + ) + require_consent_possible(yes=yes) + devices = await discover_devices(local=False, strict=True) + # Disjoint choice values keep the device-free option distinct from device IDs. + cloud = { + f"device:{item.device_id}": item for item in devices if item.backend == "cloud" + } + choices = [ + SelectChoice( + value, + item.name or item.device_id, + f"{item.device_id} · {item.state or 'unknown'}", + ) + for value, item in cloud.items() + ] + choices.append(SelectChoice("device-free", "Device-free")) + with redirect_stdout(sys.stderr) if as_json else nullcontext(): + selected = await select_prompt_async("Choose a cloud device", choices) + if selected is None: + click.echo("Cancelled.", err=True) + click.get_current_context().exit(0) + return ( + (None, True) + if selected == "device-free" + else (cloud[selected].device_id, False) + ) + + +def _sample_value(schema: dict[str, Any]) -> Any: + """Illustrate the shape without publishing literal defaults or examples.""" + for key in ("anyOf", "oneOf"): + if schema.get(key): + return _sample_value(schema[key][0]) + kind = schema.get("type") + if kind == "object" or "properties" in schema: + properties = schema.get("properties", {}) + return { + key: _sample_value(properties.get(key, {})) + for key in schema.get("required", []) + } + return ( + {"string": "", "integer": 0, "number": 0, "boolean": False, "array": []}.get( + kind + ) + if isinstance(kind, str) + else None + ) + + +def _endpoint_contract(receipt: "DeploymentReceipt", schema: dict[str, Any]) -> None: + endpoint = receipt.endpoint + if endpoint is None: + return + base_url = endpoint.url.rsplit("/triggers/", 1)[0] + sample = _sample_value(schema) or {} + click.echo( + f"Endpoint: POST {endpoint.url}\n" + "Authorization: Bearer (use MOBILERUN_API_KEY)\n" + "Idempotency-Key: (optional)\n" + "Content-Type: application/json\n" + f"Example body: {json.dumps({'payload': sample})}\n" + "HTTP 202 returns invocationId, enqueuedCount, and deduplicated, not the result.\n" + f"Poll GET {base_url}/executions?flowId={receipt.flow_id}&invocationId=;\n" + f"then GET {base_url}/executions/ for result.steps[].body.result.\n" + f"List recent runs: mobilerun sandbox runs {shlex.quote(receipt.name)}" + ) + + +@click.command("deploy") +@click.argument("file", cls=StderrArgument, prompt_label="File", type=source_file) +@click.option("--device", metavar="ID", help="Use an existing cloud device.") +@click.option("--device-free", is_flag=True, help="Deploy without a device.") +@billing_option +@yes_option +@json_option +@coro +async def deploy_command( + file: Path, + device: str | None, + device_free: bool, + billing: str | None, + yes: bool, + as_json: bool, +) -> None: + """Deploy a cloud function as an endpoint by default.""" + from mobilerun.sandbox.billing import check_deploy_billing + from mobilerun.sandbox.deployment import deploy_file + from mobilerun.sandbox.packaging import package, read_declaration + + if device is not None and device_free: + raise click.UsageError("Choose either --device or --device-free, not both.") + if device is not None and not device.strip(): + raise click.UsageError("--device requires a nonempty ID.") + try: + source = file.read_text(encoding="utf-8") + except (OSError, UnicodeError) as exc: + raise click.ClickException(f"Cannot read source: {file}") from exc + declaration = read_declaration(file, source=source) + if not device_free and device is None: + device = declaration.device + if device is None and declaration.schedule is not None: + device, device_free = await _pick_device(as_json=as_json, yes=yes) + + target = f"device {device!r}" if device is not None else "device-free" + summary = f"Deploy {declaration.name!r} ({target})" + if declaration.schedule is not None: + summary += f" on schedule {declaration.schedule!r}" + + async def authorize(attempt: Billing) -> None: + try: + await check_deploy_billing(attempt) + except BillingRequired as exc: + raise TargetedBillingRequired(exc, summary) from exc + + _, mode = await invoke_with_billing( + authorize, resolve_billing(billing), yes=yes, confirm_paid=summary + ) + artifact = package(file, source=source) + + receipt = await deploy_file( + file, + device=device, + device_free=device_free, + billing=mode, + artifact=artifact, + ) + if as_json: + click.echo(json.dumps(receipt.to_dict())) + else: + render.success(f"{receipt.name} v{receipt.version}: {receipt.status}") + fields = [("Function", receipt.function_id)] + if receipt.flow_id: + fields.append(("Flow", receipt.flow_id)) + render.kv(fields) + _endpoint_contract(receipt, artifact.input_schema) + for warning in receipt.warnings: + render.warn(warning) diff --git a/mobilerun/sandbox/cli/fire.py b/mobilerun/sandbox/cli/fire.py new file mode 100644 index 000000000..27b801a06 --- /dev/null +++ b/mobilerun/sandbox/cli/fire.py @@ -0,0 +1,80 @@ +"""Trigger an invocation without waiting for execution.""" + +import json +from pathlib import Path +from typing import Any + +import click + +from mobilerun.cli.base import render +from mobilerun.cli.base.billing import invoke_with_billing +from mobilerun.cli.base.run import coro + +from ..billing import resolve_billing +from .helpers.deployment_argument import DeploymentArgument +from .helpers.options import billing_option, json_option, source_file, yes_option + + +def _invalid_constant(value: str) -> None: + raise ValueError("Non-finite JSON number") + + +def _payload(input_json: str | None, input_file: Path | None) -> dict[str, Any]: + if input_json is not None and input_file is not None: + raise click.UsageError("Choose either --input or --input-file, not both.") + if input_file is not None: + try: + input_json = input_file.read_text(encoding="utf-8") + except (OSError, UnicodeError) as exc: + raise click.UsageError("Cannot read --input-file as UTF-8.") from exc + if input_json is None: + return {} + message = "Sandbox input must be a valid JSON object." + try: + payload = json.loads(input_json, parse_constant=_invalid_constant) + if not isinstance(payload, dict): + raise ValueError + # Python also decodes overflowing exponents as infinity. + json.dumps(payload, allow_nan=False) + except (ValueError, RecursionError) as exc: + raise click.UsageError(message) from exc + return payload + + +@click.command("fire") +@click.argument("name", cls=DeploymentArgument, requires_consent=True) +@click.option("--input", "input_json", metavar="JSON", help="Input as a JSON object.") +@click.option( + "--input-file", + type=source_file, + metavar="FILE", + help="Read input from a JSON file.", +) +@billing_option +@yes_option +@json_option +@coro +async def fire_command( + name: str, + input_json: str | None, + input_file: Path | None, + billing: str | None, + yes: bool, + as_json: bool, +) -> None: + """Trigger a sandbox run without waiting for its result.""" + from mobilerun.sandbox.execution import fire_remote + + mode = resolve_billing(billing) + payload = _payload(input_json, input_file) + result, _ = await invoke_with_billing( + lambda attempt: fire_remote(name, payload, billing=attempt), + mode, + yes=yes, + confirm_paid=f"Fire sandbox endpoint {name!r}", + ) + invocation_id = result["invocation_id"] + if as_json: + click.echo(json.dumps({"invocation_id": invocation_id})) + else: + render.success(f"Fired invocation {invocation_id}") diff --git a/mobilerun/sandbox/cli/group.py b/mobilerun/sandbox/cli/group.py index e14106ca0..0a6c9e45f 100644 --- a/mobilerun/sandbox/cli/group.py +++ b/mobilerun/sandbox/cli/group.py @@ -5,7 +5,11 @@ from mobilerun.cli.base.menu import MenuGroup from mobilerun.utils.paths import local_store_path -from . import commands +from .activation import disable_command, enable_command +from .deploy import deploy_command +from .fire import fire_command +from .list import list_command +from .runs import runs_command @click.group(cls=MenuGroup) @@ -28,11 +32,11 @@ def path(as_json: bool) -> None: for command in ( - commands.deploy_command, - commands.list_command, - commands.fire_command, - commands.runs_command, - commands.enable_command, - commands.disable_command, + deploy_command, + list_command, + fire_command, + runs_command, + enable_command, + disable_command, ): sandbox.add_command(command) diff --git a/mobilerun/sandbox/cli/helpers/README.md b/mobilerun/sandbox/cli/helpers/README.md new file mode 100644 index 000000000..77cba260e --- /dev/null +++ b/mobilerun/sandbox/cli/helpers/README.md @@ -0,0 +1,10 @@ +# CLI helpers + +Shared support for [sandbox commands](../README.md). For example, +`DeploymentArgument` prompts for a deployed function when a name is omitted. + +| File | Role | +| --- | --- | +| `deployment_argument.py` | Prompt for known deployments. | +| `stderr_argument.py` | Keep text prompts off the JSON output stream. | +| `options.py` | Shared Click options. | diff --git a/mobilerun/sandbox/cli/helpers/__init__.py b/mobilerun/sandbox/cli/helpers/__init__.py new file mode 100644 index 000000000..32a2fa167 --- /dev/null +++ b/mobilerun/sandbox/cli/helpers/__init__.py @@ -0,0 +1 @@ +"""Sandbox CLI presentation and prompting helpers.""" diff --git a/mobilerun/sandbox/cli/helpers/deployment_argument.py b/mobilerun/sandbox/cli/helpers/deployment_argument.py new file mode 100644 index 000000000..e80b95740 --- /dev/null +++ b/mobilerun/sandbox/cli/helpers/deployment_argument.py @@ -0,0 +1,80 @@ +"""Select one or more already deployed sandbox functions.""" + +import asyncio +import sys +from contextlib import redirect_stdout +from typing import Any + +import click + +from mobilerun.cli.base import menu, render +from mobilerun.cli.base.billing import require_consent_possible +from mobilerun.cli.base.prompts import SelectChoice + +from ...billing import resolve_billing + + +class DeploymentArgument(menu.PromptingArgument): + """Select deployed names without the generic argument's free-text fallback.""" + + def __init__( + self, *args: Any, requires_consent: bool = False, **kwargs: Any + ) -> None: + super().__init__(*args, **kwargs) + self.requires_consent = requires_consent + + def process_value(self, ctx: click.Context, value: Any) -> Any: + if ( + not self.value_is_missing(value) + or ctx.resilient_parsing + or not menu.is_interactive() + ): + return super().process_value(ctx, value) + + batch = self.nargs == -1 + if self.requires_consent: + # Click processes explicitly supplied options before omitted arguments. + # Refuse before the remote lookup when billing consent cannot be asked. + require_consent_possible(yes=ctx.params.get("yes", False)) + choices = self._choices(ctx) + try: + with redirect_stdout(sys.stderr): + if not choices: + click.echo("No deployed sandbox functions found.") + elif batch: + value = tuple( + menu.multi_select_prompt("Select sandbox functions", choices) + or () + ) + else: + value = menu.select_prompt("Name", choices) + except (KeyboardInterrupt, click.Abort, EOFError): + ctx.exit(130) + if not choices or not value: + if choices: + click.echo("Cancelled.", err=True) + if batch and ctx.params.get("as_json"): + click.echo("[]") + ctx.exit(0) + return super().process_value(ctx, value) + + @staticmethod + def _choices(ctx: click.Context) -> list[SelectChoice]: + from mobilerun.sandbox.flows import list_deployments + + mode = resolve_billing(ctx.params.get("billing")) + records = asyncio.run(list_deployments(billing=mode)) + choices = [] + for item in records: + name = item.get("name") + if not isinstance(name, str) or not name: + continue + latest = item.get("latestVersion", {}) + version = latest.get("version", "—") + status = render.status(latest.get("status")).plain + function_id = item["id"] + short_id = f"{function_id[:8]}…" if len(function_id) > 8 else function_id + choices.append( + SelectChoice(name, f"{name} · {short_id} · {version} · {status}") + ) + return choices diff --git a/mobilerun/sandbox/cli/helpers/options.py b/mobilerun/sandbox/cli/helpers/options.py new file mode 100644 index 000000000..6ec142e79 --- /dev/null +++ b/mobilerun/sandbox/cli/helpers/options.py @@ -0,0 +1,18 @@ +"""Click options shared by sandbox commands.""" + +from pathlib import Path + +import click + +from mobilerun.models.billing import Billing + +billing_option = click.option( + "--billing", + type=click.Choice([mode.value for mode in Billing]), + help="Billing mode.", +) +json_option = click.option("--json", "as_json", is_flag=True, help="Output JSON.") +yes_option = click.option( + "--yes", is_flag=True, help="Confirm the action without prompting." +) +source_file = click.Path(exists=True, dir_okay=False, readable=True, path_type=Path) diff --git a/mobilerun/sandbox/cli/helpers/stderr_argument.py b/mobilerun/sandbox/cli/helpers/stderr_argument.py new file mode 100644 index 000000000..f56db8f87 --- /dev/null +++ b/mobilerun/sandbox/cli/helpers/stderr_argument.py @@ -0,0 +1,29 @@ +"""Prompt for required CLI text without writing to stdout.""" + +import sys +from contextlib import redirect_stdout +from typing import Any + +import click + +from mobilerun.cli.base import menu + + +class StderrArgument(menu.PromptingArgument): + """Keep required text prompts off stdout, including in JSON mode.""" + + def process_value(self, ctx: click.Context, value: Any) -> Any: + if ( + self.value_is_missing(value) + and not ctx.resilient_parsing + and menu.is_interactive() + ): + try: + with redirect_stdout(sys.stderr): + value = menu.text_prompt(self.prompt_label).strip() + except (KeyboardInterrupt, click.Abort, EOFError): + ctx.exit(130) + if not value: + click.echo("Cancelled.", err=True) + ctx.exit(0) + return super().process_value(ctx, value) diff --git a/mobilerun/sandbox/cli/list.py b/mobilerun/sandbox/cli/list.py new file mode 100644 index 000000000..5dbb2a132 --- /dev/null +++ b/mobilerun/sandbox/cli/list.py @@ -0,0 +1,40 @@ +"""List deployed sandbox functions.""" + +import json + +import click + +from mobilerun.cli.base import render +from mobilerun.cli.base.run import coro + +from ..billing import resolve_billing +from .helpers.options import billing_option, json_option + + +@click.command("list") +@billing_option +@json_option +@coro +async def list_command(billing: str | None, as_json: bool) -> None: + """List deployed sandbox functions.""" + from mobilerun.sandbox.flows import list_deployments + + records = await list_deployments(billing=resolve_billing(billing)) + if as_json: + click.echo(json.dumps(records)) + elif not records: + render.empty( + "sandbox functions", "Run `mobilerun sandbox deploy FILE` to deploy one." + ) + else: + render.heading(len(records), "sandbox function") + render.table( + ( + item.get("name"), + item["id"], + latest.get("version"), + render.status(latest.get("status")), + ) + for item in records + for latest in [item.get("latestVersion", {})] + ) diff --git a/mobilerun/sandbox/cli/runs.py b/mobilerun/sandbox/cli/runs.py new file mode 100644 index 000000000..357827f81 --- /dev/null +++ b/mobilerun/sandbox/cli/runs.py @@ -0,0 +1,66 @@ +"""List recent sandbox executions.""" + +import json +from datetime import datetime +from typing import Any + +import click + +from mobilerun.cli.base import render +from mobilerun.cli.base.run import coro + +from ..billing import resolve_billing +from .helpers.deployment_argument import DeploymentArgument +from .helpers.options import billing_option, json_option + + +def _run_summary(record: dict[str, Any]) -> dict[str, Any]: + summary = { + key: record[key] + for key in ("id", "status", "startedAt", "finishedAt", "invocationId", "flowId") + if key in record and (record[key] is None or isinstance(record[key], str)) + } + start, end = summary.get("startedAt"), summary.get("finishedAt") + if start and end: + try: + summary["duration"] = ( + datetime.fromisoformat(end) - datetime.fromisoformat(start) + ).total_seconds() + except (ValueError, TypeError): + pass + return summary + + +@click.command("runs") +@click.argument("name", cls=DeploymentArgument) +@click.option( + "--limit", + type=click.IntRange(min=1), + default=10, + show_default=True, + help="Maximum runs.", +) +@billing_option +@json_option +@coro +async def runs_command( + name: str, limit: int, billing: str | None, as_json: bool +) -> None: + """List recent runs of a sandbox function.""" + from mobilerun.sandbox.execution import recent_runs + + records = await recent_runs(name, limit, billing=resolve_billing(billing)) + if as_json: + click.echo(json.dumps([_run_summary(record) for record in records])) + elif not records: + render.empty("sandbox runs") + else: + render.heading(len(records), "sandbox run") + render.table( + ( + item["id"], + render.status(item.get("status")), + render.relative_time(item.get("startedAt")), + ) + for item in records + ) diff --git a/mobilerun/sandbox/clients.py b/mobilerun/sandbox/clients.py deleted file mode 100644 index 78bf19887..000000000 --- a/mobilerun/sandbox/clients.py +++ /dev/null @@ -1,786 +0,0 @@ -"""Guarded async sandbox cloud function and workflow operations.""" - -from collections.abc import AsyncIterator, Awaitable, Callable -from contextlib import asynccontextmanager, nullcontext -from typing import Any - -import httpx -from mobilerun_sdk import APIError, AsyncMobilerun -from mobilerun_sdk.types.workflows.flow_create_params import Action - -from mobilerun.clients.cloud.billing import requires -from mobilerun.clients.cloud.client import cloud_client -from mobilerun.clients.cloud.errors import cloud_error -from mobilerun.clients.cloud.signed_http import _signed_client -from mobilerun.models.billing import Billing -from mobilerun.sandbox.errors import FlowCapabilityError, FlowStagingError - -from .models import FILE_UPLOAD_USES - -JSON = dict[str, Any] - - -def _data(value: Any) -> Any: - if hasattr(value, "model_dump"): - value = value.model_dump(by_alias=True, mode="json") - if isinstance(value, dict) and "data" in value: - return value["data"] - return value - - -@asynccontextmanager -async def _sdk( - billing: Billing, - client: AsyncMobilerun | None, - operation: str = "Cloud function request", -) -> AsyncIterator[AsyncMobilerun]: - async with ( - nullcontext(client) if client is not None else cloud_client(billing=billing) - ) as sdk: - try: - yield sdk - except (APIError, httpx.HTTPError) as exc: - raise cloud_error(exc, operation) from None - - -async def _paginate( - method: Callable[..., Awaitable[Any]], - *args: Any, - limit: int | None = None, - omit_none: bool = False, - **kwargs: Any, -) -> list[JSON]: - if limit is not None and limit <= 0: - return [] - result: list[JSON] = [] - page = 1 - while True: - data = _data(await method(*args, page=page, page_size=100, **kwargs)) - result.extend( - item for item in data["items"] if not omit_none or item is not None - ) - if not data["pagination"]["hasNext"] or ( - limit is not None and len(result) >= limit - ): - return result if limit is None else result[:limit] - page += 1 - - -@requires(Billing.NO_COMMERCE) -async def list_functions( - *, billing: Billing, client: AsyncMobilerun | None = None -) -> list[JSON]: - """List all functions as JSON-compatible records.""" - async with _sdk(billing, client) as sdk: - return await _paginate(sdk.compute.functions.list, omit_none=True) - - -@requires(Billing.NO_COMMERCE) -async def list_versions( - function_id: str, *, billing: Billing, client: AsyncMobilerun | None = None -) -> list[JSON]: - """List all extant versions of a function.""" - async with _sdk(billing, client) as sdk: - return await _paginate( - sdk.compute.functions.versions.list, function_id, omit_none=True - ) - - -@requires(Billing.NO_COMMERCE) -async def get_version( - function_id: str, - version: int, - *, - billing: Billing, - client: AsyncMobilerun | None = None, -) -> JSON: - """Retrieve a function version.""" - async with _sdk(billing, client) as sdk: - return _data( - await sdk.compute.functions.versions.retrieve( - version, function_id=function_id - ) - ) - - -@requires(Billing.NO_COMMERCE) -async def get_source( - function_id: str, - version: int, - *, - billing: Billing, - client: AsyncMobilerun | None = None, -) -> str: - """Retrieve the source of a function version.""" - async with _sdk(billing, client) as sdk: - return _data(await sdk.compute.functions.source(function_id, version=version))[ - "source" - ] - - -@requires(Billing.PAID) -async def create_function( - name: str, - source: str, - idempotency_key: str, - *, - billing: Billing, - client: AsyncMobilerun | None = None, -) -> JSON: - """Create a function and its initial version.""" - async with _sdk(billing, client) as sdk: - return _data( - await sdk.compute.functions.create( - name=name, source=source, idempotency_key=idempotency_key - ) - ) - - -@requires(Billing.PAID) -async def create_version( - function_id: str, - source: str, - idempotency_key: str, - *, - billing: Billing, - client: AsyncMobilerun | None = None, -) -> JSON: - """Create a version of a function.""" - async with _sdk(billing, client) as sdk: - return _data( - await sdk.compute.functions.versions.create( - function_id, source=source, idempotency_key=idempotency_key - ) - ) - - -@requires(Billing.NO_COMMERCE) -async def delete_function( - function_id: str, *, billing: Billing, client: AsyncMobilerun | None = None -) -> None: - """Delete a function.""" - async with _sdk(billing, client) as sdk: - await sdk.compute.functions.delete(function_id) - - -@requires(Billing.NO_COMMERCE) -async def run_logs( - run_id: str, *, billing: Billing, client: AsyncMobilerun | None = None -) -> str: - """Download run logs without sending SDK credentials to the signed URL.""" - async with _sdk(billing, client) as sdk: - url = _data(await sdk.compute.runs.logs(run_id))["url"] - try: - async with _signed_client( - httpx.AsyncClient(follow_redirects=True, timeout=30, trust_env=False) - ) as downloader: - response = await downloader.get(url) - response.raise_for_status() - return response.text - except ( - httpx.HTTPError, - httpx.InvalidURL, - httpx.CookieConflict, - httpx.StreamError, - TypeError, - ): - # The exception and response may include the signed URL or arbitrary headers. - raise cloud_error( - httpx.RequestError("Log download failed"), "Download run logs" - ) from None - - -async def _catalog_entry_id(sdk: AsyncMobilerun, step_name: str) -> str: - """Resolve the unique catalog entry for step_name: workflow actions are created by ID.""" - entries = await _paginate(sdk.workflows.action_catalog.list) - matches = [item["id"] for item in entries if item.get("stepName") == step_name] - if len(matches) != 1: - label = ( - step_name - if step_name in ("functions.run", "webhooks.send", FILE_UPLOAD_USES) - else "sandbox step" - ) - count = "no entries" if not matches else "more than one entry" - message = f"Workflow action catalog: found {count} for {label}" - error = FlowCapabilityError(message, operation=message, code="request_failed") - error.value_safe = True # Both interpolated labels are allowlisted above. - raise error - return matches[0] - - -@requires(Billing.NO_COMMERCE) -async def disable_flow( - flow_id: str, *, billing: Billing, client: AsyncMobilerun | None = None -) -> JSON: - """Disable a flow without activating it.""" - async with _sdk(billing, client, "Cloud workflow request") as sdk: - try: - return _data(await sdk.workflows.flows.update(flow_id, enabled=False)) - except (APIError, httpx.HTTPError) as exc: - raise cloud_error(exc, "Disable flow") from None - - -@requires(Billing.PAID) -async def enable_flow( - flow_id: str, *, billing: Billing, client: AsyncMobilerun | None = None -) -> JSON: - """Enable a flow.""" - async with _sdk(billing, client, "Cloud workflow request") as sdk: - try: - return _data(await sdk.workflows.flows.update(flow_id, enabled=True)) - except (APIError, httpx.HTTPError) as exc: - raise cloud_error(exc, "Enable flow") from None - - -def _document(document: JSON) -> tuple[JSON, list[JSON], JSON]: - """Validate the supported playground document before any SDK calls.""" - try: - if not ( - set(document) <= {"version", "name", "on", "settings", "steps", "devices"} - ): - raise ValueError - if not (document["version"] == 1 and isinstance(document["name"], str)): - raise ValueError - settings = document.get("settings", {}) - if not ( - isinstance(settings, dict) - and settings.keys() <= {"recording", "delivery"} - and settings.get("recording", {"mode": "off"}) == {"mode": "off"} - ): - raise ValueError - delivery = settings.get("delivery") - if "delivery" in settings and not ( - isinstance(delivery, dict) - and delivery.keys() == {"destination", "folder"} - and delivery["destination"] == "mobilerun" - and isinstance(delivery["folder"], str) - and delivery["folder"].startswith("/") - ): - raise ValueError - on = document["on"] - if not (isinstance(on, dict) and len(on) == 1): - raise ValueError - trigger: JSON = {"name": document["name"]} - if "custom" in on: - custom = on["custom"] - if not (isinstance(custom, dict) and set(custom) <= {"inputs"}): - raise ValueError - trigger["activation"] = "custom" - if "inputs" in custom: - if not (isinstance(custom["inputs"], dict)): - raise ValueError - trigger["custom_payload_schema"] = custom["inputs"] - else: - schedule = on["schedule"] - if not ( - isinstance(schedule, dict) and set(schedule) == {"cron", "timezone"} - ): - raise ValueError - if not (all(isinstance(schedule[k], str) for k in schedule)): - raise ValueError - trigger.update( - activation="schedule", - schedule_rule={"type": "cron", "expression": schedule["cron"]}, - timezone=schedule["timezone"], - ) - steps = document["steps"] - if not (isinstance(steps, list) and steps): - raise ValueError - for step in steps: - if not ( - isinstance(step, dict) and set(step) == {"id", "name", "uses", "with"} - ): - raise ValueError - if not ( - step["uses"] in ("functions.run", "webhooks.send", FILE_UPLOAD_USES) - and isinstance(step["with"], dict) - ): - raise ValueError - if not (isinstance(step["id"], str) and isinstance(step["name"], str)): - raise ValueError - flow: JSON = { - "name": document["name"], - "enabled": False, - "recording_enabled": False, - } - if delivery is not None: - flow["delivery"] = delivery - if "devices" in document: - if not ( - isinstance(document["devices"], list) - and all(isinstance(d, str) for d in document["devices"]) - ): - raise ValueError - flow["device_ids"] = document["devices"] - return trigger, steps, flow - except (ValueError, KeyError, TypeError): - raise FlowCapabilityError( - operation="Stage flow", code="request_failed" - ) from None - - -@requires(Billing.NO_COMMERCE) -async def prepare_action_payloads( - document: JSON, *, billing: Billing, client: AsyncMobilerun | None = None -) -> list[JSON]: - """Resolve the exact SDK action bodies before the staging intent is journaled.""" - _, steps, _ = _document(document) - async with _sdk(billing, client, "Resolve sandbox actions") as sdk: - catalog = { - uses: await _catalog_entry_id(sdk, uses) - for uses in dict.fromkeys(step["uses"] for step in steps) - } - return [ - dict( - catalog_entry_id=catalog[step["uses"]], - name=step["name"], - params=step["with"], - ) - for step in steps - ] - - -@requires(Billing.PAID) -async def create_document( - document: JSON, - idempotency_key: str, - *, - action_payloads: list[JSON] | None = None, - billing: Billing, - client: AsyncMobilerun | None = None, -) -> JSON: - """Create supported inline workflow resources and verify disabled staging.""" - trigger, steps, flow = _document(document) - trigger_id = None - action_ids: list[str] = [] - flow_id = None - async with _sdk(billing, client, "Cloud workflow request") as sdk: - try: - if action_payloads is None: - action_payloads = await prepare_action_payloads( - document, billing=billing, client=sdk - ) - if len(action_payloads) != len(steps): - raise ValueError("Incomplete action payloads") - trigger_id = _data( - await sdk.workflows.triggers.create( - **trigger, idempotency_key=idempotency_key + ":trigger" - ) - )["id"] - refs: list[Action] = [] - for position, step in enumerate(steps): - action = _data( - await sdk.workflows.actions.create( - **action_payloads[position], - idempotency_key=idempotency_key + f":action:{position}", - ) - ) - action_ids.append(action["id"]) - refs.append( - {"action_id": action["id"], "position": position, "key": step["id"]} - ) - flow_id = _data( - await sdk.workflows.flows.create( - **flow, - trigger_id=trigger_id, - actions=refs, - idempotency_key=idempotency_key + ":flow", - ) - )["id"] - verified = _data(await sdk.workflows.flows.retrieve(flow_id)) - if not isinstance(verified, dict) or verified.get("enabled") is not False: - raise FlowStagingError(trigger_id, action_ids, flow_id) - return {"flowId": flow_id, "triggerId": trigger_id, "actionIds": action_ids} - except (APIError, httpx.HTTPError) as exc: - if trigger_id is not None: - raise FlowStagingError(trigger_id, action_ids, flow_id) from None - raise cloud_error(exc, "Stage flow") from None - except (KeyError, TypeError, ValueError): - raise FlowStagingError(trigger_id, action_ids, flow_id) from None - - -async def _request( - client: AsyncMobilerun | None, - billing: Billing, - method_for: Callable[[AsyncMobilerun], Callable[..., Awaitable[Any]]], - operation: str, - *args: Any, - **kwargs: Any, -) -> Any: - async with _sdk(billing, client, "Cloud workflow request") as sdk: - try: - method = method_for(sdk) - return _data(await method(*args, **kwargs)) - except (APIError, httpx.HTTPError) as exc: - raise cloud_error(exc, operation) from None - - -async def _flow_pages( - client: AsyncMobilerun | None, - billing: Billing, - method_for: Callable[[AsyncMobilerun], Callable[..., Awaitable[Any]]], - operation: str, - *, - limit: int | None = None, - **kwargs: Any, -) -> list[JSON]: - if limit is not None and limit <= 0: - return [] - async with _sdk(billing, client, operation) as sdk: - return await _paginate(method_for(sdk), limit=limit, **kwargs) - - -@requires(Billing.NO_COMMERCE) -async def list_flows( - *, billing: Billing, client: AsyncMobilerun | None = None -) -> list[JSON]: - """List all workflows.""" - return await _flow_pages( - client, billing, lambda sdk: sdk.workflows.flows.list, "List flows" - ) - - -@requires(Billing.NO_COMMERCE) -async def get_document( - flow_id: str, *, billing: Billing, client: AsyncMobilerun | None = None -) -> JSON: - """Retrieve a workflow document.""" - return await _request( - client, - billing, - lambda sdk: sdk.workflows.flows.retrieve_document, - "Get flow document", - flow_id, - ) - - -@requires(Billing.NO_COMMERCE) -async def list_actions( - flow_id: str, *, billing: Billing, client: AsyncMobilerun | None = None -) -> list[JSON]: - """List actions attached to a workflow.""" - return await _request( - client, - billing, - lambda sdk: sdk.workflows.flows.actions.list, - "List flow actions", - flow_id, - ) - - -@requires(Billing.NO_COMMERCE) -async def list_action_definitions( - *, billing: Billing, client: AsyncMobilerun | None = None -) -> list[JSON]: - """List every account action, including definitions unattached to a flow.""" - return await _flow_pages( - client, - billing, - lambda sdk: sdk.workflows.actions.list, - "List action definitions", - ) - - -@requires(Billing.NO_COMMERCE) -async def get_trigger( - trigger_id: str, *, billing: Billing, client: AsyncMobilerun | None = None -) -> JSON: - """Retrieve a trigger.""" - return await _request( - client, - billing, - lambda sdk: sdk.workflows.triggers.retrieve, - "Get trigger", - trigger_id, - ) - - -@requires(Billing.NO_COMMERCE) -async def list_executions( - flow_id: str, - *, - invocation_id: str | None = None, - limit: int | None = None, - billing: Billing, - client: AsyncMobilerun | None = None, -) -> list[JSON]: - """List newest workflow executions, optionally filtered by invocation.""" - kwargs: JSON = { - "flow_id": flow_id, - "order_by": "startedAt", - "order_by_direction": "desc", - } - if invocation_id is not None: - kwargs["invocation_id"] = invocation_id - return await _flow_pages( - client, - billing, - lambda sdk: sdk.workflows.executions.list, - "List executions", - limit=limit, - **kwargs, - ) - - -@requires(Billing.NO_COMMERCE) -async def get_execution( - execution_id: str, *, billing: Billing, client: AsyncMobilerun | None = None -) -> JSON: - """Retrieve an execution.""" - return await _request( - client, - billing, - lambda sdk: sdk.workflows.executions.retrieve, - "Get execution", - execution_id, - ) - - -@requires(Billing.NO_COMMERCE) -async def validate_document( - document: JSON, *, billing: Billing, client: AsyncMobilerun | None = None -) -> JSON: - """Validate a workflow document using the SDK.""" - return await _request( - client, - billing, - lambda sdk: sdk.workflows.flows.validate_document, - "Validate flow document", - document=document, - ) - - -@requires(Billing.PAID) -async def replace_document( - flow_id: str, - document: JSON, - idempotency_key: str, - *, - billing: Billing, - client: AsyncMobilerun | None = None, -) -> JSON: - """Replace a disabled workflow and verify it remains disabled.""" - async with _sdk(billing, client, "Cloud workflow request") as sdk: - current = await _request( - sdk, billing, lambda sdk: sdk.workflows.flows.retrieve, "Get flow", flow_id - ) - if current.get("enabled") is not False: - raise FlowCapabilityError(operation="Replace flow", code="request_failed") - result = await _request( - sdk, - billing, - lambda sdk: sdk.workflows.flows.replace_document, - "Replace flow document", - flow_id, - document=document, - idempotency_key=idempotency_key, - ) - current = await _request( - sdk, billing, lambda sdk: sdk.workflows.flows.retrieve, "Get flow", flow_id - ) - if current.get("enabled") is not False: - raise FlowCapabilityError(operation="Replace flow", code="request_failed") - return result - - -def _parameters(params: JSON, allowed: set[str]) -> JSON: - if not isinstance(params, dict) or not params.keys() <= allowed: - raise FlowCapabilityError( - operation="Workflow parameters", code="request_failed" - ) - return params - - -_TRIGGER_FIELDS = { - "activation", - "name", - "conditions", - "custom_payload_schema", - "description", - "event_type", - "payload", - "schedule_rule", - "timezone", -} -_ACTION_FIELDS = {"catalog_entry_id", "name", "description", "params"} - - -@requires(Billing.PAID) -async def create_trigger( - params: JSON, - idempotency_key: str, - *, - billing: Billing, - client: AsyncMobilerun | None = None, -) -> JSON: - """Create a workflow trigger from SDK fields.""" - return await _request( - client, - billing, - lambda sdk: sdk.workflows.triggers.create, - "Create trigger", - **_parameters(params, _TRIGGER_FIELDS), - idempotency_key=idempotency_key, - ) - - -@requires(Billing.PAID) -async def update_trigger( - trigger_id: str, - params: JSON, - idempotency_key: str, - *, - billing: Billing, - client: AsyncMobilerun | None = None, -) -> JSON: - """Update a workflow trigger from SDK fields.""" - return await _request( - client, - billing, - lambda sdk: sdk.workflows.triggers.update, - "Update trigger", - trigger_id, - **_parameters(params, _TRIGGER_FIELDS), - idempotency_key=idempotency_key, - ) - - -@requires(Billing.PAID) -async def create_action( - params: JSON, - idempotency_key: str, - *, - billing: Billing, - client: AsyncMobilerun | None = None, -) -> JSON: - """Create a workflow action from SDK fields.""" - return await _request( - client, - billing, - lambda sdk: sdk.workflows.actions.create, - "Create action", - **_parameters(params, _ACTION_FIELDS), - idempotency_key=idempotency_key, - ) - - -@requires(Billing.PAID) -async def replace_flow_actions( - flow_id: str, - actions: list[JSON], - idempotency_key: str, - *, - billing: Billing, - client: AsyncMobilerun | None = None, -) -> list[JSON]: - """Replace a flow's action references.""" - return await _request( - client, - billing, - lambda sdk: sdk.workflows.flows.actions.replace, - "Replace flow actions", - flow_id, - actions=actions, - idempotency_key=idempotency_key, - ) - - -@requires(Billing.PAID) -async def update_flow_devices( - flow_id: str, - device_ids: list[str], - idempotency_key: str, - *, - billing: Billing, - client: AsyncMobilerun | None = None, -) -> JSON: - """Update a workflow's devices; an empty list makes it device-free.""" - return await _request( - client, - billing, - lambda sdk: sdk.workflows.flows.update, - "Update flow devices", - flow_id, - device_ids=device_ids, - idempotency_key=idempotency_key, - ) - - -@requires(Billing.PAID) -async def update_flow_delivery( - flow_id: str, - delivery: JSON | None, - idempotency_key: str, - *, - billing: Billing, - client: AsyncMobilerun | None = None, -) -> JSON: - """Set or clear the workflow's delivery settings.""" - return await _request( - client, - billing, - lambda sdk: sdk.workflows.flows.update, - "Update flow delivery", - flow_id, - delivery=delivery, - idempotency_key=idempotency_key, - ) - - -@requires(Billing.PAID) -async def fire_trigger( - trigger_id: str, - payload: JSON, - idempotency_key: str, - *, - billing: Billing, - client: AsyncMobilerun | None = None, -) -> JSON: - """Fire a custom trigger.""" - return await _request( - client, - billing, - lambda sdk: sdk.workflows.triggers.fire, - "Fire trigger", - trigger_id, - payload=payload, - idempotency_key=idempotency_key, - ) - - -@requires(Billing.NO_COMMERCE) -async def delete_flow( - flow_id: str, *, billing: Billing, client: AsyncMobilerun | None = None -) -> None: - """Delete a workflow.""" - await _request( - client, billing, lambda sdk: sdk.workflows.flows.delete, "Delete flow", flow_id - ) - - -@requires(Billing.NO_COMMERCE) -async def delete_action( - action_id: str, *, billing: Billing, client: AsyncMobilerun | None = None -) -> None: - """Delete a workflow action.""" - await _request( - client, - billing, - lambda sdk: sdk.workflows.actions.delete, - "Delete action", - action_id, - ) - - -@requires(Billing.NO_COMMERCE) -async def delete_trigger( - trigger_id: str, *, billing: Billing, client: AsyncMobilerun | None = None -) -> None: - """Delete a workflow trigger.""" - await _request( - client, - billing, - lambda sdk: sdk.workflows.triggers.delete, - "Delete trigger", - trigger_id, - ) diff --git a/mobilerun/sandbox/clients/README.md b/mobilerun/sandbox/clients/README.md new file mode 100644 index 000000000..022457d9b --- /dev/null +++ b/mobilerun/sandbox/clients/README.md @@ -0,0 +1,17 @@ +# Sandbox transport + +The [sandbox](../README.md) SDK boundary enforces billing, owns client lifetime, +and translates transport errors. An injected SDK client stays caller-owned. +Operations keep SDK models during paging and staging, and encode JSON records +for the deployment, workflow document, and execution boundaries that need them. + +For example, `await clients.list_functions(billing=Billing.NO_COMMERCE, client=sdk)` +lists functions using an existing SDK client. + +| File | Role | +| --- | --- | +| `functions.py`, `run_logs.py` | Compute function versions, source, and signed logs. | +| `flows.py`, `actions.py`, `triggers.py`, `executions.py` | Workflow resources. | +| `staging.py` | Resolve catalog entries and stage an inactive workflow. | +| `helpers/` | SDK lease, paging, and serialization. | +| `__init__.py` | Internal operations import surface. | diff --git a/mobilerun/sandbox/clients/__init__.py b/mobilerun/sandbox/clients/__init__.py new file mode 100644 index 000000000..09e1ae2ee --- /dev/null +++ b/mobilerun/sandbox/clients/__init__.py @@ -0,0 +1,39 @@ +"""Sandbox cloud operations at the JSON orchestration boundary.""" + +from .actions import WorkflowActionTransport as _WorkflowActionTransport +from .executions import ExecutionTransport as _ExecutionTransport +from .flows import WorkflowTransport as _WorkflowTransport +from .functions import FunctionTransport as _FunctionTransport +from .run_logs import RunLogTransport as _RunLogTransport +from .staging import WorkflowStagingTransport as _WorkflowStagingTransport +from .triggers import WorkflowTriggerTransport as _WorkflowTriggerTransport + +list_functions = _FunctionTransport.list_functions +list_versions = _FunctionTransport.list_versions +get_version = _FunctionTransport.get_version +get_source = _FunctionTransport.get_source +create_function = _FunctionTransport.create_function +create_version = _FunctionTransport.create_version +delete_function = _FunctionTransport.delete_function +run_logs = _RunLogTransport.run_logs +disable_flow = _WorkflowTransport.disable_flow +enable_flow = _WorkflowTransport.enable_flow +list_flows = _WorkflowTransport.list_flows +get_document = _WorkflowTransport.get_document +list_actions = _WorkflowTransport.list_actions +validate_document = _WorkflowTransport.validate_document +replace_flow_actions = _WorkflowTransport.replace_flow_actions +update_flow_devices = _WorkflowTransport.update_flow_devices +update_flow_delivery = _WorkflowTransport.update_flow_delivery +delete_flow = _WorkflowTransport.delete_flow +list_action_definitions = _WorkflowActionTransport.list_action_definitions +create_action = _WorkflowActionTransport.create_action +delete_action = _WorkflowActionTransport.delete_action +get_trigger = _WorkflowTriggerTransport.get_trigger +update_trigger = _WorkflowTriggerTransport.update_trigger +fire_trigger = _WorkflowTriggerTransport.fire_trigger +delete_trigger = _WorkflowTriggerTransport.delete_trigger +list_executions = _ExecutionTransport.list_executions +get_execution = _ExecutionTransport.get_execution +prepare_action_payloads = _WorkflowStagingTransport.prepare_action_payloads +create_document = _WorkflowStagingTransport.create_document diff --git a/mobilerun/sandbox/clients/actions.py b/mobilerun/sandbox/clients/actions.py new file mode 100644 index 000000000..91b22a353 --- /dev/null +++ b/mobilerun/sandbox/clients/actions.py @@ -0,0 +1,63 @@ +"""Sandbox actions transport.""" + +from mobilerun_sdk import AsyncMobilerun + +from mobilerun.clients.cloud.billing_policy import BillingPolicy +from mobilerun.models.billing import Billing + +from ..models import JSON +from .helpers.transport import ( + collect_pages, + json_data, + json_record, + sdk_context, + workflow_parameters, +) + + +class WorkflowActionTransport: + """Cloud operations for this sandbox resource.""" + + _FIELDS = {"catalog_entry_id", "name", "description", "params"} + + @staticmethod + @BillingPolicy.guard(Billing.NO_COMMERCE) + async def list_action_definitions( + *, billing: Billing, client: AsyncMobilerun | None = None + ) -> list[JSON]: + """List every account action, including definitions unattached to a flow.""" + async with sdk_context(billing, client, "List action definitions") as sdk: + return [ + json_record(item) + for item in await collect_pages(sdk.workflows.actions.list) + ] + + @staticmethod + @BillingPolicy.guard(Billing.PAID) + async def create_action( + params: JSON, + idempotency_key: str, + *, + billing: Billing, + client: AsyncMobilerun | None = None, + ) -> JSON: + """Create a workflow action from SDK fields.""" + params = workflow_parameters(params, WorkflowActionTransport._FIELDS) + async with sdk_context(billing, client, "Create action") as sdk: + return json_data( + await sdk.workflows.actions.create( + **params, + idempotency_key=idempotency_key, + ) + ) + + @staticmethod + @BillingPolicy.guard(Billing.NO_COMMERCE) + async def delete_action( + action_id: str, *, billing: Billing, client: AsyncMobilerun | None = None + ) -> None: + """Delete a workflow action.""" + async with sdk_context(billing, client, "Delete action") as sdk: + await sdk.workflows.actions.delete( + action_id, + ) diff --git a/mobilerun/sandbox/clients/executions.py b/mobilerun/sandbox/clients/executions.py new file mode 100644 index 000000000..03bf0b73f --- /dev/null +++ b/mobilerun/sandbox/clients/executions.py @@ -0,0 +1,54 @@ +"""Sandbox executions transport.""" + +from mobilerun_sdk import AsyncMobilerun + +from mobilerun.clients.cloud.billing_policy import BillingPolicy +from mobilerun.models.billing import Billing + +from ..models import JSON +from .helpers.transport import collect_pages, json_data, json_record, sdk_context + + +class ExecutionTransport: + """Cloud operations for this sandbox resource.""" + + @staticmethod + @BillingPolicy.guard(Billing.NO_COMMERCE) + async def list_executions( + flow_id: str, + *, + invocation_id: str | None = None, + limit: int | None = None, + billing: Billing, + client: AsyncMobilerun | None = None, + ) -> list[JSON]: + """List newest workflow executions, optionally filtered by invocation.""" + kwargs: JSON = { + "flow_id": flow_id, + "order_by": "startedAt", + "order_by_direction": "desc", + } + if invocation_id is not None: + kwargs["invocation_id"] = invocation_id + if limit is not None and limit <= 0: + return [] + async with sdk_context(billing, client, "List executions") as sdk: + return [ + json_record(item) + for item in await collect_pages( + sdk.workflows.executions.list, limit=limit, **kwargs + ) + ] + + @staticmethod + @BillingPolicy.guard(Billing.NO_COMMERCE) + async def get_execution( + execution_id: str, *, billing: Billing, client: AsyncMobilerun | None = None + ) -> JSON: + """Retrieve an execution.""" + async with sdk_context(billing, client, "Get execution") as sdk: + return json_data( + await sdk.workflows.executions.retrieve( + execution_id, + ) + ) diff --git a/mobilerun/sandbox/clients/flows.py b/mobilerun/sandbox/clients/flows.py new file mode 100644 index 000000000..61ed7f7f8 --- /dev/null +++ b/mobilerun/sandbox/clients/flows.py @@ -0,0 +1,155 @@ +"""Sandbox flows transport.""" + +from typing import cast + +from mobilerun_sdk import AsyncMobilerun +from mobilerun_sdk.types.workflows.flow_update_params import Delivery +from mobilerun_sdk.types.workflows.flows.action_replace_params import Action + +from mobilerun.clients.cloud.billing_policy import BillingPolicy +from mobilerun.models.billing import Billing + +from ..models import JSON +from .helpers.transport import collect_pages, json_data, json_record, sdk_context + + +class WorkflowTransport: + """Cloud operations for this sandbox resource.""" + + @staticmethod + @BillingPolicy.guard(Billing.NO_COMMERCE) + async def disable_flow( + flow_id: str, *, billing: Billing, client: AsyncMobilerun | None = None + ) -> JSON: + """Disable a flow without activating it.""" + async with sdk_context(billing, client, "Disable flow") as sdk: + return json_data(await sdk.workflows.flows.update(flow_id, enabled=False)) + + @staticmethod + @BillingPolicy.guard(Billing.PAID) + async def enable_flow( + flow_id: str, *, billing: Billing, client: AsyncMobilerun | None = None + ) -> JSON: + """Enable a flow.""" + async with sdk_context(billing, client, "Enable flow") as sdk: + return json_data(await sdk.workflows.flows.update(flow_id, enabled=True)) + + @staticmethod + @BillingPolicy.guard(Billing.NO_COMMERCE) + async def list_flows( + *, billing: Billing, client: AsyncMobilerun | None = None + ) -> list[JSON]: + """List all workflows.""" + async with sdk_context(billing, client, "List flows") as sdk: + return [ + json_record(item) + for item in await collect_pages(sdk.workflows.flows.list) + ] + + @staticmethod + @BillingPolicy.guard(Billing.NO_COMMERCE) + async def get_document( + flow_id: str, *, billing: Billing, client: AsyncMobilerun | None = None + ) -> JSON: + """Retrieve a workflow document.""" + async with sdk_context(billing, client, "Get flow document") as sdk: + return json_data( + await sdk.workflows.flows.retrieve_document( + flow_id, + ) + ) + + @staticmethod + @BillingPolicy.guard(Billing.NO_COMMERCE) + async def list_actions( + flow_id: str, *, billing: Billing, client: AsyncMobilerun | None = None + ) -> list[JSON]: + """List actions attached to a workflow.""" + async with sdk_context(billing, client, "List flow actions") as sdk: + return json_data( + await sdk.workflows.flows.actions.list( + flow_id, + ) + ) + + @staticmethod + @BillingPolicy.guard(Billing.NO_COMMERCE) + async def validate_document( + document: JSON, *, billing: Billing, client: AsyncMobilerun | None = None + ) -> JSON: + """Validate a workflow document using the SDK.""" + async with sdk_context(billing, client, "Validate flow document") as sdk: + return json_data( + await sdk.workflows.flows.validate_document( + document=document, + ) + ) + + @staticmethod + @BillingPolicy.guard(Billing.PAID) + async def replace_flow_actions( + flow_id: str, + actions: list[JSON], + idempotency_key: str, + *, + billing: Billing, + client: AsyncMobilerun | None = None, + ) -> list[JSON]: + """Replace a flow's action references.""" + async with sdk_context(billing, client, "Replace flow actions") as sdk: + return json_data( + await sdk.workflows.flows.actions.replace( + flow_id, + actions=cast(list[Action], actions), + idempotency_key=idempotency_key, + ) + ) + + @staticmethod + @BillingPolicy.guard(Billing.PAID) + async def update_flow_devices( + flow_id: str, + device_ids: list[str], + idempotency_key: str, + *, + billing: Billing, + client: AsyncMobilerun | None = None, + ) -> JSON: + """Update a workflow's devices; an empty list makes it device-free.""" + async with sdk_context(billing, client, "Update flow devices") as sdk: + return json_data( + await sdk.workflows.flows.update( + flow_id, + device_ids=device_ids, + idempotency_key=idempotency_key, + ) + ) + + @staticmethod + @BillingPolicy.guard(Billing.PAID) + async def update_flow_delivery( + flow_id: str, + delivery: JSON | None, + idempotency_key: str, + *, + billing: Billing, + client: AsyncMobilerun | None = None, + ) -> JSON: + """Set or clear the workflow's delivery settings.""" + async with sdk_context(billing, client, "Update flow delivery") as sdk: + return json_data( + await sdk.workflows.flows.update( + flow_id, + delivery=cast(Delivery | None, delivery), + idempotency_key=idempotency_key, + ) + ) + + @staticmethod + @BillingPolicy.guard(Billing.NO_COMMERCE) + async def delete_flow( + flow_id: str, *, billing: Billing, client: AsyncMobilerun | None = None + ) -> None: + """Delete a workflow.""" + async with sdk_context(billing, client, "Delete flow") as sdk: + await sdk.workflows.flows.delete(flow_id) diff --git a/mobilerun/sandbox/clients/functions.py b/mobilerun/sandbox/clients/functions.py new file mode 100644 index 000000000..7b1c5f740 --- /dev/null +++ b/mobilerun/sandbox/clients/functions.py @@ -0,0 +1,129 @@ +"""Sandbox functions transport.""" + +from mobilerun_sdk import AsyncMobilerun + +from mobilerun.clients.cloud.billing_policy import BillingPolicy +from mobilerun.models.billing import Billing + +from ..models import JSON +from .helpers.transport import ( + collect_pages, + json_data, + json_record, + record_field, + sdk_context, + unwrap, +) + + +class FunctionTransport: + """Cloud operations for this sandbox resource.""" + + @staticmethod + @BillingPolicy.guard(Billing.NO_COMMERCE) + async def list_functions( + *, billing: Billing, client: AsyncMobilerun | None = None + ) -> list[JSON]: + """List all functions as JSON-compatible records.""" + async with sdk_context(billing, client) as sdk: + return [ + json_record(item) + for item in await collect_pages( + sdk.compute.functions.list, omit_none=True + ) + ] + + @staticmethod + @BillingPolicy.guard(Billing.NO_COMMERCE) + async def list_versions( + function_id: str, *, billing: Billing, client: AsyncMobilerun | None = None + ) -> list[JSON]: + """List all extant versions of a function.""" + async with sdk_context(billing, client) as sdk: + return [ + json_record(item) + for item in await collect_pages( + sdk.compute.functions.versions.list, function_id, omit_none=True + ) + ] + + @staticmethod + @BillingPolicy.guard(Billing.NO_COMMERCE) + async def get_version( + function_id: str, + version: int, + *, + billing: Billing, + client: AsyncMobilerun | None = None, + ) -> JSON: + """Retrieve a function version.""" + async with sdk_context(billing, client) as sdk: + return json_data( + await sdk.compute.functions.versions.retrieve( + version, function_id=function_id + ) + ) + + @staticmethod + @BillingPolicy.guard(Billing.NO_COMMERCE) + async def get_source( + function_id: str, + version: int, + *, + billing: Billing, + client: AsyncMobilerun | None = None, + ) -> str: + """Retrieve the source of a function version.""" + async with sdk_context(billing, client) as sdk: + return record_field( + unwrap( + await sdk.compute.functions.source(function_id, version=version) + ), + "source", + "source", + ) + + @staticmethod + @BillingPolicy.guard(Billing.PAID) + async def create_function( + name: str, + source: str, + idempotency_key: str, + *, + billing: Billing, + client: AsyncMobilerun | None = None, + ) -> JSON: + """Create a function and its initial version.""" + async with sdk_context(billing, client) as sdk: + return json_data( + await sdk.compute.functions.create( + name=name, source=source, idempotency_key=idempotency_key + ) + ) + + @staticmethod + @BillingPolicy.guard(Billing.PAID) + async def create_version( + function_id: str, + source: str, + idempotency_key: str, + *, + billing: Billing, + client: AsyncMobilerun | None = None, + ) -> JSON: + """Create a version of a function.""" + async with sdk_context(billing, client) as sdk: + return json_data( + await sdk.compute.functions.versions.create( + function_id, source=source, idempotency_key=idempotency_key + ) + ) + + @staticmethod + @BillingPolicy.guard(Billing.NO_COMMERCE) + async def delete_function( + function_id: str, *, billing: Billing, client: AsyncMobilerun | None = None + ) -> None: + """Delete a function.""" + async with sdk_context(billing, client) as sdk: + await sdk.compute.functions.delete(function_id) diff --git a/mobilerun/sandbox/clients/helpers/README.md b/mobilerun/sandbox/clients/helpers/README.md new file mode 100644 index 000000000..42926b57f --- /dev/null +++ b/mobilerun/sandbox/clients/helpers/README.md @@ -0,0 +1,9 @@ +# Transport helpers + +Shared support for the [sandbox SDK resource adapters](../README.md). For a +read, `async with sdk_context(billing, client, "List flows") as sdk` opens or +borrows an SDK client and translates failures with that operation name. + +| File | Role | +| --- | --- | +| `transport.py` | Client lifetime, paged records, and SDK-to-JSON encoding. | diff --git a/mobilerun/sandbox/clients/helpers/__init__.py b/mobilerun/sandbox/clients/helpers/__init__.py new file mode 100644 index 000000000..c88559368 --- /dev/null +++ b/mobilerun/sandbox/clients/helpers/__init__.py @@ -0,0 +1 @@ +"""SDK transport support shared by sandbox cloud resources.""" diff --git a/mobilerun/sandbox/clients/helpers/transport.py b/mobilerun/sandbox/clients/helpers/transport.py new file mode 100644 index 000000000..8a41595cc --- /dev/null +++ b/mobilerun/sandbox/clients/helpers/transport.py @@ -0,0 +1,92 @@ +"""Shared SDK lifetime, paging, and JSON boundary for sandbox transports.""" + +from collections.abc import AsyncIterator, Awaitable, Callable +from contextlib import asynccontextmanager, nullcontext +from typing import Any + +import httpx +from mobilerun_sdk import APIError, AsyncMobilerun + +from mobilerun.clients.cloud.client import cloud_client +from mobilerun.clients.cloud.errors import CloudErrorMapper +from mobilerun.models.billing import Billing + +from ...errors import FlowCapabilityError +from ...models import JSON + + +def unwrap(response: Any) -> Any: + """Unwrap an SDK envelope without serializing its contents.""" + if isinstance(response, dict): + return response.get("data", response) + return getattr(response, "data", response) + + +def record_field(record: Any, attribute: str, alias: str) -> Any: + """Read a field from an SDK model or from an already decoded record.""" + if isinstance(record, dict): + return record[alias] + if not hasattr(record, attribute): + raise KeyError(alias) + return getattr(record, attribute) + + +def json_record(response: Any) -> Any: + """Encode one SDK model using the public JSON field names.""" + if hasattr(response, "model_dump"): + return response.model_dump(by_alias=True, mode="json") + return response + + +def json_data(response: Any) -> Any: + """Encode and unwrap an SDK response at the JSON boundary.""" + return unwrap(json_record(response)) + + +@asynccontextmanager +async def sdk_context( + billing: Billing, + client: AsyncMobilerun | None, + operation: str = "Cloud function request", +) -> AsyncIterator[AsyncMobilerun]: + async with ( + nullcontext(client) if client is not None else cloud_client(billing=billing) + ) as sdk: + try: + yield sdk + except (APIError, httpx.HTTPError) as exc: + raise CloudErrorMapper.from_exception(exc, operation) from None + + +async def collect_pages( + method: Callable[..., Awaitable[Any]], + *args: Any, + limit: int | None = None, + omit_none: bool = False, + **kwargs: Any, +) -> list[Any]: + if limit is not None and limit <= 0: + return [] + result: list[Any] = [] + page = 1 + while True: + data = unwrap(await method(*args, page=page, page_size=100, **kwargs)) + if not hasattr(data, "items") or not hasattr(data, "pagination"): + # JSON-compatible envelopes supplied by decoded response providers. + data = json_data(data) + items = record_field(data, "items", "items") + pagination = record_field(data, "pagination", "pagination") + result.extend(item for item in items if not omit_none or item is not None) + if not record_field(pagination, "has_next", "hasNext") or ( + limit is not None and len(result) >= limit + ): + return result if limit is None else result[:limit] + page += 1 + + +def workflow_parameters(params: JSON, allowed: set[str]) -> JSON: + if not isinstance(params, dict) or not params.keys() <= allowed: + raise FlowCapabilityError( + operation="Workflow parameters", code="request_failed" + ) + return params diff --git a/mobilerun/sandbox/clients/run_logs.py b/mobilerun/sandbox/clients/run_logs.py new file mode 100644 index 000000000..238bd9f20 --- /dev/null +++ b/mobilerun/sandbox/clients/run_logs.py @@ -0,0 +1,44 @@ +"""Sandbox run logs transport.""" + +import httpx +from mobilerun_sdk import AsyncMobilerun + +from mobilerun.clients.cloud.billing_policy import BillingPolicy +from mobilerun.clients.cloud.errors import CloudErrorMapper +from mobilerun.clients.cloud.signed_http import SignedHTTP +from mobilerun.models.billing import Billing + +from .helpers.transport import record_field, sdk_context, unwrap + + +class RunLogTransport: + """Cloud operations for this sandbox resource.""" + + @staticmethod + @BillingPolicy.guard(Billing.NO_COMMERCE) + async def run_logs( + run_id: str, *, billing: Billing, client: AsyncMobilerun | None = None + ) -> str: + """Download run logs without sending SDK credentials to the signed URL.""" + async with sdk_context(billing, client) as sdk: + url = record_field( + unwrap(await sdk.compute.runs.logs(run_id)), "url", "url" + ) + try: + async with SignedHTTP.open( + httpx.AsyncClient(follow_redirects=True, timeout=30, trust_env=False) + ) as downloader: + response = await downloader.get(url) + response.raise_for_status() + return response.text + except ( + httpx.HTTPError, + httpx.InvalidURL, + httpx.CookieConflict, + httpx.StreamError, + TypeError, + ): + # The exception and response may include the signed URL or arbitrary headers. + raise CloudErrorMapper.from_exception( + httpx.RequestError("Log download failed"), "Download run logs" + ) from None diff --git a/mobilerun/sandbox/clients/staging.py b/mobilerun/sandbox/clients/staging.py new file mode 100644 index 000000000..0eda79d75 --- /dev/null +++ b/mobilerun/sandbox/clients/staging.py @@ -0,0 +1,280 @@ +"""Sandbox staging transport.""" + +from dataclasses import dataclass +from typing import cast + +import httpx +from mobilerun_sdk import APIError, AsyncMobilerun +from mobilerun_sdk.types.workflows.action_create_params import ActionCreateParams +from mobilerun_sdk.types.workflows.flow_create_params import ( + Action, + Delivery, + FlowCreateParams, +) +from mobilerun_sdk.types.workflows.trigger_create_params import TriggerCreateParams + +from mobilerun.clients.cloud.billing_policy import BillingPolicy +from mobilerun.clients.cloud.errors import CloudErrorMapper +from mobilerun.models.billing import Billing + +from ..errors import FlowCapabilityError, FlowStagingError +from ..models import FILE_UPLOAD_USES, JSON +from .helpers.transport import collect_pages, record_field, sdk_context, unwrap + + +@dataclass(frozen=True) +class _StagedStep: + key: str + uses: str + name: str + params: dict[str, object] + + +@dataclass(frozen=True) +class _StagedDocument: + trigger: TriggerCreateParams + steps: list[_StagedStep] + delivery: Delivery | None + device_ids: list[str] | None + + +class WorkflowStagingTransport: + """Cloud operations for this sandbox resource.""" + + @staticmethod + async def _catalog_entry_id(sdk: AsyncMobilerun, step_name: str) -> str: + """Resolve the unique catalog entry for step_name: workflow actions are created by ID.""" + entries = await collect_pages(sdk.workflows.action_catalog.list) + matches = [ + record_field(item, "id", "id") + for item in entries + if (item.get("stepName") if isinstance(item, dict) else item.step_name) + == step_name + ] + if len(matches) != 1: + label = ( + step_name + if step_name in ("functions.run", "webhooks.send", FILE_UPLOAD_USES) + else "sandbox step" + ) + count = "no entries" if not matches else "more than one entry" + message = f"Workflow action catalog: found {count} for {label}" + error = FlowCapabilityError( + message, operation=message, code="request_failed" + ) + error.value_safe = True # Both interpolated labels are allowlisted above. + raise error + return matches[0] + + @staticmethod + def _document(document: JSON) -> _StagedDocument: + """Validate the supported playground document before any SDK calls.""" + try: + if not ( + set(document) + <= {"version", "name", "on", "settings", "steps", "devices"} + ): + raise ValueError + if not (document["version"] == 1 and isinstance(document["name"], str)): + raise ValueError + settings = document.get("settings", {}) + if not ( + isinstance(settings, dict) + and settings.keys() <= {"recording", "delivery"} + and settings.get("recording", {"mode": "off"}) == {"mode": "off"} + ): + raise ValueError + delivery: Delivery | None = None + if "delivery" in settings: + raw_delivery = settings["delivery"] + if not ( + isinstance(raw_delivery, dict) + and raw_delivery.keys() == {"destination", "folder"} + and raw_delivery["destination"] == "mobilerun" + and isinstance(raw_delivery["folder"], str) + and raw_delivery["folder"].startswith("/") + ): + raise ValueError + delivery = { + "destination": "mobilerun", + "folder": raw_delivery["folder"], + } + on = document["on"] + if not (isinstance(on, dict) and len(on) == 1): + raise ValueError + trigger: TriggerCreateParams + if "custom" in on: + custom = on["custom"] + if not (isinstance(custom, dict) and set(custom) <= {"inputs"}): + raise ValueError + trigger = {"name": document["name"], "activation": "custom"} + if "inputs" in custom: + if not (isinstance(custom["inputs"], dict)): + raise ValueError + trigger["custom_payload_schema"] = custom["inputs"] + else: + schedule = on["schedule"] + if not ( + isinstance(schedule, dict) and set(schedule) == {"cron", "timezone"} + ): + raise ValueError + if not (all(isinstance(schedule[k], str) for k in schedule)): + raise ValueError + trigger = { + "name": document["name"], + "activation": "schedule", + "schedule_rule": {"type": "cron", "expression": schedule["cron"]}, + "timezone": schedule["timezone"], + } + raw_steps = document["steps"] + if not (isinstance(raw_steps, list) and raw_steps): + raise ValueError + steps: list[_StagedStep] = [] + for step in raw_steps: + if not ( + isinstance(step, dict) + and set(step) == {"id", "name", "uses", "with"} + ): + raise ValueError + if not ( + step["uses"] in ("functions.run", "webhooks.send", FILE_UPLOAD_USES) + and isinstance(step["with"], dict) + ): + raise ValueError + if not (isinstance(step["id"], str) and isinstance(step["name"], str)): + raise ValueError + steps.append( + _StagedStep( + key=step["id"], + uses=step["uses"], + name=step["name"], + params=step["with"], + ) + ) + device_ids = None + if "devices" in document: + if not ( + isinstance(document["devices"], list) + and all(isinstance(d, str) for d in document["devices"]) + ): + raise ValueError + device_ids = document["devices"] + return _StagedDocument( + trigger=trigger, steps=steps, delivery=delivery, device_ids=device_ids + ) + except (ValueError, KeyError, TypeError): + raise FlowCapabilityError( + operation="Stage flow", code="request_failed" + ) from None + + @staticmethod + @BillingPolicy.guard(Billing.NO_COMMERCE) + async def prepare_action_payloads( + document: JSON, *, billing: Billing, client: AsyncMobilerun | None = None + ) -> list[JSON]: + """Resolve the exact SDK action bodies before the staging intent is journaled.""" + staged = WorkflowStagingTransport._document(document) + async with sdk_context(billing, client, "Resolve sandbox actions") as sdk: + catalog = { + uses: await WorkflowStagingTransport._catalog_entry_id(sdk, uses) + for uses in dict.fromkeys(step.uses for step in staged.steps) + } + requests: list[ActionCreateParams] = [ + { + "catalog_entry_id": catalog[step.uses], + "name": step.name, + "params": step.params, + } + for step in staged.steps + ] + return [dict(request) for request in requests] + + @staticmethod + @BillingPolicy.guard(Billing.PAID) + async def create_document( + document: JSON, + idempotency_key: str, + *, + action_payloads: list[JSON] | None = None, + billing: Billing, + client: AsyncMobilerun | None = None, + ) -> JSON: + """Create supported inline workflow resources and verify disabled staging.""" + staged = WorkflowStagingTransport._document(document) + trigger_id = None + action_ids: list[str] = [] + flow_id = None + async with sdk_context(billing, client, "Cloud workflow request") as sdk: + try: + if action_payloads is None: + action_payloads = ( + await WorkflowStagingTransport.prepare_action_payloads( + document, billing=billing, client=sdk + ) + ) + if len(action_payloads) != len(staged.steps): + raise ValueError("Incomplete action payloads") + trigger_id = record_field( + unwrap( + await sdk.workflows.triggers.create( + **staged.trigger, + idempotency_key=idempotency_key + ":trigger", + ) + ), + "id", + "id", + ) + refs: list[Action] = [] + for position, step in enumerate(staged.steps): + # Recovered requests were journaled as JSON before staging. + payload = cast(ActionCreateParams, action_payloads[position]) + action = unwrap( + await sdk.workflows.actions.create( + **payload, + idempotency_key=idempotency_key + f":action:{position}", + ) + ) + action_id = record_field(action, "id", "id") + action_ids.append(action_id) + refs.append( + { + "action_id": action_id, + "position": position, + "key": step.key, + } + ) + flow: FlowCreateParams = { + "name": staged.trigger["name"], + "trigger_id": trigger_id, + "actions": refs, + "enabled": False, + "recording_enabled": False, + } + if staged.delivery is not None: + flow["delivery"] = staged.delivery + if staged.device_ids is not None: + flow["device_ids"] = staged.device_ids + flow_id = record_field( + unwrap( + await sdk.workflows.flows.create( + **flow, + idempotency_key=idempotency_key + ":flow", + ) + ), + "id", + "id", + ) + verified = unwrap(await sdk.workflows.flows.retrieve(flow_id)) + if record_field(verified, "enabled", "enabled") is not False: + raise FlowStagingError(trigger_id, action_ids, flow_id) + return { + "flowId": flow_id, + "triggerId": trigger_id, + "actionIds": action_ids, + } + except (APIError, httpx.HTTPError) as exc: + if trigger_id is not None: + raise FlowStagingError(trigger_id, action_ids, flow_id) from None + raise CloudErrorMapper.from_exception(exc, "Stage flow") from None + except (KeyError, TypeError, ValueError): + raise FlowStagingError(trigger_id, action_ids, flow_id) from None diff --git a/mobilerun/sandbox/clients/triggers.py b/mobilerun/sandbox/clients/triggers.py new file mode 100644 index 000000000..549f6a715 --- /dev/null +++ b/mobilerun/sandbox/clients/triggers.py @@ -0,0 +1,90 @@ +"""Sandbox triggers transport.""" + +from mobilerun_sdk import AsyncMobilerun + +from mobilerun.clients.cloud.billing_policy import BillingPolicy +from mobilerun.models.billing import Billing + +from ..models import JSON +from .helpers.transport import json_data, sdk_context, workflow_parameters + + +class WorkflowTriggerTransport: + """Cloud operations for this sandbox resource.""" + + _FIELDS = { + "activation", + "name", + "conditions", + "custom_payload_schema", + "description", + "event_type", + "payload", + "schedule_rule", + "timezone", + } + + @staticmethod + @BillingPolicy.guard(Billing.NO_COMMERCE) + async def get_trigger( + trigger_id: str, *, billing: Billing, client: AsyncMobilerun | None = None + ) -> JSON: + """Retrieve a trigger.""" + async with sdk_context(billing, client, "Get trigger") as sdk: + return json_data( + await sdk.workflows.triggers.retrieve( + trigger_id, + ) + ) + + @staticmethod + @BillingPolicy.guard(Billing.PAID) + async def update_trigger( + trigger_id: str, + params: JSON, + idempotency_key: str, + *, + billing: Billing, + client: AsyncMobilerun | None = None, + ) -> JSON: + """Update a workflow trigger from SDK fields.""" + params = workflow_parameters(params, WorkflowTriggerTransport._FIELDS) + async with sdk_context(billing, client, "Update trigger") as sdk: + return json_data( + await sdk.workflows.triggers.update( + trigger_id, + **params, + idempotency_key=idempotency_key, + ) + ) + + @staticmethod + @BillingPolicy.guard(Billing.PAID) + async def fire_trigger( + trigger_id: str, + payload: JSON, + idempotency_key: str, + *, + billing: Billing, + client: AsyncMobilerun | None = None, + ) -> JSON: + """Fire a custom trigger.""" + async with sdk_context(billing, client, "Fire trigger") as sdk: + return json_data( + await sdk.workflows.triggers.fire( + trigger_id, + payload=payload, + idempotency_key=idempotency_key, + ) + ) + + @staticmethod + @BillingPolicy.guard(Billing.NO_COMMERCE) + async def delete_trigger( + trigger_id: str, *, billing: Billing, client: AsyncMobilerun | None = None + ) -> None: + """Delete a workflow trigger.""" + async with sdk_context(billing, client, "Delete trigger") as sdk: + await sdk.workflows.triggers.delete( + trigger_id, + ) diff --git a/mobilerun/sandbox/deployment.py b/mobilerun/sandbox/deployment.py index 1dc978dd5..1882f1fe4 100644 --- a/mobilerun/sandbox/deployment.py +++ b/mobilerun/sandbox/deployment.py @@ -1,139 +1,42 @@ """First deploy, redeploy and their recovery.""" -import asyncio -import copy -import json -import time from pathlib import Path -from typing import Literal from mobilerun.models.billing import Billing from . import clients -from .billing import require_paid +from .billing import require_paid, resolve_billing +from .deployments.executor import CutoverExecutor +from .deployments.initial import InitialDeployment +from .deployments.planner import CutoverPlanner from .documents import ( build_document, equivalent_document, - has_authored_steps, has_ref, same_json, - without_webhook, ) from .errors import ( - FlowStagingError, SandboxDeclarationError, SandboxDeploymentConflict, - SandboxDeploymentError, ) from .flows import ( - WebhookBindingError, - check_activation_webhook, - check_webhook, - delete_verified, - get_flow, owned_remote, - pinned_version, remote_request, - require_unshared, valid_id, - valid_version, -) -from .models import ( - JSON, - Artifact, - DeploymentReceipt, - Endpoint, - OwnershipReceipt, - resolve_billing, - validate_device, ) +from .helpers.declaration_values import validate_device +from .helpers.deployment import wait_ready +from .models import Artifact, DeploymentReceipt, OwnershipReceipt from .packaging import package, verify_scheduled_artifact from .receipts import ( ReceiptStore, checkpoint, current_scope, - pending_cutover, pending_initial, - read_authored_document, - require_current_cutover_receipt, - sha256_hex, - stage_key, ) from .settings import get_sandbox_settings -async def _wait_ready( - function_id: str, version: int, billing: Billing, receipt: OwnershipReceipt -) -> None: - deadline = time.monotonic() + 120.0 - while True: - remaining = deadline - time.monotonic() - if remaining <= 0: - raise SandboxDeploymentError( - "Sandbox version inspection timed out", receipt=receipt - ) - try: - result = await asyncio.wait_for( - clients.get_version(function_id, version, billing=billing), remaining - ) - except TimeoutError: - raise SandboxDeploymentError( - "Sandbox version inspection timed out", receipt=receipt - ) from None - if time.monotonic() >= deadline: - raise SandboxDeploymentError( - "Sandbox version inspection timed out", receipt=receipt - ) - if result.get("version") != version: - raise SandboxDeploymentError( - "Invalid sandbox version response", receipt=receipt - ) - status = result.get("status") - if status == "ready": - return - if status == "rejected": - raise SandboxDeploymentError("Sandbox version rejected", receipt=receipt) - if status not in {"pending", "pending_inspection", "inspecting", "processing"}: - raise SandboxDeploymentError( - "Invalid sandbox version status", receipt=receipt - ) - remaining = deadline - time.monotonic() - if remaining <= 0: - raise SandboxDeploymentError( - "Sandbox version inspection timed out", receipt=receipt - ) - await asyncio.sleep( - min(get_sandbox_settings().MOBILERUN_SANDBOX_POLL_INTERVAL, remaining) - ) - - -async def _can_replace_initial_version( - state: JSON, - receipt: OwnershipReceipt, - found: JSON | None, - flows: list[JSON], - mode: Billing, -) -> bool: - """Only a rejected, receipt-owned version with no staged flow can be superseded.""" - if flows or receipt.flow_id or receipt.trigger_id or receipt.action_ids: - return False - if ( - state["function_pending"] - or state["flow_pending"] - or state["document"] is not None - ): - return False - if not receipt.function_id or not found or found.get("id") != receipt.function_id: - return False - version = state["version"] - if version is None or (found.get("latestVersion") or {}).get("version") != version: - return False - record = await clients.get_version( - receipt.function_id, valid_version(version), billing=mode - ) - return record.get("version") == version and record.get("status") == "rejected" - - async def deploy_file( path: Path, *, @@ -169,6 +72,7 @@ async def deploy_file( raise SandboxDeclarationError("Endpoint schema contains unsupported $ref") scope = current_scope() store = ReceiptStore(scope, decl.name) + first = InitialDeployment(store, artifact, selected, mode) with store.lock(): receipt = store.read() initial = pending_initial(receipt) if receipt else None @@ -232,9 +136,7 @@ async def deploy_file( "Retry with the original sandbox source to recover the function ID before cleanup", receipt=receipt, ) - receipt = await _create_initial_function( - store, receipt, artifact, initial, found, mode - ) + receipt = await first.create_function(receipt, initial, found) raise SandboxDeploymentConflict( "Initial intent evidence is missing; cleanup is required before redeploying", receipt=receipt, @@ -246,8 +148,8 @@ async def deploy_file( ): if initial[ "digest" - ] == artifact.digest or not await _can_replace_initial_version( - initial, receipt, found, flows, mode + ] == artifact.digest or not await first.can_replace_version( + initial, receipt, found, flows ): raise SandboxDeploymentConflict( "Finish the original initial deployment first", receipt=receipt @@ -281,21 +183,22 @@ async def deploy_file( raise SandboxDeploymentConflict( "Initial staging intent changed", receipt=receipt ) - await _wait_ready(function_id, initial["version"], mode, receipt) - return await _finish_initial_activation( - store, receipt, artifact, initial, mode, flow.get("enabled") + await wait_ready(function_id, initial["version"], mode, receipt) + return await first.finish_activation( + receipt, initial, flow.get("enabled") ) if flows and not initial["flow_pending"]: raise SandboxDeploymentConflict( "Sandbox flow is not owned", receipt=receipt ) - return await _first_deploy( - store, receipt, artifact, selected, found, mode, flows - ) + return await first.deploy(receipt, found, flows) if receipt and receipt.flow_id: - return await _redeploy( - store, receipt, artifact, selected, found, all_flows, mode + plan = await CutoverPlanner(store, artifact, selected, mode).plan( + receipt, found, all_flows ) + if isinstance(plan, DeploymentReceipt): + return plan + return await CutoverExecutor.execute(plan) if flows: raise SandboxDeploymentConflict( "Sandbox flow is not owned", receipt=receipt @@ -312,695 +215,4 @@ async def deploy_file( None, (), ) - return await _first_deploy( - store, receipt, artifact, selected, found, mode, flows - ) - - -async def _create_initial_function( - store: ReceiptStore, - receipt: OwnershipReceipt, - artifact: Artifact, - state: JSON, - found: JSON | None, - mode: Billing, -) -> OwnershipReceipt: - """Create or replay the journaled function only; never infer its ID from a name.""" - key = state["function_key"] - receipt = store.record_stage(receipt, "function:create", key) - try: - result = await clients.create_function( - receipt.name, artifact.source, key, billing=mode - ) - except Exception: - raise SandboxDeploymentError( - "Sandbox function creation outcome uncertain; retry the original deployment", - receipt=receipt, - ) from None - function_id = valid_id(result.get("id")) - if receipt.function_id and receipt.function_id != function_id: - raise SandboxDeploymentConflict( - "Idempotent function response conflicts with remote state", receipt=receipt - ) - receipt = store.record_ids(receipt, function_id=function_id) - version = valid_version((result.get("latestVersion") or {}).get("version")) - state.update(function_pending=False, version=version) - receipt = checkpoint(store, receipt, state) - if found and found.get("id") != function_id: - raise SandboxDeploymentConflict( - "Idempotent function response conflicts with remote state", receipt=receipt - ) - return receipt - - -async def _first_deploy( - store: ReceiptStore, - receipt: OwnershipReceipt, - artifact: Artifact, - selected: str | None, - found: JSON | None, - mode: Billing, - visible_flows: list[JSON], -) -> DeploymentReceipt: - scope, decl = store.scope, artifact.declaration - state = pending_initial(receipt) - resuming = state is not None - if state is None: - await check_webhook(decl.webhook, receipt, mode) - if found is None and receipt.function_id: - raise SandboxDeploymentConflict( - "Owned sandbox function is missing", receipt=receipt - ) - # Completed cleanup starts a new intent, not a replay of deleted creations. - # Journal position is persisted through the keys below before any request. - intent_digest = sha256_hex( - json.dumps([artifact.digest, selected, len(receipt.stages)]) - ) - state = dict( - stage="initial", - preview_document=build_document( - artifact, - "placeholder", - 1, - device=selected, - ), - digest=artifact.digest, - device=selected, - function_pending=found is None, - flow_pending=False, - function_key=stage_key(scope, decl.name, intent_digest, "function:create"), - flow_key=stage_key(scope, decl.name, intent_digest, "flow:create"), - version=None, - document=None, - status="created" if found is None else "unchanged", - complete=False, - ) - receipt = checkpoint(store, receipt, state) - if state["function_pending"]: - receipt = await _create_initial_function( - store, receipt, artifact, state, found, mode - ) - elif state["version"] is None: - if found is None: - raise SandboxDeploymentConflict( - "Owned sandbox function is missing", receipt=receipt - ) - function_id = valid_id(found.get("id")) - version = valid_version((found.get("latestVersion") or {}).get("version")) - source = None - if not state.get("replacing_rejected"): - await _wait_ready(function_id, version, mode, receipt) - source = await clients.get_source(function_id, version, billing=mode) - if source == artifact.source: - status = "unchanged" - else: - key = stage_key(scope, decl.name, artifact.digest, "version:create") - receipt = store.record_stage(receipt, "version:create", key) - result = await clients.create_version( - function_id, artifact.source, key, billing=mode - ) - version = valid_version(result.get("version")) - status = "pushed" - state.update(version=version, status=status) - receipt = checkpoint(store, receipt, state) - function_id = valid_id(receipt.function_id) - version = valid_version(state["version"]) - await _wait_ready(function_id, version, mode, receipt) - receipt = store.record_ids(receipt, digest=artifact.digest) - if state["flow_pending"]: - # Replay the exact staged payload before checking external dependencies. - document = state["document"] - else: - document = build_document(artifact, function_id, version, device=selected) - if ( - document is not None - and (await clients.validate_document(document, billing=mode)).get("valid") - is not True - ): - raise SandboxDeploymentError( - "Sandbox flow validation failed", receipt=receipt - ) - if document is not None: - key = state["flow_key"] - if not state["flow_pending"]: - if resuming: - await check_webhook(decl.webhook, receipt, mode) - payloads = await clients.prepare_action_payloads(document, billing=mode) - state.update(flow_pending=True, document=document, action_payloads=payloads) - receipt = checkpoint(store, receipt, state) - elif not isinstance(state.get("action_payloads"), list): - raise SandboxDeploymentConflict( - "Cannot safely replay initial staging without journaled action payloads", - receipt=receipt, - ) - receipt = store.record_stage(receipt, "flow:create", key) - try: - staged = await clients.create_document( - document, key, billing=mode, action_payloads=state["action_payloads"] - ) - except FlowStagingError as exc: - receipt = store.record_ids( - receipt, - flow_id=exc.flow_id or receipt.flow_id, - trigger_id=exc.trigger_id or receipt.trigger_id, - action_ids=tuple(dict.fromkeys([*receipt.action_ids, *exc.action_ids])), - ) - raise SandboxDeploymentError( - "Sandbox flow staging failed", receipt=receipt - ) from None - except Exception: - raise SandboxDeploymentError( - "Sandbox flow creation outcome uncertain; retry the original deployment", - receipt=receipt, - ) from None - if not isinstance(staged, dict): - raise SandboxDeploymentError( - "Invalid sandbox flow response", receipt=receipt - ) - flow_id = valid_id(staged.get("flowId")) - if receipt.flow_id and receipt.flow_id != flow_id: - raise SandboxDeploymentConflict( - "Idempotent flow response conflicts with remote state", receipt=receipt - ) - receipt = store.record_ids(receipt, flow_id=flow_id) - trigger_id = valid_id(staged.get("triggerId")) - receipt = store.record_ids(receipt, trigger_id=trigger_id) - actions = staged.get("actionIds") - if not isinstance(actions, list) or not actions: - raise SandboxDeploymentError( - "Invalid sandbox flow response", receipt=receipt - ) - action_ids: tuple[str, ...] = () - for action in actions: - action_ids += (valid_id(action),) - receipt = store.record_ids(receipt, action_ids=action_ids) - if len(set(action_ids)) != len(document["steps"]) or len(action_ids) != len( - document["steps"] - ): - raise SandboxDeploymentError( - "Incomplete sandbox action IDs", receipt=receipt - ) - if any(f.get("id") != flow_id for f in visible_flows): - raise SandboxDeploymentConflict( - "Idempotent flow response conflicts with remote state", receipt=receipt - ) - store.write_yaml(document) - state.update(flow_pending=False, activation_pending=True) - receipt = checkpoint(store, receipt, state) - return await _finish_initial_activation( - store, receipt, artifact, state, mode, None - ) - state["complete"] = True - receipt = checkpoint(store, receipt, state) - return _deployment(receipt, artifact, version, state["status"]) - - -async def _finish_initial_activation( - store: ReceiptStore, - receipt: OwnershipReceipt, - artifact: Artifact, - state: JSON, - mode: Billing, - current: bool | None, -) -> DeploymentReceipt: - """Close staging only after the flow reflects the journaled activation intent.""" - flow_id = valid_id(receipt.flow_id) - target = state.get("enabled", True) - if target: - await check_activation_webhook(state["document"], receipt, mode) - try: - if current is not target: - stage = "flow:enable" if target else "flow:disable" - key = stage_key(store.scope, receipt.name, artifact.digest, stage) - receipt = store.record_stage(receipt, stage, key) - operation = clients.enable_flow if target else clients.disable_flow - updated = await operation(flow_id, billing=mode) - if not isinstance(updated, dict) or updated.get("enabled") is not target: - raise ValueError("Activation not confirmed") - if (await get_flow(flow_id, mode))["enabled"] is not target: - raise ValueError("Activation not confirmed") - except Exception: - raise SandboxDeploymentError( - "Sandbox flow activation failed or uncertain", receipt=receipt - ) from None - state["complete"] = True - receipt = checkpoint(store, receipt, state) - return _deployment(receipt, artifact, state["version"], state["status"]) - - -def _deployment( - receipt: OwnershipReceipt, - artifact: Artifact, - version: int, - status: Literal["created", "pushed", "unchanged"], - warnings: tuple[str, ...] = (), -) -> DeploymentReceipt: - endpoint = None - if artifact.declaration.has_endpoint: - trigger_id = valid_id(receipt.trigger_id) - endpoint = Endpoint( - receipt.origin.rstrip("/") + "/triggers/" + trigger_id + "/fire", - trigger_id, - ) - return DeploymentReceipt( - receipt.name, - valid_id(receipt.function_id), - version, - status, - receipt.flow_id, - receipt.trigger_id, - receipt.action_ids, - artifact.digest, - endpoint, - warnings, - ) - - -async def _redeploy( - store: ReceiptStore, - receipt: OwnershipReceipt, - artifact: Artifact, - selected: str | None, - found: JSON | None, - all_flows: list[JSON], - mode: Billing, -) -> DeploymentReceipt: - """Reconcile an owned flow with an on-disk write-ahead cutover journal.""" - state = pending_cutover(receipt) - require_current_cutover_receipt(state, receipt) - if not found or not receipt.trigger_id or not receipt.action_ids: - raise SandboxDeploymentConflict( - "Sandbox ownership is incomplete", receipt=receipt - ) - valid_id(receipt.function_id) - flow_id = valid_id(receipt.flow_id) - valid_id(receipt.trigger_id) - for action_id in receipt.action_ids: - valid_id(action_id) - flow = await get_flow(receipt.flow_id, mode) - expected_name = receipt.name + get_sandbox_settings().MOBILERUN_SANDBOX_FLOW_SUFFIX - if ( - flow.get("name") != expected_name - or sum(f.get("name") == expected_name for f in all_flows) != 1 - ): - raise SandboxDeploymentConflict( - "Sandbox flow ownership mismatch", receipt=receipt - ) - await require_unshared(receipt, mode) - bindings = tuple( - valid_id(a.get("actionId")) - for a in await clients.list_actions(receipt.flow_id, billing=mode) - ) - allowed = ( - [tuple(state["old_ids"]), tuple(state["new_ids"])] - if state - else [receipt.action_ids] - ) - if bindings not in allowed: - raise SandboxDeploymentConflict( - "Sandbox action bindings changed", receipt=receipt - ) - actual = await clients.get_document(receipt.flow_id, billing=mode) - if state: - requested = build_document( - artifact, receipt.function_id, state["version"], device=selected - ) - desired_changed = not same_json(requested, state["desired"]) - retarget = ( - state.get("webhook_unusable") - and desired_changed - and requested is not None - and same_json(without_webhook(requested), without_webhook(state["desired"])) - ) - if ( - state["digest"] != artifact.digest - or state["device"] != selected - or (desired_changed and not retarget) - ): - raise SandboxDeploymentConflict( - "Finish the pending sandbox deployment first", receipt=receipt - ) - expected = copy.deepcopy(state["before"]) - # Only the stage in flight may have either its old or new remote value. - candidates = [expected] - for stage, field in ( - ("replace", "steps"), - ("trigger", "on"), - ("devices", "devices"), - ): - if stage in state["done"]: - for candidate in candidates: - candidate[field] = state["desired"].get(field, []) - elif state.get("pending") == stage: - changed = copy.deepcopy(candidates[0]) - changed[field] = state["desired"].get(field, []) - candidates.append(changed) - delivery_candidates = [] - if "delivery" in state["done"]: - delivery_candidates = candidates - elif state.get("pending") == "delivery": - delivery_candidates = [copy.deepcopy(candidates[0])] - candidates.extend(delivery_candidates) - for candidate in delivery_candidates: - settings = candidate.setdefault("settings", {}) - if delivery := state["desired"].get("settings", {}).get("delivery"): - settings["delivery"] = delivery - else: - settings.pop("delivery", None) - if not any(equivalent_document(actual, c) for c in candidates): - raise SandboxDeploymentConflict( - "Sandbox remote state diverged", receipt=receipt - ) - version = state["version"] - await _wait_ready(receipt.function_id, version, mode, receipt) - desired = state["desired"] - if retarget and requested is not None: - await check_activation_webhook(requested, receipt, mode) - if (await clients.validate_document(requested, billing=mode)).get( - "valid" - ) is not True: - raise SandboxDeploymentError( - "Sandbox flow validation failed", receipt=receipt - ) - # The observed document is a verified cutover state, not new ownership. - # Keep every known action until the replacement is confirmed active. - state.update( - before=actual, - desired=requested, - action_payloads=await clients.prepare_action_payloads( - requested, billing=mode - ), - old_ids=list(bindings), - retire_ids=list(receipt.action_ids), - new_ids=[], - done=[], - pending=None, - webhook_unusable=False, - retarget_generation=len(receipt.stages), - ) - receipt = checkpoint(store, receipt, state) - desired = requested - else: - has_yaml = store.yaml_path.exists() - authored = read_authored_document(store, receipt) - if has_yaml or authored is not None: - if ( - not isinstance(authored, dict) - or (not has_yaml and not has_authored_steps(authored)) - or not equivalent_document(actual, authored) - ): - raise SandboxDeploymentConflict( - "Sandbox remote document changed", receipt=receipt - ) - pinned = pinned_version(receipt.function_id, actual, for_redeploy=True) - version = pinned - source = await clients.get_source(receipt.function_id, version, billing=mode) - if source != artifact.source: - version = valid_version((found.get("latestVersion") or {}).get("version")) - if version != pinned: - source = await clients.get_source( - receipt.function_id, version, billing=mode - ) - if source == artifact.source: - await _wait_ready(receipt.function_id, version, mode, receipt) - await check_webhook(artifact.declaration.webhook, receipt, mode) - desired = build_document( - artifact, - receipt.function_id, - version, - device=selected, - ) - if desired is None: - raise SandboxDeploymentConflict( - "Remove the owned flow explicitly first", receipt=receipt - ) - if source == artifact.source and equivalent_document(actual, desired): - if artifact.declaration.webhook and not store.yaml_path.exists(): - store.write_yaml(desired) - return _deployment(receipt, artifact, version, "unchanged") - if authored is None: - raise SandboxDeploymentConflict( - "Sandbox authored document evidence is missing", receipt=receipt - ) - if source != artifact.source: - key = stage_key( - store.scope, - receipt.name, - artifact.digest, - f"version:create:{receipt.function_id}:{pinned}:{','.join(bindings)}", - ) - receipt = store.record_stage(receipt, "version:create", key) - result = await clients.create_version( - receipt.function_id, artifact.source, key, billing=mode - ) - version = valid_version(result.get("version")) - await _wait_ready(receipt.function_id, version, mode, receipt) - desired = build_document( - artifact, - receipt.function_id, - version, - device=selected, - ) - if (await clients.validate_document(desired, billing=mode)).get( - "valid" - ) is not True: - raise SandboxDeploymentError( - "Sandbox flow validation failed", receipt=receipt - ) - state = dict( - stage="cutover", - digest=artifact.digest, - device=selected, - version=version, - before=actual, - desired=desired, - action_payloads=await clients.prepare_action_payloads( - desired, billing=mode - ), - old_ids=list(receipt.action_ids), - new_ids=[], - enabled=flow["enabled"], - done=[], - pending=None, - complete=False, - ) - receipt = checkpoint(store, receipt, state) - - payloads = state.get("action_payloads") - if not isinstance(payloads, list) or len(payloads) != len(desired["steps"]): - raise SandboxDeploymentConflict( - "Cannot safely resume cutover without journaled action payloads", - receipt=receipt, - ) - - def save(): - nonlocal receipt - receipt = checkpoint(store, receipt, state) - - def intent(stage): - nonlocal receipt - state["pending"] = stage - save() - # Includes the full desired document, so device/schema-only changes get new keys. - identity = [state["desired"], state["old_ids"]] - if "retarget_generation" in state: - identity.append(state["retarget_generation"]) - digest = sha256_hex(json.dumps(identity, sort_keys=True)) - key = stage_key(store.scope, receipt.name, digest, stage) - receipt = store.record_stage(receipt, stage, key) - return key - - def done(stage): - state["done"].append(stage) - state["pending"] = None - save() - - delivery = desired.get("settings", {}).get("delivery") - delivery_changed = not same_json( - state["before"].get("settings", {}).get("delivery"), delivery - ) - - async def update_delivery() -> None: - if delivery_changed and "delivery" not in state["done"]: - key = intent("delivery") - await clients.update_flow_delivery( - valid_id(receipt.flow_id), delivery, key, billing=mode - ) - done("delivery") - - try: - activated = "enable" in state["done"] - if not activated: - # Re-prove shutdown, including after an uncertain enable. Once enable - # is confirmed, retries only verify the live flow and retire old actions. - key = stage_key(store.scope, receipt.name, artifact.digest, "disable") - receipt = store.record_stage(receipt, "disable", key) - await clients.disable_flow(receipt.flow_id, billing=mode) - if (await get_flow(receipt.flow_id, mode))["enabled"] is not False: - raise ValueError("Shutdown not confirmed") - if "disable" not in state["done"]: - state["done"].append("disable") - save() - for index, payload in enumerate(payloads): - stage = f"create:{index}" - if stage in state["done"]: - continue - key = intent(stage) - action = await clients.create_action( - payload, - key, - billing=mode, - ) - action_id = valid_id(action.get("id")) - state["new_ids"].append(action_id) - receipt = store.record_ids( - receipt, - action_ids=tuple(dict.fromkeys([*receipt.action_ids, action_id])), - ) - done(stage) - # The service permits uploads without delivery, but not the reverse. - if delivery is None: - await update_delivery() - if "replace" not in state["done"]: - if (await get_flow(receipt.flow_id, mode))["enabled"] is not False: - raise ValueError("Shutdown no longer confirmed") - await check_activation_webhook(desired, receipt, mode) - key = intent("replace") - refs = [ - dict(action_id=a, position=i, key=desired["steps"][i]["id"]) - for i, a in enumerate(state["new_ids"]) - ] - await clients.replace_flow_actions(receipt.flow_id, refs, key, billing=mode) - done("replace") - if ( - not same_json(state["before"]["on"], desired["on"]) - and "trigger" not in state["done"] - ): - await require_unshared(receipt, mode) - on = desired["on"] - params = dict( - activation="custom", - custom_payload_schema=on.get("custom", {}).get("inputs"), - schedule_rule=None, - timezone=None, - ) - if "schedule" in on: - params.update( - activation="schedule", - schedule_rule=dict(type="cron", expression=on["schedule"]["cron"]), - timezone=on["schedule"]["timezone"], - ) - key = intent("trigger") - await clients.update_trigger(receipt.trigger_id, params, key, billing=mode) - done("trigger") - if ( - not same_json( - state["before"].get("devices", []), desired.get("devices", []) - ) - and "devices" not in state["done"] - ): - key = intent("devices") - await clients.update_flow_devices( - receipt.flow_id, desired.get("devices", []), key, billing=mode - ) - done("devices") - if delivery is not None: - await update_delivery() - if not activated: - intent("verify") - await require_unshared(receipt, mode) - expected_enabled = state["enabled"] if activated else False - if (await get_flow(flow_id, mode))[ - "enabled" - ] is not expected_enabled or not equivalent_document( - await clients.get_document(flow_id, billing=mode), desired - ): - raise ValueError("Cutover verification failed") - verified = tuple( - a.get("actionId") for a in await clients.list_actions(flow_id, billing=mode) - ) - if verified != tuple(state["new_ids"]): - raise ValueError("Cutover bindings changed") - if not activated: - done("verify") - if state["enabled"] and not activated: - await check_activation_webhook(desired, receipt, mode) - intent("enable") - await clients.enable_flow(flow_id, billing=mode) - if (await get_flow(flow_id, mode))["enabled"] is not True: - raise ValueError("Enable not confirmed") - done("enable") - unresolved = [] - retire_ids: list[str] = ( - state["retire_ids"] if "retire_ids" in state else state["old_ids"] - ) - for action_id in retire_ids: - stage = "delete:" + action_id - if stage in state["done"]: - continue - try: - intent(stage) - await require_unshared(receipt, mode) - await delete_verified(clients.delete_action(action_id, billing=mode)) - done(stage) - except Exception: - unresolved.append(action_id) - if unresolved: - raise ValueError("Old actions unresolved") - receipt = store.record_ids( - receipt, action_ids=tuple(state["new_ids"]), digest=artifact.digest - ) - store.write_yaml(desired) - state["complete"] = True - save() - warnings = ( - () if state["enabled"] else ("Flow remains disabled (enabled=False)",) - ) - return _deployment(receipt, artifact, version, "pushed", warnings) - except Exception as exc: - # A confirmed activation must not be undone by a cleanup failure. - try: - restore_old = ( - isinstance(exc, WebhookBindingError) - and state["enabled"] - and not {"replace", "delivery"}.intersection(state["done"]) - and state.get("pending") not in ("replace", "delivery") - ) - if restore_old: - # Only definitions were created; no live binding or settings changed. - await require_unshared(receipt, mode) - current = await clients.get_document(flow_id, billing=mode) - current_ids = [ - row.get("actionId") - for row in await clients.list_actions(flow_id, billing=mode) - ] - if current_ids != state["old_ids"] or not equivalent_document( - current, state["before"] - ): - raise ValueError("Previous workflow state changed") - await check_activation_webhook(state["before"], receipt, mode) - key = stage_key( - store.scope, receipt.name, artifact.digest, "restore:enable" - ) - receipt = store.record_stage(receipt, "restore:enable", key) - await clients.enable_flow(flow_id, billing=mode) - elif "enable" not in state["done"]: - key = stage_key( - store.scope, receipt.name, artifact.digest, "failure:shutdown" - ) - receipt = store.record_stage(receipt, "failure:shutdown", key) - await clients.disable_flow(receipt.flow_id, billing=mode) - except Exception: - pass - try: - enabled = (await get_flow(receipt.flow_id, mode))["enabled"] - except Exception: - enabled = "uncertain" - state["warning"] = f"Cutover incomplete; flow enabled={enabled}" - if isinstance(exc, WebhookBindingError): - state["webhook_unusable"] = True - state[ - "warning" - ] += f". {exc}. Redeploy with a usable endpoint ID or remove webhook=." - save() - raise SandboxDeploymentError(state["warning"], receipt=receipt) from None + return await first.deploy(receipt, found, flows) diff --git a/mobilerun/sandbox/deployments/README.md b/mobilerun/sandbox/deployments/README.md new file mode 100644 index 000000000..b6de25155 --- /dev/null +++ b/mobilerun/sandbox/deployments/README.md @@ -0,0 +1,16 @@ +# Sandbox deployments + +`deploy_file()` in [`../deployment.py`](../deployment.py) selects initial +staging or an owned-flow cutover. For example, changing only the selected +device updates an existing workflow without publishing an identical function +version. No stage is assumed complete until its journal is checkpointed. + +| File | Role | +| --- | --- | +| `initial.py` | First deploy and replay of incomplete initial staging. | +| `planner.py` | Prove ownership and prepare the cutover. | +| `journal.py` | Persist pending and completed cutover stages. | +| `executor.py` | Apply, verify, activate, and retire actions. | +| `recovery.py` | On failure, restore a proven prior flow or leave an incomplete one stopped. | + +Deployments can incur charges. See the [sandbox guide](../README.md). diff --git a/mobilerun/sandbox/deployments/__init__.py b/mobilerun/sandbox/deployments/__init__.py new file mode 100644 index 000000000..5a514e0ae --- /dev/null +++ b/mobilerun/sandbox/deployments/__init__.py @@ -0,0 +1 @@ +"""Sandbox deployment and cutover components.""" diff --git a/mobilerun/sandbox/deployments/executor.py b/mobilerun/sandbox/deployments/executor.py new file mode 100644 index 000000000..44dc467be --- /dev/null +++ b/mobilerun/sandbox/deployments/executor.py @@ -0,0 +1,215 @@ +"""Apply a journaled workflow cutover in dependency order.""" + +from .. import clients +from ..documents import equivalent_document, same_json +from ..errors import SandboxDeploymentConflict +from ..flows import ( + check_activation_webhook, + delete_verified, + get_flow, + require_unshared, + valid_id, +) +from ..helpers.deployment import deployment_receipt +from ..models import JSON, DeploymentReceipt +from ..receipts import stage_key +from .journal import CutoverJournal +from .recovery import CutoverRecovery + + +class CutoverExecutor: + """Apply, verify and finalize each stage before advancing the journal.""" + + @classmethod + async def execute(cls, journal: CutoverJournal) -> DeploymentReceipt: + state, receipt = journal.state, journal.receipt + desired = state["desired"] + + payloads = state.get("action_payloads") + if not isinstance(payloads, list) or len(payloads) != len(desired["steps"]): + raise SandboxDeploymentConflict( + "Cannot safely resume cutover without journaled action payloads", + receipt=receipt, + ) + activated = "enable" in state["done"] + try: + if not activated: + await cls._confirm_shutdown(journal) + await cls._create_actions(journal, payloads) + await cls._switch_bindings(journal) + await cls._verify_and_activate(journal, activated) + await cls._retire_actions(journal) + journal.receipt = journal.store.record_ids( + journal.receipt, + action_ids=tuple(state["new_ids"]), + digest=journal.artifact.digest, + ) + journal.store.write_yaml(desired) + state["complete"] = True + journal.save() + warnings = ( + () if state["enabled"] else ("Flow remains disabled (enabled=False)",) + ) + return deployment_receipt( + journal.receipt, journal.artifact, state["version"], "pushed", warnings + ) + except Exception as exc: + await CutoverRecovery.fail(journal, exc) + + @staticmethod + async def _confirm_shutdown(journal: CutoverJournal) -> None: + store, artifact, mode = journal.store, journal.artifact, journal.mode + state, receipt = journal.state, journal.receipt + flow_id = valid_id(receipt.flow_id) + # Re-prove shutdown, including after an uncertain enable. Once enable + # is confirmed, retries only verify the live flow and retire old actions. + key = stage_key(store.scope, receipt.name, artifact.digest, "disable") + journal.receipt = store.record_stage(journal.receipt, "disable", key) + await clients.disable_flow(flow_id, billing=mode) + if (await get_flow(flow_id, mode))["enabled"] is not False: + raise ValueError("Shutdown not confirmed") + if "disable" not in state["done"]: + state["done"].append("disable") + journal.save() + + @staticmethod + async def _create_actions(journal: CutoverJournal, payloads: list[JSON]) -> None: + state, store, mode = journal.state, journal.store, journal.mode + for index, payload in enumerate(payloads): + stage = f"create:{index}" + if stage in state["done"]: + continue + key = journal.intent(stage) + action = await clients.create_action( + payload, + key, + billing=mode, + ) + action_id = valid_id(action.get("id")) + state["new_ids"].append(action_id) + journal.receipt = store.record_ids( + journal.receipt, + action_ids=tuple( + dict.fromkeys([*journal.receipt.action_ids, action_id]) + ), + ) + journal.done(stage) + + @staticmethod + async def _switch_bindings(journal: CutoverJournal) -> None: + state, mode = journal.state, journal.mode + flow_id = valid_id(journal.receipt.flow_id) + desired = state["desired"] + + delivery = desired.get("settings", {}).get("delivery") + delivery_changed = not same_json( + state["before"].get("settings", {}).get("delivery"), delivery + ) + + async def update_delivery() -> None: + if delivery_changed and "delivery" not in state["done"]: + key = journal.intent("delivery") + await clients.update_flow_delivery(flow_id, delivery, key, billing=mode) + journal.done("delivery") + + # The service permits uploads without delivery, but not the reverse. + if delivery is None: + await update_delivery() + if "replace" not in state["done"]: + if (await get_flow(flow_id, mode))["enabled"] is not False: + raise ValueError("Shutdown no longer confirmed") + await check_activation_webhook(desired, journal.receipt, mode) + key = journal.intent("replace") + refs: list[JSON] = [ + {"action_id": a, "position": i, "key": desired["steps"][i]["id"]} + for i, a in enumerate(state["new_ids"]) + ] + await clients.replace_flow_actions(flow_id, refs, key, billing=mode) + journal.done("replace") + if ( + not same_json(state["before"]["on"], desired["on"]) + and "trigger" not in state["done"] + ): + await require_unshared(journal.receipt, mode) + on = desired["on"] + params = dict( + activation="custom", + custom_payload_schema=on.get("custom", {}).get("inputs"), + schedule_rule=None, + timezone=None, + ) + if "schedule" in on: + params.update( + activation="schedule", + schedule_rule=dict(type="cron", expression=on["schedule"]["cron"]), + timezone=on["schedule"]["timezone"], + ) + key = journal.intent("trigger") + await clients.update_trigger( + valid_id(journal.receipt.trigger_id), params, key, billing=mode + ) + journal.done("trigger") + if ( + not same_json( + state["before"].get("devices", []), desired.get("devices", []) + ) + and "devices" not in state["done"] + ): + key = journal.intent("devices") + await clients.update_flow_devices( + flow_id, desired.get("devices", []), key, billing=mode + ) + journal.done("devices") + if delivery is not None: + await update_delivery() + + @staticmethod + async def _verify_and_activate(journal: CutoverJournal, activated: bool) -> None: + state, mode = journal.state, journal.mode + flow_id = valid_id(journal.receipt.flow_id) + desired = state["desired"] + if not activated: + journal.intent("verify") + await require_unshared(journal.receipt, mode) + expected_enabled = state["enabled"] if activated else False + if (await get_flow(flow_id, mode))[ + "enabled" + ] is not expected_enabled or not equivalent_document( + await clients.get_document(flow_id, billing=mode), desired + ): + raise ValueError("Cutover verification failed") + verified = tuple( + a.get("actionId") for a in await clients.list_actions(flow_id, billing=mode) + ) + if verified != tuple(state["new_ids"]): + raise ValueError("Cutover bindings changed") + if not activated: + journal.done("verify") + if state["enabled"] and not activated: + await check_activation_webhook(desired, journal.receipt, mode) + journal.intent("enable") + await clients.enable_flow(flow_id, billing=mode) + if (await get_flow(flow_id, mode))["enabled"] is not True: + raise ValueError("Enable not confirmed") + journal.done("enable") + + @staticmethod + async def _retire_actions(journal: CutoverJournal) -> None: + state, mode = journal.state, journal.mode + unresolved = [] + retire_ids: list[str] = ( + state["retire_ids"] if "retire_ids" in state else state["old_ids"] + ) + for action_id in retire_ids: + stage = "delete:" + action_id + if stage in state["done"]: + continue + try: + journal.intent(stage) + await require_unshared(journal.receipt, mode) + await delete_verified(clients.delete_action(action_id, billing=mode)) + journal.done(stage) + except Exception: + unresolved.append(action_id) + if unresolved: + raise ValueError("Old actions unresolved") diff --git a/mobilerun/sandbox/deployments/initial.py b/mobilerun/sandbox/deployments/initial.py new file mode 100644 index 000000000..d8862abb9 --- /dev/null +++ b/mobilerun/sandbox/deployments/initial.py @@ -0,0 +1,307 @@ +"""First deployment and recovery of its staged resources.""" + +import json + +from mobilerun.models.billing import Billing + +from .. import clients +from ..documents import build_document +from ..errors import FlowStagingError, SandboxDeploymentConflict, SandboxDeploymentError +from ..flows import ( + check_activation_webhook, + check_webhook, + get_flow, + valid_id, + valid_version, +) +from ..helpers.deployment import deployment_receipt, wait_ready +from ..models import JSON, Artifact, DeploymentReceipt, OwnershipReceipt +from ..receipts import ReceiptStore, checkpoint, pending_initial, sha256_hex, stage_key + + +class InitialDeployment: + """Stage a function and its first flow using a replayable receipt.""" + + def __init__( + self, + store: ReceiptStore, + artifact: Artifact, + selected: str | None, + mode: Billing, + ) -> None: + self.store = store + self.artifact = artifact + self.selected = selected + self.mode = mode + + async def can_replace_version( + self, + state: JSON, + receipt: OwnershipReceipt, + found: JSON | None, + flows: list[JSON], + ) -> bool: + """Only a rejected, receipt-owned version with no staged flow can be superseded.""" + if flows or receipt.flow_id or receipt.trigger_id or receipt.action_ids: + return False + if ( + state["function_pending"] + or state["flow_pending"] + or state["document"] is not None + ): + return False + if ( + not receipt.function_id + or not found + or found.get("id") != receipt.function_id + ): + return False + version = state["version"] + if ( + version is None + or (found.get("latestVersion") or {}).get("version") != version + ): + return False + record = await clients.get_version( + receipt.function_id, valid_version(version), billing=self.mode + ) + return record.get("version") == version and record.get("status") == "rejected" + + async def create_function( + self, receipt: OwnershipReceipt, state: JSON, found: JSON | None + ) -> OwnershipReceipt: + """Create or replay the journaled function only; never infer an ID from a name.""" + store, artifact, mode = self.store, self.artifact, self.mode + key = state["function_key"] + receipt = store.record_stage(receipt, "function:create", key) + try: + result = await clients.create_function( + receipt.name, artifact.source, key, billing=mode + ) + except Exception: + raise SandboxDeploymentError( + "Sandbox function creation outcome uncertain; retry the original deployment", + receipt=receipt, + ) from None + function_id = valid_id(result.get("id")) + if receipt.function_id and receipt.function_id != function_id: + raise SandboxDeploymentConflict( + "Idempotent function response conflicts with remote state", + receipt=receipt, + ) + receipt = store.record_ids(receipt, function_id=function_id) + version = valid_version((result.get("latestVersion") or {}).get("version")) + state.update(function_pending=False, version=version) + receipt = checkpoint(store, receipt, state) + if found and found.get("id") != function_id: + raise SandboxDeploymentConflict( + "Idempotent function response conflicts with remote state", + receipt=receipt, + ) + return receipt + + async def deploy( + self, receipt: OwnershipReceipt, found: JSON | None, visible_flows: list[JSON] + ) -> DeploymentReceipt: + store, artifact, mode = self.store, self.artifact, self.mode + selected = self.selected + scope, decl = store.scope, artifact.declaration + state = pending_initial(receipt) + resuming = state is not None + if state is None: + await check_webhook(decl.webhook, receipt, mode) + if found is None and receipt.function_id: + raise SandboxDeploymentConflict( + "Owned sandbox function is missing", receipt=receipt + ) + # Completed cleanup starts a new intent, not a replay of deleted creations. + # Journal position is persisted through the keys below before any request. + intent_digest = sha256_hex( + json.dumps([artifact.digest, selected, len(receipt.stages)]) + ) + state = dict( + stage="initial", + preview_document=build_document( + artifact, + "placeholder", + 1, + device=selected, + ), + digest=artifact.digest, + device=selected, + function_pending=found is None, + flow_pending=False, + function_key=stage_key( + scope, decl.name, intent_digest, "function:create" + ), + flow_key=stage_key(scope, decl.name, intent_digest, "flow:create"), + version=None, + document=None, + status="created" if found is None else "unchanged", + complete=False, + ) + receipt = checkpoint(store, receipt, state) + if state["function_pending"]: + receipt = await self.create_function(receipt, state, found) + elif state["version"] is None: + if found is None: + raise SandboxDeploymentConflict( + "Owned sandbox function is missing", receipt=receipt + ) + function_id = valid_id(found.get("id")) + version = valid_version((found.get("latestVersion") or {}).get("version")) + source = None + if not state.get("replacing_rejected"): + await wait_ready(function_id, version, mode, receipt) + source = await clients.get_source(function_id, version, billing=mode) + if source == artifact.source: + status = "unchanged" + else: + key = stage_key(scope, decl.name, artifact.digest, "version:create") + receipt = store.record_stage(receipt, "version:create", key) + result = await clients.create_version( + function_id, artifact.source, key, billing=mode + ) + version = valid_version(result.get("version")) + status = "pushed" + state.update(version=version, status=status) + receipt = checkpoint(store, receipt, state) + function_id = valid_id(receipt.function_id) + version = valid_version(state["version"]) + await wait_ready(function_id, version, mode, receipt) + receipt = store.record_ids(receipt, digest=artifact.digest) + if state["flow_pending"]: + # Replay the exact staged payload before checking external dependencies. + document = state["document"] + else: + document = build_document(artifact, function_id, version, device=selected) + if ( + document is not None + and (await clients.validate_document(document, billing=mode)).get( + "valid" + ) + is not True + ): + raise SandboxDeploymentError( + "Sandbox flow validation failed", receipt=receipt + ) + if document is not None: + receipt = await self._stage_flow( + receipt, state, document, visible_flows, resuming + ) + return await self.finish_activation(receipt, state, None) + state["complete"] = True + receipt = checkpoint(store, receipt, state) + return deployment_receipt(receipt, artifact, version, state["status"]) + + async def _stage_flow( + self, + receipt: OwnershipReceipt, + state: JSON, + document: JSON, + visible_flows: list[JSON], + resuming: bool, + ) -> OwnershipReceipt: + store, mode = self.store, self.mode + key = state["flow_key"] + if not state["flow_pending"]: + if resuming: + await check_webhook(self.artifact.declaration.webhook, receipt, mode) + payloads = await clients.prepare_action_payloads(document, billing=mode) + state.update(flow_pending=True, document=document, action_payloads=payloads) + receipt = checkpoint(store, receipt, state) + elif not isinstance(state.get("action_payloads"), list): + raise SandboxDeploymentConflict( + "Cannot safely replay initial staging without journaled action payloads", + receipt=receipt, + ) + receipt = store.record_stage(receipt, "flow:create", key) + try: + staged = await clients.create_document( + document, + key, + billing=mode, + action_payloads=state["action_payloads"], + ) + except FlowStagingError as exc: + receipt = store.record_ids( + receipt, + flow_id=exc.flow_id or receipt.flow_id, + trigger_id=exc.trigger_id or receipt.trigger_id, + action_ids=tuple(dict.fromkeys([*receipt.action_ids, *exc.action_ids])), + ) + raise SandboxDeploymentError( + "Sandbox flow staging failed", receipt=receipt + ) from None + except Exception: + raise SandboxDeploymentError( + "Sandbox flow creation outcome uncertain; retry the original deployment", + receipt=receipt, + ) from None + if not isinstance(staged, dict): + raise SandboxDeploymentError( + "Invalid sandbox flow response", receipt=receipt + ) + flow_id = valid_id(staged.get("flowId")) + if receipt.flow_id and receipt.flow_id != flow_id: + raise SandboxDeploymentConflict( + "Idempotent flow response conflicts with remote state", + receipt=receipt, + ) + receipt = store.record_ids(receipt, flow_id=flow_id) + trigger_id = valid_id(staged.get("triggerId")) + receipt = store.record_ids(receipt, trigger_id=trigger_id) + actions = staged.get("actionIds") + if not isinstance(actions, list) or not actions: + raise SandboxDeploymentError( + "Invalid sandbox flow response", receipt=receipt + ) + action_ids: tuple[str, ...] = () + for action in actions: + action_ids += (valid_id(action),) + receipt = store.record_ids(receipt, action_ids=action_ids) + if len(set(action_ids)) != len(document["steps"]) or len(action_ids) != len( + document["steps"] + ): + raise SandboxDeploymentError( + "Incomplete sandbox action IDs", receipt=receipt + ) + if any(f.get("id") != flow_id for f in visible_flows): + raise SandboxDeploymentConflict( + "Idempotent flow response conflicts with remote state", + receipt=receipt, + ) + store.write_yaml(document) + state.update(flow_pending=False, activation_pending=True) + return checkpoint(store, receipt, state) + + async def finish_activation( + self, receipt: OwnershipReceipt, state: JSON, current: bool | None + ) -> DeploymentReceipt: + """Close staging only after the flow reflects the journaled activation intent.""" + store, artifact, mode = self.store, self.artifact, self.mode + flow_id = valid_id(receipt.flow_id) + target = state.get("enabled", True) + if target: + await check_activation_webhook(state["document"], receipt, mode) + try: + if current is not target: + stage = "flow:enable" if target else "flow:disable" + key = stage_key(store.scope, receipt.name, artifact.digest, stage) + receipt = store.record_stage(receipt, stage, key) + operation = clients.enable_flow if target else clients.disable_flow + updated = await operation(flow_id, billing=mode) + if ( + not isinstance(updated, dict) + or updated.get("enabled") is not target + ): + raise ValueError("Activation not confirmed") + if (await get_flow(flow_id, mode))["enabled"] is not target: + raise ValueError("Activation not confirmed") + except Exception: + raise SandboxDeploymentError( + "Sandbox flow activation failed or uncertain", receipt=receipt + ) from None + state["complete"] = True + receipt = checkpoint(store, receipt, state) + return deployment_receipt(receipt, artifact, state["version"], state["status"]) diff --git a/mobilerun/sandbox/deployments/journal.py b/mobilerun/sandbox/deployments/journal.py new file mode 100644 index 000000000..d86db995c --- /dev/null +++ b/mobilerun/sandbox/deployments/journal.py @@ -0,0 +1,46 @@ +"""Write-ahead receipt operations for a workflow cutover.""" + +import json + +from mobilerun.models.billing import Billing + +from ..models import Artifact, CutoverState, OwnershipReceipt +from ..receipts import ReceiptStore, checkpoint, sha256_hex, stage_key + + +class CutoverJournal: + """Keep the latest receipt and its cutover progress together.""" + + def __init__( + self, + store: ReceiptStore, + receipt: OwnershipReceipt, + artifact: Artifact, + mode: Billing, + state: CutoverState, + ) -> None: + self.store = store + self.receipt = receipt + self.artifact = artifact + self.mode = mode + self.state = state + + def save(self) -> None: + self.receipt = checkpoint(self.store, self.receipt, self.state) + + def intent(self, stage: str) -> str: + self.state["pending"] = stage + self.save() + # Include the full document so device/schema-only changes get new keys. + identity: list[object] = [self.state["desired"], self.state["old_ids"]] + if "retarget_generation" in self.state: + identity.append(self.state["retarget_generation"]) + digest = sha256_hex(json.dumps(identity, sort_keys=True)) + key = stage_key(self.store.scope, self.receipt.name, digest, stage) + self.receipt = self.store.record_stage(self.receipt, stage, key) + return key + + def done(self, stage: str) -> None: + self.state["done"].append(stage) + self.state["pending"] = None + self.save() diff --git a/mobilerun/sandbox/deployments/planner.py b/mobilerun/sandbox/deployments/planner.py new file mode 100644 index 000000000..27105a4e0 --- /dev/null +++ b/mobilerun/sandbox/deployments/planner.py @@ -0,0 +1,292 @@ +"""Prove ownership and prepare a new or resumed workflow cutover.""" + +import copy + +from mobilerun.models.billing import Billing + +from .. import clients +from ..documents import ( + build_document, + equivalent_document, + has_authored_steps, + same_json, + without_webhook, +) +from ..errors import SandboxDeploymentConflict, SandboxDeploymentError +from ..flows import ( + check_activation_webhook, + check_webhook, + get_flow, + pinned_version, + require_unshared, + valid_id, + valid_version, +) +from ..helpers.deployment import deployment_receipt, wait_ready +from ..models import JSON, Artifact, CutoverState, DeploymentReceipt, OwnershipReceipt +from ..receipts import ( + ReceiptStore, + checkpoint, + pending_cutover, + read_authored_document, + require_current_cutover_receipt, + stage_key, +) +from ..settings import get_sandbox_settings +from .journal import CutoverJournal + + +class CutoverPlanner: + """Verify the observed deployment before planning any changes to the live flow.""" + + def __init__( + self, + store: ReceiptStore, + artifact: Artifact, + selected: str | None, + mode: Billing, + ) -> None: + self.store = store + self.artifact = artifact + self.selected = selected + self.mode = mode + + async def plan( + self, receipt: OwnershipReceipt, found: JSON | None, all_flows: list[JSON] + ) -> CutoverJournal | DeploymentReceipt: + mode = self.mode + state = pending_cutover(receipt) + require_current_cutover_receipt(state, receipt) + if not found or not receipt.trigger_id or not receipt.action_ids: + raise SandboxDeploymentConflict( + "Sandbox ownership is incomplete", receipt=receipt + ) + valid_id(receipt.function_id) + flow_id = valid_id(receipt.flow_id) + valid_id(receipt.trigger_id) + for action_id in receipt.action_ids: + valid_id(action_id) + flow = await get_flow(flow_id, mode) + expected_name = ( + receipt.name + get_sandbox_settings().MOBILERUN_SANDBOX_FLOW_SUFFIX + ) + if ( + flow.get("name") != expected_name + or sum(f.get("name") == expected_name for f in all_flows) != 1 + ): + raise SandboxDeploymentConflict( + "Sandbox flow ownership mismatch", receipt=receipt + ) + await require_unshared(receipt, mode) + bindings = tuple( + valid_id(a.get("actionId")) + for a in await clients.list_actions(flow_id, billing=mode) + ) + allowed = ( + [tuple(state["old_ids"]), tuple(state["new_ids"])] + if state + else [receipt.action_ids] + ) + if bindings not in allowed: + raise SandboxDeploymentConflict( + "Sandbox action bindings changed", receipt=receipt + ) + actual = await clients.get_document(flow_id, billing=mode) + + if state is not None: + return await self._resume(receipt, state, actual, bindings) + return await self._fresh(receipt, found, flow, actual, bindings) + + async def _resume( + self, + receipt: OwnershipReceipt, + state: CutoverState, + actual: JSON, + bindings: tuple[str, ...], + ) -> CutoverJournal: + store, artifact, selected, mode = ( + self.store, + self.artifact, + self.selected, + self.mode, + ) + function_id = valid_id(receipt.function_id) + requested = build_document( + artifact, function_id, state["version"], device=selected + ) + desired_changed = not same_json(requested, state["desired"]) + retarget = ( + state.get("webhook_unusable") + and desired_changed + and requested is not None + and same_json(without_webhook(requested), without_webhook(state["desired"])) + ) + if ( + state["digest"] != artifact.digest + or state["device"] != selected + or (desired_changed and not retarget) + ): + raise SandboxDeploymentConflict( + "Finish the pending sandbox deployment first", receipt=receipt + ) + expected = copy.deepcopy(state["before"]) + # Only the stage in flight may have either its old or new remote value. + candidates = [expected] + for stage, field in ( + ("replace", "steps"), + ("trigger", "on"), + ("devices", "devices"), + ): + if stage in state["done"]: + for candidate in candidates: + candidate[field] = state["desired"].get(field, []) + elif state.get("pending") == stage: + changed = copy.deepcopy(candidates[0]) + changed[field] = state["desired"].get(field, []) + candidates.append(changed) + delivery_candidates = [] + if "delivery" in state["done"]: + delivery_candidates = candidates + elif state.get("pending") == "delivery": + delivery_candidates = [copy.deepcopy(candidates[0])] + candidates.extend(delivery_candidates) + for candidate in delivery_candidates: + settings = candidate.setdefault("settings", {}) + if delivery := state["desired"].get("settings", {}).get("delivery"): + settings["delivery"] = delivery + else: + settings.pop("delivery", None) + if not any(equivalent_document(actual, c) for c in candidates): + raise SandboxDeploymentConflict( + "Sandbox remote state diverged", receipt=receipt + ) + version = state["version"] + await wait_ready(function_id, version, mode, receipt) + if retarget and requested is not None: + await check_activation_webhook(requested, receipt, mode) + if (await clients.validate_document(requested, billing=mode)).get( + "valid" + ) is not True: + raise SandboxDeploymentError( + "Sandbox flow validation failed", receipt=receipt + ) + # The observed document is a verified cutover state, not new ownership. + # Keep every known action until the replacement is confirmed active. + state.update( + { + "before": actual, + "desired": requested, + "action_payloads": await clients.prepare_action_payloads( + requested, billing=mode + ), + "old_ids": list(bindings), + "retire_ids": list(receipt.action_ids), + "new_ids": [], + "done": [], + "pending": None, + "webhook_unusable": False, + "retarget_generation": len(receipt.stages), + } + ) + receipt = checkpoint(store, receipt, state) + return CutoverJournal(store, receipt, artifact, mode, state) + + async def _fresh( + self, + receipt: OwnershipReceipt, + found: JSON, + flow: JSON, + actual: JSON, + bindings: tuple[str, ...], + ) -> CutoverJournal | DeploymentReceipt: + store, artifact, selected, mode = ( + self.store, + self.artifact, + self.selected, + self.mode, + ) + function_id = valid_id(receipt.function_id) + has_yaml = store.yaml_path.exists() + authored = read_authored_document(store, receipt) + if has_yaml or authored is not None: + if ( + not isinstance(authored, dict) + or (not has_yaml and not has_authored_steps(authored)) + or not equivalent_document(actual, authored) + ): + raise SandboxDeploymentConflict( + "Sandbox remote document changed", receipt=receipt + ) + pinned = pinned_version(function_id, actual, for_redeploy=True) + version = pinned + source = await clients.get_source(function_id, version, billing=mode) + if source != artifact.source: + version = valid_version((found.get("latestVersion") or {}).get("version")) + if version != pinned: + source = await clients.get_source(function_id, version, billing=mode) + if source == artifact.source: + await wait_ready(function_id, version, mode, receipt) + await check_webhook(artifact.declaration.webhook, receipt, mode) + desired = build_document( + artifact, + function_id, + version, + device=selected, + ) + if desired is None: + raise SandboxDeploymentConflict( + "Remove the owned flow explicitly first", receipt=receipt + ) + if source == artifact.source and equivalent_document(actual, desired): + if artifact.declaration.webhook and not store.yaml_path.exists(): + store.write_yaml(desired) + return deployment_receipt(receipt, artifact, version, "unchanged") + if authored is None: + raise SandboxDeploymentConflict( + "Sandbox authored document evidence is missing", receipt=receipt + ) + if source != artifact.source: + key = stage_key( + store.scope, + receipt.name, + artifact.digest, + f"version:create:{function_id}:{pinned}:{','.join(bindings)}", + ) + receipt = store.record_stage(receipt, "version:create", key) + result = await clients.create_version( + function_id, artifact.source, key, billing=mode + ) + version = valid_version(result.get("version")) + await wait_ready(function_id, version, mode, receipt) + desired = build_document( + artifact, + function_id, + version, + device=selected, + ) + assert desired is not None + if (await clients.validate_document(desired, billing=mode)).get( + "valid" + ) is not True: + raise SandboxDeploymentError( + "Sandbox flow validation failed", receipt=receipt + ) + state = CutoverState( + stage="cutover", + digest=artifact.digest, + device=selected, + version=version, + before=actual, + desired=desired, + action_payloads=await clients.prepare_action_payloads( + desired, billing=mode + ), + old_ids=list(receipt.action_ids), + new_ids=[], + enabled=flow["enabled"], + done=[], + pending=None, + complete=False, + ) + receipt = checkpoint(store, receipt, state) + return CutoverJournal(store, receipt, artifact, mode, state) diff --git a/mobilerun/sandbox/deployments/recovery.py b/mobilerun/sandbox/deployments/recovery.py new file mode 100644 index 000000000..14e58288c --- /dev/null +++ b/mobilerun/sandbox/deployments/recovery.py @@ -0,0 +1,68 @@ +"""Leave an interrupted cutover in a recoverable, receipt-proven state.""" + +from typing import NoReturn + +from .. import clients +from ..documents import equivalent_document +from ..errors import SandboxDeploymentError, WebhookBindingError +from ..flows import check_activation_webhook, get_flow, require_unshared, valid_id +from ..receipts import stage_key +from .journal import CutoverJournal + + +class CutoverRecovery: + """Restore verified old bindings or keep an incomplete cutover stopped.""" + + @staticmethod + async def fail(journal: CutoverJournal, exc: Exception) -> NoReturn: + store, artifact, mode = journal.store, journal.artifact, journal.mode + state, receipt = journal.state, journal.receipt + flow_id = valid_id(receipt.flow_id) + # Confirmed activation must not be undone by a cleanup failure. + try: + restore_old = ( + isinstance(exc, WebhookBindingError) + and state["enabled"] + and not {"replace", "delivery"}.intersection(state["done"]) + and state.get("pending") not in ("replace", "delivery") + ) + if restore_old: + # Only definitions were created; no live binding or settings changed. + await require_unshared(receipt, mode) + current = await clients.get_document(flow_id, billing=mode) + current_ids = [ + row.get("actionId") + for row in await clients.list_actions(flow_id, billing=mode) + ] + if current_ids != state["old_ids"] or not equivalent_document( + current, state["before"] + ): + raise ValueError("Previous workflow state changed") + await check_activation_webhook(state["before"], receipt, mode) + key = stage_key( + store.scope, receipt.name, artifact.digest, "restore:enable" + ) + journal.receipt = store.record_stage(receipt, "restore:enable", key) + await clients.enable_flow(flow_id, billing=mode) + elif "enable" not in state["done"]: + key = stage_key( + store.scope, receipt.name, artifact.digest, "failure:shutdown" + ) + journal.receipt = store.record_stage(receipt, "failure:shutdown", key) + await clients.disable_flow(flow_id, billing=mode) + except Exception: + pass + try: + enabled = (await get_flow(flow_id, mode))["enabled"] + except Exception: + enabled = "uncertain" + state["warning"] = f"Cutover incomplete; flow enabled={enabled}" + if isinstance(exc, WebhookBindingError): + state["webhook_unusable"] = True + state[ + "warning" + ] += f". {exc}. Redeploy with a usable endpoint ID or remove webhook=." + journal.save() + raise SandboxDeploymentError( + state["warning"], receipt=journal.receipt + ) from None diff --git a/mobilerun/sandbox/documents.py b/mobilerun/sandbox/documents.py index c91e101bb..9b89af988 100644 --- a/mobilerun/sandbox/documents.py +++ b/mobilerun/sandbox/documents.py @@ -7,14 +7,8 @@ from typing import Any from .errors import SandboxDeclarationError -from .models import ( - FILE_MIME_TYPES, - FILE_UPLOAD_USES, - JSON, - Artifact, - is_result_path_part, - webhook_endpoint_id, -) +from .helpers.declaration_values import is_result_path_part, webhook_endpoint_id +from .models import FILE_MIME_TYPES, FILE_UPLOAD_USES, JSON, Artifact from .settings import WEBHOOK_STEP_ID, get_sandbox_settings diff --git a/mobilerun/sandbox/errors.py b/mobilerun/sandbox/errors.py index b25d03e30..2fe54b791 100644 --- a/mobilerun/sandbox/errors.py +++ b/mobilerun/sandbox/errors.py @@ -5,7 +5,7 @@ from typing import TYPE_CHECKING, ClassVar from mobilerun.errors.base import MobilerunError -from mobilerun.errors.cloud import CloudAPIError +from mobilerun.errors.cloud import BillingRequired, CloudAPIError if TYPE_CHECKING: from .models import OwnershipReceipt @@ -71,6 +71,10 @@ class SandboxDeploymentConflict(SandboxDeploymentError): """Observed resources conflict with recorded ownership.""" +class WebhookBindingError(SandboxDeploymentError): + """Value-safe explanation of why the endpoint cannot be used.""" + + class SandboxRunError(SandboxError): """A sandbox invocation or execution failed.""" @@ -89,3 +93,17 @@ def __init__( class SandboxRunTimeout(SandboxRunError, TimeoutError): """A sandbox run exceeded its deadline.""" + + +class TargetedBillingRequired(BillingRequired): + """Billing confirmation that identifies the affected targets.""" + + def __init__(self, error: BillingRequired, target_summary: str) -> None: + super().__init__( + needed=error.needed, given=error.given, operation=error.operation + ) + self.target_summary = target_summary + + @property + def confirmation(self) -> str: + return f"{self.target_summary}. {super().confirmation}" diff --git a/mobilerun/sandbox/execution.py b/mobilerun/sandbox/execution.py index c6e23b901..9e0d768f6 100644 --- a/mobilerun/sandbox/execution.py +++ b/mobilerun/sandbox/execution.py @@ -13,18 +13,23 @@ from mobilerun.models.billing import Billing from . import clients -from .billing import require_paid -from .documents import action_type, endpoint_schema, has_ref -from .errors import SandboxDeploymentError, SandboxRunError, SandboxRunTimeout +from .billing import require_paid, resolve_billing +from .documents import endpoint_schema, has_ref +from .errors import SandboxRunError, SandboxRunTimeout from .flows import ( activation_document, find_remote, flow_version, owned_remote, remote_request, - valid_id, ) -from .models import JSON, resolve_billing +from .helpers.run_result import ( + check_success, + function_steps, + run_identifier, + safe_snapshot, +) +from .models import JSON from .receipts import ReceiptStore, current_scope from .settings import get_sandbox_settings @@ -83,7 +88,7 @@ async def fire_remote( billing=mode, ) ) - invocation_id = _run_identifier(fired.get("invocationId")) + invocation_id = run_identifier(fired.get("invocationId")) count = fired.get("enqueuedCount") if not isinstance(count, int) or isinstance(count, bool) or count <= 0: raise SandboxRunError( @@ -106,87 +111,18 @@ async def recent_runs( records = await remote_request( clients.list_executions(flow["id"], limit=limit, billing=mode) ) - return [_snapshot(record) for record in records[:limit]] - - -def _snapshot(record: JSON) -> JSON: - """Keep the execution contract, not raw server errors or signed artifacts.""" - result: JSON = { - "id": _run_identifier(record.get("id")), - "status": record.get("status"), - } - for key in ("flowId", "invocationId", "startedAt", "finishedAt"): - if isinstance(record.get(key), str): - result[key] = record[key] - # Use this execution's own progress, not the current (possibly redeployed) flow. - for source in ("progress", "result"): - metadata = record.get(source) - if not isinstance(metadata, dict) or not isinstance( - metadata.get("steps"), list - ): - continue - if source == "result": - result["result"] = {"steps": []} - for step in metadata["steps"]: - if not isinstance(step, dict): - continue - uses = action_type(step) - status = step.get("status") - body = step.get("body") - if source == "result" and uses == "functions.run": - function: JSON = {"uses": uses} - if status is not None: - function["status"] = status if status == "success" else "failed" - if isinstance(body, dict): - function["body"] = { - k: copy.deepcopy(body[k]) - for k in ( - "result", - "outcome", - "ok", - "partialReason", - "state", - "notes", - ) - if k in body - } - if body.get("error") is not None: - function["status"] = "failed" - result["result"]["steps"].append(function) - if uses != "webhooks.send": - continue - if isinstance(body, dict) and body.get("error") is not None: - status = "failed" - elif status is None and isinstance(body, dict) and body.get("eventId"): - status = "succeeded" - if status == "success": - status = "succeeded" - if status in ("succeeded", "failed", "skipped", "cancelled"): - result["webhookStatus"] = status - elif status in ("pending", "running") and result.get("webhookStatus") in ( - None, - "pending", - ): - result["webhookStatus"] = status - if source == "result": - safe_step: JSON = {"uses": "webhooks.send"} - if "webhookStatus" in result: - safe_step["status"] = result["webhookStatus"] - if isinstance(body, dict) and isinstance(body.get("eventId"), str): - safe_step["body"] = {"eventId": body["eventId"]} - result["result"]["steps"].append(safe_step) - return result + return [safe_snapshot(record) for record in records[:limit]] async def execution_snapshot( execution_id: str, *, billing: Billing | str | None = None ) -> JSON: """Retrieve a fresh execution snapshot, preserving partial result metadata.""" - return _snapshot(await _execution_record(execution_id, billing)) + return safe_snapshot(await _execution_record(execution_id, billing)) async def _execution_record(execution_id: str, billing: Billing | str | None) -> JSON: - execution_id = _run_identifier(execution_id) + execution_id = run_identifier(execution_id) record = await remote_request( clients.get_execution(execution_id, billing=resolve_billing(billing)) ) @@ -205,13 +141,6 @@ def _timeout(invocation_id: str | None, execution_id: str | None) -> SandboxRunT ) -def _run_identifier(value: Any) -> str: - try: - return valid_id(value) - except SandboxDeploymentError: - raise SandboxRunError("Invalid sandbox run identifier") from None - - async def _within_deadline( operation: Callable[[], Awaitable[T]], deadline: float, @@ -253,7 +182,7 @@ async def resolve_execution( billing: Billing | str | None = None, ) -> str: """Resolve an invocation, sharing the caller's absolute monotonic deadline.""" - invocation_id = _run_identifier(invocation_id) + invocation_id = run_identifier(invocation_id) if ( not isinstance(deadline, (int, float)) or isinstance(deadline, bool) @@ -286,47 +215,10 @@ async def resolve_execution( row.get("invocationId", invocation_id) == invocation_id and row.get("flowId", flow["id"]) == flow["id"] ): - return _run_identifier(row.get("id")) + return run_identifier(row.get("id")) await _poll_pause(deadline, invocation_id, None) -def _function_steps(snapshot: JSON) -> list[JSON]: - result = snapshot.get("result") - if not isinstance(result, dict) or not isinstance(result.get("steps"), list): - return [] - return [ - s - for s in result["steps"] - if isinstance(s, dict) and action_type(s) == "functions.run" - ] - - -def _check_success(snapshot: JSON, invocation_id: str | None) -> None: - steps = _function_steps(snapshot) - execution_id = snapshot["id"] - if not steps: - raise SandboxRunError( - "Sandbox execution has no function result", - invocation_id=invocation_id, - execution_id=execution_id, - ) - for step in steps: - body = step.get("body") - if ( - step.get("status") not in (None, "success") - or not isinstance(body, dict) - or body.get("ok") is False - or body.get("error") is not None - or body.get("outcome") not in (None, "complete", "succeeded", "partial") - or "result" not in body - ): - raise SandboxRunError( - "Sandbox function body failed or is invalid", - invocation_id=invocation_id, - execution_id=execution_id, - ) - - async def wait_result( name: str, *, @@ -346,9 +238,9 @@ async def wait_result( if invocation_id is None and execution_id is None: raise SandboxRunError("Provide an invocation or execution ID") if invocation_id is not None: - _run_identifier(invocation_id) + run_identifier(invocation_id) if execution_id is not None: - _run_identifier(execution_id) + run_identifier(execution_id) deadline = time.monotonic() + timeout if execution_id is None: execution_id = await resolve_execution( @@ -376,7 +268,7 @@ async def wait_result( if status == "success" or ( status in ("failed", "cancelled") and webhook_failed ): - _check_success(snapshot, invocation_id) + check_success(snapshot, invocation_id) if webhook_failed: logging.getLogger(__name__).warning( "Sandbox webhook step %s; function result is available", webhook @@ -401,7 +293,7 @@ async def execution_logs( ) -> str: """Read inline function logs, or download available compute logs safely.""" record = await _execution_record(execution_id, billing) - for step in _function_steps(record): + for step in function_steps(record): body = step.get("body") if not isinstance(body, dict): continue @@ -420,7 +312,7 @@ async def execution_logs( ) return await remote_request( clients.run_logs( - _run_identifier(body["runId"]), billing=resolve_billing(billing) + run_identifier(body["runId"]), billing=resolve_billing(billing) ) ) if isinstance(logs, str) and logs != "available": diff --git a/mobilerun/sandbox/flows.py b/mobilerun/sandbox/flows.py index 2029836ac..afe8d5e0a 100644 --- a/mobilerun/sandbox/flows.py +++ b/mobilerun/sandbox/flows.py @@ -8,22 +8,21 @@ from mobilerun.models.billing import Billing from . import clients -from .billing import require_paid +from .billing import require_paid, resolve_billing from .documents import ( action_type, endpoint_schema, equivalent_document, has_authored_steps, ) -from .errors import SandboxDeploymentConflict, SandboxDeploymentError, SandboxRunError -from .models import ( - FILE_UPLOAD_USES, - JSON, - WEBHOOK_REGISTER_HINT, - OwnershipReceipt, - resolve_billing, - webhook_endpoint_id, +from .errors import ( + SandboxDeploymentConflict, + SandboxDeploymentError, + SandboxRunError, + WebhookBindingError, ) +from .helpers.declaration_values import WEBHOOK_REGISTER_HINT, webhook_endpoint_id +from .models import FILE_UPLOAD_USES, JSON, OwnershipReceipt from .receipts import ( ReceiptStore, checkpoint, @@ -36,10 +35,6 @@ from .settings import WEBHOOK_STEP_ID, get_sandbox_settings -class WebhookBindingError(SandboxDeploymentError): - """Value-safe explanation of why the endpoint cannot be used.""" - - async def check_webhook( endpoint_id: str | None, receipt: OwnershipReceipt, mode: Billing ) -> None: diff --git a/mobilerun/sandbox/handles/README.md b/mobilerun/sandbox/handles/README.md new file mode 100644 index 000000000..d8f585e35 --- /dev/null +++ b/mobilerun/sandbox/handles/README.md @@ -0,0 +1,13 @@ +# Sandbox handles + +Import the public names from `mobilerun.sandbox`. For example, +`cloud["hello"]` constructs a lazy `Remote` without contacting the cloud. +Calling a handle or firing a run can incur charges. + +| File | Role | +| --- | --- | +| `cloud.py` | Decorate a local routine or look up a named deployment. | +| `remote.py` | Inspect, fire, pause, and enable a deployment. | +| `run.py` | Resolve, poll, and read one execution. | + +See the [sandbox guide](../README.md) for runnable examples. diff --git a/mobilerun/sandbox/handles/__init__.py b/mobilerun/sandbox/handles/__init__.py new file mode 100644 index 000000000..4b7ef5e2d --- /dev/null +++ b/mobilerun/sandbox/handles/__init__.py @@ -0,0 +1 @@ +"""Public sandbox handle implementations.""" diff --git a/mobilerun/sandbox/handles/cloud.py b/mobilerun/sandbox/handles/cloud.py new file mode 100644 index 000000000..3e3655254 --- /dev/null +++ b/mobilerun/sandbox/handles/cloud.py @@ -0,0 +1,65 @@ +"""Register local cloud scripts and look up named deployments.""" + +import inspect +from collections.abc import Callable +from typing import Any, TypeVar, get_type_hints + +from pydantic import BaseModel + +from ..errors import SandboxDeclarationError +from ..models import FILES_RETURN_ERROR, CloudDeclaration +from .remote import Remote + +F = TypeVar("F", bound=Callable[..., Any]) + + +class Cloud: + """Register local scripts or look up an untyped remote by deployment name.""" + + def __call__( + self, + name: str, + schedule: str | None = None, + device: str | None = None, + endpoint: bool | None = None, + webhook: str | None = None, + *, + files: dict[str, str] | None = None, + files_folder: str | None = None, + ) -> Callable[[F], F]: + CloudDeclaration( + name, + schedule=schedule, + device=device, + endpoint=endpoint, + webhook=webhook, + files=files, + files_folder=files_folder, + ).validate() + has_files = bool(files) + + def decorate(func: F) -> F: + from .._runtime import EntryPointError, script + + hints = get_type_hints(func) if has_files else None + if hints is not None: + output = hints.get("return") + if not isinstance(output, type) or not issubclass(output, BaseModel): + raise SandboxDeclarationError(FILES_RETURN_ERROR) + try: + script(func) + except EntryPointError as exc: + raise SandboxDeclarationError(str(exc)) from exc + if hints is None: + hints = get_type_hints(func) + first = next(iter(inspect.signature(func).parameters)) + func.remote = Remote(name, hints[first], hints.get("return")) # type: ignore[attr-defined] + return func + + return decorate + + def __getitem__(self, name: str) -> Remote: + return Remote(name) + + +cloud = Cloud() diff --git a/mobilerun/sandbox/handles/remote.py b/mobilerun/sandbox/handles/remote.py new file mode 100644 index 000000000..8239ced87 --- /dev/null +++ b/mobilerun/sandbox/handles/remote.py @@ -0,0 +1,153 @@ +"""Lazy synchronous handle to a named cloud function.""" + +from __future__ import annotations + +from collections.abc import Mapping +from functools import partial +from typing import Any + +from pydantic import BaseModel + +from mobilerun.models.billing import Billing +from mobilerun.utils.billing.retry import with_billing_retry + +from .. import execution as _execution +from .. import flows as _flows +from ..billing import resolve_billing +from ..errors import SandboxDeploymentError +from ..helpers.sync import run_sync +from ..helpers.validation import validate_typed, validation_payload +from ..models import JSON, Endpoint +from .run import Run + + +class Remote: + """A named function handle; lookup itself does not contact the cloud.""" + + def __init__( + self, + name: str, + input_type: type[BaseModel] | None = None, + output_type: type[BaseModel] | None = None, + *, + billing: Billing | str | None = None, + ) -> None: + self.name = name + self.input_type = input_type + self.output_type = output_type + self._billing = resolve_billing(billing) + + def _mode(self, billing: Billing | str | None) -> Billing: + return self._billing if billing is None else resolve_billing(billing) + + @property + def _description(self) -> JSON: + return run_sync( + partial(_flows.describe_remote, self.name, billing=self._billing) + ) + + @property + def function_id(self) -> str: + return self._description["function_id"] + + @property + def version(self) -> int: + return self._description["version"] + + @property + def flow_id(self) -> str: + flow_id = self._description.get("flow_id") + if flow_id is None: + raise SandboxDeploymentError( + "Sandbox flow not found", missing_deployment=True + ) + return flow_id + + @property + def endpoint(self) -> Endpoint: + endpoint = self._description.get("endpoint") + if endpoint is None: + raise SandboxDeploymentError( + "Sandbox endpoint not found", missing_deployment=True + ) + return Endpoint(**endpoint) + + def fire( + self, + input: Mapping[str, Any] | BaseModel | None = None, + *, + billing: Billing | str | None = None, + **values: Any, + ) -> Run: + """Enqueue a run without waiting for execution to start.""" + if input is not None and values: + raise TypeError("Pass either input= or keyword payload values, not both") + if input is None: + data: Mapping[str, Any] | BaseModel = values + elif not isinstance(input, (BaseModel, Mapping)): + raise TypeError("input must be a mapping or a pydantic BaseModel") + else: + data = input + if self.input_type is not None and not isinstance(data, self.input_type): + if isinstance(data, BaseModel): + data = validation_payload(data) + data = validate_typed(self.input_type.model_validate, data, self.input_type) + payload = ( + validation_payload(data) if isinstance(data, BaseModel) else dict(data) + ) + fired, mode = run_sync( + partial( + with_billing_retry, + lambda attempt: _execution.fire_remote( + self.name, payload, billing=attempt + ), + self._mode(billing), + ) + ) + run = Run(self, invocation_id=fired["invocation_id"]) + run._billing = mode + return run + + def __call__( + self, + input: Mapping[str, Any] | BaseModel | None = None, + *, + billing: Billing | str | None = None, + **values: Any, + ) -> Any: + return self.fire(input=input, billing=billing, **values).result() + + def runs( + self, limit: int = 10, *, billing: Billing | str | None = None + ) -> list[Run]: + """Read recent executions, newest first.""" + if limit <= 0: + return [] + mode = self._mode(billing) + rows = run_sync(partial(_execution.recent_runs, self.name, limit, billing=mode)) + runs = [] + for row in rows: + run = Run(self, execution_id=row["id"], snapshot=row) + run._billing = mode + runs.append(run) + return runs + + def enable( + self, *, billing: Billing | str | None = None, yes: bool = False + ) -> JSON: + """Enable this owned flow.""" + result, _ = run_sync( + partial( + with_billing_retry, + lambda attempt: _flows.set_enabled(self.name, True, billing=attempt), + self._mode(billing), + yes=yes, + ) + ) + return result + + def disable(self, *, billing: Billing | str | None = None) -> JSON: + """Pause this owned flow until enabled again.""" + return run_sync( + partial(_flows.set_enabled, self.name, False, billing=self._mode(billing)) + ) diff --git a/mobilerun/sandbox/handles/run.py b/mobilerun/sandbox/handles/run.py new file mode 100644 index 000000000..99a827382 --- /dev/null +++ b/mobilerun/sandbox/handles/run.py @@ -0,0 +1,122 @@ +"""Synchronous handle to a sandbox execution.""" + +from __future__ import annotations + +import json +import time +from copy import deepcopy +from datetime import datetime +from functools import partial +from typing import TYPE_CHECKING, Any + +from pydantic import TypeAdapter + +from .. import execution as _execution +from ..errors import SandboxRunError +from ..helpers.sync import run_sync +from ..helpers.validation import validate_typed +from ..models import JSON +from ..settings import get_sandbox_settings + +if TYPE_CHECKING: + from .remote import Remote + + +class Run: + """A run keyed by invocation or execution ID.""" + + def __init__( + self, + remote: Remote, + *, + invocation_id: str | None = None, + execution_id: str | None = None, + snapshot: JSON | None = None, + ) -> None: + self.remote = remote + self._snapshot = deepcopy(snapshot) if snapshot is not None else {} + self.invocation_id = invocation_id or self._snapshot.get("invocationId") + self._id = execution_id or self._snapshot.get("id") + self._billing = remote._billing + + @property + def id(self) -> str: + if self._id is None: + if self.invocation_id is None: + raise SandboxRunError("Provide an invocation or execution ID") + self._id = run_sync( + partial( + _execution.resolve_execution, + self.remote.name, + self.invocation_id, + deadline=time.monotonic() + + get_sandbox_settings().MOBILERUN_SANDBOX_RUN_TIMEOUT, + billing=self._billing, + ) + ) + return self._id + + @property + def status(self) -> str: + self._snapshot = run_sync( + partial(_execution.execution_snapshot, self.id, billing=self._billing) + ) + return self._snapshot["status"] + + @property + def started_at(self) -> str | None: + return self._snapshot.get("startedAt") + + @property + def ended_at(self) -> str | None: + return self._snapshot.get("finishedAt") + + @property + def duration(self) -> float | None: + start, end = self.started_at, self.ended_at + if not start or not end: + return None + return ( + datetime.fromisoformat(end) - datetime.fromisoformat(start) + ).total_seconds() + + @property + def snapshot(self) -> JSON: + return deepcopy(self._snapshot) + + def result(self, timeout: float | None = None) -> Any: + """Wait for completion and validate the function result when typed.""" + if timeout is None: + timeout = get_sandbox_settings().MOBILERUN_SANDBOX_RUN_TIMEOUT + self._snapshot = run_sync( + partial( + _execution.wait_result, + self.remote.name, + invocation_id=self.invocation_id, + execution_id=self._id, + timeout=timeout, + billing=self._billing, + ) + ) + self._id = self._snapshot["id"] + # The orchestration helper validates the execution and function steps. + step = next( + step + for step in self._snapshot["result"]["steps"] + if isinstance(step, dict) and step.get("uses") == "functions.run" + ) + value = step["body"]["result"] + output_type = self.remote.output_type + return ( + validate_typed( + TypeAdapter(output_type).validate_json, json.dumps(value), output_type + ) + if output_type is not None + else deepcopy(value) + ) + + def logs(self) -> str: + """Return execution logs through the cloud boundary.""" + return run_sync( + partial(_execution.execution_logs, self.id, billing=self._billing) + ) diff --git a/mobilerun/sandbox/helpers/README.md b/mobilerun/sandbox/helpers/README.md new file mode 100644 index 000000000..f6915fe76 --- /dev/null +++ b/mobilerun/sandbox/helpers/README.md @@ -0,0 +1,14 @@ +# Sandbox helpers + +Shared implementation code for the [sandbox feature](../README.md). For example, +packaging reads a declaration with `source_declaration()` and checks the +generated script with `inspect_source()` before deployment. + +| File | Role | +| --- | --- | +| `declaration.py`, `source.py`, `global_reads.py`, `local_imports.py` | Parse and extract source without importing the original script. | +| `declaration_values.py`, `routine.py` | Shared declaration checks and lazy worker registration. | +| `inspection.py` | Inspect the generated artifact and project serialized outputs. | +| `deployment.py`, `flow_yaml.py` | Version readiness, receipt results, and authored YAML encoding. | +| `run_result.py` | Safe execution snapshots and result validation. | +| `sync.py`, `validation.py` | Sync API bridge and safe Pydantic validation. | diff --git a/mobilerun/sandbox/helpers/__init__.py b/mobilerun/sandbox/helpers/__init__.py new file mode 100644 index 000000000..b0b7e4062 --- /dev/null +++ b/mobilerun/sandbox/helpers/__init__.py @@ -0,0 +1 @@ +"""Helpers shared by sandbox components.""" diff --git a/mobilerun/sandbox/helpers/declaration.py b/mobilerun/sandbox/helpers/declaration.py new file mode 100644 index 000000000..d535c8d06 --- /dev/null +++ b/mobilerun/sandbox/helpers/declaration.py @@ -0,0 +1,119 @@ +"""Parse and validate the literal cloud declaration without executing the script.""" + +import ast +from typing import Any + +from ..errors import SandboxDeclarationError +from ..models import CloudDeclaration + + +def parse_source(source: str, filename: str) -> ast.Module: + try: + return ast.parse(source, filename=filename) + except (SyntaxError, ValueError) as exc: + location = ( + f"{filename}:{exc.lineno}" + if isinstance(exc, SyntaxError) and exc.lineno + else filename + ) + # SyntaxError retains the offending source line, including any webhook token. + raise SandboxDeclarationError(f"{location}: invalid Python source") + + +def source_declaration( + tree: ast.Module, filename: str +) -> tuple[CloudDeclaration, ast.FunctionDef | ast.AsyncFunctionDef]: + imports = [ + n + for n in ast.walk(tree) + if isinstance(n, ast.ImportFrom) + and n.module == "mobilerun.sandbox" + and n.level == 0 + and any(a.name == "cloud" or a.name == "*" for a in n.names) + ] + candidates = [ + (n, d) + for n in tree.body + if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) + for d in n.decorator_list + if isinstance(d, ast.Call) + and isinstance(d.func, ast.Name) + and d.func.id == "cloud" + ] + if len(imports) != 1 or imports[0] not in tree.body or len(candidates) != 1: + raise SandboxDeclarationError( + f"{filename}: expected one canonical cloud import and one @cloud(...) function" + ) + imp = imports[0] + if ( + any(a.name == "*" or a.asname for a in imp.names) + or sum(a.name == "cloud" for a in imp.names) != 1 + ): + raise SandboxDeclarationError( + f"{filename}:{imp.lineno}: aliases and star imports are not supported" + ) + cloud_names = {"cloud"} + for node in tree.body: + if isinstance(node, ast.ImportFrom) and node.module == "mobilerun.sandbox": + cloud_names.update( + a.asname or a.name for a in node.names if a.name == "cloud" + ) + if isinstance(node, ast.Assign) and ( + (isinstance(node.value, ast.Name) and node.value.id in cloud_names) + or (isinstance(node.value, ast.Attribute) and node.value.attr == "cloud") + ): + cloud_names.update(t.id for t in node.targets if isinstance(t, ast.Name)) + for node in tree.body: + if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + continue + for dec in node.decorator_list: + target = dec.func if isinstance(dec, ast.Call) else dec + is_cloud = (isinstance(target, ast.Name) and target.id in cloud_names) or ( + isinstance(target, ast.Attribute) and target.attr == "cloud" + ) + if is_cloud and (node, dec) not in candidates: + raise SandboxDeclarationError( + f"{filename}:{dec.lineno}: unsupported additional cloud declaration" + ) + func, decorator = candidates[0] + if len(func.decorator_list) != 1: + raise SandboxDeclarationError( + f"{filename}:{func.lineno}: stacked decorators are not supported" + ) + if len(decorator.args) > 1 or any(k.arg is None for k in decorator.keywords): + raise SandboxDeclarationError( + f"{filename}:{decorator.lineno}: invalid cloud options" + ) + values: dict[str, Any] = {} + try: + if decorator.args: + values["name"] = ast.literal_eval(decorator.args[0]) + for keyword in decorator.keywords: + if keyword.arg == "trigger": + raise SandboxDeclarationError( + "The manual trigger was removed; use an endpoint with device= to attach a device" + ) + if ( + keyword.arg + not in { + "name", + "schedule", + "device", + "endpoint", + "webhook", + "files", + "files_folder", + } + or keyword.arg in values + ): + raise ValueError("unknown or duplicate option") + values[keyword.arg] = ast.literal_eval(keyword.value) + declaration = CloudDeclaration(**values) + declaration.validate() + except SandboxDeclarationError as exc: + raise SandboxDeclarationError(f"{filename}:{decorator.lineno}: {exc}") from exc + except (TypeError, ValueError, SyntaxError) as exc: + raise SandboxDeclarationError( + f"{filename}:{decorator.lineno}: invalid literal cloud options" + ) from exc + return declaration, func diff --git a/mobilerun/sandbox/helpers/declaration_values.py b/mobilerun/sandbox/helpers/declaration_values.py new file mode 100644 index 000000000..a1103c75b --- /dev/null +++ b/mobilerun/sandbox/helpers/declaration_values.py @@ -0,0 +1,35 @@ +"""Checks for values shared by declarations and deployment.""" + +from uuid import UUID + +from ..errors import SandboxDeclarationError + +WEBHOOK_REGISTER_HINT = "mobilerun webhook register " +_UNSAFE_FIELD_PARTS = {"__proto__", "prototype", "constructor"} + + +def is_result_path_part(part: str) -> bool: + """Check a literal key in the worker's dot-separated template syntax.""" + return ( + bool(part) + and part == part.strip().strip("\ufeff").strip() + and not any(char in part for char in ".{}") + and part.lower() not in _UNSAFE_FIELD_PARTS + ) + + +def webhook_endpoint_id(value: str) -> str: + """Return a canonical endpoint ID without exposing invalid input.""" + if isinstance(value, str): + try: + return str(UUID(value)) + except ValueError: + pass + raise SandboxDeclarationError( + f"webhook= takes a webhook endpoint ID. Register one first: {WEBHOOK_REGISTER_HINT}" + ) + + +def validate_device(device: str | None) -> None: + if device is not None and (not isinstance(device, str) or not device.strip()): + raise SandboxDeclarationError("Device must be a nonempty string") diff --git a/mobilerun/sandbox/helpers/deployment.py b/mobilerun/sandbox/helpers/deployment.py new file mode 100644 index 000000000..3c02e78b1 --- /dev/null +++ b/mobilerun/sandbox/helpers/deployment.py @@ -0,0 +1,86 @@ +"""Readiness verification and receipt projection shared by deployment paths.""" + +import asyncio +import time +from typing import Literal + +from mobilerun.models.billing import Billing + +from .. import clients +from ..errors import SandboxDeploymentError +from ..flows import valid_id +from ..models import Artifact, DeploymentReceipt, Endpoint, OwnershipReceipt +from ..settings import get_sandbox_settings + + +async def wait_ready( + function_id: str, version: int, billing: Billing, receipt: OwnershipReceipt +) -> None: + deadline = time.monotonic() + 120.0 + while True: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise SandboxDeploymentError( + "Sandbox version inspection timed out", receipt=receipt + ) + try: + result = await asyncio.wait_for( + clients.get_version(function_id, version, billing=billing), remaining + ) + except TimeoutError: + raise SandboxDeploymentError( + "Sandbox version inspection timed out", receipt=receipt + ) from None + if time.monotonic() >= deadline: + raise SandboxDeploymentError( + "Sandbox version inspection timed out", receipt=receipt + ) + if result.get("version") != version: + raise SandboxDeploymentError( + "Invalid sandbox version response", receipt=receipt + ) + status = result.get("status") + if status == "ready": + return + if status == "rejected": + raise SandboxDeploymentError("Sandbox version rejected", receipt=receipt) + if status not in {"pending", "pending_inspection", "inspecting", "processing"}: + raise SandboxDeploymentError( + "Invalid sandbox version status", receipt=receipt + ) + remaining = deadline - time.monotonic() + if remaining <= 0: + raise SandboxDeploymentError( + "Sandbox version inspection timed out", receipt=receipt + ) + await asyncio.sleep( + min(get_sandbox_settings().MOBILERUN_SANDBOX_POLL_INTERVAL, remaining) + ) + + +def deployment_receipt( + receipt: OwnershipReceipt, + artifact: Artifact, + version: int, + status: Literal["created", "pushed", "unchanged"], + warnings: tuple[str, ...] = (), +) -> DeploymentReceipt: + endpoint = None + if artifact.declaration.has_endpoint: + trigger_id = valid_id(receipt.trigger_id) + endpoint = Endpoint( + receipt.origin.rstrip("/") + "/triggers/" + trigger_id + "/fire", + trigger_id, + ) + return DeploymentReceipt( + receipt.name, + valid_id(receipt.function_id), + version, + status, + receipt.flow_id, + receipt.trigger_id, + receipt.action_ids, + artifact.digest, + endpoint, + warnings, + ) diff --git a/mobilerun/sandbox/helpers/flow_yaml.py b/mobilerun/sandbox/helpers/flow_yaml.py new file mode 100644 index 000000000..fb368140e --- /dev/null +++ b/mobilerun/sandbox/helpers/flow_yaml.py @@ -0,0 +1,15 @@ +"""Encode flow YAML while preserving `on` as a string in YAML 1.1 readers.""" + +import yaml # type: ignore[import-untyped] + + +class FlowDumper(yaml.SafeDumper): + """Safe dumper using a quoted `on` key in workflow documents.""" + + def represent_str(self, data: str) -> yaml.nodes.ScalarNode: + return self.represent_scalar( + "tag:yaml.org,2002:str", data, style='"' if data == "on" else None + ) + + +FlowDumper.add_representer(str, FlowDumper.represent_str) diff --git a/mobilerun/sandbox/helpers/global_reads.py b/mobilerun/sandbox/helpers/global_reads.py new file mode 100644 index 000000000..3bd73f9ab --- /dev/null +++ b/mobilerun/sandbox/helpers/global_reads.py @@ -0,0 +1,150 @@ +"""Visit source scopes and record reads of undeployed globals.""" + +from __future__ import annotations + +import ast +import builtins +import symtable + +from ..errors import SandboxPackagingError +from .local_imports import is_local_import + + +class GlobalReads(ast.NodeVisitor): + def __init__( + self, + scope: symtable.SymbolTable, + filename: str, + allowed: set[str], + bound: set[str], + violations: list[tuple[int, str]], + used: set[int], + ): + self.scope, self.filename, self.allowed, self.bound = ( + scope, + filename, + allowed, + bound, + ) + self.violations, self.used = violations, used + self.hidden: set[str] = set() + + def visit_Name(self, node: ast.Name) -> None: + if isinstance(node.ctx, ast.Load): + try: + is_global = self.scope.lookup(node.id).is_global() + except KeyError: + # Deferred annotations are absent from Python's symbol table. + is_global = True + if ( + is_global + and node.id not in self.hidden + and node.id not in self.allowed + and (node.id not in dir(builtins) or node.id in self.bound) + ): + self.violations.append((node.lineno, node.id)) + + def visit_Import(self, node: ast.Import | ast.ImportFrom) -> None: + if is_local_import(node, self.filename): + raise SandboxPackagingError( + f"{self.filename}:{node.lineno}: local imports are not supported" + ) + + visit_ImportFrom = visit_Import + + def child(self, node: ast.expr | ast.stmt, name: str) -> GlobalReads: + table = next( + ( + t + for t in self.scope.get_children() + if t.get_name() == name + and t.get_lineno() == node.lineno + and t.get_id() not in self.used + ), + None, + ) + if table is not None: + self.used.add(table.get_id()) + visitor = GlobalReads( + table or self.scope, + self.filename, + self.allowed, + self.bound, + self.violations, + self.used, + ) + visitor.hidden = set(self.hidden) + return visitor + + def visit_FunctionDef(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None: + args = [ + *node.args.posonlyargs, + *node.args.args, + *node.args.kwonlyargs, + node.args.vararg, + node.args.kwarg, + ] + parts = [ + *node.decorator_list, + *node.args.defaults, + *[d for d in node.args.kw_defaults if d], + *[a.annotation for a in args if a and a.annotation], + ] + if node.returns: + parts.append(node.returns) + for part in parts: + self.visit(part) + visitor = self.child(node, node.name) + for statement in node.body: + visitor.visit(statement) + + visit_AsyncFunctionDef = visit_FunctionDef + + def visit_Lambda(self, node: ast.Lambda) -> None: + for part in [*node.args.defaults, *[d for d in node.args.kw_defaults if d]]: + self.visit(part) + self.child(node, "lambda").visit(node.body) + + def _comprehension( + self, + node: ast.ListComp | ast.SetComp | ast.GeneratorExp | ast.DictComp, + name: str, + output: list[ast.AST], + ) -> None: + self.visit(node.generators[0].iter) + visitor = self.child(node, name) + for index, generator in enumerate(node.generators): + if index: + visitor.visit(generator.iter) + visitor.hidden.update( + n.id + for n in ast.walk(generator.target) + if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store) + ) + for condition in generator.ifs: + visitor.visit(condition) + for part in output: + visitor.visit(part) + + def visit_ListComp(self, node: ast.ListComp) -> None: + self._comprehension(node, "listcomp", [node.elt]) + + def visit_SetComp(self, node: ast.SetComp) -> None: + self._comprehension(node, "setcomp", [node.elt]) + + def visit_GeneratorExp(self, node: ast.GeneratorExp) -> None: + self._comprehension(node, "genexpr", [node.elt]) + + def visit_DictComp(self, node: ast.DictComp) -> None: + self._comprehension(node, "dictcomp", [node.key, node.value]) + + def visit_ClassDef(self, node: ast.ClassDef) -> None: + for part in [ + *node.decorator_list, + *node.bases, + *(k.value for k in node.keywords), + ]: + self.visit(part) + visitor = self.child(node, node.name) + for statement in node.body: + visitor.visit(statement) diff --git a/mobilerun/sandbox/helpers/inspection.py b/mobilerun/sandbox/helpers/inspection.py new file mode 100644 index 000000000..82979339c --- /dev/null +++ b/mobilerun/sandbox/helpers/inspection.py @@ -0,0 +1,200 @@ +"""Inspect generated worker contracts, including serialized file projections.""" + +import json +import subprocess +import sys +import tempfile +from pathlib import Path +from typing import Any + +from ..errors import SandboxDeclarationError, SandboxPackagingError +from ..models import FILES_RETURN_ERROR, JSON +from ..settings import RUNTIME_MODULE, get_sandbox_settings + +# Use the same loader and inspector as the runtime's `inspect` command. Run in +# its existing child process: never import the user's original module or call +# the function. Scheduled and file-backed routines need additional model checks. +_MODEL_INSPECTOR = f"""\ +import json, sys +from contextlib import redirect_stdout +from pydantic import ValidationError +from pydantic.json_schema import GenerateJsonSchema +from {RUNTIME_MODULE}.loader import load_script +from {RUNTIME_MODULE}._contract import inspect_entry +from {RUNTIME_MODULE}.schema import _walk + +class ProjectionSchema(GenerateJsonSchema): + def generate_inner(self, schema): + result = super().generate_inner(schema) + serializer = schema.get('serialization') or {{}} + if self.mode == 'serialization' and serializer.get('type') in ('any', 'function-plain', 'function-wrap'): + # Mark this occurrence, not the shared definition used by other fields. + return dict(result, **{{'x-mobilerun-dynamic-serializer': True}}) + return result + + def field_is_required(self, field, total): + if self.mode == 'serialization' and field['type'] in ('model-field', 'dataclass-field'): + # The runner's model_dump_json(by_alias=True) includes defaults and nulls. + return field.get('serialization_exclude_if') is None + return super().field_is_required(field, total) + + def model_fields_schema(self, schema): + result = super().model_fields_schema(schema) + if any(field.get('serialization_exclude') for field in schema['fields'].values()) or any( + field.get('alias', field['property_name']) not in result.get('properties', {{}}) + for field in schema.get('computed_fields', []) + ): + result['x-mobilerun-omittable-fields'] = True + return result + +with redirect_stdout(sys.stderr): + flags, path = sys.argv[1:-1], sys.argv[-1] + entry = load_script(path) + document = inspect_entry(entry) + if 'files' in flags: + document['validFilesOutput'] = entry.output_model is not None and not entry.allows_none + if 'file_webhook' in flags and document['validFilesOutput']: + raw = entry.output_model.model_json_schema(mode='serialization', schema_generator=ProjectionSchema) + document['projectionSchema'] = _walk(raw, raw.get('$defs', {{}}), (), '') + if 'scheduled' in flags: + try: + entry.input_model.model_validate_json('{{}}') + except ValidationError as exc: + properties = document['inputSchema'].get('properties', {{}}) + locations = (error['loc'] for error in exc.errors( + include_input=False, include_context=False, include_url=False)) + document['scheduleInputErrors'] = sorted({{ + loc[0] for loc in locations if loc and loc[0] in properties + }}) + else: + document['scheduleInputErrors'] = None +print(json.dumps(document)) +""" + + +def inspect_source( + source: str, + *, + scheduled: bool = False, + files: bool = False, + file_webhook: bool = False, +) -> JSON: + """Inspect trusted generated source in an isolated temporary directory.""" + files = files or file_webhook + try: + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "script.py" + path.write_text(source, encoding="utf-8") + flags = [ + name + for name, enabled in ( + ("scheduled", scheduled), + ("files", files), + ("file_webhook", file_webhook), + ) + if enabled + ] + args = ( + ["-c", _MODEL_INSPECTOR, *flags] + if flags + else ["-m", RUNTIME_MODULE, "inspect"] + ) + result = subprocess.run( + [sys.executable, *args, str(path)], + capture_output=True, + text=True, + timeout=get_sandbox_settings().MOBILERUN_SANDBOX_INSPECTION_TIMEOUT, + check=False, + ) + if result.returncode: + raise SandboxPackagingError("Local sandbox inspection failed") + document = json.loads(result.stdout) + if ( + not isinstance(document, dict) + or document.get("ok") is not True + or not isinstance(document.get("inputSchema"), dict) + or not ( + document.get("outputSchema") is None + or isinstance(document.get("outputSchema"), dict) + ) + or "outputSchema" not in document + or (scheduled and "scheduleInputErrors" not in document) + or (files and not isinstance(document.get("validFilesOutput"), bool)) + ): + raise SandboxPackagingError( + "Local sandbox inspection returned an invalid document" + ) + if files and not document["validFilesOutput"]: + raise SandboxDeclarationError(FILES_RETURN_ERROR) + if file_webhook and not isinstance(document.get("projectionSchema"), dict): + raise SandboxPackagingError( + "Local sandbox inspection returned an invalid projection schema" + ) + if scheduled and (fields := document["scheduleInputErrors"]) is not None: + properties = document["inputSchema"].get("properties", {}) + if not isinstance(fields, list) or not all( + isinstance(field, str) and field in properties for field in fields + ): + raise SandboxPackagingError("Invalid scheduled input inspection result") + raise SandboxDeclarationError( + "Scheduled input must accept {}" + + (f"; failing fields: {', '.join(fields)}" if fields else "") + ) + return document + except ( + OSError, + UnicodeError, + subprocess.TimeoutExpired, + json.JSONDecodeError, + ): + raise SandboxPackagingError("Local sandbox inspection failed") from None + + +def validate_file_output(output: JSON, path: str) -> None: + """Require the inspected result schema to guarantee a string at this path.""" + hint = f"files output field {path!r} must be a required, non-null string" + + def dereference(node: Any) -> JSON: + seen: set[str] = set() + while isinstance(node, dict): + if node.get("nullable") is True or {"anyOf", "oneOf"} & node.keys(): + break + if "$ref" not in node: + return node + ref = node["$ref"] + if not isinstance(ref, str) or not ref.startswith("#/") or ref in seen: + break + seen.add(ref) + node = output + for token in ref[2:].split("/"): + node = ( + node.get(token.replace("~1", "/").replace("~0", "~")) + if isinstance(node, dict) + else None + ) + raise SandboxDeclarationError(hint) + + node: Any = output + parts = path.split(".") + for offset, part in enumerate(parts): + node = dereference(node) + if node.get("type") == "object" and part in node.get("required", []): + node = node.get("properties", {}).get(part) + elif node.get("type") == "array" and part.isdecimal(): + try: + size = int(part) + 1 + except ValueError: + raise SandboxDeclarationError( + f"files output field {path!r} has an unsupported array index" + ) from None + minimum = node.get("minItems", 0) + if type(minimum) is not int or minimum < size: + parent = ".".join(parts[:offset]) + raise SandboxDeclarationError( + f"files output field {path!r} requires min_length={size} on {parent or 'the result array'}" + ) + node = node.get("items") + else: + raise SandboxDeclarationError(hint) + if dereference(node).get("type") != "string": + raise SandboxDeclarationError(hint) diff --git a/mobilerun/sandbox/helpers/local_imports.py b/mobilerun/sandbox/helpers/local_imports.py new file mode 100644 index 000000000..fd583a92d --- /dev/null +++ b/mobilerun/sandbox/helpers/local_imports.py @@ -0,0 +1,21 @@ +"""Check whether a source import refers to a file omitted from the artifact.""" + +import ast +from pathlib import Path + + +def is_local_import(node: ast.Import | ast.ImportFrom, filename: str) -> bool: + if isinstance(node, ast.ImportFrom) and node.level: + return True + modules = ( + [node.module or ""] + if isinstance(node, ast.ImportFrom) + else [a.name for a in node.names] + ) + root = Path(filename).absolute().parent + return any( + (root / (name.split(".")[0] + ".py")).exists() + or (root / name.split(".")[0] / "__init__.py").exists() + for name in modules + if name + ) diff --git a/mobilerun/sandbox/helpers/routine.py b/mobilerun/sandbox/helpers/routine.py new file mode 100644 index 000000000..6aee6cce6 --- /dev/null +++ b/mobilerun/sandbox/helpers/routine.py @@ -0,0 +1,17 @@ +"""Register a routine on the optional worker runtime.""" + +from collections.abc import Callable +from typing import ParamSpec, TypeVar + +P = ParamSpec("P") +R = TypeVar("R") + + +def routine(func: Callable[P, R]) -> Callable[P, R]: + """Register a synchronous or asynchronous routine with upstream's runner. + + Use ``ctx.device()`` for the upstream synchronous device when needed. + """ + from .._runtime import script + + return script(func) diff --git a/mobilerun/sandbox/helpers/run_result.py b/mobilerun/sandbox/helpers/run_result.py new file mode 100644 index 000000000..f5a6750a4 --- /dev/null +++ b/mobilerun/sandbox/helpers/run_result.py @@ -0,0 +1,122 @@ +"""Project execution records to safe snapshots and validate their result steps.""" + +import copy +from typing import Any + +from ..documents import action_type +from ..errors import SandboxDeploymentError, SandboxRunError +from ..flows import valid_id +from ..models import JSON + + +def safe_snapshot(record: JSON) -> JSON: + """Keep the execution contract, not raw server errors or signed artifacts.""" + result: JSON = { + "id": run_identifier(record.get("id")), + "status": record.get("status"), + } + for key in ("flowId", "invocationId", "startedAt", "finishedAt"): + if isinstance(record.get(key), str): + result[key] = record[key] + # Use this execution's own progress, not the current (possibly redeployed) flow. + for source in ("progress", "result"): + metadata = record.get(source) + if not isinstance(metadata, dict) or not isinstance( + metadata.get("steps"), list + ): + continue + if source == "result": + result["result"] = {"steps": []} + for step in metadata["steps"]: + if not isinstance(step, dict): + continue + uses = action_type(step) + status = step.get("status") + body = step.get("body") + if source == "result" and uses == "functions.run": + function: JSON = {"uses": uses} + if status is not None: + function["status"] = status if status == "success" else "failed" + if isinstance(body, dict): + function["body"] = { + k: copy.deepcopy(body[k]) + for k in ( + "result", + "outcome", + "ok", + "partialReason", + "state", + "notes", + ) + if k in body + } + if body.get("error") is not None: + function["status"] = "failed" + result["result"]["steps"].append(function) + if uses != "webhooks.send": + continue + if isinstance(body, dict) and body.get("error") is not None: + status = "failed" + elif status is None and isinstance(body, dict) and body.get("eventId"): + status = "succeeded" + if status == "success": + status = "succeeded" + if status in ("succeeded", "failed", "skipped", "cancelled"): + result["webhookStatus"] = status + elif status in ("pending", "running") and result.get("webhookStatus") in ( + None, + "pending", + ): + result["webhookStatus"] = status + if source == "result": + safe_step: JSON = {"uses": "webhooks.send"} + if "webhookStatus" in result: + safe_step["status"] = result["webhookStatus"] + if isinstance(body, dict) and isinstance(body.get("eventId"), str): + safe_step["body"] = {"eventId": body["eventId"]} + result["result"]["steps"].append(safe_step) + return result + + +def run_identifier(value: Any) -> str: + try: + return valid_id(value) + except SandboxDeploymentError: + raise SandboxRunError("Invalid sandbox run identifier") from None + + +def function_steps(snapshot: JSON) -> list[JSON]: + result = snapshot.get("result") + if not isinstance(result, dict) or not isinstance(result.get("steps"), list): + return [] + return [ + s + for s in result["steps"] + if isinstance(s, dict) and action_type(s) == "functions.run" + ] + + +def check_success(snapshot: JSON, invocation_id: str | None) -> None: + steps = function_steps(snapshot) + execution_id = snapshot["id"] + if not steps: + raise SandboxRunError( + "Sandbox execution has no function result", + invocation_id=invocation_id, + execution_id=execution_id, + ) + for step in steps: + body = step.get("body") + if ( + step.get("status") not in (None, "success") + or not isinstance(body, dict) + or body.get("ok") is False + or body.get("error") is not None + or body.get("outcome") not in (None, "complete", "succeeded", "partial") + or "result" not in body + ): + raise SandboxRunError( + "Sandbox function body failed or is invalid", + invocation_id=invocation_id, + execution_id=execution_id, + ) diff --git a/mobilerun/sandbox/helpers/source.py b/mobilerun/sandbox/helpers/source.py new file mode 100644 index 000000000..c7d53f5aa --- /dev/null +++ b/mobilerun/sandbox/helpers/source.py @@ -0,0 +1,248 @@ +"""Extract a standalone worker script from the cloud declaration and its dependencies.""" + +import ast +import builtins +import symtable + +from ..errors import SandboxPackagingError +from ..settings import RUNTIME_MODULE +from .declaration import parse_source, source_declaration +from .global_reads import GlobalReads +from .local_imports import is_local_import + + +def _names(node: ast.AST, bindings: dict[str, str]) -> set[str]: + result = { + n.id + for n in ast.walk(node) + if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Load) + } + for n in ast.walk(node): + if isinstance(n, ast.AnnAssign): + result.update(_annotation_names(n.annotation, bindings)) + return result + + +def _annotation_names(node: ast.AST, bindings: dict[str, str]) -> set[str]: + result: set[str] = set() + + class AnnotationVisitor(ast.NodeVisitor): + def visit_Name(self, part: ast.Name) -> None: + if isinstance(part.ctx, ast.Load): + result.add(part.id) + + def visit_Constant(self, part: ast.Constant) -> None: + if not isinstance(part.value, str): + return + try: + self.visit(ast.parse(part.value, mode="eval")) + except SyntaxError: + pass + + def visit_Subscript(self, part: ast.Subscript) -> None: + self.visit(part.value) + if isinstance(part.value, ast.Name): + name = bindings.get(part.value.id, "") + elif ( + isinstance(part.value, ast.Attribute) + and isinstance(part.value.value, ast.Name) + and bindings.get(part.value.value.id) in ("typing", "typing_extensions") + ): + name = part.value.attr + else: + name = "" + if name == "Literal": + return + if name == "Annotated" and isinstance(part.slice, ast.Tuple): + self.visit(part.slice.elts[0]) + for item in part.slice.elts[1:]: + result.update(_names(item, bindings)) + return + self.visit(part.slice) + + AnnotationVisitor().visit(node) + return result + + +def transform(source: str, *, filename: str = "main.py") -> str: + """Extract a standalone script while rejecting omitted dependencies.""" + tree = parse_source(source, filename) + _, func = source_declaration(tree, filename) + args = [ + *func.args.posonlyargs, + *func.args.args, + *func.args.kwonlyargs, + func.args.vararg, + func.args.kwarg, + ] + annotations = [a.annotation for a in args if a and a.annotation] + if func.returns: + annotations.append(func.returns) + imports: dict[str, ast.Import | ast.ImportFrom] = {} + bindings: dict[str, str] = {} + for statement in tree.body: + if isinstance(statement, (ast.Import, ast.ImportFrom)): + for alias in statement.names: + name = alias.asname or ( + alias.name.split(".")[0] + if isinstance(statement, ast.Import) + else alias.name + ) + imports[name] = statement + if isinstance(statement, ast.Import) and alias.name in ( + "typing", + "typing_extensions", + ): + bindings[name] = alias.name + elif ( + isinstance(statement, ast.ImportFrom) + and statement.module in ("typing", "typing_extensions") + and alias.name in ("Literal", "Annotated") + ): + bindings[name] = alias.name + table = symtable.symtable(source, filename, "exec") + function_table = next( + t + for t in table.get_children() + if t.get_name() == func.name and t.get_lineno() == func.lineno + ) + bound = { + s.get_name() + for s in table.get_symbols() + if s.is_assigned() or s.is_imported() or s.is_namespace() + } + required = ( + set().union(*(_annotation_names(n, bindings) for n in annotations)) + if annotations + else set() + ) + classes = {n.name: n for n in tree.body if isinstance(n, ast.ClassDef)} + selected: set[str] = set() + while pending := (required & classes.keys()) - selected: + for name in pending: + selected.add(name) + reads: list[tuple[int, str]] = [] + GlobalReads(table, filename, set(), bound, reads, set()).visit( + classes[name] + ) + required.update(dependency for _, dependency in reads) + for node in ast.walk(classes[name]): + if isinstance(node, ast.AnnAssign): + required.update(_annotation_names(node.annotation, bindings)) + allowed = selected | (required & imports.keys()) | {"Context"} + violations: list[tuple[int, str]] = [] + for annotation in annotations: + for name in _annotation_names(annotation, bindings): + if ( + name not in classes + and name not in imports + and (name not in dir(builtins) or name in bound) + ): + violations.append((annotation.lineno, name)) + visitor = GlobalReads(function_table, filename, allowed, bound, violations, set()) + for statement in func.body: + visitor.visit(statement) + for default in [*func.args.defaults, *[d for d in func.args.kw_defaults if d]]: + for node in ast.walk(default): + if ( + isinstance(node, ast.Name) + and isinstance(node.ctx, ast.Load) + and (node.id not in dir(builtins) or node.id in bound) + ): + violations.append((node.lineno, node.id)) + for name in selected: + model_visitor = GlobalReads( + table, filename, set(imports) | selected, bound, violations, set() + ) + model_visitor.visit(classes[name]) + for node in ast.walk(classes[name]): + if isinstance(node, ast.AnnAssign): + for dependency in _annotation_names(node.annotation, bindings): + if ( + dependency not in imports + and dependency not in selected + and (dependency not in dir(builtins) or dependency in bound) + ): + violations.append((node.lineno, dependency)) + if violations: + raise SandboxPackagingError( + "\n".join( + f"{filename}:{line}: '{name}' is defined outside {func.name} — import or define it inside the function (lazy import)" + for line, name in sorted(set(violations)) + ) + ) + future = any( + isinstance(n, ast.ImportFrom) + and n.module == "__future__" + and any(a.name == "annotations" for a in n.names) + for n in tree.body + ) + generated = ["from __future__ import annotations"] if future else [] + runtime_names = ["Context", "script"] + for name in sorted(required): + import_node = imports.get(name) + if ( + isinstance(import_node, ast.ImportFrom) + and import_node.module in ("mobilerun.sandbox", RUNTIME_MODULE) + and name not in ("cloud", "Context", "script") + ): + alias = next(a for a in import_node.names if (a.asname or a.name) == name) + runtime_names.append( + alias.name + (" as " + alias.asname if alias.asname else "") + ) + generated.append(f"from {RUNTIME_MODULE} import " + ", ".join(runtime_names)) + for statement in tree.body: + if ( + not isinstance(statement, (ast.Import, ast.ImportFrom)) + or isinstance(statement, ast.ImportFrom) + and statement.module in ("mobilerun.sandbox", RUNTIME_MODULE, "__future__") + ): + continue + aliases = [ + a + for a in statement.names + if ( + a.asname + or ( + a.name.split(".")[0] + if isinstance(statement, ast.Import) + else a.name + ) + ) + in required + ] + if not aliases: + continue + if is_local_import(statement, filename): + raise SandboxPackagingError( + f"{filename}:{statement.lineno}: local imports are not supported" + ) + text = ", ".join( + a.name + (" as " + a.asname if a.asname else "") for a in aliases + ) + generated.append( + ( + "import " + if isinstance(statement, ast.Import) + else f"from {statement.module} import " + ) + + text + ) + lines = source.splitlines(keepends=True) + definitions = [ + "".join( + lines[ + min([n.lineno, *(d.lineno for d in n.decorator_list)]) + - 1 : n.end_lineno + ] + ).rstrip() + for n in tree.body + if isinstance(n, ast.ClassDef) and n.name in selected + ] + body = "".join(lines[func.lineno - 1 : func.end_lineno]).rstrip() + return ( + "\n".join(generated) + + "\n\n\n" + + "\n\n\n".join([*definitions, "@script\n" + body]) + + "\n" + ) diff --git a/mobilerun/sandbox/helpers/sync.py b/mobilerun/sandbox/helpers/sync.py new file mode 100644 index 000000000..900e33271 --- /dev/null +++ b/mobilerun/sandbox/helpers/sync.py @@ -0,0 +1,20 @@ +"""Bridge synchronous sandbox calls to async orchestration.""" + +import asyncio +from collections.abc import Callable, Coroutine +from typing import Any, TypeVar + +T = TypeVar("T") + + +def run_sync(operation: Callable[[], Coroutine[Any, Any, T]]) -> T: + """Reject a running loop before constructing the coroutine.""" + try: + asyncio.get_running_loop() + except RuntimeError: + pass + else: + raise RuntimeError( + "The synchronous sandbox API cannot run inside an active event loop" + ) + return asyncio.run(operation()) diff --git a/mobilerun/sandbox/helpers/validation.py b/mobilerun/sandbox/helpers/validation.py new file mode 100644 index 000000000..a189e6ae1 --- /dev/null +++ b/mobilerun/sandbox/helpers/validation.py @@ -0,0 +1,161 @@ +"""Round-trip typed inputs and sanitize validation errors for callers.""" + +import json +from collections.abc import Callable, Sequence +from typing import Any, TypeVar, get_args, get_origin + +from pydantic import AliasChoices, AliasPath, BaseModel, ValidationError +from pydantic_core import ErrorType, InitErrorDetails, PydanticCustomError + +from ..errors import SandboxDeclarationError +from ..models import JSON + +T = TypeVar("T") +_BUILTIN_ERROR_CODES = frozenset(get_args(ErrorType)) + + +def _write_alias(container: Any, path: Sequence[str | int], value: Any) -> None: + key, *rest = path + if isinstance(key, str) and isinstance(container, dict): + pass + elif isinstance(key, int) and key >= 0 and isinstance(container, list): + if key >= len(container): + container.extend([None] * (key + 1 - len(container))) + else: + raise ValueError("Unsupported or conflicting alias path") + if not rest: + container[key] = value + return + if isinstance(container, dict): + child = container.get(key) + else: + child = container[key] + if child is None: + child = {} if isinstance(rest[0], str) else [] + container[key] = child + _write_alias(child, rest, value) + + +def _validation_keys(value: Any, dumped: Any) -> Any: + """Shape dumped model fields according to their validation aliases.""" + if isinstance(value, BaseModel) and isinstance(dumped, dict): + fields = type(value).model_fields + result = {key: entry for key, entry in dumped.items() if key not in fields} + for name, field in fields.items(): + if name not in dumped: + continue + alias = field.validation_alias + if isinstance(alias, AliasChoices): + alias = alias.choices[0] + path = ( + alias.path + if isinstance(alias, AliasPath) + else [name if alias is None else alias] + ) + _write_alias( + result, path, _validation_keys(getattr(value, name), dumped[name]) + ) + return result + if ( + isinstance(value, (list, tuple)) + and isinstance(dumped, list) + and len(value) == len(dumped) + ): + return [ + _validation_keys(child, entry) + for child, entry in zip(value, dumped, strict=True) + ] + if isinstance(value, dict) and isinstance(dumped, dict): + return { + key: _validation_keys(value.get(key), entry) + for key, entry in dumped.items() + } + return dumped + + +def _safe_location( + model: Any, location: tuple[str | int, ...], *, extra_field: bool +) -> tuple[str | int, ...]: + """Keep declared model fields and sequence indices; unknown path segments are data.""" + result: list[str | int] = [] + for part in location: + origin, args = get_origin(model), get_args(model) + safe: str | int = "" + child = None + if ( + isinstance(model, type) + and issubclass(model, BaseModel) + and not model.__pydantic_root_model__ + ): + # An alias path or ambiguous alias may point to a different shape. + fields = model.model_fields + if isinstance(part, str) and all( + f.validation_alias is None or isinstance(f.validation_alias, str) + for f in fields.values() + ): + matches = [ + f + for name, f in fields.items() + if part in (name, f.validation_alias) + ] + if len(matches) == 1: + safe, child = part, matches[0].annotation + elif origin is list and isinstance(part, int) and part >= 0: + safe, child = part, args[0] if args else None + elif origin is tuple and isinstance(part, int) and part >= 0: + safe = part + child = ( + args[0] + if args[-1:] == (Ellipsis,) + else args[part] if part < len(args) else None + ) + elif origin is dict and len(args) == 2: + child = args[1] + result.append(safe) + model = child + if extra_field and result: + result[-1] = "" + return tuple(result) + + +def validate_typed(validate: Callable[[Any], T], value: Any, model: Any) -> T: + """Preserve validation locations and types, never values or validator messages.""" + try: + return validate(value) + except ValidationError as exc: + errors: list[InitErrorDetails] = [] + for error in exc.errors( + include_input=False, include_context=False, include_url=False + ): + code = error["type"] if error["type"] in _BUILTIN_ERROR_CODES else "invalid" + errors.append( + { + "type": PydanticCustomError(code, code), + "loc": _safe_location( + model, + error["loc"], + extra_field=error["type"] == "extra_forbidden", + ), + "input": None, + } + ) + # Raise outside the handler so the original exception is not retained as context. + raise ValidationError.from_exception_data( + "Sandbox validation", errors, hide_input=True + ) + + +def validation_payload(value: BaseModel) -> JSON: + message = "Sandbox input could not round-trip through its model's JSON validation" + try: + payload = _validation_keys( + value, value.model_dump(mode="json", by_alias=False, round_trip=True) + ) + if isinstance(payload, dict): + # Match the worker's JSON validation, including strict model types. + rendered = json.dumps(payload, allow_nan=False) + if type(value).model_validate_json(rendered) == value: + return payload + except (TypeError, ValueError, OverflowError, RecursionError): + raise SandboxDeclarationError(message) from None + raise SandboxDeclarationError(message) diff --git a/mobilerun/sandbox/models.py b/mobilerun/sandbox/models.py index e4d5b4af0..ef867ba3e 100644 --- a/mobilerun/sandbox/models.py +++ b/mobilerun/sandbox/models.py @@ -4,73 +4,44 @@ import re import unicodedata -from collections.abc import Callable from dataclasses import dataclass, field from pathlib import Path -from typing import Any, Literal, ParamSpec, TypeVar -from uuid import UUID - -from mobilerun.config.settings import get_settings -from mobilerun.models.billing import Billing +from typing import Any, Literal, NotRequired, TypedDict from .errors import SandboxDeclarationError - -P = ParamSpec("P") -R = TypeVar("R") - - -def routine(func: Callable[P, R]) -> Callable[P, R]: - """Register a synchronous or asynchronous routine with upstream's runner. - - Use ``ctx.device()`` for the upstream synchronous device when needed. - """ - from ._runtime import script - - return script(func) - +from .helpers.declaration_values import ( + is_result_path_part, + validate_device, + webhook_endpoint_id, +) JSON = dict[str, Any] -WEBHOOK_REGISTER_HINT = "mobilerun webhook register " FILES_RETURN_ERROR = "files require a non-optional Pydantic BaseModel return annotation" FILE_UPLOAD_USES = "files.upload" FILE_MIME_TYPES = {".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png"} _FILE_FIELD_PART = re.compile(r"[A-Za-z_][A-Za-z0-9_]*|0|[1-9][0-9]*") -_UNSAFE_FIELD_PARTS = {"__proto__", "prototype", "constructor"} - - -def is_result_path_part(part: str) -> bool: - """Check a literal key in the worker's dot-separated template syntax.""" - return ( - bool(part) - and part == part.strip().strip("\ufeff").strip() - and not any(char in part for char in ".{}") - and part.lower() not in _UNSAFE_FIELD_PARTS - ) - -def webhook_endpoint_id(value: str) -> str: - """Return a canonical endpoint ID without exposing invalid input.""" - if isinstance(value, str): - try: - return str(UUID(value)) - except ValueError: - pass - raise SandboxDeclarationError( - f"webhook= takes a webhook endpoint ID. Register one first: {WEBHOOK_REGISTER_HINT}" - ) +class CutoverState(TypedDict): + """Persisted cutover checkpoint shared by planning, execution and recovery.""" -def validate_device(device: str | None) -> None: - if device is not None and (not isinstance(device, str) or not device.strip()): - raise SandboxDeclarationError("Device must be a nonempty string") - - -def _utf16_length(value: str) -> int: - return len(value.encode("utf-16-le", errors="surrogatepass")) // 2 - - -def _has_control_chars(value: str) -> bool: - return any(unicodedata.category(char) == "Cc" for char in value) + stage: Literal["cutover"] + digest: str + device: str | None + version: int + before: JSON + desired: JSON + action_payloads: NotRequired[list[JSON]] + old_ids: list[str] + new_ids: list[str] + enabled: bool + done: list[str] + pending: str | None + complete: bool + retire_ids: NotRequired[list[str]] + webhook_unusable: NotRequired[bool] + retarget_generation: NotRequired[int] + warning: NotRequired[str] @dataclass(frozen=True) @@ -121,10 +92,10 @@ def _validate_files(self) -> None: not isinstance(folder, str) or not folder.removeprefix("/").strip() or ".." in folder - or _has_control_chars(folder) + or self._has_control_chars(folder) or any(part in {"", "."} for part in folder.removeprefix("/").split("/")) # JavaScript's schema counts the leading slash and UTF-16 code units. - or _utf16_length("/" + folder.removeprefix("/")) > 1024 + or self._utf16_length("/" + folder.removeprefix("/")) > 1024 ): raise SandboxDeclarationError( "files_folder must be a safe folder path of at most 1024 characters including the leading slash" @@ -133,11 +104,11 @@ def _validate_files(self) -> None: for filename, path in self.files.items(): if ( not isinstance(filename, str) - or not 1 <= _utf16_length(filename) <= 255 + or not 1 <= self._utf16_length(filename) <= 255 or filename != filename.strip().strip("\ufeff") or "/" in filename or "\\" in filename - or _has_control_chars(filename) + or self._has_control_chars(filename) ): raise SandboxDeclarationError( "file filename must be a safe single path segment" @@ -158,6 +129,14 @@ def _validate_files(self) -> None: ): raise SandboxDeclarationError("invalid output field in files") + @staticmethod + def _utf16_length(value: str) -> int: + return len(value.encode("utf-16-le", errors="surrogatepass")) // 2 + + @staticmethod + def _has_control_chars(value: str) -> bool: + return any(unicodedata.category(char) == "Cc" for char in value) + @dataclass(frozen=True) class Artifact: @@ -232,8 +211,3 @@ def to_dict(self) -> JSON: "digest": self.digest, "stages": list(self.stages), } - - -def resolve_billing(billing: Billing | str | None) -> Billing: - """Resolve explicit billing before the shared environment default.""" - return Billing(billing) if billing is not None else get_settings().MOBILERUN_BILLING diff --git a/mobilerun/sandbox/packaging.py b/mobilerun/sandbox/packaging.py index 90ff65c6c..7b16f12ae 100644 --- a/mobilerun/sandbox/packaging.py +++ b/mobilerun/sandbox/packaging.py @@ -1,28 +1,15 @@ -"""Extract one cloud declaration without executing its containing module. +"""Package trusted sandbox sources for the cloud runtime.""" -Inspection imports the generated script and its required dependencies in a -subprocess. Only inspect trusted source and trusted Python environments. -""" - -from __future__ import annotations - -import ast -import builtins import hashlib -import json -import subprocess -import symtable -import sys -import tempfile from dataclasses import dataclass from pathlib import Path -from typing import Any from .errors import SandboxDeclarationError, SandboxPackagingError -from .models import FILES_RETURN_ERROR, Artifact, CloudDeclaration -from .settings import RUNTIME_MODULE, get_sandbox_settings - -JSON = dict[str, Any] +from .helpers.declaration import parse_source, source_declaration +from .helpers.inspection import inspect_source, validate_file_output +from .helpers.source import transform +from .models import Artifact, CloudDeclaration +from .settings import RUNTIME_MODULE @dataclass(frozen=True) @@ -40,118 +27,6 @@ def verify_scheduled_artifact(artifact: Artifact) -> None: inspect_source(artifact.source, scheduled=True) -def _parse(source: str, filename: str) -> ast.Module: - try: - return ast.parse(source, filename=filename) - except (SyntaxError, ValueError) as exc: - location = ( - f"{filename}:{exc.lineno}" - if isinstance(exc, SyntaxError) and exc.lineno - else filename - ) - # SyntaxError retains the offending source line, including any webhook token. - raise SandboxDeclarationError(f"{location}: invalid Python source") - - -def _declaration( - tree: ast.Module, filename: str -) -> tuple[CloudDeclaration, ast.FunctionDef | ast.AsyncFunctionDef]: - imports = [ - n - for n in ast.walk(tree) - if isinstance(n, ast.ImportFrom) - and n.module == "mobilerun.sandbox" - and n.level == 0 - and any(a.name == "cloud" or a.name == "*" for a in n.names) - ] - candidates = [ - (n, d) - for n in tree.body - if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) - for d in n.decorator_list - if isinstance(d, ast.Call) - and isinstance(d.func, ast.Name) - and d.func.id == "cloud" - ] - if len(imports) != 1 or imports[0] not in tree.body or len(candidates) != 1: - raise SandboxDeclarationError( - f"{filename}: expected one canonical cloud import and one @cloud(...) function" - ) - imp = imports[0] - if ( - any(a.name == "*" or a.asname for a in imp.names) - or sum(a.name == "cloud" for a in imp.names) != 1 - ): - raise SandboxDeclarationError( - f"{filename}:{imp.lineno}: aliases and star imports are not supported" - ) - cloud_names = {"cloud"} - for node in tree.body: - if isinstance(node, ast.ImportFrom) and node.module == "mobilerun.sandbox": - cloud_names.update( - a.asname or a.name for a in node.names if a.name == "cloud" - ) - if isinstance(node, ast.Assign) and ( - (isinstance(node.value, ast.Name) and node.value.id in cloud_names) - or (isinstance(node.value, ast.Attribute) and node.value.attr == "cloud") - ): - cloud_names.update(t.id for t in node.targets if isinstance(t, ast.Name)) - for node in tree.body: - if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): - continue - for dec in node.decorator_list: - target = dec.func if isinstance(dec, ast.Call) else dec - is_cloud = (isinstance(target, ast.Name) and target.id in cloud_names) or ( - isinstance(target, ast.Attribute) and target.attr == "cloud" - ) - if is_cloud and (node, dec) not in candidates: - raise SandboxDeclarationError( - f"{filename}:{dec.lineno}: unsupported additional cloud declaration" - ) - func, decorator = candidates[0] - if len(func.decorator_list) != 1: - raise SandboxDeclarationError( - f"{filename}:{func.lineno}: stacked decorators are not supported" - ) - if len(decorator.args) > 1 or any(k.arg is None for k in decorator.keywords): - raise SandboxDeclarationError( - f"{filename}:{decorator.lineno}: invalid cloud options" - ) - values: dict[str, Any] = {} - try: - if decorator.args: - values["name"] = ast.literal_eval(decorator.args[0]) - for keyword in decorator.keywords: - if keyword.arg == "trigger": - raise SandboxDeclarationError( - "The manual trigger was removed; use an endpoint with device= to attach a device" - ) - if ( - keyword.arg - not in { - "name", - "schedule", - "device", - "endpoint", - "webhook", - "files", - "files_folder", - } - or keyword.arg in values - ): - raise ValueError("unknown or duplicate option") - values[keyword.arg] = ast.literal_eval(keyword.value) - declaration = CloudDeclaration(**values) - declaration.validate() - except SandboxDeclarationError as exc: - raise SandboxDeclarationError(f"{filename}:{decorator.lineno}: {exc}") from exc - except (TypeError, ValueError, SyntaxError) as exc: - raise SandboxDeclarationError( - f"{filename}:{decorator.lineno}: invalid literal cloud options" - ) from exc - return declaration, func - - def read_declaration(path: Path, *, source: str | None = None) -> CloudDeclaration: """Read a single literal declaration without importing the user's file.""" if source is None: @@ -159,580 +34,7 @@ def read_declaration(path: Path, *, source: str | None = None) -> CloudDeclarati source = path.read_text(encoding="utf-8") except (OSError, UnicodeError) as exc: raise SandboxDeclarationError(f"Cannot read declaration: {path}") from exc - return _declaration(_parse(source, str(path)), str(path))[0] - - -def _names(node: ast.AST, bindings: dict[str, str]) -> set[str]: - result = { - n.id - for n in ast.walk(node) - if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Load) - } - for n in ast.walk(node): - if isinstance(n, ast.AnnAssign): - result.update(_annotation_names(n.annotation, bindings)) - return result - - -def _annotation_names(node: ast.AST, bindings: dict[str, str]) -> set[str]: - result: set[str] = set() - - class AnnotationVisitor(ast.NodeVisitor): - def visit_Name(self, part: ast.Name) -> None: - if isinstance(part.ctx, ast.Load): - result.add(part.id) - - def visit_Constant(self, part: ast.Constant) -> None: - if not isinstance(part.value, str): - return - try: - self.visit(ast.parse(part.value, mode="eval")) - except SyntaxError: - pass - - def visit_Subscript(self, part: ast.Subscript) -> None: - self.visit(part.value) - if isinstance(part.value, ast.Name): - name = bindings.get(part.value.id, "") - elif ( - isinstance(part.value, ast.Attribute) - and isinstance(part.value.value, ast.Name) - and bindings.get(part.value.value.id) in ("typing", "typing_extensions") - ): - name = part.value.attr - else: - name = "" - if name == "Literal": - return - if name == "Annotated" and isinstance(part.slice, ast.Tuple): - self.visit(part.slice.elts[0]) - for item in part.slice.elts[1:]: - result.update(_names(item, bindings)) - return - self.visit(part.slice) - - AnnotationVisitor().visit(node) - return result - - -def _local_import(node: ast.Import | ast.ImportFrom, filename: str) -> bool: - if isinstance(node, ast.ImportFrom) and node.level: - return True - modules = ( - [node.module or ""] - if isinstance(node, ast.ImportFrom) - else [a.name for a in node.names] - ) - root = Path(filename).absolute().parent - return any( - (root / (name.split(".")[0] + ".py")).exists() - or (root / name.split(".")[0] / "__init__.py").exists() - for name in modules - if name - ) - - -class _GlobalReads(ast.NodeVisitor): - def __init__( - self, - scope: symtable.SymbolTable, - filename: str, - allowed: set[str], - bound: set[str], - violations: list[tuple[int, str]], - used: set[int], - ): - self.scope, self.filename, self.allowed, self.bound = ( - scope, - filename, - allowed, - bound, - ) - self.violations, self.used, self.hidden = violations, used, set() - - def visit_Name(self, node: ast.Name) -> None: - if isinstance(node.ctx, ast.Load): - try: - is_global = self.scope.lookup(node.id).is_global() - except KeyError: - # Deferred annotations are absent from Python's symbol table. - is_global = True - if ( - is_global - and node.id not in self.hidden - and node.id not in self.allowed - and (node.id not in dir(builtins) or node.id in self.bound) - ): - self.violations.append((node.lineno, node.id)) - - def visit_Import(self, node: ast.Import) -> None: - if _local_import(node, self.filename): - raise SandboxPackagingError( - f"{self.filename}:{node.lineno}: local imports are not supported" - ) - - visit_ImportFrom = visit_Import - - def child(self, node: ast.AST, name: str) -> _GlobalReads: - table = next( - ( - t - for t in self.scope.get_children() - if t.get_name() == name - and t.get_lineno() == node.lineno - and t.get_id() not in self.used - ), - None, - ) - if table is not None: - self.used.add(table.get_id()) - visitor = _GlobalReads( - table or self.scope, - self.filename, - self.allowed, - self.bound, - self.violations, - self.used, - ) - visitor.hidden = set(self.hidden) - return visitor - - def visit_FunctionDef(self, node: ast.FunctionDef | ast.AsyncFunctionDef) -> None: - args = [ - *node.args.posonlyargs, - *node.args.args, - *node.args.kwonlyargs, - node.args.vararg, - node.args.kwarg, - ] - parts = [ - *node.decorator_list, - *node.args.defaults, - *[d for d in node.args.kw_defaults if d], - *[a.annotation for a in args if a and a.annotation], - ] - if node.returns: - parts.append(node.returns) - for part in parts: - self.visit(part) - visitor = self.child(node, node.name) - for part in node.body: - visitor.visit(part) - - visit_AsyncFunctionDef = visit_FunctionDef - - def visit_Lambda(self, node: ast.Lambda) -> None: - for part in [*node.args.defaults, *[d for d in node.args.kw_defaults if d]]: - self.visit(part) - self.child(node, "lambda").visit(node.body) - - def _comprehension(self, node: Any, name: str, output: list[ast.AST]) -> None: - self.visit(node.generators[0].iter) - visitor = self.child(node, name) - for index, generator in enumerate(node.generators): - if index: - visitor.visit(generator.iter) - visitor.hidden.update( - n.id - for n in ast.walk(generator.target) - if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Store) - ) - for condition in generator.ifs: - visitor.visit(condition) - for part in output: - visitor.visit(part) - - def visit_ListComp(self, node: ast.ListComp) -> None: - self._comprehension(node, "listcomp", [node.elt]) - - def visit_SetComp(self, node: ast.SetComp) -> None: - self._comprehension(node, "setcomp", [node.elt]) - - def visit_GeneratorExp(self, node: ast.GeneratorExp) -> None: - self._comprehension(node, "genexpr", [node.elt]) - - def visit_DictComp(self, node: ast.DictComp) -> None: - self._comprehension(node, "dictcomp", [node.key, node.value]) - - def visit_ClassDef(self, node: ast.ClassDef) -> None: - for part in [ - *node.decorator_list, - *node.bases, - *(k.value for k in node.keywords), - ]: - self.visit(part) - visitor = self.child(node, node.name) - for part in node.body: - visitor.visit(part) - - -def transform(source: str, *, filename: str = "main.py") -> str: - """Extract a standalone script while rejecting omitted dependencies.""" - tree = _parse(source, filename) - _, func = _declaration(tree, filename) - args = [ - *func.args.posonlyargs, - *func.args.args, - *func.args.kwonlyargs, - func.args.vararg, - func.args.kwarg, - ] - annotations = [a.annotation for a in args if a and a.annotation] - if func.returns: - annotations.append(func.returns) - imports: dict[str, ast.Import | ast.ImportFrom] = {} - bindings: dict[str, str] = {} - for node in tree.body: - if isinstance(node, (ast.Import, ast.ImportFrom)): - for alias in node.names: - name = alias.asname or ( - alias.name.split(".")[0] - if isinstance(node, ast.Import) - else alias.name - ) - imports[name] = node - if isinstance(node, ast.Import) and alias.name in ( - "typing", - "typing_extensions", - ): - bindings[name] = alias.name - elif ( - isinstance(node, ast.ImportFrom) - and node.module in ("typing", "typing_extensions") - and alias.name in ("Literal", "Annotated") - ): - bindings[name] = alias.name - table = symtable.symtable(source, filename, "exec") - function_table = next( - t - for t in table.get_children() - if t.get_name() == func.name and t.get_lineno() == func.lineno - ) - bound = { - s.get_name() - for s in table.get_symbols() - if s.is_assigned() or s.is_imported() or s.is_namespace() - } - required = ( - set().union(*(_annotation_names(n, bindings) for n in annotations)) - if annotations - else set() - ) - classes = {n.name: n for n in tree.body if isinstance(n, ast.ClassDef)} - selected: set[str] = set() - while pending := (required & classes.keys()) - selected: - for name in pending: - selected.add(name) - reads: list[tuple[int, str]] = [] - _GlobalReads(table, filename, set(), bound, reads, set()).visit( - classes[name] - ) - required.update(dependency for _, dependency in reads) - for node in ast.walk(classes[name]): - if isinstance(node, ast.AnnAssign): - required.update(_annotation_names(node.annotation, bindings)) - allowed = selected | (required & imports.keys()) | {"Context"} - violations: list[tuple[int, str]] = [] - for annotation in annotations: - for name in _annotation_names(annotation, bindings): - if ( - name not in classes - and name not in imports - and (name not in dir(builtins) or name in bound) - ): - violations.append((annotation.lineno, name)) - visitor = _GlobalReads(function_table, filename, allowed, bound, violations, set()) - for statement in func.body: - visitor.visit(statement) - for default in [*func.args.defaults, *[d for d in func.args.kw_defaults if d]]: - for node in ast.walk(default): - if ( - isinstance(node, ast.Name) - and isinstance(node.ctx, ast.Load) - and (node.id not in dir(builtins) or node.id in bound) - ): - violations.append((node.lineno, node.id)) - for name in selected: - model_visitor = _GlobalReads( - table, filename, set(imports) | selected, bound, violations, set() - ) - model_visitor.visit(classes[name]) - for node in ast.walk(classes[name]): - if isinstance(node, ast.AnnAssign): - for dependency in _annotation_names(node.annotation, bindings): - if ( - dependency not in imports - and dependency not in selected - and (dependency not in dir(builtins) or dependency in bound) - ): - violations.append((node.lineno, dependency)) - if violations: - raise SandboxPackagingError( - "\n".join( - f"{filename}:{line}: '{name}' is defined outside {func.name} — import or define it inside the function (lazy import)" - for line, name in sorted(set(violations)) - ) - ) - future = any( - isinstance(n, ast.ImportFrom) - and n.module == "__future__" - and any(a.name == "annotations" for a in n.names) - for n in tree.body - ) - generated = ["from __future__ import annotations"] if future else [] - runtime_names = ["Context", "script"] - for name in sorted(required): - node = imports.get(name) - if ( - isinstance(node, ast.ImportFrom) - and node.module in ("mobilerun.sandbox", RUNTIME_MODULE) - and name not in ("cloud", "Context", "script") - ): - alias = next(a for a in node.names if (a.asname or a.name) == name) - runtime_names.append( - alias.name + (" as " + alias.asname if alias.asname else "") - ) - generated.append(f"from {RUNTIME_MODULE} import " + ", ".join(runtime_names)) - for node in tree.body: - if ( - not isinstance(node, (ast.Import, ast.ImportFrom)) - or isinstance(node, ast.ImportFrom) - and node.module in ("mobilerun.sandbox", RUNTIME_MODULE, "__future__") - ): - continue - aliases = [ - a - for a in node.names - if ( - a.asname - or (a.name.split(".")[0] if isinstance(node, ast.Import) else a.name) - ) - in required - ] - if not aliases: - continue - if _local_import(node, filename): - raise SandboxPackagingError( - f"{filename}:{node.lineno}: local imports are not supported" - ) - text = ", ".join( - a.name + (" as " + a.asname if a.asname else "") for a in aliases - ) - generated.append( - ( - "import " - if isinstance(node, ast.Import) - else f"from {node.module} import " - ) - + text - ) - lines = source.splitlines(keepends=True) - definitions = [ - "".join( - lines[ - min([n.lineno, *(d.lineno for d in n.decorator_list)]) - - 1 : n.end_lineno - ] - ).rstrip() - for n in tree.body - if isinstance(n, ast.ClassDef) and n.name in selected - ] - body = "".join(lines[func.lineno - 1 : func.end_lineno]).rstrip() - return ( - "\n".join(generated) - + "\n\n\n" - + "\n\n\n".join([*definitions, "@script\n" + body]) - + "\n" - ) - - -# Use the same loader and inspector as the runtime's `inspect` command. Run in -# its existing child process: never import the user's original module or call -# the function. Scheduled and file-backed routines need additional model checks. -_MODEL_INSPECTOR = f"""\ -import json, sys -from contextlib import redirect_stdout -from pydantic import ValidationError -from pydantic.json_schema import GenerateJsonSchema -from {RUNTIME_MODULE}.loader import load_script -from {RUNTIME_MODULE}._contract import inspect_entry -from {RUNTIME_MODULE}.schema import _walk - -class ProjectionSchema(GenerateJsonSchema): - def generate_inner(self, schema): - result = super().generate_inner(schema) - serializer = schema.get('serialization') or {{}} - if self.mode == 'serialization' and serializer.get('type') in ('any', 'function-plain', 'function-wrap'): - # Mark this occurrence, not the shared definition used by other fields. - return dict(result, **{{'x-mobilerun-dynamic-serializer': True}}) - return result - - def field_is_required(self, field, total): - if self.mode == 'serialization' and field['type'] in ('model-field', 'dataclass-field'): - # The runner's model_dump_json(by_alias=True) includes defaults and nulls. - return field.get('serialization_exclude_if') is None - return super().field_is_required(field, total) - - def model_fields_schema(self, schema): - result = super().model_fields_schema(schema) - if any(field.get('serialization_exclude') for field in schema['fields'].values()) or any( - field.get('alias', field['property_name']) not in result.get('properties', {{}}) - for field in schema.get('computed_fields', []) - ): - result['x-mobilerun-omittable-fields'] = True - return result - -with redirect_stdout(sys.stderr): - flags, path = sys.argv[1:-1], sys.argv[-1] - entry = load_script(path) - document = inspect_entry(entry) - if 'files' in flags: - document['validFilesOutput'] = entry.output_model is not None and not entry.allows_none - if 'file_webhook' in flags and document['validFilesOutput']: - raw = entry.output_model.model_json_schema(mode='serialization', schema_generator=ProjectionSchema) - document['projectionSchema'] = _walk(raw, raw.get('$defs', {{}}), (), '') - if 'scheduled' in flags: - try: - entry.input_model.model_validate_json('{{}}') - except ValidationError as exc: - properties = document['inputSchema'].get('properties', {{}}) - locations = (error['loc'] for error in exc.errors( - include_input=False, include_context=False, include_url=False)) - document['scheduleInputErrors'] = sorted({{ - loc[0] for loc in locations if loc and loc[0] in properties - }}) - else: - document['scheduleInputErrors'] = None -print(json.dumps(document)) -""" - - -def inspect_source( - source: str, - *, - scheduled: bool = False, - files: bool = False, - file_webhook: bool = False, -) -> JSON: - """Inspect trusted generated source in an isolated temporary directory.""" - files = files or file_webhook - try: - with tempfile.TemporaryDirectory() as directory: - path = Path(directory) / "script.py" - path.write_text(source, encoding="utf-8") - flags = [ - name - for name, enabled in ( - ("scheduled", scheduled), - ("files", files), - ("file_webhook", file_webhook), - ) - if enabled - ] - args = ( - ["-c", _MODEL_INSPECTOR, *flags] - if flags - else ["-m", RUNTIME_MODULE, "inspect"] - ) - result = subprocess.run( - [sys.executable, *args, str(path)], - capture_output=True, - text=True, - timeout=get_sandbox_settings().MOBILERUN_SANDBOX_INSPECTION_TIMEOUT, - check=False, - ) - if result.returncode: - raise SandboxPackagingError("Local sandbox inspection failed") - document = json.loads(result.stdout) - if ( - not isinstance(document, dict) - or document.get("ok") is not True - or not isinstance(document.get("inputSchema"), dict) - or not ( - document.get("outputSchema") is None - or isinstance(document.get("outputSchema"), dict) - ) - or "outputSchema" not in document - or (scheduled and "scheduleInputErrors" not in document) - or (files and not isinstance(document.get("validFilesOutput"), bool)) - ): - raise SandboxPackagingError( - "Local sandbox inspection returned an invalid document" - ) - if files and not document["validFilesOutput"]: - raise SandboxDeclarationError(FILES_RETURN_ERROR) - if file_webhook and not isinstance(document.get("projectionSchema"), dict): - raise SandboxPackagingError( - "Local sandbox inspection returned an invalid projection schema" - ) - if scheduled and (fields := document["scheduleInputErrors"]) is not None: - properties = document["inputSchema"].get("properties", {}) - if not isinstance(fields, list) or not all( - isinstance(field, str) and field in properties for field in fields - ): - raise SandboxPackagingError("Invalid scheduled input inspection result") - raise SandboxDeclarationError( - "Scheduled input must accept {}" - + (f"; failing fields: {', '.join(fields)}" if fields else "") - ) - return document - except ( - OSError, - UnicodeError, - subprocess.TimeoutExpired, - json.JSONDecodeError, - ): - raise SandboxPackagingError("Local sandbox inspection failed") from None - - -def _validate_file_output(output: JSON, path: str) -> None: - """Require the inspected result schema to guarantee a string at this path.""" - hint = f"files output field {path!r} must be a required, non-null string" - - def dereference(node: Any) -> JSON: - seen: set[str] = set() - while isinstance(node, dict): - if node.get("nullable") is True or {"anyOf", "oneOf"} & node.keys(): - break - if "$ref" not in node: - return node - ref = node["$ref"] - if not isinstance(ref, str) or not ref.startswith("#/") or ref in seen: - break - seen.add(ref) - node = output - for token in ref[2:].split("/"): - node = ( - node.get(token.replace("~1", "/").replace("~0", "~")) - if isinstance(node, dict) - else None - ) - raise SandboxDeclarationError(hint) - - node: Any = output - parts = path.split(".") - for offset, part in enumerate(parts): - node = dereference(node) - if node.get("type") == "object" and part in node.get("required", []): - node = node.get("properties", {}).get(part) - elif node.get("type") == "array" and part.isdecimal(): - try: - size = int(part) + 1 - except ValueError: - raise SandboxDeclarationError( - f"files output field {path!r} has an unsupported array index" - ) from None - minimum = node.get("minItems", 0) - if type(minimum) is not int or minimum < size: - parent = ".".join(parts[:offset]) - raise SandboxDeclarationError( - f"files output field {path!r} requires min_length={size} on {parent or 'the result array'}" - ) - node = node.get("items") - else: - raise SandboxDeclarationError(hint) - if dereference(node).get("type") != "string": - raise SandboxDeclarationError(hint) + return source_declaration(parse_source(source, str(path)), str(path))[0] def package(path: Path, *, source: str | None = None) -> Artifact: @@ -742,7 +44,7 @@ def package(path: Path, *, source: str | None = None) -> Artifact: source = path.read_text(encoding="utf-8") except (OSError, UnicodeError) as exc: raise SandboxPackagingError(f"Cannot read source: {path}") from exc - declaration = _declaration(_parse(source, str(path)), str(path))[0] + declaration = source_declaration(parse_source(source, str(path)), str(path))[0] generated = transform(source, filename=str(path)) scheduled = declaration.schedule is not None if declaration.files: @@ -753,7 +55,7 @@ def package(path: Path, *, source: str | None = None) -> Artifact: file_webhook=declaration.webhook is not None, ) for field_path in declaration.files.values(): - _validate_file_output(document["outputSchema"], field_path) + validate_file_output(document["outputSchema"], field_path) else: document = inspect_source(generated, scheduled=scheduled) digest = hashlib.sha256( diff --git a/mobilerun/sandbox/receipts.py b/mobilerun/sandbox/receipts.py index 995602bbb..44bbdde00 100644 --- a/mobilerun/sandbox/receipts.py +++ b/mobilerun/sandbox/receipts.py @@ -5,7 +5,7 @@ import os import sys import tempfile -from collections.abc import Iterator +from collections.abc import Iterator, Mapping from contextlib import contextmanager from dataclasses import dataclass, replace from pathlib import Path @@ -14,19 +14,16 @@ import httpx import yaml -from mobilerun.clients.local.login_store import resolve_cloud_api_key +from mobilerun.clients.local.login_store import LoginStore from mobilerun.config.settings import get_settings from mobilerun.utils.paths import local_store_path from .errors import SandboxDeploymentConflict, SandboxDeploymentError -from .models import JSON, OwnershipReceipt +from .helpers.flow_yaml import FlowDumper +from .models import JSON, CutoverState, OwnershipReceipt from .settings import SandboxSettings, get_sandbox_settings -def _windows_platform() -> bool: - return sys.platform == "win32" - - @dataclass(frozen=True) class Scope: """Cloud origin and API-key fingerprint; never the API key itself.""" @@ -42,7 +39,7 @@ def sha256_hex(value: str) -> str: def current_scope() -> Scope: """Resolve credentials exactly as the shared cloud client does.""" - key = resolve_cloud_api_key() + key = LoginStore.from_settings().resolve_api_key() if not key: raise SandboxDeploymentError("Sandbox credentials required") base = httpx.URL(str(get_settings().MOBILERUN_CLOUD_BASE_URL)) @@ -62,19 +59,6 @@ def stage_key(scope: Scope, name: str, digest: str, stage: str) -> str: ) -class _FlowDumper(yaml.SafeDumper): - pass - - -def _yaml_string(dumper: _FlowDumper, value: str) -> yaml.nodes.ScalarNode: - return dumper.represent_scalar( - "tag:yaml.org,2002:str", value, style='"' if value == "on" else None - ) - - -_FlowDumper.add_representer(str, _yaml_string) - - class ReceiptStore: """File-backed, scope-isolated ownership evidence for one deployment.""" @@ -203,7 +187,7 @@ def lock(self) -> Iterator[None]: except OSError: raise SandboxDeploymentError("Cannot open sandbox lock") from None try: - if _windows_platform(): + if sys.platform == "win32": import msvcrt handle.seek(0) @@ -268,9 +252,7 @@ def write_yaml(self, document: JSON) -> None: """Export the authored flow document, quoting YAML's ambiguous on key.""" self._write_atomic( self.yaml_path, - yaml.dump( - document, Dumper=_FlowDumper, sort_keys=False, allow_unicode=True - ), + yaml.dump(document, Dumper=FlowDumper, sort_keys=False, allow_unicode=True), ) def remove_yaml(self, *, cleanup_confirmed: bool) -> None: @@ -294,7 +276,7 @@ def pending_initial(receipt: OwnershipReceipt) -> JSON | None: return None -def pending_cutover(receipt: OwnershipReceipt) -> JSON | None: +def pending_cutover(receipt: OwnershipReceipt) -> CutoverState | None: """Return the unfinished redeploy cutover stage recorded in a receipt, if any.""" for entry in reversed(receipt.stages): value = json.loads(entry) @@ -304,7 +286,7 @@ def pending_cutover(receipt: OwnershipReceipt) -> JSON | None: def require_current_cutover_receipt( - state: JSON | None, receipt: OwnershipReceipt + state: CutoverState | None, receipt: OwnershipReceipt ) -> None: """Reject a cutover stage journaled without action payloads by an older version.""" if state is not None and "action_payloads" not in state: @@ -316,7 +298,7 @@ def require_current_cutover_receipt( def checkpoint( - store: ReceiptStore, receipt: OwnershipReceipt, state: JSON + store: ReceiptStore, receipt: OwnershipReceipt, state: Mapping[str, object] ) -> OwnershipReceipt: """Append a stage to the receipt journal and write it to the store.""" result = replace( diff --git a/mobilerun/skills/bundle.py b/mobilerun/skills/bundle.py index 0b54c0383..6031dfd3e 100644 --- a/mobilerun/skills/bundle.py +++ b/mobilerun/skills/bundle.py @@ -49,102 +49,94 @@ def skills_root() -> Path: ) -def skills_roots() -> list[Path]: - return [skills_root()] - - def list_skills() -> list[Skill]: + root = skills_root() result = [] seen = {} - for root in skills_roots(): - skill_files = sorted(root.rglob("SKILL.md")) - parents = {} - guides = sorted(root.rglob("GUIDE.md")) - references = sorted( - file - for file in root.rglob("*.md") - if file.parent.name == "references" - and file.name not in {"SKILL.md", "GUIDE.md"} - ) - for file in skill_files + guides + references: - if not file.is_file(): - continue - text = file.read_text(encoding="utf-8") - is_reference = file in references - name = file.parent.name if file.name == "SKILL.md" else "" - parent = None - parent_skill = None - if file.name != "SKILL.md": - parent_skill = next( - ( - parents[p] - for p in (file.parent, *file.parent.parents) - if p in parents - ), - None, - ) - if parent_skill is None: - continue - if is_reference and file.parent != parent_skill.path / "references": - continue - parent = parent_skill.name - if is_reference: - name = f"{parent}-{file.stem}" - lines = text.splitlines() - if file.name == "GUIDE.md" and ( - not lines - or lines[0].strip() != "---" - or not any(line.strip() == "---" for line in lines[1:]) - ): - continue - if lines and lines[0].strip() == "---": - for line in lines[1:]: - if line.strip() == "---": - break - if line.startswith("name:"): - name = line.partition(":")[2].strip().strip("\"'") or name - break - if not name: - continue - _names([name]) - if name in {"bundle", "single"}: - raise ValueError(f"reserved skill name: {name}") - if name in seen: - raise ValueError( - f"Duplicate skill name: {name} ({seen[name]}, {file.parent})" - ) - seen[name] = file.parent - skill = Skill( - name, + skill_files = sorted(root.rglob("SKILL.md")) + parents = {} + guides = sorted(root.rglob("GUIDE.md")) + references = sorted( + file + for file in root.rglob("*.md") + if file.parent.name == "references" + and file.name not in {"SKILL.md", "GUIDE.md"} + ) + for file in skill_files + guides + references: + if not file.is_file(): + continue + text = file.read_text(encoding="utf-8") + is_reference = file in references + name = file.parent.name if file.name == "SKILL.md" else "" + parent = None + parent_skill = None + if file.name != "SKILL.md": + parent_skill = next( ( - _reference_description(text, file, parent_skill) - if is_reference and parent_skill - else _description(text) + parents[p] + for p in (file.parent, *file.parent.parents) + if p in parents ), - file.parent, - root.name, - file.parent.relative_to(root), - parent, - file, + None, + ) + if parent_skill is None: + continue + if is_reference and file.parent != parent_skill.path / "references": + continue + parent = parent_skill.name + if is_reference: + name = f"{parent}-{file.stem}" + lines = text.splitlines() + if file.name == "GUIDE.md" and ( + not lines + or lines[0].strip() != "---" + or not any(line.strip() == "---" for line in lines[1:]) + ): + continue + if lines and lines[0].strip() == "---": + for line in lines[1:]: + if line.strip() == "---": + break + if line.startswith("name:"): + name = line.partition(":")[2].strip().strip("\"'") or name + break + if not name: + continue + _names([name]) + if name in {"bundle", "single"}: + raise ValueError(f"reserved skill name: {name}") + if name in seen: + raise ValueError( + f"Duplicate skill name: {name} ({seen[name]}, {file.parent})" ) - if file.name == "SKILL.md": - parents[file.parent] = skill - result.append(skill) + seen[name] = file.parent + skill = Skill( + name, + ( + _reference_description(text, file, parent_skill) + if is_reference and parent_skill + else _description(text) + ), + file.parent, + root.name, + file.parent.relative_to(root), + parent, + file, + ) + if file.name == "SKILL.md": + parents[file.parent] = skill + result.append(skill) return result def bundle_folders() -> dict[str, Path]: + root = skills_root() folders = {} - for root in skills_roots(): - for file in sorted(root.rglob("SKILL.md")): - relative = file.relative_to(root) - if len(relative.parts) < 2: - continue + for file in sorted(root.rglob("SKILL.md")): + relative = file.relative_to(root) + if len(relative.parts) >= 2: name = relative.parts[0] - folder = root / name - if name in folders and folders[name] != folder: - raise ValueError(f"Duplicate bundle folder: {name}") - folders[name] = folder + folders[name] = root / name return folders @@ -196,12 +188,11 @@ def installed( def _protect_bundle(target: Path, names: list[str]) -> None: - for root in skills_roots(): - root = root.resolve() - for name in names: - dest = (target / name).resolve() - if dest == root or dest in root.parents or root in dest.parents: - raise ValueError("Target overlaps the bundled skills") + root = skills_root().resolve() + for name in names: + dest = (target / name).resolve() + if dest == root or dest in root.parents or root in dest.parents: + raise ValueError("Target overlaps the bundled skills") def install( diff --git a/mobilerun/skills/cli/README.md b/mobilerun/skills/cli/README.md index e9c6b975a..59d015e43 100644 --- a/mobilerun/skills/cli/README.md +++ b/mobilerun/skills/cli/README.md @@ -19,13 +19,12 @@ Keep skill command presentation here; skill installation logic lives in `skills/ ## Files -- `__init__.py` — Exports `skills`. -- `common.py` — `options` — shared skill command options. -- `group.py` — `skills` — commands for installing bundled coding-agent skills. -- `install.py` — `install_command`. -- `list.py` — `list_command`. -- `show.py` — `show_command`. -- `uninstall.py` — `uninstall_command`. +| File | Purpose | +| --- | --- | +| `__init__.py`, `group.py` | Expose the skills command group. | +| `common.py` | Shared skill command options. | +| `install.py`, `uninstall.py` | Install or remove managed skills. | +| `list.py`, `show.py` | Discover skills and inspect their contents. | **Depends on / used by:** Uses `skills`, `config.settings` and `cli.base`; registered by the main CLI. diff --git a/mobilerun/utils/README.md b/mobilerun/utils/README.md index 6ad08cdd2..86e3648d0 100644 --- a/mobilerun/utils/README.md +++ b/mobilerun/utils/README.md @@ -1,34 +1,77 @@ # utils/ -Core's utilities. Feature packages keep their own utilities inside their folder. +Shared framework utilities. Feature packages keep their own utilities inside their folder. -Standalone helpers for coordinates, images, verification codes, timestamps and terminal checks. +Standalone helpers for images, verification codes, timestamps and terminal checks. -**What belongs here / what doesn't:** Helpers must not depend on Mobilerun domain packages, settings, devices or CLI behavior. +**What belongs here / what doesn't:** Helpers do not depend on framework core, settings, or CLI behavior. A few boundaries use shared value types or errors rather than creating parallel interfaces. ## Contents | Path | Purpose | | --- | --- | | `__init__.py` | Package marker | -| `coordinates.py`, `geometry.py`, `images.py` | Coordinates, bounds and image helpers | +| `images.py` | Image helpers | | `codes.py` | Verification code extraction and polling | +| [`credentials/`](credentials/README.md) | Replay masking and private atomic credential file writes | | `timestamps.py` | API timestamp formatting | | `terminal.py` | `can_prompt(output)`: the one check for whether a prompt drawn on a stream can be answered from stdin | -| `redaction.py` | `secret_scope` redacts sensitive log values; `mask_url` preserves HTTP(S) hosts and paths while dropping userinfo and fragments and masking query values. | +| `redaction.py` | `Redactor`, `redact`, and `secret_scope` mask sensitive text, JSON values, and logs. `mask_url` sanitizes HTTP(S) URLs for display. | +| `json/redaction.py` | Project safe JSON, masking sensitive keys and opaque values | +| `screen/` | Typed observation projection and safe fingerprint generation and matching | +| `billing/`, `checkout/`, `network/` | Billing retry, checkout presentation and scoped transport log controls | +| `tools/` | Task-local dispatch authorization and tool input masking | +| `webhooks/urls.py` | Validate and canonicalize HTTPS webhook destinations | | `paths.py`, `prompts.py` | Resolve package paths and load prompts. Legacy `config/prompts` paths can read `mobilerun_agents/assets/prompts` without importing the add-on. | -Device-facing helpers live in `clients/local/`. +Phone operations and native observations live in `mobilerun_core`. The +framework's [screen helpers](../core/screen/) format observations for display. -## Quick example +Cloud helpers live in [clients/cloud](../clients/cloud/README.md). + +## Redacting run data + +Create a `Redactor` per run. Register plain strings only at trusted +ingress with `remember_sensitive(values)` or `remember_codes(*codes)`. Do not +extract values from opaque `Secret` objects. Activate the instance with +`secret_scope(redactor=...)` to redact log records and use `redact(text)` for +text such as error messages. Outside a scope, `redact(text)` has no generic +text patterns and returns the text unchanged. ```python -from mobilerun.utils.coordinates import to_absolute +from mobilerun.utils.redaction import Redactor, redact, secret_scope -x, y = to_absolute(500, 500, 1080, 1920) -print(x, y) # 540 960 +redactor = Redactor() +with secret_scope(redactor=redactor): + redactor.remember_codes("482913") # Example runtime code + safe_error = redact("Could not enter 482 913") # "Could not enter ***" + safe_args = redactor.redact_json({"text": "code: 482913"}, whole_value=True) + # {"text": "***"} ``` -Cloud helpers live in [clients/cloud](../clients/cloud/README.md). +`redact_json` copies JSON and leaves keys intact; never put secrets in keys. +Use `whole_value=True` for action arguments that should not retain even the +nonsecret part of a matching value. Call `mark_sensitive()` when touching a +sensitive screen and check `sensitive_ui` before serializing UI evidence. +Registration alone does not mark the screen. `ScreenRecording` masks sensitive +UI data but stores screenshots as taken. Use `ActionRecording` to omit screenshots. + +`secret_scope(*values)` adds temporary masks without changing the surrounding +scope. Pass a fresh explicit redactor to start an independent run inside another +scope. Nested temporary scopes inherit existing masks and taint but don't change +their parent. Trusted readers and credential providers use +`remember_scoped_secrets(*values)` to register values in the current redactor and +all enclosing recording redactors without affecting later independent runs. + +Recorders open a scope that keeps surrounding masks visible. Framework mailbox +and phone-number readers register returned verification codes in the current +scope and all active recording scopes in that task context, including across +temporary scopes. History registers every contiguous 4–8-digit match and every +window of adjacent 2–4-digit groups totaling 4–8 digits, separated by spaces, +tabs, or hyphens. Recordings mask both compact and as-written forms. This can +also mask unrelated numbers. SMS polling still returns only the first +contiguous match; it does not return grouped-only codes. Mailbox polling +still returns the code supplied by the service. Unrelated tasks do not +learn those codes. **Depends on / used by:** Uses standard and third-party libraries; used across the framework. diff --git a/mobilerun/utils/__init__.py b/mobilerun/utils/__init__.py index 27724edda..6b7c9e1a4 100644 --- a/mobilerun/utils/__init__.py +++ b/mobilerun/utils/__init__.py @@ -1 +1 @@ -"""Shared helpers: coordinates, geometry, images.""" +"""Shared helpers for coordinates, images, redaction and other framework concerns.""" diff --git a/mobilerun/utils/billing/README.md b/mobilerun/utils/billing/README.md new file mode 100644 index 000000000..b50051a1f --- /dev/null +++ b/mobilerun/utils/billing/README.md @@ -0,0 +1,15 @@ +# Billing utilities + +`retry.py` provides `with_billing_retry()` for a single operation whose billing +check runs before all side effects. It retries once, after explicit or terminal +consent, and returns the result and effective mode. + +```python +result, mode = await with_billing_retry(operation, "included") +``` + +| File | Purpose | +| --- | --- | +| `retry.py` | Retry once after approval and return the effective billing mode. | + +See [cloud billing policy](../../clients/cloud/README.md#billing). diff --git a/mobilerun/utils/billing/retry.py b/mobilerun/utils/billing/retry.py new file mode 100644 index 000000000..8b4cbaa2f --- /dev/null +++ b/mobilerun/utils/billing/retry.py @@ -0,0 +1,54 @@ +"""Retry a rejected commerce preflight once after consent.""" + +import sys +from collections.abc import Awaitable, Callable +from typing import TypeVar + +from mobilerun.errors.cloud import BillingRequired +from mobilerun.models.billing import Billing +from mobilerun.utils.terminal import can_prompt + +R = TypeVar("R") + + +async def _confirm_billing(error: BillingRequired) -> bool: + from prompt_toolkit import PromptSession + from prompt_toolkit.output import create_output + + session: PromptSession[str] = PromptSession(output=create_output(stdout=sys.stderr)) + try: + answer = await session.prompt_async(f"{error.confirmation} [y/N] ") + except EOFError: + return False + return answer.strip().casefold() in {"y", "yes"} + + +async def with_billing_retry( + operation: Callable[[Billing], Awaitable[R]], + billing: Billing | str, + *, + yes: bool = False, + prompt: Callable[[BillingRequired], Awaitable[bool]] = _confirm_billing, + is_interactive: Callable[[], bool] | None = None, +) -> tuple[R, Billing]: + """Retry one operation whose billing checks run before any side effects. + + Pass a callback accepting the mode for this attempt. Return the result and + the effective mode. Without consent or a terminal on stdin and stderr, + re-raise BillingRequired. + """ + + mode = Billing(billing) + try: + return await operation(mode), mode + except BillingRequired as error: + if mode is Billing.PAID or error.given is not mode or error.needed is mode: + raise + needed = error.needed + if yes is not True: + interactive = ( + can_prompt(sys.stderr) if is_interactive is None else is_interactive() + ) + if not interactive or not await prompt(error): + raise + return await operation(needed), needed diff --git a/mobilerun/utils/checkout/README.md b/mobilerun/utils/checkout/README.md new file mode 100644 index 000000000..93c920213 --- /dev/null +++ b/mobilerun/utils/checkout/README.md @@ -0,0 +1,18 @@ +# Checkout presentation + +Explicitly opt in to printing a checkout URL or opening it in a browser. +`presentation.py` builds a callback; it does not purchase, poll, or cancel +anything. Pass `checkout_callback("print", None)` to a caller that accepts an +`on_checkout` callback to print the URL (which may be sensitive). + +```python +from mobilerun.utils.checkout.presentation import checkout_callback + +callback = checkout_callback("error", None) # Never print or launch a browser. +``` + +| File | Purpose | +| --- | --- | +| `presentation.py` | Choose how a purchase exposes its checkout URL. | + +See [cloud account checkout](../../clients/cloud/README.md) for payment behavior. diff --git a/mobilerun/utils/checkout/__init__.py b/mobilerun/utils/checkout/__init__.py new file mode 100644 index 000000000..2422a4273 --- /dev/null +++ b/mobilerun/utils/checkout/__init__.py @@ -0,0 +1 @@ +"""Checkout presentation utilities.""" diff --git a/mobilerun/clients/cloud/checkout.py b/mobilerun/utils/checkout/presentation.py similarity index 91% rename from mobilerun/clients/cloud/checkout.py rename to mobilerun/utils/checkout/presentation.py index 4ee26ac60..fc86c0ffb 100644 --- a/mobilerun/clients/cloud/checkout.py +++ b/mobilerun/utils/checkout/presentation.py @@ -5,8 +5,7 @@ import webbrowser from typing import Literal -from mobilerun.clients.cloud.payments import CheckoutCallback -from mobilerun.models.checkout import Checkout +from mobilerun.models.checkout import Checkout, CheckoutCallback CheckoutMode = Literal["error", "print", "browser"] diff --git a/mobilerun/utils/codes.py b/mobilerun/utils/codes.py index cf7a081dd..3909056e4 100644 --- a/mobilerun/utils/codes.py +++ b/mobilerun/utils/codes.py @@ -6,7 +6,8 @@ from collections.abc import Awaitable, Callable, Iterator, Mapping _CODE = re.compile(r"(? str | None: @@ -14,6 +15,22 @@ def extract_code(text: str | None) -> str | None: return match.group() if match else None +def _code_candidates(text: str) -> Iterator[str]: + """Yield all contiguous and grouped readings for conservative masking.""" + yield from _CODE.findall(text) + for run in _NUMBER_RUN.finditer(text): + groups = [m.span() for m in _DIGIT_GROUP.finditer(text, *run.span())] + for i, (start, _) in enumerate(groups): + total = 0 + for begin, end in groups[i : i + 4]: + width = end - begin + total += width + if not 2 <= width <= 4 or total > 8: + break + if begin != start: + yield text[start:end] + + def verification_read_codes(role: str, action: str, result: object) -> Iterator[str]: """Extract candidates from declared verification reads, never from sends.""" if action == "wait_for_code" and isinstance(result, str): @@ -31,11 +48,7 @@ def verification_read_codes(role: str, action: str, result: object) -> Iterator[ return for item in result if isinstance(result, (list, tuple)) else (result,): if isinstance(item, str): - yield from ( - m.group() - for pattern in (_CODE, _SPLIT_CODE) - for m in pattern.finditer(item) - ) + yield from _code_candidates(item) continue get = ( item.get @@ -45,14 +58,10 @@ def verification_read_codes(role: str, action: str, result: object) -> Iterator[ code = get("code") if isinstance(code, str) and code: yield code - for field in ("body", "text", "subject", "html"): + for field in ("body", "text", "subject", "html", "preview"): text = get(field) if isinstance(text, str): - yield from ( - m.group() - for pattern in (_CODE, _SPLIT_CODE) - for m in pattern.finditer(text) - ) + yield from _code_candidates(text) async def wait_for_code( diff --git a/mobilerun/utils/coordinates.py b/mobilerun/utils/coordinates.py deleted file mode 100644 index fe6d602bc..000000000 --- a/mobilerun/utils/coordinates.py +++ /dev/null @@ -1,25 +0,0 @@ -"""Coordinate conversion utilities for normalized [0-1000] coordinates.""" - -NORMALIZED_MAX = 1000 # Shared coordinate protocol contract. - - -def to_absolute(x: int, y: int, width: int, height: int) -> tuple[int, int]: - """Convert [0-1000] normalized to absolute pixels.""" - if width is None or height is None: - raise ValueError("Screen dimensions not available. Call get_state() first.") - return int(x * width / NORMALIZED_MAX), int(y * height / NORMALIZED_MAX) - - -def to_normalized(x: int, y: int, width: int, height: int) -> tuple[int, int]: - """Convert absolute pixels to [0-1000] normalized.""" - if width is None or height is None: - raise ValueError("Screen dimensions not available. Call get_state() first.") - return int(x * NORMALIZED_MAX / width), int(y * NORMALIZED_MAX / height) - - -def bounds_to_normalized(bounds_str: str, width: int, height: int) -> str: - """Convert 'left,top,right,bottom' bounds string to normalized.""" - left, top, right, bottom = map(int, bounds_str.split(",")) - n_left, n_top = to_normalized(left, top, width, height) - n_right, n_bottom = to_normalized(right, bottom, width, height) - return f"{n_left},{n_top},{n_right},{n_bottom}" diff --git a/mobilerun/utils/credentials/README.md b/mobilerun/utils/credentials/README.md new file mode 100644 index 000000000..4e38ae4a7 --- /dev/null +++ b/mobilerun/utils/credentials/README.md @@ -0,0 +1,21 @@ +# Credential utilities + +Credential masking and private file helpers, independent of providers and devices. + +```python +from mobilerun.utils.credentials.masking import CredentialMasks + +with CredentialMasks.scope() as masks: + # Register only at trusted ingress, then mask a caller-owned snapshot. + masks.register("login", "fixture-password") + state = {"phone_state": {}, "nodes": [{"text": "fixture-password"}]} + masks.snapshot(state) # Replaces the text with "[secret:login]". +``` + +| File | Purpose | +| --- | --- | +| `__init__.py` | Package marker | +| `masking.py` | Task-local credential masks for normalized snapshots | +| `private.py` | Atomic credential file replacement with owner-only permissions | + +See [credential providers](../../core/credentials/README.md) and [redaction](../README.md#redacting-run-data). diff --git a/mobilerun/utils/credentials/__init__.py b/mobilerun/utils/credentials/__init__.py new file mode 100644 index 000000000..194a084bf --- /dev/null +++ b/mobilerun/utils/credentials/__init__.py @@ -0,0 +1 @@ +"""Shared credential masking and private file utilities.""" diff --git a/mobilerun/core/credentials/masking.py b/mobilerun/utils/credentials/masking.py similarity index 60% rename from mobilerun/core/credentials/masking.py rename to mobilerun/utils/credentials/masking.py index 5005b0f75..52f379883 100644 --- a/mobilerun/core/credentials/masking.py +++ b/mobilerun/utils/credentials/masking.py @@ -1,69 +1,84 @@ """Per-replay masking of credential values in normalized screen observations.""" +from __future__ import annotations + import re from bisect import bisect_right from collections.abc import Callable, Iterable, Iterator from contextlib import contextmanager from contextvars import ContextVar -from functools import partial -from typing import Any - - -def _matches(pattern: re.Pattern[str], text: str) -> Iterator[tuple[int, int]]: - return (match.span() for match in pattern.finditer(text)) - - -def _bounded(pattern: str, sample: str) -> str: - first, last = sample[0], sample[-1] - if re.match(r"\w", first): - pattern = (r"(? str: - """Merge overlapping edits; the longest original match supplies the marker.""" - parts: list[str] = [] - end = 0 - best = 0 - for start, stop, length, marker in sorted(spans): - if start >= end: - parts.extend((text[end:start], marker)) - best = length - elif length > best: - parts[-1] = marker - best = length - end = max(end, stop) - return "".join([*parts, text[end:]]) - - -def _card_spans(text: str) -> Iterator[tuple[int, int]]: - """Find group-aligned, Luhn-valid 13–19 digit numbers.""" - for run in re.finditer(r"[0-9]+(?:[\s-]+[0-9]+)*", text): - groups = list(re.finditer(r"[0-9]+", run.group())) - for i, first in enumerate(groups): - digits = "" - for last in groups[i : i + 19]: - digits += last.group() - if len(digits) > 19: - break - if len(digits) >= 13: - terms = [ - int(c) * (1 + index % 2) - for index, c in enumerate(reversed(digits)) - ] - if sum(n - 9 if n > 9 else n for n in terms) % 10 == 0: - yield run.start() + first.start(), run.start() + last.end() - - class CredentialMasks: """Mask only the current replay; never change host-owned observations.""" - def __init__(self) -> None: + current: ClassVar[ContextVar[CredentialMasks | None]] = ContextVar( + "credential_masks", default=None + ) + + @classmethod + @contextmanager + def scope(cls, *, redactor: Redactor | None = None) -> Iterator[Self]: + """Keep replay masks scoped; optionally keep values on the run's redactor.""" + masks = cls(redactor=redactor) + token = cls.current.set(masks) + try: + yield masks + finally: + masks._patterns.clear() + cls.current.reset(token) + + @staticmethod + def _bounded(pattern: str, sample: str) -> str: + first, last = sample[0], sample[-1] + if re.match(r"\w", first): + pattern = (r"(? str: + """Merge overlapping edits; the longest original match supplies the marker.""" + parts: list[str] = [] + end = 0 + best = 0 + for start, stop, length, marker in sorted(spans): + if start >= end: + parts.extend((text[end:start], marker)) + best = length + elif length > best: + parts[-1] = marker + best = length + end = max(end, stop) + return "".join([*parts, text[end:]]) + + @staticmethod + def _card_spans(text: str) -> Iterator[tuple[int, int]]: + """Find group-aligned, Luhn-valid 13–19 digit numbers.""" + for run in re.finditer(r"[0-9]+(?:[\s-]+[0-9]+)*", text): + groups = list(re.finditer(r"[0-9]+", run.group())) + for i, first in enumerate(groups): + digits = "" + for last in groups[i : i + 19]: + digits += last.group() + if len(digits) > 19: + break + if len(digits) >= 13: + terms = [ + int(c) * (1 + index % 2) + for index, c in enumerate(reversed(digits)) + ] + if sum(n - 9 if n > 9 else n for n in terms) % 10 == 0: + yield run.start() + first.start(), run.start() + last.end() + + def __init__(self, *, redactor: Redactor | None = None) -> None: + self._redactor = redactor self._patterns: dict[tuple[str, str], re.Pattern[str]] = {} self.mask_card_numbers = False @@ -72,6 +87,8 @@ def active(self) -> bool: return bool(self._patterns) or self.mask_card_numbers def register(self, name: str, value: str) -> None: + if self._redactor is not None: + self._redactor.remember_sensitive(value) if not value.strip() or (name, value) in self._patterns: return digits = re.sub(r"[\s-]", "", value) @@ -82,7 +99,7 @@ def register(self, name: str, value: str) -> None: pattern = "".join(r"\s+" if t.isspace() else re.escape(t) for t in tokens) # UI providers often add whitespace around date separators. pattern = re.sub(r"(?<=\d)/(?=\d)", lambda _: r"\s*/\s*", pattern) - pattern = _bounded(pattern, value.strip()) + pattern = self._bounded(pattern, value.strip()) self._patterns[name, value] = re.compile(pattern, re.IGNORECASE) def _rules( @@ -91,9 +108,15 @@ def _rules( for (name, _), pattern in sorted( self._patterns.items(), key=lambda item: -len(item[0][1]) ): - yield f"[secret:{name}]", partial(_matches, pattern) + + def spans( + text: str, pattern: re.Pattern[str] = pattern + ) -> Iterator[tuple[int, int]]: + return (match.span() for match in pattern.finditer(text)) + + yield f"[secret:{name}]", spans if self.mask_card_numbers: - yield "[secret:card_number]", _card_spans + yield "[secret:card_number]", self._card_spans def snapshot(self, state: dict[str, Any]) -> dict[str, Any]: """Mask individual spans, including values spanning adjacent nodes.""" @@ -115,7 +138,7 @@ def snapshot(self, state: dict[str, Any]) -> dict[str, Any]: edits[i].extend( (m.start(), m.end(), length, marker) for m in re.finditer( - _bounded(re.escape(fragment), fragment), + self._bounded(re.escape(fragment), fragment), texts[i], re.IGNORECASE, ) @@ -154,21 +177,5 @@ def snapshot(self, state: dict[str, Any]) -> dict[str, Any]: for data in [state["phone_state"], *state["nodes"]]: for key, value in data.items(): if edits_for_field := pending.get((id(data), key)): - data[key] = _replace(value, edits_for_field) + data[key] = self._replace(value, edits_for_field) return state - - -current_masks: ContextVar[CredentialMasks | None] = ContextVar( - "credential_masks", default=None -) - - -@contextmanager -def masking_scope() -> Iterator[CredentialMasks]: - masks = CredentialMasks() - token = current_masks.set(masks) - try: - yield masks - finally: - masks._patterns.clear() - current_masks.reset(token) diff --git a/mobilerun/utils/credentials/private.py b/mobilerun/utils/credentials/private.py new file mode 100644 index 000000000..37ffaf9d5 --- /dev/null +++ b/mobilerun/utils/credentials/private.py @@ -0,0 +1,103 @@ +"""Atomic owner-only writes for local credential files.""" + +import os +import sys +import tempfile +import uuid +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path +from typing import TextIO + + +@contextmanager +def private_credential_writer(destination: Path) -> Iterator[TextIO]: + """Replace a credential file only after its private temporary file is complete.""" + missing = [] + parent = destination.parent + while not parent.exists(): + missing.append(parent) + parent = parent.parent + for directory in reversed(missing): + directory.mkdir(mode=0o700, exist_ok=True) + if os.name == "nt": + fd, path = _windows_private_temp(destination.parent) + else: + fd, path = tempfile.mkstemp(prefix=".credentials-", dir=destination.parent) + try: + with os.fdopen(fd, "w", encoding="utf-8") as stream: + if sys.platform != "win32" and os.name != "nt": + os.fchmod(stream.fileno(), 0o600) + yield stream + os.replace(path, destination) + finally: + if os.path.exists(path): + os.unlink(path) + + +def _windows_private_temp(parent: Path) -> tuple[int, str]: + """Create a new file with a protected owner-only DACL, never an inherited ACL.""" + if sys.platform != "win32": + raise NotImplementedError("Private DACLs require Windows") + + import ctypes as c + import msvcrt + from ctypes import wintypes as w + + class SecurityAttributes(c.Structure): + _fields_ = [("length", w.DWORD), ("descriptor", w.LPVOID), ("inherit", w.BOOL)] + + kernel = c.WinDLL("kernel32", use_last_error=True) + security = c.WinDLL("advapi32", use_last_error=True) + convert = security.ConvertStringSecurityDescriptorToSecurityDescriptorW + convert.argtypes = [w.LPCWSTR, w.DWORD, c.POINTER(w.LPVOID), c.POINTER(w.DWORD)] + convert.restype = w.BOOL + create = kernel.CreateFileW + create.argtypes = [ + w.LPCWSTR, + w.DWORD, + w.DWORD, + c.POINTER(SecurityAttributes), + w.DWORD, + w.DWORD, + w.HANDLE, + ] + create.restype = w.HANDLE + volume = kernel.GetVolumeInformationByHandleW + volume.argtypes = [ + w.HANDLE, + w.LPWSTR, + w.DWORD, + c.POINTER(w.DWORD), + c.POINTER(w.DWORD), + c.POINTER(w.DWORD), + w.LPWSTR, + w.DWORD, + ] + volume.restype = w.BOOL + descriptor = w.LPVOID() + path = str(parent / f".credentials-{uuid.uuid4().hex}") + # P = protected (no inherited ACEs); FA = full access; OW = owner rights. + if not convert("D:P(A;;FA;;;OW)", 1, c.byref(descriptor), None): + raise c.WinError(c.get_last_error()) + try: + attributes = SecurityAttributes(c.sizeof(SecurityAttributes), descriptor, False) + # GENERIC_READ | GENERIC_WRITE, no sharing, CREATE_NEW, FILE_ATTRIBUTE_NORMAL. + handle = create(path, 0xC0000000, 0, c.byref(attributes), 1, 0x80, None) + if handle == w.HANDLE(-1).value: + raise c.WinError(c.get_last_error()) + finally: + kernel.LocalFree(descriptor) + try: + flags = w.DWORD() + if not volume(handle, None, 0, None, None, c.byref(flags), None, 0): + raise c.WinError(c.get_last_error()) + if not flags.value & 0x8: # FILE_PERSISTENT_ACLS (e.g. not FAT/exFAT) + raise PermissionError( + "Credentials require a volume supporting private DACLs" + ) + return msvcrt.open_osfhandle(handle, os.O_WRONLY | os.O_BINARY), path + except BaseException: + kernel.CloseHandle(w.HANDLE(handle)) + os.unlink(path) + raise diff --git a/mobilerun/utils/geometry.py b/mobilerun/utils/geometry.py deleted file mode 100644 index f73250e56..000000000 --- a/mobilerun/utils/geometry.py +++ /dev/null @@ -1,79 +0,0 @@ -"""Geometry utilities for UI element bounds and tap point calculation.""" - -from typing import List, Optional, Tuple - -Bounds = Tuple[int, int, int, int] - - -def rects_overlap(a: Bounds, b: Bounds) -> bool: - """Check if two rectangles overlap.""" - return not (a[2] <= b[0] or b[2] <= a[0] or a[3] <= b[1] or b[3] <= a[1]) - - -def find_uncovered_point( - bounds: Bounds, blockers: List[Bounds] -) -> Optional[Tuple[int, int]]: - """Return the center of the largest remaining rectangle, including narrow gaps.""" - regions = [bounds] if bounds[0] < bounds[2] and bounds[1] < bounds[3] else [] - for blocker in blockers: - remaining = [] - for left, top, right, bottom in regions: - bl = max(left, blocker[0]) - bt = max(top, blocker[1]) - br = min(right, blocker[2]) - bb = min(bottom, blocker[3]) - if bl >= br or bt >= bb: - remaining.append((left, top, right, bottom)) - continue - for region in ( - (left, top, right, bt), - (left, bb, right, bottom), - (left, bt, bl, bb), - (br, bt, right, bb), - ): - if region[0] < region[2] and region[1] < region[3]: - remaining.append(region) - regions = remaining - if not regions: - return None - left, top, right, bottom = max(regions, key=lambda r: (r[2] - r[0]) * (r[3] - r[1])) - return (left + right) // 2, (top + bottom) // 2 - - -def find_clear_point( - bounds: Bounds, - blockers: List[Bounds], - depth: int = 0, -) -> Optional[Tuple[int, int]]: - """Find a clear point in bounds using quadrant subdivision.""" - left, top, right, bottom = bounds - cx, cy = (left + right) // 2, (top + bottom) // 2 - - blocked = any(b[0] <= cx < b[2] and b[1] <= cy < b[3] for b in blockers) - - if not blocked: - return cx, cy - - if depth > 4 or (right - left) * (bottom - top) < 100: - return None - - quadrants = [ - (left, top, cx, cy), - (cx, top, right, cy), - (left, cy, cx, bottom), - (cx, cy, right, bottom), - ] - - best_point = None - best_area = 0 - - for q in quadrants: - q_area = (q[2] - q[0]) * (q[3] - q[1]) - if q_area <= 0: - continue - point = find_clear_point(q, blockers, depth + 1) - if point and q_area > best_area: - best_point = point - best_area = q_area - - return best_point diff --git a/mobilerun/utils/images.py b/mobilerun/utils/images.py index 299bdfac4..0fbb9357e 100644 --- a/mobilerun/utils/images.py +++ b/mobilerun/utils/images.py @@ -75,34 +75,6 @@ def fit_dimensions_to_max_side( return max(1, round(width * scale)), max(1, round(height * scale)) -def resize_image_to_max_side(image: bytes, max_side: int) -> bytes: - """Resize image bytes to the same coordinate space exposed to vision agents.""" - width, height = image_dimensions(image) - target_width, target_height = fit_dimensions_to_max_side(width, height, max_side) - if (target_width, target_height) == (width, height): - return image - - with Image.open(BytesIO(image)) as source: - resized = source.convert("RGBA").resize( - (target_width, target_height), - Image.Resampling.LANCZOS, - ) - output = BytesIO() - resized.save(output, format="PNG") - return output.getvalue() - - -def resize_image_to_max_side_with_grid( - image: bytes, max_side: int, divisions: int = 10 -) -> bytes: - """Resize image and overlay a model-only coordinate grid.""" - width, height = image_dimensions(image) - target_width, target_height = fit_dimensions_to_max_side(width, height, max_side) - return resize_image_to_dimensions_with_grid( - image, target_width, target_height, divisions=divisions - ) - - def resize_image_to_dimensions_with_grid( image: bytes, target_width: int, target_height: int, divisions: int = 10 ) -> bytes: diff --git a/mobilerun/utils/json/redaction.py b/mobilerun/utils/json/redaction.py new file mode 100644 index 000000000..ad45c8671 --- /dev/null +++ b/mobilerun/utils/json/redaction.py @@ -0,0 +1,28 @@ +"""Redacted JSON projection for recording artifacts.""" + +from math import isfinite + +from pydantic import JsonValue + +from mobilerun.utils.redaction import Redactor, redact + + +def safe_json(value: object, redactor: Redactor) -> JsonValue: + """Project JSON values without exposing opaque objects or sensitive keys.""" + if isinstance(value, dict): + return { + redact(redactor.redact(key)): safe_json(item, redactor) + for key, item in value.items() + if isinstance(key, str) + } + if isinstance(value, (list, tuple)): + return [safe_json(item, redactor) for item in value] + if value is None: + return None + if isinstance(value, (str, int, float, bool)): + if isinstance(value, float) and not isfinite(value): + return "***" + if redact(str(value)) != str(value): + return "***" + return redactor.redact_json(value, whole_value=True) + return "***" diff --git a/mobilerun/utils/network/README.md b/mobilerun/utils/network/README.md new file mode 100644 index 000000000..c73c06204 --- /dev/null +++ b/mobilerun/utils/network/README.md @@ -0,0 +1,15 @@ +# Network utilities + +`quiet.py` provides `quiet_transport_logs()` for operations that handle private +URLs or headers. The context leaves diagnostics in concurrent tasks alone. + +```python +with quiet_transport_logs(): + response = await client.get(url) +``` + +| File | Purpose | +| --- | --- | +| `quiet.py` | Scope transport log filtering to the current task. | + +See [signed transfers and OAuth](../../clients/cloud/README.md). diff --git a/mobilerun/utils/network/quiet.py b/mobilerun/utils/network/quiet.py new file mode 100644 index 000000000..835986642 --- /dev/null +++ b/mobilerun/utils/network/quiet.py @@ -0,0 +1,33 @@ +"""Suppress private HTTP and SDK diagnostics within the current task.""" + +import logging +from collections.abc import Iterator +from contextlib import contextmanager +from contextvars import ContextVar + +_quiet = ContextVar("mobilerun_quiet_transport", default=False) + + +def _allow_transport_log(record: logging.LogRecord) -> bool: + return not _quiet.get() + + +@contextmanager +def quiet_transport_logs(*extra_loggers: str) -> Iterator[None]: + """Silence this task, including redirect URLs and httpcore header traces.""" + for name in ( + "httpx", + "httpcore.http11", + "httpcore.http2", + "httpcore.connection", + "httpcore.proxy", + "httpcore.socks", + *extra_loggers, + ): + # Leave the idempotent filter installed for concurrent transfers. + logging.getLogger(name).addFilter(_allow_transport_log) + token = _quiet.set(True) + try: + yield + finally: + _quiet.reset(token) diff --git a/mobilerun/utils/paths.py b/mobilerun/utils/paths.py index 3cd3ef77e..a3f43d625 100644 --- a/mobilerun/utils/paths.py +++ b/mobilerun/utils/paths.py @@ -7,9 +7,7 @@ import json import os -import sys from dataclasses import asdict, dataclass -from importlib.util import find_spec from pathlib import Path from typing import Literal, Union @@ -57,33 +55,6 @@ def get_project_root() -> Path: """ return Path(__file__).resolve().parents[1] - @staticmethod - def bundled_asset(path: Path) -> Path | None: - """Find a legacy prompt without importing the optional add-on.""" - if path.parts[:2] != ("config", "prompts") or ".." in path.parts: - return None - asset = Path("assets", *path.parts[1:]) - candidate = PathResolver.get_project_root() / asset - if candidate.exists(): - return candidate - try: - spec = find_spec("mobilerun_agents") - except ValueError: - addon = sys.modules.get("mobilerun_agents") - if addon is not None and getattr(addon, "__spec__", None) is None: - return None - raise - except ModuleNotFoundError as error: - if error.name != "mobilerun_agents": - raise - return None - if spec and spec.submodule_search_locations: - for location in spec.submodule_search_locations: - candidate = Path(location) / asset - if candidate.exists(): - return candidate - return None - @staticmethod def resolve( path: Union[str, Path], @@ -155,11 +126,6 @@ def resolve( if package_path.exists(): return package_path - # Support legacy bundled paths without overriding a user file in CWD. - legacy_asset = PathResolver.bundled_asset(path) - if legacy_asset is not None: - return legacy_asset - # Not found in either location if must_exist: raise FileNotFoundError( diff --git a/mobilerun/utils/redaction.py b/mobilerun/utils/redaction.py index 9a9adf352..c7d32899f 100644 --- a/mobilerun/utils/redaction.py +++ b/mobilerun/utils/redaction.py @@ -1,4 +1,4 @@ -"""Task-local redaction of sensitive values in logs.""" +"""Run-local masking for text, JSON values and log records.""" import json import logging @@ -8,15 +8,14 @@ from contextlib import contextmanager from contextvars import ContextVar from dataclasses import dataclass -from typing import Any +from typing import Any, cast from urllib.parse import quote, quote_plus, urlsplit, urlunsplit -from weakref import WeakSet from pydantic import JsonValue # A period immediately following a digit only joins another digit, not a new # sentence. Possessive runs consume each span of spaces/digits without backtracking. -_NUMERIC_RUN = re.compile(r"\d++(?:(?: ++(?:[./-] *+)?|[/-] *+|\.)\d++)*") +_NUMERIC_RUN = re.compile(r"\d++(?:(?:[ \t]++(?:[./-][ \t]*+)?|[/-][ \t]*+|\.)\d++)*") @dataclass(frozen=True, repr=False) @@ -25,11 +24,6 @@ class _Variants: digits: frozenset[str] -_active_secrets: ContextVar[_Variants | None] = ContextVar( - "mobilerun_input_secrets", default=None -) - - def _variants(values: tuple[str, ...], parent: _Variants | None) -> _Variants | None: literals = set(parent.literals) if parent else set() numbers = set(parent.digits) if parent else set() @@ -45,7 +39,7 @@ def _variants(values: tuple[str, ...], parent: _Variants | None) -> _Variants | except UnicodeEncodeError: pass # Lone surrogates have no UTF-8 URL encoding. digits = "".join(c for c in value if c.isdecimal()) - if len(digits) >= 4 and all(c.isdecimal() or c in " ./-" for c in value): + if len(digits) >= 4 and all(c.isdecimal() or c in " \t./-" for c in value): numbers.add(digits) if _NUMERIC_RUN.fullmatch(value): # Numeric literals use group boundaries too, e.g. 12/27 in a date. @@ -92,10 +86,6 @@ def _numeric_spans(text: str, numbers: frozenset[str]) -> Iterator[tuple[int, in yield start, ends[stop] -def _redact_secrets(text: str) -> str: - return _redact_variants(text, _active_secrets.get()) - - def _redact_variants(text: str, variants: _Variants | None) -> str: if not variants: return text @@ -116,82 +106,145 @@ def _redact_variants(text: str, variants: _Variants | None) -> str: return "".join([*parts, text[end:]]) -class KnownCodes: - """Device-local verification codes retained only in memory.""" +class Redactor: + """Remember sensitive values and UI taint for one run or device. + + Use a fresh instance for an independent run. Values come from trusted + ingress, not from opaque secret holders. Activate it with ``secret_scope`` + to apply the same redaction to module-level ``redact`` and logging. + """ def __init__(self) -> None: self._variants: _Variants | None = None - self.sensitive_values: set[str] = set() - self.observed_secrets: set[str] = set() + self._sensitive_ui = False - def remember(self, *codes: str) -> None: - self._variants = _variants(codes, self._variants) - if self._variants is not None: - self._enable_log_masking() + def __bool__(self) -> bool: + """Whether this redactor has any values registered for masking.""" + return self._variants is not None - def remember_sensitive(self, values: Iterable[str]) -> None: - self.sensitive_values.update(filter(None, values)) - if self.sensitive_values: - self._enable_log_masking() + @property + def sensitive_ui(self) -> bool: + """Whether this run or device has touched sensitive UI.""" + return self._sensitive_ui - def _enable_log_masking(self) -> None: - _known_codes.add(self) - _install_secret_factory() - _install_extra_redaction() + def mark_sensitive(self) -> None: + """Mark the UI as sensitive for the rest of this redactor's lifetime.""" + self._sensitive_ui = True - def redact(self, text: str) -> str: - return _redact_variants(text, self._variants) + def remember_codes(self, *codes: str) -> None: + """Remember runtime verification codes, including grouped digit forms.""" + self.remember_sensitive(codes) - def redact_sensitive_text(self, text: str, *, include_observed: bool = True) -> str: - values = ( - self.sensitive_values | self.observed_secrets - if include_observed - else self.sensitive_values - ) - for value in sorted(values, key=len, reverse=True): - text = re.sub(rf"(? str: - text = _redact_secrets(text) - for codes in tuple(_known_codes): - text = codes.redact(codes.redact_sensitive_text(text, include_observed=False)) - return text + def remember_sensitive(self, values: Iterable[str] | str) -> None: + """Remember plain text received at a trusted secret boundary.""" + values = (values,) if isinstance(values, str) else tuple(values) + if not all(isinstance(value, str) for value in values): + raise TypeError("Redaction values must be strings") + self._variants = _variants(values, self._variants) + def redact(self, text: str) -> str: + """Replace matching spans with ``***`` in text, including error messages.""" + return _redact_variants(text, self._variants) -def mask_step_args( - args: dict[str, JsonValue], *, contains_code: Callable[[str], bool] | None = None -) -> dict[str, JsonValue]: - """Mask active secrets and device-known codes throughout a JSON argument tree.""" - - def mask_dict(values: dict[str, JsonValue]) -> dict[str, JsonValue]: - return { - ( - "***" - if contains_code is not None and contains_code(key) - else _redact_secrets(key) - ): mask(value) - for key, value in values.items() - } + def redact_json(self, value: JsonValue, *, whole_value: bool = False) -> JsonValue: + """Copy a JSON tree with masked values, leaving dictionary keys intact. + + Set ``whole_value`` to replace an entire matching scalar with ``***`` + (e.g. recorded action arguments). Matching non-string scalars always + become ``***``. Do not use sensitive text as a dictionary key. + """ + return _mask_json(value, self.redact, whole_value=whole_value) + + +def _mask_json( + value: JsonValue, + redact_text: Callable[[str], str], + *, + whole_value: bool, + mask_keys: bool = False, + contains_code: Callable[[str], bool] | None = None, +) -> JsonValue: + def mask_key(key: str) -> str: + if not mask_keys: + return key + if contains_code is not None and contains_code(key): + return "***" + return redact_text(key) def mask(value: JsonValue) -> JsonValue: if isinstance(value, dict): - return mask_dict(value) + return {mask_key(key): mask(item) for key, item in value.items()} if isinstance(value, list): return [mask(item) for item in value] if value is not None: text = str(value) - if _redact_secrets(text) != text or ( - contains_code is not None and contains_code(text) - ): - return "***" + masked = redact_text(text) + if masked != text or (contains_code is not None and contains_code(text)): + return "***" if whole_value or not isinstance(value, str) else masked return value - return mask_dict(args) + return mask(value) + + +@dataclass(repr=False) +class _SecretScope: + redactor: Redactor + parent: "_SecretScope | None" + recording: bool + inherits_masks: bool + active: bool = True + + +_active_secrets: ContextVar[_SecretScope | None] = ContextVar( + "mobilerun_input_secrets", default=None +) + + +def _scoped_redactors(*, recording_ingress: bool = False) -> Iterator[Redactor]: + scope = _active_secrets.get() + seen: set[Redactor] = set() + while scope is not None: + if scope.active: + if ( + not recording_ingress or not seen or scope.recording + ) and scope.redactor not in seen: + seen.add(scope.redactor) + yield scope.redactor + if not recording_ingress and not scope.inherits_masks: + break + scope = scope.parent + + +def redact(text: str) -> str: + """Mask text using the current redaction scope, or return it unchanged.""" + variants: _Variants | None = None + for redactor in _scoped_redactors(): + if (other := redactor._variants) is not None: + variants = ( + other + if variants is None + else _Variants( + variants.literals | other.literals, variants.digits | other.digits + ) + ) + return _redact_variants(text, variants) + + +def remember_scoped_secrets(*values: str) -> None: + """Register trusted secret values in the current scope and enclosing recorders.""" + if values: + for redactor in _scoped_redactors(recording_ingress=True): + redactor.remember_sensitive(values) + + +def mask_step_args( + args: dict[str, JsonValue], *, contains_code: Callable[[str], bool] | None = None +) -> dict[str, JsonValue]: + """Mask scoped secrets and caller-supplied matches in a JSON argument tree.""" + safe = _mask_json( + args, redact, whole_value=True, mask_keys=True, contains_code=contains_code + ) + return cast(dict[str, JsonValue], safe) # A dict remains a dict. def is_secure_ui_node(node: dict[str, JsonValue]) -> bool: @@ -222,9 +275,12 @@ def is_secure_ui_node(node: dict[str, JsonValue]) -> bool: def mask_secure_ui( - ui: dict[str, JsonValue], *, retain_targeting: bool = False + ui: dict[str, JsonValue], + *, + retain_targeting: bool = False, + raw_state: JsonValue = None, ) -> dict[str, JsonValue]: - """Remove secure values and their copies; optionally keep live targets.""" + """Mask secure values and copies; inspect raw state without returning it.""" protected = False values: set[str] = set() targeting = ( @@ -263,6 +319,7 @@ def collect(value: JsonValue) -> None: elements = remove(ui.get("elements")) remove(ui.get("phone_state")) + remove(raw_state) if not protected: return ui # Both summaries are independently rendered and may repeat a password. @@ -286,18 +343,18 @@ def _install_secret_factory() -> None: def factory(*args: Any, **kwargs: Any) -> logging.LogRecord: record = previous(*args, **kwargs) - if _active_secrets.get() or _known_codes: - record.msg = _redact_log(record.getMessage()) + if any(_scoped_redactors()): + record.msg = redact(record.getMessage()) record.args = () if record.exc_info: - record.exc_text = _redact_log( + record.exc_text = redact( "".join(traceback.format_exception(*record.exc_info)) ) record.exc_info = None elif record.exc_text: - record.exc_text = _redact_log(record.exc_text) + record.exc_text = redact(record.exc_text) if record.stack_info: - record.stack_info = _redact_log(record.stack_info) + record.stack_info = redact(record.stack_info) return record setattr(factory, "_mobilerun_secret_redaction", True) # noqa: B010 @@ -325,16 +382,16 @@ def make_record( record = previous( self, name, level, fn, lno, msg, args, exc_info, func, extra, sinfo ) - if extra and (_active_secrets.get() or _known_codes): + if extra and any(_scoped_redactors()): for key in extra: value = record.__dict__[key] rendered = str(value) - redacted = _redact_log(rendered) + redacted = redact(rendered) if rendered != redacted: record.__dict__[key] = redacted elif not isinstance(value, str): representation = repr(value) - redacted_repr = _redact_log(representation) + redacted_repr = redact(representation) if representation != redacted_repr: record.__dict__[key] = redacted_repr return record @@ -344,18 +401,42 @@ def make_record( @contextmanager -def secret_scope(*values: str) -> Iterator[None]: - """Redact values in this task; use asyncio.to_thread for blocking work. +def secret_scope( + *values: str, redactor: Redactor | None = None, recording: bool = False +) -> Iterator[Redactor]: + """Activate a redactor for this context and restore the prior scope on exit. + + Pass a fresh redactor to start an independent run, even inside another + scope. Without one, a new redactor inherits the active scope's masks and + taint. Positional values are temporary: when supplied alongside an + explicit redactor they are added to a copy, not to that redactor. - Bare run_in_executor does not propagate context variables. If it must be - used, submit contextvars.copy_context().run with the callable instead. + A recording scope keeps enclosing masks visible and receives secrets from + ``remember_scoped_secrets`` even inside a nested scope. + + ``asyncio.to_thread`` propagates this context; bare ``run_in_executor`` + does not. Do not share an instance across independent runs. """ _install_secret_factory() _install_extra_redaction() - token = _active_secrets.set(_variants(values, _active_secrets.get())) + active = redactor + if active is None or values: + parent = active if active is not None else next(_scoped_redactors(), None) + active = Redactor() + if parent is not None: + active._variants = parent._variants + active._sensitive_ui = parent.sensitive_ui + if values: + active.remember_sensitive(values) + scope = _SecretScope( + active, _active_secrets.get(), recording, recording or redactor is None + ) + token = _active_secrets.set(scope) try: - yield + yield active finally: + if recording: + scope.active = False _active_secrets.reset(token) diff --git a/mobilerun/utils/screen_fingerprint.py b/mobilerun/utils/screen/fingerprint.py similarity index 62% rename from mobilerun/utils/screen_fingerprint.py rename to mobilerun/utils/screen/fingerprint.py index 871fcf8d9..5df49b303 100644 --- a/mobilerun/utils/screen_fingerprint.py +++ b/mobilerun/utils/screen/fingerprint.py @@ -1,8 +1,14 @@ -"""Pure screen normalization and comparison shared by recording and replay.""" +"""Build, validate, and compare structural screen fingerprints.""" -from collections.abc import Iterator, Mapping +from collections.abc import Callable, Iterator, Mapping +from typing import cast + +from mobilerun_core import Observation +from pydantic import JsonValue from mobilerun.models.recording import Fingerprint +from mobilerun.utils.redaction import Redactor, mask_secure_ui, redact +from mobilerun.utils.screen.observation import observation_ui def _first_string(data: Mapping[str, object], *keys: str) -> str | None: @@ -76,3 +82,32 @@ def fingerprint_matches( union = left | right score = len(left & right) / len(union) if union else 1.0 return score >= threshold + + +def observation_fingerprint( + observation: Observation, + *, + redactor: Redactor | None = None, + include_scope: bool = True, +) -> Fingerprint | None: + """Build a native structural guard; by default also mask task-scoped secrets.""" + if not observation.tree_present or (redactor is not None and redactor.sensitive_ui): + return None + ui = observation_ui(observation) + if mask_secure_ui(ui, raw_state=cast(JsonValue, observation.raw_state)) is not ui: + return None + return unmasked_fingerprint( + screen_fingerprint(ui), + lambda value: (include_scope and redact(value) != value) + or (redactor is not None and redactor.redact(value) != value), + ) + + +def unmasked_fingerprint( + fingerprint: Fingerprint, is_masked: Callable[[str], bool] +) -> Fingerprint | None: + """Keep only nonempty fingerprints whose identifiers pass the masking check.""" + identifiers = (fingerprint.app, fingerprint.activity, *fingerprint.elements) + if not any(identifiers) or any(value and is_masked(value) for value in identifiers): + return None + return fingerprint diff --git a/mobilerun/utils/screen/labels.py b/mobilerun/utils/screen/labels.py new file mode 100644 index 000000000..3e89a771e --- /dev/null +++ b/mobilerun/utils/screen/labels.py @@ -0,0 +1,24 @@ +"""Label selection shared by XCTest pruning and prompt projection.""" + +from mobilerun_core import Element + + +def element_label(node: Element, *, legacy_ios: bool) -> str: + """Choose a prompt label using the presentation rules for the native tree.""" + if legacy_ios: + return ( + node.label + or node.content_description + or node.resource_id + or node.placeholder + or "" + ) + return ( + node.text + or node.content_description + or node.label + or node.resource_id + or node.placeholder + or node.class_name + or "" + ) diff --git a/mobilerun/utils/screen/observation.py b/mobilerun/utils/screen/observation.py new file mode 100644 index 000000000..e507f6e0c --- /dev/null +++ b/mobilerun/utils/screen/observation.py @@ -0,0 +1,39 @@ +"""Project native observations into recording UI data.""" + +from mobilerun_core import Observation +from pydantic import JsonValue + + +def observation_ui(observation: Observation) -> dict[str, JsonValue]: + """Project typed state only: raw transport payloads may repeat secure values.""" + phone = observation.phone_state + phone_state: dict[str, JsonValue] = { + "packageName": (phone.package_name if phone else None), + "activityName": (phone.activity_name if phone else None), + "currentApp": observation.focused_app, + "keyboardVisible": (phone.keyboard_visible if phone else None), + "editable": (phone.editable if phone else None), + } + nodes: list[JsonValue] = [ + { + "className": node.class_name, + "resourceId": node.resource_id, + "packageName": node.package_name, + "text": node.text, + "label": node.label, + "value": node.value, + "hint": node.hint, + "placeholder": node.placeholder, + "contentDescription": node.content_description, + "bounds": list(node.bounds) if node.bounds else None, + "isFocused": node.focused, + "isEditable": node.editable, + "isPassword": node.password, + } + for node in observation.elements or () + ] + return { + "phone_state": phone_state, + "elements": nodes if observation.tree_present else None, + "focused_text": observation.focused_text, + } diff --git a/mobilerun/utils/tools/dispatch.py b/mobilerun/utils/tools/dispatch.py new file mode 100644 index 000000000..6e3fe5868 --- /dev/null +++ b/mobilerun/utils/tools/dispatch.py @@ -0,0 +1,26 @@ +"""Task-local authorization for value-free tool dispatch metadata.""" + +from collections.abc import Callable, Iterator +from contextlib import contextmanager +from contextvars import ContextVar + +from mobilerun.models.tool_call import ToolCallInfo + +_guards: ContextVar[tuple[Callable[[ToolCallInfo], None], ...]] = ContextVar( + "tool_guards", default=() +) + + +@contextmanager +def tool_dispatch_guard(predicate: Callable[[ToolCallInfo], None]) -> Iterator[None]: + """Run a value-free, task-local authorization check before tool dispatch.""" + token = _guards.set((*_guards.get(), predicate)) + try: + yield + finally: + _guards.reset(token) + + +def authorize_tool(info: ToolCallInfo) -> None: + for predicate in _guards.get(): + predicate(info) diff --git a/mobilerun/utils/tools/redaction.py b/mobilerun/utils/tools/redaction.py new file mode 100644 index 000000000..ec984d715 --- /dev/null +++ b/mobilerun/utils/tools/redaction.py @@ -0,0 +1,45 @@ +"""Temporarily redact values supplied to sensitive tool parameters.""" + +from collections.abc import Iterator, Mapping +from contextlib import AbstractContextManager, nullcontext +from dataclasses import fields, is_dataclass +from enum import Enum + +from pydantic import BaseModel + +from mobilerun.utils.redaction import secret_scope + + +def _iter_sensitive_values(value: object) -> Iterator[str]: + """Yield scalar strings from nested values, including mapping keys.""" + if isinstance(value, Enum): + yield from _iter_sensitive_values(value.value) + elif isinstance(value, BaseModel): + yield from _iter_sensitive_values(value.model_dump()) + elif is_dataclass(value) and not isinstance(value, type): + for item in fields(value): + yield from _iter_sensitive_values(getattr(value, item.name)) + elif isinstance(value, Mapping): + for key, item in value.items(): + yield from _iter_sensitive_values(key) + yield from _iter_sensitive_values(item) + elif isinstance(value, (list, tuple, set, frozenset)): + for item in value: + yield from _iter_sensitive_values(item) + elif value is not None: + yield str(value) + + +def tool_secret_scope( + arguments: Mapping[str, object], sensitive_parameters: frozenset[str] +) -> AbstractContextManager[object]: + if not sensitive_parameters: + return nullcontext() + return secret_scope( + *( + value + for key in sensitive_parameters + if key in arguments + for value in _iter_sensitive_values(arguments[key]) + ) + ) diff --git a/mobilerun/utils/webhooks/urls.py b/mobilerun/utils/webhooks/urls.py new file mode 100644 index 000000000..e082e9d0c --- /dev/null +++ b/mobilerun/utils/webhooks/urls.py @@ -0,0 +1,54 @@ +"""Validate and canonicalize HTTPS webhook destinations without exposing them.""" + +from pydantic import HttpUrl + +from mobilerun.errors.cloud import CloudValidationError + +_WEBHOOK_URL_MAX_LENGTH = 2048 + + +def _validate_webhook_url_length(value: str) -> None: + if len(value) > _WEBHOOK_URL_MAX_LENGTH: + raise CloudValidationError( + f"Webhook URL exceeds {_WEBHOOK_URL_MAX_LENGTH} characters." + ) + + +def validate_webhook_url(value: str) -> str: + """Return the canonical HTTPS registration URL or raise a value-safe error.""" + if not isinstance(value, str): + raise CloudValidationError("Webhook URL must be a string.") + _validate_webhook_url_length(value) + if any( + c.isspace() or ord(c) < 32 or 127 <= ord(c) <= 159 or c == "\\" for c in value + ): + raise CloudValidationError( + "Remove whitespace, control characters and backslashes from the URL." + ) + if not value.lower().startswith("https://"): + raise CloudValidationError("Webhook URL must start with https://.") + parsed = None + if value[8:9] not in ("", "/", "?", "#"): + try: + parsed = HttpUrl(value) + except ValueError: + pass # Do not chain the parser error: it contains the caller's URL. + if parsed is None: + raise CloudValidationError( + "Webhook URL needs a valid hostname and port (if specified)." + ) + if parsed.username is not None or parsed.password is not None: + raise CloudValidationError( + "Remove the username or password from the webhook URL." + ) + if parsed.fragment is not None: + raise CloudValidationError("Remove the fragment (#…) from the webhook URL.") + # webhooks-api's normalizeUrl removes trailing slashes only from the path. + base, separator, query = str(parsed).partition("?") + if parsed.path and parsed.path != "/": + base = base.rstrip("/") + if not parsed.path.rstrip("/"): + base += "/" + canonical = base + separator + query + _validate_webhook_url_length(canonical) + return canonical diff --git a/mobilerun/version.py b/mobilerun/version.py index 30b0c87ed..72937de34 100644 --- a/mobilerun/version.py +++ b/mobilerun/version.py @@ -3,3 +3,7 @@ from importlib.metadata import version __version__ = version("mobilerun") + +# Contract version for add-ons (CLI plugins, operators, macro handoff). +# Bumped on every breaking change to what an add-on may import or implement. +PLUGIN_API_VERSION = 1 diff --git a/pyproject.toml b/pyproject.toml index d1da44a87..c18b582cb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,12 +1,11 @@ [project] name = "mobilerun" -version = "0.7.4" +version = "0.9.0" description = "A framework for controlling mobile devices through LLM agents" authors = [{ name = "Niels Schmidt", email = "niels@droidrun.ai" }] dependencies = [ - "async_adbutils", "pydantic>=2.11.10", - "pydantic-settings>=2.16.0,<3", + "pydantic-settings>=2.16.0", "platformdirs>=4", "Jinja2>=3.1.6", "prompt-toolkit>=3", @@ -17,11 +16,11 @@ dependencies = [ "click>=8.1", "PyYAML>=6.0", "filelock>=4.2.1", - "tomlkit>=0.13,<1", + "tomlkit>=0.13", "requests>=2.0", "aiofiles>=25.1.0", - "mobilerun-sdk>=6.3.1,<7", - "mobilerun-core-local[cloud]>=0.6.3", + "mobilerun-sdk==6.4.0", + "mobilerun-core[local]==2.0.0", # Security floors also protect installations from the published wheel. "anyio>=4.14.2", "certifi>=2026.10.19", @@ -59,7 +58,7 @@ Documentation = "https://docs.mobilerun.ai/" [project.optional-dependencies] sandbox = [ "mobilerun-functions[device]==0.1.0", - "jsonschema>=4,<5", + "jsonschema>=4", ] dev = [ "black==26.10.1", @@ -120,80 +119,26 @@ module = [ "mobilerun.cli.base.prompts", "mobilerun.cli.base.render", "mobilerun.cli.credentials.group", - "mobilerun.cli.devices.action", - "mobilerun.cli.devices.action.extensions", - "mobilerun.cli.devices.action.list", "mobilerun.cli.devices.app", - "mobilerun.cli.devices.app.install", - "mobilerun.cli.devices.app.list", - "mobilerun.cli.devices.app.open", - "mobilerun.cli.devices.app.start", - "mobilerun.cli.devices.app.stop", - "mobilerun.cli.devices.app.uninstall", - "mobilerun.cli.devices.base.default", - "mobilerun.cli.devices.base.pickers", - "mobilerun.cli.devices.cloud", - "mobilerun.cli.devices.cloud.reboot", - "mobilerun.cli.devices.cloud.rename", - "mobilerun.cli.devices.cloud.status", - "mobilerun.cli.devices.cloud.stop", - "mobilerun.cli.devices.cloud.terminate", "mobilerun.cli.devices.file", - "mobilerun.cli.devices.file.list", - "mobilerun.cli.devices.file.pull", - "mobilerun.cli.devices.file.push", - "mobilerun.cli.devices.file.rm", "mobilerun.cli.devices.input", - "mobilerun.cli.devices.input.long_press", - "mobilerun.cli.devices.input.press", - "mobilerun.cli.devices.input.swipe", - "mobilerun.cli.devices.input.tap", - "mobilerun.cli.devices.input.type", - "mobilerun.cli.devices.ping", "mobilerun.cli.devices.screen", - "mobilerun.cli.devices.screen.screenshot", - "mobilerun.cli.devices.screen.ui", "mobilerun.cli.devices.settings", - "mobilerun.cli.devices.settings.language.get", - "mobilerun.cli.devices.settings.language.set", - "mobilerun.cli.devices.settings.location.get", - "mobilerun.cli.devices.settings.location.reset", - "mobilerun.cli.devices.settings.location.set", - "mobilerun.cli.devices.settings.timezone.get", - "mobilerun.cli.devices.settings.timezone.set", - "mobilerun.cli.doctor", - "mobilerun.cli.proxy.group", - "mobilerun.clients.cloud.apps", - "mobilerun.clients.cloud.devices", "mobilerun.clients.cloud.errors", "mobilerun.clients.cloud.mailboxes", "mobilerun.clients.cloud.numbers", "mobilerun.clients.cloud.payments", "mobilerun.clients.cloud.proxies", "mobilerun.clients.cloud.tasks", - "mobilerun.clients.portal.http", - "mobilerun.clients.portal.releases", "mobilerun.config.loader", "mobilerun.config.settings", "mobilerun.config.user_config", "mobilerun.core.credentials.cloud", "mobilerun.core.credentials.file", - "mobilerun.core.devices.android", - "mobilerun.core.devices.base", - "mobilerun.core.devices.cloud", - "mobilerun.core.devices.components.cloud_lifecycle", - "mobilerun.core.devices.components.raw", - "mobilerun.core.devices.ios", - "mobilerun.core.devices.pool", - "mobilerun.core.devices.remote", - "mobilerun.core.extensions.actions", - "mobilerun.core.extensions.base", "mobilerun.core.mailbox.cloud", "mobilerun.core.phone_number.cloud", - "mobilerun.core.state.filters.detailed_filter", "mobilerun.diagnostics.versions", "mobilerun.errors.base", - "mobilerun.macro.cli.replay", "mobilerun.mcp.settings", "mobilerun.mcp.utils", "mobilerun.sandbox._runtime", diff --git a/scripts/reinstall.sh b/scripts/reinstall.sh new file mode 100755 index 000000000..20b18af8c --- /dev/null +++ b/scripts/reinstall.sh @@ -0,0 +1,56 @@ +#!/usr/bin/env bash +# Reinstall mobilerun with a local mobilerun-core checkout into a dev venv. +# +# scripts/reinstall.sh # .venv, core from ../mobilerun-core +# scripts/reinstall.sh .venv ~/code/mobilerun-core +# +# Core is installed as a normal package built from the working tree, including +# uncommitted changes (your core checkout stays untouched). It overrides the +# mobilerun-core version pin in pyproject.toml, so a local 2.x core works. +# mobilerun is installed editable with the sandbox + dev extras. +set -euo pipefail + +cd "$(dirname "$0")/.." +venv="${1:-.venv}" +core="${2:-../mobilerun-core}" + +command -v uv >/dev/null || { echo "uv not found: brew install uv" >&2; exit 1; } +[ -f "$core/pyproject.toml" ] || { echo "core checkout not found: $core" >&2; exit 1; } +core="$(cd "$core" && pwd)" + +if [ ! -x "$venv/bin/python" ]; then + echo "creating $venv (Python 3.13)" + uv venv --python 3.13 "$venv" +fi +py="$venv/bin/python" + +if [ -f .gitmodules ] && [ -z "$(ls -A skills 2>/dev/null)" ]; then + echo "initialising submodules" + git submodule update --init +fi + +echo "uninstalling mobilerun + mobilerun-core" +uv pip uninstall --python "$py" mobilerun mobilerun-core 2>/dev/null || true + +branch="$(git -C "$core" branch --show-current 2>/dev/null || echo '?')" +commit="$(git -C "$core" log -1 --format='%h %s' 2>/dev/null || echo '?')" +dirty="$(git -C "$core" status --short 2>/dev/null | wc -l | tr -d ' ')" +echo "installing core from $core [$branch @ $commit, $dirty uncommitted files]" + +# Point every mobilerun-core requirement at the local checkout, keeping the [local] extra. +override="$(mktemp)" +trap 'rm -f "$override"' EXIT +echo "mobilerun-core[local] @ file://$core" >"$override" + +# Fresh build of the core working tree (no stale uv build cache) + editable mobilerun. +uv pip install --python "$py" --override "$override" \ + --reinstall-package mobilerun-core --refresh-package mobilerun-core --no-cache \ + -e ".[sandbox,dev]" + +"$py" - <<'PY' +import importlib.metadata as md +import mobilerun, mobilerun_core +print("mobilerun ->", mobilerun.__file__) +print("mobilerun_core ->", mobilerun_core.__file__, md.version("mobilerun-core")) +PY +echo "done. In VS Code: 'Python: Select Interpreter' -> $venv/bin/python" diff --git a/skills b/skills index f0056fe2d..d3ccb3004 160000 --- a/skills +++ b/skills @@ -1 +1 @@ -Subproject commit f0056fe2dfab0a18707e3eb66f9691b2dd859fec +Subproject commit d3ccb3004bdfe94c85432e88add8ee31eef6c3bf diff --git a/tests/conftest.py b/tests/conftest.py index 411f2feaf..f15d21985 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -3,6 +3,7 @@ import os import tempfile from pathlib import Path +from typing import Never import platformdirs import pytest @@ -157,17 +158,29 @@ def isolate_user_configuration(tmp_path, monkeypatch, request): @pytest.fixture(autouse=True) -def isolate_device_discovery(monkeypatch, request): - """Never enumerate real devices during unit tests.""" +def isolate_device_discovery( + monkeypatch: pytest.MonkeyPatch, request: pytest.FixtureRequest +) -> None: + """Require explicit fakes for unit tests that probe real device seams.""" if request.node.get_closest_marker("smoke"): return from unittest.mock import AsyncMock - from mobilerun.clients.portal import discovery + from mobilerun_core import AsyncMobilerun, LocalDevices - monkeypatch.setattr(discovery.adb, "list", AsyncMock(return_value=[])) + monkeypatch.setattr(AsyncMobilerun, "list_devices", AsyncMock(return_value=[])) monkeypatch.setattr( - discovery, - "discover_ios_device", - AsyncMock(side_effect=ValueError("No iOS device found")), + LocalDevices, "list_android_devices", AsyncMock(return_value=[]) ) + monkeypatch.setattr( + LocalDevices, + "discover_ios", + AsyncMock(side_effect=RuntimeError("No iOS device found")), + ) + + async def block_discovery(*args: object, **kwargs: object) -> Never: + pytest.fail("unit test reached real device discovery: fake it") + + monkeypatch.setattr(AsyncMobilerun, "list_cloud_devices", block_discovery) + monkeypatch.setattr(LocalDevices, "diagnose_android", block_discovery) + monkeypatch.setattr(LocalDevices, "ping_portal", block_discovery) diff --git a/tests/demos/README.md b/tests/demos/README.md index f5bde7cdc..9b17f7d41 100644 --- a/tests/demos/README.md +++ b/tests/demos/README.md @@ -4,29 +4,41 @@ Examples for exploring Mobilerun from a source checkout. Run commands from the r ## Start here -From the repository root, with a local Android emulator and Portal running: +From the repository root, no device required: ```bash -python -m tests.demos.macro_demo --serial emulator-5554 +python -m tests.demos.macro_demo --fake ``` -Record and replay a short sequence without AI or cloud charges. For a cloud vault credential on the same device, run `python -m tests.demos.vault_demo` (cloud account required). To create a cloud phone and run tasks, use `python -m tests.demos.task_demo`; **phone, proxy and tasks can cost money**. +The demo records a short Settings sequence, builds a versioned `settings-demo` macro, and replays it. Use `--device ID` for a connected Android device, or omit both flags to use `ANDROID_SERIAL`, the saved device, or the interactive picker. Without a configured target in a noninteractive terminal, it runs offline. It makes no LLM calls. + +For a cloud vault credential on a local device, use `vault_demo --live` (cloud account required). To provision a temporary cloud phone and run tasks, use `task_demo --live`; **phone, proxy and tasks can cost money**. ## Demos -Run these from a source checkout with `python -m tests.demos.NAME`; demos are not included in the built wheel. Cloud demos require authentication and may change resources. Inspect their `--help` before running. +Run from a source checkout with `python -m tests.demos.NAME`. Use `--fake` for the offline path and `--help` for options. Except for macro target selection, running without flags stays offline. Real-device or service demos require `--live`; sandbox deployment requires `--yes`. Cloud demos require authentication and may change resources. | Module | What it does | Cost | | --- | --- | --- | | [intro_demo](intro_demo.py) | Introduction to device APIs | Cloud and LLM use can cost money | | [task_demo](task_demo.py) | Temporary cloud phone, tasks and typed output | Phone, proxy and tasks cost money | | [app_demo](app_demo.py) | Installs an APK on local and cloud devices and runs tasks | Cloud and LLM use can cost money | -| [macro_demo](macro_demo.py) | Records and replays local Android actions | No cloud or LLM charges | +| [macro_demo](macro_demo.py) | Records Android actions, builds a versioned macro, and replays it | `--fake` is offline; a running cloud phone can cost money | +| [easy_macro_demo](easy_macro_demo.py) | Smallest macro example: records a Settings macro, resets the phone, and replays it. Needs a device: `python tests/demos/easy_macro_demo.py [DEVICE]` | No LLM; a running cloud phone can cost money | | [vault_demo](vault_demo.py) | Saves, uses and deletes a demo vault credential | Cloud account required; local device has no service cost | -| [phone_demo](phone_demo.py) | Rents a number and waits for an SMS code | Number and optional cloud phone can cost money | -| [mailbox_demo](mailbox_demo.py) | Creates a mailbox and waits for a code | Mailbox can cost money | -| [proxy_demo](proxy_demo.py) | Inspects or switches an existing phone's proxy | Proxy can cost money | +| [phone_demo](phone_demo.py) | Rents or reuses a number, optionally attaches it to a temporary cloud phone, and waits for an SMS code | Number and optional cloud phone can cost money | +| [mailbox_demo](mailbox_demo.py) | Creates a mailbox and waits for an email code without a phone | Mailbox can cost money | +| [proxy_demo](proxy_demo.py) | Switches the proxy on a borrowed cloud phone | Buying proxy capacity with `--country` can cost money | +| [webhook_static_demo](webhook_static_demo.py) | Deploys a device-free sandbox endpoint that returns a static webhook result | Deploying and firing can cost money | +| [atc_demo](atc_demo.py) | Packages a routine that captures recent ATC events; `--fake` only validates the package | Deploying and running can cost money | | [demo_billing](demo_billing.py) | Shared billing arguments and confirmation helper | Helper only; not a standalone demo | -`app_demo` has a hard-coded cloud device ID and APK setting; review them before use. Temporary resources are released by the demos unless retained with `--keep` or an existing resource is reused. Confirm cleanup in your cloud account after an interrupted run. +`app_demo` and `intro_demo` accept `--serial` and `--cloud-device`; otherwise they use normal local Android selection and the saved cloud target or interactive picker. `app_demo` needs a local APK at `MOBILERUN_SMOKE_APK`. Temporary resources are released unless retained with `--keep` or borrowed. Confirm cleanup after an interrupted run. + +### Resource demos +- `mailbox_demo`: send an email with a code to the displayed address. Close releases the mailbox unless `--keep` is set. +- `phone_demo --live --number-id ID`: read SMS on a borrowed number. `--bind` creates a temporary core cloud phone, attaches the number, and detaches it before the phone closes. This requires paid minute billing and an active residential Connect proxy in `MOBILERUN_CLOUD_PROXY_COUNTRY`. Without `--bind`, no phone is needed and included-only billing is available. +- `proxy_demo --live --name PHONE --proxy-id ID`: apply an active Connect proxy to a borrowed phone. `--country CC` requires paid billing and confirmation (or `--yes`). If it buys a proxy, it restores the original before releasing the purchase. If restoration cannot be confirmed, check the phone's routing before releasing the purchased proxy yourself. +- `webhook_static_demo --yes`: review the webhook ID in the declaration before explicitly approving deployment. Without `--yes`, the example only prints the sample result. +- `atc_demo --yes --device CLOUD_IPHONE_ID`: explicitly approve deployment to an existing cloud iPhone. Add scheduling and webhook delivery only after validating a live run. diff --git a/tests/demos/app_demo.py b/tests/demos/app_demo.py index c1772cf66..9713659d0 100644 --- a/tests/demos/app_demo.py +++ b/tests/demos/app_demo.py @@ -4,7 +4,6 @@ """ import argparse -import asyncio import logging import sys from pathlib import Path @@ -12,14 +11,22 @@ if __package__ in (None, ""): sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) -from pydantic import BaseModel +from mobilerun_core import AsyncDevice, AsyncMobilerun # noqa: E402 +from pydantic import BaseModel # noqa: E402 + +from mobilerun.cli.devices.utils.approval import cli_hitl_gate # noqa: E402 +from mobilerun.clients.cloud.client import cloud_client # noqa: E402 +from mobilerun.clients.local.login_store import LoginStore # noqa: E402 +from mobilerun.config.settings import get_settings # noqa: E402 +from mobilerun.core.operator.base import Operator # noqa: E402 +from mobilerun.core.operator.cloud import CloudTaskOperator # noqa: E402 +from tests.support.demo_cli import ( + UNREACHABLE, + add_mode, + choose_cloud, + run_live, +) # noqa: E402 -from mobilerun.config.settings import get_settings -from mobilerun.core.devices import AndroidDevice, CloudDevice, DevicePool -from mobilerun.core.operator.cloud import CloudTaskOperator - -LOCAL_SERIAL = None -CLOUD_DEVICE_ID = "86f8d29f-9f59-4e42-ba02-1043c721774e" # Tester 1 APK = get_settings().MOBILERUN_SMOKE_APK @@ -28,21 +35,27 @@ class CounterValue(BaseModel): # ════════════════════════════════════════════════════════════════════════════ -# COUNTER DEMO: install and count on both devices at the same time +# COUNTER DEMO: install and count on both devices # ════════════════════════════════════════════════════════════════════════════ -async def install_and_open(pool: DevicePool) -> None: - # Step 2: install the local APK on both devices. - app = await pool.install_apk(APK) +def local_operator() -> Operator: + """Load the optional agents add-on only when running the demo.""" + from mobilerun_agents import AgentOperator + + return AgentOperator() - # Step 3: open Counter and let it settle. - for device, installed in zip(pool.devices, app, strict=True): - await device.start_app(installed.package) - await pool.wait(2) +async def install_and_open(device: AsyncDevice) -> None: + # Core uploads the APK before installation when this is the cloud phone. + app = await device.install_app(APK) + await device.start_app(app.identity.app_id) + await device.wait(2) -async def main(yes: bool = False) -> None: + +async def main( + yes: bool = False, *, serial: str | None = None, cloud_device: str | None = None +) -> None: if not yes: try: answer = input("This demo uses paid cloud services. Continue? [y/N] ") @@ -53,41 +66,68 @@ async def main(yes: bool = False) -> None: return print("── counter demo: start ──") - # Step 1: connect a local agent and a cloud task device in a pool. - device = AndroidDevice(LOCAL_SERIAL) - cloud = CloudDevice(CLOUD_DEVICE_ID, operator=CloudTaskOperator()) - pool = DevicePool([device, cloud]) - try: - await install_and_open(pool) + # The demo prompt (or --yes) already approved the operations below. + settings = get_settings() + async with ( + AsyncMobilerun( + bearer=LoginStore.from_settings().resolve_api_key(), + base_url=settings.MOBILERUN_CLOUD_BASE_URL, + hitl_gate=cli_hitl_gate(yes=True), + ) as run, + cloud_client(billing=settings.MOBILERUN_BILLING) as client, + ): + serial = await run.local.select_android(serial) + local = await run.connect(serial, backend="local-android-adb") + cloud = await run.connect( + await choose_cloud(run, cloud_device), backend="cloud" + ) + devices = ( + ("local", local, local_operator()), + ("cloud", cloud, CloudTaskOperator(client=client)), + ) + for _, device, _ in devices: + await install_and_open(device) # Step 4: count to ten and print each device's typed result. - results = await pool.do( - "Count to ten: tap the increment button 10 times", - output=CounterValue, - ) - for name, result in zip(("local", "cloud"), results, strict=True): + for name, device, operator in devices: + result = await operator.do( + device, + "Count to ten: tap the increment button 10 times", + output=CounterValue, + ) print(name, "counter:", result.output.value if result.output else None) # Step 5: check the counter on both devices. - try: - expectations = await pool.expect("The counter shows 10") - except Exception as e: - print("expect failed:", e) - else: - for name, result in zip(("local", "cloud"), expectations, strict=True): - print(name, "expect:", result.passed) + for name, device, operator in devices: + try: + check = await operator.expect(device, "The counter shows 10") + except UNREACHABLE: + raise + except Exception as e: + print("expect failed:", e) + else: + print(name, "expect:", check.passed) # Step 6: return both devices to the home screen. - await pool.press_button("home") + for _, device, _ in devices: + await device.key("home") print("── counter demo: done ──") - finally: - await pool.close() if __name__ == "__main__": logging.basicConfig(level=logging.WARNING, format="%(message)s") logging.getLogger("mobilerun.actions").setLevel(logging.INFO) parser = argparse.ArgumentParser(description=__doc__) + add_mode(parser) + parser.add_argument("--serial", help="Local Android serial") + parser.add_argument("--cloud-device", help="Existing cloud device ID") parser.add_argument("--yes", action="store_true", help="Approve paid cloud usage") - asyncio.run(main(yes=parser.parse_args().yes)) + args = parser.parse_args() + if args.live: + sys.exit( + run_live( + main(yes=args.yes, serial=args.serial, cloud_device=args.cloud_device) + ) + ) + print("Offline counter output:", CounterValue(value=10).model_dump_json()) diff --git a/tests/demos/atc_demo.py b/tests/demos/atc_demo.py new file mode 100644 index 000000000..aa92f0c43 --- /dev/null +++ b/tests/demos/atc_demo.py @@ -0,0 +1,1017 @@ +"""Capture three recent ATC events on a cloud iPhone.""" + +import argparse +from datetime import datetime +from pathlib import Path + +from mobilerun_functions import Context +from pydantic import BaseModel, Field + +from mobilerun.sandbox import cloud +from mobilerun.sandbox.app import deploy +from mobilerun.sandbox.packaging import package + + +class Input(BaseModel): + map_wait_s: float = 9.0 + + +class Event(BaseModel): + airport_code: str | None = None + relative_time: str | None = None + event_title: str | None = None + flight_call_sign: str | None = None + event_link: str | None = None + transcript_text: str | None = None + map_screenshot: str + transcript_screenshot: str + + +class Output(BaseModel): + captured_at: datetime + events: list[Event] = Field(min_length=3, max_length=3) + + +# Add a schedule and a webhook endpoint ID only after a successful live run. +@cloud( + "atc-new-routine-v2", + files_folder="atc", + files={ + "event_1_map.jpg": "events.0.map_screenshot", + "event_1_transcript.jpg": "events.0.transcript_screenshot", + "event_2_map.jpg": "events.1.map_screenshot", + "event_2_transcript.jpg": "events.1.transcript_screenshot", + "event_3_map.jpg": "events.2.map_screenshot", + "event_3_transcript.jpg": "events.2.transcript_screenshot", + }, +) +def main(input: Input, ctx: Context) -> Output: + # Labels and roles observed on the iPhone. + LABELS = { + "new": "New", + "latest": "Latest Events", + "more": "More options", + "copy": "Copy Link", + "transcripts": "View Transcripts", + "close": "Close", + "close_search": "Close search", + "search": "Search", + "paste": "Paste", + "grabber": "Sheet Grabber", + "button": "Button", + "text": "StaticText", + "textfield": "TextField", + } + import base64 + import io + import json + import re + import time + from datetime import datetime, timezone + + from mobilerun_functions import NotAvailableError, ScriptError + from PIL import Image, ImageDraw, ImageFont + + def placeholder_jpeg(): + image = Image.new("L", (320, 80), 100) + ImageDraw.Draw(image).text( + (160, 40), + "no screenshot", + anchor="mm", + fill=240, + font=ImageFont.load_default(size=18), + ) + with io.BytesIO() as data: + image.save(data, format="JPEG", quality=65, optimize=True) + return base64.b64encode(data.getvalue()).decode("ascii") + + def build_output(events, captured_at): + text_fields = ( + "airport_code", + "relative_time", + "event_title", + "flight_call_sign", + "event_link", + "transcript_text", + ) + screenshot_fields = ("map_screenshot", "transcript_screenshot") + placeholder = placeholder_jpeg() + count = 0 + values = [] + replaceable = [] + for i in range(1, 4): + event = events[i - 1] if i <= len(events) else {} + item = {field: event.get(field) for field in text_fields} + for field in screenshot_fields: + value = event.get(field) + if not value: + value = placeholder + count += 1 + elif len(value) > len(placeholder): + replaceable.append((len(value), i - 1, field)) + item[field] = value + values.append(item) + output = Output(captured_at=captured_at, events=values) + for _, index, field in sorted(replaceable, reverse=True): + if len(output.model_dump_json(by_alias=True).encode("utf-8")) <= 512 * 1024: + break + setattr(output.events[index], field, placeholder) + count += 1 + if len(output.model_dump_json(by_alias=True).encode("utf-8")) > 512 * 1024: + raise ScriptError( + "atc_result_too_large", + "Result exceeds 512 KiB even after screenshot substitutions", + ) + return output, count + + started = time.monotonic() + deadline = started + 540 + run_deadline = getattr(ctx.run, "deadline", None) + if isinstance(run_deadline, datetime): + if run_deadline.tzinfo is None: + run_deadline = run_deadline.replace(tzinfo=timezone.utc) + deadline = min( + deadline, + started + (run_deadline - datetime.now(timezone.utc)).total_seconds(), + ) + + def require_budget(): + if deadline - time.monotonic() < 45: + raise ScriptError( + "atc_deadline", "Insufficient time remaining to safely continue" + ) + + transient_retries = 0 + + def transient(exc): + return ( + getattr(exc, "status_code", None) in (502, 503, 504) + or isinstance(exc, (ConnectionError, TimeoutError)) + or any( + cls.__name__ in ("APIConnectionError", "APITimeoutError") + and cls.__module__.startswith("mobilerun_sdk") + for cls in type(exc).__mro__ + ) + ) + + def call(fn, *args, **kw): + nonlocal transient_retries + for attempt in range(3): + require_budget() + try: + return fn(*args, **kw) + except Exception as exc: + if not transient(exc) or attempt == 2: + raise + delay = (2, 5)[attempt] + if deadline - time.monotonic() - 45 <= delay: + raise ScriptError( + "atc_deadline", + f"No budget left to retry transient error: {exc}", + ) from exc + transient_retries += 1 + status = getattr(exc, "status_code", None) or type(exc).__name__ + name = getattr(fn, "__name__", type(fn).__name__) + ctx.log.info( + f"transient {status} on {name}(); retry {attempt + 1}/2 in {delay}s" + ) + time.sleep(delay) + + def ui(): + require_budget() + state = call(device.ui) + require_budget() + return state + + app = "com.enhancedradar.atc" + device = ctx.device() + + def start_atc(): + require_budget() + try: + device.start_app(app) + except Exception as exc: + if not transient(exc): + raise + state = ui() + if foreground(state) != app: + raise + ctx.log.info( + "transient start_app; ATC foreground confirmed without repeating action" + ) + + def fatal_device_error(exc): + return isinstance(exc, NotAvailableError) or getattr( + exc, "status_code", None + ) in (401, 403) + + foreground_calls = 0 + + def foreground(state): + return state.focused_app or ( + state.phone_state.package_name if state.phone_state else None + ) + + def guard(state): + nonlocal foreground_calls + package = foreground(state) + if package == app: + return + foreground_calls += 1 + current = call(device.current_app_id) + if current != app or (package and package != app): + start_atc() + raise ScriptError( + "atc_foreground_changed", + "Foreground app changed; reopened ATC without tapping the other app", + ) + + def normalized(value): + return " ".join(value.split()).casefold() + + def label(node): + return ( + node.text + or node.label + or node.value + or node.content_description + or node.resource_id + or "" + ) + + def role(node): + return node.class_name or "" + + def texts(state): + return [ + label(n) + for n in state.elements or () + if label(n) and not n.hidden and not n.offscreen + ] + + def find(state, wanted, expected_role=None): + options = (wanted,) if isinstance(wanted, str) else wanted + for node in state.elements or (): + value = label(node).casefold() + if ( + not node.hidden + and not node.offscreen + and any(x.casefold() in value for x in options) + and ( + not expected_role + or expected_role.casefold() in role(node).casefold() + ) + ): + return node + return None + + def required(state, wanted, expected_role=None, exact=False): + for attempt in range(12): + node = ( + next( + ( + n + for n in state.elements or () + if not n.hidden + and not n.offscreen + and normalized(label(n)) == normalized(wanted) + and ( + not expected_role + or expected_role.casefold() in role(n).casefold() + ) + ), + None, + ) + if exact + else find(state, wanted, expected_role) + ) + if node is not None: + return node + if attempt < 11: + time.sleep(0.5) + state = ui() + raise ScriptError( + "atc_element_missing", + f"Missing {wanted!r}; visible texts: {texts(state)!r}", + ) + + def transition(target, expected_name, expect, source, select, action="tap"): + state = ui() + for attempt in range(3): + require_budget() + if attempt: + state = ui() + guard(state) + if expect(state): + return state + node = select(state) if source(state) else None + if not node: + time.sleep(0.5) + state = ui() + guard(state) + if expect(state): + return state + node = select(state) if source(state) else None + if not node: + raise ScriptError( + "atc_navigation_failed", + f"{action} {target!r}: expected {expected_name}; source screen lost; visible texts: {texts(state)!r}", + ) + if node: + if isinstance(node, tuple): + node, state = node + if attempt: + ctx.log.info(f"retry {action} {target!r} ({attempt + 1}/3)") + guard(state) + try: + if action == "tap": + device.tap_node(node) + elif action == "long_press": + device.long_press(*node.center) + else: + x, y = node.center + device.swipe(x, y, x, 700, ms=400) + except Exception as exc: + if not transient(exc): + raise + ctx.log.info( + f'transient {getattr(exc, "status_code", None) or type(exc).__name__} on {action} {target!r}; checking screen' + ) + for _ in range(4): + time.sleep(0.5) + state = ui() + guard(state) + if expect(state): + return state + raise ScriptError( + "atc_navigation_failed", + f"{action} {target!r}: expected {expected_name}; visible texts: {texts(state)!r}", + ) + + def tap_until(target, expected_name, expect, source, role_name=None, selector=None): + return transition( + target, + expected_name, + expect, + source, + selector or (lambda s: find(s, target, role_name)), + ) + + def is_home(state): + return not any( + find(state, value) + for value in ( + LABELS["latest"], + LABELS["grabber"], + LABELS["close_search"], + LABELS["more"], + LABELS["copy"], + LABELS["transcripts"], + ) + ) and any( + normalized(label(n)) == normalized(LABELS["search"]) + and LABELS["button"].casefold() in role(n).casefold() + and not n.hidden + and not n.offscreen + for n in state.elements or () + ) + + def is_latest(state): + return bool( + find(state, LABELS["latest"]) + and not find(state, "•", LABELS["text"]) + and any( + "button" in role(n).casefold() + and not n.hidden + and not n.offscreen + and re.match(r"^[A-Z]{3},\s*.+? ago,", label(n), re.I) + for n in state.elements or () + ) + ) + + def is_menu(state): + return bool(find(state, LABELS["copy"]) and find(state, LABELS["transcripts"])) + + def is_search(state): + return bool( + find(state, LABELS["close_search"], LABELS["button"]) + and any( + "textfield" in role(n).casefold() and not n.hidden and not n.offscreen + for n in state.elements or () + ) + ) + + def is_transcript(state): + return bool( + find(state, "•", LABELS["text"]) + and find(state, LABELS["grabber"], LABELS["button"]) + and not find(state, LABELS["latest"]) + ) + + def is_detail_controls(state): + return bool( + find(state, LABELS["close"], LABELS["button"]) + and find(state, LABELS["more"], LABELS["button"]) + and any( + find(state, value) + for value in ("Replay timeline", "Pause replay", "Play replay") + ) + and not any( + find(state, value) + for value in ( + LABELS["latest"], + LABELS["copy"], + LABELS["transcripts"], + "Dismiss context menu", + LABELS["grabber"], + ) + ) + ) + + def overlap(a, b): + left = set(re.findall(r"\w+", normalized(a))) + right = set(re.findall(r"\w+", normalized(b))) + left_ids = {token for token in left if any(c.isdigit() for c in token)} + right_ids = {token for token in right if any(c.isdigit() for c in token)} + if left_ids != right_ids: + return 0.0 + return len(left & right) / max(len(left), len(right), 1) + + def header_texts(state): + more = find(state, LABELS["more"], LABELS["button"]) + if not more or not more.center: + return [] + # Screen width from the app's root node when exposed, otherwise from visible nodes only. + root = next( + ( + n + for n in state.elements or () + if "application" in role(n).casefold() and n.bounds + ), + None, + ) + right = ( + root.bounds[2] + if root + else max( + ( + n.bounds[2] + for n in state.elements or () + if n.bounds and not n.hidden and not n.offscreen + ), + default=0, + ) + ) + if not right: + return [] + top = more.center[1] + 20 + bottom = top + 150 + map_button = find(state, "Back to automatic map") + if map_button and map_button.center: + bottom = min(bottom, map_button.center[1]) + return [ + " ".join(label(n).split()) + for n in state.elements or () + if not n.hidden + and not n.offscreen + and LABELS["text"].casefold() in role(n).casefold() + and n.center + and label(n).strip() + and top < n.center[1] < bottom + and abs(n.center[0] - right / 2) < 60 + ] + + def detail_headline(state, title): + if not find(state, LABELS["more"], LABELS["button"]) or any( + find(state, value) + for value in ( + LABELS["latest"], + LABELS["copy"], + LABELS["transcripts"], + "Dismiss context menu", + LABELS["grabber"], + ) + ): + return None + candidates = [ + value for value in header_texts(state) if overlap(value, title) >= 0.6 + ] + return max(candidates, key=lambda value: overlap(value, title), default=None) + + def is_detail(state, title): + return bool(detail_headline(state, title)) + + def detail_page(title): + state = ui() + for attempt in range(7): + if is_detail(state, title): + return state + if is_detail_controls(state) and header_texts(state): + raise ScriptError( + "atc_event_changed", + f"Detail headline changed: expected {title!r}; found {header_texts(state)!r}", + ) + if attempt < 6: + time.sleep(0.5) + state = ui() + if is_detail_controls(state) and not header_texts(state): + ctx.log.warning("headline not visible; identity verified at open") + return state + raise ScriptError( + "atc_detail_missing", + f"Expected detail {title!r}; visible texts: {texts(state)!r}", + ) + + def current_time(): + try: + raw = call(device.time).strip() + if raw.startswith('"'): + raw = json.loads(raw) + value = datetime.fromisoformat(raw.replace("Z", "+00:00")) + if value.tzinfo is None: + raise ValueError("device time has no timezone") + ctx.log.info("Captured timestamp from device") + return value + except Exception as exc: + if fatal_device_error(exc): + raise + ctx.log.info(f"Device time unavailable ({exc}); using UTC now") + return datetime.now(timezone.utc) + + def parse_list(state, captured): + required(state, LABELS["latest"]) + rows = [] + pattern = re.compile( + r"^([A-Z]{3}),\s*(.+? ago),\s*(?:[\d,]+ views,\s*)?(.*)$", re.I + ) + for node in state.elements or (): + match = pattern.fullmatch(label(node)) + if match and "button" in role(node).casefold(): + rows.append( + ( + (node.center or (0, 0))[1], + dict( + airport_code=match[1], + relative_time=match[2], + event_title=match[3].strip(), + captured_at=captured, + ), + ) + ) + if not rows: + raise ScriptError( + "atc_event_list_missing", + f"Missing event rows; visible texts: {texts(state)!r}", + ) + return [row for _, row in sorted(rows, key=lambda item: item[0])][:3] + + def stable_list(): + def rows(state): + return [ + label(n) + for n in sorted( + state.elements or (), key=lambda n: (n.center or (0, 0))[1] + ) + if "button" in role(n).casefold() + and re.match(r"^[A-Z]{3},\s*.+? ago,", label(n), re.I) + and not n.hidden + and not n.offscreen + ] + + previous = None + for _ in range(12): + state = ui() + current = rows(state) + if current and current == previous and find(state, LABELS["latest"]): + return state + previous = current + time.sleep(0.5) + raise ScriptError( + "atc_list_unstable", + f"Latest Events did not stabilize; visible texts: {texts(state)!r}", + ) + + def parse_transcript(state, caption, headline): + from collections import Counter + + nodes = [ + n + for n in state.elements or () + if LABELS["text"].casefold() in role(n).casefold() + and label(n) + and n.center + and not n.hidden + and not n.offscreen + ] + lines, calls, rows = [], [], [] + call = when = None + for node in nodes: + text = label(node).strip() + x, y = node.center + if y < 120: + continue + if x < 65 and re.fullmatch(r"[A-Z0-9]{2,10}", text): + call, when = text, None + calls.append(text) + elif ( + call + and x < 125 + and re.fullmatch(r"(?:.*\bago|\d{1,2}:\d{2}\s*[ap]m)", text, re.I) + ): + when = text + elif x >= 125: + lines.append(f"{call} {when}: {text}" if call and when else text) + if call and when: + rows.append((call, text)) + call = when = None + if not lines: + raise ScriptError( + "atc_transcript_missing", + f"Missing transcript rows; visible texts: {texts(state)!r}", + ) + + def normal(text): + return " ".join(re.findall(r"[a-z0-9]+", text.lower())) + + captions = [normal(value) for value in caption] + caption_matches = { + call + for call, message in rows + for value in captions + if len(value.split()) >= 2 + and (" " + value + " ") in (" " + normal(message) + " ") + } + if len(caption_matches) == 1: + return "\n".join(lines), next(iter(caption_matches)), "caption" + + title = normal(headline) + labels = set(calls) + airline_names = {"delta": "DAL", "ups": "UPS"} + matches = set() + for call in labels: + if call.startswith("N") and len(call) >= 5: + registration = call[1:].lower() + if re.search( + r"\b" + re.escape(registration) + r"\b", title + ) or re.search(r"\b" + re.escape(call.lower()) + r"\b", title): + matches.add(call) + for airline, prefix in airline_names.items(): + if not re.search(r"\b" + airline + r"\b", title): + continue + flight = re.search(r"\b" + airline + r"\s+(\d{2,5})\b", title) + # 757 is the aircraft type in a verified UPS headline, not its flight number. + number = flight.group(1) if flight and flight.group(1) != "757" else None + candidates = {call for call in labels if call.startswith(prefix)} + if number: + matches.update(call for call in candidates if call == prefix + number) + elif len(candidates) == 1: + matches.update(candidates) + if len(matches) == 1: + return "\n".join(lines), next(iter(matches)), "headline" + counts = Counter(calls).most_common() + selected = ( + counts[0][0] + if counts and (len(counts) == 1 or counts[0][1] > counts[1][1]) + else None + ) + return "\n".join(lines), selected, "frequency" if selected else "none" + + def screenshot(budget): + data = call(device.ui, screenshot=True).screenshot + if data is None: + raise ScriptError("atc_screenshot_missing", "No screenshot returned") + with Image.open(io.BytesIO(data)) as source: + image = source.convert("RGB") + image.thumbnail((1000, 1000), Image.Resampling.LANCZOS) + for quality in (70, 60, 50, 40, 30): + data = io.BytesIO() + image.save(data, format="JPEG", quality=quality, optimize=True) + encoded = base64.b64encode(data.getvalue()).decode("ascii") + if len(encoded) <= budget: + return encoded + ctx.log.warning("Screenshot exceeds its JPEG budget at quality 30; omitted") + errors.append("screenshot exceeds JPEG budget") + return None + + def latest(): + for _ in range(5): + state = ui() + try: + guard(state) + except ScriptError as exc: + if exc.code != "atc_foreground_changed": + raise + time.sleep(1) + continue + # ATC briefly exposes only its logo while a sheet or map loads. + for _ in range(12): + if any( + find(state, value) + for value in ( + LABELS["latest"], + LABELS["new"], + LABELS["close"], + LABELS["close_search"], + ) + ): + break + time.sleep(0.5) + state = ui() + try: + guard(state) + except ScriptError as exc: + if exc.code != "atc_foreground_changed": + raise + continue + if find(state, LABELS["latest"]): + return state + try: + if find(state, LABELS["close_search"], LABELS["button"]): + tap_until( + LABELS["close_search"], + "home", + is_home, + is_search, + LABELS["button"], + ) + elif find(state, LABELS["new"], LABELS["text"]): + tap_until( + LABELS["new"], + LABELS["latest"], + lambda s: find(s, LABELS["latest"]), + is_home, + LABELS["text"], + ) + elif find(state, LABELS["close"], LABELS["button"]) and find( + state, LABELS["more"], LABELS["button"] + ): + tap_until( + LABELS["close"], + LABELS["latest"], + is_latest, + is_detail_controls, + LABELS["button"], + ) + else: + ctx.log.info( + "Unexpected screen; force-closing ATC with stop_app/start_app" + ) + try: + device.stop_app(app) + except Exception as exc: + if not transient(exc): + raise + ctx.log.info( + "transient stop_app; checking screen before recovery" + ) + ui() + continue + start_atc() + except ScriptError as exc: + if exc.code != "atc_foreground_changed": + raise + continue + time.sleep(1) + state = ui() + if not find(state, LABELS["latest"]): + try: + required(state, LABELS["latest"]) + except ScriptError as exc: + if exc.code != "atc_element_missing": + raise + raise ScriptError( + "atc_latest_unavailable", f"Unable to reach Latest Events: {exc}" + ) from exc + state = ui() + return state + + def swipe_sheet(expected_name, expect, source): + return transition( + LABELS["grabber"], + expected_name, + expect, + source, + lambda s: find(s, LABELS["grabber"], LABELS["button"]), + action="swipe", + ) + + def read_copied_link(): + swipe_sheet("home", is_home, is_latest) + state = tap_until( + LABELS["search"], "search field", is_search, is_home, LABELS["button"] + ) + transition( + "search field", + "Paste menu", + lambda s: find(s, LABELS["paste"]), + is_search, + lambda s: next( + ( + n + for n in s.elements or () + if LABELS["textfield"].casefold() in role(n).casefold() + and not n.hidden + and not n.offscreen + ), + None, + ), + action="long_press", + ) + + def pasted(s): + return next( + ( + label(n) + for n in s.elements or () + if "textfield" in role(n).casefold() + and re.fullmatch(r"https://atc\.com/\S+", label(n)) + ), + None, + ) + + state = tap_until(LABELS["paste"], "URL in search field", pasted, is_search) + link = pasted(state) + tap_until(LABELS["close_search"], "home", is_home, is_search, LABELS["button"]) + return link + + errors = [] + captured = datetime.now(timezone.utc) + events = [] + try: + ctx.log.info("Opening ATC") + require_budget() + start_atc() + latest() + state = stable_list() + captured = current_time() + events = parse_list(state, captured) + except ScriptError as exc: + if exc.code not in ( + "atc_deadline", + "atc_list_unstable", + "atc_event_list_missing", + "atc_navigation_failed", + "atc_latest_unavailable", + ): + raise + errors.append(str(exc)) + used_links = set() + previous = ctx.state.previous if ctx.state.previous_schema == 1 else None + history = ( + [value for value in previous.get("links", []) if isinstance(value, str)] + if isinstance(previous, dict) and isinstance(previous.get("links"), list) + else [] + ) + history = history[-50:] + # Split equally across all anticipated screenshots; failed captures leave spare room. + image_budget = (512 * 1024 - 64 * 1024) // max(1, 2 * len(events)) + for index, event in enumerate(events): + t = time.monotonic() + try: + require_budget() + ctx.log.info(f"Event {index + 1}: opening {event['event_title']}") + latest() + pattern = re.compile( + r"^([A-Z]{3}),\s*(.+? ago),\s*(?:[\d,]+ views,\s*)?(.*)$", re.I + ) + + def row(s, index=index, event=event, pattern=pattern): + if not find(s, LABELS["latest"]): + return None + s = stable_list() + matching = [] + for node in sorted( + s.elements or (), key=lambda item: (item.center or (0, 0))[1] + ): + match = pattern.fullmatch(label(node)) + if ( + match + and "button" in role(node).casefold() + and not node.hidden + and not node.offscreen + ): + matching.append((node, match)) + if index >= len(matching): + raise ScriptError( + "atc_event_missing", + f"Event position {index + 1} no longer exists", + ) + node, match = matching[index] + if ( + normalized(match[1]) != normalized(event["airport_code"]) + or overlap(match[3], event["event_title"]) < 0.6 + ): + raise ScriptError( + "atc_event_changed", + f'Event position {index + 1} changed: expected {event["airport_code"]} {event["event_title"]!r}; found {label(node)!r}', + ) + event["event_title"] = match[3].strip() + return node, s + + detail = tap_until( + event["event_title"], + "event detail", + lambda s, event=event: is_detail(s, event["event_title"]), + is_latest, + selector=row, + ) + event["event_title"] = detail_headline(detail, event["event_title"]) + caption = [ + label(n) + for n in detail.elements or () + if "button" in role(n).casefold() and re.search(r",\s+,", label(n)) + ] + time.sleep(min(30, max(0, input.map_wait_s))) + detail_page(event["event_title"]) + event["map_screenshot"] = screenshot(image_budget) + ctx.log.info( + f"Event {index + 1}: map captured after {time.monotonic() - t:.2f}s" + ) + tap_until( + LABELS["more"], + "options menu", + is_menu, + is_detail_controls, + LABELS["button"], + ) + tap_until(LABELS["copy"], "event detail", is_detail_controls, is_menu) + detail_page(event["event_title"]) + tap_until( + LABELS["more"], + "options menu", + is_menu, + is_detail_controls, + LABELS["button"], + ) + state = tap_until( + LABELS["transcripts"], "transcript header", is_transcript, is_menu + ) + event["transcript_text"], event["flight_call_sign"], rule = ( + parse_transcript(state, caption, event["event_title"]) + ) + ctx.log.info(f"Event {index + 1}: callsign rule={rule}") + event["transcript_screenshot"] = screenshot(image_budget) + swipe_sheet("event detail", is_detail_controls, is_transcript) + tap_until( + LABELS["close"], + LABELS["latest"], + is_latest, + is_detail_controls, + LABELS["button"], + ) + link = read_copied_link() + if link and (link in used_links or link in history): + errors.append(f"event {index + 1}: duplicate or stale link") + link = None + event["event_link"] = link + if link: + used_links.add(link) + history.append(link) + ctx.log.info(f"Event {index + 1}: complete in {time.monotonic() - t:.2f}s") + except Exception as exc: + if fatal_device_error(exc): + raise + ctx.log.info( + f"Event {index + 1}: failed after {time.monotonic() - t:.2f}s: {exc}" + ) + errors.append(f"event {index + 1}: {exc}") + if isinstance(exc, ScriptError) and exc.code == "atc_deadline": + break + output, placeholder_count = build_output(events, captured) + if placeholder_count: + ctx.log.warning(f"{placeholder_count} screenshot placeholder(s) used") + errors.append(f"{placeholder_count} screenshot placeholder(s) used") + try: + ctx.state.save({"links": history[-50:]}, schema=1) + except NotAvailableError: + ctx.log.warning( + "Run state unavailable: cross-run stale links cannot be detected" + ) + if errors: + ctx.partial("; ".join(errors)[:500]) + ctx.log.info(f"Foreground current_app_id calls: {foreground_calls}") + ctx.log.info(f"Transient read retries: {transient_retries}") + ctx.log.info(f"Run finished in {time.monotonic() - started:.2f}s") + return output + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + mode = parser.add_mutually_exclusive_group() + mode.add_argument( + "--yes", action="store_true", help="Approve deployment (may charge)" + ) + mode.add_argument( + "--fake", + action="store_true", + help="Package locally without deploying (default)", + ) + parser.add_argument("--device", help="Existing cloud iPhone ID; required to deploy") + args = parser.parse_args() + if args.yes: + if not args.device: + parser.error("--yes requires --device") + deploy(__file__, device=args.device, yes=True) + else: + artifact = package(Path(__file__)) + print(f"Offline package validated: {artifact.declaration.name}") diff --git a/tests/demos/demo_billing.py b/tests/demos/demo_billing.py index 38df9296b..287cd3114 100644 --- a/tests/demos/demo_billing.py +++ b/tests/demos/demo_billing.py @@ -2,8 +2,10 @@ import argparse +from mobilerun_core import CloudPlan + from mobilerun.config.settings import get_settings -from mobilerun.models import Billing, Plan +from mobilerun.models import Billing BILLING_HELP = "included = included quota only, never charges; paid = included first, then charges (default: configured billing)." PLAN_HELP = "auto = subscription slot first, then per-minute; minute = always per-minute; subscription = included slot only." @@ -27,12 +29,24 @@ def billing_value(value: str | None) -> Billing: def check_phone_plan(billing: Billing, plan: str | None) -> None: - if billing == Billing.INCLUDED and plan in (Plan.AUTO, Plan.MINUTE): + if billing == Billing.INCLUDED and plan in ("auto", "minute"): raise ValueError( "--billing included requires --plan subscription (or omit --plan)" ) +def temporary_phone_plan(billing: Billing, plan: str | None) -> CloudPlan: + """Resolve a core phone plan that cannot overrun billing or skip cleanup.""" + check_phone_plan(billing, plan) + if billing == Billing.NO_COMMERCE: + raise ValueError("Configured billing no_commerce blocks phone creation.") + if billing != Billing.PAID or plan not in (None, "minute"): + raise ValueError( + "A temporary cloud phone requires --billing paid --plan minute." + ) + return "minute" + + def confirmation(billing: Billing) -> str: if billing == Billing.INCLUDED: return "This uses included quota only (no charges); fails if none is left. Continue? [y/N] " diff --git a/tests/demos/easy_macro_demo.py b/tests/demos/easy_macro_demo.py new file mode 100644 index 000000000..58483bfb1 --- /dev/null +++ b/tests/demos/easy_macro_demo.py @@ -0,0 +1,49 @@ +"""Easy macro demo: record a macro, reset the phone, replay the macro. + +Run `python tests/demos/easy_macro_demo.py [DEVICE]`. +Without DEVICE it uses the device saved by `mobilerun device connect`. +""" + +import click +from mobilerun_core import AsyncDevice + +from mobilerun.cli.devices.base.device import device_command +from mobilerun.core.runs import ActionRecording +from mobilerun.macro import MacroPlayer, build_macro, load_macro + +APP = "com.android.settings" +PAUSE = 1 # Seconds between steps, so you can watch the phone. + + +async def main(device: AsyncDevice) -> None: + # 1. Create the macro: do a few basic actions while recording, then save them. + async with ActionRecording(device) as recording: + await device.start_app(APP) + await device.wait(PAUSE) + await device.swipe(500, 1500, 500, 500) + await device.wait(PAUSE) + recording.finish("succeeded") + path = build_macro(recording.run_dir / "steps.jsonl", "easy-demo") + click.echo(f"1. Recorded {recording.step_index} actions: {path}") + + # 2. Reset the phone: close the app and go home. This is not in the macro. + await device.stop_app(APP) + await device.key("home") + await device.wait(PAUSE) + click.echo("2. Reset the phone") + + # 3. Replay the saved macro. + player = MacroPlayer(device) + await player.replay_macro(load_macro(path)) + click.echo(f"3. Replayed {player.executed_steps} actions") + + +@click.command() +@device_command +async def cli(device: AsyncDevice) -> None: + """Record a short Settings macro, reset the phone, and replay the macro.""" + await main(device) + + +if __name__ == "__main__": + cli() diff --git a/tests/demos/intro_demo.py b/tests/demos/intro_demo.py index 35554c473..566d2c144 100644 --- a/tests/demos/intro_demo.py +++ b/tests/demos/intro_demo.py @@ -4,32 +4,39 @@ import asyncio import logging import sys +from contextlib import AsyncExitStack from pathlib import Path +from typing import TYPE_CHECKING from uuid import uuid4 if __package__ in (None, ""): sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) +from mobilerun_core import AsyncDevice, AsyncMobilerun # noqa: E402 from pydantic import BaseModel # noqa: E402 -from mobilerun.clients.cloud.apps import upload_app # noqa: E402 +from mobilerun import Workspace # noqa: E402 +from mobilerun.cli.devices.utils.approval import cli_hitl_gate # noqa: E402 +from mobilerun.clients.cloud.billing_policy import BillingPolicy # noqa: E402 +from mobilerun.clients.cloud.client import cloud_client # noqa: E402 +from mobilerun.clients.local.login_store import LoginStore # noqa: E402 from mobilerun.config.settings import get_settings # noqa: E402 from mobilerun.core.credentials import CloudCredentials, DictCredentials # noqa: E402 -from mobilerun.core.devices import ( # noqa: E402 - AndroidDevice, - CloudDevice, - Device, - DevicePool, - RecordingDevice, -) +from mobilerun.core.operator.cloud import CloudTaskOperator # noqa: E402 +from mobilerun.core.proxy import CloudRotatingProxy # noqa: E402 +from mobilerun.core.runs import ActionRecording # noqa: E402 from mobilerun.macro import MacroOperator, build_macro # noqa: E402 from mobilerun.models import Billing # noqa: E402 from mobilerun.sandbox import cloud # noqa: E402 from mobilerun.skills import list_skills # noqa: E402 from tests.demos.demo_billing import confirmation # noqa: E402 +from tests.support.demo_cli import add_mode, choose_cloud, run_live # noqa: E402 +from tests.support.devices import fake_device # noqa: E402 + +if TYPE_CHECKING: + from mobilerun.core.operator.base import Operator + from mobilerun.models.results import ExecutionResult -LOCAL_SERIAL = "emulator-5554" -CLOUD_DEVICE_ID = "86f8d29f-9f59-4e42-ba02-1043c721774e" # Tester 1 AGENT = True # do() and expect() use LLM time and cloud credits. APK = get_settings().MOBILERUN_SMOKE_APK NEW_CLOUD_DEVICE = False # Creates a cloud phone, costs credits. @@ -40,7 +47,7 @@ class AndroidVersion(BaseModel): version: str -def AgentOperator(): +def AgentOperator() -> "Operator": """Load the optional operator only when the agent demo is enabled.""" from mobilerun_agents import AgentOperator as operator @@ -61,18 +68,17 @@ def hello(input: GreetingInput) -> GreetingOutput: return GreetingOutput(message=f"Hello, {input.name}!") -async def local_basics(device: Device) -> None: +async def local_basics(device: AsyncDevice) -> None: # Take a screenshot, count apps, and go home. - Path("local-screenshot.png").write_bytes(await device.screenshot()) + Path("local-screenshot.png").write_bytes(await device.screenshot_bytes()) print("local apps:", len(await device.list_apps())) - await device.press_button("home") + await device.key("home") -async def cloud_basics(cloud: Device) -> None: - # CloudDevice uses CloudTaskOperator by default. - Path("cloud-screenshot.png").write_bytes(await cloud.screenshot()) +async def cloud_basics(cloud: AsyncDevice) -> None: + Path("cloud-screenshot.png").write_bytes(await cloud.screenshot_bytes()) print("cloud apps:", len(await cloud.list_apps())) - await cloud.press_button("home") + await cloud.key("home") # ════════════════════════════════════════════════════════════════════════════ @@ -80,25 +86,24 @@ async def cloud_basics(cloud: Device) -> None: # ════════════════════════════════════════════════════════════════════════════ -async def macro_demo(device: Device) -> None: +async def macro_demo(device: AsyncDevice) -> None: print("── macro demo: start ──") # Step 1: record actions while they happen on the device. # UI state can differ between runs, so leave these demo actions unguarded. - recording = RecordingDevice(device, capture="actions") - await recording.start_app("com.android.settings") - await recording.wait(2) - await recording.swipe(500, 1600, 500, 500, 500) - await recording.wait(1) - await recording.press_button("back") - recording.finish("succeeded") - assert recording.run_dir is not None + async with ActionRecording(device) as recording: + await device.start_app("com.android.settings") + await device.wait(2) + await device.swipe(500, 1600, 500, 500, ms=500) + await device.wait(1) + await device.key("back") + recording.finish("succeeded") # Step 2: publish a version without replacing any previous demo macro. path = build_macro(recording.run_dir / "steps.jsonl", "intro-demo") # Step 3: return home, then replay with a one-call operator. - await device.press_button("home") - result = await device.do("Replay", operator=MacroOperator(path)) + await device.key("home") + result: ExecutionResult[BaseModel] = await MacroOperator(path).do(device, "Replay") print("macro replay:", result.success) print("── macro demo: done ──") @@ -109,25 +114,41 @@ async def macro_demo(device: Device) -> None: # ════════════════════════════════════════════════════════════════════════════ -async def credentials_demo(device: Device) -> None: +async def credentials_demo(device: AsyncDevice) -> None: print("── credentials demo: start ──") - # Step 1: attach a local credential provider. - vault = DictCredentials({"demo_password": "not-a-real-secret"}) - await vault.bind(device) - - # Step 2: open Settings and focus its search field. - await device.start_app("com.android.settings") - await device.wait(2) - await device.state.refresh() - search = next( - item for item in device.state.current.elements if "search" in str(item).lower() - ) - await device.tap_element(search["index"]) - - # Step 3: type directly; the value is never logged or sent to the model. - await vault.type_field(None, "password", name="demo_password") - await device.press_button("home") + vault = DictCredentials({"demo_password": "not-a-real-secret"}, device=device) + try: + # Open Settings and focus its search field. + await device.start_app("com.android.settings") + await device.wait(2) + state = await device.observe() + if state.focused_input is None: + search = next( + ( + item + for item in state.elements or () + if any( + "search" in (value or "").lower() + for value in ( + item.text, + item.content_description, + item.resource_id, + ) + ) + ), + None, + ) + if search is None: + raise RuntimeError("Settings search entry not found") + await device.tap_element(search) + await device.wait(1) + + # Type directly; the value is never logged or sent to the model. + await vault.type_secret("demo_password") + await device.key("home") + finally: + await vault.close() print("── credentials demo: done ──") @@ -143,13 +164,16 @@ async def vault_demo() -> None: vault = CloudCredentials() package = "ai.mobilerun.demo" name = f"demo-{uuid4().hex}" - await vault.save(package, name, {"password": "not-a-real-secret"}) try: + await vault.save(package, name, {"password": "not-a-real-secret"}) # Step 2: list names without printing values. print("vault names:", [item["name"] for item in await vault.list(package)]) finally: # Step 3: delete the throwaway credential even if listing fails. - await vault.delete(package, name) + try: + await vault.delete(package, name) + finally: + await vault.close() print("── vault demo: done ──") @@ -158,25 +182,27 @@ async def vault_demo() -> None: # ════════════════════════════════════════════════════════════════════════════ -async def local_app_install_demo(device: Device) -> None: +async def local_app_install_demo(device: AsyncDevice) -> None: print("── local app install demo: start ──") # Step 1: keep the local Counter app installed for later use. if Path(APK).is_file(): - await device.install_apk(APK, reinstall=True) + await device.install_app(APK, reinstall=True) else: print("Set MOBILERUN_SMOKE_APK to an existing APK to run the install demo.") print("── local app install demo: done ──") -async def cloud_app_install_demo(cloud: Device) -> None: +async def cloud_app_install_demo(cloud: AsyncDevice) -> None: print("── cloud app install demo: start ──") if Path(APK).is_file(): # Step 1: upload or reuse the APK in the cloud app library. - app = await upload_app(APK, billing=get_settings().MOBILERUN_BILLING) - print("app package:", app.package, "version:", app.version) + app = await Workspace(billing=get_settings().MOBILERUN_BILLING).upload_app(APK) + print( + "app package:", app.identity.app_id, "version:", app.identity.version_name + ) # Step 2: install, then remove it from the cloud phone only. - await cloud.install_app(app) - await cloud.uninstall_app(app.package) + await cloud.install_app(app.identity) + await cloud.uninstall_app(app.identity.app_id) else: print("Set MOBILERUN_SMOKE_APK to an existing APK to run the install demo.") print("── cloud app install demo: done ──") @@ -187,13 +213,23 @@ async def cloud_app_install_demo(cloud: Device) -> None: # ════════════════════════════════════════════════════════════════════════════ -async def new_cloud_device_demo() -> None: +async def new_cloud_device_demo(run: AsyncMobilerun) -> None: print("── new cloud device demo: start ──") if NEW_CLOUD_DEVICE: # Step 1: the phone is automatically terminated when the context ends. - async with CloudDevice(billing="paid") as fresh: + settings = get_settings() + proxy = await CloudRotatingProxy.select(settings.MOBILERUN_CLOUD_PROXY_COUNTRY) + async with await run.create_cloud( + plan=BillingPolicy.cloud_phone_plan( + "minute", billing=settings.MOBILERUN_BILLING + ), + keep=False, + proxy=proxy.as_device_proxy(), + ) as fresh: print("new cloud device:", fresh.device_id) - Path("fresh-cloud-screenshot.png").write_bytes(await fresh.screenshot()) + Path("fresh-cloud-screenshot.png").write_bytes( + await fresh.screenshot_bytes() + ) else: print("new cloud device: skip (NEW_CLOUD_DEVICE is False)") print("── new cloud device demo: done ──") @@ -204,56 +240,55 @@ async def new_cloud_device_demo() -> None: # ════════════════════════════════════════════════════════════════════════════ -async def emulator_demo() -> None: +async def emulator_demo(run: AsyncMobilerun) -> None: print("── emulator demo: start ──") if ANDROID_AVD: # Step 1: a running AVD is reused; otherwise the configured AVD starts. - emulator = await AndroidDevice(avd=ANDROID_AVD) - try: - Path("emulator-screenshot.png").write_bytes(await emulator.screenshot()) - finally: - await emulator.close() + async with await run.start_emulator(ANDROID_AVD) as emulator: + Path("emulator-screenshot.png").write_bytes( + await emulator.screenshot_bytes() + ) else: print("emulator: skip (set MOBILERUN_ANDROID_DEVICE_TYPE)") print("── emulator demo: done ──") -async def agent_demo(cloud: Device) -> None: +async def agent_demo(cloud: AsyncDevice, operator: "Operator") -> None: # Ask the cloud agent to act, check the result, and return typed output. - if AGENT: - result = await cloud.do("Open the Battery settings") - print("do:", result.success) - result = await cloud.expect("The Battery settings are open") - print("expect:", result.passed) - result = await cloud.do("Find the Android version", output=AndroidVersion) - if result.success and result.output: - print("Android version:", result.output.version) - else: - print(f"typed output: failed ({result.answer})") + opened: ExecutionResult[BaseModel] = await operator.do( + cloud, "Open the Battery settings" + ) + print("do:", opened.success) + check = await operator.expect(cloud, "The Battery settings are open") + print("expect:", check.passed) + result = await operator.do(cloud, "Find the Android version", output=AndroidVersion) + if result.success and result.output: + print("Android version:", result.output.version) + else: + print(f"typed output: failed ({result.answer})") # ════════════════════════════════════════════════════════════════════════════ -# POOL DEMO: one call runs on both devices at the same time +# MULTI-DEVICE DEMO: loop explicitly over borrowed devices and their operators # ════════════════════════════════════════════════════════════════════════════ -async def pool_demo(device: Device, cloud: Device) -> None: - print("── pool demo: start ──") - - # Step 1: group both devices into a pool. - pool = DevicePool([device, cloud]) - - # Step 2: every pool call runs on all devices and returns one result each. - images = await pool.screenshot() - print("pool screenshots:", len(images)) - await pool.press_button("home") - - # Step 3 (AGENT only): each device uses its own operator. - if AGENT: - print("pool do:", await pool.do("Open the Settings app")) - print("pool expect:", await pool.expect("The Settings app is open")) - - print("── pool demo: done ──") +async def multiple_devices_demo( + devices: tuple[tuple[AsyncDevice, "Operator | None"], ...], +) -> None: + print("── multi-device demo: start ──") + images = [] + for device, operator in devices: + images.append(await device.screenshot_bytes()) + await device.key("home") + if operator is not None: + result: ExecutionResult[BaseModel] = await operator.do( + device, "Open the Settings app" + ) + check = await operator.expect(device, "The Settings app is open") + print("device do:", result.success, "expect:", check.passed) + print("screenshots:", len(images)) + print("── multi-device demo: done ──") def sandbox_and_skills() -> None: @@ -264,44 +299,70 @@ def sandbox_and_skills() -> None: print("skills:", [skill.name for skill in list_skills()]) -async def local_demos(device: Device) -> None: +async def local_demos(device: AsyncDevice) -> None: await local_basics(device) await macro_demo(device) await credentials_demo(device) await local_app_install_demo(device) -async def cloud_demos(cloud: Device) -> None: +async def cloud_demos(cloud: AsyncDevice, operator: "Operator | None") -> None: await cloud_basics(cloud) - await agent_demo(cloud) + if operator is not None: + await agent_demo(cloud, operator) await vault_demo() await cloud_app_install_demo(cloud) -async def main() -> None: - # Connect to both devices. - if AGENT: - device = AndroidDevice(LOCAL_SERIAL, operator=AgentOperator()) - else: - device = AndroidDevice(LOCAL_SERIAL) - cloud = CloudDevice(CLOUD_DEVICE_ID) - await device._ensure_connected() - await cloud._ensure_connected() +async def offline() -> None: sandbox_and_skills() - - # Run both devices at once, keeping each device's demos in order. - await asyncio.gather(local_demos(device), cloud_demos(cloud)) - - # The pool uses both devices, so run it after their individual demos. - await pool_demo(device, cloud) - await new_cloud_device_demo() - await emulator_demo() - - -def cli(argv: list[str] | None = None) -> None: + async with fake_device() as device: + await credentials_demo(device) + + +async def main(*, serial: str | None = None, cloud_device: str | None = None) -> None: + async with AsyncExitStack() as stack: + run = await stack.enter_async_context( + AsyncMobilerun( + bearer=LoginStore.from_settings().resolve_api_key(), + base_url=get_settings().MOBILERUN_CLOUD_BASE_URL, + hitl_gate=cli_hitl_gate(yes=True), # The demo prompt already approved. + ) + ) + device = await run.connect( + await run.local.select_android(serial), backend="local-android-adb" + ) + cloud = await run.connect( + await choose_cloud(run, cloud_device), backend="cloud" + ) + local_operator = cloud_operator = None + if AGENT: + sdk = await stack.enter_async_context( + cloud_client(billing=get_settings().MOBILERUN_BILLING) + ) + local_operator = AgentOperator() + cloud_operator = CloudTaskOperator(client=sdk) + sandbox_and_skills() + + # Run both devices at once, keeping each device's demos in order. + async with asyncio.TaskGroup() as demos: + demos.create_task(local_demos(device)) + demos.create_task(cloud_demos(cloud, cloud_operator)) + + await multiple_devices_demo(((device, local_operator), (cloud, cloud_operator))) + await new_cloud_device_demo(run) + await emulator_demo(run) + + +def cli(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) + add_mode(parser) + parser.add_argument("--serial", help="Local Android serial") + parser.add_argument("--cloud-device", help="Existing cloud device ID") parser.add_argument("--yes", action="store_true", help="Approve paid usage") args = parser.parse_args(argv) + if not args.live: + return run_live(offline()) if not args.yes: costs = "Cloud task and LLM use can cost money" if NEW_CLOUD_DEVICE: @@ -312,11 +373,11 @@ def cli(argv: list[str] | None = None) -> None: answer = "" if answer.strip().lower() not in {"y", "yes"}: print("Cancelled.") - return + return 0 logging.basicConfig(level=logging.WARNING, format="%(message)s") logging.getLogger("mobilerun.actions").setLevel(logging.INFO) - asyncio.run(main()) + return run_live(main(serial=args.serial, cloud_device=args.cloud_device)) if __name__ == "__main__": - cli() + sys.exit(cli()) diff --git a/tests/demos/macro_demo.py b/tests/demos/macro_demo.py index 4b4c877a7..49c459f3a 100644 --- a/tests/demos/macro_demo.py +++ b/tests/demos/macro_demo.py @@ -1,10 +1,10 @@ -"""Record and replay Android actions without AI or cloud charges. +"""Record, build, and replay a macro. -Requires a local Android emulator with Portal installed. Run: -python -m tests.demos.macro_demo [--serial emulator-5554] +Run `python -m tests.demos.macro_demo [--fake | --device ID]`. +Without a flag, use ANDROID_SERIAL, the saved device, or an interactive picker. +If no target is configured and the terminal is noninteractive, run offline. """ -import argparse import asyncio import sys from pathlib import Path @@ -12,28 +12,92 @@ if __package__ in (None, ""): sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) -from mobilerun.core.devices import AndroidDevice, RecordingDevice # noqa: E402 -from mobilerun.macro import MacroPlayer, build_macro, load_macro # noqa: E402 +import click # noqa: E402 +from mobilerun_core import ( + Action, + AsyncDevice, + DeviceDisconnectedError, + PortalUnavailable, +) # noqa: E402 +from mobilerun.cli.base.menu import is_interactive # noqa: E402 +from mobilerun.cli.devices.base.device import device_command # noqa: E402 +from mobilerun.cli.devices.utils.connection.default import device_target # noqa: E402 +from mobilerun.cli.devices.utils.labels import display_label # noqa: E402 +from mobilerun.config.loader import ConfigLoader # noqa: E402 +from mobilerun.core.runs import ActionRecording # noqa: E402 +from mobilerun.core.screen import ScreenProvider # noqa: E402 +from mobilerun.macro import ( + MacroPlayer, + MacroStep, + build_macro, + load_macro, +) # noqa: E402 +from mobilerun.models import RunStep # noqa: E402 +from mobilerun.models.screen import ScreenView # noqa: E402 +from tests.support.devices import fake_device # noqa: E402 -async def main(serial: str = "emulator-5554") -> None: - device = AndroidDevice(serial) - async with device: - await device.press_button("home") - recorded = RecordingDevice(device, capture="actions") - await recorded.start_app("com.android.settings") - await recorded.tap(200, 200) - await recorded.press_button("home") - recorded.finish("succeeded") - assert recorded.run_dir is not None - path = build_macro(recorded.run_dir / "steps.jsonl", "settings-demo") - print("macro version:", path) - await MacroPlayer(device).replay_macro(load_macro(path)) + +async def main(phone: AsyncDevice) -> None: + """Record and replay a short Settings workflow on the supplied phone.""" + # ScreenProvider projects the native Observation into a redacted ScreenView. + view: ScreenView = (await ScreenProvider(phone).observe(screenshot=False)).ui + click.echo(f"Screen view: {len(view.elements)} elements") + + # The recorder uses core's before/after action hooks on the original device. + async with ActionRecording(phone) as rec: + await phone.key("home") + await phone.start_app("com.android.settings") + await phone.tap(200, 200) + await phone.key("home") + rec.finish("succeeded") + steps_path = rec.run_dir / "steps.jsonl" + click.echo(f"Recorded {rec.step_index} actions: {steps_path}") + + # Preview the same run-to-macro conversion that build_macro uses. + with steps_path.open(encoding="utf-8") as rows: + first = RunStep.model_validate_json(next(rows)) + action: Action = MacroStep.from_run_step(first).action + path = build_macro(steps_path, "settings-demo") + click.echo(f"Built macro: {path} (starts with {action.scope}:{action.name})") + + player = MacroPlayer(phone, delay_between_actions=0) + await player.replay_macro(load_macro(path)) + click.echo(f"Replayed {player.executed_steps} actions") + + +@click.command() +@click.option("--device", help="Device to record and replay on.") +@click.option("--fake", is_flag=True, help="Run offline without opening a device.") +@click.pass_context +def cli(ctx: click.Context, device: str | None, fake: bool) -> None: + """Record, build, and replay a short Settings macro.""" + if fake and device: + raise click.UsageError("Use --fake or --device, not both.") + target = None if fake else device_target(device, ConfigLoader.load().device)[0] + if fake or (target is None and not is_interactive()): + asyncio.run(offline()) + return + try: + ctx.invoke(live, device_option=device) + except (DeviceDisconnectedError, PortalUnavailable, ConnectionError, TimeoutError): + label = f"Device {display_label(target)}" if target else "Selected device" + raise click.ClickException( + f"{label} is not reachable; start it or run `mobilerun device connect`." + ) from None + + +async def offline() -> None: + async with fake_device() as phone: + await main(phone) + + +@click.command() +@device_command +async def live(device: AsyncDevice) -> None: + """Record and replay on a connected Android device with Settings installed.""" + await main(device) if __name__ == "__main__": - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument( - "--serial", default="emulator-5554", help="Local Android device serial" - ) - asyncio.run(main(parser.parse_args().serial)) + cli() diff --git a/tests/demos/mailbox_demo.py b/tests/demos/mailbox_demo.py index 347583b0a..6a5c85382 100644 --- a/tests/demos/mailbox_demo.py +++ b/tests/demos/mailbox_demo.py @@ -1,13 +1,11 @@ """Create a mailbox and wait for an emailed code. -The public mailbox API exposes code polling, not sending mail or message -contents (sender, subject, and body). Send a message containing a code from -another email account. A mailbox costs money. Run: python -m tests.demos.mailbox_demo. +No phone is needed. Send an email containing a code from another account. +A mailbox can cost money. Run: python -m tests.demos.mailbox_demo. Authenticate with MOBILERUN_API_KEY or mobilerun account login. """ import argparse -import asyncio import sys from datetime import datetime, timezone from pathlib import Path @@ -18,6 +16,7 @@ from mobilerun.core.mailbox import CloudMailbox from mobilerun.errors import PaymentRequired from tests.demos.demo_billing import add_billing, billing_value, confirmation +from tests.support.demo_cli import add_mode, run_live async def main(args: argparse.Namespace) -> None: @@ -49,8 +48,8 @@ async def main(args: argparse.Namespace) -> None: code = await mailbox.wait_for_code(timeout=args.timeout, after=after) print(f"Received code: {code}") finally: + await mailbox.close() if not args.keep: - await mailbox.release() print(f"Released mailbox {mailbox.id}.") else: print(f"Kept mailbox {mailbox.id}; it may continue to incur charges.") @@ -58,6 +57,7 @@ async def main(args: argparse.Namespace) -> None: def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) + add_mode(parser) parser.add_argument( "--yes", action="store_true", help="skip paid resource confirmation" ) @@ -78,4 +78,7 @@ def parse_args() -> argparse.Namespace: if __name__ == "__main__": - asyncio.run(main(parse_args())) + args = parse_args() + if args.live: + sys.exit(run_live(main(args))) + print("Offline preview: create a mailbox, wait for a code, then close it.") diff --git a/tests/demos/phone_demo.py b/tests/demos/phone_demo.py index 209bb2cfa..f11c2f340 100644 --- a/tests/demos/phone_demo.py +++ b/tests/demos/phone_demo.py @@ -1,43 +1,60 @@ """Rent a phone number and wait for an SMS code. -The number may cost money; --bind also creates a cloud phone. Run: -python -m tests.demos.phone_demo [--country US] [--bind] [--yes] +The number may cost money; --bind also creates a temporary cloud phone. +Use --number-id to read an existing number without releasing it. Run: +python -m tests.demos.phone_demo [--country US | --number-id ID] [--bind] [--yes] """ import argparse -import asyncio import sys from pathlib import Path if __package__ in (None, ""): sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) -from mobilerun.core.devices import CloudDevice # noqa: E402 +from mobilerun_core import ConnectProxyRef # noqa: E402 + +from mobilerun.cli.devices.base.selection import open_client # noqa: E402 +from mobilerun.cli.devices.utils.approval import cli_hitl_gate # noqa: E402 +from mobilerun.clients.cloud.billing_policy import BillingPolicy # noqa: E402 +from mobilerun.config.settings import get_settings # noqa: E402 from mobilerun.core.phone_number import CloudPhoneNumber # noqa: E402 +from mobilerun.core.proxy import CloudRotatingProxy # noqa: E402 from mobilerun.errors import PaymentRequired, PurchaseInProgress # noqa: E402 from tests.demos.demo_billing import ( # noqa: E402 add_billing, billing_value, - check_phone_plan, confirmation, + temporary_phone_plan, ) +from tests.support.demo_cli import add_mode, run_live # noqa: E402 + + +async def select_phone_proxy() -> ConnectProxyRef: + """Use existing residential capacity; never purchase a proxy implicitly.""" + country = get_settings().MOBILERUN_CLOUD_PROXY_COUNTRY + proxy = await CloudRotatingProxy.select(country) + return proxy.as_device_proxy() + + +async def receive_code(number: CloudPhoneNumber, timeout: float) -> None: + print(f"Send an SMS with a code to {number.phone_number} …") + code = await number.wait_for_code(timeout=timeout) + print(f"Received code: {code}") async def main(args: argparse.Namespace) -> None: billing = billing_value(getattr(args, "billing", None)) plan = getattr(args, "phone_plan", getattr(args, "plan", None)) number_plan = getattr(args, "number_plan", None) - if args.bind: - check_phone_plan(billing, plan) - print( - f"Billing: {billing.value}; number plan: {number_plan or 'auto'}" - + ( - f"; phone plan: {plan or ('subscription' if billing == 'included' else 'auto')}" - if args.bind - else "" - ) - ) - if not args.yes: + number_id = args.number_id + if number_id == "": + raise ValueError("--number-id must not be empty") + phone_plan = temporary_phone_plan(billing, plan) if args.bind else None + number_choice = "existing" if number_id else number_plan or "auto" + phone_choice = f"; phone plan: {phone_plan}" if phone_plan else "" + print(f"Billing: {billing.value}; number plan: {number_choice}{phone_choice}") + if (phone_plan or not number_id) and not args.yes: try: answer = input(confirmation(billing)) except EOFError: @@ -45,14 +62,19 @@ async def main(args: argparse.Namespace) -> None: if answer.strip().lower() not in {"y", "yes"}: print("Cancelled.") return + # Resolve capacity before renting a number so a missing proxy cannot cause a charge. + proxy = await select_phone_proxy() if phone_plan else None try: - number = await CloudPhoneNumber( - country=args.country or "US", - billing=billing, - **({"plan": number_plan} if number_plan is not None else {}), - checkout="print", - keep=args.keep, - ) + if number_id: + number = await CloudPhoneNumber(number_id=number_id, billing=billing) + else: + number = await CloudPhoneNumber( + country=args.country or "US", + billing=billing, + **({"plan": number_plan} if number_plan is not None else {}), + checkout="print", + keep=args.keep, + ) except (PaymentRequired, PurchaseInProgress) as exc: print(str(exc)) if exc.checkout: @@ -63,40 +85,50 @@ async def main(args: argparse.Namespace) -> None: await number.wait_ready() if not number.phone_number: raise RuntimeError("The active number has no phone number") - if args.bind: - async with CloudDevice(billing=billing, plan=plan) as phone: + if phone_plan is not None and proxy is not None: + async with open_client( + hitl_gate=cli_hitl_gate(yes=True), cloud=True + ) as run: + phone = await run.create_cloud( + plan=BillingPolicy.cloud_phone_plan(phone_plan, billing=billing), + proxy=proxy, + ) + await number.attach(phone) try: - await number.bind(phone) - print(f"phone.number is number: {phone.number is number}") - print(f"phone.sms is number: {phone.sms is number}") - print(f"Send an SMS with a code to {number.phone_number} …") - code = await number.wait_for_code(timeout=args.timeout) - print(f"Received code: {code}") + print( + f"Attached number {number.id} to cloud phone {phone.device_id}." + ) + await receive_code(number, args.timeout) finally: - await number.unbind() + await number.detach() else: - print(f"Send an SMS with a code to {number.phone_number} …") - code = await number.wait_for_code(timeout=args.timeout) - print(f"Received code: {code}") + await receive_code(number, args.timeout) finally: - if getattr(number, "resumed_existing", False) is True: + await number.close() + if number_id or number.resumed_existing: print(f"Preserved existing number {number.id}; it may keep costing.") elif args.keep: print(f"Kept number {number.id}; it may keep costing.") else: - await number.release() print(f"Released number {number.id}.") def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--country", help="Country code (default: US)") + add_mode(parser) + selection = parser.add_mutually_exclusive_group() + selection.add_argument("--country", help="Country code (default: US)") + selection.add_argument( + "--number-id", help="Use an existing number without releasing it" + ) parser.add_argument("--yes", action="store_true", help="Approve paid resources") parser.add_argument( "--keep", action="store_true", help="Keep the number after the demo" ) parser.add_argument( - "--bind", action="store_true", help="Create a cloud phone and bind the number" + "--bind", + action="store_true", + help="Create a temporary cloud phone and attach the number", ) parser.add_argument( "--timeout", type=float, default=180, help="Code wait timeout in seconds" @@ -106,7 +138,7 @@ def parse_args() -> argparse.Namespace: "--phone-plan", "--plan", choices=("auto", "minute", "subscription"), - help="Cloud phone plan (requires --bind)", + help="Cloud phone plan (requires --bind; temporary phones require minute)", ) parser.add_argument( "--number-plan", @@ -115,8 +147,10 @@ def parse_args() -> argparse.Namespace: ) args = parser.parse_args() try: + if args.number_id and args.number_plan: + parser.error("--number-plan is only for renting a new number") if args.bind: - check_phone_plan(billing_value(args.billing), args.phone_plan) + temporary_phone_plan(billing_value(args.billing), args.phone_plan) elif args.phone_plan: parser.error("--phone-plan requires --bind") except ValueError as exc: @@ -125,4 +159,7 @@ def parse_args() -> argparse.Namespace: if __name__ == "__main__": - asyncio.run(main(parse_args())) + args = parse_args() + if args.live: + sys.exit(run_live(main(args))) + print("Offline preview: rent or reuse a number and wait for an SMS code.") diff --git a/tests/demos/proxy_demo.py b/tests/demos/proxy_demo.py index ac9f333ac..f86554895 100644 --- a/tests/demos/proxy_demo.py +++ b/tests/demos/proxy_demo.py @@ -1,39 +1,54 @@ """Switch an existing cloud phone to another proxy, without creating a phone. -Run with ``python -m tests.demos.proxy_demo``. Selecting an existing -proxy is free; ``--country`` may purchase proxy capacity and requires approval. +Run with ``python -m tests.demos.proxy_demo``. Selecting an existing proxy is +free. If ``--country`` needs to buy capacity, the switch is temporary: restore +the original proxy before releasing the new one. """ import argparse import asyncio import sys from pathlib import Path -from typing import cast if __package__ in (None, ""): sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) -from mobilerun.clients.cloud import devices, proxies # noqa: E402 -from mobilerun.core.devices import CloudDevice -from mobilerun.core.proxy import ( +from mobilerun_core import ( + AsyncDevice, + ConnectProxyRef, + HitlDenied, + ProxyOperationError, +) # noqa: E402 + +from mobilerun.cli.devices.base.selection import open_client # noqa: E402 +from mobilerun.cli.devices.utils.approval import cli_hitl_gate # noqa: E402 +from mobilerun.core.proxy import ( # noqa: E402 CloudFixedProxy, - CloudProxy, CloudRotatingProxy, - Proxy, + list_connect_proxies, +) +from mobilerun.models import Billing # noqa: E402 +from tests.demos.demo_billing import ( + add_billing, + billing_value, + confirmation, ) # noqa: E402 -from mobilerun.errors import ProxyNotActive # noqa: E402 -from mobilerun.models import Billing -from tests.demos.demo_billing import add_billing, billing_value, confirmation +from tests.support.demo_cli import add_mode, choose_cloud, run_live # noqa: E402 def arguments(argv: list[str] | None = None) -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("--name", default="tester1", help="Existing phone name") + add_mode(parser) + target = parser.add_mutually_exclusive_group() + target.add_argument("--name", help="Existing phone name") + target.add_argument("--cloud-device", help="Existing cloud device ID") selection = parser.add_mutually_exclusive_group() selection.add_argument("--proxy-id", help="Existing active Connect proxy ID") selection.add_argument("--country", help="Country code; may incur charges") parser.add_argument( - "--yes", action="store_true", help="Approve country proxy charges" + "--yes", + action="store_true", + help="Approve proxy changes and any country proxy charges", ) add_billing(parser) return parser.parse_args(argv) @@ -41,6 +56,9 @@ def arguments(argv: list[str] | None = None) -> argparse.Namespace: async def main(argv: list[str] | None = None) -> int: args = arguments(argv) + if not args.live: + print("Offline preview: switch a borrowed phone to another Connect proxy.") + return 0 billing = billing_value(args.billing) if args.country and billing != Billing.PAID: print("Country proxy selection requires --billing paid.", file=sys.stderr) @@ -55,86 +73,113 @@ async def main(argv: list[str] | None = None) -> int: print("Cancelled; no proxy was changed.", file=sys.stderr) return 1 - phones = await devices.list_devices(billing=Billing.NO_COMMERCE) - matches = [item for item in phones if item.name == args.name] - if len(matches) != 1: - names = ", ".join(str(item.name) for item in phones) or "(none)" - print( - f"Phone {args.name!r} not found or not unique. Available: {names}", - file=sys.stderr, - ) - return 1 - - phone = await CloudDevice(device_id=matches[0].id, billing=billing) - try: - status = await cast(CloudProxy, phone.proxy).status() - old = status.name or "unknown" - print( - f"{args.name}: current proxy {old} ({'connected' if status.connected else 'disconnected'})" - ) - items = [] - page = 1 - while True: - result = await proxies.list_proxies( - billing=Billing.NO_COMMERCE, page=page, page_size=100 - ) - items.extend(result.items) - if not result.pagination.has_next: - break - page += 1 - for item in items: - print(f" {item.id}: {item.name} ({item.country}, {item.status})") - current = ( - [item for item in items if item.name == status.name] if status.name else [] - ) - if len(current) == 1: - old = f"{current[0].id} ({current[0].country})" - print(f"Current proxy: {old}") - if args.country: - proxy: Proxy = CloudRotatingProxy(country=args.country) - target = args.country - else: - if status.connected and len(current) != 1: - print( - "Cannot identify the current proxy uniquely; refusing to switch.", - file=sys.stderr, - ) - return 1 - options = [ - item - for item in items - if item.status == "active" and (not current or item.id != current[0].id) - ] - chosen = next( - ( - item - for item in options - if not args.proxy_id or item.id == args.proxy_id - ), - None, - ) - if chosen is None: + async with open_client( + cloud=True, hitl_gate=cli_hitl_gate(yes=args.yes or bool(args.country)) + ) as run: + if args.name: + phones = await run.list_cloud_devices() + matches = [item for item in phones if item.name == args.name] + if len(matches) != 1: + names = ", ".join(str(item.name) for item in phones) or "(none)" print( - "No active alternative proxy available for that selection.", + f"Phone {args.name!r} not found or not unique. Available: {names}", file=sys.stderr, ) return 1 - proxy = CloudFixedProxy(id=chosen.id) - target = f"{chosen.id} ({chosen.country})" + identifier = matches[0].device_id + else: + identifier = await choose_cloud(run, args.cloud_device) + phone = await run.connect(identifier, backend="cloud") + args.name = args.name or "Selected phone" try: - await proxy.bind(phone, force=True) - new_status = await cast(CloudProxy, phone.proxy).status() - except ProxyNotActive as exc: - print(f"Proxy switch failed: proxy not active ({exc})", file=sys.stderr) + return await switch_proxy(phone, args, billing) + except (HitlDenied, ProxyOperationError) as exc: + print(f"Proxy switch failed: {exc}", file=sys.stderr) return 1 - new = new_status.name or target if args.country else target + + +async def switch_proxy( + phone: AsyncDevice, args: argparse.Namespace, billing: Billing +) -> int: + status = await phone.proxy_status() + old = status.reference or "unknown" + print( + f"{args.name}: current proxy {old} ({'connected' if status.connected else 'disconnected'})" + ) + items = [item async for item in list_connect_proxies(billing=Billing.NO_COMMERCE)] + for item in items: + print(f" {item.ref.id}: {item.name} ({item.country}, {item.status})") + if status.connected and status.reference is None: + print("Cannot identify the current proxy; refusing to switch.", file=sys.stderr) + return 1 + options = [ + item + for item in items + if item.status == "active" and item.ref.id != status.reference + ] + if args.country: + options = [ + item + for item in options + if item.country.lower() == args.country.lower() + and item.type == "residential" + ] + chosen = next( + (item for item in options if not args.proxy_id or item.ref.id == args.proxy_id), + None, + ) + if chosen is not None: + proxy = CloudFixedProxy(chosen.ref, device=phone) + await proxy.apply(replace=True) + new_status = await proxy.status() print( - f"{args.name}: proxy {old} → {new} ({'connected' if new_status.connected else 'disconnected'})" + f"{args.name}: proxy {old} → {chosen.ref.id} ({chosen.country}, " + f"{'connected' if new_status.connected else 'disconnected'})" ) return 0 + if not args.country: + print( + "No active alternative proxy available for that selection.", file=sys.stderr + ) + return 1 + if status.reference is None or not any( + item.ref.id == status.reference and item.status == "active" for item in items + ): + print( + "Cannot restore the previous proxy after a purchase; refusing to buy.", + file=sys.stderr, + ) + return 1 + + previous = CloudFixedProxy(ConnectProxyRef(status.reference), device=phone) + purchased = await CloudRotatingProxy.purchase( + args.country, device=phone, billing=billing + ) + try: + await purchased.apply(replace=True) + print( + f"{args.name}: temporarily switched {old} → {purchased.id} ({args.country})." + ) finally: - await phone.close() + try: + current = await phone.proxy_status() + if current.reference == purchased.id: + await previous.apply(replace=True) + print(f"Restored proxy {old}.") + elif current.reference is None: + raise ProxyOperationError( + "Cannot confirm that the purchased proxy is detached" + ) + await purchased.close() + print(f"Released proxy {purchased.id}.") + except (Exception, asyncio.CancelledError): + print( + f"Check phone routing and release purchased proxy {purchased.id} if unused.", + file=sys.stderr, + ) + raise + return 0 if __name__ == "__main__": - sys.exit(asyncio.run(main())) + sys.exit(run_live(main())) diff --git a/tests/demos/task_demo.py b/tests/demos/task_demo.py index b6b788d45..4db452a95 100644 --- a/tests/demos/task_demo.py +++ b/tests/demos/task_demo.py @@ -4,39 +4,56 @@ """ import argparse -import asyncio import logging import sys from pathlib import Path +from typing import TYPE_CHECKING if __package__ in (None, ""): sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) -from pydantic import BaseModel +from mobilerun_core import AsyncMobilerun # noqa: E402 +from pydantic import BaseModel # noqa: E402 -from mobilerun.core.devices import CloudDevice -from mobilerun.core.proxy import CloudRotatingProxy -from mobilerun.models import Billing -from tests.demos.demo_billing import ( +from mobilerun.cli.devices.utils.approval import cli_hitl_gate # noqa: E402 +from mobilerun.clients.cloud.billing_policy import BillingPolicy # noqa: E402 +from mobilerun.clients.cloud.client import cloud_client # noqa: E402 +from mobilerun.clients.local.login_store import LoginStore # noqa: E402 +from mobilerun.config.settings import get_settings # noqa: E402 +from mobilerun.core.operator.cloud import CloudTaskOperator # noqa: E402 +from mobilerun.core.proxy import CloudRotatingProxy # noqa: E402 +from mobilerun.models import Billing # noqa: E402 +from tests.demos.demo_billing import ( # noqa: E402 add_billing, billing_value, check_phone_plan, confirmation, ) +from tests.support.demo_cli import add_mode, run_live # noqa: E402 + +if TYPE_CHECKING: + from mobilerun.models.results import ExecutionResult class AndroidVersion(BaseModel): version: str +def check_temporary_phone_plan(billing: Billing, plan: str | None) -> None: + """Validate billing before any allocation; the demo must terminate its phone.""" + check_phone_plan(billing, plan) + if billing != Billing.PAID or plan not in (None, "minute"): + raise ValueError( + "A temporary phone can only be terminated with --billing paid --plan minute" + ) + + async def main( yes: bool = False, billing: Billing | None = None, plan: str | None = None ) -> None: billing = billing_value(billing) - check_phone_plan(billing, plan) - print( - f"Billing: {billing.value}; phone plan: {plan or ('subscription' if billing == 'included' else 'auto')}" - ) + check_temporary_phone_plan(billing, plan) + print(f"Billing: {billing.value}; phone plan: minute") if not yes: try: answer = input(confirmation(billing)) @@ -47,39 +64,58 @@ async def main( return print("── cloud phone demo: start ──") - # Step 1: Create a temporary phone with an explicit US proxy. - # The phone is terminated automatically. - # Pass country="DE" to select the device's country. - proxy = CloudRotatingProxy(country="US") - async with CloudDevice( - name="cloud-phone-demo", - billing=billing, - plan=plan, - proxy=proxy, - ) as phone: - print("phone:", phone.device_id) - status = await proxy.status() - print("proxy connected:", status.connected) - print("proxy country requested: US") - - # Step 2: Use the default cloud task operator to open Settings. - # Pass operator=AgentOperator() to use your local agent instead. - result = await phone.do("Open the Settings app") - print("open task:", result.task_id) - check = await phone.expect("The Settings app is open") - print("expect task:", check.task.task_id) - - # Step 3: Ask for typed output, then run a task with a timeout. - result = await phone.do("Find the Android version", output=AndroidVersion) - print("version task:", result.task_id) - if result.output is None: - raise RuntimeError("Android version task returned no output") - print("Android version:", result.output.version) - result = await phone.do("Return to the main Settings screen", timeout=120) - print("timed task:", result.task_id) - - # Step 4: Return home before automatic termination. - await phone.press_button("home") + # Step 1: Reuse or buy a US proxy, then create a temporary cloud phone. + try: + proxy = await CloudRotatingProxy.select("US", billing=billing) + except LookupError: + proxy = await CloudRotatingProxy.purchase("US", billing=billing) + try: + async with ( + AsyncMobilerun( + bearer=LoginStore.from_settings().resolve_api_key(), + base_url=get_settings().MOBILERUN_CLOUD_BASE_URL, + hitl_gate=cli_hitl_gate(yes=True), # Already approved above. + ) as run, + cloud_client(billing=billing) as client, + await run.create_cloud( + name="cloud-phone-demo", + plan=BillingPolicy.cloud_phone_plan("minute", billing=billing), + keep=False, + proxy=proxy.as_device_proxy(), + ) as phone, + ): + print("phone:", phone.device_id) + status = await phone.proxy_status() + print("proxy connected:", status.connected) + print("proxy country requested: US") + + # Step 2: Use the cloud task operator to open and check Settings. + operator = CloudTaskOperator(client=client, billing=billing) + opened: ExecutionResult[BaseModel] = await operator.do( + phone, "Open the Settings app" + ) + print("open task:", opened.task_id) + check = await operator.expect(phone, "The Settings app is open") + print("expect task:", check.task.task_id) + + # Step 3: Ask for typed output, then run a task with a timeout. + version = await operator.do( + phone, "Find the Android version", output=AndroidVersion + ) + print("version task:", version.task_id) + if version.output is None: + raise RuntimeError("Android version task returned no output") + print("Android version:", version.output.version) + timed: ExecutionResult[BaseModel] = await operator.do( + phone, "Return to the main Settings screen", timeout=120 + ) + print("timed task:", timed.task_id) + + # Step 4: Return home before automatic termination. + await phone.key("home") + finally: + # The phone closes first. Closing a selected proxy preserves it. + await proxy.close() print("── cloud phone demo: done ──") @@ -87,11 +123,20 @@ async def main( logging.basicConfig(level=logging.WARNING, format="%(message)s") logging.getLogger("mobilerun.actions").setLevel(logging.INFO) parser = argparse.ArgumentParser(description=__doc__) + add_mode(parser) parser.add_argument("--yes", action="store_true", help="Approve paid cloud usage") add_billing(parser, plan=True) args = parser.parse_args() + if not args.live: + sample = AndroidVersion.model_validate_json('{"version": "15"}') + print(f"Offline typed result — Android version: {sample.version}") + sys.exit(0) try: - check_phone_plan(billing_value(args.billing), args.plan) + check_temporary_phone_plan(billing_value(args.billing), args.plan) except ValueError as exc: parser.error(str(exc)) - asyncio.run(main(yes=args.yes, billing=billing_value(args.billing), plan=args.plan)) + sys.exit( + run_live( + main(yes=args.yes, billing=billing_value(args.billing), plan=args.plan) + ) + ) diff --git a/tests/demos/vault_demo.py b/tests/demos/vault_demo.py index 07dc9615e..44c843a7a 100644 --- a/tests/demos/vault_demo.py +++ b/tests/demos/vault_demo.py @@ -1,131 +1,126 @@ """Save, use and delete a demo cloud vault credential on a local Android device. Vault access uses your cloud account; the local device is free. The demo opens -Settings search and types a non-secret username. Run: python -m tests.demos.vault_demo [--serial emulator-5554]. +Settings search and types a demo username. Use --live to run against a device. """ import argparse -import asyncio import sys +from contextlib import AsyncExitStack from pathlib import Path from uuid import uuid4 if __package__ in (None, ""): sys.path.insert(0, str(Path(__file__).resolve().parent.parent.parent)) -from mobilerun.core.credentials import CloudCredentials # noqa: E402 -from mobilerun.core.devices import AndroidDevice # noqa: E402 +from mobilerun_core import AsyncDevice, AsyncMobilerun, Element # noqa: E402 + +from mobilerun.cli.devices.utils.approval import cli_hitl_gate # noqa: E402 +from mobilerun.core.credentials import ( + CloudCredentials, # noqa: E402 + DictCredentials, # noqa: E402 +) +from tests.support.demo_cli import add_mode, run_live # noqa: E402 +from tests.support.devices import FakeDriver, fake_device # noqa: E402 PACKAGE = "com.example.demo" +def search_input(elements: tuple[Element, ...]) -> Element | None: + """Find the native Settings search input when it is already open.""" + return next( + ( + item + for item in elements + if (item.class_name or "").split(".")[-1] == "EditText" + ), + None, + ) + + +async def focus_settings_search(device: AsyncDevice) -> None: + """Open Settings search if needed, then clear it and focus its input.""" + elements = (await device.observe()).elements or () + edit = search_input(elements) + if edit is None: + search = next( + ( + item + for item in elements + if any( + "search" in (value or "").lower() + for value in (item.text, item.content_description, item.resource_id) + ) + ), + None, + ) + if search is None: + raise RuntimeError("Settings search entry not found") + await device.tap_element(search) + await device.wait(1) + elements = (await device.observe()).elements or () + edit = search_input(elements) + if edit is None: + raise RuntimeError("Settings search input not found") + clear = next( + (item for item in elements if "clear" in (item.resource_id or "").lower()), + None, + ) + if clear is not None: + await device.tap_element(clear) + edit = search_input((await device.observe()).elements or ()) + if edit is None: + raise RuntimeError("Settings search input not found") + await device.tap_element(edit) + + async def main(serial: str | None = None) -> None: - vault = CloudCredentials() - device = None - bound = False - name = f"mobilerun-demo-{uuid4().hex}" - attempted_save = False - settings_open = False - try: - device = AndroidDevice(serial) - await vault.bind(device) - bound = True + async with ( + AsyncMobilerun(hitl_gate=cli_hitl_gate()) as run, + AsyncExitStack() as cleanup, + ): + serial = await run.local.select_android(serial) + device = await run.connect(serial, backend="local-android-adb") + vault = CloudCredentials(device=device) + cleanup.push_async_callback(vault.close) for credential in await vault.list(PACKAGE): print( f"{credential['package']}: {credential['name']} ({', '.join(credential['fields'])})" ) - # A unique name avoids updating or deleting anyone's existing credential. - attempted_save = True - await vault.save( - PACKAGE, name, {"username": "demo-user", "password": "demo-password"} - ) - # Settings may reopen on its previous search page or its home page. + # Clean up even if the save is applied but the response is lost. + name = f"mobilerun-demo-{uuid4().hex}" + cleanup.push_async_callback(vault.delete, PACKAGE, name) + await vault.save(PACKAGE, name, {"username": "demo-user"}) await device.start_app("com.android.settings") - settings_open = True + cleanup.push_async_callback(device.key, "home") await device.wait(1) - state = await device.state.refresh() - edit = next( - (item for item in state.elements if item.get("className") == "EditText"), - None, - ) - if edit is None: - search = next( - ( - item - for item in state.elements - if "search" - in " ".join( - str(item.get(key, "")) - for key in ("text", "contentDescription", "resourceId") - ).lower() - and "index" in item - ), - None, - ) - if search is None: - raise RuntimeError("Settings search entry not found") - await device.tap_element(search["index"]) - await device.wait(1) - state = await device.state.refresh() - edit = next( - ( - item - for item in state.elements - if item.get("className") == "EditText" - ), - None, - ) - if edit is None: - raise RuntimeError("Settings search input not found") - clear = next( - ( - item - for item in state.elements - if "clear" in str(item.get("resourceId", "")).lower() - and "index" in item - ), - None, - ) - if clear is not None: - await device.tap_element(clear["index"]) - state = await device.state.refresh() - edit = next( - ( - item - for item in state.elements - if item.get("className") == "EditText" - ), - None, - ) - if edit is None or "index" not in edit: - raise RuntimeError("Settings search input not found") - await device.tap_element(edit["index"]) - await vault.type_field(PACKAGE, "username", name=name) - state = await device.state.refresh() + await focus_settings_search(device) + await vault.type_secret(name, package=PACKAGE, field="username") + state = await device.observe() if state.focused_text != "demo-user": raise RuntimeError("Demo username was not visible in the focused field") print(f"Field now contains: {state.focused_text}") - finally: - try: - if settings_open and device is not None: - await device.press_button("home") - finally: - try: - if attempted_save: - await vault.delete(PACKAGE, name) - finally: - try: - if bound: - await vault.unbind() - finally: - try: - if device is not None: - await device.close() - finally: - await vault.close() -if __name__ == "__main__": +async def offline() -> None: + driver = FakeDriver() + async with fake_device(driver=driver) as device: + vault = DictCredentials( + {PACKAGE: {"demo": {"username": "demo-user"}}}, device=device + ) + async with AsyncExitStack() as cleanup: + cleanup.push_async_callback(vault.close) + await vault.type_secret("demo", package=PACKAGE, field="username") + print(f"Offline demo typed username: {driver.calls[-1][1][0]}") + + +def cli(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description=__doc__) + add_mode(parser) parser.add_argument("--serial", default=None, help="Local Android device serial") - asyncio.run(main(parser.parse_args().serial)) + args = parser.parse_args(argv) + return run_live(main(args.serial) if args.live else offline()) + + +if __name__ == "__main__": + sys.exit(cli()) diff --git a/tests/demos/webhook_static_demo.py b/tests/demos/webhook_static_demo.py index ae3dbd74a..1eafc41e4 100644 --- a/tests/demos/webhook_static_demo.py +++ b/tests/demos/webhook_static_demo.py @@ -1,12 +1,14 @@ """Minimal cloud function that sends a static result to a webhook. -Deploy (paid, device-free endpoint): - .venv/bin/python tests/demos/webhook_static_demo.py +Deploy (may charge; no phone is created or connected): + .venv/bin/python tests/demos/webhook_static_demo.py --yes Fire it: mobilerun sandbox fire webhook-static-demo The result arrives at the webhook as `workflow.step.emit` with the return value in `data.result`. """ +import argparse + from pydantic import BaseModel from mobilerun.sandbox import cloud, deploy @@ -28,4 +30,15 @@ def main(input: Input) -> Output: if __name__ == "__main__": - deploy(__file__, device_free=True, yes=True) + parser = argparse.ArgumentParser(description=__doc__) + mode = parser.add_mutually_exclusive_group() + mode.add_argument( + "--yes", action="store_true", help="Approve cloud deployment (may charge)" + ) + mode.add_argument( + "--fake", action="store_true", help="Print the local result (default)" + ) + if parser.parse_args().yes: + deploy(__file__, device_free=True, yes=True) + else: + print(main(Input()).model_dump_json()) diff --git a/tests/support/demo_cli.py b/tests/support/demo_cli.py new file mode 100644 index 000000000..8502412bf --- /dev/null +++ b/tests/support/demo_cli.py @@ -0,0 +1,77 @@ +"""CLI options and device error handling shared by standalone demos.""" + +import argparse +import asyncio +import sys +from collections.abc import Coroutine +from typing import Any + +import click +from mobilerun_core import ( + AsyncMobilerun, + CloudLifecycleError, + DeviceDisconnectedError, + PortalError, +) + +from mobilerun.cli.base.errors import safe_error_message +from mobilerun.cli.base.menu import is_interactive +from mobilerun.cli.devices.utils.connection.default import device_target +from mobilerun.cli.devices.utils.connection.device import pick_device +from mobilerun.cli.devices.utils.targets import classify_target +from mobilerun.config.loader import ConfigLoader +from mobilerun.errors.base import MobilerunError + +UNREACHABLE = ( + CloudLifecycleError, + ConnectionError, + DeviceDisconnectedError, + PortalError, +) +_DEMO_ERRORS = ( + *UNREACHABLE, + MobilerunError, + click.ClickException, + TimeoutError, + ValueError, +) + + +def add_mode(parser: argparse.ArgumentParser) -> None: + mode = parser.add_mutually_exclusive_group() + mode.add_argument( + "--live", action="store_true", help="Use real services or devices" + ) + mode.add_argument( + "--fake", action="store_true", help="Run the offline example (default)" + ) + + +def run_live(work: Coroutine[Any, Any, int | None]) -> int: + try: + return asyncio.run(work) or 0 + except* _DEMO_ERRORS as error: + cause = error.exceptions[0] + while isinstance(cause, BaseExceptionGroup): + cause = cause.exceptions[0] + if isinstance(cause, (ValueError, TimeoutError, *UNREACHABLE)): + message = ( + "Device or service is not reachable; check the target and connection." + ) + else: + message = safe_error_message(cause) + print(f"Error: {message}", file=sys.stderr) + return 1 + + +async def choose_cloud(run: AsyncMobilerun, explicit: str | None) -> str: + if explicit: + return explicit + saved, _ = device_target(None, ConfigLoader.load().device, "cloud") + if saved and classify_target(saved) == "cloud": + return saved + if not is_interactive(): + raise click.ClickException( + "Pass --cloud-device or save a cloud phone with `mobilerun device connect`." + ) + return (await pick_device(run, "cloud")).device_id diff --git a/tests/support/devices.py b/tests/support/devices.py index ef6b7a017..935929e33 100644 --- a/tests/support/devices.py +++ b/tests/support/devices.py @@ -1,48 +1,174 @@ -"""Repository in-memory Device; never connects to a phone or service.""" +"""In-memory core device fake; never connects to a phone or service.""" -from mobilerun.core.devices.base import Device +from base64 import b64decode +from collections.abc import Collection, Mapping +from copy import deepcopy +from os import PathLike +from pathlib import Path +from typing import Any +from mobilerun_core import AsyncDevice + +_PNG = b64decode( + "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAADElEQVR4nGNgYGAAAAAEAAH2FzhVAAAAAElFTkSuQmCC" +) +_SUPPORTED = frozenset( + { + "tap", + "swipe", + "drag", + "input_text", + "press_button", + "start_app", + "stop_app", + "uninstall_app", + "open_deep_link", + "get_apps", + "get_ui_tree", + "screenshot", + "push_file", + "pull_file", + "get_date", + } +) + + +class FakeDriver: + """Scriptable independent core driver; all calls are local and ordered.""" -class MemoryDevice(Device): def __init__( self, *, - identifier: str = "memory", - cloud_id: str | None = None, platform: str = "android", - supported_operations: frozenset[str] = frozenset(), + device_id: str = "memory", + supported: Collection[str] = _SUPPORTED, + ui_tree: dict[str, Any] | None = None, + screenshot_bytes: bytes = _PNG, + apps: list[dict[str, Any]] | None = None, + files: Mapping[str, bytes] | None = None, + clipboard: str = "", + failures: Mapping[str, Exception] | None = None, ) -> None: - super().__init__() - self._identifier = identifier - self._cloud_id = cloud_id - self._platform = platform - self._supported_operations = supported_operations - self.inputs: list[str] = [] + self.platform = platform + self.device_id = device_id + self.supported = set(supported) + self.supported_buttons = {"home", "back", "recent", "enter"} + self.calls: list[tuple[str, tuple[object, ...], dict[str, object]]] = [] + self.ui_tree = ( + deepcopy(ui_tree) + if ui_tree is not None + else { + "phone_state": {"packageName": "example.app"}, + "device_context": {"screen_bounds": {"width": 100, "height": 200}}, + "a11y_tree": [ + { + "className": "EditText", + "isEditable": True, + "isFocused": True, + "boundsInScreen": { + "left": 10, + "top": 20, + "right": 30, + "bottom": 40, + }, + } + ], + } + ) + self.screenshot_bytes = screenshot_bytes + self.apps = deepcopy(apps) if apps is not None else [] + self.files = dict(files or {}) + self.clipboard = clipboard + self.failures = dict(failures or {}) + + def _record(self, name: str, *args: object, **kwargs: object) -> None: + self.calls.append((name, args, kwargs)) + if name in self.failures: + raise self.failures[name] + + async def tap(self, x: int, y: int) -> None: + self._record("tap", x, y) + + async def input_text( + self, text: str, *, clear: bool = False, humanize: bool = False, wpm: int = 0 + ) -> bool: + self._record("input_text", text, clear=clear, humanize=humanize, wpm=wpm) + return True - @property - def identifier(self) -> str: - return self._identifier + async def press_button(self, name: str) -> None: + self._record("press_button", name) - @property - def cloud_id(self) -> str | None: - return self._cloud_id + async def swipe( + self, x1: int, y1: int, x2: int, y2: int, *, duration_ms: float + ) -> None: + self._record("swipe", x1, y1, x2, y2, duration_ms=duration_ms) - @property - def platform(self) -> str: - return self._platform + async def drag( + self, x1: int, y1: int, x2: int, y2: int, *, duration: float + ) -> None: + self._record("drag", x1, y1, x2, y2, duration=duration) - @property - def supported_operations(self) -> set[str]: - return set(self._supported_operations) + async def start_app(self, app_id: str, *, activity: str | None = None) -> str: + self._record("start_app", app_id, activity=activity) + return app_id - async def connect(self) -> None: - return None + async def stop_app(self, app_id: str) -> None: + self._record("stop_app", app_id) - async def _ensure_connected(self) -> None: - return None + async def uninstall_app(self, app_id: str) -> None: + self._record("uninstall_app", app_id) - async def _input_text_raw( - self, text: str, clear: bool = False, stealth: bool = False, wpm: int = 0 - ) -> bool: - self.inputs.append(text) - return True + async def open_deep_link( + self, link: str, *, package: str | None = None, action: str | None = None + ) -> None: + self._record("open_deep_link", link, package=package, action=action) + + async def get_apps(self, *, include_system: bool) -> list[dict[str, Any]]: + self._record("get_apps", include_system=include_system) + return deepcopy(self.apps) + + async def get_ui_tree(self, *, filter: bool = True) -> dict[str, Any]: + self._record("get_ui_tree", filter=filter) + return deepcopy(self.ui_tree) + + async def screenshot(self, *, hide_overlay: bool = False) -> bytes: + self._record("screenshot", hide_overlay=hide_overlay) + return self.screenshot_bytes + + async def get_date(self) -> str: + self._record("get_date") + return "2026-01-01T00:00:00Z" + + async def push_file( + self, source: bytes | str | PathLike[str], device_path: str + ) -> None: + self._record("push_file", source, device_path) + self.files[device_path] = ( + source if isinstance(source, bytes) else Path(source).read_bytes() + ) + + async def pull_file(self, device_path: str) -> bytes: + self._record("pull_file", device_path) + return self.files[device_path] + + async def get_clipboard(self) -> str: + self._record("get_clipboard") + return self.clipboard + + async def set_clipboard(self, text: str) -> None: + self._record("set_clipboard", text) + self.clipboard = text + + +def fake_device( + *, + driver: object | None = None, + platform: str = "android", + **from_driver_options: Any, +) -> AsyncDevice: + """Wrap a supplied driver or create a default one without accessing hardware.""" + from_driver_options.setdefault("platform_hint", platform) + return AsyncDevice.from_driver( + FakeDriver(platform=platform) if driver is None else driver, + **from_driver_options, + ) diff --git a/tests/support/doctor.py b/tests/support/doctor.py index a691d4142..a9d45dacd 100644 --- a/tests/support/doctor.py +++ b/tests/support/doctor.py @@ -1,48 +1,74 @@ """Offline diagnostics and repair fixture for doctor CLI tests.""" import importlib -from types import SimpleNamespace as NS +from types import SimpleNamespace from unittest.mock import AsyncMock import pytest +from mobilerun_core import DiagnosticResult, LocalDevices, SetupResult from mobilerun.diagnostics.results import CheckResult, Status -__all__ = ["checks"] - @pytest.fixture -def checks(monkeypatch): +def checks(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace: module = importlib.import_module("mobilerun.cli.doctor") - ok = CheckResult("test", Status.PASS, "ready") - fail = CheckResult("Portal", Status.FAIL, "not installed") - warn = CheckResult("TCP", Status.WARN, "not configured") - for name in ( - "check_sdk_version", - "check_adb", - "check_content_provider", - "check_keyboard", - ): - monkeypatch.setattr(module, name, AsyncMock(return_value=ok)) - monkeypatch.setattr(module, "check_config", AsyncMock(return_value=(ok, None))) - monkeypatch.setattr( - module, "check_device", AsyncMock(return_value=(ok, NS(serial="serial"))) - ) - monkeypatch.setattr( - module, "check_portal_installed", AsyncMock(return_value=(fail, False)) - ) - monkeypatch.setattr( - module, "check_portal_version", AsyncMock(return_value=(ok, "1", "1", None)) - ) - monkeypatch.setattr( - module, "check_accessibility", AsyncMock(return_value=(ok, True)) - ) monkeypatch.setattr( - module, "check_portal_state", AsyncMock(return_value=(ok, None)) + LocalDevices, "list_android_devices", AsyncMock(return_value=[]) ) - monkeypatch.setattr(module, "check_tcp", AsyncMock(return_value=warn)) - monkeypatch.setattr(module, "install_portal", AsyncMock()) - monkeypatch.setattr( - module, "fix_enable_accessibility", AsyncMock(return_value=True) + ok = CheckResult("test", Status.PASS, "ready") + monkeypatch.setattr(module, "check_sdk_version", AsyncMock(return_value=ok)) + monkeypatch.setattr(module, "check_config", AsyncMock(return_value=ok)) + normal = { + r.check: r + for r in ( + DiagnosticResult( + "ADB", + "pass", + {"count": 1, "executable_path": "/opt/android/adb", "failure": None}, + ), + DiagnosticResult("Device", "pass", {"state": "device"}), + DiagnosticResult("Portal Installed", "pass", {"installed": True}), + DiagnosticResult( + "Portal Version", + "pass", + {"installed": "0.7.1", "compatible": "0.7.1", "mapping_fetched": True}, + ), + DiagnosticResult("Accessibility", "pass", {"enabled": True}), + DiagnosticResult("Content Provider", "pass"), + DiagnosticResult("State (content)", "pass", {"missing_keys": ()}), + DiagnosticResult("Screenshot (content)", "pass", {"bytes": 2048}), + DiagnosticResult( + "TCP Mode", "pass", {"forward_port": 17425, "failure": None} + ), + DiagnosticResult("State (tcp)", "pass", {"missing_keys": ()}), + DiagnosticResult("Screenshot (tcp)", "pass", {"bytes": 2048}), + DiagnosticResult("Keyboard", "pass", {"available": True}), + ) + } + + async def diagnose( + serial: str | None = None, + *, + client_version: str, + checks: tuple[str, ...], + allow_changes: bool = False, + ) -> list[DiagnosticResult]: + return [normal[check] for check in reversed(checks) if check in normal] + + diagnostic = AsyncMock(side_effect=diagnose) + setup = AsyncMock(return_value=SetupResult(True, "serial", "setup_portal")) + accessibility = AsyncMock(return_value=True) + release = AsyncMock(side_effect=AssertionError("unexpected Portal release lookup")) + monkeypatch.setattr(LocalDevices, "diagnose_android", diagnostic) + monkeypatch.setattr(LocalDevices, "setup_portal", setup) + monkeypatch.setattr(LocalDevices, "enable_portal_accessibility", accessibility) + monkeypatch.setattr(LocalDevices, "latest_portal_release", release) + return SimpleNamespace( + module=module, + normal=normal, + diagnostic=diagnostic, + setup=setup, + accessibility=accessibility, + release=release, ) - return module, ok, fail diff --git a/tests/support/extensions.py b/tests/support/extensions.py index 4f5b27dbb..1efd8816d 100644 --- a/tests/support/extensions.py +++ b/tests/support/extensions.py @@ -1,335 +1,31 @@ -"""Repository assertions for extension contracts. +"""Assertions for tools and public metadata of a standalone extension.""" -Factories must return fresh, isolated resources with mocked/free transports. -The checker only executes its own safe probe actions, never resource actions or purchases. -""" - -from __future__ import annotations - -import asyncio import json -from collections.abc import Awaitable, Callable -from contextlib import asynccontextmanager from dataclasses import asdict -from typing import AsyncIterator -from unittest.mock import AsyncMock, patch -from mobilerun.core.devices.base import Device -from mobilerun.core.devices.components.wrapper import DeviceWrapper -from mobilerun.core.devices.pool import DevicePool -from mobilerun.core.extensions import Extension, action, device_action -from mobilerun.errors.operators import ( - ExtensionConflict, - ExtensionNotBound, - ExtensionNotSupported, -) +from mobilerun.core.extensions import Extension, compile_tools from mobilerun.models.cloud_task import CloudTaskInputs from mobilerun.models.context import ContextItem -async def check_extension_contract( - make_extension: Callable[[str], Extension], - make_device: Callable[[], Awaitable[Device]], - *, - incompatible_device: Callable[[], Awaitable[Device]] | None = None, - unbind_requires_replacement: bool = False, -) -> None: - """Check relationship invariants and safe standalone/device action dispatch.""" - - from tests.support.devices import MemoryDevice - - class Probe(Extension): - ran = False - - @action - async def standalone(self) -> bool: - """Safely probe device-independent dispatch.""" - return True - - @device_action - async def attached(self, device: Device) -> bool: - """Safely probe facade injection without touching any resource.""" - self.ran = True - assert ( - device is self.device - ), "J: device action did not receive bound facade" - return True - - probe = Probe(name="contract_probe") - assert await probe.standalone(), "J: unbound action failed" - assert await probe.actions.call( - "contract_probe.standalone", {} - ), "J: unbound catalog action failed" - for invoke in ( - probe.attached, - lambda: probe.actions.call("contract_probe.attached", {}), - ): - try: - await invoke() - except ExtensionNotBound as error: - assert "await contract_probe.bind(device) first" in str( - error - ), "J: unclear device requirement" - else: - raise AssertionError("J: unbound device action did not reject") - assert not probe.ran, "J: unbound device action executed its body" - facade = DeviceWrapper(MemoryDevice()) - try: - await probe.bind(facade) - assert await probe.attached(), "J: bound device action failed" - assert await probe.actions.call( - "contract_probe.attached", {} - ), "J: bound catalog device action failed" - finally: - await facade.close() - await probe.close() - - @asynccontextmanager - async def scenario() -> AsyncIterator[tuple[Device, Extension]]: - device = await make_device() - extension = make_extension("first") - try: - yield device, extension - finally: - await device.close() - await extension.close() - - async with scenario() as (device, extension): - wrapper = DeviceWrapper(device) - pool = DevicePool([device]) - views = (device.extensions, wrapper.extensions, pool.extensions[0]) - await extension.bind(wrapper) - assert all( - view[extension.name] is extension for view in views - ), "A: shared registry differs" - assert ( - device.__getattr__(extension.name) is extension - ), "A: named lookup differs" - actions = extension.actions.list() - for entry in actions: - assert entry.description and entry.name.startswith( - "first." - ), "G: invalid action metadata" - json.dumps(dict(entry.input_schema), allow_nan=False) - json.dumps(dict(entry.output_schema), allow_nan=False) - assert ( - device.actions.get(entry.name).owner == extension.name - ), "G: action missing" - for item in await extension.context(): - assert isinstance(item, ContextItem), "G: context item has wrong type" - assert item.source == extension.name, "G: context source differs" - json.dumps(dict(item.data), allow_nan=False) - task_inputs = await extension.cloud_task_inputs() - assert isinstance( - task_inputs, CloudTaskInputs - ), "G: cloud task inputs have wrong type" - reference_data = asdict(task_inputs) - assert set(reference_data) == { - "credential_references" - }, "G: cloud task inputs must contain references only" - assert all( - set(reference) == {"package", "name"} - for reference in reference_data["credential_references"] - ), "G: cloud credential references must not contain values" - json.dumps(reference_data, allow_nan=False) - if unbind_requires_replacement: - for unbind in ( - extension.unbind, - lambda: device.unbind_extension(extension.name), - ): - try: - await unbind() - except ExtensionConflict: - pass - else: - raise AssertionError( - "B: required extension detached without replacement" - ) - await device.close() - else: - await extension.unbind() - assert all(not view for view in views), "B: unbind left a shared relationship" - if not unbind_requires_replacement: - await extension.bind(device) - await device.unbind_extension(extension.name) - assert all( - not view for view in views - ), "B: device-side unbind left relationship" - try: - device.__getattr__(extension.name) - except AttributeError: - pass - else: - raise AssertionError("B: missing extension attribute did not fail") - assert not any( - entry.owner == extension.name for entry in device.actions.list() - ), "G: actions survived unbind" - - for hook in ("check_bind", "on_bind"): - async with scenario() as (device, extension): - wrapper = DeviceWrapper(device) - pool = DevicePool([device]) - views = (device.extensions, wrapper.extensions, pool.extensions[0]) - snapshots = tuple(dict(view) for view in views) - binding_snapshots = { - name: (binding, binding.facade, binding.owned, binding.uncertain) - for name, binding in device._extension_state.bindings.items() - } - failure = ExtensionNotSupported("injected contract failure") - with ( - patch.object(extension, hook, AsyncMock(side_effect=failure)), - patch.object(extension, "_reconcile_bind_failure", AsyncMock()), - ): - try: - await extension.bind(device) - except ExtensionNotSupported as exc: - assert exc is failure, "C: hook error changed" - else: - raise AssertionError(f"C: {hook} failure was swallowed") - for view, snapshot in zip(views, snapshots, strict=True): - assert tuple(view) == tuple(snapshot) and all( - view[name] is value for name, value in snapshot.items() - ), f"C: {hook} failure changed a registry snapshot" - for name, observed in view.items(): - binding = observed._binding - assert ( - binding is not None - and binding.extension is observed - and binding.facade._extension_state is device._extension_state - ), f"C: {hook} registry has an orphan binding" - assert ( - device._extension_state.bindings[name] is binding - ), f"C: {hook} binding points to a different registry entry" - assert ( - extension._binding is None - ), f"C: {hook} failed handle retained a binding outside the registry" - for name, (before, facade, owned, uncertain) in binding_snapshots.items(): - after = device._extension_state.bindings[name] - assert ( - after is before - and after.facade is facade - and after.owned == owned - and after.uncertain == uncertain - ), f"C: {hook} failure modified a registry binding snapshot" - - if incompatible_device is not None: - device = await incompatible_device() - extension = make_extension("incompatible") - try: - with patch.object( - extension, "on_bind", AsyncMock(wraps=extension.on_bind) - ) as bind_hook: - try: - await extension.bind(device, force=True) - except ExtensionNotSupported: - pass - else: - raise AssertionError("E: incompatible device was accepted") - assert bind_hook.await_count == 0, "E: incompatibility reached backend" - assert not device.extensions, "E: incompatible binding published" - finally: - await extension.close() - await device.close() - - async with scenario() as (device, first): - second = make_extension("second") - try: - await first.bind(device) - with patch.object( - second, "on_bind", AsyncMock(wraps=second.on_bind) - ) as hook: - if first.exclusive is None: - await second.bind(device) - assert len(device.extensions) == 2, "D: nonexclusive binding lost" - else: - try: - await second.bind(DeviceWrapper(device)) - except ExtensionConflict as exc: - assert first.name in str( - exc - ), "D: conflict doesn't identify bound extension" - else: - raise AssertionError("D: exclusivity was bypassed") - assert hook.await_count == 0, "D: conflict reached backend" - await second.bind(device, force=True) - assert tuple(device.extensions) == ( - second.name, - ), "I: force didn't replace" - assert first._binding is None, "I: old extension still bound" - finally: - if unbind_requires_replacement: - await device.close() - await second.close() - - async with scenario() as (device, first): - second = make_extension("second") - try: - outcomes = await asyncio.wait_for( - asyncio.gather( - first.bind(device), - second.bind(DeviceWrapper(device)), - return_exceptions=True, - ), - timeout=5, - ) - if first.exclusive is not None: - assert ( - sum(isinstance(value, ExtensionConflict) for value in outcomes) == 1 - ), "F: exclusive concurrent binds didn't have one winner" - assert ( - len(device.extensions) == 1 - ), "F: concurrent registry inconsistent" - await asyncio.wait_for( - asyncio.gather( - first.bind(device, force=True), second.bind(device, force=True) - ), - timeout=5, - ) - assert ( - len(device.extensions) == 1 - ), "I: concurrent force left multiple bindings" - else: - assert not any( - isinstance(value, BaseException) for value in outcomes - ), "F: nonexclusive concurrent bind failed" - finally: - if unbind_requires_replacement: - await device.close() - await second.close() - - for owned in (False, True): - async with scenario() as (device, extension): - with ( - patch.object( - extension, "on_unbind", AsyncMock(wraps=extension.on_unbind) - ) as unbind, - patch.object( - extension, "on_close", AsyncMock(wraps=extension.on_close) - ) as close, - ): - await extension.bind(device, close_on_device_close=owned) - await device.close() - await device.close() - assert unbind.await_count == 1, "H: unbind must run once" - assert close.await_count == int(owned), "H: ownership ignored" - assert not device.extensions, "H: close left relationships" - - async with scenario() as (device, extension): - await extension.bind(device, close_on_device_close=True) - with ( - patch.object( - extension, "on_unbind", AsyncMock(side_effect=RuntimeError("injected")) - ), - patch.object(extension, "on_close", AsyncMock()) as close, - patch.object(extension, "_reconcile_bind_failure", AsyncMock()), - ): - try: - await device.close() - except ExceptionGroup: - pass - else: - raise AssertionError("H: failed unbind was swallowed") - assert ( - device.extensions[extension.name] is extension - ), "H: failed unbind lost relationship" - assert close.await_count == 0, "H: resource closed despite failed unbind" +async def check_extension_contract(extension: Extension) -> None: + """Check published schemas and context without invoking tools or closing resources.""" + for tool in compile_tools([extension], expand_atomics=False): + assert tool.name.startswith(f"{extension.name}.") + json.dumps(tool.input_schema, allow_nan=False) + json.dumps(tool.output_schema, allow_nan=False) + for item in await extension.context(): + assert isinstance(item, ContextItem) + assert item.source == extension.name + json.dumps(dict(item.data), allow_nan=False) + task_inputs = await extension.cloud_task_inputs() + assert isinstance(task_inputs, CloudTaskInputs) + reference_data = asdict(task_inputs) + assert set(reference_data) == { + "credential_references" + }, "G: cloud task inputs must contain references only" + assert all( + set(reference) == {"package", "name"} + for reference in reference_data["credential_references"] + ), "G: cloud credential references must not contain values" + json.dumps(reference_data, allow_nan=False) diff --git a/tests/support/macro.py b/tests/support/macro.py index e38d870b0..c068beff5 100644 --- a/tests/support/macro.py +++ b/tests/support/macro.py @@ -1,47 +1,36 @@ """Offline macro replay device and JSONL fixtures.""" import json +from collections.abc import Iterable, Mapping from pathlib import Path from mobilerun.models import RunStep -from tests.support.devices import MemoryDevice -class FakeDevice(MemoryDevice): - state = None - - def __init__(self, *states): - super().__init__() - self.taps = [] - self.states = list(states or ({"phone_state": {"packageName": "other"}},)) - self.observations = 0 - - async def tap(self, x, y): - self.taps.append((x, y)) - - async def _get_ui_tree(self): - self.observations += 1 - if len(self.states) > 1: - return self.states.pop(0) - return self.states[0] - - -def write_macro(tmp_path: Path, guarded: bool = False, *, rows=None) -> Path: +def write_macro( + tmp_path: Path, + guarded: bool = False, + *, + rows: Iterable[Mapping[str, object]] | None = None, +) -> Path: """Write a pinned macro; pass rows to override the default tap.""" if rows is None: - row = {"i": 1, "action": "tap", "args": {"x": 10, "y": 20}} + row: dict[str, object] = {"i": 1, "action": "tap", "args": {"x": 10, "y": 20}} if guarded: row["before"] = {"app": "expected", "activity": None, "elements": []} rows = [row] - return _write_jsonl(tmp_path / "v1.jsonl", rows) + return _write_jsonl( + tmp_path / "v1.jsonl", ({"schema_version": 2, **row} for row in rows) + ) -def write_steps(tmp_path: Path, *rows) -> Path: +def write_steps(tmp_path: Path, *rows: Mapping[str, object]) -> Path: """Write run rows with defaults that individual tests can override.""" return _write_jsonl( tmp_path / "steps.jsonl", ( { + "schema_version": 2, "i": i, "started_at": "2026-11-27T00:00:00Z", "finished_at": "2026-11-27T00:00:01Z", @@ -56,7 +45,7 @@ def write_steps(tmp_path: Path, *rows) -> Path: ) -def _write_jsonl(path, rows): +def _write_jsonl(path: Path, rows: Iterable[Mapping[str, object]]) -> Path: path.write_text("".join(json.dumps(row) + "\n" for row in rows), encoding="utf-8") return path diff --git a/tests/support/proxy.py b/tests/support/proxy.py index 158882397..dc1298dca 100644 --- a/tests/support/proxy.py +++ b/tests/support/proxy.py @@ -1,54 +1,24 @@ -"""In-memory device for local and cloud proxy extension tests.""" +"""Fake ADB shell for framework proxy tests (no device or sockets).""" -from unittest.mock import AsyncMock +import shlex -from mobilerun.core.proxy.target import ProxyTarget -from mobilerun.models.proxy import ProxyStatus -from tests.support.devices import MemoryDevice -__all__ = ["ProxyMemory"] +class FakeProxyShell: + serial = "fake-adb" + def __init__(self) -> None: + self.setting = ":0" + self.writes: list[str] = [] -class FakeTarget(ProxyTarget): - def __init__(self): - self.current = ProxyStatus(False) - self.connect = AsyncMock(side_effect=self._connect) - self.disconnect_calls = 0 + async def get_state(self) -> str: + return "device" - async def _connect(self, name): - self.current = ProxyStatus(True, name, "socks5") - return self.current - - async def connect_fixed(self, *, id): - return await self.connect(id) - - async def connect_rotating(self, *, country, smart_ip): - return await self.connect(country) - - async def connect_socks5(self, host, port, user, password): - return await self.connect(host) - - async def set_http_proxy(self, host, port): - return await self.connect(f"{host}:{port}") - - async def status(self): - return self.current - - async def disconnect(self): - self.disconnect_calls += 1 - self.current = ProxyStatus(False) - - -class ProxyMemory(MemoryDevice): - def __init__(self, cloud=False): - super().__init__( - cloud_id="cloud" if cloud else None, - supported_operations=frozenset( - {"proxy_switch"} if cloud else {"http_proxy"} - ), - ) - self.target = FakeTarget() - - @property - def _proxy_target(self): - return self.target + async def shell(self, command: str) -> str: + args = shlex.split(command) + if args == ["settings", "get", "global", "http_proxy"]: + return self.setting + if args[:4] == ["settings", "put", "global", "http_proxy"] and len(args) == 5: + self.setting = args[4] + self.writes.append(self.setting) + return "" + raise AssertionError("Unexpected ADB command") diff --git a/tests/support/sandbox_playground/extract.py b/tests/support/sandbox_playground/extract.py index 8c14d9b8a..552eb7d47 100644 --- a/tests/support/sandbox_playground/extract.py +++ b/tests/support/sandbox_playground/extract.py @@ -41,17 +41,17 @@ def main(input: Input, ctx: Context) -> Output: def visible(): return [ - n for n in device.ui().nodes if not (n.get("hidden") or n.get("offscreen")) + n for n in (device.ui().elements or ()) if not (n.hidden or n.offscreen) ] def feed_rows(): nodes = visible() - if not any(n.get("resource_id") == "feed" for n in nodes): + if not any(n.resource_id == "feed" for n in nodes): raise RuntimeError("headlines screen unavailable") return { - n["resource_id"]: n + n.resource_id: n for n in nodes - if (n.get("resource_id") or "").startswith("story:") + if (n.resource_id or "").startswith("story:") } def capture(): @@ -74,14 +74,18 @@ def read_story(row): return None try: - fields = {n.get("resource_id"): n for n in visible()} - if fields.get("title", {}).get("text") != row["text"]: + fields = {n.resource_id: n for n in visible()} + if ( + (title := fields.get("title")) is None + or not title.text + or title.text != row.text + ): issues.append("detail did not match the selected headline") return None story = Story( - title=fields["title"]["text"], - source=fields["source"]["text"], - published_at=datetime.fromisoformat(fields["published"]["text"]), + title=title.text, + source=fields["source"].text, + published_at=datetime.fromisoformat(fields["published"].text), ) try: story.image = capture() @@ -96,10 +100,10 @@ def read_story(row): device.tap_node(transcript_button, humanize=False) try: nodes = visible() - if not any(n.get("resource_id") == "transcript" for n in nodes): + if not any(n.resource_id == "transcript" for n in nodes): raise RuntimeError("incorrect transcript screen") story.transcript = "\n".join( - n["text"] for n in nodes if n.get("resource_id") == "line" + n.text for n in nodes if n.resource_id == "line" and n.text ) finally: device.key("back") diff --git a/tests/support/sandbox_playground/main.py b/tests/support/sandbox_playground/main.py index 1475f835c..3097c0470 100644 --- a/tests/support/sandbox_playground/main.py +++ b/tests/support/sandbox_playground/main.py @@ -54,8 +54,8 @@ def main(input: Input, ctx: Context) -> Output: t = time.monotonic() ctx.log.info("Reading UI tree") - nodes = device.ui().nodes - texts = [node["text"] for node in nodes if node.get("text")] + nodes = device.ui().elements or () + texts = [node.text for node in nodes if node.text] ctx.log.info( f"UI tree read in {time.monotonic() - t:.2f}s: {len(nodes)} nodes, {len(texts)} with text" ) diff --git a/tests/support/sandbox_playground/settings.py b/tests/support/sandbox_playground/settings.py index 2a411bf3d..556b1b36b 100644 --- a/tests/support/sandbox_playground/settings.py +++ b/tests/support/sandbox_playground/settings.py @@ -63,8 +63,8 @@ def capture(): ctx.log.info(f"Settled in {time.monotonic() - t:.2f}s") screenshot, captured = capture() t = time.monotonic() - nodes = device.ui().nodes - texts = [node["text"] for node in nodes if node.get("text")][:20] + nodes = device.ui().elements or () + texts = [node.text for node in nodes if node.text][:20] ctx.log.info(f"UI read: {len(nodes)} nodes in {time.monotonic() - t:.2f}s") t = time.monotonic() app_id = device.current_app_id() or "" diff --git a/tests/support/smoke_phone.py b/tests/support/smoke_phone.py index 3b8389848..89b1610df 100644 --- a/tests/support/smoke_phone.py +++ b/tests/support/smoke_phone.py @@ -1,67 +1,63 @@ -"""Conservative cleanup for minute phones created by the smoke suite.""" +"""Manage smoke phones without inferring ownership from inventory names.""" import asyncio -import sys - -from mobilerun.clients.cloud import devices -from mobilerun.clients.cloud.client import cloud_client -from mobilerun.models import Billing, Plan - - -def _candidate(listed, name): - matches = [item for item in listed if item.name == name] - if len(matches) > 1: - raise AssertionError( - f"Ambiguous phone name {name!r}: IDs {[item.id for item in matches]}" - ) - if not matches: - return None - item = matches[0] - if item.billing_strategy != Plan.MINUTE: - raise AssertionError( - f"Cannot confirm minute billing for {name!r}, ID {item.id}" - ) - return item.id - - -async def _recover_phone(name): - terminated = None - async with cloud_client(billing=Billing.INCLUDED) as client: - for _ in range(30): - listed = await devices.list_devices(billing=Billing.INCLUDED, client=client) - candidate = _candidate(listed, name) - if terminated is None and candidate is not None: - await devices.terminate( - candidate, billing=Billing.INCLUDED, client=client - ) - terminated = candidate - elif terminated is not None: - if candidate not in (None, terminated): - raise AssertionError( - f"Phone {name!r} changed IDs: {terminated} to {candidate}" - ) - if not any(item.id == terminated for item in listed): - return - await asyncio.sleep(1) - message = f"unresolved: phone named {name!r} may exist" - if terminated is not None: - message += f"; could not verify removal of ID {terminated}" - original = sys.exception() - if original is None: - raise AssertionError(message) - original.add_note(message) - - -async def close_smoke_phone(device, name): - """Close first; recover by name only when create never returned a receipt.""" +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager + +from mobilerun_core import AsyncDevice, AsyncMobilerun, ConnectProxyRef +from mobilerun_core.config import DEFAULT_CLOUD_READY_TIMEOUT_S + +from mobilerun.clients.cloud.billing_policy import BillingPolicy +from mobilerun.models import Billing + +_VERIFY_TIMEOUT_S = 30.0 + + +@asynccontextmanager +async def open_smoke_phone( + run: AsyncMobilerun, + *, + device_id: str | None = None, + name: str | None = None, + proxy: ConnectProxyRef | None = None, + ready_timeout: float = DEFAULT_CLOUD_READY_TIMEOUT_S, +) -> AsyncIterator[AsyncDevice]: + """Borrow by ID, or create a minute phone and verify its lease cleanup.""" + if device_id is not None: + if name is not None or proxy is not None: + raise ValueError("A borrowed smoke phone takes only a device ID") + async with await run.connect(device_id, backend="cloud") as borrowed: + yield borrowed + return + if name is None or proxy is None: + raise ValueError("A disposable smoke phone requires a name and Connect proxy") + + # Core rolls back known IDs if create cannot return a lease. An ambiguous + # create must never lead to an inventory search or deletion by name. + device = await run.create_cloud( + name=name, + proxy=proxy, + plan=BillingPolicy.cloud_phone_plan("minute", billing=Billing.PAID), + keep=False, + ready_timeout=ready_timeout, + ) + owned_id = device.device_id try: try: - await device.close() + yield device finally: - # name is the cached *server response*, not the constructor argument. - # A returned name with a cleared ID means readiness rollback succeeded. - if device.cloud_id is None and device.name is None: - await _recover_phone(name) - except Exception as exc: - exc.add_note(f"Smoke phone cleanup failed: name={name!r}, id={device.cloud_id}") + await device.aclose() + try: + async with asyncio.timeout(_VERIFY_TIMEOUT_S): + while any( + item.device_id == owned_id and item.state != "terminated" + for item in await run.list_cloud_devices() + ): + await asyncio.sleep(1) + except TimeoutError as exc: + raise AssertionError( + f"Could not verify termination of smoke phone {owned_id}" + ) from exc + except BaseException as exc: + exc.add_note(f"Smoke phone ID: {owned_id}") raise diff --git a/tests/unit/addons/test_plugins.py b/tests/unit/addons/test_plugins.py index 334a6ddc6..3b279428e 100644 --- a/tests/unit/addons/test_plugins.py +++ b/tests/unit/addons/test_plugins.py @@ -17,6 +17,7 @@ from mobilerun.addons import plugins from mobilerun.cli.app import _run_agent_macro, cli from mobilerun.config.user_config import MobileConfig +from mobilerun.core.operator import Operator from tests.support.paths import REPO_ROOT @@ -70,12 +71,12 @@ def test_missing_plugin_message_names_plugin_and_only_agent_has_hint(monkeypatch monkeypatch.setattr(plugins, "discover", lambda group: {}) with pytest.raises(plugins.MissingPlugin) as caught: - plugins.load("mobilerun.operators", name) + plugins.load("mobilerun.cli", name) message = str(caught.value) assert f"Command '{name}' is not installed." in message assert ( "Install the mobilerun-agents add-on (see README: Agent add-on)." in message - ) == (name != "other") + ) == (name == "agent") assert "pip install" not in message @@ -160,12 +161,20 @@ def test_plugin_list_is_lazy_and_reports_shadowed_and_check_status(monkeypatch): good = Entry("extra", click.Command("extra")) bad = Entry("bad", ValueError("sensitive")) shadow = Entry("doctor", click.Command("doctor")) - operator = Entry("agent_macro", lambda **kwargs: None) - for entry in (good, bad, shadow, operator): + operator = Entry("inventory", type("Inventory", (Operator,), {})) + invalid = Entry("not_operator", lambda **kwargs: None) + broken = Entry("broken_operator", ImportError("sensitive")) + handoff = Entry("agent_macro", lambda **kwargs: None) + all_entries = (good, bad, shadow, operator, invalid, broken, handoff) + for entry in all_entries: entry.dist = SimpleNamespace(metadata={"Name": "demo-plugin"}, version="1.2") def entries(*, group): - return [good, bad, shadow] if group == "mobilerun.cli" else [operator] + return { + "mobilerun.cli": [good, bad, shadow], + "mobilerun.operators": [operator, invalid, broken], + "mobilerun.macro_handoff": [handoff], + }[group] monkeypatch.setattr(plugins.metadata, "entry_points", entries) result = CliRunner().invoke(cli, ["plugins", "list", "--json"]) @@ -178,19 +187,26 @@ def entries(*, group): "extra": "not checked", "bad": "not checked", "doctor": "shadowed", + "inventory": "not checked", + "not_operator": "not checked", + "broken_operator": "not checked", "agent_macro": "not checked", } - assert sum(entry.loads for entry in (good, bad, shadow, operator)) == 0 + assert sum(entry.loads for entry in all_entries) == 0 result = CliRunner().invoke(cli, ["plugins", "list", "--json", "--check"]) assert result.exit_code == 0, result.output assert {row["name"]: row["status"] for row in json.loads(result.output)} == { "extra": "ok", "bad": "broken", "doctor": "shadowed", + "inventory": "ok", + "not_operator": "broken", + "broken_operator": "broken", "agent_macro": "ok", } assert "sensitive" not in result.output assert shadow.loads == 0 + assert CliRunner().invoke(cli, ["--help"]).exit_code == 0 def test_first_party_plugin_wins_duplicate_and_list_agrees(monkeypatch): @@ -224,19 +240,60 @@ def test_first_party_commands_are_entry_points(): ) -def test_macro_replay_plugin_dispatches_operator_entry_point(monkeypatch, tmp_path): +def test_fake_addon_operator_and_macro_handoff(monkeypatch, tmp_path): from importlib import metadata + from mobilerun_core import AsyncMobilerun + + from mobilerun.config.loader import ConfigLoader + from mobilerun.config.user_config import MobileConfig + from mobilerun.core.extensions import Extension + from mobilerun.core.operator import load_operator + from mobilerun.macro import MacroOperator + from mobilerun.macro.cli.replay import run_replay + from tests.support.devices import FakeDriver, fake_device from tests.support.macro import write_macro + class Inventory(Operator): + pass + + driver = FakeDriver() + + async def open_target(run, target, *, backend, **kwargs): + assert target == "fake" + assert backend == "local-android-adb" + return fake_device(driver=driver) + + config = MobileConfig() + config.device.auto_setup = False + monkeypatch.setattr(ConfigLoader, "load", lambda _: config) + monkeypatch.setattr(AsyncMobilerun, "connect", open_target) + received = {} - operator = Entry("agent_macro", lambda **kwargs: received.update(kwargs)) + + def replay_handoff(*, provider, model, **options): + received.update(options) + run_replay(MacroOperator, **options) + + operator = Entry("inventory", Inventory) + stale = Entry("agent_macro", AssertionError("legacy handoff loaded")) + handoff = Entry("agent_macro", replay_handoff) original = metadata.entry_points + groups_read = [] def entries(*, group): - return [operator] if group == "mobilerun.operators" else original(group=group) + groups_read.append(group) + if group == "mobilerun.operators": + return [operator, stale] + if group == "mobilerun.macro_handoff": + return [handoff] + return original(group=group) monkeypatch.setattr(plugins.metadata, "entry_points", entries) + extension = Extension() + assert load_operator("inventory")(extensions=[extension]).extensions == (extension,) + assert groups_read == ["mobilerun.operators"] + groups_read.clear() path = write_macro(tmp_path) result = CliRunner().invoke( cli, @@ -244,7 +301,13 @@ def entries(*, group): ) assert result.exit_code == 0, result.output assert received["path"] == str(path) - assert operator.loads == 1 + assert "Replay completed" in result.output + assert [call for call in driver.calls if call[0] == "tap"] == [ + ("tap", (10, 20), {}) + ] + assert handoff.loads == 1 + assert stale.loads == 0 + assert set(groups_read) == {"mobilerun.cli", "mobilerun.macro_handoff"} def test_fake_agent_entry_point_is_discovered(monkeypatch): diff --git a/tests/unit/architecture/test_base_ignores_addon.py b/tests/unit/architecture/test_base_ignores_addon.py new file mode 100644 index 000000000..29a7573dc --- /dev/null +++ b/tests/unit/architecture/test_base_ignores_addon.py @@ -0,0 +1,16 @@ +"""Guard the base configuration boundary against add-on dependencies.""" + +from tests.support.paths import REPO_ROOT + + +def test_base_config_and_helpers_do_not_reference_addon_internals(): + base = REPO_ROOT / "mobilerun" + paths = [ + *(base / "config").rglob("*.py"), + base / "utils" / "paths.py", + base / "cli" / "base" / "errors.py", + ] + for path in paths: + source = path.read_text() + for forbidden in ("mobilerun_agents", "mobilerun-agents["): + assert forbidden not in source, f"{path}: {forbidden}" diff --git a/tests/unit/architecture/test_functions_contract_drift.py b/tests/unit/architecture/test_functions_contract_drift.py new file mode 100644 index 000000000..eb42b2676 --- /dev/null +++ b/tests/unit/architecture/test_functions_contract_drift.py @@ -0,0 +1,200 @@ +"""Compare real service declarations without calling devices or cloud APIs.""" + +import asyncio +import inspect +from importlib import import_module +from types import SimpleNamespace +from typing import get_type_hints +from unittest.mock import AsyncMock + +import pytest +from mobilerun_core import AsyncDevice, ProxyStatus +from pydantic import TypeAdapter + +from mobilerun.core.credentials import CredentialProvider +from mobilerun.core.mailbox import CloudMailbox, Mailbox +from mobilerun.core.operator.base import Operator +from mobilerun.core.phone_number import PhoneNumber +from mobilerun.models import CredentialMetadata, ExecutionResult + +SERVICE_MEMBERS = { + "Credentials": {"list", "type_secret", "requires_approval"}, + "Mailbox": {"address", "wait_for_code"}, + "PhoneNumber": { + "id", + "phone_number", + "device_id", + "messages", + "send", + "wait_for_code", + }, + "Tasks": {"do"}, +} + + +def signature(method): + # Compare the public call shape without decorator wrappers or annotations. + sig = inspect.signature(inspect.unwrap(method)) + return sig.replace( + return_annotation=inspect.Signature.empty, + parameters=[ + p.replace(annotation=inspect.Parameter.empty) + for p in sig.parameters.values() + ], + ) + + +def differences(contract, implementation, members): + drift = set() + for name in members: + expected = inspect.getattr_static(contract, name) + actual = inspect.getattr_static(implementation, name, None) + if actual is None: + drift.add(f"{name}: missing") + elif isinstance(expected, property): + if not isinstance(actual, property) or actual.fset is not None: + drift.add(f"{name}: not a read-only property") + elif signature(actual.fget) != signature(expected.fget): + drift.add(f"{name}: property signature") + elif not inspect.isfunction(actual): + drift.add(f"{name}: not an instance method") + else: + if inspect.iscoroutinefunction(actual) != inspect.iscoroutinefunction( + expected + ): + drift.add(f"{name}: async-ness") + if signature(actual) != signature(expected): + drift.add(f"{name}: signature") + return drift + + +def test_credentials_metadata_supports_pydantic_action_schema(): + schema = TypeAdapter(list[CredentialMetadata]).json_schema()["$defs"][ + "CredentialMetadata" + ] + assert set(schema["properties"]) == {"package", "name", "fields", "source"} + assert schema["properties"]["source"]["type"] == "string" + assert set(schema["required"]) == { + "package", + "name", + "fields", + } + + +def optional_functions_module(suffix): + name = f"mobilerun_functions.{suffix}" + try: + return import_module(name) + except ModuleNotFoundError as error: + if error.name is not None and ( + error.name == name or name.startswith(error.name + ".") + ): + return None + raise + + +def mailbox_length_drift(adapter, monkeypatch): + response = SimpleNamespace(data=SimpleNamespace(code="123456")) + base_otp = AsyncMock(return_value=response) + monkeypatch.setattr("mobilerun.clients.cloud.mailboxes.Mailboxes.otp", base_otp) + sdk_otp = AsyncMock( + return_value=SimpleNamespace( + status_code=200, parse=AsyncMock(return_value=response) + ) + ) + sdk = SimpleNamespace( + mailboxes=SimpleNamespace(with_raw_response=SimpleNamespace(otp=sdk_otp)) + ) + mailbox = adapter(sdk, "mailbox-id", None) + wait = inspect.unwrap(CloudMailbox.wait_for_code) + + async def read_codes(): + assert await wait(CloudMailbox("mailbox-id")) == "123456" + assert await mailbox.wait_for_code() == "123456" + + asyncio.run(read_codes()) + limits = ("min_length", "max_length") + return tuple(base_otp.await_args.kwargs.get(k) for k in limits) != tuple( + sdk_otp.await_args.kwargs.get(k) for k in limits + ) + + +def return_type(method): + raw = inspect.unwrap(method) + return get_type_hints( + raw, + globalns={ + "AsyncDevice": AsyncDevice, + "ProxyStatus": ProxyStatus, + **raw.__globals__, + }, + ).get("return") + + +# The published 0.1.0 wheel predates the service bindings in the source audit. +# An added service changes the exact baseline; do not silently bless its drift. +# Each difference is tracked in https://linear.app/droidrun/issue/DRO-4149. +KNOWN_FUNCTIONS_DRIFT = { + "Credentials: missing service", # DRO-4149 + "Mailbox: missing service", # DRO-4149 + "PhoneNumber: missing service", # DRO-4149 + "Tasks: missing service", # DRO-4149 + "ExecutionResult: missing model", # DRO-4149 +} + + +def test_functions_drift_matches_installed_baseline(monkeypatch): + functions = pytest.importorskip("mobilerun_functions") + bindings = optional_functions_module("bindings") + results = optional_functions_module("results") + adapters = { + "Credentials": (CredentialProvider, "credentials", ("CredentialsAdapter",)), + "Mailbox": (Mailbox, "resources", ("MailboxAdapter",)), + "Tasks": (Operator, "tasks", ("CloudTasks", "RunTasks")), + "PhoneNumber": (PhoneNumber, "resources", ("PhoneNumberAdapter",)), + } + drift = set() + for name, (contract, module, class_names) in adapters.items(): + implementations = { + cls + for cls in (getattr(functions, name, None), getattr(bindings, name, None)) + if cls is not None + } + adapter_module = optional_functions_module(f"_adapters.{module}") + implementations.update( + cls + for class_name in class_names + if (cls := getattr(adapter_module, class_name, None)) is not None + ) + if not implementations: + drift.add(f"{name}: missing service") + continue + for implementation in implementations: + prefix = f"{name}.{implementation.__name__}" + drift.update( + f"{prefix}.{entry}" + for entry in differences( + contract, implementation, SERVICE_MEMBERS[name] + ) + ) + method = "list" if name == "Credentials" else None + if ( + method + and hasattr(implementation, method) + and return_type(getattr(implementation, method)) + != return_type(getattr(contract, method)) + ): + drift.add(f"{prefix}.{method}: return type") + if implementation.__name__ == "MailboxAdapter" and mailbox_length_drift( + implementation, monkeypatch + ): + drift.add(f"{prefix}.wait_for_code: OTP length limits") + + result = getattr( + results, "ExecutionResult", getattr(functions, "ExecutionResult", None) + ) + if result is None: + drift.add("ExecutionResult: missing model") + elif result is not ExecutionResult: + drift.add("ExecutionResult: distinct model") + assert drift == KNOWN_FUNCTIONS_DRIFT diff --git a/tests/unit/architecture/test_layers.py b/tests/unit/architecture/test_layers.py index 24418c0f5..461eafa35 100644 --- a/tests/unit/architecture/test_layers.py +++ b/tests/unit/architecture/test_layers.py @@ -4,6 +4,7 @@ import os import subprocess import sys +from collections.abc import Iterator from importlib.util import resolve_name from pathlib import Path @@ -16,7 +17,17 @@ LOCAL = ROOT / "clients" / "local" -SHARED = ("errors", "models", "utils", "cli", "config", "logs", "core", "clients") +SHARED = ( + "errors", + "models", + "utils", + "cli", + "config", + "logs", + "core", + "clients", + "interfaces", +) def test_base_contains_no_agent_module_references(): @@ -117,46 +128,57 @@ def test_shared_layers_do_not_contain_or_import_features(): assert not violations, violations -def test_device_package_does_not_import_cloud_driver_eagerly(): - script = """ -import builtins -real_import = builtins.__import__ -def guarded(name, *args, **kwargs): - if name == 'mobilerun_core_local.driver.cloud': - raise ImportError('cloud extra unavailable') - return real_import(name, *args, **kwargs) -builtins.__import__ = guarded -import mobilerun.core.devices as devices -assert devices.AndroidDevice -try: - devices.CloudDevice -except ImportError as error: - assert 'cloud extra unavailable' in str(error) -else: - raise AssertionError('CloudDevice should load the optional driver on access') -""" - result = subprocess.run( - [sys.executable, "-c", script], capture_output=True, text=True - ) - assert result.returncode == 0, result.stderr +def test_device_imports_use_only_public_core_apis(): + import mobilerun_core + import mobilerun_core.errors + + forbidden = { + "adbutils", + "mobilerun_core_local", + "mobilerun.core.devices", + "mobilerun.core.state", + } + public = { + "mobilerun_core": {*mobilerun_core.__all__, "config", "errors"}, + "mobilerun_core.config": {"DEFAULT_CLOUD_READY_TIMEOUT_S"}, + "mobilerun_core.errors": set(mobilerun_core.errors.__all__), + } + violations = [] + for folder in (ROOT, REPO_ROOT / "tests"): + for path in sorted(folder.rglob("*.py")): + tree = ast.parse(path.read_text(), filename=str(path)) + for line, module, member in _import_references(path, tree): + target = f"{module}.{member}" if member else module + if any(target == p or target.startswith(p + ".") for p in forbidden): + violations.append(f"{path.relative_to(REPO_ROOT)}:{line}: {target}") + elif target.startswith("mobilerun_core.") and not ( + (module in public and (member is None or member in public[module])) + ): + violations.append(f"{path.relative_to(REPO_ROOT)}:{line}: {target}") + assert not violations, "Non-public device imports:\n" + "\n".join(violations) -def test_sdk_imports_only_live_in_cloud_clients(): +def test_sdk_imports_stay_at_cloud_boundaries(): violations = [] + account_boundaries = { + ROOT / "core" / "workspace.py", + ROOT / "core" / "webhooks" / "cloud.py", + ROOT / "core" / "webhooks" / "helpers" / "requests.py", + } for path in ROOT.rglob("*.py"): - if path.is_relative_to(ROOT / "clients" / "cloud"): + if path in account_boundaries or path.is_relative_to( + ROOT / "clients" / "cloud" + ): continue for line, target in _references(path): - if ( - path == ROOT / "core/devices/components/identifiers.py" - and target == "mobilerun_sdk" - and path.read_text().splitlines()[line - 1].strip() - == '"mobilerun_sdk",' - ): - continue # Logger name, not an import or entry point. if target == "mobilerun_sdk" or target.startswith("mobilerun_sdk."): - if path == ROOT / "sandbox" / "clients.py": + if path.is_relative_to(ROOT / "sandbox" / "clients"): continue # Sandbox is a self-contained plugin with its own adapter. + if path == ROOT / "core" / "phone_number" / "cloud.py" and target in { + "mobilerun_sdk", + "mobilerun_sdk.APIError", + }: + continue # Attachment maps SDK errors where it coordinates binding. violations.append(f"{path.relative_to(ROOT)}:{line}") assert not violations, violations @@ -184,14 +206,31 @@ def test_root_import_scanner_detects_both_import_forms(tmp_path): def test_utils_import_only_utils_from_mobilerun(): """Standalone utilities must not depend on domain packages.""" + typed_boundaries = { + "utils/billing/retry.py": ( + "mobilerun.errors.cloud", + "mobilerun.errors.cloud.BillingRequired", + "mobilerun.models.billing", + "mobilerun.models.billing.Billing", + ), + "utils/screen/fingerprint.py": ("mobilerun.models.recording", "Fingerprint"), + "utils/tools/dispatch.py": ("mobilerun.models.tool_call", "ToolCallInfo"), + "utils/webhooks/urls.py": ("mobilerun.errors.cloud", "CloudValidationError"), + "utils/checkout/presentation.py": ( + "mobilerun.models.checkout", + "Checkout", + "CheckoutCallback", + ), + } violations = [] for path in (ROOT / "utils").rglob("*.py"): + boundary = typed_boundaries.get(path.relative_to(ROOT).as_posix()) for line, target in _references(path): - if path == ROOT / "utils/screen_fingerprint.py" and target in { - "mobilerun.models.recording", - "mobilerun.models.recording.Fingerprint", + if boundary and target in { + *boundary, + *(f"{boundary[0]}.{name}" for name in boundary[1:]), }: - continue # Pure run evidence value shared by core and replay. + continue # Keep one shared type or error at the typed boundary. if target.startswith("mobilerun.") and not ( target == "mobilerun.utils" or target.startswith("mobilerun.utils.") ): @@ -223,34 +262,26 @@ def _references(path): yield node.lineno, node.value -def _agent_import_references(path): +def _import_references( + path: Path, tree: ast.Module +) -> Iterator[tuple[int, str, str | None]]: package = ( - ".".join(("mobilerun", *path.relative_to(ROOT).parent.parts)) - if path.is_relative_to(ROOT) + ".".join(path.relative_to(REPO_ROOT).parent.parts) + if path.is_relative_to(REPO_ROOT) else "mobilerun" ) - for node in ast.walk(ast.parse(path.read_text())): + for node in ast.walk(tree): if isinstance(node, ast.Import): for alias in node.names: - yield node.lineno, alias.name + yield node.lineno, alias.name, None elif isinstance(node, ast.ImportFrom): module = node.module or "" if node.level: module = resolve_name("." * node.level + module, package) - yield node.lineno, module for alias in node.names: - yield node.lineno, module + "." + alias.name + yield node.lineno, module, alias.name elif isinstance(node, ast.Call) and node.args: func = node.func - if ( - isinstance(func, ast.Attribute) - and func.attr == "update" - and isinstance(func.value, ast.Name) - and func.value.id in {"LEGACY_MODULES", "_LEGACY_EXPORTS"} - ): - for value in ast.walk(node.args[0]): - if isinstance(value, ast.Constant) and isinstance(value.value, str): - yield value.lineno, value.value name = ( func.id if isinstance(func, ast.Name) @@ -262,7 +293,32 @@ def _agent_import_references(path): and isinstance(arg, ast.Constant) and isinstance(arg.value, str) ): - yield node.lineno, arg.value + yield node.lineno, arg.value, None + + +def _agent_import_references(path): + tree = ast.parse(path.read_text(), filename=str(path)) + from_modules = set() + for line, module, member in _import_references(path, tree): + if not member: + yield line, module + else: + if (line, module) not in from_modules: + from_modules.add((line, module)) + yield line, module + yield line, f"{module}.{member}" + for node in ast.walk(tree): + if isinstance(node, ast.Call) and node.args: + func = node.func + if ( + isinstance(func, ast.Attribute) + and func.attr == "update" + and isinstance(func.value, ast.Name) + and func.value.id in {"LEGACY_MODULES", "_LEGACY_EXPORTS"} + ): + for value in ast.walk(node.args[0]): + if isinstance(value, ast.Constant) and isinstance(value.value, str): + yield value.lineno, value.value elif isinstance(node, ast.Assign) and any( isinstance(target, ast.Name) and target.id in {"LEGACY_MODULES", "_LEGACY_EXPORTS"} @@ -347,8 +403,27 @@ def test_independent_features_do_not_import_each_other_or_agents(): assert not violations, violations +_SHARED_CLI_MODULES = ( + "mobilerun.cli.base", + "mobilerun.cli.devices.base", + "mobilerun.cli.devices.utils.approval", + "mobilerun.cli.devices.utils.connection.default", + "mobilerun.cli.devices.utils.connection.device", + "mobilerun.cli.devices.utils.connection.discovery", + "mobilerun.cli.devices.utils.targets", +) + + +def _is_shared_cli_import(target: str) -> bool: + return any( + target == module or target.startswith(module + ".") + for module in _SHARED_CLI_MODULES + ) + + def test_macro_dependencies_are_shared_or_internal(): allowed = { + "interfaces", "models", "macro", "core", @@ -357,16 +432,13 @@ def test_macro_dependencies_are_shared_or_internal(): "utils", "logs", "errors", + "version", } for path in (ROOT / "macro").rglob("*.py"): for line, target in _references(path): if target.startswith("mobilerun."): - assert ( - target.split(".")[1] in allowed - or target == "mobilerun.cli.base" - or target.startswith("mobilerun.cli.base.") - or target == "mobilerun.cli.devices.base" - or target.startswith("mobilerun.cli.devices.base.") + assert target.split(".")[1] in allowed or _is_shared_cli_import( + target ), f"{path}:{line}: {target}" @@ -375,10 +447,7 @@ def test_features_only_import_shared_cli_base(): for path in (ROOT / feature).rglob("*.py"): for line, target in _references(path): if target == "mobilerun.cli" or target.startswith("mobilerun.cli."): - assert any( - target == base or target.startswith(base + ".") - for base in ("mobilerun.cli.base", "mobilerun.cli.devices.base") - ), f"{path}:{line}: {target}" + assert _is_shared_cli_import(target), f"{path}:{line}: {target}" @pytest.mark.parametrize("module", ["mobilerun", "mobilerun.macro"]) @@ -449,15 +518,10 @@ def test_macro_help_and_agent_dry_run_do_not_load_agents(tmp_path): assert result.returncode == 0, result.stderr -def test_state_public_exports_are_light_and_old_paths_are_gone(): - subprocess.run( - [ - sys.executable, - "-c", - "import mobilerun.core.state as state; from importlib.util import find_spec; assert state.UIElement and state.UIState and state.StateProvider; assert state.AndroidStateProvider and state.IOSStateProvider and state.ScreenshotOnlyStateProvider; assert all(find_spec('mobilerun.core.state.' + name) is None for name in ['provider', 'ios_provider', 'screenshot_provider', 'state', 'stealth_state'])", - ], - check=True, - ) +@pytest.mark.parametrize("name", ["devices", "state"]) +def test_legacy_device_and_state_packages_are_absent(name): + assert not list((ROOT / "core" / name).rglob("*.py")) + assert not (ROOT / "core" / f"{name}.py").exists() def test_models_import_only_standard_library_third_party_and_errors(): @@ -469,7 +533,7 @@ def test_models_import_only_standard_library_third_party_and_errors(): ), f"{path}:{line}: {target}" -def test_resource_and_device_folder_contracts(): +def test_resource_folder_contracts(): assert not (ROOT / "testing").exists(), "Test support must not ship in mobilerun" support = REPO_ROOT / "tests" / "support" for name in ("__init__", "devices", "extensions"): @@ -478,36 +542,13 @@ def test_resource_and_device_folder_contracts(): folder = ROOT / "core" / name assert (folder / "base.py").is_file() assert (folder / "README.md").is_file() - devices = ROOT / "core" / "devices" - for name in ( - "android", - "ios", - "cloud", - "remote", - "base", - "pool", - "recording", - "stealth", - ): - assert (devices / f"{name}.py").is_file() - for name in ("cloud_apps", "cloud_lifecycle", "wrapper"): - assert (devices / "components" / f"{name}.py").is_file() assert (ROOT / "core" / "operator" / "cloud.py").is_file() - for name in ("base", "android", "ios", "cloud", "remote", "wrappers"): - assert ( - (devices / f"{name}.py") - if name != "wrappers" - else (devices / "components/wrapper.py") - ).is_file() - assert (devices / "README.md").is_file() - assert sorted(path.name for path in devices.glob("*.md")) == ["README.md"] assert not any((ROOT / "core" / "comms").glob("*.py")) def test_local_client_layout_and_import_boundaries(): expected = { "apk.py", - "emulator.py", "login_store.py", } assert expected <= {path.name for path in LOCAL.glob("*.py")} @@ -515,7 +556,7 @@ def test_local_client_layout_and_import_boundaries(): assert (ROOT / "core" / "credentials" / "file.py").is_file() for path in LOCAL.glob("*.py"): tree = ast.parse(path.read_text()) - assert not any(isinstance(node, ast.ClassDef) for node in ast.walk(tree)), path + assert sum(isinstance(node, ast.ClassDef) for node in tree.body) <= 1, path for node in ast.walk(tree): modules = [] if isinstance(node, ast.Import): @@ -542,7 +583,6 @@ def test_cli_domains_have_readmes_and_no_common_package(): INITIALIZER_EXCEPTIONS = { "__init__.py": "Lazy public exports", "core/__init__.py": "Lazy public core exports", - "core/devices/__init__.py": "Lazy public device exports", "sandbox/__init__.py": "Actionable error when the optional routines dependency is missing", } @@ -570,8 +610,18 @@ def test_initializers_only_export_names(): }: continue tree = ast.parse(path.read_text(), filename=str(path)) + relative = path.relative_to(ROOT).as_posix() + if relative == "sandbox/clients/__init__.py": + imported_transports = { + alias.asname + for stmt in tree.body + if isinstance(stmt, ast.ImportFrom) and stmt.level == 1 + for alias in stmt.names + if alias.name.endswith("Transport") and alias.asname == f"_{alias.name}" + } + else: + imported_transports = set() for index, node in enumerate(tree.body): - relative = path.relative_to(ROOT).as_posix() if relative in INITIALIZER_EXCEPTIONS and ( isinstance(node, ast.Assign) and len(node.targets) == 1 @@ -584,7 +634,6 @@ def test_initializers_only_export_names(): "_CORE_EXPORTS", }, "core/__init__.py": {"_EXPORT_MODULES"}, - "core/devices/__init__.py": {"_EXPORT_MODULES"}, "sandbox/__init__.py": set(), }[relative] or isinstance(node, ast.FunctionDef) @@ -596,6 +645,19 @@ def test_initializers_only_export_names(): continue if isinstance(node, (ast.Import, ast.ImportFrom)): continue + # The sandbox front door binds static operations directly, without + # instantiating transports or going through a second aliases module. + if ( + isinstance(node, ast.Assign) + and len(node.targets) == 1 + and isinstance(target := node.targets[0], ast.Name) + and isinstance(node.value, ast.Attribute) + and isinstance(node.value.value, ast.Name) + and node.value.value.id in imported_transports + and target.id == node.value.attr + and not target.id.startswith("_") + ): + continue if ( isinstance(node, ast.If) and isinstance(node.test, ast.Name) @@ -704,12 +766,10 @@ def test_package_readmes_do_not_use_template_filler(): def test_macro_utilities_expose_state_matching_and_logging(): from mobilerun.macro.utils import ( - capture_fingerprint, compare_states, configure_macro_logging, ) - assert callable(capture_fingerprint) assert callable(compare_states) assert callable(configure_macro_logging) @@ -722,17 +782,19 @@ def test_skills_utils_parse_frontmatter_description(): def test_macro_runtime_defaults_read_environment(monkeypatch): from mobilerun.macro import MacroPlayer + from tests.support.devices import fake_device monkeypatch.setenv("MOBILERUN_MACRO_STATE_TIMEOUT", "12") monkeypatch.setenv("MOBILERUN_MACRO_STATE_THRESHOLD", "0.4") monkeypatch.setenv("MOBILERUN_MACRO_DELAY", "2") monkeypatch.setenv("MOBILERUN_MACRO_POLL_INTERVAL", "0.3") - player = MacroPlayer() + device = fake_device() + player = MacroPlayer(device) assert (player.delay_between_actions, player.state_timeout) == (2, 12) assert (player.state_threshold, player.state_poll_interval) == (0.4, 0.3) monkeypatch.setenv("MOBILERUN_MACRO_STATE_TIMEOUT", "13") - assert MacroPlayer().state_timeout == 13 - assert MacroPlayer(state_timeout=7).state_timeout == 7 + assert MacroPlayer(device).state_timeout == 13 + assert MacroPlayer(device, state_timeout=7).state_timeout == 7 def test_macro_matcher_threshold_reads_environment(monkeypatch): diff --git a/tests/unit/architecture/test_public_surface.py b/tests/unit/architecture/test_public_surface.py index 40a5bd9e3..f989395fd 100644 --- a/tests/unit/architecture/test_public_surface.py +++ b/tests/unit/architecture/test_public_surface.py @@ -1,111 +1,42 @@ -"""Public Python and CLI contracts: exports, imports, device behavior, and command names.""" +"""Public Python and CLI contracts: exports, imports, and command names.""" import asyncio import importlib.util import inspect import subprocess import sys -from unittest.mock import AsyncMock, Mock import pytest from click.testing import CliRunner -from mobilerun import AndroidDevice, RecordingDevice, StealthDevice from mobilerun.cli.app import cli -from mobilerun.core.devices import Device -from mobilerun.core.devices.components.wrapper import DriverDevice -from mobilerun.core.state import StateProvider, StateProviderOptions, UIState -from mobilerun.errors import DeviceNotReady, DeviceOperationNotSupported - -DEVICE_NAMES = { - "supported_operations", - "extensions", - "actions", - "context", - "cloud_id", - "unbind_extension", - "close", - "connect", - "delete_file", - "do", - "drag", - "expect", - "get_clipboard", - "get_location", - "get_language", - "get_timezone", - "identifier", - "input_text", - "install_apk", - "install_app", - "known_codes_redactor", - "register_sensitive_values", - "list_apps", - "list_files", - "mailbox", - "number", - "open_url", - "platform", - "recording_allowed", - "recording_device", - "press_button", - "press_key_code", - "pull_file", - "push_file", - "reset_location", - "screenshot", - "set_clipboard", - "set_language", - "set_location", - "set_timezone", - "start_app", - "state", - "stop_app", - "supported_buttons", - "swipe", - "tap", - "tap_element", - "uninstall_app", - "wait", -} - -def test_exact_device_cloud_and_pool_surfaces(): - from mobilerun import CloudDevice, DevicePool - - assert {n for n in dir(Device) if not n.startswith("_")} == DEVICE_NAMES - assert {n for n in dir(CloudDevice) if not n.startswith("_")} == DEVICE_NAMES | { - "info", - "name", - "reboot", - "rename", - "reset", - "resume", - "stop", - "terminate", - "wait_ready", - } - pool = DevicePool([Device()]) - assert {n for n in dir(pool) if not n.startswith("_")} == ( - DEVICE_NAMES - - { - "identifier", - "pull_file", - "cloud_id", - "known_codes_redactor", - "register_sensitive_values", - "recording_device", - "recording_allowed", - } - ) | {"devices", "bind_each"} +CORE_EXPORTS = { + "Workspace": "workspace", + "CloudFixedProxy": "proxy.cloud_fixed", + "CloudRotatingProxy": "proxy.cloud_rotating", + "CloudSocks5Proxy": "proxy.cloud_socks5", +} def test_exact_root_and_core_exports(): import mobilerun import mobilerun.core - import mobilerun.core.devices + import mobilerun.core.proxy + from mobilerun import PLUGIN_API_VERSION + from mobilerun.version import PLUGIN_API_VERSION as declared_plugin_api_version - devices = { + assert set(mobilerun.core.__all__) == set(CORE_EXPORTS) + assert set(mobilerun.__all__) == CORE_EXPORTS.keys() | { + "__version__", + "DeviceConfig", + "LoggingConfig", + "MobileConfig", + "PLUGIN_API_VERSION", + } + assert type(PLUGIN_API_VERSION) is int + assert PLUGIN_API_VERSION == declared_plugin_api_version + for name in { "Device", "AndroidDevice", "CloudDevice", @@ -114,78 +45,20 @@ def test_exact_root_and_core_exports(): "DevicePool", "RecordingDevice", "StealthDevice", - } - proxies = { - "CloudRotatingProxy", - "CloudFixedProxy", - "CloudSocks5Proxy", - "LocalProxy", - } - assert set(mobilerun.core.devices.__all__) == devices - assert set(mobilerun.core.__all__) == devices | proxies | {"Workspace"} - assert set(mobilerun.__all__) == devices | proxies | { - "Workspace", - "__version__", - "DeviceConfig", - "LoggingConfig", - "MobileConfig", + "AndroidDriver", + "DeviceDriver", + "RecordingDriver", + "VisualRemoteDevice", "TelemetryConfig", "TracingConfig", - } - for name in mobilerun.__all__: - assert getattr(mobilerun, name) is not None - for name in proxies: - assert getattr(mobilerun, name) is getattr(mobilerun.core, name) - assert getattr(mobilerun, name) is getattr(mobilerun.core.proxy, name) + }: + assert not hasattr(mobilerun, name) + assert not hasattr(mobilerun.core, name) for prefix in ("Rotating", "Fixed", "Socks5", "Http"): name = prefix + "Proxy" assert not hasattr(mobilerun, name) assert not hasattr(mobilerun.core, name) assert not hasattr(mobilerun.core.proxy, name) - for name in { - "AndroidDriver", - "DeviceDriver", - "RecordingDriver", - "VisualRemoteDevice", - }: - assert name not in vars(mobilerun) - - -def test_device_has_no_public_plumbing(): - removed = { - "attach_state_provider", - "attach_state_provider_factory", - "default_state_provider", - "use_default_state_provider", - "attach_operator", - "default_operator", - "operator", - "unwrap", - "initialize", - "ensure_connected", - "needs_initialization", - "get_apps", - "list_packages", - "ui_state", - "recording", - "state_recovery", - "input_coordinate_size", - "get_ui_tree", - "get_date", - "is_cloud", - "push_workspace_file", - "supported", - } - assert removed.isdisjoint(dir(Device)) - assert { - "connect", - "state", - "supported_operations", - "tap", - "tap_element", - "do", - "expect", - } <= set(dir(Device)) def test_legacy_agent_root_export_is_absent(): @@ -196,7 +69,7 @@ def test_legacy_agent_root_export_is_absent(): _ = mobilerun.MobileAgentState -def test_workspace_methods_are_classmethods(): +def test_workspace_operations_use_bound_connection_settings(): from mobilerun import Workspace expected = { @@ -209,12 +82,12 @@ def test_workspace_methods_are_classmethods(): "get_app", "delete_app", "push_file", + "pull_file", } assert {name for name in vars(Workspace) if not name.startswith("_")} == expected - assert all( - isinstance(inspect.getattr_static(Workspace, name), classmethod) - for name in expected - ) + for name in expected: + parameters = inspect.signature(getattr(Workspace(), name)).parameters + assert not {"api_key", "base_url", "billing", "client"}.intersection(parameters) @pytest.mark.parametrize("suffix", ["telemetry", "credential_manager"]) @@ -270,44 +143,28 @@ def test_simple_import_does_not_load_backends(statement: str) -> None: import sys {statement} for prefix in ('mobilerun_sdk', 'adbutils', 'async_adbutils', 'httpx', 'PIL', - 'mobilerun.core.devices.android', 'mobilerun.clients.cloud'): + 'mobilerun_core_local', 'mobilerun.clients.cloud.client'): loaded = [name for name in sys.modules if name == prefix or name.startswith(prefix + '.')] assert not loaded, (prefix, loaded) """) def test_public_exports_resolve_to_original_objects() -> None: - run_python(""" -import mobilerun -from importlib import import_module -modules = { - 'Device': 'devices.base', 'AndroidDevice': 'devices.android', - 'CloudDevice': 'devices.cloud', 'IOSDevice': 'devices.ios', - 'RemoteDevice': 'devices.remote', 'DevicePool': 'devices.pool', - 'RecordingDevice': 'devices.recording', 'StealthDevice': 'devices.stealth', - 'Workspace': 'workspace', 'CloudFixedProxy': 'proxy.cloud_fixed', - 'CloudRotatingProxy': 'proxy.cloud_rotating', - 'CloudSocks5Proxy': 'proxy.cloud_socks5', 'LocalProxy': 'proxy.local', -} -assert set(mobilerun._CORE_EXPORTS) == set(modules) -assert all(getattr(mobilerun, name) is not None for name in mobilerun.__all__) -for name, module in modules.items(): - assert getattr(mobilerun, name) is getattr(import_module('mobilerun.core.' + module), name) -assert set(mobilerun.__all__) <= set(dir(mobilerun)) -namespace = {} -exec('from mobilerun import *', namespace) -assert all(namespace[name] is getattr(mobilerun, name) for name in mobilerun.__all__) -""") - + import mobilerun + import mobilerun.core -def test_generic_device_does_not_import_concrete_backends() -> None: - run_python(""" -import sys -from mobilerun import Device -assert Device.__name__ == 'Device' -assert 'mobilerun.core.devices.android' not in sys.modules -assert 'mobilerun.clients.cloud' not in sys.modules -""") + namespace: dict[str, object] = {} + exec("from mobilerun import *", namespace) + assert set(mobilerun.__all__) <= set(dir(mobilerun)) + assert set(mobilerun.core.__all__) <= set(dir(mobilerun.core)) + for name in mobilerun.__all__: + assert namespace[name] is getattr(mobilerun, name) is not None + for name, module in CORE_EXPORTS.items(): + defining_module = importlib.import_module(f"mobilerun.core.{module}") + assert getattr(mobilerun, name) is getattr(mobilerun.core, name) + assert getattr(mobilerun, name) is getattr(defining_module, name) + if module.startswith("proxy."): + assert getattr(mobilerun, name) is getattr(mobilerun.core.proxy, name) @pytest.mark.parametrize("option", ["--help", "--version"]) @@ -344,111 +201,9 @@ def test_async_prompt_loader_renders_file(tmp_path): ) -@pytest.mark.parametrize("wrapper", [RecordingDevice, StealthDevice]) -def test_explicit_wrapper_factory_replaces_inherited_provider(wrapper): - inner = Device(state_provider=StateProvider(Device())) - factory = Mock(side_effect=lambda device, options: StateProvider(device)) - options = StateProviderOptions(vision=True) - outer = wrapper(inner, state_provider_factory=factory, state_options=options) - assert outer.state._resolved_provider._device is outer - factory.assert_called_once_with(outer, options) - - -@pytest.mark.parametrize("wrapper", [RecordingDevice, StealthDevice]) -def test_wrapper_rejects_conflicting_explicit_provider_and_factory(wrapper): - with pytest.raises(TypeError, match="state_provider or state_provider_factory"): - wrapper( - Device(), - state_provider=StateProvider(Device()), - state_provider_factory=lambda device, options: StateProvider(device), - ) - - -def test_state_controller_caches_returned_snapshot(): - snapshot = UIState( - elements=[], - formatted_text="ready", - focused_text="", - phone_state={}, - screen_width=100, - screen_height=200, - ) - provider = StateProvider(Device()) - provider.get_state = AsyncMock(return_value=snapshot) - phone = Device(state_provider=provider) - with pytest.raises(DeviceNotReady, match="refresh"): - _ = phone.state.current - assert asyncio.run(phone.state.refresh()) is snapshot - assert phone.state.current is snapshot - assert {name for name in dir(phone.state) if not name.startswith("_")} == { - "refresh", - "current", - "capabilities", - } - - -def test_driver_connect_is_idempotent_and_translates_unsupported(): - raw = Mock() - raw.connect = AsyncMock(side_effect=NotImplementedError("no connect")) - - def factory(device, options): - return StateProvider(device) - - phone = DriverDevice(raw, state_provider_factory=factory) - with pytest.raises(DeviceOperationNotSupported, match="no connect"): - asyncio.run(phone.connect()) - raw.connect.side_effect = None - asyncio.run(phone.connect()) - asyncio.run(phone.connect()) - assert raw.connect.await_count == 2 - - -def test_android_constructor_exposes_typed_state_configuration(): - names = inspect.signature(AndroidDevice).parameters - assert { - "state_provider", - "state_provider_factory", - "state_options", - "operator", - } <= names.keys() - - -def test_ios_cannot_cache_wrong_provider_before_detection(monkeypatch): - from mobilerun import IOSDevice - from mobilerun.core.state.android import AndroidStateProvider - - phone = IOSDevice("http://local") - with pytest.raises(DeviceNotReady): - _ = phone.state.capabilities - monkeypatch.setattr( - "mobilerun.core.devices.ios.detect_ios_portal_kind", - AsyncMock(return_value="portal-http"), - ) - monkeypatch.setattr(phone, "_ensure_connected", AsyncMock()) - asyncio.run(phone.connect()) - assert isinstance(phone.state._resolved_provider, AndroidStateProvider) - - -def test_android_text_boundary_matches_raw_driver_signature(monkeypatch): - typed = [] - - async def input_text(self, text, clear=False): - typed.append((text, clear)) - return True - - monkeypatch.setattr( - "mobilerun.core.devices.android.AndroidDriver.input_text", input_text - ) - phone = AndroidDevice("fake") - phone._driver.ensure_connected = AsyncMock() - assert asyncio.run(phone.input_text("hello", clear=True)) - assert typed == [("hello", True)] - - @pytest.mark.parametrize( "command", [ - "run", "configure", "devices", "login", @@ -469,6 +224,7 @@ async def input_text(self, text, clear=False): "device press", "device apps", "device start", + "device action", ], ) def test_removed_cli_alias(command): diff --git a/tests/unit/cli/devices/test_app_file_commands.py b/tests/unit/cli/devices/test_app_file_commands.py new file mode 100644 index 000000000..467750022 --- /dev/null +++ b/tests/unit/cli/devices/test_app_file_commands.py @@ -0,0 +1,455 @@ +"""App and file CLI contracts with a fake core connection owner.""" + +import json +from collections.abc import Awaitable, Callable +from dataclasses import replace +from datetime import UTC, datetime +from inspect import signature +from pathlib import Path +from typing import Any +from unittest.mock import AsyncMock + +import pytest +from click.testing import CliRunner +from mobilerun_core import ( + AppIdentity, + AsyncDevice, + FileEntry, + InstalledApp, +) +from mobilerun_core.errors import AppOperationError + +from mobilerun.cli.base import menu +from mobilerun.cli.devices import device +from mobilerun.cli.devices.base import selection +from mobilerun.cli.devices.utils import approval +from mobilerun.cli.devices.utils.prompts import pickers, source +from mobilerun.clients.cloud import client as cloud_client +from mobilerun.core.workspace import Workspace +from mobilerun.models import App, WorkspaceFile +from tests.support.devices import FakeDriver, fake_device + +_CORE_SCAN = "scan_media" in signature(AsyncDevice.push_file).parameters +_WORKSPACE_SCAN = "scan_media" in signature(Workspace.push_file).parameters + + +@pytest.fixture +def driver(monkeypatch: pytest.MonkeyPatch) -> FakeDriver: + fake = FakeDriver( + device_id="serial", apps=[{"label": "Browser", "package": "com.browser"}] + ) + + class Factory: + def __init__( + self, *, hitl_gate: Callable[..., Awaitable[bool]], **kwargs: Any + ) -> None: + self.gate = hitl_gate + self.phone: AsyncDevice | None = None + + async def __aenter__(self) -> "Factory": + return self + + async def __aexit__(self, *args: object) -> None: + if self.phone is not None: + await self.phone.aclose() + fake.calls.append(("close", (), {})) + + async def connect(self, target: str, **kwargs: Any) -> AsyncDevice: + fake.calls.append(("connect", (target,), {})) + self.phone = fake_device(driver=fake, hitl_gate=self.gate) + info = replace( + self.phone.info(), backend=kwargs.get("backend") or "local-android-adb" + ) + monkeypatch.setattr(self.phone, "info", lambda: info) + + # The caller-driver backend has no native install, list or delete + # route. Stub their public facade methods; exercise the real gate. + async def install(source: object, **options: Any) -> InstalledApp: + action = "device.install_app" + details = { + "device_id": self.phone.device_id, + "source": source, + **options, + } + assert await self.gate(action, details) + fake.calls.append(("install_app", (source,), options)) + return InstalledApp(AppIdentity("org.example", 10, "1.0"), "Example") + + async def list_files(directory: str) -> list[FileEntry]: + fake.calls.append(("list_files", (directory,), {})) + return [FileEntry(f"{directory}/a.txt", "a.txt", 3, None, "file")] + + async def delete_file(path: str) -> None: + operation = "device.delete_file" + args = {"device_id": self.phone.device_id, "device_path": path} + assert await self.gate(operation, args) + fake.calls.append(("delete_file", (path,), {})) + + monkeypatch.setattr(self.phone, "install_app", install) + monkeypatch.setattr(self.phone, "list_files", list_files) + monkeypatch.setattr(self.phone, "delete_file", delete_file) + if _CORE_SCAN: + core_push = self.phone.push_file + + async def push_file( + source: bytes | str, path: str, *, scan_media: bool = False + ) -> None: + # The fake caller driver has no Android scan route. + await core_push(source, path) + if scan_media: + fake.calls.append(("scan_media", (path,), {})) + + monkeypatch.setattr(self.phone, "push_file", push_file) + return self.phone + + monkeypatch.setattr(selection, "AsyncMobilerun", Factory) + monkeypatch.setattr(selection.LoginStore, "resolve_api_key", lambda self: "test") + return fake + + +@pytest.mark.parametrize( + "args, call, stdout", + [ + ( + ["start", "org.example"], + ("start_app", ("org.example",), {"activity": None}), + "✓ serial: Started org.example\n", + ), + ( + ["stop", "org.example"], + ("stop_app", ("org.example",), {}), + "✓ Stopped org.example on serial\n", + ), + ( + ["open", "example://open"], + ("open_deep_link", ("example://open",), {"package": None, "action": None}), + "✓ Opened example://open on serial\n", + ), + ], + ids=["start", "stop", "open"], +) +def test_app_actions( + driver: FakeDriver, args: list[str], call: tuple, stdout: str +) -> None: + result = CliRunner().invoke(device, ["app", *args, "serial"]) + assert result.exit_code == 0, result.output + assert result.stdout == stdout + assert driver.calls == [("connect", ("serial",), {}), call, ("close", (), {})] + + +@pytest.mark.parametrize("machine", [False, True], ids=["plain", "json"]) +def test_app_list_preserves_output(driver: FakeDriver, machine: bool) -> None: + args = ["app", "list", "serial", "--system"] + result = CliRunner().invoke(device, [*args, "--json"] if machine else args) + assert result.exit_code == 0, result.output + if machine: + assert json.loads(result.stdout) == [ + {"label": "Browser", "app_id": "com.browser"} + ] + else: + assert result.stdout == "Apps · 1\n\nBrowser com.browser\n" + assert driver.calls[1] == ("get_apps", (), {"include_system": True}) + + +@pytest.mark.parametrize("workspace", [False, True], ids=["apk", "workspace"]) +def test_install_forwards_source_and_flags( + driver: FakeDriver, monkeypatch: pytest.MonkeyPatch, tmp_path: Path, workspace: bool +) -> None: + if workspace: + lookup = AsyncMock( + return_value=App(AppIdentity("org.example", 10, "1.0"), "Example", "asset") + ) + monkeypatch.setattr(Workspace, "get_app", lookup) + source: str | AppIdentity = AppIdentity("org.example", 10, "1.0") + args = ["--app-id", "asset", "serial", "--cloud"] + else: + path = tmp_path / "a.apk" + path.write_bytes(b"apk") + source = str(path) + args = [source, "serial", "--no-grant"] + monkeypatch.setattr(approval, "is_interactive", lambda: False) + result = CliRunner().invoke( + device, ["app", "install", *args, "--reinstall", "--yes"] + ) + assert result.exit_code == 0, result.output + assert result.stdout == "✓ serial: Installed org.example 1.0\n" + assert result.stderr == "Installing on serial…\n" + action, sources, options = driver.calls[1] + assert (action, sources) == ("install_app", (source,)) + assert options["reinstall"] is True + assert options["grant_permissions"] is workspace + if workspace: + lookup.assert_awaited_once_with("asset") + + +@pytest.mark.parametrize("machine", [False, True], ids=["plain", "json"]) +def test_file_list_renders_entries(driver: FakeDriver, machine: bool) -> None: + args = ["file", "list", "/files", "serial"] + result = CliRunner().invoke(device, [*args, "--json"] if machine else args) + assert result.exit_code == 0, result.output + if machine: + assert json.loads(result.stdout) == [ + { + "path": "/files/a.txt", + "name": "a.txt", + "size_bytes": 3, + "modified_at": None, + "kind": "file", + } + ] + else: + assert result.stdout == "Files · 1\n\n/files/a.txt\n" + assert driver.calls[1] == ("list_files", ("/files",), {}) + + +@pytest.mark.parametrize( + "name, flags, remote", + [ + pytest.param( + "a.png", + [], + "/sdcard/DCIM/Camera/a.png", + marks=pytest.mark.xfail( + not _CORE_SCAN, + strict=True, + reason="core push_file(scan_media=) landing", + ), + ), + ("a.txt", [], "/sdcard/Download/a.txt"), + ("a.txt", ["--dest", "/custom/"], "/custom/a.txt"), + ], +) +def test_push_uses_legacy_destination( + driver: FakeDriver, tmp_path: Path, name: str, flags: list[str], remote: str +) -> None: + path = tmp_path / name + path.write_bytes(b"\xff\x00") + result = CliRunner().invoke(device, ["file", "push", str(path), *flags, "serial"]) + assert result.exit_code == 0, result.output + assert result.stdout == f"{remote}\n" + assert result.stderr == "Pushing to serial…\n" + assert driver.calls[1] == ("push_file", (str(path), remote), {}) + assert driver.files[remote] == b"\xff\x00" + assert driver.calls[2:-1] == ( + [("scan_media", (remote,), {})] if name == "a.png" else [] + ) + + +@pytest.mark.parametrize( + "cloud", + [ + True, + pytest.param( + False, + ), + ], + ids=["cloud", "local-adb"], +) +def test_push_workspace_file( + driver: FakeDriver, monkeypatch: pytest.MonkeyPatch, cloud: bool +) -> None: + item = WorkspaceFile("asset", "image.png", "image/png", 3, datetime.now(UTC)) + monkeypatch.setattr(Workspace, "list_files", AsyncMock(return_value=[item])) + client = AsyncMock() + client.__aenter__.return_value = client + response = AsyncMock() + response.read.return_value = b"png" + client.files.with_raw_response.download.return_value = response + monkeypatch.setattr(cloud_client, "cloud_client", lambda *args, **kwargs: client) + result = CliRunner().invoke( + device, + [ + "file", + "push", + "--file-id", + "asset", + "serial", + *(["--cloud"] if cloud else []), + ], + ) + assert result.exit_code == 0, result.output + assert result.stdout == "/sdcard/DCIM/Camera/image.png\n" + assert driver.calls[1] == ( + "push_file", + (b"png", "/sdcard/DCIM/Camera/image.png"), + {}, + ) + assert driver.calls[2:-1] == ( + [] if cloud else [("scan_media", ("/sdcard/DCIM/Camera/image.png",), {})] + ) + + +def test_pull_writes_binary_to_local_directory( + driver: FakeDriver, tmp_path: Path +) -> None: + driver.files["/files/a.bin"] = b"\xff\x00" + result = CliRunner().invoke( + device, ["file", "pull", "/files/a.bin", str(tmp_path), "serial"] + ) + assert result.exit_code == 0, result.output + path = tmp_path / "a.bin" + assert path.read_bytes() == b"\xff\x00" + assert result.stdout == f"{path}\n" + assert result.stderr == "Pulling from serial…\n" + assert driver.calls[1] == ("pull_file", ("/files/a.bin",), {}) + + +def test_push_prompts_for_source_after_connecting(driver, monkeypatch, tmp_path): + path = tmp_path / "a.txt" + path.write_bytes(b"hello") + monkeypatch.setattr(source, "is_interactive", lambda: True) + + async def choose(*args): + assert driver.calls == [("connect", ("serial",), {})] + return "local" + + monkeypatch.setattr(source, "select_prompt_async", choose) + monkeypatch.setattr(source, "text_prompt_async", AsyncMock(return_value=str(path))) + result = CliRunner().invoke(device, ["file", "push", "--device", "serial"]) + assert result.exit_code == 0, result.output + assert result.stdout == "/sdcard/Download/a.txt\n" + assert driver.files["/sdcard/Download/a.txt"] == b"hello" + + +@pytest.mark.parametrize( + "group,verb,flag", [("app", "install", "--app-id"), ("file", "push", "--file-id")] +) +@pytest.mark.parametrize("conflict", [False, True], ids=["missing", "conflicting"]) +def test_bad_transfer_source_never_opens_device( + driver, tmp_path, group, verb, flag, conflict +): + args = [group, verb, "--device", "serial"] + if conflict: + path = tmp_path / "input.apk" + path.write_bytes(b"data") + args.extend([str(path), flag, "workspace-id"]) + result = CliRunner().invoke(device, args) + assert result.exit_code == 2, result.output + assert ("not both" if conflict else "Provide a local path") in result.stderr + assert driver.calls == [] + + +@pytest.mark.parametrize("case", ["yes", "approve", "denied", "noninteractive"]) +def test_rm_uses_core_approval( + driver: FakeDriver, + monkeypatch: pytest.MonkeyPatch, + case: str, +) -> None: + interactive = case in {"approve", "denied"} + monkeypatch.setattr(approval, "is_interactive", lambda: interactive) + prompt = AsyncMock(return_value=case == "approve") + monkeypatch.setattr(approval, "confirm_prompt_async", prompt) + flags = ["--yes"] if case == "yes" else [] + operand = "/files/a.txt" + result = CliRunner().invoke(device, ["file", "rm", operand, "serial", *flags]) + if interactive: + prompt.assert_awaited_once_with("Approve device delete file?", default=False) + else: + prompt.assert_not_awaited() + approved = case in {"yes", "approve"} + assert result.exit_code == (0 if approved else 1), result.output + assert result.stdout == (f"✓ Deleted {operand} from serial\n" if approved else "") + assert driver.calls == [ + ("connect", ("serial",), {}), + *([("delete_file", (operand,), {})] if approved else []), + ("close", (), {}), + ] + if case == "noninteractive": + assert "--yes" in result.stderr + + +def test_uninstall_failure_prints_package_manager_status(driver: FakeDriver) -> None: + driver.failures["uninstall_app"] = AppOperationError( + "App uninstall failed", reason="DELETE_FAILED_INTERNAL_ERROR" + ) + result = CliRunner().invoke( + device, ["app", "uninstall", "org.example", "serial", "--android", "--yes"] + ) + assert result.exit_code == 1 + assert result.stdout == "" + assert ( + result.stderr == "Error: App uninstall failed: DELETE_FAILED_INTERNAL_ERROR\n" + ) + + +@pytest.mark.parametrize("case", ["yes", "approve", "denied", "noninteractive"]) +def test_uninstall_uses_core_approval(driver, monkeypatch, case): + interactive = case in {"approve", "denied"} + monkeypatch.setattr(approval, "is_interactive", lambda: interactive) + prompt = AsyncMock(return_value=case == "approve") + monkeypatch.setattr(approval, "confirm_prompt_async", prompt) + flags = ["--yes"] if case == "yes" else [] + result = CliRunner().invoke( + device, ["app", "uninstall", "org.example", "serial", *flags] + ) + approved = case in {"yes", "approve"} + assert result.exit_code == (0 if approved else 1), result.output + assert driver.calls == [ + ("connect", ("serial",), {}), + *([("uninstall_app", ("org.example",), {})] if approved else []), + ("close", (), {}), + ] + if interactive: + prompt.assert_awaited_once_with( + "Approve device uninstall app (app data will be deleted)?", default=False + ) + else: + prompt.assert_not_awaited() + if case == "noninteractive": + assert "--yes" in result.stderr + + +def test_uninstall_picker_prompts_for_approval_after_choice( + driver: FakeDriver, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(menu, "is_interactive", lambda: True) + monkeypatch.setattr(pickers, "is_interactive", lambda: True) + monkeypatch.setattr(approval, "is_interactive", lambda: True) + pick = AsyncMock(return_value="com.browser") + monkeypatch.setattr(pickers, "select_prompt_async", pick) + + async def confirm(*args, **kwargs): + pick.assert_awaited_once() + return True + + prompt = AsyncMock(side_effect=confirm) + monkeypatch.setattr(approval, "confirm_prompt_async", prompt) + result = CliRunner().invoke(device, ["app", "uninstall", "--device", "serial"]) + assert result.exit_code == 0, result.output + assert "✓ Uninstalled com.browser from serial" in result.stdout + prompt.assert_awaited_once() + assert driver.calls[1:3] == [ + ("get_apps", (), {"include_system": False}), + ("uninstall_app", ("com.browser",), {}), + ] + + +def test_stop_sanitizes_transport_error_and_closes(driver: FakeDriver) -> None: + driver.failures["stop_app"] = RuntimeError("sensitive transport details") + result = CliRunner().invoke(device, ["app", "stop", "org.example", "serial"]) + assert result.exit_code == 1 + assert result.stdout == "" + assert result.stderr == "Error: stop_app request failed\n" + assert "sensitive transport details" not in result.output + assert driver.calls[1:] == [("stop_app", ("org.example",), {}), ("close", (), {})] + + +def test_open_prompts_for_url_after_connecting(driver, monkeypatch): + async def prompt(_): + assert driver.calls == [("connect", ("serial",), {})] + return "example://open" + + monkeypatch.setattr(pickers, "is_interactive", lambda: True) + monkeypatch.setattr(pickers, "text_prompt_async", prompt) + result = CliRunner().invoke(device, ["app", "open", "--device", "serial"]) + assert result.exit_code == 0, result.output + assert result.stdout == "✓ Opened example://open on serial\n" + + +def test_noninteractive_install_refuses_without_yes(driver, tmp_path): + path = tmp_path / "app.apk" + path.write_bytes(b"apk") + result = CliRunner().invoke(device, ["app", "install", str(path), "serial"]) + assert result.exit_code == 1, result.output + assert "--yes" in result.stderr + assert not any(call[0] == "install_app" for call in driver.calls) diff --git a/tests/unit/cli/devices/test_cloud_commands.py b/tests/unit/cli/devices/test_cloud_commands.py new file mode 100644 index 000000000..04c1fd62c --- /dev/null +++ b/tests/unit/cli/devices/test_cloud_commands.py @@ -0,0 +1,398 @@ +"""Cloud CLI contract at the core factory seam; no SDK or phone connection.""" + +import json +from typing import Any +from unittest.mock import AsyncMock, Mock + +import click +import pytest +from click.testing import CliRunner, Result +from mobilerun_core import CloudLifecycleError, DeviceDescriptor, HitlDenied + +from mobilerun.cli.app import cli +from mobilerun.cli.base import choices +from mobilerun.cli.devices.base import device, selection +from mobilerun.cli.devices.utils import approval +from mobilerun.cli.devices.utils.prompts import pickers +from mobilerun.config.user_config import MobileConfig +from mobilerun.errors.cloud import BillingRequired +from mobilerun.models.billing import Billing + +CLOUD = "11111111-1111-1111-1111-111111111111" + + +def invoke(*args: str) -> Result: + return CliRunner().invoke(cli, ["device", "cloud", *args]) + + +def record(**overrides: Any) -> DeviceDescriptor: + return DeviceDescriptor( + **{ + "device_id": CLOUD, + "backend": "cloud", + "name": "Phone", + "state": "stopped", + "platform": "android", + "device_type": "android_cloud_phone", + "billing_strategy": "minute", + "country": "US", + "stop_reason": "user_requested", + **overrides, + } + ) + + +class FakeRun: + def __init__(self) -> None: + self.metadata: Any = None + self.device_id = CLOUD + self.list_devices = AsyncMock(return_value=[]) + self.list_cloud_devices = AsyncMock(return_value=[]) + self.connect = AsyncMock(side_effect=AssertionError("unexpected phone attach")) + self.refresh = AsyncMock(side_effect=lambda: self.metadata) + self.dispatch = AsyncMock() + self.cloud_device = Mock(return_value=self) + self.open = Mock(side_effect=self.configure) + self.closed = Mock() + + def configure(self, **kwargs: Any) -> "FakeRun": + self.gate = kwargs["hitl_gate"] + return self + + async def __aenter__(self) -> "FakeRun": + return self + + async def __aexit__(self, *exc: Any) -> None: + self.closed() + + async def mutate(self, verb: str, *args: str) -> None: + details: dict[str, Any] = {"device_id": CLOUD} + if verb == "resume": + details["may_be_charged"] = self.metadata.billing_strategy != "subscription" + if not await self.gate(f"device.{verb}", details): + raise HitlDenied(f"device.{verb}", "not approved") + await self.dispatch(verb, *args) + + async def stop(self) -> None: + await self.mutate("stop") + + async def resume(self) -> None: + await self.mutate("resume") + + async def reboot(self) -> None: + await self.mutate("reboot") + + async def rename(self, name: str) -> DeviceDescriptor: + await self.mutate("rename", name) + return record(name=name) + + async def terminate(self) -> None: + await self.mutate("terminate") + + +@pytest.fixture +def run(monkeypatch: pytest.MonkeyPatch) -> FakeRun: + fake = FakeRun() + monkeypatch.setattr(selection, "AsyncMobilerun", fake.open) + monkeypatch.setattr( + selection.LoginStore, "resolve_api_key", lambda self: "test-bearer" + ) + monkeypatch.setattr(device.ConfigLoader, "load", lambda _: MobileConfig()) + monkeypatch.setenv("MOBILERUN_BILLING", "paid") + return fake + + +def interactive(monkeypatch: pytest.MonkeyPatch, *, accepted: bool) -> AsyncMock: + prompt = AsyncMock(return_value=accepted) + monkeypatch.setattr(approval, "is_interactive", lambda: True) + monkeypatch.setattr(approval, "confirm_prompt_async", prompt) + return prompt + + +def test_status_json_only_prints_status_fields(run: FakeRun) -> None: + run.metadata = record() + result = invoke("status", CLOUD, "--json") + assert result.exit_code == 0, result.output + assert json.loads(result.stdout) == { + "id": CLOUD, + "name": "Phone", + "state": "stopped", + "platform": "android", + "type": "android_cloud_phone", + "billing_strategy": "minute", + "stop_reason": "user_requested", + } + run.refresh.assert_awaited_once_with() + run.dispatch.assert_not_awaited() + + +@pytest.mark.parametrize("verb", ["stop", "rename", "resume", "reboot", "terminate"]) +def test_mutations_use_one_shared_yes_option(verb: str) -> None: + result = invoke(verb, "--help") + assert result.exit_code == 0 and result.stdout.count("--yes") == 1 + + +@pytest.mark.parametrize( + "verb,message", + [ + ("status", "stopped"), + ("stop", "Stopped"), + ("reboot", "Rebooted"), + ("terminate", "Terminated"), + ], +) +def test_cloud_lifecycle_without_phone_connect( + run: FakeRun, verb: str, message: str +) -> None: + run.metadata = record() + flags = ("--yes",) if verb != "status" else () + result = invoke(verb, "-d", CLOUD, "--base-url", "https://example.invalid", *flags) + assert result.exit_code == 0, result.output + if verb == "status": + run.refresh.assert_awaited_once_with() + assert "Phone" in result.stdout and message in result.stdout + else: + run.dispatch.assert_awaited_once_with(verb) + assert f"{message} {CLOUD}" in result.stdout + assert run.open.call_args.kwargs["base_url"] == "https://example.invalid" + assert run.open.call_args.kwargs["bearer"] == "test-bearer" + run.cloud_device.assert_called_once_with(CLOUD) + run.closed.assert_called_once_with() + run.connect.assert_not_awaited() + + +@pytest.mark.parametrize("verb", ["stop", "reboot", "terminate", "resume"]) +def test_mutation_without_yes_refuses_noninteractively(run: FakeRun, verb: str) -> None: + run.metadata = record() + result = invoke(verb, CLOUD) + assert result.exit_code == 1 and "--yes" in result.stderr, result.output + run.dispatch.assert_not_awaited() + run.closed.assert_called_once_with() + + +def test_stop_remains_nonbillable_and_uses_core_approval( + run: FakeRun, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("MOBILERUN_BILLING", "no_commerce") + prompt = interactive(monkeypatch, accepted=True) + result = invoke("stop", CLOUD) + assert result.exit_code == 0 and f"Stopped {CLOUD}" in result.stdout + prompt.assert_awaited_once_with("Approve device stop?", default=False) + run.dispatch.assert_awaited_once_with("stop") + + +@pytest.mark.parametrize("verb", ["reboot", "terminate"]) +@pytest.mark.parametrize("accepted", [True, False]) +def test_destructive_mutation_uses_one_core_confirmation( + run: FakeRun, + monkeypatch: pytest.MonkeyPatch, + verb: str, + accepted: bool, +) -> None: + prompt = interactive(monkeypatch, accepted=accepted) + result = invoke(verb, CLOUD) + assert result.exit_code == (0 if accepted else 1), result.output + prompt.assert_awaited_once_with(f"Approve device {verb}?", default=False) + if accepted: + run.dispatch.assert_awaited_once_with(verb) + else: + run.dispatch.assert_not_awaited() + + +@pytest.mark.parametrize("strategy", ["subscription", "minute", "auto", None]) +def test_no_commerce_blocks_resume_even_with_yes( + run: FakeRun, strategy: str | None +) -> None: + run.metadata = record(billing_strategy=strategy) + result = invoke("resume", CLOUD, "--billing", "no_commerce", "--yes") + assert result.exit_code == 1 and "billing" in result.stderr + run.open.assert_not_called() + + +@pytest.mark.parametrize("mode", ["paid", "included"]) +@pytest.mark.parametrize("strategy", ["minute", "auto", None, "subscription"]) +def test_resume_checks_strategy_on_same_handle_and_warns_for_metered( + run: FakeRun, monkeypatch: pytest.MonkeyPatch, mode: str, strategy: str | None +) -> None: + run.metadata = record(billing_strategy=strategy) + prompt = interactive(monkeypatch, accepted=True) + result = invoke("resume", CLOUD, "--billing", mode) + if mode == "included" and strategy != "subscription": + assert result.exit_code == 1 and "--billing paid" in result.stderr + run.refresh.assert_awaited_once_with() + run.dispatch.assert_not_awaited() + prompt.assert_not_awaited() + return + assert result.exit_code == 0, result.output + assert f"Resumed {CLOUD}" in result.stdout + run.cloud_device.assert_called_once_with(CLOUD) + run.refresh.assert_awaited_once_with() + run.dispatch.assert_awaited_once_with("resume") + prompt.assert_awaited_once() + assert prompt.await_args is not None + assert ("charges may apply" in prompt.await_args.args[0]) == ( + strategy != "subscription" + ) + + +@pytest.mark.parametrize("mode", ["included", "paid"]) +def test_subscription_resume_still_requires_approval_noninteractively( + run: FakeRun, mode: str +) -> None: + run.metadata = record(billing_strategy="subscription") + result = invoke("resume", CLOUD, "--billing", mode) + assert result.exit_code == 1 and "--yes" in result.stderr, result.output + run.dispatch.assert_not_awaited() + + +def test_no_commerce_blocks_even_interactive_device_discovery( + run: FakeRun, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(device, "is_interactive", lambda: True) + monkeypatch.setattr(pickers, "is_interactive", lambda: True) + result = invoke("resume", "--billing", "no_commerce", "--yes") + assert result.exit_code == 1 and "no_commerce" in result.stderr + run.open.assert_not_called() + + +def test_resume_declined_paid_consent_does_not_dispatch( + run: FakeRun, monkeypatch: pytest.MonkeyPatch +) -> None: + run.metadata = record() + prompt = interactive(monkeypatch, accepted=False) + result = invoke("resume", CLOUD, "--billing", "paid") + assert result.exit_code == 1 and "not approved" in result.stderr, result.output + prompt.assert_awaited_once() + run.dispatch.assert_not_awaited() + + +@pytest.mark.parametrize("strategy", ["subscription", "minute"]) +@pytest.mark.parametrize("mode", ["included", "paid"]) +def test_resume_yes_supplies_explicit_consent_without_prompt( + run: FakeRun, monkeypatch: pytest.MonkeyPatch, strategy: str, mode: str +) -> None: + run.metadata = record(billing_strategy=strategy) + prompt = interactive(monkeypatch, accepted=False) + result = invoke("resume", CLOUD, "--billing", mode, "-y") + if mode == "included" and strategy == "minute": + assert result.exit_code == 1 and "--billing paid" in result.stderr + prompt.assert_not_awaited() + run.dispatch.assert_not_awaited() + return + assert result.exit_code == 0, result.output + prompt.assert_not_awaited() + run.dispatch.assert_awaited_once_with("resume") + + +@pytest.mark.parametrize("strategy", ["subscription", "minute"]) +def test_resume_does_not_retry_after_dispatch(run: FakeRun, strategy: str) -> None: + run.metadata = record(billing_strategy=strategy) + run.dispatch.side_effect = BillingRequired( + needed=Billing.PAID, given=Billing.INCLUDED, operation="Resume cloud phone" + ) + result = invoke("resume", CLOUD, "--billing", "paid", "--yes") + assert result.exit_code == 1, result.output + run.dispatch.assert_awaited_once_with("resume") + + +@pytest.mark.parametrize("device_args", [(CLOUD,), ("-d", CLOUD)]) +def test_rename_arguments_and_json(run: FakeRun, device_args: tuple[str, ...]) -> None: + result = invoke( + "rename", + *device_args, + " New name ", + "--json", + "--yes", + "--base-url", + "https://example.invalid", + ) + assert result.exit_code == 0, result.output + assert json.loads(result.stdout) == {"id": CLOUD, "name": "New name"} + run.dispatch.assert_awaited_once_with("rename", "New name") + assert run.open.call_args.kwargs["base_url"] == "https://example.invalid" + + +def test_rename_prompts_after_selecting_device( + run: FakeRun, monkeypatch: pytest.MonkeyPatch +) -> None: + async def name_prompt(label: str) -> str: + assert label == "Name" + run.cloud_device.assert_called_once_with(CLOUD) + return " Phone " + + monkeypatch.setattr(pickers, "is_interactive", lambda: True) + monkeypatch.setattr(pickers, "text_prompt_async", name_prompt) + prompt = interactive(monkeypatch, accepted=True) + result = invoke("rename", CLOUD) + assert result.exit_code == 0 and f"✓ Renamed {CLOUD} to Phone" in result.stdout + prompt.assert_awaited_once_with("Approve device rename?", default=False) + run.dispatch.assert_awaited_once_with("rename", "Phone") + + +def test_rename_empty_prompt_cancels( + run: FakeRun, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(pickers, "is_interactive", lambda: True) + monkeypatch.setattr(pickers, "text_prompt_async", AsyncMock(return_value=" ")) + result = invoke("rename", CLOUD) + assert result.exit_code == 0, result.output + run.dispatch.assert_not_awaited() + run.closed.assert_called_once_with() + + +@pytest.mark.parametrize("name", [(), (" ",)]) +def test_rename_invalid_noninteractive_name( + run: FakeRun, name: tuple[str, ...] +) -> None: + result = invoke("rename", CLOUD, *name) + assert result.exit_code == 2 and "NAME" in result.stderr + run.dispatch.assert_not_awaited() + run.closed.assert_called_once_with() + + +@pytest.mark.parametrize("json_option", [(), ("--json",)]) +def test_rename_safe_core_error_is_reported_on_stderr( + run: FakeRun, json_option: tuple[str, ...] +) -> None: + error = CloudLifecycleError("rename", "request rejected", status_code=403) + error.__cause__ = RuntimeError("secret transport details") + run.dispatch.side_effect = error + result = invoke("rename", CLOUD, "New", "--yes", *json_option) + assert result.exit_code == 1 and str(error) in result.stderr + assert result.stdout == "" and "secret transport details" not in result.stderr + run.closed.assert_called_once_with() + + +@pytest.mark.parametrize("verb", ["rename", "status"]) +def test_omitted_cloud_id_picker_uses_only_cloud_choices( + run: FakeRun, monkeypatch: pytest.MonkeyPatch, verb: str +) -> None: + run.metadata = record() + run.list_cloud_devices.return_value = [record()] + monkeypatch.setattr(device, "is_interactive", lambda: True) + monkeypatch.setattr(pickers, "is_interactive", lambda: True) + monkeypatch.setattr(pickers, "text_prompt_async", AsyncMock(return_value="New")) + result = invoke(verb, "--yes") + assert result.exit_code == 0 and CLOUD in result.stdout, result.output + run.list_cloud_devices.assert_awaited_once_with() + run.list_devices.assert_not_awaited() + run.open.assert_called_once() + run.connect.assert_not_awaited() + + +def test_cloud_choices_order_labels_country_and_read_only(run: FakeRun) -> None: + run.list_cloud_devices.return_value = [ + record(device_id="sleep", name=None, country=None), + record(device_id="fast", name="Ready", state="running"), + ] + ctx = click.Context(click.Command("test")) + ctx.params["base_url"] = "https://example.invalid" + result = choices.cloud_devices(ctx) + assert [(item.value, item.label, item.hint) for item in result] == [ + ("fast", "Ready", "running · US"), + ("sleep", "sleep", "stopped"), + ] + run.list_cloud_devices.assert_awaited_once_with() + run.cloud_device.assert_not_called() + assert run.open.call_args.kwargs["base_url"] == "https://example.invalid" + run.closed.assert_called_once_with() diff --git a/tests/unit/cli/devices/test_core_device_command.py b/tests/unit/cli/devices/test_core_device_command.py new file mode 100644 index 000000000..5d9eecbc2 --- /dev/null +++ b/tests/unit/cli/devices/test_core_device_command.py @@ -0,0 +1,213 @@ +"""Device selection and lifetime through Click and a fake core owner.""" + +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import click +import pytest +from click.testing import CliRunner +from mobilerun_core import ( + AsyncDevice, + AsyncMobilerun, + CloudDeviceHandle, + DeviceDescriptor, +) + +from mobilerun.cli.devices.base import selection +from mobilerun.cli.devices.utils.connection import device as connection +from mobilerun.cli.devices.utils.connection.default import save_default_device +from mobilerun.config.loader import ConfigLoader +from mobilerun.config.user_config import DeviceConfig, MobileConfig +from tests.support.devices import FakeDriver + + +@pytest.fixture +def core(monkeypatch): + events = [] + phone = SimpleNamespace(device_id="chosen") + owner = SimpleNamespace( + connect=AsyncMock(return_value=phone), + list_devices=AsyncMock(), + cloud_device=lambda device_id: SimpleNamespace(device_id=device_id), + ) + + class Factory: + def __init__(self, **kwargs): + owner.options = kwargs + + async def __aenter__(self): + events.append("enter") + return owner + + async def __aexit__(self, *exc): + events.append("close") + + monkeypatch.setattr(selection, "AsyncMobilerun", Factory) + monkeypatch.setattr(selection.LoginStore, "resolve_api_key", lambda self: None) + return owner, events + + +@pytest.mark.parametrize( + "args,environment,expected", + [ + (["arg"], "env", "arg"), + (["--device", "flag"], "env", "flag"), + ([], "env", "env"), + ([], None, "saved"), + ], +) +def test_selection_precedence_without_discovery(core, args, environment, expected): + from mobilerun.cli.devices.base.device import device_command + + owner, events = core + save_default_device("saved") + + @click.command() + @device_command + async def show(device: AsyncDevice): + events.append(device.device_id) + + result = CliRunner().invoke(show, args, env={"ANDROID_SERIAL": environment}) + assert result.exit_code == 0, result.exception + assert owner.connect.await_args.args == (expected,) + owner.list_devices.assert_not_awaited() + assert events == ["enter", "chosen", "close"] + + +def test_noninteractive_without_target_does_not_discover(core): + from mobilerun.cli.devices.base.device import device_command + + owner, events = core + + @click.command() + @device_command + async def show(device: AsyncDevice): + pytest.fail("command ran without a device") + + result = CliRunner().invoke(show, []) + assert result.exit_code == 2 + assert "--device" in result.output + owner.list_devices.assert_not_awaited() + assert events == [] + + +@pytest.mark.parametrize("saved", [False, True], ids=["explicit", "saved"]) +def test_android_serial_applies_config_through_core_route(monkeypatch, saved): + from mobilerun.cli.devices.base.device import device_command + + serial = "usb-test" + ConfigLoader.save( + MobileConfig( + device=DeviceConfig( + serial=serial if saved else None, portal_mode="disabled", use_tcp=True + ) + ) + ) + opened = [] + + class AndroidTransport(FakeDriver): + def __init__(self, *, serial, portal_mode, use_tcp): + super().__init__(device_id=serial) + opened.append((serial, portal_mode, use_tcp)) + + async def connect(self): + pass + + monkeypatch.setattr( + "mobilerun_core.detect.adb_serial_present", lambda target: target == serial + ) + monkeypatch.setattr( + "mobilerun_core.async_mobilerun.local_module", + lambda: SimpleNamespace(AndroidDriver=AndroidTransport), + ) + + @click.command() + @device_command + async def show(device: AsyncDevice): + click.echo(device.device_id) + + result = CliRunner().invoke(show, [] if saved else [serial]) + assert result.exit_code == 0, result.exception + assert result.stdout == f"{serial}\n" + assert opened == [(serial, "disabled", True)] + + +@pytest.mark.parametrize("cancel", [False, True]) +def test_picker_redacts_url_and_runs_before_command_prompt(core, monkeypatch, cancel): + from mobilerun.cli.devices.base import device + + owner, events = core + url = "https://name:password@phone.test/private?token=secret" + owner.list_devices.return_value = [ + SimpleNamespace(info=lambda: DeviceDescriptor(url, "local-ios-http", "ios")), + SimpleNamespace( + info=lambda: DeviceDescriptor( + "serial", "local-android-adb", "android", state="device" + ) + ), + ] + + async def pick(message, choices): + assert choices[0].label == "https://phone.test (local-ios-http)" + assert choices[0].value == "0" + events.append("pick") + return None if cancel else choices[0].value + + monkeypatch.setattr(device, "is_interactive", lambda: True) + monkeypatch.setattr(connection, "select_prompt_async", pick) + + @click.command() + @device.device_command + async def show(device: AsyncDevice): + events.append("command prompt") + + result = CliRunner().invoke(show, []) + assert result.exit_code == 0, result.exception + owner.list_devices.assert_awaited_once() + if cancel: + owner.connect.assert_not_awaited() + assert events == ["enter", "pick", "close"] + return + owner.connect.assert_awaited_once_with( + backend="local-ios-http", url=None, token=None + ) + assert events == ["enter", "pick", "command prompt", "close"] + + +def test_cloud_command_uses_management_handle_without_connecting(core, monkeypatch): + from mobilerun.cli.devices.base.device import cloud_command + + monkeypatch.setattr( + selection.LoginStore, "resolve_api_key", lambda self: "test-only" + ) + owner, events = core + + @click.command() + @cloud_command + async def status(device: CloudDeviceHandle): + click.echo(device.device_id) + + result = CliRunner().invoke(status, ["cloud-id", "--base-url", "https://api.test"]) + assert result.exit_code == 0, result.exception + assert result.stdout == "cloud-id\n" + assert owner.options["base_url"] == "https://api.test" + owner.connect.assert_not_awaited() + assert events == ["enter", "close"] + + +def test_run_command_does_not_discover_or_connect(core): + from mobilerun.cli.devices.base.device import run_command + + owner, events = core + + @click.command() + @run_command + async def setup(run: AsyncMobilerun): + assert run is owner + events.append("setup") + + result = CliRunner().invoke(setup, []) + assert result.exit_code == 0, result.exception + owner.connect.assert_not_awaited() + owner.list_devices.assert_not_awaited() + assert events == ["enter", "setup", "close"] diff --git a/tests/unit/cli/devices/test_input_screen_commands.py b/tests/unit/cli/devices/test_input_screen_commands.py new file mode 100644 index 000000000..265ec60ff --- /dev/null +++ b/tests/unit/cli/devices/test_input_screen_commands.py @@ -0,0 +1,289 @@ +"""Input and screen CLI contracts through the real async core facade.""" + +from ast import literal_eval +from dataclasses import replace +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest +from click.testing import CliRunner +from mobilerun_core import AsyncDevice, DeviceDisconnectedError + +from mobilerun.cli.devices.base import selection +from mobilerun.cli.devices.group import device +from mobilerun.cli.devices.utils.prompts import pickers +from tests.support.devices import FakeDriver, fake_device + +CLOUD_ID = "11111111-1111-1111-1111-111111111111" + + +@pytest.fixture +def factory(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace: + driver = FakeDriver(device_id="serial") + connected: list[AsyncDevice] = [] + inventory = AsyncMock(return_value=[]) + + class Factory: + def __init__(self, **kwargs: object) -> None: + self.phone: AsyncDevice | None = None + + async def __aenter__(self) -> "Factory": + return self + + async def __aexit__(self, *args: object) -> None: + if self.phone is not None: + await self.phone.aclose() + + async def connect( + self, target=None, *, backend=None, url=None, **kwargs + ) -> AsyncDevice: + driver.device_id = url or target or "serial" + if backend == "local-ios-http": + driver.platform = "ios" + self.phone = fake_device(driver=driver, platform=driver.platform) + info = replace( + self.phone.info(), + backend=backend + or ("cloud" if target == CLOUD_ID else "local-android-adb"), + ) + monkeypatch.setattr(self.phone, "info", lambda: info) + connected.append(self.phone) + return self.phone + + list_devices = inventory + + monkeypatch.setattr(selection, "AsyncMobilerun", Factory) + return SimpleNamespace(driver=driver, connected=connected, inventory=inventory) + + +@pytest.mark.parametrize( + ("args", "call", "output"), + [ + (["tap", "1", "2"], ("tap", (1, 2), {}), "Tapped (1, 2)"), + ( + ["long-press", "1", "2"], + ("swipe", (1, 2, 1, 2), {"duration_ms": 1000}), + "Long pressed (1, 2)", + ), + (["press", "HOME"], ("press_button", ("home",), {}), "Pressed home"), + ( + ["swipe", "1", "2", "3", "4", "--duration", "0.5"], + ("swipe", (1, 2, 3, 4), {"duration_ms": 500}), + "Swiped (1, 2) -> (3, 4)", + ), + ( + ["type", "private text", "--clear"], + ( + "input_text", + ("private text",), + {"clear": True, "humanize": False, "wpm": 0}, + ), + "Typed text", + ), + ], +) +def test_input_command_trace_and_acknowledgement( + factory: SimpleNamespace, + args: list[str], + call: tuple[str, tuple[object, ...], dict[str, object]], + output: str, +) -> None: + result = CliRunner().invoke(device, ["input", *args, "serial", "--android"]) + assert result.exit_code == 0, (result.output, result.exception) + assert factory.driver.calls == [call] + assert result.stdout == f"✓ serial: {output}\n" + assert result.stderr == "" + + +def test_long_press_rejects_ios_without_swiping(factory: SimpleNamespace) -> None: + result = CliRunner().invoke( + device, ["input", "long-press", "1", "2", "http://phone", "--ios"] + ) + assert result.exit_code == 1 + assert result.stderr == "Error: long-press is not supported on iOS\n" + assert len(factory.connected) == 1 + assert factory.driver.calls == [] + + +def test_tap_prompts_after_connecting_and_hides_url_secrets(factory, monkeypatch): + monkeypatch.setattr(pickers, "is_interactive", lambda: True) + + async def prompt(label): + assert len(factory.connected) == 1 + return {"X coordinate": "0", "Y coordinate": "12"}[label] + + monkeypatch.setattr(pickers, "text_prompt_async", prompt) + result = CliRunner().invoke( + device, + ["input", "tap", "--ios", "--device", "https://user:secret@phone.test/path"], + ) + assert result.exit_code == 0, result.output + assert result.stdout == "✓ https://phone.test: Tapped (0, 12)\n" + assert factory.driver.calls == [("tap", (0, 12), {})] + + +@pytest.mark.parametrize("verb", ["get", "set"]) +def test_clipboard_trace_and_output( + factory: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, verb: str +) -> None: + monkeypatch.setattr( + selection.LoginStore, "resolve_api_key", lambda self: "test-key" + ) + factory.driver.supported.update({"get_clipboard", "set_clipboard"}) + factory.driver.clipboard = "clipboard content" + args = ["clipboard", verb, *(["private text"] if verb == "set" else [])] + result = CliRunner().invoke(device, ["input", *args, CLOUD_ID]) + assert result.exit_code == 0, (result.output, result.exception) + if verb == "get": + assert factory.driver.calls == [("get_clipboard", (), {})] + assert result.stdout == "clipboard content\n" + else: + assert factory.driver.calls == [("set_clipboard", ("private text",), {})] + assert result.stdout == f"✓ Clipboard set on {CLOUD_ID}\n" + + +def test_screenshot_saves_bytes_and_prints_path( + factory: SimpleNamespace, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr("tempfile.tempdir", str(tmp_path)) + factory.driver.screenshot_bytes = b"fake PNG bytes" + result = CliRunner().invoke(device, ["screen", "screenshot", "serial"]) + assert result.exit_code == 0, (result.output, result.exception) + assert result.stderr == "" + path = Path(result.stdout.rstrip("\n")) + assert path.parent == tmp_path + assert path.name.startswith("mobilerun_") and path.suffix == ".png" + assert path.read_bytes() == b"fake PNG bytes" + assert factory.driver.calls == [("screenshot", (), {"hide_overlay": True})] + + +@pytest.mark.parametrize("raw", [False, True]) +def test_ui_keeps_indexed_bounds_and_raw_indentation( + factory: SimpleNamespace, raw: bool +) -> None: + result = CliRunner().invoke( + device, ["screen", "ui", "serial", *(["--raw"] if raw else [])] + ) + assert result.exit_code == 0, (result.output, result.exception) + tree = [ + "**Current Phone State:**", + "• **App:** example.app", + "• **Keyboard:** Hidden", + "• **Focused Element:** ''", + "", + "Current Clickable UI elements:", + "'index. className: resourceId; checkedState, text - bounds(x1,y1,x2,y2)':", + '1. EditText: "EditText" - (10,20,30,40)', + ] + assert result.stdout == "\n".join( + [ + *(line if raw else f" {line}" for line in tree), + "", + "Phone state: {'packageName': 'example.app'}", + "", + ] + ) + assert factory.driver.calls == [("get_ui_tree", (), {"filter": False})] + + +@pytest.mark.parametrize( + ("platform", "package", "app", "raw_tree", "expected"), + [ + pytest.param( + "ios", + "com.apple.springboard", + "12:34", + "Home screen icons", + {"currentApp": "Home Screen", "packageName": "com.apple.springboard"}, + id="ios-home-clock", + ), + pytest.param( + "ios", + None, + "12:34", + "Home screen icons", + {"currentApp": "Home Screen", "packageName": "com.apple.springboard"}, + id="ios-home-marker-only", + ), + pytest.param( + "ios", + "com.apple.springboard", + None, + "", + {"currentApp": "Home Screen", "packageName": "com.apple.springboard"}, + id="ios-home-package-only", + ), + pytest.param( + "ios", + "com.apple.Preferences", + "Settings", + "", + {"currentApp": "Settings", "packageName": "com.apple.Preferences"}, + id="ios-in-app", + ), + pytest.param( + "android", + "example.app", + "12:34", + "", + {"currentApp": "12:34", "packageName": "example.app"}, + id="android", + ), + ], +) +def test_ui_renders_foreground_app_footer( + factory: SimpleNamespace, + platform: str, + package: str | None, + app: str | None, + raw_tree: str, + expected: dict[str, str], +) -> None: + factory.driver.platform = platform + if platform == "ios": + factory.driver.observation_format = "ios-legacy" + factory.driver.ui_tree = { + "a11y_tree": [], + "raw_a11y_tree": raw_tree, + "phone_state": {"packageName": package, "currentApp": app}, + } + target = "http://phone" if platform == "ios" else "serial" + result = CliRunner().invoke(device, ["screen", "ui", target, f"--{platform}"]) + assert result.exit_code == 0, (result.output, result.exception) + footer = result.stdout.splitlines()[-1] + assert footer.startswith("Phone state: ") + assert literal_eval(footer.removeprefix("Phone state: ")) == expected + + +def test_ui_retains_visual_remote_screenshot_only_output( + factory: SimpleNamespace, +) -> None: + factory.driver.supported = {"screenshot"} + result = CliRunner().invoke( + device, ["screen", "ui", "http://remote", "--remote", "--raw"] + ) + assert result.exit_code == 0, (result.output, result.exception) + assert "The screenshot shown to the model is 1x1" in result.stdout + assert result.stdout.endswith( + "\nPhone state: {'observationMode': 'screenshot_only', 'accessibilityTree': False}\n" + ) + assert factory.driver.calls == [("screenshot", (), {"hide_overlay": False})] + + +def test_disconnected_screenshot_sanitizes_error(factory: SimpleNamespace) -> None: + factory.driver.failures["screenshot"] = DeviceDisconnectedError("private URL") + result = CliRunner().invoke(device, ["screen", "screenshot", "serial"]) + assert result.exit_code == 1 + assert result.stdout == "" + assert result.stderr == "Error: Device disconnected. Reconnect before retrying.\n" + assert factory.driver.calls == [("screenshot", (), {"hide_overlay": True})] + + +def test_missing_required_target_does_not_connect(factory: SimpleNamespace) -> None: + result = CliRunner().invoke(device, ["input", "tap", "1", "2"]) + assert result.exit_code == 2 + assert "--device" in result.stderr + assert result.stdout == "" + assert factory.connected == [] + factory.inventory.assert_not_awaited() diff --git a/tests/unit/cli/devices/test_list_inventory.py b/tests/unit/cli/devices/test_list_inventory.py new file mode 100644 index 000000000..b2ddec746 --- /dev/null +++ b/tests/unit/cli/devices/test_list_inventory.py @@ -0,0 +1,138 @@ +"""Read-only Android inventory in device listings and pickers.""" + +import json +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import click +import pytest +from click.testing import CliRunner +from mobilerun_core import AsyncDevice, DeviceDescriptor + +from mobilerun.cli.base.prompts import SelectChoice +from mobilerun.cli.devices import connect, device +from mobilerun.cli.devices.base import device as device_base +from mobilerun.cli.devices.base import selection +from mobilerun.cli.devices.utils import approval +from mobilerun.cli.devices.utils.connection import discovery + + +@pytest.fixture +def inventory(monkeypatch: pytest.MonkeyPatch) -> AsyncMock: + adb = AsyncMock( + return_value=[ + DeviceDescriptor("off", "local-android-adb", "android", state="offline"), + DeviceDescriptor("online", "local-android-adb", "android", state="device"), + DeviceDescriptor( + "locked", "local-android-adb", "android", state="unauthorized" + ), + DeviceDescriptor( + "inventory-only-ready", "local-android-adb", "android", state="device" + ), + DeviceDescriptor( + "https://user:secret@not-an-adb-target.test", + "local-android-adb", + "android", + state="offline", + ), + ] + ) + + class FakeMobilerun: + def __init__(self, **kwargs: object) -> None: + self.local = SimpleNamespace(list_android_devices=adb) + + async def __aenter__(self) -> "FakeMobilerun": + return self + + async def __aexit__(self, *exc: object) -> None: + pass + + async def connect(self, serial: str, **kwargs: object) -> SimpleNamespace: + return SimpleNamespace(device_id=serial) + + async def list_devices( + self, *, scope: str, ready_only: bool = True + ) -> list[SimpleNamespace]: + await adb() + assert scope == "local" + return [ + SimpleNamespace( + info=lambda: DeviceDescriptor( + "online", "local-android-adb", "android", state="device" + ) + ), + SimpleNamespace( + info=lambda: DeviceDescriptor( + "https://user:secret@portal.test", "local-ios-http", "ios" + ) + ), + ] + + monkeypatch.setattr(selection, "AsyncMobilerun", FakeMobilerun) + monkeypatch.setattr(discovery.LoginStore, "resolve_api_key", lambda self: None) + monkeypatch.setattr( + approval, + "confirm_prompt_async", + AsyncMock(side_effect=AssertionError("unexpected approval prompt")), + ) + return adb + + +@pytest.mark.parametrize("args", [[], ["--json"]]) +def test_device_list_includes_non_ready_android( + inventory: AsyncMock, args: list[str] +) -> None: + result = CliRunner().invoke(device, ["list", *args]) + assert result.exit_code == 0, result.output + inventory.assert_awaited_once_with() + expected = { + "off": "offline", + "online": "device", + "locked": "unauthorized", + "inventory-only-ready": "device", + } + if args: + assert { + row["id"]: row["state"] for row in json.loads(result.stdout) + } == expected + else: + for serial, state in expected.items(): + assert f"{serial} {state}" in " ".join(result.stdout.split()) + assert "secret" not in result.output + + +def test_connect_picker_labels_non_ready_android( + inventory: AsyncMock, monkeypatch: pytest.MonkeyPatch +) -> None: + async def select(label: str, choices: list[SelectChoice]) -> str: + for choice in choices: + print(choice.label) + return "online" + + monkeypatch.setattr(connect, "is_interactive", lambda: True) + monkeypatch.setattr(connect, "select_prompt", select) + result = CliRunner().invoke(device, ["connect"]) + assert result.exit_code == 0, result.output + inventory.assert_awaited_once_with() + assert "off [offline] local (not ready)" in result.output + assert "locked [unauthorized] local (not ready)" in result.output + assert "Connected online (default device)" in result.output + assert "secret" not in result.output + + +def test_command_without_target_does_not_auto_select_non_ready_android( + inventory: AsyncMock, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr(device_base, "is_interactive", lambda: True) + + @click.command() + @device_base.device_command + async def show_target(device: AsyncDevice) -> None: + click.echo(device.device_id) + + result = CliRunner().invoke(show_target, ["--android"]) + assert result.exit_code == 0, result.output + assert "Using online" in result.stderr + assert result.stdout.strip() == "online" diff --git a/tests/unit/cli/devices/test_portal_commands.py b/tests/unit/cli/devices/test_portal_commands.py new file mode 100644 index 000000000..0dc0521e7 --- /dev/null +++ b/tests/unit/cli/devices/test_portal_commands.py @@ -0,0 +1,158 @@ +"""CLI mappings to core's public local device API; no real devices.""" + +import importlib +from collections.abc import Awaitable, Callable +from types import TracebackType +from typing import Literal +from unittest.mock import AsyncMock + +import pytest +from click.testing import CliRunner +from mobilerun_core import LocalDevices, PortalStatus, SetupResult + +from mobilerun.cli.app import cli +from mobilerun.cli.devices.utils import approval + + +@pytest.mark.parametrize( + "args,expected,transport", + [ + (["serial"], (("serial",), {"tcp": False}), "content"), + (["serial", "--tcp"], (("serial",), {"tcp": True}), "tcp"), + ( + ["http://localhost:8080"], + ((), {"url": "http://localhost:8080", "token": "test-token"}), + "http", + ), + ], +) +def test_ping_uses_requested_transport( + monkeypatch: pytest.MonkeyPatch, + args: list[str], + expected: tuple[tuple[str, ...], dict[str, str | bool]], + transport: Literal["content", "tcp", "http"], +) -> None: + monkeypatch.setenv("MOBILERUN_DEVICE_TOKEN", "test-token") + probe = AsyncMock(return_value=PortalStatus(transport, True)) + monkeypatch.setattr(LocalDevices, "ping_portal", probe) + result = CliRunner().invoke(cli, ["device", "ping", *args]) + assert result.exit_code == 0, result.output + probe.assert_awaited_once_with(*expected[0], **expected[1]) + assert "test-token" not in result.output + + +def test_ping_not_reachable_exits_one(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setattr( + LocalDevices, + "ping_portal", + AsyncMock(return_value=PortalStatus("content", False)), + ) + result = CliRunner().invoke(cli, ["device", "ping", "serial"]) + assert result.exit_code == 1 + assert "Portal is not reachable" in result.output + + +@pytest.mark.parametrize("interactive", [False, True]) +def test_setup_gate( + monkeypatch: pytest.MonkeyPatch, + interactive: bool, +) -> None: + selection = importlib.import_module("mobilerun.cli.devices.base.selection") + monkeypatch.setattr(approval, "is_interactive", lambda: interactive) + prompts: list[str] = [] + + async def confirm(message: str, *, default: bool) -> bool: + prompts.append(message) + return False + + monkeypatch.setattr(approval, "confirm_prompt_async", confirm) + writes: list[str | None] = [] + + class Core: + def __init__( + self, + *, + hitl_gate: Callable[[str, dict[str, object]], Awaitable[bool]], + **kwargs: object, + ) -> None: + self.hitl_gate = hitl_gate + self.local = self + + async def __aenter__(self) -> "Core": + return self + + async def __aexit__( + self, *args: type[BaseException] | BaseException | TracebackType | None + ) -> None: + pass + + async def setup_portal( + self, + serial: str, + *, + client_version: str, + apk_path: str | None, + portal_version: str | None, + latest: bool, + ) -> SetupResult: + action = "local.setup_portal" + details = { + "serial": serial, + "client_version": client_version, + "apk_path": apk_path, + "portal_version": portal_version, + "latest": latest, + "uninstall": True, + "package": "com.mobilerun.portal", + "will_install": True, + "touches_accessibility": True, + "selected_version": portal_version, + "source": "github.com", + } + assert await self.hitl_gate(action, details) + writes.append(portal_version) + return SetupResult( + True, + serial, + "setup_portal", + {"install_completed": True, "accessibility": True}, + ) + + monkeypatch.setattr(selection, "AsyncMobilerun", Core) + result = CliRunner().invoke(cli, ["device", "setup", "serial", "-pv", "0.7.1"]) + assert result.exit_code == 1, (result.output, result.exception) + assert ("not approved" if interactive else "pass --yes") in result.output + assert writes == [] + assert len(prompts) == int(interactive) + result = CliRunner().invoke( + cli, ["device", "setup", "serial", "-pv", "0.7.1", "--yes"] + ) + assert result.exit_code == 0, (result.output, result.exception) + assert "Setup complete!" in result.output + assert writes == ["0.7.1"] + assert len(prompts) == int(interactive) + + +def test_setup_manual_accessibility_is_not_success( + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setattr( + LocalDevices, + "setup_portal", + AsyncMock( + return_value=SetupResult( + False, + "serial", + "setup_portal", + { + "package": "com.mobilerun.portal", + "install_completed": True, + "manual_needed": True, + }, + ) + ), + ) + result = CliRunner().invoke(cli, ["device", "setup", "serial"]) + assert result.exit_code == 1, result.output + assert "manually enable" in result.output + assert "Setup complete!" not in result.output diff --git a/tests/unit/cli/devices/test_settings_commands.py b/tests/unit/cli/devices/test_settings_commands.py new file mode 100644 index 000000000..655135b76 --- /dev/null +++ b/tests/unit/cli/devices/test_settings_commands.py @@ -0,0 +1,288 @@ +"""Exercise settings through Click and core without a phone or cloud access.""" + +import json +from collections.abc import Callable +from unittest.mock import AsyncMock + +import httpx +import pytest +from click.testing import CliRunner, Result +from mobilerun_core import AsyncDevice + +from mobilerun.cli.devices import device +from mobilerun.cli.devices.base import selection +from mobilerun.cli.devices.utils import approval +from mobilerun.cli.devices.utils.prompts import pickers +from tests.support.devices import FakeDriver, fake_device + +CLOUD_ID = "11111111-1111-1111-1111-111111111111" +BASE_URL = "https://cloud.example.invalid/v1" +Trace = list[tuple[str, str, object]] + +READS = [ + ("language", [], {"locale": "de-DE"}, "Language: de-DE\n"), + ("timezone", [], {"timezone": "Europe/Berlin"}, "Timezone: Europe/Berlin\n"), + ("timezone", [], {"timezone": None}, "Timezone: Not available\n"), + ( + "location", + [], + {"latitude": 52.52, "longitude": 13.405}, + "Location: 52.5200, 13.4050\n", + ), + ( + "location", + ["--json"], + {"latitude": 52.52, "longitude": 13.405}, + '{"latitude": 52.52, "longitude": 13.405}\n', + ), + ("location", [], None, "Location: Not available\n"), + ("location", ["--json"], None, "null\n"), +] +WRITES = [ + ( + "language", + ["set", "de-DE"], + "device.set_locale", + "POST", + {"locale": "de-DE"}, + "Language set to de-DE on", + ), + ( + "timezone", + ["set", "Europe/Berlin"], + "device.set_timezone", + "POST", + {"timezone": "Europe/Berlin"}, + "Timezone set to Europe/Berlin on", + ), + ( + "location", + ["set", "52.52", "13.40"], + "device.set_location", + "POST", + {"latitude": 52.52, "longitude": 13.4}, + "Location set to 52.52, 13.4 on", + ), + ( + "location", + ["reset"], + "device.reset_location", + "DELETE", + None, + "Location reset on", + ), +] + + +@pytest.fixture +def cloud_trace(monkeypatch: pytest.MonkeyPatch) -> Callable[..., Trace]: + """Keep real cloud routing and consent; replace the network transport.""" + monkeypatch.setattr( + selection.LoginStore, "resolve_api_key", lambda self: "test-key" + ) + + def install(response: dict[str, object] | None = None) -> Trace: + calls: Trace = [] + + async def send( + client: httpx.AsyncClient, request: httpx.Request, **kwargs: object + ) -> httpx.Response: + assert request.url.host == "cloud.example.invalid" + path = request.url.path + prefix = f"/v1/devices/{CLOUD_ID}" + assert path == prefix or path.startswith(f"{prefix}/") + if path == prefix: + assert request.method == "GET" + return httpx.Response( + 200, json={"id": CLOUD_ID, "type": "android"}, request=request + ) + if path == f"{prefix}/capabilities": + assert request.method == "GET" + return httpx.Response( + 200, json={"capabilities": {"browser": False}}, request=request + ) + calls.append( + ( + request.method, + path.removeprefix(f"{prefix}/"), + json.loads(request.content or b"null"), + ) + ) + if request.method == "GET": + return httpx.Response( + 200, + content=json.dumps(response), + headers={"content-type": "application/json"}, + request=request, + ) + return httpx.Response(204, request=request) + + monkeypatch.setattr(httpx.AsyncClient, "send", send) + return calls + + return install + + +def invoke(*args: str) -> Result: + return CliRunner().invoke(device, ["settings", *args], env={"NO_COLOR": "1"}) + + +@pytest.mark.parametrize("setting,flags,response,output", READS) +def test_reads_preserve_output( + cloud_trace: Callable[..., Trace], + setting: str, + flags: list[str], + response: dict[str, object] | None, + output: str, +) -> None: + calls = cloud_trace(response) + result = invoke(setting, "get", CLOUD_ID, "--base-url", BASE_URL, *flags) + assert result.exit_code == 0, (result.output, result.exception) + assert result.stdout == output + assert result.stderr == "" + assert calls == [("GET", setting, None)] + + +@pytest.mark.parametrize("setting,args,operation,method,body,output", WRITES) +@pytest.mark.parametrize( + "interactive,yes,confirmed,error", + [ + (False, False, False, "pass --yes"), + (True, False, False, "not approved"), + (True, False, True, None), + (False, True, False, None), + ], +) +def test_writes_use_one_core_consent_gate( + cloud_trace: Callable[..., Trace], + monkeypatch: pytest.MonkeyPatch, + setting: str, + args: list[str], + operation: str, + method: str, + body: dict[str, object] | None, + output: str, + interactive: bool, + yes: bool, + confirmed: bool, + error: str | None, +) -> None: + calls = cloud_trace() + monkeypatch.setattr(approval, "is_interactive", lambda: interactive) + + async def confirm(message: str, *, default: bool) -> bool: + assert calls == [] + return confirmed + + prompt = AsyncMock(side_effect=confirm) + monkeypatch.setattr(approval, "confirm_prompt_async", prompt) + flags = ["--yes"] if yes else [] + result = invoke(setting, *args, CLOUD_ID, "--base-url", BASE_URL, *flags) + + if interactive and not yes: + label = operation.replace(".", " ").replace("_", " ") + prompt.assert_awaited_once_with(f"Approve {label}?", default=False) + else: + prompt.assert_not_awaited() + + if error: + assert result.exit_code == 1, (result.output, result.exception) + assert result.stdout == "" + assert error in result.stderr + assert calls == [] + return + + assert result.exit_code == 0, (result.output, result.exception) + assert result.stdout == f"✓ {output} {CLOUD_ID}\n" + assert result.stderr == "" + assert calls == [(method, setting, body)] + + +@pytest.mark.parametrize( + "setting,answers,body", + [ + ("language", {"Locale": "de-DE"}, {"locale": "de-DE"}), + ("timezone", {"Timezone": "Europe/Berlin"}, {"timezone": "Europe/Berlin"}), + ( + "location", + {"Latitude": "52.52", "Longitude": "13.4"}, + {"latitude": 52.52, "longitude": 13.4}, + ), + ], +) +def test_set_prompts_for_missing_operands_after_connecting( + cloud_trace: Callable[..., Trace], + monkeypatch: pytest.MonkeyPatch, + setting: str, + answers: dict[str, str], + body: dict[str, object], +) -> None: + calls = cloud_trace() + connected = False + connect = selection.AsyncMobilerun.connect + + async def track_connect(run: selection.AsyncMobilerun, *args, **kwargs): + nonlocal connected + phone = await connect(run, *args, **kwargs) + connected = True + return phone + + async def answer(label: str) -> str: + assert connected + assert not calls + return answers[label] + + monkeypatch.setattr(selection.AsyncMobilerun, "connect", track_connect) + monkeypatch.setattr(pickers, "is_interactive", lambda: True) + monkeypatch.setattr(pickers, "text_prompt_async", answer) + + result = invoke(setting, "set", "--device", CLOUD_ID, "--base-url", BASE_URL, "-y") + assert result.exit_code == 0, (result.output, result.exception) + assert calls == [("POST", setting, body)] + + +@pytest.mark.parametrize( + "args,verb", + [ + (["language", "get"], "get_locale"), + (["language", "set", "de-DE"], "set_locale"), + (["location", "get"], "get_location"), + (["location", "set", "52.52", "13.40"], "set_location"), + (["location", "reset"], "reset_location"), + (["timezone", "get"], "get_timezone"), + (["timezone", "set", "Europe/Berlin"], "set_timezone"), + ], +) +def test_unsupported_backend_is_a_cli_error( + monkeypatch: pytest.MonkeyPatch, args: list[str], verb: str +) -> None: + driver = FakeDriver(device_id="serial") + + class Factory: + def __init__(self, *, hitl_gate: Callable, **kwargs: object) -> None: + self.phone = fake_device(driver=driver, hitl_gate=hitl_gate) + + async def __aenter__(self) -> "Factory": + return self + + async def __aexit__(self, *exc_info: object) -> None: + await self.phone.aclose() + + async def connect( + self, identifier: str, *, backend: str, **kwargs: object + ) -> AsyncDevice: + assert (identifier, backend) == ("serial", "local-android-adb") + return self.phone + + monkeypatch.setattr(selection, "AsyncMobilerun", Factory) + monkeypatch.setattr(approval, "is_interactive", lambda: True) + prompt = AsyncMock(return_value=True) + monkeypatch.setattr(approval, "confirm_prompt_async", prompt) + + result = invoke(*args, "serial", "--android") + assert result.exit_code == 1, (result.output, result.exception) + assert result.stdout == "" + assert result.stderr.startswith(f"Error: {verb!r} is not supported") + assert "Traceback" not in result.stderr + assert driver.calls == [] + prompt.assert_not_awaited() diff --git a/tests/unit/cli/task/test_task_commands.py b/tests/unit/cli/task/test_task_commands.py new file mode 100644 index 000000000..19d09c7fe --- /dev/null +++ b/tests/unit/cli/task/test_task_commands.py @@ -0,0 +1,165 @@ +import json +from contextlib import asynccontextmanager +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import httpx +import pytest +from click.testing import CliRunner +from mobilerun_sdk import AuthenticationError, NotFoundError +from mobilerun_sdk.types import TaskGetStatusResponse, TaskStopResponse + +from mobilerun.cli.base import menu, safety +from mobilerun.clients.cloud import client as connection +from mobilerun.errors.cloud import CloudAuthRequired +from mobilerun.models.billing import Billing + + +@pytest.fixture +def cli(monkeypatch): + from mobilerun.cli.task import group + + monkeypatch.setattr(menu, "is_interactive", lambda: False) + return group + + +@pytest.fixture +def remote(cli, monkeypatch): + service = SimpleNamespace( + get_status=AsyncMock( + return_value=TaskGetStatusResponse( + status="running", terminal=False, steps=3, message="Opening Settings" + ) + ), + stop=AsyncMock(return_value=TaskStopResponse(cancelled=True)), + ) + opened = [] + + @asynccontextmanager + async def client(*args, billing): + assert billing is Billing.NO_COMMERCE + opened.append(True) + yield SimpleNamespace(tasks=service) + + monkeypatch.setattr(connection, "cloud_client", client) + return service, opened + + +def test_status_shows_available_results(cli, remote): + result = CliRunner().invoke(cli.task, ["status", "abc"]) + assert result.exit_code == 0, result.output + assert "running" in result.output + assert "Opening Settings" in result.output + remote[0].get_status.assert_awaited_once_with("abc") + + +def test_status_json_preserves_result_fields(cli, remote): + remote[0].get_status.return_value = TaskGetStatusResponse( + status="completed", terminal=True, steps=3, output={"ok": True} + ) + result = CliRunner().invoke(cli.task, ["status", "abc", "--json"]) + assert result.exit_code == 0, result.output + assert json.loads(result.stdout) == { + "status": "completed", + "terminal": True, + "steps": 3, + "output": {"ok": True}, + } + + +def test_status_prompts_for_missing_task_id(cli, remote, monkeypatch): + monkeypatch.setattr(menu, "is_interactive", lambda: True) + monkeypatch.setattr(menu, "text_prompt", lambda label: "prompted-id") + result = CliRunner().invoke(cli.task, ["status"]) + assert result.exit_code == 0, result.output + remote[0].get_status.assert_awaited_once_with("prompted-id") + + +@pytest.mark.parametrize( + "error,code,message", + [ + (NotFoundError, 404, "Task not found: abc"), + (AuthenticationError, 401, "mobilerun account login"), + ], +) +def test_status_cloud_errors_hide_server_details(cli, remote, error, code, message): + secret = "sentinel-test-credential" + response = httpx.Response( + code, request=httpx.Request("GET", f"https://example.test/?token={secret}") + ) + remote[0].get_status.side_effect = error(secret, response=response, body=secret) + result = CliRunner().invoke(cli.task, ["status", "abc", "--json"]) + assert result.exit_code == 1 + assert message in result.stderr + assert not result.stdout + assert secret not in result.output + + +def test_status_requires_cloud_login(cli, monkeypatch): + def missing(*args, billing): + raise CloudAuthRequired(code="credentials_required") + + monkeypatch.setattr(connection, "cloud_client", missing) + result = CliRunner().invoke(cli.task, ["status", "abc"]) + assert result.exit_code == 1 + assert "Not logged in" in result.stderr + assert "mobilerun account login" in result.stderr + + +@pytest.mark.parametrize( + "interactive,answer,yes,allowed,exit_code", + [ + (True, True, False, True, 0), + (True, False, False, False, 0), + (True, False, True, True, 0), + (False, False, True, True, 0), + (False, False, False, False, 1), + ], +) +def test_stop_requires_consent_before_opening_client( + cli, remote, monkeypatch, interactive, answer, yes, allowed, exit_code +): + service, opened = remote + monkeypatch.setattr(menu, "is_interactive", lambda: interactive) + prompt = AsyncMock(return_value=answer) + monkeypatch.setattr(safety, "confirm_prompt_async", prompt) + args = ["stop", "abc"] + (["--yes"] if yes else []) + result = CliRunner().invoke(cli.task, args) + assert result.exit_code == exit_code, result.output + assert prompt.await_count == int(interactive and not yes) + if allowed: + service.get_status.assert_awaited_once_with("abc") + service.stop.assert_awaited_once_with("abc") + assert "Stop requested for task abc" in result.output + else: + assert not opened + service.get_status.assert_not_awaited() + service.stop.assert_not_awaited() + if exit_code: + assert "pass --yes" in result.stderr + + +@pytest.mark.parametrize("state", ["completed", "failed", "cancelled"]) +def test_stop_skips_finished_tasks(cli, remote, state): + service, _ = remote + service.get_status.return_value = TaskGetStatusResponse(status=state, terminal=True) + result = CliRunner().invoke(cli.task, ["stop", "abc", "--yes", "--json"]) + assert result.exit_code == 0, result.output + assert json.loads(result.stdout) == {"task_id": "abc", "status": state} + service.stop.assert_not_awaited() + + +def test_stop_json_sends_confirmation_to_stderr(cli, remote, monkeypatch): + monkeypatch.setattr(menu, "is_interactive", lambda: True) + monkeypatch.setattr(safety, "confirm_prompt_async", AsyncMock(return_value=True)) + result = CliRunner().invoke(cli.task, ["stop", "abc", "--json"]) + assert result.exit_code == 0, result.output + assert json.loads(result.stdout) == {"task_id": "abc", "cancelled": True} + assert "This stops the task." in result.stderr + + +def test_stop_reports_rejected_cancellation(cli, remote): + remote[0].stop.return_value = TaskStopResponse(cancelled=False) + result = CliRunner().invoke(cli.task, ["stop", "abc", "--yes"]) + assert result.exit_code == 1 + assert "Task abc was not stopped" in result.stderr diff --git a/tests/unit/cli/test_cli_billing_retry.py b/tests/unit/cli/test_cli_billing_retry.py index f4fca0e3e..fdce964d7 100644 --- a/tests/unit/cli/test_cli_billing_retry.py +++ b/tests/unit/cli/test_cli_billing_retry.py @@ -1,12 +1,9 @@ """Exercise billing consent through one fake Click command.""" import asyncio -import importlib import json import sys -from collections.abc import AsyncIterator from contextlib import asynccontextmanager, contextmanager -from functools import wraps from types import SimpleNamespace as NS from unittest.mock import AsyncMock @@ -17,15 +14,11 @@ from mobilerun.cli.app import cli as app from mobilerun.cli.base import menu, safety from mobilerun.cli.base.billing import billing_option, invoke_with_billing -from mobilerun.cli.devices.base import selection from mobilerun.cli.phone_number import group as number_cli -from mobilerun.clients.cloud import mailboxes, numbers, proxies -from mobilerun.clients.cloud.billing import requires -from mobilerun.core.devices.base import Device -from mobilerun.core.devices.recording import RecordingDevice -from mobilerun.core.extensions import action -from mobilerun.core.phone_number import CloudPhoneNumber -from mobilerun.models.billing import Billing, Plan +from mobilerun.clients.cloud import client as cloud_connection +from mobilerun.clients.cloud import numbers +from mobilerun.clients.cloud.billing_policy import BillingPolicy +from mobilerun.models.billing import Billing class TTYRunner(CliRunner): @@ -73,7 +66,7 @@ def test_cli_billing_retry(monkeypatch, mode, ttys, yes, answer, exit_code, atte purchased = [] prompts = [] - @requires(Billing.PAID, operation="Buy Connect proxy") + @BillingPolicy.guard(Billing.PAID, operation="Buy Connect proxy") async def purchase(*, billing): purchased.append(billing) return "proxy-id" @@ -129,13 +122,12 @@ def buy(billing, yes): @pytest.mark.parametrize( "command,plan,mode,interactive,yes,answer,runs,exit_code", [ - (command, plan, *case) + pytest.param(command, plan, *case) for command, plan in ( ("number create", "rent"), ("mailbox create", "rent"), ("proxy buy", None), ("number send", None), - ("resume", None), ) for case in ( ("included", True, False, True, 1, 0), @@ -159,7 +151,6 @@ def buy(billing, yes): ("mailbox create", "rent"), ("proxy buy", None), ("number send", None), - ("resume", None), ) for interactive, yes, answer, runs, exit_code in ( (True, False, True, 1, 0), @@ -184,7 +175,6 @@ def test_resource_cli_retries_only_guarded_operation( ) mutate = AsyncMock(return_value=NS(data=data)) details = AsyncMock(return_value=NS(data=data)) - metadata = AsyncMock(return_value=NS(billing_strategy=Plan.MINUTE)) prompts = [] client_entries = [] @@ -192,7 +182,6 @@ def test_resource_cli_retries_only_guarded_operation( async def client(*args, **kwargs): client_entries.append(kwargs["billing"]) yield NS( - devices=NS(retrieve=metadata, resume=mutate), numbers=NS(create=mutate, retrieve=details, messages=NS(send=mutate)), mailboxes=NS(create=mutate, retrieve=details), connect=NS(proxies=NS(buy=mutate)), @@ -200,7 +189,7 @@ async def client(*args, **kwargs): async def confirm(message, *, default): mutate.assert_not_awaited() - assert len(client_entries) == (1 if command == "resume" else 0) + assert not client_entries assert answer is not None, "unexpected billing prompt" assert "charges may apply" in message and default is False prompts.append(message) @@ -208,23 +197,23 @@ async def confirm(message, *, default): monkeypatch.setattr(safety, "confirm_prompt_async", confirm) monkeypatch.setenv("MOBILERUN_BILLING", mode) - for module in ( - numbers, - mailboxes, - proxies, - importlib.import_module("mobilerun.cli.devices.cloud.resume"), - ): - monkeypatch.setattr(module, "cloud_client", client) + monkeypatch.setattr(cloud_connection, "cloud_client", client) args = command.split() if command == "number create": args += ["--country", "US"] elif command == "proxy buy": - mutate.return_value = NS(id="proxy", status="active", payment_url=None) + mutate.return_value = NS( + id="proxy", + status="active", + payment_url=None, + name="Proxy", + country="US", + type="residential", + billing_mode="paid", + ) args += ["--country", "US"] elif command == "number send": args += ["number-id", "+15550100", "hello"] - elif command == "resume": - args = ["device", "cloud", "resume", "aa111111-1111-1111-1111-111111111111"] if plan is not None: args += ["--plan", plan] @@ -234,9 +223,7 @@ async def confirm(message, *, default): assert result.exit_code == exit_code, result.output assert len(prompts) == (answer is not None) assert mutate.await_count == runs - assert metadata.await_count == (command == "resume") - if command != "resume": - assert client_entries == [Billing.PAID] * (runs + details.await_count) + assert client_entries == [Billing.PAID] * (runs + details.await_count) if plan == "included": assert mutate.await_args.kwargs["billing_preference"] == "included_only" if answer is False: @@ -250,6 +237,80 @@ async def confirm(message, *, default): ) +@pytest.mark.parametrize("command", ["number create", "mailbox create"]) +def test_included_auto_never_retries_with_metered_billing(monkeypatch, command): + from mobilerun.errors.cloud import IncludedCapacityUnavailable + + mutate = AsyncMock( + side_effect=IncludedCapacityUnavailable(resource=command.split()[0]) + ) + prompt = AsyncMock(return_value=True) + + @asynccontextmanager + async def client(*args, billing, **kwargs): + assert billing is Billing.INCLUDED + yield NS(numbers=NS(create=mutate), mailboxes=NS(create=mutate)) + + monkeypatch.setattr(cloud_connection, "cloud_client", client) + monkeypatch.setattr(safety, "confirm_prompt_async", prompt) + args = ["--country", "US"] if command.startswith("number") else [] + result = CliRunner().invoke( + app, [*command.split(), *args, "--billing", "included", "--yes"] + ) + assert result.exit_code == 1, result.output + assert mutate.await_count == 1 + assert mutate.await_args.kwargs["billing_preference"] == "included_only" + prompt.assert_not_awaited() + + +@pytest.mark.parametrize("mode", [Billing.PAID, Billing.INCLUDED, Billing.NO_COMMERCE]) +def test_typed_sms_records_one_explicit_schema_two_outcome(tmp_path, mode): + from contextlib import nullcontext + + from mobilerun.core.phone_number import CloudPhoneNumber + from mobilerun.core.runs import ActionRecording + from mobilerun.errors.cloud import BillingRequired + from tests.support.devices import fake_device + from tests.support.macro import read_run_steps + + send = AsyncMock() + release = AsyncMock() + retrieve = AsyncMock( + return_value=NS( + data=NS(phone_number="+15550100", state="active", device_binding=None) + ) + ) + sdk = NS(numbers=NS(messages=NS(send=send), cancel=release, retrieve=retrieve)) + allowed = mode is Billing.PAID + + async def run(): + phone = fake_device() + async with ActionRecording(phone, runs_dir=tmp_path) as rec: + async with CloudPhoneNumber( + "number-id", billing=mode, client=sdk + ) as number: + with nullcontext() if allowed else pytest.raises(BillingRequired): + async with rec.extension_call( + "sms.send", {"to": "***", "text": "***"} + ): + await number.send("5550100", "hello") + return rec.run_dir + + (row,) = read_run_steps(asyncio.run(run())) + assert row.schema_version == 2 and row.ok is allowed + assert row.action.name == "extension_call" + assert row.action.scope == "extension" + assert row.action.arguments == { + "name": "sms.send", + "arguments": {"to": "***", "text": "***"}, + } + if allowed: + send.assert_awaited_once_with("number-id", to="5550100", body="hello") + else: + send.assert_not_awaited() + release.assert_not_awaited() + + @pytest.mark.parametrize( "mode,plan,error", [ @@ -262,7 +323,7 @@ def test_number_create_json_refuses_without_country_lookup( monkeypatch, mode, plan, error ): countries = AsyncMock(side_effect=AssertionError("unexpected country lookup")) - monkeypatch.setattr(numbers, "countries", countries) + monkeypatch.setattr(numbers.Numbers, "countries", countries) result = TTYRunner(True, True, False).invoke( app, ["number", "create", "--billing", mode, "--plan", plan, "--json"] @@ -284,9 +345,8 @@ async def confirm(message, *, default): events.append("confirm") return True - async def countries(*, billing): + async def countries(): events.append("countries") - assert billing is Billing.INCLUDED return NS( data=NS(items=[NS(country="us", name="United States", in_stock=True)]) ) @@ -302,12 +362,14 @@ async def create(**kwargs): return NS(data=NS(number_id="num", state="active", checkout_url=None)) monkeypatch.setattr(safety, "confirm_prompt_async", confirm) - monkeypatch.setattr(numbers, "countries", countries) monkeypatch.setattr(number_cli, "_included_counts", AsyncMock(return_value=[2])) monkeypatch.setattr(number_cli, "select_prompt", pick) @asynccontextmanager async def client(*args, **kwargs): + if kwargs["billing"] is Billing.INCLUDED: + yield NS(numbers=NS(countries=countries)) + return assert kwargs["billing"] is Billing.PAID yield NS( numbers=NS( @@ -318,7 +380,7 @@ async def client(*args, **kwargs): ) ) - monkeypatch.setattr(numbers, "cloud_client", client) + monkeypatch.setattr(cloud_connection, "cloud_client", client) result = TTYRunner(True, stdout_tty, True).invoke( app, ["number", "create", "--plan", "rent", "--billing", "included", "--json"] ) @@ -331,229 +393,3 @@ async def client(*args, **kwargs): "status": "active", "phone_number": "+15550100", } - - -@pytest.mark.parametrize("mode", ["paid", "included", "no_commerce"]) -@pytest.mark.parametrize("interactive", [True, False]) -def test_subscription_resume_never_prompts( - monkeypatch: pytest.MonkeyPatch, mode: str, interactive: bool -) -> None: - metadata = AsyncMock(return_value=NS(billing_strategy=Plan.SUBSCRIPTION)) - resume = AsyncMock() - prompt = AsyncMock(side_effect=AssertionError("unexpected billing prompt")) - - @asynccontextmanager - async def client(*, base_url: str | None, billing: Billing) -> AsyncIterator[NS]: - yield NS(devices=NS(retrieve=metadata, resume=resume)) - - module = importlib.import_module("mobilerun.cli.devices.cloud.resume") - monkeypatch.setattr(module, "cloud_client", client) - monkeypatch.setattr(safety, "confirm_prompt_async", prompt) - device_id = "aa111111-1111-1111-1111-111111111111" - result = TTYRunner(interactive, False, interactive).invoke( - app, ["device", "cloud", "resume", device_id, "--billing", mode] - ) - - assert result.exit_code == 0, result.output - prompt.assert_not_awaited() - metadata.assert_awaited_once_with(device_id) - resume.assert_awaited_once_with(device_id) - - -@pytest.mark.parametrize("alias", ["sms", "work"]) -@pytest.mark.parametrize( - "mode,yes,reply,exit_code,sends", - [ - ("paid", False, True, 0, 1), - ("paid", False, False, 1, 0), - ("paid", True, None, 0, 1), - ("paid", False, None, 1, 0), - ("included", True, None, 0, 1), - ("included", False, True, 0, 1), - ("included", False, False, 1, 0), - ("included", False, None, 1, 0), - ], -) -def test_bound_cloud_sms_retries_only_sdk_send( - monkeypatch, tmp_path, alias, mode, yes, reply, exit_code, sends -): - from tests.support.macro import read_run_steps - - class BoundNumber(CloudPhoneNumber): - async def check_bind(self, device): - return () - - async def on_bind(self, device): - pass - - attempts = [] - send = numbers.send - - async def track_send(*args, billing, **kwargs): - attempts.append(billing) - return await send(*args, billing=billing, **kwargs) - - monkeypatch.setattr(numbers, "send", track_send) - transport = AsyncMock( - return_value=numbers.MessageSendResponse.model_validate( - { - "data": { - "id": "sms-id", - "createdAt": "2026-01-01T00:00:00Z", - "occurredAt": "2026-01-01T00:00:00Z", - "direction": "outbound", - "status": "queued", - } - } - ) - ) - sdk = NS(numbers=NS(messages=NS(send=transport))) - number = BoundNumber("number-id", billing=mode, client=sdk, name=alias) - phone = RecordingDevice(Device(), runs_dir=tmp_path, capture="actions") - phone.close = AsyncMock() - asyncio.run(number.bind(phone)) - open_phone = AsyncMock(return_value=phone) - monkeypatch.setattr(selection, "connect_target", open_phone) - # The extension's billing snapshot, not the CLI environment, controls SMS. - monkeypatch.setenv("MOBILERUN_BILLING", "no_commerce") - - async def confirm(message, *, default): - assert reply is not None - assert "Send SMS" in message and not default - transport.assert_not_called() - return reply - - prompt = AsyncMock(side_effect=confirm) - monkeypatch.setattr(safety, "confirm_prompt_async", prompt) - args = [ - "device", - "action", - "call", - f"{alias}.send", - "aa111111-1111-1111-1111-111111111111", - "--arg", - "to=5550100", - "--arg", - "text=hello", - "--json", - ] - interactive = reply is not None or (yes and mode == "paid") - result = TTYRunner(interactive, False, interactive).invoke( - app, [*args, *(["--yes"] if yes else [])] - ) - assert result.exit_code == exit_code, result.output - assert prompt.await_count == (reply is not None) - expected_attempts = [Billing(mode)] if mode != "paid" or sends else [] - if sends and mode != "paid": - expected_attempts.append(Billing.PAID) - assert attempts == expected_attempts - open_phone.assert_awaited_once() - phone.close.assert_awaited_once() - (row,) = read_run_steps(phone.run_dir) - assert row.ok is bool(sends) and row.action == "extension_call" - assert row.args == { - "name": f"{alias}.send", - "arguments": {"to": "5550100", "text": "hello"}, - } - if sends: - assert json.loads(result.stdout)["data"]["id"] == "sms-id" - transport.assert_awaited_once_with("number-id", to="5550100", body="hello") - else: - transport.assert_not_called() - assert ("Cancelled" if reply is False else "--yes") in result.stderr - - -@pytest.mark.parametrize( - "override", ["plain", "decorated", "mixed_inheritance", "wraps", "same_signature"] -) -def test_cloud_number_with_replaced_send_still_requires_paid_confirmation( - monkeypatch, override -): - sent = [] - - async def send(self, to: str, text: str) -> str: - """Send via a different provider.""" - sent.append((to, text)) - return "sent" - - @wraps(CloudPhoneNumber.send) - async def wrapped_send(self, to, text, **kwargs): - assert not kwargs - sent.append((to, text)) - return numbers.MessageSendResponse.model_validate( - { - "data": { - "id": "replacement-sms", - "createdAt": "2026-01-01T00:00:00Z", - "occurredAt": "2026-01-01T00:00:00Z", - "direction": "outbound", - "status": "queued", - } - } - ) - - async def typed_send( - self: "CloudPhoneNumber", to: str, text: str - ) -> numbers.MessageSendResponse: - """Replace the provider while preserving the typed signature.""" - return await wrapped_send(self, to, text) - - typed_send.__name__ = "send" - replacement = { - "wraps": wrapped_send, - "decorated": action(send), - "same_signature": typed_send, - }.get(override, send) - - class Provider(CloudPhoneNumber): - send = replacement - - async def check_bind(self, device): - return () - - async def on_bind(self, device): - pass - - class InheritedSend(CloudPhoneNumber): - pass - - class MultipleBases(InheritedSend, Provider): - pass - - phone = Device() - phone.close = AsyncMock() - number_type = MultipleBases if override == "mixed_inheritance" else Provider - asyncio.run(number_type("number-id", name="work").bind(phone)) - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=phone)) - args = [ - "device", - "action", - "call", - "work.send", - "aa111111-1111-1111-1111-111111111111", - "--arg", - "to=5550100", - "--arg", - "text=hello", - ] - monkeypatch.setenv("MOBILERUN_BILLING", "included") - result = CliRunner().invoke(app, [*args, "--yes"]) - assert sent == [] - assert result.exit_code == 1 and "MOBILERUN_BILLING=paid" in result.stderr - monkeypatch.setenv("MOBILERUN_BILLING", "paid") - result = CliRunner().invoke(app, args) - assert result.exit_code == 1 and "--yes" in result.stderr - assert sent == [] - prompt = AsyncMock(return_value=False) - monkeypatch.setattr(safety, "confirm_prompt_async", prompt) - result = TTYRunner(True, False, True).invoke(app, args) - assert result.exit_code == 1 and "Cancelled" in result.stderr - prompt.assert_awaited_once() - assert sent == [] - result = CliRunner().invoke(app, [*args, "--yes"]) - assert result.exit_code == 0, result.stderr - if override in {"wraps", "same_signature"}: - assert json.loads(result.stdout)["data"]["id"] == "replacement-sms" - else: - assert result.stdout.strip() == "sent" - assert sent == [("5550100", "hello")] diff --git a/tests/unit/cli/test_cli_feedback.py b/tests/unit/cli/test_cli_feedback.py index 6a7d2d168..86ade8bf5 100644 --- a/tests/unit/cli/test_cli_feedback.py +++ b/tests/unit/cli/test_cli_feedback.py @@ -7,6 +7,7 @@ import click import pytest from click.testing import CliRunner +from mobilerun_core import ActionHookError, ActionHooksAlreadyInstalledError from mobilerun.cli.app import LazyGroup from mobilerun.cli.base import menu @@ -60,6 +61,22 @@ def test_expected_error_is_one_line(): assert "\x1b" not in result.output +@pytest.mark.parametrize( + ("error", "message"), + [ + (ActionHookError("before"), "the action did not run"), + (ActionHookError("after"), "the action already ran"), + (ActionHooksAlreadyInstalledError(), "Action hooks are already installed"), + ], +) +def test_action_hook_errors_show_actionable_feedback(error, message, capsys): + render_error(error) + lines = capsys.readouterr().err.splitlines() + assert len(lines) == 1 + assert lines[0].startswith("Error: ") + assert message in lines[0] + + def test_unexpected_error_hides_details_unless_debug(): result = CliRunner().invoke(sample, ["bug"]) assert result.exit_code == 1 @@ -158,24 +175,15 @@ def command(): assert "Timed out after 30s" in CliRunner().invoke(command).output -@pytest.mark.parametrize( - ("module_name", "extra"), - [ - ("anthropic", "anthropic"), - ("langfuse", "langfuse"), - ("openinference", "langfuse"), - ], -) -def test_known_optional_dependency_message(module_name, extra): +@pytest.mark.parametrize("module_name", ["anthropic", "langfuse", "openinference"]) +def test_known_optional_dependency_message(module_name): @click.command() def command(): - render_error( - ModuleNotFoundError(f"No module named '{module_name}'", name=module_name) - ) + render_error(ModuleNotFoundError("private failure detail", name=module_name)) - assert ( - f"pip install 'mobilerun-agents[{extra}]'" in CliRunner().invoke(command).output - ) + output = CliRunner().invoke(command).output + assert "install the mobilerun-agents add-on" in output + assert "private failure detail" not in output def test_account_canonical_and_auth_alias(): diff --git a/tests/unit/cli/test_commerce.py b/tests/unit/cli/test_commerce.py index 1d54c0093..76728d416 100644 --- a/tests/unit/cli/test_commerce.py +++ b/tests/unit/cli/test_commerce.py @@ -9,14 +9,25 @@ import click import pytest from click.testing import CliRunner +from mobilerun_core import ( + ConnectProxyRef, + DeviceDescriptor, + ProxyAlreadyConfigured, + ProxyStatus, +) from mobilerun.cli.app import cli from mobilerun.cli.base import billing, choices, menu, safety +from mobilerun.cli.devices.base import device, selection +from mobilerun.cli.devices.utils import approval +from mobilerun.cli.devices.utils.prompts import pickers from mobilerun.cli.mailbox import group as mailbox from mobilerun.cli.phone_number import group as number from mobilerun.cli.proxy import group as proxy from mobilerun.errors import CloudAuthenticationError, CloudPermissionDenied -from mobilerun.models.billing import Billing +from tests.support.devices import fake_device + +PHONE_ID = "aa111111-1111-1111-1111-111111111111" @pytest.fixture @@ -45,7 +56,7 @@ async def client(**kwargs): def test_create_forwards_plan(monkeypatch, group, module, name, fake_number_client): create = AsyncMock(return_value=NS(id="id")) monkeypatch.setattr(module, name, lambda **kwargs: create(**kwargs)) - client = module.cloud_numbers if group == "number" else module.cloud_mailboxes + client = module.Numbers if group == "number" else module.Mailboxes data = NS(phone_number=None, address=None, state="active", status="active") monkeypatch.setattr(client, "retrieve", AsyncMock(return_value=NS(data=data))) result = CliRunner().invoke( @@ -116,7 +127,7 @@ def test_number_included_without_country_lists_all_counts( NS(country="gb", name="United Kingdom", in_stock=False), ] monkeypatch.setattr( - number.cloud_numbers, + number.Numbers, "countries", AsyncMock(return_value=NS(data=NS(items=countries))), ) @@ -157,7 +168,7 @@ def test_number_create_picker_shows_included_counts_and_hides_out_of_stock( ] monkeypatch.setattr(number, "is_interactive", lambda: True) monkeypatch.setattr( - number.cloud_numbers, + number.Numbers, "countries", AsyncMock(return_value=NS(data=NS(items=countries))), ) @@ -183,7 +194,7 @@ def test_country_capacity_partial_failure(monkeypatch, command, fake_number_clie for c, n in [("us", "United States"), ("gb", "United Kingdom")] ] monkeypatch.setattr( - number.cloud_numbers, + number.Numbers, "countries", AsyncMock(return_value=NS(data=NS(items=countries))), ) @@ -209,7 +220,7 @@ def phone(**kwargs): ready = NS(id="n1") monkeypatch.setattr(number, "complete_checkout", AsyncMock(return_value=ready)) monkeypatch.setattr( - number.cloud_numbers, + number.Numbers, "retrieve", AsyncMock(return_value=NS(data=NS(state="active", phone_number="+1555"))), ) @@ -242,7 +253,7 @@ def test_country_capacity_auth_error_is_not_swallowed( ): countries = [NS(country="us", name="United States", in_stock=True)] monkeypatch.setattr( - number.cloud_numbers, + number.Numbers, "countries", AsyncMock(return_value=NS(data=NS(items=countries))), ) @@ -269,7 +280,7 @@ def test_country_capacity_auth_error_is_not_swallowed( @pytest.mark.parametrize("command", ["included", "create"]) def test_empty_country_inventory(monkeypatch, command, fake_number_client): monkeypatch.setattr( - number.cloud_numbers, + number.Numbers, "countries", AsyncMock(return_value=NS(data=NS(items=[]))), ) @@ -287,7 +298,7 @@ def test_country_capacity_concurrency_is_bounded_and_client_reused( ): countries = [NS(country=str(i), name=str(i), in_stock=True) for i in range(5)] monkeypatch.setattr( - number.cloud_numbers, + number.Numbers, "countries", AsyncMock(return_value=NS(data=NS(items=countries))), ) @@ -318,7 +329,7 @@ async def capacity(country, *, billing, client): def test_country_capacity_failure_human_table(monkeypatch, fake_number_client): countries = [NS(country="gb", name="United Kingdom", in_stock=True)] monkeypatch.setattr( - number.cloud_numbers, + number.Numbers, "countries", AsyncMock(return_value=NS(data=NS(items=countries))), ) @@ -337,27 +348,10 @@ def test_country_capacity_failure_human_table(monkeypatch, fake_number_client): assert result.stderr.count("Warning:") == 1 and "private" not in result.stderr -def test_cloud_devices_order_labels_and_no_commerce(monkeypatch): - listing = AsyncMock( - return_value=[ - NS(id="d1", name="Sleeping", state="stopped"), - NS(id="d2", name="Ready", state="running"), - ] - ) - monkeypatch.setattr(choices, "list_devices", listing, raising=False) - result = choices.cloud_devices(click.Context(click.Command("test"))) - assert [item.value for item in result] == ["d2", "d1"] - assert "Ready" in result[0].label and "running" in ( - result[0].hint or result[0].label - ) - assert "stopped" in (result[1].hint or result[1].label) - listing.assert_awaited_once_with(billing=Billing.NO_COMMERCE, base_url=None) - - def test_resource_picker_status_and_order(monkeypatch): monkeypatch.setattr( - choices, - "list_mailboxes", + choices.Mailboxes, + "list", AsyncMock( return_value=[ NS(id="m1", address="a", status="failed"), @@ -366,8 +360,8 @@ def test_resource_picker_status_and_order(monkeypatch): ), ) monkeypatch.setattr( - choices, - "list_numbers", + choices.Numbers, + "list", AsyncMock( return_value=[ NS(id="n1", phone_number="1", state="failed"), @@ -387,7 +381,7 @@ def test_resource_picker_status_and_order(monkeypatch): ), ] ) - monkeypatch.setattr(choices, "list_proxies", listing) + monkeypatch.setattr(choices.Proxies, "list", listing) ctx = click.Context(click.Command("test")) proxy_choices = choices.proxies(ctx) for result, ids, status in [ @@ -401,118 +395,136 @@ def test_resource_picker_status_and_order(monkeypatch): assert listing.await_count == 2 -def test_proxy_bind_picks_device_and_reports_progress(monkeypatch): - monkeypatch.setattr(menu, "is_interactive", lambda: True) - monkeypatch.setattr( - choices, - "list_devices", - AsyncMock(return_value=[NS(id="dev", name="Phone", state="running")]), - raising=False, - ) - seen = [] +@pytest.fixture +def proxy_phone(monkeypatch): + phone = fake_device() + closed = AsyncMock() + write = AsyncMock() + prompt = AsyncMock() - def select(label, options): - seen.append((label, [item.value for item in options])) - return options[0].value + @asynccontextmanager + async def owner(*, hitl_gate, **kwargs): + async def connect(identifier=None, *, backend): + assert identifier == PHONE_ID and backend == "cloud" + return phone + + async def set_proxy(value, *, replace): + if not replace and state.occupied: + raise ProxyAlreadyConfigured("occupied") + assert await hitl_gate("device.set_proxy", {"replace": replace}) + await write(value, replace=replace) + + monkeypatch.setattr(phone, "set_proxy", set_proxy) + try: + yield NS(connect=connect, list_cloud_devices=state.list_cloud_devices) + finally: + await closed(PHONE_ID) - monkeypatch.setattr(menu, "select_prompt", select) - phone = NS(close=AsyncMock()) - extension = NS(bind=AsyncMock(), status=AsyncMock(return_value=NS(connected=True))) - monkeypatch.setattr(proxy, "CloudDevice", lambda **kwargs: phone) - monkeypatch.setattr(proxy, "CloudFixedProxy", lambda proxy_id: extension) - result = CliRunner().invoke(proxy.proxy, ["bind", "proxy"]) - assert result.exit_code == 0, result.output - assert seen == [("Cloud device ID", ["dev"])] - assert ( - "Binding proxy" in result.output and "Waiting for connection" in result.output + state = NS( + occupied=False, + closed=closed, + write=write, + prompt=prompt, + list_cloud_devices=AsyncMock(), + core_prompt=AsyncMock(return_value=True), ) - assert "✓ Bound proxy proxy to dev" in result.output - extension.bind.assert_awaited_once_with(phone, force=False) - - -def test_proxy_bind_conflict_asks_before_retry(monkeypatch): - from mobilerun.core.proxy import UnmanagedProxyConflict - - monkeypatch.setattr(menu, "is_interactive", lambda: True) - phone = NS(close=AsyncMock()) - extension = NS( - bind=AsyncMock( - side_effect=[ - UnmanagedProxyConflict( - "Device has an unmanaged active proxy; use force=True to take over" - ), - None, - ] - ), - status=AsyncMock(return_value=NS(connected=True)), + monkeypatch.setattr(selection, "AsyncMobilerun", owner) + monkeypatch.setattr( + selection.LoginStore, "resolve_api_key", lambda self: "fake-key" ) - monkeypatch.setattr(proxy, "CloudDevice", lambda **kwargs: phone) - monkeypatch.setattr(proxy, "CloudFixedProxy", lambda proxy_id: extension) + monkeypatch.setattr(phone, "device_id", PHONE_ID) + monkeypatch.setattr(proxy, "confirm_prompt_async", prompt) + monkeypatch.setattr(approval, "confirm_prompt_async", state.core_prompt) monkeypatch.setattr( - proxy, "confirm_prompt_async", AsyncMock(return_value=True), raising=False + phone, + "proxy_status", + AsyncMock(return_value=ProxyStatus(True, "socks5", "proxy")), ) - result = CliRunner().invoke(proxy.proxy, ["bind", "proxy", "dev"]) - assert result.exit_code == 0, result.output - assert [call.kwargs["force"] for call in extension.bind.await_args_list] == [ - False, - True, + return state + + +def test_proxy_bind_picks_device_and_reports_progress(monkeypatch, proxy_phone): + monkeypatch.setattr(device, "is_interactive", lambda: True) + monkeypatch.setattr(pickers, "is_interactive", lambda: True) + monkeypatch.setattr(menu, "is_interactive", lambda: True) + proxy_phone.list_cloud_devices.return_value = [ + DeviceDescriptor(PHONE_ID, "cloud", name="Phone") ] + seen = [] + + async def catalogue(): + proxy_phone.list_cloud_devices.assert_awaited_once_with() + yield NS(ref=ConnectProxyRef("proxy"), status="active", country="US") + async def select(label, choices): + seen.append((label, [item.value for item in choices])) + return choices[0].value + + monkeypatch.setattr(proxy, "list_connect_proxies", catalogue) + monkeypatch.setattr(pickers, "select_prompt_async", select) + result = CliRunner().invoke(proxy.proxy, ["bind", "--yes"]) + assert result.exit_code == 0, result.output + assert seen == [("proxy ID", ["proxy", "__manual__"])] + assert "Binding proxy" in result.stderr + assert f"✓ Bound proxy proxy to {PHONE_ID}" in result.stdout + proxy_phone.write.assert_awaited_once_with(ConnectProxyRef("proxy"), replace=False) + proxy_phone.prompt.assert_not_awaited() + proxy_phone.closed.assert_awaited_once_with(PHONE_ID) -def test_proxy_bind_conflict_declined(monkeypatch): - from mobilerun.core.proxy import UnmanagedProxyConflict +@pytest.mark.parametrize("approved", [True, False]) +def test_proxy_bind_conflict_confirmation_or_clean_cancellation( + monkeypatch, proxy_phone, approved +): monkeypatch.setattr(menu, "is_interactive", lambda: True) - phone = NS(close=AsyncMock()) - extension = NS( - bind=AsyncMock( - side_effect=UnmanagedProxyConflict( - "Device has an unmanaged active proxy; use force=True to take over" - ) - ) - ) - monkeypatch.setattr(proxy, "CloudDevice", lambda **kwargs: phone) - monkeypatch.setattr(proxy, "CloudFixedProxy", lambda proxy_id: extension) - monkeypatch.setattr(proxy, "confirm_prompt_async", AsyncMock(return_value=False)) - result = CliRunner().invoke(proxy.proxy, ["bind", "proxy", "dev"]) - assert result.exit_code == 0 - assert "Cancelled" in result.output - extension.bind.assert_awaited_once_with(phone, force=False) - phone.close.assert_awaited_once() + monkeypatch.setattr(approval, "is_interactive", lambda: True) + proxy_phone.occupied = True + + async def approve(message, *, default): + proxy_phone.write.assert_not_awaited() + assert default is False + return approved + proxy_phone.prompt.side_effect = approve + result = CliRunner().invoke(proxy.proxy, ["bind", "proxy", PHONE_ID]) + assert result.exit_code == 0, result.output + proxy_phone.prompt.assert_awaited_once() + if approved: + proxy_phone.core_prompt.assert_awaited_once() + proxy_phone.write.assert_awaited_once_with( + ConnectProxyRef("proxy"), replace=True + ) + else: + proxy_phone.core_prompt.assert_not_awaited() + assert "Cancelled.\n" in result.stderr + assert not result.stdout + proxy_phone.write.assert_not_awaited() + proxy_phone.closed.assert_awaited_once_with(PHONE_ID) -def test_proxy_bind_noninteractive_conflict_recommends_force(monkeypatch): - from mobilerun.core.proxy import UnmanagedProxyConflict +def test_proxy_bind_noninteractive_conflict_recommends_force(monkeypatch, proxy_phone): monkeypatch.setattr(menu, "is_interactive", lambda: False) - phone = NS(close=AsyncMock()) - extension = NS( - bind=AsyncMock( - side_effect=UnmanagedProxyConflict( - "Device has an unmanaged active proxy; use force=True to take over" - ) - ) - ) - monkeypatch.setattr(proxy, "CloudDevice", lambda **kwargs: phone) - monkeypatch.setattr(proxy, "CloudFixedProxy", lambda proxy_id: extension) - result = CliRunner().invoke(proxy.proxy, ["bind", "proxy", "dev"]) + proxy_phone.occupied = True + result = CliRunner().invoke(proxy.proxy, ["bind", "proxy", PHONE_ID]) assert result.exit_code != 0 assert "--force" in result.output assert "force=True" not in result.output + proxy_phone.prompt.assert_not_awaited() + proxy_phone.write.assert_not_awaited() -def test_proxy_bind_force_skips_confirmation(monkeypatch): - monkeypatch.setattr(menu, "is_interactive", lambda: True) - phone = NS(close=AsyncMock()) - extension = NS(bind=AsyncMock(), status=AsyncMock(return_value=NS(connected=True))) - prompt = AsyncMock() - monkeypatch.setattr(proxy, "CloudDevice", lambda **kwargs: phone) - monkeypatch.setattr(proxy, "CloudFixedProxy", lambda proxy_id: extension) - monkeypatch.setattr(proxy, "confirm_prompt_async", prompt) - result = CliRunner().invoke(proxy.proxy, ["bind", "proxy", "dev", "--force"]) - assert result.exit_code == 0 - extension.bind.assert_awaited_once_with(phone, force=True) - prompt.assert_not_awaited() +def test_proxy_bind_force_replaces_unattended_without_confirmation( + monkeypatch, proxy_phone +): + monkeypatch.setattr(approval, "is_interactive", lambda: False) + proxy_phone.occupied = True + runner = CliRunner() + args = ["bind", "proxy", PHONE_ID, "--force", "--yes"] + + approved = runner.invoke(proxy.proxy, args) + assert approved.exit_code == 0, approved.output + proxy_phone.write.assert_awaited_once_with(ConnectProxyRef("proxy"), replace=True) + proxy_phone.prompt.assert_not_awaited() def test_proxy_confirmation_default_and_escape(monkeypatch): @@ -550,7 +562,7 @@ def test_code_timeout_validation(): def test_status_commands_show_resource(monkeypatch): monkeypatch.setattr( - number.cloud_numbers, + number.Numbers, "retrieve", AsyncMock( return_value=NS( @@ -563,10 +575,10 @@ def test_status_commands_show_resource(monkeypatch): ) ), ) - from mobilerun.clients.cloud import mailboxes as cloud_mailboxes + from mobilerun.clients.cloud.mailboxes import Mailboxes monkeypatch.setattr( - cloud_mailboxes, + Mailboxes, "retrieve", AsyncMock( return_value=NS(data=NS(id="m1", status="active", address="a@example.com")) @@ -596,7 +608,7 @@ def test_code_timeout_is_actionable(monkeypatch): (number, number.number, "n1"), (mailbox, mailbox.mailbox, "m1"), ): - client = number.cloud_numbers if module is number else mailbox.cloud_mailboxes + client = number.Numbers if module is number else mailbox.Mailboxes monkeypatch.setattr( client, "retrieve", AsyncMock(side_effect=RuntimeError("offline")) ) @@ -610,13 +622,9 @@ def test_code_timeout_is_actionable(monkeypatch): group, ["code", resource, "--timeout", "2", "--sender", "example"] ) assert result.exit_code != 0 - assert ( - resource in result.output - and "example" in result.output - and "2" in result.output - and "retry" in result.output.lower() - ) - assert "Waiting" in result.stderr + fake.wait_for_code.assert_awaited_once_with(sender="example", timeout=2) + assert resource in result.stderr and "2s" in result.stderr + assert "--timeout" in result.stderr and not result.stdout def test_number_messages_countries_and_send(monkeypatch): @@ -628,9 +636,9 @@ class Message(BaseModel): messages = AsyncMock(return_value=[Message(body="hello")]) countries = AsyncMock(return_value=NS(data=NS(items=[Message(body="US")]))) send = AsyncMock() - monkeypatch.setattr(number.cloud_numbers, "messages", messages) - monkeypatch.setattr(number.cloud_numbers, "countries", countries) - monkeypatch.setattr(number.cloud_numbers, "send", send) + monkeypatch.setattr(number.Numbers, "messages", messages) + monkeypatch.setattr(number.Numbers, "countries", countries) + monkeypatch.setattr(number.Numbers, "send", send) runner = CliRunner() result = runner.invoke(number.number, ["messages", "n1", "--json"]) assert result.exit_code == 0, result.output @@ -642,7 +650,7 @@ class Message(BaseModel): number.number, ["send", "n1", "+123", "Hi", "--billing", "paid", "--yes"] ) assert result.exit_code == 0, result.output - send.assert_awaited_once_with("n1", "+123", "Hi", billing=Billing.PAID) + send.assert_awaited_once_with("n1", "+123", "Hi") def test_create_reports_address_and_state(monkeypatch): @@ -666,7 +674,7 @@ def test_create_reports_address_and_state(monkeypatch): monkeypatch.setattr( module, "complete_checkout", AsyncMock(return_value=NS(id=resource)) ) - client = number.cloud_numbers if module is number else mailbox.cloud_mailboxes + client = number.Numbers if module is number else mailbox.Mailboxes monkeypatch.setattr(client, "retrieve", AsyncMock(return_value=NS(data=data))) result = CliRunner().invoke(group, ["create", "--yes", "--json"]) assert result.exit_code == 0, result.output @@ -678,8 +686,8 @@ def test_create_reports_address_and_state(monkeypatch): ) -def test_proxy_json_buy_bind(monkeypatch): - monkeypatch.setattr(billing, "billing_prompt_is_interactive", lambda: True) +def test_proxy_json_buy_bind(monkeypatch, proxy_phone): + monkeypatch.setattr(billing, "can_prompt", lambda _stream: True) async def confirm(message, **kwargs): print(message) @@ -689,13 +697,9 @@ async def confirm(message, **kwargs): async def buy(*a, **k): print("Complete payment: example") - return NS(id="p1", status="active") + return NS(ref=ConnectProxyRef("p1"), status="active") - monkeypatch.setattr(proxy, "buy_proxy", buy) - phone = NS(close=AsyncMock()) - extension = NS(bind=AsyncMock(), status=AsyncMock(return_value=NS(connected=True))) - monkeypatch.setattr(proxy, "CloudDevice", lambda **k: phone) - monkeypatch.setattr(proxy, "CloudFixedProxy", lambda *a: extension) + monkeypatch.setattr(proxy, "purchase_connect_proxy", buy) runner = CliRunner() result = runner.invoke( proxy.proxy, @@ -705,20 +709,21 @@ async def buy(*a, **k): assert json.loads(result.stdout)["id"] == "p1" assert "Buy Connect proxy with paid billing (charges may apply)?" in result.stderr assert "Complete payment" in result.stderr - result = runner.invoke(proxy.proxy, ["bind", "p1", "d1", "--json"]) + result = runner.invoke(proxy.proxy, ["bind", "p1", PHONE_ID, "--json", "--yes"]) assert result.exit_code == 0, result.output assert json.loads(result.stdout) == { "id": "p1", "status": "connected", - "device_id": "d1", + "device_id": PHONE_ID, } - assert "Waiting" in result.stderr + assert "Binding proxy" in result.stderr + proxy_phone.write.assert_awaited_once_with(ConnectProxyRef("p1"), replace=False) def test_create_retrieval_failure_preserves_success(monkeypatch): for module, group, name, client in ( - (number, number.number, "PhoneNumber", number.cloud_numbers), - (mailbox, mailbox.mailbox, "Mailbox", mailbox.cloud_mailboxes), + (number, number.number, "PhoneNumber", number.Numbers), + (mailbox, mailbox.mailbox, "Mailbox", mailbox.Mailboxes), ): monkeypatch.setattr(module, name, lambda *a, **k: object()) monkeypatch.setattr( @@ -739,13 +744,13 @@ def test_create_retrieval_failure_preserves_success(monkeypatch): ) -def test_timeout_resolves_address_and_falls_back(monkeypatch): +def test_timeout_does_not_echo_contact_details(monkeypatch): for module, group, name, client, attr, address in ( ( number, number.number, "PhoneNumber", - number.cloud_numbers, + number.Numbers, "phone_number", "+123", ), @@ -753,7 +758,7 @@ def test_timeout_resolves_address_and_falls_back(monkeypatch): mailbox, mailbox.mailbox, "Mailbox", - mailbox.cloud_mailboxes, + mailbox.Mailboxes, "address", "a@example.com", ), @@ -763,16 +768,13 @@ def test_timeout_resolves_address_and_falls_back(monkeypatch): name, lambda *a, **k: NS(wait_for_code=AsyncMock(side_effect=TimeoutError())), ) - monkeypatch.setattr( - client, "retrieve", AsyncMock(return_value=NS(data=NS(**{attr: address}))) - ) - result = CliRunner().invoke(group, ["code", "r1", "--timeout", "2"]) - assert address in result.output - monkeypatch.setattr( - client, "retrieve", AsyncMock(side_effect=RuntimeError("offline")) - ) + retrieve = AsyncMock(return_value=NS(data=NS(**{attr: address}))) + monkeypatch.setattr(client, "retrieve", retrieve) result = CliRunner().invoke(group, ["code", "r1", "--timeout", "2"]) - assert "r1" in result.output and "Retry" in result.output + assert result.exit_code == 1 + assert "r1" in result.stderr and "--timeout" in result.stderr + assert address not in result.output and not result.stdout + retrieve.assert_not_awaited() def test_create_warning_does_not_expose_unexpected_exception_text(monkeypatch): @@ -781,7 +783,7 @@ def test_create_warning_does_not_expose_unexpected_exception_text(monkeypatch): number, "complete_checkout", AsyncMock(return_value=NS(id="n1")) ) monkeypatch.setattr( - number.cloud_numbers, + number.Numbers, "retrieve", AsyncMock(side_effect=RuntimeError("secret-token")), ) @@ -792,7 +794,7 @@ def test_create_warning_does_not_expose_unexpected_exception_text(monkeypatch): def test_confirmed_number_mailbox_create_json_and_checkout_stderr(monkeypatch): - monkeypatch.setattr(billing, "billing_prompt_is_interactive", lambda: True) + monkeypatch.setattr(billing, "can_prompt", lambda _stream: True) async def confirm(message, **kwargs): print(message) @@ -800,8 +802,8 @@ async def confirm(message, **kwargs): monkeypatch.setattr(safety, "confirm_prompt_async", confirm) for module, group, name, client in ( - (number, number.number, "PhoneNumber", number.cloud_numbers), - (mailbox, mailbox.mailbox, "Mailbox", mailbox.cloud_mailboxes), + (number, number.number, "PhoneNumber", number.Numbers), + (mailbox, mailbox.mailbox, "Mailbox", mailbox.Mailboxes), ): async def purchase(): diff --git a/tests/unit/cli/test_connect.py b/tests/unit/cli/test_connect.py index 8d0ceb464..038819d16 100644 --- a/tests/unit/cli/test_connect.py +++ b/tests/unit/cli/test_connect.py @@ -1,42 +1,96 @@ """Device command parsing, config persistence, and migration examples.""" -import importlib from types import SimpleNamespace -from unittest.mock import AsyncMock, MagicMock +from unittest.mock import AsyncMock import pytest import yaml from click.testing import CliRunner -from mobilerun_core_local.driver import ios +from mobilerun_core import DeviceDescriptor, SetupResult from mobilerun.cli.devices import connect, device, disconnect -from mobilerun.cli.devices.base import options, selection -from mobilerun.cli.devices.base.discovery import DiscoveredDevice +from mobilerun.cli.devices.base import device as device_base +from mobilerun.cli.devices.base import selection +from mobilerun.cli.devices.utils import approval +from mobilerun.cli.devices.utils.connection import device as connection +from mobilerun.config.loader import ConfigLoader from mobilerun.config.migrations import CURRENT_VERSION -from mobilerun.config.user_config import MobileConfig from tests.support.paths import REPO_ROOT CLOUD = "11111111-1111-1111-1111-111111111111" -def test_connect_discovered_sets_default(monkeypatch): +@pytest.fixture(autouse=True) +def core(monkeypatch): + class Factory: + def __init__(self, *, hitl_gate, **kwargs): + self.gate = hitl_gate + gates.append(hitl_gate) + self.local = self + + async def __aenter__(self): + return self + + async def __aexit__(self, *args): + pass + + async def connect_android(self, address): + await self.gate("local.connect_android", {"serial": address}) + return await connect_android(address) + + async def disconnect_android(self, address): + await self.gate("local.disconnect_android", {"serial": address}) + return await disconnect_android(address) + + async def discover_ios(self): + return "http://ios.test" + + async def connect(self, *args, **kwargs): + return await attach(*args, **kwargs) + + async def list_devices(self, **kwargs): + return await inventory(**kwargs) + + async def list_cloud_devices(self): + return await cloud_inventory() + + gates = [] + connect_android = AsyncMock(side_effect=AssertionError("unexpected ADB connect")) + disconnect_android = AsyncMock( + side_effect=AssertionError("unexpected ADB disconnect") + ) + attach = AsyncMock(return_value=SimpleNamespace(device_id="phone", tap=AsyncMock())) + inventory = AsyncMock(return_value=[]) + cloud_inventory = AsyncMock(return_value=[]) + monkeypatch.setattr(selection, "AsyncMobilerun", Factory) + return SimpleNamespace( + connect=connect_android, + disconnect=disconnect_android, + attach=attach, + gates=gates, + inventory=inventory, + cloud_inventory=cloud_inventory, + ) + + +def test_connect_discovered_sets_default(monkeypatch, core): monkeypatch.setattr( connect, "discover_devices", - AsyncMock(return_value=[DiscoveredDevice("usb", "local", None, None, None)]), + AsyncMock( + return_value=[DeviceDescriptor("usb", "local-android-adb", "android")] + ), ) saved = [] monkeypatch.setattr(connect, "save_default_device", saved.append) - adb_connect = AsyncMock() - monkeypatch.setattr(connect.adb, "connect", adb_connect) result = CliRunner().invoke(device, ["connect", "usb"]) assert result.exit_code == 0, result.output assert result.stdout.strip() == "✓ Connected usb (default device)" assert saved == ["usb"] - adb_connect.assert_not_awaited() + core.connect.assert_not_awaited() -def test_connect_picker_add_address(monkeypatch): +def test_connect_picker_add_address(monkeypatch, core): monkeypatch.setattr(connect, "is_interactive", lambda: True) monkeypatch.setattr(connect, "discover_devices", AsyncMock(return_value=[])) labels = [] @@ -47,16 +101,24 @@ async def select(message, choices): monkeypatch.setattr(connect, "select_prompt", select) monkeypatch.setattr(connect, "text_prompt", AsyncMock(return_value="192.168.1.2")) - monkeypatch.setattr( - connect.adb, "connect", AsyncMock(return_value="connected to 192.168.1.2:5555") + core.connect.side_effect = None + core.connect.return_value = SetupResult( + True, + "192.168.1.2:5555", + "connect_android", + {"transport_serial": "192.168.1.2:7777"}, ) + prompt = AsyncMock(return_value=True) + monkeypatch.setattr(approval, "is_interactive", lambda: True) + monkeypatch.setattr(approval, "confirm_prompt_async", prompt) saved = [] monkeypatch.setattr(connect, "save_default_device", saved.append) result = CliRunner().invoke(device, ["connect"]) assert result.exit_code == 0, result.output assert labels[-1] == "Add device by address (host:port)…" - assert saved == ["192.168.1.2:5555"] - assert "✓ Connected 192.168.1.2:5555 (default device)" in result.stdout + assert saved == ["192.168.1.2:7777"] + prompt.assert_awaited_once_with("Approve local connect android?", default=False) + assert "✓ Connected 192.168.1.2:7777 (default device)" in result.stdout def test_connect_without_target_noninteractive(monkeypatch): @@ -66,21 +128,23 @@ def test_connect_without_target_noninteractive(monkeypatch): assert "Pass a device id or host:port." in result.output -def test_disconnect_default_tcp(monkeypatch): +def test_disconnect_default_tcp(monkeypatch, core): monkeypatch.setattr( disconnect.ConfigLoader, "load", lambda path: SimpleNamespace(device=SimpleNamespace(serial="1.2.3.4:5555")), ) - adb_disconnect = AsyncMock(return_value="disconnected 1.2.3.4:5555") - monkeypatch.setattr(disconnect.adb, "disconnect", adb_disconnect) + core.disconnect.side_effect = None + core.disconnect.return_value = SetupResult( + True, "1.2.3.4:5555", "disconnect_android" + ) saved = [] monkeypatch.setattr(disconnect, "save_default_device", saved.append) - result = CliRunner().invoke(device, ["disconnect"]) + result = CliRunner().invoke(device, ["disconnect", "--yes"]) assert result.exit_code == 0, result.output assert result.stdout.strip() == "✓ Disconnected 1.2.3.4:5555" assert saved == [None] - adb_disconnect.assert_awaited_once_with("1.2.3.4:5555", raise_error=True) + core.disconnect.assert_awaited_once_with("1.2.3.4:5555") def test_connect_disconnect_preserve_config(monkeypatch, tmp_path): @@ -92,13 +156,15 @@ def test_connect_disconnect_preserve_config(monkeypatch, tmp_path): monkeypatch.setattr( connect, "discover_devices", - AsyncMock(return_value=[DiscoveredDevice("usb", "local", None, None, None)]), + AsyncMock( + return_value=[DeviceDescriptor("usb", "local-android-adb", "android")] + ), ) runner = CliRunner() result = runner.invoke(device, ["connect", "usb"]) assert result.exit_code == 0, result.output data = yaml.safe_load(path.read_text()) - assert data["device"] == {"serial": "usb", "use_tcp": True} + assert data["device"]["serial"] == "usb" and data["device"]["use_tcp"] is True assert data["custom"] == "retained" result = runner.invoke(device, ["disconnect"]) assert result.exit_code == 0, result.output @@ -107,31 +173,29 @@ def test_connect_disconnect_preserve_config(monkeypatch, tmp_path): assert data["custom"] == "retained" -def test_connect_unreachable_does_not_save(monkeypatch): +def test_connect_unreachable_does_not_save(monkeypatch, core): monkeypatch.setattr(connect, "discover_devices", AsyncMock(return_value=[])) - monkeypatch.setattr( - connect.adb, "connect", AsyncMock(return_value="failed to connect") - ) + core.connect.side_effect = None + core.connect.return_value = SetupResult(False, "host:5555", "connect_android") saved = [] monkeypatch.setattr(connect, "save_default_device", saved.append) - result = CliRunner().invoke(device, ["connect", "host:5555"]) + result = CliRunner().invoke(device, ["connect", "host:5555", "--yes"]) assert result.exit_code == 1 assert "Failed to connect to host:5555" in result.output assert saved == [] -def test_disconnect_specific_other_tcp_keeps_default(monkeypatch): +def test_disconnect_specific_other_tcp_keeps_default(monkeypatch, core): monkeypatch.setattr( disconnect.ConfigLoader, "load", lambda path: SimpleNamespace(device=SimpleNamespace(serial="usb")), ) - monkeypatch.setattr( - disconnect.adb, "disconnect", AsyncMock(return_value="disconnected host:5555") - ) + core.disconnect.side_effect = None + core.disconnect.return_value = SetupResult(True, "host:5555", "disconnect_android") saved = [] monkeypatch.setattr(disconnect, "save_default_device", saved.append) - result = CliRunner().invoke(device, ["disconnect", "host:5555"]) + result = CliRunner().invoke(device, ["disconnect", "host:5555", "--yes"]) assert result.exit_code == 0, result.output assert result.stdout.strip() == "✓ Disconnected host:5555" assert saved == [] @@ -153,14 +217,11 @@ def test_connect_picker_selects_discovered_device(monkeypatch): monkeypatch.setattr( connect, "discover_devices", - AsyncMock(return_value=[DiscoveredDevice("usb", "local", None, None, None)]), + AsyncMock( + return_value=[DeviceDescriptor("usb", "local-android-adb", "android")] + ), ) monkeypatch.setattr(connect, "select_prompt", AsyncMock(return_value="usb")) - monkeypatch.setattr( - connect.adb, - "connect", - AsyncMock(side_effect=AssertionError("unexpected TCP connection")), - ) saved = [] monkeypatch.setattr(connect, "save_default_device", saved.append) result = CliRunner().invoke(device, ["connect"]) @@ -169,126 +230,109 @@ def test_connect_picker_selects_discovered_device(monkeypatch): assert saved == ["usb"] -def test_disconnect_failure_does_not_clear_default(monkeypatch): +def test_disconnect_failure_does_not_clear_default(monkeypatch, core): monkeypatch.setattr( disconnect.ConfigLoader, "load", lambda path: SimpleNamespace(device=SimpleNamespace(serial="host:5555")), ) - monkeypatch.setattr( - disconnect.adb, "disconnect", AsyncMock(side_effect=OSError("offline")) - ) + core.disconnect.side_effect = OSError("offline") saved = [] monkeypatch.setattr(disconnect, "save_default_device", saved.append) - result = CliRunner().invoke(device, ["disconnect"]) + result = CliRunner().invoke(device, ["disconnect", "--yes"]) assert result.exit_code == 1 assert "--debug" in result.output and "offline" not in result.output assert saved == [] -def test_connect_failure_exits_nonzero(monkeypatch): +@pytest.mark.parametrize("command", ["connect", "disconnect"]) +def test_network_address_requires_approval_before_mutating(monkeypatch, core, command): + address = "localhost:5555" monkeypatch.setattr(connect, "discover_devices", AsyncMock(return_value=[])) - monkeypatch.setattr( - "mobilerun.cli.devices.connect.adb.connect", AsyncMock(return_value="failed") - ) - result = CliRunner().invoke(connect.connect, ["localhost:5555"]) - assert result.exit_code == 1 + monkeypatch.setattr(approval, "is_interactive", lambda: False) + operation = getattr(core, command) + + async def run(target): + return SetupResult(True, target, f"{command}_android") + + operation.side_effect = run + refused = CliRunner().invoke(device, [command, address]) + assert refused.exit_code == 1 + assert "pass --yes" in refused.output + operation.assert_not_awaited() + result = CliRunner().invoke(device, [command, address, "--yes"]) + assert result.exit_code == 0, result.output + operation.assert_awaited_once_with(address) @pytest.mark.parametrize( "kind,expected", [("ios", "http://ios.test"), ("android", "usb"), ("cloud", CLOUD)] ) -def test_interactive_discovery_honors_kind(monkeypatch, kind, expected): - async def discover(*, local=True, cloud=True, **kwargs): - return ( - [DiscoveredDevice("usb", "local", None, "device", None)] if local else [] - ) + ( - [DiscoveredDevice(CLOUD, "cloud", None, None, None)] - if cloud and kind != "ios" - else [] - ) - - monkeypatch.setattr(options, "is_interactive", lambda: True) - monkeypatch.setattr( - options, "select_prompt", lambda *args: pytest.fail("unexpected picker") - ) - monkeypatch.setattr(options, "discover_devices", discover) - monkeypatch.setattr( - ios, "discover_ios_device", AsyncMock(return_value="http://ios.test") +def test_interactive_discovery_honors_kind(monkeypatch, core, kind, expected): + backend = { + "ios": "local-ios-http", + "android": "local-android-adb", + "cloud": "cloud", + }[kind] + record = DeviceDescriptor( + expected, backend, state="device" if kind == "android" else None ) - connect = AsyncMock(return_value=AsyncMock()) - monkeypatch.setattr(selection, "connect_target", connect) - result = CliRunner().invoke(device, ["input", "tap", "10", "20", f"--{kind}"]) - assert result.exit_code == 0, result.output - assert connect.await_args.args == (expected,) - assert connect.await_args.kwargs["kind"] == kind - - -def test_ios_skips_incompatible_saved_android_serial(monkeypatch): - config = MobileConfig() - config.device.serial = "usb" - monkeypatch.setattr(options.ConfigLoader, "load", lambda path: config) - monkeypatch.setattr(options, "is_interactive", lambda: True) + if kind == "cloud": + core.cloud_inventory.return_value = [record] + else: + core.inventory.return_value = [SimpleNamespace(info=lambda: record)] + monkeypatch.setattr(device_base, "is_interactive", lambda: True) monkeypatch.setattr( - options, - "discover_devices", - AsyncMock(side_effect=AssertionError("unexpected ADB discovery")), + selection.LoginStore, "resolve_api_key", lambda self: "test-key" ) monkeypatch.setattr( - ios, "discover_ios_device", AsyncMock(return_value="http://ios.test") + connection, + "select_prompt_async", + AsyncMock(side_effect=AssertionError("unexpected picker")), ) - connect = AsyncMock(return_value=AsyncMock()) - monkeypatch.setattr(selection, "connect_target", connect) - result = CliRunner().invoke(device, ["input", "tap", "10", "20", "--ios"]) + result = CliRunner().invoke(device, ["input", "tap", "10", "20", f"--{kind}"]) assert result.exit_code == 0, result.output - assert connect.await_args.args == ("http://ios.test",) + if kind == "ios": + # Core rediscovers the configured endpoint rather than dialing a public URL. + assert core.attach.await_args.kwargs["url"] is None + else: + assert core.attach.await_args.args == (expected,) + assert core.attach.await_args.kwargs["backend"] == backend -def test_remote_does_not_fall_back_to_adb(monkeypatch): - monkeypatch.setattr( - options, - "discover_devices", - AsyncMock(side_effect=AssertionError("unexpected discovery")), - ) - result = CliRunner().invoke(device, ["input", "clipboard", "get", "--remote"]) +def test_remote_does_not_fall_back_to_adb(monkeypatch, core): + monkeypatch.setattr(device_base, "is_interactive", lambda: True) + result = CliRunner().invoke(device, ["input", "tap", "10", "20", "--remote"]) assert result.exit_code == 2 - assert "remote device URL" in result.output + assert "Pass a URL" in result.output + core.inventory.assert_not_awaited() + core.attach.assert_not_awaited() -@pytest.mark.parametrize("device_args", [[CLOUD], ["-d", CLOUD], ["--device", CLOUD]]) -def test_rename_positional_or_device_option(monkeypatch, device_args): - module = importlib.import_module("mobilerun.cli.devices.cloud.rename") - rename = AsyncMock() - monkeypatch.setattr(module.devices, "set_name", rename) - monkeypatch.setattr(module, "cloud_client", MagicMock()) - result = CliRunner().invoke(device, ["cloud", "rename", *device_args, "New"]) - assert result.exit_code == 0, result.output - assert rename.await_args.args == (CLOUD, "New") - - -def test_save_to_explicit_config(monkeypatch, tmp_path): +def test_picker_does_not_persist_a_default(monkeypatch, tmp_path, core): alternate = tmp_path / "alternate.yaml" alternate.write_text(f"_version: {CURRENT_VERSION}\ndevice: {{}}\n") - default = options.ConfigLoader.get_user_config_path() + default = ConfigLoader.get_user_config_path() assert default.is_relative_to(tmp_path) - options.ConfigLoader.load(None) + ConfigLoader.load(None) before = default.read_bytes() - monkeypatch.setattr(options, "is_interactive", lambda: True) - monkeypatch.setattr(options, "select_prompt", lambda *args: "usb-b") - monkeypatch.setattr(options, "confirm_prompt", lambda *args, **kwargs: True) - devices = [ - DiscoveredDevice(id, "local", None, "device", None) for id in ("usb-a", "usb-b") + monkeypatch.setattr(device_base, "is_interactive", lambda: True) + monkeypatch.setattr(connection, "select_prompt_async", AsyncMock(return_value="1")) + core.inventory.return_value = [ + SimpleNamespace( + info=lambda serial=serial: DeviceDescriptor( + serial, "local-android-adb", "android", state="device" + ) + ) + for serial in ("usb-a", "usb-b") ] - monkeypatch.setattr(options, "discover_devices", AsyncMock(return_value=devices)) - monkeypatch.setattr( - selection, "connect_target", AsyncMock(return_value=AsyncMock()) - ) result = CliRunner().invoke( device, ["input", "tap", "10", "20", "--config", str(alternate)] ) assert result.exit_code == 0, result.output assert default.read_bytes() == before - assert yaml.safe_load(alternate.read_text())["device"]["serial"] == "usb-b" + assert yaml.safe_load(alternate.read_text())["device"] == {} + assert core.attach.await_args.args == ("usb-b",) def test_documented_flat_command_replacements(): diff --git a/tests/unit/cli/test_credential_commands.py b/tests/unit/cli/test_credential_commands.py index de22e8e25..d4bf77b6a 100644 --- a/tests/unit/cli/test_credential_commands.py +++ b/tests/unit/cli/test_credential_commands.py @@ -8,6 +8,7 @@ import stat import subprocess import sys +from contextlib import asynccontextmanager from types import SimpleNamespace from unittest.mock import AsyncMock @@ -16,14 +17,13 @@ from mobilerun.cli.app import cli from mobilerun.cli.credentials import group -from mobilerun.cli.devices.base import selection -from mobilerun.clients.cloud import api_keys, device_flow -from mobilerun.clients.local import login_store as credentials +from mobilerun.clients.cloud import api_keys +from mobilerun.clients.cloud.device_flow import DeviceAuthorization +from mobilerun.clients.local.login_store import LoginStore from mobilerun.core.credentials import file as credential_file from mobilerun.core.credentials.file import FileCredentials -from mobilerun.core.devices.base import Device as DeviceMixin from mobilerun.errors import CloudAPIError, InvalidAPIKeyError -from mobilerun.models.billing import Billing +from tests.support.devices import FakeDriver, fake_device class FakeVault: @@ -66,22 +66,21 @@ def test_login_flow(monkeypatch, tmp_path): verification_uri_complete="", expires_in=60, ) - monkeypatch.setattr(device_flow, "request_code", AsyncMock(return_value=code)) monkeypatch.setattr( - device_flow, "poll_token", AsyncMock(return_value="placeholder") + DeviceAuthorization, "request_code", AsyncMock(return_value=code) ) - monkeypatch.setattr(credentials, "save_token", lambda *a: tmp_path / "auth.json") monkeypatch.setattr( - device_flow, + DeviceAuthorization, "poll_token", AsyncMock(return_value="placeholder") + ) + monkeypatch.setattr(LoginStore, "save", lambda *a: tmp_path / "auth.json") + monkeypatch.setattr( + DeviceAuthorization, "fetch_session", AsyncMock(return_value={"user": {"email": "tester@example.test"}}), ) result = CliRunner().invoke(cli, ["account", "login", "--billing", "included"]) assert result.exit_code == 0, result.output assert "Logged in as tester@example.test." in result.output - assert device_flow.request_code.await_args.kwargs["billing"] is Billing.INCLUDED - assert device_flow.poll_token.await_args.kwargs["billing"] is Billing.INCLUDED - assert device_flow.fetch_session.await_args.kwargs["billing"] is Billing.INCLUDED @pytest.mark.parametrize( @@ -90,22 +89,22 @@ def test_login_flow(monkeypatch, tmp_path): ids=["logged-in", "logged-out"], ) def test_logout_states(monkeypatch, state, expected): - monkeypatch.setattr(credentials, "clear_credentials", lambda: state) + monkeypatch.setattr(LoginStore, "clear", lambda self: state) result = CliRunner().invoke(cli, ["account", "logout"]) assert result.exit_code == 0 assert expected in result.output def test_status_states(monkeypatch): - monkeypatch.setattr(credentials, "load_credentials", lambda: None) + monkeypatch.setattr(LoginStore, "load", lambda self: None) result = CliRunner().invoke(cli, ["account", "status"]) assert result.exit_code != 0 assert "Not logged in" in result.output monkeypatch.setattr( - credentials, "load_credentials", lambda: {"access_token": "placeholder"} + LoginStore, "load", lambda self: {"access_token": "placeholder"} ) monkeypatch.setattr( - device_flow, + DeviceAuthorization, "fetch_session", AsyncMock(return_value={"user": {"email": "tester@example.test", "id": "123"}}), ) @@ -116,6 +115,15 @@ def test_status_states(monkeypatch): def test_login_auth_url_option_and_environment(monkeypatch, tmp_path): calls = [] + import importlib + + login_module = importlib.import_module("mobilerun.cli.auth.login") + + def make_auth(url, *, billing): + calls.append(url) + return DeviceAuthorization(url, billing=billing) + + monkeypatch.setattr(login_module, "DeviceAuthorization", make_auth) code = SimpleNamespace( verification_uri="https://example.test", user_code="ABCD", @@ -124,18 +132,17 @@ def test_login_auth_url_option_and_environment(monkeypatch, tmp_path): ) monkeypatch.setenv("MOBILERUN_AUTH_URL", "https://env.example.test") monkeypatch.setattr( - device_flow, + DeviceAuthorization, "request_code", - AsyncMock( - side_effect=lambda url, client, *, billing: calls.append((url, client)) - or code - ), + AsyncMock(side_effect=lambda client: calls.append(client) or code), ) monkeypatch.setattr( - device_flow, "poll_token", AsyncMock(return_value="placeholder") + DeviceAuthorization, "poll_token", AsyncMock(return_value="placeholder") + ) + monkeypatch.setattr(LoginStore, "save", lambda *args: tmp_path / "auth.json") + monkeypatch.setattr( + DeviceAuthorization, "fetch_session", AsyncMock(return_value=None) ) - monkeypatch.setattr(credentials, "save_token", lambda *args: tmp_path / "auth.json") - monkeypatch.setattr(device_flow, "fetch_session", AsyncMock(return_value=None)) runner = CliRunner() assert runner.invoke(cli, ["account", "login"]).exit_code == 0 assert ( @@ -153,16 +160,18 @@ def test_login_auth_url_option_and_environment(monkeypatch, tmp_path): == 0 ) assert calls == [ - ("https://env.example.test", "mobilerun-cli"), - ("https://option.example.test", "custom"), + "https://env.example.test", + "mobilerun-cli", + "https://option.example.test", + "custom", ] def test_api_key_login_validates_and_saves_privately(monkeypatch, tmp_path): key = "fake-api-key-9876" path = tmp_path / "credentials.json" - monkeypatch.setattr(credentials, "credential_path", lambda: path) - monkeypatch.setattr(api_keys, "validate_api_key", AsyncMock()) + monkeypatch.setattr(LoginStore, "from_settings", lambda: LoginStore(path)) + monkeypatch.setattr(api_keys.ApiKeys, "validate", AsyncMock()) result = CliRunner().invoke(cli, ["account", "login", "--api-key", key]) assert result.exit_code == 0, result.output assert key not in result.output @@ -173,17 +182,17 @@ def test_api_key_login_validates_and_saves_privately(monkeypatch, tmp_path): def test_api_key_rejected_or_network_error_does_not_save(monkeypatch, tmp_path): path = tmp_path / "credentials.json" - monkeypatch.setattr(credentials, "credential_path", lambda: path) + monkeypatch.setattr(LoginStore, "from_settings", lambda: LoginStore(path)) key = "fake-api-key-9876" for error in ( InvalidAPIKeyError("Invalid API key"), CloudAPIError("Could not reach the cloud API"), ): - async def fail(key, error=error, *, billing): + async def fail(self, error=error): raise error - monkeypatch.setattr(api_keys, "validate_api_key", fail) + monkeypatch.setattr(api_keys.ApiKeys, "validate", fail) result = CliRunner().invoke(cli, ["account", "login", "--api-key", key]) assert result.exit_code == 1 assert str(error) in result.output @@ -192,21 +201,23 @@ async def fail(key, error=error, *, billing): def test_api_key_status_logout_and_switching(monkeypatch, tmp_path): - from mobilerun.clients.local.login_store import resolve_cloud_api_key + from mobilerun.clients.local.login_store import LoginStore path = tmp_path / "credentials" / "mobilerun-cloud.json" monkeypatch.setenv("MOBILERUN_USER_CONFIG_DIR", str(tmp_path)) monkeypatch.delenv("MOBILERUN_API_KEY", raising=False) - monkeypatch.setattr(api_keys, "validate_api_key", AsyncMock()) + monkeypatch.setattr(api_keys.ApiKeys, "validate", AsyncMock()) key = "fake-api-key-9876" - credentials.save_token("old-token", "https://example.test") + LoginStore.from_settings().save( + {"access_token": "old-token", "auth_url": "https://example.test"} + ) runner = CliRunner() result = runner.invoke(cli, ["account", "login", "--api-key", key]) assert result.exit_code == 0, result.output saved = json.loads(path.read_text()) assert saved["api_key"] == key and saved["auth_type"] == "api_key" assert saved["saved_at"] and "access_token" not in saved and "auth_url" not in saved - assert resolve_cloud_api_key() == key + assert LoginStore.from_settings().resolve_api_key() == key result = runner.invoke(cli, ["account", "status"]) assert "API key login" in result.output and "fak…9876" in result.output assert key not in result.output @@ -218,8 +229,10 @@ def test_api_key_status_logout_and_switching(monkeypatch, tmp_path): assert "still set" in result.output and not path.exists() assert "env-key-1234" not in result.output monkeypatch.delenv("MOBILERUN_API_KEY") - credentials.save_credentials({"api_key": key, "auth_type": "api_key"}) - credentials.save_token("new-token", "https://example.test") + LoginStore.from_settings().save({"api_key": key, "auth_type": "api_key"}) + LoginStore.from_settings().save( + {"access_token": "new-token", "auth_url": "https://example.test"} + ) assert json.loads(path.read_text()) == { "access_token": "new-token", "auth_url": "https://example.test", @@ -252,13 +265,15 @@ def test_login_reports_optional_browser_and_session_failures(monkeypatch, tmp_pa verification_uri_complete="https://example.test/verify", expires_in=60, ) - monkeypatch.setattr(device_flow, "request_code", AsyncMock(return_value=code)) monkeypatch.setattr( - device_flow, "poll_token", AsyncMock(return_value="placeholder") + DeviceAuthorization, "request_code", AsyncMock(return_value=code) ) - monkeypatch.setattr(credentials, "save_token", lambda *args: tmp_path / "auth.json") monkeypatch.setattr( - device_flow, + DeviceAuthorization, "poll_token", AsyncMock(return_value="placeholder") + ) + monkeypatch.setattr(LoginStore, "save", lambda *args: tmp_path / "auth.json") + monkeypatch.setattr( + DeviceAuthorization, "fetch_session", AsyncMock(side_effect=CloudAPIError("unavailable")), ) @@ -627,8 +642,8 @@ def test_cloud_slug_mapping_and_1password_metadata(monkeypatch): async def listed(*args, **kwargs): return [item] - monkeypatch.setattr(cloud.secrets, "list_secrets", listed) - monkeypatch.setattr(cloud.secrets, "list_package", listed) + monkeypatch.setattr(cloud.Vault, "list", listed) + monkeypatch.setattr(cloud.Vault, "list_package", listed) async def run(): vault = cloud.CloudCredentials(api_key="fake") @@ -637,7 +652,6 @@ async def run(): assert first[0]["package"] == "com-ubercab" assert first[0]["source"] == "1password" assert (await vault.list("com.ubercab"))[0]["package"] == "com.ubercab" - assert (await vault._find("com.ubercab", "password", "main")) is not None assert (await vault.list())[0]["package"] == "com.ubercab" assert (await vault.cloud_task_inputs()).credential_references[ 0 @@ -697,7 +711,7 @@ def test_local_permission_error_shows_chmod_not_contents(tmp_path, monkeypatch): def test_atomic_write_failure_preserves_original(tmp_path, monkeypatch): - from mobilerun.core.credentials import file as file_module + from mobilerun.utils.credentials import private as private_files path = tmp_path / "credentials.yaml" store = FileCredentials(path) @@ -707,7 +721,7 @@ def test_atomic_write_failure_preserves_original(tmp_path, monkeypatch): def fail_replace(source, destination): raise OSError("replace failed") - monkeypatch.setattr(file_module.os, "replace", fail_replace) + monkeypatch.setattr(private_files.os, "replace", fail_replace) with pytest.raises(OSError): asyncio.run(store.save("other", "work", {"password": "second"})) assert path.read_bytes() == original @@ -771,21 +785,22 @@ def save(index): @pytest.mark.parametrize("private_temp", [False, True]) def test_windows_credentials_require_private_temp(tmp_path, monkeypatch, private_temp): + from mobilerun.utils.credentials import private as private_files + windows = SimpleNamespace(**vars(os)) windows.name = "nt" vars(windows).pop("fchmod", None) monkeypatch.setattr(credential_file, "os", windows) + monkeypatch.setattr(private_files, "os", windows) created = [] def private_file(parent): created.append(parent) if not private_temp: raise PermissionError("owner-only DACL unavailable") - return credential_file.tempfile.mkstemp(dir=parent) + return private_files.tempfile.mkstemp(dir=parent) - monkeypatch.setattr( - credential_file, "_windows_private_temp", private_file, raising=False - ) + monkeypatch.setattr(private_files, "_windows_private_temp", private_file) path = tmp_path / "credentials.yaml" store = credential_file.FileCredentials(path) if not private_temp: @@ -802,6 +817,8 @@ def private_file(parent): @pytest.mark.skipif(os.name != "nt", reason="requires Windows DACL APIs") def test_native_windows_shared_directory_does_not_expose_temp(tmp_path): + from mobilerun.utils.credentials import private as private_files + shared = tmp_path / "shared" shared.mkdir() subprocess.run( @@ -809,9 +826,8 @@ def test_native_windows_shared_directory_does_not_expose_temp(tmp_path): check=True, capture_output=True, ) - fd, path = credential_file._windows_private_temp(shared) + fd, path = private_files._windows_private_temp(shared) os.close(fd) - env = dict(os.environ, MOBILERUN_TEST_TEMP=path) inspected = subprocess.run( [ "powershell.exe", @@ -823,7 +839,7 @@ def test_native_windows_shared_directory_does_not_expose_temp(tmp_path): "$acl.GetAccessRules($true,$true,[System.Security.Principal.SecurityIdentifier]) | " "ForEach-Object { $_.IdentityReference.Value }", ], - env=env, + env=dict(os.environ, MOBILERUN_TEST_TEMP=path), capture_output=True, check=True, text=True, @@ -831,46 +847,33 @@ def test_native_windows_shared_directory_does_not_expose_temp(tmp_path): assert inspected.stdout.splitlines() == ["True", "S-1-3-4"] -@pytest.mark.parametrize("configured_path", [True, False]) -def test_macro_cli_attaches_config_file_before_replay( - tmp_path, monkeypatch, configured_path -): - from mobilerun.macro.cli import macro - from tests.support.macro import write_macro +def test_installed_package_picker_uses_cli_connection_seam(monkeypatch): + from mobilerun.config.loader import ConfigLoader - module = importlib.import_module("mobilerun.macro.cli.replay") - secrets = tmp_path / "credentials.yaml" - secrets.write_text("login: private-value\n") - secrets.chmod(0o600) - path = write_macro( - tmp_path, rows=[{"i": 1, "action": "type_secret", "args": {"name": "login"}}] - ) + driver = FakeDriver(apps=[{"package": "com.device.app"}]) + device = fake_device(driver=driver) + connect = AsyncMock(return_value=device) config = SimpleNamespace( - credentials={ - "enabled": True, - **({"file_path": str(secrets)} if configured_path else {}), - }, - device=SimpleNamespace(platform="android", use_tcp=False), - ) - device = DeviceMixin() - device.input_text = AsyncMock(return_value=True) - device._input_text_raw = device.input_text - device.state.refresh = AsyncMock( - return_value=SimpleNamespace( - phone_state={ - "focusedElement": {"className": "EditText"}, - "isEditable": True, - } + device=SimpleNamespace( + serial="test-serial", use_tcp=True, portal_mode="disabled" ) ) - monkeypatch.setattr(module.ConfigLoader, "load", lambda _: config) - monkeypatch.setattr( - module, "get_settings", lambda: SimpleNamespace(local_credentials_path=secrets) - ) - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=device)) - result = CliRunner().invoke( - macro, ["replay", str(path), "fake-serial", "--delay", "0"] - ) - assert result.exit_code == 0, (result.output, result.exception) - device.input_text.assert_awaited_once_with("private-value") - assert "private-value" not in result.output + client_exits = [] + + @asynccontextmanager + async def core(): + try: + yield SimpleNamespace(connect=connect) + finally: + client_exits.append(True) + + monkeypatch.setattr(ConfigLoader, "load", lambda _: config) + monkeypatch.setattr("mobilerun_core.AsyncMobilerun", core) + assert group._installed_packages() == ["com.device.app"] + connect.assert_awaited_once_with( + "test-serial", + backend="local-android-adb", + use_tcp=True, + portal_mode="disabled", + ) + assert client_exits == [True] diff --git a/tests/unit/cli/test_device_actions.py b/tests/unit/cli/test_device_actions.py index 900f84223..b106a5d17 100644 --- a/tests/unit/cli/test_device_actions.py +++ b/tests/unit/cli/test_device_actions.py @@ -1,107 +1,76 @@ -"""Device CLI actions, extension dispatch, cloud safety, and transport selection.""" +"""CLI contracts not covered by the individual device command suites.""" -import asyncio import importlib import json import subprocess import sys -from contextlib import asynccontextmanager, nullcontext +from pathlib import Path from types import SimpleNamespace from unittest.mock import AsyncMock import pytest from click.testing import CliRunner -from mobilerun_sdk.types import DeviceRetrieveResponse +from mobilerun_core import AsyncDevice, DeviceDescriptor, UnsupportedOperation from mobilerun.cli.app import cli -from mobilerun.cli.devices.base import discovery, options, selection +from mobilerun.cli.devices.base import device as device_base +from mobilerun.cli.devices.base import selection from mobilerun.cli.devices.group import device -from mobilerun.clients.cloud import devices -from mobilerun.config.settings import get_settings +from mobilerun.cli.devices.utils.connection import device as connection +from mobilerun.cli.devices.utils.connection import discovery +from mobilerun.cli.devices.utils.prompts import pickers +from mobilerun.clients.local.login_store import LoginStore +from mobilerun.config.loader import ConfigLoader from mobilerun.config.user_config import MobileConfig -from mobilerun.core.devices.base import Device -from mobilerun.core.extensions import Extension, action -from mobilerun.errors import ( - BillingRequired, - CloudPermissionDenied, - DeviceOperationNotSupported, -) -from mobilerun.models.billing import Billing -from mobilerun.models.context import ContextItem +from tests.support.devices import FakeDriver, fake_device +SECRET = "SECRET-MARKER-DO-NOT-PRINT" -@pytest.mark.parametrize( - ("args", "method", "values"), - [ - ( - ["settings", "location", "set", "52.52", "13.40"], - "set_location", - (52.52, 13.4), - ), - (["settings", "location", "reset"], "reset_location", ()), - ( - ["settings", "timezone", "set", "Europe/Berlin"], - "set_timezone", - ("Europe/Berlin",), - ), - (["app", "open", "https://example.com"], "open_url", ("https://example.com",)), - ], -) -def test_environment_cli_selects_device(monkeypatch, args, method, values): - from mobilerun.cli.devices.base import selection as environment - - phone = SimpleNamespace(close=AsyncMock()) - setattr( - phone, - method, - AsyncMock(return_value="clip" if method == "get_clipboard" else None), - ) - connect = AsyncMock(return_value=phone) - monkeypatch.setattr(environment, "connect_target", connect) - result = CliRunner().invoke(device, [*args, "--device", "emulator-5554"]) - assert result.exit_code == 0, (result.output, result.exception) - getattr(phone, method).assert_awaited_once_with(*values) - connect.assert_awaited_once() - assert connect.await_args is not None - assert connect.await_args.args[0] == "emulator-5554" - phone.close.assert_awaited_once() - if method == "get_clipboard": - assert "clip" in result.output - - -def test_unsupported_is_a_click_error(monkeypatch): - from mobilerun.cli.devices.base import selection as environment - - phone = SimpleNamespace( - close=AsyncMock(), - reset_location=AsyncMock( - side_effect=DeviceOperationNotSupported("no reset\ntry again") - ), - ) - monkeypatch.setattr(environment, "connect_target", AsyncMock(return_value=phone)) - result = CliRunner().invoke( - device, ["settings", "location", "reset", "--device", "emulator-5554"] + +@pytest.fixture +def core(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace: + connect = AsyncMock(side_effect=AssertionError("unexpected device attachment")) + close = AsyncMock() + driver = FakeDriver() + local = SimpleNamespace() + cloud_inventory = AsyncMock(side_effect=AssertionError("unexpected inventory")) + inventory = AsyncMock(side_effect=AssertionError("unexpected inventory")) + + class Factory: + def __init__(self, **kwargs: object) -> None: + self.local = local + self.list_cloud_devices = cloud_inventory + self.list_devices = inventory + + async def __aenter__(self) -> "Factory": + return self + + async def __aexit__(self, *args: object) -> None: + await close() + + async def connect(self, *args: object, **kwargs: object) -> AsyncDevice: + return await connect(*args, **kwargs) + + monkeypatch.setattr(selection, "AsyncMobilerun", Factory) + return SimpleNamespace( + connect=connect, + close=close, + driver=driver, + local=local, + cloud=cloud_inventory, + inventory=inventory, ) - assert result.exit_code == 1 - assert result.output.strip() == "Error: no reset try again" - phone.close.assert_awaited_once() @pytest.mark.parametrize("args", [["get"], ["set", "text"]]) @pytest.mark.parametrize( "target_args", [["emulator-5554"], ["http://ios.test", "--ios"]] ) -def test_clipboard_rejects_local_before_connect( - monkeypatch: pytest.MonkeyPatch, args: list[str], target_args: list[str] +def test_clipboard_rejects_local_without_accessing_clipboard( + core: SimpleNamespace, args: list[str], target_args: list[str] ) -> None: - phone = Device() - get_clipboard = AsyncMock(wraps=phone.get_clipboard) - set_clipboard = AsyncMock(wraps=phone.set_clipboard) - monkeypatch.setattr(phone, "get_clipboard", get_clipboard) - monkeypatch.setattr(phone, "set_clipboard", set_clipboard) - connect = AsyncMock(return_value=phone) - monkeypatch.setattr(selection, "connect_target", connect) - + core.connect.side_effect = None + core.connect.return_value = fake_device(driver=core.driver) result = CliRunner().invoke( device, ["input", "clipboard", *args, "--device", *target_args] ) @@ -109,717 +78,196 @@ def test_clipboard_rejects_local_before_connect( assert result.exit_code == 2, result.output assert "Clipboard commands require a cloud device ID." in result.stderr assert "Traceback" not in result.output - connect.assert_not_called() - get_clipboard.assert_not_called() - set_clipboard.assert_not_called() + core.connect.assert_awaited_once() + core.close.assert_awaited_once() + assert core.driver.calls == [] -def test_set_language_on_local_reports_unsupported( - monkeypatch: pytest.MonkeyPatch, +def test_location_prompts_for_device_before_coordinates( + monkeypatch: pytest.MonkeyPatch, core: SimpleNamespace ) -> None: - connect = AsyncMock(return_value=Device()) - monkeypatch.setattr(selection, "connect_target", connect) - result = CliRunner().invoke( - device, ["settings", "language", "set", "de-DE", "--device", "emulator-5554"] - ) - assert result.exit_code == 1 - assert result.output.strip() == "Error: Device doesn't support set_language" - connect.assert_awaited_once() - - -@pytest.mark.parametrize( - ("args", "method", "params", "output"), - [ - (["settings", "language", "set", "de-DE"], "language", {"locale": "de-DE"}, ""), - ( - ["input", "clipboard", "set", "hello"], - "clipboard_set", - {"text": "hello"}, - "", - ), - (["input", "clipboard", "get"], "clipboard_get", {}, "hello"), - ], -) -def test_cloud_only_environment_builds_typed_selected_phone( - monkeypatch, args, method, params, output -): - from mobilerun.core.devices import cloud as environment - from mobilerun.core.devices.cloud import CloudDevice - from mobilerun.core.proxy import ProxyStatus - - target = "11111111-1111-1111-1111-111111111111" - phone = CloudDevice(target, api_key="test") - monkeypatch.setattr( - phone, "_proxy_status", AsyncMock(return_value=ProxyStatus(False)) - ) - calls = [] - endpoint = AsyncMock(return_value=SimpleNamespace(text="hello")) - resources = SimpleNamespace( - retrieve_capabilities=AsyncMock( - return_value=SimpleNamespace( - capabilities=SimpleNamespace(telephony=False, proxy=True) - ) - ), - number=SimpleNamespace( - retrieve=AsyncMock(return_value=SimpleNamespace(binding=None)) - ), - language=SimpleNamespace(set=endpoint), - clipboard=SimpleNamespace(set=endpoint, get=endpoint), - ) - monkeypatch.setattr(phone, "_client", SimpleNamespace(devices=resources)) - monkeypatch.setattr(phone, "_write_client", phone._client) - close = AsyncMock() - monkeypatch.setattr(phone, "close", close) - - def build(*, device_id, base_url): - calls.append((device_id, base_url)) - return phone - - monkeypatch.setattr(environment, "CloudDevice", build) - result = CliRunner().invoke( - device, [*args, "--device", target, "--base-url", "https://example.invalid"] - ) - assert result.exit_code == 0, (result.output, result.exception) - assert calls == [(target, "https://example.invalid")] - endpoint.assert_awaited_once_with(target, **params) - close.assert_awaited_once() - if output: - assert output in result.output - if method == "clipboard_set": - assert f"Clipboard set on {target}" in result.stdout - assert params["text"] not in result.output - - -def test_location_prompts_for_device_before_coordinates(monkeypatch): - from mobilerun.cli.base import menu - from mobilerun.cli.devices.base import options - from mobilerun.cli.devices.base import selection as environment - from mobilerun.cli.devices.base.discovery import DiscoveredDevice - order = [] monkeypatch.setattr( - options, + connection, "discover_devices", AsyncMock( return_value=[ - DiscoveredDevice("emulator-5554", "local", None, "device", None), - DiscoveredDevice("emulator-5556", "local", None, "device", None), + DeviceDescriptor("emulator-5554", "local-android-adb", state="device"), + DeviceDescriptor("emulator-5556", "local-android-adb", state="device"), ] ), ) - monkeypatch.setattr(options, "is_interactive", lambda: True) - monkeypatch.setattr(menu, "is_interactive", lambda: True) + monkeypatch.setattr(device_base, "is_interactive", lambda: True) + monkeypatch.setattr(pickers, "is_interactive", lambda: True) - def pick(*args): + async def pick(label, choices) -> str: order.append("device") - return "emulator-5554" + return choices[0].value - def text(label, **kwargs): + async def text(label: str) -> str: + core.connect.assert_awaited_once() order.append(label) return "1" - monkeypatch.setattr(options, "select_prompt", pick) - monkeypatch.setattr(menu, "text_prompt", text) - monkeypatch.setattr(options, "confirm_prompt", lambda *args, **kwargs: False) - phone = SimpleNamespace(close=AsyncMock(), set_location=AsyncMock()) - monkeypatch.setattr(environment, "connect_target", AsyncMock(return_value=phone)) - result = CliRunner().invoke(device, ["settings", "location", "set"]) + monkeypatch.setattr(connection, "select_prompt_async", pick) + monkeypatch.setattr(pickers, "text_prompt_async", text) + phone = fake_device(driver=core.driver) + # The operation itself is covered by the settings lane; this fake tests + # how the CLI resolves the target and supplies prompted coordinates. + set_location = AsyncMock() + monkeypatch.setattr(phone, "set_location", set_location) + core.connect.side_effect = None + core.connect.return_value = phone + + result = CliRunner().invoke(device, ["settings", "location", "set", "--yes"]) + assert result.exit_code == 0, (result.output, result.exception) assert order == ["device", "Latitude", "Longitude"] - phone.set_location.assert_awaited_once_with(1.0, 1.0) - + assert core.connect.await_args.args == ("emulator-5554",) + set_location.assert_awaited_once_with(1.0, 1.0) -def test_unsupported_connect_is_a_click_error(monkeypatch): - from mobilerun.cli.devices.base import selection as environment - monkeypatch.setattr( - environment, - "connect_target", - AsyncMock(side_effect=DeviceOperationNotSupported("cannot connect")), +def test_unsupported_connect_is_a_click_error(core: SimpleNamespace) -> None: + core.connect.side_effect = UnsupportedOperation( + verb="connect", backend="local-android-adb", reason="cannot connect\ntry again" ) result = CliRunner().invoke( device, ["app", "open", "https://example.com", "--device", "emulator-5554"] ) assert result.exit_code == 1 - assert result.output.strip() == "Error: cannot connect" - - -class DemoExtension(Extension): - default_name = "demo" - exclusive = "example" - - async def context(self): - return [ContextItem("demo", "info", {"message": "ready"})] - - @action() - async def repeat(self, text: str, count: int, loud: bool = False) -> str: - """Repeat a message.""" - result = text * count - return result.upper() if loud else result - - -@pytest.fixture -def connected(monkeypatch): - from mobilerun.cli.devices.base import selection as extensions - - device = Device() - asyncio.run(DemoExtension().bind(device)) - device.close = AsyncMock() - monkeypatch.setattr(extensions, "connect_target", AsyncMock(return_value=device)) - return device - - -def test_extensions_json_reports_context(connected): - result = CliRunner().invoke( - device, ["action", "extensions", "emulator-5554", "--json"] + assert result.stderr == ( + "Error: 'connect' is not supported on backend='local-android-adb': " + "cannot connect try again\n" ) - assert result.exit_code == 0, result.output - assert json.loads(result.output) == [ - { - "name": "demo", - "kind": "DemoExtension", - "exclusive": "example", - "context": [ - {"source": "demo", "kind": "info", "data": {"message": "ready"}} - ], - } - ] - connected.close.assert_awaited_once() - - -def test_actions_lists_public_actions(connected): - result = CliRunner().invoke(device, ["action", "list", "emulator-5554"]) - assert result.exit_code == 0, result.output - assert "demo.repeat" in result.output and "Repeat a message" in result.output - connected.close.assert_awaited_once() + core.close.assert_awaited_once() -def test_call_converts_types_and_serializes(connected): - result = CliRunner().invoke( - device, - [ - "action", - "call", - "demo.repeat", - "emulator-5554", - "--arg", - "text=ab", - "--arg", - "count=2", - "--arg", - "loud=true", - "--json", - ], - ) - assert result.exit_code == 0, (result.output, result.exception) - assert json.loads(result.output) == "ABAB" - connected.close.assert_awaited_once() - - -def test_call_missing_arg_is_clean_error(connected): - result = CliRunner().invoke( - device, ["action", "call", "demo.repeat", "emulator-5554", "--arg", "text=x"] - ) - assert result.exit_code == 1 - assert "count" in result.output - connected.close.assert_awaited_once() - - -def test_call_prompts_required_argument(connected, monkeypatch): - import importlib - - extensions = importlib.import_module("mobilerun.cli.devices.action.call") - - monkeypatch.setattr(extensions, "is_interactive", lambda: True) - monkeypatch.setattr(extensions, "text_prompt", AsyncMock(return_value="2")) - result = CliRunner().invoke( - device, - ["action", "call", "demo.repeat", "emulator-5554", "--arg", "text=x", "--json"], - ) - assert result.exit_code == 0, (result.output, result.exception) - assert json.loads(result.output) == "xx" - +@pytest.mark.parametrize("command", ["attach", "cloud-list"]) +def test_unexpected_device_errors_show_details_only_in_debug( + monkeypatch: pytest.MonkeyPatch, core: SimpleNamespace, command: str +) -> None: + if command == "attach": + boundary = core.connect + args = ["device", "app", "open", "https://example.com", "serial"] + expected = "unexpected failure" + else: + monkeypatch.setattr( + discovery.LoginStore, "resolve_api_key", lambda self: "fake" + ) + boundary = core.cloud + args = ["device", "list", "--cloud"] + expected = "Error listing cloud devices" + boundary.side_effect = RuntimeError(SECRET) -def test_call_rejects_unknown_action_and_closes(connected): - result = CliRunner().invoke( - device, ["action", "call", "demo.missing", "emulator-5554"] - ) + result = CliRunner().invoke(cli, args) assert result.exit_code == 1 - assert result.output.strip() == "Error: Unknown action: demo.missing" - connected.close.assert_awaited_once() + assert expected in result.stderr and "--debug" in result.stderr + assert SECRET not in result.output + debug = CliRunner().invoke(cli, ["--debug", *args]) + assert debug.exit_code == 1 and SECRET in debug.stderr + assert boundary.await_count == 2 @pytest.mark.parametrize( - "arguments", + "command,endpoint", [ - ["--arg", "oops"], - ["--arg", "unknown=x"], - ["--arg", "count=bad", "--arg", "text=x"], + ("login", "request_code"), + ("status", "fetch_session"), ], ) -def test_call_bad_arguments_are_clean_errors(connected, arguments): - result = CliRunner().invoke( - device, ["action", "call", "demo.repeat", "emulator-5554", *arguments] - ) - assert result.exit_code == 1 - assert result.output.startswith("Error: ") - connected.close.assert_awaited_once() - - -def test_connection_error_is_one_line(monkeypatch): - from mobilerun.cli.devices.base import selection as extensions - - monkeypatch.setattr( - extensions, - "connect_target", - AsyncMock(side_effect=RuntimeError("offline\ntry later")), - ) - result = CliRunner().invoke(device, ["action", "list", "emulator-5554"]) - assert result.exit_code == 1 - assert "--debug" in result.output - - -CLOUD = "11111111-1111-1111-1111-111111111111" - - -def test_status_json_only_prints_status_fields(monkeypatch): - module = importlib.import_module("mobilerun.cli.devices.cloud.status") - info = DeviceRetrieveResponse.model_construct( - id=CLOUD, - name="Phone", - state="ready", - type="android_cloud_phone", - streamToken="synthetic-token", - streamUrl="https://example.invalid/synthetic-token", - futureSecret="synthetic-token", - ) - monkeypatch.setattr(module, "cloud_client", lambda **kw: nullcontext(object())) - monkeypatch.setattr(devices, "retrieve", AsyncMock(return_value=info)) - result = CliRunner().invoke(device, ["cloud", "status", CLOUD, "--json"]) - assert result.exit_code == 0 - assert json.loads(result.stdout)["state"] == "ready" - assert "streamToken" not in result.output and "stream_token" not in result.output - assert "synthetic-token" not in result.output +def test_unexpected_auth_failures_do_not_print_values( + monkeypatch: pytest.MonkeyPatch, command: str, endpoint: str +) -> None: + module = importlib.import_module(f"mobilerun.cli.auth.{command}") + fail = AsyncMock(side_effect=RuntimeError(SECRET)) + monkeypatch.setattr(module.DeviceAuthorization, endpoint, fail) + if command == "status": + monkeypatch.setattr(LoginStore, "load", lambda self: {"access_token": "fake"}) + result = CliRunner().invoke(cli, ["account", command]) + assert result.exit_code == 1, result.output + assert SECRET not in result.output and "--debug" in result.output + fail.assert_awaited_once() @pytest.mark.parametrize( - "mode,flags,expected", + "name,endpoint,args", [ - ("no_commerce", [], "paid"), - ("included", ["--yes"], "paid"), - ("paid", [], "--yes"), - ("paid", ["--yes"], "sent"), + ("connect", "connect_android", ["host:5555", "--yes"]), + ("ping", "ping_portal", ["serial"]), + ("setup", "setup_portal", ["serial"]), ], ) -@pytest.mark.parametrize("alias", ["sms", "work"]) -def test_third_party_sms_retains_legacy_confirmation( - monkeypatch, mode, flags, expected, alias -): - sent = [] - - class BoundNumber(Extension): - role = "phone_number" - - @action() - async def send(self, to: str, text: str) -> str: - """Record an outgoing SMS without calling a provider.""" - sent.append((to, text)) - return "sent" - - phone = Device() - asyncio.run(BoundNumber(name=alias).bind(phone)) - phone.close = AsyncMock() - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=phone)) - monkeypatch.setenv("MOBILERUN_BILLING", mode) - args = [ - "action", - "call", - f"{alias}.send", - CLOUD, - "--arg", - "to=5550100", - "--arg", - "text=hello", - *flags, - ] - result = CliRunner().invoke(device, args) - assert expected in result.output - assert (result.exit_code == 0) == (expected == "sent") - assert sent == ([("5550100", "hello")] if expected == "sent" else []) - - -@pytest.mark.parametrize("mode", [Billing.INCLUDED, Billing.NO_COMMERCE]) -@pytest.mark.parametrize("strategy", ["minute", None, "auto", "subscription"]) -def test_restricted_resume_checks_existing_strategy(mode, strategy): - client = SimpleNamespace( - devices=SimpleNamespace( - retrieve=AsyncMock(return_value=SimpleNamespace(billing_strategy=strategy)), - resume=AsyncMock(), - ) - ) - if strategy == "subscription": - asyncio.run(devices.resume(CLOUD, billing=mode, client=client)) - client.devices.resume.assert_awaited_once_with(CLOUD) - else: - with pytest.raises(BillingRequired, match="paid") as caught: - asyncio.run(devices.resume(CLOUD, billing=mode, client=client)) - assert (caught.value.needed, caught.value.given) == (Billing.PAID, mode) - client.devices.resume.assert_not_awaited() - client.devices.retrieve.assert_awaited_once_with(CLOUD) - - -def test_restricted_subscription_resume_never_prompts(monkeypatch): - from mobilerun.cli.base import menu, safety - - monkeypatch.setenv("MOBILERUN_BILLING", "included") - monkeypatch.setattr(menu, "is_interactive", lambda: True) - prompt = AsyncMock(side_effect=AssertionError("subscription needs no consent")) - monkeypatch.setattr(safety, "confirm_prompt_async", prompt) - transport = SimpleNamespace( - retrieve=AsyncMock( - return_value=SimpleNamespace(billing_strategy="subscription") - ), - resume=AsyncMock(), - ) - module = importlib.import_module("mobilerun.cli.devices.cloud.resume") - monkeypatch.setattr( - module, - "cloud_client", - lambda **kwargs: nullcontext(SimpleNamespace(devices=transport)), - ) - result = CliRunner().invoke(device, ["cloud", "resume", CLOUD]) - assert result.exit_code == 0, result.output - prompt.assert_not_awaited() - transport.retrieve.assert_awaited_once_with(CLOUD) - transport.resume.assert_awaited_once_with(CLOUD) - - -def test_paid_resume_needs_no_strategy_lookup(): - client = SimpleNamespace(devices=SimpleNamespace(resume=AsyncMock())) - asyncio.run(devices.resume(CLOUD, billing=Billing.PAID, client=client)) - client.devices.resume.assert_awaited_once_with(CLOUD) - - -def test_strict_discovery_withholds_unexpected_details_except_in_debug(monkeypatch): - monkeypatch.setattr(discovery, "resolve_cloud_api_key", lambda: "fake") - monkeypatch.setattr( - discovery, - "list_devices", - AsyncMock(side_effect=RuntimeError("diagnostic-canary")), - ) - args = ["device", "list", "--cloud"] - result = CliRunner().invoke(cli, args) - assert result.exit_code == 1 and "Error listing cloud devices" in result.stderr - assert "diagnostic-canary" not in result.stderr - result = CliRunner().invoke(cli, ["--debug", *args]) - assert result.exit_code == 1 and "diagnostic-canary" in result.stderr - - -@pytest.fixture -def rename_setup(monkeypatch): - module = importlib.import_module("mobilerun.cli.devices.cloud.rename") - endpoint = AsyncMock() - monkeypatch.setattr(module.devices, "set_name", endpoint) - opened = object() - calls = [] - - @asynccontextmanager - async def client(**kwargs): - calls.append(kwargs) - yield opened - - monkeypatch.setattr(module, "cloud_client", client) - return module, endpoint, opened, calls - - -def test_rename_arguments_and_json(rename_setup): - _, endpoint, opened, calls = rename_setup - result = CliRunner().invoke( - device, - [ - "cloud", - "rename", - CLOUD, - " New name ", - "--json", - "--base-url", - "https://example.test", - ], - ) - assert result.exit_code == 0, (result.output, result.exception) - assert json.loads(result.stdout) == {"id": CLOUD, "name": "New name"} - billing = get_settings().MOBILERUN_BILLING - assert calls == [{"base_url": "https://example.test", "billing": billing}] - endpoint.assert_awaited_once_with(CLOUD, "New name", billing=billing, client=opened) - - -def test_rename_interactive_prompt(rename_setup, monkeypatch): - module, endpoint, _, _ = rename_setup - monkeypatch.setattr(module, "is_interactive", lambda: True) - monkeypatch.setattr(module, "text_prompt_async", AsyncMock(return_value=" Phone ")) - result = CliRunner().invoke(device, ["cloud", "rename", CLOUD]) - assert result.exit_code == 0, (result.output, result.exception) - assert f"✓ Renamed {CLOUD} to Phone" in result.output - assert endpoint.await_args.args == (CLOUD, "Phone") - - -def test_rename_empty_prompt_cancels(rename_setup, monkeypatch): - module, endpoint, _, _ = rename_setup - monkeypatch.setattr(module, "is_interactive", lambda: True) - monkeypatch.setattr(module, "text_prompt_async", AsyncMock(return_value=" ")) - result = CliRunner().invoke(device, ["cloud", "rename", CLOUD]) - assert result.exit_code == 0 - assert result.stderr == "Cancelled.\n" - endpoint.assert_not_awaited() - - -@pytest.mark.parametrize("args", [[CLOUD, " "], [CLOUD]]) -def test_rename_invalid_noninteractive_name(rename_setup, args): - _, endpoint, _, _ = rename_setup - result = CliRunner().invoke(device, ["cloud", "rename", *args]) - assert result.exit_code != 0 - endpoint.assert_not_awaited() - - -def test_rename_picks_cloud_device_when_omitted(rename_setup, monkeypatch): - from mobilerun.cli.base import choices - from mobilerun.cli.base.prompts import SelectChoice - from mobilerun.cli.devices.base import options, pickers - - module, endpoint, _, _ = rename_setup - monkeypatch.setattr(options, "is_interactive", lambda: True) - monkeypatch.setattr(pickers, "is_interactive", lambda: True) - monkeypatch.setattr(module, "is_interactive", lambda: True) - monkeypatch.setattr(module, "text_prompt_async", AsyncMock(return_value="New")) - monkeypatch.setattr( - options, - "discover_devices", - AsyncMock(side_effect=AssertionError("local discovery")), - ) - monkeypatch.setattr( - choices, "cloud_devices", lambda ctx: [SelectChoice(CLOUD, "Phone")] - ) - monkeypatch.setattr( - pickers, "select_prompt", lambda label, entries: entries[0].value - ) - result = CliRunner().invoke(device, ["cloud", "rename"]) - assert result.exit_code == 0, (result.output, result.exception) - assert endpoint.await_args.args == (CLOUD, "New") - - -@pytest.mark.parametrize("json_option", [[], ["--json"]]) -def test_rename_cloud_error_is_reported_on_stderr(rename_setup, json_option): - _, endpoint, _, _ = rename_setup - error = CloudPermissionDenied(operation="Rename cloud phone", status=403) - endpoint.side_effect = error - result = CliRunner().invoke(device, ["cloud", "rename", CLOUD, "New", *json_option]) - assert result.exit_code != 0 - assert str(error) in result.stderr - assert result.stdout == "" - - -def test_set_name_preserves_injected_client_and_sanitizes_error(): - import asyncio - from types import SimpleNamespace - - import httpx - from mobilerun_sdk import APIStatusError - - from mobilerun.clients.cloud import devices - from mobilerun.errors import CloudPermissionDenied - - error = APIStatusError( - "sensitive-value", - response=httpx.Response( - 403, request=httpx.Request("PUT", "https://example.test") - ), - body={}, - ) - endpoint = AsyncMock(side_effect=error) - client = SimpleNamespace( - devices=SimpleNamespace(set_name=endpoint), close=AsyncMock() - ) - with pytest.raises(CloudPermissionDenied) as caught: - asyncio.run( - devices.set_name(CLOUD, "name", billing="no_commerce", client=client) - ) - assert "sensitive-value" not in str(caught.value) - client.close.assert_not_awaited() - - -SECRET = "SECRET-MARKER-DO-NOT-PRINT" - +def test_unexpected_local_failures_do_not_print_values( + monkeypatch: pytest.MonkeyPatch, + core: SimpleNamespace, + name: str, + endpoint: str, + args: list[str], +) -> None: + fail = AsyncMock(side_effect=RuntimeError(SECRET)) + setattr(core.local, endpoint, fail) + if name == "connect": + from mobilerun.cli.devices import connect -class FailingExtension(Extension): - @action() - async def fail(self) -> None: - """Fail unexpectedly.""" - raise RuntimeError(SECRET) + monkeypatch.setattr(connect, "discover_devices", AsyncMock(return_value=[])) + result = CliRunner().invoke(cli, ["device", name, *args]) -def test_actual_action_failure_is_sanitized(monkeypatch): - phone = Device() - asyncio.run(FailingExtension(name="demo").bind(phone)) - phone.close = AsyncMock() - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=phone)) - args = ["device", "action", "call", "demo.fail", "serial"] - result = CliRunner().invoke(cli, args) - assert result.exit_code == 1 and SECRET not in result.output - assert "RuntimeError" in result.output - phone.close.assert_awaited_once() + assert result.exit_code == 1, result.output + assert SECRET not in result.output and "--debug" in result.output + fail.assert_awaited_once() -def test_call_connection_failure_reaches_root_sanitizer(monkeypatch): - monkeypatch.setattr( - selection, "connect_target", AsyncMock(side_effect=RuntimeError(SECRET)) - ) - args = ["device", "action", "call", "demo.fail", "serial"] - result = CliRunner().invoke(cli, args) - assert result.exit_code == 1 and SECRET not in result.output - assert "--debug" in result.output - debug = CliRunner().invoke(cli, ["--debug", *args]) - assert debug.exit_code == 1 and SECRET in debug.output - +def test_unexpected_mixed_inventory_failure_does_not_print_values( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from mobilerun.cli.devices import list as listing -@pytest.mark.parametrize( - "module_name, boundary, args", - [ - ("auth.login", "deviceauth.request_code", ["account", "login"]), - ("auth.status", "deviceauth.fetch_session", ["account", "status"]), - ("devices.connect", "adb.connect", ["device", "connect", "host:5555"]), - ("devices.disconnect", "adb.disconnect", ["device", "disconnect", "host:5555"]), - ("devices.list", "discover_devices", ["device", "list"]), - ("devices.ping", "adb.device", ["device", "ping", "serial"]), - ("devices.setup", "adb.device", ["device", "setup", "serial"]), - ], -) -def test_unexpected_boundary_failures_do_not_print_values( - monkeypatch, module_name, boundary, args -): - module = importlib.import_module("mobilerun.cli." + module_name) - parent, _, attribute = boundary.rpartition(".") - owner = getattr(module, parent) if parent else module - monkeypatch.setattr(owner, attribute, AsyncMock(side_effect=RuntimeError(SECRET))) - if module_name == "auth.status": - monkeypatch.setattr( - module.credentials, "load_credentials", lambda: {"access_token": "fake"} - ) - if module_name == "devices.connect": - monkeypatch.setattr(module, "discover_devices", AsyncMock(return_value=[])) - result = CliRunner().invoke(cli, args) + fail = AsyncMock(side_effect=RuntimeError(SECRET)) + monkeypatch.setattr(listing, "discover_devices", fail) + result = CliRunner().invoke(cli, ["device", "list"]) assert result.exit_code == 1, result.output assert SECRET not in result.output and "--debug" in result.output + fail.assert_awaited_once() @pytest.mark.parametrize( - "platform, backend, expected", + "platform,backend,expected_backend", [ - ("ios", None, "ios"), - ("android", None, "android"), - ("ios", "visual-remote", "visual_remote"), + ("ios", None, "local-ios-http"), + ("android", None, "local-android-http"), + ("ios", "visual-remote", "visual-remote"), ], ) def test_saved_url_uses_configured_transport_without_discovery( - monkeypatch, platform, backend, expected -): + monkeypatch: pytest.MonkeyPatch, + core: SimpleNamespace, + platform: str, + backend: str | None, + expected_backend: str, +) -> None: config = MobileConfig() config.device.serial = "http://localhost:8080" config.device.platform = platform config.device.control_backend = backend - monkeypatch.setattr(options.ConfigLoader, "load", lambda path: config) - discover = AsyncMock( - side_effect=AssertionError("URL endpoints aren't discoverable") - ) - monkeypatch.setattr(options, "discover_devices", discover) - phone = AsyncMock() - connect = AsyncMock(return_value=phone) - monkeypatch.setattr(selection, "connect_target", connect) - result = CliRunner().invoke(cli, ["device", "input", "press", "HOME"]) - assert result.exit_code == 0, result.output - assert connect.await_args.args == (config.device.serial,) - assert connect.await_args.kwargs["kind"] == expected - phone.close.assert_awaited_once() - discover.assert_not_awaited() - - -def test_agent_run_ios_without_serial_discovers_portal(monkeypatch): - pytest.importorskip("mobilerun_agents", reason="requires mobilerun-agents add-on") - from mobilerun_core_local.driver import ios - - module = importlib.import_module("mobilerun_agents.cli.agent.run") - config = MobileConfig() - monkeypatch.setattr(options.ConfigLoader, "load", lambda path: config) - discovered = AsyncMock(return_value="http://localhost:8080") - monkeypatch.setattr(ios, "discover_ios_device", discovered) - monkeypatch.setattr( - options, - "discover_devices", - AsyncMock(side_effect=AssertionError("No ADB for iOS")), - ) - connect = AsyncMock(return_value=AsyncMock()) - monkeypatch.setattr(selection, "connect_target", connect) - execute = AsyncMock(return_value=SimpleNamespace(answer="done", success=True)) - monkeypatch.setattr( - module, "AgentOperator", lambda **kwargs: SimpleNamespace(execute=execute) - ) - monkeypatch.setattr(module.ConfigLoader, "load", lambda _: SimpleNamespace()) - result = CliRunner().invoke(cli, ["agent", "run", "hello", "--ios"]) - assert result.exit_code == 0, result.output - discovered.assert_awaited_once_with() - assert connect.await_args.kwargs["kind"] == "ios" - execute.assert_awaited_once_with(connect.return_value, "hello", max_steps=None) - - -def test_reboot_requires_consent_before_client(monkeypatch): - module = importlib.import_module("mobilerun.cli.devices.cloud.reboot") - calls = [] - - @asynccontextmanager - async def client(**kwargs): - calls.append(kwargs) - yield object() - - method = AsyncMock() - monkeypatch.setattr(module, "cloud_client", client) - monkeypatch.setattr(module.devices, "reboot", method) - result = CliRunner().invoke(cli, ["device", "cloud", "reboot", CLOUD]) - assert result.exit_code == 1 and "--yes" in result.output - assert calls == [] - method.assert_not_awaited() - accepted = CliRunner().invoke(cli, ["device", "cloud", "reboot", CLOUD, "--yes"]) - assert accepted.exit_code == 0, accepted.output - method.assert_awaited_once() - - -def test_reboot_warning_and_decline_prevent_billing(monkeypatch): - from mobilerun.cli.base import menu - - module = importlib.import_module("mobilerun.cli.devices.cloud.reboot") - client = AsyncMock(side_effect=AssertionError("No client before confirmation")) - monkeypatch.setattr(menu, "is_interactive", lambda: True) - from mobilerun.cli.base import safety - - monkeypatch.setattr(safety, "confirm_prompt_async", AsyncMock(return_value=False)) - monkeypatch.setattr(module, "cloud_client", client) - result = CliRunner().invoke(cli, ["device", "cloud", "reboot", CLOUD], input="n\n") - assert result.exit_code == 0, result.output - assert "may incur charges" in result.output and "Billing: paid" in result.output - client.assert_not_called() - + if platform == "android": + config.device.auth_token = "test-portal-token" + ConfigLoader.save(config) + phone = fake_device(driver=core.driver) + core.connect.side_effect = None + core.connect.return_value = phone -def test_stop_remains_nonbillable_and_does_not_require_yes(monkeypatch): - module = importlib.import_module("mobilerun.cli.devices.cloud.stop") - - @asynccontextmanager - async def client(**kwargs): - yield object() + result = CliRunner().invoke(cli, ["device", "input", "press", "HOME"]) - method = AsyncMock() - monkeypatch.setattr(module, "cloud_client", client) - monkeypatch.setattr(module.devices, "stop", method) - result = CliRunner().invoke(cli, ["device", "cloud", "stop", CLOUD]) assert result.exit_code == 0, result.output - method.assert_awaited_once() + kwargs = {"url": config.device.serial, "backend": expected_backend} + if backend == "visual-remote": + core.connect.assert_awaited_once_with(config.device.device_id, **kwargs) + else: + core.connect.assert_awaited_once_with(token=config.device.auth_token, **kwargs) + assert core.driver.calls == [("press_button", ("home",), {})] + core.close.assert_awaited_once() + core.inventory.assert_not_awaited() @pytest.mark.parametrize( @@ -827,10 +275,10 @@ async def client(**kwargs): [ ["agent", "--help"], ["agent", "task", "--help"], - ["agent", "task", "status", "--help"], + ["agent", "task", "trajectory", "--help"], ], ) -def test_agent_management_help_follows_plugin_availability(args): +def test_agent_management_help_follows_plugin_availability(args: list[str]) -> None: script = f""" import sys from click.testing import CliRunner @@ -854,7 +302,9 @@ def test_agent_management_help_follows_plugin_availability(args): @pytest.mark.parametrize("kind", ["countries", "messages"]) -def test_number_read_views_use_visual_language_and_keep_json(monkeypatch, kind): +def test_number_read_views_use_visual_language_and_keep_json( + monkeypatch: pytest.MonkeyPatch, kind: str +) -> None: module = importlib.import_module("mobilerun.cli.phone_number.group") entry = ( {"country": "US", "name": "United States", "in_stock": True, "plan_id": "plan"} @@ -874,7 +324,7 @@ def test_number_read_views_use_visual_language_and_keep_json(monkeypatch, kind): if kind == "countries" else [model] ) - monkeypatch.setattr(module.cloud_numbers, kind, AsyncMock(return_value=value)) + monkeypatch.setattr(module.Numbers, kind, AsyncMock(return_value=value)) args = ["number", kind] + (["number-1"] if kind == "messages" else []) human = CliRunner().invoke(cli, args) assert human.exit_code == 0, human.output @@ -884,7 +334,13 @@ def test_number_read_views_use_visual_language_and_keep_json(monkeypatch, kind): assert json.loads(machine.stdout) == [entry] -def test_workspace_upload_acknowledgements(monkeypatch, tmp_path): +def test_workspace_upload_acknowledgements( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + from mobilerun_core import AppIdentity + + from mobilerun.models import App + module = importlib.import_module("mobilerun.cli.workspace.group") path = tmp_path / "app.apk" path.write_bytes(b"fake") @@ -896,11 +352,7 @@ def test_workspace_upload_acknowledgements(monkeypatch, tmp_path): monkeypatch.setattr( module.Workspace, "upload_app", - AsyncMock( - return_value=SimpleNamespace( - id="app-1", name="Example", package="com.example" - ) - ), + AsyncMock(return_value=App(AppIdentity("com.example"), "Example", "app-1")), ) for group, label in [("files", "app.apk"), ("apps", "Example")]: args = ["workspace", group, "upload", str(path)] diff --git a/tests/unit/cli/test_device_commands.py b/tests/unit/cli/test_device_commands.py index cc9ad041f..4fc5285e6 100644 --- a/tests/unit/cli/test_device_commands.py +++ b/tests/unit/cli/test_device_commands.py @@ -1,93 +1,67 @@ -"""Grouped CLI contract through real Click paths, with no device/cloud access.""" +"""Cross-group CLI contracts through a fake core connection owner.""" -import asyncio import importlib -import json -from contextlib import asynccontextmanager -from types import SimpleNamespace as NS -from unittest.mock import AsyncMock, Mock +from collections.abc import Awaitable, Callable +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import AsyncMock +import click import pytest from click.testing import CliRunner +from mobilerun_core import DeviceDescriptor from mobilerun.cli.app import cli +from mobilerun.cli.base import menu +from mobilerun.cli.base.prompts import SelectChoice +from mobilerun.cli.devices.base import device as device_base from mobilerun.cli.devices.base import selection from mobilerun.cli.devices.group import device -from mobilerun.models.billing import Billing +from mobilerun.cli.devices.utils.connection import device as connection +from mobilerun.cli.devices.utils.prompts import pickers +from mobilerun.config.loader import ConfigLoader +from mobilerun.config.migrations import CURRENT_VERSION +from mobilerun.config.user_config import MobileConfig +from mobilerun.models.results import ExecutionResult +from tests.support.devices import FakeDriver, fake_device from tests.support.macro import write_macro CLOUD_ID = "11111111-1111-1111-1111-111111111111" -@pytest.mark.parametrize( - "path,method,args,output", - [ - ( - ["app", "stop", "org.example"], - "stop_app", - ("org.example",), - "Stopped org.example", - ), - ( - ["app", "open", "https://example.com"], - "open_url", - ("https://example.com",), - "Opened https://example.com", - ), - ( - ["settings", "location", "set", "52.52", "13.405"], - "set_location", - (52.52, 13.405), - "Location set to 52.52, 13.405 on serial", - ), - ( - ["settings", "location", "reset"], - "reset_location", - (), - "Location reset on serial", - ), - (["settings", "language", "get"], "get_language", (), "de-DE"), - ( - ["settings", "language", "set", "de-DE"], - "set_language", - ("de-DE",), - "Language set to de-DE on serial", - ), - (["settings", "timezone", "get"], "get_timezone", (), "Europe/Berlin"), - ( - ["settings", "timezone", "set", "Europe/Berlin"], - "set_timezone", - ("Europe/Berlin",), - "Timezone set to Europe/Berlin on serial", - ), - ( - ["input", "clipboard", "set", "private text"], - "set_clipboard", - ("private text",), - f"Clipboard set on {CLOUD_ID}", - ), - ], -) -def test_grouped_operations_acknowledge_and_close( - monkeypatch, path, method, args, output -): - phone = NS(close=AsyncMock()) - result_value = ( - "de-DE" - if method == "get_language" - else "Europe/Berlin" if method == "get_timezone" else None +@pytest.fixture +def core(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace: + driver = FakeDriver(apps=[{"package": "org.example", "label": "Example"}]) + local = SimpleNamespace( + list_android_devices=AsyncMock(return_value=[]), ensure_portal_ready=AsyncMock() ) - operation = AsyncMock(return_value=result_value) - setattr(phone, method, operation) - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=phone)) - target = CLOUD_ID if method == "set_clipboard" else "serial" - result = CliRunner().invoke(device, [*path, "-d", target]) - assert result.exit_code == 0, (result.output, result.exception) - operation.assert_awaited_once_with(*args) - phone.close.assert_awaited_once() - assert output in result.stdout - if method == "set_clipboard": - assert "private text" not in result.output + closed = AsyncMock() + + class Factory: + def __init__( + self, + *, + base_url: str, + hitl_gate: Callable[..., Awaitable[bool]], + **kwargs: object, + ) -> None: + self.base_url = base_url + self.phone = fake_device(driver=driver, hitl_gate=hitl_gate) + self.local = local + self.connect = AsyncMock(return_value=self.phone) + owners.append(self) + + async def __aenter__(self) -> "Factory": + return self + + async def __aexit__(self, *exc: object) -> None: + await self.phone.aclose() + await closed() + + owners: list[Factory] = [] + monkeypatch.setattr(selection, "AsyncMobilerun", Factory) + monkeypatch.setattr(selection.LoginStore, "resolve_api_key", lambda self: None) + return SimpleNamespace(driver=driver, owners=owners, local=local, closed=closed) @pytest.mark.parametrize( @@ -97,179 +71,79 @@ def test_grouped_operations_acknowledge_and_close( ["screen", "ui"], ["app", "stop", "app.id"], ["settings", "language", "get"], - ["action", "list"], ], + ids=["input", "screen", "app", "settings"], ) -def test_conflicting_target_never_connects(monkeypatch, path): - connect = AsyncMock() - monkeypatch.setattr(selection, "connect_target", connect) +def test_conflicting_target_never_connects( + core: SimpleNamespace, path: list[str] +) -> None: result = CliRunner().invoke(device, [*path, "first", "-d", "second"]) assert result.exit_code == 2 assert "refer to different devices" in result.output - connect.assert_not_awaited() + assert core.owners == [] -def test_operation_failure_closes(monkeypatch): - phone = NS(close=AsyncMock(), stop_app=AsyncMock(side_effect=ValueError("bad app"))) - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=phone)) - result = CliRunner().invoke(device, ["app", "stop", "bad", "-d", "serial"]) - assert result.exit_code == 1 - phone.close.assert_awaited_once() - - -@pytest.mark.parametrize("suffix", [[], ["-h"], ["--help"]]) -def test_clipboard_bare_and_help_never_connect(monkeypatch, suffix): - connect = AsyncMock() - monkeypatch.setattr(selection, "connect_target", connect) +@pytest.mark.parametrize( + "suffix", [[], ["-h"], ["--help"]], ids=["bare", "short", "long"] +) +def test_clipboard_bare_and_help_never_connect( + core: SimpleNamespace, suffix: list[str] +) -> None: result = CliRunner().invoke(cli, ["device", "input", "clipboard", *suffix]) assert result.exit_code in {0, 2} - assert "get" in result.output and "set" in result.output - connect.assert_not_awaited() + assert {"get", "set"} <= set(result.output.split()) + assert core.owners == [] @pytest.mark.parametrize( "name", - [ - "install", - "uninstall", - "pull", - "push", - "files", - "rm", - "open", - "location", - "language", - "timezone", - "clipboard", - "actions", - "call", - "extensions", - ], + "install uninstall pull push files rm open location language timezone clipboard action actions call extensions".split(), ) -def test_branch_only_flat_paths_removed(name): +def test_branch_only_flat_paths_removed(name: str) -> None: result = CliRunner().invoke(device, [name, "--help"]) assert result.exit_code == 2 @pytest.mark.parametrize( - "path", - [["app"], ["file"], ["input"], ["screen"], ["settings"], ["action"], ["cloud"]], + "name", ["app", "file", "input", "screen", "settings", "cloud"] ) -def test_group_packages_match_tree(path): - module = importlib.import_module("mobilerun.cli.devices." + path[0]) - assert module.__file__.endswith("/__init__.py") - result = CliRunner().invoke(device, [*path, "--help"]) - assert result.exit_code == 0 - +def test_group_packages_match_tree(name: str) -> None: + module = importlib.import_module(f"mobilerun.cli.devices.{name}") + assert module.__file__ is not None + assert Path(module.__file__).name == "__init__.py" + assert CliRunner().invoke(device, [name, "--help"]).exit_code == 0 -def test_every_device_command_module_matches_its_path(): - import click - def visit(group, path): +def test_every_device_command_module_matches_its_path() -> None: + def visit(group: click.Group, path: str) -> None: for name, command in group.commands.items(): if command.hidden: continue expected = path + "." + name.replace("-", "_") + assert command.callback is not None assert command.callback.__module__ == expected if isinstance(command, click.Group): module = importlib.import_module(expected) - assert module.__file__.endswith("/__init__.py") + assert module.__file__ is not None + assert Path(module.__file__).name == "__init__.py" visit(command, expected) visit(device, "mobilerun.cli.devices") -@pytest.mark.parametrize("operation", ["status", "stop", "reboot", "terminate"]) -def test_cloud_lifecycle_uses_sdk_boundary_without_phone_connect( - monkeypatch, operation -): - module = importlib.import_module(f"mobilerun.cli.devices.cloud.{operation}") - connect = AsyncMock(side_effect=AssertionError("must not open a phone")) - monkeypatch.setattr(selection, "connect_target", connect) - boundary = AsyncMock( - return_value=NS(state="stopped", model_dump_json=lambda: '{"state":"stopped"}') - ) - monkeypatch.setattr( - module.devices, "retrieve" if operation == "status" else operation, boundary - ) - fake_client = object() - seen = [] - - @asynccontextmanager - async def client(**kwargs): - seen.append(kwargs) - yield fake_client - seen.append("closed") - - monkeypatch.setattr(module, "cloud_client", client) - monkeypatch.setattr( - module, "get_settings", lambda: NS(MOBILERUN_BILLING=Billing.NO_COMMERCE) - ) - args = ["cloud", operation, "-d", CLOUD_ID, "--base-url", "https://example.invalid"] - if operation in {"terminate", "reboot"}: - refused = CliRunner().invoke(device, args) - assert refused.exit_code == 1 - boundary.assert_not_awaited() - assert not seen - args.append("--yes") - result = CliRunner().invoke(device, args) - assert result.exit_code == 0, (result.output, result.exception) - boundary.assert_awaited_once_with( - CLOUD_ID, billing=Billing.NO_COMMERCE, client=fake_client - ) - assert seen == [ - {"base_url": "https://example.invalid", "billing": Billing.NO_COMMERCE}, - "closed", - ] - connect.assert_not_awaited() - - -@pytest.mark.parametrize( - "operation", ["status", "resume", "stop", "reboot", "terminate"] -) -def test_cloud_lifecycle_rejects_local_before_client(monkeypatch, operation): - module = importlib.import_module(f"mobilerun.cli.devices.cloud.{operation}") - monkeypatch.setattr( - module, "cloud_client", lambda **kwargs: pytest.fail("must not call cloud") - ) - result = CliRunner().invoke(device, ["cloud", operation, "-d", "serial"]) - assert result.exit_code == 2 - assert "requires a cloud device ID" in result.output - - -def test_action_list_json(monkeypatch): - from mobilerun.core.devices.base import Device - - phone = Device() - phone.close = AsyncMock() - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=phone)) - result = CliRunner().invoke(device, ["action", "list", "--json", "-d", "serial"]) - assert result.exit_code == 0, result.output - assert any(entry["name"] == "device.wait" for entry in json.loads(result.stdout)) - phone.close.assert_awaited_once() - - @pytest.mark.parametrize("operation", ["start", "stop", "uninstall"]) -def test_installed_app_picker(monkeypatch, operation): - from mobilerun.cli.devices.base import pickers - - phone = NS( - close=AsyncMock(), - list_apps=AsyncMock( - return_value=[{"package": "org.example", "label": "Example"}] - ), - ) - method = AsyncMock() - setattr(phone, operation + "_app", method) - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=phone)) +def test_installed_app_picker( + core: SimpleNamespace, monkeypatch: pytest.MonkeyPatch, operation: str +) -> None: monkeypatch.setattr(pickers, "is_interactive", lambda: True) - seen = [] + monkeypatch.setattr(menu, "is_interactive", lambda: True) + seen: list[SelectChoice] = [] - def pick(label, choices): + async def pick(label: str, choices: list[SelectChoice]) -> str: seen.extend(choices) return "org.example" - monkeypatch.setattr(pickers, "select_prompt_async", AsyncMock(side_effect=pick)) + monkeypatch.setattr(pickers, "select_prompt_async", pick) args = ["app", operation, "-d", "serial"] if operation == "uninstall": args.append("--yes") @@ -277,311 +151,107 @@ def pick(label, choices): assert result.exit_code == 0, (result.output, result.exception) assert seen[0].label == "Example" assert seen[-1].value == "__manual__" - method.assert_awaited_once_with("org.example") - phone.close.assert_awaited_once() - - -def test_language_timezone_getters_and_wrappers(): - from mobilerun.clients.cloud import devices - from mobilerun.core.devices.base import Device - from mobilerun.core.devices.cloud import CloudDevice - from mobilerun.core.devices.components.wrapper import DeviceWrapper - from mobilerun.core.devices.pool import DevicePool - from mobilerun.errors import DeviceOperationNotSupported - - async def run(): - client = NS( - devices=NS( - language=NS(get=AsyncMock(return_value=NS(locale="de-DE"))), - timezone=NS(get=AsyncMock(return_value=NS(timezone="Europe/Berlin"))), - ) - ) - phone = CloudDevice(CLOUD_ID, api_key="test") - owned = phone._owned_client - phone._client = client - try: - assert ( - await devices.get_language( - CLOUD_ID, billing=Billing.NO_COMMERCE, client=client - ) - ).locale == "de-DE" - assert ( - await devices.get_timezone( - CLOUD_ID, billing=Billing.NO_COMMERCE, client=client - ) - ).timezone == "Europe/Berlin" - assert await phone.get_language() == "de-DE" - assert await phone.get_timezone() == "Europe/Berlin" - pool = DevicePool([DeviceWrapper(phone)]) - assert await pool.get_language() == ["de-DE"] - assert await pool.get_timezone() == ["Europe/Berlin"] - for name in ("get_language", "get_timezone"): - with pytest.raises(DeviceOperationNotSupported, match=name): - await getattr(Device(), name)() - finally: - await owned.close() - - asyncio.run(run()) - - -def test_cloud_picker_only_fetches_cloud_choices(monkeypatch): - from mobilerun.cli.base import choices - from mobilerun.cli.base.prompts import SelectChoice - from mobilerun.cli.devices.base import options, pickers - - module = importlib.import_module("mobilerun.cli.devices.cloud.status") - monkeypatch.setattr(options, "is_interactive", lambda: True) - monkeypatch.setattr(pickers, "is_interactive", lambda: True) - monkeypatch.setattr( - options, - "discover_devices", - AsyncMock(side_effect=AssertionError("no local discovery")), - ) - monkeypatch.setattr( - choices, "cloud_devices", lambda ctx: [SelectChoice(CLOUD_ID, "Stopped phone")] - ) - monkeypatch.setattr( - pickers, "select_prompt", lambda label, entries: entries[0].value - ) - monkeypatch.setattr( - module.devices, "retrieve", AsyncMock(return_value=NS(state="stopped")) - ) - - @asynccontextmanager - async def client(**kwargs): - yield object() - - monkeypatch.setattr(module, "cloud_client", client) - result = CliRunner().invoke(device, ["cloud", "status"]) - assert result.exit_code == 0, (result.output, result.exception) - assert CLOUD_ID in result.stdout - - -def test_file_transfer_progress_is_only_stderr(monkeypatch, tmp_path): - phone = NS( - close=AsyncMock(), - push_file=AsyncMock(return_value=NS(path="/sdcard/file")), - pull_file=AsyncMock(return_value=tmp_path / "out"), - ) - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=phone)) - local = tmp_path / "in" - local.write_text("file") - push = CliRunner().invoke(device, ["file", "push", str(local), "-d", "serial"]) - assert push.exit_code == 0, (push.output, push.exception) - assert push.stdout == "/sdcard/file\n" - assert "Pushing to serial" in push.stderr - pull = CliRunner().invoke(device, ["file", "pull", "/sdcard/file", "-d", "serial"]) - assert pull.exit_code == 0, (pull.output, pull.exception) - assert pull.stdout == f"{tmp_path / 'out'}\n" - assert "Pulling from serial" in pull.stderr - - -def test_failed_connect_closes_constructed_device(monkeypatch): - phone = NS( - connect=AsyncMock(side_effect=RuntimeError("offline")), close=AsyncMock() - ) - monkeypatch.setattr(selection, "AndroidDevice", lambda **kwargs: phone) - result = CliRunner().invoke(device, ["input", "tap", "1", "2", "-d", "serial"]) - assert result.exit_code == 1 - phone.close.assert_awaited_once() + assert core.driver.calls == [ + ("get_apps", (), {"include_system": False}), + ( + f"{operation}_app", + ("org.example",), + {"activity": None} if operation == "start" else {}, + ), + ] + core.closed.assert_awaited_once() @pytest.mark.parametrize("flag", ["--device", "-d"]) -def test_agent_run_device_option_reaches_runner(monkeypatch, flag): +def test_agent_run_device_option_reaches_runner( + monkeypatch: pytest.MonkeyPatch, core: SimpleNamespace, flag: str +) -> None: pytest.importorskip("mobilerun_agents", reason="requires mobilerun-agents add-on") module = importlib.import_module("mobilerun_agents.cli.agent.run") - phone = NS(close=AsyncMock()) - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=phone)) - execute = AsyncMock(return_value=NS(answer="done", success=True)) - monkeypatch.setattr(module, "AgentOperator", lambda **kwargs: NS(execute=execute)) - monkeypatch.setattr(module.ConfigLoader, "load", lambda _: NS()) + execute = AsyncMock(return_value=ExecutionResult(success=True, device="serial")) + monkeypatch.setattr(module, "load_config", SimpleNamespace) + monkeypatch.setattr(module, "configure_cli_logging", lambda **kwargs: None) + monkeypatch.setattr( + module, + "build_setup", + AsyncMock(return_value=SimpleNamespace(planner=None, selector=None)), + ) + monkeypatch.setattr( + module, "AgentOperator", lambda **kwargs: SimpleNamespace(execute=execute) + ) result = CliRunner().invoke(cli, ["agent", "run", "Open settings", flag, "serial"]) assert result.exit_code == 0, (result.output, result.exception) - execute.assert_awaited_once_with(phone, "Open settings", max_steps=None) - assert selection.connect_target.await_args.args == ("serial",) - assert selection.connect_target.await_args.kwargs["allow_auto_setup"] is True - phone.close.assert_awaited_once() + (owner,) = core.owners + owner.connect.assert_awaited_once_with( + "serial", backend="local-android-adb", use_tcp=False, portal_mode="auto" + ) + assert core.local.ensure_portal_ready.await_args.args == ("serial",) + execute.assert_awaited_once_with(owner.phone, "Open settings", max_steps=None) + core.closed.assert_awaited_once() @pytest.mark.parametrize("flag", ["--device", "-d"]) -def test_agent_replay_device_option_reaches_replay(monkeypatch, tmp_path, flag): +def test_agent_replay_device_option_reaches_replay( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, flag: str +) -> None: pytest.importorskip("mobilerun_agents", reason="requires mobilerun-agents add-on") module = importlib.import_module("mobilerun_agents.cli.macro_agent.replay") - monkeypatch.setattr(module.ConfigLoader, "load", lambda _: NS()) - received = [] - monkeypatch.setattr( - module, "run_replay", lambda operator, **kwargs: received.append(kwargs) - ) - path = write_macro(tmp_path) - result = CliRunner().invoke( - cli, ["macro-agent", "replay", str(path), flag, "serial"] - ) - assert result.exit_code == 0, (result.output, result.exception) - assert received[0]["target"].identifier == "serial" - assert received[0]["target"].kind == "android" - assert received[0]["target"].allow_auto_setup is True + monkeypatch.setattr(module, "load_config", SimpleNamespace) + # This callback is synchronous; keep the async replay/LLM path uncalled. + received: list[str | None] = [] + def intercept(operator: object, *, target: str | None, **kwargs: object) -> None: + received.append(target) -def test_action_picker_keeps_manual_entry(monkeypatch): - from mobilerun.cli.devices.base import pickers - from mobilerun.core.devices.base import Device - - module = importlib.import_module("mobilerun.cli.devices.action.call") - phone = Device() - phone.close = AsyncMock() - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=phone)) - monkeypatch.setattr(module, "is_interactive", lambda: True) - monkeypatch.setattr(pickers, "is_interactive", lambda: True) - seen = [] - - def pick(label, choices): - seen.extend(choice.value for choice in choices) - return "__manual__" - - monkeypatch.setattr(pickers, "select_prompt_async", AsyncMock(side_effect=pick)) - monkeypatch.setattr( - pickers, "text_prompt_async", AsyncMock(return_value="device.wait") - ) + monkeypatch.setattr(module, "run_replay", intercept) + path = write_macro(tmp_path) result = CliRunner().invoke( - device, ["action", "call", "--arg", "seconds=0", "-d", "serial"] + cli, ["macro-agent", "replay", str(path), flag, "serial"] ) assert result.exit_code == 0, (result.output, result.exception) - assert {"device.wait", "__manual__"} <= set(seen) - phone.close.assert_awaited_once() + assert received == ["serial"] -def test_macro_dry_run_keeps_transport_flags_without_device(monkeypatch, tmp_path): - from mobilerun.cli.devices.base import options - - monkeypatch.setattr( - options, - "discover_devices", - AsyncMock(side_effect=AssertionError("must not discover")), - ) - connect = AsyncMock(side_effect=AssertionError("must not connect")) - monkeypatch.setattr(selection, "connect_target", connect) +def test_macro_dry_run_keeps_transport_flags_without_device( + tmp_path: Path, core: SimpleNamespace +) -> None: path = write_macro(tmp_path) result = CliRunner().invoke( cli, ["macro", "replay", str(path), "--dry-run", "--android", "--tcp"] ) assert result.exit_code == 0, (result.output, result.exception) - connect.assert_not_awaited() + assert core.owners == [] -def test_device_help_lists_lifecycle_and_actions(): +def test_device_help_lists_lifecycle_and_action_groups() -> None: result = CliRunner().invoke(device, ["--help"]) assert result.exit_code == 0 - for command in ( - "list", - "connect", - "disconnect", - "ping", - "setup", - "input", - "app", - "screen", - "file", - "settings", - "action", - "cloud", - ): - assert command in result.output - - -def test_device_discovery_failure_and_exclusive_flags(monkeypatch): - from mobilerun.cli.devices.base import options - - monkeypatch.setattr(options, "discover_devices", AsyncMock(return_value=[])) - runner = CliRunner() - expected = "No devices found." - missing = runner.invoke(device, ["input", "tap", "1", "1"]) - assert missing.exit_code == 1 - assert expected in missing.output - multiple = runner.invoke( - device, ["input", "tap", "1", "1", "target", "--android", "--ios"] + words = set(result.output.split()) + assert ( + set( + "list connect disconnect ping setup input app screen file settings cloud".split() + ) + <= words ) - assert multiple.exit_code == 2 - assert "Choose at most one device type flag" in multiple.output -@pytest.mark.parametrize( - ("args", "method", "positional", "keyword"), - [ - (["input", "tap", "10", "20"], "tap", (10, 20), {}), - ( - ["input", "long-press", "1", "2"], - "swipe", - (1, 2, 1, 2, 1000), - {}, - ), - ( - ["input", "swipe", "1", "2", "3", "4", "--duration", "0.5"], - "swipe", - (1, 2, 3, 4), - {"duration_ms": 500}, - ), - ( - ["input", "type", "hello", "--clear"], - "input_text", - ("hello", True), - {}, - ), - (["input", "press", "home"], "press_button", ("home",), {}), - (["app", "start", "example.app"], "start_app", ("example.app",), {}), - ( - ["app", "list", "--system"], - "list_apps", - (), - {"include_system": True}, - ), - (["screen", "screenshot"], "screenshot", (), {}), - ], - ids=["tap", "long-press", "swipe", "type", "press", "start", "apps", "screenshot"], -) -def test_action_commands_call_expected_driver_methods( - monkeypatch, tmp_path, args, method, positional, keyword -): - module = importlib.import_module( - f"mobilerun.cli.devices.{args[0]}.{args[1].replace('-', '_')}" - ) - driver = AsyncMock() - driver.list_apps.return_value = [] - driver.screenshot.return_value = b"png" - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=driver)) - if method == "screenshot": - monkeypatch.setattr(module.tempfile, "tempdir", str(tmp_path)) - result = CliRunner().invoke(device, [*args, "serial", "--android"]) - assert result.exit_code == 0, (args, result.output, result.exception) - getattr(driver, method).assert_awaited_once_with(*positional, **keyword) - driver.close.assert_awaited_once_with() - - -def test_ui_prints_formatted_state(monkeypatch): - ui = importlib.import_module("mobilerun.cli.devices.screen.ui") - - driver = AsyncMock() - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=driver)) - - monkeypatch.setattr(ui, "log_progress_to_stderr", lambda: None) - provider = NS( - get_state=AsyncMock(return_value=NS(formatted_text="tree", phone_state=None)) +def test_device_rejects_exclusive_flags(core: SimpleNamespace) -> None: + result = CliRunner().invoke( + device, ["input", "tap", "1", "1", "target", "--android", "--ios"] ) - driver._create_state_provider = lambda options: provider - result = CliRunner().invoke(device, ["screen", "ui", "serial", "--android"]) - assert result.exit_code == 0, result.output - assert result.stdout == " tree\n" - + assert result.exit_code == 2 + assert "Choose at most one device type flag" in result.output + assert core.owners == [] -def test_tap_config_is_passed_to_factory_and_flags_override(monkeypatch, tmp_path): - from mobilerun.config.migrations import CURRENT_VERSION +def test_tap_passes_adb_transport_from_config( + core: SimpleNamespace, tmp_path: Path +) -> None: config = tmp_path / "device.yaml" config.write_text( - f"_version: {CURRENT_VERSION}\ndevice:\n use_tcp: true\n platform: ios\n auth_token: example\n portal_mode: disabled\n auto_setup: false\n" + f"_version: {CURRENT_VERSION}\ndevice:\n use_tcp: true\n platform: ios\n" + " auth_token: example\n portal_mode: disabled\n auto_setup: false\n" ) - factory = AsyncMock(return_value=AsyncMock()) - monkeypatch.setattr(selection, "connect_target", factory) - result = CliRunner().invoke( device, [ @@ -593,129 +263,121 @@ def test_tap_config_is_passed_to_factory_and_flags_override(monkeypatch, tmp_pat "--config", str(config), "--android", - "--no-tcp", ], ) assert result.exit_code == 0, (result.output, result.exception) - args = factory.await_args.kwargs - assert args["kind"] == "android" - assert args["tcp"] is False - assert args["config"].device.auth_token == "example" - assert args["config"].device.portal_mode == "disabled" - assert args["config"].device.auto_setup is False - + (owner,) = core.owners + owner.connect.assert_awaited_once_with( + "serial", backend="local-android-adb", use_tcp=True, portal_mode="disabled" + ) + core.local.ensure_portal_ready.assert_not_awaited() -def test_tap_loads_default_config_and_uses_tcp(monkeypatch): - from mobilerun.config.loader import ConfigLoader - from mobilerun.config.user_config import MobileConfig +def test_tap_loads_default_config_and_uses_tcp( + monkeypatch: pytest.MonkeyPatch, core: SimpleNamespace +) -> None: config = MobileConfig() config.device.use_tcp = True - paths = [] - monkeypatch.setattr(ConfigLoader, "load", lambda path: paths.append(path) or config) - factory = AsyncMock(return_value=AsyncMock()) - monkeypatch.setattr(selection, "connect_target", factory) - - result = CliRunner().invoke(device, ["input", "tap", "1", "2", "serial"]) - assert result.exit_code == 0, (result.output, result.exception) - assert paths == [None] - assert factory.await_args.kwargs["tcp"] is True - assert factory.await_args.kwargs["allow_auto_setup"] is False + paths: list[str | None] = [] + def load_default(path: str | None) -> MobileConfig: + paths.append(path) + return config -def test_tap_config_platform_is_used_for_url(monkeypatch, tmp_path): - from mobilerun.config.migrations import CURRENT_VERSION - - config = tmp_path / "device.yaml" - config.write_text(f"_version: {CURRENT_VERSION}\ndevice:\n platform: ios\n") - factory = AsyncMock(return_value=AsyncMock()) - monkeypatch.setattr(selection, "connect_target", factory) - + monkeypatch.setattr(ConfigLoader, "load", load_default) result = CliRunner().invoke( - device, ["input", "tap", "1", "2", "http://phone", "--config", str(config)] + device, ["input", "tap", "1", "2", "serial", "--android"] ) assert result.exit_code == 0, (result.output, result.exception) - assert factory.await_args.kwargs["kind"] == "ios" - - -def test_device_discovery_and_default_resolution(monkeypatch, tmp_path): - from mobilerun.clients.portal import discovery - from mobilerun.config.migrations import CURRENT_VERSION - - monkeypatch.setattr( - discovery.adb, - "list", - AsyncMock(return_value=[NS(serial="emulator", state="device")]), + assert paths == [None] + (owner,) = core.owners + owner.connect.assert_awaited_once_with( + "serial", backend="local-android-adb", use_tcp=True, portal_mode="auto" ) - factory = AsyncMock(return_value=AsyncMock()) - monkeypatch.setattr(selection, "connect_target", factory) + core.local.ensure_portal_ready.assert_not_awaited() - runner = CliRunner() - result = runner.invoke(device, ["input", "tap", "1", "2"]) - assert result.exit_code == 0, (result.output, result.exception) - assert factory.await_args.args[0] == "emulator" - assert "Using emulator" in result.stderr - monkeypatch.setenv("MOBILERUN_DEFAULT_DEVICE", "default") - result = runner.invoke(device, ["input", "tap", "1", "2"]) - assert result.exit_code == 0, result.output - assert factory.await_args.args[0] == "emulator" - monkeypatch.setattr( - discovery.adb, - "list", - AsyncMock(return_value=[NS(serial="configured", state="device")]), - ) + +@pytest.mark.parametrize("platform", ["ios", "android"]) +def test_tap_passes_portal_url_and_platform_token( + core: SimpleNamespace, tmp_path: Path, platform: str +) -> None: config = tmp_path / "device.yaml" - config.write_text(f"_version: {CURRENT_VERSION}\ndevice:\n serial: configured\n") - result = runner.invoke(device, ["input", "tap", "1", "2", "--config", str(config)]) - assert result.exit_code == 0, result.output - assert factory.await_args.args[0] == "configured" - result = runner.invoke( - device, ["input", "tap", "1", "2", "explicit", "--config", str(config)] + config.write_text( + f"_version: {CURRENT_VERSION}\ndevice:\n platform: {platform}\n auth_token: test-token\n" ) - assert result.exit_code == 0, result.output - assert factory.await_args.args[0] == "explicit" - assert "Using device:" not in result.stderr - - -def test_device_validates_saved_serial_against_discovery(monkeypatch): - from mobilerun.cli.devices.base import options - - config = options.ConfigLoader.load(None) - config.device.serial = "saved" - monkeypatch.setattr(options.ConfigLoader, "load", lambda path: config) - from mobilerun.cli.devices.base.discovery import DiscoveredDevice - - discovery = AsyncMock( - return_value=[DiscoveredDevice("saved", "local", None, "device", None)] + result = CliRunner().invoke( + device, + [ + "input", + "tap", + "1", + "2", + "http://phone", + "--config", + str(config), + f"--{platform}", + ], ) - monkeypatch.setattr(options, "discover_devices", discovery) - factory = AsyncMock(return_value=AsyncMock()) - monkeypatch.setattr(selection, "connect_target", factory) - - result = CliRunner().invoke(device, ["input", "tap", "1", "2"]) - assert result.exit_code == 0, result.output - assert factory.await_args.args[0] == "saved" - discovery.assert_awaited_once() - + assert result.exit_code == 0, (result.output, result.exception) + (owner,) = core.owners + owner.connect.assert_awaited_once_with( + backend=f"local-{platform}-http", url="http://phone", token="test-token" + ) + core.local.ensure_portal_ready.assert_not_awaited() + + +@pytest.mark.parametrize("backend", ["cloud", "visual-remote"]) +def test_tap_forwards_cloud_and_visual_remote_connection_options( + core: SimpleNamespace, tmp_path: Path, backend: str +) -> None: + if backend == "cloud": + args = [CLOUD_ID, "--base-url", "https://cloud.test"] + else: + config = tmp_path / "device.yaml" + config.write_text( + f"_version: {CURRENT_VERSION}\ndevice:\n device_id: remote-id\n" + ) + args = ["http://remote", "--remote", "--config", str(config)] + result = CliRunner().invoke(device, ["input", "tap", "1", "2", *args]) + assert result.exit_code == 0, (result.output, result.exception) + (owner,) = core.owners + if backend == "cloud": + assert owner.base_url == "https://cloud.test" + owner.connect.assert_awaited_once_with(CLOUD_ID, backend=None) + else: + owner.connect.assert_awaited_once_with( + "remote-id", backend="visual-remote", url="http://remote" + ) -def test_multiple_devices_noninteractive_error(monkeypatch): - from mobilerun.cli.devices.base import options - from mobilerun.cli.devices.base.discovery import DiscoveredDevice +def test_autoselection_ignores_obsolete_device_environment_variable( + monkeypatch: pytest.MonkeyPatch, core: SimpleNamespace +) -> None: monkeypatch.setattr( - options, + connection, "discover_devices", AsyncMock( return_value=[ - DiscoveredDevice("a", "local", None, "device", None), - DiscoveredDevice("b", "cloud", None, "ready", "android"), + DeviceDescriptor("emulator", "local-android-adb", state="device") ] ), ) + monkeypatch.setenv("MOBILERUN_DEFAULT_DEVICE", "obsolete") + monkeypatch.setattr(device_base, "is_interactive", lambda: True) + result = CliRunner().invoke(device, ["input", "tap", "1", "2"]) + assert result.exit_code == 0, (result.output, result.exception) + assert "Using emulator" in result.stderr + (owner,) = core.owners + assert owner.connect.await_args.args == ("emulator",) + + +def test_missing_device_noninteractive_errors_before_discovery( + core: SimpleNamespace, +) -> None: result = CliRunner().invoke(device, ["input", "tap", "1", "2"]) - assert result.exit_code == 1, (result.output, result.exception) - assert "a (local)" in result.output - assert "b (cloud)" in result.output + assert result.exit_code == 2, result.output + assert "Pass DEVICE or --device" in result.stderr + assert core.owners == [] @pytest.mark.parametrize( @@ -725,135 +387,17 @@ def test_multiple_devices_noninteractive_error(monkeypatch): ("192.168.1.20:5555", "android"), ("emulator-5554", "android"), ("123e4567-e89b-12d3-a456-426614174000", "cloud"), + ("http://127.0.0.1:8000", "http"), + ("HTTPS://example.test:8000", "http"), ], ) -def test_detect_device_kind(target, expected): - from mobilerun.cli.devices.base.selection import detect_device_kind - - assert detect_device_kind(target) == expected - - -def test_detect_device_kind_rejects_ambiguous_http_url(): - from mobilerun.cli.devices.base.selection import detect_device_kind - - with pytest.raises(ValueError, match="URL target: add -i/--ios"): - detect_device_kind("http://127.0.0.1:8000") - - -def test_connect_target_builds_android_and_closes_android_only(monkeypatch): - made = [] - - class FakeAndroid: - device = None - - def __init__(self, **kwargs): - self.kwargs = kwargs - made.append(self) - - async def connect(self): - pass - - monkeypatch.setattr(selection, "AndroidDevice", FakeAndroid) - device = asyncio.run(selection.connect_target("serial", tcp=True)) - assert isinstance(device, FakeAndroid) - assert made[0].kwargs == {"serial": "serial", "use_tcp": True} - - -def test_create_android_url_uses_portal_http_driver(monkeypatch): - class FakeDriver: - async def connect(self): - pass +def test_classify_target(target: str, expected: str) -> None: + from mobilerun.cli.devices.utils.targets import classify_target - driver = FakeDriver() + assert classify_target(target) == expected - def make_driver(url, token): - return driver - monkeypatch.setattr(selection, "create_android_portal_http_driver", make_driver) - monkeypatch.setattr( - selection.ConfigLoader, - "load", - lambda _: type( - "C", - (), - { - "device": type( - "D", (), {"resolve_auth_token": lambda self, platform: "token"} - )() - }, - )(), - ) - monkeypatch.setattr( - selection, "AndroidDevice", lambda **kwargs: pytest.fail("ADB used") - ) - - result = asyncio.run(selection.connect_target("http://portal.test", kind="android")) - from typing import cast - - from mobilerun.core.devices.components.wrapper import DriverDevice - - assert cast(DriverDevice, result)._driver is driver - from mobilerun.core.state.android import AndroidStateProvider - from mobilerun.core.state.options import StateProviderOptions - - assert isinstance( - result._create_state_provider(StateProviderOptions()), AndroidStateProvider - ) - - -def test_connect_target_passes_android_configuration(monkeypatch): - driver = NS(connect=AsyncMock()) - - def constructor(**kwargs): - seen.update(kwargs) - return driver - - seen = {} - monkeypatch.setattr(selection, "AndroidDevice", constructor) - config = NS(device=NS(auto_setup=False, portal_mode="disabled")) - assert ( - asyncio.run(selection.connect_target("serial", tcp=True, config=config)) - is driver - ) - assert seen == {"serial": "serial", "use_tcp": True, "portal_mode": "disabled"} - driver.connect.assert_awaited_once() - - -def test_connect_target_constructs_cloud_and_visual_remote(monkeypatch): - from mobilerun.core.devices import cloud +def test_display_label_without_device_id() -> None: + from mobilerun.cli.devices.utils.labels import display_label - driver = NS(connect=AsyncMock()) - constructor = Mock(return_value=driver) - monkeypatch.setattr(cloud, "CloudDevice", constructor) - assert ( - asyncio.run( - selection.connect_target("id", kind="cloud", base_url="https://cloud") - ) - is driver - ) - constructor.assert_called_once_with(device_id="id", base_url="https://cloud") - constructor = Mock(return_value=driver) - monkeypatch.setattr(selection, "RemoteDevice", constructor) - config = NS(device=NS(device_id="remote-id")) - assert ( - asyncio.run( - selection.connect_target( - "http://remote", kind="visual_remote", config=config - ) - ) - is driver - ) - constructor.assert_called_once_with(url="http://remote", device_id="remote-id") - - -def test_connect_target_constructs_ios_with_token(monkeypatch): - driver = NS(connect=AsyncMock()) - create = Mock(return_value=driver) - monkeypatch.setattr(selection, "IOSDevice", create) - config = NS(device=NS(resolve_auth_token=lambda platform: "token")) - result = asyncio.run( - selection.connect_target("http://ios", kind="ios", config=config) - ) - assert result is driver - create.assert_called_once_with("http://ios", token="token") - driver.connect.assert_awaited_once() + assert display_label(None) == "unknown device" diff --git a/tests/unit/cli/test_device_selection.py b/tests/unit/cli/test_device_selection.py index d4177e376..c71ae0368 100644 --- a/tests/unit/cli/test_device_selection.py +++ b/tests/unit/cli/test_device_selection.py @@ -1,283 +1,47 @@ -"""Device discovery, CLI target selection, and saved configuration guards.""" +"""Discovery and transport selection through Click and a fake core owner.""" import asyncio import json from types import SimpleNamespace -from unittest.mock import AsyncMock, Mock +from unittest.mock import AsyncMock -import click import pytest from click.testing import CliRunner +from mobilerun_core import ( + DeviceDescriptor, + DeviceDisconnectedError, + UnsupportedOperation, +) -from mobilerun.cli.base import menu from mobilerun.cli.devices import device -from mobilerun.cli.devices import list as listing -from mobilerun.cli.devices.base import discovery, options, selection -from mobilerun.cli.devices.base.discovery import DiscoveredDevice -from mobilerun.clients.local import login_store -from mobilerun.config.loader import ConfigLoader, OutdatedConfigError +from mobilerun.cli.devices.base import selection +from mobilerun.cli.devices.utils.connection import discovery +from mobilerun.clients.local.login_store import LoginStore +from mobilerun.config.loader import ConfigLoader from mobilerun.config.user_config import MobileConfig +from tests.support.devices import FakeDriver, fake_device -@click.command() -@options.device_options -def echo_target(target, **kwargs): - click.echo(target) - - -def test_device_options_expose_positional_target_and_type_flags(): - result = CliRunner().invoke(echo_target, ["--help"]) - assert result.exit_code == 0 - assert "--cloud" in result.output - assert "DEVICE" in result.output - assert "-a, --android" in result.output - assert "-i, --ios" in result.output - assert "-v, --remote" in result.output - assert "-c, --cloud" in result.output - - -def test_device_type_flags_force_detected_kind_and_reject_multiple(): - from mobilerun.cli.devices.base.options import selected_device_kind - - assert ( - selected_device_kind("http://phone", False, True, False, False, None, None) - == "ios" - ) - assert ( - selected_device_kind("not-a-uuid", False, False, True, False, None, None) - == "cloud" - ) - assert ( - selected_device_kind("serial", True, False, False, False, None, None) - == "android" - ) - assert ( - selected_device_kind("http://remote", False, False, False, True, None, None) - == "visual_remote" - ) - with pytest.raises(click.UsageError, match="at most one"): - selected_device_kind("serial", True, True, False, False, None, None) - - -def test_device_target_precedence(monkeypatch, tmp_path): - config = SimpleNamespace(device=SimpleNamespace(serial="saved")) - monkeypatch.setattr(options.ConfigLoader, "load", lambda path: config) - - monkeypatch.setattr( - options, - "discover_devices", - AsyncMock( - return_value=[ - DiscoveredDevice("discovered", "local", None, "device", None), - DiscoveredDevice("saved", "local", None, "device", None), - ] - ), - ) - monkeypatch.setenv("MOBILERUN_DEFAULT_DEVICE", "environment") - - def command(target, **kwargs): - click.echo(target) - - command.__module__ = "mobilerun.cli.devices.test" - command = click.command()(options.device_options(command)) - runner = CliRunner() - explicit_config = tmp_path / "config.yaml" - explicit_config.touch() - assert ( - "explicit" - in runner.invoke(command, ["explicit", "--config", str(explicit_config)]).output - ) - assert "saved" in runner.invoke(command, ["--config", str(explicit_config)]).output - assert "saved" in runner.invoke(command, []).output - monkeypatch.delenv("MOBILERUN_DEFAULT_DEVICE") - assert "saved" in runner.invoke(command, []).output - config.device.serial = None - monkeypatch.setattr( - options, - "discover_devices", - AsyncMock( - return_value=[DiscoveredDevice("discovered", "local", None, "device", None)] - ), - ) - assert "discovered" in runner.invoke(command, []).output - - -def test_discovery_local_and_cloud(monkeypatch): - async def local(): - return [SimpleNamespace(serial="usb-1", state="device")] - - async def cloud(**kwargs): - return [ - SimpleNamespace(id="cloud-1", name="Phone", state="stopped", type="android") - ] - - monkeypatch.setattr(discovery.adb, "list", local) - monkeypatch.setattr(discovery, "resolve_cloud_api_key", lambda: "key") - monkeypatch.setattr(discovery, "list_devices", cloud) - devices = asyncio.run(discovery.discover_devices()) - assert [(d.id, d.source, d.ready) for d in devices] == [ - ("usb-1", "local", True), - ("cloud-1", "cloud", False), - ] - - -@pytest.mark.parametrize("interactive", [True, False]) -@pytest.mark.parametrize("count", [0, 1, 2]) -def test_selection_count(monkeypatch, interactive, count): - devices = [ - DiscoveredDevice(str(i), "local", None, "device", None) for i in range(count) - ] - - async def discover(**kwargs): - return devices - - monkeypatch.setattr(options, "discover_devices", discover) - monkeypatch.setattr(options, "is_interactive", lambda: interactive) - monkeypatch.setattr(options, "select_prompt", lambda *args: "1") - monkeypatch.setattr(options, "confirm_prompt", lambda *args, **kwargs: False) - monkeypatch.setattr( - options.ConfigLoader, - "load", - lambda path: SimpleNamespace(device=SimpleNamespace(serial=None)), - ) - - result = CliRunner().invoke(echo_target, []) - if count == 0: - assert result.exit_code == 1 - assert "No devices found." in result.output - elif count == 1: - assert result.exit_code == 0 - assert result.stdout == "0\n" - assert "Using 0" in result.stderr - elif interactive: - assert result.exit_code == 0 - assert result.stdout == "1\n" - else: - assert result.exit_code == 1 - assert "0 (local)" in result.output and "1 (local)" in result.output - - -def test_missing_key_skips_cloud(monkeypatch): - monkeypatch.setattr(discovery, "resolve_cloud_api_key", lambda: None) - assert asyncio.run(discovery.discover_devices(local=False)) == [] - - -def test_cloud_error_warns_and_returns_local(monkeypatch, capsys): - async def local(): - return [SimpleNamespace(serial="usb", state="device")] - - async def cloud(**kwargs): - raise RuntimeError("offline") - - monkeypatch.setattr(discovery.adb, "list", local) - monkeypatch.setattr(discovery, "resolve_cloud_api_key", lambda: "key") - monkeypatch.setattr(discovery, "list_devices", cloud) - assert [d.id for d in asyncio.run(discovery.discover_devices())] == ["usb"] - output = capsys.readouterr().err - assert "--debug" in output and "offline" not in output - - -@pytest.mark.parametrize("explicit", [True, False]) -def test_explicit_and_default_skip_discovery(monkeypatch, explicit): - async def fail(**kwargs): - if explicit: - raise AssertionError("discovery called") - - return [DiscoveredDevice("default", "local", None, "device", None)] - - monkeypatch.setattr(options, "discover_devices", fail) - monkeypatch.setattr( - options.ConfigLoader, - "load", - lambda path: SimpleNamespace(device=SimpleNamespace(serial="default")), - ) - - result = CliRunner().invoke(echo_target, ["chosen"] if explicit else []) - assert result.exit_code == 0, result.output - assert result.stdout.strip() == ("chosen" if explicit else "default") - - -def test_picker_labels_not_ready(monkeypatch): - async def discover(**kwargs): - return [ - DiscoveredDevice("usb", "local", None, "device", None), - DiscoveredDevice("cloud", "cloud", "Phone", "stopped", "android"), - ] - - labels = [] - - def select(message, choices): - labels.extend(choice.label for choice in choices) - return "cloud" - - monkeypatch.setattr(options, "discover_devices", discover) - monkeypatch.setattr(options, "is_interactive", lambda: True) - monkeypatch.setattr(options, "select_prompt", select) - monkeypatch.setattr(options, "confirm_prompt", lambda *args, **kwargs: False) - monkeypatch.setattr( - options.ConfigLoader, - "load", - lambda path: SimpleNamespace(device=SimpleNamespace(serial=None)), - ) - - result = CliRunner().invoke(echo_target) - assert result.exit_code == 0, result.output - assert "cloud (Phone) [stopped] cloud (not ready)" in labels - - -def test_cancel_and_empty_picker(monkeypatch): - async def discover(**kwargs): - return [ - DiscoveredDevice("a", "local", None, "device", None), - DiscoveredDevice("b", "local", None, "device", None), +@pytest.fixture +def core(monkeypatch): + driver = FakeDriver() + adb = AsyncMock( + return_value=[ + DeviceDescriptor("usb", "local-android-adb", "android", state="device") ] - - monkeypatch.setattr(options, "discover_devices", discover) - monkeypatch.setattr(options, "is_interactive", lambda: True) - monkeypatch.setattr( - options.ConfigLoader, - "load", - lambda path: SimpleNamespace(device=SimpleNamespace(serial=None)), - ) - - monkeypatch.setattr(options, "select_prompt", lambda *args: None) - assert CliRunner().invoke(echo_target).exit_code == 0 - - def cancel(*args): - raise KeyboardInterrupt - - monkeypatch.setattr(options, "select_prompt", cancel) - assert CliRunner().invoke(echo_target).exit_code == 130 - - -def test_device_option_wins_over_default(monkeypatch): - monkeypatch.setattr( - options.ConfigLoader, - "load", - lambda path: SimpleNamespace(device=SimpleNamespace(serial=None)), ) + cloud = AsyncMock(return_value=[]) + connect = AsyncMock(return_value=fake_device(driver=driver)) + inventory = AsyncMock(side_effect=AssertionError("unexpected picker inventory")) + options = [] - def command(target, **kwargs): - click.echo(target) - - command.__module__ = "mobilerun.cli.devices.test" - wrapped = click.command()(options.device_options(command)) - result = CliRunner().invoke(wrapped, ["--device", "chosen"]) - assert result.exit_code == 0, result.output - assert result.stdout == "chosen\n" - - -def test_cloud_listing_uses_settings_base_url(monkeypatch): - from mobilerun.clients.cloud import client - - monkeypatch.setenv("MOBILERUN_CLOUD_BASE_URL", "https://configured.example") - monkeypatch.setattr(discovery, "resolve_cloud_api_key", lambda: "fake-key") - calls = [] - - class FakeClient: + class Factory: def __init__(self, **kwargs): - calls.append(kwargs) - self.devices = SimpleNamespace(list=self._list) + options.append(kwargs) + self.local = SimpleNamespace(list_android_devices=adb) + self.connect = connect + self.list_devices = inventory + self.list_cloud_devices = cloud async def __aenter__(self): return self @@ -285,347 +49,137 @@ async def __aenter__(self): async def __aexit__(self, *args): pass - async def _list(self, **kwargs): - return SimpleNamespace(items=[], pagination=SimpleNamespace(has_next=False)) - - monkeypatch.setattr(client, "AsyncMobilerun", FakeClient) - asyncio.run(discovery.discover_devices(local=False)) - assert calls[0]["base_url"] == "https://configured.example" + monkeypatch.setattr(selection, "AsyncMobilerun", Factory) + return SimpleNamespace( + cloud=cloud, + connect=connect, + driver=driver, + options=options, + inventory=inventory, + ) -def test_list_human_and_json(monkeypatch): - async def discover(**kwargs): - return [ - DiscoveredDevice("usb", "local", None, "device", None), - DiscoveredDevice("cloud", "cloud", "Phone", "ready", "android"), - ] +def test_discovery_local_and_cloud(monkeypatch, core): + core.cloud.return_value = [ + DeviceDescriptor("cloud-1", "cloud", "android", "Phone", "stopped", "android") + ] + monkeypatch.setenv("MOBILERUN_API_KEY", "fake-key") + devices = asyncio.run(discovery.discover_devices()) + assert [(d.device_id, d.backend, d.ready) for d in devices] == [ + ("usb", "local-android-adb", True), + ("cloud-1", "cloud", False), + ] - monkeypatch.setattr(listing, "discover_devices", discover) - runner = CliRunner() - result = runner.invoke(listing.devices, ["--json"]) + result = CliRunner().invoke(device, ["list", "--json"]) assert result.exit_code == 0, result.output assert json.loads(result.stdout) == [ {"id": "usb", "source": "local", "default": False, "state": "device"}, { - "id": "cloud", + "id": "cloud-1", "source": "cloud", "default": False, "name": "Phone", - "state": "ready", + "state": "stopped", "type": "android", }, ] - result = runner.invoke(listing.devices, []) - assert result.exit_code == 0, result.output - assert "Local devices · 1" in result.stdout - assert "usb" in result.stdout - assert "Cloud devices · 1" in result.stdout - assert "Phone cloud ● ready android" in result.stdout -def test_cloud_list_errors_are_fatal(monkeypatch): - async def fail(**kwargs): - raise RuntimeError("private upstream detail") +def test_missing_key_skips_cloud(core): + assert asyncio.run(discovery.discover_devices(local=False)) == [] + core.cloud.assert_not_awaited() - monkeypatch.setattr(discovery, "resolve_cloud_api_key", lambda: "key") - monkeypatch.setattr(discovery, "list_devices", fail) - result = CliRunner().invoke(listing.devices, ["--cloud"]) - assert result.exit_code == 1 - assert "Error listing cloud devices: offline" in result.stderr - assert "private upstream detail" not in result.stderr +def test_cloud_error_warns_and_returns_local(monkeypatch, capsys, core): + core.cloud.side_effect = RuntimeError("private upstream detail") + monkeypatch.setenv("MOBILERUN_API_KEY", "fake-key") + assert [d.device_id for d in asyncio.run(discovery.discover_devices())] == ["usb"] + output = capsys.readouterr().err + assert "--debug" in output and "private upstream detail" not in output -def test_cloud_list_uses_public_discovery(monkeypatch): - async def discover(*, local, cloud, base_url, billing, strict): - assert local is False and cloud is True and strict is True - return [DiscoveredDevice("cloud-1", "cloud", "Phone", "ready", "android")] - - monkeypatch.setattr(listing, "discover_devices", discover) - result = CliRunner().invoke(listing.devices, ["--cloud", "--json"]) - assert result.exit_code == 0, result.output - assert json.loads(result.stdout)[0]["id"] == "cloud-1" - - -def test_device_picker_precedes_coordinates(monkeypatch): - order = [] - monkeypatch.setattr( - options, - "discover_devices", - AsyncMock( - return_value=[ - DiscoveredDevice("a", "local", None, "device", None), - DiscoveredDevice("b", "local", None, "device", None), - ] - ), - ) - monkeypatch.setattr(options, "is_interactive", lambda: True) - monkeypatch.setattr(menu, "is_interactive", lambda: True) - - def pick(*args): - order.append("device") - return "a" - - def text(label, **kwargs): - order.append(label) - return "1" - - monkeypatch.setattr(options, "select_prompt", pick) - monkeypatch.setattr(menu, "text_prompt", text) - monkeypatch.setattr(options, "confirm_prompt", lambda *args, **kwargs: False) - monkeypatch.setattr( - selection, "connect_target", AsyncMock(return_value=AsyncMock()) - ) - result = CliRunner().invoke(device, ["input", "tap"]) - assert result.exit_code == 0, result.output - assert order == ["device", "X coordinate", "Y coordinate"] - - -def test_list_marks_default(monkeypatch): - monkeypatch.setattr( - listing, - "discover_devices", - AsyncMock( - return_value=[ - DiscoveredDevice("a", "local", None, "device", None), - DiscoveredDevice("b", "cloud", "Phone", "ready", "android"), - ] - ), - ) - monkeypatch.setattr( - listing.ConfigLoader, - "load", - lambda *args: SimpleNamespace(device=SimpleNamespace(serial="b")), - ) - runner = CliRunner() - result = runner.invoke(listing.devices, ["--json"]) - assert [item["default"] for item in json.loads(result.stdout)] == [False, True] - result = runner.invoke(listing.devices) - assert "★" in result.stdout and "b" in result.stdout +def test_cloud_listing_uses_settings_base_url(monkeypatch, core): + monkeypatch.setenv("MOBILERUN_CLOUD_BASE_URL", "https://configured.example") + monkeypatch.setenv("MOBILERUN_API_KEY", "fake-key") + asyncio.run(discovery.discover_devices(local=False)) + assert core.options[0]["base_url"] == "https://configured.example" -def test_unavailable_saved_default_errors_without_fallback(monkeypatch): - monkeypatch.setattr( - options.ConfigLoader, - "load", - lambda path: SimpleNamespace(device=SimpleNamespace(serial="missing")), - ) - monkeypatch.setattr( - options, - "discover_devices", - AsyncMock( - return_value=[DiscoveredDevice("other", "local", None, "device", None)] - ), - ) - monkeypatch.setattr(options, "is_interactive", lambda: False) - result = CliRunner().invoke(echo_target) +def test_cloud_list_errors_are_fatal(monkeypatch, core): + monkeypatch.setenv("MOBILERUN_API_KEY", "fake-key") + core.cloud.side_effect = RuntimeError("private upstream detail") + result = CliRunner().invoke(device, ["list", "--cloud"]) assert result.exit_code == 1 - assert "Default device missing is not available." in result.output - - -def test_picker_save_yes_and_no(monkeypatch): - devices = [ - DiscoveredDevice("a", "local", None, "device", None), - DiscoveredDevice("b", "local", None, "device", None), - ] - monkeypatch.setattr( - options.ConfigLoader, - "load", - lambda path: SimpleNamespace(device=SimpleNamespace(serial=None)), - ) - monkeypatch.setattr(options, "discover_devices", AsyncMock(return_value=devices)) - monkeypatch.setattr(options, "is_interactive", lambda: True) - monkeypatch.setattr(options, "select_prompt", lambda *args: "a") - saved = [] - monkeypatch.setattr(options, "save_default_device", saved.append) - - for answer in (False, True): - monkeypatch.setattr( - options, "confirm_prompt", lambda *args, answer=answer, **kwargs: answer - ) - result = CliRunner().invoke(echo_target) - assert result.exit_code == 0, result.output - assert saved == ["a"] - - -def test_existing_default_no_save_prompt(monkeypatch): - monkeypatch.setattr( - options.ConfigLoader, - "load", - lambda path: SimpleNamespace(device=SimpleNamespace(serial="a")), - ) - monkeypatch.setattr( - options, - "discover_devices", - AsyncMock(return_value=[DiscoveredDevice("a", "local", None, "device", None)]), - ) - monkeypatch.setattr(options, "is_interactive", lambda: True) - - def fail(*args, **kwargs): - raise AssertionError("unexpected confirmation") - - monkeypatch.setattr(options, "confirm_prompt", fail) - - result = CliRunner().invoke(echo_target) - assert result.exit_code == 0, result.output - assert result.stdout == "a\n" - - -def test_explicit_device_option_precedes_prompt_without_discovery(monkeypatch): - monkeypatch.setattr(options, "is_interactive", lambda: True) - monkeypatch.setattr(menu, "is_interactive", lambda: True) - monkeypatch.setattr( - options, - "discover_devices", - AsyncMock(side_effect=AssertionError("unexpected discovery")), - ) - monkeypatch.setattr(menu, "text_prompt", lambda *args: "1") - driver = AsyncMock() - connect = AsyncMock(return_value=driver) - monkeypatch.setattr(selection, "connect_target", connect) - result = CliRunner().invoke(device, ["input", "tap", "--device", "chosen"]) - assert result.exit_code == 0, result.output - assert connect.await_args.args[0] == "chosen" - - -@pytest.fixture -def clean_target(monkeypatch): - monkeypatch.delenv("ANDROID_SERIAL", raising=False) - monkeypatch.delenv("MOBILERUN_CONFIG", raising=False) - - -@pytest.fixture -def adb_phone(monkeypatch): - def set_devices(**states): - monkeypatch.setattr( - discovery.adb, - "list", - AsyncMock( - return_value=[ - SimpleNamespace(serial=k, state=v) for k, v in states.items() - ] - ), - ) - - return set_devices - - -@pytest.mark.usefixtures("clean_target") -@pytest.mark.parametrize( - "serial,explicit,expected", - [ - ("missing", None, None), - ("wanted", None, "wanted"), - ("missing", "chosen", "chosen"), - ], -) -def test_file_rm_respects_target_precedence( - monkeypatch, adb_phone, serial, explicit, expected -): - cfg = MobileConfig() - cfg.device.serial = "saved" - ConfigLoader.save(cfg) - monkeypatch.setenv("ANDROID_SERIAL", serial) - adb_phone(saved="device", wanted="device") - connect = AsyncMock(return_value=AsyncMock()) - monkeypatch.setattr(selection, "connect_target", connect) - args = ["file", "rm", "/demo", "--yes"] - result = CliRunner().invoke( - device, args + (["--device", explicit] if explicit else []) - ) - if expected is None: - connect.assert_not_awaited() - assert result.exit_code == 1 and serial in result.stderr - else: - assert result.exit_code == 0, result.output - assert connect.await_args.args == (expected,) - - -@pytest.mark.usefixtures("clean_target") -@pytest.mark.parametrize("online", [True, False]) -def test_only_online_adb_device_is_selected(monkeypatch, adb_phone, online): - adb_phone( - off="offline", locked="unauthorized", **({"on": "device"} if online else {}) - ) - connect = AsyncMock(return_value=AsyncMock()) - monkeypatch.setattr(selection, "connect_target", connect) - result = CliRunner().invoke(device, ["file", "rm", "/demo", "--yes"]) - if online: - assert result.exit_code == 0, result.output - assert connect.await_args.args == ("on",) - else: - assert result.exit_code == 1 and "No devices found" in result.stderr - connect.assert_not_awaited() + assert "Error listing cloud devices: offline" in result.stderr + assert "private upstream detail" not in result.stderr -@pytest.mark.usefixtures("clean_target") @pytest.mark.parametrize("args", [[], ["--json"], ["--cloud"]]) -def test_bad_login_does_not_hide_local_state(adb_phone, tmp_path, monkeypatch, args): - adb_phone(locked="unauthorized") +def test_bad_login_does_not_hide_local_state(core, tmp_path, monkeypatch, args): path = tmp_path / "bad.json" path.write_text("{") - monkeypatch.setattr(login_store, "credential_path", lambda: path) + monkeypatch.setattr(LoginStore, "from_settings", lambda: LoginStore(path)) result = CliRunner().invoke(device, ["list", *args]) assert "credentials" in result.stderr.lower() if "--cloud" in args: assert result.exit_code == 1 elif "--json" in args: assert result.exit_code == 0 - assert json.loads(result.stdout)[0]["state"] == "unauthorized" + assert json.loads(result.stdout)[0]["state"] == "device" else: - assert result.exit_code == 0 and "unauthorized" in result.stdout + assert result.exit_code == 0 and "usb" in result.stdout -@pytest.mark.usefixtures("clean_target") -def test_ios_does_not_receive_saved_android_token(monkeypatch): - cfg = MobileConfig() - cfg.device.auth_token = "android-test-token" - create = Mock(return_value=AsyncMock()) - monkeypatch.setattr(selection, "IOSDevice", create) - asyncio.run(selection.connect_target("http://ios", kind="ios", config=cfg)) - create.assert_called_once_with("http://ios", token=None) +def test_list_marks_saved_default(core): + config = MobileConfig() + config.device.serial = "usb" + ConfigLoader.save(config) + runner = CliRunner() + result = runner.invoke(device, ["list", "--json"]) + assert result.exit_code == 0, result.output + assert json.loads(result.stdout)[0]["default"] is True + result = runner.invoke(device, ["list"]) + assert "★" in result.stdout and "usb" in result.stdout -@pytest.mark.usefixtures("clean_target") -def test_android_ping_does_not_receive_saved_ios_token(monkeypatch): - from importlib import import_module +@pytest.mark.parametrize("source", ["saved", "ANDROID_SERIAL"]) +def test_unavailable_selected_target_does_not_fall_back(core, source, monkeypatch): + if source == "saved": + config = MobileConfig() + config.device.serial = "missing" + ConfigLoader.save(config) + else: + monkeypatch.setenv("ANDROID_SERIAL", "missing") + core.connect.side_effect = DeviceDisconnectedError("private transport details") - ping = import_module("mobilerun.cli.devices.ping") - cfg = MobileConfig() - cfg.device.platform = "ios" - cfg.device.auth_token = "ios-test-token" - ConfigLoader.save(cfg) - create = Mock(return_value=AsyncMock()) - monkeypatch.setattr(ping, "create_android_portal_http_driver", create) - result = CliRunner().invoke(device, ["ping", "--android", "http://portal"]) - assert result.exit_code == 0, result.output - create.assert_called_once_with("http://portal", None) + result = CliRunner().invoke(device, ["input", "tap", "1", "2"]) + assert result.exit_code == 1, result.output + assert "Device disconnected." in result.stderr + assert "private transport details" not in result.stderr + assert core.connect.await_args.args == ("missing",) + core.inventory.assert_not_awaited() -@pytest.mark.usefixtures("clean_target") -def test_missing_env_config_never_uses_global(tmp_path, monkeypatch): - ConfigLoader.save(MobileConfig()) - monkeypatch.setenv("MOBILERUN_CONFIG", str(tmp_path / "missing.yaml")) - with pytest.raises(OutdatedConfigError, match="missing.yaml"): - ConfigLoader.load() +def test_unsupported_operation_renders_cleanly(core): + core.driver.failures["tap"] = UnsupportedOperation( + verb="tap", backend="demo", reason="no input" + ) + result = CliRunner().invoke(device, ["input", "tap", "1", "2", "usb"]) + assert result.exit_code == 1 + assert "is not supported" in result.stderr -@pytest.mark.usefixtures("clean_target") -@pytest.mark.parametrize("value", ["", " \t "]) -def test_blank_env_config_uses_saved_user_config(monkeypatch, value): - config = MobileConfig() - config.device.serial = "saved" - ConfigLoader.save(config) - monkeypatch.setenv("MOBILERUN_CONFIG", value) - assert ConfigLoader.load().device.serial == "saved" - - -@pytest.mark.usefixtures("clean_target") -def test_saved_token_and_env_override(monkeypatch): - cfg = MobileConfig().device - cfg.platform = "ios" - cfg.auth_token = "ios-test-token" - assert cfg.resolve_auth_token("android") is None - assert cfg.resolve_auth_token("ios") == "ios-test-token" - monkeypatch.setenv("MOBILERUN_DEVICE_TOKEN", "test-override") - assert cfg.resolve_auth_token("android") == "test-override" + +@pytest.mark.parametrize("platform,saved", [("ios", "android"), ("android", "ios")]) +def test_portal_does_not_receive_other_platform_token(core, platform, saved): + cfg = MobileConfig() + cfg.device.platform = saved + cfg.device.auth_token = "other-platform-test-token" + ConfigLoader.save(cfg) + result = CliRunner().invoke( + device, ["input", "tap", "1", "2", f"--{platform}", "http://portal"] + ) + assert result.exit_code == 0, result.output + core.connect.assert_awaited_once_with( + backend=f"local-{platform}-http", url="http://portal", token=None + ) diff --git a/tests/unit/cli/test_doctor.py b/tests/unit/cli/test_doctor.py index 7172473c8..44014dea1 100644 --- a/tests/unit/cli/test_doctor.py +++ b/tests/unit/cli/test_doctor.py @@ -1,329 +1,342 @@ """Doctor diagnostics, opt-in repairs, and read-only Portal transport checks.""" -import asyncio import importlib from types import SimpleNamespace -from unittest.mock import AsyncMock +from unittest.mock import ANY, AsyncMock -import httpx import pytest from click.testing import CliRunner +from mobilerun_core import ( + AsyncMobilerun, + DiagnosticResult, + PortalRelease, + PortalUnavailable, + SetupResult, +) from mobilerun.cli.app import cli +from mobilerun.cli.base.prompts import SelectChoice +from mobilerun.cli.devices.base import selection +from mobilerun.cli.devices.utils import approval from mobilerun.cli.doctor import doctor -from mobilerun.diagnostics import checks as diagnostics -from mobilerun.diagnostics.checks import ReadyTcp -from mobilerun.diagnostics.results import CheckResult, Status from tests.support.doctor import checks as checks doctor_module = importlib.import_module("mobilerun.cli.doctor") -@pytest.mark.parametrize("flag", ["--device", "-d"]) -def test_doctor_legacy_device_option(monkeypatch, flag): - run = AsyncMock() - monkeypatch.setattr(doctor_module, "run_doctor", run) - result = CliRunner().invoke(doctor, [flag, "emulator-5554"]) - assert result.exit_code == 0, result.output - run.assert_awaited_once_with("emulator-5554", False, fix=False) - - -def test_doctor_passes_flags_to_diagnostics(monkeypatch): +def test_doctor_passes_flags_to_diagnostics(monkeypatch: pytest.MonkeyPatch) -> None: run = AsyncMock() monkeypatch.setattr(doctor_module, "run_doctor", run) - result = CliRunner().invoke(doctor, ["emulator-5554", "--android", "--debug"]) + result = CliRunner().invoke(doctor, ["emulator-5554", "--debug"]) assert result.exit_code == 0, result.output - run.assert_awaited_once_with("emulator-5554", True, fix=False) + run.assert_awaited_once_with(ANY, "emulator-5554", True, fix=False) -def test_doctor_portal_http_android_runs_local_only(monkeypatch): +def test_doctor_portal_http_android_runs_local_only( + monkeypatch: pytest.MonkeyPatch, +) -> None: run = AsyncMock() monkeypatch.setattr(doctor_module, "run_doctor", run) - result = CliRunner().invoke(doctor, ["http://127.0.0.1:8080", "-a"]) + result = CliRunner().invoke(doctor, ["http://127.0.0.1:8080"]) assert result.exit_code == 0, result.output assert " ".join(result.output.split()) == ( "! doctor: device checks for Portal HTTP targets aren't supported yet; ran local checks" ) - run.assert_awaited_once_with(None, False, fix=False) - - -def test_doctor_without_target_uses_discovery(monkeypatch): - run = AsyncMock() - monkeypatch.setattr(doctor_module, "run_doctor", run) - from mobilerun.clients.portal import discovery - - monkeypatch.setattr( - discovery.adb, - "list", - AsyncMock(return_value=[SimpleNamespace(serial="test-device", state="device")]), - ) - result = CliRunner().invoke(doctor, []) - assert result.exit_code == 0, result.output - assert "Using test-device" in result.stderr - run.assert_awaited_once_with("test-device", False, fix=False) + run.assert_awaited_once_with(ANY, None, False, fix=False) -def test_doctor_rejects_multiple_targets(): - result = CliRunner().invoke(doctor, ["serial", "--android", "--ios"]) +def test_doctor_rejects_multiple_targets() -> None: + result = CliRunner().invoke(doctor, ["serial", "other"]) assert result.exit_code == 2 - assert "Choose at most one device type flag" in result.output + assert "unexpected extra argument" in result.output -@pytest.mark.parametrize("kind", ["ios", "cloud", "remote"]) -def test_non_android_doctor_runs_local_checks_only(monkeypatch, kind): +def test_cloud_id_runs_local_checks_only( + monkeypatch: pytest.MonkeyPatch, +) -> None: run = AsyncMock() monkeypatch.setattr(doctor_module, "run_doctor", run) - result = CliRunner().invoke(doctor, ["target", f"--{kind}"]) + result = CliRunner().invoke(doctor, ["11111111-1111-1111-1111-111111111111"]) assert result.exit_code == 0, result.output assert ( "doctor: device checks support Android only; ran local checks" in result.output ) - run.assert_awaited_once_with(None, False, fix=False) - + run.assert_awaited_once_with(ANY, None, False, fix=False) -def test_tcp_check_reuses_existing_forward(monkeypatch): - class Device: - serial = "serial" - shell = AsyncMock() - async def forward_list(self): - yield SimpleNamespace(serial="serial", remote="tcp:8080", local="tcp:1234") - - class Client: - async def __aenter__(self): - return self - - async def __aexit__(self, *args): - pass - - async def get(self, url, **kwargs): - assert url == "http://localhost:1234/ping" - return SimpleNamespace(status_code=200) - - monkeypatch.setattr(diagnostics.asyncio, "sleep", AsyncMock()) +def test_doctor_no_target_only_runs_adb_check_even_with_an_environment_serial( + checks: SimpleNamespace, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("ANDROID_SERIAL", "ignored-serial") monkeypatch.setattr( - diagnostics.PortalClient, "_fetch_auth_token", AsyncMock(return_value=None) + AsyncMobilerun, + "list_devices", + AsyncMock(side_effect=AssertionError("discovery")), ) - monkeypatch.setattr(diagnostics.httpx, "AsyncClient", Client) - result = asyncio.run(diagnostics.check_tcp(Device(), False)) - assert result.status == diagnostics.Status.PASS, result.message - - -def test_doctor_default_does_not_repair_missing_portal(checks): - module, _, _ = checks - result = CliRunner().invoke(cli, ["doctor", "-d", "serial"]) - assert result.exit_code == 1, result.output - module.install_portal.assert_not_awaited() - module.fix_enable_accessibility.assert_not_awaited() - - -def test_doctor_fix_installs_and_rechecks(checks): - module, ok, fail = checks - module.check_portal_installed.side_effect = [(fail, False), (ok, True)] - result = CliRunner().invoke(cli, ["doctor", "-d", "serial", "--fix"]) - assert result.exit_code == 0, (result.output, result.exception) - module.install_portal.assert_awaited_once() - assert module.check_portal_installed.await_count == 2 - assert "warning" in result.output - - -@pytest.mark.parametrize("fix", [False, True]) -def test_doctor_accessibility_repairs_only_when_requested(checks, fix): - module, ok, _ = checks - module.check_portal_installed.return_value = (ok, True) - module.check_accessibility.return_value = ( - CheckResult("Accessibility", Status.FAIL, "disabled"), - False, - ) - result = CliRunner().invoke( - cli, ["doctor", "-d", "serial", *(["--fix"] if fix else [])] - ) - assert result.exit_code == (0 if fix else 1), result.output - assert module.fix_enable_accessibility.await_count == int(fix) - - -def test_doctor_adb_failure_exits_one(checks): - module, _, fail = checks - module.check_adb.return_value = fail - result = CliRunner().invoke(cli, ["doctor", "-d", "serial"]) - assert result.exit_code == 1 - module.check_device.assert_not_awaited() - module.install_portal.assert_not_awaited() - - -def test_doctor_menu_offers_diagnose_and_repair(checks, monkeypatch): - module, _, _ = checks - monkeypatch.setattr(module, "is_interactive", lambda: True) - seen = [] - - def choose(label, choices): - seen.extend(choice.label for choice in choices) - return None - - monkeypatch.setattr(module, "select_prompt", choose) result = CliRunner().invoke(cli, ["doctor"]) - assert result.exit_code == 0 - assert seen == ["Diagnose", "Diagnose and repair"] + assert result.exit_code == 0, result.output + assert "skipping device checks" in result.output + checks.diagnostic.assert_awaited_once() + assert checks.diagnostic.call_args.kwargs["checks"] == ("ADB",) -def test_setup_failure_exits_one(monkeypatch): - module = importlib.import_module("mobilerun.cli.devices.setup") - monkeypatch.setattr(module.adb, "device", AsyncMock(return_value=None)) - result = CliRunner().invoke(cli, ["device", "setup", "-d", "serial"]) - assert result.exit_code == 1, result.output - assert "Could not get device object" in result.output +def test_all_checks_pass_in_display_order(checks: SimpleNamespace) -> None: + result = CliRunner().invoke(cli, ["doctor", "serial"]) + assert result.exit_code == 0, result.output + expected = [ + "ADB: found, 1 device(s)", + "Device: serial (online)", + "Portal: installed", + "Portal Version: v0.7.1 (pinned", + "Accessibility: enabled", + "Content Provider: reachable", + "State (content): a11y_tree", + "Screenshot (content): ok (2 KB)", + "TCP Mode: localhost:17425", + "State (tcp): a11y_tree", + "Screenshot (tcp): ok (2 KB)", + "Keyboard: available", + "All checks passed.", + ] + positions = [result.output.index(text) for text in expected] + assert positions == sorted(positions) + assert all( + not call.kwargs.get("allow_changes", False) + for call in checks.diagnostic.call_args_list + ) -def test_tcp_read_only_does_not_toggle_or_forward(monkeypatch): - class Phone: - serial = "serial" - shell = AsyncMock() - forward_port = AsyncMock() +@pytest.mark.parametrize( + "check,status,facts,expected,exit_code", + [ + ( + "Device", + "fail", + {"state": "unauthorized"}, + "serial (state: unauthorized)", + 1, + ), + ("Device", "fail", {"state": "offline"}, "serial (state: offline)", 1), + ("Device", "fail", {"state": "unavailable"}, "no device connected", 1), + ("Portal Installed", "fail", {"installed": False}, "Portal: not installed", 1), + ("Portal Version", "warn", {}, "could not read version", 0), + ("Accessibility", "fail", {"enabled": False}, "Accessibility: not enabled", 1), + ("Content Provider", "fail", {}, "Content Provider: invalid response", 1), + ( + "State (content)", + "fail", + {"missing_keys": ("phone_state",)}, + "missing: phone_state", + 1, + ), + ("Screenshot (content)", "fail", {}, "Screenshot (content): capture failed", 1), + ("State (tcp)", "fail", {}, "State (tcp): invalid response", 1), + ("Screenshot (tcp)", "fail", {}, "Screenshot (tcp): capture failed", 1), + ("Keyboard", "warn", {"available": False}, "Keyboard: not listed", 0), + ], +) +def test_doctor_check_statuses_and_exit_codes( + checks: SimpleNamespace, + check: str, + status: str, + facts: dict[str, object], + expected: str, + exit_code: int, +) -> None: + checks.normal[check] = DiagnosticResult(check, status, facts) + result = CliRunner().invoke(cli, ["doctor", "serial"]) + assert result.exit_code == exit_code, (result.output, result.exception) + assert expected in " ".join(result.output.split()) + checks.setup.assert_not_awaited() + checks.accessibility.assert_not_awaited() - async def forward_list(self): - if False: - yield None - phone = Phone() - monkeypatch.setattr( - diagnostics.PortalClient, "_fetch_auth_token", AsyncMock(return_value=None) +@pytest.mark.parametrize( + "facts,exit_code,message,summary", + [ + ( + {"failure": "no_forward", "forward_port": None}, + 0, + "no existing port forward; use doctor --fix", + "1 warning", + ), + ( + {"failure": "unreachable", "forward_port": 17425}, + 1, + "ping failed", + "1 issue", + ), + ( + {"failure": "bad_status", "forward_port": 17425, "http_status": 503}, + 1, + "ping returned 503", + "1 issue", + ), + ], +) +def test_unavailable_tcp_skips_tcp_children( + checks: SimpleNamespace, + facts: dict[str, object], + exit_code: int, + message: str, + summary: str, +) -> None: + checks.normal["TCP Mode"] = DiagnosticResult( + "TCP Mode", "warn", facts, "private-payload" ) - result = asyncio.run(diagnostics.check_tcp(phone, False)) - assert result.status == Status.WARN - assert "--fix" in result.message - phone.shell.assert_not_awaited() - phone.forward_port.assert_not_awaited() - + for name in ("State (tcp)", "Screenshot (tcp)"): + checks.normal[name] = DiagnosticResult( + name, "warn", {"transport": "tcp"}, "private-payload" + ) + result = CliRunner().invoke(cli, ["doctor", "serial", "--debug"]) + assert result.exit_code == exit_code, result.output + assert f"TCP Mode: {message}" in " ".join(result.output.split()) + assert "State (tcp)" not in result.output + assert "Screenshot (tcp)" not in result.output + assert summary in result.output + assert "private-payload" not in result.output -def test_setup_manual_accessibility_is_not_success(monkeypatch): - from mobilerun.clients.portal.install import PortalSetupResult - - module = importlib.import_module("mobilerun.cli.devices.setup") - monkeypatch.setattr(module.adb, "device", AsyncMock(return_value=object())) - monkeypatch.setattr( - module, - "install_portal", - AsyncMock(return_value=PortalSetupResult(True, False, True)), - ) - result = CliRunner().invoke(cli, ["device", "setup", "-d", "serial"]) - assert result.exit_code == 1, result.output - assert "manually enable" in result.output - assert "Setup complete!" not in result.output +@pytest.mark.parametrize( + "status,facts,message,detail,exit_code", + [ + ( + "pass", + {"count": 1, "executable_path": "/opt/android/adb", "failure": None}, + "found, 1 device(s)", + "/opt/android/adb", + 0, + ), + ( + "fail", + {"executable_path": None, "failure": "missing_executable"}, + "adb not found in PATH", + "Install Android SDK Platform Tools", + 1, + ), + ( + "fail", + {"executable_path": "/opt/android/adb", "failure": "server_error"}, + "adb found but server error", + "/opt/android/adb", + 1, + ), + ], +) +def test_doctor_adb_uses_typed_facts( + checks: SimpleNamespace, + status: str, + facts: dict[str, object], + message: str, + detail: str, + exit_code: int, +) -> None: + checks.normal["ADB"] = DiagnosticResult("ADB", status, facts, "private-payload") + result = CliRunner().invoke(cli, ["doctor", "serial", "--debug"]) + assert result.exit_code == exit_code, result.output + assert f"ADB: {message}" in result.output + assert detail in result.output + assert "private-payload" not in result.output -@pytest.mark.parametrize("lost_forward", [True, False]) -def test_plain_doctor_uses_only_existing_tcp_connection( - checks, monkeypatch, lost_forward -): - module, ok, _ = checks - device = module.check_device.return_value[1] +@pytest.mark.parametrize( + "release,expected", + [(PortalRelease("0.8.1", None), "latest: 0.8.1"), (None, "expected 0.7.2")], +) +def test_older_portal_checks_latest_release( + checks: SimpleNamespace, release: PortalRelease | None, expected: str +) -> None: + checks.normal["Portal Version"] = DiagnosticResult( + "Portal Version", + "warn", + {"installed": "0.7.1-dev", "compatible": "0.7.2", "mapping_fetched": True}, + ) + if release is None: + checks.release.side_effect = PortalUnavailable("unavailable") + else: + checks.release.side_effect = None + checks.release.return_value = release + result = CliRunner().invoke(cli, ["doctor", "serial"]) + assert result.exit_code == 0, result.output + assert expected in result.output + checks.release.assert_awaited_once() - async def forwards(): - yield SimpleNamespace(serial=device.serial, local="tcp:1234", remote="tcp:8080") - device.forward_list = forwards - device.forward_port = AsyncMock() - device.shell = AsyncMock() - connect = AsyncMock(side_effect=AssertionError("must not repair")) - monkeypatch.setattr(diagnostics.PortalClient, "connect", connect) - monkeypatch.setattr( - diagnostics.PortalClient, - "_fetch_auth_token", - AsyncMock(return_value="test-token"), - ) - paths = [] - - def respond(request): - assert request.url.port == 1234 - assert request.headers["Authorization"] == "Bearer test-token" - paths.append(request.url.path) - if request.url.path == "/ping": - return httpx.Response(200) - if lost_forward: - raise httpx.ConnectError("forward disappeared") - if request.url.path == "/state_full": - return httpx.Response( - 200, - json={ - "result": dict.fromkeys( - ("a11y_tree", "phone_state", "device_context") - ) - }, - ) - assert request.url.path == "/screenshot" - return httpx.Response(200, json={"status": "success", "result": "cG5n"}) - - client = httpx.AsyncClient - monkeypatch.setattr( - diagnostics.httpx, - "AsyncClient", - lambda **kw: client(transport=httpx.MockTransport(respond), **kw), +def test_doctor_fix_installs_and_rechecks(checks: SimpleNamespace, monkeypatch) -> None: + checks.normal["Portal Installed"] = DiagnosticResult( + "Portal Installed", "fail", {"installed": False} ) - async def state(device, debug, **kwargs): - if not kwargs: - return ok, None - return await diagnostics.check_portal_state(device, debug, **kwargs) - - module.check_portal_state.side_effect = state - module.check_portal_installed.return_value = (ok, True) - monkeypatch.setattr(module, "check_tcp", diagnostics.check_tcp) - result = CliRunner().invoke(module.doctor, ["-d", device.serial]) - assert result.exit_code == int(lost_forward), result.output - assert paths == ["/ping", "/state_full", *([] if lost_forward else ["/screenshot"])] - connect.assert_not_awaited() - device.forward_port.assert_not_awaited() - device.shell.assert_not_awaited() - - -def test_plain_doctor_reports_broken_tcp_screenshot(checks, monkeypatch): - module, ok, _ = checks - tcp_portal = object() - module.check_portal_installed.return_value = (ok, True) - module.check_tcp.return_value = ReadyTcp(1234, {}, "ping ok") - module.check_portal_state.side_effect = [(ok, None), (ok, tcp_portal)] - screenshot = AsyncMock( - return_value=CheckResult("Screenshot", Status.FAIL, "empty response") - ) - monkeypatch.setattr(module, "check_screenshot", screenshot) - result = CliRunner().invoke(module.doctor, ["-d", "serial"]) - assert result.exit_code == 1, result.output - assert "Screenshot (tcp): empty response" in result.output - screenshot.assert_awaited_once_with(tcp_portal, False) - module.check_tcp.assert_awaited_once_with( - module.check_device.return_value[1], False, fix=False + gates = [] + + class ProbeClient(AsyncMobilerun): + def __init__(self, *, hitl_gate, **kwargs): + super().__init__(hitl_gate=hitl_gate, **kwargs) + gates.append(hitl_gate) + + monkeypatch.setattr(selection, "AsyncMobilerun", ProbeClient) + monkeypatch.setattr(approval, "is_interactive", lambda: False) + + async def repair(serial: str, **options: object) -> SetupResult: + details = dict( + serial=serial, + **options, + apk_path=None, + latest=False, + uninstall=True, + package="com.mobilerun.portal", + will_install=True, + touches_accessibility=True, + portal_version="0.7.1", + selected_version="0.7.1", + source="github.com", + ) + gate = gates[-1] + assert await gate("local.setup_portal", details) + checks.normal["Portal Installed"] = DiagnosticResult( + "Portal Installed", "pass", {"installed": True} + ) + return SetupResult(True, serial, "setup_portal") + + checks.setup.side_effect = repair + refused = CliRunner().invoke(cli, ["doctor", "serial", "--fix"]) + assert refused.exit_code == 1 + assert "pass --yes" in refused.output + checks.setup.reset_mock() + result = CliRunner().invoke(cli, ["doctor", "serial", "--fix", "--yes"]) + assert result.exit_code == 0, (result.output, result.exception) + checks.setup.assert_awaited_once() + assert "Setup complete!" in result.output + assert any( + call.kwargs.get("allow_changes") for call in checks.diagnostic.call_args_list ) -def test_device_without_serial_uses_adb_default(monkeypatch): - device = SimpleNamespace( - serial="device-1", get_state=AsyncMock(return_value="device") +def test_doctor_fix_accessibility_is_only_attempted_with_fix( + checks: SimpleNamespace, +) -> None: + checks.normal["Accessibility"] = DiagnosticResult( + "Accessibility", "fail", {"enabled": False} ) - lookup = AsyncMock(return_value=device) - monkeypatch.setattr(diagnostics.adb, "device", lookup) - result, selected = asyncio.run(diagnostics.check_device(None, False)) - assert result.status == Status.PASS - assert selected is device - lookup.assert_awaited_once_with() + assert CliRunner().invoke(cli, ["doctor", "serial"]).exit_code == 1 + checks.accessibility.assert_not_awaited() + result = CliRunner().invoke(cli, ["doctor", "serial", "--fix", "--yes"]) + assert result.exit_code == 0, (result.output, result.exception) + assert "enabled (auto-fixed)" in result.output + checks.accessibility.assert_awaited_once_with("serial") -@pytest.mark.parametrize( - "check, status", - [ - (diagnostics.check_content_provider, Status.FAIL), - (diagnostics.check_keyboard, Status.WARN), - ], -) -def test_non_text_adb_response_is_reported_as_failure(check, status): - result = asyncio.run( - check(SimpleNamespace(shell=AsyncMock(return_value=b"unexpected")), True) - ) - assert result.status == status - assert "non-text output" in result.message +def test_doctor_menu_offers_diagnose_and_repair( + checks: SimpleNamespace, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(checks.module, "is_interactive", lambda: True) + seen: list[str] = [] + def choose(label: str, choices: list[SelectChoice]) -> None: + seen.extend(choice.label for choice in choices) + return None -def test_portal_version_parses_numeric_dev_suffix(): - from mobilerun.diagnostics.versions import parse_portal_version - - assert parse_portal_version("v0.7.26-dev") == (0, 7, 26) + monkeypatch.setattr(checks.module, "select_prompt", choose) + result = CliRunner().invoke(cli, ["doctor"]) + assert result.exit_code == 0 + assert seen == ["Diagnose", "Diagnose and repair"] diff --git a/tests/unit/cli/test_prompts.py b/tests/unit/cli/test_prompts.py index fb82f9d56..fe69b2f72 100644 --- a/tests/unit/cli/test_prompts.py +++ b/tests/unit/cli/test_prompts.py @@ -9,6 +9,12 @@ import click import pytest from click.testing import CliRunner +from mobilerun_core import ( + ConnectProxyRef, + DeviceDescriptor, + ProxyAlreadyConfigured, + SetupResult, +) from prompt_toolkit.application import create_app_session from prompt_toolkit.input import create_pipe_input from prompt_toolkit.output import DummyOutput @@ -17,9 +23,12 @@ from mobilerun.cli.base.prompts import SelectChoice, select_prompt_async from mobilerun.cli.credentials import group as credentials from mobilerun.cli.devices.app.uninstall import uninstall -from mobilerun.cli.devices.base import pickers -from mobilerun.cli.devices.base.options import DeviceTarget +from mobilerun.cli.devices.base import selection +from mobilerun.cli.devices.utils import approval +from mobilerun.cli.devices.utils.prompts import pickers from mobilerun.cli.proxy import group as proxy +from mobilerun.clients.local.login_store import LoginStore +from tests.support.devices import FakeDriver, fake_device def test_select_inside_running_event_loop(): @@ -35,18 +44,15 @@ async def run(): def test_uninstall_interactive_app_picker(monkeypatch): - device = SimpleNamespace( - list_apps=AsyncMock( - return_value=[{"package": "com.example", "label": "Example"}] - ), - uninstall_app=AsyncMock(return_value="Success"), - ) + driver = FakeDriver(apps=[{"package": "com.example", "label": "Example"}]) @asynccontextmanager - async def open_device(self): - yield device + async def owner(*, hitl_gate, **kwargs): + async with fake_device(driver=driver, hitl_gate=hitl_gate) as phone: + yield SimpleNamespace(connect=AsyncMock(return_value=phone)) - monkeypatch.setattr(DeviceTarget, "open", open_device) + monkeypatch.setattr(selection, "AsyncMobilerun", owner) + monkeypatch.setattr(menu, "is_interactive", lambda: True) monkeypatch.setattr(pickers, "is_interactive", lambda: True) with ( create_pipe_input() as input, @@ -55,7 +61,7 @@ async def open_device(self): input.send_text("\r") result = CliRunner().invoke(uninstall, ["--yes", "--device", "fake"]) assert result.exit_code == 0, result.output - device.uninstall_app.assert_awaited_once_with("com.example") + assert driver.calls[-1] == ("uninstall_app", ("com.example",), {}) def test_prompt_failure_has_clear_error(monkeypatch): @@ -141,7 +147,9 @@ async def run(): prompt = SimpleNamespace( execute=lambda: pytest.fail("sync execute must not run") ) - with pytest.raises(click.ClickException, match="Interactive prompt failed"): + with pytest.raises( + click.ClickException, match=r"corresponding \*_async prompt" + ): prompts._execute(prompt) asyncio.run(run()) @@ -235,8 +243,6 @@ def tap(x: int) -> None: def test_menu_connect_prompts_address(monkeypatch: pytest.MonkeyPatch) -> None: - from unittest.mock import AsyncMock - from mobilerun.cli.devices import connect as connect_module from mobilerun.cli.devices.group import device @@ -245,17 +251,37 @@ def test_menu_connect_prompts_address(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setattr(connect_module, "is_interactive", lambda: True) monkeypatch.setattr(connect_module, "discover_devices", AsyncMock(return_value=[])) seen = [] + order = [] def select(message, choices): + order.append(message) seen.extend(choice.label for choice in choices) return "__add_address__" - monkeypatch.setattr(connect_module, "select_prompt", AsyncMock(side_effect=select)) + def text(message): + order.append(message) + return "127.0.0.1:5555" + + connect = AsyncMock() + + @asynccontextmanager + async def owner(*, hitl_gate, **kwargs): + async def connect_address(serial): + await hitl_gate("local.connect_android", {"serial": serial}) + return SetupResult(True, serial, "connect_android") + + connect.side_effect = connect_address + yield SimpleNamespace(local=SimpleNamespace(connect_android=connect)) + + monkeypatch.setattr(selection, "AsyncMobilerun", owner) + monkeypatch.setattr(approval, "is_interactive", lambda: True) monkeypatch.setattr( - connect_module, "text_prompt", AsyncMock(return_value="127.0.0.1:5555") + approval, + "confirm_prompt_async", + AsyncMock(side_effect=lambda message, **_: order.append(message) or True), ) - connect = AsyncMock(return_value="connected to 127.0.0.1:5555") - monkeypatch.setattr(connect_module.adb, "connect", connect) + monkeypatch.setattr(connect_module, "select_prompt", AsyncMock(side_effect=select)) + monkeypatch.setattr(connect_module, "text_prompt", AsyncMock(side_effect=text)) saved = [] monkeypatch.setattr(connect_module, "save_default_device", saved.append) result = CliRunner().invoke(device, []) @@ -263,6 +289,11 @@ def select(message, choices): assert seen[-1] == "Add device by address (host:port)…" assert saved == ["127.0.0.1:5555"] connect.assert_awaited_once_with("127.0.0.1:5555") + assert order == [ + "Select a device", + "Device address (host[:port])", + "Approve local connect android?", + ] def test_cli_command_tree_required_parameters_are_prompting() -> None: @@ -289,9 +320,6 @@ def walk(command: click.Command, path: str) -> None: def test_disconnect_clears_default(monkeypatch: pytest.MonkeyPatch) -> None: - from types import SimpleNamespace - from unittest.mock import AsyncMock - from mobilerun.cli.devices import disconnect as disconnect_module from mobilerun.cli.devices.group import device @@ -300,15 +328,18 @@ def test_disconnect_clears_default(monkeypatch: pytest.MonkeyPatch) -> None: "load", lambda _: SimpleNamespace(device=SimpleNamespace(serial="serial-1")), ) - disconnect = AsyncMock() - monkeypatch.setattr(disconnect_module.adb, "disconnect", disconnect) + + @asynccontextmanager + async def owner(**kwargs): + yield SimpleNamespace() + + monkeypatch.setattr(selection, "AsyncMobilerun", owner) saved = [] monkeypatch.setattr(disconnect_module, "save_default_device", saved.append) result = CliRunner().invoke(device, ["disconnect"]) assert result.exit_code == 0, result.output assert result.stdout.strip() == "✓ Disconnected serial-1" assert saved == [None] - disconnect.assert_not_awaited() def test_cloud_resource_choices_use_no_commerce( @@ -318,50 +349,60 @@ def test_cloud_resource_choices_use_no_commerce( from unittest.mock import AsyncMock from mobilerun.cli.base import choices - from mobilerun.models.billing import Billing list_mailboxes = AsyncMock( return_value=[SimpleNamespace(id="id-1", address="mail@example.test")] ) - monkeypatch.setattr(choices, "list_mailboxes", list_mailboxes) + monkeypatch.setattr(choices.Mailboxes, "list", list_mailboxes) result = choices.mailboxes(click.Context(click.Command("test"))) assert result == [menu.SelectChoice("id-1", "mail@example.test")] - list_mailboxes.assert_awaited_once_with(billing=Billing.NO_COMMERCE) + list_mailboxes.assert_awaited_once_with() def test_direct_tap_prompts_coordinates(monkeypatch: pytest.MonkeyPatch) -> None: - from types import SimpleNamespace - from unittest.mock import AsyncMock - - from mobilerun.cli.devices.base import options - from mobilerun.cli.devices.base import selection as tap_module + from mobilerun.cli.devices.base import device as device_commands from mobilerun.cli.devices.group import device + from mobilerun.cli.devices.utils.connection import device as connection - monkeypatch.setattr(menu, "is_interactive", lambda: True) + monkeypatch.setattr(device_commands, "is_interactive", lambda: True) + monkeypatch.setattr(pickers, "is_interactive", lambda: True) labels: list[str] = [] - def text(message: str) -> str: + async def text(message: str) -> str: + connect.assert_awaited_once() labels.append(message) return {"X coordinate": "12", "Y coordinate": "34"}[message] - monkeypatch.setattr(menu, "text_prompt", text) - phone = AsyncMock() - monkeypatch.setattr(tap_module, "connect_target", AsyncMock(return_value=phone)) + monkeypatch.setattr(pickers, "text_prompt_async", text) + driver = FakeDriver() + phone = fake_device(driver=driver) + connect = AsyncMock(return_value=phone) monkeypatch.setattr( - options, + connection, "discover_devices", AsyncMock( return_value=[ - SimpleNamespace( - id="serial-1", name=None, source="local", state=None, ready=True - ) + DeviceDescriptor( + "serial-1", "local-android-adb", "android", state="device" + ), ] ), ) + + @asynccontextmanager + async def owner(**kwargs): + try: + yield SimpleNamespace(connect=connect) + finally: + await phone.aclose() + + monkeypatch.setattr(selection, "AsyncMobilerun", owner) result = CliRunner().invoke(device, ["input", "tap"]) assert result.exit_code == 0, result.output assert labels == ["X coordinate", "Y coordinate"] - phone.tap.assert_awaited_once_with(12, 34) + connect.assert_awaited_once() + assert connect.await_args.args == ("serial-1",) + assert driver.calls == [("tap", (12, 34), {})] def test_required_text_cancels_after_whitespace( @@ -446,36 +487,10 @@ def command(): prompt.assert_not_awaited() -def test_unmanaged_proxy_conflict_is_specific_extension_conflict(): - from mobilerun.core.proxy import UnmanagedProxyConflict - from mobilerun.errors import ExtensionConflict - from mobilerun.errors import UnmanagedProxyConflict as PublicConflict - - assert issubclass(UnmanagedProxyConflict, ExtensionConflict) - assert UnmanagedProxyConflict is PublicConflict - - -def test_sync_safety_decline_exits_zero(monkeypatch): - monkeypatch.setattr(menu, "is_interactive", lambda: True) - observed = [] - monkeypatch.setattr( - safety, "confirm_prompt", lambda message, **kw: observed.append(kw) or False - ) - - @click.command() - def command(): - safety.confirm_action("delete", "paid", "Warning", yes=False) - click.echo("should not run") - - result = CliRunner().invoke(command) - assert result.exit_code == 0 - assert "should not run" not in result.output - assert observed == [{"default": False}] - - def test_async_safety_decline_exits_zero(monkeypatch): monkeypatch.setattr(menu, "is_interactive", lambda: True) - monkeypatch.setattr(safety, "confirm_prompt_async", AsyncMock(return_value=False)) + prompt = AsyncMock(return_value=False) + monkeypatch.setattr(safety, "confirm_prompt_async", prompt) @click.command() def command(): @@ -485,6 +500,7 @@ def command(): result = CliRunner().invoke(command) assert result.exit_code == 0 assert "should not run" not in result.output + prompt.assert_awaited_once_with("Continue?", default=False) def test_json_redirect_does_not_make_stdout_noninteractive_look_interactive( @@ -493,10 +509,10 @@ def test_json_redirect_does_not_make_stdout_noninteractive_look_interactive( import sys from mobilerun.cli.proxy import group - from mobilerun.clients.cloud import proxies + from mobilerun.clients.cloud import client as connection client = AsyncMock(side_effect=AssertionError("must not construct a client")) - monkeypatch.setattr(proxies, "cloud_client", client) + monkeypatch.setattr(connection, "cloud_client", client) monkeypatch.setattr(safety, "confirm_prompt_async", AsyncMock(return_value=True)) def check_ttys(): @@ -516,67 +532,63 @@ def check_ttys(): safety.confirm_prompt_async.assert_not_awaited() -def test_sync_safety_running_loop_explains_async_fix(monkeypatch): - monkeypatch.setattr(menu, "is_interactive", lambda: True) - monkeypatch.setattr(prompts, "_select", lambda *args, **kwargs: object()) +def test_async_safety_noninteractive_yes_skips_prompt(monkeypatch): + monkeypatch.setattr(menu, "is_interactive", lambda: False) + prompt = AsyncMock() + monkeypatch.setattr(safety, "confirm_prompt_async", prompt) @click.command() def command(): - async def run(): - safety.confirm_action("delete", "paid", "Warning", yes=False) - - asyncio.run(run()) + asyncio.run(safety.confirm_action_async("delete", "paid", "Warning", yes=True)) result = CliRunner().invoke(command) - assert result.exit_code == 1 - assert "confirm_action_async()" in result.output - assert "_async" in result.output - - -def test_sync_safety_inside_loop_skips_prompt_for_yes_and_noninteractive(monkeypatch): - monkeypatch.setattr( - prompts, - "_select", - lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError("prompt created")), - ) - - @click.command() - @click.option("--yes", is_flag=True) - def command(yes): - async def run(): - safety.confirm_action("delete", "paid", "Warning", yes=yes) - - asyncio.run(run()) - - monkeypatch.setattr(menu, "is_interactive", lambda: True) - accepted = CliRunner().invoke(command, ["--yes"]) - assert accepted.exit_code == 0, accepted.output - monkeypatch.setattr(menu, "is_interactive", lambda: False) - refused = CliRunner().invoke(command) - assert refused.exit_code == 1 - assert "--yes" in refused.output + assert result.exit_code == 0, result.output + prompt.assert_not_awaited() @pytest.mark.parametrize("tty", [True, False]) def test_proxy_replacement_requires_opt_in(monkeypatch, tty): - phone = SimpleNamespace(close=AsyncMock()) - extension = SimpleNamespace( - bind=AsyncMock( - side_effect=[proxy.UnmanagedProxyConflict("use force=True"), None] - ), - status=AsyncMock(return_value=SimpleNamespace(connected=True)), - ) + closed = [] + writes = [] + phone_id = "818c5ba1-e22a-4cc8-8408-aeef33d443cf" + + @asynccontextmanager + async def owner(*, hitl_gate, **kwargs): + phone = fake_device() + + async def set_proxy(value, *, replace=False): + if not replace: + raise ProxyAlreadyConfigured("occupied") + await hitl_gate("device.set_proxy", {}) + writes.append(value) + + monkeypatch.setattr(phone, "set_proxy", AsyncMock(side_effect=set_proxy)) + monkeypatch.setattr(phone, "proxy_status", AsyncMock()) + try: + yield SimpleNamespace(connect=AsyncMock(return_value=phone)) + finally: + await phone.aclose() + closed.append(phone) + prompt = AsyncMock(side_effect=lambda message, *, default: default) + core_prompt = AsyncMock(return_value=False) monkeypatch.setattr(proxy.menu, "is_interactive", lambda: tty) - monkeypatch.setattr(proxy, "CloudDevice", lambda **kwargs: phone) - monkeypatch.setattr(proxy, "CloudFixedProxy", lambda id: extension) + monkeypatch.setattr(approval, "is_interactive", lambda: tty) + monkeypatch.setattr(selection, "AsyncMobilerun", owner) + monkeypatch.setattr(selection.LoginStore, "resolve_api_key", lambda self: "test") + monkeypatch.setattr(approval, "confirm_prompt_async", core_prompt) monkeypatch.setattr(proxy, "confirm_prompt_async", prompt) - result = CliRunner().invoke(proxy.proxy, ["bind", "new", "phone"]) + result = CliRunner().invoke(proxy.proxy, ["bind", "new", phone_id]) + assert len(closed) == 1 + assert closed[0].set_proxy.await_args_list[0].args == (ConnectProxyRef("new"),) + assert closed[0].set_proxy.await_args_list[0].kwargs == {"replace": False} + assert closed[0].set_proxy.await_count == 1 + closed[0].proxy_status.assert_not_awaited() + assert writes == [] + assert prompt.await_count == int(tty) + core_prompt.assert_not_awaited() assert result.exit_code == (0 if tty else 1), result.output assert ("Cancelled." if tty else "--force") in result.output - assert prompt.await_count == int(tty) - extension.bind.assert_awaited_once_with(phone, force=False) - phone.close.assert_awaited_once() @pytest.mark.parametrize("tty", [True, False]) @@ -641,29 +653,6 @@ def device() -> None: assert "Did you mean 'device'?" in result.output -def test_proxy_status_json_redacts_secrets(monkeypatch: pytest.MonkeyPatch) -> None: - from mobilerun.cli.proxy import group - - monkeypatch.setattr( - group, - "get_proxy", - AsyncMock( - return_value=SimpleNamespace( - id="p1", country="DE", status="active", type="mobile", password="secret" - ) - ), - ) - result = CliRunner().invoke(group.proxy, ["status", "p1", "--json"]) - assert result.exit_code == 0, result.output - assert json.loads(result.output) == { - "id": "p1", - "country": "DE", - "status": "active", - "type": "mobile", - } - assert "secret" not in result.output - - @pytest.mark.parametrize( "module_name,command,args,action", [ @@ -700,7 +689,7 @@ def test_resource_actions_refuse_noninteractive_without_yes( def test_auth_status_json_masks_key(monkeypatch: pytest.MonkeyPatch) -> None: from mobilerun.cli.auth import status - monkeypatch.setattr(status.credentials, "load_credentials", lambda: None) + monkeypatch.setattr(LoginStore, "load", lambda self: None) monkeypatch.setenv("MOBILERUN_API_KEY", "abcdefghijk") result = CliRunner().invoke(status.whoami, ["--json"]) assert result.exit_code == 0, result.output diff --git a/tests/unit/cli/test_rendering.py b/tests/unit/cli/test_rendering.py index c79a177ad..9327495c3 100644 --- a/tests/unit/cli/test_rendering.py +++ b/tests/unit/cli/test_rendering.py @@ -1,5 +1,6 @@ """Human-readable and machine-readable command output.""" +import asyncio import importlib import json from contextlib import asynccontextmanager, nullcontext @@ -11,11 +12,19 @@ import click import pytest from click.testing import CliRunner +from mobilerun_core import ( + AppOperationError, + AsyncMobilerun, + DeviceDescriptor, + LocalDevices, +) from mobilerun_sdk.types.connect.proxy_list_response import ProxyListResponse from mobilerun.cli.base import menu from mobilerun.cli.base.errors import render_error -from mobilerun.cli.devices.base import selection +from mobilerun.cli.devices.utils.connection import discovery +from mobilerun.clients.local.login_store import LoginStore +from tests.support.devices import FakeDriver, fake_device def test_render_output_and_streams(monkeypatch): @@ -44,38 +53,6 @@ def command(): assert "\x1b[" not in result.output -def test_apps_human_and_json(monkeypatch): - - apps = importlib.import_module("mobilerun.cli.devices.app.list") - - driver = AsyncMock() - driver.list_apps.return_value = [{"label": "Browser", "package": "com.browser"}] - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=driver)) - runner = CliRunner() - human = runner.invoke(apps.apps, ["serial", "--android"]) - assert human.exit_code == 0 - assert "Apps · 1" in human.stdout and "Browser" in human.stdout - assert "com.browser" in human.stdout - machine = runner.invoke(apps.apps, ["serial", "--android", "--json"]) - assert json.loads(machine.stdout) == [ - {"label": "Browser", "package": "com.browser"} - ] - - -def test_press_reports_target(monkeypatch): - - press = importlib.import_module("mobilerun.cli.devices.input.press") - - monkeypatch.setattr( - selection, "connect_target", AsyncMock(return_value=AsyncMock()) - ) - result = CliRunner().invoke(press.press, ["home", "serial", "--android"]) - assert result.exit_code == 0 - assert ( - "✓" in result.stdout and "serial" in result.stdout and "home" in result.stdout - ) - - def test_skills_list_short_long_and_json(monkeypatch): from mobilerun.skills.bundle import Skill @@ -121,30 +98,6 @@ def test_macro_list_missing_directory_and_json(tmp_path, monkeypatch): assert json.loads(result.stdout) == [] -def test_device_action_success_output(monkeypatch, tmp_path): - - from mobilerun.cli.devices import device - - apk = tmp_path / "app.apk" - apk.write_bytes(b"apk") - cases = [ - ("tap", ["input", "tap", "1", "2"]), - ("swipe", ["input", "swipe", "1", "2", "3", "4"]), - ("long_press", ["input", "long-press", "1", "2"]), - ("type", ["input", "type", "hello"]), - ("start", ["app", "start", "app.id"]), - ("install", ["app", "install", str(apk)]), - ("uninstall", ["app", "uninstall", "app.id", "--yes"]), - ] - for name, args in cases: - monkeypatch.setattr( - selection, "connect_target", AsyncMock(return_value=AsyncMock()) - ) - result = CliRunner().invoke(device, [*args, "serial", "--android"]) - assert result.exit_code == 0, (name, result.exception) - assert "✓" in result.stdout and "serial" in result.stdout, name - - def test_pool_failure_lists_each_error_on_stderr(): from mobilerun.errors.base import DeviceError @@ -165,12 +118,16 @@ def command(): ] -def test_proxy_list_and_status_show_metadata_without_credentials(monkeypatch): +def test_proxy_list_and_status_show_metadata_without_credentials( + monkeypatch: pytest.MonkeyPatch, +) -> None: import mobilerun.cli.proxy.group as module + from mobilerun.clients.cloud import proxies proxy = NS( id="proxy-1", + name="Proxy 1", status="active", country="DE", type="mobile", @@ -178,11 +135,11 @@ def test_proxy_list_and_status_show_metadata_without_credentials(monkeypatch): billing_mode="standalone_paid", ) monkeypatch.setattr( - module, - "list_proxies", + proxies.Proxies, + "list", AsyncMock(return_value=NS(items=[proxy], pagination=NS(has_next=False))), ) - monkeypatch.setattr(module, "get_proxy", AsyncMock(return_value=proxy)) + monkeypatch.setattr(proxies.Proxies, "retrieve", AsyncMock(return_value=proxy)) runner = CliRunner() human = runner.invoke(module.proxy, ["list"]) assert ( @@ -200,7 +157,7 @@ def test_proxy_list_and_status_show_metadata_without_credentials(monkeypatch): @pytest.fixture def fake_proxy_pages(monkeypatch): - from mobilerun.clients.cloud import proxies + from mobilerun.clients.cloud import client as connection def item(id, **fields): return { @@ -240,7 +197,7 @@ async def list_page(*, page, page_size): async def client(*args, **kwargs): yield NS(connect=NS(proxies=NS(list=list_page))) - monkeypatch.setattr(proxies, "cloud_client", client) + monkeypatch.setattr(connection, "cloud_client", client) return pages @@ -317,8 +274,8 @@ def test_number_and_mailbox_lists_show_metadata_and_json(monkeypatch): import mobilerun.cli.phone_number.group as number monkeypatch.setattr( - number, - "list_numbers", + number.Numbers, + "list", AsyncMock( return_value=[ NS(id="n1", phone_number="+49123", country_code="DE", state="active") @@ -327,8 +284,8 @@ def test_number_and_mailbox_lists_show_metadata_and_json(monkeypatch): raising=False, ) monkeypatch.setattr( - mailbox, - "list_mailboxes", + mailbox.Mailboxes, + "list", AsyncMock( return_value=[NS(id="m1", address="person@example.test", status="active")] ), @@ -348,24 +305,6 @@ def test_number_and_mailbox_lists_show_metadata_and_json(monkeypatch): assert json.loads(machine.stdout)[0]["id"] -def test_ui_raw_preserves_original_and_default_indents(monkeypatch): - - ui = importlib.import_module("mobilerun.cli.devices.screen.ui") - - driver = AsyncMock() - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=driver)) - monkeypatch.setattr(ui, "log_progress_to_stderr", lambda: None) - driver._create_state_provider = lambda options: NS( - get_state=AsyncMock( - return_value=NS(formatted_text="root\n child", phone_state=None) - ) - ) - raw = CliRunner().invoke(ui.ui, ["serial", "--android", "--raw"]) - assert raw.stdout == "root\n child\n" - human = CliRunner().invoke(ui.ui, ["serial", "--android"]) - assert human.stdout == " root\n child\n" - - def test_doctor_result_starts_with_status_symbol(capsys): from mobilerun.cli.doctor import _print_result from mobilerun.diagnostics.results import CheckResult, Status @@ -378,11 +317,9 @@ def test_auth_status_account_fields(monkeypatch): module = importlib.import_module("mobilerun.cli.auth.status") monkeypatch.delenv("MOBILERUN_API_KEY", raising=False) + monkeypatch.setattr(LoginStore, "load", lambda self: {"access_token": "test"}) monkeypatch.setattr( - module.credentials, "load_credentials", lambda: {"access_token": "test"} - ) - monkeypatch.setattr( - module.deviceauth, + module.DeviceAuthorization, "fetch_session", AsyncMock( return_value={"user": {"email": "person@example.test", "id": "user-1"}} @@ -394,24 +331,6 @@ def test_auth_status_account_fields(monkeypatch): assert "User ID: user-1" in result.stdout -def test_device_list_json(monkeypatch): - - module = importlib.import_module("mobilerun.cli.devices.list") - from mobilerun.cli.devices.base import discovery - - monkeypatch.setattr( - discovery.adb, - "list", - AsyncMock(return_value=[NS(serial="local-1", state="device")]), - ) - monkeypatch.setattr(discovery, "resolve_cloud_api_key", lambda: None) - result = CliRunner().invoke(module.devices, ["--json"]) - assert result.exit_code == 0 - assert json.loads(result.stdout) == [ - {"id": "local-1", "source": "local", "default": False, "state": "device"} - ] - - def test_spinner_only_uses_tty(monkeypatch): from mobilerun.cli.base import render @@ -436,17 +355,32 @@ def status(self, message): assert calls == ["Working"] -def test_uninstall_failure_result_is_not_reported_as_success(monkeypatch): +def test_uninstall_failure_result_is_not_reported_as_success( + monkeypatch: pytest.MonkeyPatch, +) -> None: + from mobilerun.cli.devices import device + from mobilerun.cli.devices.base import selection + + # The ADB route now translates its failure result to this typed core error. + driver = FakeDriver( + failures={ + "uninstall_app": AppOperationError( + "App uninstall failed", reason="DELETE_FAILED_INTERNAL_ERROR" + ) + } + ) - uninstall = importlib.import_module("mobilerun.cli.devices.app.uninstall") + @asynccontextmanager + async def owner(*, hitl_gate, **kwargs): + async with fake_device(driver=driver, hitl_gate=hitl_gate) as phone: + yield NS(connect=AsyncMock(return_value=phone)) - driver = AsyncMock() - driver.uninstall_app.return_value = "Failure [DELETE_FAILED_INTERNAL_ERROR]" - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=driver)) + monkeypatch.setattr(selection, "AsyncMobilerun", owner) result = CliRunner().invoke( - uninstall.uninstall, ["bad.package", "serial", "--android", "--yes"] + device, ["app", "uninstall", "bad.package", "serial", "--android", "--yes"] ) - assert result.exit_code != 0 + assert driver.calls == [("uninstall_app", ("bad.package",), {})] + assert result.exit_code == 1 assert "✓" not in result.stdout assert "DELETE_FAILED_INTERNAL_ERROR" in result.stderr @@ -470,18 +404,36 @@ def test_no_color_disables_ansi_on_tty(monkeypatch): assert "\x1b[" not in output.getvalue() -def test_device_list_uses_shared_renderer(monkeypatch): - +def test_device_list_uses_shared_renderer(monkeypatch: pytest.MonkeyPatch) -> None: module = importlib.import_module("mobilerun.cli.devices.list") - from mobilerun.cli.devices.base import discovery monkeypatch.setattr( - discovery.adb, - "list", - AsyncMock(return_value=[NS(serial="serial", state="device")]), + LocalDevices, + "list_android_devices", + AsyncMock( + return_value=[ + DeviceDescriptor( + "serial", "local-android-adb", "android", state="device" + ) + ] + ), ) - monkeypatch.setattr(discovery, "resolve_cloud_api_key", lambda: None) + monkeypatch.setattr( + AsyncMobilerun, + "list_devices", + AsyncMock( + return_value=[ + NS( + info=lambda: DeviceDescriptor( + "serial", "local-android-adb", "android" + ) + ) + ] + ), + ) + monkeypatch.setattr(discovery.LoginStore, "resolve_api_key", lambda self: None) result = CliRunner().invoke(module.devices) + assert result.exit_code == 0, result.output assert result.stdout == "Local devices · 1\n\nserial device\n" @@ -497,8 +449,8 @@ def test_number_list_plain_and_json(monkeypatch): import mobilerun.cli.phone_number.group as module monkeypatch.setattr( - module, - "list_numbers", + module.Numbers, + "list", AsyncMock( return_value=[ NS( @@ -532,7 +484,7 @@ def test_number_list_plain_and_json(monkeypatch): def test_mailbox_empty_is_not_warning(monkeypatch): import mobilerun.cli.mailbox.group as module - monkeypatch.setattr(module, "list_mailboxes", AsyncMock(return_value=[])) + monkeypatch.setattr(module.Mailboxes, "list", AsyncMock(return_value=[])) result = CliRunner().invoke(module.mailbox, ["list"], env={"NO_COLOR": "1"}) assert result.stdout == "No mailboxes yet.\nCreate one: mobilerun mailbox create\n" @@ -555,25 +507,6 @@ def test_workspace_files_list_plain(monkeypatch): assert result.stdout == "Files · 1\n\nphoto.png 42 abcdefgh-1234\n" -def test_device_app_list_is_aligned_and_json_unchanged(monkeypatch): - - module = importlib.import_module("mobilerun.cli.devices.app.list") - driver = AsyncMock() - driver.list_apps.return_value = [ - {"label": "Browser", "package": "com.example.browser"} - ] - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=driver)) - runner = CliRunner() - result = runner.invoke(module.apps, ["serial", "--android"], env={"NO_COLOR": "1"}) - assert result.stdout == "Apps · 1\n\nBrowser com.example.browser\n" - assert ( - json.loads( - runner.invoke(module.apps, ["serial", "--android", "--json"]).stdout - )[0]["package"] - == "com.example.browser" - ) - - @pytest.mark.parametrize( "action,billing,description", [ @@ -585,13 +518,13 @@ def test_device_app_list_is_aligned_and_json_unchanged(monkeypatch): def test_non_charge_confirmation_omits_billing( monkeypatch, action, billing, description ): - from mobilerun.cli.base.safety import confirm_action + from mobilerun.cli.base.safety import confirm_action_async monkeypatch.setattr(menu, "is_interactive", lambda: True) @click.command() def command(): - confirm_action(action, billing, description, yes=True) + asyncio.run(confirm_action_async(action, billing, description, yes=True)) result = CliRunner().invoke(command) assert result.exit_code == 0, result.output @@ -628,22 +561,6 @@ def test_credentials_list_groups_by_app(monkeypatch): ] -def test_device_actions_use_table(monkeypatch): - - module = importlib.import_module("mobilerun.cli.devices.action.list") - driver = AsyncMock() - driver.actions = NS( - list=lambda **kwargs: [ - NS(name="tap", description="Tap screen", input_schema={}) - ] - ) - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=driver)) - result = CliRunner().invoke( - module.actions, ["serial", "--android"], env={"NO_COLOR": "1"} - ) - assert result.stdout == "Actions · 1\n\ntap Tap screen\n" - - def test_skills_list_plain(monkeypatch): from mobilerun.skills.bundle import Skill @@ -663,7 +580,7 @@ def test_mailbox_status_uses_status_dot_and_preserves_json(monkeypatch): import mobilerun.cli.mailbox.group as module monkeypatch.setattr( - module.cloud_mailboxes, + module.Mailboxes, "retrieve", AsyncMock( return_value=NS( @@ -682,14 +599,24 @@ def test_mailbox_status_uses_status_dot_and_preserves_json(monkeypatch): ) -def test_proxy_status_is_a_status_not_a_success(monkeypatch): +def test_proxy_status_is_a_status_not_a_success( + monkeypatch: pytest.MonkeyPatch, +) -> None: import mobilerun.cli.proxy.group as module + from mobilerun.clients.cloud import proxies monkeypatch.setattr( - module, - "get_proxy", + proxies.Proxies, + "retrieve", AsyncMock( - return_value=NS(id="proxy-1", status="active", country="DE", type="mobile") + return_value=NS( + id="proxy-1", + name="Proxy 1", + status="active", + country="DE", + type="mobile", + billing_mode=None, + ) ), ) result = CliRunner().invoke( @@ -698,33 +625,6 @@ def test_proxy_status_is_a_status_not_a_success(monkeypatch): assert result.stdout == "proxy-1 DE ● active mobile\n" -def test_setting_getters_use_labelled_output(monkeypatch): - from mobilerun.cli.devices import device - - driver = AsyncMock() - driver.get_language.return_value = "de-DE" - driver.get_timezone.return_value = "Europe/Berlin" - driver.get_location.return_value = NS(latitude=52.52, longitude=13.405) - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=driver)) - runner = CliRunner() - for setting, expected in [ - ("language", "Language: de-DE\n"), - ("timezone", "Timezone: Europe/Berlin\n"), - ("location", "Location: 52.5200, 13.4050\n"), - ]: - result = runner.invoke( - device, - ["settings", setting, "get", "serial", "--android"], - env={"NO_COLOR": "1"}, - ) - assert result.exit_code == 0, result.output - assert result.stdout == expected - machine = runner.invoke( - device, ["settings", "location", "get", "serial", "--android", "--json"] - ) - assert json.loads(machine.stdout) == {"latitude": 52.52, "longitude": 13.405} - - def test_task_status_dot_and_relative_timestamp_preserve_json(monkeypatch): pytest.importorskip("mobilerun_agents", reason="requires mobilerun-agents add-on") @@ -782,57 +682,6 @@ def test_included_resources_are_labelled_and_json_unchanged(monkeypatch): ) == {"remaining": 3} -def test_cloud_device_status_uses_name_and_state(monkeypatch): - - module = importlib.import_module("mobilerun.cli.devices.cloud.status") - - @asynccontextmanager - async def client(**kwargs): - yield object() - - monkeypatch.setattr(module, "cloud_client", client) - monkeypatch.setattr( - module.devices, - "retrieve", - AsyncMock( - return_value=NS( - name="Tester 1", - state="ready", - model_dump_json=lambda: '{"state":"ready"}', - ) - ), - ) - result = CliRunner().invoke( - module.status, ["11111111-1111-1111-1111-111111111111"], env={"NO_COLOR": "1"} - ) - assert result.exit_code == 0, result.output - assert ( - result.stdout == "Tester 1 ● ready 11111111-1111-1111-1111-111111111111\n" - ) - - -def test_device_action_acknowledgements(monkeypatch): - from mobilerun.cli.devices import device - - driver = AsyncMock() - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=driver)) - runner = CliRunner() - for args, expected in [ - ( - ["settings", "timezone", "set", "Europe/Berlin"], - "✓ Timezone set to Europe/Berlin on serial\n", - ), - (["settings", "location", "reset"], "✓ Location reset on serial\n"), - (["app", "stop", "com.example.app"], "✓ Stopped com.example.app on serial\n"), - (["file", "rm", "/sdcard/a", "--yes"], "✓ Deleted /sdcard/a from serial\n"), - ]: - result = runner.invoke( - device, [*args, "serial", "--android"], env={"NO_COLOR": "1"} - ) - assert result.exit_code == 0, (result.output, result.exception) - assert result.stdout == expected - - def test_workspace_delete_acknowledges_and_preserves_json(monkeypatch): import mobilerun.cli.workspace.group as module diff --git a/tests/unit/cli/test_resource_cleanup.py b/tests/unit/cli/test_resource_cleanup.py index a27247ce2..8cffb6f48 100644 --- a/tests/unit/cli/test_resource_cleanup.py +++ b/tests/unit/cli/test_resource_cleanup.py @@ -1,6 +1,7 @@ """Resource release, batch cleanup and workspace mutations through Click.""" import json +from contextlib import nullcontext from pathlib import Path from types import SimpleNamespace as NS from unittest.mock import AsyncMock @@ -18,7 +19,7 @@ def test_proxy_release_continues_after_failure_and_returns_json_array(monkeypatch): cancel = AsyncMock(side_effect=[RuntimeError("secret"), None]) - monkeypatch.setattr(proxy, "cancel_proxy", cancel) + monkeypatch.setattr(proxy, "release_connect_proxy", cancel) result = CliRunner().invoke( cli, ["proxy", "release", "one", "two", "--yes", "--json"] ) @@ -40,7 +41,7 @@ def test_proxy_release_selects_multiple_and_confirms_once(monkeypatch): cancel = AsyncMock() confirm = AsyncMock(return_value=True) - monkeypatch.setattr(proxy, "cancel_proxy", cancel) + monkeypatch.setattr(proxy, "release_connect_proxy", cancel) monkeypatch.setattr(menu, "is_interactive", lambda: True) argument = proxy.proxy.commands["release"].params[0] monkeypatch.setattr( @@ -66,7 +67,7 @@ def test_proxy_release_empty_selection_aborts(monkeypatch): from mobilerun.cli.base.prompts import SelectChoice cancel = AsyncMock() - monkeypatch.setattr(proxy, "cancel_proxy", cancel) + monkeypatch.setattr(proxy, "release_connect_proxy", cancel) monkeypatch.setattr(menu, "is_interactive", lambda: True) argument = proxy.proxy.commands["release"].params[0] monkeypatch.setattr(argument, "choices", lambda ctx: [SelectChoice("one", "one")]) @@ -84,7 +85,7 @@ def test_proxy_release_empty_selection_aborts(monkeypatch): ) def test_click_signal_stops_batch(monkeypatch, signal, code): cancel = AsyncMock(side_effect=[signal, None]) - monkeypatch.setattr(proxy, "cancel_proxy", cancel) + monkeypatch.setattr(proxy, "release_connect_proxy", cancel) result = CliRunner().invoke(cli, ["proxy", "release", "one", "two", "--yes"]) assert result.exit_code == code assert cancel.await_count == 1 @@ -92,7 +93,7 @@ def test_click_signal_stops_batch(monkeypatch, signal, code): def test_duplicate_ids_are_processed_once(monkeypatch): cancel = AsyncMock() - monkeypatch.setattr(proxy, "cancel_proxy", cancel) + monkeypatch.setattr(proxy, "release_connect_proxy", cancel) result = CliRunner().invoke( cli, ["proxy", "release", "one", "two", "one", "--yes", "--json"] ) @@ -105,7 +106,7 @@ def test_picker_output_does_not_contaminate_json(monkeypatch): from mobilerun.cli.base import menu from mobilerun.cli.base.prompts import SelectChoice - monkeypatch.setattr(proxy, "cancel_proxy", AsyncMock()) + monkeypatch.setattr(proxy, "release_connect_proxy", AsyncMock()) monkeypatch.setattr(menu, "is_interactive", lambda: True) argument = proxy.proxy.commands["release"].params[0] monkeypatch.setattr(argument, "choices", lambda ctx: [SelectChoice("one", "one")]) @@ -151,7 +152,7 @@ async def process(item_id, **kwargs): operation = AsyncMock(side_effect=process) billing = Billing.NO_COMMERCE if command == ("proxy", "release"): - monkeypatch.setattr(proxy, "cancel_proxy", operation) + monkeypatch.setattr(proxy, "release_connect_proxy", operation) elif command == ("number", "release") or command == ("mailbox", "release"): module, name = ( (number, "PhoneNumber") if command[0] == "number" else (mailbox, "Mailbox") @@ -165,18 +166,31 @@ async def release(): monkeypatch.setattr(module, name, factory) elif command == ("number", "unbind"): - client = AsyncMock() - client.__aenter__.return_value = client - monkeypatch.setattr(number, "cloud_client", lambda **kwargs: client) + client = NS( + numbers=NS( + retrieve=AsyncMock( + side_effect=lambda item_id: NS( + data=NS(device_binding=NS(device_id=f"device-{item_id}")) + ) + ) + ), + devices=NS( + number=NS( + retrieve=AsyncMock( + side_effect=lambda device_id: NS( + binding=NS(number_id=device_id.removeprefix("device-")) + ) + ), + unbind=operation, + ) + ), + ) - async def retrieve(item_id, **kwargs): - assert kwargs == {"billing": billing, "client": client} - return NS(data=NS(device_binding=NS(device_id=f"device-{item_id}"))) + def open_client(*, billing): + assert billing is Billing.NO_COMMERCE + return nullcontext(client) - monkeypatch.setattr( - number.cloud_numbers, "retrieve", AsyncMock(side_effect=retrieve) - ) - monkeypatch.setattr(number.devices, "unbind_number", operation) + monkeypatch.setattr(number, "cloud_client", open_client) else: monkeypatch.setattr( workspace.Workspace, @@ -208,10 +222,8 @@ async def retrieve(item_id, **kwargs): ) assert [item for item, _ in calls] == expected_ids for _, kwargs in calls: - if command[0] == "workspace": + if command[0] == "workspace" or command == ("number", "unbind"): assert kwargs == {} - elif command == ("number", "unbind"): - assert kwargs == {"billing": billing, "client": client} else: assert kwargs == {"billing": billing} @@ -291,7 +303,7 @@ def test_workspace_download_and_rm_alias(monkeypatch): def test_proxy_release_confirmation_and_json(monkeypatch): cancel = AsyncMock() - monkeypatch.setattr(proxy, "cancel_proxy", cancel, raising=False) + monkeypatch.setattr(proxy, "release_connect_proxy", cancel) runner = CliRunner() assert runner.invoke(proxy.proxy, ["release", "p1"]).exit_code != 0 cancel.assert_not_awaited() @@ -376,15 +388,17 @@ def test_proxy_cancel_wrapper_sdk_and_error_mapping(monkeypatch): import pytest from mobilerun_sdk import APIStatusError - from mobilerun.clients.cloud import proxies as client_proxies + from mobilerun.clients.cloud import client as connection + from mobilerun.clients.cloud.proxies import Proxies from mobilerun.errors.cloud import CloudResourceNotFound from mobilerun.models.billing import Billing cancel = AsyncMock() context = AsyncMock() context.__aenter__.return_value = NS(connect=NS(proxies=NS(cancel=cancel))) - monkeypatch.setattr(client_proxies, "cloud_client", lambda *a, **k: context) - asyncio.run(client_proxies.cancel_proxy("p1", billing=Billing.NO_COMMERCE)) + monkeypatch.setattr(connection, "cloud_client", lambda *a, **k: context) + proxies = Proxies(billing=Billing.NO_COMMERCE) + asyncio.run(proxies.cancel("p1")) cancel.assert_awaited_once_with("p1") response = httpx.Response( 404, request=httpx.Request("DELETE", "https://example.test/proxy") @@ -393,7 +407,7 @@ def test_proxy_cancel_wrapper_sdk_and_error_mapping(monkeypatch): "secret server response", response=response, body=None ) with pytest.raises(CloudResourceNotFound) as exc: - asyncio.run(client_proxies.cancel_proxy("p1", billing=Billing.NO_COMMERCE)) + asyncio.run(proxies.cancel("p1")) assert "secret server response" not in str(exc.value) @@ -430,14 +444,17 @@ async def confirm(message, **kwargs): def test_workspace_apps_mutation_json(monkeypatch, tmp_path): + from mobilerun_core import AppIdentity + from mobilerun.cli.base import menu + from mobilerun.models import App apk = tmp_path / "a.apk" apk.write_bytes(b"apk") monkeypatch.setattr( workspace.Workspace, "upload_app", - AsyncMock(return_value=NS(id="a1", name="App", package="pkg")), + AsyncMock(return_value=App(AppIdentity("pkg"), "App", "a1")), ) monkeypatch.setattr(workspace.Workspace, "delete_app", AsyncMock()) monkeypatch.setattr(menu, "is_interactive", lambda: True) diff --git a/tests/unit/cli/test_resource_commands.py b/tests/unit/cli/test_resource_commands.py index 0d6bbaec9..2516b2019 100644 --- a/tests/unit/cli/test_resource_commands.py +++ b/tests/unit/cli/test_resource_commands.py @@ -2,7 +2,7 @@ import json from types import SimpleNamespace as NS -from unittest.mock import AsyncMock +from unittest.mock import AsyncMock, Mock import click import pytest @@ -10,7 +10,6 @@ import mobilerun.cli.mailbox.group as mailbox_commands import mobilerun.cli.phone_number.group as number_commands -import mobilerun.cli.proxy.group as proxy_commands from mobilerun.cli.app import cli from mobilerun.cli.mailbox.group import Mailbox from mobilerun.cli.phone_number.group import PhoneNumber @@ -27,10 +26,10 @@ def fake_resource_retrieval(monkeypatch): status="active", ) monkeypatch.setattr( - number_commands.cloud_numbers, "retrieve", AsyncMock(return_value=NS(data=data)) + number_commands.Numbers, "retrieve", AsyncMock(return_value=NS(data=data)) ) monkeypatch.setattr( - mailbox_commands.cloud_mailboxes, + mailbox_commands.Mailboxes, "retrieve", AsyncMock(return_value=NS(data=data)), ) @@ -66,8 +65,9 @@ def test_cli_create_billing( "group,resource", [("number", PhoneNumber), ("mailbox", Mailbox)] ) def test_cli_list_and_release(monkeypatch, group, resource): - module = number_commands if group == "number" else mailbox_commands - name = "list_numbers" if group == "number" else "list_mailboxes" + module = ( + number_commands.Numbers if group == "number" else mailbox_commands.Mailboxes + ) item = NS( id="resource-id", address=None, @@ -76,7 +76,7 @@ def test_cli_list_and_release(monkeypatch, group, resource): country_code=None, state="active", ) - monkeypatch.setattr(module, name, AsyncMock(return_value=[item])) + monkeypatch.setattr(module, "list", AsyncMock(return_value=[item])) release = AsyncMock( return_value=NS(data=NS(state="cancel_scheduled", status="cancel_scheduled")) ) @@ -139,39 +139,33 @@ def test_included_creation_does_not_prompt( @pytest.fixture def cloud(monkeypatch): - from mobilerun.core.devices.cloud import CloudDevice + from mobilerun_core import AsyncMobilerun def no_device(*args, **kwargs): - pytest.fail("binding commands must not construct or close a CloudDevice") + pytest.fail("binding commands must not open or manage a phone") - monkeypatch.setattr(CloudDevice, "__init__", no_device) + monkeypatch.setattr(AsyncMobilerun, "connect", no_device) + monkeypatch.setattr(AsyncMobilerun, "cloud_device", no_device) client = AsyncMock() client.__aenter__.return_value = client - monkeypatch.setattr( - number_commands, "cloud_client", lambda **kwargs: client, raising=False - ) - from mobilerun.clients.cloud import devices, numbers - + owner = Mock(return_value=client) + monkeypatch.setattr(number_commands, "cloud_client", owner) capabilities = AsyncMock(return_value=NS(capabilities=NS(telephony=True))) - bind = AsyncMock() + bind = AsyncMock(return_value=NS(binding=None)) current = AsyncMock(return_value=NS(binding=None)) unbind = AsyncMock() - terminate = AsyncMock() retrieve = AsyncMock(return_value=NS(data=NS(device_binding=NS(device_id="dev-1")))) - monkeypatch.setattr(devices, "capabilities", capabilities) - monkeypatch.setattr(devices, "bind_number", bind) - monkeypatch.setattr(devices, "number", current) - monkeypatch.setattr(devices, "unbind_number", unbind) - monkeypatch.setattr(devices, "terminate", terminate) - monkeypatch.setattr(numbers, "retrieve", retrieve) + client.devices.retrieve_capabilities = capabilities + client.devices.number = NS(bind=bind, retrieve=current, unbind=unbind) + client.numbers = NS(retrieve=retrieve) return NS( client=client, + owner=owner, capabilities=capabilities, bind=bind, current=current, unbind=unbind, retrieve=retrieve, - terminate=terminate, ) @@ -186,14 +180,10 @@ def test_bind_passes_ids_billing_and_outputs_json(cloud): "number_id": "num-1", "device_id": "dev-1", } - cloud.capabilities.assert_awaited_once_with( - "dev-1", billing=Billing.INCLUDED, client=cloud.client - ) - cloud.bind.assert_awaited_once_with( - "dev-1", "num-1", billing=Billing.INCLUDED, client=cloud.client - ) + cloud.owner.assert_called_once_with(billing=Billing.INCLUDED) + cloud.capabilities.assert_awaited_once_with("dev-1") + cloud.bind.assert_awaited_once_with("dev-1", number_id="num-1") cloud.unbind.assert_not_awaited() - cloud.terminate.assert_not_awaited() def test_unsupported_device_fails_cleanly(cloud): @@ -214,19 +204,17 @@ def test_bind_rejects_existing_device_binding(cloud): def test_unbind_resolves_number_and_outputs_json(cloud): + cloud.current.return_value.binding = NS(number_id="num-1") result = CliRunner().invoke( cli, ["number", "unbind", "num-1", "--billing", "no_commerce", "--json", "--yes"], ) assert result.exit_code == 0, result.output assert json.loads(result.output) == [{"id": "num-1", "status": "unbound"}] - cloud.retrieve.assert_awaited_once_with( - "num-1", billing=Billing.NO_COMMERCE, client=cloud.client - ) - cloud.unbind.assert_awaited_once_with( - "dev-1", billing=Billing.NO_COMMERCE, client=cloud.client - ) - cloud.terminate.assert_not_awaited() + cloud.retrieve.assert_awaited_once_with("num-1") + cloud.owner.assert_called_once_with(billing=Billing.NO_COMMERCE) + cloud.unbind.assert_awaited_once_with("dev-1") + cloud.current.assert_awaited_once_with("dev-1") def test_unbind_unbound_number_reports_error(cloud): @@ -237,35 +225,29 @@ def test_unbind_unbound_number_reports_error(cloud): cloud.unbind.assert_not_awaited() +def test_unbind_does_not_remove_another_numbers_link(cloud): + cloud.current.return_value.binding = NS(number_id="other") + result = CliRunner().invoke(cli, ["number", "unbind", "num-1", "--yes"]) + assert result.exit_code == 1 + cloud.unbind.assert_not_awaited() + + def test_commands_are_in_number_menu(): with click.Context(number_commands.number) as ctx: names = {choice.value for choice in number_commands.number.menu_choices(ctx)} assert {"bind", "unbind"} <= names -def test_bind_existing_proxy_passes_force_and_closes(monkeypatch): - phone = NS(close=AsyncMock()) - extension = NS( - bind=AsyncMock(), - status=AsyncMock(return_value=NS(connected=True)), - ) - monkeypatch.setattr(proxy_commands, "CloudDevice", lambda **kwargs: phone) - monkeypatch.setattr(proxy_commands, "CloudFixedProxy", lambda id: extension) - result = CliRunner().invoke( - proxy_commands.proxy, ["bind", "proxy-id", "phone-id", "--force"] - ) - assert result.exit_code == 0, result.output - extension.bind.assert_awaited_once_with(phone, force=True) - phone.close.assert_awaited_once() - - def test_proxy_list_paginates_and_status_is_value_safe(monkeypatch): + from mobilerun.clients.cloud import proxies + listing = AsyncMock( side_effect=[ NS( items=[ NS( id="one", + name="One", country=None, status=None, type=None, @@ -278,6 +260,7 @@ def test_proxy_list_paginates_and_status_is_value_safe(monkeypatch): items=[ NS( id="two", + name="Two", country=None, status=None, type=None, @@ -288,12 +271,20 @@ def test_proxy_list_paginates_and_status_is_value_safe(monkeypatch): ), ] ) - monkeypatch.setattr(proxy_commands, "list_proxies", listing) + monkeypatch.setattr(proxies.Proxies, "list", listing) monkeypatch.setattr( - proxy_commands, - "get_proxy", + proxies.Proxies, + "retrieve", AsyncMock( - return_value=NS(status="active", country=None, password="never-print") + return_value=NS( + id="one", + name="One", + status="active", + country=None, + type=None, + billing_mode=None, + password="never-print", + ) ), ) result = CliRunner().invoke(cli, ["proxy", "list"]) @@ -304,9 +295,7 @@ def test_proxy_list_paginates_and_status_is_value_safe(monkeypatch): "one ○ unknown", "two ○ unknown", ] - listing.assert_awaited_with( - page=2, page_size=100, billing="paid", included_only=False - ) + listing.assert_awaited_with(page=2, page_size=100, included_only=False) result = CliRunner().invoke(cli, ["proxy", "status", "one"]) assert result.exit_code == 0 assert "one" in result.output and "● active" in result.output @@ -314,8 +303,20 @@ def test_proxy_list_paginates_and_status_is_value_safe(monkeypatch): def test_proxy_buy_passes_explicit_billing_and_redacts_credentials(monkeypatch): - buy = AsyncMock(return_value=NS(id="new", password="never-print")) - monkeypatch.setattr(proxy_commands, "buy_proxy", buy) + from mobilerun.clients.cloud import proxies + + buy = AsyncMock( + return_value=NS( + id="new", + name="New", + country="DE", + status="active", + type="residential", + billing_mode="paid", + password="never-print", + ) + ) + monkeypatch.setattr(proxies.Proxies, "buy", buy) result = CliRunner().invoke( cli, ["proxy", "buy", "--country", "DE", "--billing", "paid", "--yes"] ) @@ -324,7 +325,7 @@ def test_proxy_buy_passes_explicit_billing_and_redacts_credentials(monkeypatch): buy.assert_awaited_once_with( "DE", type="residential", - billing="paid", checkout="browser", payment_timeout=600, + on_checkout=None, ) diff --git a/tests/unit/cli/test_run_stub.py b/tests/unit/cli/test_run_stub.py new file mode 100644 index 000000000..7e752d5d2 --- /dev/null +++ b/tests/unit/cli/test_run_stub.py @@ -0,0 +1,71 @@ +"""The retired command only shows a migration hint unless a plugin owns it.""" + +from importlib.metadata import EntryPoint + +import click +import pytest +from click.testing import CliRunner + +from mobilerun.addons import plugins +from mobilerun.cli.app import cli + + +@pytest.fixture +def cli_entries(monkeypatch): + entries = [] + monkeypatch.setattr( + plugins.metadata, + "entry_points", + lambda *, group: entries if group == "mobilerun.cli" else [], + ) + return entries + + +def test_retired_run_shows_migration_hint_on_stderr(cli_entries): + result = CliRunner().invoke(cli, ["run"]) + + assert result.exit_code == 2 + assert result.stdout == "" + assert "moved to `mobilerun agent run`" in result.stderr + assert "mobilerun-agents add-on" in result.stderr + assert "pip install" not in result.stderr + + +def test_retired_run_ignores_arguments_and_options(cli_entries): + runner = CliRunner() + expected = runner.invoke(cli, ["run"]) + result = runner.invoke( + cli, + ["run", "private prompt", "--token=private-token", "--help", "-h", "--", "-q"], + ) + + assert result.exit_code == 2 + assert result.stdout == "" + assert "mobilerun agent run" in result.stderr + assert result.stderr == expected.stderr + + +def test_retired_run_is_hidden_from_help(cli_entries): + result = CliRunner().invoke(cli, ["--help"]) + + assert result.exit_code == 0 + assert "run" not in [ + line.split()[0] for line in result.stdout.splitlines() if line.strip() + ] + + +def test_run_plugin_takes_precedence(cli_entries, monkeypatch): + @click.command("run") + @click.option("--mode", required=True) + def plugin_run(mode): + click.echo(f"plugin run: {mode}") + + entry = EntryPoint("run", "example_plugin.cli:run", "mobilerun.cli") + monkeypatch.setattr(EntryPoint, "load", lambda self: plugin_run) + cli_entries.append(entry) + + result = CliRunner().invoke(cli, ["run", "--mode", "plugin-specific"]) + + assert result.exit_code == 0 + assert result.stdout == "plugin run: plugin-specific\n" + assert result.stderr == "" diff --git a/tests/unit/cli/test_shell.py b/tests/unit/cli/test_shell.py index f1ef652d6..8631be890 100644 --- a/tests/unit/cli/test_shell.py +++ b/tests/unit/cli/test_shell.py @@ -5,11 +5,14 @@ import logging import subprocess import sys +from contextlib import contextmanager from pathlib import Path +from unittest.mock import AsyncMock import click import pytest from click.testing import CliRunner +from mobilerun_core import LocalDevices, PortalStatus, PortalUnavailable from mobilerun.cli.app import cli from mobilerun.cli.base import menu @@ -17,14 +20,25 @@ completion = importlib.import_module("mobilerun.cli.base.completion") +class CompletionRunner(CliRunner): + def __init__(self, tty=True): + super().__init__() + self.tty = tty + + @contextmanager + def isolation(self, *args, **kwargs): + with super().isolation(*args, **kwargs) as streams: + sys.stdout.isatty = lambda: self.tty + yield streams + + def test_detected_zsh_installs_once_and_does_not_dump( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: monkeypatch.setenv("HOME", str(tmp_path)) monkeypatch.setenv("SHELL", "/bin/zsh") - monkeypatch.setattr(completion, "_stdout_is_tty", lambda: True, raising=False) for _ in range(2): - result = CliRunner().invoke(completion.completion, ["--yes"]) + result = CompletionRunner().invoke(completion.completion, ["--yes"]) assert result.exit_code == 0, result.output assert "Installed zsh completion" in result.output assert "_MOBILERUN_COMPLETE" not in result.output @@ -38,10 +52,9 @@ def test_decline_leaves_rc_unchanged( ) -> None: monkeypatch.setenv("HOME", str(tmp_path)) monkeypatch.setenv("SHELL", "/bin/zsh") - monkeypatch.setattr(completion, "_stdout_is_tty", lambda: True, raising=False) rc = tmp_path / ".zshrc" rc.write_text("# existing\n") - result = CliRunner().invoke(completion.completion, [], input="n\n") + result = CompletionRunner().invoke(completion.completion, [], input="n\n") assert result.exit_code == 0, result.output assert rc.read_text() == "# existing\n" assert (tmp_path / ".mobilerun/completion.zsh").exists() @@ -55,8 +68,7 @@ def test_completion_prints_script_without_installing( ): monkeypatch.setenv("HOME", str(tmp_path)) monkeypatch.setenv("SHELL", "/bin/zsh") - monkeypatch.setattr(completion, "_stdout_is_tty", lambda: tty) - result = CliRunner().invoke(completion.completion, ["zsh", *options]) + result = CompletionRunner(tty).invoke(completion.completion, ["zsh", *options]) assert result.exit_code == 0, result.output assert "_MOBILERUN_COMPLETE" in result.output assert not (tmp_path / ".mobilerun").exists() @@ -78,8 +90,7 @@ def test_fish_installs_to_autoload_directory( ) -> None: monkeypatch.setenv("HOME", str(tmp_path)) monkeypatch.setenv("SHELL", "/opt/homebrew/bin/fish") - monkeypatch.setattr(completion, "_stdout_is_tty", lambda: True, raising=False) - result = CliRunner().invoke(completion.completion, []) + result = CompletionRunner().invoke(completion.completion, []) assert result.exit_code == 0, result.output assert ( "_MOBILERUN_COMPLETE" @@ -93,11 +104,10 @@ def test_unknown_shell_interactively_asks( ) -> None: monkeypatch.setenv("HOME", str(tmp_path)) monkeypatch.setenv("SHELL", "/bin/unknown") - monkeypatch.setattr(completion, "_stdout_is_tty", lambda: True, raising=False) monkeypatch.setattr( completion, "select_prompt", lambda message, choices: "zsh", raising=False ) - result = CliRunner().invoke(completion.completion, ["--yes"]) + result = CompletionRunner().invoke(completion.completion, ["--yes"]) assert result.exit_code == 0, result.output assert (tmp_path / ".mobilerun/completion.zsh").exists() @@ -108,11 +118,10 @@ def test_root_menu_completion_installs_instead_of_printing( monkeypatch.setenv("HOME", str(tmp_path)) monkeypatch.setenv("SHELL", "/bin/zsh") - monkeypatch.setattr(completion, "_stdout_is_tty", lambda: True) monkeypatch.setattr(menu, "is_interactive", lambda: True) monkeypatch.setattr(menu, "select_prompt", lambda message, choices: "completion") monkeypatch.setattr(completion, "confirm_prompt", lambda message, **kwargs: True) - result = CliRunner().invoke(cli, []) + result = CompletionRunner().invoke(cli, []) assert result.exit_code == 0, result.output assert "Installed zsh completion" in result.output assert "_MOBILERUN_COMPLETE" not in result.output @@ -136,7 +145,6 @@ def run(args: list[str], **kwargs: object) -> SimpleNamespace: def test_non_tty_unknown_shell_never_prompts(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv("SHELL", "/bin/unknown") - monkeypatch.setattr(completion, "_stdout_is_tty", lambda: False) monkeypatch.setattr( completion, "select_prompt", @@ -151,7 +159,6 @@ def test_non_tty_unknown_shell_never_prompts(monkeypatch: pytest.MonkeyPatch) -> def test_interactive_completion_decline_uses_default_no(tmp_path, monkeypatch): monkeypatch.setenv("HOME", str(tmp_path)) monkeypatch.setenv("SHELL", "/bin/zsh") - monkeypatch.setattr(completion, "_stdout_is_tty", lambda: True) monkeypatch.setattr(completion.menu, "is_interactive", lambda: True) observed = [] monkeypatch.setattr( @@ -159,7 +166,7 @@ def test_interactive_completion_decline_uses_default_no(tmp_path, monkeypatch): "confirm_prompt", lambda message, **kw: observed.append((message, kw)) or False, ) - result = CliRunner().invoke(completion.completion, []) + result = CompletionRunner().invoke(completion.completion, []) assert result.exit_code == 0 assert observed == [("Add completion to ~/.zshrc?", {"default": False})] assert not (tmp_path / ".zshrc").exists() @@ -272,31 +279,36 @@ def command(): def test_ping_missing_device_fails_on_stderr(monkeypatch): module = importlib.import_module("mobilerun.cli.devices.ping") - - async def missing(target): - return None - - monkeypatch.setattr(module.adb, "device", missing) + ping = AsyncMock(side_effect=PortalUnavailable("sensitive transport payload")) + monkeypatch.setattr(LocalDevices, "ping_portal", ping) result = CliRunner().invoke(module.ping, ["missing-device"]) + ping.assert_awaited_once_with("missing-device", tcp=False) assert result.exit_code == 1 assert result.stdout == "" - assert "missing-device" in result.stderr + assert result.stderr == "Error: missing-device: device not found\n" -def test_ping_success_names_device(monkeypatch): +def test_ping_http_failure_uses_only_safe_target_label(monkeypatch): module = importlib.import_module("mobilerun.cli.devices.ping") + monkeypatch.setenv("MOBILERUN_DEVICE_TOKEN", "token-canary") + ping = AsyncMock(side_effect=PortalUnavailable("transport-canary")) + monkeypatch.setattr(LocalDevices, "ping_portal", ping) + url = "https://user:password@example.test/path?query=canary" + result = CliRunner().invoke(module.ping, [url, "--debug"]) + ping.assert_awaited_once_with(url=url, token="token-canary") + assert result.exit_code == 1 + assert result.stdout == "" + assert ( + result.stderr == "Error: https://example.test: Portal HTTP is not reachable.\n" + ) - async def device(target): - return object() - - async def ping(*args): - pass - monkeypatch.setattr(module.adb, "device", device) - monkeypatch.setattr(module, "ping_portal", ping) - monkeypatch.setattr(module, "ping_portal_content", ping) - monkeypatch.setattr(module, "ping_portal_tcp", ping) +def test_ping_success_names_device(monkeypatch): + module = importlib.import_module("mobilerun.cli.devices.ping") + ping = AsyncMock(return_value=PortalStatus("content", True)) + monkeypatch.setattr(LocalDevices, "ping_portal", ping) result = CliRunner().invoke(module.ping, ["test-device"]) + ping.assert_awaited_once_with("test-device", tcp=False) assert result.exit_code == 0 assert "✓" in result.stdout assert "test-device" in result.stdout diff --git a/tests/unit/cli/test_webhook.py b/tests/unit/cli/test_webhook.py index 3468735f7..fa6aa210e 100644 --- a/tests/unit/cli/test_webhook.py +++ b/tests/unit/cli/test_webhook.py @@ -9,8 +9,8 @@ from pydantic import SecretStr from mobilerun.cli.app import cli -from mobilerun.core.webhooks import WebhookEndpoint from mobilerun.errors.cloud import CloudConflict +from mobilerun.models import WebhookEndpoint URL = ( "https://example.invalid:8443/path?token=private-token&opaque-sentinel&other=value" @@ -275,7 +275,7 @@ def test_flow_only_endpoint_cannot_be_reused_for_sms(hooks, flags, also_request_ ], ) def test_400_redacts_untrusted_detail(hooks, message, expected): - from mobilerun.clients.cloud.webhooks import _request + from mobilerun.core.webhooks.helpers.requests import request_webhook async def rejected(): raise BadRequestError( @@ -285,7 +285,7 @@ async def rejected(): ) async def register(*a, **kw): - return await _request(rejected(), "Register webhook") + return await request_webhook(rejected(), "Register webhook") hooks.register.side_effect = register result = invoke("register", URL, "--event-type", "test") @@ -362,7 +362,7 @@ def receiver(client, method, path, **kwargs): monkeypatch.setattr(httpx.Client, "request", receiver) hooks.register.return_value = replace(hooks.get.return_value, secret=None) with pytest.raises(pytest.fail.Exception, match="signing secret"): - test_webhook_cli_lifecycle(None) + test_webhook_cli_lifecycle(real_env=None, monkeypatch=monkeypatch) hooks.delete.assert_awaited_once_with(ID) assert calls == [("POST", "/token"), ("DELETE", f"/token/{token}")] output = capsys.readouterr() diff --git a/tests/unit/cli/test_workspace.py b/tests/unit/cli/test_workspace.py index 1a57c1ee6..f423ad142 100644 --- a/tests/unit/cli/test_workspace.py +++ b/tests/unit/cli/test_workspace.py @@ -2,22 +2,50 @@ import asyncio import json +from contextlib import asynccontextmanager +from dataclasses import replace from datetime import datetime, timezone from types import SimpleNamespace -from unittest.mock import AsyncMock, MagicMock +from unittest.mock import AsyncMock import pytest from click.testing import CliRunner +from mobilerun_core import AppIdentity, InstalledApp from mobilerun.cli.app import cli -from mobilerun.cli.base import menu, safety from mobilerun.cli.devices import device -from mobilerun.cli.devices.base import selection, source +from mobilerun.cli.devices.base import selection +from mobilerun.cli.devices.utils import approval +from mobilerun.cli.devices.utils.prompts import source from mobilerun.cli.workspace import group -from mobilerun.clients.local import login_store -from mobilerun.core.state.ios import IOSStateProvider +from mobilerun.clients.local.login_store import LoginStore from mobilerun.core.workspace import Workspace -from mobilerun.models import App, DeviceFile, WorkspaceFile +from mobilerun.models import App, WorkspaceFile +from tests.support.devices import FakeDriver, fake_device + + +@pytest.fixture +def core_owner(monkeypatch): + connect = AsyncMock(side_effect=AssertionError("unexpected device connection")) + + @asynccontextmanager + async def owner(*, hitl_gate, **kwargs): + phones = [] + + async def attach(*args, **kwargs): + phone = await connect(hitl_gate, *args, **kwargs) + phones.append(phone) + return phone + + try: + yield SimpleNamespace(connect=attach) + finally: + for phone in phones: + await phone.aclose() + + monkeypatch.setattr(selection, "AsyncMobilerun", owner) + monkeypatch.setattr(selection.LoginStore, "resolve_api_key", lambda self: "test") + return connect def test_workspace_cli_upload_list_and_delete_safety(monkeypatch, tmp_path): @@ -42,58 +70,6 @@ def test_workspace_cli_upload_list_and_delete_safety(monkeypatch, tmp_path): group.Workspace.delete_file.assert_awaited_once() -def test_device_file_cli_push_list_pull_rm(monkeypatch, tmp_path): - - driver = AsyncMock() - driver.push_file.return_value = DeviceFile( - "/sdcard/DCIM/Camera/a.png", "a.png", 3, None - ) - driver.list_files.return_value = [driver.push_file.return_value] - driver.pull_file.return_value = tmp_path / "copy.png" - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=driver)) - path = tmp_path / "a.png" - path.write_bytes(b"png") - runner = CliRunner() - for args in ( - ["push", str(path), "serial", "--android"], - ["list", "/sdcard/DCIM/Camera", "serial", "--android", "--json"], - [ - "pull", - "/sdcard/DCIM/Camera/a.png", - str(tmp_path / "copy.png"), - "serial", - "--android", - ], - ["rm", "/sdcard/DCIM/Camera/a.png", "serial", "--android", "--yes"], - ): - result = runner.invoke(cli, ["device", "file", *args]) - assert result.exit_code == 0, result.output - assert ( - driver.push_file.await_count - == driver.list_files.await_count - == driver.pull_file.await_count - == driver.delete_file.await_count - == 1 - ) - - -def test_workspace_push_accepts_positional_device(monkeypatch): - - item = WorkspaceFile("f1", "a.png", "image/png", 3, datetime.now(timezone.utc)) - driver = AsyncMock() - transfer = AsyncMock(return_value=DeviceFile("/sdcard/a.png", "a.png", 3, None)) - connect = AsyncMock(return_value=driver) - monkeypatch.setattr(selection, "connect_target", connect) - monkeypatch.setattr(Workspace, "list_files", AsyncMock(return_value=[item])) - monkeypatch.setattr(Workspace, "push_file", transfer) - result = CliRunner().invoke( - cli, ["device", "file", "push", "--file-id", "f1", "serial", "--android"] - ) - assert result.exit_code == 0, result.output - assert connect.await_args.args[0] == "serial" - transfer.assert_awaited_once_with(item, driver, None) - - def test_workspace_groups_and_old_commands_removed(): runner = CliRunner() for args in ( @@ -109,7 +85,7 @@ def test_workspace_groups_and_old_commands_removed(): def test_workspace_app_operations_and_removed_commands(monkeypatch, tmp_path): - app = App("org.example", "1", "Example", id="app1") + app = App(AppIdentity("org.example", version_name="1"), "Example", "app1") monkeypatch.setattr(group.Workspace, "list_apps", AsyncMock(return_value=[app])) monkeypatch.setattr(group.Workspace, "upload_app", AsyncMock(return_value=app)) monkeypatch.setattr(group.Workspace, "delete_app", AsyncMock()) @@ -139,25 +115,8 @@ def test_workspace_app_operations_and_removed_commands(monkeypatch, tmp_path): assert runner.invoke(cli, ["workspace", group_name, command]).exit_code != 0 -def test_install_workspace_app(monkeypatch): - - app = App("org.example", "1", "Example", id="app1") - device = AsyncMock() - device.install_app.return_value = app - monkeypatch.setattr(Workspace, "get_app", AsyncMock(return_value=app)) - connect = AsyncMock(return_value=device) - monkeypatch.setattr(selection, "connect_target", connect) - result = CliRunner().invoke( - cli, ["device", "app", "install", "--app-id", "app1", "phone", "--cloud"] - ) - assert result.exit_code == 0, result.output - assert connect.await_args.args[0] == "phone" - device.install_app.assert_awaited_once_with( - app, reinstall=False, grant_permissions=True - ) - - -def test_device_source_exclusive(monkeypatch, tmp_path): +def test_device_source_exclusive(tmp_path, core_owner): + core_owner.side_effect = lambda *args, **kwargs: fake_device() apk = tmp_path / "file.apk" apk.write_bytes(b"data") runner = CliRunner() @@ -185,22 +144,41 @@ def test_workspace_picker_uses_free_lists(monkeypatch): monkeypatch.setattr( source.Workspace, "list_apps", - AsyncMock(return_value=[App("pkg", "1", "Name", id="a")]), + AsyncMock( + return_value=[App(AppIdentity("pkg", version_name="1"), "Name", "a")] + ), ) answers = iter(["workspace", "a"]) - monkeypatch.setattr(source, "select_prompt", lambda *args: next(answers)) - assert source.select_source(None, None, apps=True) == (None, "a") + monkeypatch.setattr(source, "select_prompt_async", AsyncMock(side_effect=answers)) + assert asyncio.run(source.select_source_async(None, None, apps=True)) == (None, "a") source.Workspace.list_apps.assert_awaited_once() -def test_install_passes_options_and_closes_device(monkeypatch, tmp_path): - +def test_install_passes_options_and_closes_device(monkeypatch, tmp_path, core_owner): apk = tmp_path / "example.apk" apk.write_bytes(b"apk") - driver = AsyncMock() + close = AsyncMock() + write = AsyncMock( + return_value=InstalledApp(AppIdentity("org.example", 1, "1.0"), "Example") + ) + + async def connect(gate, *args, **kwargs): + phone = fake_device() + close.side_effect = phone.aclose + monkeypatch.setattr(phone, "aclose", close) + + async def install(source, **options): + assert await gate( + "device.install_app", + {"device_id": phone.device_id, "source": source, **options}, + ) + return await write(source, **options) + + monkeypatch.setattr(phone, "install_app", install) + return phone - driver.install_apk.return_value = App("org.example", "1.0", "Example") - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=driver)) + core_owner.side_effect = connect + monkeypatch.setattr(approval, "is_interactive", lambda: False) result = CliRunner().invoke( device, [ @@ -211,74 +189,35 @@ def test_install_passes_options_and_closes_device(monkeypatch, tmp_path): "--android", "--reinstall", "--no-grant", + "--yes", ], ) + close.assert_awaited_once_with() assert result.exit_code == 0, result.output - driver.install_apk.assert_awaited_once_with( - str(apk), reinstall=True, grant_permissions=False - ) - driver.close.assert_awaited_once_with() + write.assert_awaited_once_with(str(apk), reinstall=True, grant_permissions=False) assert "org.example 1.0" in result.output -def test_uninstall_closes_device_even_on_failure(monkeypatch): +def test_uninstall_closes_device_even_on_failure(monkeypatch, core_owner): + driver = FakeDriver(failures={"uninstall_app": RuntimeError("private detail")}) + close = AsyncMock() + + async def connect(gate, *args, **kwargs): + phone = fake_device(driver=driver, hitl_gate=gate) + close.side_effect = phone.aclose + monkeypatch.setattr(phone, "aclose", close) + return phone - driver = AsyncMock() - driver.uninstall_app.side_effect = RuntimeError("failure") - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=driver)) + core_owner.side_effect = connect result = CliRunner().invoke( device, ["app", "uninstall", "example.app", "serial", "--android", "--yes"] ) assert result.exit_code == 1 - assert "--debug" in result.output - driver.uninstall_app.assert_awaited_once_with("example.app") - driver.close.assert_awaited_once_with() - - -def test_uninstall_refuses_noninteractive_without_yes(monkeypatch): - - connect = AsyncMock() - monkeypatch.setattr(selection, "connect_target", connect) - monkeypatch.setattr(menu, "is_interactive", lambda: False) - result = CliRunner().invoke(device, ["app", "uninstall", "example.app", "serial"]) - assert result.exit_code == 1 - assert ( - "Refusing to uninstall example.app without confirmation; pass --yes." - in result.output - ) - connect.assert_not_awaited() - - -def test_uninstall_interactive_cancel_before_connect(monkeypatch): - - connect = AsyncMock() - monkeypatch.setattr(selection, "connect_target", connect) - monkeypatch.setattr(menu, "is_interactive", lambda: True) - - monkeypatch.setattr(safety, "confirm_prompt_async", AsyncMock(return_value=False)) - result = CliRunner().invoke( - device, ["app", "uninstall", "example.app", "serial"], input="n\n" - ) - assert result.exit_code == 0 - assert "example.app" in result.output and "serial" in result.output - connect.assert_not_awaited() - - -@pytest.mark.parametrize( - "interactive,args", [(True, []), (False, ["-y"])], ids=["prompt", "flag"] -) -def test_confirmed_uninstall(monkeypatch, interactive, args): - driver = AsyncMock() - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=driver)) - monkeypatch.setattr(menu, "is_interactive", lambda: interactive) - prompt = AsyncMock(return_value=True) - monkeypatch.setattr(safety, "confirm_prompt_async", prompt) - result = CliRunner().invoke( - device, ["app", "uninstall", "example.app", "serial", *args] - ) - assert result.exit_code == 0, result.output - assert prompt.await_count == int(interactive) - driver.uninstall_app.assert_awaited_once_with("example.app") + assert result.stdout == "" + assert "uninstall_app request failed" in result.stderr + assert "private detail" not in result.output + assert driver.calls == [("uninstall_app", ("example.app",), {})] + close.assert_awaited_once_with() @pytest.fixture @@ -287,12 +226,16 @@ def default_config(monkeypatch): @pytest.mark.usefixtures("default_config") -def test_workspace_id_forwards_cloud_install_options(monkeypatch): - app = App("pkg", "1", "App", id="app-id") - device = AsyncMock() - device.install_app.return_value = app +def test_workspace_id_forwards_cloud_install_options(monkeypatch, core_owner): + app = App(AppIdentity("pkg", version_name="1"), "App", "app-id") + phone = fake_device() + install = AsyncMock(return_value=InstalledApp(AppIdentity("pkg", 1, "1"), "App")) + info = replace(phone.info(), backend="cloud") + monkeypatch.setattr(phone, "info", lambda: info) + monkeypatch.setattr(phone, "install_app", install) monkeypatch.setattr(Workspace, "get_app", AsyncMock(return_value=app)) - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=device)) + core_owner.side_effect = None + core_owner.return_value = phone result = CliRunner().invoke( cli, [ @@ -305,39 +248,40 @@ def test_workspace_id_forwards_cloud_install_options(monkeypatch): "app-id", "--no-grant", "--reinstall", + "--yes", ], ) assert result.exit_code == 0, result.output - device.install_app.assert_awaited_once_with( - app, reinstall=True, grant_permissions=False + # This checks argument wiring only; a real cloud install rejects --no-grant. + install.assert_awaited_once_with( + AppIdentity("pkg", version_name="1"), + reinstall=True, + grant_permissions=False, ) @pytest.mark.usefixtures("default_config") -def test_local_workspace_id_rejected_before_connection_or_lookup(monkeypatch): - lookup, connect = AsyncMock(), AsyncMock() +def test_local_workspace_id_rejected_before_lookup(monkeypatch, core_owner): + lookup = AsyncMock() monkeypatch.setattr(Workspace, "get_app", lookup) - monkeypatch.setattr(selection, "connect_target", connect) + core_owner.side_effect = None + core_owner.return_value = fake_device() result = CliRunner().invoke( cli, ["device", "app", "install", "--device", "usb", "--app-id", "id"] ) assert result.exit_code != 0 assert "local APK" in result.stderr - connect.assert_not_awaited() lookup.assert_not_awaited() @pytest.mark.usefixtures("default_config") -def test_ios_cli_distinguishes_timeout_from_empty_tree(monkeypatch): - device = MagicMock() - device.close = AsyncMock() - device._get_ui_tree = AsyncMock(side_effect=[TimeoutError(), TimeoutError(), {}]) - provider = IOSStateProvider(device) - device._create_state_provider.return_value = provider - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=device)) - assert ( - "No UI elements available" in asyncio.run(provider.get_state()).formatted_text - ) +def test_ios_cli_distinguishes_timeout_from_empty_tree(core_owner): + failed_driver = FakeDriver(platform="ios", failures={"get_ui_tree": TimeoutError()}) + empty_driver = FakeDriver(platform="ios", ui_tree={"a11y_tree": []}) + core_owner.side_effect = [ + fake_device(driver=failed_driver, platform="ios"), + fake_device(driver=empty_driver, platform="ios"), + ] args = ["device", "screen", "ui", "--ios", "http://ios.test"] failed = CliRunner().invoke(cli, args) assert failed.exit_code != 0 @@ -350,7 +294,7 @@ def test_ios_cli_distinguishes_timeout_from_empty_tree(monkeypatch): def test_env_status_ignores_broken_credentials(monkeypatch, tmp_path): path = tmp_path / "broken" path.write_text("{") - monkeypatch.setattr(login_store, "credential_path", lambda: path) + monkeypatch.setattr(LoginStore, "from_settings", lambda: LoginStore(path)) result = CliRunner().invoke( cli, ["account", "status", "--json"], env={"MOBILERUN_API_KEY": "test-only-key"} ) diff --git a/tests/unit/clients/cloud/test_apps.py b/tests/unit/clients/cloud/test_apps.py index 5042e883e..a2eef1bd5 100644 --- a/tests/unit/clients/cloud/test_apps.py +++ b/tests/unit/clients/cloud/test_apps.py @@ -1,216 +1,69 @@ -"""Cloud app installation, SDK requests, and upload contracts.""" +"""Cloud app library and APK upload contracts.""" import asyncio +import logging import traceback from types import SimpleNamespace from unittest.mock import AsyncMock import httpx import pytest -from mobilerun_sdk import AsyncMobilerun +from mobilerun_core import AppIdentity, AsyncMobilerun, UploadedApp, cloud_error_facts +from mobilerun_core.errors import AppOperationError, CloudRequestError -import mobilerun.core.devices.components.cloud_apps as cloud -from mobilerun.clients.cloud import apps +from mobilerun.clients.cloud import client as cloud_connection from mobilerun.clients.local import apk as local_apk -from mobilerun.core.devices.base import Device -from mobilerun.core.devices.cloud import CloudDevice -from mobilerun.core.devices.pool import DevicePool -from mobilerun.core.devices.recording import RecordingDevice -from mobilerun.core.devices.stealth import StealthDevice -from mobilerun.errors import CloudConnectionError, DeviceOperationNotSupported -from mobilerun.models.apps import App +from mobilerun.core.workspace import Workspace +from mobilerun.errors import CloudConnectionError from mobilerun.models.billing import Billing -def test_cloud_install_by_path_and_id(monkeypatch, tmp_path): - - apk = tmp_path / "test.apk" - apk.write_bytes(b"apk") - app = App("org.example", "1.0", "Example", id="app-id", version_code=4) - upload = AsyncMock(return_value=app) - monkeypatch.setattr(cloud, "upload_app", upload) - device = CloudDevice(device_id="device-id", api_key="test") - device._client = SimpleNamespace( - api_key="test", - base_url="https://example.test", - apps=SimpleNamespace( - retrieve=AsyncMock( - return_value=SimpleNamespace( - data=SimpleNamespace( - bundle_id="org.example", display_name="Example" - ) - ) - ) - ), - devices=SimpleNamespace( - apps=SimpleNamespace( - install=AsyncMock(), - delete=AsyncMock(), - list_installs=AsyncMock( - side_effect=[ - SimpleNamespace(installs=[]), - SimpleNamespace( - installs=[ - SimpleNamespace( - app_id="org.example", - status="succeeded", - started_at=1, - ) - ] - ), - SimpleNamespace(installs=[]), - SimpleNamespace( - installs=[ - SimpleNamespace( - app_id="org.example", - status="succeeded", - started_at=2, - ) - ] - ), - ] - ), - ) - ), - ) - device.list_apps = AsyncMock( - return_value=[{"package_name": "org.example", "version_code": 4}] - ) - asyncio.run(device.install_apk(apk)) - upload.assert_awaited_once() - device._client.devices.apps.install.assert_awaited_with( - "device-id", package_name="org.example", version_code=4, background=True - ) - asyncio.run(device.install_app(app)) - device._client.apps.retrieve.assert_not_awaited() - device._client.devices.apps.install.assert_awaited_with( - "device-id", package_name="org.example", version_code=4, background=True - ) - asyncio.run(device.uninstall_app("org.example")) - device._client.devices.apps.delete.assert_awaited_once_with( - "org.example", device_id="device-id", extra_body={} +def test_workspace_delegates_app_upload_and_normalizes_empty_version( + monkeypatch, tmp_path +): + apk = tmp_path / "sample.apk" + sdk = AsyncMock() + upload = AsyncMock( + return_value=UploadedApp("app-id", AppIdentity("org.example", 3, ""), "Example") ) + monkeypatch.setattr(AsyncMobilerun, "upload_app", upload) + app = asyncio.run(Workspace(client=sdk).upload_app(apk)) + upload.assert_awaited_once_with(apk, client=sdk) + assert app.identity == AppIdentity("org.example", 3) + assert (app.resource_id, app.name, app.path) == ("app-id", "Example", apk) + sdk.__aexit__.assert_not_awaited() -def test_wrappers_and_pool_forward_cloud_app(): - - class Fake(Device): - platform = "android" - capabilities = set() - supported_buttons = set() - _ui_state_view = SimpleNamespace(_provider=None) - operator = None - _is_cloud = True - install_app = AsyncMock(return_value="ok") - uninstall_app = AsyncMock(return_value="removed") - - async def run(): - fake = Fake() - app = App("org.example", "1", "Example", id="app-id", version_code=4) - pool = DevicePool([RecordingDevice(fake), StealthDevice(fake)]) - assert await pool.install_app(app) == ["ok", "ok"] - assert await pool.uninstall_app("org.example") == ["removed", "removed"] - assert fake.install_app.await_count == 2 - assert fake.uninstall_app.await_count == 2 - - asyncio.run(run()) - - -@pytest.mark.parametrize( - "options, message", - [({"grant_permissions": False}, "grant"), ({"reinstall": True}, "reinstall")], - ids=["grant-permissions", "reinstall"], -) -def test_cloud_install_rejects_unsupported_install_options(options, message): - - device = CloudDevice(device_id="device-id", api_key="test") - with pytest.raises(DeviceOperationNotSupported, match=message): - asyncio.run(device.install_app(App("p", "", "P", id="app-id"), **options)) - - -def test_uninstall_sends_required_empty_json_body(): - requests = [] - - async def respond(request): - requests.append(request) - return httpx.Response(204, request=request) - - async def run(): - http = httpx.AsyncClient(transport=httpx.MockTransport(respond)) - async with AsyncMobilerun( - api_key="test", base_url="https://example.test/v1", http_client=http - ) as client: - await apps.uninstall( - client, "ai.example.app", billing=Billing.NO_COMMERCE, device_id="phone" - ) - - asyncio.run(run()) - assert len(requests) == 1 - assert requests[0].method == "DELETE" - assert requests[0].url.path == "/v1/devices/phone/apps/ai.example.app" - assert requests[0].content == b"{}" - - -def test_cloud_stop_uses_sdk_and_display_without_clearing_data(): - device = CloudDevice(device_id="phone", api_key="test", display_id=7) - device._ensure_connected = AsyncMock() - stop = AsyncMock() - device._write_client = SimpleNamespace( - devices=SimpleNamespace(apps=SimpleNamespace(stop=stop)) - ) +def test_upload_maps_core_failure_and_closes_owned_sdk(monkeypatch, tmp_path, caplog): + apk = tmp_path / "sample.apk" + client = AsyncMock() - assert asyncio.run(device.stop_app("ai.example.app")) == "Stopped ai.example.app" - stop.assert_awaited_once_with( - "ai.example.app", device_id="phone", x_device_display_id=7 - ) - assert "stop_app" in device.supported_operations + def connect(api_key, base_url, *, billing): + assert (api_key, base_url, billing) == ( + "test", + "https://account.test", + Billing.INCLUDED, + ) + return client + monkeypatch.setattr(cloud_connection, "cloud_client", connect) + url = "https://signed.test?token=upload-signature-canary" + caplog.set_level(logging.INFO, logger="httpx") -def test_upload_confirms_and_marks_failure(monkeypatch, tmp_path): + async def upload(_core, path, *, client): + logging.getLogger("httpx").info("PUT %s", url) + error = CloudRequestError(cloud_error_facts(httpx.ConnectError(url))) + raise AppOperationError("APK upload request failed") from error - apk = tmp_path / "sample.apk" - apk.write_bytes(b"apk") - monkeypatch.setattr( - apps, "inspect_apk", lambda path: ("org.example", 3, "1.2", "Example") - ) - signed = SimpleNamespace( - app_id="app-id", - version_id="version-id", - r2_upload_urls=[ - SimpleNamespace(file_name="sample.apk", r2_upload_url="https://upload") - ], - ) - sdk = SimpleNamespace( - apps=SimpleNamespace( - list=AsyncMock( - return_value=SimpleNamespace( - items=[], pagination=SimpleNamespace(has_next=False) - ) - ), - create_signed_upload_url=AsyncMock(return_value=signed), - confirm_upload=AsyncMock(), - mark_failed=AsyncMock(), - ) - ) - client = AsyncMock() - client.__aenter__.return_value = sdk - monkeypatch.setattr(apps, "cloud_client", lambda *args, **kwargs: client) - http = AsyncMock() - http.__aenter__.return_value = http - http.put.return_value = SimpleNamespace(raise_for_status=lambda: None) - monkeypatch.setattr(apps.httpx, "AsyncClient", lambda **kwargs: http) - result = asyncio.run(apps.upload_app(apk, billing="included", api_key="test")) - assert result.id == "app-id" - sdk.apps.confirm_upload.assert_awaited_once_with("version-id") - http.put.side_effect = RuntimeError("upload failed") - with pytest.raises(RuntimeError, match="upload failed"): - asyncio.run(apps.upload_app(apk, billing="included", api_key="test")) - sdk.apps.mark_failed.assert_awaited_once_with("version-id") - sdk.apps.mark_failed.reset_mock() - token = "upload-signature-canary" - http.put.side_effect = httpx.ConnectError(f"https://signed.test?token={token}") + monkeypatch.setattr(AsyncMobilerun, "upload_app", upload) with pytest.raises(CloudConnectionError) as raised: - asyncio.run(apps.upload_app(apk, billing="included", api_key="test")) + asyncio.run( + Workspace( + billing=Billing.INCLUDED, + api_key="test", + base_url="https://account.test", + ).upload_app(apk) + ) error = raised.value for rendered in ( str(error), @@ -218,37 +71,9 @@ def test_upload_confirms_and_marks_failure(monkeypatch, tmp_path): "".join(traceback.format_exception(error)), ): assert "signed.test" not in rendered - assert token not in rendered - sdk.apps.mark_failed.assert_awaited_once_with("version-id") - - -def test_app_items_paginates(): - - item = SimpleNamespace( - id="id", - bundle_id="org.example", - display_name="Example", - version=SimpleNamespace(version_name="1", version_code=3), - ) - client = SimpleNamespace( - apps=SimpleNamespace( - list=AsyncMock( - side_effect=[ - SimpleNamespace( - items=[], pagination=SimpleNamespace(has_next=True) - ), - SimpleNamespace( - items=[item], pagination=SimpleNamespace(has_next=False) - ), - ] - ) - ) - ) - - assert asyncio.run(apps.list_apps(client, billing=Billing.NO_COMMERCE)) == [ - App("org.example", "1", "Example", id="id", version_code=3) - ] - assert [call.kwargs["page"] for call in client.apps.list.await_args_list] == [1, 2] + assert "upload-signature-canary" not in rendered + assert "upload-signature-canary" not in caplog.text + client.__aexit__.assert_awaited_once() def test_apk_metadata_from_build_tools(monkeypatch, tmp_path): diff --git a/tests/unit/clients/cloud/test_billing_retry.py b/tests/unit/clients/cloud/test_billing_retry.py index 9c7160261..c6d5a0487 100644 --- a/tests/unit/clients/cloud/test_billing_retry.py +++ b/tests/unit/clients/cloud/test_billing_retry.py @@ -12,10 +12,11 @@ import pytest from prompt_toolkit import PromptSession -from mobilerun.clients.cloud import billing as policy +from mobilerun.clients.cloud.billing_policy import BillingPolicy from mobilerun.errors import BillingError, BillingRequired from mobilerun.errors.base import is_value_safe from mobilerun.models.billing import Billing +from mobilerun.utils.billing.retry import with_billing_retry @pytest.mark.parametrize( @@ -35,7 +36,7 @@ def test_retry_only_runs_after_consent( effects = [] replies = [] - @policy.requires(Billing.PAID, operation="Buy Connect proxy") + @BillingPolicy.guard(Billing.PAID, operation="Buy Connect proxy") async def purchase(*, billing): effects.append(billing) return "proxy-id" @@ -54,14 +55,14 @@ async def respond(self, message): monkeypatch.setattr(sys.stderr, "isatty", lambda: tty) monkeypatch.setattr(PromptSession, "prompt_async", respond) if expected[-1] is Billing.PAID: - assert asyncio.run(policy.with_billing_retry(operation, mode, yes=yes)) == ( + assert asyncio.run(with_billing_retry(operation, mode, yes=yes)) == ( "proxy-id", Billing.PAID, ) assert effects == [Billing.PAID] else: with pytest.raises(BillingRequired) as caught: - asyncio.run(policy.with_billing_retry(operation, mode, yes=yes)) + asyncio.run(with_billing_retry(operation, mode, yes=yes)) error = caught.value assert (error.needed, error.given, error.operation) == ( Billing.PAID, @@ -95,7 +96,7 @@ async def operation(billing): raise failure with pytest.raises(second_failure) as caught: - asyncio.run(policy.with_billing_retry(operation, Billing.INCLUDED, yes=True)) + asyncio.run(with_billing_retry(operation, Billing.INCLUDED, yes=True)) assert caught.value is failure assert attempts == ( [Billing.INCLUDED, Billing.PAID] @@ -117,11 +118,11 @@ def test_nested_guard_rejects_second_attempt_with_explicit_billing_hint(): attempts = [] mutations = [] - @policy.requires(Billing.PAID, operation="Send SMS") + @BillingPolicy.guard(Billing.PAID, operation="Send SMS") async def send(*, billing): mutations.append(billing) - @policy.requires(Billing.INCLUDED, operation="Run cloud task") + @BillingPolicy.guard(Billing.INCLUDED, operation="Run cloud task") async def prepare(*, billing): await send(billing=billing) @@ -130,7 +131,7 @@ def operation(mode): return prepare(billing=mode) with pytest.raises(BillingRequired) as caught: - asyncio.run(policy.with_billing_retry(operation, Billing.NO_COMMERCE, yes=True)) + asyncio.run(with_billing_retry(operation, Billing.NO_COMMERCE, yes=True)) error = caught.value assert (error.given, error.needed, error.operation) == ( Billing.INCLUDED, @@ -148,10 +149,11 @@ def test_sdk_prompt_sigint_exits_without_enter(): master, slave = pty.openpty() script = """ import asyncio -from mobilerun.clients.cloud.billing import requires, with_billing_retry +from mobilerun.clients.cloud.billing_policy import BillingPolicy +from mobilerun.utils.billing.retry import with_billing_retry from mobilerun.models.billing import Billing -@requires(Billing.PAID) +@BillingPolicy.guard(Billing.PAID) async def purchase(*, billing): raise AssertionError('purchase must not run') @@ -197,13 +199,13 @@ async def purchase(*, billing): def test_retry_uses_exact_guard_minimum(monkeypatch, capsys, given, needed): attempts = [] - @policy.requires(needed, operation="Create cloud phone") - async def create(*, billing): + @BillingPolicy.guard(needed, operation="Buy Connect proxy") + async def purchase(*, billing): return billing def operation(billing): attempts.append(billing) - return create(billing=billing) + return purchase(billing=billing) async def respond(self, message): sys.stderr.write(message) @@ -212,7 +214,7 @@ async def respond(self, message): monkeypatch.setattr(sys.stdin, "isatty", lambda: True) monkeypatch.setattr(sys.stderr, "isatty", lambda: True) monkeypatch.setattr(PromptSession, "prompt_async", respond) - assert asyncio.run(policy.with_billing_retry(operation, given)) == (needed, needed) + assert asyncio.run(with_billing_retry(operation, given)) == (needed, needed) assert attempts[0] is Billing(given) and attempts[1] is needed prompt = capsys.readouterr().err assert f"{needed.value} billing" in prompt @@ -222,7 +224,7 @@ async def respond(self, message): def test_truthy_yes_does_not_authorize_noninteractive_retry(): attempts = [] - @policy.requires(Billing.PAID, operation="Send SMS") + @BillingPolicy.guard(Billing.PAID, operation="Send SMS") async def send(*, billing): pytest.fail("unapproved charge") @@ -232,7 +234,7 @@ def operation(billing): with pytest.raises(BillingRequired): asyncio.run( - policy.with_billing_retry( + with_billing_retry( operation, Billing.INCLUDED, yes="false", is_interactive=lambda: False ) ) @@ -245,7 +247,7 @@ def operation(billing): def test_sdk_does_not_prompt_without_visible_terminal( monkeypatch, stdin_tty, stderr_tty ): - @policy.requires(Billing.PAID, operation="Send SMS") + @BillingPolicy.guard(Billing.PAID, operation="Send SMS") async def send(*, billing): pytest.fail("unapproved charge") @@ -262,67 +264,33 @@ def unexpected_prompt(*args, **kwargs): ) with pytest.raises(BillingRequired, match="--billing paid"): asyncio.run( - policy.with_billing_retry( - lambda mode: send(billing=mode), Billing.INCLUDED - ) + with_billing_retry(lambda mode: send(billing=mode), Billing.INCLUDED) ) -def test_guard_rule_is_declared_not_inferred_from_names(): - def create(*, billing, plan=None, proxy=None): - return billing +@pytest.mark.parametrize("plan", ["auto", "included", None]) +def test_included_policy_allows_non_rental_plans(plan): + assert ( + BillingPolicy(Billing.INCLUDED).require( + Billing.INCLUDED, "Create number", plan=plan + ) + is Billing.INCLUDED + ) - # Names that used to trigger built-in rules must not change the minimum. - create.__module__ = "mobilerun.clients.cloud.devices" - undeclared = policy.requires(Billing.INCLUDED)(create) - declared = policy.requires( - Billing.INCLUDED, paid_if=lambda arguments: arguments["plan"] == "minute" - )(create) - connect = {"connect": {"country": "US"}} - assert undeclared(billing="included", plan="minute", proxy=connect) is ( - Billing.INCLUDED - ) - assert declared(billing="included", plan="subscription") is Billing.INCLUDED - assert declared(billing="paid", plan="minute") is Billing.PAID +def test_included_policy_rejects_rental(): with pytest.raises(BillingRequired) as raised: - declared(billing="included", plan="minute") + BillingPolicy(Billing.INCLUDED).require( + Billing.INCLUDED, "Create number", plan="rent" + ) assert raised.value.needed is Billing.PAID assert raised.value.given is Billing.INCLUDED -def test_guard_rule_rejects_invalid_input_before_the_call(): - def unusable(arguments): - raise ValueError("not a plan") - - @policy.requires(Billing.INCLUDED, paid_if=unusable) - def create(*, billing, plan=None): - pytest.fail("guard must refuse first") - +def test_invalid_plan_is_a_billing_error(): with pytest.raises(BillingError) as raised: - create(billing="paid", plan="weekly") + BillingPolicy(Billing.PAID).require( + Billing.INCLUDED, "Create number", plan="weekly" + ) assert raised.value.code == "invalid_billing" assert not isinstance(raised.value, BillingRequired) - - -@pytest.mark.parametrize( - "proxy,expected", - [ - ({"connect": {"country": "US"}}, True), - ({"connect": {"id": "proxy-1"}}, False), - ({"connect": {"country": ""}}, False), - ({"socks5": {"host": "127.0.0.1", "port": 1080}}, False), - ({"connect": "US"}, False), - (None, False), - ], -) -def test_only_a_new_connect_proxy_by_country_is_a_purchase(proxy, expected): - assert policy.buys_connect_proxy(proxy) is expected - - -@pytest.mark.parametrize( - "plan,expected", - [("rent", True), ("auto", False), ("included", False), (None, False)], -) -def test_only_the_rent_plan_is_a_rental(plan, expected): - assert policy.rents_resource({"plan": plan}) is expected diff --git a/tests/unit/clients/cloud/test_bound_commerce.py b/tests/unit/clients/cloud/test_bound_commerce.py new file mode 100644 index 000000000..e114a5dec --- /dev/null +++ b/tests/unit/clients/cloud/test_bound_commerce.py @@ -0,0 +1,68 @@ +"""Checkout resumes without reusing or cancelling the original client's purchase.""" + +import asyncio +from contextlib import asynccontextmanager +from types import SimpleNamespace as NS +from unittest.mock import AsyncMock + +import pytest + +from mobilerun.clients.cloud import client as connection +from mobilerun.clients.cloud import mailboxes, proxies +from mobilerun.errors import PaymentRequired +from mobilerun.models.billing import Billing + + +@pytest.mark.parametrize("kind", ["mailbox", "proxy"]) +def test_checkout_resume_opens_a_read_only_client(monkeypatch, kind): + checkout_url = "https://example.test/pay" + cancel = AsyncMock() + create = AsyncMock( + return_value=NS( + data=NS( + id="box", + status="awaiting_payment", + checkout_url=checkout_url, + checkout_expires_at=None, + ) + ) + ) + buy = AsyncMock( + return_value=NS(id="proxy", status="pending_payment", payment_url=checkout_url) + ) + paid = NS( + mailboxes=NS(create=create, delete=cancel), + connect=NS(proxies=NS(buy=buy, cancel=cancel)), + ) + mailbox = NS(data=NS(status="active", checkout_url=None, checkout_expires_at=None)) + proxy = NS(status="active", payment_url=None) + read = NS( + mailboxes=NS(retrieve=AsyncMock(return_value=mailbox)), + connect=NS(proxies=NS(retrieve=AsyncMock(return_value=proxy))), + ) + events = [] + + @asynccontextmanager + async def open_sdk(api_key, base_url, *, billing): + events.append(("open", billing)) + try: + yield paid if billing is Billing.PAID else read + finally: + events.append(("close", billing)) + + monkeypatch.setattr(connection, "cloud_client", open_sdk) + + async def run(): + with pytest.raises(PaymentRequired) as error: + if kind == "mailbox": + await mailboxes.Mailboxes(billing=Billing.PAID).create() + else: + await proxies.Proxies(billing=Billing.PAID).buy("US") + assert events == [("open", Billing.PAID), ("close", Billing.PAID)] + assert await error.value.wait_until_paid() is ( + mailbox if kind == "mailbox" else proxy + ) + + asyncio.run(run()) + assert events[2:] == [("open", Billing.NO_COMMERCE), ("close", Billing.NO_COMMERCE)] + cancel.assert_not_awaited() diff --git a/tests/unit/clients/cloud/test_bound_vault_task_keys.py b/tests/unit/clients/cloud/test_bound_vault_task_keys.py new file mode 100644 index 000000000..3746ec671 --- /dev/null +++ b/tests/unit/clients/cloud/test_bound_vault_task_keys.py @@ -0,0 +1,65 @@ +"""Offline contracts for bound vault, task and API-key operations.""" + +import asyncio +import traceback +from contextlib import nullcontext +from types import SimpleNamespace as NS +from unittest.mock import AsyncMock + +import httpx +import pytest +from mobilerun_sdk import APIStatusError + +from mobilerun.clients.cloud import api_keys, client, secrets, tasks +from mobilerun.errors import BillingRequired, CloudPermissionDenied +from mobilerun.models.billing import Billing + + +def test_api_key_validation_uses_the_explicit_key_v1_path_and_call_timeout(monkeypatch): + endpoint = AsyncMock() + + def connect(key, base_url, *, billing): + assert (key, base_url, billing) == ( + "fake-key", + "https://example.invalid/api/v1", + Billing.NO_COMMERCE, + ) + return nullcontext(NS(devices=NS(list=endpoint))) + + monkeypatch.setenv("MOBILERUN_CLOUD_BASE_URL", "https://example.invalid/api/") + monkeypatch.setenv("MOBILERUN_CLOUD_API_TIMEOUT", "1.25") + monkeypatch.setattr(client, "cloud_client", connect) + asyncio.run(api_keys.ApiKeys(api_key="fake-key", billing="no_commerce").validate()) + endpoint.assert_awaited_once_with(page_size=1, timeout=1.25) + + +def test_bound_task_can_poll_but_cannot_submit_under_no_commerce(): + status = NS(status="running") + submit = AsyncMock(side_effect=AssertionError("task submission spends credits")) + resource = tasks.Tasks( + client=NS(tasks=NS(run=submit, get_status=AsyncMock(return_value=status))), + billing="no_commerce", + ) + assert asyncio.run(resource.status("task-id")) is status + with pytest.raises(BillingRequired, match="requires billing='included'"): + asyncio.run(resource.run(device_id="phone", task="do not submit")) + submit.assert_not_awaited() + + +def test_bound_vault_write_drops_the_original_sdk_exception(): + canary = "private-vault-write-test-value" + request = httpx.Request("PATCH", "https://example.invalid") + error = APIStatusError( + canary, response=httpx.Response(403, request=request), body={"echo": canary} + ) + endpoint = AsyncMock(side_effect=error) + resource = secrets.Vault( + client=NS( + credentials=NS(packages=NS(credentials=NS(fields=NS(update=endpoint)))) + ), + billing="no_commerce", + ) + with pytest.raises(CloudPermissionDenied) as raised: + asyncio.run(resource.update("pkg", "login", "password", canary)) + assert raised.value.__cause__ is raised.value.__context__ is None + assert canary not in "".join(traceback.format_exception(raised.value)) diff --git a/tests/unit/clients/cloud/test_checkout.py b/tests/unit/clients/cloud/test_checkout.py index 562320b40..646de6fd9 100644 --- a/tests/unit/clients/cloud/test_checkout.py +++ b/tests/unit/clients/cloud/test_checkout.py @@ -10,14 +10,10 @@ import pytest from mobilerun_sdk import APIStatusError +from mobilerun.clients.cloud import client as cloud_connection from mobilerun.clients.cloud import mailboxes, numbers, proxies -from mobilerun.clients.cloud.billing import with_billing_retry from mobilerun.clients.cloud.client import AsyncMobilerun -from mobilerun.clients.cloud.payments import ( - PaymentAdapter, - wait_for_payment, - wait_until_active, -) +from mobilerun.clients.cloud.payments import PaymentFlow from mobilerun.core.mailbox.cloud import CloudMailbox from mobilerun.core.phone_number.cloud import CloudPhoneNumber from mobilerun.errors import ( @@ -28,6 +24,7 @@ from mobilerun.errors.cloud import BillingError from mobilerun.models.billing import Billing from mobilerun.models.checkout import PaymentSnapshot +from mobilerun.utils.billing.retry import with_billing_retry def _plan_client(create): @@ -35,6 +32,11 @@ def _plan_client(create): return NS(numbers=endpoint, mailboxes=endpoint) +def _creator(resource, billing, client=None): + adapter = numbers.Numbers if resource is numbers else mailboxes.Mailboxes + return adapter(billing=billing, client=client).create + + @pytest.mark.parametrize("resource", [numbers, mailboxes]) @pytest.mark.parametrize( "billing,plan,expected", @@ -60,7 +62,7 @@ def test_create_preference(resource, billing, plan, expected): create = AsyncMock(return_value=NS(data=data)) client = _plan_client(create) kwargs = {} if plan is None else {"plan": plan} - asyncio.run(resource.create(billing=billing, client=client, **kwargs)) + asyncio.run(_creator(resource, billing, client)(**kwargs)) assert create.await_args.kwargs["billing_preference"] == expected @@ -70,7 +72,7 @@ def test_rent_requires_paid(resource, billing): create = AsyncMock() client = _plan_client(create) with pytest.raises(BillingRequired) as exc: - asyncio.run(resource.create(billing=billing, client=client, plan="rent")) + asyncio.run(_creator(resource, billing, client)(plan="rent")) assert (exc.value.needed, exc.value.given) == (Billing.PAID, Billing(billing)) create.assert_not_awaited() @@ -90,9 +92,7 @@ async def confirm(error): result, mode = asyncio.run( with_billing_retry( - lambda billing: resource.create( - billing=billing, client=client, plan="rent" - ), + lambda billing: _creator(resource, billing, client)(plan="rent"), Billing.INCLUDED, prompt=confirm, is_interactive=lambda: True, @@ -116,9 +116,7 @@ def test_included_capacity_failure_never_replays_transport(resource): with pytest.raises(IncludedCapacityUnavailable): asyncio.run( with_billing_retry( - lambda billing: resource.create( - billing=billing, client=client, plan="auto" - ), + lambda billing: _creator(resource, billing, client)(plan="auto"), Billing.INCLUDED, yes=True, ) @@ -132,7 +130,7 @@ def test_authorized_proxy_purchase_reaches_transport_only_once(monkeypatch): context = AsyncMock() context.__aenter__.return_value = NS(connect=NS(proxies=NS(buy=buy))) client = Mock(return_value=context) - monkeypatch.setattr(proxies, "cloud_client", client) + monkeypatch.setattr(cloud_connection, "cloud_client", client) async def confirm(error): assert error.needed is Billing.PAID @@ -142,7 +140,7 @@ async def confirm(error): result = asyncio.run( with_billing_retry( - lambda billing: proxies.buy_proxy("US", billing=billing), + lambda billing: proxies.Proxies(billing=billing).buy("US"), Billing.INCLUDED, prompt=confirm, is_interactive=lambda: True, @@ -158,7 +156,7 @@ def test_invalid_plan_rejected_before_sdk(resource): create = AsyncMock() client = _plan_client(create) with pytest.raises(ValueError): - asyncio.run(resource.create(billing="paid", client=client, plan="invalid")) + asyncio.run(_creator(resource, "paid", client)(plan="invalid")) create.assert_not_awaited() @@ -169,9 +167,7 @@ def test_billing_preference_cannot_be_smuggled(resource, field): client = _plan_client(create) with pytest.raises(BillingError) as exc: asyncio.run( - resource.create( - billing="paid", - client=client, + _creator(resource, "paid", client)( plan="rent", **{field: {"billing_preference": "included"}}, ) @@ -181,7 +177,8 @@ def test_billing_preference_cannot_be_smuggled(resource, field): @pytest.mark.parametrize( - "cls,resource", [(CloudPhoneNumber, numbers), (CloudMailbox, mailboxes)] + "cls,resource", + [(CloudPhoneNumber, numbers.Numbers), (CloudMailbox, mailboxes.Mailboxes)], ) @pytest.mark.parametrize("plan", ["auto", "included", "rent"]) def test_core_forwards_plan(monkeypatch, cls, resource, plan): @@ -204,7 +201,8 @@ async def run(): @pytest.mark.parametrize( - "cls,resource", [(CloudPhoneNumber, numbers), (CloudMailbox, mailboxes)] + "cls,resource", + [(CloudPhoneNumber, numbers.Numbers), (CloudMailbox, mailboxes.Mailboxes)], ) @pytest.mark.parametrize( "status,expected", [("available", 3), ("exhausted", 0), ("not_included", 0)] @@ -223,7 +221,7 @@ def test_included_available(monkeypatch, cls, resource, status, expected): asyncio.run(cls.included_available(*args, billing="no_commerce", client=client)) == expected ) - capacity.assert_awaited_once_with(*args, billing="no_commerce", client=client) + capacity.assert_awaited_once_with(*args) def test_resource_plan_public_export(): @@ -239,7 +237,8 @@ def test_constructor_rejects_invalid_plan_eagerly(cls): @pytest.mark.parametrize( - "cls,resource", [(CloudPhoneNumber, numbers), (CloudMailbox, mailboxes)] + "cls,resource", + [(CloudPhoneNumber, numbers.Numbers), (CloudMailbox, mailboxes.Mailboxes)], ) def test_existing_resource_does_not_create(monkeypatch, cls, resource): data = NS( @@ -263,36 +262,31 @@ async def run(): retrieve.assert_awaited_once() -@pytest.mark.parametrize("kind", ["number", "mailbox", "proxy"]) +@pytest.mark.parametrize("kind", ["number", "mailbox"]) @pytest.mark.parametrize("keep", [False, True]) -def test_payment_required_preserves_resource(monkeypatch, kind, keep): +def test_payment_required_preserves_resource(kind, keep): url = "https://checkout.example.test/pay" data = NS( number_id="id", id="id", state="awaiting_payment", - status="pending_payment" if kind == "proxy" else "awaiting_payment", + status="awaiting_payment", checkout_url=url, checkout_expires_at=None, - payment_url=url, ) - create = AsyncMock(return_value=data if kind == "proxy" else NS(data=data)) + create = AsyncMock(return_value=NS(data=data)) cancel = AsyncMock() sdk = NS( numbers=NS(create=create, delete=cancel), mailboxes=NS(create=create, delete=cancel), - connect=NS(proxies=NS(buy=create, cancel=cancel)), ) - context = AsyncMock() - context.__aenter__.return_value = sdk - monkeypatch.setattr(proxies, "cloud_client", lambda *args, **kwargs: context) async def run(): with pytest.raises(PaymentRequired) as caught: - if kind == "proxy": - await proxies.buy_proxy("US", billing=Billing.PAID, keep=keep) + if kind == "number": + await CloudPhoneNumber(client=sdk, billing=Billing.PAID, keep=keep) else: - await (numbers if kind == "number" else mailboxes).create( + await CloudMailbox( client=cast(AsyncMobilerun, sdk), billing=Billing.PAID, keep=keep ) assert caught.value.payment_url == url @@ -309,8 +303,10 @@ def test_nonpayment_proxy_response_is_unchanged(monkeypatch): endpoint = NS(buy=AsyncMock(return_value=response), cancel=AsyncMock()) context = AsyncMock() context.__aenter__.return_value = NS(connect=NS(proxies=endpoint)) - monkeypatch.setattr(proxies, "cloud_client", lambda *args, **kwargs: context) - assert asyncio.run(proxies.buy_proxy("US", billing=Billing.PAID)) is response + monkeypatch.setattr( + cloud_connection, "cloud_client", lambda *args, **kwargs: context + ) + assert asyncio.run(proxies.Proxies(billing=Billing.PAID).buy("US")) is response endpoint.cancel.assert_not_awaited() @@ -350,10 +346,10 @@ def test_delayed_checkout_is_reported_without_cancel(monkeypatch): ) with pytest.raises(PaymentRequired) as caught: asyncio.run( - mailboxes.create( + mailboxes.Mailboxes( client=cast(AsyncMobilerun, NS(mailboxes=endpoint)), billing=Billing.PAID, - ) + ).create() ) assert caught.value.payment_url == "https://example.test/pay" assert caught.value.checkout_expires_at == expiry @@ -394,11 +390,10 @@ def test_interactive_checkout_waits_until_active(monkeypatch, capsys): ) callback = AsyncMock() asyncio.run( - mailboxes.create( + mailboxes.Mailboxes( client=cast(AsyncMobilerun, NS(mailboxes=endpoint)), billing=Billing.PAID, - on_checkout=callback, - ) + ).create(on_checkout=callback) ) callback.assert_awaited_once() assert not capsys.readouterr().out @@ -409,66 +404,55 @@ def test_left_payment_without_url_is_error(monkeypatch): from mobilerun.errors import CloudError monkeypatch.setattr(asyncio, "sleep", AsyncMock()) - cancel = AsyncMock() - adapter = PaymentAdapter( - "mailbox", "box", AsyncMock(return_value=PaymentSnapshot("failed")), cancel + adapter = PaymentFlow( + "mailbox", "box", AsyncMock(return_value=PaymentSnapshot("failed")) ) with pytest.raises(CloudError, match="without a checkout URL"): asyncio.run( - wait_for_payment( - adapter, PaymentSnapshot("awaiting_payment"), resume=AsyncMock() + adapter.wait_for_payment( + PaymentSnapshot("awaiting_payment"), resume=AsyncMock() ) ) - cancel.assert_not_awaited() -def test_checkout_budget_and_interactive_timeout_cancel(monkeypatch): - monkeypatch.setattr("webbrowser.open", lambda url: True) - cancel = AsyncMock() - adapter = PaymentAdapter("mailbox", "box", AsyncMock(), cancel) +def test_checkout_budget_and_interactive_timeout_report_recovery_id(): + adapter = PaymentFlow("mailbox", "box", AsyncMock()) with pytest.raises(TimeoutError, match="box.*check the dashboard"): asyncio.run( - wait_for_payment( - adapter, + adapter.wait_for_payment( PaymentSnapshot("awaiting_payment"), resume=AsyncMock(), checkout_timeout=0, ) ) - cancel.assert_not_awaited() with pytest.raises(TimeoutError, match="box.*check the dashboard"): asyncio.run( - wait_for_payment( - adapter, + adapter.wait_for_payment( PaymentSnapshot("awaiting_payment", "https://example.test"), on_checkout=lambda checkout: None, resume=AsyncMock(), timeout=0, ) ) - cancel.assert_awaited_once() -def test_interactive_cancellation_cancels_pending(monkeypatch): +def test_interrupted_activation_keeps_provisioning_resource(monkeypatch): monkeypatch.setattr("webbrowser.open", lambda url: True) monkeypatch.setattr(asyncio, "sleep", AsyncMock(side_effect=asyncio.CancelledError)) - cancel = AsyncMock() - adapter = PaymentAdapter( + adapter = PaymentFlow( "mailbox", "box", AsyncMock(return_value=PaymentSnapshot("provisioning")), - cancel, ) - with pytest.raises(asyncio.CancelledError): + with pytest.raises(asyncio.CancelledError) as err: asyncio.run( - wait_for_payment( - adapter, + adapter.wait_for_payment( PaymentSnapshot("awaiting_payment", "https://example.test"), on_checkout=lambda checkout: None, resume=AsyncMock(), ) ) - cancel.assert_awaited_once() + assert any("mailbox box" in note for note in err.value.__notes__) def test_proxy_checking_then_checkout(monkeypatch): @@ -484,9 +468,11 @@ def test_proxy_checking_then_checkout(monkeypatch): ) context = AsyncMock() context.__aenter__.return_value = NS(connect=NS(proxies=endpoint)) - monkeypatch.setattr(proxies, "cloud_client", lambda *args, **kwargs: context) + monkeypatch.setattr( + cloud_connection, "cloud_client", lambda *args, **kwargs: context + ) with pytest.raises(PaymentRequired) as caught: - asyncio.run(proxies.buy_proxy("US", billing=Billing.PAID)) + asyncio.run(proxies.Proxies(billing=Billing.PAID).buy("US")) assert caught.value.checkout.url == "https://example.test" assert "https://example.test" not in str(caught.value) endpoint.cancel.assert_not_awaited() @@ -501,9 +487,7 @@ def test_cli_interactive_paid_checkout(monkeypatch, resource, timeout): url = "https://example.test/pay" opened = [] - monkeypatch.setattr( - "mobilerun.cli.base.billing.billing_prompt_is_interactive", lambda: True - ) + monkeypatch.setattr("mobilerun.cli.base.billing.can_prompt", lambda _stream: True) async def confirm(message, **kwargs): print(message) @@ -523,24 +507,33 @@ async def confirm(message, **kwargs): delete=AsyncMock(), ) client = NS(numbers=endpoint) - module = numbers + module = cloud_connection args = ["number", "create", "--country", "US", "--billing", "paid"] cancel = endpoint.delete success = "✓ Created number +123 (n1; active)" else: + product = dict( + id="p1", + name="Test proxy", + country="US", + type="residential", + billing_mode=None, + ) endpoint = NS( buy=AsyncMock( - return_value=NS(id="p1", status="pending_payment", payment_url=url) + return_value=NS(**product, status="pending_payment", payment_url=url) ), retrieve=AsyncMock( return_value=NS( - status="pending_payment" if timeout else "active", payment_url=None + **product, + status="pending_payment" if timeout else "active", + payment_url=None, ) ), cancel=AsyncMock(), ) client = NS(connect=NS(proxies=endpoint)) - module = proxies + module = cloud_connection args = ["proxy", "buy", "--country", "US", "--billing", "paid"] cancel = endpoint.cancel success = "✓ Bought proxy p1 (US)" @@ -553,8 +546,9 @@ async def confirm(message, **kwargs): assert opened == [url] if timeout: assert result.exit_code != 0 - assert "Cancelled pending" in result.output - cancel.assert_awaited_once() + assert "check the dashboard" in result.output + assert ("n1" if resource == "number" else "p1") in result.output + cancel.assert_not_awaited() assert success not in result.output else: assert result.exit_code == 0, result.output @@ -589,11 +583,10 @@ def test_checkout_callback_is_typed_and_library_is_silent(monkeypatch, capsys): delete=AsyncMock(), ) asyncio.run( - mailboxes.create( + mailboxes.Mailboxes( client=cast(AsyncMobilerun, NS(mailboxes=endpoint)), billing=Billing.PAID, - on_checkout=callback, - ) + ).create(on_checkout=callback) ) callback.assert_called_once_with( Checkout("https://example.test/pay", None, "mailbox", "box") @@ -607,7 +600,7 @@ def test_core_payment_error_resumes_to_resource(monkeypatch, kind): from mobilerun.core.phone_number import CloudPhoneNumber from mobilerun.models import Checkout - module = mailboxes if kind == "mailbox" else numbers + module = mailboxes.Mailboxes if kind == "mailbox" else numbers.Numbers resource_type = CloudMailbox if kind == "mailbox" else CloudPhoneNumber checkout = Checkout("https://example.test/pay", None, kind, "resource") monkeypatch.setattr( @@ -645,60 +638,53 @@ async def run(): cancel.assert_not_awaited() -def test_resumed_timeout_does_not_cancel(): +def test_resumed_timeout_reports_recovery_id(): from mobilerun.models import Checkout - cancel = AsyncMock() - adapter = PaymentAdapter( + adapter = PaymentFlow( "mailbox", "box", AsyncMock(return_value=PaymentSnapshot("awaiting_payment")), - cancel, ) async def resume(timeout): - await wait_until_active(adapter, timeout=timeout) + await adapter.wait_until_active(timeout=timeout) error = PaymentRequired( Checkout("https://example.test", None, "mailbox", "box"), resume ) with pytest.raises(TimeoutError, match="box"): asyncio.run(error.wait_until_paid(timeout=0)) - cancel.assert_not_awaited() -def test_slow_async_callback_is_timed_out_and_cancelled(): - cancel = AsyncMock() - adapter = PaymentAdapter("mailbox", "box", AsyncMock(), cancel) +def test_slow_async_callback_times_out_with_recovery_id(): + adapter = PaymentFlow("mailbox", "box", AsyncMock()) async def callback(checkout): await asyncio.Event().wait() with pytest.raises(TimeoutError, match="box"): asyncio.run( - wait_for_payment( - adapter, + adapter.wait_for_payment( PaymentSnapshot("awaiting_payment", "https://example.test"), resume=AsyncMock(), on_checkout=callback, timeout=0.01, ) ) - cancel.assert_awaited_once() @pytest.mark.parametrize("mode", ["print", "browser"]) def test_checkout_modes_print_and_wait(mode, monkeypatch, capsys): - from mobilerun.clients.cloud.checkout import checkout_callback + from mobilerun.utils.checkout.presentation import checkout_callback opened = [] monkeypatch.setattr("webbrowser.open", lambda url: opened.append(url)) monkeypatch.setattr("sys.platform", "darwin") retrieve = AsyncMock(return_value=PaymentSnapshot("active")) - adapter = PaymentAdapter("mailbox", "box", retrieve, AsyncMock()) + adapter = PaymentFlow("mailbox", "box", retrieve) asyncio.run( - wait_for_payment( - adapter, + adapter.wait_for_payment( PaymentSnapshot("awaiting_payment", "https://example.test"), resume=AsyncMock(), on_checkout=checkout_callback(mode, None), @@ -715,8 +701,8 @@ def test_checkout_mode_and_callback_conflict(): def test_browser_checkout_headless_still_prints_expiry(monkeypatch, capsys): - from mobilerun.clients.cloud.checkout import browser_checkout from mobilerun.models.checkout import Checkout + from mobilerun.utils.checkout.presentation import browser_checkout opened = [] monkeypatch.setattr("sys.platform", "linux") @@ -733,15 +719,14 @@ def test_browser_checkout_headless_still_prints_expiry(monkeypatch, capsys): @pytest.mark.parametrize("resource", ["mailbox", "number", "proxy"]) def test_cloud_creators_reject_checkout_and_callback(resource): creator = { - "mailbox": mailboxes.create, - "number": numbers.create, - "proxy": proxies.buy_proxy, + "mailbox": _creator(mailboxes, Billing.PAID), + "number": _creator(numbers, Billing.PAID), + "proxy": proxies.Proxies(billing=Billing.PAID).buy, }[resource] params = {"country": "US"} if resource == "proxy" else {} with pytest.raises(ValueError, match="on_checkout"): asyncio.run( creator( - billing=Billing.PAID, checkout="print", on_checkout=lambda _: None, **params, @@ -751,7 +736,9 @@ def test_cloud_creators_reject_checkout_and_callback(resource): @pytest.mark.parametrize("async_callback", [False, True]) @pytest.mark.parametrize("kind", ["mailbox", "number"]) -def test_callback_failure_releases_created_resource(kind, async_callback): +def test_callback_failure_preserves_resource_and_reports_recovery_id( + kind, async_callback +): url = "https://example.test/pay" if kind == "mailbox": data = NS( @@ -760,10 +747,10 @@ def test_callback_failure_releases_created_resource(kind, async_callback): checkout_url=url, checkout_expires_at=None, ) - creator, endpoint_name, resource_id = mailboxes.create, "mailboxes", "box" + resource, endpoint_name, resource_id = mailboxes, "mailboxes", "box" else: data = NS(number_id="number", state="awaiting_payment", checkout_url=url) - creator, endpoint_name, resource_id = numbers.create, "numbers", "number" + resource, endpoint_name, resource_id = numbers, "numbers", "number" endpoint = NS(create=AsyncMock(return_value=NS(data=data)), delete=AsyncMock()) client = cast(AsyncMobilerun, NS(**{endpoint_name: endpoint})) @@ -773,12 +760,11 @@ def callback(_): async def async_cb(_): raise RuntimeError("callback failed") - with pytest.raises(RuntimeError, match="callback failed"): + with pytest.raises(RuntimeError, match="callback failed") as err: asyncio.run( - creator( - client=client, - billing=Billing.PAID, + _creator(resource, Billing.PAID, client)( on_checkout=async_cb if async_callback else callback, ) ) - endpoint.delete.assert_awaited_once_with(resource_id) + endpoint.delete.assert_not_awaited() + assert any(resource_id in note for note in err.value.__notes__) diff --git a/tests/unit/clients/cloud/test_numbers_resource.py b/tests/unit/clients/cloud/test_numbers_resource.py new file mode 100644 index 000000000..9bb95c8ce --- /dev/null +++ b/tests/unit/clients/cloud/test_numbers_resource.py @@ -0,0 +1,61 @@ +"""The bound numbers adapter borrows clients and opens fresh ones for resume.""" + +import asyncio +from contextlib import asynccontextmanager +from types import SimpleNamespace as NS +from unittest.mock import AsyncMock + +import pytest + +from mobilerun.clients.cloud import numbers +from mobilerun.errors import BillingRequired, PaymentRequired +from mobilerun.models.billing import Billing + + +def test_bound_number_checks_billing_before_using_sdk(): + endpoint = AsyncMock() + client = NS(numbers=NS(messages=NS(send=endpoint))) + with pytest.raises(BillingRequired) as raised: + asyncio.run( + numbers.Numbers(client=client, billing="included").send("n", "t", "b") + ) + assert raised.value.needed is Billing.PAID + endpoint.assert_not_called() + + +def test_number_payment_resume_opens_a_fresh_owned_client(monkeypatch): + checkout_url = "https://example.test/checkout" + ready = NS(data=NS(state="active", checkout_url=None)) + created = NS( + data=NS(number_id="n", state="awaiting_payment", checkout_url=checkout_url) + ) + events = [] + + @asynccontextmanager + async def open_client(api_key, base_url, *, billing): + events.append(("open", api_key, base_url)) + try: + yield NS( + numbers=NS( + create=AsyncMock(return_value=created), + retrieve=AsyncMock(return_value=ready), + ) + ) + finally: + events.append("close") + + async def run(): + adapter = numbers.Numbers( + api_key="fake", base_url="https://example.test", billing=Billing.PAID + ) + with pytest.raises(PaymentRequired) as raised: + await adapter.create() + assert events[-1] == "close" + assert raised.value.checkout.resource_id == "n" + assert await raised.value.wait_until_paid() is ready + + from mobilerun.clients.cloud import client + + monkeypatch.setattr(client, "cloud_client", open_client) + asyncio.run(run()) + assert events == [("open", "fake", "https://example.test"), "close"] * 2 diff --git a/tests/unit/clients/cloud/test_policy.py b/tests/unit/clients/cloud/test_policy.py index c7669a07a..575dc0717 100644 --- a/tests/unit/clients/cloud/test_policy.py +++ b/tests/unit/clients/cloud/test_policy.py @@ -2,8 +2,7 @@ import ast import asyncio -import importlib -import inspect +import traceback from collections.abc import Awaitable, Callable from contextlib import asynccontextmanager from types import SimpleNamespace as NS @@ -12,6 +11,7 @@ import httpx import pytest +from mobilerun_core import CloudPlan from mobilerun_sdk import ( APIConnectionError, APIStatusError, @@ -19,18 +19,18 @@ AsyncMobilerun, ) +from mobilerun.clients.cloud import client as cloud_connection from mobilerun.clients.cloud import ( - apps, - devices, - files, mailboxes, numbers, proxies, secrets, tasks, ) -from mobilerun.clients.local import login_store as cloud_credentials +from mobilerun.clients.cloud.billing_policy import BillingPolicy +from mobilerun.clients.local.login_store import LoginStore from mobilerun.config.settings import get_settings +from mobilerun.core.workspace import Workspace from mobilerun.errors import ( BillingError, CloudAPIError, @@ -46,70 +46,22 @@ CredentialFormatError, CredentialReadError, ) +from mobilerun.errors.cloud import BillingRequired from mobilerun.models.billing import Billing from tests.support.paths import REPO_ROOT -def _boundaries(): - root = REPO_ROOT / "mobilerun/clients/cloud" - for path in sorted(root.glob("*.py")): - if path.stem in {"billing", "checkout", "errors", "payments"}: - continue # Helpers are not transport or billing boundaries. - module = importlib.import_module(f"mobilerun.clients.cloud.{path.stem}") - for name, function in vars(module).items(): - if ( - not name.startswith("_") - and name != "requires" - and inspect.isfunction(function) - and function.__module__ == module.__name__ - ): - yield pytest.param(function, id=f"{path.stem}.{name}") - - -class _NoHTTP: - def __getattr__(self, name): - raise AssertionError(f"HTTP attempted: {name}") - - -def _arguments(function): - args, kwargs = [], {} - for param in inspect.signature(function).parameters.values(): - if param.name == "billing" or param.default is not inspect.Parameter.empty: - continue - if param.kind in (param.VAR_KEYWORD, param.VAR_POSITIONAL): - continue - value = _NoHTTP() if param.name == "client" else "test" - if param.kind is param.KEYWORD_ONLY: - kwargs[param.name] = value - else: - args.append(value) - return args, kwargs - - -@pytest.mark.parametrize("function", list(_boundaries())) -def test_missing_billing_fails_before_transport(function): - args, kwargs = _arguments(function) +def test_sdk_factory_requires_valid_explicit_billing_before_transport(): with pytest.raises(TypeError, match="billing"): - function(*args, **kwargs) - - -@pytest.mark.parametrize("function", list(_boundaries())) -def test_invalid_billing_fails_before_transport(function): - args, kwargs = _arguments(function) + cloud_connection.cloud_client("fake") with pytest.raises( - BillingError, match=f"{function.__name__}.*given.*requires.*MOBILERUN_BILLING" + BillingError, match="cloud_client.*given.*requires.*MOBILERUN_BILLING" ): - function(*args, billing="invalid", **kwargs) + cloud_connection.cloud_client("fake", billing="invalid") -@pytest.mark.parametrize( - "function", - [devices.create, numbers.create, mailboxes.create, tasks.run, tasks.run_task], -) -def test_included_functions_refuse_no_commerce_before_transport(function): - args, kwargs = _arguments(function) - with pytest.raises(BillingError, match="requires billing='included'"): - function(*args, billing=Billing.NO_COMMERCE, **kwargs) +class _TransportReached(BaseException): + pass @pytest.mark.parametrize("mode", [Billing.NO_COMMERCE, Billing.INCLUDED]) @@ -117,108 +69,27 @@ def test_paid_proxy_refuses_lower_modes_before_transport(mode): with pytest.raises( BillingError, match="Buy Connect proxy.*requires billing='paid'" ): - proxies.buy_proxy("US", billing=mode) - - -class _TransportReached(BaseException): - pass - - -class _FreeClient: - def __getattr__(self, name): - raise _TransportReached - - -@pytest.mark.parametrize("function", list(_boundaries())) -def test_no_commerce_boundary_policy(function, monkeypatch, tmp_path): - module = importlib.import_module(function.__module__) - if function in ( - devices.create, - numbers.create, - numbers.send, - mailboxes.create, - tasks.run, - tasks.run_task, - proxies.buy_proxy, - ): - args, kwargs = _arguments(function) - with pytest.raises(BillingError, match="requires billing="): - function(*args, billing=Billing.NO_COMMERCE, **kwargs) - return - - def transport(*args, **kwargs): - raise _TransportReached - - if hasattr(module, "cloud_client"): - monkeypatch.setattr(module, "cloud_client", transport) - if hasattr(module, "AsyncMobilerun"): - monkeypatch.setattr(module, "AsyncMobilerun", transport) - if hasattr(module, "_request"): - monkeypatch.setattr(module, "_request", transport) - if hasattr(module, "_exchange"): - monkeypatch.setattr(module, "_exchange", transport) - monkeypatch.setattr(module.asyncio, "sleep", AsyncMock()) - args, kwargs = _arguments(function) - sig = inspect.signature(function) - bound = sig.bind(*args, billing=Billing.NO_COMMERCE, **kwargs) - if function.__name__ == "cloud_client": - bound.arguments["api_key"] = "fake" - if "client" in bound.arguments: - bound.arguments["client"] = _FreeClient() - if function is secrets.save: - bound.arguments["fields"] = {"username": "test"} - if "params" in bound.arguments and function is proxies.connect_device: - bound.arguments["params"] = {} - if function is apps.upload_app: - path = tmp_path / "app.apk" - path.write_bytes(b"fake APK") - bound.arguments["path"] = path - monkeypatch.setattr( - apps, "inspect_apk", lambda path: ("example", 1, "1", "Example") - ) - if function is files.upload_file: - path = tmp_path / "sample.txt" - path.write_bytes(b"sample") - bound.arguments["path"] = path - if function.__name__ == "poll_token": - bound.arguments["code"] = NS(interval=1, expires_in=10, device_code="fake") - - async def exercise(): - result = function(*bound.args, **bound.kwargs) - if inspect.isasyncgen(result): - await anext(result) - elif inspect.isawaitable(result): - await result - - with pytest.raises(_TransportReached): - asyncio.run(exercise()) + asyncio.run(proxies.Proxies(billing=mode).buy("US")) def test_free_boundaries_accept_no_commerce(): retrieve = AsyncMock(return_value="result") client = NS( - devices=NS(retrieve=retrieve, retrieve_capabilities=retrieve), numbers=NS(retrieve=retrieve), - apps=NS(retrieve=retrieve), credentials=NS(packages=NS(list=AsyncMock(return_value=NS(data=[])))), ) async def run(): assert ( - await devices.capabilities("id", client=client, billing=Billing.NO_COMMERCE) - == "result" - ) - assert ( - await devices.retrieve("id", client=client, billing=Billing.NO_COMMERCE) - == "result" - ) - assert ( - await numbers.retrieve("id", client=client, billing=Billing.NO_COMMERCE) + await numbers.Numbers(client=client, billing=Billing.NO_COMMERCE).retrieve( + "id" + ) == "result" ) - assert await apps.get_app(client, "id", billing=Billing.NO_COMMERCE) == "result" assert ( - await secrets.list_package(client, "package", billing=Billing.NO_COMMERCE) + await secrets.Vault( + client=client, billing=Billing.NO_COMMERCE + ).list_package("package") == [] ) @@ -227,28 +98,47 @@ async def run(): def test_core_objects_snapshot_settings_billing(monkeypatch): from mobilerun.core.credentials import CloudCredentials - from mobilerun.core.devices.cloud import CloudDevice from mobilerun.core.mailbox import CloudMailbox as Mailbox from mobilerun.core.operator.cloud import CloudTaskOperator from mobilerun.core.phone_number import CloudPhoneNumber as PhoneNumber monkeypatch.setenv("MOBILERUN_BILLING", "paid") assert get_settings().MOBILERUN_BILLING is Billing.PAID - device = CloudDevice("existing", api_key="fake") instances = [ - device, - CloudTaskOperator(), + CloudTaskOperator(client=AsyncMock(spec=AsyncMobilerun)), PhoneNumber("existing"), - Mailbox("existing"), CloudCredentials(api_key="fake"), ] + mailbox = Mailbox("existing") + modes = [] + + @asynccontextmanager + async def sdk(*args, billing): + modes.append(billing) + yield NS( + mailboxes=NS( + retrieve=AsyncMock( + return_value=NS( + data=NS(status="active", address="test@example.test") + ) + ) + ) + ) + + monkeypatch.setattr(cloud_connection, "cloud_client", sdk) monkeypatch.setenv("MOBILERUN_BILLING", "no_commerce") assert all(instance._billing is Billing.PAID for instance in instances) + async def open_mailbox(): + return await mailbox + + assert asyncio.run(open_mailbox()).address == "test@example.test" + assert modes == [Billing.PAID] + @pytest.mark.parametrize( "resource", - ["cloud phones", "numbers", "mailboxes", "Connect proxies"], + ["numbers", "mailboxes", "Connect proxies"], ) @pytest.mark.parametrize("setting", list(Billing)) @pytest.mark.parametrize( @@ -265,19 +155,17 @@ def test_policy_matrix(monkeypatch, resource, setting, explicit): def client(*args, **kwargs): raise _TransportReached - monkeypatch.setattr(proxies, "cloud_client", client) + monkeypatch.setattr(cloud_connection, "cloud_client", client) if not blocked: with pytest.raises(_TransportReached): - asyncio.run(proxies.buy_proxy("US", billing=explicit)) + asyncio.run(proxies.Proxies(billing=explicit).buy("US")) return def call(): - return proxies.buy_proxy("US", billing=explicit) + return proxies.Proxies(billing=explicit).buy("US") else: - adapter = {"cloud phones": devices, "numbers": numbers, "mailboxes": mailboxes}[ - resource - ] + adapter = {"numbers": numbers, "mailboxes": mailboxes}[resource] endpoint = AsyncMock( return_value=NS( id="created", @@ -290,21 +178,10 @@ def call(): ), ) ) - client = NS( - **{ - "devices" if resource == "cloud phones" else resource: NS( - create=endpoint - ) - } - ) - params = ( - {"proxy": {"connect": {"id": "existing"}}} - if resource == "cloud phones" - else {} - ) + client = NS(**{resource: NS(create=endpoint)}) def call(): - return adapter.create(billing=explicit, client=client, **params) + return _creator(adapter, client, explicit)() if blocked: with pytest.raises(BillingError, match="given.*requires.*MOBILERUN_BILLING"): @@ -312,19 +189,14 @@ def call(): if resource != "Connect proxies": endpoint.assert_not_called() else: - expected = ( - ("included_only" if effective is Billing.INCLUDED else "included") - if resource in {"numbers", "mailboxes"} - else ("subscription" if effective is Billing.INCLUDED else "auto") - ) + expected = "included_only" if effective is Billing.INCLUDED else "included" asyncio.run(call()) - key = "billing" if resource == "cloud phones" else "billing_preference" - assert endpoint.call_args.kwargs[key] == expected + assert endpoint.call_args.kwargs["billing_preference"] == expected @pytest.mark.parametrize( "adapter,resource", - [(numbers, "numbers"), (mailboxes, "mailboxes"), (devices, "devices")], + [(numbers, "numbers"), (mailboxes, "mailboxes")], ) @pytest.mark.parametrize("mode", list(Billing)) def test_resource_calls_cannot_skip_policy(adapter, resource, mode): @@ -341,50 +213,64 @@ def test_resource_calls_cannot_skip_policy(adapter, resource, mode): ) ) client = NS(**{resource: NS(create=create)}) - params = {"proxy": {"connect": {"id": "existing"}}} if resource == "devices" else {} if mode is Billing.NO_COMMERCE: with pytest.raises(ValueError): - asyncio.run(adapter.create(client=client, billing=mode, **params)) + asyncio.run(_creator(adapter, client, mode)()) create.assert_not_awaited() else: - asyncio.run(adapter.create(client=client, billing=mode, **params)) - expected = ( - ("subscription" if mode is Billing.INCLUDED else "auto") - if resource == "devices" - else ("included_only" if mode is Billing.INCLUDED else "included") - ) - create.assert_awaited_once_with( - **{"billing" if resource == "devices" else "billing_preference": expected}, - **params, - ) + asyncio.run(_creator(adapter, client, mode)()) + expected = "included_only" if mode is Billing.INCLUDED else "included" + create.assert_awaited_once_with(billing_preference=expected) -@pytest.mark.parametrize("mode", ["no_commerce", "included", "paid"]) -@pytest.mark.parametrize("plan", [None, "auto", "minute", "subscription"]) -def test_cloud_phone_plan_policy(mode, plan): - blocked = mode == "no_commerce" or ( - mode == "included" and plan in {"auto", "minute"} - ) - if blocked: - with pytest.raises(ValueError): - asyncio.run(devices.create(billing=mode, plan=plan)) +@pytest.mark.parametrize("setting", list(Billing)) +@pytest.mark.parametrize( + "explicit", [None, *Billing, "paid", "included", "no_commerce"] +) +def test_cloud_phone_billing_resolution( + monkeypatch: pytest.MonkeyPatch, setting: Billing, explicit: Billing | str | None +) -> None: + monkeypatch.setenv("MOBILERUN_BILLING", setting.value) + effective = setting if explicit is None else Billing(explicit) + if effective is Billing.NO_COMMERCE: + with pytest.raises(BillingRequired) as error: + BillingPolicy.cloud_phone_plan(billing=explicit) + assert error.value.given is Billing.NO_COMMERCE + assert error.value.needed is Billing.INCLUDED else: - expected = plan or ("subscription" if mode == "included" else "auto") - create = AsyncMock() - asyncio.run( - devices.create( - billing=mode, - plan=plan, - proxy={"connect": {"id": "existing"}}, - client=NS(devices=NS(create=create)), - ) + assert BillingPolicy.cloud_phone_plan(billing=explicit) == ( + "auto" if effective is Billing.PAID else "subscription" ) - assert create.call_args.kwargs["billing"] == expected + + +@pytest.mark.parametrize( + "mode,plan,expected", + [ + ("paid", "auto", "auto"), + ("paid", "minute", "minute"), + ("paid", "subscription", "subscription"), + ("included", "subscription", "subscription"), + ("included", "auto", Billing.PAID), + ("included", "minute", Billing.PAID), + ("no_commerce", "auto", Billing.PAID), + ("no_commerce", "minute", Billing.PAID), + ("no_commerce", "subscription", Billing.INCLUDED), + ], +) +def test_cloud_phone_plan_policy( + mode: Billing | str, plan: CloudPlan, expected: CloudPlan | Billing +) -> None: + if isinstance(expected, Billing): + with pytest.raises(BillingRequired) as error: + BillingPolicy.cloud_phone_plan(plan, billing=mode) + assert error.value.needed is expected + else: + assert BillingPolicy.cloud_phone_plan(plan, billing=mode) == expected @pytest.mark.parametrize( "adapter,resource", - [(numbers, "numbers"), (mailboxes, "mailboxes"), (devices, "devices")], + [(numbers, "numbers"), (mailboxes, "mailboxes")], ) @pytest.mark.parametrize( "field", ["billing", "billingPreference", "billing_preference", "proxy"] @@ -393,11 +279,7 @@ def test_extra_body_cannot_override_commerce_policy(adapter, resource, field): create = AsyncMock() client = NS(**{resource: NS(create=create)}) with pytest.raises(ValueError): - asyncio.run( - adapter.create( - client=client, billing="included", extra_body={field: "rent"} - ) - ) + asyncio.run(_creator(adapter, client, "included")(extra_body={field: "rent"})) create.assert_not_awaited() @@ -409,91 +291,16 @@ def _offline_sdk(handler): ) -@pytest.mark.parametrize("adapter", [devices, numbers, mailboxes]) -@pytest.mark.parametrize( - "field", ["billing", "billingPreference", "billing_preference", "proxy"] -) -def test_extra_body_cannot_reach_transport(adapter, field): - seen = [] - - async def run(): - async with _offline_sdk( - lambda request: seen.append(request) or httpx.Response(400) - ) as client: - with pytest.raises(ValueError): - await adapter.create( - client=client, billing="included", extra_body={field: "rent"} - ) - - asyncio.run(run()) - assert not seen - - -@pytest.mark.parametrize( - "mode,plan,expected", - [ - ("paid", None, "auto"), - ("paid", "auto", "auto"), - ("paid", "minute", "minute"), - ("paid", "subscription", "subscription"), - ("included", None, "subscription"), - ("included", "subscription", "subscription"), - ], -) -def test_plan_reaches_real_sdk_body(mode, plan, expected): - seen = [] - - def handler(request): - seen.append(dict(request.url.params)) - return httpx.Response(400, json={"message": "test rejection"}) - - async def run(): - async with _offline_sdk(handler) as client: - with pytest.raises(CloudAPIError): - await devices.create( - client=client, - billing=mode, - plan=plan, - device_type="android_cloud_phone", - proxy={"connect": {"id": "existing"}}, - ) - - asyncio.run(run()) - assert len(seen) == 1 - assert seen[0]["billing"] == expected +def _creator(adapter, client, billing): + resource = numbers.Numbers if adapter is numbers else mailboxes.Mailboxes + return resource(client=client, billing=billing).create +@pytest.mark.parametrize("adapter", [numbers, mailboxes]) @pytest.mark.parametrize( - "mode,plan", - [ - ("no_commerce", None), - ("no_commerce", "auto"), - ("no_commerce", "minute"), - ("no_commerce", "subscription"), - ("included", "auto"), - ("included", "minute"), - ], + "field", ["billing", "billingPreference", "billing_preference", "proxy"] ) -def test_blocked_plan_never_reaches_transport(mode, plan): - seen = [] - - async def run(): - async with _offline_sdk( - lambda request: seen.append(request) or httpx.Response(400) - ) as client: - with pytest.raises(ValueError): - await devices.create( - client=client, - billing=mode, - plan=plan, - proxy={"connect": {"id": "existing"}}, - ) - - asyncio.run(run()) - assert not seen - - -def test_extra_query_cannot_override_device_billing(): +def test_extra_body_cannot_reach_transport(adapter, field): seen = [] async def run(): @@ -501,63 +308,18 @@ async def run(): lambda request: seen.append(request) or httpx.Response(400) ) as client: with pytest.raises(ValueError): - await devices.create( - client=client, - billing=Billing.INCLUDED, - extra_query={"billing": "minute"}, - ) + await _creator(adapter, client, "included")(extra_body={field: "rent"}) asyncio.run(run()) assert not seen -@pytest.mark.parametrize( - "proxy", - [ - {}, - {"connect": {}}, - {"connect": {"country": None}}, - {"socks5": {"host": "example.test"}}, - ], -) -def test_invalid_explicit_cloud_phone_proxy_is_rejected_before_http(proxy): - seen = [] - - async def run(): - async with _offline_sdk( - lambda request: seen.append(request) or httpx.Response(400) - ) as client: - with pytest.raises(ValueError, match="proxy"): - await devices.create(client=client, billing=Billing.PAID, proxy=proxy) - - asyncio.run(run()) - assert not seen - - -@pytest.mark.parametrize( - "billing,proxy,allowed", - [ - ("included", {"connect": {"country": "us"}}, False), - ("included", {"connect": {"id": "existing"}}, True), - ("included", {"socks5": {"host": "example.test", "port": 1080}}, True), - ("paid", {"connect": {"country": "us"}}, True), - ("no_commerce", {"connect": {"id": "existing"}}, False), - ], -) -def test_proxy_billing_is_checked_before_transport(billing, proxy, allowed): - seen = [] - - def handler(request): - seen.append(request) - return httpx.Response(400, json={"message": "test rejection"}) - - async def run(): - async with _offline_sdk(handler) as client: - with pytest.raises(CloudAPIError): - await devices.create(client=client, billing=billing, proxy=proxy) - - asyncio.run(run()) - assert bool(seen) is allowed +def test_cloud_phone_rejects_invalid_billing_before_core() -> None: + canary = "invalid-billing-canary" + with pytest.raises(BillingError) as error: + BillingPolicy.cloud_phone_plan(billing=canary) + assert error.value.code == "invalid_billing" + assert canary not in str(error.value) @pytest.mark.parametrize("adapter", [numbers, mailboxes]) @@ -576,32 +338,13 @@ def handler(request): async def run(): async with _offline_sdk(handler) as client: with pytest.raises(CloudAPIError): - await adapter.create(client=client, billing=mode) + await _creator(adapter, client, mode)() asyncio.run(run()) assert bodies[0]["billingPreference"] == expected -@pytest.mark.parametrize("options", [{}, {"proxy": None}]) -def test_missing_proxy_is_rejected_before_transport(options): - seen = [] - - def handler(request): - import json - - seen.append(json.loads(request.content)) - return httpx.Response(200, json={"id": "phone", "name": None}) - - async def run(): - async with _offline_sdk(handler) as client: - with pytest.raises(ValueError, match="proxy"): - await devices.create(client=client, billing=Billing.PAID, **options) - - asyncio.run(run()) - assert not seen - - -@pytest.mark.parametrize("resource", ["device", "number", "mailbox", "connect", "buy"]) +@pytest.mark.parametrize("resource", ["number", "mailbox", "buy"]) @pytest.mark.parametrize("extra", ["extra_body", "extra_query"]) @pytest.mark.parametrize( "field", ["proxy", "connect", "billing", "billingPreference", "billingMode"] @@ -609,45 +352,30 @@ async def run(): def test_commerce_fields_in_extras_never_reach_real_transport( monkeypatch, resource, extra, field ): - from contextlib import nullcontext - - from mobilerun.clients.cloud import proxies - seen = [] async def run(): async with _offline_sdk( lambda request: seen.append(request) or httpx.Response(400) ) as client: - monkeypatch.setattr( - proxies, "cloud_client", lambda *args: nullcontext(client) - ) extras = {extra: {field: {"country": "DE"}}} # Deliberately send invalid fields to exercise runtime commerce guards. with pytest.raises(ValueError): - if resource == "device": - await cast(Callable[..., Awaitable[object]], devices.create)( - client=client, - billing="paid", - proxy={"connect": {"id": "existing"}}, - **extras, - ) - elif resource == "number": - await cast(Callable[..., Awaitable[object]], numbers.create)( - client=client, billing=Billing.PAID, **extras - ) + if resource == "number": + await cast( + Callable[..., Awaitable[object]], + numbers.Numbers(client=client, billing=Billing.PAID).create, + )(**extras) elif resource == "mailbox": - await cast(Callable[..., Awaitable[object]], mailboxes.create)( - client=client, billing=Billing.PAID, **extras - ) - elif resource == "connect": await cast( - Callable[..., Awaitable[object]], proxies.connect_device - )("phone", extras, billing=Billing.NO_COMMERCE) + Callable[..., Awaitable[object]], + mailboxes.Mailboxes(client=client, billing=Billing.PAID).create, + )(**extras) else: - await cast(Callable[..., Awaitable[object]], proxies.buy_proxy)( - "DE", billing=Billing.PAID, **extras - ) + await cast( + Callable[..., Awaitable[object]], + proxies.Proxies(client=client, billing=Billing.PAID).buy, + )("DE", **extras) asyncio.run(run()) assert not seen @@ -655,7 +383,7 @@ async def run(): def test_cloud_helpers_do_not_import_sdk(): """Checkout and error helpers are not independent transport boundaries.""" - for name in ("checkout", "errors", "payments"): + for name in ("errors", "payments", "device_flow", "signed_http"): path = REPO_ROOT / "mobilerun/clients/cloud" / f"{name}.py" tree = ast.parse(path.read_text()) for node in ast.walk(tree): @@ -667,33 +395,35 @@ def test_cloud_helpers_do_not_import_sdk(): assert not (node.module or "").startswith("mobilerun_sdk") -def test_cloud_modules_require_explicit_billing(): +def test_sdk_cloud_boundaries_require_explicit_billing(): for path in (REPO_ROOT / "mobilerun/clients/cloud").glob("*.py"): - if path.stem in {"billing", "checkout", "errors", "payments"}: + if path.stem in { + "billing_policy", + "errors", + "payments", + "resource", + }: continue # Helpers do not expose billable cloud operations. tree = ast.parse(path.read_text()) - assert not any( - isinstance(node, ast.ClassDef) - and not (path.stem == "device_flow" and node.name == "CodeResponse") - for node in ast.walk(tree) - ), path - for node in tree.body: - if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): - continue - if node.name.startswith("_") or node.name == "requires": - continue - assert any( - isinstance(dec, ast.Call) - and isinstance(dec.func, ast.Name) - and dec.func.id == "requires" - for dec in node.decorator_list - ), (path, node.name) - names = [argument.arg for argument in node.args.kwonlyargs] - assert "billing" in names, (path, node.name) - assert node.args.kw_defaults[names.index("billing")] is None, ( - path, - node.name, - ) + for adapter in ( + node + for node in tree.body + if isinstance(node, ast.ClassDef) + and any(ast.unparse(base) == "CloudResource" for base in node.bases) + ): + for method in adapter.body: + if isinstance( + method, ast.AsyncFunctionDef + ) and not method.name.startswith("_"): + assert any( + isinstance(call, ast.Call) + and ast.unparse(call.func) + in {"self._request", "self._billing.require"} + and any( + ast.unparse(arg).startswith("Billing.") for arg in call.args + ) + for call in ast.walk(method) + ), (path, method.name) assert "mobilerun.core" not in path.read_text(), path @@ -711,10 +441,8 @@ def test_cloud_modules_require_explicit_billing(): (503, CloudServiceUnavailable), ], ) -@pytest.mark.parametrize( - "boundary", ["number", "mailbox", "vault", "task", "app", "device"] -) -def test_sdk_errors_are_typed_sanitized_and_chained(status, expected, boundary): +@pytest.mark.parametrize("boundary", ["number", "mailbox", "vault", "task", "app"]) +def test_sdk_errors_are_typed_and_detached(status, expected, boundary, monkeypatch): response = httpx.Response( status, headers={"x-request-id": "req-safe"}, @@ -725,38 +453,39 @@ def test_sdk_errors_are_typed_sanitized_and_chained(status, expected, boundary): ) endpoint = AsyncMock(side_effect=error) if boundary == "number": - coroutine = numbers.retrieve( - "id", billing="included", client=NS(numbers=NS(retrieve=endpoint)) - ) + coroutine = numbers.Numbers( + billing="included", client=NS(numbers=NS(retrieve=endpoint)) + ).retrieve("id") elif boundary == "mailbox": - coroutine = mailboxes.retrieve( - "id", billing="included", client=NS(mailboxes=NS(retrieve=endpoint)) - ) + coroutine = mailboxes.Mailboxes( + billing="included", client=NS(mailboxes=NS(retrieve=endpoint)) + ).retrieve("id") elif boundary == "vault": - coroutine = secrets.list_package( - NS(credentials=NS(packages=NS(list=endpoint))), - "package", - billing="included", - ) + coroutine = secrets.Vault( + client=NS(credentials=NS(packages=NS(list=endpoint))), billing="included" + ).list_package("package") elif boundary == "task": - coroutine = tasks.status( - NS(tasks=NS(get_status=endpoint)), "id", billing="included" - ) - elif boundary == "app": - coroutine = apps.get_app( - NS(apps=NS(retrieve=endpoint)), "id", billing="included" - ) + coroutine = tasks.Tasks( + client=NS(tasks=NS(get_status=endpoint)), billing="included" + ).status("id") else: - coroutine = devices.retrieve( - "id", billing="included", client=NS(devices=NS(retrieve=endpoint)) + from contextlib import nullcontext + + monkeypatch.setattr( + cloud_connection, + "cloud_client", + lambda *a, **kw: nullcontext(NS(apps=NS(retrieve=endpoint))), ) + coroutine = Workspace(billing=Billing.INCLUDED).get_app("id") with pytest.raises(expected) as raised: asyncio.run(coroutine) assert isinstance(raised.value, CloudAPIError) - assert raised.value.__cause__ is error + assert raised.value.__cause__ is None and raised.value.__context__ is None message = str(raised.value) - assert f"HTTP {status}" in message and "req-safe" in message - assert "secret" not in message and "private.test" not in message + assert f"HTTP {status}" in message + rendered = "".join(traceback.format_exception(raised.value)) + assert "req-safe" not in rendered and "secret request body" not in rendered + assert "private.test" not in rendered @pytest.mark.parametrize( @@ -767,33 +496,28 @@ def test_transport_errors(error_type, expected): error = error_type(request=httpx.Request("GET", "https://private.test")) client = NS(tasks=NS(get_status=AsyncMock(side_effect=error))) with pytest.raises(expected) as raised: - asyncio.run(tasks.status(client, "id", billing="included")) - assert raised.value.__cause__ is error + asyncio.run(tasks.Tasks(client=client, billing="included").status("id")) + assert raised.value.__cause__ is None and raised.value.__context__ is None @pytest.mark.parametrize("content", ["{broken", "[]", '{"api_key": 123}']) -def test_corrupt_credentials_are_not_silent_logout(monkeypatch, tmp_path, content): +def test_corrupt_credentials_are_not_silent_logout(tmp_path, content): path = tmp_path / "credentials.json" path.write_text(content) - monkeypatch.setattr(cloud_credentials, "credential_path", lambda: path) with pytest.raises(CredentialFormatError): - cloud_credentials.load_credentials() + LoginStore(path).load() -def test_unreadable_credentials_are_not_silent_logout(monkeypatch, tmp_path): - monkeypatch.setattr(cloud_credentials, "credential_path", lambda: tmp_path) +def test_unreadable_credentials_are_not_silent_logout(tmp_path): with pytest.raises(CredentialReadError): - cloud_credentials.load_credentials() + LoginStore(tmp_path).load() -def test_missing_credentials_are_logged_out(monkeypatch, tmp_path): - monkeypatch.setattr( - cloud_credentials, "credential_path", lambda: tmp_path / "missing" - ) - assert cloud_credentials.load_credentials() is None +def test_missing_credentials_are_logged_out(tmp_path): + assert LoginStore(tmp_path / "missing").load() is None -def test_stream_failure_is_sanitized_and_chained(): +def test_stream_failure_is_sanitized_and_detached(): error = httpx.ReadError("signed URL containing private token") class Stream: @@ -808,44 +532,14 @@ async def attach(*args, **kwargs): client = NS(tasks=NS(with_streaming_response=NS(attach=attach))) async def consume(): - return [line async for line in tasks.progress(client, "id", billing="included")] + return [ + line + async for line in tasks.Tasks(client=client, billing="included").progress( + "id" + ) + ] with pytest.raises(CloudConnectionError) as raised: asyncio.run(consume()) assert "private" not in str(raised.value) - assert raised.value.__cause__ is error - - -def test_auth_response_body_never_reaches_public_errors(monkeypatch): - from mobilerun.clients.cloud import device_flow - - response = httpx.Response( - 403, - text="private token and credentials", - request=httpx.Request("POST", "https://auth.test/device/code"), - ) - monkeypatch.setattr(device_flow, "_request", AsyncMock(return_value=response)) - with pytest.raises(CloudPermissionDenied) as raised: - asyncio.run( - device_flow.request_code("https://auth.test", "client", billing="included") - ) - assert "private" not in str(raised.value) - assert raised.value.__cause__ is not None - - -def test_driver_action_sdk_error_is_sanitized(): - from mobilerun.core.devices.cloud import CloudDevice - - device = CloudDevice("id", api_key="fake") - error = APIStatusError( - "private response text", - response=httpx.Response( - 401, request=httpx.Request("POST", "https://private.test") - ), - body=None, - ) - device._write_client = NS(devices=NS(actions=NS(tap=AsyncMock(side_effect=error)))) - with pytest.raises(CloudAuthenticationError) as raised: - asyncio.run(device.tap(1, 2)) - assert raised.value.__cause__ is error - assert "private" not in str(raised.value) + assert raised.value.__cause__ is None and raised.value.__context__ is None diff --git a/tests/unit/clients/cloud/test_privacy.py b/tests/unit/clients/cloud/test_privacy.py index cc5d3fdce..325e631fd 100644 --- a/tests/unit/clients/cloud/test_privacy.py +++ b/tests/unit/clients/cloud/test_privacy.py @@ -5,28 +5,31 @@ import re import time import traceback -from contextlib import asynccontextmanager, nullcontext +from contextlib import nullcontext from types import SimpleNamespace as NS from unittest.mock import AsyncMock, patch import httpx import pytest +from mobilerun_core import AsyncDevice, Socks5Proxy from mobilerun_sdk import APIStatusError, AsyncMobilerun, BadRequestError, NotFoundError -from mobilerun.clients.cloud import apps, devices, files, proxies, secrets -from mobilerun.clients.cloud.errors import cloud_error +from mobilerun.clients.cloud import client as cloud_connection +from mobilerun.clients.cloud.errors import CloudErrorMapper +from mobilerun.clients.cloud.numbers import Numbers +from mobilerun.clients.cloud.secrets import Vault from mobilerun.core.credentials.cloud import CloudCredentials +from mobilerun.core.extensions import compile_tools +from mobilerun.core.proxy import CloudSocks5Proxy +from mobilerun.core.workspace import Workspace from mobilerun.errors import CloudAPIError, CloudPermissionDenied, CloudValidationError from mobilerun.models.billing import Billing from mobilerun.sandbox.clients import run_logs -from mobilerun.utils.redaction import _redact_secrets, secret_scope -from tests.support.devices import MemoryDevice +from mobilerun.utils.redaction import redact, secret_scope -@pytest.mark.parametrize( - "operation", ["device", "proxy", "save", "create_field", "update"] -) -def test_sdk_request_options_never_log_secrets(monkeypatch, caplog, operation): +@pytest.mark.parametrize("operation", ["save", "create_field", "update"]) +def test_sdk_request_options_never_log_secrets(caplog, operation): secret = "sdk-sentinel-password-987654" caplog.set_level(logging.DEBUG, logger="mobilerun_sdk._base_client") sdk = AsyncMobilerun( @@ -40,64 +43,29 @@ def test_sdk_request_options_never_log_secrets(monkeypatch, caplog, operation): ), ) - @asynccontextmanager - async def client(*args, **kwargs): - yield sdk - - monkeypatch.setattr(proxies, "cloud_client", client) - async def run(): + vault = Vault(client=sdk, billing=Billing.NO_COMMERCE) try: with pytest.raises(CloudValidationError): - if operation == "device": - await devices.create( - client=sdk, - billing=Billing.PAID, - proxy={ - "socks5": { - "host": "example.test", - "port": 1080, - "password": secret, - } - }, - ) - elif operation == "proxy": - await proxies.connect_device( - "device", - { - "socks5": { - "host": "example.test", - "port": 1080, - "password": secret, - } - }, - billing=Billing.NO_COMMERCE, - ) - elif operation == "save": - await secrets.save( - sdk, + if operation == "save": + await vault.save( "pkg", "name", {"password": secret}, - billing=Billing.NO_COMMERCE, ) elif operation == "create_field": - await secrets.create_field( - sdk, + await vault.create_field( "pkg", "name", "password", secret, - billing=Billing.NO_COMMERCE, ) else: - await secrets.update( - sdk, + await vault.update( "pkg", "name", "password", secret, - billing=Billing.NO_COMMERCE, ) finally: await sdk.close() @@ -107,7 +75,34 @@ async def run(): assert all(secret not in repr(r.__dict__) for r in caplog.records) -@pytest.mark.parametrize("kind", ["logs", "file", "app"]) +def test_socks5_tool_masks_credentials_in_debug_log_records( + caplog: pytest.LogCaptureFixture, +) -> None: + username, password = "proxy-user-canary", "proxy-password-canary" + phone = AsyncMock(spec=AsyncDevice) + proxy = CloudSocks5Proxy.from_url( + f"socks5://{username}:{password}@example.test:1080", device=phone + ) + logger = logging.getLogger("proxy-test.transport") + + async def set_proxy(value: Socks5Proxy, *, replace: bool) -> None: + assert value.user is not None and value.password is not None + logger.debug("Proxy request %s", (value.user.reveal(), value.password.reveal())) + + phone.set_proxy.side_effect = set_proxy + apply = next(tool for tool in compile_tools([proxy]) if tool.name == "proxy.apply") + with caplog.at_level(logging.DEBUG, logger=logger.name): + asyncio.run(apply.invoke({})) + + assert "Proxy request" in caplog.text + assert all( + secret not in repr(record.__dict__) + for secret in (username, password) + for record in caplog.records + ) + + +@pytest.mark.parametrize("kind", ["logs", "file"]) @pytest.mark.parametrize("status", [200, 403]) def test_signed_transfers_hide_queries(kind, status, monkeypatch, caplog, tmp_path): url = "https://storage.invalid/blob?sig=first-canary" @@ -135,25 +130,18 @@ def respond(request): else: path = tmp_path / "file.apk" path.write_bytes(b"data") - if kind == "app": - monkeypatch.setattr(apps, "inspect_apk", lambda _: ("pkg", 1, "1", "name")) - monkeypatch.setattr(apps, "cloud_client", lambda *a, **kw: nullcontext(sdk)) - sdk.apps.create_signed_upload_url.return_value = NS( - version_id="v", - app_id="a", - r2_upload_urls=[NS(file_name=path.name, r2_upload_url=url)], - ) - call = apps.upload_app(path, **kw) - else: - sdk.files.upload_url.return_value = NS(put_url=url, file_id="file") - sdk.files.confirm.return_value = NS( - file_id="file", - filename=path.name, - mime_type="application/octet-stream", - size_bytes=4, - created_at=None, - ) - call = files.upload_file(sdk, path, **kw) + monkeypatch.setattr( + cloud_connection, "cloud_client", lambda *a, **kw: nullcontext(sdk) + ) + sdk.files.upload_url.return_value = NS(put_url=url, file_id="file") + sdk.files.confirm.return_value = NS( + file_id="file", + filename=path.name, + mime_type="application/octet-stream", + size_bytes=4, + created_at=None, + ) + call = Workspace(**kw).upload_file(path) text = "" if status == 403: @@ -190,11 +178,24 @@ def test_vault_sdk_echo_not_in_traceback(action): method.side_effect = rejection(403, {"echo": password}) with pytest.raises(CloudPermissionDenied) as err: asyncio.run( - getattr(secrets, action)(sdk, "pkg", "name", *args, billing="no_commerce") + getattr(Vault(client=sdk, billing="no_commerce"), action)( + "pkg", "name", *args + ) ) assert password not in "".join(traceback.format_exception(err.value)) +def test_resource_error_traceback_cannot_print_sdk_secret(): + canary = "account-server-trace-canary" + sdk = NS( + numbers=NS(retrieve=AsyncMock(side_effect=rejection(403, {"echo": canary}))) + ) + with pytest.raises(CloudPermissionDenied) as err: + asyncio.run(Numbers(client=sdk, billing="included").retrieve("id")) + assert canary not in "".join(traceback.format_exception(err.value)) + assert err.value.__context__ is None and err.value.__cause__ is None + + def test_credentials_update_preserves_safe_diagnostics(monkeypatch): sdk = AsyncMock() sdk.credentials.packages.credentials.fields.update.side_effect = rejection( @@ -208,7 +209,7 @@ def test_credentials_update_preserves_safe_diagnostics(monkeypatch): asyncio.run(vault.update("pkg", "name", "password", "vault-canary")) assert (err.value.status, err.value.request_id, err.value.value_safe) == ( 403, - "vault-req", + None, True, ) assert err.value.__context__ is None and err.value.__cause__ is None @@ -216,7 +217,10 @@ def test_credentials_update_preserves_safe_diagnostics(monkeypatch): def test_validation_with_null_location_is_still_a_cloud_error(): exc = rejection(422, {"detail": [{"loc": None}]}) - assert type(cloud_error(exc, "Cloud request")) is CloudValidationError + assert ( + type(CloudErrorMapper.from_exception(exc, "Cloud request")) + is CloudValidationError + ) def test_credentials_update_drops_unsafe_notes_and_causes(monkeypatch): @@ -224,7 +228,7 @@ def test_credentials_update_drops_unsafe_notes_and_causes(monkeypatch): password = "secret-note-canary" error.add_note(password) error.__cause__ = RuntimeError(password) - monkeypatch.setattr(secrets, "update", AsyncMock(side_effect=error)) + monkeypatch.setattr(Vault, "update", AsyncMock(side_effect=error)) monkeypatch.setattr( "mobilerun.core.credentials.cloud.cloud_client", lambda *a, **kw: AsyncMock() ) @@ -239,13 +243,13 @@ def test_vault_write_debug_logs_do_not_disclose_values(caplog): log = logging.getLogger("mobilerun_sdk._base_client") caplog.set_level(logging.DEBUG, logger=log.name) - async def update(client, package, name, field, value, **kwargs): + async def update(package, name, field, value): log.debug("request %s", {"value": value}) async def run(): vault = CloudCredentials(api_key="dummy") with patch( - "mobilerun.core.credentials.cloud.secrets.update", + "mobilerun.core.credentials.cloud.Vault.update", AsyncMock(side_effect=update), ): await vault.update("app", "work", "password", secret) @@ -261,7 +265,7 @@ def test_vault_write_failure_redacts_secret(): async def run(): vault = CloudCredentials(api_key="dummy") with patch( - "mobilerun.core.credentials.cloud.secrets.update", + "mobilerun.core.credentials.cloud.Vault.update", AsyncMock(side_effect=RuntimeError(secret)), ): with pytest.raises(RuntimeError) as error: @@ -359,12 +363,14 @@ async def delete(self, field_type, *, package_name, credential_name): del self.vault.data[package_name][credential_name][field_type] -def test_writes_create_update_delete_and_invalidate_cache(caplog): +def test_writes_create_update_delete_and_invalidate_cache(caplog, monkeypatch): async def run(): - vault = CloudCredentials(api_key="dummy", base_url="https://example.invalid") fake = FakeVault() - vault._client = NS(credentials=fake) - await vault.bind(MemoryDevice()) + monkeypatch.setattr( + "mobilerun.core.credentials.cloud.cloud_client", + lambda *a, **kw: NS(credentials=fake), + ) + vault = CloudCredentials(api_key="dummy", base_url="https://example.invalid") assert await vault.list() == [] await vault.save("app.test", "work", {"password": "hidden-value"}) assert (await vault.list())[0] == { @@ -392,13 +398,15 @@ async def run(): asyncio.run(run()) -def test_save_reuses_initialized_empty_package(): +def test_save_reuses_initialized_empty_package(monkeypatch): async def run(): - vault = CloudCredentials(api_key="dummy", base_url="https://example.invalid") fake = FakeVault() fake.data["ai-mobilerun-smoke-test"] = {} - vault._client = NS(credentials=fake) - await vault.bind(MemoryDevice()) + monkeypatch.setattr( + "mobilerun.core.credentials.cloud.cloud_client", + lambda *a, **kw: NS(credentials=fake), + ) + vault = CloudCredentials(api_key="dummy", base_url="https://example.invalid") await vault.save("ai.mobilerun.smoke.test", "work", {"password": "dummy-value"}) assert [ item["name"] for item in await vault.list("ai.mobilerun.smoke.test") @@ -409,11 +417,14 @@ async def run(): asyncio.run(run()) -def test_invalid_field_rejected_before_any_write(): +def test_invalid_field_rejected_before_any_write(monkeypatch): async def run(): - vault = CloudCredentials(api_key="dummy", base_url="https://example.invalid") fake = FakeVault() - vault._client = NS(credentials=fake) + monkeypatch.setattr( + "mobilerun.core.credentials.cloud.cloud_client", + lambda *a, **kw: NS(credentials=fake), + ) + vault = CloudCredentials(api_key="dummy", base_url="https://example.invalid") with pytest.raises(ValueError, match="field type"): await vault.save("app.test", "work", {"invalid": "secret"}) with pytest.raises(ValueError, match="field type"): @@ -425,12 +436,14 @@ async def run(): asyncio.run(run()) -def test_package_read_uses_package_endpoint_after_save(): +def test_package_read_uses_package_endpoint_after_save(monkeypatch): async def run(): - vault = CloudCredentials(api_key="dummy", base_url="https://example.invalid") fake = FakeVault() - vault._client = NS(credentials=fake) - await vault.bind(MemoryDevice()) + monkeypatch.setattr( + "mobilerun.core.credentials.cloud.cloud_client", + lambda *a, **kw: NS(credentials=fake), + ) + vault = CloudCredentials(api_key="dummy", base_url="https://example.invalid") await vault.list() await vault.save("app.test", "work", {"password": "dummy-value"}) original_list = fake.list @@ -471,32 +484,32 @@ def test_formatted_digits_redacted_in_log(caplog, value, display): @pytest.mark.parametrize("value", ["id:234567", "api234567"]) def test_alphanumeric_secrets_are_literal_only(value): with secret_scope(value): - assert _redact_secrets(f"{value}; order 234-567") == "***; order 234-567" + assert redact(f"{value}; order 234-567") == "***; order 234-567" @pytest.mark.parametrize("reverse", [False, True]) def test_overlapping_secret_variants_leave_no_suffix(reverse): values = ("4111", "4111111111111111", "label", "label-private") with secret_scope(*(values[::-1] if reverse else values)): - assert _redact_secrets("4111 1111 1111 1111 label-private") == "*** ***" + assert redact("4111 1111 1111 1111 label-private") == "*** ***" def test_short_numbers_and_longer_unrelated_digit_runs(): with secret_scope("1/2", "4826"): message = "Order 12; transaction 948267; other 94-8267" - assert _redact_secrets(message) == message - assert _redact_secrets("literal 1/2") == "literal ***" + assert redact(message) == message + assert redact("literal 1/2") == "literal ***" def test_lone_surrogate_retains_literal_and_escaped_protection(): value = "test\ud800" with secret_scope(value): - assert _redact_secrets(value + " " + repr(value)[1:-1]) == "*** ***" + assert redact(value + " " + repr(value)[1:-1]) == "*** ***" def test_no_active_scope_returns_message_unchanged(): message = "Order 12; 4111 1111 1111 1111" - assert _redact_secrets(message) is message + assert redact(message) is message @pytest.mark.parametrize( @@ -527,13 +540,13 @@ def test_no_active_scope_returns_message_unchanged(): ) def test_numeric_candidate_boundaries(value, message, expected): with secret_scope(value): - assert _redact_secrets(message) == expected + assert redact(message) == expected def test_secret_patterns_do_not_enter_process_regex_cache(): marker = "regexcachecanary723819" with secret_scope(marker): - assert _redact_secrets(marker) == "***" + assert redact(marker) == "***" assert not any(marker in str(key) for key in re._cache) @@ -544,5 +557,21 @@ def test_large_active_scope_scan_budget(): ): start = time.process_time() for _ in range(4): - assert _redact_secrets(text) is text + assert redact(text) is text assert time.process_time() - start < 0.5 + + +def test_account_error_uses_detached_core_facts_without_original_sdk_response(): + from mobilerun_core import cloud_error_facts + from mobilerun_core.errors import CloudRequestError + + facts = cloud_error_facts( + rejection(422, {"code": "unsupported_country", "message": "account-canary"}) + ) + error = CloudErrorMapper.from_exception(CloudRequestError(facts), "Create number") + assert (error.status, error.request_id, error.code) == ( + 422, + None, + "unsupported_number_country", + ) + assert "account-canary" not in str(error) diff --git a/tests/unit/clients/cloud/test_provisioning.py b/tests/unit/clients/cloud/test_provisioning.py index d02df7f21..e1ed15f67 100644 --- a/tests/unit/clients/cloud/test_provisioning.py +++ b/tests/unit/clients/cloud/test_provisioning.py @@ -1,305 +1,95 @@ -"""Cloud provisioning, ownership, billing guardrails and SDK wire contracts.""" +"""Cloud phone billing policy and account resource provisioning.""" -import ast import asyncio -import inspect -import json import logging -from contextlib import asynccontextmanager from types import SimpleNamespace as NS +from typing import cast from unittest.mock import AsyncMock import httpx import pytest -from mobilerun_core_local.driver import cloud as cloud_module -from mobilerun_core_local.driver.base import DeviceDisconnectedError -from mobilerun_sdk import APIStatusError, AsyncMobilerun - -from mobilerun.clients.cloud import devices, numbers, payments, proxies -from mobilerun.core.devices import AndroidDevice, CloudDevice, DevicePool -from mobilerun.core.devices.base import Device -from mobilerun.core.devices.components import environment +from mobilerun_core import CloudPlan +from mobilerun_sdk import APIStatusError + +from mobilerun.clients.cloud import numbers +from mobilerun.clients.cloud.billing_policy import BillingPolicy +from mobilerun.clients.cloud.payments import PaymentFlow from mobilerun.core.mailbox import CloudMailbox from mobilerun.core.phone_number import CloudPhoneNumber from mobilerun.errors import ( BillingError, CloudConflict, - CloudConnectionError, CloudError, - CloudPermissionDenied, - CloudTimeout, PurchaseInProgress, ) +from mobilerun.errors.cloud import BillingRequired from mobilerun.models import Billing from mobilerun.models.checkout import PaymentSnapshot -from tests.support.paths import REPO_ROOT -@pytest.fixture -def cloud(monkeypatch): +def test_bound_phone_adapter_reuses_factory_and_resolves_default_at_creation( + monkeypatch, +): + monkeypatch.setenv("MOBILERUN_BILLING", "included") + assert BillingPolicy.cloud_phone_plan() == "subscription" monkeypatch.setenv("MOBILERUN_BILLING", "paid") - from mobilerun_core_local.driver import cloud as driver - - devices = NS( - retrieve_capabilities=AsyncMock( - return_value=NS(capabilities=NS(telephony=False, proxy=True)) - ), - create=AsyncMock(return_value=NS(id="created", name="created")), - wait_ready=AsyncMock(), - terminate=AsyncMock(), - number=NS(retrieve=AsyncMock(return_value=NS(binding=None))), - actions=NS(tap=AsyncMock()), - ) - client = NS(devices=devices, with_options=lambda **kw: client, close=AsyncMock()) - monkeypatch.setattr(driver, "AsyncMobilerun", lambda **kw: client) - return devices - - -def test_create_on_connect_and_cleanup(cloud, monkeypatch): - monkeypatch.setenv("MOBILERUN_CLOUD_DEVICE_TYPE", "ios_phone") - - async def run(): - device = CloudDevice(api_key="test", name="example") - assert device.device_id is None - await asyncio.gather(device.connect(), device.connect()) - assert device.device_id == "created" - cloud.create.assert_awaited_once_with( - device_type="ios_phone", - name="example", - billing="auto", - proxy={"connect": {"country": "us"}, "smart_ip": True}, - ) - await device.close() - await device.close() - cloud.terminate.assert_awaited_once_with("created") - - asyncio.run(run()) - - -@pytest.mark.parametrize("keep", [False, True]) -def test_context_and_keep(cloud, keep): - async def run(): - async with CloudDevice( - api_key="test", keep=keep, device_type="device_slot" - ) as device: - assert device.identifier == "created" - assert device._keep is keep - cloud.create.assert_awaited_once_with( - device_type="device_slot", - billing="auto", - proxy={"connect": {"country": "us"}, "smart_ip": True}, - ) - assert cloud.terminate.await_count == (0 if keep else 1) - - asyncio.run(run()) - - -def test_existing_id_is_never_owned(cloud): - async def run(): - phone = CloudDevice("existing", api_key="test") - from mobilerun.core.proxy import ProxyStatus - - phone._proxy_status = AsyncMock(return_value=ProxyStatus(False)) - async with phone: - pass - phone._proxy_status.assert_awaited_once() - cloud.create.assert_not_awaited() - cloud.terminate.assert_not_awaited() - - asyncio.run(run()) - - -def test_pool_lifecycle(cloud): - async def run(): - phone = CloudDevice(api_key="test") - async with DevicePool([phone]): - assert phone.device_id == "created" - cloud.terminate.assert_awaited_once_with("created") - - asyncio.run(run()) - - -def test_action_requires_awaited_construction(cloud): - async def run(): - device = CloudDevice(api_key="test") - with pytest.raises(RuntimeError, match="Await"): - await device.tap(1, 2) - cloud.create.assert_not_awaited() - await device - await device.tap(1, 2) - assert cloud.actions.tap.await_args.args == ("created",) - await device.close() - - asyncio.run(run()) - - -def test_creation_failure_cleans_up(cloud): - cloud.wait_ready.side_effect = RuntimeError("not ready") - - async def run(): - device = CloudDevice(api_key="test") - with pytest.raises(RuntimeError, match="not ready"): - await device - cloud.terminate.assert_awaited_once_with("created") - - asyncio.run(run()) - - -def test_auto_create_accepts_device_options(cloud): - from mobilerun.core.operator import Operator - - operator = Operator() - device = CloudDevice(api_key="test", operator=operator, name="test") - assert device._operator is operator - asyncio.run(device.connect()) - cloud.create.assert_awaited_once_with( - device_type="android_cloud_phone", - name="test", - billing="auto", - proxy={"connect": {"country": "us"}, "smart_ip": True}, - ) - - -def test_documented_creation_options_reach_sdk_and_name_comes_from_server(cloud): - cloud.create.return_value = NS(id="created", name="server-name") - - async def run(): - phone = await CloudDevice( - api_key="test", - name="requested", - country="DE", - locale="de-DE", - timezone="Europe/Berlin", - android_version=15, - apps=["com.android.chrome"], - ) - assert phone.name == "server-name" - cloud.create.assert_awaited_once_with( - device_type="android_cloud_phone", - billing="auto", - name="requested", - body_country="DE", - locale="de-DE", - timezone="Europe/Berlin", - android_version=15, - apps=["com.android.chrome"], - proxy={"connect": {"country": "us"}, "smart_ip": True}, - ) - await phone.close() - - asyncio.run(run()) - - -def test_template_is_forwarded_without_request_apps_or_version(cloud): - phone = CloudDevice(api_key="test", name="prepared", template="onboarding") - asyncio.run(phone.connect()) - assert cloud.create.await_args.kwargs["template"] == "onboarding" - assert "apps" not in cloud.create.await_args.kwargs - assert "android_version" not in cloud.create.await_args.kwargs - - -def test_pool_explicit_close(cloud): - async def run(): - pool = DevicePool([CloudDevice(api_key="test")]) - await pool.__aenter__() - await pool.close() - cloud.terminate.assert_awaited_once_with("created") - - asyncio.run(run()) - - -def test_pool_context_cleans_up_if_another_device_cannot_connect(cloud): - class Broken(Device): - @property - def needs_initialization(self): - return False - - async def _ensure_connected(self): - raise RuntimeError("connect failed") - - async def close(self): - pass - - async def run(): - with pytest.raises(ExceptionGroup): - async with DevicePool([CloudDevice(api_key="test"), Broken()]): - pass - cloud.terminate.assert_awaited_once_with("created") - - asyncio.run(run()) - - -def test_owned_cloud_phone_is_terminated_through_wrapper(cloud): - from mobilerun.core.devices.recording import RecordingDevice - - async def run(): - async with RecordingDevice( - CloudDevice(api_key="test", billing="paid", plan="minute") - ) as device: - assert device.identifier == "created" - cloud.create.assert_awaited_once_with( - device_type="android_cloud_phone", - billing="minute", - proxy={"connect": {"country": "us"}, "smart_ip": True}, - ) - cloud.terminate.assert_awaited_once_with("created") - - asyncio.run(run()) + assert BillingPolicy.cloud_phone_plan() == "auto" -OPTIONS = dict( - name="named", - country="DE", - locale="de_DE", - timezone="Europe/Berlin", - android_version=15, - apps=["app"], - template="onboarding", +@pytest.mark.parametrize( + "environment,billing,plan,keep,expected", + [ + (None, None, None, True, "auto"), + ("included", None, None, True, "subscription"), + ("no_commerce", "paid", "minute", False, "minute"), + ("paid", "included", "subscription", True, "subscription"), + ("paid", None, None, False, "auto"), + ], ) +def test_create_cloud_phone_applies_billing_before_core( + monkeypatch: pytest.MonkeyPatch, + environment: str | None, + billing: str | None, + plan: CloudPlan | None, + keep: bool, + expected: CloudPlan, +) -> None: + if environment is None: + monkeypatch.delenv("MOBILERUN_BILLING", raising=False) + else: + monkeypatch.setenv("MOBILERUN_BILLING", environment) + assert BillingPolicy.cloud_phone_plan(plan, billing=billing) == expected -@pytest.mark.parametrize("key,value", OPTIONS.items()) -def test_creation_options_are_explicit_and_forbidden_for_existing_phone(key, value): - assert key in inspect.signature(CloudDevice).parameters - with pytest.raises(TypeError, match="only used when creating a phone"): - CloudDevice("existing", api_key="fake", **{key: value}) - - -def test_unknown_options_fail_before_transport(): - with pytest.raises(TypeError, match="unexpected"): - CloudDevice(api_key="fake", naem="typo") - - -def test_name_is_read_only_and_refreshed_from_info_and_rename(monkeypatch): - phone = CloudDevice("existing", api_key="fake") - monkeypatch.setattr(devices, "retrieve", AsyncMock(return_value=NS(name="old"))) - rename = AsyncMock(return_value=NS(name="server normalized")) - monkeypatch.setattr(devices, "set_name", rename) - - async def run(): - assert phone.name is None - await phone.info() - assert phone.name == "old" - await phone.rename("new") - assert phone.name == "server normalized" - rename.assert_awaited_once_with( - "existing", "new", billing=phone._billing, client=phone._cloud_client - ) - - asyncio.run(run()) - with pytest.raises(AttributeError): - phone.name = "local" - - -def test_set_name_boundary_uses_sdk_and_free_billing(): - endpoint = AsyncMock(return_value=NS(name="new")) - result = asyncio.run( - devices.set_name( - "id", "new", billing="no_commerce", client=NS(devices=NS(set_name=endpoint)) +@pytest.mark.parametrize( + "environment,billing,plan,required", + [ + ("no_commerce", None, None, Billing.INCLUDED), + ("no_commerce", None, "minute", Billing.PAID), + ("paid", "no_commerce", "subscription", Billing.INCLUDED), + ("paid", "included", "auto", Billing.PAID), + ("included", None, "minute", Billing.PAID), + ], +) +def test_create_cloud_phone_rejects_restricted_billing( + monkeypatch: pytest.MonkeyPatch, + environment: str, + billing: str | None, + plan: CloudPlan | None, + required: Billing, +) -> None: + monkeypatch.setenv("MOBILERUN_BILLING", environment) + with pytest.raises(BillingRequired) as caught: + BillingPolicy.cloud_phone_plan(plan, billing=billing) + + assert caught.value.needed is required + + +def test_create_cloud_phone_does_not_echo_invalid_plan() -> None: + with pytest.raises(ValueError, match="plan must be auto, subscription or minute"): + BillingPolicy.cloud_phone_plan( + cast(CloudPlan, "invalid-plan-canary"), billing="paid" ) - ) - assert result.name == "new" - endpoint.assert_awaited_once_with("id", name="new") def test_number_waits_for_active_with_configured_timeout(monkeypatch, caplog): @@ -311,7 +101,7 @@ def test_number_waits_for_active_with_configured_timeout(monkeypatch, caplog): NS(data=NS(state="active", phone_number="example", checkout_url=None)), ] ) - monkeypatch.setattr(numbers, "retrieve", retrieve) + monkeypatch.setattr(numbers.Numbers, "retrieve", retrieve) monkeypatch.setattr("mobilerun.core.phone_number.cloud.asyncio.sleep", AsyncMock()) number = CloudPhoneNumber("id", billing="no_commerce") with caplog.at_level("DEBUG", logger="mobilerun.core.phone_number.cloud"): @@ -323,7 +113,7 @@ def test_number_waits_for_active_with_configured_timeout(monkeypatch, caplog): @pytest.mark.parametrize("state", ["failed", "expired", "cancel_scheduled"]) def test_number_wait_rejects_terminal_states(monkeypatch, state): monkeypatch.setattr( - numbers, + numbers.Numbers, "retrieve", AsyncMock(return_value=NS(data=NS(state=state, checkout_url=None))), ) @@ -332,22 +122,6 @@ def test_number_wait_rejects_terminal_states(monkeypatch, state): assert caught.value.status == state -def test_rename_maps_sdk_errors_without_changing_cached_name(): - phone = CloudDevice("id", api_key="fake") - phone._name = "unchanged" - error = APIStatusError( - "private", - response=httpx.Response( - 403, request=httpx.Request("PUT", "https://example.test") - ), - body={}, - ) - phone._client = NS(devices=NS(set_name=AsyncMock(side_effect=error))) - with pytest.raises(CloudPermissionDenied): - asyncio.run(phone.rename("new")) - assert phone.name == "unchanged" - - @pytest.mark.parametrize("timeout", [0, -1]) def test_number_wait_rejects_invalid_timeout(timeout): with pytest.raises(ValueError, match="positive"): @@ -357,7 +131,7 @@ def test_number_wait_rejects_invalid_timeout(timeout): def test_number_wait_explicit_timeout_overrides_setting(monkeypatch): monkeypatch.setenv("MOBILERUN_CLOUD_NUMBER_READY_TIMEOUT_SECONDS", "600") monkeypatch.setattr( - numbers, + numbers.Numbers, "retrieve", AsyncMock(return_value=NS(data=NS(state="provisioning", checkout_url=None))), ) @@ -368,7 +142,7 @@ def test_number_wait_explicit_timeout_overrides_setting(monkeypatch): def test_number_wait_timeout_reports_last_state(monkeypatch): monkeypatch.setenv("MOBILERUN_CLOUD_NUMBER_READY_TIMEOUT_SECONDS", "0.001") monkeypatch.setattr( - numbers, + numbers.Numbers, "retrieve", AsyncMock(return_value=NS(data=NS(state="provisioning", checkout_url=None))), ) @@ -437,7 +211,9 @@ def test_pending_purchase_requires_verifiable_identity(options): ) with pytest.raises(CloudConflict) as caught: asyncio.run( - numbers.create(client=sdk, billing=Billing.PAID, country="US", **options) + numbers.Numbers(client=sdk, billing=Billing.PAID).create( + country="US", **options + ) ) assert not isinstance(caught.value, PurchaseInProgress) @@ -462,46 +238,6 @@ def test_number_wait_ready_uses_activation_seen_during_checkout_poll( assert number.phone_number == "+123" -def test_paid_binding_smoke_calls_match_device_client_signatures(): - # Find the workflow by test name, not filename: smoke modules can be regrouped. - name = "test_paid_number_bind_unbind_and_release" - workflows = [] - for path in (REPO_ROOT / "tests/unit/smoke").glob("test_*.py"): - source = path.read_text() - if name in source: - workflows.extend( - node - for node in ast.parse(source).body - if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) - and node.name == name - ) - assert len(workflows) == 1, f"Expected one smoke workflow named {name}" - # The workflow uses `phone` for the owned device and `observer` for the borrowed one. - attributes = { - node.attr - for node in ast.walk(workflows[0]) - if isinstance(node, ast.Attribute) - and isinstance(node.value, ast.Name) - and node.value.id in {"phone", "observer"} - } - assert {"number", "actions", "close"} <= attributes - unknown = {attr for attr in attributes if not hasattr(CloudDevice, attr)} - assert not unknown, f"Unknown CloudDevice attributes: {sorted(unknown)}" - operations = set() - for call in ast.walk(workflows[0]): - if ( - isinstance(call, ast.Call) - and isinstance(call.func, ast.Attribute) - and isinstance(call.func.value, ast.Name) - and call.func.value.id == "devices" - ): - operations.add(call.func.attr) - inspect.signature(getattr(devices, call.func.attr)).bind( - *[None for _ in call.args], **{kw.arg: None for kw in call.keywords} - ) - assert {"number", "list_devices"} <= operations, operations - - @pytest.mark.parametrize( "billing,plan,country", [("included", "auto", "US"), ("paid", "included", "US"), ("paid", "rent", "GB")], @@ -554,7 +290,9 @@ def test_sms_requires_paid_before_transport(billing): sdk = NS(numbers=NS(messages=NS(send=send))) with pytest.raises(BillingError): asyncio.run( - numbers.send("existing", "+123", "test", billing=billing, client=sdk) + numbers.Numbers(billing=billing, client=sdk).send( + "existing", "+123", "test" + ) ) send.assert_not_awaited() @@ -562,14 +300,13 @@ def test_sms_requires_paid_before_transport(billing): def test_checking_proxy_returns_at_provisioning_without_checkout_or_cancel(monkeypatch): provisioning = PaymentSnapshot("provisioning") retrieve = AsyncMock(side_effect=[provisioning, TimeoutError()]) - callback, cancel = AsyncMock(), AsyncMock() - adapter = payments.PaymentAdapter( - "Connect proxy", "proxy", retrieve, cancel, preparing=frozenset({"checking"}) + callback = AsyncMock() + adapter = PaymentFlow( + "Connect proxy", "proxy", retrieve, preparing=frozenset({"checking"}) ) monkeypatch.setattr(asyncio, "sleep", AsyncMock()) result = asyncio.run( - payments.wait_for_payment( - adapter, + adapter.wait_for_payment( PaymentSnapshot("checking"), resume=AsyncMock(), on_checkout=callback, @@ -578,18 +315,16 @@ def test_checking_proxy_returns_at_provisioning_without_checkout_or_cancel(monke assert result == provisioning retrieve.assert_awaited_once() callback.assert_not_awaited() - cancel.assert_not_awaited() @pytest.mark.parametrize("states", [["active"], ["provisioning", "active"]]) def test_activation_without_checkout_url(monkeypatch, states): retrieve = AsyncMock(side_effect=[PaymentSnapshot(state) for state in states]) - adapter = payments.PaymentAdapter("number", "existing", retrieve, AsyncMock()) + adapter = PaymentFlow("number", "existing", retrieve) callback = AsyncMock() monkeypatch.setattr(asyncio, "sleep", AsyncMock()) result = asyncio.run( - payments.wait_for_payment( - adapter, + adapter.wait_for_payment( PaymentSnapshot("awaiting_payment"), resume=AsyncMock(), on_checkout=callback, @@ -639,330 +374,3 @@ async def run(): endpoint.delete.assert_awaited_once_with(handle.id) asyncio.run(run()) - - -@pytest.mark.parametrize("cloud", [False, True]) -def test_device_catalog_dispatches_open_url(monkeypatch, cloud): - device = ( - CloudDevice("existing", api_key="test") if cloud else AndroidDevice("local") - ) - backend = AsyncMock() - monkeypatch.setattr( - environment, "cloud_open_url" if cloud else "android_shell", backend - ) - url = "https://example.test" - asyncio.run(device.actions.call("device.open_url", {"url": url})) - backend.assert_awaited_once_with( - device, url if cloud else f"am start -a android.intent.action.VIEW -d {url}" - ) - - -@pytest.fixture( - params=[(cloud_module.CloudDriver, False), (CloudDevice, True)], - ids=["driver", "device"], -) -def cloud_factory(request, monkeypatch): - clients = [] - factory_class, translates_errors = request.param - - @asynccontextmanager - async def proxy_client(*args, **kwargs): - yield clients[-1] - - monkeypatch.setattr(proxies, "cloud_client", proxy_client) - - def factory(handler, **kwargs): - def sdk_client(**options): - client = AsyncMobilerun( - **options, - http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)), - ) - clients.append(client) - return client - - monkeypatch.setattr(cloud_module, "AsyncMobilerun", sdk_client) - return factory_class( - "device-123", - api_key="test-key", - base_url="https://sdk.test/v1", - display_id=2, - **kwargs, - ) - - factory.translates_errors = translates_errors - yield factory - for client in clients: - asyncio.run(client.close()) - - -def test_connect_screenshot_tap_and_apps_use_real_sdk(cloud_factory): - seen = [] - - def handler(request): - seen.append(request) - assert request.headers["authorization"] == "Bearer test-key" - if request.url.path.endswith("/capabilities"): - return httpx.Response( - 200, - json={ - "deviceType": "android_cloud_phone", - "capabilities": {"telephony": True}, - }, - ) - if request.url.path.endswith("/number"): - return httpx.Response(200, json={"data": None}) - if request.url.path.endswith("/proxy"): - assert request.method == "GET" - return httpx.Response( - 200, - json={ - "connected": True, - "name": "mrc:known-proxy", - "protocol": "socks5", - }, - ) - assert request.headers["x-device-display-id"] == "2" - if request.url.path.endswith("/screenshot"): - return httpx.Response( - 200, - content=b"\x89PNG\r\n\x1a\nfixture", - headers={"content-type": "image/png"}, - ) - if request.url.path.endswith("/apps"): - assert request.url.params["includeSystemApps"] == "false" - return httpx.Response( - 200, - json=[ - { - "isSystemApp": False, - "label": "Example", - "packageName": "com.example", - "versionCode": 1, - "versionName": "1.0", - } - ], - ) - assert request.method == "POST" - assert request.url.path == "/v1/devices/device-123/tap" - assert json.loads(request.content) == {"x": 12, "y": 34, "stealth": True} - return httpx.Response(204) - - driver = cloud_factory(handler, stealth=True) - - async def exercise(): - await driver.connect() - if cloud_factory.translates_errors: - await driver._ensure_connected() - assert len(seen) == 3 # Capabilities, number binding and proxy adoption. - assert driver.proxy.id == "known-proxy" - else: - await driver.ensure_connected() - assert not seen - assert await driver.screenshot() == b"\x89PNG\r\n\x1a\nfixture" - await driver.tap(12, 34) - apps = ( - await driver.list_apps(include_system=False) - if cloud_factory.translates_errors - else await driver.get_apps(include_system=False) - ) - assert len(apps) == 1 - assert apps[0]["package_name"] == "com.example" - assert apps[0]["label"] == "Example" - assert apps[0]["is_system_app"] is False - - asyncio.run(exercise()) - assert len(seen) == (6 if cloud_factory.translates_errors else 3) - assert driver._client.max_retries == 4 - assert driver._write_client.max_retries == 0 - - -def test_remaining_driver_calls_preserve_wire_contract(cloud_factory): - seen = [] - tree = { - "a11y_tree": { - "boundsInScreen": {"left": 0, "top": 0, "right": 100, "bottom": 200} - } - } - - def handler(request): - assert request.headers["x-device-display-id"] == "2" - seen.append( - ( - request.method, - request.url.path, - json.loads(request.content) if request.content else None, - ) - ) - if request.url.path.endswith("/ui-state"): - return httpx.Response(200, json=tree) - if request.url.path.endswith("/time"): - return httpx.Response( - 200, text="2026-11-17", headers={"content-type": "text/plain"} - ) - if request.url.path.endswith("/packages"): - assert request.url.params["includeSystemPackages"] == "false" - return httpx.Response(200, json=["com.example"]) - return httpx.Response(204) - - driver = cloud_factory(handler) - - async def exercise(): - await driver.swipe(1, 2, 3, 4, duration_ms=500) - assert await driver.input_text("hello", clear=True, stealth=True, wpm=70) - await driver.press_button("enter") - await driver.press_button("back") - await driver.press_button("home") - assert await driver.start_app("com.example") == "App started: com.example" - await driver.start_app("com.example", activity="MainActivity") - if cloud_factory.translates_errors: - assert await driver._get_date() == "2026-11-17" - result = await driver._get_ui_tree() - else: - assert await driver.list_packages() == ["com.example"] - assert await driver.get_date() == "2026-11-17" - result = await driver.get_ui_tree() - assert result["a11y_tree"] == tree["a11y_tree"] - assert result["device_context"]["screen_bounds"] == { - "width": 100, - "height": 200, - } - - asyncio.run(exercise()) - prefix = "/v1/devices/device-123" - assert seen[:7] == [ - ( - "POST", - prefix + "/swipe", - {"startX": 1, "startY": 2, "endX": 3, "endY": 4, "duration": 500}, - ), - ( - "POST", - prefix + "/keyboard", - {"text": "hello", "clear": True, "stealth": True, "wpm": 70}, - ), - ("PUT", prefix + "/keyboard", {"key": 66}), - ("POST", prefix + "/global", {"action": 1}), - ("POST", prefix + "/global", {"action": 2}), - ("PUT", prefix + "/apps/com.example", {}), - ("PUT", prefix + "/apps/com.example", {"activity": "MainActivity"}), - ] - - -@pytest.mark.parametrize("failure", ["conflict", "connection", "timeout"]) -def test_sdk_disconnect_errors_are_translated_without_retry(cloud_factory, failure): - calls = [] - - def handler(request): - calls.append(request) - if failure == "connection": - raise httpx.ConnectError("offline", request=request) - if failure == "timeout": - raise httpx.ReadTimeout("timed out", request=request) - return httpx.Response(409, json={"detail": "device disconnected"}) - - driver = cloud_factory(handler) - expected = ( - { - "conflict": CloudConflict, - "connection": CloudConnectionError, - "timeout": CloudTimeout, - }[failure] - if cloud_factory.translates_errors - else DeviceDisconnectedError - ) - with pytest.raises(expected): - asyncio.run(driver.tap(1, 2)) - assert len(calls) == 1 - - -def test_internal_auth_headers_survive_sdk_client_copy(cloud_factory): - seen = [] - - def handler(request): - seen.append(request) - assert request.headers["authorization"] == "Bearer x" - assert request.headers["x-user-id"] == "test-user" - assert request.headers["x-owner-id"] == "test-owner" - return httpx.Response(204) - - driver = cloud_factory(handler, user_id="test-user", owner_id="test-owner") - asyncio.run(driver.tap(1, 2)) - assert len(seen) == 1 - - -def test_cli_device_listing_uses_sdk_page_and_models(monkeypatch): - import importlib - from io import StringIO - - from rich.console import Console - - listing = importlib.import_module("mobilerun.cli.devices.list") - clients = [] - output = StringIO() - - def handler(request): - assert request.method == "GET" - assert request.url.path == "/v1/devices" - return httpx.Response( - 200, - json={ - "items": [ - { - "id": "device-123", - "name": "Example", - "state": "ready", - "type": "android_cloud_phone", - "platform": "android", - "activeTaskId": "", - "assignedAt": None, - "createdAt": "2026-11-17T00:00:00Z", - "updatedAt": "2026-11-17T00:00:00Z", - "stateMessage": "", - "streamUrl": "", - "taskCount": 0, - "terminatesAt": None, - } - ], - "pagination": { - "page": 1, - "pageSize": 20, - "total": 1, - "pages": 1, - "hasNext": False, - "hasPrev": False, - }, - }, - ) - - def sdk_client(**options): - client = AsyncMobilerun( - **options, - http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)), - ) - clients.append(client) - return client - - from mobilerun.clients.cloud import client as transport - - monkeypatch.setattr(transport, "AsyncMobilerun", sdk_client) - from mobilerun.cli.devices.base import discovery - - monkeypatch.setattr(discovery, "resolve_cloud_api_key", lambda: "test-key") - monkeypatch.setattr( - listing.render, "stdout", Console(file=output, force_terminal=False) - ) - - async def exercise(): - try: - items = await discovery.discover_devices( - local=False, base_url="https://sdk.test/v1" - ) - assert len(items) == 1 - listing._render_cloud(items) - finally: - for client in clients: - await client.close() - - asyncio.run(exercise()) - assert "device-123" in output.getvalue() - assert "Example" in output.getvalue() diff --git a/tests/unit/clients/cloud/test_proxies.py b/tests/unit/clients/cloud/test_proxies.py new file mode 100644 index 000000000..cb40f456a --- /dev/null +++ b/tests/unit/clients/cloud/test_proxies.py @@ -0,0 +1,39 @@ +"""Connect catalogue filters through the cloud proxy adapter.""" + +import asyncio +from contextlib import nullcontext +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest + +from mobilerun.clients.cloud import client as connection +from mobilerun.core.proxy import list_connect_proxies + + +def test_catalogue_forwards_filters_across_pages( + monkeypatch: pytest.MonkeyPatch, +) -> None: + list_page = AsyncMock( + side_effect=[ + SimpleNamespace(items=[], pagination=SimpleNamespace(has_next=True)), + SimpleNamespace(items=[], pagination=SimpleNamespace(has_next=False)), + ] + ) + client = SimpleNamespace( + connect=SimpleNamespace(proxies=SimpleNamespace(list=list_page)) + ) + monkeypatch.setattr( + connection, "cloud_client", lambda *a, **kw: nullcontext(client) + ) + + async def collect() -> None: + async for _ in list_connect_proxies(country="de", proxy_type="residential"): + pytest.fail("The fake catalogue has no products") + + asyncio.run(collect()) + + assert [call.kwargs for call in list_page.await_args_list] == [ + {"page": 1, "page_size": 100, "country": "de", "type": ["residential"]}, + {"page": 2, "page_size": 100, "country": "de", "type": ["residential"]}, + ] diff --git a/tests/unit/clients/cloud/test_sessions.py b/tests/unit/clients/cloud/test_sessions.py index 9c1fe0b3f..5f9b3855e 100644 --- a/tests/unit/clients/cloud/test_sessions.py +++ b/tests/unit/clients/cloud/test_sessions.py @@ -1,30 +1,30 @@ -"""Cloud authentication, device sessions, capability discovery and recovery.""" +"""Cloud authentication, account SDK access and task recovery.""" import asyncio import json import os import stat -from contextlib import nullcontext +from contextlib import asynccontextmanager from types import SimpleNamespace from unittest.mock import AsyncMock import httpx import pytest from mobilerun_sdk import APIConnectionError, APIStatusError -from mobilerun_sdk.types.device_retrieve_capabilities_response import Capabilities -from mobilerun.clients.cloud import api_keys, apps, devices, proxies, tasks +from mobilerun.clients.cloud import client from mobilerun.clients.cloud import device_flow as deviceauth -from mobilerun.clients.local import login_store as credentials -from mobilerun.core.devices.components import cloud_lifecycle as lifecycle -from mobilerun.errors import CloudValidationError, DeviceOperationNotSupported +from mobilerun.clients.cloud.api_keys import ApiKeys +from mobilerun.clients.cloud.device_flow import DeviceAuthorization +from mobilerun.clients.local.login_store import LoginStore +from mobilerun.core.operator.cloud import CloudTaskOperator from mobilerun.errors.cloud import ( + BillingError, CloudAuthenticationError, CloudConnectionError, CloudPermissionDenied, CloudServiceUnavailable, ) -from mobilerun.models.apps import App from mobilerun.models.billing import Billing @@ -35,16 +35,16 @@ def fake_client(monkeypatch, error=None): devices=SimpleNamespace(list=endpoint) ) - def factory(**kwargs): + def factory(*args, **kwargs): return context - monkeypatch.setattr(api_keys, "cloud_client", factory) + monkeypatch.setattr(client, "cloud_client", factory) return endpoint def test_valid_key_uses_sdk(monkeypatch): endpoint = fake_client(monkeypatch) - asyncio.run(api_keys.validate_api_key("example-key", billing="included")) + asyncio.run(ApiKeys(api_key="example-key", billing="included").validate()) assert endpoint.await_args.kwargs["page_size"] == 1 @@ -63,8 +63,8 @@ def test_http_errors(monkeypatch, status, expected): error = APIStatusError("private response", response=response, body=None) fake_client(monkeypatch, error) with pytest.raises(expected, match=f"HTTP {status}") as raised: - asyncio.run(api_keys.validate_api_key("key", billing="included")) - assert raised.value.__cause__ is error + asyncio.run(ApiKeys(api_key="key", billing="included").validate()) + assert raised.value.__cause__ is None and raised.value.__context__ is None assert "private response" not in str(raised.value) @@ -72,7 +72,39 @@ def test_network_error(monkeypatch): error = APIConnectionError(request=httpx.Request("GET", "https://example.com")) fake_client(monkeypatch, error) with pytest.raises(CloudConnectionError): - asyncio.run(api_keys.validate_api_key("key", billing="included")) + asyncio.run(ApiKeys(api_key="key", billing="included").validate()) + + +def test_device_code_request_does_not_leak_auth_transport_details(monkeypatch, caplog): + secret = "auth-transport-canary" + + def respond(request): + assert request.url.path == "/device/code" + assert json.loads(request.content)["client_id"] == "client" + return httpx.Response(403, text=secret) + + fake = httpx.AsyncClient(transport=httpx.MockTransport(respond)) + monkeypatch.setattr(deviceauth.httpx, "AsyncClient", lambda: fake) + caplog.set_level("DEBUG", logger="httpx") + with pytest.raises(CloudPermissionDenied) as raised: + asyncio.run( + DeviceAuthorization( + f"https://{secret}.test", billing="no_commerce" + ).request_code("client") + ) + assert raised.value.__cause__ is None and raised.value.__context__ is None + assert secret not in str(raised.value) and secret not in caplog.text + assert fake.is_closed + + +def test_login_stores_keep_separate_credentials(tmp_path): + first = LoginStore(tmp_path / "first" / "login.json") + second = LoginStore(tmp_path / "second" / "login.json") + first.save({"api_key": "first"}) + second.save({"access_token": "second"}) + assert first.clear() + assert first.load() is None + assert second.load() == {"access_token": "second"} def _mode(path): @@ -85,9 +117,16 @@ def test_save_token_writes_private_file_and_repairs_directory_permissions( credential_dir = tmp_path / "credentials" credential_dir.mkdir(mode=0o755) credential_file = credential_dir / "mobilerun-cloud.json" - monkeypatch.setattr(credentials, "credential_path", lambda: credential_file) + monkeypatch.setattr( + LoginStore, "from_settings", lambda: LoginStore(credential_file) + ) - path = credentials.save_token("secret-token", "https://cloud.mobilerun.ai/api/auth") + path = LoginStore.from_settings().save( + { + "access_token": "secret-token", + "auth_url": "https://cloud.mobilerun.ai/api/auth", + } + ) assert path == credential_file assert json.loads(path.read_text()) == { @@ -106,9 +145,13 @@ def test_save_token_overwrites_existing_token_privately(monkeypatch, tmp_path): credential_file.write_text("old") if os.name != "nt": os.chmod(credential_file, 0o644) - monkeypatch.setattr(credentials, "credential_path", lambda: credential_file) + monkeypatch.setattr( + LoginStore, "from_settings", lambda: LoginStore(credential_file) + ) - credentials.save_token("new-token", "https://auth.example") + LoginStore.from_settings().save( + {"access_token": "new-token", "auth_url": "https://auth.example"} + ) assert json.loads(credential_file.read_text()) == { "access_token": "new-token", @@ -122,11 +165,13 @@ def test_clear_credentials_removes_file_and_is_idempotent(monkeypatch, tmp_path) credential_file = tmp_path / "credentials" / "mobilerun-cloud.json" credential_file.parent.mkdir() credential_file.write_text("{}") - monkeypatch.setattr(credentials, "credential_path", lambda: credential_file) + monkeypatch.setattr( + LoginStore, "from_settings", lambda: LoginStore(credential_file) + ) - assert credentials.clear_credentials() is True + assert LoginStore.from_settings().clear() is True assert credential_file.exists() is False - assert credentials.clear_credentials() is False + assert LoginStore.from_settings().clear() is False def _device_code(*, expires_in=60): @@ -140,97 +185,79 @@ def _device_code(*, expires_in=60): ) +def _mock_auth_http(monkeypatch, respond): + client = httpx.AsyncClient + monkeypatch.setattr( + deviceauth.httpx, + "AsyncClient", + lambda: client(transport=httpx.MockTransport(respond)), + ) + + +@pytest.mark.parametrize( + "method,args", + [ + ("request_code", ("client",)), + ("poll_token", ("client", _device_code())), + ("fetch_session", ("token",)), + ], +) +def test_auth_refuses_invalid_billing_before_transport(monkeypatch, method, args): + monkeypatch.setattr( + deviceauth.httpx, "AsyncClient", lambda: pytest.fail("auth transport opened") + ) + auth = DeviceAuthorization("https://auth.example", billing="invalid") + with pytest.raises(BillingError): + asyncio.run(getattr(auth, method)(*args)) + + @pytest.mark.parametrize( "reason,second_delay", [("authorization_pending", 2.0), ("slow_down", 5.0)] ) def test_poll_token_retries_until_approved(monkeypatch, reason, second_delay): monkeypatch.setenv("MOBILERUN_DEVICE_AUTH_MIN_POLL_INTERVAL", "2.0") monkeypatch.setenv("MOBILERUN_DEVICE_AUTH_SLOW_DOWN_BUMP", "3.0") - code = _device_code() - calls = [] - sleeps = [] + calls, sleeps = [], [] - async def fake_exchange(_auth_url, _client_id, _device_code): - calls.append("exchange") + def respond(request): + assert request.url.path == "/device/token" + assert json.loads(request.content) == { + "grant_type": "urn:ietf:params:oauth:grant-type:device_code", + "device_code": "device-code", + "client_id": "client", + } + calls.append(request) if len(calls) == 1: - raise deviceauth.DeviceAuthError(reason) - return "token" + return httpx.Response(400, json={"error": reason}) + return httpx.Response(200, json={"access_token": "token"}) - monkeypatch.setattr(deviceauth, "_exchange", fake_exchange) + _mock_auth_http(monkeypatch, respond) monkeypatch.setattr( deviceauth.asyncio, "sleep", AsyncMock(side_effect=sleeps.append) ) - monkeypatch.setattr(deviceauth.time, "monotonic", lambda: len(calls)) - - assert ( - asyncio.run( - deviceauth.poll_token( - "https://auth.example", "client", code, billing="included" - ) - ) - == "token" - ) - assert calls == ["exchange", "exchange"] + auth = DeviceAuthorization("https://auth.example/", billing="included") + assert asyncio.run(auth.poll_token("client", _device_code())) == "token" + assert len(calls) == 2 assert sleeps == [2.0, second_delay] -def test_poll_token_expires_pending_authorization(monkeypatch): - code = _device_code(expires_in=0) - - monkeypatch.setattr( - deviceauth, - "_exchange", - AsyncMock(side_effect=deviceauth.DeviceAuthError("authorization_pending")), - ) - monkeypatch.setattr(deviceauth.asyncio, "sleep", AsyncMock()) - ticks = iter([0, 1]) - monkeypatch.setattr( - deviceauth, - "time", - type("Clock", (), {"monotonic": staticmethod(lambda: next(ticks))}), - ) - - with pytest.raises(deviceauth.DeviceAuthError, match="expired_token"): - asyncio.run( - deviceauth.poll_token( - "https://auth.example", "client", code, billing="included" - ) - ) - - -def test_poll_token_raises_terminal_denial(monkeypatch): - code = _device_code() - - monkeypatch.setattr( - deviceauth, - "_exchange", - AsyncMock(side_effect=deviceauth.DeviceAuthError("access_denied", "denied")), +@pytest.mark.parametrize( + "reason,expected", + [("authorization_pending", "expired_token"), ("access_denied", "access_denied")], +) +def test_poll_token_raises_on_expiration_or_denial(monkeypatch, reason, expected): + _mock_auth_http( + monkeypatch, lambda request: httpx.Response(400, json={"error": reason}) ) monkeypatch.setattr(deviceauth.asyncio, "sleep", AsyncMock()) + auth = DeviceAuthorization("https://auth.example", billing="included") + with pytest.raises(deviceauth.DeviceAuthError, match=expected): + asyncio.run(auth.poll_token("client", _device_code(expires_in=0))) - with pytest.raises(deviceauth.DeviceAuthError, match="access_denied"): - asyncio.run( - deviceauth.poll_token( - "https://auth.example", "client", code, billing="included" - ) - ) - - -def _device(monkeypatch, *, api_key=None, base_url=None): - cloud = pytest.importorskip("mobilerun_core_local.driver.cloud") - from mobilerun.core.devices.cloud import CloudDevice - - calls = [] - def init(self, device_id, api_key=None, base_url=None, **kwargs): - calls.append((device_id, api_key, base_url, kwargs)) - self.device_id = device_id - self._client = None - self._write_client = None - - monkeypatch.setattr(cloud.CloudDriver, "__init__", init) - device = CloudDevice("device-1", api_key=api_key, base_url=base_url) - return device, calls[0] +def _client_options(monkeypatch, *, api_key=None): + monkeypatch.setattr(client, "AsyncMobilerun", lambda **options: options) + return client.cloud_client(api_key, billing=Billing.NO_COMMERCE) @pytest.mark.parametrize( @@ -245,8 +272,7 @@ def test_key_precedence_over_saved_login(monkeypatch, tmp_path, explicit, expect path.parent.mkdir() path.write_text(json.dumps({"api_key": "saved-secret"})) - _, call = _device(monkeypatch, api_key=explicit) - assert call[1] == expected + assert _client_options(monkeypatch, api_key=explicit)["api_key"] == expected @pytest.mark.parametrize("field", ["api_key", "access_token"]) @@ -257,21 +283,17 @@ def test_saved_login_key_variants(monkeypatch, tmp_path, field): path.parent.mkdir() path.write_text(json.dumps({field: "saved-secret"})) - _, call = _device(monkeypatch) - - assert call[1] == "saved-secret" + assert _client_options(monkeypatch)["api_key"] == "saved-secret" def test_missing_credentials_raises_safe_auth_error(monkeypatch, tmp_path): - pytest.importorskip("mobilerun_core_local.driver.cloud") - from mobilerun.core.devices.cloud import CloudDevice from mobilerun.errors import CloudAuthRequired monkeypatch.delenv("MOBILERUN_API_KEY", raising=False) monkeypatch.setenv("MOBILERUN_USER_CONFIG_DIR", str(tmp_path)) with pytest.raises(CloudAuthRequired) as error: - CloudDevice("device-1") + client.cloud_client(billing=Billing.NO_COMMERCE) assert "mobilerun account login" in str(error.value) assert "secret" not in str(error.value) @@ -280,263 +302,37 @@ def test_default_base_url_comes_from_settings(monkeypatch): from mobilerun.config.settings import get_settings monkeypatch.setenv("MOBILERUN_API_KEY", "test-secret") - _, call = _device(monkeypatch) - - assert call[2] == get_settings().MOBILERUN_CLOUD_BASE_URL - - -def test_credentials_are_not_exposed_in_device_repr_or_string(monkeypatch): - monkeypatch.setenv("MOBILERUN_API_KEY", "never-print-this") - device, _ = _device(monkeypatch) - - assert "never-print-this" not in repr(device) - assert "never-print-this" not in str(device) - - -@pytest.mark.parametrize( - "existing,keep,fail", - [ - (False, False, False), - (False, True, False), - (True, False, False), - (False, False, True), - ], -) -def test_cloud_close_closes_owned_client(monkeypatch, existing, keep, fail): - from mobilerun_core_local.driver import cloud - - from mobilerun.core.devices import CloudDevice - - client = SimpleNamespace(close=AsyncMock()) - client.with_options = lambda **kwargs: client - monkeypatch.setattr(cloud, "AsyncMobilerun", lambda **kwargs: client) - terminate = AsyncMock( - side_effect=RuntimeError("terminate failed") if fail else None - ) - monkeypatch.setattr(lifecycle.devices, "terminate", terminate) - device = CloudDevice("existing" if existing else None, api_key="test", keep=keep) - if not existing: - device.device_id = "created" - device._owned = True - - async def run(): - if fail: - with pytest.raises(RuntimeError, match="terminate failed"): - await device.close() - client.close.assert_not_awaited() - else: - await device.close() - client.close.assert_awaited_once() - - asyncio.run(run()) - - -def test_failed_termination_can_retry_with_same_owned_sdk_client(monkeypatch): - import httpx - from mobilerun_core_local.driver import cloud - from mobilerun_sdk import AsyncMobilerun - - from mobilerun.core.devices import CloudDevice - - attempts = [] - - def respond(request): - attempts.append(request) - return ( - httpx.Response(400, json={"error": "failed"}) - if len(attempts) == 1 - else httpx.Response(204) - ) - - sdk = AsyncMobilerun( - api_key="test", - base_url="https://example.test", - max_retries=0, - http_client=httpx.AsyncClient(transport=httpx.MockTransport(respond)), - ) - monkeypatch.setattr(cloud, "AsyncMobilerun", lambda **kwargs: sdk) - device = CloudDevice(api_key="test") - device.device_id = "created" - device._owned = True - - async def run(): - with pytest.raises(CloudValidationError): - await device.close() - await device.close() - assert len(attempts) == 2 - assert sdk.is_closed() - - asyncio.run(run()) - - -def test_capabilities_uses_given_client(): - retrieve = AsyncMock( - return_value=SimpleNamespace(capabilities=SimpleNamespace(telephony=True)) - ) - result = asyncio.run( - devices.capabilities( - "phone", - client=SimpleNamespace( - devices=SimpleNamespace(retrieve_capabilities=retrieve) - ), - billing=Billing.NO_COMMERCE, - ) - ) - assert result.capabilities.telephony - retrieve.assert_awaited_once_with("phone") - - -def test_capabilities_opens_client_when_needed(monkeypatch): - retrieve = AsyncMock(return_value="capabilities") - context = AsyncMock() - context.__aenter__.return_value = SimpleNamespace( - devices=SimpleNamespace(retrieve_capabilities=retrieve) - ) - - def factory(*args, **kwargs): - return context - - monkeypatch.setattr(devices, "cloud_client", factory) assert ( - asyncio.run( - devices.capabilities( - "phone", - billing=Billing.NO_COMMERCE, - api_key="fake", - base_url="https://example.test", - ) - ) - == "capabilities" - ) - retrieve.assert_awaited_once_with("phone") - context.__aexit__.assert_awaited_once() - - -def test_capabilities_maps_sdk_error(): - error = APIStatusError( - "private response", - response=httpx.Response( - 403, request=httpx.Request("GET", "https://example.test") - ), - body={}, - ) - retrieve = AsyncMock(side_effect=error) - with pytest.raises(CloudPermissionDenied) as raised: - asyncio.run( - devices.capabilities( - "phone", - billing=Billing.NO_COMMERCE, - client=SimpleNamespace( - devices=SimpleNamespace(retrieve_capabilities=retrieve) - ), - ) - ) - assert raised.value.__cause__ is error - assert "private response" not in str(raised.value) - - -@pytest.mark.parametrize("supported", [False, True, None]) -def test_proxy_capability_controls_adoption_and_operations(monkeypatch, supported): - from mobilerun.core.devices import CloudDevice - - phone = CloudDevice("phone", api_key="test") - info = SimpleNamespace( - capabilities=SimpleNamespace(telephony=False, proxy=supported) - ) - monkeypatch.setattr(devices, "capabilities", AsyncMock(return_value=info)) - status = AsyncMock( - return_value=SimpleNamespace(connected=False, name=None, protocol=None) - ) - monkeypatch.setattr(proxies, "device_status", status) - asyncio.run(phone.connect()) - assert status.await_count == int(supported is not False) - assert ("proxy_switch" in phone.supported_operations) == (supported is not False) - - -@pytest.mark.parametrize("code", ["DEVICE_TOOL_UNSUPPORTED", "OTHER"]) -def test_missing_proxy_capability_only_tolerates_unsupported(monkeypatch, code): - from mobilerun.core.devices import CloudDevice - - phone = CloudDevice("phone", api_key="test") - info = SimpleNamespace(capabilities=Capabilities.construct(telephony=False)) - monkeypatch.setattr(devices, "capabilities", AsyncMock(return_value=info)) - sdk_error = APIStatusError( - "invalid request", - response=httpx.Response( - 400, request=httpx.Request("GET", "https://example.test") - ), - body={"code": code}, - ) - status = AsyncMock(side_effect=sdk_error) - client = SimpleNamespace( - devices=SimpleNamespace(proxy=SimpleNamespace(status=status)) - ) - monkeypatch.setattr(proxies, "cloud_client", lambda *a, **kw: nullcontext(client)) - if code == "DEVICE_TOOL_UNSUPPORTED": - asyncio.run(phone.connect()) - assert "proxy_switch" not in phone.supported_operations - else: - with pytest.raises(CloudValidationError): - asyncio.run(phone.connect()) - status.assert_awaited_once() - - -def test_unknown_proxy_handles_typed_error_without_cause(monkeypatch): - from mobilerun.core.devices import CloudDevice - - phone = CloudDevice("phone", api_key="test") - info = SimpleNamespace(capabilities=SimpleNamespace(telephony=False, proxy=None)) - monkeypatch.setattr(devices, "capabilities", AsyncMock(return_value=info)) - monkeypatch.setattr( - proxies, - "device_status", - AsyncMock(side_effect=DeviceOperationNotSupported("Unsupported proxy status")), + _client_options(monkeypatch)["base_url"] + == get_settings().MOBILERUN_CLOUD_BASE_URL ) - asyncio.run(phone.connect()) - assert "proxy_switch" not in phone.supported_operations - - -def test_install_polls_background_request(monkeypatch): - from mobilerun.core.devices import CloudDevice - - phone = CloudDevice("phone", api_key="test") - app = App("pkg", "1", "Example", id="lib") - async def submit(*args, background=False, **kwargs): - if not background: - raise TimeoutError("foreground install exceeded SDK timeout") - - monkeypatch.setattr(apps, "install", submit) - attempt = SimpleNamespace(app_id="pkg", started_at=1, status="succeeded") - polls = AsyncMock( - side_effect=[SimpleNamespace(installs=[]), SimpleNamespace(installs=[attempt])] - ) - monkeypatch.setattr(apps, "list_installs", polls) - monkeypatch.setattr( - phone, - "list_apps", - AsyncMock(return_value=[{"package_name": "pkg", "version_name": "1"}]), - ) - assert asyncio.run(phone.install_app(app)) == app - assert polls.await_count == 2 +def test_progress_disconnect_polls_without_stopping(): + @asynccontextmanager + async def attach(task_id, *, timeout): + raise httpx.ReadError("disconnect") + yield -def test_progress_disconnect_polls_without_stopping(monkeypatch): - monkeypatch.setattr(tasks, "run", AsyncMock(return_value=SimpleNamespace(id="id"))) - monkeypatch.setattr( - tasks, "_progress", AsyncMock(side_effect=httpx.ReadError("disconnect")) - ) status = AsyncMock( return_value=SimpleNamespace( status="completed", succeeded=True, message="ok", steps=1 ) ) - monkeypatch.setattr(tasks, "status", status) stop = AsyncMock() - monkeypatch.setattr(tasks, "_stop", stop) - result = asyncio.run( - tasks.run_task(None, device_id="phone", task="fake", billing=Billing.PAID) + service = SimpleNamespace( + run=AsyncMock(return_value=SimpleNamespace(id="id")), + with_streaming_response=SimpleNamespace(attach=attach), + get_status=status, + stop=stop, + ) + operator = CloudTaskOperator( + client=SimpleNamespace(tasks=service), billing=Billing.PAID + ) + phone = SimpleNamespace( + device_id="phone", info=lambda: SimpleNamespace(backend="cloud") ) + result = asyncio.run(operator.do(phone, "fake")) assert result.success - status.assert_awaited_once() + status.assert_awaited_once_with("id") stop.assert_not_awaited() diff --git a/tests/unit/clients/cloud/test_tasks.py b/tests/unit/clients/cloud/test_tasks.py index 3f92f1b61..8c4e38161 100644 --- a/tests/unit/clients/cloud/test_tasks.py +++ b/tests/unit/clients/cloud/test_tasks.py @@ -4,121 +4,76 @@ import asyncio import json import logging +import traceback from contextlib import asynccontextmanager -from dataclasses import FrozenInstanceError, asdict, dataclass +from dataclasses import FrozenInstanceError, asdict from types import SimpleNamespace from typing import cast -from unittest.mock import AsyncMock, patch +from unittest.mock import AsyncMock import httpx import pytest +from mobilerun_core import AsyncDevice, DeviceDescriptor from mobilerun_sdk import APITimeoutError, AsyncMobilerun -from mobilerun_sdk.types import DeviceCreateResponse from pydantic import BaseModel -import mobilerun.core.devices.cloud as module -import mobilerun.core.operator.cloud as cloud_operator -from mobilerun.clients.cloud import tasks as task_client -from mobilerun.clients.cloud.tasks import run_task -from mobilerun.core.credentials import CloudCredentials, Credential, DictCredentials -from mobilerun.core.devices.cloud import CloudDevice -from mobilerun.core.extensions import Extension, action +import mobilerun.core.credentials.cloud as cloud_vault +from mobilerun.clients.cloud.tasks import Tasks as TaskResource +from mobilerun.core.credentials import CloudCredentials, DictCredentials +from mobilerun.core.extensions import Extension, function from mobilerun.core.mailbox import CloudMailbox from mobilerun.core.operator.cloud import CloudTaskOperator from mobilerun.core.phone_number import CloudPhoneNumber -from mobilerun.core.proxy import CloudProxy from mobilerun.errors import ( - BillingError, CloudTaskTimeout, CloudTimeout, - ExtensionActionError, OperatorNotSupported, ) -from mobilerun.models import CloudCredentialReference +from mobilerun.errors.tools import ToolInvocationError +from mobilerun.models import CloudCredentialReference, CloudTaskInputs from mobilerun.models.billing import Billing from mobilerun.models.results import ( ExecutionResult, ExpectationResult, ExpectationVerdict, ) -from tests.support.devices import MemoryDevice from tests.support.paths import REPO_ROOT +@pytest.fixture +def cloud_phone() -> AsyncDevice: + # The task operator uses only public device identity and backend metadata. + return cast( + AsyncDevice, + SimpleNamespace( + device_id="phone", info=lambda: DeviceDescriptor("phone", "cloud") + ), + ) + + @pytest.mark.parametrize( "factory", [ - lambda: DictCredentials({}), - lambda: CloudMailbox("m"), - lambda: Extension(name="custom"), + pytest.param(lambda: DictCredentials({}), id="local-vault"), + pytest.param(lambda: CloudMailbox("m"), id="mailbox"), + pytest.param(lambda: CloudPhoneNumber("number"), id="phone-number"), + pytest.param(lambda: Extension(name="custom"), id="custom"), ], ) -def test_cloud_task_rejects_local_extensions(factory): - async def run(): - phone = CloudDevice("phone", api_key="fake") - extension = factory() - await extension.bind(phone) - operator = CloudTaskOperator() - with pytest.raises( - OperatorNotSupported, match="local extensions.*mobilerun-agents.*unbind" - ): - operator.check(phone) - with patch("mobilerun.core.operator.cloud.run_task", AsyncMock()) as execute: - with pytest.raises(OperatorNotSupported): - await operator.execute(phone, "task") - execute.assert_not_awaited() - - asyncio.run(run()) - - -def test_cloud_task_allows_cloud_vault_and_phone_number(): - async def run(): - phone = CloudDevice("phone", api_key="fake") - phone._cloud_telephony = True - vault = CloudCredentials(api_key="fake") - number = CloudPhoneNumber("number") - secret = "cloud-vault-canary" - items = [ - SimpleNamespace( - package_name="app", - credential_name="work", - fields=[SimpleNamespace(field_type="password", value=secret)], - ) - ] - with ( - patch( - "mobilerun.core.credentials.cloud.secrets.list_secrets", - AsyncMock(return_value=items), - ), - patch("mobilerun.core.phone_number.cloud.devices.bind_number", AsyncMock()), - patch( - "mobilerun.core.operator.cloud.run_task", - AsyncMock(return_value=ExecutionResult(success=True, device="cloud")), - ) as execute, - ): - await vault.bind(phone) - await number.bind(phone) - inputs = await vault.cloud_task_inputs() - assert inputs.credential_references == ( - CloudCredentialReference("app", "work"), - ) - assert secret not in repr(inputs) - operator = CloudTaskOperator() - operator.check(phone) - await operator.execute(phone, "task") - assert execute.await_args.kwargs["credentials"] == [ - {"package_name": "app", "credential_names": ["work"]} - ] - assert secret not in repr(execute.await_args) - - asyncio.run(run()) +def test_cloud_task_rejects_non_native_extensions(factory, cloud_phone, monkeypatch): + execute = AsyncMock() + monkeypatch.setattr(TaskResource, "run", execute) + operator = CloudTaskOperator( + client=cast(AsyncMobilerun, SimpleNamespace()), extensions=[factory()] + ) + with pytest.raises(OperatorNotSupported, match="non-cloud-native extensions"): + asyncio.run(operator.do(cloud_phone, "task")) + execute.assert_not_awaited() def test_default_cloud_task_contract_and_reference_only_models(): - from mobilerun.models import CloudCredentialReference, CloudTaskInputs - assert Extension.cloud_native is False - assert CloudProxy.cloud_native is True + assert CloudCredentials.cloud_native is True assert asyncio.run(Extension().cloud_task_inputs()) == CloudTaskInputs() inputs = CloudTaskInputs((CloudCredentialReference("app", "login"),)) assert json.loads(json.dumps(asdict(inputs))) == { @@ -132,13 +87,7 @@ def test_default_cloud_task_contract_and_reference_only_models(): CloudCredentialReference("app", {"password": "secret"}) -def test_cloud_operator_merges_only_opted_in_extensions(monkeypatch): - from mobilerun.core.devices import CloudDevice - from mobilerun.core.operator import cloud - from mobilerun.errors import OperatorNotSupported - from mobilerun.models import CloudCredentialReference, CloudTaskInputs - from mobilerun.models.results import ExecutionResult - +def test_cloud_operator_merges_only_opted_in_extensions(monkeypatch, cloud_phone): class Contribution(Extension): cloud_native = True @@ -150,71 +99,45 @@ async def cloud_task_inputs(self) -> CloudTaskInputs: ) ) - class LocalOnly(Extension): - async def cloud_task_inputs(self) -> CloudTaskInputs: - raise AssertionError("non-native extensions must not contribute") - - run = AsyncMock(return_value=ExecutionResult(success=True, device="cloud")) - monkeypatch.setattr(cloud, "run_task", run) - - async def scenario(): - phone = CloudDevice("phone", api_key="fake") - phone._ensure_connected = AsyncMock() - await Contribution(name="first").bind(phone) - await Contribution(name="second").bind(phone) - local = await LocalOnly(name="local").bind(phone) - with pytest.raises(OperatorNotSupported, match="local extensions"): - await cloud.CloudTaskOperator().execute(phone, "sign in") - run.assert_not_awaited() - await local.unbind() - await cloud.CloudTaskOperator().execute(phone, "sign in") - assert run.await_args.kwargs["credentials"] == [ - {"package_name": "app", "credential_names": ["first", "second", "shared"]} - ] - await phone.close() - - asyncio.run(scenario()) + run = AsyncMock(return_value=SimpleNamespace(id="task-1")) + monkeypatch.setattr(TaskResource, "run", run) + service = Tasks() + client = cast(AsyncMobilerun, SimpleNamespace(tasks=service)) + operator = CloudTaskOperator( + client=client, + extensions=[Contribution(name="first"), Contribution(name="second")], + ) + asyncio.run(operator.do(cloud_phone, "sign in")) + assert service.closed + assert run.await_args.kwargs["device_id"] == "phone" + assert run.await_args.kwargs["credentials"] == [ + {"package_name": "app", "credential_names": ["first", "second", "shared"]} + ] -def test_action_errors_stay_wrapped_without_backend_details(): +def test_tool_errors_stay_wrapped_without_backend_details(): class Failing(Extension): - @action() + @function async def fail(self) -> None: - """Demonstrate safe action error conversion.""" + """Demonstrate safe tool error conversion.""" raise RuntimeError("private backend details") async def scenario(): - phone = MemoryDevice() extension = Failing() - await extension.bind(phone) - for call in (extension.fail, lambda: phone.actions.call("extension.fail", {})): - with pytest.raises(ExtensionActionError) as raised: + operator = CloudTaskOperator( + client=cast(AsyncMobilerun, SimpleNamespace()), extensions=[extension] + ) + (tool,) = operator.tools() + for call in (extension.fail, lambda: tool.invoke({})): + with pytest.raises(ToolInvocationError) as raised: await call() - assert "private backend details" not in str(raised.value) - await phone.close() + assert "private backend details" not in "".join( + traceback.format_exception(raised.value) + ) asyncio.run(scenario()) -def test_contract_kit_rejects_extra_value_fields_in_task_inputs(): - from mobilerun.models import CloudTaskInputs - from tests.support.extensions import check_extension_contract - - @dataclass(frozen=True) - class UnsafeInputs(CloudTaskInputs): - values: str = "must-not-be-published" - - class Unsafe(Extension): - async def cloud_task_inputs(self) -> CloudTaskInputs: - return UnsafeInputs() - - async def device(): - return MemoryDevice() - - with pytest.raises(AssertionError, match="G:.*references only"): - asyncio.run(check_extension_contract(lambda name: Unsafe(name=name), device)) - - class Output(BaseModel): ok: bool @@ -244,8 +167,8 @@ def __init__(self, *, block=False): self.with_streaming_response = self @asynccontextmanager - async def attach(self, task_id, **params): - assert task_id == "task-1" + async def attach(self, task_id, *, timeout): + assert task_id == "task-1" and timeout is None try: yield self finally: @@ -265,11 +188,14 @@ def test_stream_output_and_lazy_artifacts(caplog, monkeypatch, task_billing): async def run(): tasks = Tasks() with caplog.at_level("INFO", logger="mobilerun.actions"): - result = await run_task( - cast(AsyncMobilerun, SimpleNamespace(tasks=tasks)), - device_id="device", + result = await CloudTaskOperator( + client=cast(AsyncMobilerun, SimpleNamespace(tasks=tasks)), billing=Billing.INCLUDED, - task="go", + ).do( + SimpleNamespace( + device_id="device", info=lambda: SimpleNamespace(backend="cloud") + ), + "go", output=Output, ) assert result.output is not None @@ -277,13 +203,13 @@ async def run(): assert result.output.ok and tasks.closed client = cast(AsyncMobilerun, SimpleNamespace(tasks=tasks)) assert ( - await task_client.trajectory( - client, result.task_id, billing=Billing.INCLUDED + await TaskResource(client=client, billing=Billing.INCLUDED).trajectory( + result.task_id ) == "trajectory" ) - assert await task_client.screenshots( - client, result.task_id, billing=Billing.INCLUDED + assert await TaskResource(client=client, billing=Billing.INCLUDED).screenshots( + result.task_id ) == ["image"] tasks.run.assert_awaited_once_with( device_id="device", task="go", output_schema=Output.model_json_schema() @@ -302,15 +228,18 @@ async def run(): if stop_fails: tasks.stop.side_effect = RuntimeError("stop unavailable") pending = asyncio.create_task( - run_task( - cast(AsyncMobilerun, SimpleNamespace(tasks=tasks)), - device_id="device", + CloudTaskOperator( + client=cast(AsyncMobilerun, SimpleNamespace(tasks=tasks)), billing=Billing.INCLUDED, - task="go", + ).do( + SimpleNamespace( + device_id="device", info=lambda: SimpleNamespace(backend="cloud") + ), + "go", timeout=10 if cancel else 0.02, ) ) - await tasks.started.wait() + await asyncio.wait_for(tasks.started.wait(), timeout=2) if cancel: pending.cancel() with pytest.raises(asyncio.CancelledError if cancel else CloudTaskTimeout): @@ -344,11 +273,14 @@ async def stop(task_id: str) -> None: tasks.stop.side_effect = stop pending = asyncio.create_task( - run_task( - cast(AsyncMobilerun, SimpleNamespace(tasks=tasks)), - device_id="device", + CloudTaskOperator( + client=cast(AsyncMobilerun, SimpleNamespace(tasks=tasks)), billing=Billing.INCLUDED, - task="go", + ).do( + SimpleNamespace( + device_id="device", info=lambda: SimpleNamespace(backend="cloud") + ), + "go", timeout=10 if cancel_first else 0, ) ) @@ -392,11 +324,14 @@ async def run() -> None: tasks = Tasks() tasks.get_status.side_effect = error with pytest.raises(expected) as caught: - await run_task( - cast(AsyncMobilerun, SimpleNamespace(tasks=tasks)), - device_id="device", + await CloudTaskOperator( + client=cast(AsyncMobilerun, SimpleNamespace(tasks=tasks)), billing=Billing.INCLUDED, - task="go", + ).do( + SimpleNamespace( + device_id="device", info=lambda: SimpleNamespace(backend="cloud") + ), + "go", ) assert type(caught.value) is expected tasks.get_status.assert_awaited_once_with("task-1") @@ -410,115 +345,79 @@ async def run() -> None: tasks = Tasks() tasks.get_status.side_effect = KeyboardInterrupt with pytest.raises(KeyboardInterrupt): - await run_task( - cast(AsyncMobilerun, SimpleNamespace(tasks=tasks)), - device_id="device", + await CloudTaskOperator( + client=cast(AsyncMobilerun, SimpleNamespace(tasks=tasks)), billing=Billing.INCLUDED, - task="go", + ).do( + SimpleNamespace( + device_id="device", info=lambda: SimpleNamespace(backend="cloud") + ), + "go", ) tasks.stop.assert_awaited_once_with("task-1") asyncio.run(run()) -def test_local_credentials_rejected_before_any_api(monkeypatch, task_billing): - vault = CloudCredentials(api_key="test") - vault._list_credentials = AsyncMock( - side_effect=AssertionError("must not read vault") - ) - device = module.CloudDevice( - "device", - api_key="test", - ) - asyncio.run(vault.bind(device)) - asyncio.run(DictCredentials({"secret": "value"}, name="local").bind(device)) - with pytest.raises(OperatorNotSupported, match="local extensions"): - asyncio.run(device.do("go")) - vault._list_credentials.assert_not_awaited() +def test_local_credentials_rejected_before_any_api(monkeypatch, cloud_phone): + read = AsyncMock(side_effect=AssertionError("must not read vault")) + execute = AsyncMock() + monkeypatch.setattr(TaskResource, "run", execute) + monkeypatch.setattr(cloud_vault.Vault, "list", read) + async def run(): + vault = CloudCredentials(api_key="test") + try: + operator = CloudTaskOperator( + client=cast(AsyncMobilerun, SimpleNamespace()), + extensions=[vault, DictCredentials({"secret": "value"}, name="local")], + ) + with pytest.raises( + OperatorNotSupported, match="non-cloud-native extensions" + ): + await operator.do(cloud_phone, "go") + finally: + await vault.close() -def test_vault_passes_only_references(monkeypatch, task_billing): - vault = CloudCredentials(api_key="test") - vault._list_credentials = AsyncMock( - return_value=[Credential("com.example", "login", {"password": "never-send"})] - ) - device = module.CloudDevice("device", api_key="test") - asyncio.run(vault.bind(device)) - fake_run = AsyncMock( - return_value=ExecutionResult(success=True, device="CloudDevice") - ) - monkeypatch.setattr(cloud_operator, "run_task", fake_run) - asyncio.run(device.do("go")) - assert fake_run.call_args.kwargs["credentials"] == [ - {"package_name": "com.example", "credential_names": ["login"]} - ] - assert "never-send" not in repr(fake_run.call_args) + asyncio.run(run()) + read.assert_not_awaited() + execute.assert_not_awaited() -@pytest.mark.parametrize( - "name", ["resume", "stop", "terminate", "wait_ready", "reboot", "reset", "info"] -) -def test_device_lifecycle_forwards(name, task_billing): - device = module.CloudDevice("device", api_key="test") - response = SimpleNamespace(name="response") if name == "info" else "response" - method = AsyncMock(return_value=response) - endpoints = SimpleNamespace(**{"retrieve" if name == "info" else name: method}) - if name == "resume": - endpoints.retrieve = AsyncMock( - return_value=SimpleNamespace(billing_strategy="subscription") +def test_vault_passes_only_references(monkeypatch, task_billing, cloud_phone): + items = [ + SimpleNamespace( + package_name="com.example", + credential_name="login", + fields=[SimpleNamespace(field_type="password", value="never-send")], ) - device._client = cast(AsyncMobilerun, SimpleNamespace(devices=endpoints)) - assert asyncio.run(getattr(device, name)()) == response - method.assert_awaited_once_with("device") - - -def test_device_resume_refuses_minute_billing_under_included(task_billing): - device = module.CloudDevice("device", api_key="test", billing=Billing.INCLUDED) - endpoints = SimpleNamespace( - retrieve=AsyncMock(return_value=SimpleNamespace(billing_strategy="minute")), - resume=AsyncMock(), - ) - device._client = cast(AsyncMobilerun, SimpleNamespace(devices=endpoints)) - with pytest.raises(BillingError, match="paid"): - asyncio.run(device.resume()) - endpoints.resume.assert_not_awaited() - + ] + monkeypatch.setattr(cloud_vault.Vault, "list", AsyncMock(return_value=items)) + execute = AsyncMock(return_value=SimpleNamespace(id="task-1")) + monkeypatch.setattr(TaskResource, "run", execute) -def test_create_waits_ready_and_resolves_auth(monkeypatch, task_billing): - devices = SimpleNamespace( - create=AsyncMock(return_value=SimpleNamespace(id="new", name="new")), - wait_ready=AsyncMock(), - retrieve_capabilities=AsyncMock( - return_value=SimpleNamespace( - capabilities=SimpleNamespace(telephony=False, proxy=True) + async def run(): + vault = CloudCredentials(api_key="test") + try: + operator = CloudTaskOperator( + client=cast(AsyncMobilerun, SimpleNamespace(tasks=Tasks())), + extensions=[vault], ) - ), - ) - - monkeypatch.setattr(module, "resolve_cloud_api_key", lambda: "test") - from mobilerun_core_local.driver import cloud as driver - - client = SimpleNamespace(devices=devices) - client.with_options = lambda **kwargs: client - monkeypatch.setattr(driver, "AsyncMobilerun", lambda **params: client) - - async def initialize(): - return await module.CloudDevice(name="example", billing="paid") + assert (await operator.do(cloud_phone, "go")).success + assert "never-send" not in repr(await vault.cloud_task_inputs()) + finally: + await vault.close() - result = asyncio.run(initialize()) - assert result.device_id == "new" - devices.create.assert_awaited_once_with( - name="example", - proxy={"connect": {"country": "us"}, "smart_ip": True}, - billing="auto", - device_type="android_cloud_phone", - ) - devices.wait_ready.assert_awaited_once_with("new") + asyncio.run(run()) + assert execute.await_args.kwargs["credentials"] == [ + {"package_name": "com.example", "credential_names": ["login"]} + ] + assert "never-send" not in repr(execute.await_args) def test_expectation_retains_task_id_without_transport_context(task_billing): task = ExecutionResult[ExpectationVerdict]( - success=True, device="CloudDevice", task_id="id" + success=True, device="cloud", task_id="id" ) result = ExpectationResult( passed=True, condition="visible", reason="yes", task=task @@ -559,21 +458,26 @@ def handler(request): }, ) + class References(Extension): + cloud_native = True + + async def cloud_task_inputs(self): + return CloudTaskInputs((CloudCredentialReference("com.example", "login"),)) + async def run(): async with AsyncMobilerun( api_key="test", base_url="https://sdk.test/v1", http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)), ) as client: - result = await run_task( - client, - device_id="device", - billing=Billing.INCLUDED, - task="go", + result = await CloudTaskOperator( + client=client, billing=Billing.INCLUDED, extensions=[References()] + ).do( + SimpleNamespace( + device_id="device", info=lambda: SimpleNamespace(backend="cloud") + ), + "go", output=Output, - credentials=[ - {"package_name": "com.example", "credential_names": ["login"]} - ], ) assert result.output is not None assert result.success and result.output.ok @@ -583,113 +487,11 @@ async def run(): def test_local_results_have_no_cloud_artifacts(task_billing): - result = ExecutionResult(success=True, device="AndroidDevice") + result = ExecutionResult(success=True, device="local") assert not hasattr(result, "trajectory") assert not hasattr(result, "screenshots") -@pytest.mark.parametrize("explicit_type", [None, "ios_phone"]) -def test_real_sdk_create_and_lifecycle_wire_contract( - monkeypatch, explicit_type, task_billing -): - # lazy: patch the driver's SDK constructor only in this transport-only test. - from mobilerun_core_local.driver import cloud as driver_module - - expected_type = explicit_type or "android_cloud_phone" - payload = { - "id": "created-device-id", - "activeTaskId": "", - "assignedAt": None, - "createdAt": "2026-11-18T00:00:00Z", - "name": "example", - "platform": "ios" if explicit_type == "ios_phone" else "android", - "state": "ready", - "stateMessage": "", - "streamUrl": "", - "taskCount": 0, - "terminatesAt": None, - "type": expected_type, - "updatedAt": "2026-11-18T00:00:00Z", - "billingStrategy": "minute", - } - assert DeviceCreateResponse.model_validate(payload).id == "created-device-id" - seen = [] - clients = [] - - def handler(request): - seen.append((request.method, request.url.path)) - if request.method == "POST" and request.url.path == "/v1/devices": - assert dict(request.url.params) == { - "deviceType": expected_type, - "billing": "auto", - } - assert json.loads(request.content) == { - "name": "example", - "country": "US", - "proxy": {"connect": {"country": "us"}, "smartIp": True}, - } - return httpx.Response(200, json=payload) - assert request.url.path.startswith("/v1/devices/created-device-id") - if request.url.path.endswith("/capabilities"): - return httpx.Response( - 200, - json={ - "deviceType": expected_type, - "capabilities": {"telephony": False}, - }, - ) - if request.method == "GET": - return httpx.Response(200, json=payload) - return httpx.Response(204) - - def factory(**params): - client = AsyncMobilerun( - **params, - http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)), - ) - clients.append(client) - return client - - monkeypatch.setattr(driver_module, "AsyncMobilerun", factory) - - async def run(): - try: - device = await module.CloudDevice( - api_key="test", - base_url="https://sdk.test/v1", - name="example", - billing="paid", - country="US", - device_type=explicit_type, - ) - assert device.device_id == "created-device-id" - assert (await device.info()).id == device.device_id - await device.stop() - await device.resume() - await device.wait_ready() - await device.reboot() - await device.reset(mode="identity") - await device.terminate() - finally: - for client in clients: - await client.close() - - asyncio.run(run()) - prefix = "/v1/devices/created-device-id" - assert seen == [ - ("POST", "/v1/devices"), - ("GET", prefix + "/wait"), - ("GET", prefix + "/capabilities"), - ("GET", prefix), - ("POST", prefix + "/stop"), - ("POST", prefix + "/resume"), - ("GET", prefix + "/wait"), - ("POST", prefix + "/reboot"), - ("POST", prefix + "/reset"), - ("DELETE", prefix), - ] - - def test_task_boundary_does_not_probe_sdk_error_body(): path = REPO_ROOT / "mobilerun/clients/cloud/tasks.py" tree = ast.parse(path.read_text()) diff --git a/tests/unit/clients/portal/test_install.py b/tests/unit/clients/portal/test_install.py deleted file mode 100644 index e5c60b227..000000000 --- a/tests/unit/clients/portal/test_install.py +++ /dev/null @@ -1,279 +0,0 @@ -"""Offline contracts for Portal installs, setup options, and release assets.""" - -import asyncio - -import pytest -from mobilerun_core_local.driver.android import portal as sdk_portal - -import mobilerun -import mobilerun.clients.portal.install as portal -from mobilerun.clients.portal.setup import portal_version_kwargs - - -def test_portal_wait_timeout_without_polling(): - from mobilerun.clients.portal.install import wait_for_portal_service - - assert asyncio.run(wait_for_portal_service(object(), timeout=0)) is False - - -def test_install_portal_with_apk_returns_result(tmp_path, monkeypatch): - from mobilerun.clients.portal.install import install_portal - - apk = tmp_path / "portal.apk" - apk.write_bytes(b"apk") - - class Device: - async def install(self, *args, **kwargs): - pass - - async def shell(self, command): - return '"status":"success"' - - async def ready(*args, **kwargs): - return True - - monkeypatch.setattr(portal, "enable_portal_accessibility", ready) - monkeypatch.setattr(portal, "wait_for_portal_service", ready) - - result = asyncio.run(install_portal(Device(), apk_path=str(apk))) - assert result.installed - assert result.apk_source == str(apk) - - -def test_install_portal_missing_apk_raises(tmp_path): - from mobilerun.clients.portal.install import install_portal - from mobilerun.errors import PortalApkNotFound - - with pytest.raises(PortalApkNotFound): - asyncio.run(install_portal(object(), apk_path=str(tmp_path / "missing.apk"))) - - -def test_install_portal_accessibility_fallback_requests_manual_setup(tmp_path): - from mobilerun.clients.portal.install import install_portal - - apk = tmp_path / "portal.apk" - apk.write_bytes(b"apk") - - class Device: - async def install(self, *args, **kwargs): - pass - - async def shell(self, command): - return "opened" - - result = asyncio.run(install_portal(Device(), apk_path=str(apk), wait_timeout=0)) - assert result.installed - assert result.needs_manual_accessibility - - -def test_setup_cli_prints_install_success_messages(monkeypatch, tmp_path): - from click.testing import CliRunner - - from mobilerun.cli.devices import setup as setup_module - from mobilerun.clients.portal.install import PortalSetupResult - - class Device: - pass - - async def get_device(serial): - return Device() - - async def install(device, **kwargs): - return PortalSetupResult(True, True, False, str(tmp_path / "portal.apk")) - - monkeypatch.setattr(setup_module.adb, "device", get_device) - monkeypatch.setattr(setup_module, "install_portal", install) - result = CliRunner().invoke( - setup_module.setup, ["test-device", "--android", "--path", "portal.apk"] - ) - assert result.exit_code == 0 - assert "Using provided APK: portal.apk" in result.output - assert "Step 1/2: Installing APK:" in result.output - assert "Installation successful!" in result.output - assert "Accessibility service enabled successfully!" in result.output - assert "Setup complete!" in result.output - - -def test_wait_for_portal_logs_retryable_failure(monkeypatch): - from types import SimpleNamespace - from unittest.mock import AsyncMock, Mock - - from mobilerun.clients.portal.install import logger, wait_for_portal_service - - warning = Mock() - monkeypatch.setattr(logger, "warning", warning) - device = SimpleNamespace(shell=AsyncMock(side_effect=OSError("temporary"))) - assert not asyncio.run( - wait_for_portal_service(device, timeout=0.001, interval=0.002) - ) - warning.assert_called_once() - - -def test_portal_setup_can_ask_for_an_in_place_update(): - def new_setup(device, debug=False, *, version=None, uninstall=True): - return None - - def version_only_setup(device, debug=False, version=None): - return None - - def old_setup(device, debug=False): - return None - - assert portal_version_kwargs(new_setup, in_place=True) == { - "version": mobilerun.__version__, - "uninstall": False, - } - assert portal_version_kwargs(new_setup) == {"version": mobilerun.__version__} - assert portal_version_kwargs(version_only_setup) == { - "version": mobilerun.__version__ - } - assert portal_version_kwargs(old_setup) == {} - assert portal_version_kwargs(old_setup, in_place=True) == {} - - -def test_sdk_version_check_still_flags_an_rc_after_its_release(monkeypatch): - from mobilerun.diagnostics import checks as doctor - from mobilerun.diagnostics import versions as sdk_releases - - class Response: - status_code = 200 - - def json(self): - return {"tag_name": "v0.6.22"} - - monkeypatch.setattr(doctor, "__version__", "0.6.22rc1") - monkeypatch.setattr(sdk_releases.requests, "get", lambda url, **kwargs: Response()) - - result = asyncio.run(doctor.check_sdk_version(debug=False)) - - assert result.status == doctor.Status.WARN - - -SIGNED = "com.mobilerun.portal-0.7.1.apk" -DEBUG = "com.mobilerun.portal-0.7.1-debug.apk" -UNSIGNED = "com.mobilerun.portal-0.7.1-release-unsigned.apk" -PUBLIC = "mobilerun-portal-v0.7.1-release.apk" -INTERNAL = "mobilerun-portal-internal-v0.7.1-debug.apk" -DOWNLOAD_BASE = "https://github.com/droidrun/mobilerun-portal/releases/download" -STALE_BASE = "https://github.com/droidrun/droidrun-portal/releases/download" - - -def _github_asset(name): - return { - "name": name, - "browser_download_url": f"https://example.com/releases/{name}", - } - - -@pytest.mark.parametrize( - "names,expected", - [ - ([UNSIGNED, DEBUG], DEBUG), - ([UNSIGNED, DEBUG, SIGNED], SIGNED), - ([PUBLIC], PUBLIC), - ([INTERNAL], INTERNAL), - ], - ids=["debug-over-unsigned", "signed-over-debug", "public-name", "internal-name"], -) -def test_selects_release_asset(names, expected): - url, name, version = sdk_portal._select_portal_apk_asset( - [_github_asset(n) for n in names] - ) - assert name == expected and url.endswith("/" + expected) - assert version == "0.7.1" - - -def test_legacy_droidrun_portal_asset_is_not_active_match(): - with pytest.raises(Exception, match="Portal APK asset not found"): - sdk_portal._select_portal_apk_asset( - [_github_asset("droidrun-portal-v0.4.6.apk")] - ) - - -def test_ungh_download_url_asset_matches_without_name(): - url = "https://example.com/releases/download/v0.7.1/mobilerun-portal-v0.7.1.apk" - assert sdk_portal._select_portal_apk_asset([{"downloadUrl": url}]) == ( - url, - "mobilerun-portal-v0.7.1.apk", - "0.7.1", - ) - - -def test_no_matching_apk_reports_seen_assets(): - names = ["release-notes.txt", "other-app-1.0.0.apk"] - with pytest.raises(Exception, match="Portal APK asset not found") as exc: - sdk_portal._select_portal_apk_asset([_github_asset(name) for name in names]) - assert all(name in str(exc.value) for name in names) - - -@pytest.mark.parametrize("tag", [None, "v0.7.1"], ids=["latest", "tag"]) -def test_release_lookup_retries_next_host_on_request_error(monkeypatch, tag): - calls = [] - release = {"assets": [_github_asset(DEBUG)]} - - class Response: - status_code = 200 - - def raise_for_status(self): - pass - - def json(self): - return {"release": release} if tag else release - - def get(url, **kwargs): - calls.append(url) - if "api.github.com" in url: - raise sdk_portal.requests.ConnectionError("offline") - return Response() - - monkeypatch.setattr(sdk_portal.requests, "get", get) - assets = ( - sdk_portal._get_release_assets_by_tag(tag) - if tag - else sdk_portal.get_latest_release_assets() - ) - assert len(calls) == 2 - assert "api.github.com" in calls[0] and "ungh.cc" in calls[1] - assert assets[0]["name"] == DEBUG - - -def test_release_lookup_raises_clear_error_when_all_hosts_fail(monkeypatch): - def get(url, **kwargs): - raise sdk_portal.requests.ConnectionError("offline") - - monkeypatch.setattr(sdk_portal.requests, "get", get) - with pytest.raises(Exception, match="all configured hosts"): - sdk_portal.get_latest_release_assets() - - -def test_versioned_resolution_uses_release_tag_assets(monkeypatch): - def assets(version, debug=False): - return [_github_asset(n) for n in [UNSIGNED, DEBUG, SIGNED]] - - monkeypatch.setattr(sdk_portal, "_get_release_assets_by_tag", assets) - url, version, name = sdk_portal._resolve_versioned_portal_apk_asset( - "0.7.1", DOWNLOAD_BASE - ) - assert (url, version, name) == ( - _github_asset(SIGNED)["browser_download_url"], - "0.7.1", - SIGNED, - ) - - -def test_versioned_resolution_normalizes_stale_download_base_fallback(monkeypatch): - def offline(version, debug=False): - raise RuntimeError("offline") - - monkeypatch.setattr(sdk_portal, "_get_release_assets_by_tag", offline) - assert sdk_portal._resolve_versioned_portal_apk_asset("v0.7.1", STALE_BASE) == ( - f"{DOWNLOAD_BASE}/v0.7.1/{SIGNED}", - "0.7.1", - SIGNED, - ) - assert sdk_portal._normalize_download_base(STALE_BASE) == DOWNLOAD_BASE - - -@pytest.mark.parametrize("name", [SIGNED, DEBUG, UNSIGNED, PUBLIC, INTERNAL]) -def test_asset_version_parsing_ignores_build_suffixes(name): - assert sdk_portal._parse_portal_asset_version(name) == "0.7.1" diff --git a/tests/unit/config/test_environment.py b/tests/unit/config/test_environment.py index 5d8222f73..40d551b65 100644 --- a/tests/unit/config/test_environment.py +++ b/tests/unit/config/test_environment.py @@ -6,6 +6,7 @@ from pydantic import ValidationError from mobilerun.config import env, settings +from mobilerun.config.user_config import MobileConfig @pytest.mark.parametrize( @@ -111,17 +112,14 @@ def test_sdk_paths_read_at_call_time(monkeypatch): def test_configurable_defaults_are_typed_fields_and_read_fresh(monkeypatch): defaults = settings.get_settings() - assert defaults.MOBILERUN_PORTAL_REMOTE_PORT == 8080 assert defaults.MOBILERUN_AUTH_URL == "https://cloud.mobilerun.ai/api/auth" assert defaults.MOBILERUN_CLOUD_BASE_URL == "https://api.mobilerun.ai/v1" - monkeypatch.setenv("MOBILERUN_PORTAL_REMOTE_PORT", "9090") monkeypatch.setenv("MOBILERUN_AUTH_URL", "https://auth.example") monkeypatch.setenv("MOBILERUN_CLOUD_BASE_URL", "https://cloud.example") monkeypatch.setenv( "MOBILERUN_AGENTS", '{"custom":{"skills":["global","project"],"mcp":null}}' ) current = settings.get_settings() - assert current.MOBILERUN_PORTAL_REMOTE_PORT == 9090 assert current.MOBILERUN_AUTH_URL == "https://auth.example" assert current.MOBILERUN_CLOUD_BASE_URL == "https://cloud.example" assert current.MOBILERUN_AGENTS["custom"].skills == ("global", "project") @@ -142,6 +140,20 @@ def test_base_secrets_cover_cloud_environment(monkeypatch): ) +def test_saved_portal_token_is_platform_scoped_until_environment_override(monkeypatch): + device = MobileConfig.from_dict( + {"device": {"platform": "ios", "auth_token": "saved-placeholder"}} + ).device + + monkeypatch.delenv("MOBILERUN_DEVICE_TOKEN", raising=False) + assert device.resolve_auth_token("android") is None + assert device.resolve_auth_token("ios") == "saved-placeholder" + + monkeypatch.setenv("MOBILERUN_DEVICE_TOKEN", "override-placeholder") + assert device.resolve_auth_token("android") == "override-placeholder" + assert device.resolve_auth_token("ios") == "override-placeholder" + + @pytest.mark.parametrize("name", env.Secrets.model_fields) def test_secrets_are_aliased_and_masked(monkeypatch, name): monkeypatch.setenv(name, "sensitive-placeholder") diff --git a/tests/unit/config/test_paths.py b/tests/unit/config/test_paths.py index 314a74970..35395ac8a 100644 --- a/tests/unit/config/test_paths.py +++ b/tests/unit/config/test_paths.py @@ -6,11 +6,8 @@ import os import runpy import stat -import sys -from copy import deepcopy from enum import Enum from pathlib import Path -from types import ModuleType from typing import Any, get_args import pytest @@ -21,10 +18,12 @@ from mobilerun.cli.app import cli from mobilerun.config.env import Secrets -from mobilerun.config.loader import ConfigFile, ConfigLoader, OutdatedConfigError -from mobilerun.config.migrations import CURRENT_VERSION, migrate +from mobilerun.config.file import ConfigFile +from mobilerun.config.loader import ConfigLoader +from mobilerun.config.migrations import CURRENT_VERSION from mobilerun.config.settings import Settings, get_settings from mobilerun.config.user_config import MobileConfig +from mobilerun.errors.config import OutdatedConfigError from mobilerun.macro.settings import MacroSettings from mobilerun.mcp.settings import MCPSettings from mobilerun.utils import paths @@ -39,137 +38,141 @@ def test_resolve_still_finds_bundled_assets(tmp_path, monkeypatch): assert asset.is_file() -def test_legacy_prompt_handles_addon_without_spec(tmp_path, monkeypatch): - - monkeypatch.chdir(tmp_path) - monkeypatch.setitem(sys.modules, "mobilerun_agents", ModuleType("mobilerun_agents")) - prompt = "config/prompts/missing.jinja2" - assert PathResolver.resolve(prompt) == tmp_path / prompt - with pytest.raises(FileNotFoundError): - PathResolver.resolve(prompt, must_exist=True) - - -def test_legacy_prompt_propagates_other_finder_errors(monkeypatch): - - def broken_finder(name): - raise ValueError("broken finder") - - monkeypatch.delitem(sys.modules, "mobilerun_agents", raising=False) - monkeypatch.setattr(paths, "find_spec", broken_finder) - with pytest.raises(ValueError, match="broken finder"): - paths.PathResolver.resolve("config/prompts/missing.jinja2") - - -@pytest.mark.parametrize("bundle_location", ["base", "addon", "base_shadowed"]) -def test_v8_preserves_bundled_prompt_resolution(tmp_path, monkeypatch, bundle_location): - base = tmp_path / "base" - addon = tmp_path / "mobilerun_agents" - asset = "assets/prompts/split.jinja2" - legacy = "config/prompts/split.jinja2" - bundled = (addon if bundle_location == "addon" else base) / asset - bundled.parent.mkdir(parents=True) - bundled.touch() - addon.mkdir(exist_ok=True) - (addon / "__init__.py").write_text("raise AssertionError('unexpected import')") - if bundle_location == "base_shadowed": - shadow = tmp_path / asset - shadow.parent.mkdir(parents=True) - shadow.touch() - monkeypatch.setattr(PathResolver, "get_project_root", lambda: base) - monkeypatch.delitem(sys.modules, "mobilerun_agents", raising=False) - monkeypatch.syspath_prepend(str(tmp_path)) - monkeypatch.chdir(tmp_path) - config = { - "_version": 7, - "agent": {"fast": {"system_prompt": legacy, "user_prompt": legacy}}, +@pytest.mark.parametrize("version", range(1, 9)) +def test_legacy_sections_survive_base_load_migration_and_save( + tmp_path, monkeypatch, version +): + monkeypatch.setenv("MOBILERUN_USER_CONFIG_DIR", str(tmp_path)) + path = tmp_path / "config.yaml" + unknown = { + "agent": { + "codeact": {"vision": True}, + "manager": {"system_prompt": "config/prompts/manager/system.jinja2"}, + "scripter": {"system_prompt": "config/prompts/scripter/system.jinja2"}, + }, + "llm_profiles": {"codeact": {"provider": "example", "model": "x"}}, + "tools": {"disabled_tools": None}, + "external_agents": {"mai_ui": {"enabled": False}, "autoglm": None}, + "telemetry": {"enabled": False, "future_setting": [0, False, "0"]}, + "tracing": {"enabled": True, "provider": "example"}, + "mcp": ["not interpreted"], + "future_extension": {"payload": [None, False, "value"]}, } + unknown_logging = { + "save_trajectory": "all", + "trajectory_path": "old-runs", + "rich_text": True, + "trajectory_gifs": False, + "future_format": {"options": []}, + } + credentials = {"enabled": True, "file_path": "credentials.yaml"} + path.write_text( + yaml.safe_dump( + { + "_version": version, + "device": {"serial": "original"}, + "credentials": credentials, + "logging": {"debug": True, "level": "verbose", **unknown_logging}, + **unknown, + } + ) + ) - assert PathResolver.resolve(legacy, must_exist=True) == bundled - migrated = migrate(config)["agent"]["fast"] - for key in ("system_prompt", "user_prompt"): - assert PathResolver.resolve(migrated[key], must_exist=True) == bundled - assert migrated[key] == (asset if bundle_location == "base" else legacy) - - -@pytest.mark.parametrize("missing", ["mobilerun_agents", "other_dependency"]) -def test_blocked_addon_is_treated_as_missing_only_for_its_own_name( - monkeypatch, missing + config = ConfigLoader.load(str(path)) + assert config.device.serial == "original" + assert config.device.auto_setup is True + assert config.credentials == credentials + assert (config.logging.debug, config.logging.level) == (True, "verbose") + assert not any(hasattr(config, key) for key in unknown) + assert not any(hasattr(config.logging, key) for key in unknown_logging) + assert "future_setting" not in repr(config) + migrated = yaml.safe_load(path.read_text()) + assert migrated["_version"] == 8 + if version < 3: + assert migrated["device"]["auto_setup"] is True + else: + assert "auto_setup" not in migrated["device"] + for key, value in unknown.items(): + assert migrated[key] == value + for key, value in unknown_logging.items(): + assert migrated["logging"][key] == value + + config.device.serial = "updated" + config.logging.level = "debug" + assert ConfigLoader.save(config) == path + saved = yaml.safe_load(path.read_text()) + assert saved["_version"] == 8 + assert saved["device"]["serial"] == "updated" + assert saved["credentials"] == credentials + assert saved["logging"] == {"debug": True, "level": "debug", **unknown_logging} + for key, value in unknown.items(): + assert saved[key] == value + + +def test_save_fresh_config_preserves_unknown_values_already_on_disk( + tmp_path, monkeypatch ): + monkeypatch.setenv("MOBILERUN_USER_CONFIG_DIR", str(tmp_path)) + path = tmp_path / "config.yaml" + path.write_text( + "_version: 8\nfuture: null\nlogging:\n level: quiet\n future: false\n" + ) - def blocked(name): - assert name == "mobilerun_agents" - raise ModuleNotFoundError(name=missing) + ConfigLoader.save(MobileConfig()) - monkeypatch.setattr(paths, "find_spec", blocked) - prompt = Path("config/prompts/blocked-test.jinja2") - if missing != "mobilerun_agents": - with pytest.raises(ModuleNotFoundError): - paths.PathResolver.bundled_asset(prompt) - else: - assert paths.PathResolver.bundled_asset(prompt) is None + saved = yaml.safe_load(path.read_text()) + assert saved["future"] is None + assert saved["logging"] == {"debug": False, "level": "normal", "future": False} -def test_v8_leaves_missing_prompt_unchanged_and_is_idempotent(tmp_path, monkeypatch): - monkeypatch.chdir(tmp_path) - monkeypatch.setattr(PathResolver, "get_project_root", lambda: tmp_path) - monkeypatch.setattr(paths, "find_spec", lambda name: None) - config = { - "_version": 7, - "agent": {"fast_agent": {"user_prompt": "config/prompts/custom.jinja2"}}, - } - result = migrate(config) - assert ( - result["agent"]["fast_agent"]["user_prompt"] == "config/prompts/custom.jinja2" - ) - assert migrate(deepcopy(result)) == result +def test_save_stale_model_preserves_newer_unmodeled_values_on_disk( + tmp_path, monkeypatch +): + monkeypatch.setenv("MOBILERUN_USER_CONFIG_DIR", str(tmp_path)) + path = tmp_path / "config.yaml" + path.write_text("_version: 8\nfuture: old\nlogging: {future: old}\n") + config = ConfigLoader.load(str(path)) + path.write_text("_version: 8\nfuture: new\nlogging: {future: new}\n") + config.logging.level = "quiet" + ConfigLoader.save(config) -def test_v6_chain_keeps_manager_auto_selection(): - result = migrate( - { - "_version": 6, - "agent": { - "manager": {"system_prompt": "config/prompts/manager/system.jinja2"} - }, - } - ) - assert result["agent"]["manager"]["system_prompt"] is None - assert result["_version"] == 8 + saved = yaml.safe_load(path.read_text()) + assert saved["future"] == "new" + assert saved["logging"] == {"debug": False, "level": "quiet", "future": "new"} -def test_migration_preserves_cwd_override(tmp_path, monkeypatch): - monkeypatch.chdir(tmp_path) - prompt = "config/prompts/system.jinja2" - local = tmp_path / prompt - local.parent.mkdir(parents=True) - local.touch() - package = tmp_path / "package" - bundled = package / "assets/prompts/system.jinja2" - bundled.parent.mkdir(parents=True) - bundled.touch() - monkeypatch.setattr(PathResolver, "get_project_root", lambda: package) - config = { - "_version": 7, - "agent": {"fast_agent": {"system_prompt": prompt}}, - } - assert migrate(config)["agent"]["fast_agent"]["system_prompt"] == prompt +def test_save_to_new_path_preserves_values_even_when_aliased_to_base_sections( + tmp_path, monkeypatch +): + monkeypatch.setenv("MOBILERUN_USER_CONFIG_DIR", str(tmp_path)) + source = tmp_path / "old.yaml" + source.write_text( + "_version: 2\n" + "device: &device {serial: original}\n" + "logging: &logging {debug: true, future: false}\n" + "credentials: &credentials {enabled: true}\n" + "other: {device: *device, logging: *logging, credentials: *credentials}\n" + ) + config = ConfigLoader.load(str(source)) + config.logging.debug = False + config.device.serial = "new" + config.credentials["enabled"] = False + saved_path = ConfigLoader.save(config) -def test_legacy_app_card_path_is_not_redirected(tmp_path, monkeypatch): - addon = tmp_path / "mobilerun_agents" - (addon / "assets/app_cards").mkdir(parents=True) - (addon / "__init__.py").touch() - monkeypatch.delitem(sys.modules, "mobilerun_agents", raising=False) - monkeypatch.syspath_prepend(str(tmp_path)) - monkeypatch.chdir(tmp_path) - legacy_path = "config/app_cards" - config = { - "_version": 7, - "agent": {"app_cards": {"app_cards_dir": legacy_path}}, + original_other = { + "device": {"serial": "original"}, + "logging": {"debug": True, "future": False}, + "credentials": {"enabled": True}, } - - assert PathResolver.resolve(legacy_path) == tmp_path / legacy_path - assert migrate(config)["agent"]["app_cards"]["app_cards_dir"] == legacy_path + assert yaml.safe_load(source.read_text())["other"] == original_other + saved = yaml.safe_load(saved_path.read_text()) + assert saved["other"] == original_other + assert saved["logging"] == {"debug": False, "level": "normal", "future": False} + assert saved["device"]["serial"] == "new" + assert saved["device"]["auto_setup"] is True + assert saved["credentials"] == {"enabled": False} def test_default_config_is_written_on_first_load(tmp_path, monkeypatch): @@ -313,6 +316,25 @@ def reject(config): assert (tmp_path / "config.yaml.v1.bak").read_text() == original +def test_config_update_edits_env_file_preserving_unmodeled_settings( + tmp_path, monkeypatch +): + monkeypatch.setenv("MOBILERUN_USER_CONFIG_DIR", str(tmp_path / "defaults")) + path = tmp_path / "custom.yaml" + original = "device:\n serial: old\nagent:\n name: custom\n" + path.write_text(original) + monkeypatch.setenv("MOBILERUN_CONFIG", str(path)) + + assert ( + ConfigLoader.update(lambda config: setattr(config.device, "serial", "new")) + == path + ) + assert (tmp_path / "custom.yaml.v1.bak").read_text() == original + assert not (tmp_path / "defaults").exists() + assert yaml.safe_load(path.read_text())["agent"] == {"name": "custom"} + assert ConfigLoader.load().device.serial == "new" + + def test_config_overrides_are_scoped_per_subclass( addon_config_file, tmp_path, monkeypatch ): @@ -348,7 +370,8 @@ def test_unversioned_config_migrates_and_preserves_original(tmp_path): assert config.device.serial == "my-device" data = yaml.safe_load(path.read_text()) assert data["_version"] == CURRENT_VERSION - assert data["agent"]["fast_agent"]["vision"] is True + assert data["agent"] == {"codeact": {"vision": True}} + assert data["device"]["auto_setup"] is True backup = tmp_path / "config.yaml.v1.bak" assert backup.read_text() == original if os.name != "nt": @@ -460,32 +483,7 @@ def test_standalone_resolver_reads_package_asset(tmp_path, monkeypatch): bundled = tmp_path / "assets/prompts/test.jinja2" bundled.parent.mkdir(parents=True) bundled.write_text("bundled") - assert resolver.resolve("config/prompts/test.jinja2", must_exist=True) == bundled - - -def test_move_into_project_after_migration(tmp_path, monkeypatch): - monkeypatch.chdir(tmp_path) - prompt = "config/prompts/system.jinja2" - addon = tmp_path / "split" / "mobilerun_agents" - bundled = addon / "assets/prompts/system.jinja2" - bundled.parent.mkdir(parents=True) - (addon / "__init__.py").write_text("raise AssertionError('unexpected import')") - bundled.write_text("bundled") - monkeypatch.delitem(sys.modules, "mobilerun_agents", raising=False) - monkeypatch.syspath_prepend(str(tmp_path / "split")) - project = tmp_path / "project" - local = project / prompt - local.parent.mkdir(parents=True) - local.write_text("local") - path = tmp_path / "user.yaml" - path.write_text(f"_version: 7\nagent:\n fast:\n system_prompt: {prompt}\n") - - ConfigLoader.load(str(path)) - stored = yaml.safe_load(path.read_text())["agent"]["fast"]["system_prompt"] - assert stored == prompt - assert PathResolver.resolve(stored, must_exist=True) == bundled - monkeypatch.chdir(project) - assert PathResolver.resolve(stored, must_exist=True) == local + assert resolver.resolve("assets/prompts/test.jinja2", must_exist=True) == bundled @pytest.mark.parametrize("dotenv", [False, True]) diff --git a/tests/unit/core/credentials/test_secret_handling.py b/tests/unit/core/credentials/test_secret_handling.py index c7a5b261d..0ca9a8a80 100644 --- a/tests/unit/core/credentials/test_secret_handling.py +++ b/tests/unit/core/credentials/test_secret_handling.py @@ -1,128 +1,37 @@ -"""Offline contracts for credential providers, secret input and observation masking.""" +"""Credential metadata, replay masks and scoped log redaction.""" import asyncio import io -import json import logging from contextvars import copy_context from functools import partial from types import SimpleNamespace -from unittest.mock import AsyncMock, patch +from unittest.mock import AsyncMock -import httpx import pytest -from mobilerun_core_local.driver import cloud as cloud_module -from mobilerun_sdk import AsyncMobilerun from mobilerun.core.credentials import ( CloudCredentials, CredentialPolicy, DictCredentials, - EnvCredentials, - FileCredentials, ) -from mobilerun.core.credentials.masking import CredentialMasks -from mobilerun.core.devices.android import AndroidDevice -from mobilerun.core.devices.base import Device -from mobilerun.core.devices.cloud import CloudDevice -from mobilerun.core.devices.pool import DevicePool -from mobilerun.core.devices.recording import RecordingDevice -from mobilerun.core.devices.stealth import StealthDevice -from mobilerun.core.extensions import Extension -from mobilerun.core.state.options import StateProviderOptions, android_state_provider -from mobilerun.errors import ( - CredentialNotFoundError, - DeviceError, - DeviceOperationNotSupported, - ExtensionActionError, - ExtensionNotBound, - NoFocusedInput, -) -from mobilerun.macro.errors import MacroError -from mobilerun.macro.models import MacroStep -from mobilerun.macro.player import MacroPlayer -from tests.support.devices import MemoryDevice -from tests.support.extensions import check_extension_contract - - -class FakeDevice(Device): - def __init__(self, **kwargs): - super().__init__(**kwargs) - self.input_text = AsyncMock(return_value=True) - self._input_text_raw = self.input_text - self.state.refresh = AsyncMock( - return_value=SimpleNamespace( - phone_state={ - "focusedElement": {"className": "EditText"}, - "isEditable": True, - } - ) - ) +from mobilerun.models.credentials import Credential +from mobilerun.utils.credentials.masking import CredentialMasks -def test_dict_normalizes_flat_and_nested_and_redacts(): - provider = DictCredentials( - { - "gmail_password": "private-value", - "com.gmail": { - "work": {"email": "private-email", "password": "private-password"} - }, - } - ) - asyncio.run(provider.bind(FakeDevice())) - items = asyncio.run(provider.list()) - assert [(item["package"], item["name"], item["fields"]) for item in items] == [ - (None, "gmail_password", ["password"]), - ("com.gmail", "work", ["email", "password"]), - ] - assert "private-" not in repr(items) - assert "private-" not in str(items[0]) - device = provider.device - asyncio.run(provider.type_field("com.gmail", "email", "work")) - device.input_text.assert_awaited_once_with("private-email") - - -@pytest.mark.parametrize("extension", ["yaml", "json"]) -def test_file_normalizes_flat_and_nested(tmp_path, extension): - path = tmp_path / f"credentials.{extension}" - path.write_text( - json.dumps( - { - "gmail_password": "private-value", - "com.gmail": {"work": {"username": "private-name"}}, - } - ) +def test_credential_mapping_copies_nested_fields_and_keeps_scopes(): + fields = {"username": "fixture-user"} + records = Credential.from_mapping( + {"flat": "fixture-password", None: {"general": fields}, "pkg": {"app": fields}} ) - path.chmod(0o600) - provider = FileCredentials(path) - device = FakeDevice() - asyncio.run(provider.bind(device)) - asyncio.run(provider.type_field(None, "password", "gmail_password")) - asyncio.run(provider.type_field("com.gmail", "username", "work")) - assert [call.args[0] for call in device.input_text.await_args_list] == [ - "private-value", - "private-name", + fields["username"] = "changed" + assert records == [ + Credential(None, "flat", {"password": "fixture-password"}), + Credential(None, "general", {"username": "fixture-user"}), + Credential("pkg", "app", {"username": "fixture-user"}), ] -def test_yaml_flat(tmp_path): - path = tmp_path / "credentials.yaml" - path.write_text("gmail_password: private-value\n") - path.chmod(0o600) - provider = FileCredentials(path) - asyncio.run(provider.bind(FakeDevice())) - assert asyncio.run(provider.list())[0]["name"] == "gmail_password" - - -def test_env_normalizes_flat(monkeypatch): - monkeypatch.setenv("MOBILERUN_SECRET_GMAIL_PASSWORD", "private-value") - provider = EnvCredentials() - device = FakeDevice() - asyncio.run(provider.bind(device)) - asyncio.run(provider.type_field(None, "password", "GMAIL_PASSWORD")) - device.input_text.assert_awaited_once_with("private-value") - - def test_cloud_paginated_cached_and_login_key(monkeypatch): calls = [] @@ -171,11 +80,12 @@ def make_client(**kwargs): from mobilerun.clients.cloud import client as transport monkeypatch.setattr(transport, "AsyncMobilerun", make_client) - monkeypatch.setattr(transport, "resolve_cloud_api_key", lambda: "fake-login-key") + monkeypatch.setattr( + transport.LoginStore, "resolve_api_key", lambda self: "fake-login-key" + ) provider = CloudCredentials(base_url="https://fake.invalid") async def run(): - await provider.bind(FakeDevice()) assert len(await provider.list()) == 2 assert (await provider.list("com.app2"))[0]["name"] == "work" assert "private-value" not in repr(await provider.list()) @@ -188,423 +98,6 @@ async def run(): ] -def test_device_order_recording_wrappers_pool_and_no_log(caplog, tmp_path): - caplog.set_level("DEBUG") - first = DictCredentials({"login": "private-first"}) - second = DictCredentials( - {"login": "private-second", "other": "private-other"}, name="second" - ) - device = FakeDevice() - asyncio.run(first.bind(device)) - asyncio.run(second.bind(device)) - recording = RecordingDevice(device, runs_dir=tmp_path, capture="actions") - stealth = StealthDevice(recording) - assert list(stealth.extensions) == list(recording.extensions) == ["vault", "second"] - - async def run(): - assert await recording.vault.type_field(None, "password", name="login") is None - assert await recording.second.type_field(None, "password", name="other") is None - assert DevicePool([recording]).extensions[0]["vault"].device is device - assert await first.type_field(None, "password", name="login") is None - - asyncio.run(run()) - assert [call.args[0] for call in device.input_text.await_args_list] == [ - "private-first", - "private-other", - "private-first", - ] - evidence = (recording.run_dir / "steps.jsonl").read_text() - first_row, *_ = map(json.loads, evidence.splitlines()) - assert first_row["args"] == { - "name": "vault.type_field", - "arguments": {"package": None, "field": "password", "name": "login"}, - } - assert "private-" not in evidence - assert "private-" not in caplog.text - - -@pytest.mark.parametrize( - "reference", - [ - {"package": "com.gmail", "field": "email", "name": "work"}, - {"name": "login"}, - ], -) -def test_macro_uses_device_credentials(reference, caplog): - caplog.set_level("DEBUG") - device = FakeDevice() - provider = DictCredentials( - { - "login": "private-value", - "com.gmail": {"work": {"email": "private-value"}}, - } - ) - asyncio.run(provider.bind(device)) - asyncio.run( - MacroPlayer(device).play_step( - MacroStep(i=1, action="type_secret", args=reference) - ) - ) - device.input_text.assert_awaited_once_with("private-value") - assert "private-value" not in caplog.text - - -@pytest.fixture -def focused_state(monkeypatch): - from mobilerun.core.state.view import UIStateView - - monkeypatch.setattr( - UIStateView, - "refresh", - AsyncMock( - return_value=SimpleNamespace( - phone_state={ - "focusedElement": {"className": "EditText"}, - "isEditable": True, - } - ) - ), - ) - - -@pytest.mark.usefixtures("focused_state") -def test_vault_exposes_only_metadata_and_types_secret(): - asyncio.run(_check_vault()) - - -async def _check_vault(): - secret = "canary-vault-private-value" - vault = DictCredentials({"app": {"account": {"password": secret}}}) - device = MemoryDevice() - assert isinstance(vault, Extension) - await vault.bind(device) - metadata = await vault.list() - assert secret not in repr(metadata) - assert secret not in repr(await vault.context()) - assert await vault.type_field("app", "password") is None - assert device.inputs == [secret] - - -@pytest.mark.usefixtures("focused_state") -def test_dict_vault_extension_contract(): - async def device(): - return MemoryDevice() - - asyncio.run( - check_extension_contract(lambda name: DictCredentials({}, name=name), device) - ) - - -@pytest.mark.usefixtures("focused_state") -def test_file_and_env_vault_extension_contract(tmp_path): - path = tmp_path / "credentials.yml" - path.write_text("{}") - path.chmod(0o600) - - async def device(): - return MemoryDevice() - - for factory in ( - lambda name: FileCredentials(path, name=name), - lambda name: EnvCredentials("NONEXISTENT_TEST_PREFIX_", name=name), - ): - asyncio.run(check_extension_contract(factory, device)) - - -@pytest.mark.usefixtures("focused_state") -def test_cloud_vault_extension_contract(): - async def device(): - return MemoryDevice() - - with patch( - "mobilerun.core.credentials.cloud.secrets.list_secrets", - AsyncMock(return_value=[]), - ): - asyncio.run( - check_extension_contract( - lambda name: CloudCredentials(api_key="test", name=name), device - ) - ) - - -@pytest.mark.usefixtures("focused_state") -def test_type_field_sanitizes_secret_input_failure(caplog): - async def run(): - secret = "secret-canary-must-not-escape" - device = MemoryDevice() - device._input_secret = AsyncMock(side_effect=RuntimeError(secret)) - vault = DictCredentials({"app": {"one": {"password": secret}}}) - await vault.bind(device) - with pytest.raises(ExtensionActionError) as exc: - await vault.type_field("app", "password") - assert secret not in str(exc.value) - assert secret not in caplog.text - device._input_secret.assert_awaited_once_with(secret) - - asyncio.run(run()) - - -@pytest.mark.usefixtures("focused_state") -def test_type_field_reports_unsuccessful_input(): - async def run(): - device = MemoryDevice() - device._input_secret = AsyncMock(return_value=False) - vault = DictCredentials({"app": {"one": {"password": "secret"}}}) - await vault.bind(device) - with pytest.raises(ExtensionActionError) as error: - await vault.type_field("app", "password") - assert isinstance(error.value, DeviceError) - assert "secret" not in str(error.value) - - asyncio.run(run()) - - -@pytest.mark.usefixtures("focused_state") -def test_type_field_uses_typed_missing_and_unbound_errors(): - async def run(): - vault = DictCredentials({}) - with pytest.raises(ExtensionNotBound): - await vault.type_field("app", "password") - await vault.bind(MemoryDevice()) - with pytest.raises(CredentialNotFoundError) as error: - await vault.type_field("app", "password") - from mobilerun.errors import CredentialFieldNotFound - - assert isinstance(error.value, CredentialFieldNotFound) - assert not isinstance(error.value, ExtensionActionError) - assert "password-value-canary" not in str(error.value) - - asyncio.run(run()) - - -@pytest.mark.usefixtures("focused_state") -def test_type_field_device_action_rejects_unbound_before_lookup(): - async def run(): - vault = DictCredentials({}) - vault._find = AsyncMock() - assert vault.actions.get("vault.type_field").requires_device - with pytest.raises(ExtensionNotBound): - await vault.type_field("app", "password") - vault._find.assert_not_awaited() - - asyncio.run(run()) - - -@pytest.mark.parametrize( - "phone_state", - [ - {"focusedElement": None, "isEditable": False}, - {"focusedElement": {"className": "Button"}, "isEditable": False}, - ], -) -def test_secret_refuses_unfocused_or_noneditable_input(phone_state): - async def run(): - device = Device() - device.state.refresh = AsyncMock( - return_value=SimpleNamespace(phone_state=phone_state) - ) - device._input_text_raw = AsyncMock(return_value=True) - with pytest.raises(NoFocusedInput, match="No text field is focused") as error: - await device._input_secret("secret-canary") - assert "secret-canary" not in str(error.value) - device._input_text_raw.assert_not_awaited() - - asyncio.run(run()) - - -def test_secret_types_only_when_focused_and_editable(): - async def run(): - device = Device() - device.state.refresh = AsyncMock( - return_value=SimpleNamespace( - phone_state={ - "focusedElement": {"className": "EditText"}, - "isEditable": True, - } - ) - ) - device._input_text_raw = AsyncMock(return_value=True) - assert await device._input_secret("demo-user") - device._input_text_raw.assert_awaited_once_with("demo-user") - - asyncio.run(run()) - - -@pytest.mark.parametrize( - ("app_nodes", "overrides", "types_secret"), - [ - pytest.param([{}], {}, True, id="edit-text-without-editable-flag"), - pytest.param( - [{}], {"focusedElement": {}, "isEditable": True}, True, id="empty-summary" - ), - pytest.param([{"isFocused": False}], {}, False, id="ime-only"), - pytest.param([{}, {}], {}, False, id="ambiguous-focus"), - pytest.param([{"packageName": "com.other"}], {}, False, id="other-package"), - pytest.param([{"isEnabled": False}], {}, False, id="disabled"), - pytest.param([{}], {"keyboardVisible": False}, False, id="keyboard-hidden"), - pytest.param([{}], {"degraded": True}, False, id="degraded-cache"), - pytest.param( - [], {"degraded": True, "isEditable": True}, True, id="degraded-strict" - ), - pytest.param([{"windowId": 2}], {}, False, id="same-package-other-window"), - pytest.param([{"windowId": None}], {}, False, id="unknown-node-window"), - pytest.param([{}], {"rootWindowId": None}, False, id="unknown-root-window"), - pytest.param( - [{}], {"omitWindowId": True}, True, id="single-window-without-ids" - ), - pytest.param( - [ - {}, - { - "className": "android.widget.FrameLayout", - "isFocused": False, - "children": [{"className": "android.widget.TextView"}], - }, - ], - {"omitWindowId": True}, - False, - id="two-same-package-roots-without-ids", - ), - pytest.param( - [ - { - "className": "android.widget.LinearLayout", - "isFocused": False, - "children": [ - { - "className": "android.widget.EditText", - "packageName": "com.app", - "isEnabled": True, - "isFocused": True, - } - ], - }, - { - "className": "android.view.View", - "resourceId": "com.app:id/overlay", - "isFocused": False, - }, - ], - {"omitWindowId": True}, - True, - id="windowless-chrome-shape", - ), - pytest.param([{"className": "android.widget.Button"}], {}, False, id="button"), - pytest.param( - [{"className": "custom.NotAutoCompleteTextView"}], - {}, - False, - id="autocomplete-lookalike", - ), - pytest.param([{"isEditable": False}], {}, False, id="explicitly-not-editable"), - pytest.param( - [{"isEditable": True, "className": "custom.Input"}], - {}, - True, - id="explicitly-editable", - ), - pytest.param( - [{"className": "android.widget.AutoCompleteTextView"}], - {}, - True, - id="autocomplete-without-editable-flag", - ), - pytest.param( - [{}], {"omitPackage": True}, False, id="missing-foreground-package" - ), - ], -) -def test_secret_input_checks_raw_app_focus( - app_nodes: list[dict[str, object]], overrides: dict[str, object], types_secret: bool -) -> None: - async def run() -> None: - device = MemoryDevice() - device._set_state_provider( - android_state_provider(device, StateProviderOptions()) - ) - device._get_ui_tree = AsyncMock( - return_value={ - "device_context": {"screen_bounds": {"width": 100, "height": 100}}, - "phone_state": { - **( - {} - if overrides.get("omitPackage") - else {"packageName": "com.app"} - ), - "focusedElement": overrides.get( - "focusedElement", {"className": "android.widget.FrameLayout"} - ), - "keyboardVisible": overrides.get("keyboardVisible", True), - "isEditable": overrides.get("isEditable", False), - }, - "a11y_tree": { - "className": "android.widget.FrameLayout", - "packageName": "com.app", - **( - {} - if overrides.get("omitWindowId") - else {"windowId": overrides.get("rootWindowId", 1)} - ), - "children": [ - { - "className": "android.widget.EditText", - "packageName": "com.app", - **( - {} if overrides.get("omitWindowId") else {"windowId": 1} - ), - "isEnabled": True, - "isFocused": True, - **node, - } - for node in app_nodes - ], - }, - "ime_tree": { - "className": "android.widget.FrameLayout", - # Package match alone must not let an IME node count. - "packageName": "com.app", - "windowId": 1, - "isEnabled": True, - "isFocused": True, - }, - **( - {"degraded": True, "snapshotAgeMs": 500} - if overrides.get("degraded") - else {} - ), - } - ) - vault = DictCredentials({"com.app": {"demo": {"password": "demo-value"}}}) - await vault.bind(device) - if types_secret: - await vault.type_field("com.app", "password", name="demo") - assert device.inputs == ["demo-value"] - else: - with pytest.raises(NoFocusedInput): - await vault.type_field("com.app", "password", name="demo") - assert device.inputs == [] - device._get_ui_tree.assert_awaited_once() - - asyncio.run(run()) - - -def test_secret_rejects_unknown_focus_capability(): - async def run(): - device = Device() - device.state.refresh = AsyncMock( - return_value=SimpleNamespace( - phone_state={"observationMode": "screenshot_only"} - ) - ) - device._input_text_raw = AsyncMock(return_value=True) - with pytest.raises(DeviceOperationNotSupported): - await device._input_secret("secret-canary") - device._input_text_raw.assert_not_awaited() - - asyncio.run(run()) - - -@pytest.mark.usefixtures("focused_state") def test_sensitive_extra_fields_and_to_thread_are_redacted(): from mobilerun.utils.redaction import secret_scope @@ -637,7 +130,6 @@ async def run(): assert "***" in stream.getvalue() -@pytest.mark.usefixtures("focused_state") def test_secret_record_factory_chains_and_is_idempotent(): from mobilerun.utils.redaction import secret_scope @@ -669,182 +161,6 @@ def previous(*args, **kwargs): logging.setLogRecordFactory(original) -@pytest.mark.usefixtures("focused_state") -def test_new_child_and_isolated_logger_redact_at_record_creation(caplog): - secret = "new-child-secret-7492" - device = AndroidDevice("device") - stream = io.StringIO() - handler = logging.StreamHandler(stream) - isolated = logging.getLogger("external.isolated-secret-test") - isolated.addHandler(handler) - isolated.propagate = False - isolated.setLevel(logging.DEBUG) - caplog.set_level(logging.DEBUG) - - async def raw(value, *args, **kwargs): - child = logging.getLogger("mobilerun_sdk.created_during_secret_7492") - child.warning("new child %s", value) - try: - raise ValueError(value) - except ValueError: - isolated.exception("isolated %s", value, stack_info=True) - return True - - device._input_text_raw = raw - try: - asyncio.run(device._input_secret(secret)) - finally: - isolated.removeHandler(handler) - isolated.propagate = True - assert "new child ***" in caplog.text - assert secret not in caplog.text - assert "isolated ***" in stream.getvalue() - assert secret not in stream.getvalue() - - -@pytest.mark.usefixtures("focused_state") -@pytest.mark.parametrize( - ("device_factory", "logger_name"), - [ - (lambda: CloudDevice("device", api_key="test"), "mobilerun_sdk._base_client"), - (lambda: AndroidDevice("device"), "mobilerun_core_local"), - ], -) -def test_secret_input_redacts_logs_exceptions_and_recording( - device_factory, logger_name, caplog, tmp_path -): - secret = "SENSITIVE-CANARY-9321" - logger = logging.getLogger(logger_name) - caplog.set_level(logging.DEBUG, logger=logger_name) - device = device_factory() - recorded = RecordingDevice(device, runs_dir=tmp_path, capture="actions") - - async def raw(value, *args, **kwargs): - try: - raise ValueError(f"backend {value}") - except ValueError: - logger.debug("request %s", {"text": value}, exc_info=True) - raise RuntimeError(f"failure {value}") from None - - device._input_text_raw = raw - - async def run(): - with pytest.raises(RuntimeError) as exc: - await recorded._input_secret(secret) - assert secret not in str(exc.value) - assert exc.value.__context__ is None - - asyncio.run(run()) - assert secret not in caplog.text - assert all(secret not in repr(record.__dict__) for record in caplog.records) - evidence = (recorded.run_dir / "steps.jsonl").read_text() - assert secret not in evidence - assert json.loads(evidence)["args"]["text"] == "***" - - -@pytest.mark.usefixtures("focused_state") -def test_redaction_context_is_task_local_and_is_reset(caplog): - secret = "context-canary" - logger = logging.getLogger("mobilerun_sdk._base_client") - caplog.set_level(logging.DEBUG, logger=logger.name) - device = AndroidDevice("device") - entered = asyncio.Event() - resume = asyncio.Event() - - async def raw(value, *args, **kwargs): - logger.debug("inside %s", value) - entered.set() - await resume.wait() - return True - - device._input_text_raw = raw - - async def run(): - task = asyncio.create_task(device._input_secret(secret)) - await entered.wait() - logger.debug("outside %s", secret) - resume.set() - await task - logger.debug("after %s", secret) - - asyncio.run(run()) - assert caplog.records[0].getMessage() == "inside ***" - assert caplog.records[1].getMessage() == f"outside {secret}" - assert caplog.records[2].getMessage() == f"after {secret}" - - -@pytest.mark.usefixtures("focused_state") -@pytest.mark.parametrize( - "secret", ["cloud-sdk-secret-canary", "sdk-secret\nwith'quote"] -) -def test_real_cloud_sdk_debug_options_are_redacted( - monkeypatch, caplog, secret, tmp_path -): - caplog.set_level(logging.DEBUG, logger="mobilerun_sdk._base_client") - clients = [] - - def sdk_factory(**kwargs): - client = AsyncMobilerun( - **kwargs, - http_client=httpx.AsyncClient( - transport=httpx.MockTransport(lambda request: httpx.Response(204)) - ), - ) - clients.append(client) - return client - - monkeypatch.setattr(cloud_module, "AsyncMobilerun", sdk_factory) - - async def run(): - device = CloudDevice( - "device", api_key="test", base_url="https://example.invalid" - ) - recording = RecordingDevice(device, runs_dir=tmp_path, capture="actions") - assert await recording._input_secret(secret) - evidence = (recording.run_dir / "steps.jsonl").read_text() - assert secret not in evidence - assert json.loads(evidence)["args"]["text"] == "***" - for client in clients: - await client.close() - - asyncio.run(run()) - assert any("Request options" in record.getMessage() for record in caplog.records) - assert all(secret not in repr(record.__dict__) for record in caplog.records) - assert repr(secret)[1:-1] not in caplog.text - - -@pytest.mark.usefixtures("focused_state") -def test_android_driver_failed_adb_shell_log_is_redacted(caplog, tmp_path): - secret = "android-adb-secret-canary" - caplog.set_level(logging.DEBUG, logger="mobilerun_core_local") - device = AndroidDevice("device") - device._ensure_connected = AsyncMock() - device._driver.device = SimpleNamespace( - shell=AsyncMock(side_effect=RuntimeError(secret)) - ) - - async def input_text(value, *args, **kwargs): - await device._driver._try_shell(f"input text {value}") - raise ValueError(value) - - device._driver.input_text = input_text - - async def run(): - recording = RecordingDevice(device, runs_dir=tmp_path, capture="actions") - with pytest.raises(ValueError) as error: - await recording._input_secret(secret) - assert secret not in str(error.value) - evidence = (recording.run_dir / "steps.jsonl").read_text() - assert secret not in evidence - assert json.loads(evidence)["args"]["text"] == "***" - - asyncio.run(run()) - assert any( - "ADB shell command failed" in record.getMessage() for record in caplog.records - ) - assert all(secret not in repr(record.__dict__) for record in caplog.records) - - def test_reordered_split_echo_masks_only_bounded_fragments(): masks = CredentialMasks() masks.register("pin", "123456") @@ -907,29 +223,21 @@ def test_package_independent_mask_registers_every_matching_field(): ] * 2 -@pytest.mark.parametrize("protected", [True, False]) -def test_missing_named_credential_binding_fails_before_tap(protected): - async def run(): - device = MemoryDevice() - device.tap = AsyncMock() - await DictCredentials({"login": "test"}).bind(device) - macro = [ - MacroStep(i=1, action="tap", args={"x": 1, "y": 2}), - MacroStep( - i=2, - action="extension_call", - args={ - "name": "other_vault.type_field", - "arguments": {"name": "login"}, - "protected": protected, - }, - ), +def test_nested_mask_scope_restores_outer_masks_after_failure(): + with CredentialMasks.scope() as outer: + outer.register("outer", "sample-outer") + with pytest.raises(RuntimeError): + with CredentialMasks.scope() as inner: + inner.register("inner", "sample-inner") + assert CredentialMasks.current.get() is inner + raise RuntimeError("abort scope") + assert not inner.active + assert CredentialMasks.current.get() is outer + assert snapshot(outer, "sample-outer sample-inner")["nodes"] == [ + {"text": "[secret:outer] sample-inner"} ] - with pytest.raises(MacroError): - await MacroPlayer(device, delay_between_actions=0).replay_macro(macro) - device.tap.assert_not_awaited() - - asyncio.run(run()) + assert CredentialMasks.current.get() is None + assert not outer.active def test_masks_preserve_digit_word_boundaries_and_unrelated_label_text(): diff --git a/tests/unit/core/credentials/test_type_secret.py b/tests/unit/core/credentials/test_type_secret.py new file mode 100644 index 000000000..9e6ffea27 --- /dev/null +++ b/tests/unit/core/credentials/test_type_secret.py @@ -0,0 +1,402 @@ +import asyncio +import json +import logging +from pathlib import Path +from types import SimpleNamespace + +import pytest +from mobilerun_core import ( + ActionCall, + ActionEvent, + AsyncDevice, + FocusUnknown, + NoFocusedInput, + SecretInputRejected, +) + +from mobilerun.core.credentials import ( + CloudCredentials, + CredentialDeviceRequired, + CredentialPolicy, + DictCredentials, + EnvCredentials, + FileCredentials, + cloud, +) +from mobilerun.core.extensions import compile_tools +from mobilerun.core.runs import ActionRecording +from mobilerun.errors import CredentialError, CredentialFieldNotFound +from mobilerun.errors.credentials import CredentialReadError +from mobilerun.macro.models import MacroStep +from mobilerun.macro.player import MacroPlayer +from mobilerun.models.cloud_task import CloudCredentialReference +from mobilerun.utils.credentials.masking import CredentialMasks +from mobilerun.utils.redaction import redact +from tests.support.devices import FakeDriver, fake_device + +CANARY = "protected-input-canary" + + +def test_vault_exposes_read_only_device_binding() -> None: + device = fake_device() + vault = DictCredentials({}, device=device) + assert vault.device is device + assert DictCredentials({}).device is None + with pytest.raises(AttributeError): + vault.device = None # type: ignore[misc] + + +def test_type_secret_requires_explicit_device() -> None: + vault = DictCredentials({"github": "private-canary"}) + with pytest.raises(CredentialDeviceRequired, match="device=") as caught: + asyncio.run(vault.type_secret("github")) + assert "private-canary" not in str(caught.value) + assert "private-canary" not in repr(caught.value) + assert asyncio.run(vault.list()) == [ + {"package": None, "name": "github", "fields": ["password"]} + ] + + +def test_compile_secret_atomics_without_exposing_values() -> None: + vault = DictCredentials({"gmail": "private-canary", "github": "another-canary"}) + tools = compile_tools([vault]) + assert [tool.name for tool in tools] == [ + "vault.list", + "vault.type_secret_github", + "vault.type_secret_gmail", + ] + for tool in tools[1:]: + assert tool.input_schema["properties"] == {} + assert tool.name.removeprefix("vault.type_secret_") in tool.description + assert "canary" not in json.dumps([tool.input_schema, tool.output_schema]) + + +def test_duplicate_credential_names_get_distinct_package_aliases_and_replay() -> None: + first_canary = "first-package-secret-canary" + second_canary = "second-package-secret-canary" + driver = FakeDriver() + written_packages = [] + + async def input_probe( + text: str, *, clear: bool = False, humanize: bool = False + ) -> bool: + written_packages.append( + "a.b" if text == first_canary else "a_b" if text == second_canary else None + ) + return True + + driver.input_text = input_probe + entries = { + "a_b": {"login": {"password": second_canary}}, + "a.b": {"login": {"password": first_canary}}, + # This legal credential name would collide under naïve concatenation. + "a_b_login": CANARY, + } + + async def run() -> None: + async with fake_device(driver=driver) as device: + vault = DictCredentials(entries, device=device) + first_name = "vault.type_secret__encoded_p612e62_n6c6f67696e" + second_name = "vault.type_secret__encoded_p615f62_n6c6f67696e" + tools = {tool.name: tool for tool in compile_tools([vault])} + assert set(tools) == { + "vault.list", + "vault.type_secret_a_b_login", + first_name, + second_name, + } + player = MacroPlayer(device, extensions=[vault]) + for alias, package in ((first_name, "a.b"), (second_name, "a_b")): + tool = tools[alias] + assert tool.input_schema["properties"] == {} + visible = repr( + ( + tool.name, + tool.description, + tool.input_schema, + tool.output_schema, + tool, + ) + ) + if any( + value in visible for value in (first_canary, second_canary, CANARY) + ): + pytest.fail( + "A credential value was exposed in its descriptor", + pytrace=False, + ) + await tool.invoke({}) + await player.play_step( + MacroStep( + schema_version=2, + i=1, + action="extension_call", + args={ + "name": tool.canonical_name, + "arguments": {"name": "login", "package": package}, + }, + ) + ) + + asyncio.run(run()) + assert written_packages == ["a.b", "a.b", "a_b", "a_b"] + + +def test_flat_credential_is_reachable_when_a_package_reuses_its_name() -> None: + driver = FakeDriver() + typed = [] + + async def input_probe( + text: str, *, clear: bool = False, humanize: bool = False + ) -> bool: + typed.append(text == CANARY) + return True + + driver.input_text = input_probe + + async def run() -> None: + async with fake_device(driver=driver) as device: + vault = DictCredentials( + {"login": CANARY, "app": {"login": {"password": "scoped-canary"}}}, + device=device, + ) + tools = compile_tools([vault]) + assert [tool.name for tool in tools] == [ + "vault.list", + "vault.type_secret__encoded_u_n6c6f67696e", + "vault.type_secret__encoded_p617070_n6c6f67696e", + ] + for tool in tools[1:]: + await tool.invoke({}) + + asyncio.run(run()) + assert typed == [True, False] + + +@pytest.mark.parametrize("kind", ["dict", "env", "file", "cloud"]) +def test_provider_types_via_core_and_keeps_evidence_safe( + kind: str, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, +) -> None: + driver = FakeDriver() + device = fake_device(driver=driver, humanize=True) + name = "github" + received: list[bool] = [] + input_text = driver.input_text + + async def input_probe( + text: str, *, clear: bool = False, humanize: bool = False + ) -> bool: + received.append(text == CANARY and not clear and not humanize) + logging.getLogger("fake-driver.probe").warning("driver received %s", text) + # The shared fake logs ordinary typing verbatim. Its probe is the + # plaintext transport boundary for this test; record only a safe value. + return await input_text(redact(text), clear=clear, humanize=humanize) + + monkeypatch.setattr(driver, "input_text", input_probe) + vault: DictCredentials + if kind == "dict": + vault = DictCredentials({name: CANARY}, device=device) + elif kind == "env": + monkeypatch.setenv(f"TEST_VAULT_{name}", CANARY) + vault = EnvCredentials("TEST_VAULT_", device=device) + elif kind == "file": + path = tmp_path / "credentials.json" + path.write_text(json.dumps({name: CANARY})) + path.chmod(0o600) + vault = FileCredentials(path, device=device) + else: + + async def list_secrets( + *args: object, **kwargs: object + ) -> list[SimpleNamespace]: + return [ + SimpleNamespace( + package_name="example-app", + credential_name=name, + fields=[SimpleNamespace(field_type="password", value=CANARY)], + ) + ] + + monkeypatch.setattr(cloud.Vault, "list", list_secrets) + vault = CloudCredentials(api_key="fake-api-key", device=device) + + hooks: list[ActionCall | ActionEvent] = [] + + async def before(phone: AsyncDevice, call: ActionCall) -> None: + assert phone is device + hooks.append(call) + + async def after(phone: AsyncDevice, event: ActionEvent) -> None: + assert phone is device + hooks.append(event) + + async def run() -> None: + async with device, device.use_action_hooks(before=before, after=after): + try: + await vault.list() + tool = next( + t + for t in compile_tools([vault]) + if t.name == "vault.type_secret_github" + ) + with CredentialMasks.scope() as masks: + assert await tool.invoke({}) is None + state = {"phone_state": {}, "nodes": [{"text": CANARY}]} + assert masks.snapshot(state)["nodes"] == [ + {"text": "[secret:github]"} + ] + assert await vault.context() + if kind == "cloud": + assert (await vault.cloud_task_inputs()).credential_references == ( + CloudCredentialReference("example-app", name), + ) + assert CANARY not in repr(await vault.cloud_task_inputs()) + assert CANARY not in repr(await vault.context()) + finally: + await vault.close() + + asyncio.run(run()) + assert received == [True] + assert [hook.action.name for hook in hooks] == ["type_secret", "type_secret"] + for hook in hooks: + secret_arg = hook.action.arguments["secret"] + if type(secret_arg) is not str or secret_arg != "***": + pytest.fail( + "The hook did not receive a plain redaction marker", pytrace=False + ) + if CANARY in repr(hook.action.arguments): + pytest.fail("The hook arguments contain the secret value", pytrace=False) + assert [call[0] for call in driver.calls] == ["get_ui_tree", "input_text"] + assert CANARY not in repr((hooks, driver.calls, device, vault)) + assert "driver received ***" in caplog.text + assert CANARY not in caplog.text + + +def test_recorded_credential_masks_later_rows(tmp_path: Path) -> None: + async def run() -> Path: + async with fake_device() as device: + vault = DictCredentials({"github": CANARY}, device=device) + async with ActionRecording(device, runs_dir=tmp_path) as recording: + with CredentialMasks.scope(redactor=recording.redactor): + async with recording.extension_call( + "vault.type_secret", {"name": "github"} + ): + await vault.type_secret("github") + # Simulate a later device action with an argument containing a UI echo. + await device.type(f"echo: {CANARY}") + recording.finish("succeeded") + return recording.run_dir / "steps.jsonl" + + content = asyncio.run(run()).read_text() + assert CANARY not in content + rows = [json.loads(line) for line in content.splitlines()] + assert [row["action"] for row in rows] == ["extension_call", "type"] + assert rows[0]["args"]["arguments"] == {"name": "github"} + + +def test_direct_vault_typing_masks_enclosing_recordings_but_not_later_runs( + tmp_path: Path, +) -> None: + echo = f"x{CANARY}y" + + async def run() -> tuple[Path, Path, Path]: + async with fake_device() as device, fake_device() as other_device: + vault = DictCredentials({"login": CANARY}, device=device) + async with ActionRecording(other_device, runs_dir=tmp_path) as outer: + async with ActionRecording(device, runs_dir=tmp_path) as inner: + await vault.type_secret("login") + await device.type(echo) + inner.finish("succeeded") + await other_device.type(echo) + outer.finish("succeeded") + async with ActionRecording(device, runs_dir=tmp_path) as independent: + await device.type(echo) + independent.finish("succeeded") + return inner.run_dir, outer.run_dir, independent.run_dir + + inner, outer, independent = asyncio.run(run()) + + def recorded_text(run_dir: Path) -> str: + lines = (run_dir / "steps.jsonl").read_text().splitlines() + return json.loads(lines[-1])["args"]["text"] + + if recorded_text(inner) != "***" or recorded_text(outer) != "***": + pytest.fail("Credential echo leaked into recorded typing", pytrace=False) + if recorded_text(independent) != echo: + pytest.fail("An independent recording inherited a credential", pytrace=False) + + +@pytest.mark.parametrize( + ("case", "error", "writes"), + [ + ("unfocused", NoFocusedInput, 0), + ("unknown", FocusUnknown, 0), + ("rejected", SecretInputRejected, 1), + ], +) +def test_core_typing_errors_are_preserved_without_retries( + case: str, error: type[Exception], writes: int +) -> None: + driver = FakeDriver() + if case == "unfocused": + driver.ui_tree["a11y_tree"][0]["isFocused"] = False + elif case == "unknown": + driver.ui_tree["degraded"] = True + else: + driver.failures["input_text"] = RuntimeError(CANARY) + + async def run() -> None: + async with fake_device(driver=driver) as device: + vault = DictCredentials({"github": CANARY}, device=device) + with pytest.raises(error) as caught: + await vault.type_secret("github") + assert CANARY not in str(caught.value) + assert CANARY not in repr(caught.value) + assert caught.value.__context__ is None + + asyncio.run(run()) + assert sum(call[0] == "input_text" for call in driver.calls) == writes + + +def test_lookup_failure_discards_unsafe_exception( + monkeypatch: pytest.MonkeyPatch, +) -> None: + async def fail(package: str | None) -> None: + raise RuntimeError(CANARY) + + async def run() -> None: + async with fake_device() as device: + vault = DictCredentials({"github": CANARY}, device=device) + monkeypatch.setattr(vault, "_list_credentials", fail) + with pytest.raises(CredentialReadError) as caught: + await vault.type_secret("github") + assert CANARY not in str(caught.value) + assert CANARY not in repr(caught.value) + assert caught.value.__context__ is None + + asyncio.run(run()) + + +def test_protected_or_ambiguous_credential_does_not_write() -> None: + driver = FakeDriver() + + async def run() -> None: + async with fake_device(driver=driver) as device: + vault = DictCredentials( + {p: {"card": {"number": CANARY}} for p in ("a", "b")}, device=device + ) + vault.policies = ( + CredentialPolicy("card", "number", "a", requires_approval=True), + ) + with pytest.raises(CredentialFieldNotFound): + await vault.type_secret("card") + with pytest.raises(CredentialError, match="host approval"): + await vault.type_secret("card", package="a", field="number") + with pytest.raises(CredentialFieldNotFound): + await vault.type_secret("missing") + + asyncio.run(run()) + assert driver.calls == [] diff --git a/tests/unit/core/devices/test_backends.py b/tests/unit/core/devices/test_backends.py deleted file mode 100644 index 560748ba0..000000000 --- a/tests/unit/core/devices/test_backends.py +++ /dev/null @@ -1,484 +0,0 @@ -"""Offline contracts for Android, emulator, and Portal HTTP backends.""" - -import asyncio -from types import SimpleNamespace -from unittest.mock import AsyncMock - -import httpx -import pytest -from click.testing import CliRunner -from mobilerun_core_local.driver.android import AndroidPortalHttpDriver -from mobilerun_core_local.driver.android.portal import ( - PORTAL_PACKAGE_NAME, - portal_a11y_service, -) - -from mobilerun.cli.devices import device as cli -from mobilerun.cli.devices.base import selection -from mobilerun.clients.portal.http import ( - create_android_portal_http_driver, - is_portal_http_url, -) -from mobilerun.clients.portal.state_fetch import fetch_state_with_retry -from mobilerun.config.settings import get_settings -from mobilerun.config.user_config import MobileConfig -from mobilerun.core.devices import AndroidDevice, DevicePool, android -from mobilerun.core.devices.components.wrapper import DriverDevice -from mobilerun.core.devices.recording import RecordingDevice -from mobilerun.core.operator import Operator -from mobilerun.core.state.options import android_state_provider -from mobilerun.errors import StateFetchFailed -from mobilerun.models.results import ExecutionResult -from tests.support.devices import MemoryDevice - - -@pytest.mark.parametrize( - "shell_error", [None, RuntimeError()], ids=["success", "failure"] -) -def test_close_attempts_keyboard_cleanup(shell_error): - device = AndroidDevice(serial="test") - shell = AsyncMock(side_effect=shell_error) - device._adb_device = SimpleNamespace(shell=shell) - asyncio.run(device.close()) - shell.assert_awaited_once() - assert shell.await_args.args[0].startswith("ime disable ") - - -def test_disabled_portal_has_no_recovery(): - assert AndroidDevice("fake", portal_mode="disabled")._state_recovery is None - - -def test_failed_adb_only_tree_read_does_not_touch_accessibility(monkeypatch): - device = AndroidDevice("fake", portal_mode="auto") - adb = SimpleNamespace( - shell=AsyncMock(), - shell2=AsyncMock(return_value=SimpleNamespace(returncode=0, output="null")), - ) - device._adb_device = adb - fetch = AsyncMock(side_effect=RuntimeError("ADB tree unavailable")) - monkeypatch.setattr(android.asyncio, "sleep", AsyncMock()) - with pytest.raises(StateFetchFailed, match="ADB tree unavailable"): - asyncio.run( - fetch_state_with_retry( - fetch, - device._state_recovery, - max_retries=2, - retry_delays=[0], - recovery_after=1, - ) - ) - assert fetch.await_count == 2 - adb.shell.assert_not_awaited() - adb.shell2.assert_not_awaited() - - -@pytest.mark.parametrize("current", ["reader/.Main:magnifier/.Main", "null", "already"]) -def test_recovery_preserves_services(monkeypatch, current): - device = AndroidDevice("fake") - device._portal = SimpleNamespace(tcp_available=False) - portal = portal_a11y_service(PORTAL_PACKAGE_NAME) - if current == "already": - current = f"reader/.Main:{portal}" - read = AsyncMock(return_value=SimpleNamespace(output=current, returncode=0)) - shell = AsyncMock() - device._adb_device = SimpleNamespace(shell=shell, shell2=read) - monkeypatch.setattr(android.asyncio, "sleep", AsyncMock()) - asyncio.run(device._state_recovery()) - commands = [c.args[0] for c in shell.await_args_list] - read.assert_awaited_once_with( - "settings get secure enabled_accessibility_services", rstrip=True - ) - expected = [] - if portal not in current.split(":"): - merged = portal if current == "null" else f"{current}:{portal}" - expected.append(f"settings put secure enabled_accessibility_services {merged}") - expected.append("settings put secure accessibility_enabled 1") - assert commands == expected - - -def test_recovery_does_not_write_after_failed_settings_read(): - device = AndroidDevice("fake") - device._portal = SimpleNamespace(tcp_available=False) - shell = AsyncMock() - device._adb_device = SimpleNamespace( - shell=shell, - shell2=AsyncMock( - return_value=SimpleNamespace(output="permission denied", returncode=1) - ), - ) - with pytest.raises(RuntimeError, match="read"): - asyncio.run(device._state_recovery()) - shell.assert_not_awaited() - - -def test_close_waits_for_owned_emulator(monkeypatch): - async def scenario(): - device = AndroidDevice(avd="test") - entered, resume = asyncio.Event(), asyncio.Event() - - async def boot(*args, **kwargs): - entered.set() - await resume.wait() - - for name, result in [ - ("find_running", None), - ("list_avds", ["test"]), - ("start_avd", "fake"), - ("stop", None), - ]: - monkeypatch.setattr(android.emulator, name, AsyncMock(return_value=result)) - monkeypatch.setattr(android.emulator, "wait_boot", boot) - monkeypatch.setattr(device, "_ensure_connected", AsyncMock()) - startup = asyncio.create_task(device.connect()) - await entered.wait() - closing = asyncio.create_task(device.close()) - await asyncio.sleep(0) - resume.set() - await asyncio.gather(startup, closing) - android.emulator.stop.assert_awaited_once_with("fake") - assert not device._started_emulator - - asyncio.run(scenario()) - - -def test_closed_avd_cannot_start(monkeypatch): - device = AndroidDevice(avd="test") - boot = AsyncMock(side_effect=AssertionError("started after close")) - monkeypatch.setattr(device, "_boot", boot) - asyncio.run(device.close()) - with pytest.raises(RuntimeError, match="closed"): - asyncio.run(device.connect()) - boot.assert_not_awaited() - - -def test_pool_validates_execution_facade(): - class RecordingOperator(Operator): - def check(self, device): - assert isinstance(device, RecordingDevice) - - async def execute(self, device, *args, **kwargs): - self.check(device) - return ExecutionResult(success=True, device="fake") - - device = RecordingDevice(MemoryDevice(), operator=RecordingOperator()) - assert asyncio.run(DevicePool([device]).do("go"))[0].success - - -@pytest.mark.parametrize("suffix", [[], ["get"], ["set"]]) -def test_clipboard_help_identifies_supported_targets(suffix): - result = CliRunner().invoke(cli, ["input", "clipboard", *suffix, "--help"]) - assert result.exit_code == 0 - assert "cloud device" in result.output.lower().split("options:")[0] - - -@pytest.mark.parametrize("args", [["get"], ["set", "private text"]]) -def test_local_clipboard_requires_cloud_target(monkeypatch, args): - from mobilerun.cli.devices.base import selection - from mobilerun.config.loader import ConfigLoader - from mobilerun.config.user_config import MobileConfig - - monkeypatch.setattr(ConfigLoader, "load", lambda path: MobileConfig()) - - connect = AsyncMock() - monkeypatch.setattr(selection, "connect_target", connect) - result = CliRunner().invoke(cli, ["input", "clipboard", *args, "-d", "fake"]) - assert result.exit_code == 2 - assert "Clipboard commands require a cloud device ID." in result.stderr - assert "private text" not in result.output - connect.assert_not_called() - - -PORTAL_URL = "http://192.168.1.20:8080" - - -@pytest.mark.parametrize( - ("device", "expected"), - [ - ("http://192.168.1.20:8080", True), - ("HTTPS://phone.local:8080", True), - ("emulator-5554", False), - ("192.168.1.20:5555", False), - ("", False), - (None, False), - ], -) -def test_is_portal_http_url(device, expected): - assert is_portal_http_url(device) is expected - - -def test_portal_http_driver_requires_token(): - with pytest.raises(ValueError, match="MOBILERUN_DEVICE_TOKEN"): - create_android_portal_http_driver(PORTAL_URL, None) - - -def test_portal_http_driver_normalizes_url(): - driver = create_android_portal_http_driver(PORTAL_URL + "/", "sekret") - - assert isinstance(driver, AndroidPortalHttpDriver) - assert driver.url == PORTAL_URL - assert driver.token == "sekret" - - -@pytest.fixture -def driver(): - return AndroidPortalHttpDriver( - "http://portal.test", - "test-token", - transport=httpx.MockTransport(lambda _: httpx.Response(200)), - ) - - -@pytest.mark.anyio -async def test_cli_device_closes_owned_portal_client(driver, monkeypatch): - monkeypatch.setattr( - selection, "create_android_portal_http_driver", lambda *_: driver - ) - device = await selection.connect_target( - driver.url, kind="android", config=MobileConfig() - ) - client = driver._client - assert not client.is_closed - await device.close() - assert client.is_closed - - -@pytest.mark.anyio -async def test_driver_device_leaves_borrowed_portal_client_open(driver): - device = DriverDevice(driver, state_provider_factory=android_state_provider) - await device.connect() - client = driver._client - try: - await device.close() - assert not client.is_closed - finally: - await client.aclose() - - -@pytest.mark.parametrize( - "overrides, expected", - [ - (None, ("android_cloud_phone", None)), - (("custom-cloud", "Pixel_API"), ("custom-cloud", "Pixel_API")), - ], - ids=["defaults", "overrides"], -) -def test_device_type_settings(monkeypatch, overrides, expected): - keys = ("MOBILERUN_CLOUD_DEVICE_TYPE", "MOBILERUN_ANDROID_DEVICE_TYPE") - if overrides is None: - for key in keys: - monkeypatch.delenv(key, raising=False) - else: - for key, value in zip(keys, overrides, strict=True): - monkeypatch.setenv(key, value) - settings = get_settings() - assert ( - settings.MOBILERUN_CLOUD_DEVICE_TYPE, - settings.MOBILERUN_ANDROID_DEVICE_TYPE, - ) == expected - - -def test_cloud_create_uses_setting_and_explicit_override(monkeypatch): - from mobilerun.core.devices import cloud - - create = AsyncMock(return_value=SimpleNamespace(id="device", name="device")) - devices = SimpleNamespace( - create=create, - wait_ready=AsyncMock(), - retrieve_capabilities=AsyncMock( - return_value=SimpleNamespace( - capabilities=SimpleNamespace(telephony=False, proxy=True) - ) - ), - ) - - class Client: - def __init__(self, **kwargs): - self.devices = devices - - async def __aenter__(self): - return self - - async def __aexit__(self, *args): - pass - - monkeypatch.setenv("MOBILERUN_CLOUD_DEVICE_TYPE", "ios_phone") - from mobilerun_core_local.driver import cloud as driver - - client = Client() - client.with_options = lambda **kwargs: client - monkeypatch.setattr(driver, "AsyncMobilerun", lambda **kwargs: client) - - async def initialize(): - await cloud.CloudDevice(api_key="test", billing="paid") - await cloud.CloudDevice( - api_key="test", billing="paid", device_type="device_slot" - ) - - asyncio.run(initialize()) - assert [call.kwargs["device_type"] for call in create.await_args_list] == [ - "ios_phone", - "device_slot", - ] - - -@pytest.fixture -def fake_connection(monkeypatch): - monkeypatch.setattr(AndroidDevice, "_ensure_connected", AsyncMock()) - - -def run_device(device): - async def ready(): - return await device - - return asyncio.run(ready()) - - -def test_create_reuses_running_avd(fake_connection, monkeypatch): - from mobilerun.clients.local import emulator - - monkeypatch.setenv("MOBILERUN_ANDROID_DEVICE_TYPE", "configured") - monkeypatch.setattr( - emulator, "find_running", AsyncMock(return_value="emulator-5554") - ) - start = AsyncMock() - monkeypatch.setattr(emulator, "start_avd", start) - monkeypatch.setattr(emulator, "wait_boot", AsyncMock()) - device = run_device(AndroidDevice(avd="configured")) - assert device._serial == "emulator-5554" - emulator.find_running.assert_awaited_once_with("configured") - start.assert_not_awaited() - - -def test_create_starts_explicit_avd_and_terminate(fake_connection, monkeypatch): - from mobilerun.clients.local import emulator - - monkeypatch.setattr(emulator, "find_running", AsyncMock(return_value=None)) - monkeypatch.setattr(emulator, "list_avds", AsyncMock(return_value=["pixel"])) - monkeypatch.setattr(emulator, "start_avd", AsyncMock(return_value="emulator-5556")) - monkeypatch.setattr(emulator, "wait_boot", AsyncMock()) - monkeypatch.setattr(emulator, "stop", AsyncMock()) - device = run_device(AndroidDevice(avd="pixel", headless=True)) - assert device._serial == "emulator-5556" - asyncio.run(device.terminate()) - emulator.stop.assert_awaited_once_with("emulator-5556") - - -def test_unknown_avd_lists_available_avds(fake_connection, monkeypatch): - from mobilerun.clients.local import emulator - - monkeypatch.delenv("MOBILERUN_ANDROID_DEVICE_TYPE", raising=False) - find_running = AsyncMock(return_value=None) - monkeypatch.setattr(emulator, "find_running", find_running) - monkeypatch.setattr(emulator, "list_avds", AsyncMock(return_value=["pixel"])) - start_avd = AsyncMock() - monkeypatch.setattr(emulator, "start_avd", start_avd) - with pytest.raises(ValueError, match="pixel"): - run_device(AndroidDevice(avd="missing")) - find_running.assert_awaited_once_with("missing") - start_avd.assert_not_awaited() - - -def test_terminate_refuses_physical_device( - fake_connection, -): - with pytest.raises(ValueError, match="emulator"): - asyncio.run(AndroidDevice(serial="physical").terminate()) - - -def test_client_lists_avds_and_finds_running(fake_connection, monkeypatch): - from mobilerun.clients.local import emulator - - async def command(*args): - if args[-1] == "-list-avds": - return "pixel\ntablet\n" - if args[-1] == "devices": - return "List of devices attached\nemulator-5554\tdevice\nphysical\tdevice\n" - return "pixel\nOK\n" - - monkeypatch.setattr(emulator, "_command", command) - assert asyncio.run(emulator.list_avds()) == ["pixel", "tablet"] - assert asyncio.run(emulator.find_running("pixel")) == "emulator-5554" - assert asyncio.run(emulator.find_running("other")) is None - - -def test_client_start_uses_emulator_reported_port(fake_connection, monkeypatch): - from mobilerun.clients.local import emulator - - async def launch(*args, **kwargs): - assert "-port" not in args - assert "-no-window" in args - report = args[args.index("-report-console") + 1] - reader, writer = await asyncio.open_connection( - "127.0.0.1", int(report.split(":")[1]) - ) - writer.write(b"5556") - await writer.drain() - writer.close() - await writer.wait_closed() - return object() - - monkeypatch.setattr(asyncio, "create_subprocess_exec", launch) - assert asyncio.run(emulator.start_avd("pixel", headless=True)) == "emulator-5556" - - -def test_wait_boot_timeout(fake_connection, monkeypatch): - from mobilerun.clients.local import emulator - - async def command(*args): - if args[-1] == "sys.boot_completed": - await asyncio.sleep(1) - return "0" - - monkeypatch.setattr(emulator, "_command", command) - with pytest.raises(TimeoutError, match="did not boot"): - asyncio.run(emulator.wait_boot("emulator-5554", timeout=0.01)) - - -def test_find_running_uses_adb_property_when_console_unavailable( - fake_connection, monkeypatch -): - from mobilerun.clients.local import emulator - - async def command(*args): - if args[-1] == "devices": - return "List of devices attached\nemulator-5554\tdevice\n" - if args[-1] == "name": - return "" - return "pixel\n" - - monkeypatch.setattr(emulator, "_command", command) - assert asyncio.run(emulator.find_running("pixel")) == "emulator-5554" - - -def test_boot_failure_cleans_up_only_new_emulator(fake_connection, monkeypatch): - from mobilerun.clients.local import emulator - - monkeypatch.setattr(emulator, "find_running", AsyncMock(return_value=None)) - monkeypatch.setattr(emulator, "list_avds", AsyncMock(return_value=["pixel"])) - monkeypatch.setattr(emulator, "start_avd", AsyncMock(return_value="emulator-5556")) - monkeypatch.setattr( - emulator, "wait_boot", AsyncMock(side_effect=TimeoutError("boot")) - ) - stop = AsyncMock() - monkeypatch.setattr(emulator, "stop", stop) - with pytest.raises(TimeoutError, match="boot"): - run_device(AndroidDevice(avd="pixel")) - stop.assert_awaited_once_with("emulator-5556") - - -def test_stop_kills_started_process_if_adb_unavailable(fake_connection, monkeypatch): - from mobilerun.clients.local import emulator - - process = type( - "Process", - (), - {"returncode": None, "kill": lambda self: None, "wait": AsyncMock()}, - )() - monkeypatch.setitem(emulator._processes, "emulator-5556", process) - monkeypatch.setattr( - emulator, "_command", AsyncMock(side_effect=RuntimeError("offline")) - ) - killed = [] - monkeypatch.setattr(process, "kill", lambda: killed.append(True)) - asyncio.run(emulator.stop("emulator-5556")) - assert killed == [True] diff --git a/tests/unit/core/devices/test_controls.py b/tests/unit/core/devices/test_controls.py deleted file mode 100644 index 0c76dc46d..000000000 --- a/tests/unit/core/devices/test_controls.py +++ /dev/null @@ -1,736 +0,0 @@ -"""Device environment controls, app installation, and APK inspection.""" - -import asyncio -import json -import subprocess -from types import SimpleNamespace -from typing import Any, cast -from unittest.mock import AsyncMock, Mock - -import pytest -from click.testing import CliRunner -from mobilerun_core_local.driver.android import AndroidPortalHttpDriver -from mobilerun_sdk.types.shared.location import Location - -from mobilerun.cli.devices.base import selection -from mobilerun.cli.devices.group import device as device_command -from mobilerun.cli.devices.settings import location as location_command -from mobilerun.clients.cloud import apps, devices -from mobilerun.clients.local import apk -from mobilerun.core.devices.android import AndroidDevice -from mobilerun.core.devices.base import Device -from mobilerun.core.devices.cloud import CloudDevice -from mobilerun.core.devices.components.wrapper import DeviceWrapper, DriverDevice -from mobilerun.core.devices.ios import IOSDevice -from mobilerun.core.devices.pool import DevicePool -from mobilerun.errors import DeviceOperationNotSupported -from mobilerun.models.apps import App -from mobilerun.models.billing import Billing -from mobilerun.models.location import Location as DeviceLocation - - -def test_cloud_location_helper_and_device(): - async def run(): - value = Location(latitude=52.52, longitude=13.405) - get = AsyncMock(return_value=value) - client = SimpleNamespace( - devices=SimpleNamespace(location=SimpleNamespace(get=get)) - ) - assert ( - await devices.get_location( - "abc", billing=Billing.NO_COMMERCE, client=client - ) - == value - ) - phone = CloudDevice("abc", api_key="test") - phone._client = client - assert await phone.get_location() == DeviceLocation( - latitude=52.52, longitude=13.405 - ) - assert get.await_count == 2 - get.assert_awaited_with("abc") - - asyncio.run(run()) - - -def test_unsupported_and_wrapped_pool(): - async def run(): - with pytest.raises(DeviceOperationNotSupported, match="get_location"): - await AndroidDevice(serial="emulator-5554").get_location() - inner = Device() - inner.get_location = AsyncMock(return_value=Location(latitude=1, longitude=2)) - assert (await DevicePool([DeviceWrapper(inner)]).get_location())[ - 0 - ].latitude == 1 - - asyncio.run(run()) - - -@pytest.mark.parametrize( - "value,args,expected", - [ - (Location(latitude=52.52, longitude=13.405), [], "Location: 52.5200, 13.4050"), - (None, [], "Location: Not available"), - ( - Location(latitude=52.52, longitude=13.405), - ["--json"], - {"latitude": 52.52, "longitude": 13.405}, - ), - (None, ["--json"], None), - ], -) -def test_cli_location_get(monkeypatch, value, args, expected): - phone = SimpleNamespace( - get_location=AsyncMock(return_value=value), close=AsyncMock() - ) - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=phone)) - result = CliRunner().invoke( - device_command, ["settings", "location", "get", "--device", "abc", *args] - ) - assert result.exit_code == 0, result.output - assert (json.loads(result.output) if args else result.output.strip()) == expected - phone.close.assert_awaited_once() - - -def test_location_menu_lists_get(): - result = CliRunner().invoke(device_command, ["settings", "location", "--help"]) - assert "get" in result.output - - -def test_interactive_location_menu_lists_get(monkeypatch): - from mobilerun.cli.base import menu - - seen = [] - monkeypatch.setattr(menu, "is_interactive", lambda: True) - - def choose(label, choices): - seen.extend(choice.value for choice in choices) - return None - - monkeypatch.setattr(menu, "select_prompt", choose) - CliRunner().invoke(location_command, []) - assert {"get", "set", "reset"} <= set(seen) - - -def test_default_environment_is_unsupported(): - with pytest.raises(DeviceOperationNotSupported): - asyncio.run(Device().open_url("https://example.com")) - - -def test_cloud_environment_calls_sdk(): - async def run(): - device = CloudDevice("abc", api_key="test") - resources = SimpleNamespace( - location=SimpleNamespace(set=AsyncMock(), reset=AsyncMock()), - language=SimpleNamespace(set=AsyncMock()), - timezone=SimpleNamespace(set=AsyncMock()), - clipboard=SimpleNamespace( - set=AsyncMock(), - get=AsyncMock(return_value=SimpleNamespace(text="hello")), - ), - deep_link=SimpleNamespace(execute_deep_link=AsyncMock()), - ) - device._write_client = cast(Any, SimpleNamespace(devices=resources)) - device._client = device._write_client - await device.set_location(1.0, 2.0) - await device.reset_location() - await device.set_language("de-DE") - await device.set_timezone("Europe/Berlin") - await device.set_clipboard("hello") - assert await device.get_clipboard() == "hello" - await device.open_url("https://example.com") - resources.location.set.assert_awaited_once_with( - "abc", latitude=1.0, longitude=2.0 - ) - resources.location.reset.assert_awaited_once_with("abc") - resources.language.set.assert_awaited_once_with("abc", locale="de-DE") - resources.timezone.set.assert_awaited_once_with("abc", timezone="Europe/Berlin") - resources.clipboard.set.assert_awaited_once_with("abc", text="hello") - resources.deep_link.execute_deep_link.assert_awaited_once_with( - "abc", deep_link="https://example.com" - ) - - asyncio.run(run()) - - -def test_wrapper_and_pool_forward_open(): - async def run(): - inner = Device() - inner.open_url = AsyncMock() - wrapper = DeviceWrapper(inner) - await wrapper.open_url("test://url") - await DevicePool([wrapper]).open_url("test://url") - assert inner.open_url.await_count == 2 - - asyncio.run(run()) - - -def test_android_open_quotes_and_rejects_invalid_settings(): - - async def run(): - device = AndroidDevice(serial="serial") - device._ensure_connected = AsyncMock() - shell = AsyncMock(return_value=SimpleNamespace(returncode=0, output="")) - device._adb_device = cast(Any, SimpleNamespace(shell2=shell, serial="serial")) - await device.open_url("https://example.com/?a=1&b='two'") - assert shell.await_args is not None - assert ( - shell.await_args.args[0] - == "am start -a android.intent.action.VIEW -d 'https://example.com/?a=1&b='\"'\"'two'\"'\"''" - ) - with pytest.raises(ValueError): - await device.set_timezone("../bad") - with pytest.raises(DeviceOperationNotSupported, match="physical Android"): - await device.set_location(1, 2) - - asyncio.run(run()) - - -def test_emulator_reset_explains_location_persists(): - - with pytest.raises( - DeviceOperationNotSupported, - match="emulators keep the last fixed location; set a new one instead", - ): - asyncio.run(AndroidDevice(serial="emulator-5554").reset_location()) - - -def test_emulator_geo_fix_and_timezone(): - - async def run(): - device = AndroidDevice(serial="emulator-5554") - device._ensure_connected = AsyncMock() - adb_output = Mock(return_value="OK") - shell = AsyncMock(return_value=SimpleNamespace(returncode=0, output="")) - device._adb_device = cast( - Any, - SimpleNamespace( - serial="emulator-5554", adb_output=adb_output, shell2=shell - ), - ) - await device.set_location(52.52, 13.4) - adb_output.assert_called_once_with("emu", "geo", "fix", "13.4", "52.52") - await device.set_timezone("Europe/Berlin") - shell.assert_awaited_once_with("cmd alarm set-timezone Europe/Berlin") - with pytest.raises(ValueError): - await device.set_timezone("Europe/Berlin;reboot") - shell.return_value = SimpleNamespace(returncode=1, output="Permission denial") - with pytest.raises(DeviceOperationNotSupported, match="Permission denial"): - await device.set_timezone("Europe/Berlin") - adb_output.return_value = "KO: denied" - with pytest.raises(DeviceOperationNotSupported, match="rejected"): - await device.set_location(0, 0) - - asyncio.run(run()) - - -@pytest.mark.parametrize( - ("method", "args"), - [ - ("set_location", (1.0, 2.0)), - ("reset_location", ()), - ("set_timezone", ("Europe/Berlin",)), - ("open_url", ("https://example.com",)), - ("set_language", ("de-DE",)), - ("set_clipboard", ("hello",)), - ("get_clipboard", ()), - ], -) -def test_wrapper_pool_delegate_each_environment_method(method, args): - async def run(): - inner = Device() - mock = AsyncMock(return_value="value" if method == "get_clipboard" else None) - setattr(inner, method, mock) - wrapper = DeviceWrapper(inner) - assert await getattr(wrapper, method)(*args) == ( - "value" if method == "get_clipboard" else None - ) - assert await getattr(DevicePool([wrapper]), method)(*args) == ( - ["value"] if method == "get_clipboard" else [None] - ) - assert mock.await_count == 2 - mock.assert_awaited_with(*args) - - asyncio.run(run()) - - -@pytest.mark.parametrize( - ("method", "args"), - [ - ("set_location", (1.0, 2.0)), - ("reset_location", ()), - ("set_timezone", ("Europe/Berlin",)), - ("open_url", ("https://example.com",)), - ], -) -@pytest.mark.parametrize("platform", ["ios", "remote"]) -def test_unsupported_ios_remote(method, args, platform): - from mobilerun.core.devices.remote import RemoteDevice - - device = ( - IOSDevice("http://localhost:1") - if platform == "ios" - else RemoteDevice("http://localhost:1") - ) - with pytest.raises(DeviceOperationNotSupported): - asyncio.run(getattr(device, method)(*args)) - - -@pytest.mark.parametrize("serial", ["emulator-5554", "physical-serial"]) -@pytest.mark.parametrize( - ("method", "args"), - [ - ("reset_location", ()), - ], -) -def test_android_unsupported_environment_operations_on_both_kinds(serial, method, args): - - with pytest.raises(DeviceOperationNotSupported): - asyncio.run(getattr(AndroidDevice(serial=serial), method)(*args)) - - -def test_device_protocol_declares_app_installation(): - assert callable(Device.__dict__.get("install_app")) - assert callable(Device.__dict__.get("uninstall_app")) - - -def test_android_portal_app_operations_raise_domain_error(): - from mobilerun.core.state.options import android_state_provider - - device = DriverDevice( - AndroidPortalHttpDriver("http://localhost:8080", "test"), - state_provider_factory=android_state_provider, - ) - with pytest.raises(DeviceOperationNotSupported, match="cannot install"): - asyncio.run(device.install_apk("app.apk")) - with pytest.raises(DeviceOperationNotSupported, match="cannot uninstall"): - asyncio.run(device.uninstall_app("org.example")) - - -def test_ios_uninstall_raises_domain_error(): - - device = IOSDevice("http://localhost") - from mobilerun_core_local.driver.ios import IOSPortalDriver - - device._driver = IOSPortalDriver("http://localhost") - with pytest.raises(DeviceOperationNotSupported, match="uninstall"): - asyncio.run(device.uninstall_app("org.example")) - - -def test_android_local_install_delegates(monkeypatch): - - from mobilerun_core_local.driver.android import AndroidDriver - - install = AsyncMock(return_value="installed") - monkeypatch.setattr(AndroidDriver, "install_app", install) - monkeypatch.setattr( - "mobilerun.core.devices.android.inspect_apk", - lambda path: ("org.example", 1, "1", "Example"), - ) - - device = AndroidDevice("fake") - device._driver.ensure_connected = AsyncMock() - device._adb_device = SimpleNamespace( - shell=AsyncMock(return_value="package:/data/app/base.apk") - ) - assert ( - asyncio.run(device.install_apk("app.apk", reinstall=True)).package - == "org.example" - ) - install.assert_awaited_once_with("app.apk", reinstall=True) - - -def test_android_install_returns_app_and_uses_its_path(monkeypatch, tmp_path): - import mobilerun.core.devices.android as android - - apk = tmp_path / "counter.apk" - apk.write_bytes(b"apk") - monkeypatch.setattr( - android, - "inspect_apk", - lambda path: ("ai.droidrun.counter", 3, "1.2", "Counter"), - ) - install = AsyncMock(return_value="success") - monkeypatch.setattr(android.AndroidDriver, "install_app", install) - device = android.AndroidDevice(serial="test") - device._driver.ensure_connected = AsyncMock() - device._adb_device = SimpleNamespace( - shell=AsyncMock(return_value="package:/data/app/base.apk") - ) - app = asyncio.run(device.install_apk(apk)) - assert app == App( - package="ai.droidrun.counter", - version="1.2", - name="Counter", - version_code=3, - path=apk, - ) - assert asyncio.run(device.install_app(app)) == app - assert install.await_count == 2 - with pytest.raises(ValueError, match="This app has no local APK"): - asyncio.run(device.install_app(App(package="p", version="1", name="N"))) - - -def test_app_path_is_optional(): - assert App(package="p", version="1", name="N").path is None - - -def test_android_lifecycle_accepts_descriptor_and_string(monkeypatch): - import mobilerun.core.devices.android as android - - app = App("org.example", "1", "Example") - device = android.AndroidDevice(serial="test") - device._driver.ensure_connected = AsyncMock() - for method in ("start_app", "stop_app"): - fake = AsyncMock(return_value="ok") - monkeypatch.setattr(android.AndroidDriver, method, fake) - assert asyncio.run(getattr(device, method)(app.package)) == "ok" - assert fake.await_args.args[0] == "org.example" - assert asyncio.run(getattr(device, method)("org.example")) == "ok" - assert fake.await_args.args[0] == "org.example" - - fake = AsyncMock(return_value="ok") - monkeypatch.setattr(android.AndroidDriver, "uninstall_app", fake) - assert asyncio.run(device.uninstall_app(app.package)) == "ok" - - -def test_pool_pairs_installed_apps_with_devices(): - - first, second = App("one", "1", "One"), App("two", "1", "Two") - devices = [type("Fake", (), {})(), type("Fake", (), {})()] - for device, app in zip(devices, [first, second], strict=True): - device._operator = None - device.install_apk = AsyncMock(return_value=app) - device.start_app = AsyncMock() - device.uninstall_app = AsyncMock() - pool = DevicePool(devices) - apps = asyncio.run(pool.install_apk("app.apk")) - - async def run(): - for device, app in zip(pool.devices, apps, strict=True): - await device.start_app(app.package, activity=None) - await device.uninstall_app(app.package) - - asyncio.run(run()) - devices[0].start_app.assert_awaited_once_with(first.package, activity=None) - devices[1].start_app.assert_awaited_once_with(second.package, activity=None) - devices[0].uninstall_app.assert_awaited_once_with(first.package) - devices[1].uninstall_app.assert_awaited_once_with(second.package) - - -def test_cloud_install_uploads_without_billing_guard(monkeypatch, tmp_path): - - apk = tmp_path / "app.apk" - apk.write_bytes(b"apk") - monkeypatch.setattr( - apps, "inspect_apk", lambda path: ("org.example", 3, "1", "Example") - ) - signed = SimpleNamespace( - app_id="id", - version_id="version", - r2_upload_urls=[ - SimpleNamespace(file_name="app.apk", r2_upload_url="https://upload") - ], - ) - sdk = SimpleNamespace( - apps=SimpleNamespace( - list=AsyncMock( - return_value=SimpleNamespace( - items=[], pagination=SimpleNamespace(has_next=False) - ) - ), - create_signed_upload_url=AsyncMock(return_value=signed), - confirm_upload=AsyncMock(), - ) - ) - context = AsyncMock() - context.__aenter__.return_value = sdk - monkeypatch.setattr(apps, "cloud_client", lambda *args, **kwargs: context) - http = AsyncMock() - http.__aenter__.return_value = http - http.put.return_value = SimpleNamespace(raise_for_status=lambda: None) - device = CloudDevice(device_id="device", api_key="test") - monkeypatch.setattr(apps.httpx, "AsyncClient", lambda **kwargs: http) - device._ensure_connected = AsyncMock() - request = AsyncMock( - side_effect=[ - SimpleNamespace(installs=[]), - SimpleNamespace( - installs=[ - SimpleNamespace( - app_id="org.example", status="succeeded", started_at=1 - ) - ] - ), - ] - ) - device.list_apps = AsyncMock( - return_value=[{"package_name": "org.example", "version_code": 3}] - ) - monkeypatch.setattr(apps, "list_installs", request) - install = AsyncMock() - monkeypatch.setattr(apps, "install", install) - app = asyncio.run(device.install_apk(apk)) - assert app.package == "org.example" - install.assert_awaited_once_with( - device._client, - "device", - package_name="org.example", - background=True, - version_code=3, - billing="paid", - ) - - -def test_ios_lifecycle_accepts_app(monkeypatch): - import mobilerun.core.devices.ios as ios - - app = App("org.example", "1", "Example") - fake = AsyncMock(return_value="ok") - device = ios.IOSDevice("http://localhost") - device._driver = ios.IOSPortalDriver("http://localhost") - device._driver.ensure_connected = AsyncMock() - monkeypatch.setattr(device._driver, "start_app", fake) - assert asyncio.run(device.start_app(app.package)) == "ok" - fake.assert_awaited_once_with("org.example", None) - - -def test_cloud_install_app_with_local_path_uploads(monkeypatch, tmp_path): - import mobilerun.core.devices.components.cloud_apps as cloud - - path = tmp_path / "app.apk" - local = App("example", "1", "Example", path=path) - uploaded = App("example", "1", "Example", id="id", path=path) - device = CloudDevice(device_id="device", api_key="test") - device._ensure_connected = AsyncMock() - request = AsyncMock( - side_effect=[ - SimpleNamespace(installs=[]), - SimpleNamespace( - installs=[ - SimpleNamespace(app_id="example", status="succeeded", started_at=1) - ] - ), - ] - ) - device.list_apps = AsyncMock( - return_value=[{"package_name": "example", "version_name": "1"}] - ) - monkeypatch.setattr(cloud.apps, "list_installs", request) - install = AsyncMock() - monkeypatch.setattr(cloud.apps, "install", install) - upload = AsyncMock(return_value=uploaded) - monkeypatch.setattr(cloud, "upload_app", upload) - assert asyncio.run(device.install_app(local)) == uploaded - assert upload.await_args.args == (path,) - install.assert_awaited_once_with( - device._client, - "device", - package_name="example", - background=True, - billing="paid", - ) - with pytest.raises(ValueError, match="This app has no local APK"): - asyncio.run(device.install_app(App("example", "1", "Example"))) - - -@pytest.mark.parametrize( - "status, expected", [("failed", "failed"), ("running", "timed out")] -) -def test_cloud_install_failure_and_timeout(monkeypatch, status, expected): - - import mobilerun.core.devices.components.cloud_apps as cloud - - device = CloudDevice(device_id="device", api_key="test") - device._ensure_connected = AsyncMock() - install = SimpleNamespace( - app_id="example", status=status, error_class="failed", started_at=1 - ) - calls = 0 - - async def request(*args, **kwargs): - nonlocal calls - calls += 1 - return SimpleNamespace(installs=[] if calls == 1 else [install]) - - monkeypatch.setattr(cloud.apps, "list_installs", AsyncMock(side_effect=request)) - monkeypatch.setattr(cloud.apps, "install", AsyncMock()) - with pytest.raises((RuntimeError, TimeoutError), match=expected): - asyncio.run( - device.install_app(App("example", "1", "Example", id="id"), timeout=0.05) - ) - - -def test_cloud_install_waits_until_succeeded_and_installed(monkeypatch): - - import mobilerun.core.devices.components.cloud_apps as cloud - - device = CloudDevice(device_id="device", api_key="test") - device._ensure_connected = AsyncMock() - attempts = iter(["running", "succeeded"]) - seen = [] - calls = 0 - - async def request(*args, **kwargs): - nonlocal calls - calls += 1 - if calls == 1: - return SimpleNamespace(installs=[]) - status = next(attempts) - seen.append(status) - return SimpleNamespace( - installs=[SimpleNamespace(app_id="example", status=status, started_at=1)] - ) - - monkeypatch.setattr(cloud.apps, "list_installs", AsyncMock(side_effect=request)) - monkeypatch.setattr(cloud.apps, "install", AsyncMock()) - device.list_apps = AsyncMock( - return_value=[{"package_name": "example", "version_code": 3}] - ) - app = App("example", "1", "Example", id="id", version_code=3) - assert asyncio.run(device.install_app(app, timeout=2)) == app - assert seen == ["running", "succeeded"] - device.list_apps.assert_awaited_once() - - -def test_android_install_checks_package_presence(monkeypatch, tmp_path): - - import mobilerun.core.devices.android as android - - apk = tmp_path / "app.apk" - apk.write_bytes(b"apk") - monkeypatch.setattr( - android, "inspect_apk", lambda path: ("example", 1, "1", "Example") - ) - monkeypatch.setattr(android.AndroidDriver, "install_app", AsyncMock()) - device = android.AndroidDevice(serial="test") - device._driver.ensure_connected = AsyncMock() - device._adb_device = SimpleNamespace(shell=AsyncMock(return_value="")) - with pytest.raises(RuntimeError, match="not installed"): - asyncio.run(device.install_apk(apk)) - - -def test_driver_device_passes_package_to_portal(): - - driver = SimpleNamespace( - platform="android", - credentials=[], - start_app=AsyncMock(return_value="ok"), - stop_app=AsyncMock(return_value="ok"), - uninstall_app=AsyncMock(return_value="ok"), - ) - from mobilerun.core.state.options import android_state_provider - - device = DriverDevice(driver, state_provider_factory=android_state_provider) - app = App("org.example", "1", "Example") - assert asyncio.run(device.start_app(app.package)) == "ok" - assert asyncio.run(device.stop_app(app.package)) == "ok" - assert asyncio.run(device.uninstall_app(app.package)) == "ok" - driver.start_app.assert_awaited_once_with("org.example", None) - driver.stop_app.assert_awaited_once_with("org.example") - driver.uninstall_app.assert_awaited_once_with("org.example") - - -@pytest.fixture -def fake_aapt(monkeypatch, tmp_path): - path = tmp_path / "app.apk" - path.write_bytes(b"test apk") - monkeypatch.setattr(apk.shutil, "which", lambda name: str(tmp_path / "aapt")) - run = Mock() - monkeypatch.setattr(apk.subprocess, "run", run) - return path, run - - -@pytest.mark.parametrize( - "fields", - ["versionCode='3'", "name='org.example'"], - ids=["no-name", "no-version-code"], -) -@pytest.mark.parametrize("operation", ["install", "upload"]) -def test_incomplete_apk_metadata_stops_operation( - monkeypatch, fake_aapt, fields, operation -): - path, run = fake_aapt - run.return_value.stdout = f"package: {fields}\napplication-label-de:'Beispiel'\n" - if operation == "install": - device = AndroidDevice(serial="test") - downstream = AsyncMock() - monkeypatch.setattr(device, "install_app", downstream) - result = device.install_apk(path) - else: - downstream = Mock(side_effect=AssertionError("unexpected cloud client")) - monkeypatch.setattr(apps, "cloud_client", downstream) - result = apps.upload_app(path, billing=Billing.NO_COMMERCE) - with pytest.raises(ValueError, match="missing package or version"): - asyncio.run(result) - downstream.assert_not_called() - - -def test_apk_inspection_timeout(fake_aapt): - path, run = fake_aapt - run.side_effect = subprocess.TimeoutExpired("aapt", 30) - with pytest.raises(RuntimeError, match="APK inspection timed out"): - apk.inspect_apk(path) - - -@pytest.mark.parametrize( - "default_label, expected", - [("", "org.example"), ("application-label:'Example'", "Example")], -) -def test_apk_label_uses_default_or_package(fake_aapt, default_label, expected): - path, run = fake_aapt - run.return_value.stdout = ( - "package: name='org.example' versionCode='3' versionName='1.2'\n" - f"application-label-de:'Beispiel'\n{default_label}\n" - ) - assert apk.inspect_apk(path) == ("org.example", 3, "1.2", expected) - - -def test_missing_aapt_explains_build_tools(monkeypatch, tmp_path): - - monkeypatch.setattr(apk.shutil, "which", lambda name: None) - monkeypatch.setattr(apk.Path, "home", lambda: tmp_path) - monkeypatch.delenv("ANDROID_HOME", raising=False) - monkeypatch.delenv("ANDROID_SDK_ROOT", raising=False) - with pytest.raises(RuntimeError, match="Android build-tools"): - apk.inspect_apk(tmp_path / "app.apk") - - -def test_recording_device_records_package_string(tmp_path): - from mobilerun.core.devices.recording import RecordingDevice - - inner = Device() - inner.start_app = AsyncMock(return_value="ok") - device = RecordingDevice(inner, runs_dir=tmp_path, capture="actions") - app = App("org.example", "1", "Example") - assert asyncio.run(device.start_app(app.package)) == "ok" - row = json.loads((device.run_dir / "steps.jsonl").read_text()) - assert row["args"]["package"] == "org.example" - - -def test_cloud_install_rejects_stale_installed_version(monkeypatch): - import mobilerun.core.devices.components.cloud_apps as cloud - - device = CloudDevice(device_id="device", api_key="test") - device._ensure_connected = AsyncMock() - request = AsyncMock( - side_effect=[ - SimpleNamespace(installs=[]), - SimpleNamespace( - installs=[ - SimpleNamespace(app_id="example", status="succeeded", started_at=1) - ] - ), - ] - ) - monkeypatch.setattr(cloud.apps, "list_installs", request) - monkeypatch.setattr(cloud.apps, "install", AsyncMock()) - device.list_apps = AsyncMock( - return_value=[{"package_name": "example", "version_code": 2}] - ) - with pytest.raises(TimeoutError, match="timed out"): - asyncio.run( - device.install_app( - App("example", "1", "Example", id="id", version_code=3), timeout=0.05 - ) - ) diff --git a/tests/unit/core/devices/test_device_contracts.py b/tests/unit/core/devices/test_device_contracts.py deleted file mode 100644 index 1608b8034..000000000 --- a/tests/unit/core/devices/test_device_contracts.py +++ /dev/null @@ -1,631 +0,0 @@ -"""Device construction, portable operations, backend delegation, and example contracts.""" - -import asyncio -import importlib -import subprocess -import sys -from operator import attrgetter -from types import SimpleNamespace -from typing import assert_type, cast -from unittest.mock import AsyncMock - -import pytest -from mobilerun_core_local.driver.android import AndroidDriver -from mobilerun_core_local.driver.base import DeviceDriver, PlatformUnsupportedError -from mobilerun_core_local.driver.ios import IOSDriver -from mobilerun_core_local.driver.visual_remote import VisualRemoteDriver - -from mobilerun.core.credentials import DictCredentials -from mobilerun.core.devices import ( - AndroidDevice, - Device, - IOSDevice, - RecordingDevice, - RemoteDevice, - StealthDevice, -) -from mobilerun.core.devices.components.wrapper import DeviceWrapper, DriverDevice -from mobilerun.core.devices.pool import DevicePool -from mobilerun.core.state.base import StateProvider, _should_resize_model_screenshot -from mobilerun.core.state.elements import _parse_bounds -from mobilerun.core.state.options import ( - StateProviderOptions, - android_state_provider, - screenshot_state_provider, -) -from mobilerun.core.state.ui_state import UIState -from mobilerun.errors import DeviceOperationNotSupported -from mobilerun.models import CloudCredentialReference, CloudTaskInputs -from tests.support.devices import MemoryDevice - - -@pytest.mark.parametrize( - ("name", "driver", "args", "kwargs", "platform"), - [ - ( - "AndroidDevice", - AndroidDriver, - (), - {"serial": "test", "portal_mode": "disabled"}, - "Android", - ), - ("IOSDevice", IOSDriver, ("http://localhost:8080",), {}, "iOS"), - ( - "RemoteDevice", - VisualRemoteDriver, - (), - {"url": "http://localhost:8090", "device_id": "test"}, - "VisualRemote", - ), - ], -) -def test_device_constructor_and_driver_compatibility( - name, driver, args, kwargs, platform, monkeypatch -): - devices = importlib.import_module("mobilerun.core.devices") - device_class = getattr(devices, name) - assert issubclass(device_class, devices.Device) - device = device_class(*args, **kwargs) - if name == "IOSDevice": - - monkeypatch.setattr( - "mobilerun.core.devices.ios.detect_ios_portal_kind", - AsyncMock(return_value="legacy"), - ) - monkeypatch.setattr(device, "_ensure_connected", AsyncMock()) - assert device._driver is None - asyncio.run(device.connect()) - platform = "ios" - assert isinstance(device._driver, driver) - assert not isinstance(device, DeviceDriver) - assert device.platform == platform - for wrapper in (devices.RecordingDevice, devices.StealthDevice): - wrapped = wrapper(device) - assert wrapped._inner is device - assert wrapped.platform == platform - - -def test_cloud_device_is_lazy_and_other_devices_do_not_require_cloud(): - script = """ -import importlib.abc -import sys -class BlockCloud(importlib.abc.MetaPathFinder): - def find_spec(self, fullname, path=None, target=None): - if fullname == "mobilerun_core_local.driver.cloud": - raise ImportError("cloud deliberately unavailable") -sys.meta_path.insert(0, BlockCloud()) -import mobilerun.core.devices as devices -assert "mobilerun_core_local.driver.cloud" not in sys.modules -assert devices.AndroidDevice -try: - devices.CloudDevice -except ImportError as exc: - assert "cloud deliberately unavailable" in str(exc) -else: - raise AssertionError("cloud should be imported only on access") -""" - subprocess.run([sys.executable, "-c", script], check=True) - - -def test_cloud_device_constructor_and_driver_compatibility(): - cloud = pytest.importorskip("mobilerun_core_local.driver.cloud") - devices = importlib.import_module("mobilerun.core.devices") - cls = devices.CloudDevice - assert issubclass(cls, devices.Device) - device = cls("test-device", api_key="test-key") - assert isinstance(device._driver, cloud.CloudDriver) - assert not isinstance(device, DeviceDriver) - assert device.device_id == "test-device" - assert device.platform == "Android" - for wrapper in (devices.RecordingDevice, devices.StealthDevice): - assert wrapper(device)._inner is device - - -@pytest.mark.parametrize( - "name", - ["set_clipboard", "get_clipboard", "set_language"], -) -def test_environment_surface_is_portable(name: str) -> None: - from mobilerun.core.devices.cloud import CloudDevice - - for cls in (Device, DeviceWrapper, RecordingDevice, StealthDevice, DevicePool): - assert getattr(cls, name) is not None - assert getattr(CloudDevice, name) is not None - - -def test_wrappers_preserve_typed_backend_handle() -> None: - from mobilerun.core.devices.cloud import CloudDevice - - cloud = CloudDevice("phone", api_key="test") - wrapped = RecordingDevice(StealthDevice(cloud)) - assert_type(wrapped._inner._inner, CloudDevice) - assert wrapped._inner._inner is cloud - assert wrapped._unwrap() is cloud - - -def test_local_number_and_unbound_mailbox_explain_unavailability() -> None: - with pytest.raises(DeviceOperationNotSupported, match="No sms extension"): - _ = Device().number - with pytest.raises(DeviceOperationNotSupported, match="No email extension"): - _ = Device().mailbox - - -def test_cloud_resources_work_through_wrappers_and_pool(monkeypatch) -> None: - from datetime import datetime, timezone - - from mobilerun.clients.cloud import devices, mailboxes, numbers - from mobilerun.core.devices.cloud import CloudDevice - from mobilerun.core.mailbox import CloudMailbox - from mobilerun.core.phone_number import CloudPhoneNumber - - async def run() -> None: - phone = CloudDevice("phone", api_key="test") - phone._cloud_telephony = True - number = CloudPhoneNumber("number", api_key="test") - mailbox = CloudMailbox("mailbox", api_key="test") - monkeypatch.setattr(devices, "bind_number", AsyncMock()) - await number.bind(phone) - await mailbox.bind(phone) - now = datetime.now(timezone.utc) - sms = { - "id": "message", - "createdAt": now, - "occurredAt": now, - "direction": "inbound", - "status": "received", - "detectedSender": "sender", - "body": "Code 123456", - } - monkeypatch.setattr( - numbers, - "messages", - AsyncMock(return_value=[numbers.MessageItem.model_validate(sms)]), - ) - result = numbers.MessageSendResponse.model_validate({"data": sms}) - monkeypatch.setattr(numbers, "send", AsyncMock(return_value=result)) - monkeypatch.setattr( - mailboxes, - "otp", - AsyncMock( - return_value=SimpleNamespace(data=SimpleNamespace(code="654321")) - ), - ) - wrapper = DeviceWrapper(phone) - assert await wrapper.number.wait_for_code() == "123456" - assert len(await wrapper.number.messages()) == 1 - assert await wrapper.number.send("recipient", "message") == result - assert await wrapper.mailbox.wait_for_code() == "654321" - pool = DevicePool([wrapper]) - assert pool.number == [number] - assert pool.mailbox == [mailbox] - - asyncio.run(run()) - - -@pytest.mark.parametrize( - ("method", "args"), - [ - ("tap", (1, 2)), - ("swipe", (1, 2, 3, 4)), - ("drag", (1, 2, 3, 4)), - ("input_text", ("hello",)), - ("screenshot", ()), - ("start_app", ("app",)), - ("stop_app", ("app",)), - ("uninstall_app", ("app",)), - ("list_apps", ()), - ("press_button", ("home",)), - ("press_key_code", (3,)), - ("_get_ui_tree", ()), - ("_get_date", ()), - ("_ensure_connected", ()), - ], -) -def test_base_unsupported_operations_have_framework_error(method, args) -> None: - with pytest.raises(DeviceOperationNotSupported): - asyncio.run(getattr(Device(), method)(*args)) - - -@pytest.mark.parametrize("error", [NotImplementedError, PlatformUnsupportedError]) -@pytest.mark.parametrize("operation", ["tap", "stop_app", "_get_ui_tree"]) -def test_raw_adapter_translates_unsupported(error, operation) -> None: - class UnsupportedDriver(DeviceDriver): - async def tap(self, x: int, y: int) -> None: - raise error("backend unsupported") - - async def stop_app(self, package: str) -> str: - raise error("backend unsupported") - - async def get_ui_tree(self) -> dict[str, object]: - raise error("backend unsupported") - - device = DriverDevice( - UnsupportedDriver(), state_provider_factory=screenshot_state_provider - ) - args = {"tap": (1, 2), "stop_app": ("app",), "_get_ui_tree": ()}[operation] - with pytest.raises(DeviceOperationNotSupported, match="backend unsupported"): - asyncio.run(getattr(device, operation)(*args)) - - -@pytest.mark.parametrize( - "method,args", - [("list_apps", ()), ("_get_date", ()), ("_get_ui_tree", ())], -) -def test_visual_remote_does_not_report_empty_unsupported_results(method, args) -> None: - - with pytest.raises(DeviceOperationNotSupported): - asyncio.run(getattr(RemoteDevice("http://localhost:1"), method)(*args)) - - -@pytest.mark.parametrize( - "device", - [ - AndroidDevice("fake"), - IOSDevice("http://localhost"), - RemoteDevice("http://localhost"), - ], -) -def test_root_io_uses_its_backend_and_live_capabilities(device): - if device._driver is None: - from mobilerun_core_local.driver.ios import IOSPortalDriver - - device._driver = IOSPortalDriver("http://localhost") - device._driver.tap = AsyncMock() - device._driver.ensure_connected = AsyncMock() - device._driver.supported = {"tap"} - asyncio.run(device.tap(4, 8)) - device._driver.tap.assert_awaited_once_with(4, 8) - assert "tap" in device.supported_operations - - -def test_cloud_io_syncs_created_id_and_current_clients(): - from mobilerun.core.devices.cloud import CloudDevice - - device = CloudDevice(api_key="test") - device.device_id = "created" - device._ready = True - tap = AsyncMock() - device._write_client = SimpleNamespace( - devices=SimpleNamespace(actions=SimpleNamespace(tap=tap)) - ) - asyncio.run(device.tap(4, 8)) - assert tap.await_args.args == ("created",) - assert device._driver._client is device._client - assert device._driver._write_client is device._write_client - - -def test_pending_android_action_never_reaches_raw_backend(): - device = AndroidDevice(avd="fake") - device._driver.tap = AsyncMock() - with pytest.raises(RuntimeError, match="Await AndroidDevice"): - asyncio.run(device.tap(4, 8)) - device._driver.tap.assert_not_awaited() - - -@pytest.mark.parametrize("value", ["1,2,3", "1,2,3,4,5", "a,2,3,4"]) -def test_bounds_parser_rejects_malformed_geometry(value): - with pytest.raises(ValueError): - _parse_bounds(value) - - -def test_bounds_parser_has_exact_four_coordinate_shape(): - assert _parse_bounds("1,2,3,4") == (1, 2, 3, 4) - - -def test_cloud_rejects_unknown_device_type_before_create(): - from mobilerun.core.devices.cloud import CloudDevice - - with pytest.raises(ValueError, match="Invalid cloud device type"): - CloudDevice(api_key="test", device_type="not-a-device-type") - - -class CapabilityDevice(Device): - @property - def platform(self): - return "Android" - - @property - def supported_operations(self): - return {"tap"} - - @property - def supported_buttons(self): - return {"home"} - - def __init__(self): - super().__init__() - self.connected = 0 - self.closed = 0 - self.typed = [] - self.taps = [] - self.recover = AsyncMock() - - @property - def identifier(self): - return "fake" - - @property - def _state_recovery(self): - return self.recover - - async def _ensure_connected(self): - self.connected += 1 - - async def close(self): - self.closed += 1 - - async def _input_text_raw(self, text, clear=False, stealth=False, wpm=0): - self.typed.append(text) - return True - - async def tap(self, x, y): - self.taps.append((x, y)) - - async def swipe(self, x1, y1, x2, y2, duration_ms=1000): - pass - - def _create_state_provider(self, options=None): - return android_state_provider(self, options or StateProviderOptions()) - - -@pytest.mark.parametrize( - "wrappers", [(RecordingDevice, StealthDevice), (StealthDevice, RecordingDevice)] -) -def test_nested_lifecycle_await_is_outer_and_cleanup_is_once(wrappers): - root = CapabilityDevice() - wrapped = wrappers[0](wrappers[1](root)) - - async def run(): - assert await wrapped is wrapped - assert await wrapped is wrapped - async with wrapped as entered: - assert entered is wrapped - - asyncio.run(run()) - assert root.connected == 3 - assert root.closed == 1 - assert wrapped._unwrap() is root - assert wrapped.identifier == "fake" - assert wrapped._state_recovery is root.recover - - -@pytest.mark.parametrize( - "wrappers", [(RecordingDevice, StealthDevice), (StealthDevice, RecordingDevice)] -) -def test_stealth_veto_preserves_raw_secret_typing_in_both_orders(wrappers): - - root = CapabilityDevice() - wrapped = wrappers[0](wrappers[1](root)) - wrapped.state.refresh = AsyncMock( - return_value=SimpleNamespace( - phone_state={ - "focusedElement": {"className": "EditText"}, - "isEditable": True, - } - ) - ) - - async def run(): - vault = await DictCredentials( - {"app": {"work": {"password": "literal{{secret}}"}}} - ).bind(wrapped) - await vault.type_field("app", "password", name="work") - await wrapped.swipe(1, 2, 3, 4) - - asyncio.run(run()) - assert root.typed == ["literal{{secret}}"] - assert len(wrapped.extensions) == 1 - assert wrapped.recording_device() is not None - assert wrapped.recording_device().run_dir is None - - -def test_raw_adapter_requires_pairing_and_does_not_infer_close(monkeypatch): - raw = DeviceDriver() - raw.input_text = AsyncMock(return_value=True) - raw.connect = AsyncMock() - close = AsyncMock() - monkeypatch.setattr(raw, "close", close, raising=False) - with pytest.raises(TypeError, match="state_provider_factory"): - DriverDevice(raw, **{}) - device = DriverDevice(raw, state_provider_factory=android_state_provider) - asyncio.run(device.connect()) - asyncio.run(device.close()) - close.assert_not_awaited() - assert device._unwrap() is device - assert device._driver is raw - assert device._state_recovery is None - assert asyncio.run(device._input_coordinate_size(100, 200)) == (100, 200) - - -def test_provider_flags_defaults_and_resize_or_contract(): - provider = StateProvider(CapabilityDevice()) - assert not provider.use_normalized - assert not provider.requires_active_contract_for_coords - assert not _should_resize_model_screenshot(provider) - provider.requires_coordinate_tools = True - assert _should_resize_model_screenshot(provider) - - -def test_android_connection_failure_cleans_up_started_avd(monkeypatch): - - device = AndroidDevice(avd="fake") - - async def boot(): - device._pending_avd = False - device._started_emulator = True - - device._boot = boot - device._ensure_connected = AsyncMock(side_effect=RuntimeError("connection failed")) - device.terminate = AsyncMock() - with pytest.raises(RuntimeError, match="connection failed"): - asyncio.run(device.connect()) - device.terminate.assert_awaited_once() - - -@pytest.mark.parametrize("wrapper", [RecordingDevice, StealthDevice]) -def test_android_recovery_through_wrapper_restores_declared_keyboard( - monkeypatch, wrapper -): - - device = AndroidDevice("fake") - adb = SimpleNamespace( - shell=AsyncMock(), - shell2=AsyncMock(return_value=SimpleNamespace(returncode=0, output="null")), - ) - monkeypatch.setattr(device, "_adb_device", adb) - device._portal = SimpleNamespace(tcp_available=False) - device._portal_keyboard_available = True - setup = AsyncMock() - monkeypatch.setattr( - "mobilerun_core_local.driver.android.portal.setup_keyboard", setup - ) - monkeypatch.setattr("mobilerun.core.devices.android.asyncio.sleep", AsyncMock()) - recovery = wrapper(device)._state_recovery - assert recovery is not None - asyncio.run(recovery()) - setup.assert_awaited_once_with(device._adb_device) - assert adb.shell.await_count == 2 - - -def test_provider_and_factory_attachment_are_separate_and_lazy(): - root = CapabilityDevice() - - def factory(device): - return StateProvider(device) - - root._set_state_provider_factory(factory) - assert root._ui_state_view._provider is None - provider = root.state._resolved_provider - assert provider._device is root - root._set_state_provider(None) - assert root.state._resolved_provider is not provider - assert root._create_state_provider( - StateProviderOptions(normalized=True) - ).use_normalized - with pytest.raises(TypeError, match="state_provider_factory"): - root._set_state_provider(cast(StateProvider, factory)) - - -def test_view_exposes_snapshot_not_unknown_provider_members(): - root = MemoryDevice() - provider = StateProvider(root) - state = UIState([], "snapshot", "", {}, 100, 200) - provider.get_state = AsyncMock(return_value=state) - root._set_state_provider(provider) - asyncio.run(root.state.refresh()) - assert root.state.current.formatted_text == "snapshot" - assert root.state.current.screen_width == 100 - with pytest.raises(AttributeError): - attrgetter("unknown_provider_member")(root.state) - - -def test_every_declared_raw_method_is_explicitly_delegated(): - root = CapabilityDevice() - wrapped = DeviceWrapper(root) - - async def run(): - calls = [ - ("connect", ()), - ("_ensure_connected", ()), - ("screenshot", (False,)), - ("tap", (1, 2)), - ("swipe", (1, 2, 3, 4, 1000)), - ("drag", (1, 2, 3, 4, 3)), - ("press_button", ("home",)), - ("press_key_code", (4,)), - ("start_app", ("app", None)), - ("stop_app", ("app",)), - ("uninstall_app", ("app",)), - ("list_apps", (True,)), - ("_get_ui_tree", ()), - ("_get_date", ()), - ("wait", (1,)), - ("_input_coordinate_size", (10, 20)), - ] - for name, args in calls: - mock = AsyncMock(return_value=None) - # Test instrumentation, not production capability detection. - setattr(root, name, mock) - await getattr(wrapped, name)(*args) - mock.assert_awaited_once_with(*args) - - asyncio.run(run()) - - -def test_local_credentials_fail_closed_even_empty(): - assert DictCredentials({}).cloud_native is False - - -@pytest.mark.parametrize( - "kind,expected", - [("legacy", "IOSStateProvider"), ("portal-http", "AndroidStateProvider")], -) -def test_ios_factory_detects_once_and_pairs_point_coordinates( - monkeypatch, kind, expected -): - - detect = AsyncMock(return_value=kind) - monkeypatch.setattr("mobilerun.core.devices.ios.detect_ios_portal_kind", detect) - monkeypatch.setattr(IOSDevice, "_ensure_connected", AsyncMock()) - device = IOSDevice("http://localhost:8080", token="fake") - asyncio.run(device.connect()) - asyncio.run(device.connect()) - assert isinstance(device, IOSDevice) - assert type(device._create_state_provider()).__name__ == expected - assert device._state_recovery is None - assert device.identifier == "http://localhost:8080" - detect.assert_awaited_once() - device._driver.input_coordinate_size = AsyncMock(return_value=(390, 844)) - assert asyncio.run(device._input_coordinate_size(1170, 2532)) == (390, 844) - asyncio.run(device.close()) - - -def test_cloud_empty_vault_has_empty_reference_tuple(monkeypatch): - from mobilerun.core.credentials import CloudCredentials - - provider = CloudCredentials(api_key="test") - provider._list_credentials = AsyncMock(return_value=[]) - assert asyncio.run(provider.cloud_task_inputs()).credential_references == () - - -@pytest.mark.parametrize("mixed", [False, True]) -def test_cloud_operator_reference_capability_dedupes_and_rejects_local( - monkeypatch, mixed -): - from mobilerun.core.devices import CloudDevice - from mobilerun.core.operator.cloud import CloudTaskOperator - from mobilerun.errors import OperatorNotSupported - from mobilerun.models.results import ExecutionResult - - class Vault(DictCredentials): - cloud_native = True - - async def cloud_task_inputs(self): - return CloudTaskInputs( - ( - CloudCredentialReference("app", "work"), - CloudCredentialReference("app", "work"), - ) - ) - - phone = CloudDevice("id", api_key="fake") - run_task = AsyncMock( - return_value=ExecutionResult(success=True, device="CloudDevice") - ) - monkeypatch.setattr("mobilerun.core.operator.cloud.run_task", run_task) - - async def run(): - await Vault({}).bind(phone) - if mixed: - await DictCredentials({}, name="local").bind(phone) - with pytest.raises(OperatorNotSupported): - await CloudTaskOperator().execute(phone, "test") - run_task.assert_not_awaited() - else: - await CloudTaskOperator().execute(phone, "test") - assert run_task.await_args is not None - assert run_task.await_args.kwargs["credentials"] == [ - {"package_name": "app", "credential_names": ["work"]} - ] - - asyncio.run(run()) diff --git a/tests/unit/core/devices/test_device_example_workflows.py b/tests/unit/core/devices/test_device_example_workflows.py deleted file mode 100644 index 914847433..000000000 --- a/tests/unit/core/devices/test_device_example_workflows.py +++ /dev/null @@ -1,400 +0,0 @@ -"""Exercise public device examples with offline doubles.""" - -import asyncio -import importlib -from pathlib import Path -from types import SimpleNamespace - -import pytest - -from mobilerun.core.devices import Device - -NAMES = ( - "android_basics", - "cloud_device", - "ios_device", - "recording_wrapper", - "custom_device", - "visual_remote_device", -) - - -def test_examples_import(): - for name in NAMES: - assert callable(importlib.import_module(f"assets.examples.devices.{name}").run) - - -def test_quickstart_runs_with_fake_devices(tmp_path, monkeypatch, capsys): - - monkeypatch.chdir(tmp_path) - main = importlib.import_module("tests.demos.intro_demo") - devices = [] - - class Device(DemoDevice): - def __init__(self, *args, **kwargs): - super().__init__(with_state=True) - self.state.current.elements = [{"index": 9, "text": "Search settings"}] - devices.append(self) - - async def _input_secret(self, value): - self.calls.append(("credential", value)) - return True - - async def do(self, *args, **kwargs): - self.calls.append("do") - if "operator" in kwargs: - return await kwargs["operator"].execute(self, args[0]) - return SimpleNamespace(success=True, output=SimpleNamespace(version="15")) - - async def expect(self, *args, **kwargs): - self.calls.append("expect") - return SimpleNamespace(passed=True) - - class Pool: - def __init__(self, members): - self.devices = members - - async def __aenter__(self): - return self - - async def __aexit__(self, *args): - pass - - async def screenshot(self): - return [b"local", b"cloud"] - - async def press_button(self, button): - for device in self.devices: - await device.press_button(button) - - async def do(self, instruction): - return [await device.do(instruction) for device in self.devices] - - async def expect(self, condition): - return [await device.expect(condition) for device in self.devices] - - monkeypatch.setattr(main, "AgentOperator", object) - monkeypatch.setattr(main, "AndroidDevice", Device) - monkeypatch.setattr(main, "CloudDevice", Device) - monkeypatch.setattr(main, "DevicePool", Pool) - monkeypatch.setattr(main, "vault_demo", _no_sleep) - monkeypatch.setattr(main, "APK", str(tmp_path / "missing.apk")) - monkeypatch.setattr(main, "NEW_CLOUD_DEVICE", False) - monkeypatch.setattr(main, "ANDROID_AVD", None) - assert callable(main.local_basics) - assert callable(main.cloud_basics) - assert callable(main.macro_demo) - assert callable(main.agent_demo) - assert callable(main.pool_demo) - assert callable(main.sandbox_and_skills) - monkeypatch.setattr(main, "AGENT", False) - asyncio.run(main.main()) - assert Path("local-screenshot.png").read_bytes() == b"image" - assert Path("cloud-screenshot.png").read_bytes() == b"image" - assert all("connect" in device.calls for device in devices) - assert devices[0].calls.count("do") == 1 - assert "do" not in devices[1].calls - output = capsys.readouterr().out - assert "macro replay:" in output - assert "pool screenshots: 2" in output - assert "sandbox function (local): Hello, world!" in output - assert "skills:" in output - - if importlib.util.find_spec("mobilerun_agents") is not None: - monkeypatch.setattr(main, "AGENT", True) - asyncio.run(main.main()) - assert "15" in capsys.readouterr().out - assert "do" in devices[-2].calls - assert "expect" in devices[-1].calls - - -def test_macro_demo_replays_when_screen_changes(tmp_path, monkeypatch, capsys): - from tests.demos import intro_demo as main - - monkeypatch.chdir(tmp_path) - monkeypatch.setattr(asyncio, "sleep", _no_sleep) - - class ChangedScreen: - async def refresh(self): - return {"phone_state": {"package": "home"}, "elements": [{"text": "Home"}]} - - class Device(DemoDevice): - def __init__(self): - super().__init__() - self.state = ChangedScreen() - - async def _get_ui_tree(self): - return { - "phone_state": {"package": "previous"}, - "elements": [{"text": "Previous"}], - } - - async def do(self, instruction, *, operator): - return await operator.execute(self, instruction) - - device = Device() - asyncio.run(main.macro_demo(device)) - assert device.calls == [ - "start_app", - "swipe", - "back", - "home", - "start_app", - "swipe", - "back", - ] - assert "macro replay: True" in capsys.readouterr().out - - -async def _no_sleep(*_args): - return None - - -def test_agent_demo_handles_failed_typed_output(monkeypatch, capsys): - - from tests.demos import intro_demo as main - - class Cloud: - async def do(self, instruction, **kwargs): - return SimpleNamespace(success=not kwargs, output=None, answer="no result") - - async def expect(self, instruction): - return SimpleNamespace(passed=True) - - monkeypatch.setattr(main, "AGENT", True) - asyncio.run(main.agent_demo(Cloud())) - assert "typed output: failed (no result)" in capsys.readouterr().out - - -class DemoDevice(Device): - platform = "android" - capabilities = {"tap", "screenshot"} - supported_buttons = {"back", "home"} - - def __init__(self, with_state=False): - super().__init__() - self.calls = [] - self._operator = None - self.state = FakeUIState() if with_state else None - - @property - def state(self): - return self._fake_state - - @state.setter - def state(self, value): - self._fake_state = value - - async def _ensure_connected(self): - self.calls.append("connect") - - async def wait(self, seconds): - await asyncio.sleep(seconds) - - async def screenshot(self): - return b"image" - - async def start_app(self, *args): - self.calls.append("start_app") - - async def stop_app(self, *args): - self.calls.append("stop_app") - - async def tap(self, *args): - self.calls.append("tap") - - async def swipe(self, *args): - self.calls.append("swipe") - - async def input_text(self, *args, **kwargs): - self.calls.append("input_text") - return True - - async def press_button(self, button): - self.calls.append(button) - - async def _get_ui_tree(self): - return {"children": []} - - async def list_apps(self): - return ["Settings"] - - async def tap_element(self, index): - self.calls.append(f"element:{index}") - - -class FakeUIState: - elements = [{"index": 9, "text": "Network & internet"}] - - @property - def current(self): - return self - - async def refresh(self): - return object() - - -@pytest.mark.parametrize( - "name", ["android_basics", "custom_device", "recording_wrapper"] -) -def test_examples_run_with_fake_device(name, tmp_path, monkeypatch): - monkeypatch.chdir(tmp_path) - module = importlib.import_module(f"assets.examples.devices.{name}") - device = DemoDevice() - asyncio.run(module.run(device=device)) - assert "connect" in device.calls - if name == "recording_wrapper": - assert "tap" in device.calls - else: - assert Path("screenshot.png").read_bytes() == b"image" - - -def test_credentials_demo_attaches_and_types_credential(): - from tests.demos import intro_demo as main - - class Device(DemoDevice): - async def _input_secret(self, value): - self.calls.append(("credential", value)) - return True - - device = Device(with_state=True) - device.state.current.elements = [{"index": 9, "text": "Search settings"}] - asyncio.run(main.credentials_demo(device)) - assert "element:9" in device.calls - assert ("credential", "not-a-real-secret") in device.calls - - -def test_vault_demo_deletes_on_listing_failure(monkeypatch): - from tests.demos import intro_demo as main - - calls = [] - - class Vault: - async def save(self, package, name, fields): - calls.append(("save", package, name, fields)) - - async def list(self, package): - raise RuntimeError("list failed") - - async def delete(self, package, name): - calls.append(("delete", package, name)) - - monkeypatch.setattr(main, "CloudCredentials", Vault) - with pytest.raises(RuntimeError, match="list failed"): - asyncio.run(main.vault_demo()) - assert calls[1] == ("delete", calls[0][1], calls[0][2]) - - -def test_vault_demo_lists_names_and_deletes(monkeypatch, capsys): - - from tests.demos import intro_demo as main - - calls = [] - - class Vault: - async def save(self, package, name, fields): - calls.append(("save", package, name)) - - async def list(self, package): - return [{"package": package, "name": "demo-name", "fields": ["password"]}] - - async def delete(self, package, name): - calls.append(("delete", package, name)) - - monkeypatch.setattr(main, "CloudCredentials", Vault) - asyncio.run(main.vault_demo()) - assert calls[1] == ("delete", calls[0][1], calls[0][2]) - assert "demo-name" in capsys.readouterr().out - - -def test_app_install_demos_and_missing_apk(tmp_path, monkeypatch, capsys): - - from tests.demos import intro_demo as main - - calls = [] - apk = tmp_path / "counter.apk" - monkeypatch.setattr(main, "APK", str(apk)) - - class Device: - async def install_apk(self, path, **kwargs): - calls.append(("install", path, kwargs)) - - async def install_app(self, app, **kwargs): - calls.append(("install", app, kwargs)) - - async def uninstall_app(self, package): - calls.append(("uninstall", package)) - - app = SimpleNamespace(package="counter", version="1") - - async def upload(path, *, billing): - calls.append(("upload", path, billing)) - return app - - monkeypatch.setattr(main, "upload_app", upload) - asyncio.run(main.local_app_install_demo(Device())) - asyncio.run(main.cloud_app_install_demo(Device())) - assert not calls - assert "MOBILERUN_SMOKE_APK" in capsys.readouterr().out - apk.touch() - asyncio.run(main.local_app_install_demo(Device())) - asyncio.run(main.cloud_app_install_demo(Device())) - assert calls == [ - ("install", str(apk), {"reinstall": True}), - ("upload", str(apk), main.get_settings().MOBILERUN_BILLING), - ("install", app, {}), - ("uninstall", "counter"), - ] - - -def test_optional_device_demos(monkeypatch, tmp_path, capsys): - from tests.demos import intro_demo as main - - monkeypatch.chdir(tmp_path) - calls = [] - - class Cloud: - device_id = "fresh-id" - - def __init__(self, *, billing): - assert billing == "paid" - - async def __aenter__(self): - calls.append("enter") - return self - - async def __aexit__(self, *args): - calls.append("exit") - - async def screenshot(self): - return b"fresh" - - class Android: - def __init__(self, *, avd): - calls.append(("create", avd)) - - def __await__(self): - async def ready(): - return self - - return ready().__await__() - - async def screenshot(self): - return b"emulator" - - async def close(self): - calls.append("emulator-close") - - monkeypatch.setattr(main, "CloudDevice", Cloud) - monkeypatch.setattr(main, "AndroidDevice", Android) - monkeypatch.setattr(main, "NEW_CLOUD_DEVICE", False) - monkeypatch.setattr(main, "ANDROID_AVD", None) - asyncio.run(main.new_cloud_device_demo()) - asyncio.run(main.emulator_demo()) - assert not calls - assert "skip" in capsys.readouterr().out - monkeypatch.setattr(main, "NEW_CLOUD_DEVICE", True) - monkeypatch.setattr(main, "ANDROID_AVD", "test-avd") - asyncio.run(main.new_cloud_device_demo()) - asyncio.run(main.emulator_demo()) - assert calls == ["enter", "exit", ("create", "test-avd"), "emulator-close"] diff --git a/tests/unit/core/devices/test_lifecycle.py b/tests/unit/core/devices/test_lifecycle.py deleted file mode 100644 index 5c46d83cf..000000000 --- a/tests/unit/core/devices/test_lifecycle.py +++ /dev/null @@ -1,716 +0,0 @@ -"""Device connection, cleanup, pooled operations and timeout contracts.""" - -import asyncio -import json -import logging -from types import SimpleNamespace -from unittest.mock import AsyncMock - -import pytest - -from mobilerun.core.devices import ( - AndroidDevice, - DevicePool, - IOSDevice, - RecordingDevice, - RemoteDevice, - StealthDevice, -) -from mobilerun.core.devices.base import Device -from mobilerun.core.devices.cloud import CloudDevice -from mobilerun.core.devices.components.cloud_lifecycle import _CloudLifecycle -from mobilerun.core.mailbox.cloud import CloudMailbox -from mobilerun.core.operator import Operator -from mobilerun.models.apps import App -from mobilerun.models.results import ExecutionResult, ExpectationVerdict - -URL = "http://alice:secret-password@localhost:5555/path?token=hidden" - - -def test_cloud_install_verifies_system_apps(): - device = CloudDevice(device_id="device-id", api_key="test") - device._client = SimpleNamespace( - devices=SimpleNamespace( - apps=SimpleNamespace( - install=AsyncMock(), - list_installs=AsyncMock( - side_effect=[ - SimpleNamespace(installs=[]), - SimpleNamespace( - installs=[ - SimpleNamespace( - app_id="pkg", status="succeeded", started_at=1 - ) - ] - ), - ] - ), - ) - ) - ) - - async def inventory(include_system=False): - return [{"package_name": "pkg", "version_code": 4}] if include_system else [] - - device.list_apps = inventory - app = App("pkg", "1", "Example", id="app-id", version_code=4) - assert asyncio.run(device.install_app(app, timeout=0.05)) is app - - -@pytest.mark.parametrize("mode", ["direct", "wrapper", "pool", "implicit"]) -def test_remote_connection_is_serialized(mode): - async def run(): - device = RemoteDevice("http://localhost:5555") - calls = 0 - - async def connect(): - nonlocal calls - calls += 1 - await asyncio.sleep(0.01) - device._driver._connected = True - - device._driver.connect = connect - if mode == "direct": - await asyncio.gather(device.connect(), device.connect()) - elif mode == "wrapper": - wrapped = RecordingDevice(device) - await asyncio.gather(wrapped.connect(), wrapped.connect()) - elif mode == "pool": - await DevicePool([RecordingDevice(device), StealthDevice(device)]).connect() - else: - await asyncio.gather(device.connect(), device._ensure_connected()) - assert calls == 1 - - asyncio.run(run()) - - -@pytest.mark.parametrize("kind", ["remote", "legacy", "portal-http"]) -def test_backend_log_redacts_url(kind, monkeypatch, caplog): - from mobilerun.core.devices import ios - - caplog.set_level(logging.INFO) - - async def emit(*args, **kwargs): - logging.getLogger("mobilerun_core_local").info("Connected to %s", URL) - logging.getLogger("mobilerun_core_local").info("Connected to " + URL) - - async def run(): - if kind == "remote": - device = RemoteDevice(URL) - monkeypatch.setattr(device._driver, "connect", emit) - else: - device = IOSDevice(URL) - monkeypatch.setattr( - ios, "detect_ios_portal_kind", AsyncMock(return_value=kind) - ) - monkeypatch.setattr( - ios.IOSPortalDriver if kind == "legacy" else ios.IOSPortalHttpDriver, - "ensure_connected", - emit, - ) - await device.connect() - logging.getLogger("mobilerun.core.devices.test").info( - "Connected to %s", device.identifier - ) - - asyncio.run(run()) - assert caplog.records - for record in caplog.records: - assert "alice" not in record.getMessage() - assert "secret-password" not in record.getMessage() - assert "hidden" not in record.getMessage() - - -@pytest.mark.parametrize( - "mode", ["connect-button", "connect-screenshot", "first-ops", "wrappers", "pool"] -) -def test_public_operations_share_connection_lock(mode, monkeypatch): - async def run(): - device = RemoteDevice("http://localhost:5555") - calls = 0 - - async def connect(): - nonlocal calls - calls += 1 - await asyncio.sleep(0.01) - device._driver._connected = True - - async def button(_): - await device._driver.ensure_connected() - - async def screenshot(_=True): - await device._driver.ensure_connected() - return b"image" - - async def tap(*_): - await device._driver.ensure_connected() - - monkeypatch.setattr(device._driver, "connect", connect) - monkeypatch.setattr(device._driver, "press_button", button) - monkeypatch.setattr(device._driver, "screenshot", screenshot) - monkeypatch.setattr(device._driver, "tap", tap) - if mode == "connect-button": - work = asyncio.gather(device.connect(), device.press_button("home")) - elif mode == "connect-screenshot": - work = asyncio.gather(device.connect(), device.screenshot()) - elif mode == "first-ops": - work = asyncio.gather(device.tap(1, 2), device.screenshot()) - elif mode == "wrappers": - nested = RecordingDevice(StealthDevice(device)) - other = RecordingDevice(device) - work = asyncio.gather(nested.press_button("home"), other.screenshot()) - else: - pool = DevicePool([RecordingDevice(device), StealthDevice(device)]) - work = asyncio.gather(pool.press_button("home"), pool.screenshot()) - await asyncio.wait_for(work, timeout=1) - assert calls == 1 - - asyncio.run(run()) - - -@pytest.mark.parametrize( - "terminate_error", - [None, ValueError("terminate")], - ids=["cleanup-succeeds", "cleanup-fails"], -) -def test_android_cleanup_after_extension_failure(terminate_error): - device = AndroidDevice(serial="test") - device._close_extensions = AsyncMock(side_effect=RuntimeError("detach")) - device._started_emulator = True - device._keep = False - device.terminate = AsyncMock(side_effect=terminate_error) - with pytest.raises(RuntimeError, match="detach"): - asyncio.run(device.close()) - device.terminate.assert_awaited_once() - - -@pytest.mark.parametrize("kind", ["ios", "remote"]) -def test_client_cleanup_after_extension_failure(kind): - if kind == "ios": - device = IOSDevice("http://localhost") - else: - device = RemoteDevice("http://localhost") - client = SimpleNamespace(aclose=AsyncMock()) - device._driver = SimpleNamespace(_client=client) - device._close_extensions = AsyncMock(side_effect=RuntimeError("detach")) - with pytest.raises(RuntimeError, match="detach"): - asyncio.run(device.close()) - client.aclose.assert_awaited_once() - - -def test_cloud_cleanup_after_extension_failure(monkeypatch): - from mobilerun.core.devices.components import cloud_lifecycle - - device = object.__new__(_CloudLifecycle) - device._close_extensions = AsyncMock(side_effect=RuntimeError("detach")) - device._close_resources = AsyncMock() - device._connect_lock = asyncio.Lock() - device._owned = True - device._keep = False - device.device_id = "device" - device._billing = "included" - device._client = object() - device._owned_client = SimpleNamespace(close=AsyncMock()) - client = device._owned_client - terminate = AsyncMock() - monkeypatch.setattr(cloud_lifecycle.devices, "terminate", terminate) - with pytest.raises(RuntimeError, match="detach"): - asyncio.run(device.close()) - device._close_resources.assert_awaited_once() - terminate.assert_awaited_once() - client.close.assert_awaited_once() - - -def test_list_mailboxes_preserves_address(monkeypatch): - from mobilerun.core.mailbox import cloud - - monkeypatch.setattr( - cloud.mailboxes, - "list_mailboxes", - AsyncMock(return_value=[SimpleNamespace(id="id", address="a@example.com")]), - ) - result = asyncio.run(CloudMailbox.list(billing="included")) - assert result[0].address == "a@example.com" - - -def test_apk_missing_optional_version_name(monkeypatch, tmp_path): - from mobilerun.clients.local import apk - - monkeypatch.setattr(apk.shutil, "which", lambda _: "/aapt") - monkeypatch.setattr( - apk.subprocess, - "run", - lambda *a, **kw: SimpleNamespace( - stdout="package: name='example' versionCode='1'\n" - ), - ) - assert apk.inspect_apk(tmp_path / "app.apk") == ("example", 1, "", "example") - - -def test_apk_inspection_timeout(monkeypatch, tmp_path): - from mobilerun.clients.local import apk - - monkeypatch.setattr(apk.shutil, "which", lambda _: "/aapt") - - def timeout(*args, **kwargs): - assert kwargs["timeout"] > 0 - raise apk.subprocess.TimeoutExpired(args[0], kwargs["timeout"]) - - monkeypatch.setattr(apk.subprocess, "run", timeout) - with pytest.raises(RuntimeError, match="timed out"): - apk.inspect_apk(tmp_path / "app.apk") - - -def test_android_apk_inspection_runs_off_event_loop(monkeypatch, tmp_path): - import threading - - from mobilerun.core.devices import android - - loop_thread = threading.get_ident() - seen = [] - - def inspect(path): - seen.append(threading.get_ident()) - return ("example", 1, "", "Example") - - monkeypatch.setattr(android, "inspect_apk", inspect) - device = AndroidDevice(serial="test") - device.install_app = AsyncMock() - asyncio.run(device.install_apk(tmp_path / "a.apk")) - assert seen and seen[0] != loop_thread - - -def test_cloud_upload_does_not_reuse_unverified_binary(monkeypatch, tmp_path): - from mobilerun.clients.cloud import apps - - apk = tmp_path / "app.apk" - apk.write_bytes(b"new binary") - monkeypatch.setattr(apps, "inspect_apk", lambda _: ("example", 1, "1", "Example")) - item = SimpleNamespace(id="old", bundle_id="example", display_name="Example") - sdk = SimpleNamespace( - apps=SimpleNamespace( - list=AsyncMock( - return_value=SimpleNamespace( - items=[item], pagination=SimpleNamespace(has_next=False) - ) - ), - list_versions=AsyncMock( - return_value=SimpleNamespace( - data=[ - SimpleNamespace( - status="available", version_code=1, version_name="1" - ) - ] - ) - ), - create_signed_upload_url=AsyncMock( - return_value=SimpleNamespace( - app_id="new", - version_id="v", - r2_upload_urls=[ - SimpleNamespace( - file_name="app.apk", r2_upload_url="https://example.test" - ) - ], - ) - ), - confirm_upload=AsyncMock(), - mark_failed=AsyncMock(), - ) - ) - client = AsyncMock() - client.__aenter__.return_value = sdk - monkeypatch.setattr(apps, "cloud_client", lambda *a, **kw: client) - http = AsyncMock() - http.__aenter__.return_value = http - http.put.return_value = SimpleNamespace(raise_for_status=lambda: None) - monkeypatch.setattr(apps.httpx, "AsyncClient", lambda **kw: http) - result = asyncio.run(apps.upload_app(apk, billing="included")) - assert result.id == "new" - http.put.assert_awaited_once() - - -def test_cloud_upload_preparation_runs_off_event_loop(monkeypatch, tmp_path): - import threading - - from mobilerun.clients.cloud import apps - - path = tmp_path / "app.apk" - path.write_bytes(b"apk") - main_thread = threading.get_ident() - seen = [] - - def inspect(_): - seen.append(threading.get_ident()) - return ("example", 1, "", "Example") - - monkeypatch.setattr(apps, "inspect_apk", inspect) - client = AsyncMock() - client.__aenter__.side_effect = RuntimeError("stop after preparation") - monkeypatch.setattr(apps, "cloud_client", lambda *a, **kw: client) - with pytest.raises(RuntimeError, match="stop after preparation"): - asyncio.run(apps.upload_app(path, billing="included")) - assert seen and seen[0] != main_thread - - -class FakeDevice(Device): - platform = "fake" - supported_operations = {"tap"} - needs_initialization = False - - def __init__(self, value, gate=None, error=None): - super().__init__() - self.value = value - self._operator = None - self.gate = gate - self.error = error - self.finished = False - self.calls = [] - - @property - def state(self): - return self - - async def screenshot(self, hide_overlay=True): - if self.gate: - await self.gate(self.value) - self.finished = True - if self.error: - raise self.error - return self.value - - async def _ensure_connected(self): - self.calls.append("connected") - - async def connect(self): - await self._ensure_connected() - - async def close(self): - pass - - async def refresh(self): - return self.value - - async def do(self, instruction, **kwargs): - return instruction, kwargs - - async def expect(self, condition, **kwargs): - return condition, kwargs - - -def test_empty_and_invalid_concurrency(): - with pytest.raises(ValueError): - DevicePool([]) - with pytest.raises(ValueError): - DevicePool([FakeDevice(1)], concurrency=0) - - -def test_concurrent_order_and_properties(): - async def run(): - ready = asyncio.Event() - seen = [] - - async def gate(value): - seen.append(value) - if len(seen) == 2: - ready.set() - await ready.wait() - - devices = [FakeDevice(1, gate), FakeDevice(2, gate)] - pool = DevicePool(devices) - assert await asyncio.wait_for(pool.screenshot(), 1) == [1, 2] - assert len(pool) == 2 and tuple(pool) == pool.devices == tuple(devices) - assert pool.platform == ["fake", "fake"] - assert pool.supported_operations == [{"tap"}, {"tap"}] - assert await pool.state.refresh() == [1, 2] - - asyncio.run(run()) - - -def test_errors_wait_and_annotate(): - async def run(): - failure = ValueError("bad") - devices = [FakeDevice(1, error=failure), FakeDevice(2)] - with pytest.raises(ExceptionGroup) as caught: - await DevicePool(devices).screenshot() - assert all(device.finished for device in devices) - assert caught.value.exceptions == (failure,) - assert "device 0: FakeDevice" in failure.__notes__ - assert "1 of 2 devices failed: screenshot" in str(caught.value) - - asyncio.run(run()) - - -def test_operator_forwarding_and_context(): - async def run(): - devices = [FakeDevice(1), FakeDevice(2)] - operator = object() - async with DevicePool(devices) as pool: - assert ( - await pool.do("go", output=int, max_steps=2, operator=operator) - == [("go", {"output": int, "max_steps": 2, "operator": operator})] * 2 - ) - assert ( - await pool.expect("yes", operator=operator) - == [("yes", {"operator": operator})] * 2 - ) - assert all(device.calls == ["connected"] for device in devices) - - asyncio.run(run()) - - -def test_concurrency_limit(): - async def run(): - active = peak = 0 - - async def gate(value): - nonlocal active, peak - active += 1 - peak = max(peak, active) - await asyncio.sleep(0.01) - active -= 1 - - pool = DevicePool([FakeDevice(i, gate) for i in range(5)], concurrency=2) - assert await pool.screenshot() == list(range(5)) - assert peak == 2 - - asyncio.run(run()) - - -def test_context_closes_supported_devices(): - class Closable(FakeDevice): - async def close(self): - self.calls.append("closed") - - async def run(): - devices = [Closable(1), FakeDevice(2)] - async with DevicePool(devices): - pass - assert devices[0].calls == ["connected", "closed"] - assert devices[1].calls == ["connected"] - - asyncio.run(run()) - - -class FakeOperator(Operator): - def __init__(self): - self.calls = [] - - async def execute(self, device, instruction, *, output=None, max_steps=None): - self.calls.append((device, instruction, output, max_steps)) - verdict = ExpectationVerdict(passed=True, reason="visible") if output else None - return ExecutionResult(success=True, output=verdict, device="fake") - - -def test_device_expect_with_per_call_operator(): - device = AndroidDevice(serial="test", portal_mode="disabled") - operator = FakeOperator() - assert device._operator is None - assert asyncio.run(device.expect("visible", operator=operator)).passed - assert operator.calls[0][0] is device - assert device._operator is None - - -@pytest.mark.parametrize("wrapper", [RecordingDevice, StealthDevice]) -def test_wrapper_forwards_per_call_operator(wrapper): - device = AndroidDevice(serial="test", portal_mode="disabled") - wrapped = wrapper(device) - operator = FakeOperator() - assert asyncio.run(wrapped.do("go", operator=operator)).success - assert asyncio.run(wrapped.expect("visible", operator=operator)).passed - assert [call[0] for call in operator.calls] == [wrapped, wrapped] - assert device._operator is None - - -def test_pool_real_android_devices_forward_per_call_operator(monkeypatch): - async def _ensure_connected(self): - pass - - monkeypatch.setattr(AndroidDevice, "_ensure_connected", _ensure_connected) - devices = [AndroidDevice(serial=str(i), portal_mode="disabled") for i in range(2)] - operator = FakeOperator() - - async def run(): - async with DevicePool(devices) as pool: - assert all( - result.success for result in await pool.do("go", operator=operator) - ) - assert all( - result.passed - for result in await pool.expect("visible", operator=operator) - ) - - asyncio.run(run()) - assert [call[0] for call in operator.calls] == devices + devices - assert all(device._operator is None for device in devices) - - -def test_cleanup_failure_does_not_replace_body_exception(): - original = RuntimeError("body failed") - - class BrokenClose(FakeDevice): - async def close(self): - raise RuntimeError("cleanup failed") - - async def run(): - async with DevicePool([BrokenClose(1)]): - raise original - - with pytest.raises(RuntimeError) as caught: - asyncio.run(run()) - assert caught.value is original - assert any("cleanup" in note.lower() for note in original.__notes__) - - -@pytest.mark.parametrize("wrapper", [RecordingDevice, StealthDevice]) -@pytest.mark.parametrize("pending", ["_ready", "_pending_avd"]) -def test_pool_initializes_wrapped_pending_devices(wrapper, pending): - class Pending(FakeDevice): - needs_initialization = True - - def __init__(self): - super().__init__(1) - setattr(self, pending, pending == "_pending_avd") - - async def connect(self): - self.calls.append("initialized") - - async def close(self): - self.calls.append("closed") - - async def run(): - device = Pending() - wrapped = wrapper(device) - async with DevicePool([wrapped]): - assert device.calls == ["initialized"] - assert device.calls == ["initialized", "closed"] - - asyncio.run(run()) - - -def test_device_do_forwards_timeout(): - class FakeOperator(Operator): - async def execute(self, device, instruction, **kwargs): - return kwargs - - device = Device(operator=FakeOperator()) - assert asyncio.run(device.do("go", timeout=3))["timeout"] == 3 - - -def test_pool_forwards_timeout(): - class TimeoutDevice: - _operator = None - - async def do(self, instruction, **kwargs): - return kwargs - - async def expect(self, condition, **kwargs): - return kwargs - - pool = DevicePool([TimeoutDevice()]) - assert asyncio.run(pool.do("go", timeout=3))[0]["timeout"] == 3 - assert asyncio.run(pool.expect("ok", timeout=4))[0]["timeout"] == 4 - - -def test_macro_timeout_cancels_replay(monkeypatch): - from mobilerun.macro import operator as macro_module - - cancelled = [] - - class Player: - def __init__(self, device, **kwargs): - pass - - async def replay_macro(self, *args, **kwargs): - try: - await asyncio.Event().wait() - finally: - cancelled.append(True) - - monkeypatch.setattr(macro_module, "MacroPlayer", Player) - monkeypatch.setattr(macro_module, "load_macro", lambda path: []) - with pytest.raises(TimeoutError): - asyncio.run(macro_module.MacroOperator().execute(object(), "go", timeout=0.01)) - assert cancelled == [True] - - -@pytest.mark.parametrize("cancel", [False, True]) -def test_cloud_device_do_stops_task_on_timeout_or_cancel(cancel): - from contextlib import asynccontextmanager - - from mobilerun.core.operator.cloud import CloudTaskOperator - from mobilerun.errors import CloudTaskTimeout - - async def run(): - started = asyncio.Event() - - class Tasks: - run = AsyncMock(return_value=SimpleNamespace(id="task-1")) - stop = AsyncMock() - - @property - def with_streaming_response(self): - return self - - @asynccontextmanager - async def attach(self, task_id, **kwargs): - yield self - - async def iter_lines(self): - started.set() - await asyncio.Event().wait() - yield "" - - tasks = Tasks() - - class FakeCloudDevice(Device): - @property - def _is_cloud(self): - return True - - device = FakeCloudDevice(operator=CloudTaskOperator(billing="included")) - device._task_started_callback = None - device.device_id = "device-1" - device._cloud_client = SimpleNamespace(tasks=tasks) - device._ensure_connected = AsyncMock() - pending = asyncio.create_task(device.do("go", timeout=10 if cancel else 0.02)) - await asyncio.wait_for(started.wait(), 1) - if cancel: - pending.cancel() - with pytest.raises(asyncio.CancelledError if cancel else CloudTaskTimeout): - await pending - tasks.stop.assert_awaited_once_with("task-1") - - asyncio.run(run()) - - -def test_wait_sleeps_once_and_records_duration(monkeypatch, tmp_path): - sleep = AsyncMock() - monkeypatch.setattr(asyncio, "sleep", sleep) - device = Device() - recording = RecordingDevice(device, runs_dir=tmp_path, capture="actions") - asyncio.run(recording.wait(2.5)) - sleep.assert_awaited_once_with(2.5) - row = json.loads((recording.run_dir / "steps.jsonl").read_text()) - assert (row["action"], row["args"]) == ("wait", {"duration": 2.5}) - - -def test_pool_waits_once_per_device_in_parallel(monkeypatch): - entered = [] - - async def sleep(seconds): - entered.append(seconds) - if len(entered) == 2: - ready.set() - await ready.wait() - - monkeypatch.setattr(asyncio, "sleep", sleep) - - async def run(): - nonlocal ready - ready = asyncio.Event() - return await DevicePool([Device(), Device()]).wait(3) - - ready = None - assert asyncio.run(run()) == [None, None] - assert entered == [3, 3] diff --git a/tests/unit/core/devices/test_operator_integration.py b/tests/unit/core/devices/test_operator_integration.py deleted file mode 100644 index f167669aa..000000000 --- a/tests/unit/core/devices/test_operator_integration.py +++ /dev/null @@ -1,313 +0,0 @@ -"""Regressions from the device-contract review, with no live resources.""" - -import asyncio -import json -from datetime import datetime, timezone -from pathlib import Path -from types import SimpleNamespace -from unittest.mock import AsyncMock - -import pytest - -from mobilerun.core.devices import ( - AndroidDevice, - CloudDevice, - Device, - IOSDevice, - RecordingDevice, - RemoteDevice, - StealthDevice, -) -from mobilerun.core.operator import Operator -from mobilerun.core.proxy import ( - CloudFixedProxy, - CloudRotatingProxy, - CloudSocks5Proxy, - LocalProxy, -) -from mobilerun.core.proxy.target import ProxyTarget -from mobilerun.errors import DeviceOperationNotSupported -from mobilerun.logs.actions import agent_line -from mobilerun.models import Billing, WorkspaceFile -from mobilerun.models.results import ExecutionResult, ExpectationVerdict - -URL = "https://alice:secret-password@localhost:6643/path?token=hidden#hidden" -SAFE_URL = "https://localhost:6643/path" - - -@pytest.mark.parametrize("factory", [IOSDevice, AndroidDevice, RemoteDevice]) -def test_url_identifiers_and_action_logs_do_not_leak_credentials(factory): - device = factory(URL) - assert device.identifier == SAFE_URL - line = agent_line( - SimpleNamespace( - driver=device, ui=None, shared_state=SimpleNamespace(step_number=1) - ), - "tap", - {"x": 1, "y": 2}, - ) - assert SAFE_URL in line - assert all( - secret not in line for secret in ("alice", "secret-password", "token", "hidden") - ) - - -@pytest.mark.parametrize("kind", ["portal-http", "legacy"]) -def test_both_ios_factory_paths_sanitize_identifiers(monkeypatch, kind): - from mobilerun.core.devices import ios - - monkeypatch.setattr(ios, "detect_ios_portal_kind", AsyncMock(return_value=kind)) - monkeypatch.setattr(IOSDevice, "_ensure_connected", AsyncMock()) - - async def run(): - device = await IOSDevice(URL) - try: - assert device.identifier == SAFE_URL - finally: - await device.close() - - asyncio.run(run()) - - -class InputDevice(Device): - def __init__(self, **kwargs): - self.calls = [] - super().__init__(**kwargs) - - async def tap(self, x, y): - self.calls.append(("tap", x, y)) - - async def _input_text_raw(self, text, *args): - self.calls.append(("text", text)) - return True - - async def swipe(self, *args): - self.calls.append(("swipe",)) - - async def _swipe_humanized(self, *args): - self.calls.append(("humanized",)) - - -class InputOperator(Operator): - def __init__(self): - self.devices = [] - - def check(self, device): - pass - - async def execute(self, device, instruction, *, output=None, **kwargs): - self.devices.append(device) - await device.tap(1, 2) - await device.input_text("hello world") - await device.swipe(1, 2, 3, 4) - return ExecutionResult( - success=True, - device=type(device).__name__, - output=ExpectationVerdict(passed=True, reason="ok") if output else None, - ) - - -@pytest.mark.parametrize("method", ["do", "expect"]) -@pytest.mark.parametrize("mode", ["recording", "stealth", "nested"]) -@pytest.mark.parametrize("selection", ["attached", "default", "explicit"]) -def test_wrapper_operators_keep_outer_identity( - monkeypatch, method, mode, selection, tmp_path -): - operator = InputOperator() - inner = InputDevice() - monkeypatch.setattr(inner, "wait", AsyncMock(return_value=None)) - if selection == "attached": - inner._operator = operator - elif selection == "default": - monkeypatch.setattr(inner, "_default_operator", lambda: operator) - recording = RecordingDevice(inner, runs_dir=tmp_path, capture="actions") - device = ( - recording - if mode == "recording" - else StealthDevice(recording if mode == "nested" else inner) - ) - asyncio.run( - getattr(device, method)( - "test", **({"operator": operator} if selection == "explicit" else {}) - ) - ) - assert operator.devices == [device] - if mode != "recording": - assert ("humanized",) in inner.calls - assert [call[1] for call in inner.calls if call[0] == "text"] == [ - "hello", - " ", - "world", - ] - if mode == "recording": - lines = (recording.run_dir / "steps.jsonl").read_text().splitlines() - first, *_, last = map(json.loads, lines) - assert (first["action"], first["args"]) == ("tap", {"x": 1, "y": 2}) - assert last["action"] == "swipe" - else: - assert recording.run_dir is None - - -@pytest.mark.parametrize("wrapped", [False, True]) -def test_workspace_push_uses_explicit_source_not_destination(monkeypatch, wrapped): - from mobilerun import Workspace - from mobilerun.clients.cloud import client, files - - phone = CloudDevice( - "phone", - api_key="device-key", - base_url="https://device.test/v1", - billing=Billing.PAID, - ) - file = WorkspaceFile( - "file", "image.png", "image/png", 3, datetime.now(timezone.utc) - ) - source = AsyncMock() - source.__aenter__.return_value = source - clients = [] - - def connect(api_key, base_url, *, billing): - clients.append((api_key, base_url, billing)) - return source - - monkeypatch.setattr(client, "cloud_client", connect) - download = AsyncMock(return_value=b"abc") - monkeypatch.setattr(files, "download_file", download) - - async def push(path, dest): - assert Path(path).read_bytes() == b"abc" - assert Path(path).name == "image.png" - return dest - - monkeypatch.setattr(phone, "push_file", push) - device = RecordingDevice(phone) if wrapped else phone - assert ( - asyncio.run( - Workspace.push_file( - file, - device, - "/sdcard/image.png", - api_key="source-key", - base_url="https://source.test/v1", - billing=Billing.PAID, - ) - ) - == "/sdcard/image.png" - ) - download.assert_awaited_once_with(source, "file", billing=Billing.PAID) - assert clients == [("source-key", "https://source.test/v1", Billing.PAID)] - source.__aexit__.assert_awaited_once() - - -def test_url_sanitizer_preserves_non_url_ids_and_ipv6(): - from mobilerun.core.devices.components.identifiers import _sanitize_identifier - - assert _sanitize_identifier("emulator-5554") == "emulator-5554" - assert _sanitize_identifier(None) is None - assert ( - _sanitize_identifier("https://user:pass@[::1]:6643/path?token=x#secret") - == "https://[::1]:6643/path" - ) - assert _sanitize_identifier("http://user:pass@[bad") == "invalid-url" - - -def test_visual_remote_retains_meaningful_device_ids(): - device = RemoteDevice(URL) - device._driver.device_id = "remote-phone" - assert device.identifier == "remote-phone" - device._driver.device_id = URL - assert device.identifier == SAFE_URL - - -@pytest.mark.parametrize( - "proxy", - [ - CloudRotatingProxy("US"), - CloudFixedProxy("id"), - CloudSocks5Proxy("host", 1080), - LocalProxy("host", 8080), - ], -) -def test_neutral_proxy_target_error(proxy): - with pytest.raises( - DeviceOperationNotSupported, - match=f"{type(proxy).__name__} isn't supported on this device", - ): - asyncio.run(proxy._apply(ProxyTarget())) - - -def test_managed_proxies_use_distinct_hooks(): - class Target(ProxyTarget): - connect_rotating = AsyncMock() - connect_fixed = AsyncMock() - - target = Target() - asyncio.run(CloudRotatingProxy("DE", False)._apply(target)) - target.connect_rotating.assert_awaited_once_with(country="DE", smart_ip=False) - asyncio.run(CloudFixedProxy("p")._apply(target)) - target.connect_fixed.assert_awaited_once_with(id="p") - - -def test_base_phone_binding_is_an_unsupported_operation(): - assert not hasattr(Device(), "_bind_phone_number") - - -@pytest.mark.parametrize( - "method,args", - [ - ("push_file", ("file",)), - ("list_files", ("/",)), - ("pull_file", ("remote", "local")), - ("delete_file", ("file",)), - ("set_location", (1, 2)), - ("reset_location", ()), - ("set_timezone", ("UTC",)), - ("open_url", ("https://example.com",)), - ("install_apk", ("file",)), - ("install_app", (None,)), - ("_ensure_connected", ()), - ("screenshot", ()), - ("tap", (1, 2)), - ("swipe", (1, 2, 3, 4)), - ("start_app", ("p",)), - ("stop_app", ("p",)), - ("uninstall_app", ("p",)), - ("list_apps", ()), - ("press_button", ("home",)), - ("press_key_code", (1,)), - ("drag", (1, 2, 3, 4)), - ("_get_ui_tree", ()), - ("_get_date", ()), - ], -) -def test_base_unsupported_message_format(method, args): - with pytest.raises(DeviceOperationNotSupported) as error: - asyncio.run(getattr(Device(), method)(*args)) - assert str(error.value) == f"Device doesn't support {method}" - - -@pytest.mark.parametrize("cls", [Device, AndroidDevice, CloudDevice, RecordingDevice]) -@pytest.mark.parametrize("method", ["install_app", "install_apk"]) -def test_install_options_are_typed(cls, method): - from typing import Unpack, get_origin, get_type_hints - - annotation = get_type_hints(getattr(cls, method))["kwargs"] - assert get_origin(annotation) is Unpack - from mobilerun.core.devices.base import InstallOptions - - assert get_type_hints(InstallOptions) == { - "timeout": float, - "reinstall": bool, - "grant_permissions": bool, - } - - -@pytest.mark.parametrize("property_name", ["number", "mailbox"]) -def test_base_resource_unsupported_message_format(property_name): - with pytest.raises(DeviceOperationNotSupported) as error: - getattr(Device(), property_name) - expected = { - "number": "No sms extension is bound", - "mailbox": "No email extension is bound", - } - assert str(error.value) == expected[property_name] diff --git a/tests/unit/core/devices/test_recording.py b/tests/unit/core/devices/test_recording.py deleted file mode 100644 index b3670aa87..000000000 --- a/tests/unit/core/devices/test_recording.py +++ /dev/null @@ -1,827 +0,0 @@ -import asyncio -import json -import logging - -import pytest - -from mobilerun.core.credentials import DictCredentials -from mobilerun.core.devices import AndroidDevice, Device, RecordingDevice, StealthDevice -from mobilerun.core.devices.components.wrapper import DeviceWrapper -from mobilerun.core.extensions import Extension, action, device_action -from mobilerun.core.runs import recording_policy, recording_scope -from mobilerun.core.state.base import StateProvider -from mobilerun.core.state.ui_state import UIState -from mobilerun.utils.redaction import secret_scope -from tests.support.devices import MemoryDevice - - -class Phone(MemoryDevice): - def __init__(self): - super().__init__() - self.calls = [] - self.waits = [] - self.dumps = 0 - self.screenshots = 0 - - async def tap(self, x, y): - self.calls.append((x, y)) - if x < 0: - raise ValueError("backend detail must not persist") - - async def _input_text_raw(self, text, clear=False, stealth=False, wpm=0): - self.calls.append(text) - return False - - async def wait(self, seconds): - self.waits.append(seconds) - - async def screenshot(self, hide_overlay=True): - self.screenshots += 1 - return b"fake png" - - -class Provider(StateProvider): - async def get_state(self): - self._device.dumps += 1 - return UIState( - [{"resourceId": "button", "text": "free-form screen text"}], - "formatted text", - "focused text", - {"packageName": "app", "activityName": f"View{len(self._device.calls)}"}, - 10, - 10, - ) - - -def rows(recording): - return [ - json.loads(line) - for line in (recording.run_dir / "steps.jsonl").read_text().splitlines() - ] - - -@pytest.mark.parametrize("stealth_outer", [False, True]) -def test_stealth_context_suppresses_actions_in_both_wrapper_orders( - tmp_path, stealth_outer -): - class Probe(Extension): - @action() - async def inspect(self) -> None: - """Read context through an older extension implementation.""" - - async def context(self): - await self.inspect() - return () - - async def run(): - phone = Phone() - recorder = RecordingDevice( - phone if stealth_outer else StealthDevice(phone), - runs_dir=tmp_path, - capture="actions", - ) - facade = StealthDevice(recorder) if stealth_outer else recorder - await Probe().bind(recorder) - await DictCredentials({"login": "secret"}).bind(recorder) - assert await facade.extensions["extension"].context() == () - assert (await facade.context())[0].kind == "credentials" - assert recorder.run_dir is None - - asyncio.run(run()) - - -def test_stealth_undecorated_helper_cannot_record_its_nested_action(tmp_path): - class Probe(Extension): - @action() - async def ready(self) -> bool: - """Return readiness.""" - return True - - async def helper(self): - return await self.ready() - - async def run(): - recorder = RecordingDevice(Phone(), runs_dir=tmp_path, capture="actions") - await Probe(name="probe").bind(recorder) - assert await StealthDevice(recorder).probe.helper() - assert recorder.run_dir is None - assert await recorder.probe.helper() - assert rows(recorder)[0]["args"]["name"] == "probe.ready" - - asyncio.run(run()) - - -def test_registered_secret_is_masked_at_dispatch_and_omitted_from_macro( - tmp_path, caplog, monkeypatch -): - from mobilerun.macro import build_macro, load_macro - - class AcceptingPhone(Phone): - async def _input_text_raw(self, text, clear=False, stealth=False, wpm=0): - logging.getLogger(__name__).warning("typed %s", text) - self.calls.append(text) - return True - - async def run(): - phone = AcceptingPhone() - recording = RecordingDevice( - phone, runs_dir=tmp_path / "runs", capture="actions" - ) - phone.register_sensitive_values(iter(["s3cret"])) - - async def tool(): - await DeviceWrapper(recording).input_text("s3cret") - - await tool() - await recording.input_text("hello") - await recording.input_text("s3cretary") - assert phone.calls == ["s3cret", "hello", "s3cretary"] - assert [row["args"]["text"] for row in rows(recording)] == [ - "***", - "hello", - "s3cretary", - ] - assert caplog.messages == ["typed ***", "typed hello", "typed s3cretary"] - path = build_macro(recording.run_dir / "steps.jsonl", "secret-free") - assert [step.args["text"] for step in load_macro(path)] == [ - "hello", - "s3cretary", - ] - - monkeypatch.setenv("MOBILERUN_MACRO_DIRECTORY", str(tmp_path / "macros")) - asyncio.run(run()) - - -def test_stealth_lazy_helpers_keep_veto_during_iteration_and_close(tmp_path): - class Probe(Extension): - @action() - async def ready(self) -> bool: - """Return readiness.""" - return True - - async def lazy(self): - try: - yield await self.ready() - finally: - await self.ready() - - def lazy_sync(self): - try: - yield self.device.start_run() - finally: - self.device.start_run() - - async def run(): - recorder = RecordingDevice(Phone(), runs_dir=tmp_path, capture="actions") - await Probe(name="probe").bind(recorder) - facade = StealthDevice(recorder) - lazy = facade.probe.lazy() - assert await anext(lazy) - assert recording_policy()[0] # The caller is outside the generator scope. - assert recorder.run_dir is None - await lazy.aclose() - assert recorder.run_dir is None - sync = facade.probe.lazy_sync() - assert next(sync) is None - sync.close() - assert recorder.run_dir is None - - asyncio.run(run()) - - -def test_known_otp_keeps_live_elements_and_regenerates_sanitized_text(): - from mobilerun.core.state.snapshot import DeviceSnapshot - - class Mail(Extension): - @action() - async def wait_for_code(self) -> str: - """Read a fake verification code.""" - return "482913" - - class Screen(Provider): - async def get_state(self): - state = await super().get_state() - state.elements = [ - { - "index": 1, - "resourceId": "otp", - "text": "482-913", - "bounds": "0,0,10,10", - }, - { - "index": 2, - "resourceId": "submit", - "className": "Button", - "text": "Submit", - "bounds": "0,0,10,10", - }, - ] - state.formatted_text = state.focused_text = "482-913" - return state - - async def run(): - phone = Phone() - recorder = RecordingDevice( - phone, state_provider=Screen(phone), capture="actions" - ) - await Mail(name="mail").bind(phone) - await phone.mail.wait_for_code() - snapshot = await DeviceSnapshot.observe(recorder) - assert snapshot.ui.get_element(2)["text"] == "Submit" - assert snapshot.ui.get_element_coords(2) == (5, 5) - assert snapshot.ui.get_element(1)["text"] == "***" - assert '2. Button: "submit", "Submit"' in snapshot.ui.formatted_text - assert "482-913" not in snapshot.ui.formatted_text - - asyncio.run(run()) - - -def test_raw_android_prefilled_password_is_safe_on_disk_and_targetable_live(tmp_path): - from mobilerun.core.state.snapshot import DeviceSnapshot - - class Android(AndroidDevice): - async def _get_ui_tree(self): - return { - "a11y_tree": { - "isPassword": True, - "isFocused": False, - "resourceId": "login_password", - "className": "android.widget.EditText", - "text": "raw-password-canary", - "boundsInScreen": { - "left": 10, - "top": 10, - "right": 70, - "bottom": 30, - }, - "children": [], - }, - "phone_state": { - "packageName": "example.app", - "focusedElement": None, - "isEditable": False, - }, - "device_context": {"screen_bounds": {"width": 100, "height": 100}}, - } - - async def tap(self, x, y): - pass - - async def wait(self, seconds): - pass - - async def screenshot(self, hide_overlay=True): - return b"unchanged PNG" - - async def run(): - device = Android("fake") - recorder = RecordingDevice(device, runs_dir=tmp_path) - await recorder.tap(10, 10) - for files in rows(recorder)[0]["screens"].values(): - assert ( - "raw-password-canary" - not in (recorder.run_dir / files["json"]).read_text() - ) - assert (recorder.run_dir / files["png"]).read_bytes() == b"unchanged PNG" - live = await DeviceSnapshot.observe(device) - assert live.ui.get_element(1)["text"] == "***" - assert live.ui.get_element_coords(1) == (40, 20) - assert '1. EditText: "login_password", "***"' in live.ui.formatted_text - assert "raw-password-canary" not in live.ui.formatted_text - - asyncio.run(run()) - - -def test_full_observation_keeps_vault_context_without_dispatching_actions(tmp_path): - class Probe(Extension): - @action() - async def ready(self) -> bool: - """Return a non-sensitive result.""" - return True - - async def run(): - phone = Phone() - recorder = RecordingDevice( - phone, state_provider=Provider(phone), runs_dir=tmp_path - ) - await DictCredentials({"login": "private-vault-value"}).bind(recorder) - await Probe().bind(recorder) - await recorder.tap(1, 2) - assert await recorder.extension.ready() - assert [row["action"] for row in rows(recorder)] == ["tap", "extension_call"] - after = rows(recorder)[-1]["screens"]["after"]["json"] - data = (recorder.run_dir / after).read_text() - assert json.loads(data)["device_context"][0]["kind"] == "credentials" - assert "private-vault-value" not in data - - asyncio.run(run()) - - -def test_tainted_fingerprints_are_omitted_after_secret_scope_and_on_cache_hits( - tmp_path, monkeypatch -): - from mobilerun.macro import build_macro - - monkeypatch.setenv("MOBILERUN_MACRO_DIRECTORY", str(tmp_path / "macros")) - secret = "dynamic-secret-canary" - - class DynamicProvider(Provider): - async def get_state(self): - state = await super().get_state() - if secret in self._device.calls: - state.elements[0]["resourceId"] = secret - return state - - async def run(): - phone = Phone() - recorder = RecordingDevice( - phone, state_provider=DynamicProvider(phone), runs_dir=tmp_path / "runs" - ) - with secret_scope(secret): - await recorder.input_text(secret) - assert await recorder.capture_fingerprint() is None - await recorder.tap(1, 2) - assert rows(recorder)[-1]["before"] is rows(recorder)[-1]["after"] is None - path = recorder.run_dir / "steps.jsonl" - assert secret not in path.read_text() - assert secret not in build_macro(path, "no-leak").read_text() - - asyncio.run(run()) - - -@pytest.mark.parametrize( - "secure", - [ - {"isPassword": True}, - {"password": "true"}, - {"secure": True}, - {"inputType": "textPassword"}, - {"inputType": 129}, - {"className": "XCUIElementTypeSecureTextField"}, - ], -) -def test_prefilled_secure_values_are_omitted_from_json_not_png(tmp_path, secure): - class PasswordProvider(Provider): - async def get_state(self): - state = await super().get_state() - state.elements.append( - { - "children": [ - { - **secure, - "value": "prefilled-canary", - "text": "prefilled-canary", - } - ] - } - ) - state.phone_state["focusedElement"] = {"text": "prefilled-canary"} - state.formatted_text = state.focused_text = "prefilled-canary" - return state - - async def run(): - phone = Phone() - recorder = RecordingDevice( - phone, state_provider=PasswordProvider(phone), runs_dir=tmp_path - ) - await recorder.tap(1, 2) - for files in rows(recorder)[0]["screens"].values(): - data = (recorder.run_dir / files["json"]).read_text() - assert "prefilled-canary" not in data - assert "free-form screen text" in data - assert (recorder.run_dir / files["png"]).read_bytes() == b"fake png" - - asyncio.run(run()) - - -def test_finish_detaches_observer_without_closing_device(tmp_path): - class Probe(Extension): - @action() - async def ready(self) -> bool: - """Return readiness.""" - return True - - async def run(): - phone = Phone() - recorder = RecordingDevice(phone, runs_dir=tmp_path, capture="actions") - probe = await Probe().bind(phone) - assert await recorder.extension.ready() - recorder.finish("succeeded") - recorder.finish("succeeded") - assert not phone._extension_state.observers - assert await probe.ready() - await recorder.tap(2, 3) - assert phone.calls == [(2, 3)] - assert [row["action"] for row in rows(recorder)] == ["extension_call"] - await recorder.close() - assert not phone._extension_state.observers - - asyncio.run(run()) - - -def test_finish_while_action_is_in_flight_does_not_write_or_break_action(tmp_path): - async def run(): - entered, resume = asyncio.Event(), asyncio.Event() - - class BlockingPhone(Phone): - async def tap(self, x, y): - entered.set() - await resume.wait() - await super().tap(x, y) - - phone = BlockingPhone() - recorder = RecordingDevice(phone, runs_dir=tmp_path, capture="actions") - pending = asyncio.create_task(recorder.tap(1, 2)) - await entered.wait() - recorder.finish("succeeded") - resume.set() - await pending - assert phone.calls == [(1, 2)] - assert rows(recorder) == [] - - asyncio.run(run()) - - -def test_verification_code_is_not_written_to_run_or_macro(tmp_path, monkeypatch): - from mobilerun.macro import build_macro, load_macro - - monkeypatch.setenv("MOBILERUN_MACRO_DIRECTORY", str(tmp_path / "macros")) - - class Mail(Extension): - role = "mailbox" - - @action() - async def wait_for_code(self) -> str: - """Read a fake verification code.""" - return "731284" - - @action() - async def echo(self, value: dict[str, list[str | int]]) -> bool: - """Accept a nested input.""" - return True - - class AcceptingPhone(Phone): - async def _input_text_raw(self, text, clear=False, stealth=False, wpm=0): - self.calls.append(text) - return True - - async def run(): - phone = AcceptingPhone() - recorder = RecordingDevice( - phone, state_provider=Provider(phone), runs_dir=tmp_path - ) - await Mail(name="email").bind(phone) - code = await recorder.mailbox.wait_for_code() - assert await recorder.input_text(code) - assert await recorder.mailbox.echo({"values": [code, int(code)]}) - await recorder.tap(1, 2) - path = recorder.run_dir / "steps.jsonl" - assert phone.calls[0] == code - assert code not in path.read_text() - assert [ - row["args"]["text"] - for row in rows(recorder) - if row["action"] == "input_text" - ] == ["***"] - assert phone.screenshots > 0 - assert all( - code not in p.read_text() for p in path.parent.glob("screens/*.json") - ) - macro = build_macro(path, "verification") - assert code not in macro.read_text() - assert [step.action for step in load_macro(macro)] == ["extension_call", "tap"] - - asyncio.run(run()) - - -def test_message_code_formats_are_masked_in_logs_and_action_rows(tmp_path, caplog): - class Number(Extension): - role = "phone_number" - - @action() - async def messages(self) -> list[dict[str, str]]: - """Return an inbound SMS.""" - return [{"body": "Verification code: 482913"}] - - async def run(): - phone = Phone() - recording = RecordingDevice(phone, runs_dir=tmp_path, capture="actions") - await Number(name="sms").bind(phone) - redact = StealthDevice(recording).known_codes_redactor() - assert redact("use 482 913") == "use 482 913" - assert await asyncio.create_task(phone.sms.messages()) == [ - {"body": "Verification code: 482913"} - ] - logging.getLogger(__name__).warning( - "code: %s", "482-913", extra={"pin": "482 913"} - ) - await recording.input_text("482-913") - assert phone.calls == ["482-913"] - assert rows(recording)[0]["args"]["text"] == "***" - assert "code: ***" in caplog.text - assert caplog.records[-1].pin == "***" - assert redact("use 482 913") == "use ***" - assert Phone().known_codes_redactor()("482913") == "482913" - - asyncio.run(run()) - - -@pytest.mark.parametrize("catalog", [False, True]) -def test_stealth_extension_veto_reaches_the_bound_action_body(tmp_path, catalog): - class Probe(Extension): - @device_action - async def try_start(self, device: Device) -> bool: - """Try to start a run on the original bound facade.""" - return device.recording_device().start_run() is not None - - async def run(): - recorder = RecordingDevice(Phone(), runs_dir=tmp_path, capture="actions") - await Probe(name="probe").bind(recorder) - probe = StealthDevice(recorder).extensions["probe"] - result = ( - await probe.actions.call("probe.try_start", {}) - if catalog - else await probe.try_start() - ) - assert result is False - assert not list(tmp_path.glob("*/run.json")) - assert await recorder.probe.try_start() - - asyncio.run(run()) - - -def test_step_collection_inherits_into_new_tasks_but_excludes_existing_tasks(tmp_path): - async def run(): - recorder = RecordingDevice(Phone(), runs_dir=tmp_path, capture="actions") - proceed = asyncio.Event() - - async def sibling(): - await proceed.wait() - await recorder.tap(7, 8) - - pending = asyncio.create_task(sibling()) - with recorder.collect_steps() as collected: - await recorder.tap(1, 2) - await asyncio.create_task(recorder.tap(3, 4)) - proceed.set() - await pending - with recorder.collect_steps() as nested: - await asyncio.create_task(recorder.tap(5, 6)) - assert collected == [1, 2, 4] - assert nested == [4] - assert recorder.step_index == 4 - - asyncio.run(run()) - - -def test_close_cancels_active_manifest(tmp_path): - async def run(): - recorder = RecordingDevice(Phone(), runs_dir=tmp_path, capture="actions") - await recorder.tap(1, 2) - await recorder.close() - assert ( - json.loads((recorder.run_dir / "run.json").read_text())["status"] - == "cancelled" - ) - - asyncio.run(run()) - - -def test_failed_finish_detaches_and_context_preserves_body_exception( - tmp_path, monkeypatch -): - from mobilerun.core.runs import RunWriter - - def fail(*args, **kwargs): - raise OSError("manifest failure") - - monkeypatch.setattr(RunWriter, "finish", fail) - - async def run(): - recorder = RecordingDevice(Phone(), runs_dir=tmp_path, capture="actions") - with pytest.raises(KeyError, match="body failed"): - async with recorder: - await recorder.tap(1, 2) - raise KeyError("body failed") - assert not recorder._extension_state.observers - other = RecordingDevice(Phone(), runs_dir=tmp_path, capture="actions") - other.start_run() - with pytest.raises(OSError, match="manifest failure"): - other.finish("succeeded") - assert not other._extension_state.observers - await other.tap(2, 3) - assert rows(other) == [] - - asyncio.run(run()) - - -def test_records_outcomes_and_reuses_current_and_after_samples(tmp_path): - phone = Phone() - recorder = RecordingDevice(phone, state_provider=Provider(phone), runs_dir=tmp_path) - - async def run(): - await recorder.state.refresh() - assert recorder.run_dir is None - with recording_scope(by="agent"): - await recorder.tap(1, 2) - with pytest.raises(ValueError, match="backend detail"): - await recorder.tap(-1, 2) - assert await recorder.input_text("plain", clear=True, wpm=12) is False - recorder.finish("failed", failed_step=2) - - asyncio.run(run()) - first, second, third = rows(recorder) - assert [(r["i"], r["ok"], r["error"], r["by"]) for r in (first, second, third)] == [ - (1, True, None, "agent"), - (2, False, "ValueError", "script"), - (3, False, "returned_false", "script"), - ] - assert first["before"] == { - "app": "app", - "activity": "View0", - "elements": ["id:button"], - } - assert first["after"] == second["before"] - assert second["after"] == third["before"] - assert third["args"] == { - "text": "plain", - "clear": True, - "stealth": False, - "wpm": 12, - } - assert phone.dumps == 4 - assert phone.waits == [0.25] * 3 - assert recorder.step_index == 3 - manifest = json.loads((recorder.run_dir / "run.json").read_text()) - assert (manifest["status"], manifest["failed_step"]) == ("failed", 2) - - -@pytest.mark.parametrize("stealth_outer", [True, False]) -def test_stealth_vetoes_both_wrapper_orders(tmp_path, stealth_outer): - phone = Phone() - runs_dir = tmp_path / "runs" - if stealth_outer: - recorder = RecordingDevice(phone, runs_dir=runs_dir) - facade = StealthDevice(recorder) - else: - facade = recorder = RecordingDevice(StealthDevice(phone), runs_dir=runs_dir) - assert facade.recording_device() is recorder - assert not facade.recording_allowed() - if not stealth_outer: - assert recorder.start_run() is None - asyncio.run(facade.tap(1, 2)) - assert phone.calls == [(1, 2)] - assert not runs_dir.exists() - - -def test_lookup_reuses_recorder_and_scope_veto_cannot_be_lifted(tmp_path): - phone = Phone() - assert phone.recording_device() is None - recorder = RecordingDevice(phone, runs_dir=tmp_path, capture="actions") - facade = DeviceWrapper(RecordingDevice(recorder, runs_dir=tmp_path / "unused")) - assert facade.recording_device() is recorder - assert facade.recording_allowed() - - async def run(): - with recording_scope(enabled=False), recording_scope(enabled=True, by="agent"): - assert recorder.start_run() is None - await facade.tap(1, 2) - assert recorder.step_index == 0 - await facade.tap(3, 4) - - asyncio.run(run()) - assert phone.calls == [(1, 2), (3, 4)] - assert [r["args"] for r in rows(recorder)] == [{"x": 3, "y": 4}] - - -def test_forced_fingerprint_refresh_and_suppressed_dispatch_invalidate_cache(tmp_path): - phone = Phone() - recorder = RecordingDevice(phone, state_provider=Provider(phone), runs_dir=tmp_path) - - async def run(): - assert (await recorder.capture_fingerprint()).activity == "View0" - await phone.tap(1, 2) - assert (await recorder.capture_fingerprint()).activity == "View0" - assert (await recorder.capture_fingerprint(fresh=True)).activity == "View1" - with recording_scope(enabled=False): - await recorder.tap(3, 4) - assert recorder.run_dir is None - assert (await recorder.capture_fingerprint()).activity == "View2" - - asyncio.run(run()) - assert phone.dumps == 3 - - -def test_actions_capture_skips_observation_and_replays(tmp_path, monkeypatch): - from mobilerun.macro import MacroPlayer, build_macro, load_macro - - monkeypatch.setenv("MOBILERUN_MACRO_DIRECTORY", str(tmp_path / "macros")) - phone = Phone() - recorder = RecordingDevice( - phone, state_provider=Provider(phone), runs_dir=tmp_path, capture="actions" - ) - - async def run(): - await recorder.tap(1, 2) - with secret_scope("sensitive-canary"): - assert not await recorder.input_text("sensitive-canary") - await recorder.tap(3, 4) - assert phone.dumps == phone.screenshots == 0 - assert not phone.waits - macro = load_macro( - build_macro(recorder.run_dir / "steps.jsonl", "actions-only") - ) - replay = Phone() - await MacroPlayer(replay, delay_between_actions=0).replay_macro(macro) - assert replay.calls == [(1, 2), (3, 4)] - assert await recorder.capture_fingerprint(fresh=True) is None - - asyncio.run(run()) - public, sensitive, _ = rows(recorder) - assert public["before"] is public["after"] is None - assert phone.screenshots == 0 - assert sensitive["args"]["text"] == "***" - assert sensitive["screens"] is None - assert not (recorder.run_dir / "screens").exists() - assert "sensitive-canary" not in (recorder.run_dir / "steps.jsonl").read_text() - - -def test_snapshots_and_action_timing_reuse_previous_after(tmp_path): - from datetime import datetime - - phone = Phone() - recorder = RecordingDevice(phone, state_provider=Provider(phone), runs_dir=tmp_path) - - async def run(): - await recorder.tap(1, 2) - await recorder.tap(3, 4) - with secret_scope("sensitive-canary"): - await recorder.input_text("sensitive-canary") - - asyncio.run(run()) - first, second, sensitive = rows(recorder) - assert first["screens"]["before"]["json"] == "screens/1.before.json" - assert first["screens"]["after"]["json"] == "screens/1.after.json" - assert second["screens"]["before"] == first["screens"]["after"] - for phase in ("before", "after"): - assert ( - recorder.run_dir / sensitive["screens"][phase]["png"] - ).read_bytes() == b"fake png" - assert ( - json.loads( - (recorder.run_dir / sensitive["screens"]["after"]["json"]).read_text() - )["ui"]["focused_text"] - == "***" - ) - snapshot = json.loads( - (recorder.run_dir / first["screens"]["before"]["json"]).read_text() - ) - assert snapshot["ui"]["formatted_text"] == "formatted text" - assert snapshot["device_context"] == [] - assert phone.dumps == 4 - assert "png" in first["screens"]["before"] - assert datetime.fromisoformat(first["started_at"]) <= datetime.fromisoformat( - first["finished_at"] - ) - - -def test_writer_failure_does_not_redispatch(tmp_path): - phone = Phone() - recorder = RecordingDevice(phone, runs_dir=tmp_path, capture="actions") - - async def run(): - run_dir = recorder.start_run() - (run_dir / "steps.jsonl").unlink() - with pytest.raises(OSError): - await recorder.tap(1, 2) - with pytest.raises(RuntimeError, match="closed for recording"): - await recorder.tap(3, 4) - - asyncio.run(run()) - assert phone.calls == [(1, 2)] - assert recorder.step_index == 0 - - -def test_direct_secret_dispatch_records_only_a_masked_literal(tmp_path): - class EditableProvider(Provider): - async def get_state(self): - state = await super().get_state() - state.phone_state.update( - focusedElement={"className": "EditText"}, isEditable=True - ) - return state - - phone = Phone() - recorder = RecordingDevice( - phone, - state_provider=EditableProvider(phone), - runs_dir=tmp_path, - capture="actions", - ) - assert asyncio.run(recorder._input_secret("sensitive-canary")) is False - (row,) = rows(recorder) - assert (row["action"], row["args"]["text"], row["ok"]) == ( - "input_text", - "***", - False, - ) diff --git a/tests/unit/core/devices/test_state.py b/tests/unit/core/devices/test_state.py deleted file mode 100644 index 83c4e31b9..000000000 --- a/tests/unit/core/devices/test_state.py +++ /dev/null @@ -1,701 +0,0 @@ -"""Device state providers, observation coordinates and tap safety.""" - -import asyncio -from copy import deepcopy -from io import BytesIO -from types import SimpleNamespace -from unittest.mock import AsyncMock - -import pytest -from PIL import Image - -import mobilerun.core.state.android as android_device -import mobilerun.core.state.ios as ios_device -import mobilerun.core.state.screenshot as visual_remote_device -from mobilerun.clients.portal.state_fetch import fetch_state_with_retry -from mobilerun.config.settings import get_settings -from mobilerun.core.devices import ( - AndroidDevice, - CloudDevice, - IOSDevice, - RecordingDevice, - RemoteDevice, - StealthDevice, -) -from mobilerun.core.state.android import AndroidStateProvider -from mobilerun.core.state.base import ( - StateProvider, - _resize_model_screenshot_with_grid, - _should_resize_model_screenshot, -) -from mobilerun.core.state.filters import DetailedFilter, get_filter -from mobilerun.core.state.formatters import IndexedFormatter -from mobilerun.core.state.ios import IOSStateProvider -from mobilerun.core.state.options import StateProviderOptions -from mobilerun.core.state.screenshot import ( - ScreenshotOnlyStateProvider, -) -from mobilerun.core.state.stealth import StealthUIState -from mobilerun.errors import StateFetchFailed, UnsupportedStateCapability -from mobilerun.utils.geometry import find_uncovered_point -from mobilerun.utils.images import ( - image_dimensions, - resize_image_to_max_side_with_grid, -) - - -def test_platform_defaults_are_lazy_and_use_expected_provider(monkeypatch): - made = [] - - def android(driver, **kwargs): - made.append(("android", kwargs)) - return AndroidStateProvider.__new__(AndroidStateProvider) - - def ios(driver, **kwargs): - made.append(("ios", kwargs)) - return IOSStateProvider.__new__(IOSStateProvider) - - def screenshot(driver, **kwargs): - made.append(("screenshot", kwargs)) - return ScreenshotOnlyStateProvider.__new__(ScreenshotOnlyStateProvider) - - monkeypatch.setattr(android_device, "AndroidStateProvider", android) - monkeypatch.setattr(ios_device, "IOSStateProvider", ios) - monkeypatch.setattr(visual_remote_device, "ScreenshotOnlyStateProvider", screenshot) - devices = [ - AndroidDevice("a"), - CloudDevice("c", api_key="fake"), - IOSDevice("http://i"), - RemoteDevice(url="http://v", device_id="v"), - ] - assert made == [] - from mobilerun_core_local.driver.ios import IOSPortalDriver - - devices[2]._driver = IOSPortalDriver("http://i") - [device.state._resolved_provider for device in devices] - assert [kind for kind, _ in made] == [ - "android", - "android", - "ios", - "screenshot", - ] - assert made[0][1]["tree_filter"].__class__ is DetailedFilter - assert made[0][1]["tree_formatter"].__class__ is IndexedFormatter - - -def test_provider_override_and_reset_to_default(monkeypatch): - device = AndroidDevice("a") - override = object() - device._set_state_provider(override) - assert device.state._resolved_provider is override - device._set_state_provider(None) - assert isinstance(device.state._resolved_provider, AndroidStateProvider) - - -def test_use_default_provider_passes_options(monkeypatch): - args = [] - monkeypatch.setattr( - android_device, - "AndroidStateProvider", - lambda d, **kw: args.append(kw) or object(), - ) - device = AndroidDevice("a") - device._reset_state_provider(StateProviderOptions(vision=False, normalized=True)) - _ = device.state._resolved_provider - assert args[0]["vision_enabled"] is False - assert args[0]["use_normalized"] is True - - -def test_wrappers_build_default_provider_against_outer_device(): - for wrapper_type in (RecordingDevice, StealthDevice): - inner = AndroidDevice("a") - provider = inner.state._resolved_provider - wrapped = wrapper_type(inner) - assert wrapped.state._resolved_provider is not provider - assert wrapped.state._resolved_provider._device is wrapped - - -class Snapshot: - elements = ["first", "second"] - formatted_text = "indexed UI" - - def get_element_coords(self, index): - return (index * 10, index * 20) - - def convert_point(self, x, y): - return x + 1, y + 1 - - -class FakeProvider: - capabilities = {"element_index"} - - def __init__(self, device): - self.device = device - self.reads = 0 - - async def get_state(self): - self.reads += 1 - return Snapshot() - - async def get_final_state(self): - return Snapshot() - - -class FullCapabilityProvider(FakeProvider): - capabilities = {"element_index", "convert_point"} - - -DEVICE_CASES = [ - (AndroidDevice, ("serial-1",), {"use_tcp": True}), - ( - CloudDevice, - ("device-1",), - { - "display_id": 2, - "api_key": "fake", - "base_url": get_settings().MOBILERUN_CLOUD_BASE_URL, - }, - ), - (RemoteDevice, (), {"url": "http://visual-device", "device_id": "v1"}), -] - - -def patch_driver_init(monkeypatch, device_class): - - driver_class = device_class._backend - calls = [] - - def fake_init(self, *args, **kwargs): - calls.append((args, kwargs.copy())) - self._driver_args = args - self._driver_kwargs = kwargs.copy() - self.tapped = None - self._client = None - self._write_client = None - self._serial = None - - async def fake_tap(self, x, y): - self.tapped = (x, y) - - async def fake_ensure_connected(self): - pass - - monkeypatch.setattr(driver_class, "__init__", fake_init) - monkeypatch.setattr(driver_class, "tap", fake_tap, raising=False) - monkeypatch.setattr(driver_class, "ensure_connected", fake_ensure_connected) - return calls - - -@pytest.mark.parametrize("device_class,args,kwargs", DEVICE_CASES) -@pytest.mark.parametrize("provider_kind", ["class", "factory", "instance"]) -def test_each_device_accepts_provider_without_changing_driver_args( - monkeypatch, device_class, args, kwargs, provider_kind -): - calls = patch_driver_init(monkeypatch, device_class) - expected_args = (args, kwargs) - if provider_kind == "class": - provider = FakeProvider - elif provider_kind == "factory": - - def provider(device): - return FakeProvider(device) - - else: - provider = FakeProvider(None) - - device = device_class(*args, **kwargs) - if provider_kind == "instance": - device._set_state_provider(provider) - else: - device._set_state_provider_factory(provider) - - assert calls == [expected_args] - assert device._driver._driver_args == args - assert device._driver._driver_kwargs == kwargs - assert isinstance(device.state._resolved_provider, FakeProvider) - if provider_kind == "instance": - assert device.state._resolved_provider is provider - else: - assert device.state._resolved_provider.device is device - - -def test_refresh_caches_returned_snapshot_and_passthrough(): - async def check(): - device = AndroidDevice("serial") - device._set_state_provider_factory(FakeProvider) - snapshot = await device.state.refresh() - assert device.state.current is snapshot - assert device.state.current.formatted_text == "indexed UI" - assert device.state.current.elements == ["first", "second"] - assert device.state.current.get_element_coords(2) == (20, 40) - assert device.state._resolved_provider.reads == 1 - - asyncio.run(check()) - - -def test_unsupported_capability_names_provider_and_capability(): - device = AndroidDevice("serial") - device._set_state_provider_factory(FakeProvider) - with pytest.raises(UnsupportedStateCapability, match="FakeProvider.*convert_point"): - device.state._require("convert_point") - - -def test_device_without_default_has_clear_error(): - device = AndroidDevice("serial") - - def unavailable(): - from mobilerun.errors import DeviceNotReady - - raise DeviceNotReady("no state provider attached and no default") - - device._ui_state_view._default_provider = unavailable - with pytest.raises(RuntimeError, match="no state provider attached and no default"): - _ = device.state._resolved_provider - - -def test_attach_replaces_provider_and_clears_cached_state(): - async def check(): - device = AndroidDevice("serial") - device._set_state_provider_factory(FakeProvider) - old_state = await device.state.refresh() - replacement = FullCapabilityProvider(device) - device._set_state_provider(replacement) - assert device.state._resolved_provider is replacement - with pytest.raises(RuntimeError, match="not been refreshed"): - _ = device.state.current - assert await device.state.refresh() is not old_state - - asyncio.run(check()) - - -def test_tap_element_uses_indexed_coordinates(monkeypatch): - async def check(): - patch_driver_init(monkeypatch, AndroidDevice) - device = AndroidDevice("serial") - device._set_state_provider_factory(FakeProvider) - await device.state.refresh() - await device.tap_element(3) - assert device._driver.tapped == (30, 60) - - asyncio.run(check()) - - -def test_explicit_view_methods_reject_unsupported_capabilities(): - async def check(): - device = AndroidDevice("serial") - device._set_state_provider_factory(FakeProvider) - await device.state.refresh() - names = dir(device.state) - assert "formatted_text" not in names - assert "elements" not in names - assert "get_element_coords" not in names - assert device.state.current.formatted_text == "indexed UI" - with pytest.raises(UnsupportedStateCapability): - device.state._require("convert_point") - - asyncio.run(check()) - - -def test_state_retry_settings_are_read_from_environment(monkeypatch): - monkeypatch.setenv("MOBILERUN_STATE_RETRY_DELAYS", "[0,0]") - monkeypatch.setenv("MOBILERUN_STATE_MAX_RETRIES", "2") - calls = 0 - - async def fetch(): - nonlocal calls - calls += 1 - if calls == 1: - raise RuntimeError("temporary") - return {"a11y_tree": {}, "phone_state": {}, "device_context": {}} - - result = asyncio.run(fetch_state_with_retry(fetch)) - - assert calls == 2 - assert result["a11y_tree"] == {} - - -def test_retry_exhaustion_raises_state_fetch_failed(monkeypatch): - monkeypatch.setenv("MOBILERUN_STATE_MAX_RETRIES", "1") - monkeypatch.setenv("MOBILERUN_STATE_RETRY_DELAYS", "[0]") - - async def fetch(): - raise RuntimeError("offline") - - try: - asyncio.run(fetch_state_with_retry(fetch)) - except StateFetchFailed as exc: - assert str(exc) == "Failed to get state after 1 attempts: offline" - else: - raise AssertionError("Expected StateFetchFailed") - - -NATIVE_W, NATIVE_H = 1080, 2400 - - -def test_screenshot_fallback_uses_configured_max_side(monkeypatch): - monkeypatch.setenv("MOBILERUN_MODEL_SCREENSHOT_MAX_SIDE", "500") - image = BytesIO() - Image.new("RGB", (1000, 2000)).save(image, format="PNG") - geometry = SimpleNamespace( - model_screenshot_width=None, - model_screenshot_height=None, - model_screenshot_grid=False, - ) - assert image_dimensions( - _resize_model_screenshot_with_grid(geometry, image.getvalue()) - ) == ( - 250, - 500, - ) - - -def _combined_data(width=NATIVE_W, height=NATIVE_H): - return { - "a11y_tree": { - "boundsInScreen": {"left": 0, "top": 0, "right": width, "bottom": height}, - "className": "android.widget.FrameLayout", - "text": "root", - "children": [ - { - "boundsInScreen": { - "left": 221, - "top": 409, - "right": 600, - "bottom": 460, - }, - "className": "android.widget.TextView", - "text": "Services & preferences", - "children": [], - } - ], - }, - "device_context": {"screen_bounds": {"width": width, "height": height}}, - "phone_state": { - "currentApp": "Settings", - "packageName": "com.android.settings", - }, - } - - -def _provider(width=NATIVE_W, height=NATIVE_H, **kwargs): - driver = SimpleNamespace( - _state_recovery=None, - _get_ui_tree=AsyncMock(return_value=_combined_data(width, height)), - ) - return AndroidStateProvider( - driver, - tree_filter=SimpleNamespace(filter=lambda tree, ctx: tree), - tree_formatter=IndexedFormatter(), - **kwargs, - ) - - -def _get_state(provider): - return asyncio.run(provider.get_state()) - - -def test_resize_flags_pair_providers_with_agent_gating(): - # The providers declare the flag… - assert StateProvider.resize_model_screenshot is False - assert ScreenshotOnlyStateProvider.resize_model_screenshot is True - assert _provider(vision_enabled=True).resize_model_screenshot is True - assert _provider().resize_model_screenshot is False - - -def test_legacy_injected_screenshot_providers_keep_getting_resized(): - """Injected providers that only implement the pre-existing - ``requires_coordinate_tools`` contract must still get resized screenshots: - the tool registry, prompts, and validation all still treat them as - screenshot-coordinate mode.""" - - class LegacyScreenshotProvider(StateProvider): - requires_coordinate_tools = True - - assert _should_resize_model_screenshot(LegacyScreenshotProvider(SimpleNamespace())) - - class DuckTypedLegacyProvider(StateProvider): - requires_coordinate_tools = True - - assert _should_resize_model_screenshot(DuckTypedLegacyProvider(SimpleNamespace())) - - # Non-coordinate providers are unaffected - assert not _should_resize_model_screenshot(StateProvider(SimpleNamespace())) - assert not _should_resize_model_screenshot(_provider()) - assert not _should_resize_model_screenshot(StateProvider(SimpleNamespace())) - - # And the new contract still activates it - assert _should_resize_model_screenshot(_provider(vision_enabled=True)) - assert _should_resize_model_screenshot( - ScreenshotOnlyStateProvider(SimpleNamespace()) - ) - - -def test_provider_scale_matches_what_agents_actually_send(): - """The invariant that PR #355 lacked: the provider's scale must describe - the image the agents really attach.""" - buf = BytesIO() - Image.new("RGB", (NATIVE_W, NATIVE_H)).save(buf, format="PNG") - sent = resize_image_to_max_side_with_grid(buf.getvalue(), 2048) - sent_w, sent_h = image_dimensions(sent) - - state = _get_state(_provider(vision_enabled=True)) - assert sent_w == round(NATIVE_W / state.coordinate_scale_x) - assert sent_h == round(NATIVE_H / state.coordinate_scale_y) - - -POINTS_W, POINTS_H = 440, 956 -PIXELS_W, PIXELS_H = 1320, 2868 # 3x physical screenshot - -RAW_A11Y = """Attributes: Application, pid: 123, label: 'Settings' -Element subtree: - ->Application, pid: 123, label: 'Settings' - Window (Main), {{0.0, 0.0}, {440.0, 956.0}} - Cell, {{20.0, 200.0}, {400.0, 44.0}}, label: 'General' - StaticText, {{20.0, 119.7}, {133.0, 40.7}}, label: 'Settings' -""" - - -def _png(width, height): - buf = BytesIO() - Image.new("RGB", (width, height), color=(10, 20, 30)).save(buf, format="PNG") - return buf.getvalue() - - -class FakeIOSDriver: - def __init__( - self, screenshot_bytes=None, screenshot_error=None, screenshot_plan=None - ): - # screenshot_plan: per-call behaviors (bytes or Exception); the last - # entry repeats. Overrides screenshot_bytes/screenshot_error. - self._plan = screenshot_plan or ( - [screenshot_error] if screenshot_error else [screenshot_bytes] - ) - self.screenshot_calls = 0 - self.ui_tree_error = None - - async def _get_ui_tree(self): - if self.ui_tree_error: - raise self.ui_tree_error - return { - "phone_state": { - "currentApp": "Settings", - "packageName": "com.apple.Preferences", - }, - "device_context": { - "screen_bounds": {"width": POINTS_W, "height": POINTS_H} - }, - "a11y_tree": RAW_A11Y, - } - - async def screenshot(self): - step = self._plan[min(self.screenshot_calls, len(self._plan) - 1)] - self.screenshot_calls += 1 - if isinstance(step, Exception): - raise step - return step - - -def _general_element(state): - return next(e for e in state.elements if e.get("text") == "General") - - -def test_resize_flag_pairs_with_agent_gating(): - driver = FakeIOSDriver(screenshot_bytes=_png(PIXELS_W, PIXELS_H)) - assert _should_resize_model_screenshot( - IOSStateProvider(driver, vision_enabled=True) - ) - assert not _should_resize_model_screenshot(IOSStateProvider(driver)) - assert not _should_resize_model_screenshot( - IOSStateProvider(driver, use_normalized=True, vision_enabled=True) - ) - - -def test_failed_probe_recovers_and_snapshots_keep_their_contract(): - driver = FakeIOSDriver( - screenshot_plan=[RuntimeError("probe failed"), _png(PIXELS_W, PIXELS_H)] - ) - provider = IOSStateProvider(driver, vision_enabled=True) - - fallback = _get_state(provider) - assert provider.resize_model_screenshot is False - assert fallback.coordinate_contract_active is False - - good = _get_state(provider) - assert provider.resize_model_screenshot is True - assert good.coordinate_contract_active is True - assert good.convert_point(471, 1024) == (220, 478) - assert fallback.coordinate_contract_active is False - - provider.resize_model_screenshot = False - assert good.coordinate_contract_active is True - assert good.convert_point(471, 1024) == (220, 478) - provider.resize_model_screenshot = True - assert fallback.coordinate_contract_active is False - - -def test_tree_failure_returns_inactive_contract(): - driver = FakeIOSDriver(screenshot_bytes=_png(PIXELS_W, PIXELS_H)) - provider = IOSStateProvider(driver, vision_enabled=True) - driver.ui_tree_error = RuntimeError("tree fetch failed") - - state = _get_state(provider) - assert state.coordinate_contract_active is False - - -def test_non_vision_ios_does_not_require_contract(): - provider = IOSStateProvider(FakeIOSDriver(screenshot_bytes=_png(8, 8))) - state = _get_state(provider) - - assert provider.requires_active_contract_for_coords is False - assert state.convert_point(100, 200) == (100, 200) - - -def test_normalized_mode_shows_normalized_bounds_and_taps_points(): - driver = FakeIOSDriver(screenshot_bytes=_png(8, 8)) - provider = IOSStateProvider(driver, use_normalized=True) - state = _get_state(provider) - - element = _general_element(state) - assert element["bounds"] == "20,200,420,244" - assert element["displayBounds"] == "45,209,954,255" - assert "(normalized [0-1000])" in state.formatted_text - assert "(45,209,954,255)" in state.formatted_text - assert "(20,200,420,244)" not in state.formatted_text - # element taps keep points - assert state.get_element_coords(element["index"]) == (220, 222) - assert driver.screenshot_calls == 0 - - -def _bounds(left, top, right, bottom): - return {"left": left, "top": top, "right": right, "bottom": bottom} - - -@pytest.mark.parametrize( - "name,options,expected_indices,partial_bounds", - [ - ("concise", {}, [1, 3, 4, 6], (-90, 10, 10, 20)), - ("detailed", {}, [1, 2, 3, 6], (-90, 10, 10, 20)), - ("detailed", {"clip_bounds": True}, [1, 2, 3, 6], (0, 10, 10, 20)), - ("detailed", {"filter_keyboard": False}, [1, 2, 3, 4, 6], (-90, 10, 10, 20)), - ], - ids=["concise", "detailed", "clipped", "keyboard-retained"], -) -def test_filter_mixed_observation_preserves_indices_bounds_and_input( - name, options, expected_indices, partial_bounds -): - def node(index, bounds, **extra): - return {"index": index, "boundsInScreen": _bounds(*bounds), **extra} - - tree = node( - 0, - (0, 0, 100, 100), - children=[ - node(1, (10, 10, 20, 20)), - node(2, (20, 20, 25, 30)), # Width exactly at concise minimum. - node(3, (-90, 10, 10, 20)), # Exactly 10% visible. - node( - 4, - (10, 40, 60, 90), - resourceId="com.google.android.inputmethod.latin:id/keyboard", - children=[node(5, (12, 44, 20, 52))], - ), - node(6, (70, 70, 80, 80)), - node(7, (100, 10, 120, 20)), # Touches the edge, but entirely off-screen. - ], - ) - original = deepcopy(tree) - context = { - "screen_bounds": {"width": 100, "height": 100}, - "filtering_params": {"min_element_size": 5}, - } - filtered = get_filter(name, **options).filter(tree, context) - assert filtered["index"] == 0 - assert [child["index"] for child in filtered["children"]] == expected_indices - for child in filtered["children"]: - index = child["index"] - source = next(item for item in original["children"] if item["index"] == index) - expected = _bounds(*partial_bounds) if index == 3 else source["boundsInScreen"] - assert child["boundsInScreen"] == expected - if index == 4: - assert [key["index"] for key in child["children"]] == [5] - assert tree == original - - -def test_detailed_filter_keeps_exact_visibility_threshold_but_not_just_below(): - root = { - "boundsInScreen": _bounds(0, 0, 100, 100), - "children": [ - {"index": 1, "boundsInScreen": _bounds(-10, 0, 10, 20)}, - {"index": 2, "boundsInScreen": _bounds(-11, 0, 9, 20)}, - ], - } - filtered = DetailedFilter(visibility_threshold=0.5).filter( - root, {"screen_bounds": {"width": 100, "height": 100}} - ) - assert [child["index"] for child in filtered["children"]] == [1] - - -@pytest.mark.xfail( - strict=True, - raises=AssertionError, - reason="Clipping rewrites children on a parent without bounds", -) -def test_clipping_a_boundless_parent_preserves_the_original_child_bounds(): - tree = {"children": [{"index": 1, "boundsInScreen": _bounds(-5, 0, 10, 10)}]} - result = DetailedFilter(clip_bounds=True).filter( - tree, {"screen_bounds": {"width": 20, "height": 20}} - ) - assert result["children"][0]["boundsInScreen"] == _bounds(0, 0, 10, 10) - assert tree["children"][0]["boundsInScreen"] == _bounds(-5, 0, 10, 10) - - -def _contains(bounds, point): - left, top, right, bottom = bounds - x, y = point - return left <= x < right and top <= y < bottom - - -@pytest.mark.parametrize( - "blockers,fully_covered", - [ - ([(0, 0, 7, 7), (3, 3, 10, 10)], False), - ([(0, 0, 4, 10), (5, 0, 10, 10)], False), - ([(0, 0, 6, 10), (4, 0, 10, 10)], True), - ], - ids=["overlap", "one-pixel-strip", "total-occlusion"], -) -def test_uncovered_point_avoids_every_blocker(blockers, fully_covered): - target = (0, 0, 10, 10) - point = find_uncovered_point(target, blockers) - if fully_covered: - assert point is None - else: - assert point is not None and _contains(target, point) - assert all(not _contains(blocker, point) for blocker in blockers) - - -@pytest.mark.xfail( - strict=True, - raises=AssertionError, - reason="Stealth jitter does not recheck sibling bounds", -) -def test_stealth_clear_point_stays_outside_sibling_after_jitter(monkeypatch): - target = (0, 0, 100, 100) - sibling = (55, 0, 100, 100) - state = StealthUIState( - elements=[ - {"index": i, "bounds": ",".join(map(str, bounds))} - for i, bounds in enumerate([target, sibling]) - ], - formatted_text="", - focused_text="", - phone_state={}, - screen_width=100, - screen_height=100, - ) - monkeypatch.setattr( - "mobilerun.core.state.stealth.random.randint", lambda low, high: high - ) - point = state.get_clear_point(0) - assert _contains(target, point) - assert not _contains(sibling, point) diff --git a/tests/unit/core/extensions/test_binding.py b/tests/unit/core/extensions/test_binding.py deleted file mode 100644 index f4bc75de8..000000000 --- a/tests/unit/core/extensions/test_binding.py +++ /dev/null @@ -1,758 +0,0 @@ -"""Extension binding, action dispatch, and optional resource contracts.""" - -import asyncio -import json -from enum import Enum -from types import SimpleNamespace as NS -from unittest.mock import AsyncMock - -import pytest - -from mobilerun.core.credentials import ( - CloudCredentials, - DictCredentials, - EnvCredentials, - FileCredentials, -) -from mobilerun.core.devices import ( - AndroidDevice, - CloudDevice, - IOSDevice, - RecordingDevice, - StealthDevice, -) -from mobilerun.core.devices.base import Device -from mobilerun.core.devices.components.wrapper import DeviceWrapper -from mobilerun.core.extensions import Extension, action, device_action -from mobilerun.core.mailbox import CloudMailbox -from mobilerun.core.proxy import CloudFixedProxy, CloudRotatingProxy, LocalProxy -from mobilerun.errors import ( - CredentialFieldNotFound, - DeviceOperationNotSupported, - ExtensionActionError, - ExtensionConflict, - ExtensionNotBound, - ExtensionNotSupported, - MobilerunError, - ProxyNotActive, -) -from mobilerun.models.context import ContextItem -from tests.support.devices import MemoryDevice -from tests.support.extensions import check_extension_contract - - -class Choice(str, Enum): - ONE = "one" - - -def test_public_contract_kit(): - class Authenticator(Extension): - default_name = "auth" - exclusive = "authenticator" - - @action() - async def code(self, label: str = "work") -> str: - """Return a deterministic test OTP, never a seed.""" - return "123456" - - async def context(self): - return (ContextItem(self.name, "authenticator", {"method": "totp"}),) - - async def device(): - return MemoryDevice() - - asyncio.run(check_extension_contract(lambda name: Authenticator(name=name), device)) - - -def test_schema_and_call_preserve_enums_and_null_defaults(): - class Example(Extension): - default_name = "example" - - @action() - async def read(self, choice: Choice, optional: str | None = None) -> list[str]: - """Return selected values.""" - return [choice.value, optional or "default"] - - async def scenario(): - device = MemoryDevice() - ext = Example() - await ext.bind(device) - entry = device.actions.get("example.read") - assert "$defs" in entry.input_schema - assert entry.input_schema["required"] == ["choice"] - assert await device.actions.call("example.read", {"choice": "one"}) == [ - "one", - "default", - ] - await device.close() - - asyncio.run(scenario()) - - -def test_action_rejects_sync_and_missing_docs(): - with pytest.raises(TypeError, match="async"): - action()(lambda: None) - - async def undocumented() -> None: - pass - - with pytest.raises(TypeError, match="docstring"): - action()(undocumented) - - -def test_compatibility_precedes_force_and_reserved_names_fail(): - class OnlyCloud(Extension): - default_name = "cloud_ext" - exclusive = "kind" - - async def check_bind(self, device): - conflicts = await super().check_bind(device) - if device.cloud_id is None: - raise ExtensionNotSupported("requires cloud") - return conflicts - - async def scenario(): - device = MemoryDevice() - old = Extension(name="old") - await old.bind(device) - with pytest.raises(ExtensionNotSupported): - await OnlyCloud().bind(device, force=True) - with pytest.raises(ExtensionConflict, match="reserved"): - await Extension(name="close").bind(device) - assert tuple(device.extensions) == ("old",) - await device.close() - - asyncio.run(scenario()) - - -def test_named_actions_record_through_outer_wrapper(tmp_path): - class Example(Extension): - @action() - async def echo(self, value: str) -> str: - """Return a public value.""" - return value - - async def scenario(): - raw = MemoryDevice(supported_operations=frozenset({"input_text"})) - recording = RecordingDevice(raw, runs_dir=tmp_path, capture="actions") - await recording.actions.call("device.input_text", {"text": "hello"}) - ext = Example(name="example") - await ext.bind(raw) - await recording.example.echo("world") - lines = (recording.run_dir / "steps.jsonl").read_text().splitlines() - assert [(row["action"], row["args"]) for row in map(json.loads, lines)] == [ - ( - "input_text", - {"text": "hello", "clear": False, "stealth": False, "wpm": 0}, - ), - ( - "extension_call", - {"name": "example.echo", "arguments": {"value": "world"}}, - ), - ] - await recording.close() - - asyncio.run(scenario()) - - -def test_undecorated_action_override_keeps_recording(tmp_path): - class Parent(Extension): - @action() - async def value(self) -> int: - """Return the current value.""" - return 1 - - class Child(Parent): - async def value(self) -> int: - """Return the overridden value.""" - return 2 - - async def scenario(): - device = RecordingDevice(MemoryDevice(), runs_dir=tmp_path, capture="actions") - child = Child(name="child") - await child.bind(device) - assert await child.value() == 2 - row = json.loads((device.run_dir / "steps.jsonl").read_text()) - assert row["args"]["name"] == "child.value" - await device.close() - - asyncio.run(scenario()) - - -def test_observer_records_outer_dispatch_outcomes_without_primitive_duplicates( - tmp_path, -): - class Example(Extension): - @device_action() - async def write(self, device: Device, mode: str) -> bool: - """Write the requested value and return a status.""" - await device.input_text(mode) - if mode == "raise": - raise ValueError("backend details") - return mode == "ok" - - async def scenario(): - raw = MemoryDevice() - recording = RecordingDevice(raw, runs_dir=tmp_path, capture="actions") - ext = await Example().bind(recording) - with pytest.raises(ExtensionActionError): - await recording.actions.call("extension.write", {"mode": 7}) - assert recording.run_dir is None - assert await ext.write("ok") is True - assert await ext.write("false") is False - with pytest.raises(ExtensionActionError): - await ext.write("raise") - lines = (recording.run_dir / "steps.jsonl").read_text().splitlines() - assert [(r["action"], r["ok"], r["error"]) for r in map(json.loads, lines)] == [ - ("extension_call", True, None), - ("extension_call", False, "returned_false"), - ("extension_call", False, "ValueError"), - ] - assert raw.inputs == ["ok", "false", "raise"] - - asyncio.run(scenario()) - - -def test_nested_sensitive_action_redacts_public_aliases(tmp_path): - class Example(Extension): - @action() - async def outer(self, public_alias: str) -> None: - """Pass a value to the nested action.""" - await self.inner(public_alias) - - @action(sensitive_parameters=frozenset({"secret"})) - async def inner(self, secret: str) -> None: - """Accept a sensitive value.""" - pass - - async def scenario(): - recording = RecordingDevice( - MemoryDevice(), runs_dir=tmp_path, capture="actions" - ) - extension = await Example().bind(recording) - await extension.outer("private-canary") - evidence = (recording.run_dir / "steps.jsonl").read_text() - assert "private-canary" not in evidence - row = json.loads(evidence) - assert row["args"]["arguments"] == {"public_alias": "***"} - - asyncio.run(scenario()) - - -def test_stealth_catalog_vetoes_extension_bound_to_raw_sibling(tmp_path): - class Example(Extension): - @action() - async def ready(self) -> bool: - """Return readiness.""" - return True - - async def scenario(): - raw = MemoryDevice() - recording = RecordingDevice(raw, runs_dir=tmp_path, capture="actions") - await Example().bind(raw) - assert ( - await StealthDevice(recording).actions.call("extension.ready", {}) is True - ) - assert recording.run_dir is None - - asyncio.run(scenario()) - - -def test_only_invoking_recorder_observes_direct_and_catalog_extension_calls(tmp_path): - class Example(Extension): - @action() - async def ready(self) -> bool: - """Return readiness.""" - return True - - async def scenario(): - raw = MemoryDevice() - first = RecordingDevice(raw, runs_dir=tmp_path, capture="actions") - second = RecordingDevice(raw, runs_dir=tmp_path, capture="actions") - await Example().bind(first) - assert await StealthDevice(first).extension.ready() - assert await StealthDevice(first).extensions["extension"].ready() - assert await raw.extension.ready() - assert first.run_dir is None and second.run_dir is None - assert await second.extension.ready() - assert first.step_index == 0 and second.step_index == 1 - assert await first.actions.call("extension.ready", {}) - assert first.step_index == second.step_index == 1 - - asyncio.run(scenario()) - - -def test_dispatch_guard_blocks_nested_commerce_even_without_recording(): - from mobilerun.core.extensions import dispatch_guard - - calls = [] - - async def retry(owner, policy): - calls.append("paid") - - class Example(Extension): - role = "phone_number" - - @action() - async def outer(self) -> None: - """Call the nested method.""" - await self.buy() - - @action(billing_retry=retry) - async def buy(self) -> None: - """Simulate a paid dispatch.""" - calls.append("paid") - - def deny(info): - if info.supports_billing_retry: - assert (info.extension_role, info.extension_name, info.action_name) == ( - "phone_number", - "example", - "buy", - ) - raise ExtensionActionError("commerce blocked") - - async def scenario(): - example = Example(name="example") - with dispatch_guard(deny), dispatch_guard(lambda info: None): - with pytest.raises(ExtensionActionError, match="commerce blocked"): - await example.outer() - assert calls == [] - await example.outer() - assert calls == ["paid"] - - asyncio.run(scenario()) - - -def test_close_cannot_race_a_queued_bind(): - async def scenario(): - extension = Extension() - phone = MemoryDevice() - await extension._lifecycle_lock.acquire() - closing = asyncio.create_task(extension.close()) - await asyncio.sleep(0) - binding = asyncio.create_task(extension.bind(phone)) - await asyncio.sleep(0) - extension._lifecycle_lock.release() - await closing - try: - await binding - except ExtensionConflict: - pass - assert extension.device is None - assert not phone.extensions - await phone.close() - - asyncio.run(scenario()) - - -def test_failed_force_finishes_rollback_before_old_close(): - async def scenario(): - started, finish = asyncio.Event(), asyncio.Event() - events = [] - - class Old(Extension): - exclusive = "resource" - - async def on_bind(self, device): - events.append("bind") - - async def on_unbind(self, device): - events.append("unbind") - - async def on_close(self): - events.append("close") - - class Incoming(Extension): - exclusive = "resource" - - async def on_bind(self, device): - started.set() - await finish.wait() - raise RuntimeError("incoming failed") - - phone = MemoryDevice() - old, incoming = Old(name="old"), Incoming(name="incoming") - await old.bind(phone) - switching = asyncio.create_task(incoming.bind(phone, force=True)) - await started.wait() - closing = asyncio.create_task(old.close()) - await asyncio.sleep(0) - finish.set() - with pytest.raises(RuntimeError, match="incoming failed"): - await switching - await closing - assert events == ["bind", "unbind", "bind", "unbind", "close"] - assert old.device is None - assert not phone.extensions - await phone.close() - - asyncio.run(scenario()) - - -class Resource(Extension): - @action() - async def read(self) -> str: - """Read resource metadata without a device.""" - return "available" - - @device_action - async def device_name(self, device: Device) -> str: - """Read a device identifier when explicitly bound.""" - self.received = device - return device.identifier or "unknown" - - @action() - async def fail(self) -> None: - """Fail without exposing private backend details.""" - raise RuntimeError("private backend value") - - -def test_unbound_direct_and_catalog_actions_work_and_wrap_errors(): - async def scenario(): - resource = Resource(name="resource") - assert await resource.read() == "available" - assert await resource.actions.call("resource.read", {}) == "available" - for call in (resource.fail, lambda: resource.actions.call("resource.fail", {})): - with pytest.raises(ExtensionActionError) as raised: - await call() - assert "private backend value" not in str(raised.value) - - asyncio.run(scenario()) - - -def test_device_action_rejects_before_body_and_injects_facade(): - async def scenario(): - resource = Resource(name="vault") - for call in ( - resource.device_name, - lambda: resource.actions.call("vault.device_name", {}), - ): - with pytest.raises( - ExtensionNotBound, - match=r"needs a bound device; await vault.bind\(device\) first", - ): - await call() - assert not hasattr(resource, "received") - phone = DeviceWrapper(MemoryDevice()) - await resource.bind(phone) - assert await resource.device_name() == "memory" - assert resource.received is phone - assert await resource.actions.call("vault.device_name", {}) == "memory" - assert resource.received is phone - await phone.close() - - asyncio.run(scenario()) - - -@pytest.mark.parametrize("uncertain", [False, True]) -def test_bound_uncertain_and_draining_checks_still_apply(uncertain): - async def scenario(): - resource = Resource() - phone = MemoryDevice() - await resource.bind(phone) - if uncertain: - resource._binding.uncertain = True - else: - phone._extension_state.closing = True - for call in ( - resource.read, - lambda: resource.actions.call("extension.read", {}), - ): - with pytest.raises( - ExtensionNotBound, match="uncertain" if uncertain else "closing" - ): - await call() - await phone.close() - - asyncio.run(scenario()) - - -def test_unbound_actions_keep_serialization_and_cross_extension_guard(): - active = 0 - peak = 0 - - class Counter(Extension): - @action() - async def read(self) -> int: - """Check action serialization without a device.""" - nonlocal active, peak - active += 1 - peak = max(peak, active) - await asyncio.sleep(0) - active -= 1 - return 1 - - @action() - async def cross(self) -> int: - """Attempt a cross-extension unbound action.""" - return await other.read() - - async def scenario(): - resource = Counter() - await asyncio.gather( - *(resource.read() for _ in range(5)), - *(resource.actions.call("extension.read", {}) for _ in range(5)), - ) - assert peak == 1 - with pytest.raises(ExtensionActionError, match="Cross-extension"): - await resource.cross() - - other = Counter(name="other") - asyncio.run(asyncio.wait_for(scenario(), timeout=1)) - - -def test_local_proxy_status_explicitly_requires_device(): - proxy = LocalProxy("localhost", 8080) - with pytest.raises( - ExtensionNotBound, - match=r"needs a bound device; await proxy.bind\(device\) first", - ): - asyncio.run(proxy.status()) - - -def test_cloud_proxy_status_works_unbound(): - assert not asyncio.run(CloudFixedProxy("known").status()).connected - - -def test_device_action_metadata_schema_and_signature(): - import inspect - - class Typed(Extension): - @device_action(public=False, sensitive_parameters=frozenset({"value"})) - async def write(self, device: Device, value: str) -> str: - """Return a typed value with a hidden injected device.""" - return value - - resource = Typed() - entry = resource.actions.get("extension.write") - assert entry.requires_device - assert not entry.public - assert set(entry.input_schema["properties"]) == {"value"} - assert list(inspect.signature(resource.write).parameters) == ["value"] - assert not Resource().actions.get("extension.read").requires_device - - -def test_inherited_device_action_override_keeps_injection(): - class Override(Resource): - async def device_name(self, device: Device) -> str: - """Override a device action without repeating its decorator.""" - self.received = device - return "override" - - async def scenario(): - resource = Override() - assert resource.actions.get("extension.device_name").requires_device - with pytest.raises(ExtensionNotBound): - await resource.actions.call("extension.device_name", {}) - phone = MemoryDevice() - await resource.bind(phone) - assert await resource.actions.call("extension.device_name", {}) == "override" - assert resource.received is phone - await phone.close() - - asyncio.run(scenario()) - - -def test_nested_device_actions_inject_facade_and_reject_unbound_before_body(): - class Nested(Extension): - ran = False - - @device_action() - async def inner(self, device: Device, value: str) -> str: - """Use the injected facade in a nested call.""" - self.ran = True - assert device is self.device - return value - - @action - async def outer(self, value: str) -> str: - """Delegate to a device-dependent action on the same extension.""" - return await self.inner(value) - - async def scenario(): - resource = Nested() - with pytest.raises( - ExtensionNotBound, match="extension.inner.*needs a bound device" - ): - await resource.outer("value") - assert not resource.ran - facade = DeviceWrapper(MemoryDevice()) - await resource.bind(facade) - assert await resource.outer("value") == "value" - assert resource.ran - await facade.close() - - asyncio.run(asyncio.wait_for(scenario(), timeout=1)) - - -def test_device_action_rejects_missing_or_wrong_device_annotation(): - with pytest.raises(TypeError, match="device: Device"): - - @device_action - async def missing(self) -> None: - """Missing the injected parameter.""" - - with pytest.raises(TypeError, match="device: Device"): - - @device_action - async def wrong(self, device: str) -> None: - """Incorrectly annotated injected parameter.""" - - -@pytest.mark.parametrize( - "error", - [ - CredentialFieldNotFound("Credential field not found"), - DeviceOperationNotSupported("Operation unavailable"), - ], -) -def test_value_safe_action_errors_preserve_type_and_identity(error): - class Failing(Extension): - @action - async def run(self) -> None: - """Raise a public value-safe typed error.""" - raise error - - async def scenario(): - resource = Failing() - for invoke in ( - resource.run, - lambda: resource.actions.call("extension.run", {}), - ): - with pytest.raises(type(error)) as raised: - await invoke() - assert raised.value is error - - asyncio.run(scenario()) - - -@pytest.mark.parametrize( - "error", - [RuntimeError("CANARY-PRIVATE-VALUE"), MobilerunError("CANARY-PRIVATE-VALUE")], -) -def test_unsafe_action_errors_remain_wrapped_without_values(error): - class Failing(Extension): - @action - async def run(self) -> None: - """Raise an unsafe backend failure.""" - raise error - - async def scenario(): - resource = Failing() - for invoke in ( - resource.run, - lambda: resource.actions.call("extension.run", {}), - ): - with pytest.raises(ExtensionActionError) as raised: - await invoke() - assert "CANARY-PRIVATE-VALUE" not in str(raised.value) - assert raised.value.__suppress_context__ - - asyncio.run(scenario()) - - -@pytest.mark.parametrize("kind", ["dict", "file", "env", "cloud"]) -def test_every_provider_binds_and_unbinds_in_order(kind, tmp_path, monkeypatch): - path = tmp_path / "credentials.yaml" - path.write_text("login: example-only\n") - path.chmod(0o600) - monkeypatch.setenv("MOBILERUN_SECRET_LOGIN", "example-only") - provider = { - "dict": lambda: DictCredentials({}, name="second"), - "file": lambda: FileCredentials(path, name="second"), - "env": lambda: EnvCredentials(name="second"), - "cloud": lambda: CloudCredentials(api_key="fake", name="second"), - }[kind]() - phone = AndroidDevice("local") - first = DictCredentials({"login": "first"}) - - async def exercise(): - await first.bind(phone) - wrapped = StealthDevice(RecordingDevice(phone)) - await provider.bind(wrapped) - await provider.bind(phone) - assert list(phone.extensions) == list(wrapped.extensions) == ["vault", "second"] - assert phone.extensions["vault"] is first - assert wrapped.extensions["second"] is provider - await first.unbind() - assert list(phone.extensions) == ["second"] - await provider.unbind() - await provider.unbind() - assert not phone.extensions - if isinstance(provider, CloudCredentials): - await provider.close() - - asyncio.run(exercise()) - - -@pytest.mark.parametrize( - "factory", - [ - lambda: AndroidDevice("local", credentials=[]), - lambda: IOSDevice("http://local", credentials=[]), - lambda: CloudDevice(api_key="fake", credentials=[]), - ], -) -def test_device_credentials_constructor_is_removed(factory): - with pytest.raises( - TypeError, match="provider.bind|unexpected keyword argument 'credentials'" - ): - factory() - - -def test_mailbox_binding_is_local_and_supports_local_typing(): - phone = AndroidDevice("local") - mailbox = CloudMailbox("mailbox", api_key="fake") - mailbox.wait_for_code = AsyncMock(return_value="123456") - - async def exercise(): - await mailbox.bind(RecordingDevice(phone)) - assert phone.extensions[mailbox.name].device is mailbox.device - assert await phone.mailbox.wait_for_code() == "123456" - await mailbox.unbind() - with pytest.raises(DeviceOperationNotSupported, match="No email extension"): - _ = phone.mailbox - - asyncio.run(exercise()) - - -@pytest.mark.parametrize( - "connected,restarted", [(True, False), (False, False), (True, True)] -) -def test_phone_proxy_switch_checks_status_and_waits_after_restart( - monkeypatch, connected, restarted -): - from mobilerun.clients.cloud import proxies - - phone = CloudDevice("phone", api_key="fake", billing="paid") - connect = AsyncMock() - monkeypatch.setattr(proxies, "connect_device", connect) - phone.info = AsyncMock( - return_value=NS(state="restarting" if restarted else "ready") - ) - phone.wait_ready = AsyncMock() - from mobilerun.core.proxy import ProxyStatus - - phone._proxy_status = AsyncMock(return_value=ProxyStatus(connected=connected)) - proxy = CloudRotatingProxy(country="DE") - - async def exercise(): - if connected: - await proxy.bind(phone, force=True) - assert (await proxy.status()).connected - assert phone.extensions["proxy"] is proxy - else: - with pytest.raises(ProxyNotActive): - await proxy.bind(phone, force=True) - assert not phone.extensions - - asyncio.run(exercise()) - assert phone.wait_ready.await_count == int(restarted) - connect.assert_awaited_once() - assert proxy.exclusive == "proxy" - - -def test_default_proxy_uses_smart_ip_setting(monkeypatch): - monkeypatch.setenv("MOBILERUN_CLOUD_PROXY_SMART_IP", "false") - assert CloudRotatingProxy._from_settings().smart_ip is False diff --git a/tests/unit/core/extensions/test_extension_lifecycle.py b/tests/unit/core/extensions/test_extension_lifecycle.py index 1017d5aaa..2d6829d3d 100644 --- a/tests/unit/core/extensions/test_extension_lifecycle.py +++ b/tests/unit/core/extensions/test_extension_lifecycle.py @@ -1,974 +1,129 @@ -"""Extension lifecycle, shared device operations, and sensitive action contracts.""" +"""Standalone extension lifecycle and value-safety contracts.""" import asyncio -import copy import json import logging -import pickle from dataclasses import dataclass from enum import Enum -from functools import wraps -from types import SimpleNamespace from typing import Annotated, Literal, cast -from unittest.mock import AsyncMock, patch import pytest from pydantic import BaseModel, Field -from mobilerun.core.devices.base import Device -from mobilerun.core.devices.components.wrapper import DeviceWrapper -from mobilerun.core.devices.pool import DevicePool -from mobilerun.core.devices.recording import RecordingDevice -from mobilerun.core.extensions import BillingRetry, Extension, action, device_action -from mobilerun.core.extensions.registry import Binding -from mobilerun.core.phone_number import CloudPhoneNumber -from mobilerun.core.proxy import CloudFixedProxy, ExistingCloudProxy, LocalProxy -from mobilerun.errors import ( - DeviceOperationNotSupported, - ExtensionActionError, - ExtensionClosed, - ExtensionConflict, - ExtensionNotBound, -) +from mobilerun.core.extensions import Extension, compile_tools, function from mobilerun.models import CloudCredentialReference, CloudTaskInputs -from mobilerun.models.billing import Billing -from mobilerun.models.proxy import ProxyStatus -from tests.support.devices import MemoryDevice from tests.support.extensions import check_extension_contract -from tests.support.proxy import ProxyMemory -def test_outer_decorator_preserves_action_discovery(): - def trace(fn): - @wraps(fn) - async def wrapper(*args, **kwargs): - return f"traced: {await fn(*args, **kwargs)}" - - return wrapper - +def test_close_releases_the_resource_once_even_with_concurrent_callers(): class Resource(Extension): - @trace - @action(public=False) - async def echo(self, text: str) -> str: - """Echo a value through the tracing decorator.""" - return text - - actions = Resource().actions - assert [entry.name for entry in actions.list()] == ["extension.echo"] - assert actions.list(audience="cli") == () - assert asyncio.run(actions.call("extension.echo", {"text": "ok"})) == "traced: ok" - - -@pytest.mark.parametrize("descriptor", [classmethod, staticmethod]) -def test_descriptor_override_remains_discoverable(descriptor): - class Parent(Extension): - @action - async def echo(self, text: str) -> str: - """Echo a value.""" - return text - - class Child(Parent): - async def class_echo(cls, text: str) -> str: - return f"{cls.__name__}: {text}" - - async def static_echo(text: str) -> str: - return f"static: {text}" - - echo = descriptor(class_echo if descriptor is classmethod else static_echo) - - actions = Child().actions - expected = "Child: ok" if descriptor is classmethod else "static: ok" - assert [entry.name for entry in actions.list()] == ["extension.echo"] - assert asyncio.run(actions.call("extension.echo", {"text": "ok"})) == expected + releases = 0 - -def test_billing_retry_is_call_policy_not_an_action_argument(): - class Resource(Extension): - async def _retry(self, policy: BillingRetry, /, text: str) -> str: - async def send_with_mode(mode: Billing) -> str: - return f"{mode.value}: {text}" - - result, _ = await policy(send_with_mode, Billing.INCLUDED) - return result - - @action(billing_retry=_retry) - async def send(self, text: str) -> str: - """Send once at the configured billing mode.""" - return f"included: {text}" - - async def authorize(operation, mode): - assert mode is Billing.INCLUDED - return await operation(Billing.PAID), Billing.PAID + async def on_close(self) -> None: + await asyncio.sleep(0) + self.releases += 1 async def scenario(): resource = Resource() - device = MemoryDevice() - await resource.bind(device) - entry = device.actions.get("extension.send") - assert set(entry.input_schema["properties"]) == {"text"} - with pytest.raises(ExtensionActionError, match="Invalid arguments"): - await device.actions.call( - "extension.send", {"text": "hello", "billing_retry": True} - ) - assert await resource.send("hello") == "included: hello" - assert ( - await device.actions.call( - "extension.send", {"text": "hello"}, billing_retry=authorize - ) - == "paid: hello" - ) - assert await resource.send("hello") == "included: hello" - await device.close() - - asyncio.run(scenario()) - - -def test_billing_retry_action_can_have_public_owner_argument(): - class Resource(Extension): - async def _retry(self, policy: BillingRetry, /, owner: str) -> str: - return owner - - @action(billing_retry=_retry) - async def echo(self, owner: str) -> str: - """Return the public owner argument.""" - return owner - - async def policy(operation, mode): - return await operation(mode), mode - - async def scenario(): - actions = Resource().actions - assert await actions.call("extension.echo", {"owner": "public"}) == "public" - assert ( - await actions.call( - "extension.echo", {"owner": "public"}, billing_retry=policy - ) - == "public" - ) - - asyncio.run(scenario()) - - -def test_diamond_inheritance_uses_merged_action_visibility_and_sensitivity(tmp_path): - class Private(Extension): - @action(public=False, sensitive_parameters=frozenset({"text"})) - async def echo(self, text: str) -> int: - """Return the length without exposing the text.""" - return len(text) - - class Inherited(Private): - pass - - class Public(Private): - @action - async def echo(self, text: str) -> int: - """Return the length plus one.""" - return len(text) + 1 - - class Diamond(Inherited, Public): - pass - - async def scenario(): - phone = RecordingDevice(MemoryDevice(), runs_dir=tmp_path, capture="actions") - await Diamond().bind(phone) - for audience in ("cli", "operator"): - assert "extension.echo" not in { - entry.name for entry in phone.actions.list(audience=audience) - } - assert await phone.actions.call("extension.echo", {"text": "secret"}) == 7 - row = json.loads((phone.run_dir / "steps.jsonl").read_text()) - assert row["args"]["arguments"] == {"text": "***"} - await phone.close() + await asyncio.gather(resource.close(), resource.close()) + await resource.close() + assert resource.releases == 1 asyncio.run(scenario()) -def test_ordinary_billing_retry_parameters_stay_public_action_arguments(): +def test_close_can_retry_failed_cleanup(): class Resource(Extension): - @action - async def optional(self, *, billing_retry: str | None = None) -> str | None: - """Echo an optional value.""" - return billing_retry - - @action - async def required(self, *, billing_retry: str) -> str: - """Echo a required value.""" - return billing_retry + attempts = 0 - @action - async def defaulted(self, *, billing_retry: str = "default") -> str: - """Echo a defaulted value.""" - return billing_retry + async def on_close(self) -> None: + self.attempts += 1 + if self.attempts == 1: + raise RuntimeError("cleanup failed") async def scenario(): resource = Resource() - for name in ("optional", "required", "defaulted"): - qualified = f"extension.{name}" - entry = resource.actions.get(qualified) - assert "billing_retry" in entry.input_schema["properties"] - result = await resource.actions.call(qualified, {"billing_retry": "custom"}) - assert result == "custom" - assert await resource.optional(billing_retry=None) is None - assert await resource.defaulted() == "default" - - asyncio.run(scenario()) - - -class LateBoundResource(Extension): - async def _retry(self, policy, /, *, billing_retry): - return f"authorized: {billing_retry}" - - @action(billing_retry=_retry) - async def echo(self, *, billing_retry: "str | None" = None) -> "LateResult": - """Return a type that does not exist when the action is declared.""" - return billing_retry or "default" - - -LateResult = str - - -def test_retry_handler_and_public_billing_retry_argument_are_independent(): - actions = LateBoundResource().actions - arguments = {"billing_retry": "public"} - assert asyncio.run(actions.call("extension.echo", arguments)) == "public" - assert ( - asyncio.run( - actions.call("extension.echo", arguments, billing_retry=AsyncMock()) - ) - == "authorized: public" - ) - - -def test_unmarked_retry_override_uses_ordinary_signature(): - class Parent(Extension): - async def _retry(self, policy: BillingRetry) -> str: - raise AssertionError("Unmarked replacement inherited retry handler") - - @action(billing_retry=_retry) - async def send(self) -> str: - """Return the parent marker.""" - return "parent" - - class Child(Parent): - async def send(self: "Extension", *, billing_retry: str | None = None) -> str: - """Do not receive a retry policy.""" - return billing_retry or "child" - - child = Child() - assert asyncio.run(child.send(billing_retry=None)) == "child" - assert asyncio.run(child.send(billing_retry="public")) == "public" - entry = child.actions.get("extension.send") - assert set(entry.input_schema["properties"]) == {"billing_retry"} - assert not entry.supports_billing_retry - with pytest.raises(ExtensionActionError, match="does not support billing retry"): - asyncio.run(child.actions.call(entry.name, {}, billing_retry=AsyncMock())) - - -def test_retry_enabled_action_can_call_unmarked_parent(): - class Parent(Extension): - @action() - async def send(self, text: str) -> str: - """Return the text without receiving billing policy.""" - return text - - class Child(Parent): - async def _retry(self, policy: BillingRetry, /, text: str) -> str: - return await super().send(text) - - @action(billing_retry=_retry) - async def send(self, text: str) -> str: - """Delegate to the parent after selecting billing.""" - return await super().send(text) - - child = Child() - assert ( - asyncio.run(child.actions.call("extension.send", {"text": "hello"})) == "hello" - ) - assert ( - asyncio.run( - child.actions.call( - "extension.send", {"text": "ok"}, billing_retry=AsyncMock() - ) - ) - == "ok" - ) - - -def test_reciprocal_cross_extension_actions_fail_without_deadlock(): - async def scenario(): - ready = asyncio.Barrier(2) - - class Peer(Extension): - @action() - async def inner(self) -> None: - """Return without doing work.""" - - @action() - async def outer(self) -> None: - """Attempt a reciprocal nested action.""" - await ready.wait() - await peers[1 if self is peers[0] else 0].inner() - - phone = MemoryDevice() - peers = [Peer(name="first"), Peer(name="second")] - for peer in peers: - await peer.bind(phone) - results = await asyncio.gather( - *(peer.outer() for peer in peers), return_exceptions=True - ) - assert all( - isinstance(result, ExtensionActionError) - and "Cross-extension" in str(result) - for result in results - ) - await phone.close() - - asyncio.run(asyncio.wait_for(scenario(), timeout=1)) - - -def test_unbind_waiting_for_cross_extension_call_finishes(): - async def scenario(): - entered, proceed = asyncio.Event(), asyncio.Event() - - class Peer(Extension): - @action() - async def inner(self) -> None: - """Return without doing work.""" - - @action() - async def outer(self) -> None: - """Try another extension while unbind is waiting.""" - entered.set() - await proceed.wait() - await second.inner() - - phone = MemoryDevice() - first, second = Peer(name="first"), Peer(name="second") - await first.bind(phone) - await second.bind(phone) - running = asyncio.create_task(first.outer()) - await entered.wait() - unbinding = asyncio.create_task(first.unbind()) - await asyncio.sleep(0) - proceed.set() - with pytest.raises(ExtensionActionError, match="Cross-extension"): - await running - await unbinding - assert first.device is None - await phone.close() - - asyncio.run(asyncio.wait_for(scenario(), timeout=1)) - - -@pytest.mark.parametrize("detached", [False, True]) -def test_close_waits_for_unbound_action_and_rejects_new_actions(detached): - async def scenario(): - entered, proceed = asyncio.Event(), asyncio.Event() - - class Resource(Extension): - released = False - - @action - async def inner(self) -> bool: - """Finish same-extension work while shutdown waits.""" - assert not self.released - return True - - @action - async def read(self) -> bool: - """Hold an unbound resource until the caller permits completion.""" - entered.set() - await proceed.wait() - assert not self.released - return await self.inner() - - async def on_close(self) -> None: - self.released = True - - resource = Resource() - phone = MemoryDevice() - if detached: - await resource.bind(phone) - await resource.unbind() - running = asyncio.create_task(resource.read()) - await entered.wait() - # This call queues behind the running body; shutdown must reject it too. - queued = asyncio.create_task(resource.inner()) - await asyncio.sleep(0) - closing = asyncio.create_task(resource.close()) - await asyncio.sleep(0) - assert not closing.done() - assert not resource.released - with pytest.raises(ExtensionClosed): - await resource.inner() - proceed.set() - assert await running - with pytest.raises(ExtensionClosed): - await queued - await closing - assert resource.released - for invoke in ( - resource.inner, - lambda: resource.actions.call("extension.inner", {}), - ): - with pytest.raises(ExtensionClosed) as raised: - await invoke() - assert raised.value.value_safe + with pytest.raises(RuntimeError, match="cleanup failed"): + await resource.close() await resource.close() - await phone.close() - - asyncio.run(asyncio.wait_for(scenario(), timeout=2)) - - -@pytest.mark.parametrize("mutating", [False, True]) -def test_cancelled_close_only_stays_closed_after_mutation_started(mutating): - async def run(): - entered, release = asyncio.Event(), asyncio.Event() - - class Resource(Extension): - @action - async def read(self) -> bool: - """Safely read the resource.""" - return True - - async def on_close(self) -> None: - entered.set() - await release.wait() - - resource = Resource() - if not mutating: - await resource._action_lock.acquire() - closing = asyncio.create_task(resource.close()) - if mutating: - await entered.wait() - else: - await asyncio.sleep(0) - closing.cancel() - with pytest.raises(asyncio.CancelledError): - await closing - if not mutating: - resource._action_lock.release() - assert await resource.read() - else: - with pytest.raises(ExtensionClosed): - await resource.read() - release.set() await resource.close() - - asyncio.run(asyncio.wait_for(run(), timeout=2)) - - -def test_refused_cloud_proxy_close_does_not_poison_the_handle(): - async def run(): - phone = ProxyMemory(True) - proxy = CloudFixedProxy("old") - await proxy.bind(phone) - with pytest.raises(ExtensionConflict): - await proxy.close() - assert proxy.device is phone - assert (await proxy.status()).connected - assert not proxy._closing - await phone.close() - - asyncio.run(run()) - - -@pytest.mark.parametrize("force", [False, True]) -@pytest.mark.parametrize("cancel", [False, True]) -def test_failed_local_detach_reconciles_actual_remote_state(force, cancel): - async def scenario(): - phone = ProxyMemory(False) - old = LocalProxy("host", 8080) - incoming = LocalProxy("new", 8081) - await old.bind(phone) - detached = asyncio.Event() - original = RuntimeError("detached then failed") - - async def disconnect(): - phone.target.current = ProxyStatus(False) - detached.set() - if cancel: - await asyncio.Event().wait() - raise original - - phone.target.disconnect = disconnect - task = asyncio.create_task( - incoming.bind(phone, force=True) if force else old.unbind() - ) - await detached.wait() - if cancel: - task.cancel() - with pytest.raises( - asyncio.CancelledError if cancel else RuntimeError - ) as raised: - await task - if not cancel: - assert raised.value is original - assert not phone.extensions - assert old.device is None - assert incoming.device is None - await phone.close() - - asyncio.run(asyncio.wait_for(scenario(), timeout=1)) - - -@pytest.mark.parametrize("force", [False, True]) -def test_failed_detach_with_unreadable_status_is_uncertain(force): - async def scenario(): - phone = ProxyMemory(False) - old = LocalProxy("host", 8080) - incoming = LocalProxy("new", 8081) - await old.bind(phone) - original = RuntimeError("detach failed") - phone.target.disconnect = AsyncMock(side_effect=original) - phone.target.status = AsyncMock(side_effect=RuntimeError("status unreadable")) - with pytest.raises(RuntimeError) as raised: - if force: - await incoming.bind(phone, force=True) - else: - await old.unbind() - assert raised.value is original - assert phone.proxy is old - assert old._binding.uncertain - assert any("uncertain" in note for note in original.__notes__) - with pytest.raises(ExtensionNotBound, match="uncertain"): - await old.status() - assert incoming.device is None - phone.target.disconnect = AsyncMock() - await phone.close() + assert resource.attempts == 2 asyncio.run(scenario()) -def test_successful_rollback_with_different_unresolvable_reference_does_not_preserve_handle(): - async def run(): - phone = ProxyMemory(True) - old = CloudFixedProxy("old") - await old.bind(phone) - original = RuntimeError("switch failed") - - async def connect(name): - phone.target.current = ProxyStatus(True, "different-reference") - if name == "new": - raise original - return ProxyStatus(True, "mrc:old") - - phone.target.connect.side_effect = connect - phone.target._resolve_reference = AsyncMock(return_value=None) - with pytest.raises(RuntimeError) as raised: - await CloudFixedProxy("new").bind(phone, force=True) - assert raised.value is original - assert isinstance(phone.proxy, ExistingCloudProxy) - assert old.device is None - await phone.close() - - asyncio.run(run()) - - -@pytest.mark.parametrize("connected", [False, True]) -def test_number_readback_uses_extension_owned_identity_and_update_hooks(connected): - async def run(): - phone = MemoryDevice( - cloud_id="device", supported_operations=frozenset({"cloud_telephony"}) - ) - - class ThirdPartyNumber(Extension): - role = "phone_number" - exclusive = "phone_number" - observed = "not-called" - - def _matches_remote(self, observed: object) -> bool: - return getattr(observed, "number_id", None) == "third-party" - - def _observe_remote_binding( - self, device: Device, observed: object | None - ) -> None: - assert device is phone - self.observed = observed - - original = ThirdPartyNumber(name="sms") - await original.bind(phone, close_on_device_close=True) - binding = original._binding - remote = ( - SimpleNamespace(number_id="third-party", phone_number="+123") - if connected - else None - ) - with patch( - "mobilerun.core.phone_number.cloud.devices.number", - AsyncMock(return_value=SimpleNamespace(binding=remote)), - ): - await CloudPhoneNumber("incoming")._reconcile_bind_failure( - phone, RuntimeError("response lost") - ) - if connected: - assert original.observed.number_id == remote.number_id - assert original.observed.phone_number == remote.phone_number - assert phone.number is original - assert original._binding is binding - assert binding.owned - else: - assert not phone.extensions - assert original.device is None - await phone.close() - - asyncio.run(run()) - - -def test_contract_checker_detects_orphan_inserted_after_failed_bind(): - class Broken(Extension): - async def bind(self, device, **kwargs): - try: - return await super().bind(device, **kwargs) - except Exception: - orphan = Extension(name="orphan") - device._extension_state.bindings["orphan"] = Binding( - orphan, device, False - ) - raise - - async def device(): - return MemoryDevice() - - with pytest.raises(AssertionError, match="C:.*registry"): - asyncio.run(check_extension_contract(lambda name: Broken(name=name), device)) - - -@pytest.mark.parametrize("secret_view", ["root", "wrapper", "pool"]) -@pytest.mark.parametrize("other_view", ["root", "wrapper", "pool", "catalog"]) -@pytest.mark.parametrize("operation", ["tap", "input_text"]) -def test_focus_precheck_and_secret_typing_are_atomic_across_views( - secret_view, other_view, operation -): - async def run(): - entered, release = asyncio.Event(), asyncio.Event() - - class FocusDevice(MemoryDevice): - focus = "password" - - def __init__(self): - super().__init__(supported_operations=frozenset({"tap", "input_text"})) - self.timeline = [] - - async def _input_text_raw( - self, - text: str, - clear: bool = False, - stealth: bool = False, - wpm: int = 0, - ) -> bool: - if text == "secret-canary": - entered.set() - await release.wait() - self.timeline.append((text, self.focus)) - return True - - async def tap(self, x: int, y: int) -> None: - self.timeline.append(("tap", self.focus)) - self.focus = "chat" - - class Vault(Extension): - @device_action - async def type_field(self, device: Device) -> bool: - """Type a non-secret test canary through the bound facade.""" - return await device._input_secret("secret-canary") - - root = FocusDevice() - wrapper = DeviceWrapper(RecordingDevice(root)) - for view in (root, wrapper): - view.state.refresh = AsyncMock( - return_value=SimpleNamespace( - phone_state={ - "focusedElement": {"id": "password"}, - "isEditable": True, - } - ) - ) - pool = DevicePool([wrapper]) - vault = Vault(name="vault") - await vault.bind(wrapper) - if secret_view == "pool": - secret = asyncio.create_task(pool.actions.call("vault.type_field", {})) - else: - secret = asyncio.create_task( - (root if secret_view == "root" else wrapper)._input_secret( - "secret-canary" - ) - ) - await entered.wait() - arguments = {"x": 1, "y": 1} if operation == "tap" else {"text": "plain"} - if other_view == "catalog": - other = asyncio.create_task( - root.actions.call(f"device.{operation}", arguments) - ) - else: - view = {"root": root, "wrapper": wrapper, "pool": pool}[other_view] - other = asyncio.create_task(getattr(view, operation)(**arguments)) - for _ in range(3): - await asyncio.sleep(0) - assert not other.done() - assert root.focus == "password" - release.set() - await secret - await other - assert root.timeline[0] == ("secret-canary", "password") - assert root.timeline[1][0] == ("tap" if operation == "tap" else "plain") - await root.close() - await vault.close() - - asyncio.run(asyncio.wait_for(run(), timeout=2)) - - -@pytest.mark.parametrize( - ("name", "arguments"), - [ - ("swipe", (0, 0, 1, 1)), - ("drag", (0, 0, 1, 1)), - ("press_button", ("home",)), - ("press_key_code", (1,)), - ("start_app", ("app",)), - ("stop_app", ("app",)), - ("open_url", ("https://example.com",)), - ("tap_element", (1,)), - ], -) -def test_other_focus_changing_operations_share_the_root_lock(name, arguments): - async def run(): - root = MemoryDevice() - wrapper = DeviceWrapper(root) - async with root._input_operations.hold(): - queued = asyncio.create_task(getattr(wrapper, name)(*arguments)) - await asyncio.sleep(0) - assert not queued.done() - # The in-memory backend may not implement the operation. It must only - # reach its body after the root input lock has been released. - await asyncio.gather(queued, return_exceptions=True) - - asyncio.run(asyncio.wait_for(run(), timeout=2)) - - -def test_child_tasks_do_not_inherit_input_lock_ownership_and_cancel_releases_it(): - async def run(): - root = MemoryDevice() - async with root._input_operations.hold(): - # Same-task nested delegation is reentrant. - assert await DeviceWrapper(root).input_text("first") - child = asyncio.create_task(root.input_text("cancelled")) - await asyncio.sleep(0) - assert not child.done() - child.cancel() - with pytest.raises(asyncio.CancelledError): - await child - assert await root.input_text("last") - assert root.inputs == ["first", "last"] - - asyncio.run(asyncio.wait_for(run(), timeout=2)) - - -def test_inherited_mixin_operations_and_independent_roots_use_the_correct_lock(): - class NavigationMixin: - async def open_url(self, url: str) -> None: - self.opened = url - - class MixedDevice(NavigationMixin, MemoryDevice): - pass - - async def run(): - root = MixedDevice() - independent = MemoryDevice() - async with root._input_operations.hold(): - pending = asyncio.create_task( - DeviceWrapper(root).open_url("https://example.com") - ) - await asyncio.sleep(0) - assert not pending.done() - assert await independent.input_text("independent") - await pending - assert root.opened == "https://example.com" - - asyncio.run(asyncio.wait_for(run(), timeout=2)) - - -def test_cancelling_active_input_releases_the_root_lock(): - async def run(): - started = asyncio.Event() - - class BlockingDevice(MemoryDevice): - async def tap(self, x: int, y: int) -> None: - started.set() - await asyncio.Event().wait() - - root = BlockingDevice() - tapping = asyncio.create_task(DeviceWrapper(root).tap(1, 1)) - await started.wait() - tapping.cancel() - with pytest.raises(asyncio.CancelledError): - await tapping - assert await root.input_text("after cancellation") - - asyncio.run(asyncio.wait_for(run(), timeout=2)) - - def test_sensitive_parameter_default_is_rejected_at_declaration(): with pytest.raises(TypeError, match="Sensitive.*default"): class Unsafe(Extension): - @action(sensitive_parameters=frozenset({"password"})) + @function(sensitive_parameters=("password",)) async def login(self, password: str = "TOP-SECRET") -> None: """Use credentials.""" +class SecretChoice(str, Enum): + FIRST = "ENUM-CANARY-ONE" + SECOND = "ENUM-CANARY-TWO" + + class SecretInput(BaseModel): - token: str = Field(default="NESTED-SECRET", examples=["EXAMPLE-SECRET"]) - kind: Literal["CONST-SECRET"] = "CONST-SECRET" + token: str = Field(default="NESTED-CANARY", examples=["EXAMPLE-CANARY"]) + kind: Literal["CONST-CANARY"] = "CONST-CANARY" + choice: SecretChoice + constrained: Annotated[str, Field(pattern="PATTERN-CANARY")] -def test_sensitive_schemas_strip_examples_defaults_and_const_in_definitions(): +def test_sensitive_schemas_strip_values_from_referenced_definitions(): class Safe(Extension): - @action(sensitive_parameters=frozenset({"credentials"})) + @function(sensitive_parameters=("credentials",)) async def login( self, credentials: Annotated[ - SecretInput, Field(examples=[{"token": "ROOT-SECRET"}]) + SecretInput, Field(examples=[{"token": "ROOT-CANARY"}]) ], count: int = 3, ) -> None: """Use credentials without publishing examples.""" - for audience in ("python", "operator", "cli"): - schema = Safe().actions.list(audience=audience)[0].input_schema - assert "SECRET" not in json.dumps(schema) - assert schema["properties"]["count"]["default"] == 3 - - -@pytest.mark.parametrize("bound", [False, True]) -def test_sensitive_action_redacts_sdk_logs_and_nested_sensitive_calls(caplog, bound): - logger = logging.getLogger("review.mock_sdk") - - class Resource(Extension): - @action(sensitive_parameters=frozenset({"password"})) - async def login(self, password: str) -> None: - """Make an SDK request that logs its password.""" - logger.warning("request password=%s", password) - if hasattr(self, "outer_value"): - logger.warning("nested outer=%s inner=%s", self.outer_value, password) - - @action(sensitive_parameters=frozenset({"credentials"})) - async def outer(self, credentials: dict[str, str]) -> None: - """Keep outer secrets active through an inner sensitive action.""" - self.outer_value = credentials["password"] - await self.login("INNER-CANARY") - del self.outer_value - logger.warning("outer password=%s", credentials["password"]) - - async def scenario(): - resource = Resource() - phone = MemoryDevice() - if bound: - await resource.bind(phone) - await resource.login("DIRECT-CANARY") - await resource.outer({"password": "OUTER-CANARY"}) - await resource.actions.call("extension.login", {"password": "CATALOG-CANARY"}) - await phone.close() - await resource.close() - - with caplog.at_level(logging.WARNING): - asyncio.run(scenario()) - assert len(caplog.records) == 5 - assert all("CANARY" not in record.getMessage() for record in caplog.records) - assert all("***" in record.getMessage() for record in caplog.records) - # The context must not permanently redact unrelated later log records. - logger.warning("outside password=%s", "DIRECT-CANARY") - assert "DIRECT-CANARY" in caplog.records[-1].getMessage() - - -class SecretChoice(str, Enum): - FIRST = "ENUM-CANARY-ONE" - SECOND = "ENUM-CANARY-TWO" - - -class SecretConstraints(BaseModel): - literal: Literal["LITERAL-CANARY-ONE", "LITERAL-CANARY-TWO"] - choice: SecretChoice - token: Annotated[str, Field(pattern="PATTERN-CANARY")] + (tool,) = compile_tools([Safe()]) + assert "CANARY" not in json.dumps(tool.input_schema) + assert tool.input_schema["properties"]["count"]["default"] == 3 def test_sensitive_enum_registers_the_underlying_value(caplog): class Resource(Extension): - @action(sensitive_parameters=frozenset({"choice"})) + @function(sensitive_parameters=("choice",)) async def use(self, choice: SecretChoice) -> None: """Simulate an SDK serializing an enum into its request log.""" - logging.getLogger("review.mock_sdk").warning( - "request value=%s", choice.value - ) + logging.getLogger(__name__).warning("request value=%s", choice.value) asyncio.run(Resource().use(SecretChoice.FIRST)) assert "ENUM-CANARY" not in caplog.text assert "***" in caplog.text -def test_sensitive_schema_strips_enum_literal_and_pattern_from_referenced_defs(): - class Resource(Extension): - @action(sensitive_parameters=frozenset({"secret"})) - async def use(self, secret: SecretConstraints) -> None: - """Accept constrained secret inputs without publishing their values.""" - - import json - - for audience in ("python", "operator", "cli"): - schema = Resource().actions.list(audience=audience)[0].input_schema - assert "CANARY" not in json.dumps(dict(schema)) - assert "enum" not in json.dumps(dict(schema)) - assert "pattern" not in json.dumps(dict(schema)) - - -def test_wrapper_copy_and_pickle_are_explicitly_rejected(): - wrapper = DeviceWrapper(MemoryDevice()) - for operation in (copy.copy, copy.deepcopy, pickle.dumps): - with pytest.raises(TypeError, match="copied or pickled"): - operation(wrapper) - partial = DeviceWrapper.__new__(DeviceWrapper) - with pytest.raises(AttributeError): - partial.__getattr__("missing") - - -def test_device_has_no_typed_get_api(): - with pytest.raises(AttributeError): - _ = MemoryDevice().get - - -@pytest.mark.parametrize( - ("role", "default", "attribute"), - [("phone_number", "sms", "number"), ("mailbox", "email", "mailbox")], -) -def test_resource_lookup_uses_declared_roles_and_default_names( - role, default, attribute -): - selected_role = role +def test_nested_sensitive_functions_mask_both_scopes_without_leaking(caplog): + logger = logging.getLogger(__name__) class Resource(Extension): - role = selected_role + @function(sensitive_parameters=("outer_value",)) + async def outer(self, outer_value: str) -> None: + await self.inner("INNER-CANARY", outer_value) - async def scenario(): - phone = MemoryDevice() - first = Resource(name="first") - second = Resource(name="second") - preferred = Resource(name=default) - unrelated = Extension(name=default) - await unrelated.bind(phone) - with pytest.raises(DeviceOperationNotSupported, match="No"): - getattr(phone, attribute) - await first.bind(phone) - assert getattr(phone, attribute) is first - await second.bind(phone) - with pytest.raises(DeviceOperationNotSupported, match="Multiple"): - getattr(phone, attribute) - await unrelated.unbind() - await preferred.bind(phone) - assert getattr(phone, attribute) is preferred - await phone.close() + @function(sensitive_parameters=("value",)) + async def inner(self, value: str, outer_value: str) -> None: + logger.warning("nested outer=%s inner=%s", outer_value, value) - asyncio.run(scenario()) + resource = Resource() + tool = next( + tool for tool in compile_tools([resource]) if tool.name.endswith(".outer") + ) + asyncio.run(tool.invoke({"outer_value": "OUTER-CANARY"})) + assert [record.getMessage() for record in caplog.records] == [ + "nested outer=*** inner=***" + ] + logger.warning("outside=%s", "OUTER-CANARY") + assert caplog.records[-1].getMessage() == "outside=OUTER-CANARY" def test_cloud_task_reference_validation_checks_fields_not_concrete_class(): @@ -982,3 +137,16 @@ class Reference: assert inputs.credential_references[0] is reference with pytest.raises(TypeError): CloudTaskInputs((cast(CloudCredentialReference, object()),)) + + +def test_extension_contract_rejects_extra_value_fields_in_task_inputs(): + @dataclass(frozen=True) + class UnsafeInputs(CloudTaskInputs): + value: str = "private-canary" + + class Unsafe(Extension): + async def cloud_task_inputs(self) -> CloudTaskInputs: + return UnsafeInputs() + + with pytest.raises(AssertionError, match="references only"): + asyncio.run(check_extension_contract(Unsafe())) diff --git a/tests/unit/core/extensions/test_tools.py b/tests/unit/core/extensions/test_tools.py new file mode 100644 index 000000000..62b123899 --- /dev/null +++ b/tests/unit/core/extensions/test_tools.py @@ -0,0 +1,574 @@ +import asyncio +import logging +from dataclasses import dataclass +from typing import Annotated, Literal + +import pytest +from pydantic import BaseModel, Field, field_validator + +from mobilerun.core import extensions +from mobilerun.core.extensions import bind_atomic +from mobilerun.core.operator import Operator + + +class Payload(BaseModel): + value: int + + +@dataclass +class Report: + count: int + + +def test_decorated_method_exposes_schemas_and_invokes_with_typed_arguments(): + class Mail(extensions.Extension): + @extensions.function + async def summarize( + self, + query: str, + limit: int, + ratio: float, + unread: bool, + labels: list[str], + payload: Payload, + report: Report, + folder: Literal["inbox", "drafts"] = "inbox", + skip: int | None = None, + ) -> Report: + """Summarize matching messages. + Include the selected folder. + + This paragraph is not shown to the agent. + """ + return Report(payload.value + report.count) + + async def hidden(self) -> None: + raise AssertionError("not a tool") + + (tool,) = Operator(extensions=[Mail(name="mail")]).tools() + assert isinstance(tool, extensions.Tool) + assert tool.name == "mail.summarize" + assert ( + tool.description == "Summarize matching messages. Include the selected folder." + ) + schema = tool.input_schema + props = schema["properties"] + assert schema["additionalProperties"] is False + assert schema["required"] == [ + "query", + "limit", + "ratio", + "unread", + "labels", + "payload", + "report", + ] + assert { + name: props[name]["type"] + for name in ("query", "limit", "ratio", "unread", "labels") + } == { + "query": "string", + "limit": "integer", + "ratio": "number", + "unread": "boolean", + "labels": "array", + } + assert props["labels"]["items"] == {"type": "string"} + assert props["folder"]["enum"] == ["inbox", "drafts"] + assert props["folder"]["default"] == "inbox" + assert props["skip"]["anyOf"] == [{"type": "integer"}, {"type": "null"}] + assert schema["$defs"]["Payload"]["properties"]["value"]["type"] == "integer" + assert tool.output_schema["properties"]["count"]["type"] == "integer" + assert asyncio.run( + tool.invoke( + dict( + query="go", + limit=1, + ratio=0.5, + unread=True, + labels=["work"], + payload={"value": 4}, + report={"count": 2}, + ) + ) + ) == {"count": 6} + + +@pytest.mark.parametrize( + "arguments", [{}, {"count": "1"}, {"count": 1, "extra": True}, []] +) +def test_input_rejected_before_call(arguments): + class Counter(extensions.Extension): + @extensions.function() + async def set_count(self, count: int) -> None: + pytest.fail("invalid arguments reached the body") + + (tool,) = Operator(extensions=[Counter()]).tools() + with pytest.raises(extensions.ToolArgumentsError, match="extension.set_count"): + asyncio.run(tool.invoke(arguments)) + + +def test_sensitive_values_are_not_in_errors_logs_reprs_or_schema(caplog): + secret = "test-secret-canary-282" + + class Vault(extensions.Extension): + @extensions.function(sensitive_parameters=("value",)) + async def put(self, value: list[Literal["test-secret-canary-282"]]) -> None: + logging.getLogger(__name__).warning("writing %s", value) + raise ValueError(value) + + vault = Vault(name="vault") + (tool,) = Operator(extensions=[vault]).tools() + assert tool.sensitive_parameters == frozenset({"value"}) + for operation in (tool.invoke({"value": [secret]}), vault.put([secret])): + with pytest.raises(extensions.ToolInvocationError) as captured: + asyncio.run(operation) + assert captured.value.__context__ is None + assert captured.value.__cause__ is None + assert secret not in str(captured.value) + repr(captured.value) + with pytest.raises(extensions.ToolArgumentsError) as captured: + asyncio.run(tool.invoke({"value": secret})) + assert captured.value.__context__ is None + assert ( + secret + not in repr(captured.value) + repr(tool) + repr(tool.input_schema) + caplog.text + ) + + +@pytest.mark.parametrize( + "alias_kind", ["alias", "validation_alias", "serialization_alias"] +) +def test_sensitive_tool_parameter_rejects_pydantic_alias(alias_kind): + canary = "synthetic-tool-schema-example" + + class Vault(extensions.Extension): + @extensions.function(sensitive_parameters=("password",)) + async def put( + self, + password: Annotated[str, Field(examples=[canary], **{alias_kind: "token"})], + ) -> None: + pass + + with pytest.raises( + extensions.ToolCompilationError, match="Invalid tool for 'vault.put'" + ) as caught: + extensions.compile_tools([Vault(name="vault")]) + if canary in str(caught.value): + pytest.fail("Compilation exposed a sensitive example", pytrace=False) + assert caught.value.__context__ is None + + +def test_public_tool_parameter_accepts_pydantic_alias(): + class Search(extensions.Extension): + @extensions.function + async def count(self, query: Annotated[str, Field(alias="q")]) -> int: + return len(query) + + (tool,) = extensions.compile_tools([Search()]) + assert set(tool.input_schema["properties"]) == {"q"} + assert asyncio.run(tool.invoke({"q": "sample"})) == 6 + + +def test_wrong_output_is_a_safe_invocation_error(): + class Bad(extensions.Extension): + @extensions.function + async def count(self) -> int: + return "wrong output canary" + + (tool,) = Operator(extensions=[Bad()]).tools() + with pytest.raises(extensions.ToolInvocationError) as captured: + asyncio.run(tool.invoke({})) + assert "wrong output canary" not in repr(captured.value) + assert captured.value.__context__ is None + + +def test_validate_arguments_returns_typed_values_without_dispatch(): + class Counter(extensions.Extension): + @extensions.function + async def update(self, payload: Payload, multiplier: int = 2) -> None: + pytest.fail("preflight invoked the tool") + + def reject_dispatch(info): + pytest.fail(f"preflight attempted to dispatch {info.name}") + + (tool,) = extensions.compile_tools([Counter()]) + with extensions.tool_dispatch_guard(reject_dispatch): + values = dict(tool.validate_arguments({"payload": {"value": 4}})) + assert isinstance(values["payload"], Payload) + assert values == {"payload": Payload(value=4), "multiplier": 2} + + +@pytest.mark.parametrize("render", [repr, str], ids=["repr", "str"]) +def test_validated_sensitive_value_is_hidden_but_still_dispatched(render): + canary = "validated-argument-canary" + + class Vault(extensions.Extension): + @extensions.function(sensitive_parameters=("password",)) + async def check(self, password: str, attempts: int = 2) -> bool: + return password == canary and attempts == 2 + + (tool,) = Operator(extensions=[Vault()]).tools() + arguments = {"password": canary} + parsed = tool.validate_arguments(arguments) + if canary in render(parsed): + pytest.fail("Validated arguments exposed a sensitive value", pytrace=False) + assert "attempts=2" in render(parsed) + assert asyncio.run(tool.invoke(arguments)) is True + + +@pytest.mark.parametrize("invoke", [False, True]) +def test_sensitive_values_are_masked_during_input_validation(caplog, invoke): + class SecretPayload(BaseModel): + value: str + + @field_validator("value") + @classmethod + def report(cls, value): + logging.getLogger(__name__).warning("validating %s", value) + raise ValueError(value) + + class Vault(extensions.Extension): + @extensions.function(sensitive_parameters=("token",)) + async def put(self, token: SecretPayload) -> None: + pytest.fail("invalid input reached the body") + + (tool,) = Operator(extensions=[Vault()]).tools() + arguments = {"token": {"value": "validation-canary-283"}} + with pytest.raises(extensions.ToolArgumentsError) as captured: + if invoke: + asyncio.run(tool.invoke(arguments)) + else: + tool.validate_arguments(arguments) + assert captured.value.__context__ is None + assert "validation-canary-283" not in str(captured.value) + assert "validation-canary-283" not in caplog.text + + +def test_atomic_tools_replace_parent_in_order_and_keep_canonical_identity(): + calls = [] + compiled = [] + + def aliases(bound): + compiled.append(bound.__self__) + + async def github() -> None: + """Type the GitHub credential.""" + await bound("github") + + @extensions.function(name="gmail", description="Type the Gmail credential.") + async def narrowed() -> None: + await bound("gmail") + + return github, narrowed + + class Vault(extensions.Extension): + @extensions.function(name="start", description="Start typing.") + async def begin(self) -> None: + pass + + @extensions.function(to_atomic=aliases, sensitive_parameters=("name",)) + async def type_secret(self, name: str) -> None: + calls.append(name) + + @extensions.function(to_atomic=lambda _: ()) + async def suppressed(self) -> None: + pass + + vault = Vault(name="vault") + other = Vault(name="other") + tools = Operator(extensions=[vault, other]).tools() + assert [tool.name for tool in tools] == [ + "vault.start", + "vault.github", + "vault.gmail", + "other.start", + "other.github", + "other.gmail", + ] + assert tools[0].description == "Start typing." + assert tools[1].description == "Type the GitHub credential." + assert tools[2].description == "Type the Gmail credential." + assert tools[1].canonical_name == "vault.type_secret" + assert tools[0].bound_arguments is None + assert tools[1].is_atomic and tools[1].bound_arguments is None + assert tools[1].sensitive_parameters == frozenset({"name"}) + assert tools[1].input_schema["properties"] == {} + assert tools[1].output_schema == {"type": "null"} + for tool in tools[1:3]: + assert asyncio.run(tool.invoke({})) is None + assert compiled == [vault, other] + assert calls == ["github", "gmail"] + canonical = extensions.compile_tools([vault], expand_atomics=False) + assert [tool.name for tool in canonical] == [ + "vault.start", + "vault.type_secret", + "vault.suppressed", + ] + assert compiled == [vault, other] + asyncio.run(canonical[1].invoke({"name": "python"})) + assert calls[-1] == "python" + + +@pytest.mark.parametrize("count", [2, "2"]) +def test_bound_atomic_arguments_are_validated_and_safe(count): + canary = "atomic-input-canary" + + def aliases(bound): + async def pick() -> bool: + return await bound(count=count, token=canary, labels=["work"]) + + return ( + bind_atomic(pick, {"count": count, "token": canary, "labels": ["work"]}), + ) + + class Vault(extensions.Extension): + @extensions.function(to_atomic=aliases, sensitive_parameters=("token",)) + async def check(self, count: int, token: str, labels: list[str]) -> bool: + return count == 2 and token == canary and labels == ["work"] + + if isinstance(count, str): + with pytest.raises( + extensions.ToolCompilationError, match="Invalid atomic expansion" + ): + extensions.compile_tools([Vault()]) + return + (tool,) = extensions.compile_tools([Vault()]) + assert tool.is_atomic and tool.bound_arguments == { + "count": 2, + "token": "***", + "labels": ["work"], + } + with pytest.raises(TypeError): + tool.bound_arguments["count"] = 3 + tool.bound_arguments["labels"].append("changed") + assert tool.bound_arguments["labels"] == ["work"] + assert "work" not in repr(tool) and canary not in repr(tool) + assert asyncio.run(tool.invoke({})) is True + + +def test_bound_atomic_arguments_keep_wire_alias_without_defaults(): + def aliases(bound): + async def ready() -> str: + return await bound("ok") + + return (bind_atomic(ready, {"wireText": "ok"}),) + + class Service(extensions.Extension): + @extensions.function(to_atomic=aliases) + async def send( + self, + text: Annotated[ + str, Field(validation_alias="wireText", serialization_alias="outText") + ], + suffix: str = "!", + ) -> str: + return text + suffix + + service = Service() + (atomic,) = extensions.compile_tools([service]) + (canonical,) = extensions.compile_tools([service], expand_atomics=False) + assert asyncio.run(atomic.invoke({})) == "ok!" + assert atomic.bound_arguments == {"wireText": "ok"} + assert asyncio.run(canonical.invoke(atomic.bound_arguments)) == "ok!" + + +def test_guard_sees_value_free_alias_and_nested_canonical_call(): + calls = [] + guarded = [] + + def alias(bound): + async def choice() -> None: + await bound("not in guard metadata") + + return (choice,) + + class Vault(extensions.Extension): + @extensions.function(to_atomic=alias, sensitive_parameters=("name",)) + async def secret(self, name: str) -> None: + calls.append(name) + + (tool,) = Operator(extensions=[Vault(name="vault")]).tools() + with extensions.tool_dispatch_guard(guarded.append): + asyncio.run(tool.invoke({})) + assert [ + (info.name, info.canonical_name, info.sensitive_parameters) for info in guarded + ] == [ + ("vault.choice", "vault.secret", frozenset({"name"})), + ("vault.secret", "vault.secret", frozenset({"name"})), + ] + assert "not in guard metadata" not in repr(guarded) + assert len(calls) == 1 + + +def test_direct_typed_call_cannot_bypass_dispatch_guard(): + class Vault(extensions.Extension): + @extensions.function + async def disallowed(self) -> None: + pytest.fail("guard failed to stop direct call") + + def deny(info): + raise PermissionError(info.name) + + with ( + extensions.tool_dispatch_guard(deny), + pytest.raises(PermissionError, match="extension.disallowed"), + ): + asyncio.run(Vault().disallowed()) + + +def test_atomic_alias_with_same_name_as_replaced_parent_is_still_guarded(): + def select(bound): + async def pick() -> str: + pytest.fail("guard failed to stop alias") + + return (pick,) + + class Vault(extensions.Extension): + @extensions.function(to_atomic=select) + async def pick(self, name: str) -> str: + return name + + def deny(info): + raise PermissionError(info.name) + + (tool,) = Operator(extensions=[Vault()]).tools() + with ( + extensions.tool_dispatch_guard(deny), + pytest.raises(PermissionError, match="extension.pick"), + ): + asyncio.run(tool.invoke({})) + + +def test_attribute_override_must_opt_in_and_discovery_does_not_run_properties(): + class Parent(extensions.Extension): + @extensions.function + async def inherited(self) -> None: + pass + + @extensions.function + async def opt_out(self) -> None: + pass + + class Child(Parent): + async def opt_out(self) -> None: + pass + + @property + def property_that_must_not_run(self): + pytest.fail("discovery evaluated a property") + + @extensions.function + async def last(self) -> None: + pass + + assert [tool.name for tool in Operator(extensions=[Child()]).tools()] == [ + "extension.inherited", + "extension.last", + ] + + +def test_sync_function_is_rejected(): + with pytest.raises(TypeError, match="async"): + + @extensions.function + def sync_method(self) -> None: + pass + + +async def with_default(value: int = 1) -> None: + pass + + +async def unnamed() -> None: + pass + + +unnamed.__name__ = "" + + +def broken_factory(_): + raise ValueError("do not show factory exception") + + +@pytest.mark.parametrize( + "factory", + [ + lambda _: None, + lambda _: (object(),), + lambda _: (with_default,), + lambda _: (unnamed,), + lambda _: (lambda: None,), + broken_factory, + ], +) +def test_invalid_atomic_expansion_names_the_owner(factory): + class Vault(extensions.Extension): + @extensions.function(to_atomic=factory) + async def type_secret(self, name: str) -> None: + pass + + with pytest.raises( + extensions.ToolCompilationError, match="vault.type_secret" + ) as captured: + Operator(extensions=[Vault(name="vault")]).tools() + assert "do not show factory exception" not in repr(captured.value) + assert captured.value.__context__ is None + + +def test_duplicate_tool_names_report_both_owners(): + class First(extensions.Extension): + @extensions.function(name="same") + async def one(self) -> None: + pass + + class Second(extensions.Extension): + @extensions.function(name="same") + async def two(self) -> None: + pass + + with pytest.raises( + extensions.ToolCompilationError, match=r"mail.same.*First.one.*Second.two" + ): + Operator(extensions=[First(name="mail"), Second(name="mail")]).tools() + + +@pytest.mark.parametrize("expand_atomics", [True, False]) +def test_distinct_atomic_aliases_do_not_hide_duplicate_canonical_names(expand_atomics): + async def first_alias() -> None: + pass + + async def second_alias() -> None: + pass + + class Vault(extensions.Extension): + @extensions.function(name="same", to_atomic=lambda _: (first_alias,)) + async def one(self) -> None: + pass + + @extensions.function(name="same", to_atomic=lambda _: (second_alias,)) + async def two(self) -> None: + pass + + with pytest.raises( + extensions.ToolCompilationError, match=r"vault.same.*Vault.one.*Vault.two" + ): + extensions.compile_tools([Vault(name="vault")], expand_atomics=expand_atomics) + + +def test_duplicate_visible_alias_names_still_report_both_owners(): + async def alias() -> None: + pass + + class Vault(extensions.Extension): + @extensions.function(to_atomic=lambda _: (alias,)) + async def one(self) -> None: + pass + + @extensions.function(to_atomic=lambda _: (alias,)) + async def two(self) -> None: + pass + + with pytest.raises( + extensions.ToolCompilationError, match=r"vault.alias.*Vault.one.*Vault.two" + ): + Operator(extensions=[Vault(name="vault")]).tools() diff --git a/tests/unit/core/mailbox/test_messages.py b/tests/unit/core/mailbox/test_messages.py index c47a314c1..039681550 100644 --- a/tests/unit/core/mailbox/test_messages.py +++ b/tests/unit/core/mailbox/test_messages.py @@ -15,14 +15,14 @@ ) from mobilerun.cli.app import cli -from mobilerun.clients.cloud import mailboxes, numbers +from mobilerun.clients.cloud import numbers +from mobilerun.clients.cloud.mailboxes import Mailboxes +from mobilerun.core.extensions import ToolInvocationError, compile_tools from mobilerun.core.mailbox import CloudMailbox from mobilerun.core.phone_number import CloudPhoneNumber from mobilerun.errors import PaymentRequired, PurchaseInProgress from mobilerun.models.billing import Billing from mobilerun.models.checkout import Checkout -from tests.support.devices import MemoryDevice -from tests.support.extensions import check_extension_contract def message(id="msg-1"): @@ -48,7 +48,7 @@ def test_mailbox_messages_paginates_and_uses_existing_client(): mailboxes=SimpleNamespace(messages=SimpleNamespace(list=listing)) ) result = asyncio.run( - mailboxes.messages("box-1", billing=Billing.NO_COMMERCE, client=client) + Mailboxes(billing=Billing.NO_COMMERCE, client=client).messages("box-1") ) assert [item.id for item in result] == ["msg-1", "msg-2"] assert listing.await_args_list[1].kwargs["cursor"] == "next" @@ -57,7 +57,7 @@ def test_mailbox_messages_paginates_and_uses_existing_client(): @pytest.mark.parametrize("populated", [True, False], ids=["populated", "empty"]) def test_mailbox_messages_cli_json_and_text(monkeypatch, populated): monkeypatch.setattr( - mailboxes, "messages", AsyncMock(return_value=[message()] if populated else []) + Mailboxes, "messages", AsyncMock(return_value=[message()] if populated else []) ) runner = CliRunner() args = ["mailbox", "messages", "box-1"] @@ -79,28 +79,58 @@ def test_mailbox_messages_cli_json_and_text(monkeypatch, populated): assert "messages" in result.output.lower() -def test_mailbox_extension_contract(): - async def device(): - return MemoryDevice() - - asyncio.run( - check_extension_contract(lambda name: CloudMailbox("id", name=name), device) - ) - - -def test_mailbox_code_and_context(): +def test_standalone_mailbox_tools_return_code_only_to_caller(caplog): async def run(): mailbox = CloudMailbox("id") mailbox._address = "test@example.com" - await mailbox.bind(MemoryDevice()) + tools = {tool.name: tool for tool in compile_tools([mailbox])} + assert set(tools) == {"email.messages", "email.wait_for_code"} with patch( - "mobilerun.core.mailbox.cloud.mailboxes.otp", + "mobilerun.clients.cloud.mailboxes.Mailboxes.otp", AsyncMock( - return_value=SimpleNamespace(data=SimpleNamespace(code="123456")) + return_value=SimpleNamespace(data=SimpleNamespace(code="482913")) ), ): - assert await mailbox.wait_for_code() == "123456" + assert await mailbox.wait_for_code() == "482913" + assert await tools["email.wait_for_code"].invoke({}) == "482913" + with patch.object(Mailboxes, "messages", AsyncMock(return_value=[message()])): + history = await tools["email.messages"].invoke({}) + assert isinstance(history, list) and history[0]["id"] == "msg-1" assert "test@example.com" in repr(await mailbox.context()) + assert "482913" not in repr(await mailbox.context()) + caplog.text + await mailbox.close() + + asyncio.run(run()) + + +def test_mailbox_tool_error_does_not_expose_provider_code(caplog): + async def run(): + mailbox = CloudMailbox("id", name="inbox") + tool = next( + t for t in compile_tools([mailbox]) if t.name == "inbox.wait_for_code" + ) + with patch.object( + Mailboxes, "otp", AsyncMock(side_effect=RuntimeError("482913")) + ): + with pytest.raises(ToolInvocationError) as caught: + await tool.invoke({}) + assert caught.value.__context__ is None + assert "482913" not in str(caught.value) + caplog.text + + asyncio.run(run()) + + +def test_closed_mailbox_rejects_precompiled_tools(): + async def run(): + mailbox = CloudMailbox("id") + tools = {tool.name: tool for tool in compile_tools([mailbox])} + await mailbox.close() + with patch.object( + Mailboxes, "otp", AsyncMock(return_value=SimpleNamespace(data=None)) + ) as otp: + with pytest.raises(ToolInvocationError): + await tools["email.wait_for_code"].invoke({"timeout": 0.01}) + otp.assert_not_awaited() asyncio.run(run()) @@ -116,7 +146,7 @@ def _data(status, address=None): async def _payment_error(monkeypatch): checkout = Checkout("https://checkout.test", None, "mailbox", "mailbox-id") monkeypatch.setattr( - mailboxes, + Mailboxes, "create", AsyncMock(side_effect=PaymentRequired(checkout, AsyncMock())), ) @@ -131,7 +161,7 @@ async def run(): retrieve = AsyncMock( side_effect=[_data("active"), _data("active", "ready@example.test")] ) - monkeypatch.setattr(mailboxes, "retrieve", retrieve) + monkeypatch.setattr(Mailboxes, "retrieve", retrieve) result = await error.wait_until_paid(timeout=2) assert result.address == "ready@example.test" assert retrieve.await_count == 2 @@ -143,10 +173,10 @@ def test_resume_timeout_keeps_mailbox(monkeypatch): async def run(): error = await _payment_error(monkeypatch) monkeypatch.setattr( - mailboxes, "retrieve", AsyncMock(return_value=_data("active")) + Mailboxes, "retrieve", AsyncMock(return_value=_data("active")) ) delete = AsyncMock() - monkeypatch.setattr(mailboxes, "delete", delete) + monkeypatch.setattr(Mailboxes, "delete", delete) with pytest.raises(TimeoutError, match="mailbox-id"): await error.wait_until_paid(timeout=0.01) delete.assert_not_awaited() @@ -158,7 +188,7 @@ def test_resume_terminal_state_is_clear(monkeypatch): async def run(): error = await _payment_error(monkeypatch) monkeypatch.setattr( - mailboxes, "retrieve", AsyncMock(return_value=_data("archived")) + Mailboxes, "retrieve", AsyncMock(return_value=_data("archived")) ) with pytest.raises(RuntimeError, match="archived"): await error.wait_until_paid(timeout=1) @@ -170,7 +200,7 @@ def test_resume_payment_and_address_share_one_timeout(monkeypatch): async def run(): error = await _payment_error(monkeypatch) retrieve = AsyncMock(side_effect=[_data("awaiting_payment"), _data("active")]) - monkeypatch.setattr(mailboxes, "retrieve", retrieve) + monkeypatch.setattr(Mailboxes, "retrieve", retrieve) started = asyncio.get_running_loop().time() with pytest.raises(TimeoutError, match="mailbox-id"): await error.wait_until_paid(timeout=1.1) @@ -206,8 +236,8 @@ async def run(): ) ) with pytest.raises(PurchaseInProgress) as caught: - await numbers.create( - billing=Billing.PAID, client=sdk, country="US", label="work" + await numbers.Numbers(billing=Billing.PAID, client=sdk).create( + country="US", label="work" ) assert caught.value.resource_id == "pending-id" assert caught.value.checkout.url == "https://checkout.test/pay" @@ -218,7 +248,7 @@ async def run(): def test_new_mailbox_waits_for_active_address(monkeypatch): async def run(): monkeypatch.setattr( - mailboxes, + Mailboxes, "create", AsyncMock( return_value=SimpleNamespace( @@ -232,7 +262,7 @@ async def run(): ), ) monkeypatch.setattr( - mailboxes, + Mailboxes, "retrieve", AsyncMock( return_value=SimpleNamespace( @@ -257,7 +287,7 @@ async def run(): "https://checkout.test/pay", None, "phone number", "pending-id" ) monkeypatch.setattr( - numbers, + numbers.Numbers, "create", AsyncMock(side_effect=PurchaseInProgress("pending-id", checkout)), ) @@ -268,10 +298,12 @@ async def run(): device_binding=None, ) monkeypatch.setattr( - numbers, "retrieve", AsyncMock(return_value=SimpleNamespace(data=data)) + numbers.Numbers, + "retrieve", + AsyncMock(return_value=SimpleNamespace(data=data)), ) delete = AsyncMock() - monkeypatch.setattr(numbers, "delete", delete) + monkeypatch.setattr(numbers.Numbers, "delete", delete) callback = AsyncMock() number = await CloudPhoneNumber(billing="paid", on_checkout=callback) assert number.id == "pending-id" @@ -289,12 +321,12 @@ async def run(): "https://checkout.test/pay", None, "phone number", "pending-id" ) monkeypatch.setattr( - numbers, + numbers.Numbers, "create", AsyncMock(side_effect=PurchaseInProgress("pending-id", checkout)), ) delete = AsyncMock() - monkeypatch.setattr(numbers, "delete", delete) + monkeypatch.setattr(numbers.Numbers, "delete", delete) async def slow(_checkout): await asyncio.sleep(1) @@ -314,13 +346,13 @@ async def run(): id="mailbox", status="provisioning", address=None, checkout_url=None ) monkeypatch.setattr( - mailboxes, "create", AsyncMock(return_value=SimpleNamespace(data=data)) + Mailboxes, "create", AsyncMock(return_value=SimpleNamespace(data=data)) ) monkeypatch.setattr( - mailboxes, "retrieve", AsyncMock(return_value=SimpleNamespace(data=data)) + Mailboxes, "retrieve", AsyncMock(return_value=SimpleNamespace(data=data)) ) delete = AsyncMock() - monkeypatch.setattr(mailboxes, "delete", delete) + monkeypatch.setattr(Mailboxes, "delete", delete) with pytest.raises(TimeoutError, match="mailbox"): await CloudMailbox(billing="paid", ready_timeout=0.001) delete.assert_not_awaited() @@ -366,7 +398,6 @@ async def run(): ) ) mailbox = await CloudMailbox(client=sdk, billing="paid", ready_timeout=1) - await mailbox.bind(MemoryDevice()) assert await mailbox.wait_for_code(timeout=1) == "012345" asyncio.run(run()) @@ -379,10 +410,10 @@ async def run(): id="mailbox", status=status, address=None, checkout_url=None ) monkeypatch.setattr( - mailboxes, "create", AsyncMock(return_value=SimpleNamespace(data=data)) + Mailboxes, "create", AsyncMock(return_value=SimpleNamespace(data=data)) ) monkeypatch.setattr( - mailboxes, "retrieve", AsyncMock(return_value=SimpleNamespace(data=data)) + Mailboxes, "retrieve", AsyncMock(return_value=SimpleNamespace(data=data)) ) with pytest.raises(RuntimeError, match=status): await CloudMailbox(billing="paid", ready_timeout=1) @@ -393,7 +424,7 @@ async def run(): def test_resuming_without_checkout_raises_typed_conflict(monkeypatch): async def run(): monkeypatch.setattr( - numbers, + numbers.Numbers, "create", AsyncMock(side_effect=PurchaseInProgress("pending", None)), ) @@ -439,7 +470,7 @@ async def run(): with pytest.raises( CloudConflict if ambiguous else PurchaseInProgress ) as caught: - await numbers.create(billing=Billing.PAID, client=sdk) + await numbers.Numbers(billing=Billing.PAID, client=sdk).create() if ambiguous: assert not isinstance(caught.value, PurchaseInProgress) else: @@ -453,12 +484,12 @@ def test_cancelled_resume_does_not_delete(monkeypatch): async def run(): checkout = Checkout("https://checkout.test", None, "phone number", "pending") monkeypatch.setattr( - numbers, + numbers.Numbers, "create", AsyncMock(side_effect=PurchaseInProgress("pending", checkout)), ) delete = AsyncMock() - monkeypatch.setattr(numbers, "delete", delete) + monkeypatch.setattr(numbers.Numbers, "delete", delete) callback = AsyncMock(side_effect=asyncio.CancelledError()) with pytest.raises(asyncio.CancelledError): await CloudPhoneNumber(billing="paid", on_checkout=callback) @@ -468,22 +499,18 @@ async def run(): def test_payment_failure_does_not_disclose_server_text(): - from mobilerun.clients.cloud.payments import ( - PaymentAdapter, - wait_until_active, - ) + from mobilerun.clients.cloud.payments import PaymentFlow from mobilerun.errors import CloudError from mobilerun.models.checkout import PaymentSnapshot async def run(): - adapter = PaymentAdapter( + adapter = PaymentFlow( "phone", "id", AsyncMock(return_value=PaymentSnapshot("server-secret-canary")), - AsyncMock(), ) with pytest.raises(CloudError) as caught: - await wait_until_active(adapter) + await adapter.wait_until_active() assert "server-secret-canary" not in str(caught.value) assert caught.value.status == "server-secret-canary" assert caught.value.value_safe @@ -491,8 +518,8 @@ async def run(): asyncio.run(run()) -def test_cloud_error_allows_support_request_id_but_not_response_body(): - from mobilerun.clients.cloud.errors import cloud_error +def test_cloud_error_drops_server_request_id_and_response_body(): + from mobilerun.clients.cloud.errors import CloudErrorMapper response = httpx.Response( 400, @@ -504,33 +531,7 @@ def test_cloud_error_allows_support_request_id_but_not_response_body(): response=response, body={"message": "server-secret-canary"}, ) - error = cloud_error(sdk_error, "Create number") - assert "support-request-id" in str(error) + error = CloudErrorMapper.from_exception(sdk_error, "Create number") + assert error.request_id is None and "support-request-id" not in str(error) assert "server-secret-canary" not in str(error) assert error.value_safe - - -def test_cloud_error_action_passthrough_does_not_expose_response_body(): - from mobilerun.clients.cloud.errors import cloud_error - from mobilerun.core.extensions import Extension, action - from mobilerun.errors import CloudValidationError - - class Resource(Extension): - @action - async def run(self) -> None: - """Report a sanitized cloud error.""" - response = httpx.Response( - 400, request=httpx.Request("POST", "https://example.test") - ) - raise cloud_error( - APIStatusError( - "private-canary", - response=response, - body={"detail": "private-canary"}, - ), - "Create number", - ) - - with pytest.raises(CloudValidationError) as caught: - asyncio.run(Resource().run()) - assert "private-canary" not in str(caught.value) diff --git a/tests/unit/core/operator/test_operator_execution.py b/tests/unit/core/operator/test_operator_execution.py index 0f6e5fd5d..642e4e5df 100644 --- a/tests/unit/core/operator/test_operator_execution.py +++ b/tests/unit/core/operator/test_operator_execution.py @@ -1,32 +1,24 @@ -"""Operator selection, cloud task execution and structured expectations.""" +"""Explicit operator pairing, cloud task execution and structured expectations.""" import ast import asyncio from contextlib import asynccontextmanager +from dataclasses import replace from types import SimpleNamespace -from typing import cast +from typing import TypeVar, cast import httpx import pytest -from mobilerun_sdk import NotFoundError, UnprocessableEntityError +from mobilerun_core import ActionEvent, AsyncDevice +from mobilerun_sdk import AsyncMobilerun, NotFoundError, UnprocessableEntityError from pydantic import BaseModel -import mobilerun.core.operator.cloud as cloud_module -from mobilerun.clients.cloud import tasks as cloud_tasks -from mobilerun.clients.cloud.tasks import run_task -from mobilerun.core.devices import ( - AndroidDevice, - CloudDevice, - Device, - DevicePool, - IOSDevice, - RecordingDevice, - RemoteDevice, - StealthDevice, -) +from mobilerun.clients.cloud.tasks import Tasks as TaskResource +from mobilerun.core.extensions import Extension, function from mobilerun.core.operator import Operator from mobilerun.core.operator.cloud import CloudTaskOperator from mobilerun.errors import ( + BillingRequired, CloudDeviceNotFound, CloudResourceNotFound, CloudTaskTimeout, @@ -37,118 +29,16 @@ OperatorNotAvailable, OperatorNotSupported, ) +from mobilerun.models.cloud_task import CloudCredentialReference, CloudTaskInputs from mobilerun.models.results import ( ExecutionResult, ExpectationResult, ExpectationVerdict, ) -from mobilerun.utils.prompts import PromptLoader, load_prompt_text +from tests.support.devices import FakeDriver, fake_device from tests.support.paths import REPO_ROOT -def test_operator_default_check_is_noop(): - assert Operator().check(Device()) is None - - -def test_device_initializes_extension_registry(): - - device = Device() - assert not device.extensions - assert not hasattr(device, "_mailbox") - assert not hasattr(device, "_placeholder_resources") - - -def test_unwrap_device_stops_before_non_device_driver(): - from mobilerun.core.devices.base import _unwrap_device - from mobilerun.core.devices.components.wrapper import DeviceWrapper - - class WithInner(Device): - inner: object - - inner = WithInner() - inner._inner = object() - outer = DeviceWrapper(inner) - assert _unwrap_device(outer) is inner - - -def test_device_constructor_checks_operator(): - - class RejectingOperator(Operator): - def check(self, device): - raise ValueError("invalid pairing") - - with pytest.raises(ValueError, match="invalid pairing"): - Device(operator=RejectingOperator()) - - -def test_device_rejects_operator_without_check(): - - with pytest.raises(AttributeError, match="check"): - Device(operator=cast(Operator, object())) - - -def test_android_requires_operator(): - - device = AndroidDevice(serial="test", portal_mode="disabled") - with pytest.raises(OperatorNotAvailable): - asyncio.run(device.do("hello")) - - -def test_operator_precedence(): - - class Op(Operator): - def __init__(self, value): - self.value = value - - async def execute( - self, device, instruction, *, output=None, max_steps=None, timeout=None - ): - return self.value - - class DeviceWithDefault(Device): - def _default_operator(self): - return Op("default") - - device = DeviceWithDefault(operator=Op("attached")) - assert asyncio.run(device.do("hello", operator=Op("call"))) == "call" - assert asyncio.run(device.do("hello")) == "attached" - assert asyncio.run(DeviceWithDefault().do("hello")) == "default" - - -def test_operator_base_raises(): - - with pytest.raises( - OperatorNotAvailable, match="from mobilerun_agents import AgentOperator" - ): - asyncio.run(Operator().execute(cast(Device, object()), "hello")) - - -def test_android_expect_uses_attached_operator(): - - class FakeOperator(Operator): - async def execute( - self, device, instruction, *, output=None, max_steps=None, timeout=None - ): - assert output is ExpectationVerdict - return ExecutionResult[ExpectationVerdict]( - success=True, - output=ExpectationVerdict(passed=True, reason="yes"), - device="AndroidDevice", - ) - - device = AndroidDevice( - serial="test", portal_mode="disabled", operator=FakeOperator() - ) - assert asyncio.run(device.expect("visible")).passed - - -def test_cloud_default_operator(): - - assert isinstance( - CloudDevice("id", api_key="test")._default_operator(), CloudTaskOperator - ) - - def test_core_has_no_agent_imports(): for path in (REPO_ROOT / "mobilerun" / "core").rglob("*.py"): @@ -165,57 +55,6 @@ def test_core_has_no_agent_imports(): ), path -def test_constructor_and_attachment_reject_local(): - - with pytest.raises(OperatorNotSupported, match="is not a cloud device"): - AndroidDevice("emulator-5554", operator=CloudTaskOperator()) - assert "attach_operator" not in dir(AndroidDevice) - - -def test_per_call_and_pool_validate(): - - device = AndroidDevice("emulator-5554") - with pytest.raises(OperatorNotSupported): - asyncio.run(device.do("noop", operator=CloudTaskOperator())) - with pytest.raises(OperatorNotSupported): - asyncio.run(device.expect("noop", operator=CloudTaskOperator())) - device._operator = CloudTaskOperator() - with pytest.raises(OperatorNotSupported): - DevicePool([device]) - - -def test_cloud_pairing_works(): - device = CloudDevice("id", api_key="test", operator=CloudTaskOperator()) - assert device._cloud_client is not None - DevicePool([device]) - - -@pytest.mark.parametrize("wrapper", [RecordingDevice, StealthDevice]) -def test_cloud_capability_delegates_through_wrappers(wrapper): - local = AndroidDevice("serial") - cloud = CloudDevice("id", api_key="test") - assert local._is_cloud is False - assert cloud._is_cloud is True - assert wrapper(local)._is_cloud is False - assert wrapper(cloud)._is_cloud is True - CloudTaskOperator().check(wrapper(cloud)) - - -def test_wrappers_validate_inner_device(): - - for wrapper in (RecordingDevice, StealthDevice): - with pytest.raises(OperatorNotSupported): - wrapper(AndroidDevice("emulator-5554"), operator=CloudTaskOperator()) - device = wrapper(AndroidDevice("emulator-5554")) - expected = rf"{wrapper.__name__}\(AndroidDevice\)" - with pytest.raises(OperatorNotSupported, match=expected): - asyncio.run(device.do("noop", operator=CloudTaskOperator())) - device._inner._operator = CloudTaskOperator() - device._operator = device._inner._operator - with pytest.raises(OperatorNotSupported, match=expected): - DevicePool([device]) - - @pytest.mark.parametrize( "status,body,expected", [ @@ -259,12 +98,10 @@ async def run(**kwargs): with pytest.raises(expected, match=f"HTTP {status}") as caught: asyncio.run( - run_task( - SimpleNamespace(tasks=SimpleNamespace(run=run)), - device_id="123", - task="noop", + TaskResource( + client=SimpleNamespace(tasks=SimpleNamespace(run=run)), billing="included", - ) + ).run(device_id="123", task="noop") ) # The device-specific errors subclass the generic errors for the same status. assert type(caught.value) is expected @@ -290,51 +127,7 @@ async def stop(self, task_id): pass -@pytest.mark.parametrize( - "device", - [ - IOSDevice("http://localhost:8080"), - RemoteDevice(url="http://localhost:8090", device_id="test"), - ], -) -@pytest.mark.parametrize("method", ["do", "expect"]) -def test_unsupported_devices_raise(device, method): - with pytest.raises(OperatorNotAvailable, match="No operator"): - asyncio.run(getattr(device, method)("test")) - - -def test_cloud_do_maps_client_result(monkeypatch): - device = CloudDevice("device", api_key="test-key") - outcome = ExecutionResult[ExampleOutput]( - success=True, - task_id="task-x", - output=ExampleOutput(ok=True), - device="CloudDevice", - ) - - async def fake_run(client, **kwargs): - assert client is device._client - assert kwargs == { - "billing": "paid", - "device_id": "device", - "task": "instruction", - "output": ExampleOutput, - "max_steps": 6, - } - return outcome - - monkeypatch.setattr(cloud_module, "run_task", fake_run) - result = asyncio.run(device.do("instruction", output=ExampleOutput, max_steps=6)) - assert isinstance(result, ExecutionResult) - assert (result.task_id, result.success, result.output.ok, result.device) == ( - "task-x", - True, - True, - "CloudDevice", - ) - - -def test_client_run_task_polls_and_validates_output(monkeypatch): +def test_cloud_operator_polls_and_validates_output(monkeypatch, cloud_phone): calls = [] statuses = iter( [ @@ -358,25 +151,19 @@ async def get_status(self, task_id): assert task_id == "task-z" return next(statuses) - async def no_sleep(_): - return None - - monkeypatch.setattr(cloud_tasks.asyncio, "sleep", no_sleep) + monkeypatch.setenv("MOBILERUN_CLOUD_TASK_POLL_INTERVAL_SECONDS", "0") result = asyncio.run( - run_task( - SimpleNamespace(tasks=Tasks()), - device_id="d", - billing="included", - task="t", + CloudTaskOperator(client=SimpleNamespace(tasks=Tasks()), billing="included").do( + cloud_phone, + "t", output=ExampleOutput, max_steps=3, timeout=4, - poll_interval=0, ) ) assert calls == [ { - "device_id": "d", + "device_id": "cloud-phone", "task": "t", "output_schema": ExampleOutput.model_json_schema(), "max_steps": 3, @@ -391,7 +178,7 @@ async def no_sleep(_): ) -def test_client_run_task_timeout_is_typed(): +def test_cloud_operator_timeout_is_typed(cloud_phone): class Tasks(StreamedTasks): async def run(self, **kwargs): return SimpleNamespace(id="task-timeout") @@ -401,19 +188,18 @@ async def get_status(self, task_id): with pytest.raises(CloudTaskTimeout, match="task-timeout.*did not finish"): asyncio.run( - run_task( - SimpleNamespace(tasks=Tasks()), - device_id="d", - billing="included", - task="t", + CloudTaskOperator( + client=SimpleNamespace(tasks=Tasks()), billing="included" + ).do( + cloud_phone, + "t", timeout=0, - poll_interval=0, ) ) @pytest.mark.parametrize("slow_phase", ["submit", "status"]) -def test_client_run_task_timeout_bounds_submit_and_status(slow_phase): +def test_cloud_operator_timeout_bounds_submit_and_status(slow_phase, cloud_phone): class Tasks(StreamedTasks): async def run(self, **kwargs): if slow_phase == "submit": @@ -429,18 +215,17 @@ async def get_status(self, task_id): with pytest.raises(CloudTaskTimeout): asyncio.run( - run_task( - SimpleNamespace(tasks=Tasks()), - device_id="d", - billing="included", - task="t", + CloudTaskOperator( + client=SimpleNamespace(tasks=Tasks()), billing="included" + ).do( + cloud_phone, + "t", timeout=0.01, - poll_interval=0, ) ) -def test_cloud_invalid_output_returns_failed_typed_result(monkeypatch): +def test_cloud_invalid_output_returns_failed_typed_result(cloud_phone): class Tasks(StreamedTasks): async def run(self, **kwargs): return SimpleNamespace(id="task-invalid") @@ -455,14 +240,11 @@ async def get_status(self, task_id): ) result = asyncio.run( - run_task( - SimpleNamespace(tasks=Tasks()), - device_id="d", - billing="included", - task="t", + CloudTaskOperator(client=SimpleNamespace(tasks=Tasks()), billing="included").do( + cloud_phone, + "t", output=ExampleOutput, timeout=1, - poll_interval=0, ) ) assert isinstance(result, ExecutionResult) @@ -470,49 +252,226 @@ async def get_status(self, task_id): assert "validation error" in result.answer +T = TypeVar("T", bound=BaseModel) + + +class InputOperator(Operator): + def __init__(self, task: ExecutionResult[ExpectationVerdict]) -> None: + super().__init__() + self.task = task + self.checked: list[AsyncDevice] = [] + self.executed: list[ + tuple[AsyncDevice, str, object, int | None, float | None] + ] = [] + + def check(self, device: AsyncDevice) -> None: + self.checked.append(device) + + async def _execute( + self, + device: AsyncDevice, + instruction: str, + *, + output: type[T] | None = None, + max_steps: int | None = None, + timeout: float | None = None, + ) -> ExecutionResult[T]: + self.executed.append((device, instruction, output, max_steps, timeout)) + await device.tap(1, 2) + await device.type("hello world") + await device.swipe(1, 2, 3, 4) + return cast(ExecutionResult[T], self.task) + + +@pytest.mark.anyio +async def test_do_keeps_device_identity_and_core_hooks() -> None: + driver = FakeDriver() + task = ExecutionResult[ExpectationVerdict](success=True, device="AsyncDevice") + operator = InputOperator(task) + recorded: list[tuple[AsyncDevice, str]] = [] + + async def record(device: AsyncDevice, event: ActionEvent) -> None: + recorded.append((device, event.action.name)) + + async with fake_device(driver=driver) as phone: + async with phone.use_action_hooks(after=record): + assert await operator.do(phone, "type", max_steps=4, timeout=2) is task + assert operator.checked == [phone] + assert operator.executed == [(phone, "type", None, 4, 2)] + assert [name for name, _, _ in driver.calls] == ["tap", "input_text", "swipe"] + assert recorded == [(phone, "tap"), (phone, "type"), (phone, "swipe")] + + +@pytest.mark.anyio +async def test_operator_base_raises_without_implementation() -> None: + async with fake_device() as phone: + with pytest.raises( + OperatorNotAvailable, match="from mobilerun_agents import AgentOperator" + ): + await Operator().do(phone, "hello") + + +@pytest.mark.anyio @pytest.mark.parametrize("passed", [True, False]) -def test_expect_renders_prompt_and_returns_or_raises(monkeypatch, passed): - assert "a blue button exists" in PromptLoader.render_template( - load_prompt_text("devices/expect.jinja2"), {"condition": "a blue button exists"} - ) - device = object.__new__(AndroidDevice) +async def test_expect_requests_structured_verdict(passed: bool) -> None: task = ExecutionResult[ExpectationVerdict]( success=True, - output=ExpectationVerdict(passed=passed, reason="not visible"), - device="AndroidDevice", + output=ExpectationVerdict(passed=passed, reason="evidence"), + device="AsyncDevice", ) - - async def fake_do(instruction, *, output=None, max_steps=None): - assert "a blue button exists" in instruction - assert output is ExpectationVerdict - return task - - monkeypatch.setattr(device, "do", fake_do, raising=False) - if passed: - result = asyncio.run(device.expect("a blue button exists")) - assert isinstance(result, ExpectationResult) and result.passed - else: - with pytest.raises(ExpectationFailed, match="not visible") as error: - asyncio.run(device.expect("a blue button exists")) - assert error.value.result.reason == "not visible" + operator = InputOperator(task) + async with fake_device() as phone: + if passed: + result = await operator.expect(phone, "a blue button exists", timeout=3) + assert isinstance(result, ExpectationResult) and result.passed + else: + with pytest.raises(ExpectationFailed, match="evidence") as caught: + await operator.expect(phone, "a blue button exists", timeout=3) + assert caught.value.result.reason == "evidence" + [(executed_phone, instruction, output, steps, timeout)] = operator.executed + assert (executed_phone, output, steps, timeout) == ( + phone, + ExpectationVerdict, + None, + 3, + ) + assert "a blue button exists" in instruction + assert operator.checked == [phone] +@pytest.mark.anyio @pytest.mark.parametrize( ("success", "answer"), [(True, "passed=true text"), (False, "task failed")] ) -def test_expect_without_verdict_is_inconclusive(monkeypatch, success, answer): - device = object.__new__(AndroidDevice) +async def test_expect_without_verdict_is_inconclusive( + success: bool, answer: str +) -> None: task = ExecutionResult[ExpectationVerdict]( - success=success, answer=answer, output=None, device="AndroidDevice" + success=success, answer=answer, device="AsyncDevice" + ) + async with fake_device() as phone: + with pytest.raises(ExpectationInconclusive) as caught: + await InputOperator(task).expect(phone, "Settings is open") + assert caught.value.condition == "Settings is open" + assert caught.value.task is task + assert answer not in str(caught.value) + + +class NativeExtension(Extension): + cloud_native = True + + def __init__( + self, name: str, references: tuple[CloudCredentialReference, ...] + ) -> None: + super().__init__(name=name) + self.references = references + self.reads = 0 + + async def cloud_task_inputs(self) -> CloudTaskInputs: + self.reads += 1 + return CloudTaskInputs(self.references) + + async def on_close(self) -> None: + pytest.fail("operator must not close borrowed extensions") + + @function(to_atomic=lambda _: pytest.fail("cloud must not expand tools")) + async def local_tool(self) -> None: + pytest.fail("cloud must not invoke local tools") + + +@pytest.fixture +def cloud_phone(monkeypatch: pytest.MonkeyPatch) -> AsyncDevice: + phone = fake_device(driver=FakeDriver(device_id="cloud-phone")) + metadata = replace(phone.info(), backend="cloud") + monkeypatch.setattr(phone, "info", lambda: metadata) + return phone + + +@pytest.mark.anyio +async def test_cloud_do_submits_only_explicit_reference_inputs( + cloud_phone: AsyncDevice, +) -> None: + submissions = [] + started: list[str] = [] + + class Tasks(StreamedTasks): + async def run(self, **kwargs): + submissions.append(kwargs) + return SimpleNamespace(id="task-x") + + async def get_status(self, task_id): + assert task_id == "task-x" + return SimpleNamespace( + status="completed", + succeeded=True, + message="done", + output={"ok": True}, + steps=4, + ) + + client = cast(AsyncMobilerun, SimpleNamespace(tasks=Tasks())) + first = NativeExtension("first", (CloudCredentialReference("app", "work"),)) + second = NativeExtension( + "second", + ( + CloudCredentialReference("app", "work"), + CloudCredentialReference("app", "home"), + CloudCredentialReference("other", "work"), + ), ) + operator = CloudTaskOperator( + client=client, + extensions=[first, second], + billing="included", + on_task_started=started.append, + ) + result = await operator.do( + cloud_phone, "instruction", output=ExampleOutput, max_steps=6, timeout=1 + ) + assert (result.task_id, result.success, result.output, result.device) == ( + "task-x", + True, + ExampleOutput(ok=True), + "AsyncDevice", + ) + assert started == ["task-x"] + assert (first.reads, second.reads) == (1, 1) + assert submissions == [ + { + "device_id": "cloud-phone", + "task": "instruction", + "max_steps": 6, + "output_schema": ExampleOutput.model_json_schema(), + "credentials": [ + {"package_name": "app", "credential_names": ["home", "work"]}, + {"package_name": "other", "credential_names": ["work"]}, + ], + } + ] - async def fake_do(*args, **kwargs): - return task - monkeypatch.setattr(device, "do", fake_do, raising=False) - with pytest.raises(ExpectationInconclusive) as error: - asyncio.run(device.expect("Settings is open")) - assert error.value.condition == "Settings is open" - assert error.value.task is task - assert "no structured verdict" in str(error.value) - assert answer not in str(error.value) +@pytest.mark.anyio +async def test_cloud_rejects_local_target_or_extensions_before_reading_inputs( + cloud_phone: AsyncDevice, +) -> None: + native = NativeExtension("native", ()) + client = cast(AsyncMobilerun, object()) + async with fake_device() as phone: + with pytest.raises(OperatorNotSupported, match="is not a cloud device"): + await CloudTaskOperator(client=client, extensions=[native]).do( + phone, "noop" + ) + with pytest.raises(OperatorNotSupported, match="local_only"): + await CloudTaskOperator( + client=client, extensions=[native, Extension(name="local_only")] + ).do(cloud_phone, "noop") + assert native.reads == 0 + + +@pytest.mark.anyio +async def test_cloud_do_preserves_billing_guard(cloud_phone: AsyncDevice) -> None: + operator = CloudTaskOperator( + client=cast(AsyncMobilerun, object()), billing="no_commerce" + ) + with pytest.raises(BillingRequired): + await operator.do(cloud_phone, "noop") diff --git a/tests/unit/core/operator/test_operator_extensions.py b/tests/unit/core/operator/test_operator_extensions.py new file mode 100644 index 000000000..78ce5b637 --- /dev/null +++ b/tests/unit/core/operator/test_operator_extensions.py @@ -0,0 +1,39 @@ +import asyncio + +from mobilerun.core.extensions import Extension, function +from mobilerun.core.operator import Operator +from mobilerun.models.context import ContextItem + + +def test_operator_snapshots_borrowed_extensions_and_collects_ordered_context(): + class ContextExtension(Extension): + async def context(self): + return [ContextItem(self.name, "id", {"name": self.name})] + + async def on_close(self): + raise AssertionError("the borrower closed the extension") + + first = ContextExtension(name="first") + second = ContextExtension(name="second") + supplied = [first, Extension(name="empty"), second] + operator = Operator(extensions=supplied) + assert operator.extensions == tuple(supplied) + supplied.clear() + assert [item.source for item in asyncio.run(operator.context())] == [ + "first", + "second", + ] + assert operator.tools() == () + assert Operator().extensions == () + + +def test_operator_compiles_tools_from_its_own_extensions() -> None: + class Echo(Extension): + @function + async def echo(self, value: str) -> str: + return value + + operator = Operator(extensions=[Echo(name="first"), Echo(name="second")]) + first, second = operator.tools() + assert (first.name, second.name) == ("first.echo", "second.echo") + assert asyncio.run(first.invoke({"value": "hello"})) == "hello" diff --git a/tests/unit/core/operator/test_operator_plugins.py b/tests/unit/core/operator/test_operator_plugins.py new file mode 100644 index 000000000..322b92d28 --- /dev/null +++ b/tests/unit/core/operator/test_operator_plugins.py @@ -0,0 +1,61 @@ +"""Validate class entry points before constructing an operator.""" + +from importlib import metadata +from types import SimpleNamespace +from unittest.mock import Mock + +import pytest + +from mobilerun.core.operator import Operator + + +class LegacyOperator(Operator): + def __init__(self): + pass + + +@pytest.fixture +def entry(monkeypatch): + entry = Mock(spec=metadata.EntryPoint, name="entry") + entry.name = "inventory" + entry.value = "example:Inventory" + entry.dist = SimpleNamespace(metadata={"Name": "example-operators"}) + monkeypatch.setattr( + metadata, + "entry_points", + lambda *, group: [entry] if group == "mobilerun.operators" else [], + ) + return entry + + +def test_unknown_operator_lists_available_names_without_importing(entry): + from mobilerun.core.operator import load_operator + from mobilerun.errors.operator_plugins import OperatorPluginError + + with pytest.raises(OperatorPluginError, match="missing.*Available.*inventory"): + load_operator("missing") + entry.load.assert_not_called() + + +@pytest.mark.parametrize("export", [object, Operator(), LegacyOperator]) +def test_invalid_operator_export_names_distribution(entry, export): + from mobilerun.core.operator import load_operator + from mobilerun.errors.operator_plugins import OperatorPluginError + + entry.load.return_value = export + with pytest.raises(OperatorPluginError, match="inventory.*example-operators"): + load_operator("inventory") + + +def test_broken_operator_preserves_import_error(entry): + from mobilerun.core.operator import load_operator + from mobilerun.errors.operator_plugins import OperatorPluginError + + failure = ImportError("private import details") + entry.load.side_effect = failure + with pytest.raises( + OperatorPluginError, match="inventory.*example-operators" + ) as exc: + load_operator("inventory") + assert exc.value.__cause__ is failure + assert "private import details" not in str(exc.value) diff --git a/tests/unit/core/phone_number/test_attachment.py b/tests/unit/core/phone_number/test_attachment.py new file mode 100644 index 000000000..f2bfb9e9f --- /dev/null +++ b/tests/unit/core/phone_number/test_attachment.py @@ -0,0 +1,265 @@ +"""Explicit cloud number attachment and link ownership, without a transport.""" + +import asyncio +import json +import traceback +from contextlib import nullcontext +from dataclasses import replace +from types import SimpleNamespace as NS + +import httpx +import pytest +from click.testing import CliRunner +from mobilerun_sdk import APIStatusError + +from mobilerun.cli.phone_number import group +from mobilerun.core.phone_number import CloudPhoneNumber +from mobilerun.errors import CloudConflict, CloudDeviceNotFound, ExtensionNotSupported +from mobilerun.errors.cloud import BillingRequired, NumberAttachmentConflict +from tests.support.devices import FakeDriver, fake_device + + +class PhoneNumbers: + def __init__(self, current=None, *, telephony=True): + self.current = current + self.telephony = telephony + self.writes = [] + self.failure = None + self.client = NS( + devices=NS(number=self, retrieve_capabilities=self.capabilities), + numbers=NS( + retrieve=self.retrieve_number, delete=self.delete, create=self.create + ), + ) + + async def capabilities(self, device_id): + assert device_id == "phone" + return NS(capabilities=NS(telephony=self.telephony)) + + async def retrieve(self, device_id): + assert device_id == "phone" + return NS( + binding=( + NS(number_id=self.current, phone_number="+15555550123") + if self.current + else None + ) + ) + + async def bind(self, device_id, *, number_id): + assert device_id == "phone" and self.current is None + self.writes.append(("attach", number_id)) + if self.failure is not None and number_id == "new": + raise self.failure + self.current = number_id + return await self.retrieve(device_id) + + async def unbind(self, device_id): + assert device_id == "phone" + self.writes.append(("detach", self.current)) + self.current = None + + async def retrieve_number(self, number_id): + return NS( + data=NS( + device_binding=( + NS(device_id="phone") if number_id == self.current else None + ), + phone_number="+15555550123", + state="active", + checkout_url=None, + ) + ) + + async def delete(self, number_id): + self.writes.append(("release", number_id)) + + async def create(self, **kwargs): + self.writes.append(("purchase", None)) + return NS(data=NS(number_id="new", state="active", checkout_url=None)) + + +@pytest.fixture +def phone(monkeypatch): + driver = FakeDriver(device_id="phone") + device = fake_device(driver=driver) + # The shared fake is a caller driver, not core's optional real CloudDriver. + info = device.info() + monkeypatch.setattr(device, "info", lambda: replace(info, backend="cloud")) + yield device + assert driver.calls == [] + + +def test_attach_and_detach_update_the_server(phone): + async def run(): + sdk = PhoneNumbers() + number = CloudPhoneNumber("new", billing="no_commerce", client=sdk.client) + await number.attach(phone) + assert number.device_id == "phone" and sdk.current == "new" + assert await number.detach() is True + assert number.device_id is None and sdk.current is None + await number.close() + assert sdk.writes == [("attach", "new"), ("detach", "new")] + + asyncio.run(run()) + + +def test_occupied_phone_requires_explicit_replace(phone, caplog): + async def run(): + sdk = PhoneNumbers("old") + number = CloudPhoneNumber("new", client=sdk.client) + with pytest.raises(NumberAttachmentConflict, match="already has") as caught: + await number.attach(phone) + assert "+15555550123" not in str(caught.value) + caplog.text + assert sdk.current == "old" and sdk.writes == [] + await number.attach(phone, replace=True) + assert sdk.current == "new" + assert sdk.writes == [("detach", "old"), ("attach", "new")] + + asyncio.run(run()) + + +def test_close_leaves_existing_server_link_when_not_created_here(phone): + async def run(): + sdk = PhoneNumbers("new") + number = await CloudPhoneNumber("new", client=sdk.client) + await number.attach(phone) + await number.close() + assert sdk.current == "new" and sdk.writes == [] + + asyncio.run(run()) + + +@pytest.mark.parametrize("owned", [False, True]) +def test_close_only_releases_owned_number(phone, owned): + async def run(): + sdk = PhoneNumbers() + number = await CloudPhoneNumber(None if owned else "new", client=sdk.client) + await number.attach(phone) + await number.close() + await number.close() + assert sdk.current is None + assert sdk.writes == ([("purchase", None)] if owned else []) + [ + ("attach", "new"), + ("detach", "new"), + ] + ([("release", "new")] if owned else []) + + asyncio.run(run()) + + +def test_detach_does_not_clear_someone_elses_number(phone): + async def run(): + sdk = PhoneNumbers() + number = CloudPhoneNumber("new", client=sdk.client) + await number.attach(phone) + sdk.current = "other" + assert await number.detach() is False + assert number.device_id is None and sdk.current == "other" + assert sdk.writes == [("attach", "new")] + + asyncio.run(run()) + + +def test_no_commerce_blocks_paid_number_purchase(): + async def run(): + sdk = PhoneNumbers() + with pytest.raises(BillingRequired): + await CloudPhoneNumber( + billing="no_commerce", plan="rent", client=sdk.client + ) + assert sdk.writes == [] + + asyncio.run(run()) + + +def test_local_device_rejected_before_telephony_requests(): + async def run(): + number = CloudPhoneNumber("new", client=object()) + with pytest.raises(ExtensionNotSupported, match="cloud telephony"): + await number.attach(fake_device()) + + asyncio.run(run()) + + +def test_missing_phone_in_capabilities_preflight_is_a_device_error(phone): + async def run(): + sdk = PhoneNumbers() + + async def missing(device_id): + raise APIStatusError( + "private response", + response=httpx.Response( + 404, request=httpx.Request("GET", "https://example.invalid") + ), + body=None, + ) + + sdk.client.devices.retrieve_capabilities = missing + number = CloudPhoneNumber("new", client=sdk.client) + with pytest.raises(CloudDeviceNotFound) as caught: + await number.attach(phone) + assert caught.value.status == 404 + assert caught.value.operation == "Retrieve cloud phone capabilities" + assert caught.value.__cause__ is None and caught.value.__context__ is None + assert sdk.writes == [] + + asyncio.run(run()) + + +def test_rejected_replacement_restores_the_displaced_number(phone): + async def run(): + sdk = PhoneNumbers("old") + canary = "PRIVATE-TELEPHONY-RESPONSE" + sdk.failure = APIStatusError( + canary, + response=httpx.Response( + 409, + request=httpx.Request("POST", "https://example.invalid"), + headers={"x-request-id": "support-id"}, + ), + body={"detail": canary}, + ) + number = CloudPhoneNumber("new", client=sdk.client) + with pytest.raises(CloudConflict) as caught: + await number.attach(phone, replace=True) + error = caught.value + assert error.status == 409 + assert error.operation == "Bind phone number" + assert error.request_id is None and "support-id" not in str(error) + assert error.__cause__ is None and error.__context__ is None + assert canary not in "".join(traceback.format_exception(error)) + assert sdk.current == "old" + assert sdk.writes == [("detach", "old"), ("attach", "new"), ("attach", "old")] + + asyncio.run(run()) + + +def test_cancelled_replacement_does_not_replay_a_write(phone): + async def run(): + sdk = PhoneNumbers("old") + sdk.failure = asyncio.CancelledError() + number = CloudPhoneNumber("new", client=sdk.client) + with pytest.raises(asyncio.CancelledError): + await number.attach(phone, replace=True) + await number.close() + assert sdk.writes == [("detach", "old"), ("attach", "new")] + + asyncio.run(run()) + + +def test_cli_attachment_and_detachment_without_ui_or_prompt(monkeypatch): + sdk = PhoneNumbers() + monkeypatch.setattr(group, "cloud_client", lambda **kwargs: nullcontext(sdk.client)) + runner = CliRunner() + result = runner.invoke(group.number, ["bind", "new", "phone", "--json"]) + assert result.exit_code == 0, result.output + assert json.loads(result.stdout) == { + "id": "new", + "device_id": "phone", + "number_id": "new", + "status": "bound", + } + result = runner.invoke(group.number, ["unbind", "new", "--yes", "--json"]) + assert result.exit_code == 0, result.output + assert json.loads(result.stdout) == [{"id": "new", "status": "unbound"}] + assert sdk.writes == [("attach", "new"), ("detach", "new")] diff --git a/tests/unit/core/phone_number/test_comms.py b/tests/unit/core/phone_number/test_comms.py index b3dd454ff..b84455566 100644 --- a/tests/unit/core/phone_number/test_comms.py +++ b/tests/unit/core/phone_number/test_comms.py @@ -1,6 +1,9 @@ """Phone number and mailbox policy, ownership, polling, and SDK contracts.""" import asyncio +import json +import logging +import traceback from contextlib import asynccontextmanager from datetime import datetime, timezone from types import SimpleNamespace as NS @@ -13,19 +16,19 @@ from mobilerun.cli.phone_number import group from mobilerun.clients.cloud import numbers -from mobilerun.clients.cloud.errors import cloud_error +from mobilerun.clients.cloud.errors import CloudErrorMapper from mobilerun.config.settings import get_settings -from mobilerun.core.devices.cloud import CloudDevice +from mobilerun.core.extensions import ToolInvocationError, compile_tools from mobilerun.core.mailbox import CloudMailbox as Mailbox from mobilerun.core.phone_number import CloudPhoneNumber as PhoneNumber -from mobilerun.errors import CloudConflict, DeviceOperationNotSupported +from mobilerun.core.runs import ActionRecording +from mobilerun.errors import CloudConflict, ExtensionClosed from mobilerun.errors.base import is_value_safe from mobilerun.errors.cloud import CloudAPIError from mobilerun.models.billing import Billing from mobilerun.utils import codes from mobilerun.utils.codes import extract_code -from tests.support.devices import MemoryDevice -from tests.support.extensions import check_extension_contract +from tests.support.devices import fake_device def run(coro): @@ -230,6 +233,15 @@ def test_resource_requires_id_get_verifies_and_list_is_full(sdk, resource): [ ("Code: 0123", "0123"), ("code 12345678!", "12345678"), + ("Code: 1 2 3 4", None), + ("Your code: 12 34 56 10 minutes", None), + ("Support: 021 555 12 34", None), + ("2026-11-27 10:30", "2026"), + ("Paid 12.34 56 times", None), + ("Your code 123456 10 minutes", "123456"), + ("code 123456 5 min", "123456"), + ("1234 56", "1234"), + ("call 555 123 4567 ext 12", "4567"), ("123456789", None), ("123", None), ("no code", None), @@ -262,10 +274,6 @@ def test_sms_wait_filters_sender_and_after_and_send(sdk): {"data": message} ) number = PhoneNumber("number-id", client=sdk) - device = MemoryDevice( - cloud_id="device", supported_operations=frozenset({"cloud_telephony"}) - ) - run(number.bind(device)) assert run(number.wait_for_code(sender="example", after=after)) == "012345" sdk.numbers.messages.list.assert_awaited_once_with( "number-id", @@ -281,415 +289,183 @@ def test_sms_wait_filters_sender_and_after_and_send(sdk): @pytest.mark.parametrize("resource", [PhoneNumber, Mailbox]) -def test_wait_timeout_is_clear(sdk, resource): - from mobilerun.errors import ExtensionActionError - +def test_wait_timeout_is_safe(sdk, resource): item = resource("id", client=sdk) - device = MemoryDevice( - cloud_id="device", supported_operations=frozenset({"cloud_telephony"}) - ) - run(item.bind(device)) - with pytest.raises(ExtensionActionError, match="failed") as caught: + with pytest.raises(ToolInvocationError, match="failed") as caught: run(item.wait_for_code(timeout=0.001)) - assert isinstance(caught.value.__context__, TimeoutError) + assert caught.value.__context__ is None def test_mailbox_otp_filters_and_cursor_messages(sdk): sdk.mailboxes.otp.return_value = NS(data=NS(code="012345")) mailbox = Mailbox("id", client=sdk) - run(mailbox.bind(MemoryDevice())) assert run(mailbox.wait_for_code(sender="example")) == "012345" assert sdk.mailboxes.otp.call_args.kwargs["sender"] == "example" assert sdk.mailboxes.otp.call_args.kwargs["min_length"] == 4 -@pytest.mark.parametrize("keep", [False, True]) -@pytest.mark.parametrize("owned", [False, True]) -def test_device_ownership_existing_never_released(sdk, monkeypatch, keep, owned): - from mobilerun.clients.cloud import devices - - monkeypatch.setattr( - devices, - "capabilities", - AsyncMock(return_value=NS(capabilities=NS(telephony=True, proxy=True))), - ) - sdk.numbers.retrieve.return_value = NS( - data=NS( - device_binding=None, phone_number=None, state="active", checkout_url=None - ) - ) - phone = CloudDevice("phone", api_key="fake", billing="paid", keep=keep) - phone._client = sdk - phone._owned = True - phone._cloud_telephony = True - sdk.devices.terminate = AsyncMock() - - async def exercise(): - number = await PhoneNumber( - None if owned else "existing", client=sdk, billing="paid" - ) - mailbox = await Mailbox( - None if owned else "existing", client=sdk, billing="paid" - ) - await number.bind(phone, close_on_device_close=owned and not keep) - await mailbox.bind(phone, close_on_device_close=owned and not keep) - assert phone.number is number - assert phone.mailbox is mailbox - await phone.close() - await phone.close() - - run(exercise()) - assert sdk.numbers.delete.await_count == (1 if owned and not keep else 0) - assert sdk.mailboxes.delete.await_count == (1 if owned and not keep else 0) - assert sdk.devices.terminate.await_count == (0 if keep else 1) - assert sdk.devices.number.unbind.await_count == 1 - - -def test_thin_adapter_pagination_and_metadata(sdk): - sdk.numbers.list.side_effect = [page([NS(id="one")], True), page([NS(id="two")])] - assert [ - item.id - for item in run(numbers.list_numbers(billing=Billing.INCLUDED, client=sdk)) - ] == [ - "one", - "two", - ] - run(numbers.countries(billing=Billing.INCLUDED, client=sdk)) - run(numbers.capacity("US", billing=Billing.INCLUDED, client=sdk)) - sdk.numbers.capacity.assert_awaited_once_with(country="US") - - -def test_binding_local_device_rejects_before_requests(sdk): - from mobilerun.core.devices import AndroidDevice - from mobilerun.errors import ExtensionNotSupported - - with pytest.raises(ExtensionNotSupported): - run(PhoneNumber("number", client=sdk).bind(AndroidDevice("local"))) - sdk.numbers.retrieve.assert_not_awaited() - - +@pytest.mark.parametrize("resource", [PhoneNumber, Mailbox]) @pytest.mark.parametrize( - "telephony,bound,error", - [(False, None, "telephony"), (True, "elsewhere", "already bound")], + "message,typed", + [ + pytest.param( + "Code 843791 and backup 126 408", + ("843791", "126408", "126 408"), + id="existing", + ), + pytest.param( + "Verification code: 12 34 56", ("123456", "12 34 56"), id="spaces" + ), + pytest.param( + "Verification code: 12-34-56", ("123456", "12-34-56"), id="hyphens" + ), + pytest.param( + "Verification code: 12\t34\t56", ("123456", "12\t34\t56"), id="tabs" + ), + pytest.param("Your code 123456 10 minutes", ("123456",), id="trailing-number"), + pytest.param("1234 56", ("1234", "123456", "1234 56"), id="ambiguous"), + pytest.param( + "Your code: 123-456 10 minutes", + ("123456", "123-456"), + id="grouped-expiry-10", + ), + pytest.param( + "Your code: 123-456 5 minutes", ("123456", "123-456"), id="grouped-expiry-5" + ), + pytest.param( + "Backup codes: 123-456,789-012", + ("123456", "123-456", "789012", "789-012"), + id="comma-separated-backups", + ), + pytest.param( + "Your code: 12 34 56 10 minutes", + ("123456", "12 34 56"), + id="same-width-expiry", + ), + pytest.param("No code here", (), id="no-code"), + ], ) -def test_binding_capability_and_ownership_errors( - sdk, monkeypatch, telephony, bound, error +def test_history_masks_codes_in_direct_recording( + sdk, resource, message, typed, tmp_path ): - from mobilerun.clients.cloud import devices - from mobilerun.core.devices import CloudDevice - from mobilerun.errors import DeviceError - - monkeypatch.setattr( - devices, - "capabilities", - AsyncMock(return_value=NS(capabilities=NS(telephony=telephony, proxy=True))), - ) - sdk.numbers.retrieve.return_value = NS( - data=NS( - device_binding=NS(device_id=bound) if bound else None, phone_number=None + if resource is PhoneNumber: + sdk.numbers.messages.list.return_value = page([NS(body=message)]) + field = "body" + else: + sdk.mailboxes.messages.list.return_value = NS( + items=[NS(preview=message)], next_cursor=None ) - ) - phone = CloudDevice("phone", api_key="fake") - phone._client = sdk - phone._cloud_telephony = telephony - if bound: - sdk.devices.number.bind.side_effect = DeviceError("already bound") - with pytest.raises(DeviceError, match=error): - run(PhoneNumber("number", client=sdk).bind(phone)) - assert sdk.devices.number.bind.await_count == int(telephony) - - -def test_attachments_are_read_only_and_old_phone_helpers_are_gone(): - from mobilerun.core.devices import AndroidDevice, CloudDevice - - for phone in (AndroidDevice("local"), CloudDevice("phone", api_key="fake")): - for name in ("number", "mailbox"): - with pytest.raises(AttributeError): - setattr(phone, name, object()) - with pytest.raises(DeviceOperationNotSupported): - getattr(phone, name) - assert not hasattr(phone, "set_number") - with pytest.raises(TypeError, match="number.bind"): - CloudDevice(api_key="fake", number="id") - - -def test_number_unbind_and_mailbox_detach(sdk, monkeypatch): - from mobilerun.clients.cloud import devices - from mobilerun.core.devices import CloudDevice - - monkeypatch.setattr( - devices, - "capabilities", - AsyncMock(return_value=NS(capabilities=NS(telephony=True, proxy=True))), - ) - sdk.numbers.retrieve.return_value = NS( - data=NS(device_binding=None, phone_number=None) - ) - phone = CloudDevice("phone", api_key="fake") - phone._client = sdk - phone._cloud_telephony = True + field = "preview" async def exercise(): - number = PhoneNumber("number", client=sdk) - mailbox = Mailbox("mailbox", client=sdk) - await number.bind(phone) - assert number.device_id == "phone" - await number.unbind() - assert number.device_id is None - with pytest.raises(DeviceOperationNotSupported, match="No sms extension"): - _ = phone.number - await mailbox.bind(phone) - assert phone.mailbox is mailbox - await mailbox.unbind() - with pytest.raises(DeviceOperationNotSupported, match="No email extension"): - _ = phone.mailbox + item = resource("known-id", client=sdk) + async with ( + fake_device() as device, + ActionRecording(device, runs_dir=tmp_path) as recording, + ): + history = await item.messages() + assert [getattr(entry, field) for entry in history] == [message] + if not typed: + assert not recording.redactor + return + for text in typed: + await device.type(text) + recording.finish("succeeded") + rows = (recording.run_dir / "steps.jsonl").read_text().splitlines() + if [json.loads(row)["args"]["text"] for row in rows] != ["***"] * len(typed): + pytest.fail( + "Message history codes leaked into recorded typing", pytrace=False + ) run(exercise()) - sdk.devices.number.unbind.assert_awaited_once_with("phone") - -def test_existing_phone_fetches_and_caches_number_from_device_api(sdk): - from mobilerun.core.devices import CloudDevice - from mobilerun.core.proxy import ProxyStatus - sdk.devices.number.retrieve.return_value = NS( - binding=NS(number_id="bound", phone_number="+15555550123") +def test_sms_wait_does_not_guess_a_code_from_a_grouped_message(sdk): + sdk.numbers.messages.list.return_value = page( + [NS(body="Your code: 12 34 56 10 minutes")] ) - phone = CloudDevice("phone", api_key="fake") - phone._client = sdk - phone._proxy_status = AsyncMock(return_value=ProxyStatus(False)) - - async def exercise(): - await phone - assert phone.number.id == "bound" - assert phone.number.device_id == "phone" - assert phone.number.phone_number == "+15555550123" - await phone - - run(exercise()) - sdk.devices.number.retrieve.assert_awaited_once_with("phone") - - -@pytest.mark.parametrize("error", [RuntimeError("ambiguous"), asyncio.CancelledError()]) -def test_number_ambiguous_bind_reconciles_remote_binding(error): - async def run(): - device = MemoryDevice( - cloud_id="device", supported_operations=frozenset({"cloud_telephony"}) - ) - number = PhoneNumber("number") - response = NS(binding=NS(number_id="number", phone_number="+123")) - with ( - patch( - "mobilerun.core.phone_number.cloud.devices.bind_number", - AsyncMock(side_effect=error), - ), - patch( - "mobilerun.core.phone_number.cloud.devices.number", - AsyncMock(return_value=response), - ), - ): - with pytest.raises(type(error)): - await number.bind(device) - assert device.number.id == "number" - assert device.number.device_id == "device" - - asyncio.run(run()) - - -def test_number_failed_readback_marks_binding_uncertain(): - async def run(): - device = MemoryDevice( - cloud_id="device", supported_operations=frozenset({"cloud_telephony"}) - ) - number = PhoneNumber("number") - with ( - patch( - "mobilerun.core.phone_number.cloud.devices.bind_number", - AsyncMock(side_effect=RuntimeError("failed")), - ), - patch( - "mobilerun.core.phone_number.cloud.devices.number", - AsyncMock(side_effect=RuntimeError("offline")), - ), - ): - with pytest.raises(RuntimeError): - await number.bind(device) - assert device._extension_state.bindings["sms"].uncertain - - asyncio.run(run()) + with pytest.raises(ToolInvocationError, match="failed"): + run(PhoneNumber("known-id", client=sdk).wait_for_code(timeout=0.05)) -def test_number_unbind_failure_adopts_remote_absence(): - async def run(): - device = MemoryDevice( - cloud_id="device", supported_operations=frozenset({"cloud_telephony"}) - ) - number = PhoneNumber("number") - with ( - patch("mobilerun.core.phone_number.cloud.devices.bind_number", AsyncMock()), - patch( - "mobilerun.core.phone_number.cloud.devices.unbind_number", - AsyncMock(side_effect=RuntimeError("lost response")), - ), - patch( - "mobilerun.core.phone_number.cloud.devices.number", - AsyncMock(return_value=NS(binding=None)), - ), - ): - await number.bind(device) - with pytest.raises(RuntimeError): - await number.unbind() - assert not device.extensions - assert number.device is None - - asyncio.run(run()) - - -def test_number_force_rollback_failure_reads_back_observed_binding(): - async def run(): - device = MemoryDevice( - cloud_id="device", supported_operations=frozenset({"cloud_telephony"}) - ) - old = PhoneNumber("old") - new = PhoneNumber("new") - bind = AsyncMock( - side_effect=[ - None, - RuntimeError("new response lost"), - RuntimeError("restore failed"), - ] +@pytest.mark.parametrize("resource", [PhoneNumber, Mailbox]) +def test_wait_for_code_masks_the_returned_code(sdk, resource, tmp_path): + if resource is PhoneNumber: + sdk.numbers.messages.list.return_value = page( + [NS(body="Support: 021 555 12 34"), NS(body="Your code: 938271")] ) - response = NS(binding=NS(number_id="new", phone_number="+123")) - with ( - patch("mobilerun.core.phone_number.cloud.devices.bind_number", bind), - patch( - "mobilerun.core.phone_number.cloud.devices.unbind_number", AsyncMock() - ), - patch( - "mobilerun.core.phone_number.cloud.devices.number", - AsyncMock(return_value=response), - ), - ): - await old.bind(device) - with pytest.raises(RuntimeError, match="new response lost"): - await new.bind(device, force=True) - assert device.number.id == "new" - assert old.device is None - - asyncio.run(run()) + expected, grouped = "938271", "938 271" + else: + expected, grouped = "93 -\t82 - 71", "93 -\t82 - 71" + sdk.mailboxes.otp.return_value = NS(data=NS(code=expected)) - -def test_number_force_successful_rollback_also_reads_back(): - async def run(): - device = MemoryDevice( - cloud_id="device", supported_operations=frozenset({"cloud_telephony"}) - ) - old = PhoneNumber("old") - new = PhoneNumber("new") - bind = AsyncMock(side_effect=[None, RuntimeError("new response lost"), None]) - readback = AsyncMock( - return_value=NS(binding=NS(number_id="old", phone_number="+123")) - ) - with ( - patch("mobilerun.core.phone_number.cloud.devices.bind_number", bind), - patch( - "mobilerun.core.phone_number.cloud.devices.unbind_number", AsyncMock() - ), - patch("mobilerun.core.phone_number.cloud.devices.number", readback), + async def exercise(): + item = resource("known-id", client=sdk) + async with ( + fake_device() as device, + ActionRecording(device, runs_dir=tmp_path) as recording, ): - await old.bind(device) - with pytest.raises(RuntimeError): - await new.bind(device, force=True) - readback.assert_awaited_once() + assert await item.wait_for_code(timeout=0.05) == expected + await device.type("938271") + await device.type(grouped) + recording.finish("succeeded") + rows = (recording.run_dir / "steps.jsonl").read_text().splitlines() + if [json.loads(row)["args"]["text"] for row in rows] != ["***", "***"]: + pytest.fail("Polled code leaked into recorded typing", pytrace=False) - asyncio.run(run()) - - -def test_number_extension_contract(): - async def device(): - return MemoryDevice( - cloud_id="device", supported_operations=frozenset({"cloud_telephony"}) - ) + run(exercise()) - async def incompatible(): - return MemoryDevice() - with ( - patch("mobilerun.core.phone_number.cloud.devices.bind_number", AsyncMock()), - patch("mobilerun.core.phone_number.cloud.devices.unbind_number", AsyncMock()), - ): - asyncio.run( - check_extension_contract( - lambda name: PhoneNumber("number", name=name), - device, - incompatible_device=incompatible, - ) - ) +@pytest.mark.parametrize("resource", [PhoneNumber, Mailbox]) +@pytest.mark.parametrize("resource_id", [None, "existing"], ids=["new", "existing"]) +@pytest.mark.parametrize("operation", ["enter", "await", "wait_until_paid", "release"]) +def test_closed_uninitialized_handle_cannot_enter_or_access_backend( + sdk, resource, resource_id, operation +): + async def exercise(): + item = resource(resource_id, client=sdk) + await item.close() + with pytest.raises(ExtensionClosed): + if operation == "enter": + async with item: + pass + elif operation == "await": + await item + else: + await getattr(item, operation)() + run(exercise()) + adapter = sdk.numbers if resource is PhoneNumber else sdk.mailboxes + for endpoint in (adapter.create, adapter.retrieve, adapter.delete): + assert endpoint.call_args_list == [] -def test_number_bind_and_unbind_call_backend(): - async def run(): - client = object() - device = MemoryDevice( - cloud_id="device", supported_operations=frozenset({"cloud_telephony"}) - ) - number = PhoneNumber("number", client=client) - with ( - patch( - "mobilerun.core.phone_number.cloud.devices.bind_number", AsyncMock() - ) as bind, - patch( - "mobilerun.core.phone_number.cloud.devices.unbind_number", AsyncMock() - ) as unbind, - ): - await number.bind(device) - await number.unbind() - assert bind.await_args.args == ("device", "number") - assert unbind.await_args.args == ("device",) - assert bind.await_args.kwargs["client"] is client - assert unbind.await_args.kwargs["client"] is client - asyncio.run(run()) +def test_closed_number_cannot_poll_readiness(sdk): + async def exercise(): + number = PhoneNumber("existing", client=sdk) + await number.close() + with pytest.raises(ExtensionClosed): + await number.wait_ready() + run(exercise()) + assert sdk.numbers.retrieve.call_args_list == [] -def test_connect_adopts_number_without_mutation(): - async def run(): - phone = CloudDevice("device", api_key="test") - response = NS(binding=NS(number_id="number", phone_number="+123")) - capabilities = NS(capabilities=NS(telephony=True, proxy=True)) - with ( - patch( - "mobilerun.core.devices.components.cloud_lifecycle.devices.number", - AsyncMock(return_value=response), - ), - patch( - "mobilerun.core.devices.components.cloud_lifecycle.devices.capabilities", - AsyncMock(return_value=capabilities), - ), - patch( - "mobilerun.core.phone_number.cloud.devices.bind_number", AsyncMock() - ) as bind, - patch( - "mobilerun.core.phone_number.cloud.devices.unbind_number", AsyncMock() - ) as unbind, - patch("mobilerun.core.proxy.adoption._adopt_remote_proxy", AsyncMock()), - ): - await phone.connect() - assert phone.number.id == "number" - assert phone.number.phone_number == "+123" - assert "cloud_telephony" in phone.supported_operations - bind.assert_not_awaited() - number = phone.number - await phone.close() - assert not phone.extensions - assert number.device is None - assert number.device_id == "device" - unbind.assert_not_awaited() - asyncio.run(run()) +def test_thin_adapter_pagination_and_metadata(sdk): + sdk.numbers.list.side_effect = [page([NS(id="one")], True), page([NS(id="two")])] + assert [ + item.id + for item in run(numbers.Numbers(billing=Billing.INCLUDED, client=sdk).list()) + ] == [ + "one", + "two", + ] + run(numbers.Numbers(billing=Billing.INCLUDED, client=sdk).countries()) + run(numbers.Numbers(billing=Billing.INCLUDED, client=sdk).capacity("US")) + sdk.numbers.capacity.assert_awaited_once_with(country="US") -def test_sms_code_and_typed_send(): +def test_sms_tools_read_without_exposing_send_or_recording_codes(caplog): async def run(): now = datetime.now(timezone.utc) @@ -702,18 +478,16 @@ async def run(): "detectedSender": "Example", "body": "Code 012345", } - device = MemoryDevice( - cloud_id="device", supported_operations=frozenset({"cloud_telephony"}) - ) number = PhoneNumber("number") + tools = {tool.name: tool for tool in compile_tools([number])} + assert set(tools) == {"sms.messages", "sms.wait_for_code"} with ( - patch("mobilerun.core.phone_number.cloud.devices.bind_number", AsyncMock()), patch( - "mobilerun.core.phone_number.cloud.numbers.messages", + "mobilerun.clients.cloud.numbers.Numbers.messages", AsyncMock(return_value=[numbers.MessageItem.model_validate(item)]), ), patch( - "mobilerun.core.phone_number.cloud.numbers.send", + "mobilerun.clients.cloud.numbers.Numbers.send", AsyncMock( return_value=numbers.MessageSendResponse.model_validate( {"data": item} @@ -721,23 +495,49 @@ async def run(): ), ), ): - await number.bind(device) - assert await number.wait_for_code(sender="example") == "012345" + assert ( + await tools["sms.wait_for_code"].invoke({"sender": "example"}) + == "012345" + ) + history = await tools["sms.messages"].invoke({}) + assert isinstance(history, list) and history[0]["body"] == "Code 012345" assert (await number.send("to", "body")).data.id == "one" + assert "012345" not in repr(await number.context()) + caplog.text asyncio.run(run()) -def sdk_conflict(body): +def test_send_does_not_disclose_recipient_or_sms_body(sdk, caplog): + target, body = "+15551234567", "code-canary-092132" + + async def error(number_id, *, to, body): + logging.getLogger(__name__).warning("SMS to %s: %s", to, body) + raise APIStatusError( + f"Provider rejected {to}: {body}", + response=httpx.Response( + 400, request=httpx.Request("POST", "https://test.invalid") + ), + body={"message": body}, + ) + + sdk.numbers.messages.send.side_effect = error + with pytest.raises(CloudAPIError) as caught: + run(PhoneNumber("number", billing="paid", client=sdk).send(target, body)) + output = "".join(traceback.format_exception(caught.value)) + caplog.text + assert target not in output and body not in output + assert caught.value.__context__ is None and caught.value.__cause__ is None + + +def sdk_status_error(body, *, status=409): response = httpx.Response( - 409, request=httpx.Request("DELETE", "https://example.test") + status, request=httpx.Request("DELETE", "https://example.test") ) return APIStatusError("server secret", response=response, body=body) def test_not_cancellable_number_release_has_specific_safe_message(): - error = cloud_error( - sdk_conflict({"code": "not_cancellable", "message": "server secret"}), + error = CloudErrorMapper.from_exception( + sdk_status_error({"code": "not_cancellable", "message": "server secret"}), "Release number", ) assert isinstance(error, CloudConflict) @@ -750,7 +550,7 @@ def test_not_cancellable_number_release_has_specific_safe_message(): @pytest.mark.parametrize("body", [None, "invalid json", [], {}, {"code": "other"}]) def test_other_conflicts_keep_generic_message(body): - error = cloud_error(sdk_conflict(body), "Release number") + error = CloudErrorMapper.from_exception(sdk_status_error(body), "Release number") assert type(error) is CloudConflict assert str(error) == ( "Release number failed (HTTP 409). " @@ -759,7 +559,9 @@ def test_other_conflicts_keep_generic_message(body): def test_not_cancellable_code_for_other_operation_stays_generic(): - error = cloud_error(sdk_conflict({"code": "not_cancellable"}), "Release mailbox") + error = CloudErrorMapper.from_exception( + sdk_status_error({"code": "not_cancellable"}), "Release mailbox" + ) assert type(error) is CloudConflict @@ -769,43 +571,34 @@ def test_number_create_without_country_reaches_api(): return_value=NS(data=NS(number_id="n1", state="active", checkout_url=None)) ) ) - asyncio.run(numbers.create(billing=Billing.PAID, client=NS(numbers=endpoint))) + asyncio.run( + numbers.Numbers(billing=Billing.PAID, client=NS(numbers=endpoint)).create() + ) endpoint.create.assert_awaited_once_with(billing_preference="included") def test_known_validation_code_is_safe_and_actionable(): - exc = NS( - status_code=422, - response=None, - request_id=None, - body={"code": "unsupported_country", "message": "SECRET"}, + exc = sdk_status_error( + {"code": "unsupported_country", "message": "SECRET"}, status=422 ) - error = cloud_error(exc, "Create number") + error = CloudErrorMapper.from_exception(exc, "Create number") assert "mobilerun number countries" in str(error) assert "SECRET" not in str(error) def test_unknown_validation_code_does_not_leak(): - exc = NS( - status_code=422, - response=None, - request_id=None, - body={"code": "SECRET", "message": "SECRET"}, - ) - assert "SECRET" not in str(cloud_error(exc, "Create number")) + exc = sdk_status_error({"code": "SECRET", "message": "SECRET"}, status=422) + assert "SECRET" not in str(CloudErrorMapper.from_exception(exc, "Create number")) def test_known_device_validation_code_is_safe(): - exc = NS( - status_code=422, - response=None, - request_id=None, - body={"code": "DEVICE_TYPE_UNAVAILABLE", "message": "SECRET"}, + exc = sdk_status_error( + {"code": "DEVICE_TYPE_UNAVAILABLE", "message": "SECRET"}, status=422 ) - result = str(cloud_error(exc, "Create cloud phone")) + result = str(CloudErrorMapper.from_exception(exc, "Create cloud phone")) assert "cloud phone type is unavailable" in result assert "SECRET" not in result @@ -820,7 +613,7 @@ async def phone(**kwargs): monkeypatch.setattr(group, "PhoneNumber", phone) monkeypatch.setattr( - group.cloud_numbers, + group.Numbers, "retrieve", AsyncMock(return_value=NS(data=NS(state="active", phone_number="+1"))), ) @@ -837,7 +630,7 @@ async def client(**kwargs): monkeypatch.setattr(group, "cloud_client", client) monkeypatch.setattr(group, "is_interactive", lambda: True) monkeypatch.setattr( - group.cloud_numbers, + group.Numbers, "countries", AsyncMock( return_value=NS( @@ -855,7 +648,7 @@ async def phone(**kwargs): phone.included_available = AsyncMock(return_value=1) monkeypatch.setattr(group, "PhoneNumber", phone) monkeypatch.setattr( - group.cloud_numbers, + group.Numbers, "retrieve", AsyncMock(return_value=NS(data=NS(state="active", phone_number="+1"))), ) diff --git a/tests/unit/core/proxy/test_products.py b/tests/unit/core/proxy/test_products.py new file mode 100644 index 000000000..b5677fc77 --- /dev/null +++ b/tests/unit/core/proxy/test_products.py @@ -0,0 +1,125 @@ +import asyncio +import logging +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest +from mobilerun_core import ( + ConnectProxyRef, + Socks5Proxy, +) + +from mobilerun.core.proxy import ( + CloudFixedProxy, + CloudRotatingProxy, + CloudSocks5Proxy, +) +from mobilerun.errors.cloud import BillingRequired +from mobilerun.models.billing import Billing + + +def test_products_convert_without_phone_or_purchase() -> None: + first, rotating = ConnectProxyRef("first"), ConnectProxyRef("rotating") + assert CloudFixedProxy(first).as_device_proxy() is first + assert CloudRotatingProxy(rotating).as_device_proxy() is rotating + + +def test_socks5_url_credentials_are_opaque(caplog: pytest.LogCaptureFixture) -> None: + url = "socks5://canary-user:canary%40password@example.test:1080" + with caplog.at_level(logging.DEBUG): + product = CloudSocks5Proxy.from_url(url) + value = product.as_device_proxy() + assert isinstance(value, Socks5Proxy) + assert (value.host, value.port) == ("example.test", 1080) + assert value.user is not None and value.user.reveal() == "canary-user" + assert ( + value.password is not None and value.password.reveal() == "canary@password" + ) + with pytest.raises(ValueError) as caught: + CloudSocks5Proxy.from_url(url.replace("1080", "bad")) + for secret in ("canary-user", "canary%40password", "canary@password"): + assert secret not in repr((product, value, caught.value)) + caplog.text + + +def test_rotating_selects_active_matching_capacity( + monkeypatch: pytest.MonkeyPatch, +) -> None: + async def scenario() -> None: + from mobilerun.core.proxy import account + + row = dict( + name="Label", + country="de", + status="active", + type="residential", + billing_mode="included", + ) + catalog = AsyncMock( + side_effect=[ + SimpleNamespace( + items=[ + SimpleNamespace(id="ended-de", **(row | {"status": "ended"})) + ], + pagination=SimpleNamespace(has_next=True), + ), + SimpleNamespace( + items=[ + SimpleNamespace(id="active-us", **(row | {"country": "us"})), + SimpleNamespace(id="active-de", **row), + ], + pagination=SimpleNamespace(has_next=False), + ), + ] + ) + monkeypatch.setattr(account.Proxies, "list", catalog) + selected = await CloudRotatingProxy.select("DE", billing=Billing.NO_COMMERCE) + assert selected.as_device_proxy() == ConnectProxyRef("active-de") + assert [call.kwargs["page"] for call in catalog.await_args_list] == [1, 2] + + asyncio.run(scenario()) + + +def test_only_purchased_proxy_is_released_on_close( + monkeypatch: pytest.MonkeyPatch, +) -> None: + async def scenario() -> None: + from mobilerun.core.proxy import account + + purchase = AsyncMock( + return_value=SimpleNamespace( + id="bought", + name="My proxy", + country="de", + status="active", + type="dedicated_residential", + billing_mode=None, + ) + ) + release = AsyncMock() + monkeypatch.setattr(account.Proxies, "buy", purchase) + monkeypatch.setattr(account.Proxies, "cancel", release) + await CloudFixedProxy(ConnectProxyRef("borrowed")).close() + owned = await CloudFixedProxy.purchase("de") + assert owned.as_device_proxy() == ConnectProxyRef("bought") + await owned.close() + await owned.close() + assert [call.args for call in release.await_args_list] == [("bought",)] + assert purchase.await_args is not None + assert purchase.await_args.kwargs["type"] == "dedicated_residential" + product = await account.purchase_connect_proxy("de") + assert product.ref == ConnectProxyRef("bought") + + asyncio.run(scenario()) + + +def test_no_commerce_blocks_before_sdk_access(monkeypatch: pytest.MonkeyPatch) -> None: + async def scenario() -> None: + from mobilerun.clients.cloud import client as connection + + client = AsyncMock() + monkeypatch.setattr(connection, "cloud_client", client) + with pytest.raises(BillingRequired): + await CloudFixedProxy.purchase("de", billing=Billing.NO_COMMERCE) + client.assert_not_called() + + asyncio.run(scenario()) diff --git a/tests/unit/core/proxy/test_proxy.py b/tests/unit/core/proxy/test_proxy.py index a5bb7879f..fba0ee849 100644 --- a/tests/unit/core/proxy/test_proxy.py +++ b/tests/unit/core/proxy/test_proxy.py @@ -1,697 +1,128 @@ -"""Proxy binding, device operations, billing guards and SDK wire contracts.""" +"""Proxy extension tests at the public core device boundary.""" import asyncio -from contextlib import nullcontext -from types import SimpleNamespace -from typing import cast +import logging from unittest.mock import AsyncMock import pytest - -from mobilerun.core.devices import AndroidDevice, CloudDevice, Device, DevicePool -from mobilerun.core.devices.components.wrapper import DeviceWrapper -from mobilerun.core.proxy import ( - CloudFixedProxy, - CloudRotatingProxy, - CloudSocks5Proxy, - LocalProxy, - Proxy, +from mobilerun_core import ( + ConnectProxyRef, + ProxyAlreadyConfigured, ProxyStatus, + UnsupportedOperation, ) -from mobilerun.errors import ExtensionConflict, ExtensionNotSupported -from mobilerun.models.billing import Billing -from tests.support.devices import MemoryDevice -from tests.support.extensions import check_extension_contract -from tests.support.proxy import ProxyMemory - - -@pytest.mark.parametrize( - "factory,cloud", - [ - (lambda name: LocalProxy("localhost", 8080, name=name), False), - (lambda name: CloudFixedProxy("proxy-id", name=name), True), - (lambda name: CloudRotatingProxy("US", name=name), True), - (lambda name: CloudSocks5Proxy("host", 1080, name=name), True), - ], -) -def test_proxy_contract(factory, cloud): - async def device(): - return ProxyMemory(cloud) - - async def incompatible(): - return MemoryDevice(cloud_id=None if cloud else "cloud") - - asyncio.run( - check_extension_contract( - factory, - device, - incompatible_device=incompatible, - unbind_requires_replacement=cloud, - ) - ) - - -def test_cloud_proxy_force_switch_and_required_proxy(): - async def scenario(): - phone = ProxyMemory(True) - first = CloudFixedProxy("first") - second = CloudFixedProxy("second") - await first.bind(phone) - assert phone.__getattr__("proxy") is first - with pytest.raises(ExtensionConflict, match="unbind it first"): - await second.bind(phone) - assert phone.target.connect.await_count == 1 - with pytest.raises(ExtensionConflict, match="cloud phones need a proxy"): - await first.unbind() - await second.bind(phone, force=True) - assert first.device is None - assert phone.extensions["proxy"] is second - assert phone.target.connect.await_count == 2 - assert phone.target.disconnect_calls == 0 - await phone.close() - - asyncio.run(scenario()) - - -def test_cloud_unmanaged_proxy_needs_force(): - async def scenario(): - phone = ProxyMemory(True) - phone.target.current = ProxyStatus(True, "unmanaged") - proxy = CloudFixedProxy("new") - from mobilerun.core.proxy import UnmanagedProxyConflict - - with pytest.raises(UnmanagedProxyConflict, match="unmanaged"): - await proxy.bind(phone) - assert "proxy" not in phone.extensions - assert proxy.device is None - assert phone.target.connect.await_count == 0 - await proxy.bind(phone, force=True) - assert phone.extensions["proxy"] is proxy - await phone.close() - - asyncio.run(scenario()) - -def test_failed_force_restores_old_or_marks_it_uncertain(): - async def scenario(restore_fails): - phone = ProxyMemory(True) - old = CloudFixedProxy("old") - new = CloudFixedProxy("new") - await old.bind(phone) - failure = RuntimeError("backend failed") - phone.target.connect.side_effect = [ - failure, - failure if restore_fails else ProxyStatus(True, "old"), +from mobilerun.core.extensions import compile_tools, tool_dispatch_guard +from mobilerun.core.proxy import CloudFixedProxy, CloudSocks5Proxy +from mobilerun.errors.tools import ToolInvocationError +from tests.support.devices import FakeDriver, fake_device + + +def test_proxy_tools_and_explicit_replacement_reach_core_device( + monkeypatch: pytest.MonkeyPatch, +) -> None: + set_proxy = AsyncMock(side_effect=[None, ProxyAlreadyConfigured(), None]) + clear_proxy = AsyncMock() + proxy_status = AsyncMock( + side_effect=[ + ProxyStatus(True, "socks5", "one"), + ProxyStatus(True, "socks5", "two"), + ProxyStatus(False, None, None), ] - if restore_fails: - phone.target.status = AsyncMock( - side_effect=[ - phone.target.current, - phone.target.current, - RuntimeError("status read failed"), - ] - ) - with pytest.raises(RuntimeError) as raised: - await new.bind(phone, force=True) - assert raised.value is failure - assert new.device is None - if restore_fails: - assert phone.extensions["proxy"] is old - assert old._binding.uncertain - else: - assert phone.proxy is old - assert not old._binding.uncertain - phone.target.connect.side_effect = phone.target._connect - await phone.close() - - asyncio.run(scenario(False)) - asyncio.run(scenario(True)) - + ) -def test_force_does_not_release_owned_old_proxy(): - async def scenario(): - phone = ProxyMemory(True) - old = CloudFixedProxy("old") - old.on_close = AsyncMock() - await old.bind(phone, close_on_device_close=True) - new = CloudFixedProxy("new") - await new.bind(phone, force=True) - old.on_close.assert_not_awaited() - assert old.device is None - await phone.close() + async def scenario() -> None: + async with fake_device() as phone: + monkeypatch.setattr(phone, "set_proxy", set_proxy) + monkeypatch.setattr(phone, "clear_proxy", clear_proxy) + monkeypatch.setattr(phone, "proxy_status", proxy_status) + first = CloudFixedProxy(ConnectProxyRef("one"), name="first", device=phone) + second = CloudFixedProxy(ConnectProxyRef("two"), device=phone) + tools = {tool.name: tool for tool in compile_tools([first])} + assert set(tools) == {"first.apply", "first.clear", "first.status"} + await tools["first.apply"].invoke({}) + assert await tools["first.status"].invoke({}) == { + "connected": True, + "protocol": "socks5", + "reference": "one", + } + with pytest.raises(ProxyAlreadyConfigured): + await second.apply() + await second.apply(replace=True) + assert await second.status() == ProxyStatus(True, "socks5", "two") + await tools["first.clear"].invoke({}) + assert await second.status() == ProxyStatus(False, None, None) asyncio.run(scenario()) - - -def test_unmanaged_refusal_does_not_reconcile_before_forced_retry(): - async def scenario(): - from mobilerun.core.proxy import UnmanagedProxyConflict - - phone = ProxyMemory(True) - phone.target.current = ProxyStatus(True, "unmanaged") - original = phone.target.status - phone.target.status = AsyncMock( - side_effect=[ - phone.target.current, - RuntimeError("readback failed"), - phone.target.current, + assert [(call.args, call.kwargs) for call in set_proxy.await_args_list] == [ + ((ConnectProxyRef("one"),), {"replace": False}), + ((ConnectProxyRef("two"),), {"replace": False}), + ((ConnectProxyRef("two"),), {"replace": True}), + ] + clear_proxy.assert_awaited_once_with() + + +def test_unsupported_caller_driver_uses_core_error() -> None: + driver = FakeDriver(supported={"set_proxy", "proxy_status", "clear_proxy"}) + + async def scenario() -> None: + async with fake_device(driver=driver) as phone: + proxy = CloudFixedProxy(ConnectProxyRef("borrowed"), device=phone) + assert proxy.as_device_proxy() == ConnectProxyRef("borrowed") + tools = {tool.name: tool for tool in compile_tools([proxy])} + checked = [] + with tool_dispatch_guard(checked.append): + for verb, call in ( + ("set_proxy", proxy.apply), + ("proxy_status", proxy.status), + ("clear_proxy", proxy.clear), + ): + with pytest.raises(UnsupportedOperation) as raised: + await call() + assert raised.value.verb == verb + with pytest.raises(ToolInvocationError) as tool_error: + await tools[f"proxy.{call.__name__}"].invoke({}) + assert tool_error.value.__context__ is None + assert [info.name for info in checked] == [ + "proxy.apply", + "proxy.status", + "proxy.clear", ] - ) - proxy = CloudFixedProxy("new") - with pytest.raises(UnmanagedProxyConflict): - await proxy.bind(phone) - assert proxy._binding is None - phone.target.status = AsyncMock(side_effect=original) - await proxy.bind(phone, force=True) - assert phone.extensions["proxy"] is proxy - await phone.close() asyncio.run(scenario()) + assert driver.calls == [] -def test_cli_accepts_after_unmanaged_refusal_without_reconciliation(monkeypatch): - from click.testing import CliRunner - - from mobilerun.cli.base import menu - from mobilerun.cli.proxy import group +def test_status_tool_respects_product_override() -> None: + class Product(CloudFixedProxy): + async def status(self) -> ProxyStatus: + return ProxyStatus(True, "socks5", "borrowed") - phone = ProxyMemory(True) - phone.target.current = ProxyStatus(True, "unmanaged") - phone.target.status = AsyncMock( - side_effect=[phone.target.current, RuntimeError("unexpected readback")] + status = next( + tool + for tool in compile_tools([Product("borrowed")]) + if tool.name == "proxy.status" ) - monkeypatch.setattr(menu, "is_interactive", lambda: True) - monkeypatch.setattr(group, "CloudDevice", lambda **kwargs: phone) - - async def accept(message, *, default): - assert default is False - assert phone.target.status.await_count == 1 - phone.target.status = AsyncMock(return_value=phone.target.current) - return True - - monkeypatch.setattr(group, "confirm_prompt_async", accept) - result = CliRunner().invoke(group.proxy, ["bind", "new", "phone"]) - assert result.exit_code == 0, result.output - phone.target.connect.assert_awaited_once_with("new") - - -@pytest.mark.parametrize( - "proxy", - [ - CloudFixedProxy(id="p"), - CloudRotatingProxy(country="US"), - CloudSocks5Proxy("host", 1080), - ], -) -def test_local_rejects_non_http_without_connecting(proxy): - device = AndroidDevice(serial="local") - with pytest.raises(ExtensionNotSupported, match="cloud device"): - asyncio.run(proxy.bind(device)) - - -def test_cloud_rejects_http_without_sdk_calls(): - device = CloudDevice("cloud", api_key="test") - with pytest.raises( - ExtensionNotSupported, - match="local Android", - ): - asyncio.run(LocalProxy("host", 8080).bind(device)) - - -def test_http_application_status_and_clear(monkeypatch): - async def run(): - phone = AndroidDevice(serial="local") - phone._ensure_connected = AsyncMock() - commands: list[str] = [] - value = "null" - - async def shell(command, **kwargs): - nonlocal value - commands.append(command) - if command.startswith("settings put global http_proxy "): - value = command.removeprefix("settings put global http_proxy ").strip( - "'" - ) - return value - - monkeypatch.setattr(phone, "_adb_device", SimpleNamespace(shell=shell)) - proxy = LocalProxy("::1", 8888) - await proxy.bind(phone) - assert await proxy.status() == ProxyStatus(True, "[::1]:8888") - assert phone.extensions["proxy"] is proxy - await proxy.unbind() - assert not phone.extensions - assert await phone._proxy_target.status() == ProxyStatus(False) - assert "settings put global http_proxy '[::1]:8888'" in commands - - asyncio.run(run()) - - -@pytest.mark.parametrize( - ("proxy", "params"), - [ - (CloudFixedProxy(id="managed"), {"connect": {"id": "managed"}}), - ( - CloudRotatingProxy(country="US"), - {"connect": {"country": "US"}, "smart_ip": True}, - ), - ( - CloudSocks5Proxy("host", 1080, "user", "password"), - { - "socks5": { - "host": "host", - "port": 1080, - "user": "user", - "password": "password", - } - }, - ), - ], -) -def test_cloud_proxy_types_status_and_clear(monkeypatch, proxy, params): - from mobilerun.clients.cloud import proxies - - async def run(): - phone = CloudDevice("cloud", api_key="test") - connect = AsyncMock() - disconnect = AsyncMock() - monkeypatch.setattr(proxies, "connect_device", connect) - monkeypatch.setattr(proxies, "disconnect_device", disconnect) - monkeypatch.setattr( - proxies, - "device_status", - AsyncMock( - return_value=SimpleNamespace( - connected=True, name="active", protocol="socks5" - ) - ), - ) - monkeypatch.setattr( - phone, "info", AsyncMock(return_value=SimpleNamespace(state="ready")) - ) - await proxy.bind(phone, force=True) - assert await proxy.status() == ProxyStatus(True, "active", "socks5") - assert connect.await_args is not None - assert connect.await_args.args == ("cloud", params) - assert phone.extensions["proxy"] is proxy - with pytest.raises(ExtensionConflict, match="cloud phones need a proxy"): - await proxy.unbind() - await phone.close() - assert not phone.extensions - disconnect.assert_not_awaited() - - asyncio.run(run()) - - -@pytest.mark.parametrize( - "method,args", - [ - ("set_proxy", (LocalProxy("host", 80),)), - ("clear_proxy", ()), - ("proxy_status", ()), - ], -) -def test_removed_device_proxy_operations(method, args): - with pytest.raises(AttributeError, match=method): - getattr(Device(), method) - - -@pytest.mark.parametrize( - ("proxy", "payload"), - [ - (CloudRotatingProxy("US"), {"connect": {"country": "US"}, "smartIp": True}), - ( - CloudRotatingProxy("DE", smart_ip=False), - {"connect": {"country": "DE"}, "smartIp": False}, - ), - (CloudFixedProxy("existing"), {"connect": {"id": "existing"}}), - ], -) -def test_managed_proxy_sdk_wire_payloads(monkeypatch, proxy, payload): - import json - - import httpx - - from mobilerun.clients.cloud import devices, proxies - from mobilerun.clients.cloud.client import AsyncMobilerun - from mobilerun.core.proxy.target import CloudProxyTarget - - seen = [] - - def handler(request): - seen.append(json.loads(request.content)) - return httpx.Response(200, json={"id": "phone", "name": None}) - - async def run(): - async with AsyncMobilerun( - api_key="test", - base_url="https://sdk.test/v1", - http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)), - ) as client: - monkeypatch.setattr( - proxies, "cloud_client", lambda *args, **kwargs: nullcontext(client) - ) - await devices.create( - client=client, - billing=Billing.PAID, - proxy=cast(devices.Proxy, proxy._parameters()), - ) - - async def connect(params): - await proxies.connect_device("phone", params, billing=Billing.PAID) - return ProxyStatus(True) - - await proxy._apply(CloudProxyTarget(connect)) - - asyncio.run(run()) - assert seen == [{"proxy": payload}, payload] - - -def test_disconnect_conflict_is_clear_not_retried_and_preserves_selection(monkeypatch): - - import httpx - - from mobilerun.clients.cloud import proxies - from mobilerun.clients.cloud.client import AsyncMobilerun - from mobilerun.errors import CloudAPIError - - seen = [] - - def handler(request): - seen.append(request) - return httpx.Response(409, json={"detail": "No devices available"}) - - async def run(): - async with AsyncMobilerun( - api_key="test", - base_url="https://sdk.test/v1", - http_client=httpx.AsyncClient(transport=httpx.MockTransport(handler)), - ) as client: - monkeypatch.setattr( - proxies, "cloud_client", lambda *args, **kwargs: nullcontext(client) - ) - phone = CloudDevice("phone", api_key="test") - with pytest.raises( - CloudAPIError, match="HTTP 409.*backend could not disconnect.*no retry" - ): - await phone._proxy_target.disconnect() - assert not phone.extensions - - asyncio.run(run()) - assert len(seen) == 1 - - -def test_old_managed_proxy_class_is_not_exported(): - import mobilerun.core.proxy as proxies - - assert not hasattr(proxies, "ConnectProxy") - assert not hasattr(CloudFixedProxy("existing"), "smart_ip") - assert not hasattr(CloudSocks5Proxy("host", 1080), "smart_ip") - - -def test_wrapper_pool_proxy_operations(): - from mobilerun.core.proxy.target import AndroidProxyTarget - - class ProxyDevice(MemoryDevice): - def __init__(self): - super().__init__(supported_operations=frozenset({"http_proxy"})) - self.current = ProxyStatus(False) - - @property - def _proxy_target(self): - return AndroidProxyTarget(self.apply, self.status, self.disconnect) - - async def apply(self, host, port): - self.current = ProxyStatus(True, f"{host}:{port}") - return self.current - - async def status(self): - return self.current - - async def disconnect(self): - self.current = ProxyStatus(False) - - async def run(): - pool = DevicePool([DeviceWrapper(ProxyDevice()), ProxyDevice()]) - await pool.bind_each(lambda _: LocalProxy("host", 80)) - assert ( - await pool.actions.call("proxy.status", {}) - == [ProxyStatus(True, "host:80")] * 2 - ) - await pool.unbind_extension("proxy") - assert not any(pool.extensions) - - asyncio.run(run()) - - -@pytest.mark.parametrize("host", ["a>/x", "$(id)", "a b", "a None: + phone = fake_device() + proxy = CloudSocks5Proxy.from_url( + "socks5://user-canary:password-canary@example.test:1080", device=phone ) - monkeypatch.setattr(driver, "AsyncMobilerun", lambda **kw: client) - context = AsyncMock() - context.__aenter__.return_value = client - monkeypatch.setattr(proxies, "cloud_client", lambda *args, **kwargs: context) - - async def run(): - device = CloudDevice("one", api_key="test") - proxy = CloudFixedProxy(id="p") - await proxy.bind(device, force=True) - assert device.extensions["proxy"] is proxy - assert (await proxy.status()).connected - endpoint.connect.assert_awaited_once_with("one", connect={"id": "p"}) - local = AndroidDevice(serial="emulator-5554") - adb = SimpleNamespace(shell=AsyncMock(return_value="example.org:8080")) - monkeypatch.setattr(local, "_adb_device", adb) - local._driver._connected = True - - await LocalProxy("example.org", 8080).bind(local) - replacement = LocalProxy("::1", 8888) - await replacement.bind(local, force=True) - await replacement.unbind() - assert [call.args[0] for call in adb.shell.await_args_list] == [ - "settings put global http_proxy example.org:8080", - "settings get global http_proxy", - "settings put global http_proxy :0", - "settings put global http_proxy '[::1]:8888'", - "settings get global http_proxy", - "settings put global http_proxy :0", - ] - - asyncio.run(run()) - - -def test_paid_setting(monkeypatch): - from mobilerun.config.settings import get_settings - - monkeypatch.setenv("MOBILERUN_BILLING", "paid") - assert get_settings().MOBILERUN_BILLING == "paid" - -def test_connect_proxy_helpers_and_paid_guard(monkeypatch): - from mobilerun.clients.cloud import proxies + async def set_proxy(value: object, *, replace: bool = False) -> None: + assert value is proxy.as_device_proxy() + logging.getLogger(__name__).warning("driver user-canary password-canary") - endpoint = SimpleNamespace( - list=AsyncMock(return_value="list"), - retrieve=AsyncMock(return_value="get"), - ensure_healthy=AsyncMock(), - ping=AsyncMock(), - buy=AsyncMock(), - ) - client = SimpleNamespace(connect=SimpleNamespace(proxies=endpoint)) - client.__aenter__ = AsyncMock(return_value=client) - - class Context: - async def __aenter__(self): - return client - - async def __aexit__(self, *args): - pass - - monkeypatch.setattr(proxies, "cloud_client", lambda *args, **kwargs: Context()) - - async def run(): - assert ( - await proxies.list_proxies(billing=Billing.INCLUDED, country="DE") == "list" - ) - assert await proxies.get_proxy("one", billing=Billing.INCLUDED) == "get" - with pytest.raises(ValueError): - await proxies.buy_proxy("DE", billing=cast(Billing, None)) - endpoint.buy.assert_not_awaited() - await proxies.buy_proxy("DE", billing=Billing.PAID) - endpoint.buy.assert_awaited_once_with(country="DE", type="residential") - - asyncio.run(run()) - - -@pytest.mark.parametrize("billing", ["no_commerce", "included", "paid"]) -def test_connect_country_guard_and_existing_id(monkeypatch, billing): - from mobilerun.clients.cloud import proxies - - endpoint = SimpleNamespace(connect=AsyncMock()) - sdk = SimpleNamespace(devices=SimpleNamespace(proxy=endpoint)) - context = AsyncMock() - context.__aenter__.return_value = sdk - monkeypatch.setattr(proxies, "cloud_client", lambda *args, **kwargs: context) - - async def exercise(): - await proxies.connect_device( - "phone", {"connect": {"id": "existing"}}, billing=billing - ) - endpoint.connect.reset_mock() - if billing == "paid": - await proxies.connect_device( - "phone", {"connect": {"country": "DE"}}, billing=Billing(billing) - ) - endpoint.connect.assert_awaited_once_with( - "phone", connect={"country": "DE"} - ) - else: - with pytest.raises( - ValueError, match="billing='paid'.*MOBILERUN_BILLING=paid" - ): - await proxies.connect_device( - "phone", {"connect": {"country": "DE"}}, billing=billing - ) - endpoint.connect.assert_not_awaited() - - asyncio.run(exercise()) - - -def test_cloud_phone_defaults_to_rotating_proxy_and_rejects_none(monkeypatch): - - monkeypatch.delenv("MOBILERUN_CLOUD_PROXY_COUNTRY", raising=False) - proxy = CloudRotatingProxy._from_settings() - assert proxy.country == "us" and proxy.smart_ip is True - device = CloudDevice(api_key="test") - assert device._create_options["proxy"] == proxy._parameters() - assert device._creation_proxy._parameters() == proxy._parameters() - with pytest.raises(ValueError, match="proxy"): - CloudDevice(api_key="test", proxy=None) - device = CloudDevice(api_key="test", proxy=proxy) - assert device._create_options["proxy"] == { - "connect": {"country": "us"}, - "smart_ip": True, - } + monkeypatch.setattr(phone, "set_proxy", set_proxy) + asyncio.run(proxy.apply()) + assert "driver *** ***" in caplog.text + assert "canary" not in caplog.text diff --git a/tests/unit/core/proxy/test_proxy_cli.py b/tests/unit/core/proxy/test_proxy_cli.py new file mode 100644 index 000000000..4b8b107e0 --- /dev/null +++ b/tests/unit/core/proxy/test_proxy_cli.py @@ -0,0 +1,133 @@ +"""CLI coverage of product projection, billing and the core device seam.""" + +import json +from contextlib import asynccontextmanager +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest +from click.testing import CliRunner +from mobilerun_core import ( + AsyncDevice, + ConnectProxyRef, + ProxyStatus, +) + +from mobilerun.cli.devices.base import selection +from mobilerun.cli.devices.utils import approval +from mobilerun.cli.proxy import group +from mobilerun.core.proxy import account +from tests.support.devices import FakeDriver + + +def test_cli_lists_and_reads_only_safe_account_fields( + monkeypatch: pytest.MonkeyPatch, +) -> None: + row = SimpleNamespace( + id="id-1", + country="de", + type="residential", + status="active", + name="socks5://user-canary:password-canary@example.test:1080", + billing_mode="included", + password="password-canary", + ) + monkeypatch.setattr(account.Proxies, "retrieve", AsyncMock(return_value=row)) + catalogue = AsyncMock( + return_value=SimpleNamespace( + items=[row], pagination=SimpleNamespace(has_next=False) + ) + ) + monkeypatch.setattr(account.Proxies, "list", catalogue) + cli = CliRunner() + status = cli.invoke(group.proxy, ["status", row.id, "--json"]) + included = cli.invoke(group.proxy, ["included", "--json"]) + assert status.exit_code == included.exit_code == 0 + assert json.loads(status.stdout) == { + "id": "id-1", + "country": "de", + "status": "active", + "type": "residential", + } + assert json.loads(included.stdout) == [json.loads(status.stdout)] + assert catalogue.await_args is not None + assert catalogue.await_args.kwargs["included_only"] is True + assert "canary" not in status.output + included.output + + +@pytest.mark.parametrize( + "case", ["first", "first_without_yes", "force", "approve", "unapproved"] +) +def test_cli_bind_uses_core_approval_and_separate_replacement_consent( + monkeypatch: pytest.MonkeyPatch, case: str +) -> None: + calls: list[object] = [] + closed: list[str] = [] + phone_id = "818c5ba1-e22a-4cc8-8408-aeef33d443cf" + occupied = case in {"force", "approve", "unapproved"} + + class ProxyDevice(AsyncDevice): + proxy_types = (ConnectProxyRef,) + + async def _prepare_proxy_set(self, proxy): + async def write(): + calls.append(proxy) + + current = ( + ProxyStatus(True, "socks5", "existing") + if occupied + else ProxyStatus(False, None, None) + ) + return current, write + + async def _proxy_status(self): + return ProxyStatus(True, "socks5", "id-1") + + @asynccontextmanager + async def owner(*, hitl_gate: approval.AsyncHitlGate, **kwargs): + phone = ProxyDevice.from_driver( + FakeDriver(device_id=phone_id), hitl_gate=hitl_gate + ) + + async def connect(identifier, *, backend): + assert identifier == phone_id and backend == "cloud" + return phone + + try: + yield SimpleNamespace(connect=connect) + finally: + await phone.aclose() + closed.append(phone_id) + + monkeypatch.setattr(selection, "AsyncMobilerun", owner) + monkeypatch.setattr( + selection.LoginStore, "resolve_api_key", lambda self: "test-bearer" + ) + monkeypatch.setattr(group.menu, "is_interactive", lambda: case == "approve") + monkeypatch.setattr(approval, "is_interactive", lambda: False) + prompt = AsyncMock(return_value=True) + monkeypatch.setattr(group, "confirm_prompt_async", prompt) + args = ["bind", "id-1", phone_id, "--billing", "no_commerce", "--json"] + if case != "first_without_yes": + args.append("--yes") + if case == "force": + args.append("--force") + success = CliRunner().invoke(group.proxy, args) + assert closed == [phone_id] + if case == "first_without_yes": + assert success.exit_code == 1 and "--yes" in success.stderr + assert calls == [] + assert success.stdout == "" + return + if case == "unapproved": + assert success.exit_code == 1 and "--force" in success.output + assert calls == [] + return + assert success.exit_code == 0, success.output + assert json.loads(success.stdout) == { + "id": "id-1", + "status": "connected", + "device_id": phone_id, + } + assert calls == [ConnectProxyRef("id-1")] + assert prompt.await_count == int(case == "approve") diff --git a/tests/unit/core/proxy/test_proxy_reconciliation.py b/tests/unit/core/proxy/test_proxy_reconciliation.py deleted file mode 100644 index 449bf6f26..000000000 --- a/tests/unit/core/proxy/test_proxy_reconciliation.py +++ /dev/null @@ -1,484 +0,0 @@ -"""Read-only cloud proxy adoption and reconciliation of partial switches.""" - -import asyncio -from types import SimpleNamespace -from typing import cast -from unittest.mock import AsyncMock - -import pytest - -from mobilerun.core.devices import CloudDevice -from mobilerun.core.proxy import CloudFixedProxy, CloudProxy -from mobilerun.errors import ExtensionConflict, ExtensionNotBound -from mobilerun.models.proxy import ProxyStatus -from tests.support.proxy import ProxyMemory - - -@pytest.fixture(autouse=True) -def isolated_number_loading(monkeypatch): - from mobilerun.clients.cloud import devices - - monkeypatch.setattr( - devices, - "capabilities", - AsyncMock( - return_value=SimpleNamespace( - capabilities=SimpleNamespace(telephony=False, proxy=True) - ) - ), - ) - monkeypatch.setattr(CloudDevice, "_load_number", AsyncMock()) - - -@pytest.mark.parametrize("name", ["mrc:known-id", "resolvable-reference"]) -def test_existing_cloud_connect_adopts_known_proxy_without_mutation(monkeypatch, name): - from mobilerun.clients.cloud import proxies - - status = AsyncMock(return_value=ProxyStatus(True, name, "socks5")) - resolve = AsyncMock(return_value=SimpleNamespace(id="known-id")) - switch, disconnect = AsyncMock(), AsyncMock() - monkeypatch.setattr(proxies, "device_status", status) - monkeypatch.setattr(proxies, "get_proxy", resolve) - monkeypatch.setattr(proxies, "connect_device", switch) - monkeypatch.setattr(proxies, "disconnect_device", disconnect) - - async def scenario(): - phone = CloudDevice("phone", api_key="test") - phone._ensure_connected = AsyncMock() - await asyncio.gather(phone.connect(), phone.connect()) - proxy = cast(CloudFixedProxy, phone.proxy) - assert proxy.id == "known-id" - assert proxy.device is phone - assert phone.proxy is proxy - await phone.connect() - status.assert_awaited_once() - assert (await proxy.status()).connected - with pytest.raises(ExtensionConflict, match="cloud phones need a proxy"): - await proxy.unbind() - await phone.close() - switch.assert_not_awaited() - disconnect.assert_not_awaited() - if name.startswith("mrc:"): - resolve.assert_not_awaited() - else: - assert resolve.await_args.args == (name,) - - asyncio.run(scenario()) - - -@pytest.mark.parametrize("name", ["", None, "unresolvable-reference"]) -def test_existing_cloud_connect_adopts_unknown_proxy(monkeypatch, name): - from mobilerun.clients.cloud import proxies - from mobilerun.errors.cloud import CloudResourceNotFound - - status = AsyncMock(return_value=ProxyStatus(True, name, "socks5")) - monkeypatch.setattr(proxies, "device_status", status) - monkeypatch.setattr( - proxies, "get_proxy", AsyncMock(side_effect=CloudResourceNotFound()) - ) - switch = AsyncMock() - monkeypatch.setattr(proxies, "connect_device", switch) - - async def scenario(): - from mobilerun.core.proxy import ExistingCloudProxy - - phone = CloudDevice("phone", api_key="test") - phone._ensure_connected = AsyncMock() - await phone.connect() - observed = cast(ExistingCloudProxy, phone.proxy) - assert observed.exclusive == "proxy" - assert observed.device is phone - assert (await observed.status()).connected - assert "unknown" in str((await observed.context())[0].data) - with pytest.raises(ExtensionConflict, match="cloud phones need a proxy"): - await observed.unbind() - with pytest.raises(ExtensionConflict, match="unbind it first"): - await CloudFixedProxy("new").bind(phone) - switch.assert_not_awaited() - await phone.close() - - asyncio.run(scenario()) - - -def test_disconnected_cloud_connect_has_clear_missing_proxy_error(monkeypatch): - from mobilerun.clients.cloud import proxies - - monkeypatch.setattr( - proxies, "device_status", AsyncMock(return_value=ProxyStatus(False)) - ) - switch = AsyncMock() - monkeypatch.setattr(proxies, "connect_device", switch) - - async def scenario(): - phone = CloudDevice("phone", api_key="test") - phone._ensure_connected = AsyncMock() - await phone.connect() - assert not phone.extensions - with pytest.raises(AttributeError, match=r"no active proxy.*bind"): - _ = phone.proxy - await phone.close() - switch.assert_not_awaited() - - asyncio.run(scenario()) - - -@pytest.mark.parametrize("failure_kind", ["error", "timeout", "cancel"]) -def test_partial_initial_switch_reconciles_before_original_error(failure_kind): - async def scenario(): - phone = ProxyMemory(True) - started = asyncio.Event() - original = RuntimeError("backend changed state then failed") - - async def partial_switch(name): - phone.target.current = ProxyStatus(True, "mrc:actually-active", "socks5") - started.set() - if failure_kind in ("cancel", "timeout"): - await asyncio.Event().wait() - raise original - - phone.target.connect.side_effect = partial_switch - incoming = CloudFixedProxy("requested") - - async def bind(): - async with asyncio.timeout(0.05 if failure_kind == "timeout" else None): - await incoming.bind(phone) - - task = asyncio.create_task(bind()) - await started.wait() - if failure_kind == "cancel": - task.cancel() - error_type = { - "error": RuntimeError, - "timeout": TimeoutError, - "cancel": asyncio.CancelledError, - }[failure_kind] - with pytest.raises(error_type) as raised: - await task - if failure_kind == "error": - assert raised.value is original - actual = cast(CloudFixedProxy, phone.proxy) - assert actual.id == "actually-active" - assert actual.device is phone - assert incoming.device is None - assert (await actual.status()).connected - assert phone.target.connect.await_count == 1 - await phone.close() - - asyncio.run(scenario()) - - -def test_partial_bind_failed_status_read_marks_uncertain_and_preserves_error(): - async def scenario(): - phone = ProxyMemory(True) - original = RuntimeError("switch failed") - phone.target.connect.side_effect = original - phone.target.status = AsyncMock( - side_effect=[ProxyStatus(False), RuntimeError("status failed")] - ) - incoming = CloudFixedProxy("requested") - with pytest.raises(RuntimeError) as raised: - await incoming.bind(phone) - assert raised.value is original - assert any("uncertain" in note for note in original.__notes__) - assert phone.extensions["proxy"] is incoming - with pytest.raises(ExtensionNotBound, match="uncertain"): - await incoming.status() - await phone.close() - - asyncio.run(scenario()) - - -@pytest.mark.parametrize( - "remote", - [ProxyStatus(True, "mrc:actual"), ProxyStatus(True, ""), ProxyStatus(False)], -) -def test_failed_force_rollback_adopts_actual_remote_state(remote): - async def scenario(): - phone = ProxyMemory(True) - old = CloudFixedProxy("old") - await old.bind(phone) - original = RuntimeError("switch failed") - - async def fail(name): - phone.target.current = remote - raise original - - phone.target.connect.side_effect = fail - incoming = CloudFixedProxy("new") - with pytest.raises(RuntimeError) as raised: - await incoming.bind(phone, force=True) - assert raised.value is original - assert old.device is None - assert incoming.device is None - if remote.connected: - adopted = cast(CloudProxy, phone.proxy) - assert adopted.device is phone - if remote.name: - assert cast(CloudFixedProxy, phone.proxy).id == "actual" - else: - from mobilerun.core.proxy import ExistingCloudProxy - - assert cast(ExistingCloudProxy, phone.proxy) is adopted - assert not adopted._binding.uncertain - else: - assert not phone.extensions - await phone.close() - - asyncio.run(scenario()) - - -@pytest.mark.parametrize("remote_name", ["mrc:old", "old", ""]) -def test_successful_force_rollback_preserves_original_matching_or_unknown_proxy( - remote_name, -): - async def scenario(): - phone = ProxyMemory(True) - old = CloudFixedProxy("old") - await old.bind(phone, close_on_device_close=True) - original_binding = old._binding - original = RuntimeError("switch response lost") - - async def connect(name): - phone.target.current = ProxyStatus(True, remote_name) - if name == "new": - raise original - return ProxyStatus(True, "old") - - phone.target.connect.side_effect = connect - incoming = CloudFixedProxy("new") - with pytest.raises(RuntimeError) as raised: - await incoming.bind(phone, force=True) - assert raised.value is original - assert phone.proxy is old - assert old._binding is original_binding - assert old._binding.owned - assert not old._binding.uncertain - assert old.device is phone - assert incoming.device is None - await phone.close() - - asyncio.run(scenario()) - - -@pytest.mark.parametrize("cancel_readback", [False, True]) -def test_successful_force_rollback_still_adopts_remote_truth(cancel_readback): - async def scenario(): - phone = ProxyMemory(True) - old = CloudFixedProxy("old") - await old.bind(phone) - original = RuntimeError("switch response lost") - - async def connect(name): - phone.target.current = ProxyStatus(True, "mrc:actual") - if name == "new": - raise original - # Rollback returns success, but remote truth still differs. - return ProxyStatus(True, "mrc:old") - - phone.target.connect.side_effect = connect - readback_started, finish_readback = asyncio.Event(), asyncio.Event() - original_reconcile = old._reconcile_bind_failure - - async def readback(device, failure): - readback_started.set() - await finish_readback.wait() - await original_reconcile(device, failure) - - reconcile = AsyncMock(side_effect=readback) - old._reconcile_bind_failure = reconcile - incoming = CloudFixedProxy("new") - switching = asyncio.create_task(incoming.bind(phone, force=True)) - await readback_started.wait() - if cancel_readback: - for _ in range(2): - switching.cancel() - await asyncio.sleep(0) - assert not switching.done() - finish_readback.set() - with pytest.raises(RuntimeError) as raised: - await switching - assert raised.value is original - reconcile.assert_awaited_once_with(phone, original) - assert cast(CloudFixedProxy, phone.proxy).id == "actual" - assert not phone.proxy._binding.uncertain - assert old.device is None - assert incoming.device is None - await phone.close() - - asyncio.run(asyncio.wait_for(scenario(), timeout=2)) - - -def test_unknown_proxy_satisfies_public_contract(): - from mobilerun.core.proxy import ExistingCloudProxy - from tests.support.extensions import check_extension_contract - - async def device(): - phone = ProxyMemory(True) - phone.target.current = ProxyStatus(True, "") - return phone - - async def incompatible(): - return ProxyMemory(False) - - asyncio.run( - check_extension_contract( - lambda name: ExistingCloudProxy(name=name), - device, - incompatible_device=incompatible, - unbind_requires_replacement=True, - ) - ) - - -def test_repeated_cancel_waits_for_reconciliation_and_preserves_first_cancel(): - async def scenario(): - phone = ProxyMemory(True) - switched, reading, release_read = ( - asyncio.Event(), - asyncio.Event(), - asyncio.Event(), - ) - status_calls = 0 - - async def switch(name): - switched.set() - await asyncio.Event().wait() - - async def status(): - nonlocal status_calls - status_calls += 1 - if status_calls == 1: - return ProxyStatus(False) - reading.set() - await release_read.wait() - return ProxyStatus(True, "mrc:actual") - - phone.target.connect.side_effect = switch - phone.target.status = status - task = asyncio.create_task(CloudFixedProxy("requested").bind(phone)) - await switched.wait() - task.cancel("first cancellation") - await reading.wait() - task.cancel("second cancellation") - release_read.set() - with pytest.raises(asyncio.CancelledError) as raised: - await task - assert raised.value.args == ("first cancellation",) - assert cast(CloudFixedProxy, phone.proxy).id == "actual" - await phone.close() - - asyncio.run(asyncio.wait_for(scenario(), timeout=2)) - - -def test_connect_recovers_uncertain_proxy_without_switching(monkeypatch): - from mobilerun.clients.cloud import proxies - - original = RuntimeError("switch failed") - status = AsyncMock( - side_effect=[ - ProxyStatus(False), - RuntimeError("status unavailable"), - ProxyStatus(True, "mrc:actual"), - ] - ) - switch = AsyncMock(side_effect=original) - monkeypatch.setattr(proxies, "device_status", status) - monkeypatch.setattr(proxies, "connect_device", switch) - - async def scenario(): - phone = CloudDevice("phone", api_key="test") - phone._ensure_connected = AsyncMock() - with pytest.raises(RuntimeError) as raised: - await CloudFixedProxy("requested").bind(phone) - assert raised.value is original - with pytest.raises(ExtensionNotBound, match="uncertain"): - await phone.proxy.status() - await phone.connect() - assert cast(CloudFixedProxy, phone.proxy).id == "actual" - assert not phone.extensions["proxy"]._binding.uncertain - switch.assert_awaited_once() - await phone.close() - - asyncio.run(scenario()) - - -def test_unknown_proxy_is_replaced_only_with_force_without_disconnect(): - from mobilerun.core.proxy import ExistingCloudProxy - - async def scenario(): - phone = ProxyMemory(True) - phone.target.current = ProxyStatus(True, "") - observed = ExistingCloudProxy() - await observed.bind(phone) - incoming = CloudFixedProxy("new") - with pytest.raises(ExtensionConflict, match="unbind it first"): - await incoming.bind(phone) - phone.target.connect.assert_not_awaited() - await incoming.bind(phone, force=True) - assert phone.proxy is incoming - assert observed.device is None - assert incoming.device is phone - assert phone.target.connect.await_count == 1 - assert phone.target.disconnect_calls == 0 - await phone.close() - - asyncio.run(scenario()) - - -def test_existing_phone_failed_status_read_can_be_retried(monkeypatch): - from mobilerun.clients.cloud import proxies - - unavailable = RuntimeError("status unavailable") - status = AsyncMock(side_effect=[unavailable, ProxyStatus(True, "mrc:actual")]) - monkeypatch.setattr(proxies, "device_status", status) - - async def scenario(): - phone = CloudDevice("phone", api_key="test") - phone._ensure_connected = AsyncMock() - with pytest.raises(RuntimeError) as raised: - await phone.connect() - assert raised.value is unavailable - assert not phone.extensions - await phone.connect() - assert cast(CloudFixedProxy, phone.proxy).id == "actual" - await phone.close() - - asyncio.run(scenario()) - - -@pytest.mark.parametrize("lookup_timeout", [False, True]) -def test_failed_identity_lookup_adopts_known_active_unknown_instead_of_uncertain( - monkeypatch, lookup_timeout -): - from mobilerun.core.proxy import ExistingCloudProxy, adoption - - monkeypatch.setattr(adoption, "_READBACK_TIMEOUT", 0.02) - - async def scenario(): - phone = ProxyMemory(True) - original = RuntimeError("partial switch failed") - - async def switch(name): - phone.target.current = ProxyStatus(True, "unresolved-alias") - raise original - - phone.target.connect.side_effect = switch - - async def resolve(reference): - if lookup_timeout: - await asyncio.Event().wait() - raise RuntimeError("identity lookup failed") - - phone.target._resolve_reference = resolve - requested = CloudFixedProxy("requested") - with pytest.raises(RuntimeError) as raised: - await requested.bind(phone) - assert raised.value is original - actual = cast(ExistingCloudProxy, phone.proxy) - assert actual.device is phone - assert not actual._binding.uncertain - assert requested.device is None - assert (await actual.status()).connected - await phone.close() - - asyncio.run(scenario()) diff --git a/tests/unit/core/runs/test_device_identity.py b/tests/unit/core/runs/test_device_identity.py new file mode 100644 index 000000000..580dec85b --- /dev/null +++ b/tests/unit/core/runs/test_device_identity.py @@ -0,0 +1,20 @@ +"""The run wire format stores the route, not an observation handle ID.""" + +import json +from pathlib import Path + +import pytest +from mobilerun_core import AsyncDevice + +from mobilerun.core.runs import ActionRecording +from tests.support.devices import FakeDriver + + +@pytest.mark.anyio +async def test_manifest_keeps_minimal_route_identity(tmp_path: Path) -> None: + phone = AsyncDevice.from_driver(FakeDriver(device_id="phone-route")) + async with ActionRecording(phone, runs_dir=tmp_path) as recording: + assert phone.observation_device_id != "phone-route" + await phone.tap(1, 2) + manifest = json.loads((recording.run_dir / "run.json").read_text()) + assert manifest["device"] == {"identifier": "phone-route", "platform": "android"} diff --git a/tests/unit/core/runs/test_evidence.py b/tests/unit/core/runs/test_evidence.py new file mode 100644 index 000000000..442981a23 --- /dev/null +++ b/tests/unit/core/runs/test_evidence.py @@ -0,0 +1,118 @@ +import json +from pathlib import Path + +import pytest + +from mobilerun.core.runs import ScreenRecording, observation_fingerprint +from mobilerun.core.runs.evidence import ScreenSample +from mobilerun.core.screen import ScreenProvider +from mobilerun.utils.redaction import Redactor, secret_scope +from tests.support.devices import FakeDriver, fake_device + + +@pytest.mark.anyio +@pytest.mark.parametrize("failed_read", ["get_ui_tree", "screenshot"]) +async def test_capture_keeps_successful_channel_in_observation(tmp_path, failed_read): + driver = FakeDriver(failures={failed_read: RuntimeError("read failed")}) + async with fake_device(driver=driver) as device: + sample = await ScreenSample.capture(device) + assert sample.observation is not None + assert sample.observation.device_id == device.observation_device_id + assert sample.observation.observation_id + assert sample.observation.tree_present is (failed_read == "screenshot") + expected_screenshot = ( + driver.screenshot_bytes if failed_read == "get_ui_tree" else None + ) + assert sample.observation.screenshot == expected_screenshot + + files = sample.save(tmp_path, 1, "before", Redactor()) + assert set(files) == ({"png"} if failed_read == "get_ui_tree" else {"json"}) + + +@pytest.mark.anyio +@pytest.mark.parametrize( + ("app", "local_mask", "scoped_mask", "prompt_app", "replay_app"), + [ + ("example.app", (), (), "example.app", "example.app"), + (None, (), (), None, None), + ("example.private", ("private",), (), None, None), + ("example.private", (), ("private",), "example.private", None), + ("example.***", (), (), None, "example.***"), + ], + ids=["safe", "empty", "run-mask", "scope-mask", "literal-marker"], +) +async def test_prompt_and_replay_keep_distinct_fingerprint_masking( + app: str | None, + local_mask: tuple[str, ...], + scoped_mask: tuple[str, ...], + prompt_app: str | None, + replay_app: str | None, +) -> None: + driver = FakeDriver(ui_tree={"phone_state": {"packageName": app}, "a11y_tree": []}) + redactor = Redactor() + redactor.remember_sensitive(local_mask) + with secret_scope(*scoped_mask): + async with fake_device(driver=driver) as device: + prompt = ( + await ScreenProvider(device, redactor=redactor).observe() + ).fingerprint + observation = await device.observe(screenshot=False) + assert observation.tree_present + replay = observation_fingerprint(observation, redactor=redactor) + assert (prompt.app if prompt else None) == prompt_app + assert (replay.app if replay else None) == replay_app + assert (prompt is None) == (prompt_app is None) + assert (replay is None) == (replay_app is None) + + +@pytest.mark.anyio +@pytest.mark.parametrize( + ("marker", "secure"), + [ + ({"inputType": 129}, True), + ({"inputType": 0x91}, True), + ({"inputType": "0xe1"}, True), + ({"inputType": 0x1012}, True), + ({"isPassword": True}, True), + ({"inputType": 0x11}, False), # Text URI, not a number password. + ], + ids=["text", "visible", "web", "number", "flag", "text-uri"], +) +async def test_recording_masks_native_password_evidence( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + marker: dict[str, object], + secure: bool, +) -> None: + monkeypatch.setenv("MOBILERUN_RUN_SETTLE_SECONDS", "0") + canary = "synthetic-password-canary" + driver = FakeDriver() + driver.ui_tree["a11y_tree"][0].update(text=canary, **marker) + driver.ui_tree["a11y_tree"].append( + {"className": "TextView", "text": f"Copy: {canary}"} + ) + + async with fake_device(driver=driver) as phone: + observation = await phone.observe(screenshot=False) + async with ScreenRecording(phone, runs_dir=tmp_path) as rec: + await phone.tap(50, 60) + + (row,) = [ + json.loads(line) + for line in (rec.run_dir / "steps.jsonl").read_text().splitlines() + ] + assert row["action"] == "tap" + for phase in ("before", "after"): + state = (rec.run_dir / f"screens/1.{phase}.json").read_text() + if (canary not in state) is not secure: + pytest.fail(f"Wrong {phase} JSON masking") + assert (row[phase] is None) is secure + ui = json.loads(state)["ui"] + if secure: + assert ui["focused_text"] == "***" + assert [node["text"] for node in ui["elements"]] == ["***", "***"] + assert "inputType" not in state and "a11y_tree" not in state + assert (rec.run_dir / f"screens/1.{phase}.png").read_bytes() == ( + driver.screenshot_bytes + ) + assert (observation_fingerprint(observation) is None) is secure diff --git a/tests/unit/core/runs/test_recording.py b/tests/unit/core/runs/test_recording.py new file mode 100644 index 000000000..7d45e789d --- /dev/null +++ b/tests/unit/core/runs/test_recording.py @@ -0,0 +1,489 @@ +import asyncio +import json +from datetime import UTC, datetime +from pathlib import Path +from types import SimpleNamespace +from unittest.mock import AsyncMock + +import pytest +from mobilerun_core import ( + ActionEvent, + ActionHookError, + ActionHooksAlreadyInstalledError, + AsyncDevice, + HitlDenied, + Secret, +) + +from mobilerun.clients.cloud import mailboxes, numbers +from mobilerun.core.mailbox import CloudMailbox +from mobilerun.core.phone_number import CloudPhoneNumber +from mobilerun.core.runs import ( + ActionRecording, + ScreenRecording, + recording_scope, + screen, +) +from mobilerun.macro import build_macro +from mobilerun.macro.builder import load_macro +from mobilerun.macro.errors import MacroError +from mobilerun.macro.player import MacroPlayer +from mobilerun.utils.redaction import redact, secret_scope +from tests.support.devices import FakeDriver, fake_device + + +@pytest.fixture(autouse=True) +def no_screen_settle(monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("MOBILERUN_RUN_SETTLE_SECONDS", "0") + + +def rows(directory: Path) -> list[dict]: + return [ + json.loads(line) + for line in (directory / "steps.jsonl").read_text().splitlines() + ] + + +def manifest(directory: Path) -> dict: + return json.loads((directory / "run.json").read_text()) + + +def assert_absent_from_run(directory: Path, canary: str) -> None: + for path in directory.rglob("*"): + if path.is_file() and canary.encode() in path.read_bytes(): + pytest.fail(f"Sensitive input was written to {path.name}", pytrace=False) + + +@pytest.fixture +def mailbox_with_code(monkeypatch: pytest.MonkeyPatch) -> CloudMailbox: + monkeypatch.setattr( + mailboxes.Mailboxes, + "otp", + AsyncMock(return_value=SimpleNamespace(data=SimpleNamespace(code="761823"))), + ) + return CloudMailbox("existing") + + +@pytest.mark.anyio +@pytest.mark.parametrize("channel", ["email", "sms"]) +async def test_verification_code_is_masked_and_not_replayed( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + mailbox_with_code: CloudMailbox, + channel: str, +) -> None: + canary = "761823" + monkeypatch.setenv("MOBILERUN_MACRO_DIRECTORY", str(tmp_path / "macros")) + message = numbers.MessageItem.model_validate( + { + "id": "sms", + "direction": "inbound", + "body": f"Your code is {canary}", + "status": "received", + "createdAt": datetime.now(UTC), + "occurredAt": datetime.now(UTC), + } + ) + monkeypatch.setattr(numbers.Numbers, "messages", AsyncMock(return_value=[message])) + resource = mailbox_with_code if channel == "email" else CloudPhoneNumber("existing") + + phone = fake_device() + async with ActionRecording(phone, runs_dir=tmp_path) as rec: + await phone.tap(1, 2) + await phone.type(await resource.wait_for_code()) + assert_absent_from_run(rec.run_dir, canary) + _, typed = rows(rec.run_dir) + assert typed["ok"] and typed["args"]["text"] == "***" + macro = build_macro(rec.run_dir / "steps.jsonl", "tap-only") + assert [(step.i, step.action.name) for step in load_macro(macro)] == [(1, "tap")] + + +@pytest.mark.anyio +async def test_code_read_updates_all_recordings_in_context_but_not_another_task( + tmp_path: Path, mailbox_with_code: CloudMailbox +) -> None: + first, second, other = (fake_device() for _ in range(3)) + other_started = asyncio.Event() + read_ready = asyncio.Event() + + async def independent() -> ActionRecording: + async with ActionRecording(other, runs_dir=tmp_path) as rec: + other_started.set() + await read_ready.wait() + # This task never reads an OTP; its text is not a known secret here. + await other.type("761823") + return rec + + other_task = asyncio.create_task(independent()) + try: + await asyncio.wait_for(other_started.wait(), timeout=2) + with secret_scope("outer-mask"): + async with ActionRecording(first, runs_dir=tmp_path) as outer: + async with ActionRecording(second, runs_dir=tmp_path) as inner: + with secret_scope("temporary-mask"): + code = await mailbox_with_code.wait_for_code() + read_ready.set() + await second.type(f"code: {code}") + await first.type(code) + await first.type("outer-mask") + assert redact("outer-mask") == "***" + assert redact(code) != "***" + unrelated = await other_task + finally: + if not other_task.done(): + other_task.cancel() + with pytest.raises(asyncio.CancelledError): + await other_task + + for rec in (outer, inner): + assert_absent_from_run(rec.run_dir, "761823") + assert_absent_from_run(rec.run_dir, "outer-mask") + assert rows(rec.run_dir)[0]["args"]["text"] == "***" + if rows(unrelated.run_dir)[0]["args"]["text"] != "761823": + pytest.fail("An unrelated recording changed ordinary text", pytrace=False) + + +@pytest.mark.anyio +async def test_clipboard_payload_is_masked_without_known_values(tmp_path: Path) -> None: + canary = "clipboard-canary" + driver = FakeDriver() + driver.supported.add("set_clipboard") + phone = fake_device(driver=driver) + async with ActionRecording(phone, runs_dir=tmp_path) as rec: + await phone.set_clipboard(canary) + assert_absent_from_run(rec.run_dir, canary) + (row,) = rows(rec.run_dir) + assert row["ok"] and row["args"] == {"value": "***"} + + +@pytest.mark.anyio +async def test_action_rows_use_core_arguments_and_record_outcomes( + tmp_path: Path, +) -> None: + driver = FakeDriver() + phone = fake_device(driver=driver) + async with ActionRecording(phone, runs_dir=tmp_path) as rec: + assert rec.device is phone + with rec.collect_steps() as committed: + await phone.tap(10, 20) + assert await phone.type("hello") is True + with pytest.raises(ValueError) as failure: + await phone.key("power") + with recording_scope(by="agent"): + await phone.wait(0) + assert committed == [1, 2, 3, 4] + rec.finish("succeeded") + + written = rows(rec.run_dir) + assert [row["action"] for row in written] == ["tap", "type", "key", "wait"] + assert [row["i"] for row in written] == [1, 2, 3, 4] + assert all(row["schema_version"] == 2 and row["screens"] is None for row in written) + assert written[0]["args"] == {"x": 10, "y": 20} + assert written[1]["args"] == { + "text": "hello", + "clear": False, + "humanize": None, + "wpm": None, + } + assert written[1]["result"] is True and written[1]["error"] is None + assert written[2]["ok"] is False and written[2]["result"] is None + assert written[2]["error"] == type(failure.value).__name__ + assert written[3]["args"] == {"seconds": 0} and written[3]["by"] == "agent" + assert [call[0] for call in driver.calls] == ["tap", "input_text"] + times = [ + datetime.fromisoformat(row[key]) + for row in written + for key in ("started_at", "finished_at") + ] + assert times == sorted(times) + assert manifest(rec.run_dir)["schema_version"] == 2 + assert manifest(rec.run_dir)["status"] == "succeeded" + + +@pytest.mark.anyio +@pytest.mark.parametrize("approved", [True, False], ids=["succeeded", "denied"]) +async def test_only_successful_element_taps_are_replayable( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, approved: bool +) -> None: + monkeypatch.setenv("MOBILERUN_MACRO_DIRECTORY", str(tmp_path / "macros")) + driver = FakeDriver() + async with fake_device(driver=driver, hitl_gate=lambda *_: approved) as phone: + observation = await phone.observe() + assert observation.elements is not None + (element,) = observation.elements + async with ActionRecording(phone, runs_dir=tmp_path) as rec: + if approved: + await phone.tap_element(element) + else: + with pytest.raises(HitlDenied): + await phone.tap_element(element) + + (row,) = rows(rec.run_dir) + steps_path = rec.run_dir / "steps.jsonl" + taps = [call for call in driver.calls if call[0] == "tap"] + assert row["schema_version"] == 2 + assert row["result"] is None + if not approved: + assert row["action"] == "tap_element" + assert row["args"] == {"element": "***"} + assert row["ok"] is False and row["error"] == "HitlDenied" + assert taps == [] + with pytest.raises(MacroError, match="No replayable steps"): + build_macro(steps_path, "element-tap") + return + + assert taps == [("tap", (20, 30), {})] + assert row["action"] == "tap" + assert row["args"] == {"x": 20, "y": 30} + assert row["ok"] is True and row["error"] is None + macro = build_macro(steps_path, "element-tap") + replay_driver = FakeDriver() + async with fake_device(driver=replay_driver) as replay_phone: + assert await MacroPlayer(replay_phone).replay_macro(load_macro(macro)) + assert replay_driver.calls == [("tap", (20, 30), {})] + + +@pytest.mark.anyio +async def test_exit_releases_hooks_without_closing_device(tmp_path: Path) -> None: + phone = fake_device() + with pytest.raises(LookupError, match="body error"): + async with ActionRecording(phone, runs_dir=tmp_path) as first: + await phone.tap(1, 1) + with pytest.raises(ActionHooksAlreadyInstalledError): + async with ActionRecording(phone, runs_dir=tmp_path): + pytest.fail("second recorder attached") + raise LookupError("body error") + async with ActionRecording(phone, runs_dir=tmp_path) as second: + await phone.tap(2, 2) + await phone.tap(3, 3) + assert [row["args"]["x"] for row in rows(first.run_dir)] == [1] + assert [row["args"]["x"] for row in rows(second.run_dir)] == [2] + assert manifest(first.run_dir)["status"] == "failed" + assert manifest(second.run_dir)["status"] == "cancelled" + + +@pytest.mark.anyio +async def test_custom_after_hook_and_explicit_failed_finish(tmp_path: Path) -> None: + class CustomRecording(ActionRecording): + async def after_action(self, device: AsyncDevice, event: ActionEvent) -> None: + if event.action.name == "wait": + raise LookupError("sink failed after dispatch") + await super().after_action(device, event) + + phone = fake_device() + async with CustomRecording(phone, runs_dir=tmp_path) as rec: + await phone.tap(1, 2) + with pytest.raises(ActionHookError): + await phone.wait(0) + rec.finish("failed") + assert [row["action"] for row in rows(rec.run_dir)] == ["tap"] + assert manifest(rec.run_dir)["status"] == "failed" + await phone.wait(0) + + +@pytest.mark.anyio +async def test_extension_call_suppresses_nested_rows_and_redacts_args( + tmp_path: Path, +) -> None: + phone = fake_device() + async with ActionRecording(phone, runs_dir=tmp_path) as rec: + rec.redactor.remember_codes("482913") + async with rec.extension_call( + "mail.confirm", {"text": "code: 482 913"} + ) as outcome: + await asyncio.create_task(phone.tap(1, 2)) + async with rec.extension_call("mail.helper", {}): + await phone.wait(0) + outcome.set_result("do not persist this service response") + with pytest.raises(ValueError), recording_scope(enabled=False): + async with rec.extension_call("mail.suppressed", {}): + raise ValueError("not persisted") + await phone.tap(3, 4) + written = rows(rec.run_dir) + assert [row["action"] for row in written] == ["extension_call", "tap"] + assert written[0]["args"] == {"name": "mail.confirm", "arguments": {"text": "***"}} + assert written[0]["result"] is None + + +@pytest.mark.anyio +async def test_cancelling_recording_preserves_committed_rows(tmp_path: Path) -> None: + committed = asyncio.Event() + phone = fake_device() + rec = ActionRecording(phone, runs_dir=tmp_path) + rec.redactor.remember_sensitive("cancel-canary") + + async def run() -> None: + try: + async with rec: + await phone.tap(1, 2) + committed.set() + assert redact("cancel-canary") == "***" + await asyncio.Future() + finally: + assert redact("cancel-canary") != "***" + + task = asyncio.create_task(run()) + await asyncio.wait_for(committed.wait(), timeout=2) + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + await phone.wait(0) + assert [(row["action"], row["ok"]) for row in rows(rec.run_dir)] == [("tap", True)] + assert manifest(rec.run_dir)["status"] == "cancelled" + + +@pytest.mark.anyio +async def test_screen_recording_links_fresh_evidence_and_does_not_record_reads( + tmp_path: Path, +) -> None: + driver = FakeDriver() + phone = fake_device(driver=driver) + async with ScreenRecording(phone, runs_dir=tmp_path) as rec: + assert await rec.checkpoint() is not None + assert not rec.run_dir.exists() + await phone.observe() + await phone.tap(10, 20) + (row,) = rows(rec.run_dir) + assert row["action"] == "tap" + assert [call[0] for call in driver.calls] == [ + "get_ui_tree", + "screenshot", + "get_ui_tree", + "get_ui_tree", + "screenshot", + "tap", + "get_ui_tree", + "screenshot", + ] + for phase in ("before", "after"): + assert row[phase] is not None + assert row["screens"][phase] == { + "json": f"screens/1.{phase}.json", + "png": f"screens/1.{phase}.png", + } + state = json.loads((rec.run_dir / row["screens"][phase]["json"]).read_text()) + assert state["ui"]["elements"] + image = (rec.run_dir / row["screens"][phase]["png"]).read_bytes() + assert image == driver.screenshot_bytes + + +@pytest.mark.anyio +async def test_secret_is_masked_and_screen_pixels_are_still_saved( + tmp_path: Path, +) -> None: + phone = fake_device() + async with ScreenRecording(phone, runs_dir=tmp_path) as rec: + await phone.type_secret(Secret("credential-canary")) + with secret_scope("scoped-canary"): + await phone.type("scoped-canary") + first, second = rows(rec.run_dir) + assert first["action"] == "type_secret" and first["ok"] is True + assert first["args"] == {"secret": "***", "clear": False} + assert second["args"]["text"] == "***" + for row in (first, second): + assert row["after"] is None + files = row["screens"]["after"] + assert (rec.run_dir / files["png"]).is_file() + assert json.loads((rec.run_dir / files["json"]).read_text())["ui"] == "***" + assert "canary" not in (rec.run_dir / "steps.jsonl").read_text() + + +@pytest.mark.anyio +@pytest.mark.parametrize("seconds", [0.0, 0.42]) +async def test_screen_recording_settles_only_between_dispatch_and_after_capture( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, seconds: float +) -> None: + monkeypatch.setenv("MOBILERUN_RUN_SETTLE_SECONDS", str(seconds)) + driver = FakeDriver() + phone = fake_device(driver=driver) + sleeps: list[tuple[float, list[str]]] = [] + + async def sleep(delay: float) -> None: + sleeps.append((delay, [call[0] for call in driver.calls])) + + monkeypatch.setattr( + screen, + "asyncio", + SimpleNamespace(sleep=sleep), + ) + async with ScreenRecording(phone, runs_dir=tmp_path) as rec: + await phone.tap(1, 2) + + before_settle = ["get_ui_tree", "screenshot", "tap"] + assert sleeps == ([(seconds, before_settle)] if seconds else []) + assert [call[0] for call in driver.calls] == [ + *before_settle, + "get_ui_tree", + "screenshot", + ] + assert [row["action"] for row in rows(rec.run_dir)] == ["tap"] + + +@pytest.mark.anyio +async def test_explicit_failed_finish_after_first_custom_hook_failure( + tmp_path: Path, +) -> None: + class BrokenRecording(ActionRecording): + async def after_action(self, device: AsyncDevice, event: ActionEvent) -> None: + raise LookupError("first post hook failed") + + phone = fake_device() + async with BrokenRecording(phone, runs_dir=tmp_path) as rec: + with pytest.raises(ActionHookError): + await phone.tap(1, 2) + rec.finish("failed") + assert rows(rec.run_dir) == [] + assert manifest(rec.run_dir)["status"] == "failed" + + +@pytest.mark.anyio +async def test_evidence_sink_failure_keeps_committed_rows_and_never_redispatches( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + driver = FakeDriver() + phone = fake_device(driver=driver) + async with ScreenRecording(phone, runs_dir=tmp_path) as rec: + await phone.tap(1, 1) + with monkeypatch.context() as patch: + + def fail_write(path: Path, data: bytes) -> int: + raise OSError("private failure detail") + + patch.setattr(Path, "write_bytes", fail_write) + with pytest.raises(ActionHookError) as failure: + await phone.tap(2, 2) + assert str(failure.value.__cause__) == "Recording sink failed" + with pytest.raises(ActionHookError): + await phone.tap(3, 3) + rec.finish("failed") + + assert [call[1] for call in driver.calls if call[0] == "tap"] == [(1, 1), (2, 2)] + assert [row["i"] for row in rows(rec.run_dir)] == [1] + assert manifest(rec.run_dir)["status"] == "failed" + + +@pytest.mark.anyio +async def test_screen_json_redacts_known_codes_and_secure_values( + tmp_path: Path, +) -> None: + driver = FakeDriver( + ui_tree={ + "phone_state": {"packageName": "example.app"}, + "a11y_tree": [ + {"className": "EditText", "isPassword": True, "text": "prefilled-pass"}, + {"className": "TextView", "text": "prefilled-pass / code 482 913"}, + {"className": "TextView", "text": "code 482 913"}, + ], + } + ) + phone = fake_device(driver=driver) + async with ScreenRecording(phone, runs_dir=tmp_path) as rec: + rec.redactor.remember_codes("482913") + await phone.tap(1, 2) + (row,) = rows(rec.run_dir) + assert row["before"] is None and row["after"] is None + for evidence in row["screens"].values(): + state = (rec.run_dir / evidence["json"]).read_text() + assert "prefilled-pass" not in state and "482 913" not in state + assert "***" in state + assert (rec.run_dir / evidence["png"]).read_bytes() == driver.screenshot_bytes diff --git a/tests/unit/core/runs/test_writer.py b/tests/unit/core/runs/test_writer.py index 88247d04e..7370de63a 100644 --- a/tests/unit/core/runs/test_writer.py +++ b/tests/unit/core/runs/test_writer.py @@ -6,6 +6,7 @@ from stat import S_IMODE import pytest +from mobilerun_core import Action @pytest.fixture @@ -13,6 +14,7 @@ def record(): from mobilerun.models import DeviceInfo, RunRecord return RunRecord( + schema_version=2, run_id="run-1", kind="recording", device=DeviceInfo(platform="android", identifier="fake"), @@ -24,11 +26,11 @@ def _step(i=1, ok=True): from mobilerun.models import RunStep return RunStep( + schema_version=2, i=i, started_at=datetime.now(timezone.utc), finished_at=datetime.now(timezone.utc), - action="tap", - args={"x": 1, "y": 2}, + action=Action("tap", {"x": 1, "y": 2}, "device"), ok=ok, by="script", ) @@ -46,7 +48,10 @@ def test_writer_starts_lazily_commits_rows_and_atomically_finishes(record, tmp_p manifest = writer.run_dir / "run.json" rows = writer.run_dir / "steps.jsonl" assert json.loads(manifest.read_text())["status"] == "running" - assert json.loads(rows.read_text())["i"] == 1 + payload = json.loads(rows.read_text()) + assert payload["i"] == 1 + assert payload["action"] == "tap" + assert payload["args"] == {"x": 1, "y": 2} assert writer.step_index == 1 writer.append(_step(2, ok=False)) with manifest.open() as original: @@ -151,6 +156,28 @@ def fail_replace(source, destination): writer.finish("succeeded") +def test_short_append_rolls_back_incomplete_jsonl_row(record, tmp_path, monkeypatch): + from mobilerun.core.runs import RunWriter + from mobilerun.core.runs import writer as writer_module + + writer = RunWriter(record, tmp_path) + writer.append(_step()) + rows = writer.run_dir / "steps.jsonl" + original = rows.read_bytes() + write = os.write + + def partial_write(fd: int, data: bytes) -> int: + return write(fd, data[:8]) + + with monkeypatch.context() as patch: + patch.setattr(writer_module.os, "write", partial_write) + with pytest.raises(OSError): + writer.append(_step(2)) + writer.finish("failed") + assert rows.read_bytes() == original + assert writer.step_index == 1 + + def test_recording_scope_restores_actor_and_cannot_override_veto(): from mobilerun.core.runs import recording_policy, recording_scope diff --git a/tests/unit/core/screen/test_screen.py b/tests/unit/core/screen/test_screen.py new file mode 100644 index 000000000..fe48ba016 --- /dev/null +++ b/tests/unit/core/screen/test_screen.py @@ -0,0 +1,400 @@ +"""Screen projection exercises core's native provider over an injected driver.""" + +from io import BytesIO +from typing import Any, cast + +import pytest +from mobilerun_core import HitlDenied, StaleElement +from PIL import Image + +from mobilerun.core.screen import ScreenOptions, ScreenProvider +from mobilerun.utils.redaction import Redactor +from tests.support.devices import FakeDriver, fake_device + +pytestmark = pytest.mark.anyio + + +@pytest.fixture +def anyio_backend() -> str: + return "asyncio" + + +def bounds(left: int, top: int, right: int, bottom: int) -> dict[str, int]: + return dict(left=left, top=top, right=right, bottom=bottom) + + +@pytest.fixture +def settings_tree() -> dict: + # Ported from _combined_data in tests/unit/core/devices/test_state.py. + return { + "a11y_tree": { + "boundsInScreen": bounds(0, 0, 1080, 2400), + "className": "android.widget.FrameLayout", + "text": "root", + "children": [ + { + "boundsInScreen": bounds(221, 409, 600, 460), + "className": "android.widget.TextView", + "text": "Services & preferences", + "children": [], + } + ], + }, + "device_context": {"screen_bounds": {"width": 1080, "height": 2400}}, + "phone_state": { + "currentApp": "Settings", + "packageName": "com.android.settings", + }, + } + + +# Captured from the old formatter against the fixture above. Do not import it. +SETTINGS_PROMPT = """**Current Phone State:** +• **App:** Settings (com.android.settings) +• **Keyboard:** Hidden +• **Focused Element:** '' + +Current Clickable UI elements: +'index. className: resourceId; checkedState, text - bounds(x1,y1,x2,y2)': +1. FrameLayout: "root" - (0,0,1080,2400) +2. TextView: "Services & preferences" - (221,409,600,460)""" + + +def png(size: tuple[int, int]) -> bytes: + buffer = BytesIO() + Image.new("RGB", size).save(buffer, format="PNG") + return buffer.getvalue() + + +async def test_indexed_text_matches_old_formatter(settings_tree: dict) -> None: + async with fake_device(driver=FakeDriver(ui_tree=settings_tree)) as device: + assert ( + await ScreenProvider(device).observe() + ).ui.formatted_text == SETTINGS_PROMPT + + +async def test_fingerprint_includes_native_element_pruned_from_prompt( + settings_tree: dict, +) -> None: + settings_tree["a11y_tree"]["children"].append( + { + "className": "android.widget.Button", + "resourceId": "settings:hidden", + "boundsInScreen": bounds(0, 0, 1, 1), + } + ) + async with fake_device(driver=FakeDriver(ui_tree=settings_tree)) as device: + state = await ScreenProvider( + device, options=ScreenOptions(detail="concise") + ).observe() + + assert "settings:hidden" not in state.ui.formatted_text + assert state.fingerprint is not None + assert "id:settings:hidden" in state.fingerprint.elements + + +async def test_projection_keeps_native_flags_and_exact_focus( + settings_tree: dict, +) -> None: + first = settings_tree["a11y_tree"]["children"][0] + first.update( + className="android.widget.EditText", + isClickable=False, + isEnabled=False, + isVisibleToUser=False, + ) + settings_tree["a11y_tree"]["children"].append( + { + **first, + "boundsInScreen": bounds(221, 509, 600, 560), + "isFocused": True, + "isEditable": True, + "isEnabled": True, + "isVisibleToUser": True, + "isClickable": None, + } + ) + async with fake_device(driver=FakeDriver(ui_tree=settings_tree)) as device: + state = await ScreenProvider( + device, options=ScreenOptions(normalized=True) + ).observe() + first_row, focused_row = state.ui.elements[1:] + assert (first_row.clickable, first_row.enabled, first_row.visible) == ( + False, + False, + False, + ) + assert (focused_row.clickable, focused_row.enabled, focused_row.visible) == ( + None, + True, + True, + ) + assert state.ui.focused_index == 3 + assert state.ui.geometry.project_bounds(focused_row.bounds) == (204, 212, 555, 233) + + +async def test_opaque_screen_geometry_is_available_but_not_serialized( + settings_tree: dict, +) -> None: + settings_tree["a11y_tree"]["children"][0]["text"] = "opaque fixture value" + redactor = Redactor() + redactor.mark_sensitive() + async with fake_device(driver=FakeDriver(ui_tree=settings_tree)) as device: + state = await ScreenProvider(device, redactor=redactor).observe() + assert state.ui.element(2).bounds == (221, 409, 600, 460) + assert state.ui.geometry.to_device(220, 409) == (220, 409) + assert "opaque fixture value" not in state.ui.formatted_text + assert state.ui.model_dump()["elements"] == () + assert state.ui.model_dump()["geometry"]["input_size"] is None + + +async def test_numeric_secret_does_not_round_trip_through_typed_bounds( + settings_tree: dict, +) -> None: + settings_tree["a11y_tree"]["children"][0]["boundsInScreen"] = bounds( + 221, 1234, 600, 1400 + ) + redactor = Redactor() + redactor.remember_codes("1234") + async with fake_device(driver=FakeDriver(ui_tree=settings_tree)) as device: + state = await ScreenProvider(device, redactor=redactor).observe() + assert state.element(2).bounds == (221, 1234, 600, 1400) + assert state.ui.element(2).bounds is None + assert "1234" not in state.ui.model_dump_json() + + +async def test_legacy_ios_formats_core_nodes_in_actionable_order() -> None: + # Structured equivalent of RAW_A11Y in tests/unit/core/devices/test_state.py. + class LegacyDriver(FakeDriver): + observation_format = "ios-legacy" + + driver = LegacyDriver( + platform="ios", + ui_tree={ + "device_context": {"screen_bounds": {"width": 440, "height": 956}}, + "a11y_tree": [ + { + "className": "Window (Main)", + "boundsInScreen": bounds(0, 0, 440, 956), + }, + { + "className": "Cell", + "contentDescription": "General", + "boundsInScreen": bounds(20, 200, 420, 244), + }, + { + "className": "StaticText", + "contentDescription": "Settings", + "boundsInScreen": bounds(20, 119, 153, 160), + }, + ], + }, + ) + async with fake_device(driver=driver, platform="ios") as device: + state = await ScreenProvider(device).observe() + assert state.ui.formatted_text == ( + "Current UI elements:\n'index. className: text - bounds(x1,y1,x2,y2)':\n" + "0. Cell: General - (20,200,420,244)\n" + "1. StaticText: Settings - (20,119,153,160)" + ) + assert state.element(0).label == "General" + + +async def test_filters_reindex_the_remaining_native_targets( + settings_tree: dict, +) -> None: + # The mixed-filter fixture used a five-pixel-wide item and a Gboard node. + settings_tree["a11y_tree"]["children"][:0] = [ + {"text": "thin", "boundsInScreen": bounds(10, 10, 15, 30)}, + { + "text": "keyboard", + "resourceId": "com.google.android.inputmethod.latin:id/keyboard", + "boundsInScreen": bounds(10, 100, 200, 200), + }, + ] + async with fake_device(driver=FakeDriver(ui_tree=settings_tree)) as device: + concise = await ScreenProvider( + device, options=ScreenOptions(detail="concise") + ).observe() + detailed = await ScreenProvider(device).observe() + assert ( + 'keyboard"' in concise.ui.formatted_text + and '"thin"' not in concise.ui.formatted_text + ) + assert ( + '"thin"' in detailed.ui.formatted_text + and 'keyboard"' not in detailed.ui.formatted_text + ) + assert concise.element(2).node_id == (0, 1) + assert detailed.element(2).node_id == (0, 0) + assert concise.element(3).node_id == detailed.element(3).node_id == (0, 2) + + +async def test_index_dispatches_once_through_core(settings_tree: dict) -> None: + driver = FakeDriver(ui_tree=settings_tree) + async with fake_device(driver=driver, hitl_gate=lambda *_: True) as device: + view = ScreenProvider(device) + state = await view.observe() + await device.tap_element(state.element(2)) + assert [call for call in driver.calls if call[0] == "tap"] == [ + ("tap", (410, 434), {}) + ] + + +async def test_stale_index_surfaces_core_error(settings_tree: dict) -> None: + driver = FakeDriver(ui_tree=settings_tree) + async with fake_device(driver=driver, hitl_gate=lambda *_: True) as device: + view = ScreenProvider(device) + previous = await view.observe() + cast(dict[str, Any], driver.ui_tree["a11y_tree"])["children"][0][ + "boundsInScreen" + ] = bounds(230, 409, 609, 460) + await view.observe() + with pytest.raises(StaleElement): + await device.tap_element(previous.element(2)) + assert not any(name == "tap" for name, *_ in driver.calls) + + +async def test_denied_index_never_falls_back_to_direct_tap(settings_tree: dict) -> None: + driver = FakeDriver(ui_tree=settings_tree) + async with fake_device(driver=driver) as device: + view = ScreenProvider(device) + state = await view.observe() + with pytest.raises(HitlDenied): + await device.tap_element(state.element(2)) + assert not any(name == "tap" for name, *_ in driver.calls) + + +async def test_normalized_point_round_trip_and_edges(settings_tree: dict) -> None: + async with fake_device(driver=FakeDriver(ui_tree=settings_tree)) as device: + state = await ScreenProvider( + device, options=ScreenOptions(normalized=True) + ).observe() + assert state.ui.geometry.to_device(250, 750) == (270, 1800) + assert state.ui.geometry.from_device(270, 1800) == (250, 750) + assert state.ui.geometry.to_device(*state.ui.geometry.from_device(59, 123)) == ( + 59, + 123, + ) + assert state.ui.geometry.to_device(1000, 1000) == (1079, 2399) + assert "(normalized [0-1000])" in state.ui.formatted_text + with pytest.raises(ValueError): + state.ui.geometry.to_device(1001, 0) + + +async def test_screenshot_size_matches_model_coordinate_space( + settings_tree: dict, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("MOBILERUN_MODEL_SCREENSHOT_MAX_SIDE", "500") + driver = FakeDriver(ui_tree=settings_tree, screenshot_bytes=png((1000, 2000))) + async with fake_device(driver=driver) as device: + state = await ScreenProvider(device).observe(screenshot=True) + assert state.screenshot is not None + with Image.open(BytesIO(state.screenshot)) as image: + assert image.size == (250, 500) + assert state.ui.geometry.to_device(125, 250) == (540, 1200) + assert state.ui.geometry.from_device(540, 1200) == (125, 250) + assert [name for name, *_ in driver.calls].count("screenshot") == 1 + + +async def test_known_code_is_redacted_without_changing_target( + settings_tree: dict, +) -> None: + settings_tree["a11y_tree"]["children"][0]["text"] = "Enter 482 913" + settings_tree["phone_state"]["focusedElement"] = {"text": "482913"} + redactor = Redactor() + redactor.remember_codes("482913") + async with fake_device(driver=FakeDriver(ui_tree=settings_tree)) as device: + state = await ScreenProvider(device, redactor=redactor).observe() + assert '"Enter ***"' in state.ui.formatted_text + assert state.ui.focused_text == "***" + assert state.element(2).text == "Enter 482 913" + assert "482" not in str(state.to_json_data()) + assert "482913" not in repr(state) and "482 913" not in repr(state) + assert state.fingerprint is not None + assert state.fingerprint.app == "com.android.settings" + redactor.mark_sensitive() + assert state.fingerprint is None + assert state.to_json_data()["ui"] == "***" + + +async def test_filtered_secure_node_does_not_expose_duplicates( + settings_tree: dict, +) -> None: + children = settings_tree["a11y_tree"]["children"] + children[0]["text"] = "duplicate sample password" + children.append( + { + "className": "android.widget.EditText", + "inputType": 0x81, + "text": "sample password", + "boundsInScreen": bounds(0, 0, 1, 1), + } + ) + settings_tree["phone_state"]["focusedElement"] = {"text": "sample password"} + async with fake_device(driver=FakeDriver(ui_tree=settings_tree)) as device: + view = ScreenProvider(device, options=ScreenOptions(detail="concise")) + state = await view.observe() + assert "sample password" not in state.ui.formatted_text + assert "sample password" not in str(state.to_json_data()) + assert state.ui.focused_text == "***" + assert state.fingerprint is None + + +@pytest.mark.parametrize( + ("payload", "expected", "unexpected"), + [ + ({"a11y_tree": []}, "No UI elements found", "Screenshot-only mode"), + ({}, "Screenshot-only mode", "No UI elements found"), + ], + ids=["empty-tree", "tree-unavailable"], +) +async def test_ios_prompt_distinguishes_empty_from_unavailable_tree( + payload: dict, expected: str, unexpected: str +) -> None: + driver = FakeDriver(platform="ios", ui_tree=payload) + driver.observation_format = "ios-legacy" + async with fake_device(driver=driver, platform="ios") as device: + state = await ScreenProvider(device).observe(screenshot=False) + assert state.ui.elements == () + assert expected in state.ui.formatted_text + assert unexpected not in state.ui.formatted_text + + +async def test_screenshot_only_read_yields_an_image_without_indices() -> None: + driver = FakeDriver( + supported={"screenshot", "tap"}, screenshot_bytes=png((80, 120)) + ) + async with fake_device(driver=driver) as device: + state = await ScreenProvider(device).observe() + assert state.ui.elements == () + assert state.screenshot is not None + assert "Screenshot-only mode is active" in state.ui.formatted_text + assert state.ui.geometry.to_device(40, 60) == (40, 60) + with pytest.raises(ValueError, match="index 1"): + state.element(1) + assert [name for name, *_ in driver.calls] == ["screenshot"] + + +async def test_latest_state_updates_only_after_success(settings_tree: dict) -> None: + driver = FakeDriver(ui_tree=settings_tree) + async with fake_device(driver=driver) as device: + view = ScreenProvider(device) + native = device.state_provider + assert view.current is None + first = await view.observe() + cast(dict[str, Any], driver.ui_tree["a11y_tree"])["children"][0][ + "text" + ] = "Network" + second = await view.observe() + assert first is not second and view.current is second + assert ( + '"Network"' in second.ui.formatted_text + and '"Network"' not in first.ui.formatted_text + ) + driver.failures["get_ui_tree"] = RuntimeError("read failed") + with pytest.raises(RuntimeError, match="read failed"): + await view.observe() + assert view.current is second + assert device.state_provider is native + assert [name for name, *_ in driver.calls] == ["get_ui_tree"] * 3 diff --git a/tests/unit/core/webhooks/test_endpoints.py b/tests/unit/core/webhooks/test_endpoints.py index a29f10d1b..3bd6868a4 100644 --- a/tests/unit/core/webhooks/test_endpoints.py +++ b/tests/unit/core/webhooks/test_endpoints.py @@ -58,8 +58,7 @@ def test_url_accepts_canonical_length_at_limit_after_trimming_slash(): @pytest.fixture def service(monkeypatch): - from mobilerun.clients.cloud import webhooks - from mobilerun.core.webhooks import CloudWebhooks + from mobilerun.core.webhooks import CloudWebhooks, cloud requests = [] clients = [] @@ -117,7 +116,7 @@ def factory(*, billing): clients.append(client) return client - monkeypatch.setattr(webhooks, "cloud_client", factory) + monkeypatch.setattr(cloud, "cloud_client", factory) return CloudWebhooks(billing="no_commerce"), requests, clients diff --git a/tests/unit/core/workspace/test_transfers.py b/tests/unit/core/workspace/test_transfers.py index 6af8e5d93..55e269cdc 100644 --- a/tests/unit/core/workspace/test_transfers.py +++ b/tests/unit/core/workspace/test_transfers.py @@ -6,30 +6,24 @@ import sys import traceback from datetime import datetime, timezone +from pathlib import Path from types import SimpleNamespace -from typing import cast from unittest.mock import AsyncMock import httpx import pytest +from mobilerun_core import AppIdentity, FileOperationError from mobilerun_sdk import AsyncMobilerun from mobilerun import Workspace -from mobilerun.clients.cloud import apps as cloud_apps from mobilerun.clients.cloud import client as cloud_connection -from mobilerun.clients.cloud import files as cloud_files -from mobilerun.clients.local import login_store -from mobilerun.core.devices.android import AndroidDevice -from mobilerun.core.devices.base import Device -from mobilerun.core.devices.cloud import CloudDevice -from mobilerun.core.devices.components import files as device_files -from mobilerun.core.devices.components.wrapper import DeviceWrapper -from mobilerun.core.devices.pool import DevicePool -from mobilerun.errors import CloudPermissionDenied, DeviceOperationNotSupported +from mobilerun.clients.local.login_store import LoginStore +from mobilerun.errors import CloudPermissionDenied from mobilerun.models import App, Billing, WorkspaceFile +from tests.support.devices import FakeDriver, fake_device -def test_workspace_import_keeps_cloud_adapters_private_and_lazy(): +def test_workspace_import_keeps_cloud_adapters_private_and_lazy() -> None: script = """ import sys from mobilerun import Workspace @@ -43,7 +37,18 @@ def test_workspace_import_keeps_cloud_adapters_private_and_lazy(): subprocess.run([sys.executable, "-c", script], check=True) -def test_catalog_pagination_mapping_and_delete(monkeypatch): +def test_workspace_operations_borrow_the_same_sdk_without_closing_it() -> None: + sdk = AsyncMock() + sdk.files.list.return_value = SimpleNamespace(files=[]) + workspace = Workspace(client=sdk) + assert asyncio.run(workspace.list_files()) == [] + asyncio.run(workspace.delete_file("file-id")) + sdk.files.delete.assert_awaited_once_with("file-id") + sdk.__aenter__.assert_not_awaited() + sdk.__aexit__.assert_not_awaited() + + +def test_catalog_pagination_mapping_and_delete(monkeypatch: pytest.MonkeyPatch) -> None: client = AsyncMock() client.__aenter__.return_value = client first = SimpleNamespace( @@ -64,26 +69,28 @@ def test_catalog_pagination_mapping_and_delete(monkeypatch): ] calls = [] - def connect(api_key, base_url, *, billing): + def connect( + api_key: str | None, base_url: str | None, *, billing: Billing + ) -> AsyncMock: calls.append((api_key, base_url, billing)) return client monkeypatch.setattr(cloud_connection, "cloud_client", connect) - options = dict( - api_key="source", base_url="https://source.test", billing=Billing.NO_COMMERCE - ) - assert asyncio.run(Workspace.list_apps(**options)) == [ - App("one", "1", "One", id="a", version_code=3), - App("two", "", "Two", id="b", version_code=4), + workspace = Workspace(api_key="source", base_url="https://source.test") + assert asyncio.run(workspace.list_apps()) == [ + App(AppIdentity("one", 3, "1"), "One", "a"), + App(AppIdentity("two", 4), "Two", "b"), ] assert [call.kwargs["page"] for call in client.apps.list.await_args_list] == [1, 2] - asyncio.run(Workspace.delete_app("a", **options)) + asyncio.run(workspace.delete_app("a")) client.apps.delete.assert_awaited_once_with("a") assert calls == [("source", "https://source.test", Billing.NO_COMMERCE)] * 2 assert client.__aexit__.await_count == 2 -def test_get_app_default_billing_and_client_cleanup_on_failure(monkeypatch): +def test_get_app_default_billing_and_client_cleanup_on_failure( + monkeypatch: pytest.MonkeyPatch, +) -> None: client = AsyncMock() client.__aenter__.return_value = client client.apps.retrieve.return_value = SimpleNamespace( @@ -91,231 +98,175 @@ def test_get_app_default_billing_and_client_cleanup_on_failure(monkeypatch): ) calls = [] - def connect(api_key, base_url, *, billing): + def connect( + api_key: str | None, base_url: str | None, *, billing: Billing + ) -> AsyncMock: calls.append((api_key, base_url, billing)) return client monkeypatch.setattr(cloud_connection, "cloud_client", connect) - assert asyncio.run(Workspace.get_app("a")) == App("one", "", "One", id="a") + app = asyncio.run(Workspace().get_app("a")) + assert app.resource_id == "a" + assert app.identity.app_id == "one" + assert app.identity.version_code is None client.apps.retrieve.side_effect = RuntimeError("unavailable") with pytest.raises(RuntimeError, match="unavailable"): - asyncio.run(Workspace.get_app("b")) + asyncio.run(Workspace().get_app("b")) assert calls == [(None, None, Billing.NO_COMMERCE)] * 2 assert client.__aexit__.await_count == 2 -def test_workspace_upload_app_passes_overrides(monkeypatch): - app = App("one", "1", "One", id="a") - upload = AsyncMock(return_value=app) - monkeypatch.setattr(cloud_apps, "upload_app", upload) - assert ( - asyncio.run( - Workspace.upload_app( - "one.apk", api_key="key", base_url="https://source.test" - ) - ) - is app - ) - upload.assert_awaited_once_with( - "one.apk", - api_key="key", - base_url="https://source.test", - billing=Billing.NO_COMMERCE, - ) - - -def test_canonical_api_key_only_and_saved_login_fallback(monkeypatch): +def test_canonical_api_key_only_and_saved_login_fallback( + monkeypatch: pytest.MonkeyPatch, +) -> None: - monkeypatch.setattr(login_store, "load_credentials", lambda: {"api_key": "saved"}) + monkeypatch.setattr(LoginStore, "load", lambda self: {"api_key": "saved"}) monkeypatch.setenv("MOBILERUN_CLOUD_API_KEY", "obsolete") monkeypatch.delenv("MOBILERUN_API_KEY", raising=False) - assert login_store.resolve_cloud_api_key() == "saved" + assert LoginStore.from_settings().resolve_api_key() == "saved" monkeypatch.setenv("MOBILERUN_API_KEY", "canonical") - assert login_store.resolve_cloud_api_key() == "canonical" + assert LoginStore.from_settings().resolve_api_key() == "canonical" -def test_workspace_api_owns_client_and_downloads_into_directory(monkeypatch, tmp_path): +def test_workspace_api_owns_client_and_downloads_into_directory( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: - item = WorkspaceFile("id", "photo.jpg", "image/jpeg", 5, datetime.now(timezone.utc)) + now = datetime.now(timezone.utc) + item = WorkspaceFile("id", "photo.jpg", "image/jpeg", 5, now) client = AsyncMock() client.__aenter__.return_value = client monkeypatch.setattr( cloud_connection, "cloud_client", lambda *args, **kwargs: client ) - monkeypatch.setattr(cloud_files, "upload_file", AsyncMock(return_value=item)) - monkeypatch.setattr(cloud_files, "list_files", AsyncMock(return_value=[item])) - monkeypatch.setattr(cloud_files, "download_file", AsyncMock(return_value=b"image")) - monkeypatch.setattr(cloud_files, "delete_file", AsyncMock()) - - assert ( - asyncio.run(Workspace.upload_file("photo.jpg", billing=Billing.NO_COMMERCE)) - == item + client.files.list.return_value = SimpleNamespace( + files=[ + SimpleNamespace( + file_id="id", + filename="photo.jpg", + mime_type="image/jpeg", + size_bytes=5, + created_at=now, + ) + ] ) - assert asyncio.run(Workspace.list_files(billing=Billing.NO_COMMERCE)) == [item] - result = asyncio.run( - Workspace.download_file("id", tmp_path, billing=Billing.NO_COMMERCE) + client.files.with_raw_response.download.return_value = SimpleNamespace( + read=AsyncMock(return_value=b"image") ) + assert asyncio.run(Workspace().list_files()) == [item] + result = asyncio.run(Workspace().download_file("id", tmp_path)) assert result == tmp_path / "photo.jpg" assert result.read_bytes() == b"image" - asyncio.run(Workspace.delete_file("id", billing=Billing.NO_COMMERCE)) - cloud_files.delete_file.assert_awaited_once_with( - client, "id", billing=Billing.NO_COMMERCE - ) - assert client.__aenter__.await_count == client.__aexit__.await_count == 4 + asyncio.run(Workspace().delete_file("id")) + client.files.delete.assert_awaited_once_with("id") + assert [call.kwargs for call in client.files.list.await_args_list] == [ + {"zone": "user"} + ] * 2 + client.files.with_raw_response.download.assert_awaited_once_with("id") + assert client.__aenter__.await_count == client.__aexit__.await_count == 3 -def test_download_rejects_unknown_file(monkeypatch, tmp_path): +def test_download_rejects_unknown_file( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: client = AsyncMock() client.__aenter__.return_value = client monkeypatch.setattr( cloud_connection, "cloud_client", lambda *args, **kwargs: client ) - monkeypatch.setattr(cloud_files, "list_files", AsyncMock(return_value=[])) + client.files.list.return_value = SimpleNamespace(files=[]) with pytest.raises(FileNotFoundError): - asyncio.run( - Workspace.download_file("missing", tmp_path, billing=Billing.NO_COMMERCE) - ) - - -def test_base_device_rejects_file_operations(): - async def run(): - device = Device() - with pytest.raises(DeviceOperationNotSupported): - await device.push_file("x") - with pytest.raises(DeviceOperationNotSupported): - await device.list_files("/sdcard") - with pytest.raises(DeviceOperationNotSupported): - await device.pull_file("x", "y") - with pytest.raises(DeviceOperationNotSupported): - await device.delete_file("x") + asyncio.run(Workspace().download_file("missing", tmp_path)) - asyncio.run(run()) - -def test_android_push_uses_media_directory_and_scans_quoted_path(tmp_path): - - image = tmp_path / "a ' photo.png" - image.write_bytes(b"image") - adb = SimpleNamespace( - sync=SimpleNamespace(push=AsyncMock()), - shell2=AsyncMock(return_value=SimpleNamespace(returncode=0, output="")), - ) - device = cast( - AndroidDevice, SimpleNamespace(_ensure_connected=AsyncMock(), _adb_device=adb) +@pytest.fixture +def workspace_client(monkeypatch: pytest.MonkeyPatch) -> AsyncMock: + client = AsyncMock() + client.__aenter__.return_value = client + monkeypatch.setattr( + cloud_connection, "cloud_client", lambda *args, **kwargs: client ) - result = asyncio.run(device_files.android_push_file(device, image)) - assert result.path == "/sdcard/DCIM/Camera/a ' photo.png" - adb.sync.push.assert_awaited_once_with(image, result.path) - command = adb.shell2.await_args.args[0] - assert "MEDIA_SCANNER_SCAN_FILE" in command - assert "'\"'\"'" in command + return client -def test_android_file_operations_and_document_destination(tmp_path): +def test_workspace_file_round_trip( + workspace_client: AsyncMock, monkeypatch: pytest.MonkeyPatch +) -> None: + now = datetime.now(timezone.utc) + item = WorkspaceFile("source", "source.png", "image/png", 3, now) + workspace_client.files.with_raw_response.download.return_value = SimpleNamespace( + read=AsyncMock(return_value=b"\x00\xff!"), + ) + driver = FakeDriver(supported={"push_file", "pull_file"}) + device = fake_device(driver=driver) + staged = [] + + async def upload(self: Workspace, path: Path) -> WorkspaceFile: + staged.append(path) + assert path.name == "renamed.png" + assert path.read_bytes() == b"\x00\xff!" + return WorkspaceFile("uploaded", path.name, "image/png", 3, now) + + monkeypatch.setattr(Workspace, "upload_file", upload) + + async def run() -> WorkspaceFile: + await Workspace().push_file(item, device, "/sdcard/renamed.png") + return await Workspace(api_key="target").pull_file( + device, "/sdcard/renamed.png" + ) - document = tmp_path / "a file.txt" - document.write_bytes(b"text") + assert asyncio.run(run()) == WorkspaceFile( + "uploaded", "renamed.png", "image/png", 3, now + ) + assert driver.files == {"/sdcard/renamed.png": b"\x00\xff!"} + assert len(staged) == 1 and not staged[0].exists() + workspace_client.files.with_raw_response.download.assert_awaited_once_with("source") - async def entries(path): - yield SimpleNamespace(path="a file.txt", size=4, mtime=None) - adb = SimpleNamespace( - sync=SimpleNamespace( - push=AsyncMock(), pull=AsyncMock(), iter_directory=entries - ), - shell2=AsyncMock(return_value=SimpleNamespace(returncode=0, output="")), - ) - device = cast( - AndroidDevice, SimpleNamespace(_ensure_connected=AsyncMock(), _adb_device=adb) +def test_workspace_push_forwards_scan_media_only_when_requested( + workspace_client: AsyncMock, monkeypatch: pytest.MonkeyPatch +) -> None: + item = WorkspaceFile( + "source", "photo.jpg", "image/jpeg", 5, datetime.now(timezone.utc) ) - pushed = asyncio.run(device_files.android_push_file(device, document)) - assert pushed.path == "/sdcard/Download/a file.txt" - assert adb.shell2.await_count == 0 - overridden = asyncio.run( - device_files.android_push_file(device, document, "/sdcard/custom") + workspace_client.files.with_raw_response.download.return_value = SimpleNamespace( + read=AsyncMock(return_value=b"image"), ) - assert overridden.path == "/sdcard/custom/a file.txt" - listed = asyncio.run(device_files.android_list_files(device, "/sdcard/Download")) - assert [(f.path, f.size_bytes) for f in listed] == [(pushed.path, 4)] - output = tmp_path / "out.txt" - assert ( - asyncio.run(device_files.android_pull_file(device, pushed.path, output)) - == output - ) - adb.sync.pull.assert_awaited_once_with(pushed.path, output) - asyncio.run(device_files.android_delete_file(device, pushed.path)) - assert adb.shell2.await_args.args[0] == "rm -- '/sdcard/Download/a file.txt'" - - -def test_android_device_delegates_file_operations(monkeypatch, tmp_path): - - device = AndroidDevice(serial="emulator-5554") - push = AsyncMock(return_value=SimpleNamespace(path="/sdcard/a")) - monkeypatch.setattr(device_files, "android_push_file", push) - result = asyncio.run(device.push_file(tmp_path / "a", "/sdcard")) - assert result.path == "/sdcard/a" - push.assert_awaited_once_with(device, tmp_path / "a", "/sdcard") + device = fake_device() + push_file = AsyncMock() + monkeypatch.setattr(device, "push_file", push_file) + asyncio.run(Workspace().push_file(item, device, "/sdcard/photo.jpg")) + push_file.assert_awaited_once_with(b"image", "/sdcard/photo.jpg") -def test_push_workspace_downloads_then_pushes(monkeypatch): - - item = WorkspaceFile("id", "image.png", "image/png", 3, datetime.now(timezone.utc)) - download = AsyncMock(return_value=b"abc") - client = AsyncMock() - client.__aenter__.return_value = client - monkeypatch.setattr(cloud_connection, "cloud_client", lambda *a, **k: client) - monkeypatch.setattr(cloud_files, "download_file", download) - device = Device() - device.push_file = AsyncMock(return_value="done") - assert asyncio.run(Workspace.push_file(item, device, "/sdcard")) == "done" - assert download.await_args is not None - assert device.push_file.await_args is not None - assert download.await_args.args[1] == "id" - assert device.push_file.await_args.args[0].name == "image.png" - assert device.push_file.await_args.args[1] == "/sdcard" - - -def test_cloud_device_files_use_sdk_transport(monkeypatch, tmp_path): - - device = CloudDevice("id", api_key="test") - device._ensure_connected = AsyncMock() - push = AsyncMock() - listing = AsyncMock(return_value=[]) - pull = AsyncMock(return_value=b"abc") - remove = AsyncMock() - monkeypatch.setattr(cloud_files, "push_device_file", push) - monkeypatch.setattr(cloud_files, "list_device_files", listing) - monkeypatch.setattr(cloud_files, "download_device_file", pull) - monkeypatch.setattr(cloud_files, "delete_device_file", remove) - path = tmp_path / "a.png" - path.write_bytes(b"abc") - result = asyncio.run(device.push_file(path)) - assert result.path == "/sdcard/DCIM/Camera/a.png" - assert asyncio.run(device.list_files("/sdcard")) == [] - out = tmp_path / "copy.png" - assert asyncio.run(device.pull_file(result.path, out)).read_bytes() == b"abc" - asyncio.run(device.delete_file(result.path)) - assert ( - push.await_count - == listing.await_count - == pull.await_count - == remove.await_count - == 1 + asyncio.run( + Workspace().push_file(item, device, "/sdcard/photo.jpg", scan_media=True) ) + assert push_file.await_args_list[-1].args == (b"image", "/sdcard/photo.jpg") + assert push_file.await_args_list[-1].kwargs == {"scan_media": True} + +def test_pull_preserves_typed_core_error(workspace_client: AsyncMock) -> None: + error = FileOperationError("file request failed") + device = fake_device(driver=FakeDriver(failures={"pull_file": error})) + with pytest.raises(FileOperationError) as caught: + asyncio.run(Workspace().pull_file(device, "/sdcard/source.png")) + assert caught.value is error + workspace_client.__aenter__.assert_not_awaited() -def test_wrapper_and_pool_forward_files(): - device = Device() - device.list_files = AsyncMock(return_value=[]) - wrapped = DeviceWrapper(device) - assert asyncio.run(wrapped.list_files("/sdcard")) == [] - assert asyncio.run(DevicePool([wrapped]).list_files("/sdcard")) == [[]] - assert device.list_files.await_count == 2 +@pytest.mark.parametrize("device_path", ["/", "..", "/sdcard/", "/sdcard/."]) +def test_pull_requires_a_filename(device_path: str) -> None: + driver = FakeDriver() + with pytest.raises(ValueError, match="including its filename"): + asyncio.run(Workspace().pull_file(fake_device(driver=driver), device_path)) + assert driver.calls == [] -def test_upload_confirms_only_after_put_and_cancels_on_failure(monkeypatch, tmp_path): +def test_upload_confirms_only_after_put_and_cancels_on_failure( + workspace_client: AsyncMock, monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: path = tmp_path / "photo.jpg" path.write_bytes(b"image") @@ -335,14 +286,12 @@ def test_upload_confirms_only_after_put_and_cancels_on_failure(monkeypatch, tmp_ ), cancel_pending=AsyncMock(), ) - client = SimpleNamespace(files=resource) + workspace_client.files = resource http = AsyncMock() http.__aenter__.return_value = http http.put.return_value = SimpleNamespace(raise_for_status=lambda: None) - monkeypatch.setattr(cloud_files.httpx, "AsyncClient", lambda: http) - result = asyncio.run( - cloud_files.upload_file(client, path, billing=Billing.NO_COMMERCE) - ) + monkeypatch.setattr(httpx, "AsyncClient", lambda: http) + result = asyncio.run(Workspace().upload_file(path)) assert (result.id, result.name, result.size_bytes) == ("f1", "photo.jpg", 5) resource.upload_url.assert_awaited_once_with( filename="photo.jpg", mime_type="image/jpeg", size_bytes=5, zone="user" @@ -357,93 +306,22 @@ def test_upload_confirms_only_after_put_and_cancels_on_failure(monkeypatch, tmp_ resource.cancel_pending.assert_not_awaited() http.put.side_effect = RuntimeError("failure") with pytest.raises(RuntimeError, match="failure"): - asyncio.run(cloud_files.upload_file(client, path, billing=Billing.NO_COMMERCE)) + asyncio.run(Workspace().upload_file(path)) resource.cancel_pending.assert_awaited_once_with("f1") resource.confirm.assert_awaited_once_with("f1") -def test_list_download_and_delete(monkeypatch, tmp_path): - - now = datetime.now(timezone.utc) - item = SimpleNamespace( - file_id="f1", - filename="photo.jpg", - mime_type="image/jpeg", - size_bytes=5, - created_at=now, - ) - raw = SimpleNamespace(read=AsyncMock(return_value=b"image")) - resource = SimpleNamespace( - list=AsyncMock(return_value=SimpleNamespace(files=[item])), - delete=AsyncMock(), - with_raw_response=SimpleNamespace(download=AsyncMock(return_value=raw)), - ) - client = SimpleNamespace(files=resource) - items = asyncio.run(cloud_files.list_files(client, billing=Billing.NO_COMMERCE)) - assert items[0].name == "photo.jpg" - assert ( - asyncio.run( - cloud_files.download_file(client, "f1", billing=Billing.NO_COMMERCE) - ) - == b"image" - ) - asyncio.run(cloud_files.delete_file(client, "f1", billing=Billing.NO_COMMERCE)) - resource.list.assert_awaited_once_with(zone="user") - resource.with_raw_response.download.assert_awaited_once_with("f1") - resource.delete.assert_awaited_once_with("f1") - - -def test_device_file_sdk_transport(tmp_path): - - path = tmp_path / "picture.png" - path.write_bytes(b"png") - item = SimpleNamespace(name="picture.png", size=3, modified_at=None) - raw = SimpleNamespace(read=AsyncMock(return_value=b"png")) - resource = SimpleNamespace( - upload=AsyncMock(), - list=AsyncMock(return_value=SimpleNamespace(files=[item])), - delete=AsyncMock(), - with_raw_response=SimpleNamespace(download=AsyncMock(return_value=raw)), - ) - client = SimpleNamespace(devices=SimpleNamespace(files=resource)) - asyncio.run( - cloud_files.push_device_file( - client, "device", path, "/sdcard", billing=Billing.NO_COMMERCE - ) - ) - resource.upload.assert_awaited_once_with("device", path="/sdcard", file=path) - listed = asyncio.run( - cloud_files.list_device_files( - client, "device", "/sdcard", billing=Billing.NO_COMMERCE - ) - ) - assert listed[0].path == "/sdcard/picture.png" - assert ( - asyncio.run( - cloud_files.download_device_file( - client, "device", "/sdcard/picture.png", billing=Billing.NO_COMMERCE - ) - ) - == b"png" - ) - asyncio.run( - cloud_files.delete_device_file( - client, "device", "/sdcard/picture.png", billing=Billing.NO_COMMERCE - ) - ) - resource.delete.assert_awaited_once_with("device", path="/sdcard/picture.png") - - -@pytest.mark.parametrize("device", [False, True]) @pytest.mark.parametrize("status", [200, 403]) -def test_sdk_download_redirect_hides_signature_and_strips_auth(caplog, device, status): +def test_sdk_download_redirect_hides_signature_and_strips_auth( + caplog: pytest.LogCaptureFixture, status: int, monkeypatch: pytest.MonkeyPatch +) -> None: requests = [] signature = "storage-redirect-canary" caplog.set_level(logging.INFO, logger="httpx") caplog.set_level(logging.DEBUG, logger="mobilerun_sdk._base_client") - def respond(request): + def respond(request: httpx.Request) -> httpx.Response: requests.append(request) if request.url.host == "api.example": return httpx.Response( @@ -454,20 +332,20 @@ def respond(request): status, content=b"\x00\xff" if status == 200 else b"denied" ) - async def run(): + async def run() -> bytes: http = httpx.AsyncClient( transport=httpx.MockTransport(respond), follow_redirects=True ) - async with AsyncMobilerun( + client = AsyncMobilerun( api_key="test", base_url="https://api.example", http_client=http - ) as client: - if device: - return await cloud_files.download_device_file( - client, "id", "/sdcard/test", billing=Billing.NO_COMMERCE - ) - return await cloud_files.download_file( - client, "id", billing=Billing.NO_COMMERCE - ) + ) + monkeypatch.setattr(cloud_connection, "cloud_client", lambda *a, **kw: client) + driver = FakeDriver(supported={"push_file"}) + item = WorkspaceFile( + "id", "x", "application/octet-stream", 2, datetime.now(timezone.utc) + ) + await Workspace().push_file(item, fake_device(driver=driver), "/x") + return driver.files["/x"] if status == 200: assert asyncio.run(run()) == b"\x00\xff" diff --git a/tests/unit/demos/test_demo_entrypoints.py b/tests/unit/demos/test_demo_entrypoints.py new file mode 100644 index 000000000..7e316f38c --- /dev/null +++ b/tests/unit/demos/test_demo_entrypoints.py @@ -0,0 +1,72 @@ +"""Exercise demo CLI paths without opening devices or spending credits.""" + +import subprocess +import sys + +import pytest +from mobilerun_core import DeviceDisconnectedError + +from tests.demos import vault_demo +from tests.support.paths import REPO_ROOT + + +@pytest.mark.parametrize( + ("name", "output"), + [ + ("app_demo", "counter"), + ("intro_demo", "Hello, world!"), + ("mailbox_demo", "Offline preview"), + ("phone_demo", "Offline preview"), + ("proxy_demo", "Offline preview"), + ("task_demo", "Android version"), + ("vault_demo", "demo-user"), + ], +) +def test_demo_defaults_to_offline(name, output): + result = subprocess.run( + [sys.executable, str(REPO_ROOT / "tests" / "demos" / f"{name}.py")], + stdin=subprocess.DEVNULL, + capture_output=True, + text=True, + timeout=15, + ) + assert result.returncode == 0, result.stderr + assert output in result.stdout + + +@pytest.mark.parametrize("name", ["atc_demo", "webhook_static_demo"]) +def test_sandbox_demo_help_does_not_deploy(name): + code = """import runpy +import sys +import mobilerun.sandbox +import mobilerun.sandbox.app + +def blocked(*args, **kwargs): + raise AssertionError('--help attempted a cloud deployment') + +mobilerun.sandbox.deploy = blocked +mobilerun.sandbox.app.deploy = blocked +path = sys.argv[1] +sys.argv = [path, '--help'] +runpy.run_path(path, run_name='__main__') +""" + result = subprocess.run( + [sys.executable, "-c", code, str(REPO_ROOT / "tests" / "demos" / f"{name}.py")], + capture_output=True, + text=True, + timeout=15, + ) + assert result.returncode == 0, result.stderr + assert "--yes" in result.stdout + + +def test_vault_reports_disconnected_device_in_one_line(monkeypatch, capsys): + async def disconnected(*args, **kwargs): + raise DeviceDisconnectedError("private target") + + monkeypatch.setattr(vault_demo, "main", disconnected) + assert vault_demo.cli(["--live"]) == 1 + output = capsys.readouterr().err.splitlines() + assert len(output) == 1 + assert "not reachable" in output[0] + assert "private target" not in output[0] diff --git a/tests/unit/demos/test_device_demos.py b/tests/unit/demos/test_device_demos.py index 02f5f565f..9e28086f2 100644 --- a/tests/unit/demos/test_device_demos.py +++ b/tests/unit/demos/test_device_demos.py @@ -1,4 +1,4 @@ -"""Offline contracts for the introduction, app, macro, and vault device demos.""" +"""Offline contracts for the device demos.""" import asyncio import subprocess @@ -7,9 +7,13 @@ from unittest.mock import AsyncMock, Mock import pytest +from click.testing import CliRunner +from mobilerun_core import AppIdentity, InstalledApp -from mobilerun.core.devices.base import Device -from tests.demos import intro_demo +from mobilerun.cli.devices.base import selection as device_selection +from mobilerun.models import Billing +from tests.demos import app_demo, intro_demo, task_demo, vault_demo +from tests.support.devices import FakeDriver, fake_device from tests.support.paths import REPO_ROOT @@ -50,26 +54,97 @@ def test_agent_demo_uses_public_operator(monkeypatch): assert intro_demo.AgentOperator() is operator.return_value -def test_main_without_agent_uses_base_device(monkeypatch): - device = Mock(_ensure_connected=AsyncMock()) - cloud = Mock(_ensure_connected=AsyncMock()) - android = Mock(return_value=device) +def fake_run(monkeypatch, demo, *devices): + """Replace factory I/O and still close every connected core device.""" + + class FakeMobilerun: + def __init__(self): + self.connect = AsyncMock(side_effect=devices) + self.create_cloud = AsyncMock(side_effect=devices) + self.local = SimpleNamespace(select_android=AsyncMock(return_value="usb")) + self.closed = False + + async def __aenter__(self): + return self + + async def __aexit__(self, *exc): + for device in devices: + await device.aclose() + self.closed = True + + run = FakeMobilerun() + monkeypatch.setattr(demo, "AsyncMobilerun", Mock(return_value=run)) + return run + + +def test_main_without_agent_opens_borrowed_devices(monkeypatch): + device, cloud = fake_device(), fake_device() + run = fake_run(monkeypatch, intro_demo, device, cloud) monkeypatch.setattr(intro_demo, "AGENT", False) - monkeypatch.setattr(intro_demo, "AndroidDevice", android) - monkeypatch.setattr(intro_demo, "CloudDevice", Mock(return_value=cloud)) + monkeypatch.setattr(intro_demo, "cloud_client", Mock(), raising=False) monkeypatch.setattr(intro_demo, "sandbox_and_skills", Mock()) for name in ( "local_demos", "cloud_demos", - "pool_demo", + "multiple_devices_demo", "new_cloud_device_demo", "emulator_demo", ): - monkeypatch.setattr(intro_demo, name, AsyncMock()) - asyncio.run(intro_demo.main()) - android.assert_called_once_with(intro_demo.LOCAL_SERIAL) + monkeypatch.setattr(intro_demo, name, AsyncMock(), raising=False) + asyncio.run(intro_demo.main(cloud_device="borrowed")) + assert [call.kwargs["backend"] for call in run.connect.await_args_list] == [ + "local-android-adb", + "cloud", + ] intro_demo.local_demos.assert_awaited_once_with(device) - intro_demo.cloud_demos.assert_awaited_once_with(cloud) + intro_demo.cloud_demos.assert_awaited_once_with(cloud, None) + intro_demo.cloud_client.assert_not_called() + assert run.closed + + +def test_intro_temporary_phone_uses_a_borrowed_proxy(monkeypatch, tmp_path): + monkeypatch.chdir(tmp_path) + driver = FakeDriver(device_id="temporary") + run = fake_run(monkeypatch, intro_demo, fake_device(driver=driver)) + proxy = SimpleNamespace(as_device_proxy=lambda: "proxy-reference") + rotating = SimpleNamespace(select=AsyncMock(return_value=proxy)) + monkeypatch.setattr(intro_demo, "CloudRotatingProxy", rotating, raising=False) + monkeypatch.setattr(intro_demo, "NEW_CLOUD_DEVICE", True) + asyncio.run(intro_demo.new_cloud_device_demo(run)) + run.create_cloud.assert_awaited_once() + options = run.create_cloud.await_args.kwargs + assert (options["plan"], options["keep"], options["proxy"]) == ( + "minute", + False, + "proxy-reference", + ) + assert ( + tmp_path / "fresh-cloud-screenshot.png" + ).read_bytes() == driver.screenshot_bytes + + +def test_intro_records_and_replays_core_actions(monkeypatch, tmp_path, capsys): + from mobilerun.macro import load_macro + + monkeypatch.setenv("MOBILERUN_MACRO_DIRECTORY", str(tmp_path / "macros")) + monkeypatch.setenv("MOBILERUN_RUNS_DIR", str(tmp_path / "runs")) + monkeypatch.setenv("MOBILERUN_MACRO_DELAY", "0") + driver = FakeDriver() + + async def run(): + async with fake_device(driver=driver) as device: + await intro_demo.macro_demo(device) + + asyncio.run(run()) + assert [step.action.name for step in load_macro("intro-demo")] == [ + "start_app", + "wait", + "swipe", + "wait", + "key", + ] + assert [call[0] for call in driver.calls].count("swipe") == 2 + assert "macro replay: True" in capsys.readouterr().out def test_help_exits_without_running_demo(monkeypatch): @@ -91,7 +166,7 @@ def test_declining_does_not_run_demo(monkeypatch, capsys, new_phone): monkeypatch.setattr(intro_demo, "NEW_CLOUD_DEVICE", new_phone) prompts = [] monkeypatch.setattr("builtins.input", lambda prompt: prompts.append(prompt) or "n") - intro_demo.cli([]) + intro_demo.cli(["--live"]) main.assert_not_called() assert "cloud task" in prompts[0].lower() assert "llm" in prompts[0].lower() @@ -103,8 +178,8 @@ def test_yes_runs_main(monkeypatch): main = AsyncMock() monkeypatch.setattr(intro_demo, "main", main) monkeypatch.setattr("builtins.input", lambda _: pytest.fail("unexpected prompt")) - intro_demo.cli(["--yes"]) - main.assert_awaited_once_with() + intro_demo.cli(["--live", "--yes"]) + main.assert_awaited_once_with(serial=None, cloud_device=None) def test_script_help_in_isolated_mode(): @@ -132,336 +207,331 @@ def test_script_help_in_isolated_mode(): assert "--yes" in result.stdout -@pytest.fixture -def app_demo(): - pytest.importorskip("mobilerun_agents", reason="demo requires the agents add-on") - from tests.demos import app_demo - - return app_demo - - -def test_app_demo_runs_on_both_devices(app_demo, monkeypatch, capsys): - - devices = [] - - class FakeDevice(Device): - def __init__(self, identifier, **kwargs): - super().__init__() - self._identifier = identifier - self._operator = None - self.calls = [] - devices.append(self) - - @property - def identifier(self): - return self._identifier - - async def install_apk(self, path): - self.calls.append(("install", path)) - return SimpleNamespace(package=self.identifier or "local") - - async def start_app(self, package, activity=None): - self.calls.append(("start", package)) - - async def uninstall_app(self, app): - self.calls.append(("uninstall", app)) - - async def wait(self, seconds): - self.calls.append(("wait", seconds)) - - async def do(self, instruction, **kwargs): - self.calls.append(("do", instruction, kwargs["output"])) - return SimpleNamespace(output=app_demo.CounterValue(value=10)) - - async def expect(self, condition): - self.calls.append(("expect", condition)) - return SimpleNamespace(passed=True) - - async def press_button(self, button): - self.calls.append(("press", button)) - - monkeypatch.setattr(app_demo, "AndroidDevice", FakeDevice) - monkeypatch.setattr(app_demo, "CloudDevice", FakeDevice) - monkeypatch.setattr(app_demo, "CloudTaskOperator", lambda **kwargs: object()) - asyncio.run(app_demo.main(yes=True)) - - assert [device.identifier for device in devices] == [ - app_demo.LOCAL_SERIAL, - app_demo.CLOUD_DEVICE_ID, - ] - for device in devices: - assert device.calls[:3] == [ - ("install", app_demo.APK), - ("start", device.identifier or "local"), - ("wait", 2), +@pytest.mark.parametrize("expect_fails", [False, True]) +def test_app_demo_runs_on_both_devices(monkeypatch, capsys, expect_fails): + from contextlib import nullcontext + + drivers = [FakeDriver(device_id="usb"), FakeDriver(device_id="remote")] + devices = [fake_device(driver=driver) for driver in drivers] + run = fake_run(monkeypatch, app_demo, *devices) + client = object() + monkeypatch.setattr(app_demo, "cloud_client", lambda **_: nullcontext(client)) + operators = [] + for i, device in enumerate(devices): + monkeypatch.setattr( + device, + "install_app", + AsyncMock( + return_value=InstalledApp( + AppIdentity(f"counter.app{i}", 1, "1.0"), + "Counter", + ) + ), + ) + monkeypatch.setattr(device, "wait", AsyncMock()) + operators.append( + SimpleNamespace( + do=AsyncMock( + return_value=SimpleNamespace(output=app_demo.CounterValue(value=10)) + ), + expect=AsyncMock(return_value=SimpleNamespace(passed=True)), + ) + ) + if expect_fails: + operators[1].expect.side_effect = RuntimeError("expectation unavailable") + monkeypatch.setattr(app_demo, "local_operator", lambda: operators[0]) + cloud_operator = Mock(return_value=operators[1]) + monkeypatch.setattr(app_demo, "CloudTaskOperator", cloud_operator) + asyncio.run(app_demo.main(yes=True, cloud_device="borrowed")) + + cloud_operator.assert_called_once_with(client=client) + run.create_cloud.assert_not_awaited() + assert run.closed + for i, (device, driver, operator) in enumerate( + zip(devices, drivers, operators, strict=True) + ): + device.install_app.assert_awaited_once_with(app_demo.APK) + device.wait.assert_awaited_once_with(2) + assert [call[:2] for call in driver.calls] == [ + ("start_app", (f"counter.app{i}",)), + ("press_button", ("home",)), ] - - -def test_app_demo_does_not_reuse_execution_results_when_expect_fails( - app_demo, monkeypatch, capsys -): - - class Pool: - def __init__(self, devices): - pass - - async def do(self, *args, **kwargs): - return [SimpleNamespace(output=None), SimpleNamespace(output=None)] - - async def expect(self, condition): - raise RuntimeError("expectation unavailable") - - async def press_button(self, button): - pass - - async def close(self): - pass - - async def install(pool): - pass - - monkeypatch.setattr(app_demo, "CloudDevice", lambda *a, **kw: object()) - monkeypatch.setattr(app_demo, "CloudTaskOperator", lambda: object()) - monkeypatch.setattr(app_demo, "DevicePool", Pool) - monkeypatch.setattr(app_demo, "install_and_open", install) - asyncio.run(app_demo.main(yes=True)) - assert "expect failed: expectation unavailable" in capsys.readouterr().out - - -def test_app_demo_zips_one_cloud_label_with_one_result(app_demo, monkeypatch, capsys): - - class Pool: - def __init__(self, devices): - pass - - async def do(self, *args, **kwargs): - return [ - SimpleNamespace(output=app_demo.CounterValue(value=10)), - SimpleNamespace(output=app_demo.CounterValue(value=10)), - ] - - async def expect(self, condition): - return [SimpleNamespace(passed=True), SimpleNamespace(passed=True)] - - async def press_button(self, button): - pass - - async def close(self): - pass - - async def install(pool): - pass - - monkeypatch.setattr(app_demo, "AndroidDevice", lambda *a, **kw: object()) - monkeypatch.setattr(app_demo, "CloudDevice", lambda *a, **kw: object()) - monkeypatch.setattr(app_demo, "CloudTaskOperator", lambda: object()) - monkeypatch.setattr(app_demo, "DevicePool", Pool) - monkeypatch.setattr(app_demo, "install_and_open", install) - asyncio.run(app_demo.main(yes=True)) + operator.do.assert_awaited_once_with( + device, + "Count to ten: tap the increment button 10 times", + output=app_demo.CounterValue, + ) + operator.expect.assert_awaited_once_with(device, "The counter shows 10") output = capsys.readouterr().out assert "local counter: 10" in output assert "cloud counter: 10" in output assert "local expect: True" in output - assert "cloud expect: True" in output - + assert ("cloud expect: True" in output) is not expect_fails + assert ("expect failed: expectation unavailable" in output) is expect_fails -def test_app_demo_decline_does_not_create(app_demo, monkeypatch): +@pytest.mark.parametrize("demo", [app_demo, task_demo]) +def test_decline_does_not_open_device_client(demo, monkeypatch): create = Mock() - monkeypatch.setattr(app_demo, "CloudDevice", create) + monkeypatch.setattr(demo, "AsyncMobilerun", create) + monkeypatch.setattr( + demo, "cloud_client", Mock(side_effect=AssertionError("unexpected SDK client")) + ) + if demo is task_demo: + monkeypatch.setattr( + demo, + "CloudRotatingProxy", + Mock(side_effect=AssertionError("unexpected proxy")), + ) monkeypatch.setattr("builtins.input", lambda _: "n") - asyncio.run(app_demo.main(yes=False)) + asyncio.run(demo.main(yes=False)) create.assert_not_called() -def test_macro_records_replays_and_closes(monkeypatch, tmp_path): - from mobilerun.macro import load_macro +@pytest.mark.parametrize( + ("billing", "plan"), + [ + (Billing.INCLUDED, None), + (Billing.INCLUDED, "minute"), + (Billing.NO_COMMERCE, None), + (Billing.PAID, "subscription"), + (Billing.PAID, "auto"), + ], +) +def test_task_refuses_incompatible_billing_or_plan(monkeypatch, billing, plan): + factory = Mock() + monkeypatch.setattr(task_demo, "AsyncMobilerun", factory) + proxy = Mock() + monkeypatch.setattr(task_demo, "CloudRotatingProxy", proxy) + with pytest.raises(ValueError, match="--plan"): + asyncio.run(task_demo.main(yes=True, billing=billing, plan=plan)) + factory.assert_not_called() + assert not proxy.mock_calls + + +@pytest.mark.parametrize("purchase", [False, True]) +@pytest.mark.parametrize("fail", [False, True]) +def test_task_passes_phone_to_operator_and_closes_proxy_last( + monkeypatch, capsys, purchase, fail +): + from contextlib import nullcontext + + from mobilerun_core import ConnectProxyRef + + driver = FakeDriver(device_id="temporary") + phone = fake_device(driver=driver) + monkeypatch.setattr( + phone, "proxy_status", AsyncMock(return_value=SimpleNamespace(connected=True)) + ) + run = fake_run(monkeypatch, task_demo, phone) + released = [] + ref = ConnectProxyRef("demo-proxy") + + async def close_proxy(): + assert run.closed + if purchase: + released.append(ref.id) + + proxy = SimpleNamespace( + as_device_proxy=lambda: ref, close=AsyncMock(side_effect=close_proxy) + ) + rotating = SimpleNamespace( + select=AsyncMock(return_value=proxy), purchase=AsyncMock(return_value=proxy) + ) + if purchase: + rotating.select.side_effect = LookupError("no capacity") + monkeypatch.setattr(task_demo, "CloudRotatingProxy", rotating) + client = object() + monkeypatch.setattr(task_demo, "cloud_client", lambda **_: nullcontext(client)) + operator = SimpleNamespace( + do=AsyncMock( + side_effect=[ + SimpleNamespace(task_id="open"), + SimpleNamespace( + task_id="version", output=task_demo.AndroidVersion(version="15") + ), + SimpleNamespace(task_id="timed"), + ] + ), + expect=AsyncMock( + return_value=SimpleNamespace(task=SimpleNamespace(task_id="check")) + ), + ) + operator_factory = Mock(return_value=operator) + monkeypatch.setattr(task_demo, "CloudTaskOperator", operator_factory) + if fail: + operator.do.side_effect = RuntimeError("task failed") + with pytest.raises(RuntimeError, match="task failed"): + asyncio.run(task_demo.main(yes=True, billing=Billing.PAID)) + else: + asyncio.run(task_demo.main(yes=True, billing=Billing.PAID)) + assert "Android version: 15" in capsys.readouterr().out + assert ("press_button", ("home",), {}) in driver.calls + operator.expect.assert_awaited_once_with(phone, "The Settings app is open") + assert operator.do.await_args.kwargs == {"timeout": 120} + operator_factory.assert_called_once_with(client=client, billing=Billing.PAID) + assert all(call.args[0] is phone for call in operator.do.await_args_list) + assert run.create_cloud.await_args.kwargs["proxy"] == ref + assert run.create_cloud.await_args.kwargs["keep"] is False + assert run.create_cloud.await_args.kwargs["plan"] == "minute" + assert rotating.purchase.await_count == int(purchase) + proxy.close.assert_awaited_once() + assert released == ([ref.id] if purchase else []) + + +def test_macro_closes_device_on_success(monkeypatch, tmp_path): from tests.demos import macro_demo as demo - from tests.support.devices import MemoryDevice monkeypatch.setenv("MOBILERUN_MACRO_DIRECTORY", str(tmp_path / "macros")) monkeypatch.setenv("MOBILERUN_RUNS_DIR", str(tmp_path / "runs")) monkeypatch.setenv("MOBILERUN_MACRO_DELAY", "0") - device = MemoryDevice() - device.start_app = AsyncMock() - device.tap = AsyncMock() - device.press_button = AsyncMock() - device.close = AsyncMock() - monkeypatch.setattr(demo, "AndroidDevice", lambda *a, **kw: device) - # Exercise the real recorder and player against a fake device. - asyncio.run(demo.main()) - assert device.start_app.await_count == 2 - assert device.tap.await_count == 2 - assert device.press_button.await_count == 3 - device.close.assert_awaited_once() - assert [step.action for step in load_macro("settings-demo")] == [ - "start_app", - "tap", - "button_press", - ] + run = fake_run(monkeypatch, device_selection, fake_device()) + result = CliRunner().invoke(demo.cli, ["--device", "emulator-5556"]) + assert result.exit_code == 0, result.output + run.connect.assert_awaited_once_with( + "emulator-5556", backend="local-android-adb", portal_mode="auto", use_tcp=False + ) + assert run.closed def test_macro_closes_device_on_failure(monkeypatch, tmp_path): from tests.demos import macro_demo as demo - from tests.support.devices import MemoryDevice monkeypatch.setenv("MOBILERUN_RUNS_DIR", str(tmp_path / "runs")) - device = MemoryDevice() - device.press_button = AsyncMock() - device.start_app = AsyncMock(side_effect=RuntimeError("failed")) - device.close = AsyncMock() - monkeypatch.setattr(demo, "AndroidDevice", lambda *a, **kw: device) - with pytest.raises(RuntimeError, match="failed"): - asyncio.run(demo.main()) - device.close.assert_awaited_once() - - -def setup_vault_demo(monkeypatch, *, fail=False): - from tests.demos import vault_demo as demo - - calls = [] - snapshots = [ - SimpleNamespace( - elements=[{"index": 7, "text": "Search settings", "resourceId": "search"}], - focused_text="", - ), - SimpleNamespace( - elements=[ - { - "index": 8, - "className": "EditText", - "resourceId": "search_input", - "text": "", - } - ], - focused_text="", - ), - SimpleNamespace(elements=[], focused_text="demo-user"), - ] - device = SimpleNamespace( - close=AsyncMock(side_effect=lambda: calls.append("device.close")), - start_app=AsyncMock(), - wait=AsyncMock(), - tap_element=AsyncMock(), - press_button=AsyncMock(), - state=SimpleNamespace(refresh=AsyncMock(side_effect=snapshots)), - ) - vault = SimpleNamespace() - - async def bind(target): - assert target is device - calls.append("bind") - - async def list_metadata(package): - assert calls == ["bind"] - assert package == demo.PACKAGE - return [{"package": package, "name": "work", "fields": ["username"]}] - - async def type_field(package, field, *, name): - assert calls[0] == "bind" - calls.append("type") + driver = FakeDriver(failures={"start_app": RuntimeError("failed")}) + run = fake_run(monkeypatch, device_selection, fake_device(driver=driver)) + result = CliRunner().invoke(demo.cli, ["--device", "emulator-5554"]) + assert isinstance(result.exception, RuntimeError) + assert str(result.exception) == "failed" + assert run.closed + + +def setup_vault_demo(monkeypatch, *, initial="home", typed="demo-user", fail=False): + driver = FakeDriver() + edit = driver.ui_tree["a11y_tree"][0] + search = { + "resourceId": "search", + "text": "Search settings", + "boundsInScreen": {"left": 10, "top": 0, "right": 30, "bottom": 20}, + } + clear = { + "resourceId": "search_clear_button", + "boundsInScreen": {"left": 40, "top": 20, "right": 60, "bottom": 40}, + } + driver.ui_tree["a11y_tree"] = { + "home": [search], + "search": [edit, clear], + "missing": [], + }[initial] + device = fake_device(driver=driver, hitl_gate=lambda _action, _args: True) + monkeypatch.setattr(device, "wait", AsyncMock()) + run = fake_run(monkeypatch, vault_demo, device) + real_tap = driver.tap + + async def tap(x, y): + await real_tap(x, y) + if y < 20 or x >= 40: + driver.ui_tree["a11y_tree"] = [edit] + + monkeypatch.setattr(driver, "tap", tap) + + async def type_secret(name, *, package, field): if fail: raise RuntimeError("failed") + edit["text"] = typed - vault.bind = AsyncMock(side_effect=bind) - vault.list = AsyncMock(side_effect=list_metadata) - vault.type_field = AsyncMock(side_effect=type_field) - vault.save = AsyncMock() - vault.delete = AsyncMock() - vault.unbind = AsyncMock(side_effect=lambda: calls.append("unbind")) - vault.close = AsyncMock() - monkeypatch.setattr(demo, "CloudCredentials", lambda: vault) - monkeypatch.setattr(demo, "AndroidDevice", lambda *a, **kw: device) - return demo, vault, device, calls + vault = SimpleNamespace( + list=AsyncMock( + return_value=[ + {"package": vault_demo.PACKAGE, "name": "work", "fields": ["username"]} + ] + ), + save=AsyncMock(), + delete=AsyncMock(), + close=AsyncMock(), + type_secret=AsyncMock(side_effect=type_secret), + ) + provider = Mock(return_value=vault) + monkeypatch.setattr(vault_demo, "CloudCredentials", provider) + return vault, provider, device, driver, run def test_vault_demo_saves_types_and_cleans_up(monkeypatch, capsys): - demo, vault, device, calls = setup_vault_demo(monkeypatch) - asyncio.run(demo.main()) + vault, provider, device, driver, run = setup_vault_demo(monkeypatch) + asyncio.run(vault_demo.main()) name = vault.save.await_args.args[1] - vault.type_field.assert_awaited_once_with(demo.PACKAGE, "username", name=name) - vault.delete.assert_awaited_once_with(demo.PACKAGE, name) - vault.unbind.assert_awaited_once() + provider.assert_called_once_with(device=device) + vault.type_secret.assert_awaited_once_with( + name, package=vault_demo.PACKAGE, field="username" + ) + vault.delete.assert_awaited_once_with(vault_demo.PACKAGE, name) vault.close.assert_awaited_once() - device.close.assert_awaited_once() - assert calls == ["bind", "type", "unbind", "device.close"] + assert run.closed output = capsys.readouterr().out assert "work" in output assert "demo-password" not in output assert "Field now contains: demo-user" in output - device.start_app.assert_awaited_once_with("com.android.settings") - assert [item.args for item in device.tap_element.await_args_list] == [(7,), (8,)] - device.press_button.assert_awaited_once_with("home") + assert driver.calls[0][:2] == ("start_app", ("com.android.settings",)) + assert [args for action, args, _ in driver.calls if action == "tap"] == [ + (20, 10), + (20, 30), + ] + assert driver.calls[-1][:2] == ("press_button", ("home",)) def test_vault_cleanup_on_typing_error(monkeypatch): - demo, vault, device, calls = setup_vault_demo(monkeypatch, fail=True) + vault, _, _, driver, run = setup_vault_demo(monkeypatch, fail=True) with pytest.raises(RuntimeError, match="failed"): - asyncio.run(demo.main()) + asyncio.run(vault_demo.main()) vault.delete.assert_awaited_once() - vault.unbind.assert_awaited_once() vault.close.assert_awaited_once() - device.close.assert_awaited_once() - assert calls == ["bind", "type", "unbind", "device.close"] + assert driver.calls[-1][:2] == ("press_button", ("home",)) + assert run.closed -def test_vault_closes_after_bind_failure_without_deleting(monkeypatch): - demo, vault, device, _ = setup_vault_demo(monkeypatch) - vault.bind.side_effect = RuntimeError("binding failed") - with pytest.raises(RuntimeError, match="binding failed"): - asyncio.run(demo.main()) +def test_vault_closes_after_list_failure_without_deleting(monkeypatch): + vault, _, _, _, run = setup_vault_demo(monkeypatch) + vault.list.side_effect = RuntimeError("listing failed") + with pytest.raises(RuntimeError, match="listing failed"): + asyncio.run(vault_demo.main()) vault.save.assert_not_awaited() vault.delete.assert_not_awaited() - vault.unbind.assert_not_awaited() vault.close.assert_awaited_once() - device.close.assert_awaited_once() + assert run.closed def test_vault_closes_device_even_if_delete_fails(monkeypatch): - demo, vault, device, calls = setup_vault_demo(monkeypatch) + vault, _, _, _, run = setup_vault_demo(monkeypatch) vault.delete.side_effect = RuntimeError("delete failed") with pytest.raises(RuntimeError, match="delete failed"): - asyncio.run(demo.main()) - vault.unbind.assert_awaited_once() + asyncio.run(vault_demo.main()) vault.close.assert_awaited_once() - device.close.assert_awaited_once() - assert calls == ["bind", "type", "unbind", "device.close"] + assert run.closed def test_existing_search_is_cleared_before_typing(monkeypatch): - demo, vault, device, _ = setup_vault_demo(monkeypatch) - device.state.refresh.side_effect = [ - SimpleNamespace( - elements=[ - {"index": 2, "className": "EditText"}, - {"index": 3, "resourceId": "search_clear_button"}, - ] - ), - SimpleNamespace(elements=[{"index": 4, "className": "EditText"}]), - SimpleNamespace(elements=[], focused_text="demo-user"), + vault, _, _, driver, _ = setup_vault_demo(monkeypatch, initial="search") + asyncio.run(vault_demo.main()) + assert [args for action, args, _ in driver.calls if action == "tap"] == [ + (50, 30), + (20, 30), ] - asyncio.run(demo.main()) - assert [item.args for item in device.tap_element.await_args_list] == [(3,), (4,)] - vault.type_field.assert_awaited_once() + vault.type_secret.assert_awaited_once() def test_missing_search_still_cleans_up(monkeypatch): - demo, vault, device, _ = setup_vault_demo(monkeypatch) - device.state.refresh.side_effect = [SimpleNamespace(elements=[])] + vault, _, _, driver, run = setup_vault_demo(monkeypatch, initial="missing") with pytest.raises(RuntimeError, match="search entry not found"): - asyncio.run(demo.main()) - vault.type_field.assert_not_awaited() + asyncio.run(vault_demo.main()) + vault.type_secret.assert_not_awaited() vault.delete.assert_awaited_once() - device.press_button.assert_awaited_once_with("home") - device.close.assert_awaited_once() + assert driver.calls[-1][:2] == ("press_button", ("home",)) + assert run.closed def test_wrong_focused_text_is_not_printed(monkeypatch, capsys): - demo, vault, device, _ = setup_vault_demo(monkeypatch) - snapshots = list(device.state.refresh.side_effect) - snapshots[2].focused_text = "private-existing-text" - device.state.refresh.side_effect = snapshots + vault, _, _, _, _ = setup_vault_demo(monkeypatch, typed="private-existing-text") with pytest.raises(RuntimeError, match="not visible"): - asyncio.run(demo.main()) + asyncio.run(vault_demo.main()) assert "private-existing-text" not in capsys.readouterr().out vault.delete.assert_awaited_once() diff --git a/tests/unit/demos/test_easy_macro_demo.py b/tests/unit/demos/test_easy_macro_demo.py new file mode 100644 index 000000000..9771636d3 --- /dev/null +++ b/tests/unit/demos/test_easy_macro_demo.py @@ -0,0 +1,79 @@ +"""Exercise the easy macro demo without a phone.""" + +import asyncio +from contextlib import asynccontextmanager +from pathlib import Path +from unittest.mock import AsyncMock + +import pytest +from click.testing import CliRunner + +from mobilerun.macro import load_macro +from tests.demos import easy_macro_demo +from tests.support.devices import FakeDriver, fake_device + +_RECORDED = [ + ("start_app", ("com.android.settings",), {"activity": None}), + ("swipe", (500, 1500, 500, 500), {"duration_ms": 300}), +] +_RESET = [ + ("stop_app", ("com.android.settings",), {}), + ("press_button", ("home",), {}), +] + + +@pytest.fixture(autouse=True) +def _fast_and_isolated(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("MOBILERUN_MACRO_DIRECTORY", str(tmp_path / "macros")) + monkeypatch.setenv("MOBILERUN_RUNS_DIR", str(tmp_path / "runs")) + monkeypatch.setenv("MOBILERUN_MACRO_DELAY", "0") + monkeypatch.setattr(easy_macro_demo, "PAUSE", 0) + + +def test_easy_macro_demo_records_resets_then_replays(tmp_path: Path) -> None: + driver = FakeDriver() + + async def run() -> None: + async with fake_device(driver=driver) as phone: + await easy_macro_demo.main(phone) + + asyncio.run(run()) + + assert driver.calls == _RECORDED + _RESET + _RECORDED + steps = load_macro(tmp_path / "macros" / "easy-demo" / "v1.jsonl") + assert [step.action.name for step in steps] == [ + "start_app", + "wait", + "swipe", + "wait", + ] + times = [step.action.started_at for step in steps] + assert None not in times and times == sorted(times) + + +def test_easy_macro_demo_runs_on_the_given_device( + monkeypatch: pytest.MonkeyPatch, +) -> None: + driver = FakeDriver() + connect = AsyncMock() + + class Run: + pass + + Run.connect = connect + + @asynccontextmanager + async def open_client(**kwargs): + async with fake_device(driver=driver) as phone: + connect.return_value = phone + yield Run() + + monkeypatch.setattr("mobilerun.cli.devices.base.device.open_client", open_client) + + result = CliRunner().invoke(easy_macro_demo.cli, ["adb-1"]) + + assert result.exit_code == 0, result.output + assert connect.await_args.args == ("adb-1",) + lines = result.output.splitlines() + assert lines[0].startswith("1. Recorded 4 actions: ") + assert lines[1:] == ["2. Reset the phone", "3. Replayed 4 actions"] diff --git a/tests/unit/demos/test_macro_demo.py b/tests/unit/demos/test_macro_demo.py new file mode 100644 index 000000000..b7a37241e --- /dev/null +++ b/tests/unit/demos/test_macro_demo.py @@ -0,0 +1,111 @@ +"""Exercise the local macro demo without ADB.""" + +import asyncio +from contextlib import asynccontextmanager +from pathlib import Path +from unittest.mock import AsyncMock + +import pytest +from click.testing import CliRunner +from mobilerun_core import Action, DeviceDisconnectedError + +from mobilerun.macro import load_macro +from tests.demos import macro_demo +from tests.support.devices import FakeDriver, fake_device + + +def test_macro_demo_replays_the_recorded_actions( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + macro_dir = tmp_path / "macros" + monkeypatch.setenv("MOBILERUN_MACRO_DIRECTORY", str(macro_dir)) + monkeypatch.setenv("MOBILERUN_RUNS_DIR", str(tmp_path / "runs")) + driver = FakeDriver() + + async def run() -> None: + async with fake_device(driver=driver) as phone: + await macro_demo.main(phone) + + asyncio.run(run()) + + actions = [ + ("press_button", ("home",), {}), + ("start_app", ("com.android.settings",), {"activity": None}), + ("tap", (200, 200), {}), + ("press_button", ("home",), {}), + ] + assert [call for call in driver.calls if call[0] != "get_ui_tree"] == actions * 2 + steps = load_macro(macro_dir / "settings-demo" / "v1.jsonl") + assert steps[2].action == Action("tap", {"x": 200, "y": 200}, "device") + + +@pytest.mark.parametrize("args, serial", [([], ""), (["--fake"], "configured-serial")]) +def test_macro_demo_runs_offline_without_opening_a_connection( + tmp_path, monkeypatch, args, serial +): + monkeypatch.setenv("MOBILERUN_MACRO_DIRECTORY", str(tmp_path / "macros")) + monkeypatch.setenv("MOBILERUN_RUNS_DIR", str(tmp_path / "runs")) + + def forbid_connection(*args, **kwargs): + pytest.fail("Offline demo tried to open a real device connection") + + monkeypatch.setattr( + "mobilerun.cli.devices.base.device.open_client", forbid_connection + ) + result = CliRunner().invoke( + macro_demo.cli, + args, + env={"ANDROID_SERIAL": serial, "MOBILERUN_USER_CONFIG_DIR": str(tmp_path)}, + ) + assert result.exit_code == 0, result.output + assert "Recorded 4 actions" in result.output + assert "Built macro" in result.output + assert "Replayed 4 actions" in result.output + + +@pytest.mark.parametrize( + "explicit, serial, reachable, backend", + [ + (None, "", True, None), + (None, "", False, None), + (None, "adb-1", True, "local-android-adb"), + ("chosen", "adb-1", True, "local-android-adb"), + ], +) +def test_macro_demo_resolves_device_and_reports_connection_failure( + tmp_path, monkeypatch, explicit, serial, reachable, backend +): + device_id = "9bfe222d-ec3c-47d1-a4ca-ff8fbe8f7fe6" + config = tmp_path / "mobilerun.yaml" + config.write_text(f"device:\n serial: {device_id}\n") + monkeypatch.setenv("MOBILERUN_CONFIG", str(config)) + monkeypatch.setenv("MOBILERUN_MACRO_DIRECTORY", str(tmp_path / "macros")) + monkeypatch.setenv("MOBILERUN_RUNS_DIR", str(tmp_path / "runs")) + driver = FakeDriver() + + class Run: + connect = AsyncMock( + side_effect=None if reachable else DeviceDisconnectedError("private detail") + ) + + @asynccontextmanager + async def open_client(**kwargs): + async with fake_device(driver=driver) as phone: + Run.connect.return_value = phone + yield Run() + + monkeypatch.setattr("mobilerun.cli.devices.base.device.open_client", open_client) + args = ["--device", explicit] if explicit else [] + result = CliRunner().invoke(macro_demo.cli, args, env={"ANDROID_SERIAL": serial}) + target = explicit or serial or device_id + assert Run.connect.await_count == 1 + assert Run.connect.await_args.args == (target,) + assert Run.connect.await_args.kwargs["backend"] == backend + if reachable: + assert result.exit_code == 0, result.output + assert "Replayed 4 actions" in result.output + else: + assert result.exit_code == 1 + assert result.output.splitlines() == [ + f"Error: Device {device_id} is not reachable; start it or run `mobilerun device connect`." + ] diff --git a/tests/unit/demos/test_resources.py b/tests/unit/demos/test_resources.py index cc17e9bb8..89809b7e6 100644 --- a/tests/unit/demos/test_resources.py +++ b/tests/unit/demos/test_resources.py @@ -2,13 +2,15 @@ import asyncio from argparse import Namespace +from contextlib import asynccontextmanager from types import SimpleNamespace -from typing import cast from unittest.mock import AsyncMock import pytest +from mobilerun_core import ConnectProxyRef, ProxyOperationError, ProxyStatus from tests.demos import mailbox_demo, phone_demo, proxy_demo, task_demo +from tests.support.devices import FakeDriver, fake_device def test_payment_checkout_is_printed(monkeypatch, capsys): @@ -44,7 +46,7 @@ def test_confirmation_accepts_y(monkeypatch, capsys): id="box-1", address="test@example.com", wait_for_code=AsyncMock(return_value="1234"), - release=AsyncMock(), + close=AsyncMock(), ) monkeypatch.setattr(mailbox_demo, "CloudMailbox", AsyncMock(return_value=mailbox)) @@ -61,7 +63,7 @@ def confirm(prompt): assert ( "This may use paid cloud services. Continue? [y/N]" in capsys.readouterr().out ) - mailbox.release.assert_awaited_once() + mailbox.close.assert_awaited_once() def test_yes_receives_code_and_releases(monkeypatch, capsys): @@ -69,7 +71,7 @@ def test_yes_receives_code_and_releases(monkeypatch, capsys): id="box-1", address="test@example.com", wait_for_code=AsyncMock(return_value="123456"), - release=AsyncMock(), + close=AsyncMock(), ) create = AsyncMock(return_value=mailbox) monkeypatch.setattr(mailbox_demo, "CloudMailbox", create) @@ -82,7 +84,7 @@ def test_yes_receives_code_and_releases(monkeypatch, capsys): billing="paid", keep=False, checkout="print", payment_timeout=600 ) assert mailbox.wait_for_code.await_args.kwargs["timeout"] == 25 - mailbox.release.assert_awaited_once() + mailbox.close.assert_awaited_once() output = capsys.readouterr().out assert "test@example.com" in output and "123456" in output assert "Released mailbox box-1." in output @@ -93,7 +95,7 @@ def test_timeout_still_releases(monkeypatch): id="box-1", address="test@example.com", wait_for_code=AsyncMock(side_effect=TimeoutError), - release=AsyncMock(), + close=AsyncMock(), ) monkeypatch.setattr(mailbox_demo, "CloudMailbox", AsyncMock(return_value=mailbox)) with pytest.raises(TimeoutError): @@ -102,46 +104,36 @@ def test_timeout_still_releases(monkeypatch): Namespace(payment_timeout=600, yes=True, keep=False, timeout=1) ) ) - mailbox.release.assert_awaited_once() + mailbox.close.assert_awaited_once() -def test_keep_does_not_release_mailbox(monkeypatch): - mailbox = SimpleNamespace( - id="box-1", - address="test@example.com", - wait_for_code=AsyncMock(return_value="1234"), - release=AsyncMock(), - ) - create = AsyncMock(return_value=mailbox) - monkeypatch.setattr(mailbox_demo, "CloudMailbox", create) - asyncio.run( - mailbox_demo.main( - Namespace(payment_timeout=600, yes=True, keep=True, timeout=1) - ) - ) - create.assert_called_once_with( - billing="paid", keep=True, checkout="print", payment_timeout=600 - ) - mailbox.release.assert_not_awaited() - - -def test_real_unbound_mailbox_waits_for_code(monkeypatch): +@pytest.mark.parametrize("keep", [False, True]) +def test_mailbox_without_phone_polls_then_honors_keep(monkeypatch, capsys, keep): from mobilerun.core.mailbox import cloud - mailbox = cloud.CloudMailbox("box-1", billing="paid") - mailbox._address = "test@example.com" - fetch = AsyncMock(return_value="1234") - monkeypatch.setattr(cloud, "wait_for_code", fetch) - monkeypatch.setattr(mailbox_demo, "CloudMailbox", AsyncMock(return_value=mailbox)) - release = AsyncMock() - monkeypatch.setattr(mailbox, "release", release) + create = AsyncMock( + return_value=SimpleNamespace( + data=SimpleNamespace( + id="box-1", address="test@example.com", status="active" + ) + ) + ) + fetch = AsyncMock(return_value=SimpleNamespace(data=SimpleNamespace(code="1234"))) + delete = AsyncMock() + monkeypatch.setattr(cloud.Mailboxes, "create", create) + monkeypatch.setattr(cloud.Mailboxes, "otp", fetch) + monkeypatch.setattr(cloud.Mailboxes, "delete", delete) asyncio.run( mailbox_demo.main( - Namespace(payment_timeout=600, yes=True, keep=False, timeout=1) + Namespace(payment_timeout=600, yes=True, keep=keep, timeout=1) ) ) fetch.assert_awaited_once() - release.assert_awaited_once() + assert "Received code: 1234" in capsys.readouterr().out + if keep: + delete.assert_not_awaited() + else: + delete.assert_awaited_once_with("box-1") def test_included_uses_quota_and_passes_billing(monkeypatch): @@ -149,7 +141,7 @@ def test_included_uses_quota_and_passes_billing(monkeypatch): id="box", address="example", wait_for_code=AsyncMock(return_value="1234"), - release=AsyncMock(), + close=AsyncMock(), ) create = AsyncMock(return_value=mailbox) monkeypatch.setattr(mailbox_demo, "CloudMailbox", create) @@ -177,6 +169,7 @@ def phone_args(**kwargs): country=kwargs.get("country", None), keep=kwargs.get("keep", False), bind=kwargs.get("bind", False), + number_id=kwargs.get("number_id"), timeout=30, ) @@ -188,15 +181,58 @@ def phone_setup(monkeypatch): phone_number="+15555550100", wait_ready=AsyncMock(), wait_for_code=AsyncMock(return_value="123456"), - bind=AsyncMock(), - unbind=AsyncMock(), + attach=AsyncMock(), + detach=AsyncMock(), + close=AsyncMock(), release=AsyncMock(), + resumed_existing=False, ) create = AsyncMock(return_value=number) monkeypatch.setattr(phone_demo, "CloudPhoneNumber", create) return number, create +def test_supplied_number_is_closed_not_released(phone_setup, capsys): + number, create = phone_setup + asyncio.run(phone_demo.main(phone_args(number_id="number-1"))) + create.assert_awaited_once_with(number_id="number-1", billing="paid") + number.close.assert_awaited_once() + number.release.assert_not_awaited() + assert "Preserved existing number number-1" in capsys.readouterr().out + + +def test_empty_number_id_does_not_rent_number(phone_setup): + _, create = phone_setup + with pytest.raises(ValueError, match="--number-id"): + asyncio.run(phone_demo.main(phone_args(number_id=""))) + create.assert_not_called() + + +def test_borrowed_number_waits_without_deleting(monkeypatch, capsys): + from mobilerun.core.phone_number import cloud + + read = AsyncMock( + return_value=SimpleNamespace( + data=SimpleNamespace( + state="active", + phone_number="+15555550100", + device_binding=None, + checkout_url=None, + ) + ) + ) + delete = AsyncMock() + monkeypatch.setattr(cloud.Numbers, "retrieve", read) + monkeypatch.setattr(cloud.Numbers, "delete", delete) + monkeypatch.setattr( + cloud.CloudPhoneNumber, "wait_for_code", AsyncMock(return_value="1234") + ) + asyncio.run(phone_demo.main(phone_args(number_id="number-1", yes=False))) + assert "Received code: 1234" in capsys.readouterr().out + read.assert_awaited() + delete.assert_not_awaited() + + def test_happy_path(phone_setup, capsys): number, create = phone_setup asyncio.run(phone_demo.main(phone_args())) @@ -205,7 +241,7 @@ def test_happy_path(phone_setup, capsys): ) number.wait_ready.assert_awaited_once() number.wait_for_code.assert_awaited_once_with(timeout=30) - number.release.assert_awaited_once() + number.close.assert_awaited_once() assert "Send an SMS with a code to +15555550100" in capsys.readouterr().out @@ -233,7 +269,7 @@ def test_timeout_releases_number(phone_setup): number.wait_for_code.side_effect = TimeoutError with pytest.raises(TimeoutError): asyncio.run(phone_demo.main(phone_args())) - number.release.assert_awaited_once() + number.close.assert_awaited_once() def test_keep_does_not_release_phone(phone_setup, capsys): @@ -242,64 +278,70 @@ def test_keep_does_not_release_phone(phone_setup, capsys): create.assert_awaited_once_with( country="DE", billing="paid", checkout="print", keep=True ) - number.release.assert_not_awaited() + number.close.assert_awaited_once() assert "Kept number" in capsys.readouterr().out -def test_bind_unbinds_before_phone_closes(phone_setup, monkeypatch, capsys): - number, _ = phone_setup - events = [] - phone = SimpleNamespace(number=number, sms=number, device_id="phone") - - async def unbind(): - events.append("unbind") - - number.unbind.side_effect = unbind - - class Phone: - def __init__(self, **kwargs): - assert kwargs == {"billing": "paid", "plan": None} - - async def __aenter__(self): - return phone - - async def __aexit__(self, *args): - events.append("close") - - monkeypatch.setattr(phone_demo, "CloudDevice", Phone) - asyncio.run(phone_demo.main(phone_args(bind=True))) - number.bind.assert_awaited_once_with(phone) - assert events == ["unbind", "close"] - number.release.assert_awaited_once() - assert "phone.number" in capsys.readouterr().out +@pytest.fixture +def phone_device(monkeypatch): + driver = FakeDriver(device_id="phone") + phone = fake_device(driver=driver) + run = SimpleNamespace(create_cloud=AsyncMock(return_value=phone)) + closed = AsyncMock(wraps=phone.aclose) + monkeypatch.setattr(phone, "aclose", closed) + + @asynccontextmanager + async def open_client(**kwargs): + assert kwargs["cloud"] is True + assert await kwargs["hitl_gate"]("device.create_cloud", {}) is True + async with phone: + yield run + + monkeypatch.setattr(phone_demo, "open_client", open_client, raising=False) + monkeypatch.setattr( + phone_demo, + "select_phone_proxy", + AsyncMock(return_value=ConnectProxyRef("existing-proxy")), + raising=False, + ) + return phone, closed, run -def test_bind_timeout_unbinds_before_phone_closes(phone_setup, monkeypatch): +@pytest.mark.parametrize("timeout", [False, True]) +def test_detaches_before_phone_closes(phone_setup, phone_device, timeout): number, _ = phone_setup - events = [] - phone = SimpleNamespace(number=number, sms=number, device_id="phone") - number.wait_for_code.side_effect = TimeoutError - - async def unbind(): - events.append("unbind") + phone, closed, run = phone_device - number.unbind.side_effect = unbind + async def detach(): + closed.assert_not_awaited() - class Phone: - def __init__(self, **kwargs): - pass + number.detach.side_effect = detach + if timeout: + number.wait_for_code.side_effect = TimeoutError + with pytest.raises(TimeoutError): + asyncio.run(phone_demo.main(phone_args(bind=True))) + else: + asyncio.run(phone_demo.main(phone_args(bind=True))) + assert run.create_cloud.await_count == 1 + assert run.create_cloud.await_args.kwargs["plan"] == "minute" + assert run.create_cloud.await_args.kwargs["proxy"] == ConnectProxyRef( + "existing-proxy" + ) + number.attach.assert_awaited_once_with(phone) + number.detach.assert_awaited_once() + closed.assert_awaited_once() + number.close.assert_awaited_once() - async def __aenter__(self): - return phone - async def __aexit__(self, *args): - events.append("close") +def test_attachment_conflict_never_detaches_borrowed_link(phone_setup, phone_device): + from mobilerun.errors.cloud import NumberAttachmentConflict - monkeypatch.setattr(phone_demo, "CloudDevice", Phone) - with pytest.raises(TimeoutError): - asyncio.run(phone_demo.main(phone_args(bind=True))) - assert events == ["unbind", "close"] - number.release.assert_awaited_once() + number, _ = phone_setup + number.attach.side_effect = NumberAttachmentConflict(operation="Attach", status=409) + with pytest.raises(NumberAttachmentConflict): + asyncio.run(phone_demo.main(phone_args(bind=True, number_id="number-1"))) + number.detach.assert_not_awaited() + number.close.assert_awaited_once() def test_readiness_failure_releases_number(phone_setup): @@ -308,7 +350,7 @@ def test_readiness_failure_releases_number(phone_setup): with pytest.raises(TimeoutError): asyncio.run(phone_demo.main(phone_args())) number.wait_for_code.assert_not_awaited() - number.release.assert_awaited_once() + number.close.assert_awaited_once() def test_included_billing_is_used_for_number(phone_setup, capsys): @@ -321,32 +363,14 @@ def test_included_billing_is_used_for_number(phone_setup, capsys): assert "Billing: included" in capsys.readouterr().out -def test_included_binding_uses_subscription_and_quota_warning( - phone_setup, monkeypatch, capsys -): - number, _ = phone_setup - options = phone_args(bind=True, yes=False) +def test_included_attachment_refuses_unterminable_phone(phone_setup): + _, create = phone_setup + options = phone_args(bind=True) options.billing = "included" options.plan = "subscription" - prompts = [] - monkeypatch.setattr("builtins.input", lambda text: prompts.append(text) or "y") - phone = SimpleNamespace(number=number, sms=number, device_id="phone") - - class Phone: - def __init__(self, **kwargs): - assert kwargs == {"billing": "included", "plan": "subscription"} - - async def __aenter__(self): - return phone - - async def __aexit__(self, *unused): - pass - - monkeypatch.setattr(phone_demo, "CloudDevice", Phone) - asyncio.run(phone_demo.main(options)) - assert "included quota only (no charges)" in prompts[0] - assert "paid" not in prompts[0].lower() - assert "phone plan: subscription" in capsys.readouterr().out + with pytest.raises(ValueError, match="temporary.*minute"): + asyncio.run(phone_demo.main(options)) + create.assert_not_called() def test_included_minute_rejected_before_purchase(phone_setup): @@ -381,135 +405,200 @@ def test_phone_plan_cli_alias(monkeypatch, flag): @pytest.fixture def proxy_setup(monkeypatch): + from mobilerun.models.proxy import ProxyProduct + phone = SimpleNamespace( - proxy_status=AsyncMock( - return_value=SimpleNamespace(connected=True, name="old") - ), - set_proxy=AsyncMock(return_value=SimpleNamespace(connected=True, name="new")), - close=AsyncMock(), - stop=AsyncMock(), - terminate=AsyncMock(), + proxy_status=AsyncMock(return_value=ProxyStatus(True, "socks5", "old-id")), + set_proxy=AsyncMock(), + aclose=AsyncMock(), ) - phone.proxy = SimpleNamespace(status=phone.proxy_status) - monkeypatch.setattr( - proxy_demo.proxies, - "device_status", - AsyncMock(side_effect=AssertionError("bypass")), + run = SimpleNamespace( + connect=AsyncMock(return_value=phone), + list_cloud_devices=AsyncMock( + return_value=[SimpleNamespace(name="tester1", device_id="phone")] + ), ) - async def bind(proxy, device, **kwargs): - assert kwargs == {"force": True} - await device.set_proxy(proxy) - device.proxy = proxy - return proxy - - monkeypatch.setattr(proxy_demo.Proxy, "bind", bind) + @asynccontextmanager + async def open_client(*, cloud, hitl_gate): + assert cloud is True + try: + yield run + finally: + if run.connect.await_count: + await phone.aclose() + + items = [ + ProxyProduct( + ConnectProxyRef("old-id"), "old", "US", "active", "residential", None + ), + ProxyProduct( + ConnectProxyRef("new-id"), "new", "DE", "active", "residential", None + ), + ] - async def status(proxy): - return SimpleNamespace(connected=True, name="new") + async def list_connect_proxies(*, billing): + assert billing == "no_commerce" + for item in items: + yield item - monkeypatch.setattr(proxy_demo.Proxy, "status", status) - device = AsyncMock(return_value=phone) - monkeypatch.setattr(proxy_demo, "CloudDevice", device) - monkeypatch.setattr( - proxy_demo.devices, - "list_devices", - AsyncMock(return_value=[SimpleNamespace(name="tester1", id="phone")]), - ) + monkeypatch.setattr(proxy_demo, "open_client", open_client, raising=False) monkeypatch.setattr( - proxy_demo.proxies, - "list_proxies", - AsyncMock( - return_value=SimpleNamespace( - items=[ - SimpleNamespace( - id="old-id", name="old", country="US", status="active" - ), - SimpleNamespace( - id="new-id", name="new", country="DE", status="active" - ), - ], - pagination=SimpleNamespace(has_next=False), - ) - ), + proxy_demo, "list_connect_proxies", list_connect_proxies, raising=False ) - return phone, device + return phone, run, items def run_proxy_demo(*args): - return asyncio.run(proxy_demo.main(list(args))) + target = [] if "--name" in args else ["--name", "tester1"] + return asyncio.run(proxy_demo.main(["--live", *target, *args])) def test_selects_different_existing_proxy_and_closes_without_stopping( proxy_setup, capsys ): - phone, device = proxy_setup - assert run_proxy_demo() == 0 - device.assert_awaited_once_with(device_id="phone", billing=proxy_demo.Billing.PAID) - assert phone.set_proxy.await_args.args[0].id == "new-id" - phone.close.assert_awaited_once() - phone.stop.assert_not_awaited() - phone.terminate.assert_not_awaited() + phone, run, _ = proxy_setup + assert run_proxy_demo("--yes") == 0 + run.connect.assert_awaited_once_with("phone", backend="cloud") + phone.set_proxy.assert_awaited_once_with(ConnectProxyRef("new-id"), replace=True) + phone.aclose.assert_awaited_once() assert "old" in capsys.readouterr().out def test_missing_phone_lists_names(proxy_setup, capsys): assert run_proxy_demo("--name", "missing") == 1 assert "tester1" in capsys.readouterr().err - proxy_setup[1].assert_not_awaited() + proxy_setup[1].connect.assert_not_awaited() def test_explicit_proxy_id(proxy_setup): - assert run_proxy_demo("--proxy-id", "new-id") == 0 + assert run_proxy_demo("--proxy-id", "new-id", "--yes") == 0 assert proxy_setup[0].set_proxy.await_args.args[0].id == "new-id" def test_no_alternative(proxy_setup, capsys): - cast(AsyncMock, proxy_demo.proxies.list_proxies).return_value.items.pop() + proxy_setup[2].pop() assert run_proxy_demo() == 1 assert "alternative" in capsys.readouterr().err.lower() proxy_setup[0].set_proxy.assert_not_awaited() - proxy_setup[0].close.assert_awaited_once() + proxy_setup[0].aclose.assert_awaited_once() def test_country_decline_never_switches(proxy_setup, monkeypatch): monkeypatch.setattr("builtins.input", lambda _: "n") assert run_proxy_demo("--country", "DE") == 1 - proxy_setup[1].assert_not_awaited() + proxy_setup[1].list_cloud_devices.assert_not_awaited() -def test_country_yes_uses_paid(proxy_setup): +def test_country_reuses_existing_without_purchase(proxy_setup, monkeypatch): + purchase = AsyncMock(side_effect=AssertionError("should reuse existing proxy")) + monkeypatch.setattr(proxy_demo.CloudRotatingProxy, "purchase", purchase) assert run_proxy_demo("--country", "DE", "--yes") == 0 - proxy_setup[1].assert_awaited_once_with( - device_id="phone", billing=proxy_demo.Billing.PAID + proxy_setup[0].set_proxy.assert_awaited_once_with( + ConnectProxyRef("new-id"), replace=True ) - assert proxy_setup[0].set_proxy.await_args.args[0].country == "DE" + purchase.assert_not_awaited() + + +def test_country_purchase_restores_existing_proxy_before_releasing( + proxy_setup, monkeypatch +): + from unittest.mock import call + + phone, _, items = proxy_setup + items.pop() + proxy = proxy_demo.CloudRotatingProxy(ConnectProxyRef("temporary-id"), device=phone) + purchase = AsyncMock(return_value=proxy) + monkeypatch.setattr(proxy_demo.CloudRotatingProxy, "purchase", purchase) + phone.proxy_status.side_effect = [ + ProxyStatus(True, "socks5", "old-id"), + ProxyStatus(True, "socks5", "temporary-id"), + ] + + async def close(): + assert phone.set_proxy.await_args_list == [ + call(ConnectProxyRef("temporary-id"), replace=True), + call(ConnectProxyRef("old-id"), replace=True), + ] + + monkeypatch.setattr(proxy, "close", AsyncMock(side_effect=close)) + assert run_proxy_demo("--country", "DE", "--yes") == 0 + assert purchase.await_args.kwargs["billing"] == "paid" + proxy.close.assert_awaited_once() + + +def test_country_purchase_is_not_released_when_restore_fails( + proxy_setup, monkeypatch, capsys +): + phone, _, items = proxy_setup + items.pop() + proxy = proxy_demo.CloudRotatingProxy(ConnectProxyRef("temporary-id"), device=phone) + monkeypatch.setattr( + proxy_demo.CloudRotatingProxy, "purchase", AsyncMock(return_value=proxy) + ) + close = AsyncMock() + monkeypatch.setattr(proxy, "close", close) + phone.proxy_status.side_effect = [ + ProxyStatus(True, "socks5", "old-id"), + ProxyStatus(True, "socks5", "temporary-id"), + ] + phone.set_proxy.side_effect = [None, ProxyOperationError("restore failed")] + assert run_proxy_demo("--country", "DE", "--yes") == 1 + close.assert_not_awaited() + assert "release purchased proxy temporary-id if unused" in capsys.readouterr().err def test_unknown_current_proxy_fails_safely(proxy_setup, capsys): - proxy_setup[0].proxy_status.return_value.name = None + proxy_setup[0].proxy_status.return_value = ProxyStatus(True, "socks5", None) assert run_proxy_demo() == 1 assert "identify" in capsys.readouterr().err.lower() proxy_setup[0].set_proxy.assert_not_awaited() -def test_proxy_not_active_reports_error_and_closes(proxy_setup, capsys): - proxy_setup[0].set_proxy.side_effect = proxy_demo.ProxyNotActive("disconnected") +def test_proxy_error_reports_failure_and_closes(proxy_setup, capsys): + proxy_setup[0].set_proxy.side_effect = ProxyOperationError("disconnected") assert run_proxy_demo() == 1 - assert "not active" in capsys.readouterr().err - proxy_setup[0].close.assert_awaited_once() + assert "Proxy switch failed" in capsys.readouterr().err + proxy_setup[0].aclose.assert_awaited_once() -def test_demo_creates_minute_phone_and_closes(monkeypatch, capsys): - proxy_status = AsyncMock(return_value=SimpleNamespace(connected=False)) - proxy = SimpleNamespace(country="US", status=proxy_status) - monkeypatch.setattr(task_demo, "CloudRotatingProxy", lambda **kwargs: proxy) - phone = SimpleNamespace( - device_id="phone", - proxy=SimpleNamespace( - status=AsyncMock(side_effect=AssertionError("Use proxy handle")) - ), - info=AsyncMock(return_value=SimpleNamespace()), +def test_task_demo_creates_minute_phone_and_closes(monkeypatch, capsys): + events = [] + driver = FakeDriver(device_id="phone") + phone = fake_device(driver=driver) + proxy_status = AsyncMock(return_value=ProxyStatus(False, None, None)) + monkeypatch.setattr(phone, "proxy_status", proxy_status) + proxy = SimpleNamespace( + as_device_proxy=lambda: ConnectProxyRef("task-proxy"), + close=AsyncMock(side_effect=lambda: events.append("proxy")), + ) + monkeypatch.setattr( + task_demo.CloudRotatingProxy, "select", AsyncMock(return_value=proxy) + ) + phone_create = AsyncMock(return_value=phone) + run = SimpleNamespace(create_cloud=phone_create) + client = object() + + @asynccontextmanager + async def core_client(**kwargs): + yield run + + @asynccontextmanager + async def account_client(*, billing): + assert billing == "paid" + yield client + + monkeypatch.setattr(task_demo, "AsyncMobilerun", core_client) + monkeypatch.setattr(task_demo, "cloud_client", account_client) + monkeypatch.setattr(task_demo.LoginStore, "resolve_api_key", lambda self: None) + close = phone.aclose + + async def close_phone(): + events.append("phone") + await close() + + monkeypatch.setattr(phone, "aclose", close_phone) + operator = SimpleNamespace( do=AsyncMock( side_effect=[ SimpleNamespace(task_id="open"), @@ -522,32 +611,22 @@ def test_demo_creates_minute_phone_and_closes(monkeypatch, capsys): expect=AsyncMock( return_value=SimpleNamespace(task=SimpleNamespace(task_id="expect")) ), - press_button=AsyncMock(), ) - class Device: - def __init__(self, **kwargs): - proxy = kwargs.pop("proxy") - assert proxy is not None and proxy.country == "US" - assert kwargs == { - "name": "cloud-phone-demo", - "billing": "paid", - "plan": None, - } - - async def __aenter__(self): - return phone - - async def __aexit__(self, *args): - phone.closed = True + def make_operator(*, client, billing): + assert billing == "paid" + return operator - monkeypatch.setattr(task_demo, "CloudDevice", Device) + monkeypatch.setattr(task_demo, "CloudTaskOperator", make_operator) asyncio.run(task_demo.main(yes=True)) - assert phone.closed - phone.info.assert_not_awaited() + assert phone_create.await_args.kwargs["name"] == "cloud-phone-demo" + assert phone_create.await_args.kwargs["plan"] == "minute" + assert phone_create.await_args.kwargs["proxy"] == ConnectProxyRef("task-proxy") + assert events == ["phone", "proxy"] proxy_status.assert_awaited_once() - phone.press_button.assert_awaited_once_with("home") - assert phone.do.await_count == 3 + assert ("press_button", ("home",), {}) in driver.calls + assert operator.do.await_count == 3 + assert operator.do.await_args.args[0] is phone assert "15" in capsys.readouterr().out @@ -555,37 +634,37 @@ def test_task_demo_decline_does_not_create(monkeypatch): from unittest.mock import Mock create = Mock() - monkeypatch.setattr(task_demo, "CloudDevice", create) + monkeypatch.setattr(task_demo.CloudRotatingProxy, "select", create) monkeypatch.setattr("builtins.input", lambda _: "n") asyncio.run(task_demo.main(yes=False)) create.assert_not_called() -def test_included_plan_passed_to_phone_and_warns(monkeypatch): +def test_task_demo_included_subscription_rejected_before_creation(monkeypatch): from mobilerun.models import Billing - calls = [] - prompts = [] - monkeypatch.setattr("builtins.input", lambda text: prompts.append(text) or "y") - - def phone(**kwargs): - calls.append(kwargs) - raise RuntimeError("stop before creation") - - monkeypatch.setattr(task_demo, "CloudDevice", phone) - with pytest.raises(RuntimeError, match="stop before creation"): + create = AsyncMock() + monkeypatch.setattr(task_demo.CloudRotatingProxy, "select", create) + with pytest.raises(ValueError, match="temporary.*minute"): asyncio.run(task_demo.main(billing=Billing.INCLUDED, plan="subscription")) - assert calls[0]["billing"] == "included" - assert calls[0]["plan"] == "subscription" - assert "included quota only (no charges)" in prompts[0] - assert "paid" not in prompts[0].lower() + create.assert_not_called() def test_included_minute_is_rejected_before_creation(monkeypatch): from mobilerun.models import Billing create = AsyncMock() - monkeypatch.setattr(task_demo, "CloudDevice", create) + monkeypatch.setattr(task_demo.CloudRotatingProxy, "select", create) with pytest.raises(ValueError, match="subscription"): asyncio.run(task_demo.main(yes=True, billing=Billing.INCLUDED, plan="minute")) create.assert_not_called() + + +def test_static_webhook_returns_result_without_a_device(): + from tests.demos import webhook_static_demo + + assert webhook_static_demo.main(webhook_static_demo.Input()).model_dump() == { + "message": "hello from mobilerun", + "source": "webhook-static-demo", + "ok": True, + } diff --git a/tests/unit/errors/test_errors.py b/tests/unit/errors/test_errors.py index ce5625be2..cf6329849 100644 --- a/tests/unit/errors/test_errors.py +++ b/tests/unit/errors/test_errors.py @@ -3,8 +3,6 @@ import ast import asyncio import importlib -import logging -import traceback from types import SimpleNamespace from unittest.mock import AsyncMock @@ -13,15 +11,12 @@ from mobilerun_sdk import APIStatusError from mobilerun.clients.cloud import mailboxes, numbers -from mobilerun.clients.portal.state_fetch import fetch_state_with_retry -from mobilerun.core.extensions import Extension, action from mobilerun.errors import ( BillingError, CloudConflict, CloudServiceUnavailable, + CredentialFieldNotFound, ExpectationInconclusive, - ExtensionActionError, - StateFetchFailed, ) from mobilerun.errors.base import CloudError, DeviceError, MobilerunError, is_value_safe from mobilerun.models.billing import Billing @@ -33,65 +28,34 @@ [ ("mobilerun.errors.credentials", "CredentialNotFoundError"), ("mobilerun.errors.device", "DeviceAuthError"), - ("mobilerun.errors.device", "DeviceNotFound"), - ( - "mobilerun.errors.device", - "DeviceOperationNotSupported", - ), ("mobilerun.errors.operators", "ExpectationFailed"), ("mobilerun.errors.cloud", "InvalidAPIKeyError"), - ( - "mobilerun.errors.credentials", - "LocalCredentialsNotAllowed", - ), ("mobilerun.errors.operators", "OperatorNotAvailable"), ("mobilerun.errors.operators", "OperatorNotSupported"), - ("mobilerun.errors.device", "PortalApkNotFound"), - ("mobilerun.errors.device", "PortalInstallFailed"), - ("mobilerun.errors.device", "UnsupportedStateCapability"), - ("mobilerun.errors.device", "StateFetchFailed"), ("mobilerun.macro.errors", "MacroMismatch"), - ("mobilerun.config.loader", "OutdatedConfigError"), + ("mobilerun.errors.config", "OutdatedConfigError"), ], ) def test_errors_share_root(module, name): assert issubclass(getattr(importlib.import_module(module), name), MobilerunError) -def test_new_error_types_keep_builtin_compatibility(): - from mobilerun.errors import CredentialFormatError, DeviceNotReady, PlaceholderError - - assert issubclass(CredentialFormatError, ValueError) - assert issubclass(DeviceNotReady, RuntimeError) - assert issubclass(PlaceholderError, ValueError) - - def test_invalid_values_raise_typed_errors(): - from mobilerun.core.credentials.base import normalize - from mobilerun.core.state.view import UIStateView - from mobilerun.errors import CredentialFormatError, DeviceNotReady + from mobilerun.errors import CredentialFormatError + from mobilerun.models.credentials import Credential + assert issubclass(CredentialFormatError, ValueError) with pytest.raises(CredentialFormatError): - normalize({"app": 123}) - with pytest.raises(DeviceNotReady): - _ = UIStateView(None).current + Credential.from_mapping({"app": 123}) def test_error_classes_discovered_by_ast_share_root(): root = REPO_ROOT / "mobilerun" named_errors = { - "DeviceNotFound", - "DeviceNotReady", - "DeviceOperationNotSupported", "ExpectationFailed", "ExpectationInconclusive", - "LocalCredentialsNotAllowed", "OperatorNotAvailable", "OperatorNotSupported", - "PortalApkNotFound", - "PortalInstallFailed", - "StateFetchFailed", - "UnsupportedStateCapability", "MacroMismatch", "SandboxNotImplemented", } @@ -119,38 +83,16 @@ def test_inconclusive_verdict_keeps_sensitive_details_out_of_message(): assert isinstance(error, DeviceError) -def test_portal_error_does_not_expose_device_state(caplog): - async def fetch(): - return {"error": "secret-error", "phone_state": "secret-state"} - - with pytest.raises(StateFetchFailed) as caught: - asyncio.run(fetch_state_with_retry(fetch, max_retries=1, retry_delays=[0])) - assert "secret" not in str(caught.value) - assert "secret" not in caplog.text +def test_free_text_cloud_error_is_not_value_safe(): + assert not is_value_safe(CloudServiceUnavailable("PRIVATE-CANARY")) -@pytest.mark.parametrize("level", [logging.INFO, logging.DEBUG]) -def test_sensitive_direct_free_text_cloud_error_is_wrapped(level, caplog): - caplog.set_level(level, logger="mobilerun") - canary = "PRIVATE-CANARY" +def test_value_safety_requires_a_framework_error_contract(): + assert is_value_safe(CredentialFieldNotFound("Credential field not found")) + assert not is_value_safe(RuntimeError("PRIVATE-CANARY")) - class Vault(Extension): - @action(sensitive_parameters=frozenset({"password"})) - async def login(self, password: str) -> None: - """Reject unsafe legacy cloud messages.""" - raise CloudServiceUnavailable(password) - with pytest.raises(ExtensionActionError) as caught: - asyncio.run(Vault().login(canary)) - assert caught.value.cause_type == "CloudServiceUnavailable" - assert caught.value.__cause__ is None - assert canary not in "".join(traceback.format_exception(caught.value)) - - -@pytest.mark.parametrize("level", [logging.INFO, logging.DEBUG]) -@pytest.mark.parametrize("sensitive", [False, True]) -def test_real_number_messages_wrapper_drops_unsafe_sdk_chain(level, sensitive, caplog): - caplog.set_level(level, logger="mobilerun") +def test_number_messages_renders_only_safe_sdk_diagnostics(): canary = "SDK-PRIVATE-CANARY" request = httpx.Request("GET", "https://example.invalid/numbers") response = httpx.Response( @@ -163,79 +105,21 @@ def test_real_number_messages_wrapper_drops_unsafe_sdk_chain(level, sensitive, c ) ) - class Inbox(Extension): - @action( - sensitive_parameters=frozenset({"password"}) if sensitive else frozenset() - ) - async def read(self, password: str) -> None: - """Read through the real SDK translation boundary.""" - await numbers.messages("number-id", billing=Billing.NO_COMMERCE, client=sdk) - with pytest.raises(CloudServiceUnavailable) as caught: - asyncio.run(Inbox().read(canary)) + asyncio.run( + numbers.Numbers(billing=Billing.NO_COMMERCE, client=sdk).messages( + "number-id" + ) + ) error = caught.value - assert error.value_safe + assert is_value_safe(error) assert error.status == 503 assert error.operation == "List SMS messages" - assert error.request_id == "support-id" - assert error.__cause__ is None - assert error.__context__ is None - assert canary not in "".join(traceback.format_exception(error)) + assert error.request_id is None and "support-id" not in str(error) + assert canary not in str(error) + repr(error) sdk.numbers.messages.list.assert_awaited_once() -@pytest.mark.parametrize("explicit", [False, True]) -@pytest.mark.parametrize("level", [logging.INFO, logging.DEBUG]) -def test_safe_chain_preserves_identity_metadata_and_only_safe_causes( - explicit, level, caplog -): - caplog.set_level(level, logger="mobilerun") - canary = "CHAIN-PRIVATE-CANARY" - unsafe = CloudError(canary) - safe_cause = CloudError(operation="List SMS messages", status=503) - safe_cause.__cause__ = unsafe - top = CloudServiceUnavailable(status=503, detail={"raw": canary}) - - class Resource(Extension): - @action(sensitive_parameters=frozenset({"password"})) - async def run(self, password: str) -> None: - """Retain the typed error, not backend contexts.""" - try: - raise safe_cause - except CloudError: - if explicit: - raise top from safe_cause - raise top # noqa: B904 -- exercise implicit SDK-style context. - - with pytest.raises(CloudServiceUnavailable) as caught: - asyncio.run(Resource().run(canary)) - assert caught.value is top - assert top.detail == {"raw": canary} - assert top.__context__ is None - assert top.__cause__ is (safe_cause if explicit else None) - if explicit: - assert safe_cause.__cause__ is None - assert safe_cause.__context__ is None - assert canary not in "".join(traceback.format_exception(top)) - - -def test_safe_cause_cycles_are_removed(): - top, cause = CloudError(), CloudError() - top.__cause__, cause.__cause__ = cause, top - - class Resource(Extension): - @action - async def run(self) -> None: - """Avoid retaining cyclic safe exception chains.""" - raise top - - with pytest.raises(CloudError) as caught: - asyncio.run(Resource().run()) - assert caught.value is top - assert top.__cause__ is cause - assert cause.__cause__ is None - - def test_typed_cloud_fields_do_not_render_arbitrary_labels_or_status(): canary = "FIELD-PRIVATE-CANARY" error = CloudError( @@ -268,35 +152,8 @@ def test_new_cloud_operation_labels_are_retained(operation): ) -@pytest.mark.parametrize("level", [logging.INFO, logging.DEBUG]) -@pytest.mark.parametrize("on_cause", [False, True]) -def test_safe_errors_drop_notes_on_every_retained_exception(level, on_cause, caplog): - caplog.set_level(level, logger="mobilerun") - canary = "NOTE-PRIVATE-CANARY" - top, cause = CloudServiceUnavailable(status=503), CloudError(status=503) - top.__cause__ = cause - - class Resource(Extension): - @action(sensitive_parameters=frozenset({"password"})) - async def run(self, password: str) -> None: - """Do not propagate provider notes as safe diagnostics.""" - (cause if on_cause else top).add_note(password) - raise top - - with pytest.raises(CloudServiceUnavailable) as caught: - asyncio.run(Resource().run(canary)) - assert caught.value is top - assert top.__cause__ is cause - assert not getattr(top, "__notes__", []) - assert not getattr(cause, "__notes__", []) - assert canary not in "".join(traceback.format_exception(top)) - - -@pytest.mark.parametrize("level", [logging.INFO, logging.DEBUG]) -@pytest.mark.parametrize("sensitive", [False, True]) @pytest.mark.parametrize("bypass", ["str", "repr", "init", "args", "opted_str"]) -def test_cloud_rendering_bypasses_are_wrapped(level, sensitive, bypass, caplog): - caplog.set_level(level, logger="mobilerun") +def test_cloud_rendering_bypasses_are_not_value_safe(bypass): canary = "RENDER-PRIVATE-CANARY" class CustomString(CloudServiceUnavailable): @@ -326,22 +183,10 @@ def __str__(self): }[bypass] original = error_type(status=503, detail=canary) - class Resource(Extension): - @action( - sensitive_parameters=frozenset({"password"}) if sensitive else frozenset() - ) - async def run(self, password: str) -> None: - """Reject mutable or unaudited error rendering.""" - if bypass == "args": - original.args = (password,) - raise original - - with pytest.raises(ExtensionActionError) as caught: - asyncio.run(Resource().run(canary)) - assert caught.value.__cause__ is None - assert canary not in "".join(traceback.format_exception(caught.value)) if bypass == "args": + original.args = (canary,) assert canary not in str(original) + assert not is_value_safe(original) def test_private_cloud_message_is_write_once(): @@ -358,7 +203,7 @@ def test_private_cloud_message_is_write_once(): @pytest.mark.parametrize( "contract", ["stock", "inherited", "explicit", "payment", "purchase"] ) -def test_audited_or_explicit_safe_rendering_retains_error_identity(contract): +def test_audited_or_explicit_safe_rendering_is_value_safe(contract): from mobilerun.errors import PaymentRequired, PurchaseInProgress from mobilerun.models.checkout import Checkout @@ -386,50 +231,10 @@ async def resume(timeout): "purchase": lambda: PurchaseInProgress("id", checkout), }[contract]() - class Resource(Extension): - @action - async def run(self) -> None: - """Keep audited renderers and explicit safe-rendering opt-ins.""" - raise original - - with pytest.raises(type(original)) as caught: - asyncio.run(Resource().run()) - assert caught.value is original - - -@pytest.mark.parametrize("level", [logging.INFO, logging.DEBUG]) -@pytest.mark.parametrize("bypass", ["str", "args"]) -def test_retained_cloud_causes_are_revalidated(level, bypass, caplog): - caplog.set_level(level, logger="mobilerun") - canary = "CAUSE-RENDER-PRIVATE-CANARY" - - class Custom(CloudServiceUnavailable): - def __str__(self): - return self.detail - - cause = Custom(status=503, detail=canary) if bypass == "str" else CloudError() - if bypass == "args": - cause.args = (canary,) - top = CloudServiceUnavailable(status=503) - top.__cause__ = cause - - class Resource(Extension): - @action(sensitive_parameters=frozenset({"password"})) - async def run(self, password: str) -> None: - """Drop a cause whose rendering contract no longer holds.""" - raise top - - with pytest.raises(CloudServiceUnavailable) as caught: - asyncio.run(Resource().run(canary)) - assert caught.value is top - assert top.__cause__ is None - assert canary not in "".join(traceback.format_exception(top)) + assert is_value_safe(original) -@pytest.mark.parametrize("level", [logging.INFO, logging.DEBUG]) -@pytest.mark.parametrize("as_cause", [False, True]) -def test_computed_hint_is_never_trusted(level, as_cause, caplog): - caplog.set_level(level, logger="mobilerun") +def test_computed_hint_is_never_trusted(): canary = "HINT-PRIVATE-CANARY" class ComputedHint(CloudServiceUnavailable): @@ -437,29 +242,9 @@ class ComputedHint(CloudServiceUnavailable): def _hint(self): return str(self.detail) - original = ComputedHint(status=503, detail=canary) - top = CloudServiceUnavailable(status=503) if as_cause else original - if as_cause: - top.__cause__ = original - - class Resource(Extension): - @action - async def run(self) -> None: - """Apply the allowlist to top-level errors and retained causes.""" - raise top - - if as_cause: - with pytest.raises(CloudServiceUnavailable) as caught: - asyncio.run(Resource().run()) - assert caught.value is top - else: - with pytest.raises(ExtensionActionError) as caught: - asyncio.run(Resource().run()) - assert caught.value.__cause__ is None - assert canary not in "".join(traceback.format_exception(caught.value)) + assert not is_value_safe(ComputedHint(status=503, detail=canary)) -@pytest.mark.parametrize("level", [logging.INFO, logging.DEBUG]) @pytest.mark.parametrize( "addition", [ @@ -475,9 +260,7 @@ async def run(self) -> None: "nested_behavior", ], ) -def test_extra_subclass_behavior_is_untrusted(level, addition, caplog): - caplog.set_level(level, logger="mobilerun") - +def test_extra_subclass_behavior_is_untrusted(addition): def extra(self): return "not-rendering-related" @@ -500,17 +283,7 @@ def __get__(self, instance, owner): "args": {"args": property(lambda self: (CloudError.__str__(self),))}, }[addition] custom = type("ExtraBehavior", (CloudServiceUnavailable,), attrs) - original = custom(status=503) - - class Resource(Extension): - @action - async def run(self) -> None: - """Unknown subclass behavior is not audited by inheritance.""" - raise original - - with pytest.raises(ExtensionActionError) as caught: - asyncio.run(Resource().run()) - assert caught.value.__cause__ is None + assert not is_value_safe(custom(status=503)) @pytest.mark.parametrize( @@ -523,19 +296,9 @@ async def run(self) -> None: {"__annotations__": {"retryable": bool}, "retryable": True}, ], ) -def test_plain_constant_subclasses_retain_identity(attrs): +def test_plain_constant_subclasses_are_value_safe(attrs): custom = type("ConstantData", (CloudServiceUnavailable,), attrs) - original = custom(status=503) - - class Resource(Extension): - @action - async def run(self) -> None: - """Constant class metadata does not add rendering behavior.""" - raise original - - with pytest.raises(custom) as caught: - asyncio.run(Resource().run()) - assert caught.value is original + assert is_value_safe(custom(status=503)) @pytest.mark.parametrize("parent_behavior", [False, True]) @@ -563,15 +326,7 @@ class StaticHint(CloudServiceUnavailable): original = StaticHint(status=503) assert "Wait for the service to recover." in str(original) - class Resource(Extension): - @action - async def run(self) -> None: - """Static allowlisted ClassVar data does not alter behavior.""" - raise original - - with pytest.raises(StaticHint) as caught: - asyncio.run(Resource().run()) - assert caught.value is original + assert is_value_safe(original) def test_mro_does_not_hide_behavior_after_the_cloud_base(): @@ -582,16 +337,7 @@ def unrelated(self): class Mixed(CloudServiceUnavailable, Behavior): pass - original = Mixed(status=503) - - class Resource(Extension): - @action - async def run(self) -> None: - """Inspect every unaudited MRO entry, including late mixins.""" - raise original - - with pytest.raises(ExtensionActionError): - asyncio.run(Resource().run()) + assert not is_value_safe(Mixed(status=503)) @pytest.mark.parametrize( @@ -609,13 +355,12 @@ def test_create_capacity_conflict(module, resource, plural, code): with pytest.raises( BillingError if code == "included_capacity_unavailable" else CloudConflict ) as caught: - asyncio.run( - module.create( - billing=Billing.PAID, - client=sdk, - **({"country": "US"} if resource == "numbers" else {}), + if module is numbers: + asyncio.run( + numbers.Numbers(billing=Billing.PAID, client=sdk).create(country="US") ) - ) + else: + asyncio.run(module.Mailboxes(billing=Billing.PAID, client=sdk).create()) assert is_value_safe(caught.value) if code == "included_capacity_unavailable": assert f"No included {plural} left" in str(caught.value) @@ -664,8 +409,8 @@ def test_capacity_country_from_client_never_renders_arbitrary_text(): sdk = SimpleNamespace(numbers=SimpleNamespace(create=AsyncMock(side_effect=error))) with pytest.raises(BillingError) as caught: asyncio.run( - numbers.create( - billing=Billing.INCLUDED, client=sdk, country="PRIVATE-COUNTRY" + numbers.Numbers(billing=Billing.INCLUDED, client=sdk).create( + country="PRIVATE-COUNTRY" ) ) assert is_value_safe(caught.value) diff --git a/tests/unit/extension_action_typing.py b/tests/unit/extension_action_typing.py index 5b15b7fd1..f230dda00 100644 --- a/tests/unit/extension_action_typing.py +++ b/tests/unit/extension_action_typing.py @@ -1,32 +1,21 @@ -"""Static Pyright fixture: injected Device is absent from caller signatures.""" +"""Static typing fixture: declaring tools preserves their Python signatures.""" from typing import assert_type -from mobilerun.core.devices import Device -from mobilerun.core.extensions import Extension, action, device_action +from mobilerun.core.extensions import Extension, function -class TypedActions(Extension): - @action - async def list(self, package: str) -> str: - """Read standalone metadata.""" +class TypedTools(Extension): + @function + async def list_packages(self, package: str) -> str: return package - @device_action - async def type_field(self, device: Device, package: str, field: str) -> None: - """Use the nonoptional injected device.""" - assert_type(device, Device) - await device.input_text(package + field) - - @device_action(public=False) - async def configured(self, device: Device, value: int = 1) -> int: - """Exercise configured decorator inference.""" - assert_type(device, Device) + @function(name="count") + async def configured(self, value: int = 1) -> int: return value -async def check_public_signatures(vault: TypedActions) -> None: - assert_type(await vault.list("pkg"), str) - assert_type(await vault.type_field("pkg", "username"), None) +async def check_public_signatures(vault: TypedTools) -> None: + assert_type(await vault.list_packages("pkg"), str) assert_type(await vault.configured(), int) - assert_type(await vault.configured(2), int) + assert_type(await vault.configured(value=2), int) diff --git a/tests/unit/harness/test_fake_device.py b/tests/unit/harness/test_fake_device.py new file mode 100644 index 000000000..be250f562 --- /dev/null +++ b/tests/unit/harness/test_fake_device.py @@ -0,0 +1,86 @@ +import pytest +from mobilerun_core import ActionCall, ActionEvent, AsyncDevice, UnsupportedOperation + +from tests.support import devices + + +@pytest.mark.anyio +async def test_fake_dispatches_native_actions_in_order() -> None: + driver = devices.FakeDriver() + async with devices.fake_device(driver=driver) as phone: + await phone.tap(10, 20) + await phone.type("example", clear=True) + await phone.key("home") + await phone.swipe(1, 2, 3, 4, ms=125) + await phone.start_app("example.app") + + assert [name for name, _, _ in driver.calls] == [ + "tap", + "input_text", + "press_button", + "swipe", + "start_app", + ] + assert driver.calls[0][1] == (10, 20) + assert driver.calls[1][2]["clear"] is True + assert driver.calls[3][2]["duration_ms"] == 125 + + +@pytest.mark.anyio +async def test_fake_scripts_observation_and_screenshot() -> None: + driver = devices.FakeDriver() + driver.ui_tree["phone_state"] = {"packageName": "scripted.app"} + async with devices.fake_device(driver=driver) as phone: + assert (await phone.observe(screenshot=True)).focused_app == "scripted.app" + assert await phone.screenshot_bytes() == driver.screenshot_bytes + + +@pytest.mark.anyio +async def test_fake_runs_core_action_hooks() -> None: + driver = devices.FakeDriver() + events: list[str] = [] + + async def before(device: AsyncDevice, call: ActionCall) -> None: + assert device is phone + assert not driver.calls + events.append(call.action.name) + + async def after(device: AsyncDevice, event: ActionEvent) -> None: + assert device is phone + assert driver.calls == [("tap", (1, 2), {})] + events.append(event.action.name) + + async with devices.fake_device(driver=driver) as phone: + async with phone.use_action_hooks(before=before, after=after): + await phone.tap(1, 2) + assert events == ["tap", "tap"] + + +@pytest.mark.anyio +async def test_fake_does_not_dispatch_unsupported_verb() -> None: + driver = devices.FakeDriver(supported=set()) + async with devices.fake_device(driver=driver) as phone: + with pytest.raises(UnsupportedOperation): + await phone.tap(1, 2) + assert driver.calls == [] + + +@pytest.mark.anyio +async def test_fake_scripts_apps_files_clipboard_and_failures() -> None: + failure = RuntimeError("scripted failure") + driver = devices.FakeDriver( + apps=[{"packageName": "example.app"}], + files={"/sdcard/example": b"content"}, + clipboard="initial", + failures={"tap": failure}, + ) + async with devices.fake_device(driver=driver) as phone: + assert len(await phone.list_apps()) == 1 + assert await phone.pull_file("/sdcard/example") == b"content" + with pytest.raises(RuntimeError, match="scripted failure"): + await phone.tap(1, 2) + + # Core does not expose a clipboard route for independent injected drivers. + assert await driver.get_clipboard() == "initial" + await driver.set_clipboard("updated") + assert await driver.get_clipboard() == "updated" diff --git a/tests/unit/harness/test_isolation.py b/tests/unit/harness/test_isolation.py index 1619899eb..f5789c6cb 100644 --- a/tests/unit/harness/test_isolation.py +++ b/tests/unit/harness/test_isolation.py @@ -1,21 +1,18 @@ """Isolation and offline safety contracts for the pytest harness.""" -import asyncio import os import subprocess import sys -from contextlib import nullcontext +from contextlib import asynccontextmanager from pathlib import Path from types import SimpleNamespace as NS from unittest.mock import AsyncMock import platformdirs import pytest +from mobilerun_core import ConnectProxyRef, DeviceDescriptor -from mobilerun.clients.cloud import devices from mobilerun.config.settings import get_settings -from mobilerun.core.devices import CloudDevice -from mobilerun.models import Billing, Plan from tests.support import smoke_phone from tests.support.paths import REPO_ROOT @@ -25,7 +22,7 @@ def test_user_paths_are_isolated(tmp_path): - from mobilerun.clients.local.login_store import credential_path + from mobilerun.clients.local.login_store import LoginStore from mobilerun.config.loader import ConfigLoader settings = get_settings() @@ -33,7 +30,7 @@ def test_user_paths_are_isolated(tmp_path): for path in ( settings.MOBILERUN_USER_CONFIG_DIR, ConfigLoader.get_user_config_path(), - credential_path(), + LoginStore.from_settings().path, ): assert path.is_relative_to(tmp_path) @@ -243,90 +240,112 @@ def test_smoke_apk_defaults_to_user_cache_and_respects_override(monkeypatch, tmp assert get_settings().MOBILERUN_SMOKE_APK == override -def phone(id, name=NAME, billing="minute"): - return NS(id=id, name=name, billing_strategy=billing) +PROXY = ConnectProxyRef(id="existing-proxy") @pytest.fixture -def inventory(monkeypatch): - listed, terminate = AsyncMock(), AsyncMock() - monkeypatch.setattr(devices, "list_devices", listed) - monkeypatch.setattr(devices, "terminate", terminate) - monkeypatch.setattr(smoke_phone, "cloud_client", lambda **kw: nullcontext(None)) - monkeypatch.setattr(smoke_phone.asyncio, "sleep", AsyncMock()) - return listed, terminate - - -def lost_phone(): - return NS(cloud_id=None, name=None, close=AsyncMock()) - - -def test_single_exact_minute_match_terminated_and_verified(inventory): - listed, terminate = inventory - other = phone("other", NAME + "-other") - listed.side_effect = [[other], [other, phone("owned")], [other]] - asyncio.run(smoke_phone.close_smoke_phone(lost_phone(), NAME)) - terminate.assert_awaited_once_with("owned", billing=Billing.INCLUDED, client=None) - assert listed.await_count == 3 - - -@pytest.mark.parametrize( - "matches", - [ - [phone("one"), phone("two")], - [phone("one"), phone("two", billing="subscription")], - [phone("subscription-id", billing="subscription")], - ], -) -def test_unsafe_matches_never_deleted(inventory, matches): - listed, terminate = inventory - listed.return_value = matches - with pytest.raises(AssertionError) as caught: - asyncio.run(smoke_phone.close_smoke_phone(lost_phone(), NAME)) - assert NAME in str(caught.value) - assert all(item.id in str(caught.value) for item in matches) - terminate.assert_not_awaited() - - -def test_readiness_failure_rolled_back_without_scanning(monkeypatch, inventory): - listed, terminate = inventory - failure = TimeoutError("readiness failed") - monkeypatch.setattr(devices, "create", AsyncMock(return_value=phone("owned"))) - monkeypatch.setattr(devices, "wait_ready", AsyncMock(side_effect=failure)) - - async def exercise(): - device = CloudDevice( - api_key="fake", billing=Billing.PAID, plan=Plan.MINUTE, name=NAME +def phone_run(): + # Factory fakes model the public lease contract. A second phone + # with the same name makes name-based deletion/verification observable. + inventory = { + "borrowed": DeviceDescriptor("borrowed", "cloud", name=NAME, state="ready") + } + + @asynccontextmanager + async def borrowed_lease(device_id): + yield NS(device_id=device_id) + + async def create_cloud(**kwargs): + inventory["owned"] = DeviceDescriptor( + "owned", "cloud", name=NAME, state="ready" ) - try: - await device - finally: - await smoke_phone.close_smoke_phone(device, NAME) - with pytest.raises(TimeoutError) as caught: - asyncio.run(exercise()) - assert caught.value is failure and not getattr(failure, "__notes__", []) - listed.assert_not_awaited() - terminate.assert_awaited_once() + async def close_owned(): + del inventory["owned"] + return NS(device_id="owned", aclose=close_owned) + + async def list_cloud_devices(): + return list(inventory.values()) + + return NS( + connect=AsyncMock(return_value=borrowed_lease("borrowed")), + create_cloud=AsyncMock(side_effect=create_cloud), + list_cloud_devices=AsyncMock(side_effect=list_cloud_devices), + ) -def test_missing_phone_preserves_create_failure_with_unresolved_note(inventory): - listed, terminate = inventory - listed.return_value = [] - failure = TimeoutError("create response lost") - async def exercise(): - try: +@pytest.mark.anyio +async def test_smoke_phone_borrows_id_without_creating_or_cleaning_up(phone_run): + async with smoke_phone.open_smoke_phone(phone_run, device_id="borrowed") as phone: + assert phone.device_id == "borrowed" + phone_run.connect.assert_awaited_once_with("borrowed", backend="cloud") + phone_run.create_cloud.assert_not_awaited() + phone_run.list_cloud_devices.assert_not_awaited() + + +@pytest.mark.anyio +async def test_smoke_phone_checks_owned_id_after_body_failure(phone_run, monkeypatch): + monkeypatch.setenv("MOBILERUN_BILLING", "no_commerce") + failure = RuntimeError("smoke body failed") + with pytest.raises(RuntimeError) as caught: + async with smoke_phone.open_smoke_phone( + phone_run, name=NAME, proxy=PROXY + ) as phone: + assert phone.device_id == "owned" raise failure - finally: - await smoke_phone.close_smoke_phone(lost_phone(), NAME) + assert caught.value is failure + phone_run.create_cloud.assert_awaited_once() + arguments = phone_run.create_cloud.await_args.kwargs + assert arguments["name"] == NAME + assert arguments["proxy"] == PROXY + assert arguments["plan"] == "minute" and arguments["keep"] is False + phone_run.connect.assert_not_awaited() + phone_run.list_cloud_devices.assert_awaited_once() + assert [item.device_id for item in await phone_run.list_cloud_devices()] == [ + "borrowed" + ] + + +@pytest.mark.anyio +async def test_smoke_phone_reports_owned_id_still_in_inventory(phone_run, monkeypatch): + monkeypatch.setattr(smoke_phone, "_VERIFY_TIMEOUT_S", 0.01) + phone_run.list_cloud_devices.side_effect = None + phone_run.list_cloud_devices.return_value = [ + DeviceDescriptor("owned", "cloud", state="ready") + ] + with pytest.raises(AssertionError, match="owned"): + async with smoke_phone.open_smoke_phone(phone_run, name=NAME, proxy=PROXY): + pass + +@pytest.mark.anyio +async def test_smoke_phone_reports_lease_cleanup_failure(phone_run): + failure = RuntimeError("lease cleanup failed") + + async def failed_cleanup(): + raise failure + + phone_run.create_cloud.side_effect = None + phone_run.create_cloud.return_value = NS(device_id="owned", aclose=failed_cleanup) + with pytest.raises(RuntimeError) as caught: + async with smoke_phone.open_smoke_phone(phone_run, name=NAME, proxy=PROXY): + pass + assert caught.value is failure + assert any("owned" in note for note in failure.__notes__) + + +@pytest.mark.anyio +async def test_smoke_phone_preserves_unknown_create_failure_without_scanning(phone_run): + failure = TimeoutError("create response lost") + failure.add_note("Cloud create outcome unknown; request key test-request") + phone_run.create_cloud.side_effect = failure with pytest.raises(TimeoutError) as caught: - asyncio.run(exercise()) + async with smoke_phone.open_smoke_phone(phone_run, name=NAME, proxy=PROXY): + pytest.fail("must not yield without a confirmed lease") assert caught.value is failure - assert any( - f"unresolved: phone named {NAME!r} may exist" in note - for note in failure.__notes__ - ) - assert 1 < listed.await_count <= 30 - terminate.assert_not_awaited() + assert failure.__notes__ == [ + "Cloud create outcome unknown; request key test-request" + ] + phone_run.create_cloud.assert_awaited_once() + phone_run.list_cloud_devices.assert_not_awaited() diff --git a/tests/unit/logs/test_action_reporting.py b/tests/unit/logs/test_action_reporting.py index 7457b909c..efb817797 100644 --- a/tests/unit/logs/test_action_reporting.py +++ b/tests/unit/logs/test_action_reporting.py @@ -3,21 +3,17 @@ import ast import asyncio import logging -import traceback from types import SimpleNamespace +from unittest.mock import AsyncMock import pytest +from mobilerun_core import ActionEvent, AsyncDevice, Secret -from mobilerun.clients.cloud.tasks import _progress from mobilerun.config.user_config import LoggingConfig -from mobilerun.core.extensions import Extension, action -from mobilerun.errors import ( - CloudServiceUnavailable, - CredentialFieldNotFound, - ExtensionActionError, -) -from mobilerun.logs.actions import agent_line, format_action +from mobilerun.core.operator.cloud import CloudTaskOperator +from mobilerun.logs.actions import format_action from mobilerun.logs.handlers import VERBOSE, configure_logging, resolve_log_level +from tests.support.devices import fake_device from tests.support.paths import REPO_ROOT PACKAGE = REPO_ROOT / "mobilerun" @@ -63,223 +59,88 @@ async def iter_lines(self): client = SimpleNamespace( tasks=SimpleNamespace( - with_streaming_response=SimpleNamespace(attach=lambda *a, **kw: Stream()) + run=AsyncMock(return_value=SimpleNamespace(id="task")), + with_streaming_response=SimpleNamespace(attach=lambda *a, **kw: Stream()), + get_status=AsyncMock( + return_value=SimpleNamespace( + status="completed", succeeded=True, message=None, steps=1 + ) + ), ) ) # CLI setup can route records to stderr instead of pytest's root handler. monkeypatch.setattr(logging.getLogger("mobilerun"), "propagate", True) with caplog.at_level(logging.INFO, logger="mobilerun.actions"): - asyncio.run(_progress(client, "task", *device_args, billing="no_commerce")) + phone = SimpleNamespace( + device_id=device_args[0] if device_args else "", + info=lambda: SimpleNamespace(backend="cloud"), + ) + operator = CloudTaskOperator(client=client, billing="included") + assert asyncio.run(operator.do(phone, "fake task")).success assert [record.message for record in caplog.records] == [expected] -def test_action_never_shows_text_or_description(): - for field in ("text", "contentDescription", "description"): - for label in ("Your code ABCDEF", "secret passphrase", "+", "Settings"): - ui = SimpleNamespace( - get_element=lambda index, field=field, label=label: { - field: label, - "className": "android.widget.Button", - "resourceId": "com.example:id/increment", - } - ) - assert format_action("tap", {"index": 8}, ui) == "tap Button[increment] #8" - - -def test_action_target_uses_available_class_id_and_index(): - for element, expected in ( - ({"className": "android.widget.EditText"}, "tap EditText #3"), - ({"resourceId": "com.example:id/increment"}, "tap [increment] #3"), - ({"text": "secret"}, "tap #3"), - ): - ui = SimpleNamespace(get_element=lambda index, element=element: element) - assert format_action("tap", {"index": 3}, ui) == expected - assert format_action("tap", {"x": 1, "y": 2}) == "tap (1, 2)" +def test_core_hook_uses_bound_public_argument_names() -> None: + summaries: list[str | None] = [] + async def record(_phone: AsyncDevice, event: ActionEvent) -> None: + summaries.append(format_action(event.action.name, event.action.arguments)) -def test_action_logging_accepts_context_without_optional_state_or_ui(): - ctx = SimpleNamespace(driver=SimpleNamespace(identifier="device")) - assert agent_line(ctx, "tap", {"x": 1, "y": 2}) == ("device · step 1 tap (1, 2)") - - -def test_agent_action_uses_device_identifier_not_legacy_attributes(): - from mobilerun.core.devices.base import Device - - class ExampleDevice(Device): - @property - def identifier(self): - return "typed-id" - - serial = "stale-secret" - device_id = "old-id" - - ctx = SimpleNamespace( - driver=ExampleDevice(), shared_state=SimpleNamespace(step_number=1), ui=None - ) - assert agent_line(ctx, "tap", {"x": 1, "y": 2}) == "typed-id · step 1 tap (1, 2)" - - -def test_agent_action_with_no_identifier_has_safe_unknown_label(): - from mobilerun.core.devices.base import Device - - ctx = SimpleNamespace( - driver=Device(), shared_state=SimpleNamespace(step_number=1), ui=None - ) - assert agent_line(ctx, "tap", {"x": 1, "y": 2}) == "unknown · step 1 tap (1, 2)" - - -@pytest.mark.parametrize("timeout", [180, 180.0]) -def test_timeout_reports_type_and_configured_nonsensitive_timeout(timeout, caplog): - caplog.set_level(logging.INFO, logger="mobilerun") - - class Mailbox(Extension): - @action - async def wait_for_code(self, timeout: float = 180) -> str: - """Wait for a test verification code.""" - raise TimeoutError("BACKEND-CANARY") - - async def run(): - mailbox = Mailbox(name="email") - for invoke in ( - mailbox.wait_for_code, - lambda: mailbox.wait_for_code(timeout), - lambda: mailbox.actions.call("email.wait_for_code", {"timeout": timeout}), - lambda: mailbox.actions.call("email.wait_for_code", {}), - ): - with pytest.raises(ExtensionActionError) as raised: - await invoke() - assert ( - str(raised.value) - == "Action email.wait_for_code failed: TimeoutError (timed out after 180s)" - ) - assert raised.value.cause_type == "TimeoutError" - assert raised.value.__cause__ is None - assert "BACKEND-CANARY" not in "".join( - traceback.format_exception(raised.value) - ) + async def run() -> None: + async with fake_device() as phone, phone.use_action_hooks(after=record): + await phone.tap(1, 2) + await phone.key("home") asyncio.run(run()) + assert summaries == ["tap (1, 2)", "button home"] -def test_timeout_without_a_configured_timeout_does_not_guess(caplog): - caplog.set_level(logging.INFO, logger="mobilerun") - - class Resource(Extension): - @action - async def run(self) -> None: - """Fail with an unknown backend timeout.""" - raise TimeoutError("PRIVATE-CANARY") - - with pytest.raises(ExtensionActionError) as raised: - asyncio.run(Resource().run()) - assert str(raised.value) == "Action extension.run failed: TimeoutError (timed out)" - assert raised.value.cause_type == "TimeoutError" - - -@pytest.mark.parametrize("level", [logging.INFO, logging.DEBUG]) -def test_sensitive_action_never_exposes_backend_message_or_chain(level, caplog): - caplog.set_level(level, logger="mobilerun") - canary = "PRIVATE-CANARY" - - class Vault(Extension): - @action(sensitive_parameters=frozenset({"password"})) - async def login(self, password: str, timeout: float = 180) -> None: - """Perform a sensitive SDK operation.""" - raise TimeoutError(f"secret={password}") - - with pytest.raises(ExtensionActionError) as raised: - asyncio.run(Vault().login(canary)) - assert raised.value.cause_type == "TimeoutError" - assert "180s" in str(raised.value) - assert raised.value.__cause__ is None - assert "PRIVATE-CANARY" not in "".join(traceback.format_exception(raised.value)) - - -def test_sensitive_timeout_is_not_added_to_message(caplog): - caplog.set_level(logging.INFO, logger="mobilerun") - - class Resource(Extension): - @action(sensitive_parameters=frozenset({"timeout"})) - async def run(self, timeout: float) -> None: - """Treat the timeout itself as confidential.""" - raise TimeoutError("PRIVATE-CANARY") - - with pytest.raises(ExtensionActionError) as raised: - asyncio.run(Resource().run(987654)) - assert "TimeoutError (timed out)" in str(raised.value) - assert "987654" not in str(raised.value) - - -@pytest.mark.parametrize("level", [logging.INFO, logging.DEBUG]) -def test_cloud_error_propagates_unchanged(level, caplog): - caplog.set_level(level, logger="mobilerun") - original = CloudServiceUnavailable(operation="List SMS messages", status=503) - - class Resource(Extension): - @action - async def run(self) -> None: - """Exercise opt-in debug diagnostics.""" - raise original - - with pytest.raises(CloudServiceUnavailable) as raised: - asyncio.run(Resource().run()) - assert raised.value is original - - -@pytest.mark.parametrize("level", [logging.INFO, logging.DEBUG]) -def test_nonsensitive_debug_action_chains_only_when_debug_enabled(level, caplog): - caplog.set_level(level, logger="mobilerun") - original = RuntimeError("BACKEND-CANARY") - - class Resource(Extension): - @action - async def run(self) -> None: - """Exercise opt-in debug diagnostics for ordinary exceptions.""" - raise original - - with pytest.raises(ExtensionActionError) as raised: - asyncio.run(Resource().run()) - assert raised.value.cause_type == "RuntimeError" - assert "RuntimeError" in str(raised.value) - assert "BACKEND-CANARY" not in str(raised.value) - assert raised.value.__cause__ is (original if level == logging.DEBUG else None) +def test_core_hook_never_logs_secret_input(caplog, monkeypatch) -> None: + logger = logging.getLogger("mobilerun.actions") + monkeypatch.setattr(logging.getLogger("mobilerun"), "propagate", True) + canary = "SECRET-INPUT-CANARY" + async def report(_phone: AsyncDevice, event: ActionEvent) -> None: + logger.info("%s", format_action(event.action.name, event.action.arguments)) -def test_nested_nonsensitive_action_cannot_escape_sensitive_debug_scope(caplog): - caplog.set_level(logging.DEBUG, logger="mobilerun") - canary = "PRIVATE-CANARY" + async def run() -> None: + async with fake_device() as phone, phone.use_action_hooks(after=report): + await phone.type_secret(Secret(canary), clear=True) - class Resource(Extension): - @action - async def inner(self) -> None: - """Fail inside the parent sensitive scope.""" - raise RuntimeError(canary) + with caplog.at_level(logging.INFO, logger=logger.name): + asyncio.run(run()) + assert caplog.messages == ["type "] + assert canary not in caplog.text - @action(sensitive_parameters=frozenset({"password"})) - async def outer(self, password: str) -> None: - """Delegate within a sensitive call.""" - await self.inner() - with pytest.raises(ExtensionActionError) as raised: - asyncio.run(Resource().outer(canary)) - assert raised.value.cause_type == "RuntimeError" - assert raised.value.__cause__ is None - assert "PRIVATE-CANARY" not in "".join(traceback.format_exception(raised.value)) - - -def test_value_safe_error_still_propagates_unchanged(caplog): - caplog.set_level(logging.DEBUG, logger="mobilerun") - original = CredentialFieldNotFound("Credential field not found") - - class Resource(Extension): - @action - async def run(self) -> None: - """Expose a public value-safe typed failure.""" - raise original - - with pytest.raises(CredentialFieldNotFound) as raised: - asyncio.run(Resource().run()) - assert raised.value is original +@pytest.mark.parametrize( + ("name", "args", "summary"), + [ + ( + "type_secret", + {"secret": "SECRET-INPUT-CANARY", "x": 12, "y": 34}, + "type ", + ), + ("tap_element", {"element": {"text": "SECRET-ELEMENT"}}, "tap element"), + ("set_clipboard", {"value": "SECRET-CLIPBOARD"}, "set clipboard "), + ( + "open_deep_link", + {"deep_link": "https://example.invalid/?token=SECRET"}, + "open deep link", + ), + ( + "extension_call", + { + "name": "credentials.type_secret", + "arguments": {"name": "SECRET-REFERENCE"}, + }, + "extension call", + ), + ("unknown", {"password": "SECRET-UNKNOWN"}, None), + ], +) +def test_recorded_action_summary_does_not_render_opaque_arguments(name, args, summary): + assert format_action(name, args) == summary @pytest.mark.parametrize( @@ -399,7 +260,7 @@ def test_shared_library_has_no_browser_or_stdout_presentation(): for directory in ("utils", "clients", "core"): for path in (PACKAGE / directory).rglob("*.py"): # Opt-in checkout handlers are the only library presentation boundary. - if path == PACKAGE / "clients" / "cloud" / "checkout.py": + if path == PACKAGE / "utils" / "checkout" / "presentation.py": continue tree = ast.parse(path.read_text(encoding="utf-8")) for node in ast.walk(tree): @@ -427,7 +288,7 @@ def test_library_does_not_call_print(): violations = [] for path in PACKAGE.rglob("*.py"): # Opt-in checkout handlers deliberately print payment instructions. - if path == PACKAGE / "clients" / "cloud" / "checkout.py": + if path == PACKAGE / "utils" / "checkout" / "presentation.py": continue if "cli" in path.relative_to(PACKAGE).parts: continue diff --git a/tests/unit/macro/fixtures/head-7341bde/steps.jsonl b/tests/unit/macro/fixtures/head-7341bde/steps.jsonl new file mode 100644 index 000000000..b7da33508 --- /dev/null +++ b/tests/unit/macro/fixtures/head-7341bde/steps.jsonl @@ -0,0 +1,10 @@ +{"i": 1, "started_at": "2025-01-01T00:00:00Z", "finished_at": "2025-01-01T00:00:00Z", "action": "tap", "args": {"x": 10, "y": 20}, "ok": true, "error": null, "before": null, "after": null, "note": null, "target": null, "by": "script", "screens": null} +{"i": 2, "started_at": "2025-01-01T00:00:00Z", "finished_at": "2025-01-01T00:00:00Z", "action": "button_press", "args": {"button": "back"}, "ok": true, "error": null, "before": null, "after": null, "note": null, "target": null, "by": "script", "screens": null} +{"i": 3, "started_at": "2025-01-01T00:00:00Z", "finished_at": "2025-01-01T00:00:00Z", "action": "press_key_code", "args": {"key_code": 3}, "ok": true, "error": null, "before": null, "after": null, "note": null, "target": null, "by": "script", "screens": null} +{"i": 4, "started_at": "2025-01-01T00:00:00Z", "finished_at": "2025-01-01T00:00:00Z", "action": "swipe", "args": {"start_x": 1, "start_y": 2, "end_x": 3, "end_y": 4, "duration_ms": 500}, "ok": true, "error": null, "before": null, "after": null, "note": null, "target": null, "by": "script", "screens": null} +{"i": 5, "started_at": "2025-01-01T00:00:00Z", "finished_at": "2025-01-01T00:00:00Z", "action": "drag", "args": {"start_x": 1, "start_y": 2, "end_x": 3, "end_y": 4, "duration": 1.25}, "ok": true, "error": null, "before": null, "after": null, "note": null, "target": null, "by": "script", "screens": null} +{"i": 6, "started_at": "2025-01-01T00:00:00Z", "finished_at": "2025-01-01T00:00:00Z", "action": "wait", "args": {"duration": 0.25}, "ok": true, "error": null, "before": null, "after": null, "note": null, "target": null, "by": "script", "screens": null} +{"i": 7, "started_at": "2025-01-01T00:00:00Z", "finished_at": "2025-01-01T00:00:00Z", "action": "input_text", "args": {"text": "hello", "clear": true, "stealth": false, "wpm": 0}, "ok": true, "error": null, "before": null, "after": null, "note": null, "target": null, "by": "script", "screens": null} +{"i": 8, "started_at": "2025-01-01T00:00:00Z", "finished_at": "2025-01-01T00:00:00Z", "action": "start_app", "args": {"package": "org.example", "activity": null}, "ok": true, "error": null, "before": null, "after": null, "note": null, "target": null, "by": "script", "screens": null} +{"i": 9, "started_at": "2025-01-01T00:00:00Z", "finished_at": "2025-01-01T00:00:00Z", "action": "stop_app", "args": {"package": "org.example"}, "ok": true, "error": null, "before": null, "after": null, "note": null, "target": null, "by": "script", "screens": null} +{"i": 10, "started_at": "2025-01-01T00:00:00Z", "finished_at": "2025-01-01T00:00:00Z", "action": "extension_call", "args": {"name": "vault.type_field", "arguments": {"package": null, "field": "password", "name": "fixture"}}, "ok": true, "error": null, "before": null, "after": null, "note": null, "target": null, "by": "script", "screens": null} diff --git a/tests/unit/macro/fixtures/head-7341bde/v1.jsonl b/tests/unit/macro/fixtures/head-7341bde/v1.jsonl new file mode 100644 index 000000000..d1274f59c --- /dev/null +++ b/tests/unit/macro/fixtures/head-7341bde/v1.jsonl @@ -0,0 +1,10 @@ +{"i":1,"action":"tap","args":{"x":10,"y":20}} +{"i":2,"action":"button_press","args":{"button":"back"}} +{"i":3,"action":"press_key_code","args":{"key_code":3}} +{"i":4,"action":"swipe","args":{"start_x":1,"start_y":2,"end_x":3,"end_y":4,"duration_ms":500}} +{"i":5,"action":"drag","args":{"start_x":1,"start_y":2,"end_x":3,"end_y":4,"duration":1.25}} +{"i":6,"action":"wait","args":{"duration":0.25}} +{"i":7,"action":"input_text","args":{"text":"hello","clear":true,"stealth":false,"wpm":0}} +{"i":8,"action":"start_app","args":{"package":"org.example","activity":null}} +{"i":9,"action":"stop_app","args":{"package":"org.example"}} +{"i":10,"action":"extension_call","args":{"name":"vault.type_field","arguments":{"package":null,"field":"password","name":"fixture"}}} diff --git a/tests/unit/macro/test_builder.py b/tests/unit/macro/test_builder.py index b7f01f6bb..105859c90 100644 --- a/tests/unit/macro/test_builder.py +++ b/tests/unit/macro/test_builder.py @@ -1,14 +1,17 @@ """Versioned macros keep only replayable evidence.""" +import json from concurrent.futures import ThreadPoolExecutor +from datetime import datetime, timezone +from pathlib import Path from threading import Barrier import pytest from mobilerun.macro import builder -from mobilerun.macro.errors import MacroError +from mobilerun.macro.errors import MacroError, OlderMacroError from mobilerun.models import Fingerprint -from tests.support.macro import write_steps +from tests.support.macro import write_macro, write_steps @pytest.fixture(autouse=True) @@ -29,27 +32,61 @@ def test_selected_export_omits_failed_masked_and_run_only_data(tmp_path): { "i": 6, "action": "extension_call", - "args": {"name": "vault.type_field", "arguments": {"name": "login"}}, + "args": {"name": "vault.type_secret", "arguments": {"name": "login"}}, "note": "Type credential", "target": "login field", "screens": {"after": {"png": "screens/6.after.png"}}, + "result": "run-only output", }, ) output = builder.build_macro(path, "routine", step_ids={2, 3, 4, 6, 1}) rows = builder.load_macro(output) assert [row.i for row in rows] == [1, 6] - assert rows[1].args == { - "name": "vault.type_field", + assert rows[1].action.name == "extension_call" + assert rows[1].action.scope == "extension" + assert rows[1].action.arguments == { + "name": "vault.type_secret", "arguments": {"name": "login"}, } + assert json.loads(output.read_text().splitlines()[1]) == { + "schema_version": 2, + "i": 6, + "action": "extension_call", + "args": {"name": "vault.type_secret", "arguments": {"name": "login"}}, + "started_at": "2026-11-27T00:00:00Z", + "note": "Type credential", + "target": "login field", + } assert (rows[1].note, rows[1].target) == ("Type credential", "login field") + assert rows[1].action.started_at == datetime(2026, 11, 27, tzinfo=timezone.utc) assert ( - not {"started_at", "finished_at", "ok", "error", "by", "screens"} + not {"finished_at", "ok", "error", "by", "screens", "result"} & rows[1].model_dump().keys() ) +def test_macro_without_action_timestamps_still_loads(tmp_path): + path = write_macro(tmp_path) + + (step,) = builder.load_macro(path) + + assert step.action.started_at is None + assert "started_at" not in step.model_dump(exclude_defaults=True) + + +def test_export_omits_successful_actions_outside_replay_vocabulary(tmp_path): + path = write_steps( + tmp_path, + {"i": 1, "action": "tap", "args": {"x": 10, "y": 20}}, + {"i": 2, "action": "uninstall_app", "args": {"app_id": "example.app"}}, + ) + + output = builder.build_macro(path, "routine") + + assert [row.i for row in builder.load_macro(output)] == [1] + + def test_latest_is_numeric_and_file_pins_version(tmp_path): first = builder.build_macro( write_steps(tmp_path, {"i": 1}), "routine", after_version=8 @@ -120,7 +157,55 @@ def test_v2_is_not_a_macro_or_run(tmp_path): old = tmp_path / "macro.json" old.write_text('{"macro_schema_version": "2.0", "actions": []}') for target in (old, tmp_path): - with pytest.raises(MacroError, match="Unsupported macro schema"): + with pytest.raises( + OlderMacroError, match="^recorded with an older Mobilerun; re-record it$" + ): builder.load_macro(target) - with pytest.raises(MacroError, match="Unsupported macro schema"): + with pytest.raises( + OlderMacroError, match="^recorded with an older Mobilerun; re-record it$" + ): builder.build_macro(old, "routine") + + +def test_explicit_unsupported_schema_requires_rerecording(tmp_path): + old = tmp_path / "v1.jsonl" + old.write_text('{"schema_version":1,"i":1,"action":"tap","args":{"x":10,"y":20}}\n') + with pytest.raises(OlderMacroError) as caught: + builder.load_macro(old) + assert str(caught.value) == "recorded with an older Mobilerun; re-record it" + + +def test_head_run_and_macro_load_without_rewriting_legacy_files(): + # Produced by RunWriter.append and build_macro from commit 7341bde. + fixtures = Path(__file__).parent / "fixtures" / "head-7341bde" + old_run, old_macro = fixtures / "steps.jsonl", fixtures / "v1.jsonl" + originals = [path.read_bytes() for path in (old_run, old_macro)] + exported = builder.build_macro(old_run, "from-head") + points = {"x1": 1, "y1": 2, "x2": 3, "y2": 4} + expected = [ + ("tap", {"x": 10, "y": 20}), + ("key", {"name_or_code": "back"}), + ("key", {"name_or_code": 3}), + ("swipe", {**points, "ms": 500}), + ("drag", {**points, "ms": 1250}), + ("wait", {"seconds": 0.25}), + ("type", {"text": "hello", "clear": True}), + ("start_app", {"app_id": "org.example", "activity": None}), + ("stop_app", {"app_id": "org.example"}), + ( + "extension_call", + { + "name": "vault.type_secret", + "arguments": {"package": None, "field": "password", "name": "fixture"}, + }, + ), + ] + for path in (old_macro, exported): + rows = builder.load_macro(path) + assert [(row.action.name, row.action.arguments) for row in rows] == expected + assert all(row.schema_version == 2 for row in rows) + assert all( + json.loads(line)["schema_version"] == 2 + for line in exported.read_text().splitlines() + ) + assert [path.read_bytes() for path in (old_run, old_macro)] == originals diff --git a/tests/unit/macro/test_cli.py b/tests/unit/macro/test_cli.py index f76f98eba..c0eed8430 100644 --- a/tests/unit/macro/test_cli.py +++ b/tests/unit/macro/test_cli.py @@ -12,14 +12,57 @@ import click import pytest from click.testing import CliRunner +from mobilerun_core import AsyncMobilerun, DeviceDescriptor, LocalDevices from mobilerun.cli.app import cli -from mobilerun.cli.devices.base import discovery, options, selection -from mobilerun.cli.devices.base.options import device_options +from mobilerun.cli.devices.base import selection +from mobilerun.cli.devices.utils import approval +from mobilerun.cli.devices.utils.connection import discovery +from mobilerun.config.user_config import MobileConfig from mobilerun.macro.cli import macro from mobilerun.macro.utils import configure_macro_logging from mobilerun.models.results import ExecutionResult -from tests.support.macro import FakeDevice, write_macro +from tests.support.devices import FakeDriver, fake_device +from tests.support.macro import write_macro + +replay_module = importlib.import_module("mobilerun.macro.cli.replay") + + +def test_replay_requests_portal_setup_before_connecting(monkeypatch, tmp_path): + events = [] + + class Core(AsyncMobilerun): + def __init__(self, *, hitl_gate, **kwargs): + super().__init__(hitl_gate=hitl_gate, **kwargs) + self.gate = hitl_gate + self._local = SimpleNamespace(ensure_portal_ready=self.setup) + + async def setup(self, serial, *, client_version): + await self.gate( + "local.ensure_portal_ready", + dict( + serial=serial, + client_version=client_version, + package="com.mobilerun.portal", + touches_accessibility=True, + ), + ) + events.append(("setup", serial)) + + async def connect(self, serial, **kwargs): + events.append(("connect", serial)) + return fake_device() + + monkeypatch.setattr(selection, "AsyncMobilerun", Core) + monkeypatch.setattr(approval, "is_interactive", lambda: False) + args = ["replay", str(write_macro(tmp_path)), "serial"] + result = CliRunner().invoke(macro, args) + assert result.exit_code == 1 + assert "pass --yes" in result.output + assert events == [] + result = CliRunner().invoke(macro, [*args, "--yes"]) + assert result.exit_code == 0, result.output + assert events == [("setup", "serial"), ("connect", "serial")] def test_macro_group_exposes_list_and_replay(): @@ -32,7 +75,8 @@ def test_macro_group_exposes_list_and_replay(): def test_macro_replay_discovery_and_exclusive_flags(tmp_path, monkeypatch): - monkeypatch.setattr(options, "discover_devices", AsyncMock(return_value=[])) + monkeypatch.setattr(AsyncMobilerun, "list_devices", AsyncMock(return_value=[])) + monkeypatch.setattr(replay_module, "is_interactive", lambda: True) path = write_macro(tmp_path) runner = CliRunner() missing = runner.invoke(macro, ["replay", str(path)]) @@ -46,20 +90,16 @@ def test_macro_replay_discovery_and_exclusive_flags(tmp_path, monkeypatch): def fake_device_factory(monkeypatch): - device = FakeDevice() + driver = FakeDriver() targets = [] - async def create(target, **kwargs): + async def create(run, target, **kwargs): targets.append(target) - return device - - async def close(): - pass + return fake_device(driver=driver) - device.close = close - - monkeypatch.setattr(selection, "connect_target", create) - return device, targets + monkeypatch.setattr(AsyncMobilerun, "connect", create) + monkeypatch.setattr(LocalDevices, "ensure_portal_ready", AsyncMock()) + return driver, targets def test_macro_cli_replays_on_selected_device(monkeypatch, tmp_path): @@ -69,7 +109,7 @@ def test_macro_cli_replays_on_selected_device(monkeypatch, tmp_path): cli, ["macro", "replay", str(write_macro(tmp_path)), "serial", "--delay", "0"] ) assert result.exit_code == 0, result.output - assert device.taps == [(10, 20)] + assert device.calls == [("tap", (10, 20), {})] assert targets == ["serial"] @@ -89,7 +129,7 @@ def test_macro_cli_mismatch_exits_nonzero_without_action(monkeypatch, tmp_path): ) assert result.exit_code == 1 assert "mismatch at step 1 (before)" in result.output - assert device.taps == [] + assert not any(call[0] == "tap" for call in device.calls) def test_dry_run_does_not_connect(monkeypatch, tmp_path): @@ -101,7 +141,7 @@ def test_dry_run_does_not_connect(monkeypatch, tmp_path): assert result.exit_code == 0, result.output assert "tap" in result.output assert targets == [] - assert device.taps == [] + assert device.calls == [] def test_versioned_targets_list_and_replay(tmp_path, monkeypatch): @@ -111,8 +151,8 @@ def test_versioned_targets_list_and_replay(tmp_path, monkeypatch): pin = write_macro(folder) current = folder / "v10.jsonl" current.write_text( - '{"i":3,"action":"tap","args":{"x":11,"y":20}}\n' - '{"i":8,"action":"wait","args":{"duration":0}}\n' + '{"schema_version":2,"i":3,"action":"tap","args":{"x":11,"y":20}}\n' + '{"schema_version":2,"i":8,"action":"wait","args":{"seconds":0}}\n' ) (folder / "v2.jsonl").write_text(pin.read_text()) (tmp_path / "other").mkdir() @@ -127,7 +167,7 @@ def test_versioned_targets_list_and_replay(tmp_path, monkeypatch): macro, ["replay", target, "--dry-run", "--start-from", "2"] ) assert result.exit_code == 0, result.output - assert result.output == "8: wait duration=0\n" + assert result.output == "8: wait seconds=0\n" result = runner.invoke(macro, ["replay", str(pin), "--dry-run"]) assert result.exit_code == 0, result.output assert result.output == "1: tap x=10 y=20\n" @@ -136,7 +176,7 @@ def test_versioned_targets_list_and_replay(tmp_path, monkeypatch): @pytest.mark.parametrize("flags", [[], ["--yes"], ["--on-mismatch", "agent"]]) def test_invalid_macro_fails_before_device_discovery(tmp_path, monkeypatch, flags): discovery = AsyncMock(side_effect=AssertionError("must not discover")) - monkeypatch.setattr(options, "discover_devices", discovery) + monkeypatch.setattr(AsyncMobilerun, "list_devices", discovery) path = tmp_path / "v1.jsonl" path.write_text("not a macro\n") result = CliRunner().invoke(macro, ["replay", str(path), *flags]) @@ -145,51 +185,36 @@ def test_invalid_macro_fails_before_device_discovery(tmp_path, monkeypatch, flag discovery.assert_not_awaited() -def test_optional_device_with_no_discovery(monkeypatch): +def test_adb_failure_does_not_hide_cloud_devices(monkeypatch): monkeypatch.setattr( - "mobilerun.cli.devices.base.options.discover_devices", - AsyncMock(return_value=[]), + AsyncMobilerun, + "list_devices", + AsyncMock(side_effect=RuntimeError("adb unavailable")), ) - - @click.command() - @device_options(optional=True) - def command(**kwargs): - click.echo(str(kwargs["target"])) - - result = CliRunner().invoke(command, []) - assert result.exit_code == 0, result.output - assert "None" in result.output - - -def test_adb_failure_does_not_hide_cloud_devices(monkeypatch): - monkeypatch.setattr( - discovery.adb, "list", AsyncMock(side_effect=RuntimeError("adb unavailable")) + discovery.LoginStore, "resolve_api_key", lambda self: "offline-fixture" ) - monkeypatch.setattr(discovery, "resolve_cloud_api_key", lambda: "fake") monkeypatch.setattr( - discovery, - "list_devices", + AsyncMobilerun, + "list_cloud_devices", AsyncMock( return_value=[ - SimpleNamespace( - id="cloud-id", name="phone", state="ready", type="android" + DeviceDescriptor( + "cloud-id", "cloud", "android", name="phone", state="ready" ) ] ), ) devices = asyncio.run(discovery.discover_devices()) - assert [d.id for d in devices] == ["cloud-id"] + assert [d.device_id for d in devices] == ["cloud-id"] def test_macro_dry_run_never_discovers_device(monkeypatch, tmp_path): discovery = AsyncMock(side_effect=AssertionError("must not discover")) - monkeypatch.setattr( - "mobilerun.cli.devices.base.options.discover_devices", discovery - ) + monkeypatch.setattr(AsyncMobilerun, "list_devices", discovery) path = write_macro( - tmp_path, rows=[{"i": 1, "action": "wait", "args": {"duration": 0}}] + tmp_path, rows=[{"i": 1, "action": "wait", "args": {"seconds": 0}}] ) result = CliRunner().invoke(macro, ["replay", str(path), "--dry-run"]) assert result.exit_code == 0, repr(result.exception) @@ -232,24 +257,26 @@ def test_macro_module_entrypoint(): def test_replay_config_reaches_device_connection(monkeypatch, tmp_path): - replay_module = importlib.import_module("mobilerun.macro.cli.replay") - - config = SimpleNamespace( - credentials={}, - device=SimpleNamespace(serial=None, platform="android", use_tcp=False), - ) + config = MobileConfig() + config.device.use_tcp = True + config.device.auto_setup = False monkeypatch.setattr(replay_module.ConfigLoader, "load", lambda *args: config) - connect = AsyncMock(return_value=SimpleNamespace(close=AsyncMock())) - monkeypatch.setattr(selection, "connect_target", connect) + connect = AsyncMock(return_value=fake_device()) + setup = AsyncMock(side_effect=AssertionError("Portal auto-setup is disabled")) + monkeypatch.setattr(AsyncMobilerun, "connect", connect) + monkeypatch.setattr(LocalDevices, "ensure_portal_ready", setup) monkeypatch.setattr( replay_module.MacroOperator, - "execute", + "do", AsyncMock(return_value=ExecutionResult(success=True, device="fake")), ) path = write_macro(tmp_path) result = CliRunner().invoke(macro, ["replay", str(path), "-d", "serial"]) assert result.exit_code == 0, repr(result.exception) - assert connect.await_args.kwargs["config"] is config + connect.assert_awaited_once_with( + "serial", backend="local-android-adb", use_tcp=True, portal_mode="auto" + ) + setup.assert_not_awaited() def test_macro_agent_handoff_accepts_injected_runner(tmp_path): @@ -273,7 +300,7 @@ def test_macro_agent_handoff_accepts_injected_runner(tmp_path): parent=parent, ) assert result.exit_code == 0, result.output - assert received[0]["target"].identifier == "serial" + assert received[0]["target"] == "serial" assert received[0]["path"] == str(path) @@ -287,7 +314,7 @@ def test_preview_shows_coordinates_without_snapshot_or_payload(tmp_path): "before": {"app": secret, "activity": None, "elements": []}, "note": secret, }, - {"i": 2, "action": "input_text", "args": {"text": secret}}, + {"i": 2, "action": "type", "args": {"text": secret}}, { "i": 3, "action": "extension_call", @@ -299,7 +326,7 @@ def test_preview_shows_coordinates_without_snapshot_or_payload(tmp_path): assert result.exit_code == 0, result.exception assert "PRIVATE-UI-TEXT" not in result.output assert "1: tap x=10 y=20" in result.output - assert "input_text [redacted]" in result.output + assert "type [redacted]" in result.output assert "extension_call [redacted]" in result.output assert len(result.output) < 200 diff --git a/tests/unit/macro/test_core_dialect.py b/tests/unit/macro/test_core_dialect.py new file mode 100644 index 000000000..cb4a87f3d --- /dev/null +++ b/tests/unit/macro/test_core_dialect.py @@ -0,0 +1,137 @@ +"""Schema-2 recording and replay against the real core device facade.""" + +from pathlib import Path + +import pytest +from mobilerun_core import Secret +from pydantic import BaseModel, JsonValue + +from mobilerun.core.credentials import DictCredentials +from mobilerun.core.runs import ActionRecording +from mobilerun.macro import ( + MacroError, + MacroOperator, + MacroPlayer, + MacroSecretError, + MacroStep, + build_macro, + load_macro, +) +from mobilerun.models.results import ExecutionResult +from tests.support.devices import FakeDriver, fake_device +from tests.support.macro import read_run_steps + + +@pytest.fixture +def anyio_backend() -> str: + return "asyncio" + + +@pytest.mark.anyio +@pytest.mark.parametrize( + ("verb", "args"), + [ + ("tap", {"x": 10, "y": 20}), + ("swipe", {"x1": 1, "y1": 2, "x2": 3, "y2": 4, "ms": 300}), + ("drag", {"x1": 1, "y1": 2, "x2": 3, "y2": 4, "ms": 1200}), + ("type", {"text": "hello", "clear": True, "humanize": False, "wpm": 23}), + ("key", {"name_or_code": "home"}), + ("start_app", {"app_id": "example.app", "activity": ".Demo"}), + ("stop_app", {"app_id": "example.app"}), + ("wait", {"seconds": 0}), + ], +) +async def test_round_trip( + verb: str, + args: dict[str, JsonValue], + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + monkeypatch.setenv("MOBILERUN_MACRO_DIRECTORY", str(tmp_path / "macros")) + original, replayed = FakeDriver(), FakeDriver() + async with fake_device(driver=original) as phone: + async with ActionRecording(phone, runs_dir=tmp_path) as rec: + await getattr(phone, verb)(**args) + rec.finish("succeeded") + macro = build_macro(rec.run_dir / "steps.jsonl", "roundtrip") + (step,) = load_macro(macro) + assert step.schema_version == 2 and step.action.name == verb + assert args.items() <= step.action.arguments.items() + async with fake_device(driver=replayed) as phone: + async with ActionRecording(phone, runs_dir=tmp_path) as replay: + result: ExecutionResult[BaseModel] = await MacroOperator(macro).do( + phone, "ignored" + ) + replay.finish("succeeded") + assert result.success and result.steps == 1 + assert replayed.calls == original.calls + (replayed_step,) = read_run_steps(replay.run_dir) + assert ( + replayed_step.action.name == verb + and replayed_step.action.arguments == step.action.arguments + ) + + +@pytest.mark.anyio +@pytest.mark.parametrize( + ("action", "args"), + [("aclose", {}), ("tap", {"x": "12", "y": 20}), ("type_secret", {"secret": "***"})], +) +async def test_all_rows_preflight_even_outside_selected_slice( + action: str, args: dict[str, JsonValue] +) -> None: + driver = FakeDriver() + first = MacroStep(schema_version=2, i=1, action="tap", args={"x": 10, "y": 20}) + invalid = MacroStep(schema_version=2, i=2, action=action, args=args) + async with fake_device(driver=driver) as phone: + with pytest.raises(MacroError): + await MacroPlayer(phone).replay_macro([first, invalid], max_steps=1) + assert driver.calls == [] + + +@pytest.mark.anyio +async def test_recorded_secret_reference_resolves_without_persisting_value( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture +) -> None: + monkeypatch.setenv("MOBILERUN_MACRO_DIRECTORY", str(tmp_path / "macros")) + canary = "synthetic-password-canary" + driver = FakeDriver() + async with fake_device() as phone: + async with ActionRecording(phone, runs_dir=tmp_path) as rec: + async with rec.extension_call("vault.type_secret", {"name": "login"}): + await phone.type_secret(Secret(canary)) + rec.finish("succeeded") + macro = build_macro(rec.run_dir / "steps.jsonl", "credential") + assert canary not in macro.read_text() + async with fake_device(driver=driver) as phone: + vault = DictCredentials({"login": canary}, device=phone) + result: ExecutionResult[BaseModel] = await MacroOperator( + macro, extensions=[vault] + ).do(phone, "ignored") + assert result.success + assert any( + name == "input_text" and args == (canary,) for name, args, _ in driver.calls + ) + assert canary not in caplog.text + + +@pytest.mark.anyio +async def test_bare_secret_keeps_mask_but_cannot_guess_credential( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setenv("MOBILERUN_MACRO_DIRECTORY", str(tmp_path / "macros")) + canary = "synthetic-bare-secret" + async with fake_device() as phone: + async with ActionRecording(phone, runs_dir=tmp_path) as rec: + await phone.type_secret(Secret(canary), clear=True) + rec.finish("succeeded") + path = build_macro(rec.run_dir / "steps.jsonl", "masked") + (step,) = load_macro(path) + assert step.action.arguments == {"secret": "***", "clear": True} + assert canary not in path.read_text() + driver = FakeDriver() + async with fake_device(driver=driver) as phone: + vault = DictCredentials({"login": canary}, device=phone) + with pytest.raises(MacroSecretError, match="No credential reference"): + await MacroOperator(path, extensions=[vault]).do(phone, "ignored") + assert driver.calls == [] diff --git a/tests/unit/macro/test_replay.py b/tests/unit/macro/test_replay.py index 653b66ff4..7a3428f86 100644 --- a/tests/unit/macro/test_replay.py +++ b/tests/unit/macro/test_replay.py @@ -1,227 +1,119 @@ -"""Guarded playback uses original evidence indices and fails closed.""" +"""Guarded playback preserves the phase and original row position.""" -import asyncio -from unittest.mock import AsyncMock +from typing import Any import pytest -from mobilerun.core.credentials import CredentialPolicy, DictCredentials -from mobilerun.errors.base import DeviceError -from mobilerun.macro.errors import MacroError, MacroMismatch -from mobilerun.macro.models import MacroStep -from mobilerun.macro.operator import MacroOperator -from mobilerun.macro.player import MacroPlayer +from mobilerun.macro import ( + MacroMismatch, + MacroOperator, + MacroPlayer, + MacroStep, + load_macro, +) +from mobilerun.macro.builder import _replay_snapshot from mobilerun.models import Fingerprint -from tests.support.macro import FakeDevice, write_macro +from tests.support.devices import FakeDriver, fake_device +from tests.support.macro import write_macro -READY = Fingerprint(app="settings", activity=".Ready", elements=("id:continue",)) -DONE = Fingerprint(app="settings", activity=".Done", elements=()) - - -def test_stepwise_replay_refuses_handoff_after_a_vault_row(): - from mobilerun.core.credentials.masking import current_masks - - async def run(): - device = FakeDevice(_screen(".Wrong")) - device._input_secret = AsyncMock(return_value=True) - await DictCredentials({"login": "example-secret"}).bind(device) - player = MacroPlayer(device, state_timeout=0) - with player.replay_scope(): - await player.play_step(_step(action="type_secret", args={"name": "login"})) - assert player.tainted - assert current_masks.get().active - with pytest.raises(MacroError, match="handoff refused"): - await player.play_step(_step(before=READY)) - assert current_masks.get() is None - assert player.tainted - - asyncio.run(run()) - - -def test_masks_prepare_once_per_replay_scope_and_lazily_outside_it(): - class Vault(DictCredentials): - preparations = 0 - - async def prepare_masks(self, masks): - self.preparations += 1 - await super().prepare_masks(masks) - - async def run(): - device = FakeDevice() - vault = await Vault({"login": "example-secret"}).bind(device) - player = MacroPlayer(device) - with player.replay_scope(): - assert vault.preparations == 0 - await player.play_step(_step()) - with player.replay_scope(): - await player.play_step(_step()) - assert vault.preparations == 1 - await player.play_step(_step()) - assert vault.preparations == 2 - - asyncio.run(run()) - - -def _screen(activity, element=None): - return { - "phone_state": {"packageName": "settings", "activityName": activity}, - "elements": [element] if element is not None else [], - } +READY = Fingerprint(app="example.app", activity=None, elements=("class:EditText",)) +DONE = Fingerprint(app="example.done", activity=None, elements=()) def _step(**fields): - return MacroStep(**{"i": 7, "action": "tap", "args": {"x": 60, "y": 40}, **fields}) - - -def test_player_polls_guards_and_uses_saved_coordinates(): - device = FakeDevice( - _screen(".Loading"), - _screen(".Ready", {"resourceId": "continue", "bounds": "100,100,120,120"}), - _screen(".Done"), + return MacroStep( + **{ + "schema_version": 2, + "i": 7, + "action": "tap", + "args": {"x": 60, "y": 40}, + **fields, + } ) - player = MacroPlayer(device, state_timeout=0.5, state_poll_interval=0) - asyncio.run(player.play_step(_step(before=READY, after=DONE, target="continue"))) - assert device.taps == [(60, 40)] - assert device.observations == 3 +@pytest.fixture +def anyio_backend(): + return "asyncio" +@pytest.mark.anyio @pytest.mark.parametrize("phase", ["before", "action", "after"]) -def test_divergence_reports_original_index_and_phase(phase): - class RejectTap(FakeDevice): - async def tap(self, x, y): - if phase == "action": - raise DeviceError("not accepted") - await super().tap(x, y) - - ready = _screen(".Ready", {"resourceId": "continue"}) - device = RejectTap(_screen(".Wrong") if phase == "before" else ready, ready) - player = MacroPlayer(device, state_timeout=0) +async def test_divergence_reports_original_index_and_phase(phase): + driver = FakeDriver( + failures={"tap": OSError("not accepted")} if phase == "action" else {} + ) + if phase == "before": + driver.ui_tree["phone_state"]["packageName"] = "wrong.app" step = _step(before=READY, after=DONE) - - with pytest.raises(MacroMismatch, match=rf"step 7.*{phase}") as caught: - asyncio.run(player.replay_macro([_step(i=2), step], start_from_step=1)) - + async with fake_device(driver=driver) as device: + player = MacroPlayer(device, state_timeout=0) + with pytest.raises(MacroMismatch, match=rf"step 7.*{phase}") as caught: + await player.replay_macro([_step(i=2), step], start_from_step=1) assert caught.value.step is step assert caught.value.phase == phase - assert caught.value.observed == ( - Fingerprint(app="settings", activity=".Wrong", elements=()) - if phase == "before" - else READY - ) - assert device.taps == ([(60, 40)] if phase == "after" else []) - - -def test_false_input_text_stops_at_action_without_checking_after(): - class RejectText(FakeDevice): - async def input_text(self, text, clear=False): - self.inputs.append((text, clear)) - return False - - device = RejectText() - player = MacroPlayer(device, state_timeout=0) - step = _step( - action="input_text", args={"text": "offline", "clear": True}, after=DONE - ) - with pytest.raises(MacroMismatch) as caught: - asyncio.run(player.play_step(step)) - assert caught.value.phase == "action" - assert caught.value.observed is None - assert device.inputs == [("offline", True)] - assert device.observations == 0 + expected_calls = [] if phase == "before" else [("tap", (60, 40), {})] + assert [call for call in driver.calls if call[0] == "tap"] == expected_calls +@pytest.mark.anyio @pytest.mark.parametrize("guard", ["before", "after"]) -def test_missing_observed_evidence_cannot_pass_present_guard(guard): - device = FakeDevice({}) - player = MacroPlayer(device, state_timeout=0, state_threshold=0) - - with pytest.raises(MacroMismatch) as caught: - asyncio.run(player.play_step(_step(**{guard: READY}))) - +async def test_missing_observed_evidence_cannot_pass_present_guard(guard): + driver = FakeDriver(failures={"get_ui_tree": OSError("not available")}) + async with fake_device(driver=driver) as device: + player = MacroPlayer(device, state_timeout=0, state_threshold=0) + with pytest.raises(MacroMismatch) as caught: + await player.play_step(_step(**{guard: READY})) assert caught.value.phase == guard assert caught.value.observed is None - assert device.taps == ([(60, 40)] if guard == "after" else []) -def test_missing_guards_skip_observation(): - device = FakeDevice({}) - asyncio.run(MacroPlayer(device).play_step(_step())) - assert device.taps == [(60, 40)] - assert device.observations == 0 +@pytest.mark.anyio +async def test_guard_polls_and_uses_saved_coordinates(): + class LoadingDriver(FakeDriver): + async def get_ui_tree(self, *, filter: bool = True) -> dict[str, Any]: + tree = await super().get_ui_tree(filter=filter) + if len(self.calls) == 1: + tree["phone_state"]["packageName"] = "loading.app" + return tree - -def test_unavailable_state_samples_are_not_observations(): - device = FakeDevice(None) - player = MacroPlayer(device, state_timeout=0) - with pytest.raises(MacroMismatch) as caught: - asyncio.run(player.play_step(_step(before=READY))) - assert caught.value.observed is None - assert device.taps == [] - - -def test_active_credential_masks_match_recorded_structural_keys(): - async def run(): - device = FakeDevice(_screen(".Ready", {"resourceId": "private-canary"})) - vault = await DictCredentials({"login": "private-canary"}).bind(device) - vault.policies = (CredentialPolicy("login", mask_from_start=True),) - player = MacroPlayer(device, state_timeout=0) - expected = READY.model_copy(update={"elements": ("id:[secret:login]",)}) - await player.play_step(_step(before=expected)) - assert device.taps == [(60, 40)] - - asyncio.run(run()) - - -def test_credential_reference_types_field_without_persisting_value(caplog): - async def run(): - device = FakeDevice() - device._input_secret = AsyncMock(return_value=True) - await DictCredentials({"login": "private-canary"}).bind(device) - await MacroPlayer(device).play_step( - _step(action="type_secret", args={"name": "login"}) + driver = LoadingDriver() + async with fake_device(driver=driver) as device: + await MacroPlayer(device, state_timeout=0.5, state_poll_interval=0).play_step( + _step(before=READY) ) - device._input_secret.assert_awaited_once_with("private-canary") - - with caplog.at_level("DEBUG"): - asyncio.run(run()) - assert "private-canary" not in caplog.text - - -def test_credential_preflight_blocks_earlier_actions_and_observation(): - async def run(): - device = FakeDevice() - vault = await DictCredentials({"login": "example-only"}).bind(device) - vault.policies = (CredentialPolicy("login", requires_approval=True),) - player = MacroPlayer(device) - protected = _step( - i=8, - action="extension_call", - args={ - "name": "vault.type_field", - "arguments": {"name": "login", "field": "password", "package": None}, - }, - ) - with pytest.raises(MacroError, match="approval"): - await player.replay_macro([_step(before=READY), protected]) - assert device.taps == [] - assert device.observations == 0 - - asyncio.run(run()) - - -def test_masked_macro_argument_is_not_sent_to_device(): - device = FakeDevice() - step = _step(action="input_text", args={"text": "prefix [secret:login]"}) - with pytest.raises(MacroError, match="redacted"): - asyncio.run(MacroPlayer(device).play_step(step)) - assert device.inputs == [] + assert [call[0] for call in driver.calls] == ["get_ui_tree", "get_ui_tree", "tap"] + assert driver.calls[-1] == ("tap", (60, 40), {}) + + +@pytest.mark.anyio +async def test_false_type_stops_at_action_without_checking_after(): + class RejectText(FakeDriver): + async def input_text( + self, + text: str, + *, + clear: bool = False, + humanize: bool = False, + wpm: int = 0, + ) -> bool: + await super().input_text(text, clear=clear, humanize=humanize, wpm=wpm) + return False + driver = RejectText() + async with fake_device(driver=driver) as device: + with pytest.raises(MacroMismatch) as caught: + await MacroPlayer(device).play_step( + _step( + action="type", args={"text": "offline", "clear": True}, after=DONE + ) + ) + assert caught.value.phase == "action" + assert [call[0] for call in driver.calls] == ["input_text"] -def test_operator_consumes_preflight_snapshot_even_if_file_changes(tmp_path): - from mobilerun.macro.builder import _replay_snapshot, load_macro +@pytest.mark.anyio +async def test_operator_consumes_preflight_snapshot_even_if_file_changes(tmp_path): path = write_macro(tmp_path) snapshot = load_macro(path) token = _replay_snapshot.set((path, snapshot)) @@ -229,10 +121,10 @@ def test_operator_consumes_preflight_snapshot_even_if_file_changes(tmp_path): write_macro( tmp_path, rows=[{"i": 2, "action": "tap", "args": {"x": 1, "y": 2}}] ) - device = FakeDevice() - result = asyncio.run(MacroOperator().execute(device, str(path))) + driver = FakeDriver() + async with fake_device(driver=driver) as device: + result = await MacroOperator().do(device, str(path)) finally: _replay_snapshot.reset(token) - assert result.success and result.steps == 1 - assert device.taps == [(10, 20)] + assert driver.calls == [("tap", (10, 20), {})] diff --git a/tests/unit/macro/test_replay_actions.py b/tests/unit/macro/test_replay_actions.py new file mode 100644 index 000000000..7309030b7 --- /dev/null +++ b/tests/unit/macro/test_replay_actions.py @@ -0,0 +1,44 @@ +import pytest +from mobilerun_core import Action + +from mobilerun.macro.errors import MacroPreflightError +from mobilerun.macro.models import MacroStep +from mobilerun.macro.replay_actions import validate_action + + +def test_replay_accepts_recorded_native_defaults(): + swipe = MacroStep( + schema_version=2, + i=1, + action=Action( + "swipe", + {"x1": 1, "y1": 2, "x2": 3, "y2": 4, "ms": None, "hold_ms": 0}, + "device", + ), + ) + stop = MacroStep( + schema_version=2, + i=2, + action=Action( + "stop_app", + {"app_id": "example.app", "clear_data": False}, + "device", + ), + ) + assert validate_action(swipe).model_dump()["hold_ms"] == 0 + assert validate_action(stop).model_dump()["clear_data"] is False + + +@pytest.mark.parametrize( + ("action", "args"), + [ + ("swipe", {"x1": 1, "y1": 2, "x2": 3, "y2": 4, "hold_ms": 10}), + ("stop_app", {"app_id": "example.app", "clear_data": True}), + ("open_deep_link", {"deep_link": "https://example.invalid"}), + ], +) +def test_replay_keeps_portability_and_approval_restrictions(action, args): + with pytest.raises(MacroPreflightError): + validate_action( + MacroStep(schema_version=2, i=1, action=Action(action, args, "device")) + ) diff --git a/tests/unit/macro/test_secret_preflight.py b/tests/unit/macro/test_secret_preflight.py index a408448d5..9263f0dd8 100644 --- a/tests/unit/macro/test_secret_preflight.py +++ b/tests/unit/macro/test_secret_preflight.py @@ -1,259 +1,370 @@ -import asyncio +"""Credential errors are preflighted and never expose values.""" + +import json import traceback -from enum import Enum -from unittest.mock import AsyncMock import pytest -from pydantic import BaseModel - -from mobilerun.core.credentials import DictCredentials -from mobilerun.core.devices import Device, RecordingDevice -from mobilerun.core.extensions import Extension, device_action -from mobilerun.errors import ExtensionActionError -from mobilerun.macro import MacroStep -from mobilerun.macro.errors import MacroError, MacroMismatch -from mobilerun.macro.player import MacroPlayer +from mobilerun_core import Secret + +from mobilerun.core.credentials import CredentialPolicy, DictCredentials +from mobilerun.core.extensions import Extension, function +from mobilerun.core.runs import ActionRecording +from mobilerun.errors.base import is_value_safe +from mobilerun.macro import ( + MacroError, + MacroHandoffRefused, + MacroMismatch, + MacroPlayer, + MacroPreflightError, + MacroSecretError, + MacroStep, +) from mobilerun.models import Fingerprint -from tests.support.devices import MemoryDevice -from tests.support.macro import read_run_steps +from mobilerun.utils.credentials.masking import CredentialMasks +from tests.support.devices import FakeDriver, fake_device + + +@pytest.fixture +def anyio_backend(): + return "asyncio" + + +def _secret(name: str = "login", **selector: str | bool) -> MacroStep: + return MacroStep( + schema_version=2, + i=2, + action="extension_call", + args={"name": "vault.type_secret", "arguments": {"name": name, **selector}}, + ) + + +def _tap(*, before: Fingerprint | None = None) -> MacroStep: + return MacroStep( + schema_version=2, i=1, action="tap", args={"x": 10, "y": 20}, before=before + ) -@pytest.mark.parametrize("direct", [True, False]) +@pytest.mark.anyio @pytest.mark.parametrize( - "action,args", - [ - ("type_secret", {"name": "login", "protected": True}), - ("type_secret", {"name": " "}), - ("input_text", {"text": "[secret:login]"}), - ( - "extension_call", - { - "name": "vault.type_field", - "arguments": {"package": None, "field": "password"}, - }, - ), - ], + "case", ["no_vault", "missing", "protected", "pre_mask", "lookup_error"] ) -def test_credential_gate_precedes_all_device_actions(action, args, direct): - async def run(): - device = MemoryDevice() - device.tap = AsyncMock() - device._input_secret = AsyncMock(return_value=True) - await DictCredentials({"login": "dummy"}).bind(device) - player = MacroPlayer(device, delay_between_actions=0) - step = MacroStep(i=2, action=action, args=args) - macro = [ - MacroStep(i=1, action="tap", args={"x": 1, "y": 2}), - step, - MacroStep(i=3, action="tap", args={"x": 1, "y": 2}), - ] - with pytest.raises(MacroError, match="approval|package or name|redacted"): - if direct: - await player.play_step(step) - else: - await player.replay_macro(macro) - device.tap.assert_not_awaited() - device._input_secret.assert_not_awaited() - assert await player.replay_macro(macro, max_steps=1) - assert await player.replay_macro(macro, start_from_step=2) - - asyncio.run(run()) - - -class Mode(Enum): - FIRST = "first" - - -def test_unreadable_start_mask_aborts_without_observation_or_provider_error(): - from mobilerun.core.credentials import CredentialPolicy - - async def run(): - device = MemoryDevice() - vault = await DictCredentials({}).bind(device) - vault.policies = (CredentialPolicy("missing", mask_from_start=True),) - vault._list_credentials = AsyncMock(side_effect=ValueError("private-example")) - player = MacroPlayer(device) - player.state_provider = AsyncMock() - device.tap = AsyncMock() - macro = [ - MacroStep( - i=1, - action="tap", - args={"x": 1, "y": 2}, - before={"app": "settings", "activity": None, "elements": []}, +async def test_credential_preflight_stops_before_guard_or_action(case, caplog): + canary = "synthetic-private-resolver-error" + + class Vault(DictCredentials): + async def _list_credentials(self, package=None): + if case == "lookup_error": + raise ValueError(canary) + return await super()._list_credentials(package) + + driver = FakeDriver() + async with fake_device(driver=driver) as device: + vault = Vault({"login": "sample-secret"}, device=device) + if case == "protected": + vault.policies = (CredentialPolicy("login", requires_approval=True),) + elif case == "pre_mask": + vault.policies = (CredentialPolicy("absent", mask_from_start=True),) + player = MacroPlayer(device, extensions=[] if case == "no_vault" else [vault]) + with pytest.raises(MacroSecretError) as caught: + await player.replay_macro( + [ + _tap( + before=Fingerprint(app="something", activity=None, elements=()) + ), + _secret("missing" if case == "missing" else "login"), + ] ) + assert driver.calls == [] + assert canary not in "".join(traceback.format_exception(caught.value)) + assert canary not in caplog.text + + +@pytest.mark.anyio +@pytest.mark.parametrize("scope", ["flat", "package"]) +@pytest.mark.parametrize("missing", [False, True], ids=["present", "missing"]) +async def test_credential_replay_selects_only_the_recorded_scope(scope, missing): + flat_value = "synthetic-flat-credential" + package_value = "synthetic-package-credential" + driver = FakeDriver() + typed = [] + + async def input_probe(text: str, *, clear: bool, humanize: bool) -> bool: + typed.append({flat_value: "flat", package_value: "package"}.get(text)) + return True + + driver.input_text = input_probe + entries = {} + if not missing or scope != "flat": + entries["login"] = flat_value + if not missing or scope != "package": + entries["com.example"] = {"login": {"password": package_value}} + step = _secret(unscoped=True) if scope == "flat" else _secret(package="com.example") + async with fake_device(driver=driver) as device: + vault = DictCredentials(entries, device=device) + player = MacroPlayer(device, delay_between_actions=0, extensions=[vault]) + if missing: + with pytest.raises(MacroSecretError, match="Could not resolve.*step 2"): + await player.replay_macro([_tap(), step]) + assert driver.calls == [] + assert typed == [] + else: + assert await player.replay_macro([step]) + assert typed == [scope] + + +@pytest.mark.anyio +@pytest.mark.parametrize("target", ["other", "missing", "matching"]) +async def test_credential_replay_requires_the_same_device_handle(target): + other_driver, replay_driver = FakeDriver(), FakeDriver() + typed_on = [] + + async def type_on_other(text, **kwargs): + typed_on.append("other") + return True + + async def type_on_replay(text, **kwargs): + typed_on.append("replay") + return True + + other_driver.input_text = type_on_other + replay_driver.input_text = type_on_replay + async with ( + fake_device(driver=other_driver) as other_device, + fake_device(driver=replay_driver) as replay_device, + ): + assert other_device is not replay_device + assert other_device.device_id == replay_device.device_id + device = {"other": other_device, "missing": None, "matching": replay_device}[ + target ] - with pytest.raises(MacroError, match="prepare credential masking") as exc: - await player.replay_macro(macro) - assert exc.value.__context__ is None - player.state_provider.get_state.assert_not_awaited() - device.tap.assert_not_awaited() - - asyncio.run(run()) - - -def test_resolver_error_in_debug_traceback_never_contains_value(caplog): - async def run(): - device = MemoryDevice() - vault = await DictCredentials({}).bind(device) - vault._find = AsyncMock(side_effect=ValueError("private-canary")) - with pytest.raises(MacroMismatch) as exc: - await MacroPlayer(device).play_step( - MacroStep(i=1, action="type_secret", args={"name": "login"}) + vault = DictCredentials({"login": "synthetic-credential"}, device=device) + player = MacroPlayer(replay_device, delay_between_actions=0, extensions=[vault]) + if target == "matching": + assert await player.replay_macro([_tap(), _secret()]) + assert typed_on == ["replay"] + assert replay_driver.calls[0] == ("tap", (10, 20), {}) + else: + with pytest.raises(MacroSecretError, match="same device.*step 2"): + await player.replay_macro([_tap(), _secret()]) + assert typed_on == [] + assert replay_driver.calls == [] + assert other_driver.calls == [] + + +@pytest.mark.anyio +async def test_credential_preflight_rejects_conflicting_scope_selectors(): + driver = FakeDriver() + async with fake_device(driver=driver) as device: + vault = DictCredentials( + {"com.example": {"login": {"password": "synthetic-package-credential"}}}, + device=device, + ) + player = MacroPlayer(device, delay_between_actions=0, extensions=[vault]) + with pytest.raises(MacroSecretError, match="Invalid credential reference"): + await player.replay_macro( + [_tap(), _secret(package="com.example", unscoped=True)] ) - assert "private-canary" not in "".join(traceback.format_exception(exc.value)) - - with caplog.at_level("DEBUG", logger="mobilerun"): - asyncio.run(run()) - - -def test_provider_policy_blocks_package_only_and_named_extension_replay(): - from mobilerun.core.credentials import CredentialPolicy + assert driver.calls == [] + + +@pytest.mark.anyio +async def test_stepwise_replay_refuses_handoff_after_a_vault_row(): + async with fake_device() as device: + vault = DictCredentials({"login": "sample-secret"}, device=device) + player = MacroPlayer(device, state_timeout=0, extensions=[vault]) + with player.replay_scope(): + await player.play_step(_secret()) + assert player.tainted + assert CredentialMasks.current.get().active + with pytest.raises(MacroError, match="handoff refused"): + await player.play_step( + _tap(before=Fingerprint(app="wrong", activity=None, elements=())) + ) + assert CredentialMasks.current.get() is None + assert player.tainted + + +class Counter(Extension): + def __init__(self) -> None: + super().__init__(name="counter") + self.count = 0 + + @function(to_atomic=lambda _: pytest.fail("Replay must not expand atomics")) + async def add(self, amount: int) -> None: + """Add to the count.""" + self.count += amount + + +@pytest.mark.anyio +@pytest.mark.parametrize( + "name, amount", [("counter.add", 2), ("counter.add", "2"), ("missing.add", 2)] +) +async def test_canonical_extension_arguments_preflight(name, amount): + driver = FakeDriver() + counter = Counter() + row = MacroStep( + schema_version=2, + i=2, + action="extension_call", + args={"name": name, "arguments": {"amount": amount}}, + ) + async with fake_device(driver=driver) as device: + player = MacroPlayer(device, delay_between_actions=0, extensions=[counter]) + if name == "counter.add" and amount == 2: + assert await player.replay_macro([_tap(), row]) + assert counter.count == 2 + assert driver.calls == [("tap", (10, 20), {})] + else: + with pytest.raises(MacroPreflightError): + await player.replay_macro([_tap(), row]) + assert driver.calls == [] + assert counter.count == 0 + + +@pytest.mark.anyio +async def test_replay_records_extension_only_step(tmp_path): + counter = Counter() + step = MacroStep( + schema_version=2, + i=1, + action="extension_call", + args={"name": "counter.add", "arguments": {"amount": 3}}, + ) + async with fake_device() as device: + async with ActionRecording(device, runs_dir=tmp_path) as recorder: + player = MacroPlayer(device, extensions=[counter], recorder=recorder) + assert await player.replay_macro([step]) + recorder.finish("succeeded") + + assert counter.count == 3 + [line] = (recorder.run_dir / "steps.jsonl").read_text().splitlines() + row = json.loads(line) + assert row["action"] == "extension_call" + assert row["args"] == step.action.arguments + assert row["ok"] is True + + +@pytest.mark.anyio +async def test_replay_records_only_the_vault_reference(tmp_path): + canary = "synthetic-replay-audit-credential" + async with fake_device() as device: + vault = DictCredentials({"login": canary}, device=device) + async with ActionRecording(device, runs_dir=tmp_path) as recorder: + player = MacroPlayer(device, extensions=[vault], recorder=recorder) + await player.play_step(_secret()) + assert player.tainted + assert recorder.redactor.sensitive_ui + if canary in recorder.redactor.redact(f"echo: {canary}"): + pytest.fail("The recorder did not learn the replay mask", pytrace=False) + recorder.finish("succeeded") + + for path in recorder.run_dir.rglob("*"): + if path.is_file() and canary.encode() in path.read_bytes(): + pytest.fail("The run contains a plaintext credential", pytrace=False) + [line] = (recorder.run_dir / "steps.jsonl").read_text().splitlines() + row = json.loads(line) + assert row["action"] == "extension_call" + assert row["args"] == _secret().action.arguments + assert row["ok"] is True + + +@pytest.mark.anyio +@pytest.mark.parametrize("failure_phase", ["action", "after"]) +async def test_replay_refuses_handoff_after_a_non_vault_extension_types_secret( + tmp_path, failure_phase +): + async with fake_device() as device: + + class SecretInput(Extension): + @function + async def enter(self) -> bool: + await device.type_secret(Secret("synthetic-extension-secret")) + return failure_phase != "action" - async def run(): - device = MemoryDevice() - device.tap = AsyncMock() - vault = await DictCredentials( - {"pkg": {"card": {"password": "dummy"}}}, name="cards" - ).bind(device) - vault.policies = ( - CredentialPolicy("card", package="pkg", requires_approval=True), - ) step = MacroStep( - i=2, + schema_version=2, + i=7, action="extension_call", - args={ - "name": "cards.type_field", - "arguments": {"package": "pkg", "field": "password"}, - }, + args={"name": "input.enter", "arguments": {}}, + after=Fingerprint(app="wrong", activity=None, elements=()), ) - with pytest.raises(MacroError, match="approval"): - await MacroPlayer(device).replay_macro( - [MacroStep(i=1, action="tap", args={"x": 1, "y": 2}), step] + async with ActionRecording(device, runs_dir=tmp_path) as recorder: + player = MacroPlayer( + device, + extensions=[SecretInput(name="input")], + recorder=recorder, + state_timeout=0, ) - device.tap.assert_not_awaited() - - asyncio.run(run()) - + with pytest.raises( + MacroHandoffRefused, match=rf"\({failure_phase}\).*handoff refused" + ) as caught: + await player.play_step(step) + assert is_value_safe(caught.value) + assert vars(caught.value) == {"step_index": 7, "phase": failure_phase} + assert not isinstance(caught.value, MacroMismatch) + assert recorder.redactor.sensitive_ui + assert player.tainted + + +@pytest.mark.anyio +@pytest.mark.parametrize("already_tainted", [False, True]) +async def test_replay_checks_recorder_taint_before_a_guard_mismatch( + tmp_path, already_tainted +): + async with fake_device() as device: + async with ActionRecording(device, runs_dir=tmp_path) as recorder: + if already_tainted: + recorder.redactor.mark_sensitive() + player = MacroPlayer(device, recorder=recorder, state_timeout=0) + step = _tap(before=Fingerprint(app="wrong", activity=None, elements=())) + if already_tainted: + with pytest.raises( + MacroHandoffRefused, match=r"\(before\).*handoff refused" + ) as caught: + await player.play_step(step) + assert is_value_safe(caught.value) + assert vars(caught.value) == {"step_index": 1, "phase": "before"} + assert not isinstance(caught.value, MacroMismatch) + else: + with pytest.raises(MacroMismatch): + await player.play_step(step) + assert player.tainted is already_tainted + assert recorder.step_index == 0 + + +@pytest.mark.anyio +@pytest.mark.parametrize("blocked_by", ["preflight", "screen"]) +async def test_replay_does_not_record_an_extension_blocked_before_dispatch( + tmp_path, blocked_by +): + counter = Counter() + step = MacroStep( + schema_version=2, + i=1, + action="extension_call", + args={ + "name": "counter.add", + "arguments": {"amount": "invalid" if blocked_by == "preflight" else 3}, + }, + before=Fingerprint(app="wrong", activity=None, elements=()), + ) + async with fake_device() as device: + async with ActionRecording(device, runs_dir=tmp_path) as recorder: + player = MacroPlayer( + device, extensions=[counter], recorder=recorder, state_timeout=0 + ) + expected = ( + MacroPreflightError if blocked_by == "preflight" else MacroMismatch + ) + with pytest.raises(expected): + await player.play_step(step) + assert recorder.step_index == 0 + assert counter.count == 0 -def test_structural_guard_ignores_card_text_without_resolving_fields(): - from mobilerun.core.credentials import CredentialPolicy - async def run(): - device = MemoryDevice() - vault = await DictCredentials({}).bind(device) - vault.policies = (CredentialPolicy("login", mask_card_numbers=True),) - vault._find = AsyncMock( - side_effect=AssertionError("ordinary values must not be resolved") - ) - player = MacroPlayer(device, state_timeout=0) - player.state_provider = AsyncMock() - texts = ["prefix", "4111", "1111", "1111", "1111", "invalid 4111111111111112"] - player.state_provider.get_state.return_value = { - "phone_state": {"packageName": "settings"}, - "elements": [{"text": v} for v in texts], - } - pre = Fingerprint(app="settings", activity=None, elements=()) - assert await player.replay_macro( - [MacroStep(i=1, action="wait", args={"duration": 0}, before=pre)] - ) - vault._find.assert_not_awaited() - - asyncio.run(run()) - - -def test_prefilled_and_typed_values_ignored_by_structural_guards(caplog): - from mobilerun.core.credentials import CredentialPolicy - - async def run(): - device = MemoryDevice() - vault = await DictCredentials( - {"card": "4111111111111111", "login": "private-login"} - ).bind(device) - vault.policies = (CredentialPolicy("card", mask_from_start=True),) - player = MacroPlayer(device, state_timeout=0, delay_between_actions=0) - first = { - "phone_state": {"packageName": "settings"}, - "nodes": [{"text": "4111 1111 1111 1111"}], - } - later = { - "phone_state": {"packageName": "settings"}, - "nodes": [{"text": "private-login"}], - } - player.state_provider = AsyncMock() - player.state_provider.get_state.side_effect = [first, later] - device._input_secret = AsyncMock(return_value=True) - - guard = Fingerprint(app="settings", activity=None, elements=()) - macro = [ - MacroStep(i=1, action="type_secret", args={"name": "login"}, before=guard), - MacroStep(i=2, action="wait", args={"duration": 0}, before=guard), - ] - assert await player.replay_macro(macro) - assert first["nodes"][0]["text"] == "4111 1111 1111 1111" - assert later["nodes"][0]["text"] == "private-login" - device._input_secret.assert_awaited_once_with("private-login") - - with caplog.at_level("INFO"): - asyncio.run(run()) - assert "4111111111111111" not in caplog.text - assert "private-login" not in caplog.text - - -class Payload(BaseModel): - n: int - - -class InternalPayload(Payload): - private_note: str - - -class Mutator(Extension): - @device_action(sensitive_parameters=frozenset({"private"})) - async def mutate( - self, - device: Device, - values: list[int], - mode: Mode, - data: Payload, - private: str, - fail: bool = False, - ) -> None: - """Mutate arguments and optionally fail.""" - values.append(2) - data.n += 1 - if fail: - raise ValueError("failed") - - -def test_recorded_arguments_are_redacted_before_mutation_even_on_failure(tmp_path): - async def run(): - recorder = RecordingDevice(MemoryDevice(), runs_dir=tmp_path, capture="actions") - extension = await Mutator(name="test").bind(recorder) - args = ( - [1], - Mode.FIRST, - InternalPayload(n=1, private_note="not in action schema"), - "private-example", - ) - await extension.mutate(*args) - with pytest.raises(ExtensionActionError): - await extension.mutate(*args, fail=True) - succeeded, failed = read_run_steps(recorder.run_dir) - assert succeeded.ok and not failed.ok - assert succeeded.args["arguments"] == { - "values": [1], - "mode": "first", - "data": {"n": 1}, - "private": "***", - "fail": False, - } - assert failed.args["arguments"] == { - "values": [1], - "mode": "first", - "data": {"n": 2}, - "private": "***", - "fail": True, - } - - asyncio.run(run()) +@pytest.mark.anyio +async def test_replay_rejects_a_recorder_bound_to_a_different_device(tmp_path): + async with fake_device() as device, fake_device() as other_device: + recorder = ActionRecording(other_device, runs_dir=tmp_path) + with pytest.raises(ValueError, match="recorder belongs to a different device"): + MacroPlayer(device, recorder=recorder) diff --git a/tests/unit/macro/test_sms_preflight.py b/tests/unit/macro/test_sms_preflight.py index afb0c7a4c..43559f0a6 100644 --- a/tests/unit/macro/test_sms_preflight.py +++ b/tests/unit/macro/test_sms_preflight.py @@ -1,25 +1,127 @@ """Paid replay consent through the real CLI and an offline device.""" -import asyncio -from contextlib import asynccontextmanager +from importlib import import_module from unittest.mock import AsyncMock import pytest from click import Context from click.testing import CliRunner +from mobilerun_core import AsyncMobilerun, HitlDenied from mobilerun.cli.base import billing, safety -from mobilerun.cli.devices.base import options, selection -from mobilerun.core.extensions import Extension, action +from mobilerun.cli.base.billing import BillingConsentError +from mobilerun.cli.devices.base import selection +from mobilerun.cli.devices.utils import approval +from mobilerun.config.loader import ConfigLoader +from mobilerun.config.user_config import MobileConfig +from mobilerun.core.extensions import Extension, function from mobilerun.macro import MacroOperator from mobilerun.macro.cli import macro from mobilerun.macro.cli.replay import run_replay -from tests.support.devices import MemoryDevice +from tests.support.devices import FakeDriver, fake_device from tests.support.macro import write_macro +@pytest.mark.parametrize("flags", [(), ("--yes",), None]) +def test_replay_only_approves_automatic_portal_setup(monkeypatch, tmp_path, flags): + driver = FakeDriver(device_id="serial") + monkeypatch.setenv("MOBILERUN_MACRO_DIRECTORY", str(tmp_path)) + folder = tmp_path / "routine" + folder.mkdir() + write_macro(folder, rows=[{"i": 1, "action": "tap", "args": {"x": 10, "y": 20}}]) + monkeypatch.setattr(approval, "is_interactive", lambda: True) + prompt = AsyncMock(return_value=False) + monkeypatch.setattr(approval, "confirm_prompt_async", prompt) + monkeypatch.setattr(ConfigLoader, "load", lambda path: MobileConfig()) + requests = [] + + async def caller_gate(action, args): + requests.append((action, args)) + return action == "device.uninstall_app" + + class ReplayWithUninstall(MacroOperator): + async def _execute(self, device, instruction, **kwargs): + await device.uninstall_app("example.app") + return await super()._execute(device, instruction, **kwargs) + + class Core: + def __init__(self, *, hitl_gate, **kwargs): + self.gate = hitl_gate + self.local = self + + async def __aenter__(self): + return self + + async def __aexit__(self, *args): + pass + + async def ensure_portal_ready(self, serial, *, client_version): + action = "local.ensure_portal_ready" + args = dict( + serial=serial, + package="com.mobilerun.portal", + client_version=client_version, + touches_accessibility=True, + will_install=False, + ) + assert not await self.gate(action, {**args, "serial": "other"}) + assert await self.gate(action, args) + + async def connect(self, serial, **kwargs): + if flags is not None: + assert not await self.gate("device.delete_file", {"device_id": serial}) + return fake_device(driver=driver, hitl_gate=self.gate) + + monkeypatch.setattr(selection, "AsyncMobilerun", Core) + if flags is None: + run_replay( + ReplayWithUninstall, + path="routine", + target="serial", + device_kind="android", + delay=0, + start_from=1, + max_steps=None, + debug=False, + dry_run=False, + state_timeout=0, + state_threshold=0.85, + config_path=None, + hitl_gate=caller_gate, + yes=True, + ) + assert requests == [ + ("device.uninstall_app", {"device_id": "serial", "app_id": "example.app"}) + ] + assert driver.calls == [ + ("uninstall_app", ("example.app",), {}), + ("tap", (10, 20), {}), + ] + else: + execute = MacroOperator._execute + + async def verify_strict_gate(operator, device, instruction, **kwargs): + with pytest.raises(HitlDenied, match="uninstall_app"): + await device.uninstall_app("example.app") + return await execute(operator, device, instruction, **kwargs) + + monkeypatch.setattr(MacroOperator, "_execute", verify_strict_gate) + result = CliRunner().invoke( + macro, ["replay", "routine", "serial", "--delay", "0", *flags] + ) + if not flags: + assert result.exit_code == 1 + assert "not approved" in result.output + assert driver.calls == [] + prompt.assert_awaited_once() + return + assert result.exit_code == 0, (result.output, result.exception) + assert driver.calls == [("tap", (10, 20), {})] + prompt.assert_not_awaited() + + class Outbox(Extension): - """Offline provider with the same action shape as a bound phone number.""" + """Offline provider with the same tool shape as a phone number.""" role = "phone_number" @@ -27,7 +129,7 @@ def __init__(self, name): super().__init__(name=name) self.messages = [] - @action() + @function async def send(self, to: str, text: str) -> None: """Record the message without sending it.""" self.messages.append((to, text)) @@ -36,12 +138,10 @@ async def send(self, to: str, text: str) -> None: @pytest.fixture def replay_sms(tmp_path, monkeypatch, request): name = getattr(request, "param", "outbox") - device = MemoryDevice(cloud_id="offline-cloud") - device.tap = AsyncMock() + driver = FakeDriver() outbox = Outbox(name) if name != "outbox": outbox.role = None - asyncio.run(outbox.bind(device)) monkeypatch.setenv("MOBILERUN_MACRO_DIRECTORY", str(tmp_path)) folder = tmp_path / "routine" folder.mkdir() @@ -62,8 +162,18 @@ def replay_sms(tmp_path, monkeypatch, request): ], ], ) - monkeypatch.setattr(selection, "connect_target", AsyncMock(return_value=device)) - monkeypatch.setattr(billing, "billing_prompt_is_interactive", lambda: True) + + async def open_fake(run, target, **kwargs): + return fake_device(driver=driver) + + def cli_operator(**kwargs): + return MacroOperator(**(kwargs | {"extensions": [outbox]})) + + monkeypatch.setattr(AsyncMobilerun, "connect", open_fake) + monkeypatch.setattr( + import_module("mobilerun.macro.cli.replay"), "MacroOperator", cli_operator + ) + monkeypatch.setattr(billing, "can_prompt", lambda _stream: True) monkeypatch.setenv("MOBILERUN_BILLING", "paid") confirm = AsyncMock(return_value=False) monkeypatch.setattr(safety, "confirm_prompt_async", confirm) @@ -82,7 +192,7 @@ def invoke(*flags, parent=None, explicit_target=True): parent=parent, ) - return invoke, device, outbox, confirm + return invoke, driver, outbox, confirm @pytest.mark.parametrize("replay_sms", ["outbox", "sms", "other"], indirect=True) @@ -95,7 +205,7 @@ def test_declining_paid_sms_replays_nothing(replay_sms): confirm.assert_awaited_once_with( "Send 2 SMS with paid billing (charges may apply)?", default=False ) - device.tap.assert_not_awaited() + assert device.calls == [] assert outbox.messages == [] @@ -103,7 +213,7 @@ def test_accepting_paid_sms_replays_with_one_prompt(replay_sms): invoke, device, outbox, confirm = replay_sms async def accept(message, *, default): - device.tap.assert_not_awaited() + assert device.calls == [] assert outbox.messages == [] return True @@ -114,43 +224,43 @@ async def accept(message, *, default): confirm.assert_awaited_once_with( "Send 2 SMS with paid billing (charges may apply)?", default=False ) - device.tap.assert_awaited_once_with(10, 20) + assert device.calls == [("tap", (10, 20), {})] assert outbox.messages == [("+15550100000", "first"), ("+15550100000", "second")] def test_yes_replays_paid_sms_without_a_terminal(replay_sms, monkeypatch): invoke, device, outbox, confirm = replay_sms - monkeypatch.setattr(billing, "billing_prompt_is_interactive", lambda: False) + monkeypatch.setattr(billing, "can_prompt", lambda _stream: False) result = invoke("--yes") assert result.exit_code == 0, result.output confirm.assert_not_awaited() - device.tap.assert_awaited_once_with(10, 20) + assert device.calls == [("tap", (10, 20), {})] assert len(outbox.messages) == 2 def test_noninteractive_paid_sms_requires_yes_before_any_step(replay_sms, monkeypatch): invoke, device, outbox, confirm = replay_sms - monkeypatch.setattr(billing, "billing_prompt_is_interactive", lambda: False) + monkeypatch.setattr(billing, "can_prompt", lambda _stream: False) result = invoke() assert result.exit_code == 1, result.output assert "pass --yes" in result.output confirm.assert_not_awaited() - device.tap.assert_not_awaited() + assert device.calls == [] assert outbox.messages == [] def test_custom_sms_in_included_mode_still_requires_consent(replay_sms, monkeypatch): invoke, device, outbox, confirm = replay_sms monkeypatch.setenv("MOBILERUN_BILLING", "included") - monkeypatch.setattr(billing, "billing_prompt_is_interactive", lambda: False) + monkeypatch.setattr(billing, "can_prompt", lambda _stream: False) result = invoke() assert result.exit_code == 1, result.output assert "pass --yes" in result.output confirm.assert_not_awaited() - device.tap.assert_not_awaited() + assert device.calls == [] assert outbox.messages == [] @@ -159,21 +269,16 @@ def test_sms_refusal_never_discovers_or_opens_device( replay_sms, monkeypatch, interactive ): invoke, device, _, _ = replay_sms - discoveries = AsyncMock( - return_value=[ - options.DiscoveredDevice("offline-cloud", "cloud", None, "ready", "android") - ] - ) + discoveries = AsyncMock(side_effect=AssertionError("unexpected discovery")) opened = [] - @asynccontextmanager - async def fake_open(target): + async def fake_open(run, target, **kwargs): opened.append(target) - yield device + return fake_device(driver=device) - monkeypatch.setattr(options, "discover_devices", discoveries) - monkeypatch.setattr(options.DeviceTarget, "open", fake_open) - monkeypatch.setattr(billing, "billing_prompt_is_interactive", lambda: interactive) + monkeypatch.setattr(AsyncMobilerun, "list_devices", discoveries) + monkeypatch.setattr(AsyncMobilerun, "connect", fake_open) + monkeypatch.setattr(billing, "can_prompt", lambda _stream: interactive) for explicit_target in (True, False): result = invoke(explicit_target=explicit_target) assert result.exit_code == 1, result.output @@ -190,7 +295,7 @@ def test_agent_handoff_replay_keeps_the_sms_preflight(replay_sms): def handoff(*, provider, model, **options): handed_off.append(True) - run_replay(MacroOperator, **options) + run_replay(MacroOperator, extensions=[outbox], **options) parent.meta["macro_agent_handoff"] = handoff result = invoke("--on-mismatch", "agent", parent=parent) @@ -199,7 +304,7 @@ def handoff(*, provider, model, **options): assert "Cancelled." in result.output confirm.assert_awaited_once() assert handed_off == [] - device.tap.assert_not_awaited() + assert device.calls == [] assert outbox.messages == [] @@ -213,23 +318,22 @@ def test_replay_uses_the_recording_checked_before_open( def handoff(*, provider, model, **options): assert options["path"] == str(path) - run_replay(MacroOperator, **options) + run_replay(MacroOperator, extensions=[outbox], **options) parent.meta["macro_agent_handoff"] = handoff - @asynccontextmanager - async def fake_open(target): + async def fake_open(run, target, **kwargs): replacement = "\n".join(path.read_text().splitlines()[1:]) + "\n" path.write_text(replacement) (path.parent / "v2.jsonl").write_text(replacement) - yield device + return fake_device(driver=device) - monkeypatch.setattr(options.DeviceTarget, "open", fake_open) + monkeypatch.setattr(AsyncMobilerun, "connect", fake_open) result = invoke("--max-steps", "1", *flags, parent=parent) assert result.exit_code == 0, result.output confirm.assert_not_awaited() - device.tap.assert_awaited_once_with(10, 20) + assert device.calls == [("tap", (10, 20), {})] assert outbox.messages == [] @@ -239,7 +343,7 @@ def test_replay_without_sms_in_selected_steps_does_not_prompt(replay_sms): assert result.exit_code == 0, result.output confirm.assert_not_awaited() - device.tap.assert_awaited_once_with(10, 20) + assert device.calls == [("tap", (10, 20), {})] assert outbox.messages == [] @@ -252,7 +356,7 @@ def test_paid_sms_confirmation_counts_only_selected_steps(replay_sms): confirm.assert_awaited_once_with( "Send 1 SMS with paid billing (charges may apply)?", default=False ) - device.tap.assert_not_awaited() + assert device.calls == [] assert outbox.messages == [("+15550100000", "second")] @@ -263,5 +367,148 @@ def test_dry_run_with_paid_sms_does_not_prompt_or_replay(replay_sms): assert result.exit_code == 0, result.output assert "extension_call [redacted]" in result.output confirm.assert_not_awaited() - device.tap.assert_not_awaited() + assert device.calls == [] + assert outbox.messages == [] + + +@pytest.fixture +def direct_replay(replay_sms, monkeypatch): + _, device, outbox, confirm = replay_sms + opened = [] + + async def fake_open(run, target, **kwargs): + opened.append(target) + return fake_device(driver=device) + + monkeypatch.setattr(AsyncMobilerun, "connect", fake_open) + + def invoke(**overrides): + arguments = dict( + path="routine", + target="offline-cloud", + device_kind="cloud", + delay=0, + start_from=1, + max_steps=None, + debug=False, + dry_run=False, + state_timeout=0, + state_threshold=0.85, + config_path=None, + ) + run_replay(MacroOperator, extensions=[outbox], **(arguments | overrides)) + + return invoke, opened, outbox, confirm + + +def test_direct_replay_requires_consent_before_opening(direct_replay, monkeypatch): + invoke, opened, outbox, confirm = direct_replay + monkeypatch.setattr(billing, "can_prompt", lambda _stream: False) + + with pytest.raises(BillingConsentError, match="without confirmation"): + invoke() + + assert opened == [] + assert outbox.messages == [] + confirm.assert_not_awaited() + + +def test_direct_replay_accepts_explicit_yes(direct_replay, monkeypatch): + invoke, opened, outbox, confirm = direct_replay + monkeypatch.setattr(billing, "can_prompt", lambda _stream: False) + + invoke(yes=True) + + assert len(opened) == 1 + assert len(outbox.messages) == 2 + confirm.assert_not_awaited() + + +@pytest.mark.parametrize("accept", [True, False]) +def test_direct_replay_prompts_for_selected_sms_only(direct_replay, accept): + invoke, opened, outbox, confirm = direct_replay + + async def answer(message, *, default): + assert opened == [] + return accept + + confirm.side_effect = answer + if accept: + invoke(start_from=3, max_steps=1) + assert len(opened) == 1 + assert outbox.messages == [("+15550100000", "second")] + else: + with pytest.raises(BillingConsentError, match="Cancelled"): + invoke(start_from=3, max_steps=1) + assert opened == [] + assert outbox.messages == [] + confirm.assert_awaited_once_with( + "Send 1 SMS with paid billing (charges may apply)?", default=False + ) + + +@pytest.mark.parametrize("max_steps", [0, 1]) +def test_direct_replay_without_selected_sms_does_not_prompt(direct_replay, max_steps): + invoke, opened, outbox, confirm = direct_replay + + invoke(max_steps=max_steps) + + assert len(opened) == 1 + assert outbox.messages == [] + confirm.assert_not_awaited() + + +@pytest.mark.parametrize("selection", [{"start_from": 0}, {"max_steps": -1}]) +def test_direct_replay_rejects_invalid_range_before_opening(direct_replay, selection): + invoke, opened, _, confirm = direct_replay + + with pytest.raises(ValueError, match="start_from|max_steps"): + invoke(**selection) + + assert opened == [] + confirm.assert_not_awaited() + + +def test_direct_replay_rejects_an_operator_macro_file_override(direct_replay, tmp_path): + invoke, opened, outbox, confirm = direct_replay + safe_file = tmp_path / "safe.jsonl" + safe_file.write_text( + '{"schema_version":2,"i":1,"action":"wait","args":{"seconds":0}}\n' + ) + + with pytest.raises(ValueError, match="path.*macro_file"): + invoke(path=str(safe_file), macro_file="routine") + + assert opened == [] + assert outbox.messages == [] + confirm.assert_not_awaited() + + +@pytest.mark.parametrize("change", ["file", "range"]) +def test_agent_handoff_cannot_reuse_consent_for_different_rows( + replay_sms, tmp_path, change +): + invoke, device, outbox, confirm = replay_sms + parent = Context(macro) + path = tmp_path / "routine" / "v1.jsonl" + replacement = path.with_name("v2.jsonl") + + def handoff(*, provider, model, **options): + if change == "file": + replacement.write_bytes(path.read_bytes()) + options["path"] = str(replacement) + else: + options["start_from"] = 3 + run_replay(MacroOperator, extensions=[outbox], **options) + + parent.meta["macro_agent_handoff"] = handoff + confirm.side_effect = [True, False] + result = invoke( + "--on-mismatch", "agent", "--start-from", "2", "--max-steps", "1", parent=parent + ) + + assert result.exit_code == 1, result.output + assert "Cancelled." in result.output + assert confirm.await_count == 2 + assert device.calls == [] assert outbox.messages == [] diff --git a/tests/unit/models/test_values.py b/tests/unit/models/test_values.py index 704871b23..377a350bc 100644 --- a/tests/unit/models/test_values.py +++ b/tests/unit/models/test_values.py @@ -2,16 +2,13 @@ import importlib from dataclasses import FrozenInstanceError from datetime import datetime, timedelta, timezone -from types import SimpleNamespace from unittest.mock import AsyncMock, patch import pytest from pydantic import ValidationError -from mobilerun.clients.cloud import devices from mobilerun.config.settings import Settings -from mobilerun.errors import BillingError -from mobilerun.models import Billing, Plan +from mobilerun.models import Billing from mobilerun.utils.timestamps import to_api_timestamp @@ -44,7 +41,7 @@ async def poll(fetch, **kwargs): with ( patch( - "mobilerun.core.mailbox.cloud.mailboxes.otp", new_callable=AsyncMock + "mobilerun.clients.cloud.mailboxes.Mailboxes.otp", new_callable=AsyncMock ) as otp, patch("mobilerun.core.mailbox.cloud.wait_for_code", side_effect=poll), ): @@ -58,35 +55,20 @@ async def poll(fetch, **kwargs): assert after.endswith("Z") -def test_file_models_are_immutable_value_objects() -> None: - from mobilerun.models.files import DeviceFile, WorkspaceFile +def test_workspace_file_is_an_immutable_value_object() -> None: + from mobilerun.models import WorkspaceFile now = datetime.now(timezone.utc) workspace = WorkspaceFile("id", "photo.jpg", "image/jpeg", 12, now) - device = DeviceFile("/sdcard/photo.jpg", "photo.jpg", 12, now) - assert workspace.name == device.name - assert workspace.size_bytes == device.size_bytes + assert workspace.name == "photo.jpg" + assert workspace.size_bytes == 12 with pytest.raises(FrozenInstanceError): workspace.name = "changed" # type: ignore[misc] - with pytest.raises(FrozenInstanceError): - device.path = "changed" # type: ignore[misc] - - -def test_location_is_a_shared_value_model() -> None: - from mobilerun.models import Location - from mobilerun.models.location import Location as LocationModel - - assert Location is LocationModel - assert Location(latitude=52.52, longitude=13.405).model_dump() == { - "latitude": 52.52, - "longitude": 13.405, - } @pytest.mark.parametrize( ("name", "module"), [ - ("ProxyStatus", "proxy"), ("RunRecord", "recording"), ("RunStep", "recording"), ("Fingerprint", "recording"), @@ -95,7 +77,8 @@ def test_location_is_a_shared_value_model() -> None: ("RunStatus", "recording"), ("Actor", "recording"), ("CredentialMetadata", "credentials"), - ("UIElement", "ui"), + ("ExecutionResult", "results"), + ("WebhookEndpoint", "webhooks"), ("PaymentSnapshot", "checkout"), ], ) @@ -105,27 +88,19 @@ def test_public_value_model_identity(name: str, module: str) -> None: assert getattr(models, name) is getattr(home, name) -def test_existing_core_exports_keep_model_identity() -> None: - from mobilerun.core.proxy import ProxyStatus - from mobilerun.core.state import UIElement - from mobilerun.models import ProxyStatus as ModelProxyStatus - from mobilerun.models import UIElement as ModelUIElement - - assert ProxyStatus is ModelProxyStatus - assert UIElement is ModelUIElement - - def test_run_schema_serializes_utc_and_round_trips_json_values() -> None: from mobilerun.models import DeviceInfo, Fingerprint, RunRecord, RunStep t = datetime(2026, 1, 1, 2, tzinfo=timezone(timedelta(hours=2))) record = RunRecord( + schema_version=2, run_id="a1", kind="recording", device=DeviceInfo(platform="android", identifier="local"), started_at=t, ) step = RunStep( + schema_version=2, i=1, started_at=t, finished_at=t + timedelta(seconds=1), @@ -140,6 +115,8 @@ def test_run_schema_serializes_utc_and_round_trips_json_values() -> None: assert step.model_dump(mode="json")["started_at"] == "2026-01-01T00:00:00Z" assert step.model_dump(mode="json")["finished_at"] == "2026-01-01T00:00:01Z" assert RunStep.model_validate_json(step.model_dump_json()) == step + assert step.action.started_at == step.started_at + assert step.model_dump_json().count("started_at") == 1 @pytest.mark.parametrize( @@ -150,6 +127,7 @@ def test_run_step_rejects_invalid_input(override) -> None: now = datetime.now(timezone.utc) values = dict( + schema_version=2, i=1, started_at=now, finished_at=now, @@ -162,31 +140,6 @@ def test_run_step_rejects_invalid_input(override) -> None: RunStep.model_validate(values | override) -@pytest.mark.parametrize("plan", [Plan.MINUTE, "minute"]) -@pytest.mark.parametrize("billing", [Billing.PAID, "paid"]) -def test_public_enums_and_strings(billing, plan): - create = AsyncMock(return_value="created") - asyncio.run( - devices.create( - billing=billing, - plan=plan, - proxy={"connect": {"id": "existing"}}, - client=SimpleNamespace(devices=SimpleNamespace(create=create)), - ) - ) - assert create.call_args.kwargs["billing"] == "minute" - - -@pytest.mark.parametrize("billing,plan", [("wrong", "auto"), ("paid", "wrong")]) -def test_invalid_policy_values(billing, plan): - with pytest.raises(BillingError, match="create.*given.*requires"): - asyncio.run( - devices.create( - billing=billing, plan=plan, proxy={"connect": {"id": "existing"}} - ) - ) - - def test_billing_setting_is_enum(monkeypatch): monkeypatch.setenv("MOBILERUN_BILLING", "paid") assert Settings().MOBILERUN_BILLING is Billing.PAID diff --git a/tests/unit/sandbox/conftest.py b/tests/unit/sandbox/conftest.py new file mode 100644 index 000000000..e2009f973 --- /dev/null +++ b/tests/unit/sandbox/conftest.py @@ -0,0 +1,23 @@ +"""Include the extracted deployment components in shared fake injection.""" + +import pytest + +from mobilerun.sandbox.deployments import executor, initial, planner, recovery +from mobilerun.sandbox.helpers import deployment +from tests.support import sandbox_fixtures + + +@pytest.fixture(autouse=True) +def patch_deployment_components(monkeypatch): + monkeypatch.setattr( + sandbox_fixtures, + "_SANDBOX_MODULES", + ( + *sandbox_fixtures._SANDBOX_MODULES, + executor, + initial, + planner, + recovery, + deployment, + ), + ) diff --git a/tests/unit/sandbox/test_cloud_transport.py b/tests/unit/sandbox/test_cloud_transport.py index 823b950ec..8fa01c3db 100644 --- a/tests/unit/sandbox/test_cloud_transport.py +++ b/tests/unit/sandbox/test_cloud_transport.py @@ -12,6 +12,8 @@ from mobilerun.errors.cloud import BillingError, CloudAPIError from mobilerun.models.billing import Billing from mobilerun.sandbox import clients +from mobilerun.sandbox.clients.helpers import transport as sdk_transport +from mobilerun.sandbox.errors import FlowCapabilityError, FlowStagingError DOCUMENT = { "version": 1, @@ -52,10 +54,65 @@ def flow_sdk(): @pytest.mark.anyio async def test_catalog_uses_stable_step_name_and_all_pages(): client = flow_sdk() - assert await clients._catalog_entry_id(client, "functions.run") == "catalog" + assert await clients.prepare_action_payloads( + DOCUMENT, billing=Billing.NO_COMMERCE, client=client + ) == [ + { + "catalog_entry_id": "catalog", + "name": "action", + "params": {"functionId": "fn"}, + } + ] assert client.workflows.action_catalog.list.await_count == 2 +@pytest.mark.anyio +async def test_catalog_resolves_sdk_models_without_serializing_the_page(monkeypatch): + from mobilerun_sdk.types.workflows.action_catalog_list_response import ( + ActionCatalogListResponse, + ) + + response = ActionCatalogListResponse.model_validate( + { + "items": [ + { + "id": "catalog", + "deviceFree": True, + "method": "legacy-name", + "name": "Run a function", + "provider": "mobilerun", + "service": "sandbox_api", + "stepName": "functions.run", + } + ], + "pagination": { + "hasNext": False, + "hasPrev": False, + "page": 1, + "pageSize": 100, + "pages": 1, + "total": 1, + }, + } + ) + client = flow_sdk() + client.workflows.action_catalog.list = AsyncMock(return_value=response) + + def no_dump(*args, **kwargs): + pytest.fail("Catalog lookup should read the typed page and items directly") + + monkeypatch.setattr(ActionCatalogListResponse, "model_dump", no_dump) + assert await clients.prepare_action_payloads( + DOCUMENT, billing=Billing.NO_COMMERCE, client=client + ) == [ + { + "catalog_entry_id": "catalog", + "name": "action", + "params": {"functionId": "fn"}, + } + ] + + @pytest.mark.anyio @pytest.mark.parametrize( "step,count,reason", @@ -71,8 +128,12 @@ async def test_catalog_entry_errors_are_specific_and_value_safe(step, count, rea "pagination": {"hasNext": False}, } ) - with pytest.raises(clients.FlowCapabilityError) as caught: - await clients._catalog_entry_id(client, step) + with pytest.raises(FlowCapabilityError) as caught: + await clients.prepare_action_payloads( + {**DOCUMENT, "steps": [{**DOCUMENT["steps"][0], "uses": step}]}, + billing=Billing.NO_COMMERCE, + client=client, + ) assert str(caught.value) == f"Workflow action catalog: found {reason} for {step}" assert caught.value.code == "request_failed" and is_value_safe(caught.value) @@ -88,7 +149,7 @@ async def test_disable_is_free_and_uses_update(): def test_enable_rejects_before_factory(monkeypatch): factory = AsyncMock() - monkeypatch.setattr(clients, "cloud_client", factory) + monkeypatch.setattr(sdk_transport, "cloud_client", factory) with pytest.raises(BillingError): clients.enable_flow("flow", billing=Billing.NO_COMMERCE) factory.assert_not_called() @@ -111,6 +172,32 @@ async def test_create_document_stages_and_verifies_disabled(): w.flows.retrieve.assert_awaited_once_with("f") +@pytest.mark.anyio +async def test_create_document_stages_schedule_and_explicit_devices(): + client = flow_sdk() + w = client.workflows + w.triggers = SimpleNamespace(create=AsyncMock(return_value={"data": {"id": "t"}})) + w.actions = SimpleNamespace(create=AsyncMock(return_value={"data": {"id": "a"}})) + w.flows.create = AsyncMock(return_value={"data": {"id": "f"}}) + w.flows.retrieve = AsyncMock(return_value={"data": {"id": "f", "enabled": False}}) + doc = { + **DOCUMENT, + "on": {"schedule": {"cron": "0 9 * * *", "timezone": "Europe/Berlin"}}, + "devices": [], + } + + await clients.create_document(doc, "key", billing=Billing.PAID, client=client) + + w.triggers.create.assert_awaited_once_with( + activation="schedule", + name=DOCUMENT["name"], + schedule_rule={"type": "cron", "expression": "0 9 * * *"}, + timezone="Europe/Berlin", + idempotency_key="key:trigger", + ) + assert w.flows.create.await_args.kwargs["device_ids"] == [] + + @pytest.mark.anyio async def test_create_document_stages_file_actions_and_delivery(): client = flow_sdk() @@ -187,8 +274,8 @@ async def test_update_flow_delivery_forwards_value_and_key(delivery): @pytest.mark.anyio async def test_unsupported_document_fails_before_client_creation(monkeypatch): factory = AsyncMock() - monkeypatch.setattr(clients, "cloud_client", factory) - with pytest.raises(clients.FlowCapabilityError): + monkeypatch.setattr(sdk_transport, "cloud_client", factory) + with pytest.raises(FlowCapabilityError): await clients.create_document({"unknown": True}, "key", billing=Billing.PAID) factory.assert_not_called() @@ -204,7 +291,7 @@ async def test_action_failure_preserves_trigger_for_recovery(failure): if failure == "transport": action.side_effect = httpx.ConnectError("secret") client.workflows.actions = SimpleNamespace(create=action) - with pytest.raises(clients.FlowStagingError) as error: + with pytest.raises(FlowStagingError) as error: await clients.create_document( DOCUMENT, "key", billing=Billing.PAID, client=client ) @@ -267,16 +354,13 @@ async def test_paginated_reads_and_execution_order(): @pytest.mark.anyio -async def test_mutations_forward_typed_parameters_and_verify_replacement(): +async def test_workflow_adapters_forward_typed_parameters(): w = SimpleNamespace( flows=SimpleNamespace( validate_document=AsyncMock(return_value={"data": {"valid": True}}), - retrieve=AsyncMock(return_value={"data": {"enabled": False}}), - replace_document=AsyncMock(return_value={"data": {"id": "f"}}), actions=SimpleNamespace(replace=AsyncMock(return_value={"data": []})), ), triggers=SimpleNamespace( - create=AsyncMock(return_value={"data": {"id": "t"}}), update=AsyncMock(return_value={"data": {"id": "t"}}), fire=AsyncMock(return_value={"data": {"id": "i"}}), ), @@ -285,11 +369,6 @@ async def test_mutations_forward_typed_parameters_and_verify_replacement(): c = SimpleNamespace(workflows=w) kw = {"billing": Billing.PAID, "client": c} assert await clients.validate_document({"name": "x"}, **kw) == {"valid": True} - assert await clients.replace_document("f", {"name": "x"}, "k", **kw) == {"id": "f"} - assert w.flows.retrieve.await_count == 2 - assert await clients.create_trigger( - {"activation": "custom", "name": "t"}, "k", **kw - ) == {"id": "t"} assert await clients.update_trigger("t", {"name": "updated"}, "k", **kw) == { "id": "t" } @@ -306,21 +385,6 @@ async def test_mutations_forward_typed_parameters_and_verify_replacement(): w.triggers.fire.assert_awaited_once_with("t", payload={"n": 1}, idempotency_key="k") -@pytest.mark.anyio -async def test_replace_rejects_enabled_flow(): - w = SimpleNamespace( - flows=SimpleNamespace( - retrieve=AsyncMock(return_value={"data": {"enabled": True}}), - replace_document=AsyncMock(), - ) - ) - with pytest.raises(clients.FlowCapabilityError): - await clients.replace_document( - "f", {}, "k", billing=Billing.PAID, client=SimpleNamespace(workflows=w) - ) - w.flows.replace_document.assert_not_awaited() - - @pytest.mark.anyio @pytest.mark.parametrize("resource", ["flow", "action", "trigger"]) async def test_deletes_are_free_and_ignore_response(resource): @@ -346,9 +410,7 @@ async def test_deletes_are_free_and_ignore_response(resource): ("delete_trigger", ("t",), False), ("validate_document", ({},), False), ("create_document", (DOCUMENT, "k"), True), - ("replace_document", ("f", {}, "k"), True), ("enable_flow", ("f",), True), - ("create_trigger", ({"activation": "custom", "name": "t"}, "k"), True), ("update_trigger", ("t", {"name": "t"}, "k"), True), ("create_action", ({"catalog_entry_id": "c", "name": "a"}, "k"), True), ("replace_flow_actions", ("f", [], "k"), True), @@ -388,7 +450,6 @@ def method(): retrieve=method(), retrieve_document=method(), validate_document=method(), - replace_document=method(), create=method(), update=method(), delete=method(), @@ -418,7 +479,7 @@ async def test_billing_matrix(name, args, paid, monkeypatch): c = managed_flow_sdk() factory = Mock(return_value=c.manager) - monkeypatch.setattr(clients, "cloud_client", factory) + monkeypatch.setattr(sdk_transport, "cloud_client", factory) fn = getattr(clients, name) with pytest.raises(TypeError): fn(*args) @@ -441,7 +502,7 @@ async def test_client_ownership(name, args, paid, monkeypatch): await getattr(clients, name)(*args, billing=Billing.PAID, client=injected) assert not injected.closed owned = managed_flow_sdk() - monkeypatch.setattr(clients, "cloud_client", lambda **kwargs: owned.manager) + monkeypatch.setattr(sdk_transport, "cloud_client", lambda **kwargs: owned.manager) await getattr(clients, name)(*args, billing=Billing.PAID) assert owned.closed @@ -452,7 +513,7 @@ async def test_cloud_error_is_sanitized_and_owned_client_closed(monkeypatch): c = managed_flow_sdk() c.workflows.flows.list.side_effect = httpx.ConnectError("secret-url") - monkeypatch.setattr(clients, "cloud_client", lambda **kwargs: c.manager) + monkeypatch.setattr(sdk_transport, "cloud_client", lambda **kwargs: c.manager) with pytest.raises(CloudConnectionError) as error: await clients.list_flows(billing=Billing.NO_COMMERCE) assert "secret-url" not in str(error.value) @@ -490,9 +551,7 @@ async def test_execution_list_fetches_all_pages_then_limits_and_uses_descending_ "delete_trigger": "triggers.delete", "validate_document": "flows.validate_document", "create_document": "action_catalog.list", - "replace_document": "flows.retrieve", "enable_flow": "flows.update", - "create_trigger": "triggers.create", "update_trigger": "triggers.update", "create_action": "actions.create", "replace_flow_actions": "flows.actions.replace", @@ -510,7 +569,7 @@ async def test_client_ownership_on_transport_failure(name, args, paid, monkeypat method = getattr(method, part) method.side_effect = httpx.ConnectError("secret-url") - monkeypatch.setattr(clients, "cloud_client", Mock(return_value=c.manager)) + monkeypatch.setattr(sdk_transport, "cloud_client", Mock(return_value=c.manager)) with pytest.raises(CloudAPIError) as error: await getattr(clients, name)( *args, billing=Billing.PAID, client=c if injected else None @@ -524,7 +583,7 @@ async def test_client_ownership_on_transport_failure(name, args, paid, monkeypat async def test_malformed_verification_preserves_all_created_ids(bad): c = managed_flow_sdk() c.workflows.flows.retrieve.return_value = {"data": bad} - with pytest.raises(clients.FlowStagingError) as error: + with pytest.raises(FlowStagingError) as error: await clients.create_document(DOCUMENT, "key", billing=Billing.PAID, client=c) assert error.value.trigger_id == "id" assert error.value.action_ids == ("id",) @@ -549,7 +608,7 @@ async def test_staging_failure_preserves_each_created_id(failure_stage): c.workflows.flows.retrieve.side_effect = httpx.ConnectError("private") c.workflows.actions.create.side_effect = action_results doc = {**DOCUMENT, "steps": DOCUMENT["steps"] * 2} - with pytest.raises(clients.FlowStagingError) as error: + with pytest.raises(FlowStagingError) as error: await clients.create_document(doc, "key", billing=Billing.PAID, client=c) assert error.value.trigger_id == "t" assert error.value.action_ids == tuple(["a0", "a1"][:failure_stage]) @@ -558,7 +617,6 @@ async def test_staging_failure_preserves_each_created_id(failure_stage): def test_flow_errors_are_safe_rendering(): from mobilerun.errors.base import is_value_safe - from mobilerun.sandbox.errors import FlowCapabilityError, FlowStagingError assert is_value_safe( FlowCapabilityError(operation="Stage flow", code="request_failed") @@ -713,7 +771,7 @@ def test_get_source(): @pytest.mark.parametrize("billing", [None, "invalid"]) def test_invalid_billing_rejected_before_factory(monkeypatch, name, args, billing): factory = Mock() - monkeypatch.setattr(clients, "cloud_client", factory) + monkeypatch.setattr(sdk_transport, "cloud_client", factory) with pytest.raises(BillingError): asyncio.run(getattr(clients, name)(*args, billing=billing)) factory.assert_not_called() @@ -728,7 +786,7 @@ def test_paid_creations_reject_lower_modes_before_factory( monkeypatch, name, args, billing ): factory = Mock() - monkeypatch.setattr(clients, "cloud_client", factory) + monkeypatch.setattr(sdk_transport, "cloud_client", factory) with pytest.raises(BillingError): asyncio.run(getattr(clients, name)(*args, billing=billing)) factory.assert_not_called() @@ -743,7 +801,7 @@ def test_owned_client_closed_and_transport_errors_sanitized(monkeypatch, fails): "secret-url", request=httpx.Request("GET", "https://secret.test/token") ) owned = Owned(sdk) - monkeypatch.setattr(clients, "cloud_client", Mock(return_value=owned)) + monkeypatch.setattr(sdk_transport, "cloud_client", Mock(return_value=owned)) if fails: with pytest.raises(Exception) as caught: asyncio.run(clients.delete_function("f", billing=Billing.NO_COMMERCE)) @@ -772,7 +830,7 @@ def test_run_logs_uses_separate_unauthenticated_client(monkeypatch): ) real = httpx.AsyncClient monkeypatch.setattr( - clients.httpx, + httpx, "AsyncClient", lambda **kwargs: real(transport=transport, **kwargs), ) @@ -793,7 +851,7 @@ def test_run_logs_http_error_does_not_expose_signed_url(monkeypatch): ) real = httpx.AsyncClient monkeypatch.setattr( - clients.httpx, + httpx, "AsyncClient", lambda **kwargs: real(transport=transport, **kwargs), ) @@ -831,7 +889,7 @@ def test_run_logs_other_httpx_errors_are_sanitized(monkeypatch, error_type): ) real = httpx.AsyncClient monkeypatch.setattr( - clients.httpx, + httpx, "AsyncClient", lambda **kwargs: real(transport=transport, **kwargs), ) @@ -865,7 +923,7 @@ def sdk_method(sdk, path): @pytest.mark.parametrize("name,args,path", ALL_OPERATIONS) def test_billing_required_before_factory(monkeypatch, name, args, path): factory = Mock() - monkeypatch.setattr(clients, "cloud_client", factory) + monkeypatch.setattr(sdk_transport, "cloud_client", factory) with pytest.raises(TypeError): getattr(clients, name)(*args) factory.assert_not_called() @@ -965,7 +1023,7 @@ def test_logs_owns_both_clients_and_accepts_all_billing( "data": {"url": "https://signed.example/log?token=secret"} } owned = Owned(sdk) - monkeypatch.setattr(clients, "cloud_client", Mock(return_value=owned)) + monkeypatch.setattr(sdk_transport, "cloud_client", Mock(return_value=owned)) seen = [] def respond(request): @@ -981,7 +1039,7 @@ def make_client(**kwargs): http_clients.append(downloader) return downloader - monkeypatch.setattr(clients.httpx, "AsyncClient", make_client) + monkeypatch.setattr(httpx, "AsyncClient", make_client) if fail_download: with pytest.raises(Exception) as caught: @@ -1010,7 +1068,7 @@ def respond(request): transport = httpx.MockTransport(respond) actual = httpx.AsyncClient monkeypatch.setattr( - clients.httpx, + httpx, "AsyncClient", lambda **kwargs: actual(transport=transport, **kwargs), ) diff --git a/tests/unit/sandbox/test_deployment.py b/tests/unit/sandbox/test_deployment.py index 8b5cc5248..4c15dfebb 100644 --- a/tests/unit/sandbox/test_deployment.py +++ b/tests/unit/sandbox/test_deployment.py @@ -10,8 +10,8 @@ from mobilerun_functions.schema import output_schema from pydantic import BaseModel, ConfigDict, Field, SecretStr -from mobilerun.core.webhooks import WebhookEndpoint from mobilerun.errors.cloud import BillingRequired, CloudResourceNotFound +from mobilerun.models import WebhookEndpoint from mobilerun.sandbox import cleanup as sandbox_cleanup from mobilerun.sandbox import deployment as deploy from mobilerun.sandbox import documents as sandbox_documents @@ -24,6 +24,7 @@ SandboxDeploymentConflict, SandboxDeploymentError, ) +from mobilerun.sandbox.helpers import deployment as deployment_helpers from mobilerun.sandbox.models import Artifact, CloudDeclaration, OwnershipReceipt from tests.support.sandbox_fakes import ProcessInterrupted from tests.support.sandbox_fixtures import setup_deploy as setup_deploy @@ -367,8 +368,8 @@ def test_sdk_declined_deploy_writes_no_receipt_and_makes_no_cloud_calls( ): from functools import partial - from mobilerun.clients.cloud.billing import with_billing_retry from mobilerun.sandbox import app + from mobilerun.utils.billing.retry import with_billing_retry monkeypatch.setattr(app, "package", lambda _: env.artifact) prompt = AsyncMock(return_value=False) @@ -656,7 +657,9 @@ async def test_same_source_not_ready_never_activates(env, status, monkeypatch): owned(env) env.fake.get_version.return_value = {"version": 1, "status": status} times = iter([0.0, 121.0]) - monkeypatch.setattr(deploy.time, "monotonic", lambda: next(times, 121.0)) + monkeypatch.setattr( + deployment_helpers.time, "monotonic", lambda: next(times, 121.0) + ) with pytest.raises(SandboxDeploymentError): await deploy.deploy_file(env.path) env.fake.enable_flow.assert_not_awaited() @@ -802,7 +805,7 @@ async def test_pending_initial_intent_cannot_be_changed(initial_cloud, monkeypat @pytest.mark.anyio async def test_ready_response_after_inspection_deadline_is_rejected(env, monkeypatch): clock = [0.0] - monkeypatch.setattr(deploy.time, "monotonic", lambda: clock[0]) + monkeypatch.setattr(deployment_helpers.time, "monotonic", lambda: clock[0]) async def late(*args, **kwargs): clock[0] = 121.0 @@ -810,7 +813,7 @@ async def late(*args, **kwargs): env.fake.get_version.side_effect = late with pytest.raises(SandboxDeploymentError, match="timed out"): - await deploy._wait_ready("f", 1, deploy.Billing.PAID, owned(env)) + await deployment_helpers.wait_ready("f", 1, deploy.Billing.PAID, owned(env)) @pytest.mark.anyio @@ -827,11 +830,13 @@ async def bounded(awaitable, timeout): async def slow(*args, **kwargs): await asyncio.Event().wait() - monkeypatch.setattr(deploy.asyncio, "wait_for", bounded) + monkeypatch.setattr(deployment_helpers.asyncio, "wait_for", bounded) env.fake.get_version.side_effect = slow # The outer test guard fails fast if production forgets to bound the request. with pytest.raises(SandboxDeploymentError, match="timed out"): - await original(deploy._wait_ready("f", 1, deploy.Billing.PAID, owned(env)), 0.1) + await original( + deployment_helpers.wait_ready("f", 1, deploy.Billing.PAID, owned(env)), 0.1 + ) assert len(budgets) == 1 and 0 < budgets[0] <= 120 diff --git a/tests/unit/sandbox/test_execution.py b/tests/unit/sandbox/test_execution.py index 91c1f7b83..1c9351e4a 100644 --- a/tests/unit/sandbox/test_execution.py +++ b/tests/unit/sandbox/test_execution.py @@ -230,10 +230,12 @@ async def test_invocation_lookup_and_recent_runs_use_paginated_boundary( ) @asynccontextmanager - async def client(*args): + async def client(**kwargs): yield sdk - monkeypatch.setattr(clients, "_sdk", client) + from mobilerun.sandbox.clients.helpers import transport + + monkeypatch.setattr(transport, "cloud_client", client) monkeypatch.setattr(clients, "list_executions", LIST_EXECUTIONS) assert ( await sandbox_execution.resolve_execution( @@ -706,7 +708,7 @@ async def test_missing_function_step_never_fires_or_enables(remote): def test_sandbox_extra_declares_plain_validator_without_optional_formats(): project = tomllib.loads((REPO_ROOT / "pyproject.toml").read_text()) - assert "jsonschema>=4,<5" in project["project"]["optional-dependencies"]["sandbox"] + assert "jsonschema>=4" in project["project"]["optional-dependencies"]["sandbox"] @pytest.mark.anyio diff --git a/tests/unit/sandbox/test_packaging.py b/tests/unit/sandbox/test_packaging.py index 3c54a5b32..0396699fa 100644 --- a/tests/unit/sandbox/test_packaging.py +++ b/tests/unit/sandbox/test_packaging.py @@ -11,7 +11,8 @@ import mobilerun.sandbox as sandbox from mobilerun.sandbox.errors import SandboxDeclarationError, SandboxPackagingError -from mobilerun.sandbox.packaging import package, read_declaration, transform +from mobilerun.sandbox.helpers.source import transform +from mobilerun.sandbox.packaging import package, read_declaration from tests.support.sandbox_fixtures import patch_sandbox @@ -562,8 +563,8 @@ def test_nonliteral_declaration_rejected(tmp_path: Path, decorator: str): def test_inspection_failure_stops_package(tmp_path, monkeypatch): - from mobilerun.sandbox import clients as functions from mobilerun.sandbox import packaging + from mobilerun.sandbox.clients.helpers import transport from mobilerun.sandbox.errors import SandboxPackagingError source = tmp_path / "main.py" @@ -576,7 +577,7 @@ def boundary(*args, **kwargs): calls.append("cloud") raise AssertionError("cloud boundary called") - monkeypatch.setattr(functions, "cloud_client", boundary) + monkeypatch.setattr(transport, "cloud_client", boundary) def fail(_source, *, scheduled): calls.append("inspect") @@ -604,7 +605,7 @@ def test_inspection_uses_runtime_timeout_and_cleans_up(monkeypatch): import sys from types import SimpleNamespace - from mobilerun.sandbox import packaging + from mobilerun.sandbox.helpers import inspection from mobilerun.sandbox.settings import RUNTIME_MODULE seen = [] @@ -621,12 +622,12 @@ def run(command, **kwargs): ) monkeypatch.setattr( - packaging, + inspection, "get_sandbox_settings", lambda: SimpleNamespace(MOBILERUN_SANDBOX_INSPECTION_TIMEOUT=3), ) - monkeypatch.setattr(packaging.subprocess, "run", run) - assert packaging.inspect_source("trusted source")["ok"] is True + monkeypatch.setattr(inspection.subprocess, "run", run) + assert inspection.inspect_source("trusted source")["ok"] is True assert not seen[0].exists() @@ -644,16 +645,16 @@ def test_inspection_failures_are_sanitized(monkeypatch, stdout, returncode): import traceback from types import SimpleNamespace - from mobilerun.sandbox import packaging from mobilerun.sandbox.errors import SandboxPackagingError + from mobilerun.sandbox.helpers import inspection monkeypatch.setattr( - packaging.subprocess, + inspection.subprocess, "run", lambda *a, **kw: SimpleNamespace(stdout=stdout, returncode=returncode), ) with pytest.raises(SandboxPackagingError) as error: - packaging.inspect_source("trusted source") + inspection.inspect_source("trusted source") assert "secret" not in str(error.value) assert "secret" not in "".join(traceback.format_exception(error.value)) @@ -680,8 +681,8 @@ def test_digest_includes_runtime_and_exact_generated_bytes(tmp_path): def test_timeout_error_and_cleanup_are_sanitized(monkeypatch): import subprocess - from mobilerun.sandbox import packaging from mobilerun.sandbox.errors import SandboxPackagingError + from mobilerun.sandbox.helpers import inspection paths = [] @@ -689,9 +690,9 @@ def run(command, **kwargs): paths.append(Path(command[-1])) raise subprocess.TimeoutExpired(command, 1, output="secret") - monkeypatch.setattr(packaging.subprocess, "run", run) + monkeypatch.setattr(inspection.subprocess, "run", run) with pytest.raises(SandboxPackagingError) as error: - packaging.inspect_source("trusted source") + inspection.inspect_source("trusted source") assert "secret" not in str(error.value) assert not paths[0].exists() diff --git a/tests/unit/sandbox/test_playground.py b/tests/unit/sandbox/test_playground.py index 85dbf1340..444279fc5 100644 --- a/tests/unit/sandbox/test_playground.py +++ b/tests/unit/sandbox/test_playground.py @@ -165,13 +165,16 @@ def start_app(self, app): def ui(self): return SimpleNamespace( - nodes=self.screens[self.stack[-1] if self.stack else self.page] + elements=tuple( + SimpleNamespace(**{"hidden": False, "offscreen": False, **node}) + for node in self.screens[self.stack[-1] if self.stack else self.page] + ) ) def tap_node(self, node, *, humanize): assert not humanize - assert node in self.ui().nodes - row = node["resource_id"].removeprefix("story:") + assert node in self.ui().elements + row = node.resource_id.removeprefix("story:") self.actions.append(("tap", row)) if row == self.failed_story: raise RuntimeError("unavailable") @@ -295,7 +298,7 @@ def test_collects_device_snapshot_and_opens_requested_app(tmp_path): device = Mock(device_id="fake-device") device.screenshot.return_value = str(shot) device.ui.return_value = SimpleNamespace( - nodes=[{"text": "Hello"}, {"text": ""}, {"text": "World"}] + elements=[SimpleNamespace(text=text) for text in ("Hello", "", "World")] ) log = Mock() ctx = SimpleNamespace( @@ -393,7 +396,9 @@ def run(app="com.android.settings"): device.screenshot.return_value = str(path) device.current_app_id.return_value = app device.ui.return_value = SimpleNamespace( - nodes=[{"text": "Settings"}, {"text": ""}, {"text": "Network"}] + elements=[ + SimpleNamespace(text=text) for text in ("Settings", "", "Network") + ] ) ctx = SimpleNamespace(device=lambda: device, log=Mock(), partial=Mock()) return run_settings(ctx), device, ctx diff --git a/tests/unit/sandbox/test_receipt_recovery.py b/tests/unit/sandbox/test_receipt_recovery.py index 9513819c0..58c46e4ec 100644 --- a/tests/unit/sandbox/test_receipt_recovery.py +++ b/tests/unit/sandbox/test_receipt_recovery.py @@ -76,7 +76,9 @@ def store(tmp_path, s=None, name="../unsafe"): def test_scope_uses_cloud_client_key_resolver_and_no_secret(monkeypatch): - monkeypatch.setattr(sandbox_receipts, "resolve_cloud_api_key", lambda: "sensitive") + monkeypatch.setattr( + sandbox_receipts.LoginStore, "resolve_api_key", lambda self: "sensitive" + ) monkeypatch.setattr( sandbox_receipts, "get_settings", @@ -86,7 +88,9 @@ def test_scope_uses_cloud_client_key_resolver_and_no_secret(monkeypatch): assert s.origin == "https://a/" assert s.account_id == hashlib.sha256(b"sensitive").hexdigest() assert "sensitive" not in repr(s) - monkeypatch.setattr(sandbox_receipts, "resolve_cloud_api_key", lambda: None) + monkeypatch.setattr( + sandbox_receipts.LoginStore, "resolve_api_key", lambda self: None + ) with pytest.raises(SandboxDeploymentError, match="credentials"): sandbox_receipts.current_scope() @@ -214,9 +218,7 @@ def test_windows_lock_backend_is_selected_and_released(tmp_path, monkeypatch): locking=lambda fd, mode, size: calls.append((mode, size)), ) monkeypatch.setitem(sys.modules, "msvcrt", fake) - monkeypatch.setattr( - sandbox_receipts, "_windows_platform", lambda: True, raising=False - ) + monkeypatch.setattr(sys, "platform", "win32") with store(tmp_path).lock(): assert calls == [(1, 1)] assert calls == [(1, 1), (2, 1)] @@ -936,7 +938,9 @@ async def get_source(fid, version, **kwargs): def test_url_aliases_recover_ownership_or_fail_closed(tmp_path, monkeypatch): base = "https://example.test/v1" - monkeypatch.setattr(sandbox_receipts, "resolve_cloud_api_key", lambda: "key") + monkeypatch.setattr( + sandbox_receipts.LoginStore, "resolve_api_key", lambda self: "key" + ) monkeypatch.setenv("MOBILERUN_SANDBOX_DIRECTORY", str(tmp_path)) def scoped(url): diff --git a/tests/unit/sandbox/test_remote_calls.py b/tests/unit/sandbox/test_remote_calls.py index 9c0d6e879..3b9b66e2d 100644 --- a/tests/unit/sandbox/test_remote_calls.py +++ b/tests/unit/sandbox/test_remote_calls.py @@ -17,7 +17,6 @@ ) import mobilerun.sandbox as sandbox -from mobilerun.clients.cloud.billing import with_billing_retry from mobilerun.models.billing import Billing from mobilerun.sandbox.errors import ( SandboxDeclarationError, @@ -25,6 +24,7 @@ SandboxRunError, SandboxRunTimeout, ) +from mobilerun.utils.billing.retry import with_billing_retry from tests.support.sandbox_fixtures import Input, Output from tests.support.sandbox_fixtures import backend as backend @@ -54,12 +54,12 @@ def test_lazy_lookup_refreshes_after_redeploy(backend): @pytest.mark.parametrize("operation", ["fire", "enable", "call"]) def test_remote_mutations_retry_with_paid(backend, monkeypatch, operation): - from mobilerun.sandbox import app from mobilerun.sandbox.billing import require_paid + from mobilerun.sandbox.handles import remote prompt = AsyncMock(return_value=True) monkeypatch.setattr( - app, + remote, "with_billing_retry", partial(with_billing_retry, prompt=prompt, is_interactive=lambda: True), ) diff --git a/tests/unit/sandbox/test_routine_runtime.py b/tests/unit/sandbox/test_routine_runtime.py index 508667d89..02538cbd0 100644 --- a/tests/unit/sandbox/test_routine_runtime.py +++ b/tests/unit/sandbox/test_routine_runtime.py @@ -13,7 +13,7 @@ def test_billing_precedence(monkeypatch): from mobilerun.models.billing import Billing - from mobilerun.sandbox.models import resolve_billing + from mobilerun.sandbox.billing import resolve_billing monkeypatch.delenv("MOBILERUN_BILLING", raising=False) assert resolve_billing(None) == Billing.PAID diff --git a/tests/unit/sandbox/test_sandbox_cli.py b/tests/unit/sandbox/test_sandbox_cli.py index 2597a1950..3406618ba 100644 --- a/tests/unit/sandbox/test_sandbox_cli.py +++ b/tests/unit/sandbox/test_sandbox_cli.py @@ -9,10 +9,11 @@ import click import pytest from click.testing import CliRunner +from mobilerun_core import DeviceDescriptor from mobilerun.cli.app import cli from mobilerun.cli.base import menu, safety -from mobilerun.cli.devices.base import discovery +from mobilerun.cli.devices.utils.connection import discovery from mobilerun.models.billing import Billing from mobilerun.sandbox import packaging from mobilerun.sandbox.models import Artifact, DeploymentReceipt, Endpoint @@ -478,7 +479,7 @@ def test_endpoint_text_uses_required_schema_fields_and_never_prints_api_key( def test_paid_picker_prompts_stay_off_json_stdout( pick_phone, selected, script, receipt, monkeypatch ): - from mobilerun.sandbox.cli import commands + from mobilerun.sandbox.cli import deploy as deploy_cli path = script("schedule='0 12 * * *'") monkeypatch.setattr(menu, "is_interactive", lambda: True) @@ -491,8 +492,8 @@ def prompt_file(message): monkeypatch.setattr(menu, "text_prompt", prompt_file) discovery.discover_devices.side_effect = None discovery.discover_devices.return_value = [ - discovery.DiscoveredDevice("cloud-id", "cloud", "Cloud Phone", "ready", None), - discovery.DiscoveredDevice("local-id", "local", "Local Phone", None, None), + DeviceDescriptor("cloud-id", "cloud", "android", "Cloud Phone", "ready"), + DeviceDescriptor("local-id", "local-android-adb", "android", "Local Phone"), ] async def pick(message, choices): @@ -501,7 +502,7 @@ async def pick(message, choices): return choices[0 if pick_phone else 1].value if selected else None picker = AsyncMock(side_effect=pick) - monkeypatch.setattr(commands, "select_prompt_async", picker) + monkeypatch.setattr(deploy_cli, "select_prompt_async", picker) async def confirm(message, *, default): click.echo(message) @@ -581,7 +582,7 @@ def stub_flow_previews(): def test_deploy_uses_same_artifact_after_file_changes( script, receipt, monkeypatch, device ): - from mobilerun.sandbox.cli import commands + from mobilerun.sandbox.cli import deploy as deploy_cli path = script("schedule='0 12 * * *'") monkeypatch.setattr(menu, "is_interactive", lambda: True) @@ -604,7 +605,7 @@ async def pick_device(*, as_json, yes): path.write_text(path.read_text().replace("'demo'", "'changed'")) return device, device is None - monkeypatch.setattr(commands, "_pick_device", pick_device) + monkeypatch.setattr(deploy_cli, "_pick_device", pick_device) monkeypatch.setattr(safety, "confirm_prompt_async", prompt) monkeypatch.setattr(packaging, "package", inspect) result = BillingRunner().invoke( diff --git a/tests/unit/skills/test_distribution.py b/tests/unit/skills/test_distribution.py index 3feab90cc..33c906139 100644 --- a/tests/unit/skills/test_distribution.py +++ b/tests/unit/skills/test_distribution.py @@ -1,7 +1,6 @@ """Skill distribution: release archives, catalog discovery and safe installation.""" import json -import os import shutil import subprocess import sys @@ -86,19 +85,32 @@ def test_skills_wheel_and_sdist_include_full_tree_and_installed_cli(tmp_path): capture_output=True, text=True, ) - env = os.environ.copy() - env["PYTHONPATH"] = sysconfig.get_paths()["purelib"] - command = "import sys,sysconfig; sys.path.insert(0,sysconfig.get_paths()['purelib']); from mobilerun.cli.app import cli; cli()" + # Reuse the test environment's dependencies, including editable installs, + # but load Mobilerun itself from the wheel installed in the child venv. + command = """ +import site +import sys +import sysconfig +from pathlib import Path + +site.addsitedir(sys.argv.pop(1)) +import mobilerun + +assert Path(mobilerun.__file__).parent.parent == Path(sysconfig.get_path("purelib")) +from mobilerun.cli.app import cli + +cli() +""" def run(*args): - return subprocess.run( - [str(python), "-c", command, *args], + result = subprocess.run( + [str(python), "-I", "-c", command, sysconfig.get_path("purelib"), *args], cwd=tmp_path, - env=env, - check=True, capture_output=True, text=True, ) + assert result.returncode == 0, result.stderr + return result entries = json.loads(run("skills", "list", "--json").stdout) assert {entry["source"] for entry in entries} == {"skills"} diff --git a/tests/unit/smoke/README.md b/tests/unit/smoke/README.md index 39a42787a..1b90a0d44 100644 --- a/tests/unit/smoke/README.md +++ b/tests/unit/smoke/README.md @@ -4,17 +4,52 @@ Opt in with `pytest --smoke tests/unit/smoke`; normal `pytest` skips this direct Start with `pytest --smoke tests/unit/smoke/test_00_requirements.py -s` for a value-free requirements table. Use `-m smoke_device` for a local emulator (no service cost), `-m smoke_cloud` for cloud operations, or `-m smoke_llm` for local LLM calls. Cloud operations and tasks may incur charges; local LLM calls may consume provider tokens. Running all smoke tests invokes both. Select individual tests only after reviewing their source and prerequisites. -Set `MOBILERUN_SMOKE_SERIAL` (default `emulator-5554`), `MOBILERUN_SMOKE_CLOUD_DEVICE_ID` (default Tester 1), `MOBILERUN_SMOKE_LLM_PROVIDER` (default `openai_oauth`). Set `MOBILERUN_API_KEY`. The emulator must be online with Mobilerun Portal installed; the cloud device must be ready. +Install `.[dev]` in `.venv` (add `sandbox` for the function checks). Set +`MOBILERUN_SMOKE_SERIAL` (default `emulator-5554`), +`MOBILERUN_SMOKE_CLOUD_DEVICE_ID` (default Tester 1), and +`MOBILERUN_SMOKE_LLM_PROVIDER` (default `openai_oauth`) as needed. Source +`~/.agent-env` for `MOBILERUN_API_KEY`. Set `MOBILERUN_CLOUD_BASE_URL` when +targeting a non-default cloud environment. The emulator must be online with +Mobilerun Portal installed for Portal-dependent cases; the borrowed cloud +phone must be ready. For the cloud-device creation cases that request it, set +`MOBILERUN_SMOKE_CONNECT_PROXY_ID` to an existing active Connect proxy. The test harness redirects HOME and the config directory before importing application code. Secrets are restored in memory only for individual smoke tests. OAuth profiles, when needed, are copied read-only from the real config into a temporary directory; the original is never opened for writing. Tests can change device UI and end on the home screen. -TODO: Add local/cloud pool ordering, agent/context provider, skills and remaining CLI/macro coverage. +Device tests use `mobilerun_core.AsyncMobilerun` and `AsyncDevice`. The CLI +tests use explicit commands such as `mobilerun device cloud status` and +`mobilerun device screen screenshot`; the generic device action catalogue is gone. `test_cloud_devices.py::test_cloud_info_and_wait_ready` and `test_cloud_devices.py::test_cloud_rejects_local_secrets` do not create a phone or run a task; check your account pricing before running cloud operations. `test_cloud_devices.py::test_paid_cloud_create_lifecycle` creates a billable -phone and resets it; collect only until explicitly approved. The typed-output -task smoke also checks lazy trajectory and screenshot reads. +phone and resets it; `test_auto_create_and_terminate` also creates a billable +minute phone. Collect only until explicitly approved. The typed-output +task smoke uses `CloudTaskOperator(client=..., extensions=...)` and checks +trajectory and screenshot reads by task ID after `do`. The `do`/`expect` +pair submits two paid tasks. The timeout and cancellation cases each submit +one paid task and check that it stopped. All use the borrowed phone, return +its UI to Home, and close the connection without terminating it. + +## Cloud resources and vaults + +- Read-only inventory, capacity, and borrowed-resource tests do not purchase + resources. Mailbox message reads need no phone. Cloud vault CRUD manages a + uniquely named test credential and deletes it in `finally`. The shared + `ai.mobilerun.smoke.test` vault package is retained (created if missing). +- The minute-phone, phone-number attachment, and create-with-proxy cases + create disposable minute phones. They pass a borrowed Connect proxy value to + `create_cloud`; closing the owned phone terminates it. No case purchases or + releases a Connect proxy. The optional German-proxy switch requires a + different active residential proxy; the dedicated create-with-proxy case + skips when no active German residential proxy is available. +- Number rental (and SMS when enabled) and mailbox rental are paid. A freshly + rented number is explicitly attached and detached on the disposable phone; + the number is closed before the phone. Rented mailboxes are closed without + using a phone. Provider cancellation can take effect at period end. +- The local proxy case skips an already configured emulator and clears only + its own test setting. Local vault tests type a test value on the borrowed + emulator; only a named reference goes into the recording/macro. ## Webhook CLI @@ -81,4 +116,9 @@ matches, and do not assume re-running pytest will clean up a prior UUID. ## Cleanup -Tests can change device UI. Review each test’s `finally` cleanup before running; after interruption, check the cloud dashboard for newly created phones and other resources, and release any that should not be retained. Existing devices are not automatically deleted. Never assume an interrupted run cleaned up. +Review each test’s cleanup before running. After an interruption or cleanup +failure, inspect recorded resource IDs, the core create request key if +reported, and any sandbox receipt. Verify ownership in the target account +before releasing anything. A lost create response can leave ownership +unconfirmed; never delete based on a name alone. Resources supplied by ID are +borrowed, not released. Never assume an interrupted run cleaned up. diff --git a/tests/unit/smoke/conftest.py b/tests/unit/smoke/conftest.py index 6aa608320..f41d78893 100644 --- a/tests/unit/smoke/conftest.py +++ b/tests/unit/smoke/conftest.py @@ -1,19 +1,20 @@ """Isolated fixtures for explicitly requested real-service checks.""" import asyncio -import importlib.util import json import os -import shutil -import subprocess +from pathlib import Path +from typing import Protocol import pytest +from mobilerun_core import AsyncMobilerun, ConnectProxyRef, HitlGate -SERIAL = os.getenv("MOBILERUN_SMOKE_SERIAL", "emulator-5554") -CLOUD_ID = os.getenv( - "MOBILERUN_SMOKE_CLOUD_DEVICE_ID", "86f8d29f-9f59-4e42-ba02-1043c721774e" -) -PROVIDER = os.getenv("MOBILERUN_SMOKE_LLM_PROVIDER", "openai_oauth") +from mobilerun.config.settings import get_settings +from tests.support.smoke_settings import CLOUD_ID, PROVIDER, SERIAL + + +class CloudRunFactory(Protocol): + def __call__(self, *, hitl_gate: HitlGate | None = None) -> AsyncMobilerun: ... @pytest.fixture(autouse=True) @@ -21,100 +22,129 @@ def android_sdk_for_smoke(monkeypatch, real_android_sdk, isolate_user_configurat monkeypatch.setenv("ANDROID_HOME", real_android_sdk) +@pytest.hookimpl(tryfirst=True) def pytest_collection_modifyitems(items): for item in items: - if "/smoke/" in str(item.path): + if item.path.is_relative_to(Path(__file__).parent): item.add_marker(pytest.mark.smoke) -def check_requirements(auth_path): - checks = {} - key = os.getenv("MOBILERUN_API_KEY") - checks["Cloud API key present"] = bool(key) - checks["mobilerun_sdk importable"] = ( - importlib.util.find_spec("mobilerun_sdk") is not None - ) - checks["Cloud API key accepted"] = False - checks["Cloud device exists"] = False - checks["Cloud device ready"] = False - if key and checks["mobilerun_sdk importable"]: - - async def lookup(): - from mobilerun_sdk import AsyncMobilerun - - from mobilerun.config.settings import get_settings - - async with AsyncMobilerun( - api_key=key, - base_url=get_settings().MOBILERUN_CLOUD_BASE_URL, - timeout=15.0, - ) as client: - return await client.devices.list() - - try: - response = asyncio.run(lookup()) - checks["Cloud API key accepted"] = True - item = next( - (item for item in response.items if str(item.id) == CLOUD_ID), None - ) - checks["Cloud device exists"] = item is not None - checks["Cloud device ready"] = item is not None and item.state == "ready" - except Exception: - pass - adb = shutil.which("adb") - checks["adb on PATH"] = bool(adb) - checks["Local serial online"] = False - if adb: - try: - result = subprocess.run( - [adb, "-s", SERIAL, "get-state"], - capture_output=True, - text=True, - timeout=10, - ) - checks["Local serial online"] = ( - result.returncode == 0 and result.stdout.strip() == "device" - ) - except (OSError, subprocess.TimeoutExpired): - pass - if PROVIDER.endswith("_oauth"): - try: - profile = json.loads(auth_path.read_text()) - slot = { - "openai_oauth": "openaiOauth", - "anthropic_oauth": "anthropicOauth", - "gemini_oauth": "geminiOauth", - "grok_oauth": "grokOauth", - }.get(PROVIDER) - checks["LLM credentials"] = bool(slot and profile.get(slot)) - except (OSError, ValueError): - checks["LLM credentials"] = False - else: - checks["LLM credentials"] = bool(os.getenv(PROVIDER.upper() + "_API_KEY")) +@pytest.fixture +def cloud_run() -> CloudRunFactory: + def open_run(*, hitl_gate: HitlGate | None = None) -> AsyncMobilerun: + return AsyncMobilerun( + base_url=get_settings().MOBILERUN_CLOUD_BASE_URL, hitl_gate=hitl_gate + ) + + return open_run + + +def cloud_key_present() -> bool: + return bool(os.getenv("MOBILERUN_API_KEY")) + + +@pytest.fixture +def cloud_key(real_env) -> None: + if not cloud_key_present(): + pytest.skip("MOBILERUN_API_KEY is not set") + + +@pytest.fixture +def cloud_connect_proxy(cloud_key) -> ConnectProxyRef: + proxy_id = os.getenv("MOBILERUN_SMOKE_CONNECT_PROXY_ID") + if not proxy_id: + pytest.skip("MOBILERUN_SMOKE_CONNECT_PROXY_ID is not set") + return ConnectProxyRef(proxy_id) + + +@pytest.fixture +def cloud_requirements(real_env, cloud_run: CloudRunFactory) -> dict[str, bool]: + checks = { + "Cloud API key present": cloud_key_present(), + "Cloud API key accepted": False, + "Cloud device exists": False, + "Cloud device ready": False, + } + if not checks["Cloud API key present"]: + return checks + + async def lookup() -> None: + async with cloud_run() as run: + async with asyncio.timeout(15): + devices = await run.list_cloud_devices() + checks["Cloud API key accepted"] = True + device = next((item for item in devices if item.device_id == CLOUD_ID), None) + checks["Cloud device exists"] = device is not None + checks["Cloud device ready"] = device is not None and device.state == "ready" + + try: + asyncio.run(lookup()) + except Exception: + # Report facts only; exception chains can include transport details. + pass return checks @pytest.fixture -def requirements(real_env, copied_auth_profiles): - return check_requirements(copied_auth_profiles) +def local_android_ids() -> list[str]: + async def lookup() -> list[str]: + async with AsyncMobilerun() as run: + async with asyncio.timeout(10): + return [ + device.device_id + for device in await run.list_devices(scope="local") + if device.info().backend == "local-android-adb" + ] + + try: + return asyncio.run(lookup()) + except Exception: + return [] @pytest.fixture -def cloud_ready(requirements): - if not all( - requirements[name] - for name in ( - "Cloud API key present", - "mobilerun_sdk importable", - "Cloud API key accepted", - "Cloud device exists", - "Cloud device ready", - ) - ): +def local_requirements(local_android_ids: list[str]) -> dict[str, bool]: + return {"Local serial online": SERIAL in local_android_ids} + + +def _llm_credentials_present(auth_path: Path) -> bool: + if not PROVIDER.endswith("_oauth"): + return bool(os.getenv(PROVIDER.upper() + "_API_KEY")) + try: + profile = json.loads(auth_path.read_text()) + except (OSError, ValueError): + return False + slot = { + "openai_oauth": "openaiOauth", + "anthropic_oauth": "anthropicOauth", + "gemini_oauth": "geminiOauth", + "grok_oauth": "grokOauth", + }.get(PROVIDER) + return bool(isinstance(profile, dict) and slot and profile.get(slot)) + + +@pytest.fixture +def requirements(cloud_requirements, local_requirements, copied_auth_profiles): + return { + **cloud_requirements, + **local_requirements, + "LLM credentials": _llm_credentials_present(copied_auth_profiles), + } + + +@pytest.fixture +def cloud_ready(cloud_requirements): + if not all(cloud_requirements.values()): pytest.skip("Cloud requirement missing; run test_00_requirements.py") @pytest.fixture -def local_ready(requirements): - if not requirements["Local serial online"]: +def local_ready(local_requirements): + if not local_requirements["Local serial online"]: pytest.skip("Local requirement missing; run test_00_requirements.py") + + +@pytest.fixture +def single_local_android(local_android_ids: list[str]) -> None: + if local_android_ids != [SERIAL]: + pytest.skip("requires exactly the configured local Android device") diff --git a/tests/unit/smoke/test_00_requirements.py b/tests/unit/smoke/test_00_requirements.py index 76a11b383..d0e0b2c07 100644 --- a/tests/unit/smoke/test_00_requirements.py +++ b/tests/unit/smoke/test_00_requirements.py @@ -1,7 +1,7 @@ -"""One diagnostic table, without disclosing credential values.""" +"""Read-only core device and credential checks without reporting secret values.""" -def test_all_requirements(requirements): +def test_all_requirements(requirements: dict[str, bool]) -> None: table = "\n".join( f"{name:28} {'ok' if ok else 'missing'}" for name, ok in requirements.items() ) diff --git a/tests/unit/smoke/test_cli_offline.py b/tests/unit/smoke/test_cli_offline.py index eed0bbfae..907bf0ce4 100644 --- a/tests/unit/smoke/test_cli_offline.py +++ b/tests/unit/smoke/test_cli_offline.py @@ -4,11 +4,20 @@ import sys from pathlib import Path +import pytest -def test_installed_cli_bash_completion(monkeypatch): + +@pytest.mark.parametrize( + ("words", "index", "expected"), + [ + ("mobilerun ", "1", {"plain,account", "plain,device", "plain,macro"}), + ("mobilerun device ", "2", {"plain,app", "plain,input", "plain,screen"}), + ], +) +def test_installed_cli_bash_completion(monkeypatch, words, index, expected): monkeypatch.setenv("_MOBILERUN_COMPLETE", "bash_complete") - monkeypatch.setenv("COMP_WORDS", "mobilerun ") - monkeypatch.setenv("COMP_CWORD", "1") + monkeypatch.setenv("COMP_WORDS", words) + monkeypatch.setenv("COMP_CWORD", index) result = subprocess.run( [str(Path(sys.executable).with_name("mobilerun"))], capture_output=True, @@ -16,9 +25,9 @@ def test_installed_cli_bash_completion(monkeypatch): timeout=15, ) assert result.returncode == 0, result.stderr - assert {"plain,account", "plain,device", "plain,macro"} <= set( - result.stdout.splitlines() - ) + completions = set(result.stdout.splitlines()) + assert expected <= completions + assert "plain,action" not in completions def test_offline_cli_protects_local_skill_notes(tmp_path): diff --git a/tests/unit/smoke/test_cloud_devices.py b/tests/unit/smoke/test_cloud_devices.py index df0b31ac7..974d4ae18 100644 --- a/tests/unit/smoke/test_cloud_devices.py +++ b/tests/unit/smoke/test_cloud_devices.py @@ -5,90 +5,123 @@ import os import subprocess import sys +from collections.abc import Mapping from pathlib import Path from uuid import uuid4 import pytest +from mobilerun_core import CloudLifecycleError, ConnectProxyRef -from mobilerun.clients.cloud.api_keys import validate_api_key +from mobilerun.clients.cloud.api_keys import ApiKeys +from mobilerun.clients.cloud.client import cloud_client from mobilerun.core.credentials import DictCredentials -from mobilerun.core.devices import CloudDevice -from mobilerun.errors import ( - CloudAuthRequired, - CloudDeviceNotFound, - LocalCredentialsNotAllowed, -) +from mobilerun.core.operator.cloud import CloudTaskOperator from mobilerun.errors.cloud import CloudAuthenticationError -from mobilerun.models import Billing, Plan -from tests.support.smoke_phone import close_smoke_phone +from mobilerun.errors.operators import OperatorNotSupported +from mobilerun.models import Billing from tests.support.smoke_settings import CLOUD_ID +pytestmark = pytest.mark.smoke_cloud -@pytest.mark.smoke_cloud -def test_cloud_info_and_wait_ready(cloud_ready): - async def run(): - device = CloudDevice(CLOUD_ID) - assert (await device.info()).id == CLOUD_ID - await device.wait_ready(timeout=30) - asyncio.run(run()) +def test_cloud_info_and_wait_ready(cloud_ready, cloud_run): + async def exercise() -> None: + async with cloud_run() as run: + handle = run.cloud_device(CLOUD_ID) + assert (await handle.refresh()).device_id == CLOUD_ID + assert (await handle.wait_ready(timeout=30)).state == "ready" + asyncio.run(exercise()) -@pytest.mark.smoke_cloud -def test_cloud_rejects_local_secrets(cloud_ready): - async def run(): - device = CloudDevice(CLOUD_ID) - await DictCredentials({"test": "not-a-real-secret"}).bind(device) - with pytest.raises(LocalCredentialsNotAllowed): - await device.do("This must never be submitted") - asyncio.run(run()) +def test_cloud_rejects_local_secrets(cloud_ready, cloud_run): + async def exercise() -> None: + async with cloud_run() as run, cloud_client(billing=Billing.NO_COMMERCE) as sdk: + async with await run.connect(CLOUD_ID, backend="cloud") as device: + vault = DictCredentials({"test": "not-a-real-secret"}, device=device) + try: + operator = CloudTaskOperator( + client=sdk, billing=Billing.NO_COMMERCE, extensions=[vault] + ) + with pytest.raises(OperatorNotSupported, match="non-cloud-native"): + await operator.do(device, "This must never be submitted") + finally: + await vault.close() + asyncio.run(exercise()) -@pytest.mark.smoke_cloud -def test_paid_cloud_create_lifecycle(cloud_ready, record_property): - async def run(): + +def _approve_paid_lifecycle(verb: str, args: Mapping[str, object]) -> bool: + if verb == "device.create_cloud": + return args.get("plan") == "minute" and args.get("keep") is False + return verb in {"device.stop", "device.resume", "device.reboot", "device.reset"} + + +def test_paid_cloud_create_lifecycle( + cloud_run, cloud_connect_proxy: ConnectProxyRef, record_property +): + async def exercise() -> None: name = f"SDK lifecycle smoke {uuid4().hex}" record_property("device_name", name) - device = CloudDevice(name=name, billing=Billing.PAID, plan=Plan.MINUTE) - try: - await device - info = await device.info() - assert info.id == device.cloud_id - assert info.type == "android_cloud_phone" - await device.stop() - await device.resume() - await device.wait_ready() - await device.reboot() - await device.wait_ready() - await device.reset(mode="identity") - await device.wait_ready() - finally: - await close_smoke_phone(device, name) - - asyncio.run(run()) - - -@pytest.mark.smoke -def test_auto_create_and_terminate(real_env, record_property): - async def run(): - device = CloudDevice(billing="paid", plan="minute") - async with device: - assert device._adb_device_id - record_property("created_device", device._adb_device_id) - assert not device._owned - record_property("terminated_device", device._adb_device_id) - - asyncio.run(run()) - - -def test_unknown_cloud_device_has_clear_error(real_env): - device = CloudDevice("00000000-0000-0000-0000-000000000000") - with pytest.raises(CloudDeviceNotFound): - asyncio.run(device.do("noop", max_steps=1)) - - -@pytest.mark.smoke_cloud + async with cloud_run(hitl_gate=_approve_paid_lifecycle) as run: + async with await run.create_cloud( + name=name, + device_type="android_cloud_phone", + plan="minute", + proxy=cloud_connect_proxy, + keep=False, + ) as device: + record_property("created_device", device.device_id) + handle = run.cloud_device(device.device_id) + info = await handle.refresh() + assert info.device_id == device.device_id + assert info.device_type == "android_cloud_phone" + assert info.billing_strategy == "minute" + await handle.stop() + await handle.resume() + await handle.wait_ready() + await handle.reboot() + await handle.wait_ready() + await handle.reset() + await handle.wait_ready() + + asyncio.run(exercise()) + + +def test_auto_create_and_terminate( + cloud_run, cloud_connect_proxy: ConnectProxyRef, record_property +): + async def exercise() -> None: + name = f"SDK ownership smoke {uuid4().hex}" + record_property("device_name", name) + async with cloud_run(hitl_gate=_approve_paid_lifecycle) as run: + async with await run.create_cloud( + name=name, plan="minute", proxy=cloud_connect_proxy, keep=False + ) as device: + device_id = device.device_id + record_property("created_device", device_id) + # Check the close side effect with public control-plane metadata. + assert all( + item.state == "terminated" + for item in await run.list_cloud_devices() + if item.device_id == device_id + ) + record_property("terminated_device", device_id) + + asyncio.run(exercise()) + + +def test_unknown_cloud_device_has_clear_error(cloud_key, cloud_run): + async def exercise() -> None: + async with cloud_run() as run: + unknown = run.cloud_device("00000000-0000-0000-0000-000000000000") + with pytest.raises(CloudLifecycleError, match="HTTP 404") as failure: + await unknown.refresh() + assert failure.value.status_code == 404 + + asyncio.run(exercise()) + + def test_status_json_excludes_connection_credentials(cloud_ready): result = subprocess.run( [ @@ -112,11 +145,7 @@ def test_status_json_excludes_connection_credentials(cloud_ready): ) -@pytest.mark.smoke_cloud -@pytest.mark.parametrize( - "args", - [["device", "list", "--cloud"], ["account", "status"]], -) +@pytest.mark.parametrize("args", [["device", "list", "--cloud"], ["account", "status"]]) def test_cloud_cli(cloud_ready, args): result = subprocess.run( [str(Path(sys.executable).with_name("mobilerun")), *args], @@ -131,14 +160,18 @@ def test_cloud_cli(cloud_ready, args): assert CLOUD_ID in result.stdout -@pytest.mark.smoke_cloud -def test_missing_cloud_key(real_env, monkeypatch): - monkeypatch.delenv("MOBILERUN_API_KEY", raising=False) - with pytest.raises(CloudAuthRequired): - CloudDevice(device_id=CLOUD_ID) +def test_missing_cloud_key(monkeypatch, cloud_run): + for name in ("MOBILERUN_API_KEY", "MOBILERUN_CLOUD_API_KEY"): + monkeypatch.delenv(name, raising=False) + + async def exercise() -> None: + async with cloud_run() as run: + with pytest.raises(RuntimeError, match="no bearer in env"): + run.cloud_device(CLOUD_ID) + + asyncio.run(exercise()) -@pytest.mark.smoke_cloud def test_cloud_ping_reports_unsupported(cloud_ready): result = subprocess.run( [str(Path(sys.executable).with_name("mobilerun")), "device", "ping", CLOUD_ID], @@ -150,14 +183,19 @@ def test_cloud_ping_reports_unsupported(cloud_ready): assert "supports Android targets only" in result.stderr -def test_real_api_key_is_valid(real_env): - if not os.environ.get("MOBILERUN_API_KEY"): - pytest.skip("MOBILERUN_API_KEY is not set") - asyncio.run(validate_api_key(os.environ["MOBILERUN_API_KEY"], billing="included")) +def test_real_api_key_is_valid(cloud_key): + asyncio.run( + ApiKeys( + api_key=os.environ["MOBILERUN_API_KEY"], billing=Billing.NO_COMMERCE + ).validate() + ) def test_bad_api_key_is_invalid(real_env): with pytest.raises(CloudAuthenticationError): asyncio.run( - validate_api_key("obviously-invalid-mobilerun-api-key", billing="included") + ApiKeys( + api_key="obviously-invalid-mobilerun-api-key", + billing=Billing.NO_COMMERCE, + ).validate() ) diff --git a/tests/unit/smoke/test_cloud_resources.py b/tests/unit/smoke/test_cloud_resources.py index 48288c4f2..7f97113a4 100644 --- a/tests/unit/smoke/test_cloud_resources.py +++ b/tests/unit/smoke/test_cloud_resources.py @@ -12,44 +12,75 @@ from uuid import uuid4 import pytest +from mobilerun_core import AsyncMobilerun, ConnectProxyRef, HttpProxy, ProxyStatus from mobilerun_sdk import APIStatusError -from mobilerun.clients.cloud import devices, mailboxes, numbers, proxies +from mobilerun.clients.cloud import mailboxes, numbers from mobilerun.clients.cloud.client import cloud_client -from mobilerun.clients.cloud.devices import list_devices -from mobilerun.clients.cloud.proxies import device_status, list_proxies +from mobilerun.clients.local.login_store import LoginStore from mobilerun.config.settings import get_settings -from mobilerun.core.devices import AndroidDevice, CloudDevice from mobilerun.core.mailbox import CloudMailbox from mobilerun.core.phone_number import CloudPhoneNumber -from mobilerun.core.proxy import CloudRotatingProxy -from mobilerun.errors import DeviceOperationNotSupported -from mobilerun.models.billing import Billing, Plan -from tests.support.smoke_phone import close_smoke_phone +from mobilerun.core.proxy import CloudRotatingProxy, list_connect_proxies +from mobilerun.models.billing import Billing from tests.support.smoke_settings import CLOUD_ID, SERIAL +async def _approve_owned_cloud_changes( + action: str, arguments: dict[str, object] +) -> bool: + """Permit a disposable minute phone and replacement with borrowed proxy capacity.""" + if action == "device.create_cloud": + return arguments.get("plan") == "minute" and arguments.get("keep") is False + return action == "device.set_proxy" + + +def _cloud(*, create: bool = False) -> AsyncMobilerun: + return AsyncMobilerun( + bearer=LoginStore.from_settings().resolve_api_key(), + base_url=get_settings().MOBILERUN_CLOUD_BASE_URL, + hitl_gate=_approve_owned_cloud_changes if create else None, + ) + + +async def _existing_proxy() -> ConnectProxyRef: + async for product in list_connect_proxies(billing=Billing.NO_COMMERCE): + if product.status == "active": + return product.ref + pytest.skip("No existing active Connect proxy; this smoke does not buy one") + + +async def _verify_terminated(core: AsyncMobilerun, device_id: str) -> None: + async with asyncio.timeout(30): + while any( + item.device_id == device_id and item.state != "terminated" + for item in await core.list_cloud_devices() + ): + await asyncio.sleep(1) + + @pytest.mark.smoke_cloud def test_free_clients_no_commerce(real_env): async def run(): + async with _cloud() as core: + assert isinstance(await core.list_cloud_devices(), list) async with cloud_client(billing=Billing.NO_COMMERCE) as client: assert isinstance( - await devices.list_devices(client=client, billing=Billing.NO_COMMERCE), - list, - ) - assert isinstance( - await numbers.list_numbers(client=client, billing=Billing.NO_COMMERCE), + await numbers.Numbers( + client=client, billing=Billing.NO_COMMERCE + ).list(), list, ) assert isinstance( - await mailboxes.list_mailboxes( + await mailboxes.Mailboxes( client=client, billing=Billing.NO_COMMERCE - ), + ).list(), list, ) - assert ( - await proxies.list_proxies(billing=Billing.NO_COMMERCE) - ).items is not None + assert isinstance( + [item async for item in list_connect_proxies(billing=Billing.NO_COMMERCE)], + list, + ) asyncio.run(run()) @@ -57,42 +88,25 @@ async def run(): @pytest.mark.smoke_cloud def test_paid_minute_phone_released(real_env, record_property): async def run(): - listed = await proxies.list_proxies(billing=Billing.NO_COMMERCE, page_size=100) - proxy = next((item for item in listed.items if item.status == "active"), None) - if proxy is None: - pytest.skip( - "No existing active Connect proxy; do not purchase a proxy for this smoke" - ) + proxy = await _existing_proxy() started = time.monotonic() - async with cloud_client(billing=Billing.PAID) as client: - phone = await devices.create( - client=client, - billing=Billing.PAID, - plan=Plan.MINUTE, - proxy={"connect": {"id": proxy.id}}, - device_type=get_settings().MOBILERUN_CLOUD_DEVICE_TYPE, - name="client-billing-minute-smoke", - ) - record_property("created_device", phone.id) - try: - await devices.wait_ready( - phone.id, client=client, billing=Billing.PAID, timeout=180 - ) - assert ( - await devices.retrieve( - phone.id, client=client, billing=Billing.NO_COMMERCE - ) - ).id == phone.id - finally: - await devices.terminate( - phone.id, client=client, billing=Billing.NO_COMMERCE - ) - record_property("terminated_device", phone.id) - record_property("elapsed_seconds", round(time.monotonic() - started, 2)) - record_property( - "billing_plan", - "minute; actual monetary debit not exposed by this API", - ) + name = f"client-billing-minute-smoke-{uuid4().hex}" + record_property("device_name", name) + async with _cloud(create=True) as core: + async with await core.create_cloud( + plan="minute", proxy=proxy, name=name, ready_timeout=180 + ) as phone: + device_id = phone.device_id + record_property("created_device", device_id) + record = await core.cloud_device(device_id).refresh() + assert record.device_id == device_id and record.ready + assert record.billing_strategy == "minute" + await _verify_terminated(core, device_id) + record_property("terminated_device", device_id) + record_property("elapsed_seconds", round(time.monotonic() - started, 2)) + record_property( + "billing_plan", "minute; actual monetary debit not exposed by this API" + ) asyncio.run(run()) @@ -106,37 +120,40 @@ def run_check(coro): ) -@pytest.mark.smoke +@pytest.mark.smoke_cloud def test_free_lists_countries_and_capacity(real_env): async def exercise(): - await numbers.list_numbers(billing="no_commerce") - countries = await numbers.countries(billing="no_commerce") + adapter = numbers.Numbers(billing="no_commerce") + await adapter.list() + countries = await adapter.countries() assert countries.data.items - await numbers.capacity(countries.data.items[0].country, billing="no_commerce") - await mailboxes.list_mailboxes(billing="no_commerce") - await mailboxes.capacity(billing="no_commerce") + await adapter.capacity(countries.data.items[0].country) + await mailboxes.Mailboxes(billing="no_commerce").list() + await mailboxes.Mailboxes(billing="no_commerce").capacity() run_check(exercise()) -@pytest.mark.smoke +@pytest.mark.smoke_cloud def test_paid_number_create_release_and_sms(real_env, record_property): async def exercise(): - countries = await numbers.countries(billing="included") + adapter = numbers.Numbers(billing="included") + countries = await adapter.countries() country = next( (item.country for item in countries.data.items if item.in_stock), None ) if not country: pytest.skip("No phone numbers in stock") - number = await CloudPhoneNumber( - country=country, billing="paid", label="mobilerun-comms-smoke" - ) - record_property("created_number", number.id) + label = f"smoke-{uuid4().hex}" + record_property("number_label", label) + number = CloudPhoneNumber(country=country, billing="paid", label=label) try: + await number + record_property("created_number", number.id) # Poll for provisioning without creating any further resources. info = None for _ in range(30): - info = (await numbers.retrieve(number.id, billing="included")).data + info = (await adapter.retrieve(number.id)).data if info.state != "provisioning": break await asyncio.sleep(2) @@ -144,73 +161,87 @@ async def exercise(): record_property( "sms_flow", "unavailable: number not active/send-enabled" ) - return - after = datetime.now(timezone.utc) - code = str(secrets.randbelow(900000) + 100000) - await number.send(info.phone_number, "Mobilerun test verification: " + code) - received = await number.wait_for_code(timeout=60, after=after) - if received != code: - pytest.fail("SMS verification did not match; values omitted") - record_property("sms_flow", "verified") + else: + after = datetime.now(timezone.utc) + code = str(secrets.randbelow(900000) + 100000) + await number.send( + info.phone_number, "Mobilerun test verification: " + code + ) + received = await number.wait_for_code(timeout=60, after=after) + if received != code: + pytest.fail("SMS verification did not match; values omitted") + record_property("sms_flow", "verified") finally: - await number.release() - remaining = next( - ( - item - for item in await numbers.list_numbers(billing="included") - if item.id == number.id - ), - None, - ) - assert ( - remaining is None - or remaining.cancel_at_period_end - or remaining.state in ("expired", "failed") - ) - record_property("released_number", number.id) + await number.close() + await _verify_released_number(number.id) + record_property("released_number", number.id) run_check(exercise()) -@pytest.mark.smoke +async def _verify_released_number(number_id: str) -> None: + remaining = next( + ( + item + for item in await numbers.Numbers(billing=Billing.NO_COMMERCE).list() + if item.id == number_id + ), + None, + ) + assert ( + remaining is None + or remaining.cancel_at_period_end + or remaining.state in ("expired", "failed") + ) + + +@pytest.mark.smoke_cloud def test_paid_mailbox_create_release(real_env, record_property): async def exercise(): - mailbox = await CloudMailbox(billing="paid", label="mobilerun-comms-smoke") - record_property("created_mailbox", mailbox.id) + label = f"smoke-{uuid4().hex}" + record_property("mailbox_label", label) + mailbox = CloudMailbox(billing="paid", label=label) try: - await mailboxes.retrieve(mailbox.id, billing="included") + await mailbox + record_property("created_mailbox", mailbox.id) + await mailboxes.Mailboxes(billing="included").retrieve(mailbox.id) # Receiving real email requires an external sender, which this SDK lacks. record_property( "email_flow", "not run: no authorized outbound email transport" ) finally: - await mailbox.release() - remaining = next( - ( - item - for item in await mailboxes.list_mailboxes(billing="included") - if item.id == mailbox.id - ), - None, - ) - assert ( - remaining is None - or remaining.cancel_at_period_end - or remaining.status in ("archived", "billing_error") - ) - record_property("released_mailbox", mailbox.id) + await mailbox.close() + remaining = next( + ( + item + for item in await mailboxes.Mailboxes( + billing=Billing.NO_COMMERCE + ).list() + if item.id == mailbox.id + ), + None, + ) + assert ( + remaining is None + or remaining.cancel_at_period_end + or remaining.status in ("archived", "billing_error") + ) + record_property("released_mailbox", mailbox.id) run_check(exercise()) -@pytest.mark.smoke +@pytest.mark.smoke_cloud def test_existing_mailbox_messages(real_env): async def exercise(): - existing = await mailboxes.list_mailboxes(billing="no_commerce") + existing = await CloudMailbox.list(billing=Billing.NO_COMMERCE) if not existing: pytest.skip("No existing mailbox available") - result = await mailboxes.messages(existing[0].id, billing="no_commerce") - assert isinstance(result, list) + mailbox = existing[0] + try: + assert isinstance(await mailbox.messages(), list) + finally: + await mailbox.close() asyncio.run(exercise()) @@ -243,107 +274,91 @@ def test_number_included_all_countries(real_env): ) -@pytest.mark.smoke -def test_paid_number_bind_unbind_and_release(real_env, record_property): +@pytest.mark.smoke_cloud +def test_paid_number_attach_detach_and_release(real_env, record_property): async def exercise(): - countries = await numbers.countries(billing=Billing.NO_COMMERCE) + countries = await numbers.Numbers(billing=Billing.NO_COMMERCE).countries() country = next( (item.country for item in countries.data.items if item.in_stock), None ) if country is None: pytest.skip("No phone numbers in stock") - number = await CloudPhoneNumber( - country=country, billing=Billing.PAID, label="mobilerun-binding-smoke" - ) - record_property("created_number", number.id) - started = asyncio.get_running_loop().time() - phone = CloudDevice( - billing=Billing.PAID, plan=Plan.MINUTE, name="mobilerun-binding-smoke" - ) - try: - await number.wait_ready() - record_property( - "number_ready_seconds", - f"{asyncio.get_running_loop().time() - started:.1f}", - ) - await phone - phone_id = phone.cloud_id - assert phone_id is not None - record_property("created_phone", phone_id) - await number.bind(phone) - assert phone.number is number - assert number.device_id == phone_id - async with CloudDevice(phone_id, billing=Billing.NO_COMMERCE) as observer: - assert observer.number.id == number.id - assert observer.actions.get("device.open_url") - async with cloud_client(billing=Billing.NO_COMMERCE) as client: - remote = await devices.number( - phone_id, billing=Billing.NO_COMMERCE, client=client + initial_proxy = await _existing_proxy() + name = f"mobilerun-number-smoke-{uuid4().hex}" + record_property("device_name", name) + async with _cloud(create=True) as core: + async with await core.create_cloud( + plan="minute", proxy=initial_proxy, name=name + ) as phone: + phone_id = phone.device_id + record_property("created_phone", phone_id) + label = f"smoke-{uuid4().hex}" + record_property("number_label", label) + number = CloudPhoneNumber( + country=country, billing=Billing.PAID, label=label ) - assert remote.binding and remote.binding.number_id == number.id - await number.unbind() - assert number.device_id is None - with pytest.raises(DeviceOperationNotSupported): - _ = phone.number - proxy = CloudRotatingProxy(country="DE") - await proxy.bind(phone, force=True) - assert (await proxy.status()).connected and phone.extensions[ - "proxy" - ] is proxy - record_property("proxy_switch", "US->DE: active") - finally: - # Number cleanup is attempted even if phone cleanup subsequently fails. - try: - await number.release() + started = time.monotonic() + try: + await number + record_property("created_number", number.id) + await number.wait_ready() + record_property("number_ready_seconds", time.monotonic() - started) + await number.attach(phone) + assert number.device_id == phone_id + async with cloud_client(billing=Billing.NO_COMMERCE) as client: + remote = await client.devices.number.retrieve(phone_id) + assert remote.binding and remote.binding.number_id == number.id + assert await number.detach() + assert number.device_id is None + remote = await client.devices.number.retrieve(phone_id) + assert remote.binding is None + finally: + # Close while the phone still exists so it can detach an owned link. + await number.close() + await _verify_released_number(number.id) record_property("released_number", number.id) - finally: - terminated_id = phone.cloud_id - await phone.close() - if terminated_id is not None: - record_property("terminated_phone", terminated_id) - remaining = next( - ( - item - for item in await numbers.list_numbers(billing=Billing.NO_COMMERCE) - if item.id == number.id - ), - None, - ) - assert ( - remaining is None - or remaining.cancel_at_period_end - or remaining.state in ("expired", "failed") - ) - for _ in range(30): - listed = await devices.list_devices(billing=Billing.NO_COMMERCE) - if all(item.id != phone_id for item in listed): - break - await asyncio.sleep(1) - else: - pytest.fail("Terminated phone is still listed") + + # A switch uses another existing product, never an implicit purchase. + try: + replacement = await CloudRotatingProxy.select("DE", device=phone) + except LookupError: + record_property("proxy_switch", "not run: no active DE proxy") + else: + if replacement.id == initial_proxy.id: + record_property("proxy_switch", "not run: same proxy ID") + else: + await phone.set_proxy( + replacement.as_device_proxy(), replace=True + ) + status = await phone.proxy_status() + assert status.connected and status.reference == replacement.id + record_property("proxy_switch", "DE: active") + await _verify_terminated(core, phone_id) + record_property("terminated_phone", phone_id) asyncio.run(exercise()) @pytest.mark.smoke_cloud -def test_connected_phone_advertises_server_proxy_capability(cloud_ready): +def test_connected_phone_exposes_core_proxy_status(cloud_ready): async def run(): - info = await devices.capabilities(CLOUD_ID, billing=Billing.NO_COMMERCE) - async with CloudDevice(CLOUD_ID, billing=Billing.NO_COMMERCE) as phone: - assert ( - "proxy_switch" in phone.supported_operations - ) == info.capabilities.proxy - assert await phone.screenshot() + async with _cloud() as core: + async with await core.connect(CLOUD_ID, backend="cloud") as phone: + assert phone.supports("proxy_status") + assert isinstance(await phone.proxy_status(), ProxyStatus) + assert await phone.screenshot_bytes() asyncio.run(run()) -@pytest.mark.smoke -def test_list_and_existing_status(real_env): +@pytest.mark.smoke_cloud +def test_list_and_existing_status(cloud_ready): async def run(): - assert (await list_proxies(billing=Billing.INCLUDED)).items is not None - status = await device_status(CLOUD_ID, billing=Billing.INCLUDED) - assert isinstance(status.connected, bool) + async for product in list_connect_proxies(billing=Billing.NO_COMMERCE): + assert product.ref.id and product.status + async with _cloud() as core: + async with await core.connect(CLOUD_ID, backend="cloud") as phone: + assert isinstance((await phone.proxy_status()).connected, bool) asyncio.run(run()) @@ -372,77 +387,50 @@ def test_proxy_list_included_json(real_env): assert all(set(entry) == {"id", "country", "status", "type"} for entry in entries) -@pytest.mark.smoke @pytest.mark.smoke_device -def test_local_proxy_cleared(real_env): - async def run(): - device = AndroidDevice(serial=SERIAL, portal_mode="disabled") - from mobilerun.core.proxy import LocalProxy +def test_local_proxy_cleared(local_ready): + async def approve_proxy(action: str, _arguments: dict[str, object]) -> bool: + return action in {"device.set_proxy", "device.clear_proxy"} - proxy = LocalProxy("127.0.0.1", 8888) - try: - if (await device._proxy_target.status()).connected: - pytest.skip("Preserving the emulator's existing proxy") - await proxy.bind(device) - assert device.proxy is proxy - assert proxy.device is device - assert (await proxy.status()).connected - await proxy.unbind() - assert not device.extensions - assert not (await device._proxy_target.status()).connected - finally: - await device.close() + async def run(): + proxy = HttpProxy("127.0.0.1", 8888) + configured = ProxyStatus(True, "http", f"{proxy.host}:{proxy.port}") + async with AsyncMobilerun(hitl_gate=approve_proxy) as core: + async with await core.connect( + SERIAL, backend="local-android-adb", portal_mode="disabled" + ) as device: + if (await device.proxy_status()).connected: + pytest.skip("Preserving the emulator's existing proxy") + try: + await device.set_proxy(proxy) + assert await device.proxy_status() == configured + finally: + # Re-read even if the write failed; never clear an unrelated value. + if await device.proxy_status() == configured: + await device.clear_proxy() + assert not (await device.proxy_status()).connected asyncio.run(run()) -@pytest.mark.smoke +@pytest.mark.smoke_cloud def test_paid_create_with_proxy(real_env, record_property): async def run(): - before = await list_proxies( - billing=Billing.INCLUDED, country="de", page_size=100 - ) - if not any( - item.status == "active" and item.type == "residential" - for item in before.items - ): + try: + proxy = await CloudRotatingProxy.select("DE", billing=Billing.NO_COMMERCE) + except LookupError: pytest.skip("No active German residential proxy available for safe reuse") - name = f"proxy smoke {uuid4().hex}" + name = f"proxy-smoke-{uuid4().hex}" record_property("device_name", name) - device = CloudDevice( - proxy=CloudRotatingProxy(country="DE"), - billing=Billing.PAID, - plan=Plan.MINUTE, - name=name, - ) - try: - await device - record_property("device_id", device.cloud_id) - assert (await device.proxy.status()).connected - finally: - await close_smoke_phone(device, name) - device_id = device.cloud_id - if device_id: - for _ in range(30): - listed = await list_devices(billing=Billing.INCLUDED) - if all(item.id != device_id for item in listed): - break - await asyncio.sleep(1) - else: - pytest.fail(f"Terminated phone {device_id} is still listed") - record_property("released_device", device_id) - before_ids = {item.id for item in before.items} - new = [] - for _ in range(30): - after = await list_proxies( - billing=Billing.INCLUDED, country="de", page_size=100 - ) - new = [item for item in after.items if item.id not in before_ids] - if all(item.status == "ended" for item in new): - break - await asyncio.sleep(1) - for item in new: - record_property("new_proxy", f"{item.id}:{item.status}") - assert all(item.status == "ended" for item in new), "New proxy is not released" + record_property("borrowed_proxy", proxy.id) + async with _cloud(create=True) as core: + async with await core.create_cloud( + proxy=proxy.as_device_proxy(), plan="minute", name=name + ) as device: + device_id = device.device_id + record_property("device_id", device_id) + assert (await device.proxy_status()).connected + await _verify_terminated(core, device_id) + record_property("released_device", device_id) asyncio.run(run()) diff --git a/tests/unit/smoke/test_device_workflows.py b/tests/unit/smoke/test_device_workflows.py index fadc30d6f..014ba23fd 100644 --- a/tests/unit/smoke/test_device_workflows.py +++ b/tests/unit/smoke/test_device_workflows.py @@ -4,85 +4,77 @@ import os import subprocess import sys +from collections.abc import Mapping from pathlib import Path import pytest +from mobilerun_core import AppIdentity, AsyncDevice, AsyncMobilerun +from mobilerun.core.runs import ActionRecording from tests.support.macro import read_run_steps from tests.support.smoke_settings import CLOUD_ID, SERIAL +PNG = b"\x89PNG\r\n\x1a\n" +COUNTER = "ai.droidrun.counter" -async def exercise(device): - await device.connect() + +async def exercise(device: AsyncDevice) -> None: try: - assert (await device.screenshot()).startswith(b"\x89PNG\r\n\x1a\n") + assert (await device.screenshot_bytes()).startswith(PNG) await device.start_app("com.android.settings") - state = await device.state.refresh() - assert state.elements + assert (await device.observe(screenshot=False)).elements assert await device.list_apps() - await device.swipe(200, 800, 200, 400, duration_ms=300) + await device.swipe(200, 800, 200, 400, ms=300) await device.tap(100, 100) finally: - await device.press_button("home") + await device.key("home") @pytest.mark.smoke_device def test_local_device(local_ready): - from mobilerun.core.devices import AndroidDevice + async def run() -> None: + async with AsyncMobilerun() as core: + async with await core.connect( + SERIAL, backend="local-android-adb" + ) as device: + await exercise(device) - asyncio.run(exercise(AndroidDevice(serial=SERIAL))) + asyncio.run(run()) @pytest.mark.smoke_device -def test_local_wrapper_and_pool_state(local_ready): - from mobilerun import AndroidDevice, DevicePool, RecordingDevice - - async def run(): - async with AndroidDevice(SERIAL) as root: - wrapped = RecordingDevice(root) - await wrapped.connect() - await wrapped.connect() - try: - await wrapped.start_app("com.android.settings") - states = await DevicePool([wrapped]).state.refresh() - assert states[0] is wrapped.state.current - assert states[0].elements - await wrapped.press_button("home") - row = read_run_steps(wrapped.run_dir)[-1] - assert row.ok and row.action == "button_press" - assert row.args == {"button": "home"} - wrapped.finish("succeeded") - finally: - await root.press_button("home") +def test_local_observation_and_recording(local_ready, tmp_path): + async def run() -> None: + async with AsyncMobilerun() as core: + async with await core.connect( + SERIAL, backend="local-android-adb" + ) as device: + try: + async with ActionRecording(device, runs_dir=tmp_path) as recording: + await device.start_app("com.android.settings") + assert (await device.observe(screenshot=False)).elements + await device.key("home") + recording.finish("succeeded") + row = read_run_steps(recording.run_dir)[-1] + assert row.ok and row.action == "key" + assert row.args == {"name_or_code": "home"} + finally: + await device.key("home") asyncio.run(run()) @pytest.mark.smoke_cloud -def test_cloud_device(cloud_ready): - from mobilerun.core.devices.cloud import CloudDevice - - asyncio.run(exercise(CloudDevice(device_id=CLOUD_ID))) - - -@pytest.mark.smoke_cloud -def test_cloud_pool(cloud_ready): - from mobilerun.core.devices.cloud import CloudDevice - from mobilerun.core.devices.pool import DevicePool - - async def run(): - device = CloudDevice(device_id=CLOUD_ID) - await device.connect() - try: - images = await DevicePool([device]).screenshot() - assert len(images) == 1 and images[0].startswith(b"\x89PNG\r\n\x1a\n") - finally: - await device.press_button("home") +def test_cloud_device(cloud_ready, cloud_run): + async def run() -> None: + async with cloud_run() as core: + async with await core.connect(CLOUD_ID, backend="cloud") as device: + await exercise(device) asyncio.run(run()) -def cli(*args, env): +def cli(*args: str, env: Mapping[str, str]) -> subprocess.CompletedProcess[str]: return subprocess.run( [str(Path(sys.executable).with_name("mobilerun")), *args], capture_output=True, @@ -93,17 +85,7 @@ def cli(*args, env): @pytest.mark.smoke_device -def test_single_adb_device_default(local_ready): - result = subprocess.run( - ["adb", "devices"], capture_output=True, text=True, check=True - ) - devices = [ - line.split()[0] - for line in result.stdout.splitlines()[1:] - if line.endswith("\tdevice") - ] - if devices != [SERIAL]: - pytest.skip("requires exactly the configured local adb device") +def test_single_adb_device_default(single_local_android): env = os.environ.copy() # This case exercises local-only discovery, not mixed local/cloud selection. env.pop("MOBILERUN_API_KEY", None) @@ -119,8 +101,7 @@ def test_config_default(local_ready, tmp_path): config = tmp_path / "device.yaml" config.write_text(f"_version: {CURRENT_VERSION}\ndevice:\n serial: {SERIAL}\n") - env = os.environ.copy() - result = cli("device", "app", "list", "--config", str(config), env=env) + result = cli("device", "app", "list", "--config", str(config), env=os.environ) assert result.returncode == 0, result.stderr assert result.stdout.strip() @@ -131,104 +112,122 @@ def test_cloud_config_default(cloud_ready, tmp_path): config = tmp_path / "device.yaml" config.write_text(f"_version: {CURRENT_VERSION}\ndevice:\n serial: {CLOUD_ID}\n") - env = os.environ.copy() - env["TMPDIR"] = str(tmp_path) + env = {**os.environ, "TMPDIR": str(tmp_path)} result = cli("device", "screen", "screenshot", "--config", str(config), env=env) - assert result.returncode == 0, result.stderr + assert result.returncode == 0, "Cloud screenshot failed; output withheld" image = Path(result.stdout.strip()) assert image.is_relative_to(tmp_path) - assert image.read_bytes().startswith(b"\x89PNG\r\n\x1a\n") + assert image.read_bytes().startswith(PNG) @pytest.fixture -def counter_apk(real_smoke_apk): +def counter_apk(real_smoke_apk: Path) -> Path: from mobilerun.clients.local.apk import inspect_apk - path = real_smoke_apk - if not path.is_file(): - pytest.skip(f"Counter smoke APK missing: {path}; set MOBILERUN_SMOKE_APK") - package, _, _, _ = inspect_apk(path) - if package != "ai.droidrun.counter": + if not real_smoke_apk.is_file(): + pytest.skip("Counter smoke APK missing; set MOBILERUN_SMOKE_APK") + package, _, _, _ = inspect_apk(real_smoke_apk) + if package != COUNTER: pytest.skip("Smoke APK is not the Counter app; refusing to modify another app") - return path + return real_smoke_apk -def _has_counter(apps): - return any( - (app.get("package") or app.get("package_name") or app.get("packageName")) - == "ai.droidrun.counter" - for app in apps - ) +def _approve_app_changes(verb: str, args: Mapping[str, object]) -> bool: + if verb == "device.install_app": + source = args.get("source") + return isinstance(source, Path) or ( + isinstance(source, AppIdentity) and source.app_id == COUNTER + ) + return verb == "device.uninstall_app" and args.get("app_id") == COUNTER + + +async def _has_counter(device: AsyncDevice) -> bool: + return any(app.identity.app_id == COUNTER for app in await device.list_apps()) + + +async def _exercise_counter(device: AsyncDevice, source: Path | AppIdentity) -> None: + if await _has_counter(device): + pytest.skip( + "Counter is already installed; refusing to replace a pre-existing app" + ) + installed = False + try: + app = await device.install_app(source) + installed = True + assert app.package_name == COUNTER + await device.start_app(app.package_name) + assert await _has_counter(device) + finally: + if installed or await _has_counter(device): + await device.uninstall_app(COUNTER) + assert not await _has_counter(device) @pytest.mark.smoke_device def test_local_counter_install(local_ready, counter_apk): - from mobilerun.core.devices import AndroidDevice - - async def run(): - device = AndroidDevice(serial=SERIAL) - await device.connect() - app = await device.install_apk(str(counter_apk), reinstall=True) - assert app.package == "ai.droidrun.counter" - try: - await device.start_app(app.package) - assert _has_counter(await device.list_apps()) - await device.uninstall_app(app.package) - finally: - await device.install_apk(str(counter_apk), reinstall=True) - assert _has_counter(await device.list_apps()) + async def run() -> None: + async with AsyncMobilerun(hitl_gate=_approve_app_changes) as core: + async with await core.connect( + SERIAL, backend="local-android-adb" + ) as device: + await _exercise_counter(device, counter_apk) asyncio.run(run()) @pytest.mark.smoke_cloud -def test_cloud_counter_upload_install_and_uninstall(cloud_ready, counter_apk): - from mobilerun.core.devices.cloud import CloudDevice - - async def run(): - device = CloudDevice(device_id=CLOUD_ID) - await device.connect() - app = await device.install_apk(counter_apk) - assert app.package == "ai.droidrun.counter" - try: - await device.start_app(app.package) - assert _has_counter(await device.list_apps()) - await device.uninstall_app(app.package) - finally: - await device.install_app(app) - assert _has_counter(await device.list_apps()) +def test_cloud_counter_install_and_uninstall(cloud_ready, cloud_run): + # Use an existing library entry: APK uploads leave a shared server-side artifact. + async def run() -> None: + async with cloud_run(hitl_gate=_approve_app_changes) as core: + async with await core.connect(CLOUD_ID, backend="cloud") as device: + await _exercise_counter(device, AppIdentity(COUNTER)) asyncio.run(run()) @pytest.mark.smoke_device def test_record_named_home_then_replay_wait(local_ready, tmp_path, monkeypatch): - from mobilerun import AndroidDevice, RecordingDevice - from mobilerun.core.devices import Device - from mobilerun.core.extensions import Extension, device_action + from mobilerun.core.extensions import Extension, compile_tools, function from mobilerun.macro import MacroPlayer, build_macro, load_macro monkeypatch.setenv("MOBILERUN_MACRO_DIRECTORY", str(tmp_path / "macros")) class Navigation(Extension): - @device_action() - async def home(self, device: Device) -> None: + def __init__(self, device: AsyncDevice) -> None: + super().__init__(name="navigation") + self.device = device + + @function + async def home(self) -> None: """Return the emulator to its home screen.""" - await device.press_button("home") - - async def run(): - async with AndroidDevice(SERIAL) as device: - recorder = RecordingDevice(device, runs_dir=tmp_path, capture="actions") - navigation = await Navigation(name="navigation").bind(recorder) - await navigation.home() - await recorder.wait(0.01) - recorder.finish("succeeded") - home, wait = read_run_steps(recorder.run_dir) - assert home.ok and home.action == "extension_call" - assert home.args == {"name": "navigation.home", "arguments": {}} - assert wait.ok and wait.action == "wait" and wait.args == {"duration": 0.01} - assert recorder.run_dir is not None - path = build_macro(recorder.run_dir / "steps.jsonl", "home", step_ids={2}) - assert await MacroPlayer(device).replay_macro(load_macro(path)) + await self.device.key("home") + + async def run() -> None: + async with AsyncMobilerun() as core: + async with await core.connect( + SERIAL, backend="local-android-adb" + ) as device: + navigation = Navigation(device) + try: + (home_tool,) = compile_tools([navigation]) + async with ActionRecording(device, runs_dir=tmp_path) as recording: + async with recording.extension_call( + home_tool.name, {} + ) as outcome: + outcome.set_result(await home_tool.invoke({})) + await device.wait(0.01) + recording.finish("succeeded") + home, wait = read_run_steps(recording.run_dir) + assert home.ok and home.action == "extension_call" + assert home.args == {"name": "navigation.home", "arguments": {}} + assert wait.ok and wait.action == "wait" + assert wait.args == {"seconds": 0.01} + path = build_macro( + recording.run_dir / "steps.jsonl", "home", step_ids={2} + ) + assert await MacroPlayer(device).replay_macro(load_macro(path)) + finally: + await navigation.close() asyncio.run(run()) diff --git a/tests/unit/smoke/test_jobs.py b/tests/unit/smoke/test_jobs.py index 16c0e6ff1..04c9b2418 100644 --- a/tests/unit/smoke/test_jobs.py +++ b/tests/unit/smoke/test_jobs.py @@ -2,11 +2,21 @@ import asyncio import time +from collections.abc import AsyncIterator +from contextlib import asynccontextmanager, suppress import pytest +from mobilerun_core import AsyncDevice, AsyncMobilerun +from mobilerun_sdk import AsyncMobilerun as CloudSDK from pydantic import BaseModel -from mobilerun.clients.cloud import tasks +from mobilerun.clients.cloud.client import cloud_client +from mobilerun.clients.cloud.tasks import Tasks +from mobilerun.clients.local.login_store import LoginStore +from mobilerun.config.settings import get_settings +from mobilerun.core.operator.cloud import CloudTaskOperator +from mobilerun.errors import CloudTaskTimeout +from mobilerun.models.billing import Billing from tests.support.smoke_settings import CLOUD_ID pytestmark = pytest.mark.smoke_cloud @@ -16,105 +26,130 @@ class VisibleScreen(BaseModel): screen: str -def test_cloud_do_and_expect(cloud_ready): - from mobilerun.core.devices.cloud import CloudDevice +@asynccontextmanager +async def _task_phone() -> AsyncIterator[tuple[AsyncDevice, CloudSDK]]: + key = LoginStore.from_settings().resolve_api_key() + base_url = get_settings().MOBILERUN_CLOUD_BASE_URL + async with ( + cloud_client(key, base_url, billing=Billing.NO_COMMERCE) as client, + AsyncMobilerun(bearer=key, base_url=base_url) as core, + await core.connect(CLOUD_ID, backend="cloud") as device, + ): + try: + yield device, client + finally: + await device.key("home") + +def test_cloud_do_and_expect(cloud_ready): async def run(): - device = CloudDevice(device_id=CLOUD_ID) - await device.connect() - try: + async with _task_phone() as (device, client): + operator = CloudTaskOperator( + client=client, extensions=(), billing=Billing.PAID + ) start = time.monotonic() - result = await device.do("Open the Settings app", max_steps=3) + result = await operator.do(device, "Open the Settings app", max_steps=3) print( f"do task_id={result.task_id} duration={time.monotonic() - start:.1f}s success={result.success}" ) assert result.success start = time.monotonic() - result = await device.expect("The Settings app is open") + verdict = await operator.expect(device, "The Settings app is open") print( - f"expect task_id={result.task.task_id} duration={time.monotonic() - start:.1f}s passed={result.passed}" + f"expect task_id={verdict.task.task_id} duration={time.monotonic() - start:.1f}s passed={verdict.passed}" ) - assert result.passed - finally: - await device.press_button("home") + assert verdict.passed asyncio.run(run()) def test_cloud_typed_output(cloud_ready): - from mobilerun.core.devices.cloud import CloudDevice - async def run(): - device = CloudDevice(device_id=CLOUD_ID) - await device.connect() - try: - device._task_started_callback = lambda task_id: print( - f"typed task_id={task_id}", flush=True + async with _task_phone() as (device, client): + operator = CloudTaskOperator( + client=client, + extensions=(), + billing=Billing.PAID, + on_task_started=lambda task_id: print( + f"typed task_id={task_id}", flush=True + ), ) started = time.monotonic() - result = await device.do( - "Describe the current screen briefly", output=VisibleScreen, max_steps=1 + result = await operator.do( + device, + "Describe the current screen briefly", + output=VisibleScreen, + max_steps=1, ) print( f"typed duration={time.monotonic() - started:.1f}s success={result.success}" ) assert result.success and isinstance(result.output, VisibleScreen) + assert result.task_id assert ( - await tasks.trajectory( - device._cloud_client, result.task_id, billing="included" + await Tasks(client=client, billing=Billing.NO_COMMERCE).trajectory( + result.task_id ) is not None ) assert ( - await tasks.screenshots( - device._cloud_client, result.task_id, billing="included" + await Tasks(client=client, billing=Billing.NO_COMMERCE).screenshots( + result.task_id ) is not None ) - finally: - await device.press_button("home") asyncio.run(run()) @pytest.mark.parametrize("cancel", [False, True], ids=["timeout", "cancel"]) def test_cloud_do_timeout_stops_task(cloud_ready, cancel): - from mobilerun.core.devices.cloud import CloudDevice - from mobilerun.errors import CloudTaskTimeout - async def run(): - device = CloudDevice(device_id=CLOUD_ID) - await device.connect() - task_ids = [] - started = asyncio.Event() - - def task_started(task_id): - task_ids.append(task_id) - print(f"task_id={task_id}", flush=True) - started.set() - - device._task_started_callback = task_started - try: + async with _task_phone() as (device, client): + task_ids: list[str] = [] + started = asyncio.Event() + + def task_started(task_id: str) -> None: + task_ids.append(task_id) + print(f"task_id={task_id}", flush=True) + started.set() + + operator = CloudTaskOperator( + client=client, + extensions=(), + billing=Billing.PAID, + on_task_started=task_started, + ) pending = asyncio.create_task( - device.do( + operator.do( + device, "Open the Settings app, then open About phone, then scroll to the bottom", + max_steps=5, timeout=30 if cancel else 5, ) ) - if cancel: - await asyncio.wait_for(started.wait(), 20) - pending.cancel() - with pytest.raises(asyncio.CancelledError if cancel else CloudTaskTimeout): - await pending + try: + if cancel: + await asyncio.wait_for(started.wait(), 20) + pending.cancel() + with pytest.raises( + asyncio.CancelledError if cancel else CloudTaskTimeout + ): + await pending + finally: + if not pending.done(): + pending.cancel() + with suppress(asyncio.CancelledError): + await pending assert task_ids for _ in range(20): - status = await device._client.tasks.get_status(task_ids[0]) + status = await Tasks(client=client, billing=Billing.NO_COMMERCE).status( + task_ids[0] + ) print(f"task_id={task_ids[0]} status={status.status}", flush=True) if status.status in {"cancelled", "stopped", "failed", "completed"}: break await asyncio.sleep(1) assert status.status in {"cancelled", "stopped", "failed"} - finally: - await device.press_button("home") asyncio.run(run()) diff --git a/tests/unit/smoke/test_local_controls.py b/tests/unit/smoke/test_local_controls.py index 7c91e9795..fdb095a0c 100644 --- a/tests/unit/smoke/test_local_controls.py +++ b/tests/unit/smoke/test_local_controls.py @@ -1,20 +1,25 @@ """Local Android smoke checks for discovery, controls, diagnostics and emulator reuse.""" import asyncio -import json import os import subprocess import sys +from collections.abc import Mapping from pathlib import Path import pytest +from mobilerun_core import AsyncMobilerun, HitlDenied +from mobilerun import __version__ from mobilerun.config.migrations import CURRENT_VERSION -from mobilerun.core.devices.android import AndroidDevice from tests.support.smoke_settings import SERIAL +pytestmark = pytest.mark.smoke_device -def _android_app_list(config, *, env=None): + +def _android_app_list( + config: Path, *, env: Mapping[str, str] | None = None +) -> subprocess.CompletedProcess[str]: return subprocess.run( [ str(Path(sys.executable).with_name("mobilerun")), @@ -32,7 +37,6 @@ def _android_app_list(config, *, env=None): ) -@pytest.mark.smoke_device def test_unavailable_android_serial_refuses_read_only_app_list(local_ready, tmp_path): """Even with an online phone, an unavailable serial cannot select it.""" config = tmp_path / "device.yaml" @@ -42,14 +46,7 @@ def test_unavailable_android_serial_refuses_read_only_app_list(local_ready, tmp_ assert result.returncode == 1 and f"ANDROID_SERIAL {serial}" in result.stderr -@pytest.mark.smoke_device -def test_grouped_app_list_discovers_only_android(local_ready, tmp_path): - adb = subprocess.run(["adb", "devices"], check=True, capture_output=True, text=True) - online = [ - line.split()[0] for line in adb.stdout.splitlines() if line.endswith("\tdevice") - ] - if online != [SERIAL]: - pytest.skip("requires exactly the configured local Android device") +def test_grouped_app_list_discovers_only_android(single_local_android, tmp_path): config = tmp_path / "alternate.yaml" config.write_text(f"_version: {CURRENT_VERSION}\ndevice: {{}}\n") result = _android_app_list(config) @@ -58,33 +55,34 @@ def test_grouped_app_list_discovers_only_android(local_ready, tmp_path): assert result.stdout.strip() -@pytest.mark.smoke_device def test_doctor_checks_existing_tcp_forward(local_ready): - from mobilerun.config.settings import get_settings - - def portal_forwards(): - remote = f"tcp:{get_settings().MOBILERUN_PORTAL_REMOTE_PORT}" - lines = subprocess.check_output(["adb", "forward", "--list"], text=True) - return { - line for line in lines.splitlines() if line.split()[::2] == [SERIAL, remote] - } - - before = portal_forwards() - if not before: - pytest.skip("requires an existing Portal TCP forward") + async def forward_port() -> int | None: + async with AsyncMobilerun() as core: + results = await core.local.diagnose_android( + SERIAL, client_version=__version__, checks=("TCP Mode",) + ) + for result in results: + if result.check == "TCP Mode" and result.status == "pass": + port = result.facts.get("forward_port") + if isinstance(port, int): + return port + return None + + before = asyncio.run(forward_port()) + if before is None: + pytest.skip("requires an existing reachable Portal TCP forward") result = subprocess.run( - [sys.executable, "-m", "mobilerun", "doctor", "-d", SERIAL], + [sys.executable, "-m", "mobilerun", "doctor", SERIAL], capture_output=True, text=True, timeout=120, ) output = result.stdout + result.stderr - assert portal_forwards() == before + assert asyncio.run(forward_port()) == before assert result.returncode == 0, output assert "State (tcp)" in output and "Screenshot (tcp)" in output -@pytest.mark.smoke_device def test_local_android_clipboard_reports_unsupported(local_ready): result = subprocess.run( [ @@ -103,49 +101,22 @@ def test_local_android_clipboard_reports_unsupported(local_ready): assert "Clipboard commands require a cloud device ID." in result.stderr -@pytest.mark.smoke_device -def test_local_device_actions_and_extensions(local_ready): - executable = str(Path(sys.executable).with_name("mobilerun")) - env = os.environ.copy() - for command in ( - ["list", SERIAL], - ["extensions", SERIAL, "--json"], - ["call", "device.wait", SERIAL, "--arg", "seconds=0", "--json"], - ): - result = subprocess.run( - [executable, "device", "action", *command], - capture_output=True, - text=True, - timeout=90, - env=env, - ) - assert result.returncode == 0, result.stderr - if command[0] == "list": - assert "device.wait" in result.stdout - else: - json.loads(result.stdout) - - -@pytest.mark.smoke -def test_reuse_running_emulator(): - result = subprocess.run( - ["adb", "-s", "emulator-5554", "emu", "avd", "name"], - capture_output=True, - text=True, - check=True, - ) - if not result.stdout.strip(): - result = subprocess.run( - ["adb", "-s", "emulator-5554", "shell", "getprop", "ro.boot.qemu.avd_name"], - capture_output=True, - text=True, - check=True, - ) - name = result.stdout.splitlines()[0].strip() - - async def ready(): - return await AndroidDevice(avd=name) - - device = asyncio.run(ready()) - assert device._serial == "emulator-5554" - assert not device._started_emulator +def test_reuse_running_emulator(local_ready): + avd = os.getenv("MOBILERUN_SMOKE_AVD") + if not avd or not SERIAL.startswith("emulator-"): + pytest.skip("set MOBILERUN_SMOKE_AVD to the AVD of the running smoke emulator") + + async def run() -> None: + # The default gate denies starting a new process; a running AVD is borrowed. + async with AsyncMobilerun() as core: + try: + device = await core.start_emulator(avd, keep=False) + except HitlDenied: + pytest.fail("Configured smoke AVD is not already running") + async with device: + assert device.device_id == SERIAL + assert SERIAL in { + device.device_id for device in await core.list_devices(scope="local") + } + + asyncio.run(run()) diff --git a/tests/unit/smoke/test_sandbox_functions.py b/tests/unit/smoke/test_sandbox_functions.py index 6ffea98c3..d491921a8 100644 --- a/tests/unit/smoke/test_sandbox_functions.py +++ b/tests/unit/smoke/test_sandbox_functions.py @@ -72,7 +72,9 @@ def test_device_free_sandbox_webhook(real_env, tmp_path, monkeypatch): from mobilerun.errors.cloud import CloudResourceNotFound from mobilerun.models.billing import Billing - hooks = CloudWebhooks(billing=Billing.PAID) + # Deployment and execution are paid; registering/deleting this endpoint is not. + # Unlike the CLI, direct registration rejects duplicate URLs rather than adopting one. + hooks = CloudWebhooks(billing=Billing.NO_COMMERCE) endpoint = asyncio.run(hooks.register(webhook, event_types=[DEFAULT_WEBHOOK_EVENT])) try: print(f"smoke webhook endpoint: {endpoint.id}", flush=True) diff --git a/tests/unit/smoke/test_smoke_credentials.py b/tests/unit/smoke/test_smoke_credentials.py index 0d32d0dbc..70f4d14e0 100644 --- a/tests/unit/smoke/test_smoke_credentials.py +++ b/tests/unit/smoke/test_smoke_credentials.py @@ -7,8 +7,9 @@ from uuid import uuid4 import pytest +from mobilerun_core import AsyncDevice, AsyncMobilerun -from mobilerun import AndroidDevice, RecordingDevice +from mobilerun.core.runs import ActionRecording from mobilerun.macro import MacroStep, build_macro from mobilerun.macro.errors import MacroError from mobilerun.macro.player import MacroPlayer @@ -18,40 +19,44 @@ VALUE = "demo-user" -async def settings_search(device): - await device.press_button("back") +async def settings_search(device: AsyncDevice) -> None: + await device.key("back") await device.start_app("com.android.settings") deadline = time.monotonic() + 15 while time.monotonic() < deadline: - state = await device.state.refresh() + state = await device.observe() field = next( ( element - for element in state.elements - if element.get("className") == "EditText" + for element in state.elements or () + if (element.class_name or "").endswith("EditText") ), None, ) if field: - await device.tap_element(field["index"]) - await asyncio.sleep(0.5) + await device.tap_element(field) + await device.wait(0.5) return search = next( ( element - for element in state.elements - if element.get("resourceId", "").endswith("search_action_bar") + for element in state.elements or () + if (element.resource_id or "").endswith("search_action_bar") ), None, ) if search: - await device.tap_element(search["index"]) - await asyncio.sleep(0.5) + await device.tap_element(search) + await device.wait(0.5) raise AssertionError( "Settings search input did not become available within 15 seconds" ) +async def approve_smoke_tap(action: str, _arguments: dict[str, object]) -> bool: + return action == "device.tap_element" + + @pytest.mark.smoke_device @pytest.mark.parametrize("kind", ["dict", "file", "env"]) def test_credentials_type_real_field(local_ready, tmp_path, monkeypatch, caplog, kind): @@ -60,30 +65,39 @@ def test_credentials_type_real_field(local_ready, tmp_path, monkeypatch, caplog, EnvCredentials, FileCredentials, ) - from mobilerun.core.devices import AndroidDevice - - if kind == "dict": - provider = DictCredentials({"TEST": VALUE}) - elif kind == "file": - path = tmp_path / "credentials.json" - path.write_text(json.dumps({"TEST": VALUE})) - provider = FileCredentials(path) - else: - monkeypatch.setenv("MOBILERUN_SECRET_TEST", VALUE) - provider = EnvCredentials() + caplog.set_level("DEBUG") async def run(): - device = AndroidDevice(serial=SERIAL, use_tcp=True, portal_mode="required") - await provider.bind(device) - await device.connect() - try: - await settings_search(device) - await provider.type_field(None, "password", name="TEST") - state = await device.state.refresh() - assert VALUE in repr(state.elements) - finally: - await device.press_button("home") + async with AsyncMobilerun(hitl_gate=approve_smoke_tap) as core: + device = await core.connect( + SERIAL, + backend="local-android-adb", + use_tcp=True, + portal_mode="required", + ) + async with device: + if kind == "dict": + provider = DictCredentials({"TEST": VALUE}, device=device) + elif kind == "file": + path = tmp_path / "credentials.json" + path.write_text(json.dumps({"TEST": VALUE})) + path.chmod(0o600) + provider = FileCredentials(path, device=device) + else: + monkeypatch.setenv("MOBILERUN_SECRET_TEST", VALUE) + provider = EnvCredentials(device=device) + try: + await settings_search(device) + await provider.type_secret("TEST") + state = await device.observe() + assert any( + VALUE in (element.text or "") + for element in state.elements or () + ) + finally: + await provider.close() + await device.key("home") asyncio.run(run()) assert VALUE not in caplog.text @@ -92,43 +106,49 @@ async def run(): @pytest.mark.smoke_device def test_record_secret_and_replay_wait(local_ready, tmp_path, caplog, monkeypatch): from mobilerun.core.credentials import DictCredentials - from mobilerun.core.devices import AndroidDevice - from mobilerun.core.devices.recording import RecordingDevice from mobilerun.macro.operator import MacroOperator + from mobilerun.utils.credentials.masking import CredentialMasks caplog.set_level("DEBUG") monkeypatch.setenv("MOBILERUN_MACRO_DIRECTORY", str(tmp_path / "macros")) async def run(): - device = AndroidDevice(serial=SERIAL, use_tcp=True, portal_mode="required") - vault = await DictCredentials({"TEST": VALUE}).bind(device) - await device.connect() - recorder = RecordingDevice(device, runs_dir=tmp_path, capture="actions") - try: - await settings_search(device) - await vault.type_field(None, "password", name="TEST") - await recorder.wait(0.4) - recorder.finish("succeeded") - assert [row.action for row in read_run_steps(recorder.run_dir)] == [ - "extension_call", - "wait", - ] - assert recorder.run_dir is not None - steps = recorder.run_dir / "steps.jsonl" - assert VALUE not in steps.read_text() - assert VALUE not in build_macro(steps, "credential").read_text() - # Avoid retyping the credential: select only the recorded wait. - path = build_macro(steps, "wait", step_ids={2}) - started = time.monotonic() - result = await MacroOperator(str(path), delay_between_actions=0).execute( - device, "" + async with AsyncMobilerun(hitl_gate=approve_smoke_tap) as core: + device = await core.connect( + SERIAL, + backend="local-android-adb", + use_tcp=True, + portal_mode="required", ) - assert result.success and time.monotonic() - started >= 0.4 - finally: - try: - await device.press_button("home") - finally: - await recorder.close() + async with device: + vault = DictCredentials({"TEST": VALUE}, device=device) + try: + await settings_search(device) + recorder = ActionRecording(device, runs_dir=tmp_path) + async with recorder: + with CredentialMasks.scope(redactor=recorder.redactor): + async with recorder.extension_call( + "vault.type_secret", {"name": "TEST"} + ): + await vault.type_secret("TEST") + await device.wait(0.4) + recorder.finish("succeeded") + assert [row.action for row in read_run_steps(recorder.run_dir)] == [ + "extension_call", + "wait", + ] + steps = recorder.run_dir / "steps.jsonl" + assert VALUE not in steps.read_text() + assert VALUE not in build_macro(steps, "credential").read_text() + path = build_macro(steps, "wait", step_ids={2}) + started = time.monotonic() + result = await MacroOperator(path, delay_between_actions=0).do( + device, "" + ) + assert result.success and time.monotonic() - started >= 0.4 + finally: + await vault.close() + await device.key("home") asyncio.run(run()) assert VALUE not in caplog.text @@ -136,15 +156,21 @@ async def run(): @pytest.mark.smoke_cloud def test_cloud_wait(cloud_ready): - from mobilerun.core.devices.cloud import CloudDevice + from mobilerun.clients.local.login_store import LoginStore + from mobilerun.config.settings import get_settings async def run(): - device = CloudDevice(device_id=CLOUD_ID) - await device.connect() - started = time.monotonic() - await device.wait(0.25) - assert time.monotonic() - started >= 0.25 - await device.press_button("home") + async with AsyncMobilerun( + bearer=LoginStore.from_settings().resolve_api_key(), + base_url=get_settings().MOBILERUN_CLOUD_BASE_URL, + ) as core: + async with await core.connect(CLOUD_ID, backend="cloud") as device: + try: + started = time.monotonic() + await device.wait(0.25) + assert time.monotonic() - started >= 0.25 + finally: + await device.key("home") asyncio.run(run()) @@ -171,20 +197,40 @@ async def run(): @pytest.mark.smoke_device -def test_protected_step_prevents_navigation(local_ready): +def test_protected_step_prevents_navigation(local_ready, tmp_path): + from mobilerun.core.credentials import CredentialPolicy, DictCredentials + async def run(): - async with RecordingDevice(AndroidDevice(SERIAL)) as recorder: + async with AsyncMobilerun() as core: + async with await core.connect( + SERIAL, backend="local-android-adb" + ) as device: + await assert_preflight(device) + + async def assert_preflight(device: AsyncDevice) -> None: + vault = DictCredentials({"example": VALUE}, device=device) + vault.policies = (CredentialPolicy("example", requires_approval=True),) + try: macro = [ - MacroStep(i=1, action="button_press", args={"button": "home"}), MacroStep( + schema_version=2, i=1, action="key", args={"name_or_code": "home"} + ), + MacroStep( + schema_version=2, i=2, - action="type_secret", - args={"name": "example", "protected": True}, + action="extension_call", + args={ + "name": "vault.type_secret", + "arguments": {"name": "example"}, + }, ), ] - with pytest.raises(MacroError, match="approval"): - await MacroPlayer(recorder).replay_macro(macro) - assert recorder.run_dir is None + async with ActionRecording(device, runs_dir=tmp_path) as recorder: + with pytest.raises(MacroError, match="approval"): + await MacroPlayer(device, extensions=[vault]).replay_macro(macro) + assert not (recorder.run_dir / "steps.jsonl").exists() + finally: + await vault.close() asyncio.run(run()) @@ -237,10 +283,10 @@ async def run(): {"password": "smoke-updated-value", "username": "smoke-user"}, ) await vault.update(package, name, "password", "smoke-final-value") - item = await vault._find(package, name=name) - assert item is not None - assert set(item.fields) == {"password", "username"} - assert item.fields["password"] == "smoke-final-value" + item = next( + item for item in await vault.list(package) if item["name"] == name + ) + assert set(item["fields"]) == {"password", "username"} await vault.delete(package, name, "username") assert any( item["name"] == name and set(item["fields"]) == {"password"} diff --git a/tests/unit/smoke/test_webhook_cli.py b/tests/unit/smoke/test_webhook_cli.py index 10ab80f22..1e5010155 100644 --- a/tests/unit/smoke/test_webhook_cli.py +++ b/tests/unit/smoke/test_webhook_cli.py @@ -14,7 +14,8 @@ @pytest.mark.smoke_cloud -def test_webhook_cli_lifecycle(real_env): +def test_webhook_cli_lifecycle(real_env, monkeypatch): + monkeypatch.setenv("MOBILERUN_BILLING", "no_commerce") runner = CliRunner() with ( httpx.Client(base_url="https://webhook.site", timeout=15) as receiver, diff --git a/tests/unit/test_plugin_api_version.py b/tests/unit/test_plugin_api_version.py new file mode 100644 index 000000000..7dfb2bf54 --- /dev/null +++ b/tests/unit/test_plugin_api_version.py @@ -0,0 +1,8 @@ +"""The add-on contract uses an integer version marker.""" + +from mobilerun.version import PLUGIN_API_VERSION + + +def test_plugin_api_version(): + assert type(PLUGIN_API_VERSION) is int + assert PLUGIN_API_VERSION == 1 diff --git a/tests/unit/utils/test_prompt_loader.py b/tests/unit/utils/test_prompt_loader.py index 29d151f7e..ecd6ab4ca 100644 --- a/tests/unit/utils/test_prompt_loader.py +++ b/tests/unit/utils/test_prompt_loader.py @@ -94,6 +94,69 @@ def _actions(n): } _STRING_HISTORY = {**_POPULATED, "action_history": "a1\na2"} +_UNREPORTED_SCREEN = dict(package=None, activity=None, focus=None, keyboard=None) +# LastStepBlock reduces the ScreenView to this sanitized template context. +_MEMORY_CONTEXTS = { + "memory/last_step.jinja2": ( + { + "step": 2, + "calls": [("tap_element", '{"index": 1}', True, "Opened Settings")], + "thought": "Open Settings", + "before": _UNREPORTED_SCREEN, + "after": dict( + package="com.android.settings", + activity="Settings", + focus='EditText "Search settings"', + keyboard=False, + ), + "screen_changed": True, + }, + { + "step": 1, + "calls": [], + "thought": None, + "before": _UNREPORTED_SCREEN, + "after": _UNREPORTED_SCREEN, + "screen_changed": None, + }, + ), + "memory/last_subgoal.jinja2": ( + { + "result": { + "subgoal": "Open Settings", + "status": { + "message": "Done", + "reason": "complete", + "jev_abstention": None, + }, + "screen_changed": True, + }, + "status": "Succeeded", + "before": ("launcher", None), + "after": ("com.android.settings", "Settings"), + "summary": "", + "plan": ["Read battery level"], + }, + { + "result": { + "subgoal": "Open Settings", + "status": { + "message": None, + "reason": "blocked", + "jev_abstention": None, + }, + "screen_changed": None, + }, + "status": "Failed", + "before": None, + "after": None, + "summary": "", + "plan": [], + }, + ), + "memory/notes.jinja2": ({"notes": ["Battery 100%"]}, {"notes": []}), +} + TEMPLATES = sorted(PROMPTS_DIR.rglob("*.jinja2")) if PROMPTS_DIR else [] @@ -118,6 +181,8 @@ def test_bundled_templates_found(): ids=["populated", "empty", "string-history"], ) def test_bundled_templates_render_identically(path, variables): + if contexts := _MEMORY_CONTEXTS.get(path.relative_to(PROMPTS_DIR).as_posix()): + variables = variables | contexts[1 if variables is _EMPTY else 0] source = path.read_text(encoding="utf-8") plain = Environment( trim_blocks=True, lstrip_blocks=True, keep_trailing_newline=False diff --git a/tests/unit/utils/test_redaction.py b/tests/unit/utils/test_redaction.py new file mode 100644 index 000000000..6accfad20 --- /dev/null +++ b/tests/unit/utils/test_redaction.py @@ -0,0 +1,228 @@ +"""Public persistence redaction and legacy masking behavior.""" + +import asyncio +import logging + +import pytest + +from mobilerun.utils import redaction +from mobilerun.utils.codes import verification_read_codes + + +def test_redactor_masks_text_and_json_values_without_changing_keys(): + redactor = redaction.Redactor() + redactor.remember_codes("482913") + redactor.remember_sensitive(["fixture-credential"]) + value = {"fixture-credential": ["PIN 482 913", {"error": "bad fixture-credential"}]} + + assert redactor.redact("OTP 482 913; credential=fixture-credential") == ( + "OTP ***; credential=***" + ) + assert redactor.redact_json(value) == { + "fixture-credential": ["PIN ***", {"error": "bad ***"}] + } + assert redactor.redact_json([value, 482913, 42, None], whole_value=True) == [ + {"fixture-credential": ["***", {"error": "***"}]}, + "***", + 42, + None, + ] + assert value["fixture-credential"][0] == "PIN 482 913" + + +@pytest.mark.parametrize( + "message,compacted", + [ + ("call 555 123 4567 ext 12", "5551234567"), + ("at 12:34", "1234"), + ("paid 12.34", "1234"), + ("due 2026-11-27 10:30", "202611271030"), + ], +) +def test_history_does_not_register_unrelated_number_groups(message, compacted): + redactor = redaction.Redactor() + redactor.remember_codes(*verification_read_codes("mailbox", "messages", message)) + assert redactor.redact(compacted) == compacted + + +def test_redactor_masks_tab_grouping_from_a_compact_code(): + redactor = redaction.Redactor() + redactor.remember_codes("123456") + assert redactor.redact("OTP 12\t34\t56") == "OTP ***" + + +@pytest.mark.parametrize( + "message,expected", + [ + ("12 34 56", ["12 34", "12 34 56", "34 56"]), + ("123-456", ["123-456"]), + ("Your code 123456 10 minutes", ["123456"]), + ("1234 56", ["1234", "1234 56"]), + ("call 555 123 4567 ext 12", ["4567", "555 123", "123 4567"]), + ( + "2026-11-27 10:30", + ["2026", "2026-11", "2026-11-27", "11-27", "11-27 10", "27 10"], + ), + ("Your code: 123-456 10 minutes", ["123-456", "123-456 10", "456 10"]), + ("Your code: 123-456 5 minutes", ["123-456"]), + ("Your code: 123 456 5 min", ["123 456"]), + ], +) +def test_history_code_candidates(message, expected): + assert list(verification_read_codes("mailbox", "messages", message)) == expected + + +def test_history_candidate_windows_are_bounded_in_a_long_run(): + group_count = 1024 + message = " ".join(["12"] * group_count) + candidates = list(verification_read_codes("mailbox", "messages", message)) + assert len(candidates) == 3 * group_count - 6 + assert set(candidates) == {"12 12", "12 12 12", "12 12 12 12"} + + +@pytest.mark.parametrize( + "message,grouped", + [ + ("Your code: 123-456 10 minutes", "123-456"), + ("Your code: 123-456 5 minutes", "123-456"), + ("Your code: 123 456 5 min", "123 456"), + ("Code 81 42 73 15 minutes left", "81 42 73"), + ("Use 083-175-20 30 minutes after login", "083-175-20"), + ("12 34 56 is your sign-in code", "12 34 56"), + ("97-24-61. Do not share it.", "97-24-61"), + ("Sign in with code 15 29 83 47", "15 29 83 47"), + ("OTP 00 42 expires now", "00 42"), + ("OTP: 4321-7654!", "4321-7654"), + ("Code: 12\t34\t56\t5 min", "12\t34\t56"), + ("Code: 41 -\t27 - 83", "41 -\t27 - 83"), + ("Use 16\t72 48 to verify", "16\t72 48"), + ("Code 64-25 81 to verify your device", "64-25 81"), + ("Call 555 123 4567. Your code is 65 43 21.", "65 43 21"), + ("Code 21 43 65 555 123 4567 is our support number", "21 43 65"), + ("555 123 4567 77-31-92 is your one-time code", "77-31-92"), + ("On 2026-11-27 at 10:30 use 17-48-62", "17-48-62"), + ("Use 35 72 19 2026-11-27 is the expiration date", "35 72 19"), + ("Purchase $12.34. Code: 36-72-19", "36-72-19"), + ("Use 45-67-89 12.50 USD charged", "45-67-89"), + ("At 12:34 45-67-89 was issued", "45-67-89"), + ("Backup codes: 123-456,789-012", "123-456"), + ("Backup codes: 123-456,789-012", "789-012"), + ("Your code: 12 34 56 10 minutes", "12 34 56"), + ("Support: 021 555 12 34\nYour code: 938271", "938 271"), + ("1.5 123-456", "123-456"), + ("10:30 123 456", "123 456"), + ("2026-11-27 123-456", "123-456"), + ("ref 12/34 code 12 34 56", "12 34 56"), + ("Paid $12.34,123-456 is your code", "123-456"), + ], +) +def test_history_masks_both_code_forms_in_realistic_messages(message, grouped): + redactor = redaction.Redactor() + redactor.remember_codes(*verification_read_codes("mailbox", "messages", message)) + compact = grouped.translate(str.maketrans("", "", " \t-")) + assert redactor.redact(compact) == "***" + assert redactor.redact(grouped) == "***" + + +def test_redactor_taint_and_representation(): + redactor = redaction.Redactor() + redactor.remember_sensitive("fixture-credential") + redactor.remember_codes("482913") + assert redactor.redact("fixture-credential") == "***" + assert not redactor.sensitive_ui + redactor.mark_sensitive() + assert redactor.sensitive_ui + assert not redaction.Redactor().sensitive_ui + with pytest.raises(AttributeError): + redactor.sensitive_ui = False # type: ignore[misc] + for rendering in (str(redactor), repr(redactor)): + assert "fixture-credential" not in rendering + assert "482913" not in rendering + + +def test_separate_runs_and_nested_argument_scopes(): + first = redaction.Redactor() + first.remember_sensitive("first-canary") + with redaction.secret_scope(redactor=first) as active: + assert active is first + with redaction.secret_scope("temporary-canary", ""): + assert redaction.redact("first-canary temporary-canary") == "*** ***" + assert ( + redaction.redact("first-canary temporary-canary") == "*** temporary-canary" + ) + with redaction.secret_scope("second-canary", redactor=redaction.Redactor()): + assert redaction.redact("first-canary second-canary") == "first-canary ***" + assert redaction.redact("first-canary second-canary") == "*** second-canary" + + assert first.redact("temporary-canary") == "temporary-canary" + assert redaction.redact("first-canary 482913") == "first-canary 482913" + + +def test_concurrent_scopes_mask_only_their_own_codes_and_credentials(): + text = "first-canary 482913; second-canary 365901" + + async def run(secret, code, ready, peer_ready): + with redaction.secret_scope(secret) as active: + active.remember_codes(code) + ready.set() + await peer_ready.wait() + return redaction.redact(text) + + async def run_both(): + a_ready = asyncio.Event() + b_ready = asyncio.Event() + return await asyncio.gather( + run("first-canary", "482913", a_ready, b_ready), + run("second-canary", "365901", b_ready, a_ready), + ) + + assert asyncio.run(run_both()) == [ + "*** ***; second-canary 365901", + "first-canary 482913; *** ***", + ] + assert redaction.redact(text) == text + + +def test_active_scope_redacts_error_text_and_logged_traceback(caplog): + logger = logging.getLogger(__name__) + with redaction.secret_scope() as active: + active.remember_codes("482913") + active.remember_sensitive("fixture-credential") + try: + raise ValueError("PIN 482-913 with fixture-credential") + except ValueError as error: + assert redaction.redact(str(error)) == "PIN *** with ***" + logger.exception("rejected fixture-credential") + assert "rejected ***" in caplog.text + assert "ValueError: PIN *** with ***" in caplog.text + assert "482-913" not in caplog.text + assert "fixture-credential" not in caplog.text + + +def test_recording_scope_masks_overlapping_outer_and_recording_values(): + recorder = redaction.Redactor() + recorder.remember_sensitive("scope-canary") + with redaction.secret_scope("outer-scope"): + with redaction.secret_scope(redactor=recorder, recording=True): + assert redaction.redact("outer-scope-canary") == "***" + + +def test_argument_masking_masks_keys_and_whole_values(): + with redaction.secret_scope("fixture-credential"): + assert redaction.mask_step_args( + {"prefix fixture-credential": ["error fixture-credential", "OTP 482913"]}, + contains_code=lambda text: "482913" in text, + ) == {"prefix ***": ["***", "***"]} + + +def test_remember_sensitive_does_not_coerce_opaque_values(): + class OpaqueSecret: + def __str__(self): + raise AssertionError("opaque secret was rendered") + + __repr__ = __str__ + + redactor = redaction.Redactor() + with pytest.raises(TypeError, match="Redaction values must be strings"): + redactor.remember_sensitive(["fixture-credential", OpaqueSecret()]) + assert redactor.redact("fixture-credential") == "fixture-credential" diff --git a/tests/unit/utils/test_screen_fingerprint.py b/tests/unit/utils/test_screen_fingerprint.py index f763e53e0..bfc461d44 100644 --- a/tests/unit/utils/test_screen_fingerprint.py +++ b/tests/unit/utils/test_screen_fingerprint.py @@ -2,7 +2,7 @@ def test_fingerprint_normalizes_camelcase_and_legacy_snapshots(): - from mobilerun.utils.screen_fingerprint import screen_fingerprint + from mobilerun.utils.screen.fingerprint import screen_fingerprint raw = { "phone_state": {"packageName": "example", "activityName": "main"}, @@ -41,7 +41,7 @@ def test_fingerprint_normalizes_camelcase_and_legacy_snapshots(): def test_fingerprint_ignores_text_only_nodes_and_keeps_app_with_empty_tree(): from mobilerun.models import Fingerprint - from mobilerun.utils.screen_fingerprint import screen_fingerprint + from mobilerun.utils.screen.fingerprint import screen_fingerprint assert screen_fingerprint({}) == Fingerprint(app=None, activity=None, elements=()) assert screen_fingerprint( @@ -66,7 +66,7 @@ def test_fingerprint_match_requires_same_app_and_activity( app, activity, elements, threshold, matched ): from mobilerun.models import Fingerprint - from mobilerun.utils.screen_fingerprint import fingerprint_matches + from mobilerun.utils.screen.fingerprint import fingerprint_matches expected = Fingerprint(app="app", activity="main", elements=("a", "b")) observed = Fingerprint(app=app, activity=activity, elements=elements) @@ -75,7 +75,7 @@ def test_fingerprint_match_requires_same_app_and_activity( def test_fingerprint_match_rejects_missing_observation_and_matches_app_only(): from mobilerun.models import Fingerprint - from mobilerun.utils.screen_fingerprint import fingerprint_matches + from mobilerun.utils.screen.fingerprint import fingerprint_matches empty = Fingerprint(app=None, activity=None, elements=()) app_only = Fingerprint(app="example", activity=None, elements=()) diff --git a/tests/unit/utils/test_terminal.py b/tests/unit/utils/test_terminal.py index 4a0d92c22..0f3e8aae0 100644 --- a/tests/unit/utils/test_terminal.py +++ b/tests/unit/utils/test_terminal.py @@ -6,7 +6,7 @@ import pytest from mobilerun.cli.base import menu -from mobilerun.clients.cloud import billing +from mobilerun.cli.base.billing import BillingConsentError, require_consent_possible from mobilerun.utils.terminal import can_prompt @@ -39,6 +39,12 @@ def test_cli_and_billing_checks_differ_only_by_stream( monkeypatch.setattr(sys, "stdin", _stream(True)) monkeypatch.setattr(sys, "stdout", _stream(stdout)) monkeypatch.setattr(sys, "stderr", _stream(stderr)) - results = menu.is_interactive(), billing.billing_prompt_is_interactive() + try: + require_consent_possible(yes=False) + except BillingConsentError: + can_bill = False + else: + can_bill = True + results = menu.is_interactive(), can_bill monkeypatch.undo() assert results == (menu_prompts, billing_prompts) diff --git a/uv.lock b/uv.lock index 16602a038..75533049a 100644 --- a/uv.lock +++ b/uv.lock @@ -660,7 +660,7 @@ wheels = [ [[package]] name = "mobilerun" -version = "0.7.4" +version = "0.9.0" source = { editable = "." } dependencies = [ { name = "aiofiles" }, @@ -672,6 +672,7 @@ dependencies = [ { name = "httpx" }, { name = "inquirerpy" }, { name = "jinja2" }, + { name = "mobilerun-core" }, { name = "mobilerun-core-local", extra = ["cloud"] }, { name = "mobilerun-sdk" }, { name = "pillow" }, @@ -725,7 +726,8 @@ requires-dist = [ { name = "inquirerpy", specifier = ">=0.3.4" }, { name = "jinja2", specifier = ">=3.1.6" }, { name = "jsonschema", marker = "extra == 'sandbox'", specifier = ">=4,<5" }, - { name = "mobilerun-core-local", extras = ["cloud"], specifier = ">=0.6.3" }, + { name = "mobilerun-core", specifier = ">=1.12.1,<2" }, + { name = "mobilerun-core-local", extras = ["cloud"], specifier = ">=0.7.3" }, { name = "mobilerun-functions", extras = ["device"], marker = "extra == 'sandbox'", specifier = "==0.1.0" }, { name = "mobilerun-sdk", specifier = ">=6.3.1,<7" }, { name = "mypy", marker = "extra == 'dev'", specifier = ">=1.0.0" }, @@ -756,19 +758,19 @@ dev = [ [[package]] name = "mobilerun-core" -version = "1.12.0" +version = "1.12.1" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "mobilerun-sdk" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/a7/f4/356f9ad9af849c1152fe466967cffd8f5973ffef62aa40f7e607d4646603/mobilerun_core-1.12.0.tar.gz", hash = "sha256:cca13d678ffb715dfcbd76d1166bdd5f44799bcb6920eb7129531e43dd5a13d3", size = 123751, upload-time = "2026-11-12T19:05:12.957Z" } +sdist = { url = "https://files.pythonhosted.org/packages/b3/69/4f75c7d2138bfd9aeaa57144e48c25947b804cc41e8171f4e9d8fbfb5119/mobilerun_core-1.12.1.tar.gz", hash = "sha256:77fb2faf34678ee768533faeb243a7fdb717e6bd974b61550e315dd6cab13506", size = 185329, upload-time = "2026-11-27T12:47:05.659Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/29/76/593c82c4c0dfdf22e75dfc1b8d248c591033aeba7ba28c744cc2349917ac/mobilerun_core-1.12.0-py3-none-any.whl", hash = "sha256:2f754c26712ee5fc42e30c1ab08154134b497d19579a2bba3c63dda081305190", size = 63833, upload-time = "2026-11-12T19:05:11.268Z" }, + { url = "https://files.pythonhosted.org/packages/51/91/8f59cfe3b4eb032c9c51ab4e4f9616fa2b27eda9b731d6e877fb160caa2a/mobilerun_core-1.12.1-py3-none-any.whl", hash = "sha256:503a4d8fcd206c49525b5584f49954e5e6445a8371c9b641547d47decabdd42f", size = 94980, upload-time = "2026-11-27T12:47:04.208Z" }, ] [[package]] name = "mobilerun-core-local" -version = "0.6.3" +version = "0.7.3" source = { registry = "https://pypi.org/simple" } dependencies = [ { name = "async-adbutils" }, @@ -776,9 +778,9 @@ dependencies = [ { name = "requests" }, { name = "rich" }, ] -sdist = { url = "https://files.pythonhosted.org/packages/db/ce/288ebd92a732d314d5122186863c72ed72b33cab70cce3073d5aaf8130e3/mobilerun_core_local-0.6.3.tar.gz", hash = "sha256:f7187d42f060767e58037c3aa3bdbf774920ea4e4519879c301c9b2bc7a00458", size = 54914, upload-time = "2026-10-13T17:02:26.808Z" } +sdist = { url = "https://files.pythonhosted.org/packages/20/f3/ff1b8502aa9d0eb9ee11dc82e57980fe2a93e86f24cf4e8b6c6cc03fe3cc/mobilerun_core_local-0.7.3.tar.gz", hash = "sha256:35afb599cbc476df9cd3e39cfbe20e18cd4c060838e24bd47ba3b1807b59b254", size = 88644, upload-time = "2026-11-27T11:59:46.83Z" } wheels = [ - { url = "https://files.pythonhosted.org/packages/dc/9b/19572366a08eef8c8c475693d71432af16ed5e12efcdc610cb2cad51356d/mobilerun_core_local-0.6.3-py3-none-any.whl", hash = "sha256:91364da308591a3c50911f481e4a6d783cde9ae91cc948bbfe4f9ea72c6e2d4a", size = 52246, upload-time = "2026-10-13T17:02:25.282Z" }, + { url = "https://files.pythonhosted.org/packages/c6/26/79074c5363ab6400941ea51e3e67872fb8dc35eeb8bb270a9e4d8c7cf3df/mobilerun_core_local-0.7.3-py3-none-any.whl", hash = "sha256:b2a5931ea8fe65feee5b63b5e91e47ead867f816d8ecedca64cdbdb726a31cad", size = 64765, upload-time = "2026-11-27T11:59:45.638Z" }, ] [package.optional-dependencies]