Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ jobs:
apps/codex-plugin/test/mcp-launch.test.ts apps/codex-plugin/test/plugin-updates.test.ts
packages/core/test/agent-device-runtime.test.ts
packages/core/test/android-sdk.test.ts packages/core/test/android.test.ts packages/core/test/android-emulator.test.ts
packages/core/test/android-avd-ram.test.ts packages/core/test/resource-saving.test.ts
packages/core/test/app-storage.test.ts packages/core/test/testing-run.test.ts packages/core/test/windows-adb-trace.test.ts
packages/core/test/app-flow-presentations-bindings.test.ts packages/core/test/app-flow-typescript-runtime.test.ts
packages/runtimes/test/serve-emu-node.test.ts packages/ui/test/simulator-panel.test.ts packages/ui/test/testing-panel.test.ts
Expand Down
16 changes: 13 additions & 3 deletions docs/devices.md
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,19 @@ Click the camera button in either simulator toolbar to add a PNG to the chat inp

## Resource saving

On Windows, emulators use the AVD's configured resources. The bundled Android optimizer (`avdslim`) is an Apple Silicon macOS binary, so the **Save resources** control is unavailable on Windows.

The leaf button beside device settings controls **Save resources** for the selected
On Windows x64, **Reduce emulator RAM** is available for eligible Android phone
AVDs configured above the profile's target. It is off by default. Mobile Dev
requests 2560 MiB for API 35–36 and 4096 MiB for API 37 or a display of at
least three million pixels. The emulator can raise the allocation to satisfy
its own requirements. The switch changes only the next Mobile Dev start.
Turning it off starts the emulator with the AVD's configured RAM again.

The Windows profile leaves the AVD configuration, installed packages and app
data in place. Guest package pruning with avdslim is deferred. Its restoration
record can disappear before Android persists re-enabled packages, and an empty
package list can trigger a broad restore. [Windows RAM measurements and package restoration tests](performance/windows-avd-ram-profile.md)

On Apple silicon Macs the leaf button beside device settings controls **Save resources** for the selected
iOS simulator or Android emulator. It is enabled by default and is available while
the device is stopped, so a device can opt out before its first optimized start.
Preferences are stored on this Mac by simulator UDID or AVD name, across plugin
Expand Down
60 changes: 60 additions & 0 deletions docs/performance/windows-avd-ram-profile.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
# Windows Android emulator RAM profile

The Windows profile passes one launch argument, `-memory`, to the Android
Emulator. The next stock start uses the RAM in the AVD configuration. The
profile changes neither Android's low-RAM mode nor its package settings.

## Device checks

Two isolated x86_64 Medium Phone AVDs used WHPX, four guest cores and
a 1080 × 2400 display on Windows 11 Pro x64 (build 26200), with an AMD
Ryzen 7 7700X, Android Emulator 37.3.10 and Platform-Tools 37.0.1.
Mobile Dev's MCP tools set the preference, started and stopped the AVDs,
and installed and launched a test APK. Each device cold booted at its stock
allocation, then with the profile on, off, on and off.

The test checked the effective allocation in `hardware-qemu.ini`, guest
`MemTotal`, the installed APK digest and an app-private value written on first
launch. It also compared user 0's installed and enabled flags and checked that a
deliberately disabled Print Spooler retained its `disabled-user` override.

Each idle reading averaged 11 one-second-spaced samples of the QEMU process
after 15 seconds on the Home screen with no stream open. Working set measures
resident pages. Private bytes measure committed private memory. The initial
setup boot is excluded from mode comparisons.

| Final Windows package | Boots per mode | Effective guest RAM, stock → profile | Host working set, stock → profile | Host private bytes, stock → profile |
| --- | ---: | ---: | ---: | ---: |
| Android 16, API 36 Google APIs | 1 | 4096 → 2560 MiB | 4401.6 → 3344.0 MiB | 5806.9 → 4311.0 MiB |
| Android 17, API 37.0 Google Play | 2 | 6144 → 4096 MiB | 5560.1 → 4905.8 MiB | 7876.8 → 5824.0 MiB |

