Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -398,6 +398,10 @@ The old spellings are removed; there are no aliases. Replace them as follows:
| Run `--steps` | `-s` / `--max-steps` |
| Run `--control-backend`, `--device-id` | `--backend`, `--backend-device` for visual remote control |
| Run `--no-vision-only` | Omit `--vision-only` |
| `-p GoogleGenAI`, `OpenAIResponses`, `OpenAILike` | `-p gemini`, `openai`, `openai-like` |
| `-p openai_oauth`, `anthropic_oauth`, `gemini_oauth_code_assist`, `xai_oauth` | `-p openai-oauth`, `anthropic-oauth`, `gemini-oauth`, `xai-oauth` |
| Device command `--tcp` / `--no-tcp`, `apps --no-system` | Omit |
| Device commands installing the Portal on first use | `mobilerun device setup` |
| Setup `--path`, `-pv` | `--apk`, `--portal-version` |
| Macro replay `-m` (step limit), `-t` (delay), `-s` (start step) | `-s` / `--max-steps`, `--delay`, `--start-from`; `-m` now selects a model |
| `DROIDRUN_CONFIG`, `DROIDRUN_TELEMETRY_ENABLED` | `MOBILERUN_CONFIG`, `MOBILERUN_TELEMETRY_ENABLED` |
Expand Down
39 changes: 29 additions & 10 deletions mobilerun/cli/device_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,15 @@
)


def _tree_unavailable(state):
return (
getattr(state, "dead_tree", False)
or getattr(state, "a11y_tree_available", True) is False
)


@contextmanager
def device_driver(params=None, *, selection=None):
def device_driver(params=None, *, selection=None, require_portal=False):
"""Resolve Click's device options once and yield the connected core Device."""
from mobilerun.agent.utils.android_device import is_portal_http_url

Expand All @@ -58,21 +65,34 @@ def device_driver(params=None, *, selection=None):
)
token = portal_token(selection)
client = core_client(params["api_url"], cloud=selection.backend == "cloud")
with local_adb_errors(selection.backend == "local-android-adb"):
over_adb = selection.backend == "local-android-adb"
# Only the ADB backend can run with or without the Portal.
options = {}
if over_adb:
portal_mode = selection.config.device.portal_mode
if require_portal and portal_mode == "auto":
portal_mode = "required"
options["portal_mode"] = portal_mode
with local_adb_errors(over_adb):
try:
connected = client.connect(
selection.device,
backend=selection.backend,
platform=selection.platform,
url=selection.device if is_portal_http_url(selection.device) else None,
token=token,
**options,
)
# Connecting over ADB makes the Portal keyboard the active one.
keyboard_set = selection.backend == "local-android-adb"
# Connecting through the Portal makes its keyboard the active one.
keyboard_set = over_adb and options["portal_mode"] != "disabled"
try:
yield connected
except Exception as exc:
keyboard_set = keyboard_set and not adb_unavailable(exc)
if over_adb and "Portal is not available" in str(exc):
raise click.ClickException(
f"{exc}. Install it with `mobilerun device setup`."
) from None
raise
finally:
connected.close()
Expand All @@ -83,8 +103,10 @@ def device_driver(params=None, *, selection=None):


def probe_device(params, *, selection=None):
with device_driver(params, selection=selection) as device:
device.ui()
"""Read the UI once, through the Portal unless the config turns it off."""
with device_driver(params, selection=selection, require_portal=True) as device:
if _tree_unavailable(device.ui()):
raise click.ClickException("The device UI tree is unavailable.")


@click.group(
Expand Down Expand Up @@ -196,10 +218,7 @@ def ui(json_output, all_elements, **params):
emit(json.loads(device.ui_json()), json_output=True)
return
state = device.ui()
if (
getattr(state, "dead_tree", False)
or getattr(state, "a11y_tree_available", True) is False
):
if _tree_unavailable(state):
raise click.ClickException("The device UI tree is unavailable.")
for line in ui_lines(state, all_elements):
emit(line)
Expand Down
20 changes: 15 additions & 5 deletions mobilerun/cli/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,13 @@ def clean(value):
"--steps": "-s/--max-steps",
"-pv": "--portal-version",
"--control-backend": "--backend",
# No replacement: the flag restated the default.
"--no-debug": None,
"--no-vision-only": None,
"--no-system": None,
# Only reached on commands without a TCP mode.
"--tcp": None,
"--no-tcp": None,
}


