From 03dc8dbdc0698dacdbc2ca05ebed85c10e057302 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Hanno=20J=2E=20G=C3=B6decke?= Date: Sat, 21 Nov 2026 15:46:47 +0100 Subject: [PATCH] feat(android): add an opt-in Windows emulator RAM profile --- .github/workflows/ci.yml | 1 + docs/devices.md | 16 +++- docs/performance/windows-avd-ram-profile.md | 60 +++++++++++++ docs/telemetry.md | 7 ++ packages/core/src/android-avd-ram.ts | 90 +++++++++++++++++++ packages/core/src/android-emulator.ts | 19 +++- packages/core/src/resource-saving-tools.ts | 8 +- packages/core/src/resource-saving.ts | 81 ++++++++++++++--- packages/core/src/serve-emu.ts | 10 ++- packages/core/src/telemetry.ts | 6 ++ packages/core/test/android-avd-ram.test.ts | 80 +++++++++++++++++ packages/core/test/android-emulator.test.ts | 13 +++ packages/core/test/android.test.ts | 17 ++-- packages/core/test/resource-saving.test.ts | 42 ++++++++- packages/core/test/telemetry.test.ts | 5 +- packages/shared/src/resource-saving.ts | 2 + packages/skills/mobile-dev/SKILL.md | 5 +- .../ui/src/components/resource-saving.tsx | 27 ++++-- packages/ui/test/react-ui.test.ts | 26 +++++- website/src/content/docs/docs/devices.md | 2 +- 20 files changed, 470 insertions(+), 47 deletions(-) create mode 100644 docs/performance/windows-avd-ram-profile.md create mode 100644 packages/core/src/android-avd-ram.ts create mode 100644 packages/core/test/android-avd-ram.test.ts diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 120e88df..a130e897 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 diff --git a/docs/devices.md b/docs/devices.md index 95a2e175..1561ebc1 100644 --- a/docs/devices.md +++ b/docs/devices.md @@ -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 diff --git a/docs/performance/windows-avd-ram-profile.md b/docs/performance/windows-avd-ram-profile.md new file mode 100644 index 00000000..899a57a8 --- /dev/null +++ b/docs/performance/windows-avd-ram-profile.md @@ -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) diff --git a/docs/telemetry.md b/docs/telemetry.md index 0d2514c2..719c783c 100644 --- a/docs/telemetry.md +++ b/docs/telemetry.md @@ -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 diff --git a/packages/core/src/android-avd-ram.ts b/packages/core/src/android-avd-ram.ts new file mode 100644 index 00000000..002c2954 --- /dev/null +++ b/packages/core/src/android-avd-ram.ts @@ -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(); + 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(); + 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(); + 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, 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 { + 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. + } +} diff --git a/packages/core/src/android-emulator.ts b/packages/core/src/android-emulator.ts index 4e9a9bb1..c52de6f2 100644 --- a/packages/core/src/android-emulator.ts +++ b/packages/core/src/android-emulator.ts @@ -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) ?? []; @@ -14,14 +15,30 @@ type BootOptions = { signal: AbortSignal; ready: () => Promise; resourceSaving?: boolean; + ramMiB?: number; }; export async function bootAndroidEmulator(options: BootOptions, launch: typeof spawn = spawn): Promise { 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 { 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, }); diff --git a/packages/core/src/resource-saving-tools.ts b/packages/core/src/resource-saving-tools.ts index f9d79794..ffc43aef 100644 --- a/packages/core/src/resource-saving-tools.ts +++ b/packages/core/src/resource-saving-tools.ts @@ -16,8 +16,8 @@ const targetSchema = z.discriminatedUnion("platform", [ type Target = z.infer; 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 => { 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."); @@ -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!); })); diff --git a/packages/core/src/resource-saving.ts b/packages/core/src/resource-saving.ts index 5a973707..ddbb8e3d 100644 --- a/packages/core/src/resource-saving.ts +++ b/packages/core/src/resource-saving.ts @@ -6,7 +6,9 @@ import { homedir } from "node:os"; import { dirname, isAbsolute, join } from "node:path"; import { promisify } from "node:util"; import { z } from "zod"; +import { ExpectedOperationError } from "@mobile-dev/shared/error-reporting.ts"; import type { ResourceSavingDevice, ResourceSavingState } from "@mobile-dev/shared/resource-saving.ts"; +import { windowsAvdRamMiB } from "./android-avd-ram.ts"; import { adbPath } from "./native-logs.ts"; import { isMissingFile, MissingRuntimeError } from "./install-integrity.ts"; import { panelRuntimePath } from "./panel-runtime.ts"; @@ -14,8 +16,11 @@ import { captureServerError, recordResourceSaving } from "./telemetry.ts"; const execute = promisify(execFile); const home = homedir(); -const directory = join(home, "Library/Application Support/mobile-dev/resource-saving"); +const directory = process.platform === "win32" + ? join(process.env.LOCALAPPDATA || join(home, "AppData", "Local"), "mobile-dev", "resource-saving") + : join(home, "Library/Application Support/mobile-dev/resource-saving"); const preferenceSchema = z.object({ enabled: z.boolean() }); +const ramBootSchema = z.object({ bootId: z.uuid(), ramMiB: z.number().int().positive() }); const androidStateSchema = z.object({ disabled_packages: z.array(z.string()), settings: z.record(z.string(), z.string().nullable()) }); export const IOS_RESOURCE_SAVING_EXCEPT = "store,web,pim,photos,connectivity,telemetry"; export const ANDROID_RESOURCE_SAVING_SKIP = "animations,bglimit,sync,location,setup,bluetooth"; @@ -25,8 +30,8 @@ const androidKeep = [ "com.google.android.marvin.talkback", "com.google.android.apps.accessibility.voiceaccess", "com.google.android.tts", ]; -type Run = (file: string, args: string[], options: { timeout: number; maxBuffer: number; encoding: "utf8"; env?: NodeJS.ProcessEnv; signal?: AbortSignal }) => Promise<{ stdout: string }>; -type Options = { directory?: string; run?: Run; executable?: (platform: "ios" | "android") => Promise; adb?: () => Promise }; +type Run = (file: string, args: string[], options: { timeout: number; maxBuffer: number; encoding: "utf8"; env?: NodeJS.ProcessEnv; signal?: AbortSignal; windowsHide?: boolean }) => Promise<{ stdout: string }>; +type Options = { directory?: string; run?: Run; executable?: (platform: "ios" | "android") => Promise; adb?: () => Promise; ramLimit?: typeof windowsAvdRamMiB }; async function executable(platform: "ios" | "android") { const name = platform === "ios" ? "simslim" : "avdslim"; @@ -41,7 +46,8 @@ async function executable(platform: "ios" | "android") { export class ResourceSaving { readonly directory: string; - readonly supported: boolean; + private readonly bundledOptimizers: boolean; + private readonly ramLimit?: typeof windowsAvdRamMiB; private readonly run: Run; private readonly locate: typeof executable; private readonly adb: () => Promise; @@ -50,13 +56,18 @@ export class ResourceSaving { constructor(options: Options = {}) { // Both packaged optimizers are macOS arm64 executables. - this.supported = options.executable !== undefined || (process.platform === "darwin" && process.arch === "arm64"); + this.bundledOptimizers = !options.ramLimit && (options.executable !== undefined || (process.platform === "darwin" && process.arch === "arm64")); + this.ramLimit = options.ramLimit ?? (!this.bundledOptimizers && process.platform === "win32" && process.arch === "x64" ? windowsAvdRamMiB : undefined); this.directory = options.directory ?? directory; this.run = options.run ?? execute; this.locate = options.executable ?? executable; this.adb = options.adb ?? adbPath; } + supports(platform: ResourceSavingDevice["platform"]) { + return this.bundledOptimizers || (platform === "android" && this.ramLimit !== undefined); + } + private filename(device: Pick) { const hash = createHash("sha256"); hash.update(`${device.platform}:${device.key}`); @@ -69,7 +80,7 @@ export class ResourceSaving { let text: string; try { text = await readFile(path, "utf8"); } catch (error) { - if (isMissingFile(error)) return true; + if (isMissingFile(error)) return this.bundledOptimizers; throw error; } const parsed: unknown = JSON.parse(text); @@ -78,23 +89,67 @@ export class ResourceSaving { } async state(device: ResourceSavingDevice): Promise { - const enabled = await this.enabled(device); - const key = this.filename(device); const running = device.state === "Booted"; - return { enabled, running, restartRequired: running && this.applied.get(key) !== enabled }; + const unavailable = { supported: false, enabled: false, running, restartRequired: false }; + if (!this.supports(device.platform)) return unavailable; + const enabled = await this.enabled(device); + if (this.ramLimit) { + const ramMiB = await this.ramLimit(device.key); + const activeRam = running ? await this.runningRam(device) : undefined; + if (ramMiB === undefined && !enabled && activeRam === undefined) return unavailable; + const expected = enabled ? ramMiB : undefined; + return { profile: "ram", ramMiB, enabled, running, restartRequired: running && activeRam !== expected }; + } + return { enabled, running, restartRequired: running && this.applied.get(this.filename(device)) !== enabled }; } async set(device: ResourceSavingDevice, enabled: boolean) { + if (!this.supports(device.platform) || (this.ramLimit && enabled && await this.ramLimit(device.key) === undefined)) { + throw new ExpectedOperationError("unsupported_platform", "Resource saving is unavailable for this virtual device."); + } + await this.writeJson(this.filename(device), { enabled }); + return this.state(device); + } + + private async writeJson(path: string, value: object) { await mkdir(this.directory, { recursive: true, mode: 0o700 }); - const path = this.filename(device); const suffix = randomUUID(); const temporary = `${path}.${suffix}.tmp`; - const text = JSON.stringify({ enabled }); try { - await writeFile(temporary, text, { mode: 0o600 }); + await writeFile(temporary, JSON.stringify(value), { mode: 0o600 }); await rename(temporary, path); } finally { await rm(temporary, { force: true }); } - return this.state(device); + } + + async androidBootOptions(device: ResourceSavingDevice): Promise<{ ramMiB?: number; resourceSaving?: boolean }> { + const enabled = await this.enabled(device); + if (this.ramLimit) return { ramMiB: enabled ? await this.ramLimit(device.key) : undefined }; + return { resourceSaving: enabled }; + } + + private async bootId(serial: string) { + try { + const result = await this.run(await this.adb(), ["-s", serial, "shell", "cat", "/proc/sys/kernel/random/boot_id"], { + timeout: 3000, maxBuffer: 1024, encoding: "utf8", windowsHide: true, + }); + return z.uuid().safeParse(result.stdout.trim()).data; + } catch { return undefined; } + } + + private async runningRam(device: ResourceSavingDevice) { + let text: string; + try { text = await readFile(this.filename(device) + ".boot", "utf8"); } + catch (error) { if (isMissingFile(error)) return; throw error; } + try { + const receipt = ramBootSchema.parse(JSON.parse(text)); + if (receipt.bootId === await this.bootId(device.id)) return receipt.ramMiB; + } catch { /* An unreadable boot record cannot confirm the applied profile. */ } + } + + async rememberRamBoot(device: ResourceSavingDevice, ramMiB: number) { + // A serial and AVD name can both be reused after a start outside Mobile Dev. + const bootId = await this.bootId(device.id); + if (bootId) await this.writeJson(this.filename(device) + ".boot", { bootId, ramMiB }); } forget(device: Pick) { diff --git a/packages/core/src/serve-emu.ts b/packages/core/src/serve-emu.ts index 72d8574e..ea2b702a 100644 --- a/packages/core/src/serve-emu.ts +++ b/packages/core/src/serve-emu.ts @@ -147,15 +147,19 @@ export class ServeEmu { if (!id.startsWith("avd:")) throw new SimulatorUnavailableError("Reconnect and authorize this Android device through adb."); // Launch separately from serve-emu so closing the panel never stops the AVD. const target = { platform: "android" as const, id, key: device.name, state: device.state }; - const resourceSaving = await this.resourceSaving?.enabled(target); + const profile = await this.resourceSaving?.androidBootOptions(target); const status = await bootAndroidEmulator({ name: device.name, executable: await sdkToolPath("emulator"), signal: this.lifetime.signal, ready: () => this.emulatorReady(item => item.name === device.name, "boot"), - resourceSaving, + ...profile, }); const running = status.devices.find(item => item.kind === "emulator" && item.name === device.name && item.state === "Booted"); if (running === undefined) throw new Error("The started Android emulator is no longer available."); - await this.resourceSaving?.apply({ ...target, id: running.udid, state: running.state }, this.lifetime.signal, resourceSaving); + if (profile?.resourceSaving !== undefined) { + await this.resourceSaving?.apply({ ...target, id: running.udid, state: running.state }, this.lifetime.signal, profile.resourceSaving); + } else if (profile?.ramMiB !== undefined) { + await this.resourceSaving?.rememberRamBoot({ ...target, id: running.udid }, profile.ramMiB); + } return status; } diff --git a/packages/core/src/telemetry.ts b/packages/core/src/telemetry.ts index a15eee34..df9164c0 100644 --- a/packages/core/src/telemetry.ts +++ b/packages/core/src/telemetry.ts @@ -21,6 +21,12 @@ export function recordResourceSaving(platform: "ios" | "android", enabled: boole Sentry.metrics.distribution("resource_saving.duration", duration, { unit: "millisecond", attributes }); } +export function recordAndroidRamProfileBoot(duration: number, outcome: "booted" | "failed") { + if (process.env.MOBILE_DEV_TELEMETRY === "off") return; + const attributes = { component: "server", surface: "simulator", device_platform: "android", device_kind: "emulator", outcome }; + Sentry.metrics.distribution("android.ram_profile.boot.duration", duration, { unit: "millisecond", attributes }); +} + export function recordBrowserPanelSessions(active: number) { if (process.env.MOBILE_DEV_TELEMETRY === "off") return; Sentry.metrics.gauge("browser_panel.sessions", active, { attributes: { component: "server" } }); diff --git a/packages/core/test/android-avd-ram.test.ts b/packages/core/test/android-avd-ram.test.ts new file mode 100644 index 00000000..c42f90ed --- /dev/null +++ b/packages/core/test/android-avd-ram.test.ts @@ -0,0 +1,80 @@ +import assert from "node:assert/strict"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test, { type TestContext } from "node:test"; +import { windowsAvdRamMiB } from "../src/android-avd-ram.ts"; + +async function fixture(t: TestContext) { + const root = await mkdtemp(join(tmpdir(), "mobile-dev avd ")); + const registry = join(root, "avd"); + const device = join(root, "relocated phone.avd"); + const original = process.env.ANDROID_AVD_HOME; + process.env.ANDROID_AVD_HOME = registry; + t.after(async () => { + if (original === undefined) delete process.env.ANDROID_AVD_HOME; + else process.env.ANDROID_AVD_HOME = original; + await rm(root, { force: true, recursive: true }); + }); + await Promise.all([mkdir(registry), mkdir(device)]); + const descriptor = join(registry, "my_phone.ini"); + await writeFile(descriptor, `path=${device}\r\n`); + const config = { + "image.sysdir.1": "system-images\\android-36\\google_apis\\x86_64\\", + "hw.device.name": "pixel_8", + "hw.ramSize": "6144", + "hw.lcd.width": "1080", + "hw.lcd.height": "2400", + }; + const writeConfig = async (overrides: Record) => { + const text = Object.entries({ ...config, ...overrides }).map(([k, v]) => `${k} = ${v}`).join("\r\n"); + await writeFile(join(device, "config.ini"), text); + }; + return { root, descriptor, device, writeConfig }; +} + +test("Windows RAM profile reads relocated phone AVDs and respects the API and large-screen floors", async t => { + const { writeConfig } = await fixture(t); + for (const [image, expected] of [ + ["system-images/android-35/default/x86_64/", 2560], + ["system-images/android-36/google_apis/x86_64/", 2560], + ["system-images/android-37.0/google_apis_playstore/x86_64/", 4096], + ["system-images/android-37.1/google_apis/x86_64/", 4096], + ] as const) { + await writeConfig({ "image.sysdir.1": image, "hw.ramSize": "6G" }); + assert.equal(await windowsAvdRamMiB("my_phone"), expected); + } + await writeConfig({ "hw.lcd.width": "1250" }); + assert.equal(await windowsAvdRamMiB("my_phone"), 4096); +}); + +test("an unknown image or device, conflicting metadata, or insufficient configured RAM uses the stock launch", async t => { + const { writeConfig, descriptor, device } = await fixture(t); + for (const overrides of [ + { "image.sysdir.1": "system-images/android-38/google_apis/x86_64/" }, + { "image.sysdir.1": "system-images/android-36/android-wear/x86_64/" }, + { "image.sysdir.1": "/custom/sdk-image/" }, + { "tag.id": "android-automotive" }, { "abi.type": "arm64-v8a" }, + { "hw.device.name": "pixel_9_pro_fold" }, { "hw.device.name": "my_device" }, + { "hw.lcd.width": "" }, { "hw.ramSize": "2G" }, { "hw.ramSize": "2560M" }, { "hw.ramSize": "many" }, + ] as Record[]) { + await writeConfig(overrides); + assert.equal(await windowsAvdRamMiB("my_phone"), undefined, JSON.stringify(overrides)); + } + await writeConfig({}); + await writeFile(descriptor, `path=${device}\ntarget=android-37\n`); + assert.equal(await windowsAvdRamMiB("my_phone"), undefined); + assert.equal(await windowsAvdRamMiB("../my_phone"), undefined); + assert.equal(await windowsAvdRamMiB("absent"), undefined); +}); + +test("relative descriptors resolve against the AVD registry parent and conflicting live paths are skipped", async t => { + const { root, descriptor, device, writeConfig } = await fixture(t); + await writeConfig({}); + await writeFile(descriptor, `path=${join(root, "missing.avd")}\npath.rel=relocated phone.avd\n`); + assert.equal(await windowsAvdRamMiB("my_phone"), 2560); + const other = join(root, "other.avd"); + await mkdir(other); + await writeFile(descriptor, `path=${device}\npath.rel=other.avd\n`); + assert.equal(await windowsAvdRamMiB("my_phone"), undefined); +}); diff --git a/packages/core/test/android-emulator.test.ts b/packages/core/test/android-emulator.test.ts index 9626b326..88545cf7 100644 --- a/packages/core/test/android-emulator.test.ts +++ b/packages/core/test/android-emulator.test.ts @@ -55,6 +55,19 @@ test("resource-saving launches bypass snapshots and only the enabled mode change } }); +test("the RAM-only profile passes a single override and keeps the emulator's image minimum", async () => { + const fake = fakeLauncher(); + const opts = { name: "API_37", executable: "emulator", signal: new AbortController().signal, ready: async () => status }; + await bootAndroidEmulator({ ...opts, ramMiB: 4096 }, fake.launch); + const args = fake.calls[0][1] as string[]; + assert.deepEqual(args.slice(-2), ["-memory", "4096"]); + assert.equal(args.includes("-lowram"), false); + for (const ramMiB of [0, Infinity, 1999.5, 8193]) { + await assert.rejects(bootAndroidEmulator({ ...opts, ramMiB }, fake.launch), /RAM must be an integer/); + } + assert.equal(fake.calls.length, 1); +}); + test("an early emulator exit interrupts an in-flight adb check", async () => { const fake = fakeLauncher(); let release!: () => void; const polling = new Promise(resolve => { release = resolve; }); diff --git a/packages/core/test/android.test.ts b/packages/core/test/android.test.ts index b24b755d..ebd12298 100644 --- a/packages/core/test/android.test.ts +++ b/packages/core/test/android.test.ts @@ -15,6 +15,7 @@ import { Baguette } from "../src/baguette.ts"; import { createTestPlugin, fakeBaguette, fakeSimulatorInput, PNG } from "../../test-support/fixtures.ts"; import { fakeInspectionSdk } from "../../test-support/android-inspection-fixtures.ts"; import { createPanel } from "../src/panel-tools.ts"; +import { ResourceSaving } from "../src/resource-saving.ts"; import { registerAndroidTools } from "../src/android-tools.ts"; import type { PhysicalAndroidDevice } from "@mobile-dev/shared/android-devices.ts"; @@ -239,21 +240,19 @@ test("Android streams relay video, validate batches, and refuse a device switch" test("Android MCP flow lists without booting, captures, streams, and closes", async t => { const fake = await fakeAndroid(); const ios = await fakeBaguette(); - const plugin = await createTestPlugin("", { panel: createPanel({ baguette: new Baguette(ios.url), simulatorInput: fakeSimulatorInput(), copyScreenshot: async bytes => { assert.deepEqual(bytes, PNG); } }), android: fake.backend }); + const resourceSaving = new ResourceSaving({ ramLimit: async () => undefined }); + const plugin = await createTestPlugin("", { panel: createPanel({ baguette: new Baguette(ios.url), resourceSaving, simulatorInput: fakeSimulatorInput(), copyScreenshot: async bytes => { assert.deepEqual(bytes, PNG); } }), android: fake.backend }); const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); const client = new Client({ name: "android-test", version: "1" }); t.after(async () => { await client.close(); await plugin.close(); await fake.close(); await ios.close(); }); await plugin.server.connect(serverTransport); await client.connect(clientTransport); const listed = await client.callTool({ name: "mobile_list_android_devices", arguments: {} }); assert.equal((listed.structuredContent?.devices as { udid: string }[])[0].udid, ID); - if (process.platform === "win32") { - assert.equal(fake.backend.resourceSaving, undefined, "a Windows boot must leave snapshot/RAM settings to the AVD"); - const target = { platform: "android", id: ID }; - const saving = await client.callTool({ name: "mobile_resource_saving", arguments: { target } }); - assert.deepEqual(saving.structuredContent?.state, { supported: false, enabled: false, running: true, restartRequired: false }); - const setting = await client.callTool({ name: "mobile_set_resource_saving", arguments: { target, enabled: true } }); - assert.equal(setting.isError, true); - } + const target = { platform: "android", id: ID }; + const saving = await client.callTool({ name: "mobile_resource_saving", arguments: { target } }); + assert.deepEqual(saving.structuredContent?.state, { supported: false, enabled: false, running: true, restartRequired: false }); + const setting = await client.callTool({ name: "mobile_set_resource_saving", arguments: { target, enabled: true } }); + assert.equal(setting.isError, true, "an ineligible AVD cannot enable the RAM profile"); assert.deepEqual(fake.backend.boots, []); assert.equal(fake.sockets.clients.size, 0); const captured = await client.callTool({ name: "mobile_android_capture_screenshot", arguments: { deviceId: ID } }); assert.deepEqual(captured.content[0], { type: "image", mimeType: "image/png", data: PNG.toString("base64") }); diff --git a/packages/core/test/resource-saving.test.ts b/packages/core/test/resource-saving.test.ts index 5237d66f..20f06590 100644 --- a/packages/core/test/resource-saving.test.ts +++ b/packages/core/test/resource-saving.test.ts @@ -42,7 +42,7 @@ test("resource saving defaults on and persists opt-outs by stable device identit const initial = await f.saving.state(ios); assert.deepEqual(initial, { enabled: true, running: true, restartRequired: true }); await f.saving.set(android, false); - const restarted = new ResourceSaving({ directory: f.directory }); + const restarted = new ResourceSaving({ directory: f.directory, executable: async () => "/runtime/android" }); const otherSerial = { ...android, id: "emulator-5560" }; const enabled = await restarted.enabled(otherSerial); assert.equal(enabled, false); @@ -56,6 +56,46 @@ test("resource saving defaults on and persists opt-outs by stable device identit await assert.rejects(malformed, /JSON/); }); +test("the RAM profile is opt-in per eligible AVD and applies only at boot", async t => { + const directory = await mkdtemp(join(tmpdir(), "avd-ram-test-")); + t.after(() => rm(directory, { recursive: true, force: true })); + let limit: number | undefined = 2560; + let bootId = "9353e965-eee6-4d69-b07e-2c08087d15cc"; + const options = { + directory, ramLimit: async (name: string) => name === android.key ? limit : undefined, + adb: async () => "/sdk/adb", run: async (_file: string, args: string[]) => { + assert.deepEqual(args, ["-s", android.id, "shell", "cat", "/proc/sys/kernel/random/boot_id"]); + return { stdout: bootId }; + }, + }; + const saving = new ResourceSaving(options); + const stopped = { ...android, id: "avd:Pixel_8", state: "Shutdown" }; + assert.equal(saving.supports("ios"), false); + assert.equal(saving.supports("android"), true); + assert.deepEqual(await saving.state(stopped), { profile: "ram", ramMiB: 2560, enabled: false, running: false, restartRequired: false }); + assert.deepEqual(await saving.androidBootOptions(stopped), { ramMiB: undefined }); + assert.equal((await saving.state(android)).restartRequired, false, "an unmodified external boot is already using its own configuration"); + assert.equal((await saving.set(android, true)).restartRequired, true); + const restarted = new ResourceSaving(options); + const launch = await restarted.androidBootOptions(stopped); + assert.deepEqual(launch, { ramMiB: 2560 }); + await restarted.rememberRamBoot(android, launch.ramMiB!); + assert.equal((await restarted.state(android)).restartRequired, false); + assert.equal((await saving.state(android)).restartRequired, false, "another server recognizes the same boot"); + bootId = "79acd8d9-186d-41c5-9417-368680c91daa"; + assert.equal((await saving.state(android)).restartRequired, true, "a fresh external boot can reuse the same serial"); + limit = 4096; + assert.equal((await restarted.state(android)).restartRequired, true); + limit = undefined; + assert.equal((await restarted.state(android)).enabled, true, "the saved opt-in remains accessible to clear"); + assert.deepEqual(await restarted.androidBootOptions(stopped), { ramMiB: undefined }); + await assert.rejects(restarted.set(android, true), /unavailable/); + await restarted.set(stopped, false); + assert.equal((await restarted.state(android)).supported, false); + limit = 2560; + assert.deepEqual(await saving.androidBootOptions(stopped), { ramMiB: undefined }); +}); + test("iOS slimming preserves required features, verifies the profile, and never silently succeeds on failure", async t => { const f = await fixture(t); await f.saving.apply(ios); diff --git a/packages/core/test/telemetry.test.ts b/packages/core/test/telemetry.test.ts index 7e075c8e..6d0228e1 100644 --- a/packages/core/test/telemetry.test.ts +++ b/packages/core/test/telemetry.test.ts @@ -11,7 +11,7 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { InMemoryTransport } from "@modelcontextprotocol/sdk/inMemory.js"; import { z } from "zod"; import { MeasurementWindow, sampleTrace, scrubErrorEvent, scrubMetric, scrubSpan, sampleMetric, createErrorEventFilter, METRIC_SAMPLE_RATE, TELEMETRY_META_KEY } from "../../shared/src/telemetry.ts"; -import { captureServerError, installTracePropagation, instrumentMcpServer, IOSLogProcessingTelemetry, recordAndroidBackendStartup, recordAndroidBootWait, recordIosMirrorSharing, recordBrowserPanelContext, recordBrowserPanelSessions, recordPanelRuntime, recordResourceSaving } from "../src/telemetry.ts"; +import { captureServerError, installTracePropagation, instrumentMcpServer, IOSLogProcessingTelemetry, recordAndroidBackendStartup, recordAndroidBootWait, recordAndroidRamProfileBoot, recordIosMirrorSharing, recordBrowserPanelContext, recordBrowserPanelSessions, recordPanelRuntime, recordResourceSaving } from "../src/telemetry.ts"; import { recordPluginUpdate } from "../../../apps/codex-plugin/server/plugin-updates.ts"; import { deferEpisodeReport, ExpectedOperationError, FailureEpisodes } from "../../shared/src/error-reporting.ts"; import { parseResourceInput } from "../src/resource-input.ts"; @@ -1449,6 +1449,7 @@ test("browser session counts describe plugin resources and honor telemetry opt-o recordPanelRuntime("failed", 30, undefined, "network"); recordResourceSaving("ios", true, "success", 2500); recordResourceSaving("android", false, "failed", 100); + recordAndroidRamProfileBoot(18000, "booted"); await Sentry.flush(); const sent = JSON.stringify(envelopes); contains(sent, "browser_panel.sessions"); @@ -1459,6 +1460,7 @@ test("browser session counts describe plugin resources and honor telemetry opt-o contains(sent, "panel_runtime.download_bytes"); contains(sent, "resource_saving.apply"); contains(sent, "resource_saving.duration"); + contains(sent, "android.ram_profile.boot.duration"); contains(sent, '"reason":{"value":"network"'); contains(sent, '"component":{"value":"server"'); for (const fragment of ["sessionId", "user.id", "telemetry_session", "localhost", "127.0.0.1", "github.com", "panel-runtime-darwin"]) contains(sent, fragment, false); @@ -1467,6 +1469,7 @@ test("browser session counts describe plugin resources and honor telemetry opt-o recordBrowserPanelContext("stored", 10); recordPanelRuntime("cached", 5); recordResourceSaving("ios", false, "success", 10); + recordAndroidRamProfileBoot(10, "failed"); await Sentry.flush(); assert.equal(JSON.stringify(envelopes), sent); }); diff --git a/packages/shared/src/resource-saving.ts b/packages/shared/src/resource-saving.ts index 4912d943..e5e22d5b 100644 --- a/packages/shared/src/resource-saving.ts +++ b/packages/shared/src/resource-saving.ts @@ -1,5 +1,7 @@ export type ResourceSavingState = { supported?: boolean; + profile?: "ram"; + ramMiB?: number; enabled: boolean; running: boolean; restartRequired: boolean; diff --git a/packages/skills/mobile-dev/SKILL.md b/packages/skills/mobile-dev/SKILL.md index 43acda87..2c05de16 100644 --- a/packages/skills/mobile-dev/SKILL.md +++ b/packages/skills/mobile-dev/SKILL.md @@ -8,8 +8,9 @@ description: Use when building, running, changing, or debugging local iOS, Andro Use the Mobile Dev MCP tools for local iOS and Android work. Codex on Windows supports Android emulators and phones. An Apple Silicon Mac also supports local iOS devices with Xcode. Mobile Dev starts its bundled device backends as needed. Start stopped virtual devices through `mobile_boot_simulator` or -`mobile_boot_android_emulator` before using agent-device. Windows emulators use -the AVD's configured resources. On Apple Silicon Macs these start paths apply +`mobile_boot_android_emulator` before using agent-device. Windows x64 emulators use +the AVD's configured RAM unless the user enables **Reduce emulator RAM** for +an eligible phone AVD. On Apple Silicon Macs these start paths apply the device's saved resource-saving mode, enabled by default. The leaf control beside device settings can opt a device out, including while it is stopped. Changing the mode saves it for the next start; only the user's explicit diff --git a/packages/ui/src/components/resource-saving.tsx b/packages/ui/src/components/resource-saving.tsx index 59bfa0e9..c86d0f0f 100644 --- a/packages/ui/src/components/resource-saving.tsx +++ b/packages/ui/src/components/resource-saving.tsx @@ -10,13 +10,28 @@ export function ResourceSaving({ store }: { store: ResourceSavingStore }) { const id = useId(); if (!state.visible || state.value?.supported === false) return null; const disabled = state.disabled || state.loading || state.busy || state.value === undefined; - const enabled = state.value?.enabled ?? true; + const enabled = state.value?.enabled === true; + const ramProfile = state.value?.profile === "ram"; + const label = ramProfile ? "Emulator RAM profile" : "Resource saving"; + const ramMiB = state.value?.ramMiB; + const ramHint = ramMiB === undefined + ? "This AVD will use its configured RAM on the next start. You can clear the saved preference." + : `Requests ${ramMiB} MiB of guest RAM. Some system images require more.`; + const restartHint = ramProfile + ? "Restart this emulator from Mobile Dev to apply the RAM setting. Running apps will close." + : "Restart this device to apply the saved setting. Running apps will close."; + const timingHint = ramProfile ? "Applies the next time Mobile Dev starts this emulator." + : state.value?.running ? "The saved setting was applied when this device started." : "Applies the next time this device starts."; return { if (open) void store.load(); }}> - - -
void store.change(value)} />
-

Reduce background services and memory use. Saved for this device and enabled by default.

-

{state.value?.restartRequired ? "Restart this device to apply the saved setting. Running apps will close." : state.value?.running ? "The saved setting was applied when this device started." : "Applies the next time this device starts."}

+ + +
void store.change(value)} />
+ {state.value && <> +

{ramProfile + ? ramHint + : "Reduce background services and memory use. Saved for this device and enabled by default."}

+

{state.value.restartRequired ? restartHint : timingHint}

+ } {state.value?.restartRequired && } {state.busy &&

Applying…

} {state.error &&

{state.error}

} diff --git a/packages/ui/test/react-ui.test.ts b/packages/ui/test/react-ui.test.ts index e56a22cb..ec9b435d 100644 --- a/packages/ui/test/react-ui.test.ts +++ b/packages/ui/test/react-ui.test.ts @@ -61,9 +61,9 @@ test("React log controls filter virtual rows, attach full logs, and preserve sim await rm(directory, { recursive: true, force: true }); }); const output = resolve(directory, "workspace.mjs"); - await build({ stdin: { contents: 'export { Workspace } from "./packages/mcp-app/src/components/workspace.tsx"; export { getDeviceSettings } from "./packages/ui/src/device-settings.ts"; export { getDevicePicker } from "./packages/ui/src/device-picker.ts"; export { getAppTools } from "./packages/ui/src/app-tools.ts";', resolveDir: process.cwd(), loader: "ts" }, outfile: output, bundle: true, format: "esm", platform: "node", jsx: "automatic", + await build({ stdin: { contents: 'export { Workspace } from "./packages/mcp-app/src/components/workspace.tsx"; export { getDeviceSettings } from "./packages/ui/src/device-settings.ts"; export { getDevicePicker } from "./packages/ui/src/device-picker.ts"; export { getAppTools } from "./packages/ui/src/app-tools.ts"; export { getResourceSaving } from "./packages/ui/src/resource-saving.ts";', resolveDir: process.cwd(), loader: "ts" }, outfile: output, bundle: true, format: "esm", platform: "node", jsx: "automatic", external: ["recharts", "react", "react/*", "react-dom", "react-dom/*", "@legendapp/list/react", "radix-ui", "lucide-react", "@base-ui/react/*", "react-resizable-panels", "@xyflow/react"] }); - const { Workspace, getDeviceSettings, getDevicePicker, getAppTools } = await import(pathToFileURL(output).href); + const { Workspace, getDeviceSettings, getDevicePicker, getAppTools, getResourceSaving } = await import(pathToFileURL(output).href); const { act, createElement, Profiler } = await import("react"); const { createRoot } = await import("react-dom/client"); let sentLog: StackedLog | undefined; @@ -206,6 +206,28 @@ test("React log controls filter virtual rows, attach full logs, and preserve sim assert.equal(bookingOption.textContent, bookingName + deviceSpecs); assert.equal(bookingOption.querySelector("checkout"), null); await act(async () => { (bookingOption as HTMLButtonElement).click(); }); + const androidSaving = getResourceSaving(dom.window.document.querySelector('#android-panel [data-element="settings"]')); + let ramEnabled = false; + androidSaving.request = async (enabled?: boolean) => { + if (enabled !== undefined) ramEnabled = enabled; + return { profile: "ram", ramMiB: 2560, enabled: ramEnabled, running: true, restartRequired: ramEnabled }; + }; + await act(async () => { androidSaving.configure("Pixel", true, false); }); + const ramButton = dom.window.document.querySelector('#android-panel [aria-label="Emulator RAM profile"]')!; + assert.equal(ramButton.title, "Emulator RAM profile off"); + await act(async () => { ramButton.click(); }); + const ramPopover = dom.window.document.querySelector('[data-slot="popover-content"][aria-label="Emulator RAM profile"]')!; + assert.match(ramPopover.textContent!, /2560 MiB of guest RAM/); + assert.match(ramPopover.textContent!, /next time Mobile Dev starts/); + assert.doesNotMatch(ramPopover.textContent!, /background services|enabled by default/); + const ramSwitch = ramPopover.querySelector('[role="switch"]')!; + assert.equal(ramSwitch.getAttribute("aria-checked"), "false"); + await act(async () => { ramSwitch.click(); }); + assert.equal(ramEnabled, true); + assert.equal(ramButton.title, "Emulator RAM profile on"); + assert.match(ramPopover.textContent!, /Running apps will close/); + assert.match(ramPopover.textContent!, /Restart to apply/); + await act(async () => { ramButton.click(); }); const iosSettings = getDeviceSettings(dom.window.document.querySelector('#ios-panel [data-element="settings"]')); const changes: unknown[] = []; iosSettings.request = async (change: unknown) => { changes.push(change); return { appearance: "light", contentSize: "large", increaseContrast: false, locationSupported: true }; }; diff --git a/website/src/content/docs/docs/devices.md b/website/src/content/docs/docs/devices.md index 05af0159..bc6618d2 100644 --- a/website/src/content/docs/docs/devices.md +++ b/website/src/content/docs/docs/devices.md @@ -43,7 +43,7 @@ Close Device Hub's mirroring window while using Mobile Dev's physical iOS mirror On Windows, Mobile Dev cold boots AVDs it starts. Installed apps and AVD user data persist. To use Android Studio’s Quick Boot, start the AVD in Device Manager and select the running emulator in Mobile Dev. -Windows uses the AVD's configured memory and CPU settings. The **Save resources** control uses the Apple Silicon macOS helper `avdslim` and is unavailable on Windows. The iOS tab remains visible. Local iOS simulators and physical iOS mirroring require macOS and Xcode. [Set up Android](/docs/getting-started#set-up-android) +Windows x64 uses the AVD's configured memory by default. For eligible phone AVDs with API 35–37, the leaf button offers **Reduce emulator RAM**. The preference applies to the next Mobile Dev start and leaves the AVD configuration and guest packages in place. Turn it off to return to the configured RAM. Local iOS simulators and physical iOS mirroring require macOS and Xcode. [Set up Android](/docs/getting-started#set-up-android) ## Physical Android devices