Skip to content

Commit d3dca44

Browse files
authored
fix(device): launch older Android emulators and report boot failures (pingdotgg#22012)
1 parent bb86c24 commit d3dca44

12 files changed

Lines changed: 574 additions & 159 deletions

File tree

‎.macroscope/check-run-agents/effect-service-conventions.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ Review changed TypeScript for the conventions below. They apply when a pull requ
5757
- Define service failures with `Schema.TaggedError` and structured attributes: operation or stage, resource path or entity identifier, normalized category or status. Derive `message` from those attributes only. Never derive it from `cause`, `cause.message`, or a stringified defect, and do not add a `detail` field that copies `cause.message`.
5858
- When wrapping a real failure, keep the immediate underlying error as `cause` so the chain and stack survive. Make `cause` required if every construction wraps a failure. Pure validation or domain errors created without an underlying failure need no cause.
5959
- Keep attributes and log annotations safe and bounded: no raw wire payloads, command arguments or output, signed URLs, credentials, query strings, or arbitrary defect text. Preserve the exact value only as `cause`; expose normalized categories, lengths, counts, and safe URL protocol or hostname where useful.
60+
The documented exception is `DeviceBootError.diagnostics`: device hub launch commands and failure text are intentionally exposed to authorized device users and agents, capped at 2,000 characters and included in the error message. Do not apply this exception to other service errors.
6061
- At a translation boundary, pass through an already structured domain error when it is part of the target error channel; wrap only unknown or lower-level failures. Map failures where the context is known instead of wrapping a whole multi-step pipeline in one generic error.
6162
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Split into separate error classes when a discriminator drives caller control flow or the user-facing message; a discriminator used only for diagnostics may stay a field. Caller-visible messages exposed through HTTP, RPC, persisted state, or UI are behavior and must survive a structural refactor.
6263
- Do not add a helper whose only behavior is `(...args) => new SomeError({ ...args })`. Construct the error at the failure boundary. Keep a mapper only when it performs real normalization, passes through domain errors, or adds reusable context; when such a mapper belongs to the target error type, prefer a static factory on that class.

‎apps/server/src/device/DeviceService.test.ts‎

Lines changed: 107 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { describe, expect, it } from "@effect/vitest";
22
import {
33
DEFAULT_SERVER_SETTINGS,
4+
DeviceBootError,
45
DeviceId,
56
DeviceOperationError,
67
LOCAL_DEVICE_HOST_ID,
@@ -37,6 +38,8 @@ import { NodeRuntimeUnavailableError } from "@t3tools/shared/nodeRuntime";
3738
import * as DeviceService from "./DeviceService.ts";
3839

3940
const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
41+
const decodeBootError = Schema.decodeUnknownSync(Schema.fromJsonString(DeviceBootError));
42+
const encodeBootError = Schema.encodeSync(Schema.fromJsonString(DeviceBootError));
4043

4144
const baseState: DeviceServiceState = {
4245
hosts: [],
@@ -77,7 +80,7 @@ describe("DeviceService.stateStream", () => {
7780

7881
const fixture = Effect.fn("fixture")(function* (
7982
onBoot: Effect.Effect<void> = Effect.void,
80-
bootError?: string,
83+
bootError?: string | { error?: string; errors?: Array<{ message: string; error?: string }> },
8184
failListAfterShutdown = false,
8285
runtimeFailure?:
8386
| NodeRuntimeUnavailableError
@@ -92,6 +95,7 @@ const fixture = Effect.fn("fixture")(function* (
9295
const agentStops: string[] = [];
9396
const requests: string[] = [];
9497
const devices: Array<Omit<DeviceSummary, "hostId">> = [];
98+
const discoveryErrors = yield* Ref.make<Array<{ message: string; error?: string }>>([]);
9599
const encoderResult = yield* Ref.make({ code: 0, stdout: " V....D libx264", stderr: "" });
96100
let booted = false;
97101
let shutDown = false;
@@ -212,7 +216,12 @@ const fixture = Effect.fn("fixture")(function* (
212216
return HttpClientResponse.fromWeb(
213217
request,
214218
Response.json(
215-
bootError ? { ok: false, error: bootError } : { ok: true, serial: "emulator-5554" },
219+
bootError
220+
? {
221+
ok: false,
222+
...(typeof bootError === "string" ? { error: bootError } : bootError),
223+
}
224+
: { ok: true, serial: "emulator-5554" },
216225
),
217226
);
218227
}
@@ -222,6 +231,7 @@ const fixture = Effect.fn("fixture")(function* (
222231
return HttpClientResponse.fromWeb(
223232
request,
224233
Response.json({
234+
errors: yield* Ref.get(discoveryErrors),
225235
simulators: devices.filter((device) => device.platform === "ios"),
226236
emulators: [
227237
...devices.filter((device) => device.platform === "android"),
@@ -244,7 +254,17 @@ const fixture = Effect.fn("fixture")(function* (
244254
),
245255
),
246256
);
247-
return { service, starts, agentStarts, agentStops, requests, settings, devices, encoderResult };
257+
return {
258+
service,
259+
starts,
260+
agentStarts,
261+
agentStops,
262+
requests,
263+
settings,
264+
devices,
265+
encoderResult,
266+
discoveryErrors,
267+
};
248268
});
249269

250270
describe("device setup consent", () => {
@@ -506,6 +526,60 @@ describe("device discovery after server restart", () => {
506526
);
507527
});
508528

529+
const missingPlistMessage =
530+
"[apple-utils] Failed to read CoreSimulator plist at /Users/test/Library/Developer/CoreSimulator/Devices/deleted-simulator/device.plist:";
531+
532+
it.effect.each([
533+
{
534+
message: missingPlistMessage,
535+
error: "Error: ENOENT: no such file or directory, open 'device.plist'",
536+
ignored: true,
537+
},
538+
{
539+
message: missingPlistMessage,
540+
error: "Error: EACCES: permission denied, open 'device.plist'",
541+
ignored: false,
542+
},
543+
{ message: missingPlistMessage, error: undefined, ignored: false },
544+
{
545+
message: "[apple-utils] Failed to parse CoreSimulator device.plist:",
546+
error: "Invalid XML",
547+
ignored: false,
548+
},
549+
{
550+
message: "[apple-utils] Failed to list devices:",
551+
error: "Error: ENOENT: simctl missing",
552+
ignored: false,
553+
},
554+
])("handles discovery diagnostic: $error", ({ message, error, ignored }) =>
555+
Effect.gen(function* () {
556+
const { service, discoveryErrors } = yield* fixture();
557+
yield* Ref.set(discoveryErrors, [{ message, ...(error ? { error } : {}) }]);
558+
const state = yield* service.configure({ enabled: true });
559+
expect(state.hostStatus).toBe("ready");
560+
expect(state.devices.map((device) => device.id)).toEqual(["Pixel_API_35"]);
561+
expect(state.hostStatusDetail).toBe(ignored ? undefined : message);
562+
expect(state.hostStatuses.local?.detail).toBe(ignored ? undefined : message);
563+
}).pipe(Effect.scoped),
564+
);
565+
566+
it.effect("keeps other discovery warnings and clears them when only a deleted plist remains", () =>
567+
Effect.gen(function* () {
568+
const { service, discoveryErrors } = yield* fixture();
569+
const missing = {
570+
message: missingPlistMessage,
571+
error: "Error: ENOENT: no such file or directory",
572+
};
573+
yield* Ref.set(discoveryErrors, [missing, { message: "Android discovery failed." }]);
574+
const initial = yield* service.configure({ enabled: true });
575+
expect(initial.hostStatusDetail).toBe("Android discovery failed.");
576+
yield* Ref.set(discoveryErrors, [missing]);
577+
const refreshed = yield* service.list;
578+
expect(refreshed.hostStatusDetail).toBeUndefined();
579+
expect(refreshed.hostStatuses.local?.detail).toBeUndefined();
580+
}).pipe(Effect.scoped),
581+
);
582+
509583
it.effect.each([
510584
{
511585
diagnostic: "Insufficient disk space at /private/user/path",
@@ -518,7 +592,8 @@ it.effect.each([
518592
message: "did not become ready in time",
519593
},
520594
{
521-
diagnostic: "Unexpected failure: secret-token",
595+
diagnostic:
596+
"The emulator process exited with code 1.\nTry manually: emulator -avd Pixel_API_35",
522597
reason: "launch_failed",
523598
message: "could not start",
524599
},
@@ -535,7 +610,34 @@ it.effect.each([
535610
.pipe(Effect.flip);
536611
expect(error._tag).toBe("DeviceBootError");
537612
expect(error.message).toContain(message);
538-
expect(error.message).not.toContain(diagnostic);
613+
expect(error.message).toContain(diagnostic);
614+
expect((yield* service.state).bootingDevices).toEqual([]);
615+
}).pipe(Effect.scoped),
616+
);
617+
618+
it.effect("includes nested hub boot diagnostics and bounds them to 2,000 characters", () =>
619+
Effect.gen(function* () {
620+
const diagnostic = "Error: emulator binary missing\n" + "diagnostic output\n".repeat(200);
621+
const { service } = yield* fixture(Effect.void, {
622+
error: "Failed to spawn emulator",
623+
errors: [{ message: "Failed to launch emulator binary", error: diagnostic }],
624+
});
625+
yield* service.configure({ enabled: true });
626+
const error = yield* service
627+
.open({
628+
threadId: ThreadId.make("nested-boot-failure"),
629+
deviceId: "Pixel_API_35",
630+
platform: "android",
631+
})
632+
.pipe(Effect.flip);
633+
expect(error._tag).toBe("DeviceBootError");
634+
if (error._tag !== "DeviceBootError") return;
635+
const expected = `Failed to spawn emulator\n\nFailed to launch emulator binary\n\n${diagnostic}`;
636+
expect(error.diagnostics).toBe(`${expected.slice(0, 1_999)}…`);
637+
expect(error.diagnostics).toHaveLength(2_000);
638+
expect(error.message).toContain(error.diagnostics);
639+
const roundTrip = decodeBootError(encodeBootError(error));
640+
expect(roundTrip.message).toBe(error.message);
539641
expect((yield* service.state).bootingDevices).toEqual([]);
540642
}).pipe(Effect.scoped),
541643
);

‎apps/server/src/device/DeviceService.ts‎

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -96,13 +96,18 @@ const HubDevice = Schema.Struct({
9696
const HubDeviceList = Schema.Struct({
9797
simulators: Schema.Array(HubDevice),
9898
emulators: Schema.Array(HubDevice),
99-
errors: Schema.optional(Schema.Array(Schema.Struct({ message: Schema.String }))),
99+
errors: Schema.optional(
100+
Schema.Array(Schema.Struct({ message: Schema.String, error: Schema.optional(Schema.String) })),
101+
),
100102
});
101103
const HubActionResult = Schema.Struct({
102104
ok: Schema.Boolean,
103105
id: Schema.optional(Schema.String),
104106
serial: Schema.optional(Schema.String),
105107
error: Schema.optional(Schema.String),
108+
errors: Schema.optional(
109+
Schema.Array(Schema.Struct({ message: Schema.String, error: Schema.optional(Schema.String) })),
110+
),
106111
});
107112

108113
export interface DeviceScreenshot {
@@ -439,7 +444,16 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
439444
}
440445
}
441446
}
442-
return { devices, detail: list.errors?.map((error) => error.message).join("\n") || undefined };
447+
const warnings = list.errors?.filter(
448+
(error) =>
449+
// CoreSimulator can retain deleted devices; their optional usage timestamps are absent.
450+
!(
451+
error.message.startsWith("[apple-utils] Failed to read CoreSimulator plist at ") &&
452+
/\/CoreSimulator\/Devices\/[^/]+\/device\.plist:$/.test(error.message) &&
453+
/(?:^Error:\s*ENOENT:|\bcode:\s*['"]ENOENT['"])/.test(error.error ?? "")
454+
),
455+
);
456+
return { devices, detail: warnings?.map((error) => error.message).join("\n") || undefined };
443457
});
444458

445459
const refresh = Effect.fn("DeviceService.refresh")(function* (ready: DeviceReadiness) {
@@ -630,16 +644,29 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
630644
Effect.flatMap((request) => hubJson(request, HubActionResult, "boot", BOOT_TIMEOUT)),
631645
);
632646
if (!result.ok) {
647+
// Keep the hub's launch command and nested failure available to agents for recovery.
648+
const diagnostics = [
649+
result.error,
650+
...(result.errors ?? []).flatMap((error) => [error.message, error.error]),
651+
]
652+
.filter((text) => text?.trim())
653+
.join("\n\n");
633654
return yield* new DeviceBootError({
634655
hostId: ready.hostId,
635656
deviceId: device.id,
636657
reason: /insufficient.*(?:disk|space)|not enough.*(?:disk|space)|no space left/i.test(
637-
result.error ?? "",
658+
diagnostics,
638659
)
639660
? "disk_space"
640-
: /timed? out|timeout/i.test(result.error ?? "")
661+
: /timed? out|timeout/i.test(diagnostics)
641662
? "timeout"
642663
: "launch_failed",
664+
...(diagnostics
665+
? {
666+
diagnostics:
667+
diagnostics.length > 2_000 ? `${diagnostics.slice(0, 1_999)}…` : diagnostics,
668+
}
669+
: {}),
643670
cause: result,
644671
});
645672
}

‎apps/server/src/device/LocalDeviceHost.test.ts‎

Lines changed: 67 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -458,7 +458,73 @@ it.effect(
458458
Effect.provideService(FileSystem.FileSystem, FileSystem.makeNoop({})),
459459
);
460460
expect(missing.XDG_RUNTIME_DIR).toBeUndefined();
461-
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
461+
}).pipe(
462+
Effect.scoped,
463+
Effect.provide(Layer.provideMerge(ProcessRunner.layer, NodeServices.layer)),
464+
),
465+
);
466+
467+
it.effect.each([
468+
{
469+
name: "old SDK",
470+
front: "emulated webcam<N> none",
471+
back: "emulated virtualscene none",
472+
code: 0,
473+
extra: undefined,
474+
expected: "-camera-front emulated -camera-back emulated",
475+
},
476+
{
477+
name: "imagefile-capable SDK",
478+
front: "emulated imagefile:<path> none",
479+
back: "emulated imagefile:<path> none",
480+
code: 0,
481+
extra: undefined,
482+
expected: undefined,
483+
},
484+
{
485+
name: "user overrides",
486+
front: "emulated none",
487+
back: "emulated none",
488+
code: 0,
489+
extra: "-memory 4096 -camera-front none",
490+
expected: "-camera-front emulated -camera-back emulated -memory 4096 -camera-front none",
491+
},
492+
{
493+
name: "different camera capabilities",
494+
front: "emulated none",
495+
back: "emulated imagefile:<path> none",
496+
code: 0,
497+
extra: undefined,
498+
expected: "-camera-front emulated",
499+
},
500+
{
501+
name: "failed help probe",
502+
front: "emulated none",
503+
back: "emulated none",
504+
code: 1,
505+
extra: undefined,
506+
expected: undefined,
507+
},
508+
])("configures supported emulator cameras for $name", ({ front, back, code, extra, expected }) =>
509+
Effect.gen(function* () {
510+
const result = yield* LocalDeviceHost.__testing
511+
.hubEnvironment({ ANDROID_HOME: "/sdk", EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS: extra })
512+
.pipe(
513+
Effect.provideService(HostProcess.Platform, "darwin"),
514+
Effect.provideService(HostProcess.UserId, 1000),
515+
Effect.provideService(ProcessRunner.ProcessRunner, {
516+
run: (input) => {
517+
expect(input.command).toBe("/sdk/emulator/emulator");
518+
expect(input.args[0]).toMatch(/^-help-camera-(front|back)$/);
519+
return Effect.succeed(
520+
processOutput(code, input.args[0] === "-help-camera-front" ? front : back),
521+
);
522+
},
523+
}),
524+
Effect.provide(NodeServices.layer),
525+
);
526+
expect(result.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS).toBe(expected);
527+
}),
462528
);
463529

464530
it.live("limits hub discovery to Android unless the host is a Mac", () =>

‎apps/server/src/device/LocalDeviceHost.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -208,6 +208,40 @@ const hubEnvironment = Effect.fn("LocalDeviceHost.hubEnvironment")(function* (
208208
const env: NodeJS.ProcessEnv = { ...environment, FORCE_COLOR: "0", NO_COLOR: "1" };
209209
const platform = yield* HostProcess.Platform;
210210
const uid = yield* HostProcess.UserId;
211+
if (env.ANDROID_HOME) {
212+
const path = yield* Path.Path;
213+
const runner = yield* ProcessRunner.ProcessRunner;
214+
const emulator = path.join(
215+
env.ANDROID_HOME,
216+
"emulator",
217+
platform === "win32" ? "emulator.exe" : "emulator",
218+
);
219+
const cameraArgs = yield* Effect.forEach(["front", "back"], (facing) =>
220+
runner
221+
.run({
222+
command: emulator,
223+
args: [`-help-camera-${facing}`],
224+
env,
225+
timeout: Duration.seconds(5),
226+
})
227+
.pipe(
228+
Effect.map((result) => {
229+
const help = `${result.stdout}\n${result.stderr}`;
230+
// The hub wires imagefile cameras unconditionally; older SDK emulators reject that mode.
231+
return result.code === 0 && /\bemulated\b/.test(help) && !/\bimagefile\b/.test(help)
232+
? `-camera-${facing} emulated`
233+
: "";
234+
}),
235+
Effect.orElseSucceed(() => ""),
236+
),
237+
);
238+
const overrides = cameraArgs.filter(Boolean).join(" ");
239+
if (overrides) {
240+
env.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS = [overrides, env.EXPO_DEVICE_HUB_EMULATOR_EXTRA_ARGS]
241+
.filter(Boolean)
242+
.join(" ");
243+
}
244+
}
211245
if (platform === "linux" && env.XDG_RUNTIME_DIR === undefined && uid !== undefined) {
212246
// SSH sessions may omit the directory where the emulator publishes its gRPC token.
213247
const runtimeDir = `/run/user/${uid}`;
@@ -409,6 +443,8 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {
409443
stderr: "pipe",
410444
env: yield* hubEnvironment(hostEnvironment).pipe(
411445
Effect.provideService(FileSystem.FileSystem, fs),
446+
Effect.provideService(Path.Path, path),
447+
Effect.provideService(ProcessRunner.ProcessRunner, runner),
412448
Effect.provideService(HostProcess.Platform, hostPlatform),
413449
),
414450
},

0 commit comments

Comments
 (0)