diff --git a/packages/agentenv-protocol/src/agentenv_protocol/computer/__init__.py b/packages/agentenv-protocol/src/agentenv_protocol/computer/__init__.py index 1fdc2622c..3b4ec1cfb 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/computer/__init__.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/computer/__init__.py @@ -71,6 +71,7 @@ pointer_position, pointer_up, press, + read_files, record, run_in_session, scroll, @@ -138,8 +139,8 @@ def __getattr__(name: str) -> Any: "display", "set_display", "capture", "click", "drag", "scroll", "type_text", "press", "pointer_move", "pointer_down", "pointer_up", "pointer_position", "key_down", "key_up", "navigate", "history", "tabs", "dialog", "upload", "page_state", - "run_in_session", "write_files", "record", "Recording", "RecordHints", "RecordedFrame", "RecordedSegment", - "frames_in_thread", "RecordingManifest", "ManifestSegment", + "run_in_session", "write_files", "read_files", "record", "Recording", "RecordHints", "RecordedFrame", + "RecordedSegment", "frames_in_thread", "RecordingManifest", "ManifestSegment", "ComputerError", "InvalidArgument", "OutOfBounds", "StaleFrame", "InputBusy", "PermissionDenied", "Unsupported", "BackgroundUnavailable", "TargetUnavailable", "DeviceUnavailable", "DialogOpen", "LimitExceeded", "Timeout", "DeliveryFailed", diff --git a/packages/agentenv-protocol/src/agentenv_protocol/computer/_adb.py b/packages/agentenv-protocol/src/agentenv_protocol/computer/_adb.py new file mode 100644 index 000000000..d958517d9 --- /dev/null +++ b/packages/agentenv-protocol/src/agentenv_protocol/computer/_adb.py @@ -0,0 +1,119 @@ +"""The base class's defaults for the OS operations on Android, for a driver beside the device: each goes through adb, +as the device's ``shell`` user and never ``su``, the home being /sdcard. adb is ``AGENTENV_ADB`` or the one on PATH, and +reads its own ``ANDROID_SERIAL`` and ``ADB_SERVER_SOCKET`` for the device and the server it goes through. A file +written is announced to the media scanner, so the gallery and file apps list it.""" +from __future__ import annotations + +import asyncio +import contextlib +import os +import shlex +import tempfile +import uuid +from pathlib import Path, PurePosixPath + +from ._linux import DRAIN_S, _Capped +from .errors import DeliveryFailed, DeviceUnavailable, InvalidArgument +from .operations import ExecResult + +#: The variable naming the adb binary. +ADB_ENV = "AGENTENV_ADB" +HOME = PurePosixPath("/sdcard") +#: How long one adb check may take, and one push or pull of a file. +ADB_TIMEOUT_S = 60 +TRANSFER_TIMEOUT_S = 600 +#: What the device prints on stderr, exiting 127, when a command can't start: its folder or its program isn't there. +CANNOT_RUN = "agentenv-cannot-run:" +MEDIA_SCAN = "android.intent.action.MEDIA_SCANNER_SCAN_FILE" + + +def adb() -> str: + return os.environ.get(ADB_ENV) or "adb" + + +async def run_in_session(argv: list[str], cwd: str | None, env: dict[str, str] | None, timeout_s: float, *, + output_bytes: int) -> ExecResult: + """Run ``argv`` on the device with ``env`` added, in ``cwd`` relative to /sdcard, keeping at most ``output_bytes`` + of each stream as it's read; past ``timeout_s`` adb is killed, which ends the command.""" + folder, program = shlex.quote(str(HOME / (cwd or ""))), shlex.quote(argv[0]) + assignments = "".join(f"{shlex.quote(f'{name}={value}')} " for name, value in (env or {}).items()) + lookup = f"PATH={shlex.quote(env['PATH'])}; " if env and "PATH" in env else "" + command = (f"cd {folder} 2>/dev/null || {{ echo '{CANNOT_RUN} no such folder' >&2; exit 127; }}; " + f"({lookup}command -v {program}) >/dev/null 2>&1 || {{ echo '{CANNOT_RUN} not found' >&2; exit 127; }}; " + f"exec {'env ' + assignments if assignments else ''}{shlex.join(argv)}") + process = await _spawn("shell", command) + outputs = [_Capped(output_bytes), _Capped(output_bytes)] + readers = asyncio.gather(*(out.read(stream) for out, stream in zip(outputs, (process.stdout, process.stderr)))) + timed_out = False + try: + await asyncio.wait_for(process.wait(), timeout_s) + except asyncio.TimeoutError: + timed_out = True + with contextlib.suppress(ProcessLookupError): + process.kill() + await process.wait() + with contextlib.suppress(asyncio.TimeoutError): + await asyncio.wait_for(readers, DRAIN_S) + stdout, stderr = outputs + if process.returncode == 127 and stderr.kept.startswith(CANNOT_RUN.encode()): + why = stderr.kept.decode(errors="replace").removeprefix(CANNOT_RUN).strip() + raise InvalidArgument(f"cannot run {argv[0]!r} in {cwd or '~'!r}: {why} on the device") + return ExecResult(exit_code=None if timed_out else process.returncode, stdout=bytes(stdout.kept), + stderr=bytes(stderr.kept), timed_out=timed_out, truncated=stdout.cut or stderr.cut) + + +async def write_files(files: dict[str, bytes]) -> None: + """Write each file under /sdcard atomically, pushed beside it and renamed over it, then announce it to the media + scanner.""" + for relative, data in files.items(): + target = HOME / relative + partial = target.parent / f".agentenv-{uuid.uuid4().hex[:12]}.part" + with tempfile.TemporaryDirectory() as scratch: + local = Path(scratch) / target.name + local.write_bytes(data) + await _adb("shell", f"mkdir -p {shlex.quote(str(target.parent))}") + try: + await _adb("push", str(local), str(partial), timeout_s=TRANSFER_TIMEOUT_S) + await _adb("shell", f"mv -f {shlex.quote(str(partial))} {shlex.quote(str(target))}") + except BaseException: + with contextlib.suppress(Exception): + await _adb("shell", f"rm -f {shlex.quote(str(partial))}") + raise + await _adb("shell", f"am broadcast -a {MEDIA_SCAN} -d {shlex.quote('file://' + str(target))}") + + +async def read_files(paths: list[str], into: Path) -> None: + """Pull each of ``paths`` under /sdcard that exists to the same path under ``into``; adb failing raises, rather + than reading as a missing path.""" + for relative in paths: + remote = str(HOME / relative) + answer = (await _adb("shell", f"if [ -e {shlex.quote(remote)} ]; then echo yes; else echo no; fi")).strip() + if answer == b"no": + continue + if answer != b"yes": + raise DeliveryFailed(f"the device didn't say whether {relative!r} exists: {answer[:200]!r}") + (into / relative).parent.mkdir(parents=True, exist_ok=True) + await _adb("pull", remote, str((into / relative).parent), timeout_s=TRANSFER_TIMEOUT_S) + + +async def _spawn(*args: str) -> asyncio.subprocess.Process: + try: + return await asyncio.create_subprocess_exec(adb(), *args, stdin=asyncio.subprocess.DEVNULL, + stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE) + except FileNotFoundError: + raise DeviceUnavailable(f"{adb()} is not installed") from None + + +async def _adb(*args: str, timeout_s: float = ADB_TIMEOUT_S) -> bytes: + """adb's output, or DeliveryFailed with what it said when it fails or doesn't answer within ``timeout_s``.""" + process = await _spawn(*args) + try: + stdout, stderr = await asyncio.wait_for(process.communicate(), timeout_s) + except asyncio.TimeoutError: + with contextlib.suppress(ProcessLookupError): + process.kill() + await process.wait() + raise DeliveryFailed(f"adb {args[0]} gave no answer in {timeout_s:g}s") from None + if process.returncode != 0: + raise DeliveryFailed(f"adb {args[0]}: {(stderr or stdout).decode(errors='replace').strip()}") + return stdout diff --git a/packages/agentenv-protocol/src/agentenv_protocol/computer/card.py b/packages/agentenv-protocol/src/agentenv_protocol/computer/card.py index 2f99ca982..13f319a7a 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/computer/card.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/computer/card.py @@ -6,7 +6,6 @@ from typing import TYPE_CHECKING from . import clock -from .dataplane import DEFAULT_DATA_PATHS from .recording import recording_params from ..types import METHOD_ADD, EnvironmentExtension, EnvironmentTool, IntakeDeclaration, IntakeFormat, intake_extension @@ -86,15 +85,16 @@ def extension_params(driver: ComputerDriverEnvironment, uri: str) -> dict: def computer_features(driver: ComputerDriverEnvironment) -> dict: - """computer/v1's params: what the seven tools take, how input is delivered, the platform and the default data - paths.""" + """computer/v1's params: what the seven tools take, how input is delivered, the platform, the default data paths + and where the driver runs.""" return { "buttons": list(driver.buttons), "max_click_count": driver.max_click_count, "keys": driver.keys if driver.keys == "all" else list(driver.keys), "max_text_length": driver.max_text_length, "max_wait_ms": driver.max_wait_ms, "max_drag_points": driver.max_drag_points, "max_duration_ms": driver.max_duration_ms, "max_key_repeat": driver.max_key_repeat, "max_scroll_amount": driver.max_scroll_amount, "delivery": "foreground", "platform": driver.platform.as_dict(), - "supports": list(driver.supports), "default_data_paths": list(DEFAULT_DATA_PATHS), "screen": driver.screen_kind, + "supports": list(driver.supports), "default_data_paths": list(driver.default_data_paths), + "screen": driver.screen_kind, "placement": driver.placement, } diff --git a/packages/agentenv-protocol/src/agentenv_protocol/computer/checks.py b/packages/agentenv-protocol/src/agentenv_protocol/computer/checks.py index 28a568c24..ae89f1f02 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/computer/checks.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/computer/checks.py @@ -45,6 +45,11 @@ def check_features(cls: type) -> None: problems.append(f"Settings is ComputerSettings or a subclass of it, got {cls.Settings!r}") if cls.screen_kind not in ("desktop", "page"): problems.append(f"screen_kind is desktop or page, got {cls.screen_kind!r}") + if cls.placement == "provider": + problems.append("placement provider, a driver its device's provider serves, isn't supported yet: use inside " + "or beside") + elif cls.placement not in ("inside", "beside"): + problems.append(f"placement is inside or beside, got {cls.placement!r}") if ("set_display" in declared(cls)) != bool(cls.display_modes): problems.append("display_modes and @set_display come together") problems += check_recording(cls.recording) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/computer/conformance/checks.py b/packages/agentenv-protocol/src/agentenv_protocol/computer/conformance/checks.py index 27da96e12..3c80dad0f 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/computer/conformance/checks.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/computer/conformance/checks.py @@ -6,6 +6,7 @@ import asyncio import base64 import contextlib +import hashlib import io import json import math @@ -52,8 +53,10 @@ DATA_PLANE = (INTAKE_EXTENSION_URI, DATA_OBJECTS_EXTENSION_URI) #: Where the fixture is staged and keeps its state, relative to the session user's home. STAGE = ".agentenv-probe" -#: How the probe reads a staged file's owner: through the python3 the fixture runs on, the same on every OS. +#: How the probe reads a staged file's owner: through the python3 the fixture runs on, the same on every OS; beside a +#: device, which has no python3, through its stat. OWNER = ("python3", "-c", "import os, sys; print(os.stat(sys.argv[1]).st_uid)") +DEVICE_OWNER = ("stat", "-c", "%u") #: Where a page driver's computer_upload takes files from, relative to the session user's home. UPLOADS = "Uploads" #: What the probe answers the page fixture's prompt with. @@ -144,6 +147,8 @@ def __init__(self, driver: Driver, session: ClientSession, ready_timeout_s: floa self.gtk = not self.page and platform.get("display") == "wayland" self.fixture = "page_fixture.py" if self.page else "wayland_fixture.py" if self.gtk else "fixture.py" self.windows = platform.get("os") == "windows" + #: Whether the driver runs beside its device, which may have no python3, and keeps its recordings off it. + self.beside = self.features.get("placement") == "beside" #: The chord that selects a text box's text: Tk's Ctrl+/, which the Tk desk binds everywhere, or on the GTK #: desk GTK's own Ctrl+A. self.select_all = ["Control", "a"] if self.gtk else ["Control", "/"] @@ -690,7 +695,8 @@ async def one_account() -> str | None: async def one_user() -> str | None: uid = (await self.driver.run("id", "-u"))["stdout"].strip() - owner = (await self.driver.run(*OWNER, f"{STAGE}/{self.fixture}"))["stdout"].strip() + reader = DEVICE_OWNER if self.beside else OWNER + owner = (await self.driver.run(*reader, f"{STAGE}/{self.fixture}"))["stdout"].strip() if uid == "0": return "commands run as root" return None if owner == uid else f"data/add wrote as uid {owner}, commands run as uid {uid}" @@ -1177,8 +1183,11 @@ async def _segments_match(self, wire: dict, fps: int) -> str | None: async def _read_back(self, segment: ManifestSegment) -> bytes | str: """A segment a recording without a grant kept on the computer, read back and matched to its manifest entry's - size and digest; what is wrong, as a string, when it can't be.""" + size and digest; what is wrong, as a string, when it can't be. Beside a device, through data/get, which reads + the recordings where the driver keeps them, needing no python3.""" path = f"{RECORDINGS_DIR}/{segment.path}" + if self.beside: + return await self._read_back_through_data_get(segment, path) out = await self.driver.run("python3", "-c", READ_DIGEST, path) if out.get("exit_code") != 0: return f"segment {segment.index} couldn't be read back: {out.get('stderr', '')[-200:]}" @@ -1196,6 +1205,18 @@ async def _read_back(self, segment: ManifestSegment) -> bytes | str: data += read return data + async def _read_back_through_data_get(self, segment: ManifestSegment, path: str) -> bytes | str: + got = await self.driver.rpc("data/get", {"paths": [path]}) + parts = (got.get("result") or {}).get("parts") + if not parts: + return f"segment {segment.index} couldn't be read back through data/get: it answered {str(got)[:200]}" + data = base64.b64decode(parts[0]["file"]["bytes"]) + digest = hashlib.sha256(data).hexdigest() + if (len(data), digest) != (segment.bytes, segment.sha256): + return f"segment {segment.index}'s file is {len(data)} bytes, sha256 {digest[:12]}; " \ + f"the manifest says {segment.bytes}, {segment.sha256[:12]}" + return data + async def _annotated_click(self, wire: dict, size: tuple[int, int], point: tuple[int, int], inside: tuple[int, int], was: tuple[int, int, int]) -> str | None: """What is wrong with an annotated recording of one click at frame pixel ``point`` of a frame ``size``, the diff --git a/packages/agentenv-protocol/src/agentenv_protocol/computer/dataplane.py b/packages/agentenv-protocol/src/agentenv_protocol/computer/dataplane.py index be25c769a..85d278af1 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/computer/dataplane.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/computer/dataplane.py @@ -1,7 +1,8 @@ """The data plane on a computer: ``data/add`` writes files under the session user's home, ``data/get`` returns the -files under the paths its caller names, or under ``DEFAULT_DATA_PATHS`` when it names none, leaving out those under a -path one of the computer's apps keeps its data in. Each file part names its path, relative to the home, under the -``data-objects/v1`` marker.""" +files under the paths its caller names, or under the driver's ``default_data_paths`` when it names none, leaving out +those under a path one of the computer's apps keeps its data in. Each file part names its path, relative to the home, +under the ``data-objects/v1`` marker. A driver beside a device reads its files with ``@read_files``; the recordings +it keeps are in its own home.""" from __future__ import annotations import base64 @@ -27,6 +28,8 @@ MAX_URL_BYTES = 1 << 30 #: What ``data/get`` returns when its caller names no paths: the folders a desktop keeps its user's files in. DEFAULT_DATA_PATHS = ("Desktop", "Documents", "Downloads") +#: Where the base class writes recordings, relative to the driver's home, and keeps them when there is no grant. +RECORDINGS_DIR = ".agentenv-recordings" _PATHS = TypeAdapter(list[RelativePath]) @@ -35,6 +38,8 @@ class DataPlane: _computer: ComputerRuntime settings: ComputerSettings + default_data_paths: tuple[str, ...] + placement: str @add_data async def _computer_data_add(self, parts: list) -> None: @@ -56,10 +61,20 @@ async def _computer_data_add(self, parts: list) -> None: async def _computer_data_get(self, write_namespace: Optional[WriteNamespaceGrant] = None, paths: Optional[list[str]] = None) -> list: try: - named = _PATHS.validate_python(paths) if paths is not None else list(DEFAULT_DATA_PATHS) + named = _PATHS.validate_python(paths) if paths is not None else list(self.default_data_paths) except ValidationError: raise ValueError(f"data/get on a computer takes paths relative to the home, not {paths!r}") from None - return await file_parts(Path.home(), named, write_namespace, leaving_out=await self._computer.app_paths()) + leaving_out = await self._computer.app_paths() + if not self._computer.has("read_files"): + return await file_parts(Path.home(), named, write_namespace, leaving_out=leaving_out) + kept_here = [path for path in named + if self.placement == "beside" and PurePosixPath(path).is_relative_to(RECORDINGS_DIR)] + on_device = [path for path in named if path not in kept_here] + with tempfile.TemporaryDirectory() as into: + if on_device: + await self._computer.call("read_files", on_device, Path(into)) + return await parts_of(listed(Path(into), on_device, leaving_out) + listed(Path.home(), kept_here), + write_namespace) async def file_parts(home: Path, paths: list[str], write_namespace: Optional[WriteNamespaceGrant], @@ -67,8 +82,18 @@ async def file_parts(home: Path, paths: list[str], write_namespace: Optional[Wri """A part for each file under ``paths`` of ``home`` but under none of ``leaving_out``, naming its path relative to ``home``: uploaded under ``write_namespace`` when there is one, else inline. A file a running app removes before it's read is left out.""" - files = [(relative, source) for relative, source in data_files(home, paths) - if not any(PurePosixPath(relative).is_relative_to(owned) for owned in leaving_out)] + return await parts_of(listed(home, paths, leaving_out), write_namespace) + + +def listed(home: Path, paths: list[str], leaving_out: list[str] = ()) -> list[tuple[str, Path]]: + """Every file under ``paths`` of ``home`` but under none of ``leaving_out``, by its path relative to ``home``.""" + return [(relative, source) for relative, source in data_files(home, paths) + if not any(PurePosixPath(relative).is_relative_to(owned) for owned in leaving_out)] + + +async def parts_of(files: list[tuple[str, Path]], write_namespace: Optional[WriteNamespaceGrant]) -> list: + """A part for each of ``files``, named by its relative path: all uploaded under one ``write_namespace``, whose + limits they share, when there is one, else inline.""" parts = [] if write_namespace is not None: uploader = NamespaceUploader(write_namespace) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/computer/driver.py b/packages/agentenv-protocol/src/agentenv_protocol/computer/driver.py index f9d22dc84..56c90549c 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/computer/driver.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/computer/driver.py @@ -21,9 +21,9 @@ control_check, environment_card, read_only_tools) from ..tool_context import ToolContext from ..types import EnvironmentCard, EnvironmentExtension, EnvironmentTool -from . import _linux, annotate, apps, card, svc +from . import _adb, _linux, annotate, apps, card, svc from .checks import check_features, check_names -from .dataplane import DataPlane +from .dataplane import DEFAULT_DATA_PATHS, DataPlane from .errors import TargetUnavailable from .extensions import Extensions from .operations import ReadyCheck, check_class, default_for @@ -63,6 +63,11 @@ class DriverDeclaration(BaseModel): platforms: list[DriverPlatform] settings: Optional[dict[str, Any]] = None + @property + def placement(self) -> str: + """Where the driver runs, as its card says: ``inside`` its computer, or ``beside`` a device it reaches.""" + return next((p.features["placement"] for p in self.platforms if "placement" in p.features), "inside") + class ComputerDriverEnvironment(Tools, Extensions, DataPlane, AgentEnvEnvironment): """Subclass it and mark the methods that capture and send input (see ``operations``); the class is checked when @@ -104,6 +109,11 @@ class ComputerDriverEnvironment(Tools, Extensions, DataPlane, AgentEnvEnvironmen #: What the computer's screen shows, its card's ``screen``: a ``desktop``, or a website browser's ``page``, its #: active tab. screen_kind: ClassVar[Literal["desktop", "page"]] = "desktop" + #: Where the driver runs, on its card: ``inside`` its computer as the session user, or ``beside`` a device it + #: reaches, such as a phone over adb, whose platform it passes to ``__init__``. + placement: ClassVar[Literal["inside", "beside"]] = "inside" + #: The folders under the session user's home that data/get returns when its caller names none, on the card. + default_data_paths: ClassVar[tuple[str, ...]] = DEFAULT_DATA_PATHS tool_access = True #: What the base class keeps for the driver, built by ``__init__``. _computer: ComputerRuntime | None = None @@ -300,7 +310,7 @@ def _computer_require_init(self) -> None: if self._computer is None: raise TypeError(f"{type(self).__qualname__}.__init__ must call super().__init__()") - # The defaults for the OS operations on Linux, macOS and Windows. + # The defaults for the OS operations on Linux, macOS and Windows, and from beside an Android device. @default_for("run_in_session", os=["linux", "macos", "windows"]) async def _computer_linux_run_in_session(self, argv: list, cwd: str | None, env: dict | None, timeout_s: float): @@ -310,6 +320,18 @@ async def _computer_linux_run_in_session(self, argv: list, cwd: str | None, env: async def _computer_linux_write_files(self, files: dict) -> None: await asyncio.to_thread(_linux.write_files, files) + @default_for("run_in_session", os="android") + async def _computer_android_run_in_session(self, argv: list, cwd: str | None, env: dict | None, timeout_s: float): + return await _adb.run_in_session(argv, cwd, env, timeout_s, output_bytes=self.settings.exec_output_bytes) + + @default_for("write_files", os="android") + async def _computer_android_write_files(self, files: dict) -> None: + await _adb.write_files(files) + + @default_for("read_files", os="android") + async def _computer_android_read_files(self, paths: list, into: Path) -> None: + await _adb.read_files(paths, into) + def computer_driver(name: str | None = None, *, supports: list | None = None) -> Callable: """Name a driver, its card's name unless ENVIRONMENT_NAME gives one, and declare the platforms it supports.""" diff --git a/packages/agentenv-protocol/src/agentenv_protocol/computer/operations.py b/packages/agentenv-protocol/src/agentenv_protocol/computer/operations.py index c0e119643..19b9630c9 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/computer/operations.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/computer/operations.py @@ -11,6 +11,7 @@ pointer_move(x, y), pointer_down(button), pointer_up(button), pointer_position() -> (x, y) key_down(keys), key_up(keys) run_in_session(argv, cwd, env, timeout_s) -> ExecResult write_files({path: bytes}) + read_files(paths, into) copies the files under paths into the local folder into record(hints) -> an async iterator of RecordedFrame or RecordedSegment, until it is closed The page group, for a driver whose screen is a website browser's active tab: @@ -37,7 +38,7 @@ "keyboard": ("key_down", "key_up"), "page": ("navigate", "history", "tabs", "dialog", "upload", "page_state"), } -OPTIONAL = ("set_display", "run_in_session", "write_files", "record") +OPTIONAL = ("set_display", "run_in_session", "write_files", "read_files", "record") INPUT = frozenset({"click", "drag", "scroll", "type_text", "press", "pointer_move", "pointer_down", "pointer_up", "key_down", "key_up", "navigate", "history", "tabs", "dialog", "upload"}) #: The input a page's open dialog blocks, which is refused while one is open there. @@ -173,6 +174,7 @@ def deco(f: Callable) -> Callable: page_state = _marker("page_state") run_in_session = _marker("run_in_session") write_files = _marker("write_files") +read_files = _marker("read_files") record = _marker("record") diff --git a/packages/agentenv-protocol/src/agentenv_protocol/computer/platform.py b/packages/agentenv-protocol/src/agentenv_protocol/computer/platform.py index 3b0f5d02b..95bbda03a 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/computer/platform.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/computer/platform.py @@ -16,7 +16,7 @@ #: The platform (``platform_key``) the computer's composer built an app for, which its server and install steps read in #: place of what /etc/os-release says, so they act on the install the image holds; unset outside a composed computer. PLATFORM_ENV = "AGENTENV_PLATFORM" -_OS = {"linux": "linux", "darwin": "macos", "win32": "windows"} +_OS = {"linux": "linux", "darwin": "macos", "win32": "windows", "android": "android"} @dataclass(frozen=True) diff --git a/packages/agentenv-protocol/src/agentenv_protocol/computer/recording.py b/packages/agentenv-protocol/src/agentenv_protocol/computer/recording.py index d3e7ec076..ee5aef0e3 100644 --- a/packages/agentenv-protocol/src/agentenv_protocol/computer/recording.py +++ b/packages/agentenv-protocol/src/agentenv_protocol/computer/recording.py @@ -29,6 +29,7 @@ from ..transfers import NamespaceUploader, WriteNamespaceGrant from . import annotate as annotating +from .dataplane import RECORDINGS_DIR from .errors import InvalidArgument, LimitExceeded, Unsupported from .frames import to_pil from .manifest import ManifestSegment, RecordingManifest @@ -37,8 +38,6 @@ from .runtime import ComputerRuntime MP4 = "video/mp4; codecs=avc1" -#: Where segments are written, relative to the session user's home, and kept when there is no grant. -RECORDINGS_DIR = ".agentenv-recordings" SCOPES = ("display", "window") REASONS = ("end", "reset", "teardown") #: What an ended recording's manifest is uploaded as, under its id beside its segments. diff --git a/packages/agentenv-protocol/tests/test_computer_beside.py b/packages/agentenv-protocol/tests/test_computer_beside.py new file mode 100644 index 000000000..07f4c3d0c --- /dev/null +++ b/packages/agentenv-protocol/tests/test_computer_beside.py @@ -0,0 +1,205 @@ +"""A driver beside an Android device: the base class's Android defaults go through adb under /sdcard, write atomically, +keep output under its cap, share one upload grant with the recordings kept in the driver's home, and fail rather than +look empty; and the probe reads a recording back through data/get, with no python3.""" +from __future__ import annotations + +import base64 +import hashlib +import json +import sys +import textwrap +from datetime import datetime, timedelta, timezone +from unittest.mock import AsyncMock, patch + +import pytest + +pytest.importorskip("mcp.server.fastmcp") +pytest.importorskip("PIL") + +from computer_fake import FakeDriver, http_client, rpc # noqa: E402 + +from agentenv_protocol import DATA_OBJECTS_EXTENSION_URI # noqa: E402 +from agentenv_protocol.computer import _adb # noqa: E402 +from agentenv_protocol.computer.conformance.checks import Probe # noqa: E402 +from agentenv_protocol.computer.errors import DeliveryFailed, InvalidArgument # noqa: E402 +from agentenv_protocol.computer.dataplane import RECORDINGS_DIR # noqa: E402 +from agentenv_protocol.computer.manifest import ManifestSegment # noqa: E402 +from agentenv_protocol.computer.platform import Platform # noqa: E402 + +ANDROID = Platform(os="android", arch="amd64", display="none") +FAKE_ADB = textwrap.dedent('''\ + import json, os, shutil, subprocess, sys + from pathlib import Path + device = Path(os.environ["FAKE_DEVICE"]) + args = sys.argv[1:] + if os.environ.get("FAKE_OFFLINE"): + print("error: device offline", file=sys.stderr); sys.exit(1) + with open(device.parent / "calls.jsonl", "a") as out: + out.write(json.dumps({"args": args, "serial": os.environ.get("ANDROID_SERIAL"), + "server": os.environ.get("ADB_SERVER_SOCKET")}) + "\\n") + def local(remote): + return device / Path(remote).relative_to("/sdcard") + if args[0] == "push" and os.environ.get("FAKE_PUSH_FAILS"): + local(args[2]).write_bytes(b"half"); print("error: connection reset", file=sys.stderr); sys.exit(1) + elif args[0] == "push": + shutil.copy(args[1], local(args[2])) + elif args[0] == "pull": + source = local(args[1]) + (shutil.copytree if source.is_dir() else shutil.copy)(source, Path(args[2]) / source.name) + elif args[0] == "shell" and not args[1].startswith("am broadcast"): + sys.exit(subprocess.run(["sh", "-c", args[1].replace("/sdcard", str(device))]).returncode) +''') + + +class BesideDriver(FakeDriver): + placement = "beside" + default_data_paths = ("Download", "DCIM") + + def __init__(self) -> None: + super().__init__(platform=ANDROID) + + +@pytest.fixture +def device(tmp_path, monkeypatch): + (tmp_path / "sdcard").mkdir() + adb = tmp_path / "fake-adb" + adb.write_text(f"#!{sys.executable}\n{FAKE_ADB}") + adb.chmod(0o755) + monkeypatch.setenv("AGENTENV_ADB", str(adb)) + monkeypatch.setenv("FAKE_DEVICE", str(tmp_path / "sdcard")) + monkeypatch.setenv("ANDROID_SERIAL", "emulator-5554") + monkeypatch.setenv("ADB_SERVER_SOCKET", "tcp:10.0.0.2:5037") + monkeypatch.setenv("HOME", str(tmp_path / "home")) + (tmp_path / "home").mkdir() + return tmp_path / "sdcard" + + +def _calls(device) -> list[dict]: + path = device.parent / "calls.jsonl" + return [json.loads(line) for line in path.read_text().splitlines()] if path.exists() else [] + + +def _part(path: str, data: bytes) -> dict: + return {"kind": "file", "file": {"bytes": base64.b64encode(data).decode()}, + "metadata": {DATA_OBJECTS_EXTENSION_URI: {"path": path}}} + + +@pytest.mark.asyncio +async def test_commands_and_files_go_through_adb_under_sdcard_and_recordings_stay_in_the_drivers_home(device): + kept = device.parent / "home" / RECORDINGS_DIR / "rec-1" + kept.mkdir(parents=True) + (kept / "0.mp4").write_bytes(b"mp4") + driver = BesideDriver() + async with http_client(driver) as http: + await http.post("/agentenv", json=rpc("data/add", {"parts": [_part("Download/f.csv", b"1,2")]})) + got = (await http.post("/agentenv", json=rpc("data/get", {"paths": ["Download", f"{RECORDINGS_DIR}/rec-1"]})) + ).json()["result"]["parts"] + card = (await http.get("/.well-known/agent-env.json")).json() + ran = await driver._computer.call("run_in_session", ["test", "-f", "f.csv"], "Download", None, 10) + + assert {p["metadata"][DATA_OBJECTS_EXTENSION_URI]["path"]: base64.b64decode(p["file"]["bytes"]) for p in got} == { + "Download/f.csv": b"1,2", f"{RECORDINGS_DIR}/rec-1/0.mp4": b"mp4"} + assert ran.exit_code == 0 + computer = {e["uri"]: e for e in card["capabilities"]["extensions"]}["urn:agentenv:computer/v1"]["params"] + assert (computer["placement"], computer["default_data_paths"]) == ("beside", ["Download", "DCIM"]) + calls = _calls(device) + assert [call["args"][0] for call in calls] == ["shell", "push", "shell", "shell", "shell", "pull", "shell"] + assert calls[1]["args"][2].startswith("/sdcard/Download/.agentenv-") and calls[1]["args"][2].endswith(".part") + assert calls[2]["args"][1] == f"mv -f {calls[1]['args'][2]} /sdcard/Download/f.csv" + assert calls[3]["args"][1].startswith("am broadcast -a android.intent.action.MEDIA_SCANNER_SCAN_FILE") + command = calls[-1]["args"][1] + assert command.startswith("cd /sdcard/Download ") and command.endswith("exec test -f f.csv") + assert {(call["serial"], call["server"]) for call in calls} == {("emulator-5554", "tcp:10.0.0.2:5037")} + + +class _ProbedDriver: + """What the probe sees of a beside driver: its card, and a data/get that answers one kept segment. It has no + computer-exec, so a probe that ran python3 on the device would fail.""" + + def __init__(self, data: bytes) -> None: + self.data = data + self.asked: list = [] + + def params(self, uri: str) -> dict: + return {"placement": "beside", "platform": ANDROID.as_dict()} + + async def rpc(self, method: str, params: dict | None = None) -> dict: + self.asked.append((method, params)) + path = params["paths"][0] + return {"result": {"parts": [{"kind": "file", "file": {"bytes": base64.b64encode(self.data).decode()}, + "metadata": {DATA_OBJECTS_EXTENSION_URI: {"path": path}}}]}} + + async def run(self, *argv: str, timeout_s: float = 30) -> dict: + raise AssertionError(f"the probe ran {argv} on a device with no python3") + + +@pytest.mark.asyncio +async def test_the_probe_reads_a_beside_drivers_recording_back_through_data_get_without_python3(): + data = b"segment bytes" + driver = _ProbedDriver(data) + probe = Probe(driver, session=None, ready_timeout_s=1) + segment = ManifestSegment(index=0, path="rec-1/0.mp4", bytes=len(data), sha256=hashlib.sha256(data).hexdigest(), + uploaded=False) + assert await probe._read_back(segment) == data + assert driver.asked == [("data/get", {"paths": [f"{RECORDINGS_DIR}/rec-1/0.mp4"]})] + wrong = segment.model_copy(update={"bytes": 99}) + assert "the manifest says 99" in await probe._read_back(wrong) + + +@pytest.mark.asyncio +async def test_a_commands_output_is_kept_only_up_to_the_cap(device): + result = await _adb.run_in_session(["sh", "-c", "head -c 100000 /dev/zero"], None, None, 10, output_bytes=100) + assert (len(result.stdout), result.truncated, result.exit_code) == (100, True, 0) + + +@pytest.mark.asyncio +async def test_device_files_and_recordings_upload_under_one_grants_limits(device): + (device / "Download").mkdir() + (device / "Download" / "f.csv").write_bytes(b"1,2") + kept = device.parent / "home" / RECORDINGS_DIR / "rec-1" + kept.mkdir(parents=True) + (kept / "0.mp4").write_bytes(b"mp4") + grant = {"root_path": "runs/1", "expires_at": (datetime.now(timezone.utc) + timedelta(hours=1)).isoformat(), + "max_objects": 5, "max_object_bytes": 100, "max_total_bytes": 500, + "write": {"kind": "http-post-policy", "url": "https://store.test/", "fields": {}, + "path_field": "key", "file_field": "file"}} + with patch("agentenv_protocol.computer.dataplane.NamespaceUploader") as uploader: + uploader.return_value.upload = AsyncMock() + async with http_client(BesideDriver()) as http: + await http.post("/agentenv", json=rpc("data/get", {"write_namespace": grant, + "paths": ["Download", f"{RECORDINGS_DIR}/rec-1"]})) + assert uploader.call_count == 1 + assert [call.args[0] for call in uploader.return_value.upload.await_args_list] == [ + "Download/f.csv", f"{RECORDINGS_DIR}/rec-1/0.mp4"] + + +@pytest.mark.asyncio +async def test_a_failed_push_leaves_the_old_file_whole_and_an_unreachable_device_fails_a_read(device, monkeypatch, + tmp_path): + (device / "Download").mkdir() + (device / "Download" / "f.csv").write_bytes(b"old") + monkeypatch.setenv("FAKE_PUSH_FAILS", "1") + with pytest.raises(DeliveryFailed, match="connection reset"): + await _adb.write_files({"Download/f.csv": b"new contents"}) + assert [p.name for p in (device / "Download").iterdir()] == ["f.csv"] + assert (device / "Download" / "f.csv").read_bytes() == b"old" + monkeypatch.setenv("FAKE_OFFLINE", "1") + with pytest.raises(DeliveryFailed, match="device offline"): + await _adb.read_files(["Download"], tmp_path) + + +@pytest.mark.asyncio +async def test_a_program_or_folder_that_isnt_there_is_refused_and_a_command_failing_is_a_result(device): + run = _adb.run_in_session + with pytest.raises(InvalidArgument, match="not found on the device"): + await run(["agentenv-probe-no-such-program"], None, None, 10, output_bytes=100) + with pytest.raises(InvalidArgument, match="no such folder"): + await run(["true"], "Nowhere", None, 10, output_bytes=100) + failed = await run(["sh", "-c", 'printf "$B"; exit 127'], None, {"A;touch x": "y", "B": "it's"}, 10, + output_bytes=100) + assert (failed.exit_code, failed.stdout) == (127, b"it's") and not (device / "x").exists() + (device / "bin").mkdir() + (device / "bin" / "agentenv-hello").write_text("#!/bin/sh\necho hello\n") + (device / "bin" / "agentenv-hello").chmod(0o755) + found = await run(["agentenv-hello"], None, {"PATH": "/sdcard/bin:/usr/bin:/bin"}, 10, output_bytes=100) + assert found.stdout == b"hello\n" diff --git a/packages/agentenv-protocol/tests/test_computer_driver.py b/packages/agentenv-protocol/tests/test_computer_driver.py index 680c738f3..2ddea9e75 100644 --- a/packages/agentenv-protocol/tests/test_computer_driver.py +++ b/packages/agentenv-protocol/tests/test_computer_driver.py @@ -119,6 +119,7 @@ def test_unknown_predicates_are_refused(): ({"keys": ("Return",)}, "keys: 'Return' is not a W3C key value"), ({"display_modes": ((10, 10),)}, "display_modes and @set_display come together"), ({"screen_kind": "tablet"}, "screen_kind is desktop or page, got 'tablet'"), + ({"placement": "provider"}, "placement provider, a driver its device's provider serves, isn't supported yet"), ({"screenshot_delay_ms": -1}, "screenshot_delay_ms is an integer from 0 to 10000, got -1"), ({"screenshot_delay_ms": 0.5}, "screenshot_delay_ms is an integer from 0 to 10000, got 0.5"), ]) @@ -132,11 +133,12 @@ def test_set_display_without_modes_is_refused(): _define({"resize": set_display(lambda self, w, h, s: None)}) -def test_a_driver_method_replaces_the_linux_default(): +def test_a_driver_method_replaces_the_os_defaults(): Driver = _define({"run": run_in_session(lambda self, *a: None)}) assert declared(Driver)["run_in_session"] == [("run", {})] - assert declared(MinimalDriver)["run_in_session"] == [("_computer_linux_run_in_session", - {"os": frozenset({"linux", "macos", "windows"})})] + assert sorted(declared(MinimalDriver)["run_in_session"]) == [ + ("_computer_android_run_in_session", {"os": frozenset({"android"})}), + ("_computer_linux_run_in_session", {"os": frozenset({"linux", "macos", "windows"})})] def test_the_platform_is_detected(tmp_path, monkeypatch): diff --git a/src/agent_env/env/envs/computer/driver_env.py b/src/agent_env/env/envs/computer/driver_env.py index 3e6b8ecab..579778fa9 100644 --- a/src/agent_env/env/envs/computer/driver_env.py +++ b/src/agent_env/env/envs/computer/driver_env.py @@ -30,6 +30,8 @@ #: The port the SDK serves a driver on when MCP_PORT doesn't name one. DEFAULT_PORT = 18765 MAX_PORT = 65535 +#: Where a driver runs: composed ``inside`` its computer, or ``beside`` the device it reaches. +PLACEMENTS = ("inside", "beside") class KnownFailure(BaseModel): @@ -50,7 +52,7 @@ class ComputerDriverEnv(Env): def __init__(self, id: str, version: Optional[int], module: str, files: FileArtifactUniverse, declaration: DriverDeclaration, install: Optional[dict[str, Install]] = None, port: int = DEFAULT_PORT, metadata: Optional[dict[str, Any]] = None, - known_failures: Optional[dict[str, list[KnownFailure]]] = None): + known_failures: Optional[dict[str, list[KnownFailure]]] = None, placement: str = "inside"): super().__init__(id, version, metadata=metadata) self.module = module self.files = files @@ -58,13 +60,14 @@ def __init__(self, id: str, version: Optional[int], module: str, files: FileArti self.install = install or {} self.port = port self.known_failures = known_failures or {} + self.placement = placement def to_dict(self) -> dict: return {**super().to_dict(), "module": self.module, "declaration": self.declaration.model_dump(mode="json", exclude_none=True), "files": {"id": self.files.id, "version": self.files.version, "type": self.files.type}, "install": {os_type: install.model_dump(exclude_none=True) for os_type, install in self.install.items()}, - "port": self.port, + "port": self.port, **({"placement": self.placement} if self.placement != "inside" else {}), **({"known_failures": {os_type: [failure.model_dump() for failure in failures] for os_type, failures in self.known_failures.items()}} if self.known_failures else {})} @@ -77,20 +80,25 @@ def from_dict(cls, data: dict) -> ComputerDriverEnv: return cls(id=data["id"], version=data.get("version"), module=data["module"], files=files, declaration=DriverDeclaration.model_validate(data["declaration"]), install=install, port=data.get("port", DEFAULT_PORT), metadata=data.get("metadata") or {}, - known_failures=_known_failures(data.get("known_failures") or {})[0]) + known_failures=_known_failures(data.get("known_failures") or {})[0], + placement=data.get("placement", "inside")) @classmethod def from_toml(cls, data: dict, ctx: AuthoringContext) -> ComputerDriverEnv: """The driver's class is read in a process of its own (``declared``).""" fields = cls.accept_toml(data, ctx) declaration = DriverDeclaration.model_validate(declared(ctx, fields["module"], cls.type)) - if problems := [*unsupported(fields["install"], declaration.supports, "install"), - *unsupported(fields.get("known_failures") or {}, declaration.supports, "known_failures")]: + placement = fields.get("placement", "inside") + problems = [*unsupported(fields["install"], declaration.supports, "install"), + *unsupported(fields.get("known_failures") or {}, declaration.supports, "known_failures")] + if placement != declaration.placement: + problems.append(f"placement is {placement!r}, but the driver's class says {declaration.placement!r}") + if problems: ctx.refuse(list(map(ctx.config_problem, problems))) universe = FileArtifactUniverse.put_bundled(derive_id(ctx.id, "files"), files=ctx.files()) return cls.put(id=ctx.id, module=fields["module"], files=universe, declaration=declaration, install=fields["install"], port=fields.get("port", DEFAULT_PORT), - known_failures=fields.get("known_failures")) + known_failures=fields.get("known_failures"), placement=placement) def to_toml(self, out: ExportContext) -> dict: """The env.toml of a folder holding the driver's files, which ``from_toml`` reads back as it.""" @@ -98,6 +106,8 @@ def to_toml(self, out: ExportContext) -> dict: toml = {"type": self.type, "module": self.module} if self.port != DEFAULT_PORT: toml["port"] = self.port + if self.placement != "inside": + toml["placement"] = self.placement if self.install: toml["install"] = {key: install.model_dump(mode="json", exclude_none=True, exclude_defaults=True) for key, install in self.install.items()} @@ -109,11 +119,12 @@ def to_toml(self, out: ExportContext) -> dict: @classmethod def accept_toml(cls, data: dict, ctx: AuthoringContext) -> dict: """The keys of ``data``, an env.toml, a computer driver env takes: ``module = ":"``, naming a file - of its folder; ``port``, where it serves; ``install``, by OS type, whose files and requirements are in its + of its folder; ``port``, where it serves; ``placement``, ``inside`` its computer (the default) or ``beside`` the + device it reaches, as its class says too; ``install``, by OS type, whose files and requirements are in its folder; and ``known_failures``, by OS type, the probe checks it fails there. An install or known failures for a distribution, ``/``, replace its OS type's there. Raises BundleError listing every problem.""" - fields, refused = ctx.accepted(data, module=str, port=int, install=dict, known_failures=dict) + fields, refused = ctx.accepted(data, module=str, port=int, placement=str, install=dict, known_failures=dict) files = ctx.files() module, problems = fields.get("module"), [] if module is None and "module" not in data: @@ -123,6 +134,11 @@ def accept_toml(cls, data: dict, ctx: AuthoringContext) -> dict: f"{', '.join(sorted(files))}") if not 1 <= fields.get("port", DEFAULT_PORT) <= MAX_PORT: problems.append(f"port must be 1 to {MAX_PORT}, not {fields['port']}") + if fields.get("placement") == "provider": + problems.append("placement provider, a driver its device's provider serves, isn't supported yet: use " + "inside or beside") + elif fields.get("placement", "inside") not in PLACEMENTS: + problems.append(f"placement is one of {list(PLACEMENTS)}, not {fields['placement']!r}") fields["known_failures"], unknown = _known_failures(fields.get("known_failures", {})) problems += unknown fields["install"], invalid = installs(fields.get("install", {})) diff --git a/src/agent_env/env/envs/computer/env.py b/src/agent_env/env/envs/computer/env.py index dd79b4c67..e9e93c303 100644 --- a/src/agent_env/env/envs/computer/env.py +++ b/src/agent_env/env/envs/computer/env.py @@ -58,6 +58,8 @@ #: Where load_artifact puts files in a computer by default: one of the folders data/get returns by default. DEFAULT_DESTINATION = "Downloads" +#: The default destination on an OS whose downloads folder is named otherwise. +DEFAULT_DESTINATIONS = {"android": "Download"} #: The computer app env's type: an app composed into a computer env, and a computer env of its own. APP_TYPE = "computer_app" #: The statuses of a build a deploy boots, by form: a disk may also boot unprobed, as KVM is where a disk is probed, and @@ -393,12 +395,13 @@ async def from_deployed_env(cls, deployed: DeployedEnv) -> ComputerEnv: async def load_file_artifact_universe(self, file_artifact_universe: Any, destination_path: Optional[str] = None) -> LoadFileArtifactUniverseResult: """Write each file of ``file_artifact_universe`` under ``destination_path``, a folder relative to the session - user's home (``Downloads`` by default), through the driver's ``data/add``, as that user; the result's paths are - relative to the home too, since the home's path differs by OS.""" + user's home (``Downloads`` by default, on Android ``Download``), through the driver's ``data/add``, as that + user; the result's paths are relative to the home too, since the home's path differs by OS.""" if destination_path is not None and posixpath.isabs(destination_path): raise ValueError(f"{self.id}: a computer's destination_path is relative to its session user's home, not " f"{destination_path!r}") - destination = posixpath.normpath(destination_path or DEFAULT_DESTINATION) + destination = posixpath.normpath(destination_path or DEFAULT_DESTINATIONS.get(self.computer.os.type, + DEFAULT_DESTINATION)) validate_relative_filename(destination) files = file_artifact_universe.get_file_artifacts() for filename in files: diff --git a/tst/unit/bundle/computer_driver_env_test.py b/tst/unit/bundle/computer_driver_env_test.py index 2b3eac873..d26fe998c 100644 --- a/tst/unit/bundle/computer_driver_env_test.py +++ b/tst/unit/bundle/computer_driver_env_test.py @@ -186,10 +186,14 @@ def test_a_driver_is_written_again_only_when_one_of_its_files_changes(bundle_dir "install.linux/omarchy: no supports entry names 'omarchy' on linux, so this never applies"), (f'{TOML}[[known_failures."linux/omarchy"]]\ncheck = "P6"\nname = "typed text"\nreason = "its plugin"\n', LINUX, ("left",), "known_failures.linux/omarchy: no supports entry names 'omarchy' on linux, so this never applies"), + (f'{TOML}placement = "provider"\n', LINUX, ("left",), + "placement provider, a driver its device's provider serves, isn't supported yet: use inside or beside"), + (f'{TOML}placement = "beside"\n', LINUX, ("left",), + "placement is 'beside', but the driver's class says 'inside'"), ], ids=["no-module", "module-file", "module-class", "button", "no-platform", "unknown-key", "port", "install-os", "install-python", "install-files", "install-escape", "no-service", "service-twice", "service-scope", "run-missing", "apt-word", "sources-alone", "download-sha", "install-port", "distribution-key", - "unsupported-distribution", "unsupported-known-failures"]) + "unsupported-distribution", "unsupported-known-failures", "placement-provider", "placement-disagrees"]) def test_a_driver_its_class_cant_be_read_from_is_refused_before_any_write(bundle_dir, toml, supports, buttons, problem): _bundle(bundle_dir, toml=toml, supports=supports, buttons=buttons) @@ -199,6 +203,24 @@ def test_a_driver_its_class_cant_be_read_from_is_refused_before_any_write(bundle Env.get(f"{ROOT}/desk") +def _beside() -> str: + return DRIVER.format(supports=ANDROID, buttons=("left",)).replace(" buttons = ", + ' placement = "beside"\n buttons = ') + + +ANDROID = [{"os": {"type": "android", "display": ["none"]}, "arch": ["amd64"]}] + + +def test_a_driver_beside_its_device_is_written_saying_so_and_its_card_echoes_it(bundle_dir): + _bundle(bundle_dir, toml=f'{TOML}placement = "beside"\n', supports=ANDROID, **{"envs/desk/driver.py": _beside()}) + + _run(bundle_dir) + env = Env.get(f"{ROOT}/desk") + + assert env.placement == "beside" and env.declaration.platforms[0].features["placement"] == "beside" + assert ComputerDriverEnv.from_dict(env.to_dict()).placement == "beside" + + def test_a_driver_takes_an_install_and_known_failures_for_a_distribution_it_supports(bundle_dir): omarchy = [{"os": {"type": "linux", "display": ["x11"]}, "arch": ["amd64", "arm64"]}, {"os": {"type": "linux", "distribution": "omarchy", "display": ["wayland"]}, "arch": ["amd64"]}]