On API 36 the final package repeated the on/off pair on the same AVD after
the initial five-boot development run. All 250 package overrides matched their
baseline. On API 37 the final package ran the entire sequence. During initial
setup, an NFC package changed from default to disabled. Android recorded the
package itself as the caller. A separate fresh API 37 AVD reproduced the
transition at stock RAM without ever enabling the profile.
The installed APK, private app data and disabled Print Spooler survived every
cold boot. A fresh MCP server also recognized the active RAM profile without
requesting another restart on both images. The configured RAM stayed the same.
On first use the emulator increased its data partition from 4 to 6 GiB.
These idle samples cover one host
and two images. Memory under app load and performance on API 35 were not measured.

## Why Windows package pruning is deferred

In a separate API 36 Google APIs experiment, avdslim removed its restore record
and reported success. After an immediate emulator stop and cold boot, 38 of 38
managed packages were still disabled with 1.0.16 and 11 of 38 with 1.0.17
(172 ms between the latter restore and stop). An orderly guest shutdown restored
40 of 40 on the API 37 Google Play image in one run.

A second issue occurs when there are zero managed packages. Upstream can write
`disabled_packages: null`, which the existing Mobile Dev reader rejects.
In a synthetic adb test, the released Windows x64 1.0.17 binary issued
`pm enable` for 70 distinct targets with either `null` or `[]`. It changed a
previously disabled test package from disabled-user (3) to explicitly enabled
(1). With one managed package, restoration changed its original default (0) to
explicitly enabled (1). A Windows package optimizer
would need a durable per-user record of the original overrides and recovery that
can verify the result after a cold boot. [avdslim 1.0.17 source](https://github.com/kdbhalala/avdslim/tree/v1.0.17)
7 changes: 7 additions & 0 deletions docs/telemetry.md
Original file line number Diff line number Diff line change
Expand Up @@ -890,6 +890,13 @@ readback. Attributes are limited to `component=server`, `surface=simulator`,
fixed-message `resource_saving.apply` error report. Preferences have separate
fixed-message `resource_saving.read` and `resource_saving.set` reports.

On Windows x64, `android.ram_profile.boot.duration` measures a cold start with
the optional RAM profile in milliseconds, from launching the emulator until
Android reports boot completion or the launch fails. The distribution uses
`outcome=booted|failed` and the fixed Android emulator/simulator-surface
attributes. It honors telemetry opt-out. The macOS post-boot optimizer retains
its existing measurement boundary.

The UI records `ui.resource_saving.change` duration and
`ui.resource_saving.failure` through the existing UI operation helper. All paths
use the existing sampling, scrubbing and telemetry opt-out. No device IDs, AVD
Expand Down
90 changes: 90 additions & 0 deletions packages/core/src/android-avd-ram.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { readFile, realpath } from "node:fs/promises";
import { homedir } from "node:os";
import { dirname, isAbsolute, join, resolve } from "node:path";
import { isMissingFile } from "./install-integrity.ts";

async function readIni(path: string) {
const contents = await readFile(path, "utf8");
const properties = new Map<string, string>();
for (const line of contents.split(/\r?\n/)) {
const equals = line.indexOf("=");
if (equals <= 0 || /^\s*[#;]/.test(line)) continue;
const key = line.slice(0, equals).trim();
const value = line.slice(equals + 1).trim();
if (properties.has(key) && properties.get(key) !== value) throw new Error("Ambiguous AVD configuration.");
properties.set(key, value);
}
return properties;
}

function avdRoots() {
const env = process.env;
if (env.ANDROID_AVD_HOME) return [env.ANDROID_AVD_HOME];
const roots = new Set<string>();
for (const home of [env.ANDROID_USER_HOME, env.ANDROID_EMULATOR_HOME, env.ANDROID_PREFS_ROOT, env.ANDROID_SDK_HOME]) {
if (home) roots.add(join(home, "avd"));
}
for (const home of [env.ANDROID_PREFS_ROOT, env.ANDROID_SDK_HOME, env.TEST_TMPDIR, env.USER_HOME, env.HOME, homedir()]) {
if (home) roots.add(join(home, ".android", "avd"));
}
return [...roots];
}

// Emulator releases differ in lookup order when multiple SDK homes or both
// absolute and relative AVD paths exist. Only use an unambiguous match.
async function uniqueExistingPath(paths: string[]) {
const matches = new Map<string, string>();
for (const path of paths) {
// Keep the registry path. A descriptor symlink's path.rel belongs to its
// registry, even when the descriptor file itself lives elsewhere.
try { matches.set(await realpath(path), path); }
catch (error) { if (!isMissingFile(error)) throw error; }
}
return matches.size === 1 ? matches.values().next().value : undefined;
}

function profileRam(config: Map<string, string>, target: string | undefined) {
const image = config.get("image.sysdir.1")?.replaceAll("\\", "/");
const match = /^system-images\/android-(35|36|37)(?:\.\d+)?\/(default|google_apis|google_apis_playstore)\/x86_64\/?$/.exec(image ?? "");
if (!match || config.get("image.sysdir.2")) return;
const [, api, imageTag] = match;
if (target && !new RegExp(`^android-${api}(?:\\.\\d+)?$`).test(target)) return;
if (config.has("tag.id") && config.get("tag.id") !== imageTag) return;
if (config.has("abi.type") && config.get("abi.type") !== "x86_64") return;
const model = config.get("hw.device.name")?.toLowerCase().replaceAll(" ", "_");
if (!/^(?:(?:small|medium)_phone|pixel(?:_xl|_\d+a?(?:_pro)?(?:_xl)?)?)$/.test(model ?? "")) return;
if (config.get("hw.sensor.hinge") === "yes" || config.get("hw.sensor.roll") === "yes") return;

const size = /^(\d+)([MG]?)$/i.exec(config.get("hw.ramSize") ?? "");
if (!size) return;
const configured = Number(size[1]) * (size[2].toUpperCase() === "G" ? 1024 : 1);
if (!Number.isSafeInteger(configured)) return;
// Use 4 GiB for newer phones and larger displays. The emulator can still
// raise either target to meet the requirements of its own version and image.
let ramMiB = 4096;
if (api !== "37") {
const width = Number(config.get("hw.lcd.width"));
const height = Number(config.get("hw.lcd.height"));
if (!Number.isSafeInteger(width) || !Number.isSafeInteger(height) || width <= 0 || height <= 0) return;
if (width * height < 3_000_000) ramMiB = 2560;
}
return configured > ramMiB ? ramMiB : undefined;
}

export async function windowsAvdRamMiB(name: string): Promise<number | undefined> {
if (!/^[\w.-]+$/.test(name)) return;
try {
const descriptor = await uniqueExistingPath(avdRoots().map(root => join(root, `${name}.ini`)));
if (!descriptor) return;
const info = await readIni(descriptor);
const paths: string[] = [];
const absolute = info.get("path");
const relative = info.get("path.rel");
if (absolute && isAbsolute(absolute)) paths.push(absolute);
if (relative && !isAbsolute(relative)) paths.push(resolve(dirname(descriptor), "..", relative.replaceAll("\\", "/")));
const directory = await uniqueExistingPath(paths);
if (directory) return profileRam(await readIni(join(directory, "config.ini")), info.get("target"));
} catch {
// Missing or unreadable metadata makes the optional profile unavailable.
}
}
19 changes: 18 additions & 1 deletion packages/core/src/android-emulator.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { spawn } from "node:child_process";
import { setTimeout as delay } from "node:timers/promises";
import type { Status } from "@mobile-dev/shared/protocol.ts";
import { recordAndroidRamProfileBoot } from "./telemetry.ts";

export function parseAvdName(stdout: string | undefined): string | undefined {
const lines = stdout?.split(/\r?\n/).map(line => line.trim()).filter(Boolean) ?? [];
Expand All @@ -14,14 +15,30 @@ type BootOptions = {
signal: AbortSignal;
ready: () => Promise<Status | undefined>;
resourceSaving?: boolean;
ramMiB?: number;
};

export async function bootAndroidEmulator(options: BootOptions, launch: typeof spawn = spawn): Promise<Status> {
options.signal.throwIfAborted();
if (options.ramMiB === undefined) return launchAndWait(options, launch);
if (!Number.isSafeInteger(options.ramMiB) || options.ramMiB < 1536 || options.ramMiB > 8192) {
throw new Error("Android emulator RAM must be an integer between 1536 and 8192 MiB.");
}
const started = performance.now();
let outcome: "booted" | "failed" = "failed";
try {
const status = await launchAndWait(options, launch);
outcome = "booted";
return status;
} finally { recordAndroidRamProfileBoot(performance.now() - started, outcome); }
}

async function launchAndWait(options: BootOptions, launch: typeof spawn): Promise<Status> {
const args = ["-avd", options.name, "-no-window", "-no-boot-anim", "-gpu", "host"];
// Headless Quick Boot on Windows can leave adb offline or hang shell commands after restore.
if (process.platform === "win32" || options.resourceSaving !== undefined) args.push("-no-snapshot-load", "-no-snapshot-save");
if (options.resourceSaving) args.push("-lowram", "-memory", "1536");
if (options.ramMiB !== undefined) args.push("-memory", String(options.ramMiB));
else if (options.resourceSaving) args.push("-lowram", "-memory", "1536");
const child = launch(options.executable, args, {
detached: true, stdio: "ignore", shell: false, windowsHide: true,
});
Expand Down
8 changes: 3 additions & 5 deletions packages/core/src/resource-saving-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@ const targetSchema = z.discriminatedUnion("platform", [
type Target = z.infer<typeof targetSchema>;

export function registerResourceSavingTools(server: McpServer, baguette: Baguette, android: ServeEmu, saving = new ResourceSaving()) {
baguette.resourceSaving = saving.supported ? saving : undefined;
android.resourceSaving = saving.supported ? saving : undefined;
baguette.resourceSaving = saving.supports("ios") ? saving : undefined;
android.resourceSaving = saving.supports("android") ? saving : undefined;
const device = async (target: Target): Promise<ResourceSavingDevice> => {
const found = target.platform === "ios" ? await baguette.device(target.id) : await android.device(target.id);
if (found.kind === "physical") throw new ExpectedOperationError("invalid_input", "Resource saving is available only for simulators and emulators.");
Expand All @@ -34,18 +34,16 @@ export function registerResourceSavingTools(server: McpServer, baguette: Baguett
}
};
registerAppTool(server, "mobile_resource_saving", {
title: "Read resource saving", description: "Read the selected virtual device's saved resource-saving preference. Enabled by default. Does not boot or optimize the device.",
title: "Read resource saving", description: "Read the selected virtual device's available profile, saved preference and restart status.",
inputSchema: { target: targetSchema }, annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, _meta: { ui: { visibility: ["app"] } },
}, guarded("read", async target => {
const selected = await device(target);
if (!saving.supported) return { supported: false, enabled: false, running: selected.state === "Booted", restartRequired: false };
return saving.state(selected);
}));
registerAppTool(server, "mobile_set_resource_saving", {
title: "Set resource saving", description: "Save resource saving for one existing simulator or emulator. The preference applies on the next start; it never restarts a running device.",
inputSchema: { target: targetSchema, enabled: z.boolean() }, annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false }, _meta: { ui: { visibility: ["app"] } },
}, guarded("set", async (target, enabled) => {
if (!saving.supported) throw new ExpectedOperationError("unsupported_platform", "The bundled resource-saving tools require an Apple silicon Mac.");
const selected = await device(target);
return saving.set(selected, enabled!);
}));
Expand Down
Loading
Loading