Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(mobile): recover orphaned emulators and harden device lifecycle
trohitge1766bcfc5f9
diff --git a/client/src/components/mobile/MobileWorkspace.tsx b/client/src/components/mobile/MobileWorkspace.tsxindex 1f8e67b4..7dcfabd7 100644--- a/client/src/components/mobile/MobileWorkspace.tsx+++ b/client/src/components/mobile/MobileWorkspace.tsx@@ -242,7 +242,8 @@ function MobileSession({ workflowId, nodeId, visible }: { workflowId: string; no})}>{setupFailed ? 'Retry setup' : 'Set up phone'}</Button>{(setupActive || setupFailed || status?.setup_progress) && <SetupProgress status={status} ticking={visible && pageVisible} />}</section>}- {!running && !status?.starting && installed && <p className="m-0 text-sm text-fg-muted">Your phone is ready to turn on. Click Start phone to use it.</p>}+ {!error && status?.start_error && <p role="alert" className="m-0 text-sm text-destructive">{status.start_error}</p>}+ {!running && !status?.starting && installed && !status?.start_error && <p className="m-0 text-sm text-fg-muted">Your phone is ready to turn on. Click Start phone to use it.</p>}</div>}{running && <><div ref={surface} className={`relative flex min-h-0 min-w-0 flex-1 touch-none items-center justify-center overflow-hidden bg-slate-950 ${held ? 'cursor-crosshair' : ''}`} onPointerDown={down} onPointerUp={up} onPointerCancel={() => { pointer.current = null; }} aria-label={held ? 'Phone screen: tap or drag to interact' : 'Phone screen, view only'}>diff --git a/client/src/components/mobile/__tests__/MobileWorkspace.test.tsx b/client/src/components/mobile/__tests__/MobileWorkspace.test.tsxindex 191534d9..deaffb1b 100644--- a/client/src/components/mobile/__tests__/MobileWorkspace.test.tsx+++ b/client/src/components/mobile/__tests__/MobileWorkspace.test.tsx@@ -22,6 +22,13 @@ beforeEach(() => {afterEach(() => { cleanup(); vi.unstubAllGlobals(); });describe('Mobile Workspace', () => {+ it('retains a startup failure across status refreshes without claiming the phone is ready', async () => {+ snapshot.start_error = 'This phone is already open, but could not be safely reconnected.';+ render(<MobileWorkspace workflowId="flow" nodes={nodes} />);+ expect(await screen.findByRole('alert')).toHaveTextContent('already open');+ expect(screen.queryByText(/Your phone is ready to turn on/)).toBeNull();+ expect(screen.getByRole('button', { name: 'Start phone' })).toBeEnabled();+ });it('keeps the phone connected and preserves a task draft when secondary panels collapse', async () => {snapshot.running = true;render(<MobileWorkspace workflowId="flow" nodes={nodes} />);diff --git a/client/src/components/mobile/api.ts b/client/src/components/mobile/api.tsindex 24e46888..9e0890ee 100644--- a/client/src/components/mobile/api.ts+++ b/client/src/components/mobile/api.ts@@ -8,6 +8,7 @@ export interface MobileStatus {geometry?: Geometry | null;setup?: string | Record<string, unknown> | null;setup_error?: string | null;+ start_error?: string | null;setup_progress?: { message?: string; started_at?: number | null; updated_at?: number | null; finished_at?: number | null; events?: { at: number; message: string }[] } | null;controller?: string | null;epoch: number;diff --git a/docs/mobile-workspace.md b/docs/mobile-workspace.mdindex 006be9ed..c1a29af3 100644--- a/docs/mobile-workspace.md+++ b/docs/mobile-workspace.md@@ -135,6 +135,10 @@ Minitap's [platform](https://www.minitap.ai/platform#slack-cli-mcp) and [miniTes## Validation and limitations+Phone startup first checks for an existing emulator. Recovery requires the console-reported AVD path to match this installation and the process to belong to its Android SDK. A process-wide device lock prevents two updated backends from owning the same writable phone. A disconnected automation driver can be restarted without launching a second emulator. Stop waits for the emulator and cleans up its owned child processes; it does not wipe phone data or stop unrelated emulators.++If startup fails, the message remains in Workspace after a refresh. A duplicate-AVD error means another emulator still holds the phone; if verified reconnection is unavailable, close that OpenCompany emulator and retry. Do not delete AVD lock files or use `-read-only` to bypass ownership. `emulator.log` retains launcher output and rotates to `emulator.previous.log` before a new launch when it exceeds 2 MiB. Error classification reads only the current attempt; `mobile.log` records recovery and boot-probe timeout events without model prompts or credentials.+Run backend validation with a boolean `DEBUG` environment value (for example, `$env:DEBUG='false'` in PowerShell). Values such as `release` fail settings validation in subprocess tests. Source-boundary checks exclude installed runtime data in `.opencompany` and legacy `.machina`; the mobile engine runs in its own dependency environment. The Android tool intentionally receives canvas edges to resolve its connected model, and the device driver's JSON wire replies are protocol output rather than application logs.Automated tests exercise fencing, successful-operation deduplication, cancellation while draining, takeover and resume with fake subprocesses, queued cancellation, source-patch compatibility, and Python syntax compilation of the patched upstream package. Additional tests use the actual loopback HTTP broker with a fake driver, reject unsafe archives and checksum mismatches, and verify that SDK tools run through Java arguments without a command shell. Patch tests require `.tmp/mobile-use-upstream` or `MOBILE_USE_UPSTREAM_SOURCE` pointing to the pinned checkout; they skip when that fixture is absent.diff --git a/server/nodes/mobile/_emulator.py b/server/nodes/mobile/_emulator.pynew file mode 100644index 00000000..89e088cd--- /dev/null+++ b/server/nodes/mobile/_emulator.py@@ -0,0 +1,125 @@+"""Verified emulator recovery and a process-wide lease for one writable AVD."""++import asyncio+import os+import re+from pathlib import Path++import psutil++from ._control import MobileError+from ._process import command+++class DeviceLock:+ def __init__(self, root: Path):+ self.file = (root / "device.lock").open("a+b")+ try:+ self.file.seek(0, 2)+ if not self.file.tell():+ self.file.write(b"0")+ self.file.flush()+ self.file.seek(0)+ if os.name == "nt":+ import msvcrt+ msvcrt.locking(self.file.fileno(), msvcrt.LK_NBLCK, 1)+ else:+ import fcntl+ fcntl.flock(self.file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)+ except OSError:+ self.file.close()+ raise MobileError("device_in_use", "Another OpenCompany backend is using this phone. Stop that backend before trying again.") from None++ def close(self):+ self.file.close() # The OS releases the lock, including after a crash.+++class RecoveredProcess:+ """Small asyncio.Process-compatible handle with psutil PID-reuse protection."""++ def __init__(self, process):+ self.process = process+ self.pid = process.pid++ @property+ def returncode(self):+ return None if self.process.is_running() else 0++ async def wait(self):+ while self.returncode is None:+ await asyncio.sleep(0.2)+ return self.returncode++ def kill(self):+ try:+ self.process.kill()+ except psutil.NoSuchProcess:+ pass+++def owned_children(pid):+ if not isinstance(pid, int) or pid <= 0:+ return []+ try:+ return psutil.Process(pid).children(recursive=True)+ except (psutil.Error, TypeError):+ return []+++async def stop_children(children):+ for child in children:+ try:+ child.kill() # psutil checks process identity before signalling.+ except psutil.NoSuchProcess:+ pass+ _, alive = await asyncio.to_thread(psutil.wait_procs, children, timeout=5)+ if alive:+ raise MobileError("stop_failed", "Android is still closing. Wait a moment and retry Stop phone.")+++async def recover_emulator(adb: Path, emulator: Path, avd: Path):+ """Require both the console's exact AVD path and an SDK process match."""+ output = await command([str(adb), "devices"], timeout=10)+ matches = []+ for line in output.splitlines():+ match = re.fullmatch(r"(emulator-(\d+))\s+device", line.strip())+ if not match:+ continue+ serial, port = match.groups()+ try:+ identity = await command([str(adb), "-s", serial, "emu", "avd", "path"], timeout=5)+ paths = [s.strip() for s in identity.splitlines() if s.strip() and s.strip() != "OK"]+ if len(paths) != 1 or Path(paths[0]).resolve() != avd.resolve():+ continue+ for proc in psutil.process_iter(["exe", "cmdline"]):+ try:+ args = proc.info["cmdline"] or []+ exe = Path(proc.info["exe"] or "").resolve()+ if not exe.is_relative_to(emulator.parent.resolve()):+ continue+ if "-port" in args and args[args.index("-port") + 1] == port and exe.name.lower().startswith("qemu-system"):+ matches.append((RecoveredProcess(proc), serial))+ except (psutil.Error, IndexError, OSError):+ continue+ except (OSError, RuntimeError, TimeoutError):+ continue+ if len(matches) > 1:+ raise MobileError("device_conflict", "More than one process owns this phone. Close the duplicate emulator before retrying.")+ return matches[0] if matches else None+++def boot_error(log: Path, offset: int, returncode) -> MobileError:+ try:+ with log.open("rb") as stream:+ stream.seek(0, 2)+ stream.seek(max(offset, stream.tell() - 16384))+ tail = stream.read().decode("utf-8", "replace").lower()+ except OSError:+ tail = ""+ if "multiple emulators with the same avd" in tail or "already running" in tail:+ return MobileError("device_in_use", "This phone is already open, but could not be safely reconnected. Close the existing OpenCompany emulator and try Start phone again. Your apps and data are preserved.")+ if "not enough" in tail and ("disk" in tail or "space" in tail):+ return MobileError("disk_full", "Android could not start because disk space is low. Free space on the phone's drive and try again.")+ if "acceleration" in tail and ("required" in tail or "not installed" in tail):+ return MobileError("acceleration_unavailable", "Android hardware acceleration is unavailable. Open Host readiness for setup instructions, then restart the computer.")+ return MobileError("boot_failed", f"Android closed during startup (exit code {returncode}). Try Start phone again. Diagnostic details: {log}")diff --git a/server/nodes/mobile/_router.py b/server/nodes/mobile/_router.pyindex a509e936..c1d519fe 100644--- a/server/nodes/mobile/_router.py+++ b/server/nodes/mobile/_router.py@@ -97,7 +97,12 @@ async def status(principal: str = Depends(authorize)):# During startup/shutdown return lifecycle status without touching the# driver. The serial is assigned before Android and automation are ready.if runtime.serial and not runtime.lifecycle_lock.locked():- await call(runtime.driver_call("geometry"))+ try:+ await runtime.driver_call("geometry")+ except Exception:+ # A lost connection is device state, not a failed status endpoint.+ # Return the fresh snapshot so the UI can offer Start/reconnect.+ runtime.start_error = "The phone connection was lost. Click Start phone to reconnect."return runtime.snapshot()diff --git a/server/nodes/mobile/_runtime.py b/server/nodes/mobile/_runtime.pyindex 40ce77f7..92dfccaf 100644--- a/server/nodes/mobile/_runtime.py+++ b/server/nodes/mobile/_runtime.py@@ -14,6 +14,7 @@ from ._install import AVD_NAME, install_engine, create_device, engine_ready, sdkfrom ._paths import mobile_root, runtime_pythonfrom ._process import command, hidden_optionsfrom ._diagnostics import event, recent+from ._emulator import DeviceLock, recover_emulator, boot_error, owned_children, stop_childrenREADS = frozenset({"geometry", "observe", "date", "packages", "foreground"})ACTIONS = frozenset({"tap", "swipe", "touch", "text", "erase", "key", "launch", "terminate", "url", "rotate"})@@ -27,6 +28,8 @@ class MobileRuntime:self.worker: asyncio.subprocess.Process | None = Noneself.serial: str | None = Noneself.geometry: dict | None = None+ self.device_lock = None+ self.start_error = ""self.driver_lock = asyncio.Lock()self.lifecycle_lock = asyncio.Lock()self.task_lock = asyncio.Lock()@@ -112,6 +115,7 @@ class MobileRuntime:"device": "Shared Android device","setup": self.setup_state,"setup_error": self.setup_error,+ "start_error": self.start_error,"setup_progress": self.setup_progress,"diagnostics": recent(),"active": {k: v for k, v in (self.active or {}).items() if k not in {"prompt"}},@@ -217,74 +221,106 @@ class MobileRuntime:async with self.lifecycle_lock:if self.stopping or (self.setup_task and not self.setup_task.done()):raise MobileError("device_busy", "Wait for setup or shutdown to finish")- if self.process and self.process.returncode is None:- return self.snapshot()- if self.process is not None:- await self._stop_driver()- self.process = None- self.serial = None- emulator, adb = sdk_tool("emulator"), sdk_tool("adb")- if not emulator or not adb or not engine_ready() or not (mobile_root() / "resource.json").is_file():- raise MobileError("setup_required", "Complete Mobile setup before starting the device")- port = None- for candidate in range(5560, 5680, 2):- held = []- try:- for n in (candidate, candidate + 1):- test = socket.socket()- held.append(test)- test.bind(("127.0.0.1", n))- port = candidate- break- except OSError:- pass- finally:- for test in held:- test.close()- if port is None:- raise MobileError("ports_busy", "No emulator port pair is free")- root = mobile_root()- event("phone_starting")- root.mkdir(parents=True, exist_ok=True)- log = (root / "emulator.log").open("ab")- env = {**os.environ, "ANDROID_AVD_HOME": str(root / "avd"), "ANDROID_SDK_ROOT": str(sdk_root())}- try:- self.process = await asyncio.create_subprocess_exec(- str(emulator),- "-avd",- AVD_NAME,- "-port",- str(port),- "-no-window",- "-no-audio",- stdout=log,- stderr=log,- env=env,- **hidden_options(),- )- finally:- log.close()- self.serial = f"emulator-{port}"+ self.start_error = ""try:- deadline = time.monotonic() + 180- while time.monotonic() < deadline:- if self.process.returncode is not None:- raise MobileError("boot_failed", "Emulator exited; inspect the Mobile emulator log")- boot = await command([str(adb), "-s", self.serial, "shell", "getprop", "sys.boot_completed"], check=False, timeout=10)- if boot.strip() == "1":- break- await asyncio.sleep(1)- else:- raise MobileError("boot_timeout", "Android did not finish booting within three minutes")- await self._start_driver()- event("phone_ready", serial=self.serial)- self.control.revoke()- self.control.state = "idle"+ return await self._start_locked()except BaseException as exc:+ self.start_error = str(exc) if isinstance(exc, MobileError) else "Phone startup was interrupted. Try Start phone again."event("phone_start_failed", failed=True, error_type=type(exc).__name__, code=getattr(exc, "code", "startup_failed"))await self._stop_owned()raise++ async def _start_locked(self) -> dict:+ if self.stopping or (self.setup_task and not self.setup_task.done()):+ raise MobileError("device_busy", "Wait for setup or shutdown to finish")+ if self.process and self.process.returncode is None:+ if not self.driver or self.driver.returncode is not None or self.geometry is None:+ await self._stop_driver()+ await self._start_driver()+ self.control.revoke()+ self.control.state = "idle"+ return self.snapshot()+ if self.process is not None:+ await self._stop_driver()+ self.process = None+ self.serial = None+ emulator, adb = sdk_tool("emulator"), sdk_tool("adb")+ if not emulator or not adb or not engine_ready() or not (mobile_root() / "resource.json").is_file():+ raise MobileError("setup_required", "Complete Mobile setup before starting the device")+ root = mobile_root()+ root.mkdir(parents=True, exist_ok=True)+ if self.device_lock is None:+ self.device_lock = DeviceLock(root)+ recovered = await recover_emulator(adb, emulator, root / "avd" / f"{AVD_NAME}.avd")+ if recovered:+ self.process, self.serial = recovered+ event("phone_reconnected", serial=self.serial)+ await self._start_driver()+ self.control.revoke()+ self.control.state = "idle"return self.snapshot()+ port = None+ for candidate in range(5560, 5680, 2):+ held = []+ try:+ for n in (candidate, candidate + 1):+ test = socket.socket()+ held.append(test)+ test.bind(("127.0.0.1", n))+ port = candidate+ break+ except OSError:+ pass+ finally:+ for test in held:+ test.close()+ if port is None:+ raise MobileError("ports_busy", "No emulator port pair is free")+ root = mobile_root()+ event("phone_starting")+ root.mkdir(parents=True, exist_ok=True)+ log_path = root / "emulator.log"+ if log_path.exists() and log_path.stat().st_size > 2 * 1024 * 1024:+ log_path.replace(root / "emulator.previous.log")+ log = log_path.open("ab")+ log_offset = log.tell()+ env = {**os.environ, "ANDROID_AVD_HOME": str(root / "avd"), "ANDROID_SDK_ROOT": str(sdk_root())}+ try:+ self.process = await asyncio.create_subprocess_exec(+ str(emulator),+ "-avd",+ AVD_NAME,+ "-port",+ str(port),+ "-no-window",+ "-no-audio",+ stdout=log,+ stderr=log,+ env=env,+ **hidden_options(),+ )+ finally:+ log.close()+ self.serial = f"emulator-{port}"+ deadline = time.monotonic() + 180+ while time.monotonic() < deadline:+ if self.process.returncode is not None:+ raise boot_error(log_path, log_offset, self.process.returncode)+ try:+ boot = await command([str(adb), "-s", self.serial, "shell", "getprop", "sys.boot_completed"], check=False, timeout=10)+ except TimeoutError:+ event("phone_boot_probe_timeout", serial=self.serial)+ continue+ if boot.strip() == "1":+ break+ await asyncio.sleep(1)+ else:+ raise MobileError("boot_timeout", "Android did not finish booting within three minutes")+ await self._start_driver()+ event("phone_ready", serial=self.serial)+ self.control.revoke()+ self.control.state = "idle"+ return self.snapshot()def driver_env(self) -> dict:allowed = {@@ -605,6 +641,7 @@ class MobileRuntime:async def _stop_driver(self):proc, self.driver = self.driver, None+ self.geometry = Noneif proc and proc.returncode is None:proc.kill()await proc.wait()@@ -615,17 +652,23 @@ class MobileRuntime:self.capabilities.clear()await self._stop_worker()await self._stop_driver()- proc, self.process = self.process, None+ proc = self.process+ children = owned_children(getattr(proc, "pid", None)) if proc else []if proc and proc.returncode is None:if self.serial:with contextlib.suppress(Exception):- await command([str(sdk_tool("adb")), "-s", self.serial, "emu", "kill"], timeout=2)+ await command([str(sdk_tool("adb")), "-s", self.serial, "emu", "kill"], timeout=5)try:- await asyncio.wait_for(proc.wait(), 2)+ await asyncio.wait_for(proc.wait(), 10)except asyncio.TimeoutError:proc.kill()- await proc.wait()+ await asyncio.wait_for(proc.wait(), 5)+ await stop_children(children)+ self.process = Noneself.serial, self.geometry = None, None+ if self.device_lock is not None:+ self.device_lock.close()+ self.device_lock = Noneasync with self.control.lock:self.control.state = "idle"self.control.results.clear()@@ -638,6 +681,7 @@ class MobileRuntime:raise MobileError("device_busy", "Cancel the active task before stopping the device")async with self.lifecycle_lock:await self._stop_owned()+ self.start_error = ""async def shutdown(self):self.stopping = True@@ -648,7 +692,8 @@ class MobileRuntime:if self.active:self.active["status"] = "cancelled"self.resume_event.set()- await self._stop_owned()+ async with self.lifecycle_lock:+ await self._stop_owned()if self.broker_runner:await self.broker_runner.cleanup()self.broker_runner, self.broker_url = None, Nonediff --git a/server/tests/test_mobile_emulator.py b/server/tests/test_mobile_emulator.pynew file mode 100644index 00000000..dd4956b2--- /dev/null+++ b/server/tests/test_mobile_emulator.py@@ -0,0 +1,139 @@+"""Emulator ownership, recovery, and startup failure regression coverage."""++from pathlib import Path+from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest++from nodes.mobile import _emulator as emulator+from nodes.mobile import _runtime as runtime+from nodes.mobile._control import MobileError+++def test_device_lock_excludes_second_backend_and_releases(tmp_path):+ first = emulator.DeviceLock(tmp_path)+ try:+ with pytest.raises(MobileError, match="Another OpenCompany"):+ emulator.DeviceLock(tmp_path)+ finally:+ first.close()+ emulator.DeviceLock(tmp_path).close()+++def test_boot_error_ignores_previous_attempts(tmp_path):+ log = tmp_path / "emulator.log"+ old = b"FATAL Running multiple emulators with the same AVD\n"+ log.write_bytes(old + b"new attempt failed\n")+ assert emulator.boot_error(log, 0, 1).code == "device_in_use"+ assert emulator.boot_error(log, len(old), 7).code == "boot_failed"+ assert "7" in str(emulator.boot_error(log, len(old), 7))++[email protected]("same_path,same_sdk,expected", [(True, True, True), (False, True, False), (True, False, False)])+async def test_recovery_requires_avd_path_and_sdk_process(monkeypatch, tmp_path, same_path, same_sdk, expected):+ avd = tmp_path / "avd" / "OpenCompany.avd"+ sdk = tmp_path / "sdk" / "emulator"+ executable = sdk / "emulator.exe"+ proc = SimpleNamespace(pid=123, info={+ "exe": str((sdk if same_sdk else tmp_path / "other") / "qemu-system-x86_64.exe"),+ "cmdline": ["qemu", "-avd", "OpenCompany", "-port", "5560"],+ })+ calls = AsyncMock(side_effect=["List of devices attached\nemulator-5560\tdevice\n", str(avd if same_path else tmp_path / "other.avd") + "\nOK\n"])+ monkeypatch.setattr(emulator, "command", calls)+ monkeypatch.setattr(emulator.psutil, "process_iter", lambda *_: [proc])+ result = await emulator.recover_emulator(Path("adb"), executable, avd)+ assert bool(result) is expected+ if result:+ assert result[1] == "emulator-5560"+++def test_missing_pid_never_targets_backend_children(monkeypatch):+ monkeypatch.setattr(emulator.psutil, "Process", lambda *_: pytest.fail("must not inspect current process"))+ assert emulator.owned_children(None) == []+++def phone(monkeypatch, tmp_path):+ value = runtime.MobileRuntime()+ monkeypatch.setattr(runtime, "mobile_root", lambda: tmp_path)+ monkeypatch.setattr(runtime, "event", lambda *_args, **_kwargs: None)+ monkeypatch.setattr(runtime, "sdk_tool", lambda name: tmp_path / name)+ monkeypatch.setattr(runtime, "engine_ready", lambda: True)+ (tmp_path / "resource.json").write_text("{}")+ return value+++async def test_reconnect_does_not_launch_duplicate(phone, monkeypatch):+ proc = SimpleNamespace(returncode=None)+ monkeypatch.setattr(runtime, "recover_emulator", AsyncMock(return_value=(proc, "emulator-5560")))+ spawn = AsyncMock(side_effect=AssertionError("must reuse existing phone"))+ monkeypatch.setattr(runtime.asyncio, "create_subprocess_exec", spawn)++ async def driver():+ phone.driver = SimpleNamespace(returncode=None)+ phone.geometry = {"width": 1080, "height": 2400}++ monkeypatch.setattr(phone, "_start_driver", driver)+ try:+ assert (await phone.start())["running"] is True+ assert phone.serial == "emulator-5560"+ spawn.assert_not_awaited()+ finally:+ phone.device_lock.close()+++async def test_live_emulator_with_dead_driver_reconnects(phone, monkeypatch):+ phone.process = SimpleNamespace(returncode=None)+ phone.driver = SimpleNamespace(returncode=1)+ phone.geometry = {"width": 1}+ start = AsyncMock()+ monkeypatch.setattr(phone, "_start_driver", start)+ await phone.start()+ start.assert_awaited_once()+ assert phone.geometry is None+++async def test_spawn_failure_releases_lock_and_retains_error(phone, monkeypatch):+ monkeypatch.setattr(runtime, "recover_emulator", AsyncMock(return_value=None))+ monkeypatch.setattr(runtime.asyncio, "create_subprocess_exec", AsyncMock(side_effect=OSError("spawn failed")))+ with pytest.raises(OSError):+ await phone.start()+ assert phone.device_lock is None+ assert phone.process is None+ assert phone.snapshot()["start_error"]+++async def test_stop_kills_owned_children_after_launcher_exit(phone, monkeypatch):+ phone.process = SimpleNamespace(returncode=0, pid=456)+ children = [object()]+ monkeypatch.setattr(runtime, "owned_children", lambda pid: children if pid == 456 else [])+ stop = AsyncMock()+ monkeypatch.setattr(runtime, "stop_children", stop)+ await phone.stop()+ stop.assert_awaited_once_with(children)+ assert phone.process is None+++async def test_boot_probe_timeout_retries_instead_of_killing_phone(phone, monkeypatch):+ monkeypatch.setattr(runtime, "recover_emulator", AsyncMock(return_value=None))+ monkeypatch.setattr(runtime, "command", AsyncMock(side_effect=[TimeoutError(), "1"]))+ proc = SimpleNamespace(returncode=None)+ monkeypatch.setattr(runtime.asyncio, "create_subprocess_exec", AsyncMock(return_value=proc))+ monkeypatch.setattr(phone, "_start_driver", AsyncMock())+ try:+ await phone.start()+ assert runtime.command.await_count == 2+ assert phone.process is proc+ finally:+ phone.device_lock.close()+++async def test_status_returns_disconnection_state_instead_of_http_error(phone, monkeypatch):+ from nodes.mobile._router import status+ phone.serial = "emulator-5560"+ monkeypatch.setattr(runtime, "get_runtime", lambda: phone)+ monkeypatch.setattr(phone, "driver_call", AsyncMock(side_effect=MobileError("device_offline", "offline")))+ result = await status(principal="owner")+ assert result["running"] is False+ assert "reconnect" in result["start_error"]