Skip to content

refactor: mobilerun base rework - #553

Draft
Cyro292 wants to merge 34 commits into
droidrun:developfrom
Cyro292:feat/mobilerun-base-rework
Draft

Cyro292 wants to merge 34 commits into
droidrun:developfrom
Cyro292:feat/mobilerun-base-rework

Conversation

@Cyro292

@Cyro292 Cyro292 commented Nov 22, 2026 •

Copy link
Copy Markdown
Collaborator

Lean core with an optional mobilerun-agents add-on, feature packages that mirror the top-level layout, standalone utils, grouped errors, JSONC-safe MCP install with sign-in reminders, sub-skill install (Everything / Bundle / Single) and InquirerPy Yes/No confirmations, including the proxy bind replace prompt.

New: webhooks

Register an endpoint once, then send each sandbox function's result to it.

mobilerun webhook register https://your.server/hook   # prints the endpoint ID + signing secret (shown once)
mobilerun webhook ping                                # signed test delivery, e.g. "Delivered: HTTP 200 OK"
mobilerun webhook list | get | delete
@cloud("daily-report", webhook="<endpoint-id>")
def report(...): ...
# every run POSTs {"type": "workflow.step.emit", "data": {"result": ...}} to the endpoint
  • @cloud(webhook=) takes an endpoint ID only; a URL or unknown ID fails before anything is deployed, with a mobilerun webhook register <url> hint.
  • Core API: mobilerun.core.webhooks.CloudWebhooks (register, list, get, delete, find_by_url, ping).
  • Receivers verify the HMAC signature with the signing secret; per-endpoint bearer tokens need backend support.
  • Commits: b6750da, 53583a1.

Known compatibility breaks (accepted for this release):

  • mobilerun.macro.state and mobilerun.macro.matcher removed (now macro.models / macro.utils), no legacy alias.
  • mobilerun.mcp no longer exports the 0.7.4 MCP client API (MCPConfig, MCPClientManager, mcp.config/client/adapter).
  • Legacy tools.helpers.images resize helpers now require max_side.
  • The droidrun compatibility shim is removed; import mobilerun instead.
  • mobilerun-agents is a separate add-on and is not yet publicly published; agent commands report it as not installed.
  • Root CLI commands moved, with no aliases:
Old New
mobilerun run mobilerun agent run (add-on)
mobilerun configure, provider OAuth subcommands mobilerun agent llm configure, mobilerun agent llm login PROVIDER (add-on)
mobilerun login / logout / whoami mobilerun account login / logout / status
mobilerun devices mobilerun device list
mobilerun connect / disconnect mobilerun device connect / disconnect
mobilerun ping / setup mobilerun device ping / setup
mobilerun device tap, swipe, type, … (0.7 flat commands) grouped: device input …, device screen …, device app …

Devices come from mobilerun-core

Merged in from #558: the framework drops its own device stack and uses AsyncDevice from mobilerun-core 2.0.0 (droidrun/mobilerun-core#83). Commands receive a connected core device; recording runs on core action hooks; macro rows keep each action's started_at.

Why CI (including lint) fails here

CI can't install the project yet, so every job that installs it fails before any check runs:

Because there is no version of mobilerun-core[local]==2.0.0 and your project depends on
mobilerun-core[local]==2.0.0, we can conclude that your project's requirements are unsatisfiable.
  • mobilerun-core 2.0.0 isn't on PyPI yet. It's droidrun/mobilerun-core#83, still in review.
  • mobilerun-functions (sandbox extra) still pins mobilerun-core<2. Its code already works with core 2; only the pin needs a release.
  • lint: the black step passes. The Type check step runs uv run --locked … mypy, which has to install the project first, so it fails on the same error. pytest and check-image fail the same way.

Verified locally with a clean install from the CI commands, using a locally built core 2.0.0 wheel: uv lock and uv sync --locked resolve, black, ruff and mypy mobilerun are clean, and pytest tests/unit gives 3,117 passed, 75 skipped.

To get CI green: release core 2.0.0 (#83), release mobilerun-functions with the core 2 pin, then regenerate uv.lock here.

lutz-grex and others added 4 commits November 4, 2026 22:05
* fix(inference): expose empty response metadata

* fix(inference): classify empty responses

Add a machine-readable category (provider_blocked, truncated,
tool_calls_only, thinking_only, blocks_without_text, empty_stream,
empty_content, no_response, no_message), read finish_reason from
LiteLLM choices[0] / Gemini candidates[0] and pydantic raw payloads,
and cover the handout's test cases (empty, safety, thinking-only,
tool-only, empty stream, redaction, completion, structured).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* refactor(inference): trim diagnostics

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* fix(inference): classify adapter empties

* fix(inference): classify responses truncation

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* refactor(inference): trim diagnostics and tests

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* fix(inference): keep str enum reasons

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Lean core with an optional mobilerun-agents add-on, feature packages that
mirror the top-level layout, standalone utils, grouped errors, JSONC-safe
MCP install with sign-in reminders, sub-skill install (Everything / Bundle /
Single) and InquirerPy Yes/No confirmations, including the proxy bind
replace prompt.

Linear: DRO-3970, DRO-3975

Known compatibility breaks (accepted for this release):
- mobilerun.macro.state and mobilerun.macro.matcher removed (now
  macro.models / macro.utils), no legacy alias.
