diff --git a/e2e/helpers/test-android-sdk.test.ts b/e2e/helpers/test-android-sdk.test.ts new file mode 100644 index 000000000..72709392b --- /dev/null +++ b/e2e/helpers/test-android-sdk.test.ts @@ -0,0 +1,112 @@ +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { describe, expect, it } from "vitest"; + +import { MemoryFilesystem } from "../../src/ports/index.js"; +import { findAndroidSdk, runSdkTool } from "./test-android-sdk.js"; + +const SDK = "/Local/Android/Sdk"; +const WINDOWS_TOOLS = [ + "cmdline-tools/latest/bin/avdmanager.bat", + "cmdline-tools/latest/bin/sdkmanager.bat", + "emulator/emulator.exe", + "platform-tools/adb.exe", +]; + +async function sdkWith(tools: readonly string[]): Promise { + const filesystem = new MemoryFilesystem(); + await filesystem.mkdirp(SDK); + for (const tool of tools) { + const path = `${SDK}/${tool}`; + await filesystem.mkdirp(path.slice(0, path.lastIndexOf("/"))); + await filesystem.writeFileAtomic(path, ""); + } + return filesystem; +} + +// why: the lookup's search order and tool names are proven in src/drivers/android/prerequisites.test.ts; +// these prove only what this helper adds: a skip on anything short of a complete SDK, and that a +// tool which fails or runs past its timeout rejects, as `execFile` did. +describe("findAndroidSdk", () => { + it("finds a Windows SDK under %LOCALAPPDATA% with its .exe and .bat tools", async () => { + const sdk = await findAndroidSdk( + { LOCALAPPDATA: "/Local" }, + "/Users/me", + await sdkWith(WINDOWS_TOOLS), + "win32", + ); + + expect(sdk).toEqual({ + adb: "/Local/Android/Sdk/platform-tools/adb.exe", + avdmanager: "/Local/Android/Sdk/cmdline-tools/latest/bin/avdmanager.bat", + emulator: "/Local/Android/Sdk/emulator/emulator.exe", + root: "/Local/Android/Sdk", + sdkmanager: "/Local/Android/Sdk/cmdline-tools/latest/bin/sdkmanager.bat", + }); + }); + + it.each([ + [ + "an SDK missing its emulator (incomplete)", + WINDOWS_TOOLS.filter((t) => !t.startsWith("emulator/")), + ], + [ + "an SDK of extensionless tools on Windows (incomplete)", + WINDOWS_TOOLS.map((t) => t.replace(/\.(bat|exe)$/, "")), + ], + ])("is undefined for %s", async (_case, tools) => { + await expect( + findAndroidSdk({ ANDROID_HOME: SDK }, "/Users/me", await sdkWith(tools), "win32"), + ).resolves.toBeUndefined(); + }); + + it("is undefined when no searched root exists (absent)", async () => { + await expect( + findAndroidSdk({ ANDROID_HOME: "/nowhere" }, "/Users/me", new MemoryFilesystem(), "darwin"), + ).resolves.toBeUndefined(); + }); +}); + +describe("runSdkTool", () => { + it("answers a tool that exits 0 with its output", async () => { + await expect( + runSdkTool(process.execPath, ["-e", 'process.stdout.write("ok")']), + ).resolves.toMatchObject({ stdout: "ok" }); + }); + + it("rejects a tool that exits non-zero, not killed", async () => { + await expect(runSdkTool(process.execPath, ["-e", "process.exit(3)"])).rejects.toMatchObject({ + killed: false, + }); + }); + + it("rejects a tool its timeout ended, killed", async () => { + await expect( + runSdkTool(process.execPath, ["-e", "setTimeout(() => {}, 60000)"], { timeout: 200 }), + ).rejects.toMatchObject({ killed: true }); + }); + + // why: avdmanager on Windows is a .bat under the SDK root, which may hold spaces; the slow tests reach it only through this helper. + it.runIf(process.platform === "win32")( + "runs a .bat under a path with spaces and hands it an argument with spaces intact", + async () => { + const directory = await mkdtemp(join(tmpdir(), "simlock sdk ")); + const printer = join(directory, "print-args.cjs"); + const tool = join(directory, "avd manager.bat"); + await writeFile(printer, "console.log(JSON.stringify(process.argv.slice(2)));\n"); + await writeFile( + tool, + ["@echo off", `"${process.execPath}" "${printer}" %*`, ""].join("\r\n"), + ); + try { + const result = await runSdkTool(tool, ["list", "with space"]); + + expect(JSON.parse(result.stdout)).toEqual(["list", "with space"]); + } finally { + await rm(directory, { force: true, recursive: true }); + } + }, + ); +}); diff --git a/e2e/helpers/test-android-sdk.ts b/e2e/helpers/test-android-sdk.ts new file mode 100644 index 000000000..b4258a79e --- /dev/null +++ b/e2e/helpers/test-android-sdk.ts @@ -0,0 +1,57 @@ +import { homedir } from "node:os"; + +import { type AndroidSdkPaths, locateSdk } from "../../src/drivers/android/testing.js"; +import { type Filesystem, NodeFilesystem, NodeProcessRunner } from "../../src/ports/index.js"; + +const runner = new NodeProcessRunner(); + +/** + * why: the slow Android tests skip exactly when the real driver could not start, so they ask the + * driver's own `locateSdk` (which knows `%LOCALAPPDATA%` and the `.exe`/`.bat` tools on Windows) + * rather than a lookup of their own that silently skips on a host it does not know. + */ +export async function findAndroidSdk( + env: Readonly>, + homeDirectory: string, + filesystem: Filesystem, + platform: NodeJS.Platform, +): Promise { + const location = await locateSdk(env, homeDirectory, filesystem, platform); + return location.kind === "complete" ? location.paths : undefined; +} + +export const ANDROID_SDK: AndroidSdkPaths | undefined = await findAndroidSdk( + process.env, + homedir(), + new NodeFilesystem(), + process.platform, +); + +export function requireAndroidSdk(): AndroidSdkPaths { + if (ANDROID_SDK === undefined) { + throw new Error("no complete Android SDK on this host: the test should have been skipped"); + } + return ANDROID_SDK; +} + +/** + * why: a `.bat` tool (`avdmanager` on Windows) runs through the ports' process runner, which owns + * how a batch file runs under cmd.exe and which arguments it refuses. As `execFile` did, a non-zero + * exit rejects, and a run its timeout ended rejects with `killed: true`. + */ +export async function runSdkTool( + tool: string, + args: readonly string[], + options: { readonly timeout?: number } = {}, +): Promise<{ readonly stdout: string; readonly stderr: string }> { + const result = await runner.run( + tool, + args, + options.timeout === undefined ? {} : { timeoutMs: options.timeout }, + ); + if (result.code === 0) return result; + throw Object.assign( + new Error(`${tool} ${args.join(" ")} exited ${String(result.code)}: ${result.stderr}`), + { killed: result.code === null }, + ); +} diff --git a/e2e/slow-android-lease-files.test.ts b/e2e/slow-android-lease-files.test.ts index dec43bebe..6ecb06ba5 100644 --- a/e2e/slow-android-lease-files.test.ts +++ b/e2e/slow-android-lease-files.test.ts @@ -1,16 +1,7 @@ -import { existsSync } from "node:fs"; -import { homedir } from "node:os"; -import { join } from "node:path"; import { describe, expect, it } from "vitest"; import { DEVICE_READY_MS, waitFor, withHttpDaemon } from "./helpers/index.js"; - -const ANDROID_HOME = - process.env.ANDROID_HOME ?? - process.env.ANDROID_SDK_ROOT ?? - join(homedir(), "Library/Android/sdk"); -const hasAndroidSdk = - existsSync(ANDROID_HOME) && existsSync(join(ANDROID_HOME, "platform-tools", "adb")); +import { ANDROID_SDK } from "./helpers/test-android-sdk.js"; const FILE_BYTES = 70_000_000; @@ -35,7 +26,7 @@ async function readSse(response: Response): Promise { } // why: only a real emulator proves that the folder a lease's upload went to is the folder `adb push` reads from, and that `adb pull` leaves a file the GET route serves, at a size no fake pipe is asked to carry. -describe.skipIf(!hasAndroidSdk)( +describe.skipIf(ANDROID_SDK === undefined)( "a lease's files on a real emulator", { tags: ["slow", "android"] }, () => { diff --git a/e2e/slow-android-smoke.test.ts b/e2e/slow-android-smoke.test.ts index 7e9d2463b..1f00ce792 100644 --- a/e2e/slow-android-smoke.test.ts +++ b/e2e/slow-android-smoke.test.ts @@ -2,26 +2,22 @@ import { execFile } from "node:child_process"; import { existsSync } from "node:fs"; import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises"; import { randomUUID } from "node:crypto"; -import { homedir, userInfo } from "node:os"; +import { tmpdir, userInfo } from "node:os"; import { dirname, join } from "node:path"; import { promisify } from "node:util"; import { describe, expect, it } from "vitest"; +import type { AndroidSdkPaths } from "../src/drivers/android/testing.js"; +import { defaultWorkerLockPath } from "../src/ports/index.js"; +import { ANDROID_SDK, requireAndroidSdk, runSdkTool } from "./helpers/test-android-sdk.js"; import { withDaemon } from "./helpers/index.js"; import { DEVICE_READY_MS, waitFor } from "./helpers/wait.js"; const execFileAsync = promisify(execFile); -const ANDROID_HOME = - process.env.ANDROID_HOME ?? - process.env.ANDROID_SDK_ROOT ?? - join(homedir(), "Library/Android/sdk"); -const hasAndroidSdk = - existsSync(ANDROID_HOME) && existsSync(join(ANDROID_HOME, "platform-tools", "adb")); /** Simlock's emulators live on Simlock's own adb server, so that is the one to ask. */ -async function adbDevices(serverPort: number): Promise { - const adb = join(ANDROID_HOME, "platform-tools", "adb"); - const { stdout } = await execFileAsync(adb, ["-P", String(serverPort), "devices"]).catch(() => ({ +async function adbDevices(sdk: AndroidSdkPaths, serverPort: number): Promise { + const { stdout } = await runSdkTool(sdk.adb, ["-P", String(serverPort), "devices"]).catch(() => ({ stdout: "", })); return stdout @@ -37,9 +33,8 @@ async function adbDevices(serverPort: number): Promise { * Android Studio, and `-crash-report-mode never` deletes the ones in the database it reads. * Returns the shared `completed/` folder of the installed emulator. */ -async function sharedCrashCompletedDir(): Promise { - const emulator = join(ANDROID_HOME, "emulator", "emulator"); - const { stdout } = await execFileAsync(emulator, ["-version"]); +async function sharedCrashCompletedDir(sdk: AndroidSdkPaths): Promise { + const { stdout } = await runSdkTool(sdk.emulator, ["-version"]); const version = /emulator version (\d+\.\d+\.\d+)/.exec(stdout)?.[1]; if (version === undefined) { throw new Error(`could not read the emulator version from: ${stdout}`); @@ -56,12 +51,62 @@ function firstMissingAncestor(path: string): string | undefined { return missing; } -async function avdManagerList(): Promise { - const avdmanager = join(ANDROID_HOME, "cmdline-tools", "latest", "bin", "avdmanager"); - const binary = existsSync(avdmanager) - ? avdmanager - : join(ANDROID_HOME, "tools", "bin", "avdmanager"); - const { stdout } = await execFileAsync(binary, ["list", "avd"]).catch(() => ({ stdout: "" })); +interface CrashDump { + readonly completedDir: string; + readonly createdRoot: string | undefined; + readonly id: string; + readonly planted: string; +} + +/** why: the planted dump needs crashpad's database xattrs, which only macOS's `xattr` writes; elsewhere there is no dump and the rest of the smoke test still runs. */ +async function crashDumpTarget(sdk: AndroidSdkPaths): Promise { + if (process.platform !== "darwin") return undefined; + const completedDir = await sharedCrashCompletedDir(sdk); + const id = randomUUID(); + return { + completedDir, + createdRoot: firstMissingAncestor(completedDir), + id, + planted: join(completedDir, `${id}.dmp`), + }; +} + +/** why: crashpad skips a report file without its database xattrs, so a plain file would never be read, let alone deleted. */ +async function plantCrashDump(dump: CrashDump | undefined): Promise { + if (dump === undefined) return; + await mkdir(dump.completedDir, { recursive: true }); + await writeFile(dump.planted, "simlock slow-lane crash dump marker"); + await execFileAsync("xattr", [ + "-w", + "org.chromium.crashpad.database.uuid", + dump.id, + dump.planted, + ]); + await execFileAsync("xattr", [ + "-w", + "org.chromium.crashpad.database.creation_time", + String(Math.floor(Date.now() / 1000)), + dump.planted, + ]); +} + +/** why: with no dump planted there is nothing the lease could have deleted. */ +function crashDumpKept(dump: CrashDump | undefined): boolean { + return dump === undefined || existsSync(dump.planted); +} + +async function removeCrashDump(dump: CrashDump | undefined): Promise { + if (dump === undefined) return; + await rm(dump.planted, { force: true }); + if (dump.createdRoot !== undefined) { + await rm(dump.createdRoot, { recursive: true, force: true }); + } +} + +async function avdManagerList(sdk: AndroidSdkPaths): Promise { + const { stdout } = await runSdkTool(sdk.avdmanager, ["list", "avd"]).catch(() => ({ + stdout: "", + })); return [...stdout.matchAll(/Name:\s*(\S+)/g)].map((match) => match[1] as string); } @@ -76,7 +121,7 @@ interface AndroidCatalogOutput { }[]; } -function checkCatalog(output: AndroidCatalogOutput): void { +function checkCatalog(sdk: AndroidSdkPaths, output: AndroidCatalogOutput): void { const android = output.platforms.find((platform) => platform.platform === "android"); if (android === undefined) { throw new Error("simlock catalog reported no android platform -- SDK discovery failed"); @@ -90,13 +135,7 @@ function checkCatalog(output: AndroidCatalogOutput): void { expect(images.length, "expected the installed system images to be listed").toBeGreaterThan(0); for (const image of images) { expect(android.runtimes).toContain(image.runtime); - const path = join( - ANDROID_HOME, - "system-images", - `android-${image.runtime}`, - image.tag, - image.abi, - ); + const path = join(sdk.root, "system-images", `android-${image.runtime}`, image.tag, image.abi); expect(existsSync(path), `listed image ${JSON.stringify(image)} is not installed`).toBe(true); } @@ -107,14 +146,15 @@ function checkCatalog(output: AndroidCatalogOutput): void { // Real emulator boots are slow and this SDK layout is host-specific, so this lane is // gated on an actually-discoverable Android SDK rather than just `process.platform`. -describe.skipIf(!hasAndroidSdk)( +describe.skipIf(ANDROID_SDK === undefined)( "Android smoke (real emulator/adb)", { tags: ["slow", "android"] }, () => { it( - "catalog lists Simlock's Pixel 9 first, a cold lease of Pixel 9 boots a real emulator with the library screen size and leaves a dump in the user's shared crash database alone, and a released emulator is deleted from the root and from avdmanager with no crash or false provenance finding", + "catalog lists Simlock's Pixel 9 first, a cold lease of Pixel 9 boots a real emulator with the library screen size and, on macOS, leaves a dump in the user's shared crash database alone, and a released emulator is deleted from the root and from avdmanager with no crash or false provenance finding", { timeout: 420_000 }, async () => { + const sdk = requireAndroidSdk(); const env = await withDaemon({ driver: "real", // why: a learned warm kind would re-boot the emulator the idle shutdown just stopped. @@ -124,29 +164,12 @@ describe.skipIf(!hasAndroidSdk)( if (adbServerPort === undefined) { throw new Error("the real-SDK lane must allocate its own adb server port"); } - const completedDir = await sharedCrashCompletedDir(); - // why: crashpad skips a report file without its database xattrs, so a plain file would never be read, let alone deleted. - const dumpId = randomUUID(); - const planted = join(completedDir, `${dumpId}.dmp`); - const createdRoot = firstMissingAncestor(completedDir); + const crashDump = await crashDumpTarget(sdk); try { - await mkdir(completedDir, { recursive: true }); - await writeFile(planted, "simlock slow-lane crash dump marker"); - await execFileAsync("xattr", [ - "-w", - "org.chromium.crashpad.database.uuid", - dumpId, - planted, - ]); - await execFileAsync("xattr", [ - "-w", - "org.chromium.crashpad.database.creation_time", - String(Math.floor(Date.now() / 1000)), - planted, - ]); + await plantCrashDump(crashDump); const catalog = await env.cli(["catalog", "--json", "--platform", "android"]); expect(catalog.code).toBe(0); - checkCatalog(catalog.json as AndroidCatalogOutput); + checkCatalog(sdk, catalog.json as AndroidCatalogOutput); const lease = await env.cli( [ @@ -190,7 +213,7 @@ describe.skipIf(!hasAndroidSdk)( // why: the lease is up, so no dialog blocked the boot, and the launch must have left the user's shared crash database alone. expect( - existsSync(planted), + crashDumpKept(crashDump), "the lease deleted a dump in the user's shared crash db", ).toBe(true); @@ -202,7 +225,7 @@ describe.skipIf(!hasAndroidSdk)( // deliberately keeps opaque outside drivers/android (architecture.md #2) -- // the grant names simlock's own AVD, not the adb serial, so this only // asserts that *an* emulator is actually online, not which one by serial. - const onlineSerials = await adbDevices(adbServerPort); + const onlineSerials = await adbDevices(sdk, adbServerPort); expect( onlineSerials.length, "expected at least one booted emulator visible to Simlock's own adb server", @@ -214,7 +237,7 @@ describe.skipIf(!hasAndroidSdk)( existsSync(join(avdFolder, "simlock.avd")), "expected the AVD to live inside Simlock's own device root", ).toBe(true); - const avdNames = await avdManagerList(); + const avdNames = await avdManagerList(sdk); expect( avdNames.includes("simlock") || avdNames.includes(avdName), "a Simlock AVD must not appear in the user's own AVD home", @@ -235,7 +258,7 @@ describe.skipIf(!hasAndroidSdk)( { timeout: 120_000, interval: 500, label: "device deleted after release" }, ); expect(existsSync(avdFolder), "the released emulator's folder is gone").toBe(false); - expect((await avdManagerList()).includes(avdName)).toBe(false); + expect((await avdManagerList(sdk)).includes(avdName)).toBe(false); // why: `doctor` must not crash on a deleted device nor report it as drift. const doctorReport = await env.cli(["doctor"]); @@ -262,7 +285,11 @@ describe.skipIf(!hasAndroidSdk)( expect(list.code).toBe(0); // why: ADR 0059: the worker with real drivers holds the machine's worker lock while it runs and frees it at its stop. - const lockFolder = join(`/tmp/simlock-${process.getuid?.() ?? 0}`, "worker.lock"); + const lockFolder = defaultWorkerLockPath( + process.platform, + process.getuid?.() ?? 0, + tmpdir(), + ); const owner = JSON.parse(await readFile(join(lockFolder, "owner.json"), "utf8")) as { folder: string; pid: number; @@ -277,10 +304,7 @@ describe.skipIf(!hasAndroidSdk)( label: "daemon stop left the worker lock behind", }); } finally { - await rm(planted, { force: true }); - if (createdRoot !== undefined) { - await rm(createdRoot, { recursive: true, force: true }); - } + await removeCrashDump(crashDump); await env .cli(["nuke", "--delete-devices", "--yes"], { timeout: 120_000 }) .catch(() => undefined); diff --git a/e2e/slow-android-stream.test.ts b/e2e/slow-android-stream.test.ts index a3ee823a1..06b5541c1 100644 --- a/e2e/slow-android-stream.test.ts +++ b/e2e/slow-android-stream.test.ts @@ -1,18 +1,9 @@ import { execFile } from "node:child_process"; -import { existsSync } from "node:fs"; -import { homedir } from "node:os"; -import { join } from "node:path"; import { describe, expect, it } from "vitest"; +import { ANDROID_SDK } from "./helpers/test-android-sdk.js"; import { DEVICE_READY_MS, deviceStreamUrl, waitFor, withHttpDaemon } from "./helpers/index.js"; -const ANDROID_HOME = - process.env.ANDROID_HOME ?? - process.env.ANDROID_SDK_ROOT ?? - join(homedir(), "Library/Android/sdk"); -const hasAndroidSdk = - existsSync(ANDROID_HOME) && existsSync(join(ANDROID_HOME, "platform-tools", "adb")); - const TAG = { alive: 0x06, description: 0x01, keyframe: 0x02, delta: 0x03, meta: 0x05 } as const; interface Frame { @@ -50,7 +41,7 @@ async function readFrames( return frames; } -describe.skipIf(!hasAndroidSdk)( +describe.skipIf(ANDROID_SDK === undefined)( "Android screen stream (real emulator)", { tags: ["slow", "android"] }, () => { @@ -257,10 +248,15 @@ describe.skipIf(!hasAndroidSdk)( expect(release.code, release.stderr).toBe(0); await Promise.race([draining, new Promise((resolve) => setTimeout(resolve, 15_000))]); expect(lastEnded, "the stream outlived its lease").toBe(true); - const hostShells = await new Promise((resolve) => { - execFile("pgrep", ["-fl", "[s]imlock-scrcpy-"], (_error, stdout) => resolve(stdout)); - }); - expect(hostShells, "a host adb shell for the capture outlived the lease").toBe(""); + // why: Windows has no pgrep, and src/ports has no way to list processes by command + // line (ProcessSupervisor reads one known pid), so this host-side check runs on macOS + // and Linux only; the device-side checks above still run everywhere. + if (process.platform !== "win32") { + const hostShells = await new Promise((resolve) => { + execFile("pgrep", ["-fl", "[s]imlock-scrcpy-"], (_error, stdout) => resolve(stdout)); + }); + expect(hostShells, "a host adb shell for the capture outlived the lease").toBe(""); + } } finally { await env .cli(["nuke", "--delete-devices", "--yes"], { timeout: 120_000 }) diff --git a/e2e/slow-android-tunnel.test.ts b/e2e/slow-android-tunnel.test.ts index 9b96ebba0..4b3c07315 100644 --- a/e2e/slow-android-tunnel.test.ts +++ b/e2e/slow-android-tunnel.test.ts @@ -1,8 +1,8 @@ import { execFile } from "node:child_process"; -import { existsSync, mkdtempSync } from "node:fs"; +import { mkdtempSync } from "node:fs"; import { createServer } from "node:http"; import { connect } from "node:net"; -import { homedir, tmpdir } from "node:os"; +import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterAll, beforeAll, describe, expect, it } from "vitest"; @@ -16,13 +16,7 @@ import { withSharedDaemon, type SharedTestEnv, } from "./helpers/index.js"; - -const ANDROID_HOME = - process.env.ANDROID_HOME ?? - process.env.ANDROID_SDK_ROOT ?? - join(homedir(), "Library/Android/sdk"); -const hasAndroidSdk = - existsSync(ANDROID_HOME) && existsSync(join(ANDROID_HOME, "platform-tools", "adb")); +import { ANDROID_SDK } from "./helpers/test-android-sdk.js"; const BODY = "simlock-tunnel-ok"; @@ -62,7 +56,7 @@ async function waitForWorkerJoined(gateway: SharedTestEnv): Promise { } // why: only a real emulator proves that `adb reverse` reaches the caller's loopback listener through the tunnel socket; the fast end-to-end test fakes the device side. -describe.skipIf(!hasAndroidSdk)( +describe.skipIf(ANDROID_SDK === undefined)( "simlock tunnel reverse on a real emulator against a lone worker", { tags: ["slow", "android"] }, () => { @@ -156,7 +150,7 @@ describe.skipIf(!hasAndroidSdk)( const FORWARD_IN = "/data/local/tmp/simlock-forward-in"; // why: through a gateway the holder's socket is relayed to the worker, and only a real emulator proves both directions of the device side there: `adb reverse` reaching the caller, and the host protocol reaching a device server. -describe.skipIf(!hasAndroidSdk)( +describe.skipIf(ANDROID_SDK === undefined)( "simlock tunnel reverse and forward on a real emulator through a gateway", { tags: ["slow", "android"] }, () => { @@ -336,7 +330,7 @@ describe.skipIf(!hasAndroidSdk)( { env: { ANDROID_ADB_SERVER_PORT: String(callerServerPort), - ANDROID_HOME, + ANDROID_HOME: ANDROID_SDK?.root, HOME: callerHome, }, }, @@ -394,7 +388,7 @@ describe.skipIf(!hasAndroidSdk)( }, ); -const ADB = join(ANDROID_HOME, "platform-tools", "adb"); +const ADB = ANDROID_SDK?.adb ?? "adb"; // why: the worker runs its own adb server (`adbServerPort`), which the user's default server cannot see; the rules a tunnel set live there. function workerAdb( @@ -426,7 +420,7 @@ onclick="fetch('/tapped?'+Date.now()).catch(function(){})">tap const CHROME = "com.android.chrome"; // why: a gateway relays a lease's input socket and tunnel socket to its worker side by side, and only a real emulator proves a relayed tap moves its screen and that a request it causes comes back through the relayed tunnel. -describe.skipIf(!hasAndroidSdk)( +describe.skipIf(ANDROID_SDK === undefined)( "input and tunnel together on a real emulator through a gateway", { tags: ["slow", "android"] }, () => { diff --git a/e2e/slow-baseline.test.ts b/e2e/slow-baseline.test.ts index cc75918a8..dea5c6834 100644 --- a/e2e/slow-baseline.test.ts +++ b/e2e/slow-baseline.test.ts @@ -1,22 +1,15 @@ import { existsSync } from "node:fs"; import { mkdir, readdir, writeFile } from "node:fs/promises"; -import { homedir } from "node:os"; import { join } from "node:path"; import { describe, expect, it } from "vitest"; import { IOS } from "./helpers/agent-device-targets.js"; +import { ANDROID_SDK } from "./helpers/test-android-sdk.js"; import { withDaemon } from "./helpers/index.js"; import type { TestEnv } from "./helpers/env.js"; import { iosDeviceSet, setDevices, sweepStaleDeviceSets } from "./helpers/ios-device-set.js"; import { DEVICE_READY_MS } from "./helpers/wait.js"; -const ANDROID_HOME = - process.env.ANDROID_HOME ?? - process.env.ANDROID_SDK_ROOT ?? - join(homedir(), "Library/Android/sdk"); -const hasAndroidSdk = - existsSync(ANDROID_HOME) && existsSync(join(ANDROID_HOME, "platform-tools", "adb")); - interface ListedBaseline { readonly name: string; readonly version: number; @@ -164,7 +157,7 @@ describe.skipIf(process.platform !== "darwin")( }, ); -describe.skipIf(!hasAndroidSdk)( +describe.skipIf(ANDROID_SDK === undefined)( "baseline save (real emulator)", { tags: ["slow", "android"] }, () => { diff --git a/e2e/slow-warm-pool.test.ts b/e2e/slow-warm-pool.test.ts index 57e919501..e9b557b43 100644 --- a/e2e/slow-warm-pool.test.ts +++ b/e2e/slow-warm-pool.test.ts @@ -1,11 +1,11 @@ import { execFile } from "node:child_process"; import { existsSync, readdirSync } from "node:fs"; import { readFile, writeFile } from "node:fs/promises"; -import { homedir } from "node:os"; import { join } from "node:path"; import { promisify } from "node:util"; import { describe, expect, it } from "vitest"; +import { ANDROID_SDK, requireAndroidSdk, runSdkTool } from "./helpers/test-android-sdk.js"; import { withDaemon, waitFor, type RecordedEvent, type TestEnv } from "./helpers/index.js"; import { iosDeviceSet, setDevices, sweepStaleDeviceSets } from "./helpers/ios-device-set.js"; @@ -20,10 +20,6 @@ const execFileAsync = promisify(execFile); * Run only through `scripts/slow-e2e.sh e2e/slow-warm-pool.test.ts`, never in CI. */ -const ANDROID_HOME = - process.env.ANDROID_HOME ?? - process.env.ANDROID_SDK_ROOT ?? - join(homedir(), "Library/Android/sdk"); /** The ABI an emulator runs natively on this host; an image of the other ABI is listed but cannot boot. */ const HOST_ABI = process.arch === "arm64" ? "arm64-v8a" : "x86_64"; @@ -107,16 +103,11 @@ async function installedIosRuntimes(): Promise { } } -/** Whether an emulator, adb and a system image of the host's ABI (`system-images///`) exist. */ +/** why: the daemon boots only an image of the host's ABI (`system-images///`) from the SDK it finds, so the image is looked for under that SDK's root. */ function installedAndroidImages(): boolean { - const root = join(ANDROID_HOME, "system-images"); - if ( - !existsSync(join(ANDROID_HOME, "emulator", "emulator")) || - !existsSync(join(ANDROID_HOME, "platform-tools", "adb")) || - !existsSync(root) - ) { - return false; - } + if (ANDROID_SDK === undefined) return false; + const root = join(ANDROID_SDK.root, "system-images"); + if (!existsSync(root)) return false; try { return readdirSync(root).some((api) => readdirSync(join(root, api)).some((tag) => existsSync(join(root, api, tag, HOST_ABI))), @@ -132,17 +123,20 @@ async function missingPlatform(): Promise { return "iOS is missing: no macOS host with an installed iOS runtime"; } if (!installedAndroidImages()) { - return `Android is missing: no emulator, adb and installed ${HOST_ABI} system image`; + return `Android is missing: no complete SDK with an installed ${HOST_ABI} system image`; } return undefined; } /** Simlock's emulators live on Simlock's own adb server, so that is the one to ask. */ async function onlineEmulators(adbServerPort: number): Promise { - const adb = join(ANDROID_HOME, "platform-tools", "adb"); - const { stdout } = await execFileAsync(adb, ["-P", String(adbServerPort), "devices"], { - timeout: QUERY_TIMEOUT, - }).catch((error: unknown) => { + const { stdout } = await runSdkTool( + requireAndroidSdk().adb, + ["-P", String(adbServerPort), "devices"], + { + timeout: QUERY_TIMEOUT, + }, + ).catch((error: unknown) => { // A timed-out adb is a hang to report, not "no emulator online". if ((error as { killed?: boolean }).killed === true) throw error; return { stdout: "" }; diff --git a/src/drivers/android/testing.ts b/src/drivers/android/testing.ts index 589769570..05a012f10 100644 --- a/src/drivers/android/testing.ts +++ b/src/drivers/android/testing.ts @@ -65,3 +65,5 @@ export { emptyLines, copyPathExpectation, } from "./test-emulator-host.js"; + +export { locateSdk, type AndroidSdkPaths } from "./sdk-paths.js";