← Back to Pull requests

feat: lease local devices so several agents can share them #536

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Oct 28, 2026 00:40 UTC
Author

Summary

Running several agents against one machine (a few Claude Code / Codex sessions, or many clients of one --listen server) today means they can grab the same emulator or phone and step on each other. This adds opt-in local device leasing: an agent leases a device, gets a handle, and passes that handle as device to any existing tool. Others are refused politely until the lease is released or expires.

Closes #534. Discussed in #534 as CONTRIBUTING asks for larger features.

What's new

| Tool | What it does |
|---|---|
| mobile_lease_device | Leases a free local device that matches platform / type / device (id or exact name). Options: holder label, ttlSeconds (default 600, max 3600), wait + timeoutSeconds (default 300) to block until one frees. Returns { device: "lease:<token>", lease: {...} }. |
| mobile_renew_lease | Extends a lease (optionally with a new ttlSeconds) without touching the device. |
| mobile_release_lease | Releases a lease. The device state is left as-is (unlike mobile_release_remote_device). |
| mobile_list_leases | Read-only: who holds which device, until when. Never shows handles. |

mobile_list_available_devices adds a lease field to leased devices (free devices are unchanged), plus a hint to wait when every local device is leased. The server instructions get two lines on when to lease.

// mobile_lease_device { "platform": "android", "holder": "checkout tests", "wait": true }
{ "device": "lease:k3J9…", "lease": { "leaseId": "1b2a831a", "device": "emulator-5554", "deviceName": "Pixel 9",
  "holder": "checkout tests", "ttlSeconds": 600, "expiresAt": "2026-10-27T12:10:00.000Z" }, "hint": "…" }

// mobile_launch_app { "device": "lease:k3J9…", "packageName": "com.example" }   -> works, renews the lease
// mobile_launch_app { "device": "emulator-5554", ... } from another agent      -> isError:
//   Device "emulator-5554" is leased by "checkout tests" until 2026-10-27T12:10:00.000Z (expires in 412s). Pass your own lease handle …
// mobile_release_lease { "lease": "lease:k3J9…" }

Design

  • Resolved once, in the tool() helper. Every tool whose schema has device gets it passed through DeviceLeaseStore.resolve() before its callback runs, so no tool schema changed and recording/crash tools (which use the id directly rather than getRobotFromDevice) are covered too. The wrapped callback is what mobile_batch_commands calls, so each batch step is checked as well. Exempt: mobile_release_remote_device (cloud id), mobile_lease_device (its device is a filter) and the batch tool itself (it hands its device to the steps).

  • Backward compatible. A raw id resolves to itself unless an active lease names that device. With no lease file this costs one failed readFile, with no lock and no write. If the state directory can't be read, raw ids fall through (logged) so machines that never lease are never broken.

  • Cross-process, stateless. Leases live in leases.json under $MOBILEMCP_STATE_DIR or $XDG_STATE_HOME/mobile-mcp (~/.local/state/mobile-mcp; %LOCALAPPDATA%\mobile-mcp on Windows). Dir is 0700, file is 0600. Writes are temp file + rename. Changes happen under an O_EXCL lock file (leases.lock) holding {pid, hostname, nonce, createdAt}. A lock is stale if its pid is dead on this host or it's older than 10s (locks are held for milliseconds). Stale locks are moved aside with an atomic rename and restored with link() if another process replaced them in between. A process only unlinks a lock carrying its own nonce. Because handles are tokens rather than MCP sessions, this works the same over stdio and stateless Streamable HTTP.

  • Security. Tokens are 24 random bytes (crypto.randomBytes, base64url). Only their sha256 is stored. trace() output of args, responses and errors goes through redactLeaseHandles() (lease:AbCd…). The public leaseId can't act on a device.

  • Expiry. Every successful use renews the TTL (writes are skipped when the extension would be under 1s). Expired leases are pruned on every write and ignored on every read, so a crashed agent frees its device after ttlSeconds. The file is deleted when the last lease goes.

  • Small refactor, needed for reuse. The body of mobile_list_available_devices moved, unchanged, into a listLocalDevices() helper so mobile_lease_device filters exactly the same device list (legacy robot mode included). Most of the server.ts diff is that move.
  • Out of scope / open questions

  • Leasing is advisory between mobile-mcp processes. Other tools (adb, Xcode, a second user with a different state dir) aren't blocked.

  • No forced release/admin override: an abandoned lease expires within its TTL (max 1h). Happy to add force if maintainers want it.

  • The README translations (ja, zh-CN) aren't updated.
  • Testing

    No device needed. Everything runs under the existing npm test (Playwright as the runner, c8 for coverage):

  • test/device-leases.test.ts: the store on its own, with a fake clock. Covers acquire, conflict, next-free candidate, raw-id refusal naming holder/expiry, foreign/malformed handles, expiry, renew-on-use, explicit renew with new TTL, release and file cleanup, TTL clamping, redaction, a damaged file, three stale-lock cases (dead pid, old lock from another host, empty old file), a live lock timing out, 20 concurrent store instances racing for one device, and 8 separate Node processes racing for 3 devices (the store is transpiled with the typescript devDependency into a temp file so no build is needed).

  • test/server-leases.test.ts: through the MCP client. Covers raw id refused, handle allowed, batch step refused, unleased device untouched, list/renew/release tools, and formatAvailableDevices with leases. With a stand-in MOBILECLI_PATH shell script it also covers mobile_lease_device end-to-end (filters, conflict message, wait picking the device up once it's released, no match).

  • test/server-annotations.test.ts: annotations for the 4 new tools.
  • npm run build   # ok
    npm run lint    # ok
    npm test        # 179 passed (148 before + 31 new); device-leases suite repeated 15× with no flakes
    

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: bhargavmehta01 Review duration: 48528m
    All Vouch review confidence checks passed
    Residual risk 0.38 = Change Risk (0.64) × (1 − Review Confidence (0.41)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.64 · 650 lines diff across 8 files
    0.64
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    40%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.344
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    1 comments
    "Review active on #536"
    general weight: 0.35
    Assignees
    Unassigned
    Labels
    risk: medium confidence: 40.9% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 64% (MEDIUM) · Higher = larger blast radius
    64%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 40.9% · Lower = rushed or shallow review
    40.9%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 37.8% · Moderate risk
    37.8%