- mobilerun.mcp no longer exports the 0.7.4 MCP client API
  (MCPConfig, MCPClientManager, mcp.config/client/adapter).
- Legacy tools.helpers.images resize helpers now require max_side.

Known failing unit tests (pre-existing, 10): cloud list errors, secrets
billing contract/boundary, clients-import-core boundary, local client
layout, number country checkout, initializer exports, removed module paths
(agent, config_manager, tools).
…exports

- Features (macro, mcp, skills) register CLI via mobilerun.cli entry points;
  root CLI keeps core commands + discovery; `mobilerun plugins list`.
- Agent add-on discovered via entry points; no hardcoded mobilerun.agents in base.
- Remove all legacy compatibility: droidrun shim (compat/), mobilerun/_legacy,
  deprecated CLI aliases; publish workflow builds mobilerun only.
- Placement rule: shared errors/models/utils/cli/config serve core+clients;
  features own their settings/errors (MacroError, SandboxError, MCP settings).
- Clients never import core or the root package; codes, prompts, paths moved
  to utils/; value types (Location, ProxyStatus, RecordedAction,
  CredentialMetadata, UIElement, PaymentSnapshot) moved to models/.
- Lazy public exports: import mobilerun loads 329 modules (was 1,307).
- mobilerun-routines moved to the `sandbox` extra; sandbox stays a placeholder.
- Architecture tests: removability, placement, import boundaries.
- Remove glama.json; ignore docs/superpowers/.

Refs: DRO-3975, DRO-3973
- number create: picker shows included quota per in-stock country
  (fail-soft, bounded concurrency); number included lists all countries
- mailbox messages: list past emails
- number release: clear not_cancellable 409 message
- macro path + credentials path --json via shared local_store_path;
  macros default to <config dir>/macros (BREAKING: ./trajectories)
- multiselect for release/unbind/rm commands; one confirm, per-ID
  results, --json always an array (BREAKING)
mobilerun device cloud rename [DEVICE] [NAME]: picker, name prompt, --json; free (no_commerce).
- @cloud("name") deploys an endpoint by default; schedule= for UTC cron;
  endpoint=False for function only; trigger="manual" removed
- mobilerun sandbox deploy/list/fire/runs/enable/disable/path CLI plugin
- explicit consent, no deploy on import; receipt-verified ownership,
  disabled staging, safe redeploy cutover, lost-response recovery
- local store under MOBILERUN_SANDBOX_DIRECTORY (default <config>/sandbox)
- runtime mobilerun-functions[device]==0.1.0, mobilerun-sdk>=6.3.1, jsonschema
- SDK adapter in mobilerun/sandbox/clients.py (narrow boundary exception)
- playground port, generic examples, opt-in paid smoke with cleanup
…edaction, recovery, CLI)

- Billing and ownership: closing a device keeps an existing number
  binding; failed checkout never deletes caller-supplied numbers or
  mailboxes; pending-purchase recovery only when paid and the request
  matches; SMS send needs paid billing and CLI confirmation; resume
  refuses minute phones in restricted billing modes; checkouts that
  activate or provision without a URL succeed.
- Secrets: signed URLs (incl. redirects) kept out of httpx logs and
  tracebacks; vault errors drop unsafe causes but keep typed metadata;
  status JSON allowlist; nested action recording no longer leaks
  sensitive text; type_secret requires a selector; dry-run and sandbox
  validation errors carry no payload values.
- Sandbox deploy recovery: full-intent compare (type-aware), legacy
  receipts, persisted disable, verified activation, stale cutover
  cleanup, rejected versions replaceable.
- Files: atomic config migration (symlink-safe, retryable), legacy
  prompt fallback at read time; MCP JSONC edits keep concurrent saves
  and comments; skills keep user files unless --discard-changes; wheel
  ships tracked skill files only.
- CLI: plugin discovery isolated per distribution; completion without
  loading plugins; lazy InquirerPy; proxy replace defaults to No;
  read-only doctor TCP checks; device kind filtering, rename -d,
  --config save target; Portal HTTP client closed.
- Tests: stale and leaky smoke tests fixed (minute plan, unique-name
  cleanup); smoke APK default moved out of /tmp; ruff clean.
- uv.lock relocked (mobilerun-sdk 6.3.2, mobilerun-functions,
  jsonschema).

Refs DRO-3975
@RasulOs

RasulOs commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator

develop branch pls

@RasulOs RasulOs left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex: Review of 9f0c5c3

I recommend changes before merging. The PR targets main. Retarget it to develop and resolve the integration conflicts. A trial merge against develop at e5b48a8 found 80 conflicted paths. This review treats the architecture change and intentional compatibility breaks as accepted.

The main blockers are unintended device mutations during read and close paths, destructive operations selecting a different device, fail-open credential replay and sensitive recording, billing restrictions bypassed through shared cloud actions, and a stale lockfile that fails both Docker builds. The inline comments also cover sandbox deployment recovery, CLI regressions, and SDK behavior.

Python 3.12 and 3.13 each returned 3,016 passed, 76 skipped, and 3 failures with SDK 6.3.1 and core-local 0.6.3. Two failures are already listed in the PR. The emulator test hit the local environment's loopback bind restriction. The wheel and source archive built, including a wheel rebuilt from the archive. Cloud and device reproductions used mocks or the local Functions worker. Live smoke tests and the separate agents add-on remain unverified.

