Skip to content

Commit 3feaf42

Browse files
committed
fix(device): report emulator launch diagnostics and dismiss stale warnin
- Include bounded boot failure details in device errors. - Ignore deleted simulator plist warnings and keep device notices dismissible.
1 parent 54983e3 commit 3feaf42

6 files changed

Lines changed: 445 additions & 154 deletions

File tree

‎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/mcp/McpDeviceToolkit.test.ts‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { expect, it } from "@effect/vitest";
22
import * as NodeServices from "@effect/platform-node/NodeServices";
33
import {
4+
DeviceBootError,
45
DeviceHostUnavailableError,
56
DeviceId,
67
EnvironmentId,
@@ -124,6 +125,45 @@ const layerTest = McpHttpServer.layerDeviceToolkit.pipe(
124125
Layer.provide(NodeServices.layer),
125126
);
126127

128+
it.effect("returns the complete bounded launch diagnostics to the agent", () => {
129+
const diagnostics =
130+
"Emulator exited with code 1.\nTry manually: emulator -avd TestPhone\n" + "x".repeat(1_930);
131+
const failure = new DeviceBootError({
132+
hostId: "local",
133+
deviceId: "UDID-1",
134+
reason: "launch_failed",
135+
diagnostics: diagnostics.slice(0, 2_000),
136+
cause: { ok: false, error: diagnostics },
137+
});
138+
const failedDevices = Layer.mock(DeviceService.DeviceService)({
139+
list: Effect.succeed(state),
140+
agentTarget: () => Effect.succeed([]),
141+
open: () => Effect.fail(failure),
142+
});
143+
return Effect.gen(function* () {
144+
const server = yield* McpServer.McpServer;
145+
const result = yield* server
146+
.callTool({ name: "device_open", arguments: { platform: "ios" } })
147+
.pipe(
148+
Effect.provideService(McpInvocationContext.McpInvocationContext, invocation(["device"])),
149+
Effect.provideService(McpSchema.McpServerClient, client),
150+
);
151+
expect(result.isError).toBe(true);
152+
expect(result.content).toEqual([{ type: "text", text: failure.message }]);
153+
}).pipe(
154+
Effect.scoped,
155+
Effect.provide(
156+
McpHttpServer.layerDeviceToolkit.pipe(
157+
Layer.provideMerge(McpServer.McpServer.layer),
158+
Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),
159+
Layer.provide(failedDevices),
160+
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-boot-error-test-" })),
161+
Layer.provide(NodeServices.layer),
162+
),
163+
),
164+
);
165+
});
166+
127167
it.effect("registers the device tools and returns the screenshot as image content", () =>
128168
Effect.scoped(
129169
Effect.gen(function* () {

0 commit comments

Comments
 (0)