feat(mobile): add photos and videos to the library with device.addMedia (ENG-1061)

Draft
KD
10h ago
+825-43

What

device.addMedia(paths) adds photos and videos to the device's library, so a test can pick them in the system photo picker:

test('attaches the receipt from the photo library', async ({ app, device, screen }) => {
  await device.addMedia('tests/fixtures/receipt.jpg');
  await app.open();
  await screen.getByLabel('Choose photo').tap();
  await screen.getByRole('image', /^Photo, /).first().tap();
  await expect(screen.getByText(/^Receipt attached/)).toBeVisible();
});

It works on an iOS simulator, an Android emulator, and an Android phone on this machine's adb. The two platforms differ when the same file is added again:

  • iOS adds a copy on every call. simctl addmedia has no way to replace or skip a photo, so a suite that calls it on every run grows the library. Identical copies are harmless to a locator (.first() takes the newest), but an agent step cannot tell them apart. This is left to the suite, as before, and documented.
  • Android replaces a file of the same name from an earlier call. The file goes to /sdcard/Pictures/<name>, so a rerun overwrites the earlier copy instead of adding one. Within one call, two names that differ at most in case are INVALID_ARGUMENT (the storage ignores case, so the second would silently replace the first), and so is a name starting with a dot (the media scanner hides it).

A physical iPhone, a device a provider leased, and a device behind a remote agent-device daemon are UNSUPPORTED_CAPABILITY, before anything runs.

Why

ENG-1061: tests of the iOS PHPicker had no way to put a photo in the library, so suites shelled out to xcrun simctl addmedia with the simulator's UDID from device.unstable_raw (the docs' own sample and the mobile benchmark did), and Android had no answer at all. The migrate-to-e2e skill listed Maestro's addMedia as a gap and asked agents to send feedback about it, which brought a second report.

The issue's other half, driving the picker itself, already works on main: the picker's photos are in the screen tree as image "Photo, <date>". This PR changes nothing there.

How it works

agent-device (0.21.43 and the 0.22 nightly) has no media command, so the engine runs the platform's own tool on this machine.

  1. device.addMedia is a device.<method> step labeled with the file names only, never their directories (packages/mobile/src/device.ts:404, label at :275). It passes the phase signal and config.actionTimeout to the surface. init keeps what agent-device booted the device as (simulator, emulator, device) (packages/mobile/src/surface.ts:701).
  2. AgentDeviceSurface.addMedia (surface.ts:1968) starts its timeout budget with the call, so time spent checking files counts too, then checks before anything runs:
    • mediaFiles (packages/mobile/src/media.ts:72): one or more non-empty paths, holes in an array included, else INVALID_ARGUMENT.
    • mediaRefusal (:115): UNSUPPORTED_CAPABILITY for a slot with another daemon, a provider lease, or provider client config; for AGENT_DEVICE_DAEMON_BASE_URL; for a physical iPhone, whose library no tool writes.
    • assertMediaFiles (:88): each path is a readable file, and the Android name rules from What. It returns the file sizes for step 5.
  3. The programs run with the runner process's environment, process.env, not the run's: the agent-device client lives in that process and so does the daemon it starts, so adb reaches the same adb server (ANDROID_ADB_SERVER_PORT). findAdb (:218) picks the adb agent-device would: platform-tools/adb under ANDROID_SDK_ROOT, ANDROID_HOME, the macOS default SDK, or ~/Android/Sdk, else adb on PATH.
  4. mediaCommands (:149) builds the programs. iOS: one xcrun simctl addmedia <udid> <files...>, with --set <path> when AGENT_DEVICE_IOS_SIMULATOR_DEVICE_SET names the simulator set agent-device keeps its devices in. Android, per file: adb -s <serial> push <file> /sdcard/Pictures/<name>, then a MEDIA_SCANNER_SCAN_FILE broadcast for it. The broadcast URI is percent-encoded and single-quoted, since adb shell hands it to the device's shell. The scan is sent on every version: Android 10 and earlier index only what is scanned, and a reviewer saw API 36 skip a case-only replacement and a name with : or ? until it.
  5. Android: am broadcast returns before the scan finishes, so the step then polls the media index every 250 ms (surface.ts:1991) with androidIndexQuery (media.ts:176), a content query for photos and videos (media_type IN (1, 3)) under a Pictures directory, with a fixed where clause and no file name in the device's shell. unindexedFiles (:197) takes a file as indexed only from a row at /storage/emulated/<user>/Pictures/<name>, name compared ignoring case, whose _size equals the local file's: a same-named file in another album or volume, or the old row of a replaced file, does not end the wait.
  6. runHostCommand (:49) runs each program through execFile, no shell. On an abort it sends SIGKILL itself and settles once the child has exited: execFile's own signal option sends SIGTERM whatever killSignal says (seen on Node 26), so a program that catches it kept working. No program starts once the budget has run out.
  7. hostCommandError (:239) maps the step's own abort to CANCELLED, the timeout to OPERATION_TIMEOUT (which the runner reports to the test as ACTION_FAILED, like every device step past actionTimeout), and a missing program or a failure to ENGINE_FAILURE with its stderr. Stderr over 2,000 characters is left out whole rather than cut, because the runner redacts whole secret values only, and the child-process error is not kept as the cause: its cmd and stderr fields are not redacted.
  8. Docs: the picker sample in docs/mobile.mdx uses addMedia in place of the 20-line marker-file helper, and "What doesn't work on a phone" says it refuses an iPhone with its own error. The reference page gets the entry with its error table. The Maestro and TesterArmy guides move addMedia from Planned to their mapping tables, the Appium guide's pushFile row points photos at it, the Revyl page lists it among the methods its leases refuse, and skills/e2e lists the method. The migrate-to-e2e skill's example gap becomes --device-locale, which is still missing.

