Add white paper source
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369# EspressoGym
## Turning open-source UI tests into reinforcement-learning environments
Status: Concept and validation white paper Last updated: 2026-10-15
Despite the name, EspressoGym is not limited to tests written with Android'sEspresso framework. The name communicates the core operation: take existingAndroid UI tests and mint them into executable reinforcement-learningenvironments. Espresso, Compose UI tests, UI Automator, and other supported testframeworks are source material for the same environment-production pipeline.
## Why this matters
Training better mobile-control agents does not primarily require another actiongrammar or another emulator wrapper. It requires many more environments in whichan agent can act, make mistakes, recover, and receive trustworthy feedback.
Today, those environments are expensive to create by hand. Meanwhile,open-source Android projects already contain thousands of UI tests whose authorshave implemented realistic setup, exercised useful workflows, and writtenexecutable definitions of success. EspressoGym is an attempt to turn thatdistributed work into reusable training infrastructure.
## 1. Goal
Build the largest practical collection of **reproducible, executable Androidtraining environments with source-backed success signals**.
Each environment should provide:
- a natural-language goal;- a real Android app in a known initial state;- freedom for an external agent to interact using any control scheme;- executable checkpoints derived from the app's existing assertions;- clean reset and teardown behavior;- a known-good trajectory for qualification and health checks;- pinned source, artifacts, licenses, and build provenance.
EspressoGym is not intended to define the model loop, observation format, actiongrammar, optimizer, or reward function. It supplies the environment and rawevidence. A training system decides how to act, score, and stop.
The desired result is not merely a larger benchmark. It is a corpus that canproduce new rollouts for reinforcement learning, including off-path behavior andrecovery, instead of only replaying prerecorded demonstrations.
## 2. Problem
### 2.1 Interactive environments are the scarce resource
An emulator and a tap API are generic. A useful task is not. Every task alsoneeds a valid starting state, a meaningful goal, reliable success conditions,cleanup, and a way to distinguish ordinary failure from a broken environment.
That task-specific work is why executable mobile benchmarks remain much smallerthan offline trajectory datasets.
Offline demonstrations are valuable for imitation learning, but they cannot tellan agent what happens after a novel action. They do not naturally supportexploration, recovery, or repeated checkpoint evaluation. Hand-authored onlinetasks solve those problems, but they are costly to scale.
### 2.2 Existing projects solve adjacent problems
The relevant prior art spans three different products: general Android-controlinfrastructure, offline training data, and manually authored online benchmarks.Each establishes an important part of the solution, but none provides a scalableenvironment-production pipeline from existing application tests.
| Project | What it establishes | Why it does not close this gap || --- | --- | --- || [AndroidEnv](https://github.com/google-deepmind/android_env) | A reusable RL interface, simulator integration, observations, actions, and task/reward APIs. | It makes Android tasks runnable but does not manufacture them. Goals, initial state, event/reward definitions, and task-specific cleanup still have to be authored. || [AndroidControl](https://github.com/google-research/google-research/tree/master/android_control) | More than 15,000 human demonstrations across 833 apps: strong evidence that broad mobile-control data improves training and transfer. | It is an offline trajectory dataset. A learner cannot take a novel action, observe its consequence, recover, or query a live success condition. || [AndroidWorld](https://github.com/google-research/android_world) | A reproducible emulator environment with durable programmatic rewards for 116 task templates across 20 apps. | The task implementations are hand-authored. Randomized names, dates, and values create useful instances, but not new semantic workflows; the reusable semantic task count remains 116. || [MobileAgentBench](https://arxiv.org/abs/2406.08184) | Automated evaluation of 100 tasks across 10 open-source apps with several difficulty levels and agent integrations. | It is a carefully curated benchmark, not a system for converting the much larger body of existing app tests into environments. || [SPA-Bench](https://github.com/ai-agents-2030/SPA-Bench) | 340 bilingual tasks across 66 system and third-party apps, including cross-app tasks, agent integrations, automated metrics, and Android snapshots. | It broadens evaluation substantially, but tasks and validators remain curated benchmark assets. Third-party production dependencies are not source-backed, and it does not provide an ecosystem-scale environment-generation path. || [MobileBench-OL](https://aclanthology.org/2026.findings-acl.668/) | 1,080 manually created tasks across 80 Chinese apps, executed on physical devices with trajectory rules, golden paths, noise injection, and automated reset workflows. | The apps are predominantly proprietary and use their live production backends. The authors used three phones with real verified accounts; success is inferred from UI/action traces, and reset is another UI task rather than restoration of app and server state. This is impressive live evaluation coverage, but not a hermetic high-volume RL corpus. || [MobileWorld](https://tongyi-mai.github.io/MobileWorld/) | The closest architectural prior art: 201 tasks across 20 apps in a containerized Android environment with open-source applications, self-hosted backends, snapshots, database inspection, local-state checks, and deterministic evaluation. | Its environments and integrations are deliberately engineered app by app and its tasks are still authored for the benchmark. It demonstrates that hermetic backend-aware mobile environments work; it does not solve how to manufacture thousands of them from work already present in open-source repositories. |
MobileBench-OL deserves particular clarification because its headline scale soundssimilar to EspressoGym's goal. It does not provide 1,080 self-contained backends. Itsapps talk to their normal production services under real network conditions.Annotators wrote tasks and golden trajectories from scratch; experts then createdXPath-like success rules over UI elements and critical actions. After evaluation,an agent follows manually written inverse instructions such as disabling a settingor clearing search history. Some tasks are explicitly considered infeasible toreset and receive alternative success handling. The released APKs pin clientversions, but they do not make the proprietary applications or their backends opensource, immutable, or locally reproducible.
MobileWorld, conversely, proves that the stronger environment model is possible:containerized Android, controlled open-source services, inspectable databases, andsnapshot restoration. Its limitation is economic rather than conceptual—twentyapps and 201 tasks required purpose-built environment engineering.
The remaining gap is therefore a **manufacturing problem**. We need a repeatableway to discover, transform, validate, package, and maintain source-verifiableinteractive environments without manually implementing every task and backend.EspressoGym's claim is that open-source UI tests contain enough of that missingwork to make the process scalable.
### 2.3 UI tests are promising, but not environments yet
An existing UI test usually runs setup, performs a fixed action sequence, checksassertions, and exits. An RL agent instead needs the test to pause after setup,remain alive while an external controller acts, evaluate relevant assertionsafter steps, and cleanly end only when the caller chooses.
Real repositories add further complications:
- old commits and dependencies may no longer build;- setup, actions, assertions, and cleanup may be interleaved;- assertions may depend on local variables, fakes, rules, or custom runners;- some tests use tiny mocks that do not represent a useful app workflow;- tests may accidentally depend on execution order or shared state;- leaving the scripted path may crash, dead-end, or corrupt later episodes;- several tests may represent the same semantic task with different values.
The problem is therefore not extracting text from test files. It is producing aqualified, resettable environment without changing what the original test means.
## 3. Solution
### 3.1 Core bet
The project rests on six claims:
1. Open-source maintainers have already paid much of the semantic authoring cost in their ordinary UI tests.2. A capable model can identify task intent, the agent-control boundary, and meaningful checkpoint boundaries.3. Once those labels exist, deterministic code generation can transform the test; an LLM does not need to synthesize or repair evaluator code.4. The original test, known-good replay, negative controls, mutations, and reset checks can mechanically reject unsafe conversions.5. Apps and generated test harnesses can be compiled once and distributed as versioned bundles rather than rebuilt during training.6. Labels describe semantic boundaries, not a particular model or controller, so runtime improvements require regeneration rather than relabeling.
If these claims hold, the marginal cost of a new environment becomes repositoryqualification, limited labeling inference, compilation, and deterministicvalidation—not a human writing another environment and reward function by hand.
### 3.2 Authoring model
The original UI test remains a normal test. Existing setup, actions, andassertions are not replaced with an EspressoGym DSL. Labeling adds only a caseannotation and semantic markers:
```kotlin@TrainerCase("contacts.create-contact")@Testfun createContact() { val contacts = FakeContacts() launchContacts(contacts)
Trainer.start()
onView(withId(R.id.add)).perform(click()) onView(withId(R.id.name)).perform(typeText("Ada")) onView(withId(R.id.save)).perform(click())
Trainer.checkpoint("contact-created") onView(withText("Ada")).check(matches(isDisplayed())) assertThat(contacts.savedNames).contains("Ada")}```
In normal CI, `Trainer.start()` and `Trainer.checkpoint()` are no-ops and the testruns as originally written. For dataset production, a deterministic generatoruses the markers to create a persistent episode implementation. The lastcheckpoint is the terminal goal checkpoint; earlier checkpoints may provideuseful progress evidence.
This keeps assertions in ordinary test code, retains IDE navigation, and makesthe source auditable by Android developers who know nothing about the trainingharness.
### 3.3 Runtime contract
The training harness controls the emulator directly and calls a small environmentSDK around its own action loop:
```pythonenv = RLEnvironment(config_path=case_path, serial=serial)
goal = env.goalenv.start()
while harness.should_continue: harness.observe_and_act(serial, goal) result = env.step_ended() harness.record_and_score(result)
env.end(reason="caller_finished")```
`start()` resets device state and runs the original test fixture and setup.`step_ended()` synchronously runs whichever checkpoints are due and returns rawobservations. `end()` performs final checks and unwinds the original cleanuplifecycle.
The environment never assumes how the caller produced an action. It can be usedwith ADB, accessibility, UI Automator, coordinates, a learned action grammar, ora human. Likewise, a terminal checkpoint passing does not force the episode toend. The caller owns reward and stopping policy.
### 3.4 Checkpoints and partial credit
Each checkpoint has a stable ID, description, suggested score, and executionpolicy. Policies can evaluate a checkpoint after every step, every N steps, ondemand, or only when the episode ends. Passed checks may latch to avoid repeatedcost.
The runtime reports raw states such as `PASSED`, `FAILED`, `NOT_OBSERVABLE`, and`ERROR`. A failed assertion is normal evidence that the agent has not yet reachedthat state. An assertion infrastructure error, app crash, test-process death, ortransport failure is environment health data—not task failure disguised as azero reward.
This separation lets researchers experiment with sparse terminal reward, shapedreward, regression penalties, or custom scoring without rebuilding the APKs.
### 3.5 Deterministic production pipeline
The intended dataset workflow is:
```textcataloged repository and pinned revision -> build qualification and permitted build-system repair -> model proposes goal, start marker, checkpoints, and config -> validators ensure existing app/test logic was not changed -> deterministic episode and golden-trace generation -> app APK and EspressoGym test APK compilation -> original-test, replay, reset, negative, and mutation qualification -> content-addressed project bundle -> balanced dataset shard and release catalog```
The labeling agent may make several attempts to get a repository building and toproduce valid labels. It may update build configuration and dependencies, but itmust not rewrite application behavior or existing test actions and assertions.Accepted changes are committed automatically only after mechanical guards andbuild checks pass. Cases that cannot be converted safely are recorded with areason rather than silently repaired.
The released bundle contains precompiled APKs, the case configuration, generatedepisode mapping, checkpoint metadata, golden trace, qualification receipts,licenses, hashes, and provenance. Bundles are grouped into balanced shards so oneemulator can run an installed app while another shard or app is downloaded andprepared.
### 3.6 Generated qualification, not model review
Each labeled case produces a small deterministic validation suite:
- replay the original actions as the golden trajectory and require success;- run no actions and require that terminal success is absent;- truncate or mutate the trajectory and ensure ordinary mistakes do not break the harness;- inject a recoverable detour and return to the golden path;- reset and replay the golden trajectory again to prove state isolation;- run cases alone, repeatedly, and in shuffled order to detect dependencies.
This suite tests both the environment and its prerecorded trajectory. It does notprove that a model can recover—that requires training—but it can prove that commonwrong actions remain bounded and do not poison the next rollout.
### 3.7 Probe evidence and potential scale
The current static census found:
| Funnel stage | Cases | Projects || --- | ---: | ---: || Recognized UI interaction | 6,620 | 424 || Device-capable after excluding Robolectric-only tests | 5,910 | 391 || Strict action-plus-assertion candidates | 5,002 | 346 |
The 710 Robolectric-only or local-shadow cases removed at the device-capable stageare not part of the headline pool or yield forecast. They do not expose a realdevice UI for a mobile-control agent. Projects that also contain genuineinstrumentation or device tests remain eligible through those tests.
These are candidates, not finished environments. Static analysis establishes thattests perform UI actions and contain assertions; it does not prove that the pinnedcommit builds, the task is meaningful, or the environment tolerates off-pathbehavior.
The candidate pool is also unevenly distributed. The median UI project contributesfive cases, the top 10% contributes 60.3%, and inverse-HHI gives an effectiveproject count of 59.8. Final releases must report raw cases, each project'scontribution, and semantic clusters rather than inflate diversity with repeatedvalues. EspressoGym publishes qualified environments without imposing a per-appcap; downstream users control sampling and balancing.
An initial 50-project execution probe selected 22 tests that ran, of which 15passed. The sample was small and non-random. More importantly, the failure auditfound that 22 of the 28 projects without a test result were blocked by first-passrunner defects or missing host tooling; only six required project-specific repair.A separate source-feasibility sample classified 37 of 43 device cases as directlypollable or segmentable, with six harder continuation cases. A selected labelerpilot converted 10 of 11 attempted cases into fully emulator-green environments.None of these is a production-yield measurement, but together they make 20% toopessimistic as the base expectation.
The realistic planning range is **50–70% raw technical conversion**, or roughly**2,500–3,500 published qualified environments** from the 5,002 strict,device-capable candidates. This applies neither a per-app cap nor an assumedsemantic-deduplication loss. Twenty percent remains a downside scenario. A fixedprospective pilot must replace this planning range before substantial inferenceor cloud-build spending.
Scale comparisons should remain explicit:
- 5,002 strict candidates are about **43x** AndroidWorld's 116 semantic templates;- the raw qualified planning range would be about **22–30x** AndroidWorld;- MobileBench-OL currently reports 1,080 online tasks, so the qualified-environment planning range would be about **2.3–3.2x** its task count;- AndroidControl remains much larger as an offline demonstration collection.
The defensible ambition is not “more rows than every dataset.” It is a uniquelylarge collection of semantically distinct, executable, source-verifiable trainingenvironments. Final claims must use published, qualified bundles—not the census.
### 3.8 What must be proven before scaling
The next fixed pilot should cover 10 projects and 30–50 selected candidates. Itmust measure, without changing the denominator:
- project build yield and case packaging yield;- semantic acceptance and duplicate rate;- original-test preservation;- golden, negative, recovery, and post-reset behavior;- checkpoint latency and per-episode reset/setup time;- app, assertion, transport, and emulator failure rates;- model tokens, retries, wall time, and cost per accepted environment;- cases rejected for mocks, lifecycle coupling, state leakage, or weak terminal assertions.
The approach should be reconsidered if build maintenance dominates total cost,source tests cannot be transformed while preserving lifecycle semantics, usefulcheckpoints are too slow to evaluate during training, wrong-path actions commonlycorrupt future episodes, or semantic deduplication collapses the candidate pool.
## 4. Where collaborators can help
This project crosses several specialties, and the highest-leverage work is notlimited to model inference:
- Android/JUnit engineers: lifecycle preservation, instrumentation, rules, runners, Compose/Espresso compatibility, and fast reset.- Compiler/tooling engineers: reliable Java/Kotlin analysis and deterministic episode generation.- ML systems researchers: checkpoint scheduling, scoring policies, environment APIs, rollout health, and training experiments.- Build/infrastructure engineers: reproducible Android toolchains, distributed workers, resumable artifact publication, and balanced shards.- Dataset researchers: semantic clustering, contamination analysis, diversity measurement, and statistically sound yield estimates.- App maintainers: identifying which tests represent meaningful end-user tasks and which depend on unrealistic fakes.
The detailed runtime contract is in[`ESPRESSOGYM_PRD.md`](ESPRESSOGYM_PRD.md). Dataset qualification andpackaging requirements are in [`DATASET_PRD.md`](DATASET_PRD.md), and the concreteimplementation sequence is in [`IMPLEMENTATION_HANDOFF.md`](IMPLEMENTATION_HANDOFF.md).ESPRESSOGYM_WHITEPAPER.mdAdded+369