Before merging, rerun locked builds and unit tests on the resolved develop candidate and add regression coverage for the ownership, target selection, credential, and recovery cases.

async with self._extension_state.lock:
number._check_name(self)
number._action_entries()
adopted = Binding(number, self, False)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex: [P1] Preserve an existing SMS binding when the device closes

Using the real screenshot command with mocked HTTP, I saw a successful screenshot followed by DELETE /devices/<id>/number. This records the observed server binding as a borrowed extension, and generic close calls unbind() on it. The backend then stops routing messages from that number to the device. Track adopted server bindings separately and discard the local reference on close.

Comment thread mobilerun/cli/devices/base/options.py Outdated
from mobilerun_core_local.driver.ios import discover_ios_device

return asyncio.run(discover_ios_device())
devices = asyncio.run(discover_devices(base_url=kwargs.get(base_url_name)))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex: [P1] Honor an explicit Android serial before discovery

With ANDROID_SERIAL set to one serial and a different ADB device as the only discovery result, device file rm --yes returned success after calling the fake connection for the other device. Resolve the explicit Android serial first and fail if it cannot be used.

Comment thread mobilerun/core/devices/android.py Outdated
await device.shell("settings put secure accessibility_enabled 0")
await asyncio.sleep(0.5)
await device.shell(
f"settings put secure enabled_accessibility_services {shlex.quote(a11y)}"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex: [P1] Preserve other Android accessibility services during recovery

A failed device screen ui read reached this recovery hook even with portal_mode: disabled. The resulting ADB writes replaced the existing accessibility-service list with Portal. Gate recovery on Portal actually being in use and preserve the other enabled services during recovery.

Comment thread mobilerun/macro/player.py Outdated
if len(candidates) != 1:
raise MacroError("Bind one vault to replay a secret action")
vault = candidates[0]
await vault.type_field(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex: [P1] Reject protected or unreferenced credential actions before replay

develop preflights approval-gated actions. The v2 player here accepts type_secret with protected: true and sends the credential to the device. A separate fake-device test with no credential reference typed the first matching vault entry. Restore a fail-closed preflight over the replayed steps so these cases cannot perform device actions.

Comment thread mobilerun/core/extensions/base.py Outdated
if device is None
else tuple(device._extension_state.observers)
):
observe(entry.name, safe)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex: [P1] Keep nested device effects out of extension recordings

One extension tap produced both a tap and an extension_call, and replay tapped twice. A private extension with a sensitive argument also put the original text into a nested input_text record even though the outer event was redacted. Record one logical operation and apply the sensitivity context to any nested recording.

Comment thread mobilerun/core/devices/pool.py Outdated
for device in devices:
operator = device._operator
if operator is not None:
operator.check(_unwrap_device(device))

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex: [P2] Validate an operator against the facade it will receive

A custom operator that accepts RecordingDevice paired and ran successfully on the wrapper but failed during pool construction because this check received the unwrapped device. Validate the same object that execution passes to the operator.

Comment thread mobilerun/cli/workspace/group.py Outdated
entries = []
for path in paths:
click.echo(f"Uploading {path}…", err=True)
item = await Workspace.upload_file(path)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex: [P2] Keep successful file IDs when a JSON batch partially fails

In a two-file upload, the first file was created and the second request failed. The command exited with empty stdout, so an automation caller could not recover the ID of the successful upload. Return per-file outcomes and retain a failing exit status for partial errors.

Comment thread mobilerun/mcp/installer.py Outdated
and any(field in value for field in ("type", "url", "command"))
for value in servers.values()
)
if fmt.nested_servers and ("servers" in servers or not legacy):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex: [P2] Find the Mobilerun entry in mixed OpenCode configurations

OpenCode supports legacy entries alongside mcp.servers. With a legacy Mobilerun entry and another server nested under servers, both status and uninstall reported not installed while the original server remained active. Check both supported locations before installing or removing an entry. OpenCode migration guide

relative = paths.mcp[scope == "project"]
if relative is None:
raise ValueError(f"{agent} does not support {scope} scope")
path = (Path.home() if scope == "user" else Path.cwd()) / relative

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex: [P3] Use the active Codex home for user-scope MCP installation

With CODEX_HOME set to an existing alternate directory, the command reported success but updated only ~/.codex/config.toml. Resolve the default Codex user path from the active Codex home while preserving explicit registry overrides. Codex config loader

Comment thread mobilerun/skills/bundle.py Outdated
elif not _managed(dest, managed_sources):
results.append(InstallResult(name, "not managed", dest))
else:
shutil.rmtree(dest)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Codex: [P3] Handle dependent subskills before removing their parent

Single-install creates a subskill whose references point into the installed parent directory. Uninstalling the parent succeeded and left that subskill installed with broken links. Refuse the removal while managed dependents exist or remove them together with explicit feedback.

@Cyro292
Cyro292 changed the base branch from main to develop November 25, 2026 11:24
@Cyro292

Cyro292 commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator Author

@RasulOs retargeted to develop. Heads-up: the branch was cut from main, so it currently conflicts with develop (~80 files, mostly old agent/config_manager/cli modules this rework moves or removes). I'll merge develop in next.

@RasulOs

RasulOs commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator

@RasulOs retargeted to develop. Heads-up: the branch was cut from main, so it currently conflicts with develop (~80 files, mostly old agent/config_manager/cli modules this rework moves or removes). I'll merge develop in next.

