Skip to content

Commit bca622a

Browse files
Merge remote-tracking branch 'origin/main' into fix/issue-31867
2 parents 7b8fbed + 202d5b5 commit bca622a

15 files changed

Lines changed: 451 additions & 85 deletions

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,8 @@ export interface DeviceOperations {
110110
readonly detail: string | undefined;
111111
/** Some Android virtual devices could not be listed; the rest are. */
112112
readonly androidDiscoveryIncomplete?: boolean;
113+
/** Platforms that could not be listed; their last known devices stay listed. */
114+
readonly incompletePlatforms?: ReadonlyArray<DevicePlatform>;
113115
},
114116
DeviceOperationError
115117
>;

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

Lines changed: 44 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,19 @@ import {
66
} from "@t3tools/contracts";
77
import * as Duration from "effect/Duration";
88
import * as Effect from "effect/Effect";
9+
import * as Option from "effect/Option";
910
import * as Schema from "effect/Schema";
1011
import { HttpClient, HttpClientError, HttpClientRequest, HttpClientResponse } from "effect/http";
1112

1213
import type { DeviceHostReady, DeviceOperations, HostDevice } from "./DeviceHost.ts";
1314

1415
const BOOT_TIMEOUT = Duration.minutes(3);
1516
const SCREENSHOT_TIMEOUT = Duration.seconds(20);
17+
// Let the hub's 30 s simctl timeout report its cause first.
18+
const LIST_TIMEOUT_SECONDS = 40;
19+
// expo-device-hub 0.19.1 reports a failed simulator listing only as text; its error ids are hashes.
20+
const SIMULATOR_LIST_FAILED =
21+
/^\[apple-utils\] (?:Failed to (?:run `xcrun simctl list devices|parse JSON output:|list devices:)|`xcrun simctl list devices --json` did not respond within )/;
1622

1723
const HubDevice = Schema.Struct({
1824
id: Schema.String,
@@ -63,30 +69,35 @@ export const makeDeviceHubOperations = (options: {
6369
readonly origin: string;
6470
readonly http: HttpClient.HttpClient;
6571
readonly run: DeviceHostReady["run"];
66-
/** Whether to list AVDs, which the hub does not report until they boot. */
67-
readonly androidAvailable: Effect.Effect<boolean>;
72+
/** Android gates listing AVDs, which the hub does not report until they boot. */
73+
readonly platformAvailable: (platform: DevicePlatform) => Effect.Effect<boolean>;
6874
}): DeviceOperations => {
6975
const { hostId, origin, run } = options;
7076
const httpClient = options.http.pipe(HttpClient.withScope);
7177

78+
const fetchJson = Effect.fn("DeviceHubOperations.fetchJson")(function* <A, I>(
79+
request: HttpClientRequest.HttpClientRequest,
80+
schema: Schema.Codec<A, I>,
81+
) {
82+
return yield* httpClient
83+
.execute(request)
84+
.pipe(
85+
Effect.flatMap(HttpClientResponse.filterStatusOk),
86+
Effect.flatMap(HttpClientResponse.schemaBodyJson(schema)),
87+
Effect.scoped,
88+
);
89+
});
90+
7291
const hubJson = <A, I>(
7392
request: HttpClientRequest.HttpClientRequest,
7493
schema: Schema.Codec<A, I>,
7594
operation: string,
7695
timeout: Duration.Input = Duration.seconds(15),
7796
) =>
78-
httpClient.execute(request).pipe(
79-
Effect.flatMap(HttpClientResponse.filterStatusOk),
80-
Effect.flatMap(HttpClientResponse.schemaBodyJson(schema)),
81-
Effect.scoped,
97+
fetchJson(request, schema).pipe(
8298
Effect.timeout(timeout),
8399
Effect.mapError(
84-
(cause) =>
85-
new DeviceOperationError({
86-
operation,
87-
reason: "request_failed",
88-
cause,
89-
}),
100+
(cause) => new DeviceOperationError({ operation, reason: "request_failed", cause }),
90101
),
91102
);
92103

@@ -106,13 +117,27 @@ export const makeDeviceHubOperations = (options: {
106117
);
107118

108119
const list: DeviceOperations["list"] = Effect.gen(function* () {
109-
const hubList = yield* hubJson(
120+
const listed = yield* fetchJson(
110121
HttpClientRequest.get(`${origin}/api/devices`),
111122
HubDeviceList,
112-
"list",
123+
).pipe(
124+
Effect.mapError(
125+
(cause) => new DeviceOperationError({ operation: "list", reason: "request_failed", cause }),
126+
),
127+
Effect.timeoutOption(Duration.seconds(LIST_TIMEOUT_SECONDS)),
113128
);
129+
if (Option.isNone(listed)) {
130+
return {
131+
devices: [],
132+
detail: `The device hub did not answer within ${LIST_TIMEOUT_SECONDS} seconds.`,
133+
incompletePlatforms: yield* Effect.filter(["ios", "android"] as const, (platform) =>
134+
options.platformAvailable(platform),
135+
),
136+
};
137+
}
138+
const hubList = listed.value;
114139
const devices: Array<HostDevice> = [...hubList.simulators, ...hubList.emulators];
115-
const androidAvailable = yield* options.androidAvailable;
140+
const androidAvailable = yield* options.platformAvailable("android");
116141
const warnings = hubList.errors?.filter(
117142
(error) =>
118143
// The host summary already explains a missing Android SDK; the hub's failed probes are noise.
@@ -155,10 +180,14 @@ export const makeDeviceHubOperations = (options: {
155180
}
156181
}
157182
}
183+
const simulatorsUnlisted =
184+
hubList.simulators.length === 0 &&
185+
(hubList.errors ?? []).some((error) => SIMULATOR_LIST_FAILED.test(error.message));
158186
return {
159187
devices,
160188
detail: details.join("\n") || undefined,
161189
androidDiscoveryIncomplete,
190+
...(simulatorsUnlisted ? { incompletePlatforms: ["ios"] as const } : {}),
162191
};
163192
}).pipe(Effect.withSpan("DeviceHubOperations.list"));
164193

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ it.effect("keeps hosts independent when serials collide and another host fails",
5252
origin: `http://${id}`,
5353
http,
5454
run,
55-
androidAvailable: Effect.succeed(true),
55+
platformAvailable: () => Effect.succeed(true),
5656
}),
5757
agentDevice: { baseUrl: `http://${id}`, token: "test", entryPath: "/agent-device" },
5858
releaseAgentSession: releaseAgentDeviceSession(http, {

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

Lines changed: 112 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ import * as Ref from "effect/Ref";
2929
import * as Schema from "effect/Schema";
3030
import * as Sink from "effect/Sink";
3131
import * as Stream from "effect/Stream";
32+
import * as TestClock from "effect/testing/TestClock";
3233
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
3334
import { HttpClient, HttpClientResponse } from "effect/http";
3435
import * as ServerConfig from "../config.ts";
@@ -59,7 +60,7 @@ it.effect.each([400, 500])(
5960
),
6061
),
6162
run: () => Effect.die("Screenshot does not run a command"),
62-
androidAvailable: Effect.succeed(false),
63+
platformAvailable: () => Effect.succeed(false),
6364
});
6465
const result = yield* operations
6566
.screenshot({
@@ -103,7 +104,9 @@ const fixture = Effect.fn("fixture")(function* (
103104
const devices: Array<Omit<DeviceSummary, "hostId">> = [];
104105
const discoveryErrors = yield* Ref.make<Array<{ message: string; error?: string }>>([]);
105106
const androidAvailable = yield* Ref.make(true);
107+
const iosAvailable = yield* Ref.make(true);
106108
const encoderResult = yield* Ref.make({ code: 0, stdout: " V....D libx264", stderr: "" });
109+
const listing = { hangs: false, requested: yield* Deferred.make<void>() };
107110
let booted = false;
108111
let shutDown = false;
109112
const connection = { online: true, kind: "local" as "local" | "ssh", failShutdown: false };
@@ -168,6 +171,11 @@ const fixture = Effect.fn("fixture")(function* (
168171
if (request.url.endsWith("/grid/api/start")) {
169172
return HttpClientResponse.fromWeb(request, Response.json({ ok: true }));
170173
}
174+
if (listing.hangs) {
175+
return yield* Deferred.succeed(listing.requested, undefined).pipe(
176+
Effect.andThen(Effect.never),
177+
);
178+
}
171179
return HttpClientResponse.fromWeb(
172180
request,
173181
Response.json({
@@ -205,7 +213,8 @@ const fixture = Effect.fn("fixture")(function* (
205213
origin: "http://device.test",
206214
http,
207215
run,
208-
androidAvailable: Ref.get(androidAvailable),
216+
platformAvailable: (platform) =>
217+
Ref.get(platform === "ios" ? iosAvailable : androidAvailable),
209218
}),
210219
...(options.endsDevices ? { endsDevices: true } : {}),
211220
},
@@ -330,6 +339,8 @@ const fixture = Effect.fn("fixture")(function* (
330339
encoderResult,
331340
discoveryErrors,
332341
androidAvailable,
342+
iosAvailable,
343+
listing,
333344
endDevice,
334345
};
335346
});
@@ -829,6 +840,101 @@ it.effect("keeps the cause from the hub's error in discovery warnings, without t
829840
}).pipe(Effect.scoped),
830841
);
831842

843+
it.effect(
844+
"keeps the last simulators while simctl cannot list them, and drops them once it can",
845+
() =>
846+
Effect.gen(function* () {
847+
const { service, devices, discoveryErrors } = yield* fixture();
848+
const simulator = {
849+
id: DeviceId.make("iphone"),
850+
name: "iPhone",
851+
platform: "ios",
852+
version: "iOS 26",
853+
booted: true,
854+
physical: false,
855+
} as const;
856+
devices.push(simulator, { ...simulator, id: DeviceId.make("pixel"), platform: "android" });
857+
yield* service.configure({ enabled: true, agentAccessEnabled: true });
858+
yield* service.agentReadinessIfSupported();
859+
devices.length = 0;
860+
yield* Ref.set(discoveryErrors, [{ message: simctlMessage }]);
861+
const failed = yield* service.list;
862+
expect(failed.devices.map((device) => device.id)).toEqual(["iphone", "Pixel_API_35"]);
863+
expect(failed.hostStatuses.local).toEqual({
864+
status: "ready",
865+
detail: simctlMessage,
866+
incompletePlatforms: ["ios"],
867+
});
868+
yield* service.agentReadinessIfSupported();
869+
expect((yield* service.state).hostStatuses.local).toEqual(failed.hostStatuses.local);
870+
yield* Ref.set(discoveryErrors, []);
871+
const recovered = yield* service.list;
872+
expect(recovered.devices.map((device) => device.id)).toEqual(["Pixel_API_35"]);
873+
expect(recovered.hostStatuses.local).toEqual({ status: "ready" });
874+
}).pipe(Effect.scoped),
875+
);
876+
877+
it.effect.each([
878+
{
879+
ios: true,
880+
android: true,
881+
incompletePlatforms: ["ios", "android"],
882+
kept: ["iphone", "Pixel_API_35"],
883+
},
884+
{ ios: true, android: false, incompletePlatforms: ["ios"], kept: ["iphone"] },
885+
{ ios: false, android: true, incompletePlatforms: ["android"], kept: ["Pixel_API_35"] },
886+
] as const)(
887+
"keeps the devices of listable platforms when the hub does not answer within 40 seconds (iOS: $ios, Android SDK: $android)",
888+
({ ios, android, incompletePlatforms, kept }) =>
889+
Effect.gen(function* () {
890+
const { service, devices, listing, androidAvailable, iosAvailable } = yield* fixture();
891+
yield* Ref.set(androidAvailable, android);
892+
yield* Ref.set(iosAvailable, ios);
893+
devices.push({
894+
id: DeviceId.make("iphone"),
895+
name: "iPhone",
896+
platform: "ios",
897+
version: "iOS 26",
898+
booted: true,
899+
physical: false,
900+
});
901+
yield* service.configure({ enabled: true });
902+
listing.hangs = true;
903+
const listed = yield* service.list.pipe(Effect.forkScoped);
904+
yield* Deferred.await(listing.requested);
905+
yield* TestClock.adjust("40 seconds");
906+
const timedOut = yield* Fiber.join(listed);
907+
expect(timedOut.devices.map((device) => device.id)).toEqual(kept);
908+
expect(timedOut.hostStatuses.local).toEqual({
909+
status: "ready",
910+
detail: "The device hub did not answer within 40 seconds.",
911+
incompletePlatforms,
912+
});
913+
}).pipe(Effect.scoped),
914+
);
915+
916+
it.effect("does not open a retained pre-boot entry when the post-boot listing is incomplete", () =>
917+
Effect.gen(function* () {
918+
const afterBoot = { run: Effect.void as Effect.Effect<void> };
919+
const android = yield* fixture(Effect.suspend(() => afterBoot.run));
920+
afterBoot.run = Effect.sync(() => {
921+
android.listing.hangs = true;
922+
});
923+
yield* android.service.configure({ enabled: true });
924+
const opening = yield* android.service
925+
.open({
926+
threadId: ThreadId.make("boot-timeout"),
927+
deviceId: "Pixel_API_35",
928+
platform: "android",
929+
})
930+
.pipe(Effect.flip, Effect.forkScoped);
931+
yield* Deferred.await(android.listing.requested);
932+
yield* TestClock.adjust("40 seconds");
933+
expect((yield* Fiber.join(opening))._tag).toBe("DeviceNotFoundError");
934+
expect((yield* android.service.state).sessions).toEqual([]);
935+
}).pipe(Effect.scoped),
936+
);
937+
832938
it.effect.each([
833939
{
834940
diagnostic: "Insufficient disk space at /private/user/path",
@@ -964,7 +1070,7 @@ it.effect.each(["shutdown", "close"] as const)(
9641070
origin: "http://device.test",
9651071
http,
9661072
run,
967-
androidAvailable: Effect.succeed(true),
1073+
platformAvailable: () => Effect.succeed(true),
9681074
}),
9691075
helpers: { serveSimAxSettings: null, serveSimCli: null },
9701076
run,
@@ -1126,7 +1232,7 @@ it.effect("leaves a session its host leases to every thread open when one thread
11261232
origin: "http://device.test",
11271233
http,
11281234
run,
1129-
androidAvailable: Effect.succeed(true),
1235+
platformAvailable: () => Effect.succeed(true),
11301236
}),
11311237
agentEndpoint: () =>
11321238
Effect.succeed({
@@ -1248,7 +1354,7 @@ it.effect.each([
12481354
origin: "http://device.test",
12491355
http,
12501356
run,
1251-
androidAvailable: Effect.succeed(true),
1357+
platformAvailable: () => Effect.succeed(true),
12521358
}),
12531359
helpers: { serveSimAxSettings: null, serveSimCli: null },
12541360
run,
@@ -1320,7 +1426,7 @@ it.effect.each([LOCAL_DEVICE_HOST_ID, "ssh-fixture"])(
13201426
origin: "http://device.test",
13211427
http,
13221428
run,
1323-
androidAvailable: Effect.succeed(true),
1429+
platformAvailable: () => Effect.succeed(true),
13241430
}),
13251431
helpers: { serveSimAxSettings: null, serveSimCli: null },
13261432
run,

0 commit comments

Comments
 (0)