Expand All @@ -292,11 +299,11 @@ def parse_args(self, ctx, args):
if exc.option_name in {"p", "-p"} and legacy_cluster
else exc.option_name
)
replacement = self.removed_flags.get(flag)
if replacement:
if flag in self.removed_flags:
replacement = self.removed_flags[flag]
advice = f"Use {replacement} instead." if replacement else "Omit it."
raise click.UsageError(
f"Removed option: {flag}. Use {replacement} instead.",
ctx,
f"Removed option: {flag}. {advice}", ctx
) from None
if self.dash_hint:
exc.message += "\nPut `--` before arguments that start with a dash."
Expand Down Expand Up @@ -457,7 +464,10 @@ def resolve_command(self, ctx, args):
"'" + " ".join(_follow(path, command, args[1:])) + "'"
for path, command in matches
)
exc.message += f" Did you mean {suggestions}?"
# A plain usage error keeps click from adding its own guess.
raise click.UsageError(
f"{exc.message} Did you mean {suggestions}?", ctx
) from None
raise

def suggest_commands(self, ctx, name):
Expand Down
31 changes: 30 additions & 1 deletion mobilerun/cli/providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,40 @@ def runtime(self):
}


_RENAMED_PROVIDERS = {
"googlegenai": "gemini",
"google": "gemini",
"gemini_oauth_code_assist": "gemini-oauth",
"openairesponses": "openai",
"gpt": "openai",
"openai_oauth": "openai-oauth",
"claude": "anthropic",
"anthropic_oauth": "anthropic-oauth",
"xai_oauth": "xai-oauth",
"openailike": "openai-like",
"openai_like": "openai-like",
"openai_compatible": "openai-like",
"z.ai": "zai",
}


class ProviderChoice(click.Choice):
"""Point a removed provider name at its replacement."""

def convert(self, value, param, ctx):
renamed = _RENAMED_PROVIDERS.get(str(value).lower())
if renamed in self.choices:
self.fail(
f"Removed provider name: {value}. Use {renamed} instead.", param, ctx
)
return super().convert(value, param, ctx)