In next? Why?

Also pls, reduce number of test files pls, didn't we discuss it?

The add-on moved from the mobilerun.agents namespace package to the
top-level mobilerun_agents package. Base follows without importing it:

- PathResolver.bundled_asset finds legacy prompt/app-card paths under
  mobilerun_agents/assets via find_spec; v008 reuses it.
- Drop the pkgutil extend_path namespace hook from mobilerun/__init__.
- Operator hint shows 'from mobilerun_agents import AgentOperator'.
- Docs, demo and boundary tests use the new name; tests of add-on
  internals move to the add-on repo.

Refs DRO-3975
Keep the base-rework tree for every conflict and drop develop's
additions that only fit the old layout:
- droidrun#548 CLI devx/QR/polish modules (flat cli/*.py) are superseded by
  the grouped CLI.
- droidrun#528 action selectors and decision models belong to the
  mobilerun-agents add-on.
- droidrun#534 secret approval gate and droidrun#539 secret masking live in removed
  packages; they are ported in a follow-up commit.

Refs DRO-3975
P1:
- Device selection honors ANDROID_SERIAL and never substitutes another
  device; only ADB state "device" is auto-selected.
- Macro replay preflights every step before any device action:
  protected, selectorless and unbound credential steps are refused
  (also for direct replay_action). Ports the replay guard from
  develop's secret approval gate (droidrun#534) and snapshot masking (droidrun#539);
  log redaction stays with mobilerun.utils.redaction.
- Android accessibility recovery keeps other services, and runs only
  when Portal is in use.
- Cloud proxy adoption follows the device's proxy capability; an
  unsupported tool no longer aborts connect.

P2/P3:
- Sandbox: pause without a document read, canonical receipt scope,
  rollback no-op, scheduled {} validated against the real model,
  JSON-mode typed results.
- Cloud: background app installs, progress failure falls back to
  status polling.
- Core: extension args snapshotted before execution, emulator
  close/start race, pool checks the facade operator.
- CLI/config: per-platform Portal tokens, cloud credential errors keep
  local devices, missing MOBILERUN_CONFIG fails, workspace app flags,
  strict iOS UI read, auth status env key first, partial upload IDs,
  clipboard scoped to cloud.
- Windows owner-only credential files, OpenCode mixed configs,
  CODEX_HOME, dependent subskill removal.

Refs DRO-3975
secret_scope now also masks registered digit secrets written with
spaces, dashes, dots or slashes (cards, PINs, expiry), using one fixed
candidate pattern and plain substring search for literal variants, so
no secret enters the regex cache. Matches merge against the original
message; longer dates and IDs stay intact; alphanumeric secrets stay
literal-only; values that cannot be URL-encoded no longer raise.

Refs DRO-3975
- core/webhooks: register, list, get, delete, find_by_url, ping and
  URL validation over the webhooks API; tunables in config/settings.py,
  mask_url in utils/redaction.py
- `mobilerun webhook` CLI: register (URL only, reuses existing),
  list/get with masked query values, delete, ping with HTTP status,
  interactive ID picker
- sandbox: @cloud(name, webhook=<endpoint id>) appends a webhooks.send
  step that posts the function result; IDs only, sandbox never owns
  endpoints; safer cutover/cleanup recovery and webhookStatus in runs
- tests: unit suite reorganized into package folders; webhook unit and
  paid smoke tests
- AGENTS.md: core subpackages have no own settings/utils/errors/models

Linear: DRO-3975
- sandbox: @cloud(files=, files_folder=) uploads result images before
  the webhook step; webhook payload replaces them with path + fileId
- billing: ask once and retry with the needed mode; SMS billing retry
  via @action(billing_retry=...) without CLI type checks
- proxy: `mobilerun proxy included` and `proxy list --included`
- webhooks (review of b6750da): redeploy rechecks the endpoint before
  replacing bindings and keeps old actions until activation; register
  reuses an endpoint only if it covers the requested events; sandbox
  smoke asserts the exact payload; mask_url documents why paths show

Linear: DRO-3975
- README.md, mobilerun/README.md, package READMEs: webhooks in feature,
  CLI and package lists; register/ping and @cloud(webhook=<id>) examples
- AGENTS.md: core/webhooks + cli/webhook in the repo map; webhook smoke
  tests use webhook.site and clean up their endpoints
- skills: bump to f0056fe (webhooks reference, schedule input contract)

Linear: DRO-3975
- AGENTS.md, READMEs: structure rule "Could someone delete this folder
  and still use the rest of Mobilerun?"; topic map in core/README.md;
  dependency diagram with all four features
- cli: skip first-party feature entry points whose package is missing;
  third-party plugins and real import errors behave as before; root
  help falls back when skills is absent
- config: v008 and PathResolver handle prompts only (app cards live in
  the agents add-on and skills); add-on-only prompt paths stay resolvable
- core/workspace.py: direct deferred cloud imports instead of the
  module __getattr__ self-import

Linear: DRO-3975
- android state: confirm the focused editable field from the raw tree
  when the summary is empty; refuse stale cached states, focused
  buttons and fields in another window of the same app
- devices: _input_secret uses the stricter focus check before typing
- tests: fallback accept/reject cases, including Chrome's address bar
- credentials README: document the fallback

Linear: DRO-3975
@Cyro292

Cyro292 commented Nov 26, 2026