The mobile benchmark's Photo Picker scenario is unchanged: it seeds in a prepare step outside any test, and turning it on for Android needs new recordings.

Issue

ENG-1061

Verified

Ran it locally: yes, on an iPhone 18 Pro simulator and API 36 emulators, through the built CLI in a scratch project that imports the built e2e and @e2e-dev/mobile. The test calls device.addMedia('tests/receipt-e2e.png'), then on iOS opens Photos and expects an image "사진, <date>" (the simulator's language is Korean). A second test passes a missing file and expects INVALID_ARGUMENT.

$ node node_modules/e2e/dist/cli/bin.js run --target ios          # at 76b72d4
   ✓ |ios| tests/add-media.e2e.ts > adds a photo to the library 4.31s
   ✓ |ios| tests/add-media.e2e.ts > refuses a missing file 2ms
      Tests  2 passed (2)
# the simulator's DCIM went from 14 to 15 files

$ adb -s emulator-5590 shell content query ...                    # a fresh AVD, before
No result found.
$ node node_modules/e2e/dist/cli/bin.js run --target android      # at 7f4955f, with the index wait
   ✓ |android| tests/add-media.e2e.ts > adds a photo to the library 2.16s
   ✓ |android| tests/add-media.e2e.ts > refuses a missing file 7ms
      Tests  2 passed (2)
$ adb -s emulator-5590 shell content query --uri content://media/external/file --projection _data --where "\"_data LIKE '%/Pictures/%'\""
Row: 0 _data=/storage/emulated/0/Pictures/receipt-e2e.png
iOS Photos after addMedia (the test icon copies)Android system photo picker after addMedia
iOS PhotosAndroid photo picker

The last commits were not run end to end on a device: by then other sessions on this machine had claimed both the simulator and the emulator for their own benchmark runs. What they change was checked this way instead:

  • The head's index query and parser against real API 36 output: the query with media_type IN (1, 3) left a pushed .txt out (the same query without it listed the file), and unindexedFiles accepted receipt-e2e.png with its real size and kept waiting on a wrong size.
  • The rewritten runHostCommand against real xcrun: it returned simctl list's stdout and, for an unknown UDID, the stderr Invalid device: ..., so no device changed.
  • packages/mobile/tests/unit/media.test.ts (20 tests): the refusals, the name rules, the iOS --set form, the timeout and cancellation paths, the index wait (a lagging index, another album or volume, a stale size, a case-changed row), and a real child that ignores SIGTERM, which fails the test if the runner sends SIGTERM.

Not run live: the refusals for a provider lease, another daemon, and a physical iPhone, and Android 10 or earlier (only API 36 images are installed here).

No pnpm bench:ab table: the change adds a method and touches no existing engine path (init only stores one more field), and the mobile benchmark's app is not installed on this machine. CI's microbenchmarks reported no case moving by 0.5% or more.

Three rounds of four independent reviewers (Codex gpt-6.2-astra and gpt-6.2-sol, Claude Opus 5.5 and Sonnet 5.5) raised 20 findings, all applied, each commit on its own. The last round was not clean: it raised seven findings, all now fixed, and its fixes have not been reviewed again.

🤖 Generated with Claude Code