def _provider_option(names, note=""):
return click.option(
"-p",
"--provider",
type=click.Choice(names, case_sensitive=False),
type=ProviderChoice(names, case_sensitive=False),
metavar="PROVIDER",
help="LLM provider: "
+ ", ".join(names)
Expand Down
1 change: 1 addition & 0 deletions mobilerun/cli/run.py
Original file line number Diff line number Diff line change
Expand Up @@ -490,6 +490,7 @@ def shell_complete(self, ctx, incomplete):

@click.command(
cls=Command,
removed_flags={**Command.removed_flags, "--device-id": "--backend-device"},
epilog=examples(
'mobilerun run "Open Settings"',
'mobilerun run "Open Settings" -d DEVICE -p openai -m MODEL',
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ description = "A framework for controlling mobile devices through LLM agents"
authors = [{ name = "Niels Schmidt", email = "niels@droidrun.ai" }]
dependencies = [
"async_adbutils",
"click>=8.3,<9",
"llama-index==0.14.23",
"posthog>=6.7.6",
"pydantic>=2.11.10",
Expand Down
7 changes: 7 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@
CHROME_BAR = "com.android.chrome:id/url_bar"


@pytest.fixture(autouse=True)
def no_ambient_cloud_key(monkeypatch):
"""A key exported in the developer's shell must not reach the tests."""
monkeypatch.delenv("MOBILERUN_API_KEY", raising=False)
monkeypatch.delenv("MOBILERUN_CLOUD_API_KEY", raising=False)


@pytest.fixture(autouse=True)
def no_keyboard_hand_back(monkeypatch):
"""Device command tests fake the device, so nothing may reach real ADB."""
Expand Down
155 changes: 155 additions & 0 deletions tests/test_cli_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -433,6 +433,157 @@ async def disable(serial):
assert calls == ["tap", "close", "keyboard:serial"]


def _adb_selection(portal_mode="auto"):
config = MobileConfig()
config.device.portal_mode = portal_mode
return SimpleNamespace(
device="serial", backend="local-android-adb", platform="android", config=config
)


def _fake_device_commands(monkeypatch, selection, device):
from mobilerun.cli import device_commands

client = SimpleNamespace(connect=Mock(return_value=device), close=Mock())
monkeypatch.setattr(
device_commands, "select_device", AsyncMock(return_value=selection)
)
monkeypatch.setattr(device_commands, "core_client", lambda *a, **kw: client)
disable = AsyncMock()
monkeypatch.setattr(device_commands, "disable_portal_keyboard", disable)
return client, disable


@pytest.mark.parametrize(
("configured", "command", "sent"),
[
("auto", ["tap", "1", "2"], "auto"),
("required", ["tap", "1", "2"], "required"),
("disabled", ["tap", "1", "2"], "disabled"),
("auto", ["ping"], "required"),
("disabled", ["ping"], "disabled"),
# An invalid value reaches the driver's own check on ping too.
("bogus", ["ping"], "bogus"),
],
)
def test_device_commands_follow_the_configured_portal_mode(
monkeypatch, configured, command, sent
):
device = SimpleNamespace(
tap=Mock(), ui=Mock(return_value=SimpleNamespace()), close=Mock()
)
client, disable = _fake_device_commands(
monkeypatch, _adb_selection(configured), device
)

result = CliRunner().invoke(cli, ["device", *command, "-d", "serial"])

assert result.exit_code == 0, result.output
assert client.connect.call_args.kwargs["portal_mode"] == sent
# With the Portal off, its keyboard was never switched on.
assert disable.await_count == (0 if sent == "disabled" else 1)


@pytest.mark.parametrize(
"state",
[SimpleNamespace(dead_tree=True), SimpleNamespace(a11y_tree_available=False)],
)
def test_ping_fails_without_a_usable_ui_tree(monkeypatch, state):
device = SimpleNamespace(ui=Mock(return_value=state), close=Mock())
_fake_device_commands(monkeypatch, _adb_selection(), device)

result = CliRunner().invoke(cli, ["device", "ping", "-d", "serial"])

assert result.exit_code == 1
assert "UI tree is unavailable" in result.output


def test_ping_fails_when_the_portal_is_missing(monkeypatch):
def ui():
raise ConnectionError("Portal is not available on this Android device")

device = SimpleNamespace(ui=ui, close=Mock())
_fake_device_commands(monkeypatch, _adb_selection(), device)

result = CliRunner().invoke(cli, ["device", "ping", "-d", "serial"])

assert result.exit_code == 1
assert "Portal is not available" in result.output
assert "mobilerun device setup" in result.output


@pytest.mark.parametrize(
("backend", "message"),
[
("local-android-http", "Could not connect to Android Portal HTTP at URL"),
("local-ios-http", "No iOS portal answered at URL"),
],
)
def test_setup_hint_is_only_for_a_missing_portal_over_adb(
monkeypatch, backend, message
):
def ui():
raise ConnectionError(message)

device = SimpleNamespace(ui=ui, close=Mock())
selection = SimpleNamespace(
device="http://127.0.0.1:8080",
backend=backend,
platform="android",
config=MobileConfig(),
)
_fake_device_commands(monkeypatch, selection, device)
monkeypatch.setattr("mobilerun.cli.device_commands.portal_token", lambda _: "token")

result = CliRunner().invoke(cli, ["device", "ping"])

assert result.exit_code == 1
assert message in result.output
assert "device setup" not in result.output


@pytest.mark.parametrize(
("old", "new"),
[
("GoogleGenAI", "gemini"),
("OpenAIResponses", "openai"),
("openai_oauth", "openai-oauth"),
("anthropic_oauth", "anthropic-oauth"),
("gemini_oauth_code_assist", "gemini-oauth"),
("xai_oauth", "xai-oauth"),
("OpenAILike", "openai-like"),
("openai_like", "openai-like"),
("z.ai", "zai"),
],
)
@pytest.mark.parametrize(
"command", [["run", "task"], ["configure"], ["macro", "replay", "x"]]
)
def test_removed_provider_names_point_at_the_new_one(command, old, new):
result = CliRunner().invoke(cli, [*command, "-p", old, "-m", "model"])

assert result.exit_code == 2
assert f"Removed provider name: {old}. Use {new} instead." in result.output


@pytest.mark.parametrize(
"args",
[
["run", "task", "--no-debug"],
["run", "task", "--no-vision-only"],
["device", "apps", "--no-system"],
["device", "tap", "1", "2", "--tcp"],
["doctor", "--no-debug"],
],
)
def test_removed_flags_that_restated_a_default_say_to_omit_them(args):
result = CliRunner().invoke(cli, args)

assert result.exit_code == 2
assert f"Removed option: {args[-1]}. Omit it." in result.output
assert "Did you mean" not in result.output


def test_keyboard_is_left_alone_when_adb_never_answered(monkeypatch):
from mobilerun.cli import device_commands

Expand Down Expand Up @@ -830,6 +981,7 @@ def test_device_verbs_call_core_directly(
driver.list_apps.return_value = [{"package": "example"}]
driver.screenshot.return_value = "cG5n"
driver.ui_json.return_value = '{"a11y_tree": {"text": "Hello"}}'
driver.ui.return_value = SimpleNamespace(dead_tree=False)
core = Mock()
core.connect.return_value = driver
factory = Mock(return_value=core)
Expand All @@ -839,6 +991,9 @@ def test_device_verbs_call_core_directly(
getattr(driver, verb).assert_called_once_with(*expected_args, **expected_kwargs)
assert core.connect.call_args.args == ("serial",)
assert core.connect.call_args.kwargs["backend"] == "local-android-adb"
assert core.connect.call_args.kwargs["portal_mode"] == (
"required" if args == ["ping"] else "auto"
)
assert factory.call_args.kwargs["base_url"] == "https://api.mobilerun.ai/v1"
driver.close.assert_called_once()
core.close.assert_called_once()
Expand Down
Loading
Loading