Copy link
Copy Markdown
Collaborator Author

Credential input on cloud phones: _input_secret focus fallback (uncommitted, local)

Why: credential typing worked before the rework and stopped working on cloud phones.

  • Before: main (e340042) typed secrets via type_secret(secret_id, index): tap the element, then plain input_text(value). There was no focus check, so it worked on cloud phones.
  • Now: vault.type_field → Device._input_secret (added in 2729360) requires phone_state.focusedElement + isEditable is True.
  • What the cloud reports: on cloud phones the ui-state summary names the keyboard (IME FrameLayout) as focusedElement with isEditable=false. Meanwhile a11y_tree in the same response marks the app's EditText as isFocused=true. Base passes that summary through unchanged.
  • The result: every vault.type_field raises NoFocusedInput. Reproduced live on a cloud phone in the Chrome omnibox and in Settings search; plain input_text works on the same fields.

Change (keeps the strict path; adds a narrow fallback):

  • The strict check is unchanged: focusedElement dict + isEditable is True passes, as before.
  • The fallback applies only when the strict check fails. It passes only if all of these hold:
    • keyboardVisible is True;
    • the snapshot is not degraded;
    • the raw app tree (the IME tree is ignored) has exactly one enabled, focused node from the foreground package, in an unambiguous foreground window;
    • that node is editable: isEditable is True when present, otherwise an EditText-type class.
  • Everything else still raises NoFocusedInput. Unsupported state still raises DeviceOperationNotSupported.
  • Files: core/devices/base.py, core/state/android.py, core/state/ui_state.py, core/credentials/README.md, tests/unit/core/credentials/test_secret_handling.py.

Tests:

  • New cases:
    • IME-focused summary + one focused app EditText → types;
    • no focused app node → refuses;
    • two focused nodes → refuses;
    • other package → refuses;
    • focused button → refuses;
    • degraded snapshot → refuses;
    • ambiguous window → refuses.
  • The full unit suite shows the same 6 pre-existing failures as clean HEAD (SDK humanize/stealth, two duplicate-log asserts).
  • Live: vault.type_field in the Chrome omnibox succeeded. Note that on that run it went through the strict path, so the fallback itself hasn't been exercised live yet.

Root cause is upstream: devices-api derives phone_state focus from the full multi-window tree (humantouch uitree.DerivePhoneState), so the IME wins. This fallback restores the previous behavior until that is fixed; the guard can then go back to strict-only.

Status: these changes are still uncommitted in my local checkout; not pushed to this PR yet.

@lutz-grex lutz-grex left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I reviewed this together with mobile-jev#12, with a focus on the contract between the base and the add-on and on what can be swapped. Some of it is already right: CLI plugins load lazily (--help reads only metadata), Device.do(operator=...) accepts any Operator, and clients/cloud uses the generated SDK. What is missing is a contract the add-on can use without base internals, and an upgrade path for existing users.

  1. The version goes backwards. version = "0.7.4", but develop is at 0.8.0 and 0.7.4 is already on PyPI. The mobilerun-core-local floor also drops from 0.7.2 to 0.6.3. Please use a new breaking version (for example 0.9.0), restore the floors and export a PLUGIN_API_VERSION.

  2. The paid SMS confirmation only sits in the CLI wrapper. run_replay has no check, so mobilerun macro-agent replay sends paid SMS without a prompt. Please move count-and-confirm into run_replay and add yes to ReplayOptions.

  3. One folder for the contracts with other repos. Mailbox, PhoneNumber, Credentials, Proxy, Webhooks, AI and Tasks are implemented in mobilerun-functions, so they need one shared contract.

    • Please put these Protocols into one folder, for example mobilerun/interfaces/.
    • Only Protocols and data models go there. No I/O, no SDK, no CLI and no imports from the rest of mobilerun, enforced by a layer test.
    • Today both repos define their own versions, and they differ: credentials type_field/list, proxy status, and Mailbox is defined twice. Please align them with mobilerun-functions and add a conformance test.
    • Please keep mobilerun-functions free of runtime imports from mobilerun, so that the CLI extra does not create a cycle.

    Internal types (Device, Operator, UIState, actions) stay where they are.

  4. Code outside this repo must be able to implement the interfaces.

    • Device: a custom device has to override private methods (_ensure_connected, _input_text_raw, _create_state_provider, _get_ui_tree). Please make that surface public and abstract.
    • Services: they inherit Extension and need private overrides (CredentialProvider._find), and Proxy reaches into device._proxy_target. Please keep the binding lifecycle separate from the Protocol.
    • Secrets: please expose a public redact(text) and an observation hook, so that consumers can mask what they persist (run data, checkpoints, macros) with the base's masking.
  5. The add-on uses private base members. These are Device._unwrap, _is_cloud, UIStateView._resolved_provider and _current, Action._arguments, MacroOperator._execute_macro, plus the CLI helpers in cli.base and macro.cli.replay. Please make what the add-on needs public, in the place where it lives now.

  6. Cloud services and the sandbox belong in mobilerun-functions.

    • The split: this repo keeps the interfaces, the local implementations and the CLI. mobilerun-functions implements the cloud services over the SDK and the sandbox runtime.
    • Please remove the sandbox re-export, deploy, packaging and billing code. Thin mobilerun sandbox commands can stay.
    • Moving the Cloud* service classes can be a follow-up, but please do not grow them in this PR.
  7. Operator plugins. mobilerun.operators holds a macro-handoff callable, and real operators use the add-on's own mobilerun.agents group. Please let the base load Operator plugins, and give the handoff its own slot.

  8. The base knows the add-on.

    • Agent config is parsed here: agent, llm_profiles, tools, external_agents, telemetry and tracing.
    • utils/paths.py probes for mobilerun_agents.
    • cli/base/errors.py suggests mobilerun-agents[anthropic], an extra that does not exist.

    Please move these to the add-on, with a one-time config migration there.

  9. Upgrade path. This release removes mobilerun run while the add-on is not published yet. Please release both together, and keep a hidden run stub that prints the migration hint.

  10. Owner facts. Please return a typed element model and the geometry from UIState, expose a macro action encoder, and normalise swipe.duration_ms for cloud devices. Then the add-on no longer has to compute these itself.

  11. CI. This repo has no pytest workflow. Please add one, with a fake-add-on test that covers an operator plugin and an agent_macro replay.

