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
12 changes: 12 additions & 0 deletions .github/workflows/black.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,15 @@ jobs:
options: "--check --diff --verbose"
src: "."
version: "26.10.1"

syntax:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4

- uses: actions/setup-python@v5
with:
python-version: "3.11"

# The oldest supported interpreter has to be able to parse the package.
- run: python -m compileall -q mobilerun
9 changes: 9 additions & 0 deletions mobilerun/cli/device_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@
verbose_option,
)
from mobilerun.cli.selection import (
adb_unavailable,
core_client,
disable_portal_keyboard,
local_adb_errors,
portal_token,
select_device,
Expand Down Expand Up @@ -65,10 +67,17 @@ def device_driver(params=None, *, selection=None):
url=selection.device if is_portal_http_url(selection.device) else None,
token=token,
)
# Connecting over ADB makes the Portal keyboard the active one.
keyboard_set = selection.backend == "local-android-adb"
try:
yield connected
except Exception as exc:
keyboard_set = keyboard_set and not adb_unavailable(exc)
raise
finally:
connected.close()
if keyboard_set:
asyncio.run(disable_portal_keyboard(selection.device))
finally:
client.close()

Expand Down
2 changes: 1 addition & 1 deletion mobilerun/cli/options.py
Original file line number Diff line number Diff line change
Expand Up @@ -454,7 +454,7 @@ def resolve_command(self, ctx, args):
matches = self.suggest_commands(ctx, args[0])
if matches:
suggestions = ", ".join(
f"'{" ".join(_follow(path, command, args[1:]))}'"
"'" + " ".join(_follow(path, command, args[1:])) + "'"
for path, command in matches
)
exc.message += f" Did you mean {suggestions}?"
Expand Down
12 changes: 6 additions & 6 deletions mobilerun/cli/providers.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ def runtime(self):
"gemini": Provider("gemini", "api_key", "http_options"),
"gemini-oauth": Provider("gemini", "oauth", "code_assist_endpoint"),
"xai": Provider("xai", "api_key", "api_base"),
"xai-oauth": Provider("xai", "oauth", "api_base"),
"ollama": Provider("ollama", "none", "base_url"),
"openai-like": Provider("openai_like", "api_key", "base_url"),
"minimax": Provider("minimax", "api_key", "base_url"),
Expand Down Expand Up @@ -67,14 +68,13 @@ def _provider_option(names, note=""):
def llm_url_kwargs(runtime, url):
if url is None:
return {}
# These loaders prefer api_base, so set both or a saved api_base wins.
if runtime in {"OpenAILike", "DeepSeek", "MiniMax", "ZAI"}:
return {"base_url": url, "api_base": url}
spec = next((spec for spec in PROVIDERS.values() if spec.runtime == runtime), None)
if spec is None:
# Only these loaders normalise the generic base_url keyword.
if runtime in {"OpenAILike", "DeepSeek", "MiniMax", "ZAI"}:
return {"base_url": url}
# Grok credentials only ever go to xAI's own endpoint.
if spec is None or runtime in {"XAI", "xai_oauth"}:
raise click.UsageError(f"-u/--llm-url is not supported for provider {runtime}")
if runtime == "XAI":
raise click.UsageError("-u/--llm-url is not supported for provider XAI")
return {
spec.url_keyword: (
{"base_url": url} if spec.url_keyword == "http_options" else url
Expand Down
81 changes: 51 additions & 30 deletions mobilerun/cli/selection.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,45 @@
from mobilerun.config_manager import MobileConfig


def adb_unavailable(exc):
"""Whether the failure means ADB itself could not be reached."""
from async_adbutils import AdbError, AdbTimeout

message = str(exc).lower()
missing_binary = (
isinstance(exc, FileNotFoundError)
and exc.filename
and (
str(exc.filename).rsplit("/", 1)[-1] in {"adb", "adb.exe"}
or exc.filename == os.environ.get("ADBUTILS_ADB_PATH")
)
)
return bool(
isinstance(exc, (ConnectionRefusedError, asyncio.TimeoutError, AdbTimeout))
or missing_binary
or (
isinstance(exc, ModuleNotFoundError)
and exc.name in {"adbutils", "adbutils.binaries"}
)
or (
isinstance(exc, AdbError)
and any(
text in message
for text in (
"no adb exe",
"cannot connect",
"can't connect",
"connection refused",
)
)
)
)


@contextmanager
def local_adb_errors(enabled=True):
"""Translate local ADB startup failures after the library tries to start it."""
from async_adbutils import AdbError, AdbTimeout
from async_adbutils import AdbError

try:
yield
Expand All @@ -30,35 +65,7 @@ def local_adb_errors(enabled=True):
FileNotFoundError,
ModuleNotFoundError,
) as exc:
message = str(exc).lower()
missing_binary = (
isinstance(exc, FileNotFoundError)
and exc.filename
and (
str(exc.filename).rsplit("/", 1)[-1] in {"adb", "adb.exe"}
or exc.filename == os.environ.get("ADBUTILS_ADB_PATH")
)
)
unavailable = (
isinstance(exc, (ConnectionRefusedError, asyncio.TimeoutError, AdbTimeout))
or missing_binary
or (
isinstance(exc, ModuleNotFoundError)
and exc.name in {"adbutils", "adbutils.binaries"}
)
or (
isinstance(exc, AdbError)
and any(
text in message
for text in (
"no adb exe",
"cannot connect",
"can't connect",
"connection refused",
)
)
)
)
unavailable = adb_unavailable(exc)
if enabled and unavailable:
raise click.ClickException(ADB_HINT) from None
raise
Expand Down Expand Up @@ -238,6 +245,20 @@ async def _native_driver(selection, config, api_url):
return driver


async def disable_portal_keyboard(serial):
"""Hand the phone's keyboard back after controlling it over ADB."""
from async_adbutils import adb
from mobilerun_core_local.driver.android.portal import disable_keyboard

async def disable():
await disable_keyboard(await adb.device(serial=serial))

try:
await asyncio.wait_for(disable(), timeout=10)
except Exception:
pass


async def teardown_native_driver(driver):
"""Disable the framework keyboard after macro replay on local Android."""
from mobilerun_core_local.driver.android import AndroidDriver
Expand Down
12 changes: 11 additions & 1 deletion tests/conftest.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Shared fakes for the secret approval tests."""
"""Shared fixtures, and fakes for the secret approval tests."""

import asyncio

Expand All @@ -22,6 +22,16 @@
CHROME_BAR = "com.android.chrome:id/url_bar"


@pytest.fixture(autouse=True)
def no_keyboard_hand_back(monkeypatch):
"""Device command tests fake the device, so nothing may reach real ADB."""

async def skip(serial):
return None

monkeypatch.setattr("mobilerun.cli.device_commands.disable_portal_keyboard", skip)


@pytest.fixture
def no_settle(monkeypatch):
monkeypatch.setattr(actions, "_SECRET_FOCUS_SETTLE_SECONDS", 0)
Expand Down
1 change: 1 addition & 0 deletions tests/test_agent_model_loading.py
Original file line number Diff line number Diff line change
Expand Up @@ -585,6 +585,7 @@ def test_cli_custom_provider_uses_bounded_retry_defaults(
expected: dict[str, object] = {
"model": "test",
"base_url": "https://example.test",
"api_base": "https://example.test",
"max_retries": 1,
}
if temperature is not None:
Expand Down
123 changes: 123 additions & 0 deletions tests/test_cli_contract.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,13 +357,136 @@ def test_provider_table_matches_wizard_and_loaders():
resolve_provider_variant(provider.family, provider.auth_mode).id
== provider.runtime
)
assert PROVIDERS["xai-oauth"].runtime == "xai_oauth"
assert llm_url_kwargs("Ollama", "http://x") == {"base_url": "http://x"}
assert llm_url_kwargs("OpenAIResponses", "http://x") == {"api_base": "http://x"}
assert llm_url_kwargs("GoogleGenAI", "http://x") == {
"http_options": {"base_url": "http://x"}
}


@pytest.mark.parametrize("provider", ["OpenAILike", "MiniMax", "ZAI", "DeepSeek"])
def test_llm_url_replaces_a_saved_endpoint(provider):
from mobilerun.agent.utils.llm_picker import load_llm
from mobilerun.config_manager.config_manager import LLMProfile

profile = LLMProfile(
provider=provider,
model="model",
base_url="http://saved.test/v1",
api_base="http://saved.test/v1",
kwargs={"api_key": "key"},
)
profile.kwargs.update(llm_url_kwargs(provider, "http://flag.test/v1"))

llm = load_llm(provider, **profile.to_load_llm_kwargs())

assert llm.api_base == "http://flag.test/v1"


@pytest.mark.parametrize("runtime", ["XAI", "xai_oauth"])
def test_llm_url_is_refused_for_grok(runtime):
with pytest.raises(click.UsageError, match="not supported"):
llm_url_kwargs(runtime, "http://x")


def test_run_accepts_the_grok_sign_in(monkeypatch):
callback = AsyncMock(return_value=(True, "done", 1))
monkeypatch.setattr(run_module, "_run_task", callback)

result = CliRunner().invoke(
cli, ["run", "task", "-p", "xai-oauth", "-m", "grok-4.7"]
)

assert result.exit_code == 0, result.output
assert callback.await_args.kwargs["provider"] == "xai_oauth"


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

calls = []
device = SimpleNamespace(
tap=lambda *a, **kw: calls.append("tap"),
close=lambda: calls.append("close"),
)
client = SimpleNamespace(connect=lambda *a, **kw: device, close=Mock())
selection = SimpleNamespace(
device="serial",
backend="local-android-adb",
platform="android",
config=MobileConfig(),
)
monkeypatch.setattr(
device_commands, "select_device", AsyncMock(return_value=selection)
)
monkeypatch.setattr(device_commands, "core_client", lambda *a, **kw: client)

async def disable(serial):
calls.append(f"keyboard:{serial}")

monkeypatch.setattr(device_commands, "disable_portal_keyboard", disable)

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

assert result.exit_code == 0, result.output
assert calls == ["tap", "close", "keyboard:serial"]


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

def tap(*args, **kwargs):
raise ConnectionRefusedError

device = SimpleNamespace(tap=tap, close=Mock())
client = SimpleNamespace(connect=lambda *a, **kw: device, close=Mock())
selection = SimpleNamespace(
device="serial",
backend="local-android-adb",
platform="android",
config=MobileConfig(),
)
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)

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

assert result.exit_code == 1
assert "adb" in result.output.lower()
disable.assert_not_called()


@pytest.mark.parametrize("backend", ["cloud", "local-android-http", "local-ios-http"])
def test_other_backends_leave_the_keyboard_alone(monkeypatch, backend):
from mobilerun.cli import device_commands

device = SimpleNamespace(tap=Mock(), close=Mock())
client = SimpleNamespace(connect=lambda *a, **kw: device, close=Mock())
selection = SimpleNamespace(
device="http://127.0.0.1:8080",
backend=backend,
platform="android",
config=MobileConfig(),
)
monkeypatch.setattr(
device_commands, "select_device", AsyncMock(return_value=selection)
)
monkeypatch.setattr(device_commands, "core_client", lambda *a, **kw: client)
monkeypatch.setattr(device_commands, "portal_token", lambda _: "token")
disable = AsyncMock()
monkeypatch.setattr(device_commands, "disable_portal_keyboard", disable)

result = CliRunner().invoke(cli, ["device", "tap", "10", "20"])

assert result.exit_code == 0, result.output
disable.assert_not_called()


def test_interrupt_exits_130(monkeypatch):
monkeypatch.setattr(
device_lifecycle.adb, "connect", AsyncMock(side_effect=KeyboardInterrupt)
Expand Down
20 changes: 20 additions & 0 deletions tests/test_keyboard_cleanup.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,3 +287,23 @@ def unexpected_driver(*args, **kwargs):

assert agent.android_serial == "emulator-5556"
assert config.device.serial is None


def test_device_command_hand_back_disables_the_portal_keyboard(fake_adb):
from mobilerun.cli.selection import disable_portal_keyboard

asyncio.run(disable_portal_keyboard("emulator-0000"))

assert _serials(fake_adb) == ["emulator-0000"]
assert fake_adb[0].commands == [DISABLE_IME]


def test_device_command_hand_back_ignores_adb_failures(monkeypatch):
from mobilerun.cli.selection import disable_portal_keyboard

async def device(serial=None):
raise ConnectionRefusedError

monkeypatch.setattr(cli_main.adb, "device", device)

asyncio.run(disable_portal_keyboard("emulator-0000"))
Loading