From b29886950e1e7357128f15d5a6418ab78d68928e Mon Sep 17 00:00:00 2001 From: Jackson Miller Date: Mon, 23 Nov 2026 16:18:49 -0500 Subject: [PATCH 1/2] fix(server): closing an exited Android emulator with shutdown no longer leaves its session open Co-Authored-By: Claude Opus 5.5 --- apps/server/src/device/DeviceHubOperations.ts | 40 +++++++- apps/server/src/device/DeviceService.test.ts | 98 ++++++++++++++++++- 2 files changed, 132 insertions(+), 6 deletions(-) diff --git a/apps/server/src/device/DeviceHubOperations.ts b/apps/server/src/device/DeviceHubOperations.ts index 3a1bcee7a8e2a..9dbc7d6ca64b4 100644 --- a/apps/server/src/device/DeviceHubOperations.ts +++ b/apps/server/src/device/DeviceHubOperations.ts @@ -14,6 +14,9 @@ import type { DeviceHostReady, DeviceOperations, HostDevice } from "./DeviceHost const BOOT_TIMEOUT = Duration.minutes(3); const SCREENSHOT_TIMEOUT = Duration.seconds(20); +// The hub's Android shutdown waits up to 30 s for the emulator to leave adb after the kill. +const ANDROID_SHUTDOWN_TIMEOUT = Duration.seconds(45); +const ADB_DEVICES_TIMEOUT = Duration.seconds(10); // Let the hub's 30 s simctl timeout report its cause first. const LIST_TIMEOUT_SECONDS = 40; // expo-device-hub 0.19.1 reports a failed simulator listing only as text; its error ids are hashes. @@ -296,11 +299,26 @@ export const makeDeviceHubOperations = (options: { ? attachIosStream(device.id, "open").pipe(Effect.asVoid) : Effect.void; + // The hub rejects a shutdown once `adb emu kill` has no serial left, as on a retry after an + // exit that outlasted the request. Like the hub, count an emulator as off once adb no longer + // lists its serial in any state. + const emulatorExited = (serial: string) => + /^emulator-\d+$/.test(serial) + ? run("adb", ["devices"], { timeoutMs: Duration.toMillis(ADB_DEVICES_TIMEOUT) }).pipe( + Effect.map( + ({ code, stdout }) => + code === 0 && + !stdout.split(/\r?\n/).some((line) => line.trim().split(/\s+/)[0] === serial), + ), + Effect.orElseSucceed(() => false), + ) + : Effect.succeed(false); + const shutdown: DeviceOperations["shutdown"] = Effect.fn("DeviceHubOperations.shutdown")( function* (device) { - const postShutdown = (path: string, body: Record) => + const postShutdown = (path: string, body: Record, timeout?: Duration.Input) => postJson(path, body, "shutdown").pipe( - Effect.flatMap((request) => hubJson(request, HubActionResult, "shutdown")), + Effect.flatMap((request) => hubJson(request, HubActionResult, "shutdown", timeout)), Effect.flatMap((result) => result.ok ? Effect.void @@ -329,7 +347,23 @@ export const makeDeviceHubOperations = (options: { ), ), ) - : postShutdown("/api/devices/shutdown", { platform: device.platform, id: device.id }); + : postShutdown( + "/api/devices/shutdown", + { platform: device.platform, id: device.id }, + ANDROID_SHUTDOWN_TIMEOUT, + ).pipe( + Effect.catch((cause) => + emulatorExited(device.id).pipe( + Effect.flatMap((exited) => + exited + ? Effect.logInfo("Android emulator has exited", { + deviceId: device.id, + }) + : Effect.fail(cause), + ), + ), + ), + ); }, ); diff --git a/apps/server/src/device/DeviceService.test.ts b/apps/server/src/device/DeviceService.test.ts index 00e942f1e6df5..c16116e631e10 100644 --- a/apps/server/src/device/DeviceService.test.ts +++ b/apps/server/src/device/DeviceService.test.ts @@ -18,6 +18,7 @@ import { SshCommandError } from "@t3tools/ssh/errors"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; import * as Fiber from "effect/Fiber"; import * as FileSystem from "effect/FileSystem"; import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver"; @@ -192,7 +193,14 @@ const fixture = Effect.fn("fixture")(function* ( const listing = { hangs: false, requested: yield* Deferred.make() }; let booted = false; let shutDown = false; - const connection = { online: true, kind: "local" as "local" | "ssh", failShutdown: false }; + const connection = { + online: true, + kind: "local" as "local" | "ssh", + failShutdown: false, + shutdownDelay: undefined as Duration.Input | undefined, + adbDevices: undefined as { code: number; stdout: string; stderr: string } | undefined, + }; + const shutdownRequested = yield* Deferred.make(); const http = HttpClient.make((request) => Effect.gen(function* () { requests.push(request.url); @@ -230,6 +238,8 @@ const fixture = Effect.fn("fixture")(function* ( return HttpClientResponse.fromWeb(request, new Response(yield* Ref.get(screenshotBody))); } if (request.url.endsWith("/shutdown")) { + yield* Deferred.succeed(shutdownRequested, undefined); + if (connection.shutdownDelay !== undefined) yield* Effect.sleep(connection.shutdownDelay); if (connection.failShutdown) return HttpClientResponse.fromWeb(request, Response.json({ ok: false })); shutDown = true; @@ -283,10 +293,19 @@ const fixture = Effect.fn("fixture")(function* ( ); }), ); - const run = (command: string) => + const run = (command: string, args: ReadonlyArray) => command === "emulator" ? Effect.succeed({ code: 0, stdout: "Pixel_API_35\n", stderr: "" }) - : Ref.get(encoderResult); + : command === "adb" && args.join(" ") === "devices" + ? Effect.sync( + () => + connection.adbDevices ?? { + code: 0, + stdout: `List of devices attached\n${booted ? "emulator-5554\tdevice\n" : ""}`, + stderr: "", + }, + ) + : Ref.get(encoderResult); const ready: DeviceHost.DeviceHostReady = { nodePath: process.execPath, hub: { origin: "http://device.test" }, @@ -426,6 +445,7 @@ const fixture = Effect.fn("fixture")(function* ( iosAvailable, listing, endDevice, + shutdownRequested, }; }); @@ -1574,6 +1594,78 @@ it.effect.each([ }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true }))), ); +describe("Android close with shutdown", () => { + const openEmulator = Effect.fn("openEmulator")(function* () { + const harness = yield* fixture(); + yield* harness.service.configure({ enabled: true }); + const threadId = ThreadId.make("android-close"); + const session = yield* harness.service.open({ + threadId, + deviceId: "Pixel_API_35", + platform: "android", + }); + expect(session.deviceId).toBe("emulator-5554"); + return { ...harness, threadId }; + }); + + it.effect("closes the session on a retry once the emulator has exited", () => + Effect.gen(function* () { + const { service, connection, endDevice, threadId } = yield* openEmulator(); + // The hub's `adb emu kill` fails once the serial is gone, so every attempt is rejected. + connection.failShutdown = true; + const first = yield* Effect.exit(service.close({ threadId, shutdown: true })); + expect(Exit.isFailure(first)).toBe(true); + expect((yield* service.state).sessions).toHaveLength(1); + + endDevice(); + yield* service.close({ threadId, shutdown: true }); + expect((yield* service.state).sessions).toEqual([]); + }), + ); + + it.effect.each([ + { + adb: "lists it offline", + result: { code: 0, stdout: "List of devices attached\nemulator-5554\toffline\n", stderr: "" }, + }, + { adb: "fails", result: { code: 1, stdout: "", stderr: "adb: no server" } }, + ])("keeps the session after a rejected shutdown when adb $adb", ({ result }) => + Effect.gen(function* () { + const { service, connection, threadId } = yield* openEmulator(); + connection.failShutdown = true; + connection.adbDevices = result; + const exit = yield* Effect.exit(service.close({ threadId, shutdown: true })); + expect(Exit.isFailure(exit)).toBe(true); + expect((yield* service.state).sessions).toHaveLength(1); + }), + ); + + it.effect("waits for an emulator the hub takes longer than 15 seconds to see exit", () => + Effect.gen(function* () { + const { service, connection, shutdownRequested, threadId } = yield* openEmulator(); + // The hub allows the emulator 30 seconds to leave adb after the kill. + connection.shutdownDelay = Duration.seconds(25); + const closing = yield* Effect.forkChild(service.close({ threadId, shutdown: true })); + yield* Deferred.await(shutdownRequested); + yield* TestClock.adjust(Duration.seconds(25)); + expect(Exit.isSuccess(yield* Fiber.await(closing))).toBe(true); + expect((yield* service.state).sessions).toEqual([]); + }), + ); + + it.effect("still fails a rejected shutdown of an AVD that adb cannot list by name", () => + Effect.gen(function* () { + const { service, connection } = yield* fixture(); + yield* service.configure({ enabled: true }); + connection.failShutdown = true; + const exit = yield* Effect.exit( + service.shutdown({ deviceId: DeviceId.make("Pixel_API_35"), platform: "android" }), + ); + expect(Exit.isFailure(exit)).toBe(true); + }), + ); +}); + it.effect.each([LOCAL_DEVICE_HOST_ID, "ssh-fixture"])( "retains hub inventory on %s when AVD enumeration fails and recovers on retry", (hostId) => From 6624d6afd62160d0b6491d49efc0cf495969a033 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Tue, 24 Nov 2026 02:17:14 +0000 Subject: [PATCH 2/2] test(server): drop the redundant AVD-name shutdown test Co-Authored-By: Claude Opus 5.5 --- apps/server/src/device/DeviceService.test.ts | 12 ------------ 1 file changed, 12 deletions(-) diff --git a/apps/server/src/device/DeviceService.test.ts b/apps/server/src/device/DeviceService.test.ts index c16116e631e10..972a9a2b150b2 100644 --- a/apps/server/src/device/DeviceService.test.ts +++ b/apps/server/src/device/DeviceService.test.ts @@ -1652,18 +1652,6 @@ describe("Android close with shutdown", () => { expect((yield* service.state).sessions).toEqual([]); }), ); - - it.effect("still fails a rejected shutdown of an AVD that adb cannot list by name", () => - Effect.gen(function* () { - const { service, connection } = yield* fixture(); - yield* service.configure({ enabled: true }); - connection.failShutdown = true; - const exit = yield* Effect.exit( - service.shutdown({ deviceId: DeviceId.make("Pixel_API_35"), platform: "android" }), - ); - expect(Exit.isFailure(exit)).toBe(true); - }), - ); }); it.effect.each([LOCAL_DEVICE_HOST_ID, "ssh-fixture"])(