Optional:

  • task status/stop belongs in the base CLI.
  • Macro snapshots read package, but the state sends packageName. This bug comes from develop.
  • Webhooks would be easier to review as their own PR.

…ingDevice (DRO-4031)

- RecordingDevice(capture=full|actions) writes runs/<id>/run.json + steps.jsonl
  (timing, ok/error, before/after fingerprints, redacted UI tree + screenshots in full mode)
- core/runs: RunWriter, RecordingSession, capture; core/state/snapshot DeviceSnapshot
- macros as macros/<name>/vN.jsonl built from successful steps; player before/after checks
- dispatch_guard, collect_steps, register_sensitive_values, known_codes_redactor
- stealth veto across extension access; secret/OTP masking in recorded args and logs
- remove MacroRecorder, RecordedAction and v2 macro format
refactor!: commands use core devices directly; actions carry timestamps (DRO-4147)
Take droidrun#556 (stealth -> humanize): its old agent, tools and config modules
are removed by the rework, so keep those deletions and drop the test for
the removed config manager. Keep the example config rename.
Exact versions live in uv.lock and CI.
@Cyro292
Cyro292 requested a review from lutz-grex December 1, 2026 17:46

@lutz-grex lutz-grex left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Big step forward. The framework now uses core's AsyncDevice everywhere and has no device stack of its own. Version 0.9.0 with PLUGIN_API_VERSION, the SMS check inside run_replay, operator plugins with their own mobilerun.macro_handoff slot, agent config out of the base, the hidden run stub, typed screen models and a pytest workflow with a fake add-on test all landed.

Still open from the last round, and new:

  1. The sandbox is still in the framework, and it grew. mobilerun/sandbox went from about 5,800 to 6,450 lines, with new deployments/*, sandbox/cli/* and sandbox/clients/*. It belongs in mobilerun-functions; thin mobilerun sandbox commands can stay. It also blocks CI: the sandbox extra pins mobilerun-functions[device]>=0.1.0,<0.2, functions 0.1.0 requires mobilerun-core<2, and pytest.yml/black.yml install --extra sandbox. So CI stays red even after core 2.0 is out. Please remove the sandbox code and the extra.

  2. Extensions should declare what they need from the device. Today each place checks on its own: backend != "cloud" in CloudTaskOperator and CloudPhoneNumber.attach, per-backend gates in the CLI (clipboard/get.py:11, set.py:15, long_press.py:16, file/push.py:46), and none at all for proxies. Please add requires = {"set_proxy", …} on Extension and one check_bind(device) in the base that runs in Operator.do and checks requires against device.supports(). Two bugs go away with it:

    • The clipboard commands reject local Android, although core supports the clipboard through Portal.
    • A credential provider always types into the device it was built with (credentials/base.py:174, 211). Operator.do(phone_b) with FileCredentials(..., device=phone_a) types the password into whatever field is focused on phone A. check_bind should reject an extension bound to another device.
  3. Billing modes don't belong in the framework. MOBILERUN_BILLING (no_commerce / included / paid), BillingPolicy and with_billing_retry decide locally, from a fixed table, which call may cost money. About 120 call sites in clients/cloud, core and sandbox check it before every SDK request. The backend already owns this: devices take billing=minute|subscription, numbers and mailboxes take billingPreference, and the API answers with awaiting_payment plus a checkout URL or a 402. The local copy drifts and already has a bug: with MOBILERUN_BILLING=no_commerce, mobilerun proxy buy --country us --yes hits BillingRequired, retries at paid without asking (utils/billing/retry.py:45-54) and buys the proxy, and test_billing_retry.py:134 asserts that. Please replace it with:

    • Library: no billing modes. buy(), create() and rent() send the billing choice to the API as it is and return the checkout URL as a normal result (or a typed error that carries it). No prompts and no retry in library code.
    • CLI: one list of the commands that cost money (proxy buy, phone-number create, mailbox create, device create, sms send, device resume, sandbox deploy, …), each with a one-line cost note. They ask once; without a terminal they need --yes and abort otherwise. No other command asks.
    • Checkout: if the API returns a checkout URL, the CLI shows it and waits for activation. That's the thin part of PaymentFlow that stays.

    MOBILERUN_BILLING, BillingPolicy, with_billing_retry, the @BillingPolicy.guard decorators and the escalation all go.

  4. Run recordings keep secrets in screenshots. core/runs/evidence.py:106-108 always writes the PNG, while the JSON next to it is masked when sensitive_ui is set. A card number typed with type_secret into a normal field ends up in clear text in screens/N.after.png. Please skip or blank the screenshot under the same rule ScreenProvider already uses (core/screen/provider.py:154).

  5. Proxy checkout recovery loses the extension. When CloudFixedProxy.purchase() needs checkout, the PaymentRequired from purchase_connect_proxy escapes and its resume returns a ProxyProduct, not the proxy extension. After paying, the caller has no apply()/close(), and _owned is never set, so close doesn't release the proxy. Please wrap the resume so it returns the constructed extension with ownership.

  6. One folder for the cross-repo contracts. There is still no mobilerun/interfaces/. Mailbox and PhoneNumber inherit Extension, CredentialProvider needs private abstract methods (_known_entries, _list_credentials), Proxy, Webhooks and AI have no contract, and the drift test lists every service as an accepted gap. Please add the Protocols for Mailbox, PhoneNumber, Credentials, Proxy, Webhooks, AI and Tasks there, keep the binding lifecycle out of them, and make the conformance test fail on drift.

  7. Read error codes, not messages. The webhooks client matches service message text (core/webhooks/helpers/requests.py:20, :53), and clients/cloud/tasks.py:78 searches the detail for "device" and "not found". Please branch on the code field the services return.

  8. Facts core should own. The framework re-detects the iOS home screen from the raw tree (core/screen/provider.py:26-27, 119-126) and secure input from raw_state (utils/redaction.py:250-274). _OPAQUE_ARGS (core/runs/recording.py:42-51) repeats masking that core's action hooks already do for type_secret, set_clipboard and set_proxy. Please drop the duplicate _OPAQUE_ARGS entries here. The secure-input flag and home-screen state should come from core as fields; that can be a core follow-up.

  9. Release order. Merge #559, then release core 2.0.0, regenerate uv.lock here (it still pins core 1.12.1 and SDK 6.3.2) and get CI green. Release this together with mobilerun-agents, since run goes away. MacroOperator._execute_macro is still private; please make what the add-on uses public. PLUGIN_API_VERSION is only checked if each add-on asserts it itself (addons/README.md); the loader (addons/plugins.py:74-94) loads any add-on. Please let add-ons declare the version they target and have the loader check it once, so an add-on that forgets the assert fails at load and not later. macro.json recordings from 0.8.0 are rejected with "please re-record" (macro/builder.py:86-103); please migrate them on load, or call it out as a breaking change in the upgrade notes.

Smaller:

  • .DS_Store is committed.
  • cli/base/errors.py:62-66 still names the add-on's dependencies (anthropic, langfuse, openinference).
  • Code with no caller in this repo outside tests (drop it unless the add-on uses it): BillingPolicy.cloud_phone_plan, the RunWriter(record, …) overload, started_dir, Redactor.remember_codes, and collect_steps/start_run/checkpoint in core/runs/recording.py. utils/network/quiet.py copies core's quiet_logs. utils/screen/fingerprint.py accepts five key aliases and walks raw trees, although its only caller passes one fixed shape. The split left 11 folders with a single file each.
  • CHANGELOG.md says core ==2.0.0 and mentions a mobilerun.interfaces that never shipped.
  • The hint in addons/plugins.py:79-80 still points at mobilerun.operators for the handoff.
  • clients/local/apk.py duplicates core's inspect_apk and has no caller.
  • clients/cloud/numbers.py and tasks.py import the SDK's private _types.
  • The "awaiting payment" status set is written in five places (payments.py, mailboxes.py:62, core/mailbox/cloud.py, core/phone_number/cloud.py, numbers.py); with the thin checkout step it belongs in one place.
  • Webhooks and run recording would still be easier to review as their own PRs.

- Extensions declare required device actions (`requires`) and validate
  pairing in `check_bind`; `Operator.preflight` runs it before execution,
  so an extension bound to another device is rejected.
- Clipboard CLI works on any device that supports the clipboard action.
- Proxy checkout resume returns the owned `CloudFixedProxy`, within the
  caller's deadline, without a second purchase.
- Add `mobilerun.interfaces` service Protocols with a strict conformance
  test.
- Webhook registration branches on structured error codes; task 404s no
  longer guess from message text.
- Drop recording masks core already applies and unused run helpers;
  simplify screen fingerprints.
- One awaiting-payment status set; public SDK types only.
- Cleanup: remove .DS_Store, stale add-on hints, apk.py from runtime,
  BillingPolicy.cloud_phone_plan; flatten single-module CLI groups.
@Cyro292

Cyro292 commented Dec 4, 2026

Copy link
Copy Markdown
Collaborator Author

I agree the API should own pricing, quota, and checkout. Roughly 120 local checks are too many, and the repeated payment statuses show how easily they drift.

I'd still keep one framework-side spend gate, MOBILERUN_BILLING. Python callers and unattended replay reach billable operations without going through the CLI; replay can send paid SMS. A checkout URL is not a consent boundary either: a proxy purchase can already be active when the API responds. So callers that must never spend (unattended runs, offline tests) need a way to block paid calls before the request is sent. The default stays paid, so existing scripts keep working; no_commerce blocks billable calls locally.

You're right about proxy buy --yes: it still upgrades no_commerce to paid without prompting. I'll remove that retry. --yes can answer a CLI prompt; it can't override the spend setting. Beyond the gate, the API decides what a request costs and whether checkout is needed. The CLI shows the URL and waits. No local pricing table.

Keep the agent removal: structured_output_agent.py and its test move to
the mobilerun-agents add-on. Keep mobilerun-core >=2.0.0,<3; drop the
develop-only OpenTelemetry/pyasn1 requirements the base package no
longer uses.
@Cyro292
Cyro292 requested a review from lutz-grex December 4, 2026 09:11
- Merge origin/develop. Port URL precedence and CLI error diagnostics
  into the reworked modules; keep retired CLI modules deleted.
- Remove mobilerun/sandbox, the sandbox and functions extras, and the
  function/routine/sandbox commands. They move to mobilerun-functions.
- Regenerate uv.lock. Core 2.0 stays pinned to a Git commit until it is
  published.
- Refuse cloud resume outside paid billing.
- Keep server SMS bindings on close.
- Snapshot extension arguments before execution, with a masked fallback.
- Check device support in long press, file push and clipboard set.
- Honor --config when saving the default device. List local devices
  despite a broken saved login.
- Fall back when os.fchmod is missing. Sanitize wrapped HTTP errors
  under --debug.
…logs

Check the exception chain for HTTP status errors in normal and debug modes. Log a fixed message when non-strict cloud discovery fails. Drop the unused billing-operation label.
…, code-based errors, plugin API version check

- No automatic billing escalation; --yes only skips confirmation, --billing paid authorizes
- Cost-capable calls take billing=, default MOBILERUN_BILLING; cloud tasks require paid
- Invalid billing input never echoed in errors, tracebacks, settings errors or CLI output
- Service contracts live in mobilerun.interfaces (incl. CloudTasks); Mailbox and
  PhoneNumber bases implement them for subclassing
- Cloud errors classified by service code via CloudErrorMapper
- Every entry-point module, bundled or add-on, declares PLUGIN_API_VERSION, checked once at load
- CloudPhoneNumber.send goes through the tool dispatch guard
- Remove unused MacroOperator._execute_macro

@lutz-grex lutz-grex left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, a lot landed: the sandbox and its extra are gone, extensions declare requires and the base checks them once in check_bind (clipboard works on local Android, a credential provider bound to another phone is rejected), proxy checkout resume returns the owned extension, mobilerun/interfaces/ has the cross-repo Protocols with a conformance test that fails on drift, errors branch on codes, --yes no longer upgrades no_commerce, the loader checks PLUGIN_API_VERSION, and most of the smaller items are done.

Still open:

  1. CI can't install the package. [tool.uv.sources] takes mobilerun-core from a git commit (c6803d2) that exists only on a branch of a private repo, so lint, pytest and check-image all fail with "failed to fetch commit". Merged like this, every later develop PR would be red too. The wheel asks for mobilerun-core>=2.0.0,<3, and PyPI has 1.12.2, so a 0.9.0 tag now would not install. Please release core 2.0.0, drop the git source, re-lock against PyPI and get CI green before this leaves draft.
  2. Run recordings still keep secrets in screenshots. core/runs/evidence.py writes screens/N.after.png even when sensitive_ui is set, the JSON next to it is masked, and test_recording.py now asserts that the PNG is kept. A card number typed with type_secret into a normal field is stored in clear. Please skip the PNG under the same rule core/screen/provider.py:154 uses, and change the test.
  3. Billing: one switch, not a policy. Fair point that unattended runs and Python callers need a way to never spend. Please do that with one switch and one list: the single list of paid operations the CLI uses for its confirmation also backs one library switch that blocks them before the request. Everything else goes: the three modes and the included tier, BillingPolicy, the ~70 require(NO_COMMERCE, …) calls that only validate the mode, the local "a task run needs paid" rule, the billing parameters on the interfaces, and the CLI checks that repeat the library ones. Whether an operation costs money and whether checkout is needed stays with the API.
  4. Contracts should not depend on the cloud SDK. interfaces/phone_number.py returns mobilerun_sdk types (MessageSendResponse, message_list_response.Item), so any other implementation has to build cloud SDK models. Please give the Protocol its own small result types; the cloud implementation maps to them.
  5. Release order. mobilerun-functions on PyPI pins mobilerun-core<2 for device and local, so it can't be installed next to 0.9.0. Please write the order into the PR body: core 2.0.0 → mobilerun-functions with mobilerun-core>=2,<3 → mobilerun 0.9.0 together with mobilerun-agents (so run has a home). The function, routine and sandbox commands from develop are removed here; please note in the upgrade notes that they come back as a mobilerun-functions CLI add-on. The PR body still describes the @cloud(webhook=) sandbox API and the sandbox extra in CI.

Smaller:

  • cli/webhook.py:163 still suggests @cloud(..., webhook=).
  • addons/plugins.py:80 imports the module before checking the version, so an incompatible add-on fails with "failed to load" instead of the version error.
  • cli/base/errors.py:146-162 follows __context__, so an unrelated, already handled HTTPStatusError replaces the real error message.
  • clients/cloud/tasks.py:20-44 copies the SDK's TaskRunParams field by field, including the vpn_country value list; please use the SDK type.
  • No caller outside tests: Redactor.remember_codes, collect_steps, start_run, BillingPolicy.require_cloud_creation, and CloudTasks in interfaces/tasks.py. Drop them unless mobilerun-agents uses them.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants