Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import {
3 DEFAULT_SERVER_SETTINGS,
4 DeviceBootError,
5 DeviceId,
6 DeviceOperationError,
7 LOCAL_DEVICE_HOST_ID,
8 ThreadId,
9 type DeviceSummary,
10 type ServerSettings as Settings,
11 type SshDeviceHostConfig,
12} from "@t3tools/contracts";
13import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
14import * as NodeServices from "@effect/platform-node/NodeServices";
15import * as NetService from "@t3tools/shared/Net";
16import * as Effect from "effect/Effect";
17import * as Exit from "effect/Exit";
18import * as Deferred from "effect/Deferred";
19import * as Fiber from "effect/Fiber";
20import * as FileSystem from "effect/FileSystem";
21import * as Layer from "effect/Layer";
22import * as Option from "effect/Option";
23import * as PubSub from "effect/PubSub";
24import * as Queue from "effect/Queue";
25import * as Ref from "effect/Ref";
26import * as Schema from "effect/Schema";
27import * as Sink from "effect/Sink";
28import * as Stream from "effect/Stream";
29import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
30import { HttpClient, HttpClientResponse } from "effect/http";
31import * as ServerConfig from "../config.ts";
32import * as ProcessRunner from "../processRunner.ts";
33import * as ServerSettings from "../serverSettings.ts";
34import * as DeviceHost from "./DeviceHost.ts";
35import { makeDeviceHubOperations } from "./DeviceHubOperations.ts";
36import { NodeRuntimeUnavailableError } from "@t3tools/shared/nodeRuntime";
37
38import * as DeviceService from "./DeviceService.ts";
39import { agentDeviceSession } from "./AgentDeviceTarget.ts";
40
41const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
42const decodeBootError = Schema.decodeUnknownSync(Schema.fromJsonString(DeviceBootError));
43const encodeBootError = Schema.encodeSync(Schema.fromJsonString(DeviceBootError));
44
45const fixture = Effect.fn("fixture")(function* (
46 onBoot: Effect.Effect<void> = Effect.void,
47 bootError?: string | { error?: string; errors?: Array<{ message: string; error?: string }> },
48 failListAfterShutdown = false,
49 runtimeFailure?:
50 | NodeRuntimeUnavailableError
51 | DeviceHost.DeviceHostError
52 | DeviceHost.AgentDeviceStartError,
53 inspectError = false,
54 installTool?: Parameters<typeof DeviceService.makeWithHosts>[3],
55 options: { readonly endsDevices?: boolean } = {},
56) {
57 const settings = yield* Ref.make(DEFAULT_SERVER_SETTINGS);
58 const starts: string[] = [];
59 const agentStarts: string[] = [];
60 const agentStops: string[] = [];
61 const requests: string[] = [];
62 const devices: Array<Omit<DeviceSummary, "hostId">> = [];
63 const discoveryErrors = yield* Ref.make<Array<{ message: string; error?: string }>>([]);
64 const androidAvailable = yield* Ref.make(true);
65 const encoderResult = yield* Ref.make({ code: 0, stdout: " V....D libx264", stderr: "" });
66 let booted = false;
67 let shutDown = false;
68 const http = HttpClient.make((request) =>
69 Effect.gen(function* () {
70 requests.push(request.url);
71 if (request.url.includes("/api/screenshot")) {
72 return HttpClientResponse.fromWeb(request, new Response(new Uint8Array([137, 80, 78, 71])));
73 }
74 if (request.url.endsWith("/shutdown")) {
75 shutDown = true;
76 booted = false;
77 return HttpClientResponse.fromWeb(request, Response.json({ ok: true }));
78 }
79 if (shutDown && failListAfterShutdown) {
80 return HttpClientResponse.fromWeb(request, new Response("Discovery busy", { status: 503 }));
81 }
82 if (request.url.endsWith("/boot")) {
83 yield* onBoot;
84 booted = true;
85 return HttpClientResponse.fromWeb(
86 request,
87 Response.json(
88 bootError
89 ? { ok: false, ...(typeof bootError === "string" ? { error: bootError } : bootError) }
90 : { ok: true, serial: "emulator-5554" },
91 ),
92 );
93 }
94 if (request.url.endsWith("/grid/api/start")) {
95 return HttpClientResponse.fromWeb(request, Response.json({ ok: true }));
96 }
97 return HttpClientResponse.fromWeb(
98 request,
99 Response.json({
100 errors: yield* Ref.get(discoveryErrors),
101 simulators: devices.filter((device) => device.platform === "ios"),
102 emulators: [
103 ...devices.filter((device) => device.platform === "android"),
104 ...(booted
105 ? [
106 {
107 id: "emulator-5554",
108 name: "Pixel_API_35",
109 platform: "android",
110 version: "Android 15",
111 booted: true,
112 physical: false,
113 },
114 ]
115 : []),
116 ],
117 }),
118 );
119 }),
120 );
121 const run = (command: string) =>
122 command === "emulator"
123 ? Effect.succeed({ code: 0, stdout: "Pixel_API_35\n", stderr: "" })
124 : Ref.get(encoderResult);
125 const ready: DeviceHost.DeviceHostReady = {
126 nodePath: process.execPath,
127 hub: { origin: "http://device.test" },
128 devices: {
129 ...makeDeviceHubOperations({
130 hostId: LOCAL_DEVICE_HOST_ID,
131 origin: "http://device.test",
132 http,
133 run,
134 androidAvailable: Ref.get(androidAvailable),
135 }),
136 ...(options.endsDevices ? { endsDevices: true } : {}),
137 },
138 helpers: { serveSimAxSettings: null, serveSimCli: null },
139 run,
140 };
141 const host: DeviceHost.DeviceHost["Service"] = {
142 ...(inspectError
143 ? {
144 inspect: Effect.fail(
145 new DeviceHost.DeviceHostError({
146 hostId: LOCAL_DEVICE_HOST_ID,
147 step: "probe",
148 cause: new Error("offline"),
149 }),
150 ),
151 }
152 : {}),
153 id: LOCAL_DEVICE_HOST_ID,
154 label: "This machine",
155 summary: Effect.succeed({
156 id: LOCAL_DEVICE_HOST_ID,
157 kind: "local",
158 label: "Test server",
159 platforms: [
160 { platform: "android", available: true },
161 { platform: "ios", available: true },
162 ],
163 hubInstalled: true,
164 agentDeviceInstalled: false,
165 }),
166 platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
167 ensureReady: (onPhase) =>
168 Effect.gen(function* () {
169 if (runtimeFailure && runtimeFailure._tag !== "AgentDeviceStartError")
170 return yield* runtimeFailure;
171 starts.push("start");
172 yield* onPhase("installing", "Updating device hub from 0.9.0 to 0.10.1…");
173 return ready;
174 }),
175 ensureAgentReady: (onPhase) =>
176 Effect.gen(function* () {
177 if (runtimeFailure) return yield* runtimeFailure;
178 agentStarts.push("start");
179 yield* onPhase("starting");
180 return {
181 ...ready,
182 agentDevice: { baseUrl: "http://agent.test", token: "test", entryPath: "/agent" },
183 };
184 }),
185 current: Effect.succeed(null),
186 stopAgent: Effect.sync(() => {
187 agentStops.push("stop");
188 }),
189 stop: Effect.sync(() => {
190 starts.push("stop");
191 }),
192 };
193 const service = yield* DeviceService.makeWithHosts(
194 new Map([[host.id, host]]),
195 undefined,
196 undefined,
197 installTool,
198 ).pipe(
199 Effect.provide(NodeCrypto.layer),
200 Effect.provideService(DeviceHost.DeviceHost, host),
201 Effect.provideService(
202 ServerSettings.ServerSettingsService,
203 ServerSettings.ServerSettingsService.of({
204 updateProviderInstance: () => Effect.die("Unexpected provider mutation"),
205 withSettingsSnapshot: (use) => Effect.flatMap(Ref.get(settings), use),
206 start: Effect.void,
207 ready: Effect.void,
208 getSettings: Ref.get(settings),
209 updateSettings: (patch) =>
210 Ref.updateAndGet(settings, (current) => ({
211 ...current,
212 enableDeviceSupport: patch.enableDeviceSupport ?? current.enableDeviceSupport,
213 enableAgentDeviceAccess:
214 patch.enableAgentDeviceAccess ?? current.enableAgentDeviceAccess,
215 deviceOnboardingCompleted:
216 patch.deviceOnboardingCompleted ?? current.deviceOnboardingCompleted,
217 })),
218 streamChanges: Stream.empty,
219 subscribeChanges: Effect.succeed(Stream.empty),
220 }),
221 ),
222 );
223 // The host ending a device on its own, as EAS does at a session's limits.
224 const endDevice = () => {
225 booted = false;
226 };
227 return {
228 service,
229 starts,
230 agentStarts,
231 agentStops,
232 requests,
233 settings,
234 devices,
235 encoderResult,
236 discoveryErrors,
237 androidAvailable,
238 endDevice,
239 };
240});
241
242describe("device setup consent", () => {
243 it.effect("exposes daemon startup diagnostics through agent readiness and host status", () =>
244 Effect.gen(function* () {
245 const startupError = new DeviceHost.AgentDeviceStartError({
246 hostId: LOCAL_DEVICE_HOST_ID,
247 stateDir: "/test/device/agent-device",
248 exitCode: 1,
249 reason: "daemon_lock_not_directory",
250 cause: { stdout: "private startup diagnostics", code: 1 },
251 });
252 const { service, settings } = yield* fixture(Effect.void, undefined, false, startupError);
253 yield* Ref.update(settings, (current) => ({
254 ...current,
255 enableDeviceSupport: true,
256 enableAgentDeviceAccess: true,
257 }));
258 const error = yield* service.agentReadinessIfSupported().pipe(Effect.flip);
259 expect(error).toMatchObject({
260 _tag: "DeviceHostUnavailableError",
261 reason: startupError.message,
262 cause: startupError,
263 });
264 expect(error.message).toContain("daemon.lock is not a directory");
265 expect(error.message).not.toContain("private startup diagnostics");
266 expect((yield* service.state).hostStatuses[LOCAL_DEVICE_HOST_ID]).toEqual({
267 status: "failed",
268 detail: startupError.message,
269 });
270 }).pipe(Effect.scoped),
271 );
272
273 it.effect("listing and provider startup do not start helpers before consent", () =>
274 Effect.gen(function* () {
275 const { service, starts, requests } = yield* fixture();
276 expect((yield* service.list).hostStatus).toBe("disabled");
277 expect(yield* service.readinessIfSupported()).toBeNull();
278 const readiness = yield* service.readiness().pipe(Effect.result);
279 expect(readiness._tag).toBe("Failure");
280 expect(starts).toEqual([]);
281 expect(requests).toEqual([]);
282 }).pipe(Effect.scoped),
283 );
284
285 it.effect(
286 "explicit setup discovers never-booted AVDs; disabling stops helpers and blocks agents",
287 () =>
288 Effect.gen(function* () {
289 const { service, starts, settings } = yield* fixture();
290 const state = yield* service.configure({ enabled: true });
291 expect((yield* Ref.get(settings)).enableDeviceSupport).toBe(true);
292 expect(state.devices.map((device) => [device.id, device.booted])).toEqual([
293 ["Pixel_API_35", false],
294 ]);
295 expect(starts).toEqual(["start"]);
296 const disabled = yield* service.configure({ enabled: false });
297 expect(disabled.hostStatus).toBe("disabled");
298 expect(disabled.devices).toEqual([]);
299 expect((yield* Ref.get(settings)).enableDeviceSupport).toBe(false);
300 expect(yield* service.readinessIfSupported()).toBeNull();
301 expect(starts).toEqual(["start", "stop"]);
302 }).pipe(Effect.scoped),
303 );
304
305 it.effect("boots a stopped Android AVD and uses its emulator serial without duplicating it", () =>
306 Effect.gen(function* () {
307 const { service, requests } = yield* fixture();
308 yield* service.configure({ enabled: true });
309 const session = yield* service.open({
310 threadId: ThreadId.make("thread-1"),
311 deviceId: "Pixel_API_35",
312 platform: "android",
313 });
314 expect(session.deviceId).toBe("emulator-5554");
315 expect(requests.filter((url) => url.endsWith("/boot"))).toHaveLength(1);
316 const state = yield* service.state;
317 expect(state.devices.map((device) => device.id)).toEqual(["emulator-5554"]);
318 expect(state.bootingDevices).toEqual([]);
319 }).pipe(Effect.scoped),
320 );
321
322 it.effect("blocks only emulator video until ffmpeg is usable, then allows retry", () =>
323 Effect.gen(function* () {
324 const { service, requests, devices, encoderResult } = yield* fixture();
325 devices.push(
326 {
327 id: DeviceId.make("physical-android"),
328 name: "Pixel",
329 platform: "android",
330 version: "Android 15",
331 booted: true,
332 physical: true,
333 },
334 {
335 id: DeviceId.make("ios-simulator"),
336 name: "iPhone",
337 platform: "ios",
338 version: "iOS 18",
339 booted: true,
340 physical: false,
341 },
342 );
343 yield* Ref.set(encoderResult, { code: 127, stdout: "", stderr: "spawn ffmpeg ENOENT" });
344 const state = yield* service.configure({ enabled: true });
345 expect(state.devices.map((device) => device.id)).toEqual([
346 "ios-simulator",
347 "physical-android",
348 "Pixel_API_35",
349 ]);
350 const threadId = ThreadId.make("emulator-video-readiness");
351 const physical = yield* service.open({
352 threadId,
353 deviceId: "physical-android",
354 platform: "android",
355 });
356 const ios = yield* service.open({ threadId, deviceId: "ios-simulator", platform: "ios" });
357 expect(physical.deviceId).toBe("physical-android");
358 expect(ios.deviceId).toBe("ios-simulator");
359
360 const openEmulator = service.open({
361 threadId,
362 deviceId: "Pixel_API_35",
363 platform: "android",
364 });
365 const missing = yield* openEmulator.pipe(Effect.flip);
366 expect(missing.message).toMatch(/ffmpeg/i);
367 expect(missing.message).toMatch(/emulator/i);
368 expect(requests.filter((url) => url.endsWith("/boot"))).toEqual([]);
369 expect((yield* service.state).sessions).toEqual([physical, ios]);
370 expect((yield* service.state).bootingDevices ?? []).toEqual([]);
371
372 yield* Ref.set(encoderResult, { code: 1, stdout: "", stderr: "cannot execute ffmpeg" });
373 expect((yield* openEmulator.pipe(Effect.flip)).message).toMatch(/ffmpeg/i);
374 yield* Ref.set(encoderResult, {
375 code: 0,
376 stdout: " V....D libx264rgb libx264 H.264 / AVC RGB (codec h264)",
377 stderr: "",
378 });
379 expect((yield* openEmulator.pipe(Effect.flip)).message).toMatch(/libx264/i);
380 expect(requests.filter((url) => url.endsWith("/boot"))).toEqual([]);
381 expect((yield* service.state).sessions).toEqual([physical, ios]);
382
383 devices.push({
384 id: DeviceId.make("emulator-5556"),
385 name: "Already_booted",
386 platform: "android",
387 version: "Android 15",
388 booted: true,
389 physical: false,
390 });
391 expect(
392 (yield* service
393 .open({ threadId, deviceId: "emulator-5556", platform: "android" })
394 .pipe(Effect.flip)).message,
395 ).toMatch(/libx264/i);
396
397 yield* Ref.set(encoderResult, { code: 0, stdout: " V....D libx264", stderr: "" });
398 const emulator = yield* openEmulator;
399 expect(emulator.deviceId).toBe("emulator-5554");
400 expect(requests.filter((url) => url.endsWith("/boot"))).toHaveLength(1);
401 }).pipe(Effect.scoped),
402 );
403
404 it.effect("installs agent support only after the separate agent permission", () =>
405 Effect.gen(function* () {
406 const { service, agentStarts, agentStops, settings } = yield* fixture();
407 yield* service.configure({ enabled: true });
408 expect(agentStarts).toEqual([]);
409 expect(yield* service.agentReadinessIfSupported()).toBeNull();
410
411 yield* service.configure({ agentAccessEnabled: true });
412 expect(agentStarts).toEqual(["start"]);
413 expect((yield* Ref.get(settings)).enableAgentDeviceAccess).toBe(true);
414 expect((yield* service.state).agentAccessEnabled).toBe(true);
415
416 yield* service.configure({ agentAccessEnabled: false, onboardingCompleted: true });
417 expect(agentStops).toEqual(["stop"]);
418 expect((yield* service.state).onboardingCompleted).toBe(true);
419 expect((yield* Ref.get(settings)).deviceOnboardingCompleted).toBe(true);
420 }).pipe(Effect.scoped),
421 );
422});
423
424it.effect("publishes boot progress and does not restore sessions after support is disabled", () =>
425 Effect.gen(function* () {
426 const started = yield* Deferred.make<void>();
427 const finish = yield* Deferred.make<void>();
428 const { service } = yield* fixture(
429 Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(finish))),
430 );
431 yield* service.configure({ enabled: true });
432 const opening = yield* service
433 .open({ threadId: ThreadId.make("thread-1"), deviceId: "Pixel_API_35", platform: "android" })
434 .pipe(Effect.result, Effect.forkChild);
435 yield* Deferred.await(started);
436 expect((yield* service.state).bootingDevices?.map((device) => device.name)).toEqual([
437 "Pixel_API_35",
438 ]);
439 yield* service.configure({ enabled: false });
440 yield* Deferred.succeed(finish, undefined);
441 expect((yield* Fiber.join(opening))._tag).toBe("Failure");
442 const state = yield* service.state;
443 expect(state.hostStatus).toBe("disabled");
444 expect(state.devices).toEqual([]);
445 expect(state.sessions).toEqual([]);
446 expect(state.bootingDevices).toEqual([]);
447 }).pipe(Effect.scoped),
448);
449
450it.effect.each([
451 { case: "drops it on a host that ends devices itself", endsDevices: true, kept: 0 },
452 {
453 case: "keeps it on a host that can miss a device for one listing",
454 endsDevices: false,
455 kept: 1,
456 },
457])("when a host stops listing a session's device, $case", ({ endsDevices, kept }) =>
458 Effect.gen(function* () {
459 const { service, endDevice } = yield* fixture(
460 Effect.void,
461 undefined,
462 false,
463 undefined,
464 false,
465 undefined,
466 { endsDevices },
467 );
468 yield* service.configure({ enabled: true });
469 const threadId = ThreadId.make("ended-by-host");
470 yield* service.open({ threadId, deviceId: "Pixel_API_35", platform: "android" });
471 expect((yield* service.state).sessions.map((session) => session.deviceId)).toEqual([
472 "emulator-5554",
473 ]);
474 endDevice();
475 yield* service.list;
476 expect((yield* service.state).sessions).toHaveLength(kept);
477 }).pipe(Effect.scoped),
478);
479
480describe("device discovery after server restart", () => {
481 it.effect("captures an explicit device before any client lists devices", () =>
482 Effect.gen(function* () {
483 const { service, settings, requests } = yield* fixture();
484 yield* Ref.update(settings, (current) => ({ ...current, enableDeviceSupport: true }));
485 expect((yield* service.state).devices).toEqual([]);
486 const capture = yield* service.screenshot({ deviceId: DeviceId.make("Pixel_API_35") });
487 expect(capture.device.id).toBe("Pixel_API_35");
488 expect(Array.from(capture.png)).toEqual([137, 80, 78, 71]);
489 expect(requests.some((url) => url.endsWith("/api/devices"))).toBe(true);
490 }).pipe(Effect.scoped),
491 );
492});
493
494const missingPlistMessage =
495 "[apple-utils] Failed to read CoreSimulator plist at /Users/test/Library/Developer/CoreSimulator/Devices/deleted-simulator/device.plist:";
496
497it.effect("keeps other discovery warnings and clears them when only a deleted plist remains", () =>
498 Effect.gen(function* () {
499 const { service, discoveryErrors } = yield* fixture();
500 const missing = {
501 message: missingPlistMessage,
502 error: "Error: ENOENT: no such file or directory",
503 };
504 yield* Ref.set(discoveryErrors, [missing, { message: "Android discovery failed." }]);
505 const initial = yield* service.configure({ enabled: true });
506 expect(initial.hostStatusDetail).toBe("Android discovery failed.");
507 yield* Ref.set(discoveryErrors, [missing]);
508 const refreshed = yield* service.list;
509 expect(refreshed.hostStatusDetail).toBeUndefined();
510 expect(refreshed.hostStatuses.local?.detail).toBeUndefined();
511 }).pipe(Effect.scoped),
512);
513
514it.effect("hides Android discovery failures when the host has no Android SDK", () =>
515 Effect.gen(function* () {
516 const { service, discoveryErrors, androidAvailable } = yield* fixture();
517 const avdmanagerFailure = { message: "[android-utils] Failed to run `avdmanager list avd`:" };
518 yield* Ref.set(discoveryErrors, [avdmanagerFailure, { message: "iOS discovery failed." }]);
519 yield* Ref.set(androidAvailable, false);
520 const withoutSdk = yield* service.configure({ enabled: true });
521 expect(withoutSdk.hostStatusDetail).toBe("iOS discovery failed.");
522 yield* Ref.set(androidAvailable, true);
523 const withSdk = yield* service.list;
524 expect(withSdk.hostStatusDetail).toBe(`${avdmanagerFailure.message}\niOS discovery failed.`);
525 }).pipe(Effect.scoped),
526);
527
528it.effect.each([
529 {
530 diagnostic: "Insufficient disk space at /private/user/path",
531 reason: "disk_space",
532 message: "not enough free disk space",
533 },
534 {
535 diagnostic: "Timed out spawning /private/user/command",
536 reason: "timeout",
537 message: "did not become ready in time",
538 },
539 {
540 diagnostic:
541 "The emulator process exited with code 1.\nTry manually: emulator -avd Pixel_API_35",
542 reason: "launch_failed",
543 message: "could not start",
544 },
545] as const)("normalizes boot failure: $reason", ({ diagnostic, message }) =>
546 Effect.gen(function* () {
547 const { service } = yield* fixture(Effect.void, diagnostic);
548 yield* service.configure({ enabled: true });
549 const error = yield* service
550 .open({
551 threadId: ThreadId.make("boot-failure"),
552 deviceId: "Pixel_API_35",
553 platform: "android",
554 })
555 .pipe(Effect.flip);
556 expect(error._tag).toBe("DeviceBootError");
557 expect(error.message).toContain(message);
558 expect(error.message).toContain(diagnostic);
559 expect((yield* service.state).bootingDevices).toEqual([]);
560 }).pipe(Effect.scoped),
561);
562
563// regression: #22012 report Android emulator boot failures
564it.effect("includes nested hub boot diagnostics and bounds them to 2,000 characters", () =>
565 Effect.gen(function* () {
566 const diagnostic = "Error: emulator binary missing\n" + "diagnostic output\n".repeat(200);
567 const { service } = yield* fixture(Effect.void, {
568 error: "Failed to spawn emulator",
569 errors: [{ message: "Failed to launch emulator binary", error: diagnostic }],
570 });
571 yield* service.configure({ enabled: true });
572 const error = yield* service
573 .open({
574 threadId: ThreadId.make("nested-boot-failure"),
575 deviceId: "Pixel_API_35",
576 platform: "android",
577 })
578 .pipe(Effect.flip);
579 expect(error._tag).toBe("DeviceBootError");
580 if (error._tag !== "DeviceBootError") return;
581 const expected = `Failed to spawn emulator\n\nFailed to launch emulator binary\n\n${diagnostic}`;
582 expect(error.diagnostics).toBe(`${expected.slice(0, 1_999)}…`);
583 expect(error.diagnostics).toHaveLength(2_000);
584 expect(error.message).toContain(error.diagnostics);
585 const roundTrip = decodeBootError(encodeBootError(error));
586 expect(roundTrip.message).toBe(error.message);
587 expect((yield* service.state).bootingDevices).toEqual([]);
588 }).pipe(Effect.scoped),
589);
590
591it.effect("keeps shutdown successful when subsequent discovery fails", () =>
592 Effect.gen(function* () {
593 const { service } = yield* fixture(Effect.void, undefined, true);
594 yield* service.configure({ enabled: true });
595 const threadId = ThreadId.make("shutdown-refresh");
596 const session = yield* service.open({
597 threadId,
598 deviceId: "Pixel_API_35",
599 platform: "android",
600 });
601 yield* service.close({ threadId, deviceId: session.deviceId, shutdown: true });
602 const state = yield* service.state;
603 expect(state.sessions).toEqual([]);
604 expect(state.devices.find((device) => device.id === session.deviceId)?.booted).toBe(false);
605 }).pipe(Effect.scoped),
606);
607
608it.effect.each(["shutdown", "close"] as const)(
609 "%s releases iOS capture and the session's launcher so reopening uses a fresh session",
610 (operation) =>
611 Effect.gen(function* () {
612 const deviceId = DeviceId.make("11111111-1111-1111-1111-111111111111");
613 const threadId = ThreadId.make("capture-recovery");
614 let booted = true;
615 let capture: number | null = null;
616 let generation = 0;
617 const http = HttpClient.make((request) =>
618 Effect.sync(() => {
619 const path = new URL(request.url).pathname;
620 if (path === "/api/devices") {
621 return HttpClientResponse.fromWeb(
622 request,
623 Response.json({
624 emulators: [],
625 simulators: [
626 {
627 id: deviceId,
628 name: "iPhone",
629 platform: "ios",
630 version: "26",
631 physical: false,
632 booted,
633 },
634 ],
635 }),
636 );
637 }
638 if (path === "/vendor/serve-sim/grid/api/start") capture ??= ++generation;
639 else if (path === "/vendor/serve-sim/grid/api/shutdown") {
640 if (request.body._tag !== "Uint8Array") throw new Error("Missing shutdown body");
641 expect(decodeJson(new TextDecoder().decode(request.body.body))).toEqual({
642 udid: deviceId,
643 });
644 capture = null;
645 booted = false;
646 } else if (path === "/api/devices/shutdown") {
647 // This route powers off without releasing serve-sim's cached capture.
648 booted = false;
649 } else if (path === "/api/devices/boot") booted = true;
650 else throw new Error(`Unexpected hub path: ${path}`);
651 return HttpClientResponse.fromWeb(request, Response.json({ ok: true, id: deviceId }));
652 }),
653 );
654 const run = () => Effect.succeed({ code: 0, stdout: "", stderr: "" });
655 const ready: DeviceHost.DeviceHostReady = {
656 nodePath: process.execPath,
657 hub: { origin: "http://device.test" },
658 devices: makeDeviceHubOperations({
659 hostId: LOCAL_DEVICE_HOST_ID,
660 origin: "http://device.test",
661 http,
662 run,
663 androidAvailable: Effect.succeed(true),
664 }),
665 helpers: { serveSimAxSettings: null, serveSimCli: null },
666 run,
667 };
668 const host: DeviceHost.DeviceHost["Service"] = {
669 id: LOCAL_DEVICE_HOST_ID,
670 label: "This machine",
671 summary: Effect.succeed({
672 id: LOCAL_DEVICE_HOST_ID,
673 kind: "local",
674 label: "Simulator host",
675 platforms: [{ platform: "ios", available: true }],
676 hubInstalled: true,
677 agentDeviceInstalled: false,
678 }),
679 platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
680 ensureReady: () => Effect.succeed(ready),
681 ensureAgentReady: () => Effect.die("Agent access is not used in this test"),
682 current: Effect.succeed(ready),
683 stopAgent: Effect.void,
684 stop: Effect.void,
685 };
686 const launchers = new Set(["t3-from-a-previous-run"]);
687 const released: Array<[string, boolean]> = [];
688 // Whether the device was still on when each session was released.
689 const releasedWhileBooted: Array<boolean> = [];
690 let pauseBind: { entered: Deferred.Deferred<void>; proceed: Deferred.Deferred<void> } | null =
691 null;
692 const service = yield* DeviceService.makeWithHosts(
693 new Map([[host.id, host]]),
694 undefined,
695 undefined,
696 undefined,
697 {
698 bind: ({ session }) =>
699 Effect.gen(function* () {
700 if (pauseBind) {
701 yield* Deferred.succeed(pauseBind.entered, undefined);
702 yield* Deferred.await(pauseBind.proceed);
703 }
704 launchers.add(session);
705 return session;
706 }),
707 prune: (live) =>
708 Effect.sync(() => {
709 for (const session of launchers) if (!live.has(session)) launchers.delete(session);
710 }),
711 // Records whether the launcher still existed, since its close runs through it.
712 release: (launcher) =>
713 Effect.sync(() => {
714 released.push([launcher, launchers.has(launcher)]);
715 releasedWhileBooted.push(booted);
716 }),
717 },
718 ).pipe(Effect.provide(NodeCrypto.layer));
719 expect(launchers).toEqual(new Set());
720 const input = { threadId, deviceId, platform: "ios" as const };
721 const other = { ...input, threadId: ThreadId.make("capture-recovery-other") };
722 const target = (thread: ThreadId) => ({
723 threadId: thread,
724 hostId: LOCAL_DEVICE_HOST_ID,
725 deviceId,
726 });
727 const bind = Effect.fnUntraced(function* (open: typeof input) {
728 yield* service.open(open);
729 yield* service.agentLauncher({ ...target(open.threadId), targetArgs: [] });
730 return yield* agentDeviceSession(open.threadId, LOCAL_DEVICE_HOST_ID, deviceId);
731 }, Effect.provide(NodeCrypto.layer));
732 const session = yield* bind(input);
733 yield* bind(other);
734 expect(capture).toBe(1);
735 expect(launchers.size).toBe(2);
736 if (operation === "shutdown") yield* service.shutdown(input);
737 else yield* service.close({ threadId, deviceId, shutdown: true });
738 expect(capture).toBeNull();
739 expect((yield* service.state).sessions).toEqual([]);
740 expect(launchers).toEqual(new Set());
741 // Retiring a session ends its agent-device session too, which releases the device claim.
742 // Powering the device off retires the other thread's session on it as well.
743 const firstOther = yield* agentDeviceSession(
744 other.threadId,
745 LOCAL_DEVICE_HOST_ID,
746 deviceId,
747 ).pipe(Effect.provide(NodeCrypto.layer));
748 expect(new Set(released.map(([launcher]) => launcher))).toEqual(
749 new Set([session, firstOther]),
750 );
751 expect(released.every(([, existed]) => existed)).toBe(true);
752 // agent-device can close the session's app only while the device is on.
753 expect(releasedWhileBooted).toEqual([true, true]);
754 // A device_open that was still preparing when the close landed.
755 expect(yield* service.agentLauncher({ ...target(threadId), targetArgs: [] })).toEqual(
756 Option.none(),
757 );
758 expect(launchers).toEqual(new Set());
759 expect(yield* bind(input)).toBe(session);
760 // Reopening the same device ends nothing.
761 expect(released).toHaveLength(2);
762 expect(capture).toBe(2);
763 expect((yield* service.state).sessions).toHaveLength(1);
764 const otherSession = yield* bind(other);
765 yield* service.close({ threadId: other.threadId });
766 expect(launchers).toEqual(new Set([session]));
767 expect(released.slice(2)).toEqual([[otherSession, true]]);
768 expect(otherSession).not.toBe(session);
769 // A caller interrupted after retirement committed, while a bind holds the launcher lock.
770 pauseBind = { entered: yield* Deferred.make<void>(), proceed: yield* Deferred.make<void>() };
771 const binding = yield* Effect.forkChild(
772 service.agentLauncher({ ...target(threadId), targetArgs: [] }),
773 );
774 yield* Deferred.await(pauseBind.entered);
775 const updates = yield* service.subscribe;
776 const retiring = yield* Effect.forkChild(
777 operation === "shutdown" ? service.shutdown(input) : service.close({ threadId }),
778 );
779 expect((yield* PubSub.take(updates)).sessions).toEqual([]);
780 // list writes through the same state lock, so the retirement has committed.
781 expect((yield* service.list).sessions).toEqual([]);
782 yield* Effect.sync(() => retiring.interruptUnsafe());
783 yield* Deferred.succeed(pauseBind.proceed, undefined);
784 yield* Fiber.join(binding);
785 yield* Fiber.await(retiring);
786 expect(launchers).toEqual(new Set());
787 }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true })), Effect.scoped),
788);
789
790it.effect.each([
791 { hubReports: "off", outcome: "succeeds" },
792 { hubReports: "booted", outcome: "fails" },
793 { hubReports: "missing", outcome: "fails" },
794] as const)(
795 "iOS shutdown $outcome when serve-sim rejects it and the hub reports the simulator $hubReports",
796 ({ hubReports, outcome }) =>
797 Effect.gen(function* () {
798 const deviceId = DeviceId.make("22222222-2222-2222-2222-222222222222");
799 const paths: string[] = [];
800 let listed: "booted" | "off" | "missing" = "booted";
801 const http = HttpClient.make((request) =>
802 Effect.sync(() => {
803 const path = new URL(request.url).pathname;
804 paths.push(path);
805 if (path === "/api/devices") {
806 return HttpClientResponse.fromWeb(
807 request,
808 Response.json({
809 emulators: [],
810 simulators:
811 listed === "missing"
812 ? []
813 : [
814 {
815 id: deviceId,
816 name: "iPhone",
817 platform: "ios",
818 version: "26",
819 physical: false,
820 booted: listed === "booted",
821 },
822 ],
823 errors: listed === "missing" ? [{ message: "simctl list failed" }] : [],
824 }),
825 );
826 }
827 if (path === "/vendor/serve-sim/grid/api/shutdown") {
828 // serve-sim runs `simctl shutdown` bare and returns its failure as-is.
829 listed = hubReports;
830 return HttpClientResponse.fromWeb(
831 request,
832 Response.json(
833 { ok: false, error: "Unable to shutdown device in current state: Shutdown" },
834 { status: 500 },
835 ),
836 );
837 }
838 throw new Error(`Unexpected hub path: ${path}`);
839 }),
840 );
841 const run = () => Effect.succeed({ code: 0, stdout: "", stderr: "" });
842 const ready: DeviceHost.DeviceHostReady = {
843 nodePath: process.execPath,
844 hub: { origin: "http://device.test" },
845 devices: makeDeviceHubOperations({
846 hostId: LOCAL_DEVICE_HOST_ID,
847 origin: "http://device.test",
848 http,
849 run,
850 androidAvailable: Effect.succeed(true),
851 }),
852 helpers: { serveSimAxSettings: null, serveSimCli: null },
853 run,
854 };
855 const host: DeviceHost.DeviceHost["Service"] = {
856 id: LOCAL_DEVICE_HOST_ID,
857 label: "This machine",
858 summary: Effect.succeed({
859 id: LOCAL_DEVICE_HOST_ID,
860 kind: "local",
861 label: "Simulator host",
862 platforms: [{ platform: "ios", available: true }],
863 hubInstalled: true,
864 agentDeviceInstalled: false,
865 }),
866 platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
867 ensureReady: () => Effect.succeed(ready),
868 ensureAgentReady: () => Effect.die("Agent access is not used in this test"),
869 current: Effect.succeed(ready),
870 stopAgent: Effect.void,
871 stop: Effect.void,
872 };
873 const service = yield* DeviceService.makeWithHosts(new Map([[host.id, host]])).pipe(
874 Effect.provide(NodeCrypto.layer),
875 );
876 yield* service.list;
877 const exit = yield* Effect.exit(service.shutdown({ deviceId, platform: "ios" }));
878 expect(paths.filter((path) => path.endsWith("shutdown"))).toEqual([
879 "/vendor/serve-sim/grid/api/shutdown",
880 ]);
881 if (outcome === "succeeds") {
882 expect(Exit.isSuccess(exit)).toBe(true);
883 expect(
884 (yield* service.state).devices.find((device) => device.id === deviceId)?.booted,
885 ).toBe(false);
886 } else {
887 expect(Exit.isFailure(exit)).toBe(true);
888 expect(
889 (yield* service.state).devices.find((device) => device.id === deviceId)?.booted,
890 ).toBe(true);
891 }
892 }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true })), Effect.scoped),
893);
894
895it.effect.each([LOCAL_DEVICE_HOST_ID, "ssh-fixture"])(
896 "retains hub inventory on %s when AVD enumeration fails and recovers on retry",
897 (hostId) =>
898 Effect.gen(function* () {
899 let enumeration = { code: 1, stdout: "private stdout", stderr: "private stderr" };
900 const run = () => Effect.sync(() => enumeration);
901 const hubDevices = [
902 { id: "iphone", name: "iPhone", platform: "ios", physical: false },
903 { id: "phone", name: "Pixel", platform: "android", physical: true },
904 { id: "emulator-5554", name: "Running_AVD", platform: "android", physical: false },
905 ].map((device) => ({ ...device, booted: true, version: "test" }));
906 const http = HttpClient.make((request) =>
907 Effect.succeed(
908 HttpClientResponse.fromWeb(
909 request,
910 Response.json({ simulators: hubDevices.slice(0, 1), emulators: hubDevices.slice(1) }),
911 ),
912 ),
913 );
914 const ready: DeviceHost.DeviceHostReady = {
915 nodePath: process.execPath,
916 hub: { origin: "http://device.test" },
917 devices: makeDeviceHubOperations({
918 hostId,
919 origin: "http://device.test",
920 http,
921 run,
922 androidAvailable: Effect.succeed(true),
923 }),
924 helpers: { serveSimAxSettings: null, serveSimCli: null },
925 run,
926 };
927 const host: DeviceHost.DeviceHost["Service"] = {
928 id: hostId,
929 label: "Test device host",
930 summary: Effect.succeed({
931 id: hostId,
932 kind: hostId === LOCAL_DEVICE_HOST_ID ? "local" : "ssh",
933 label: "Test device host",
934 platforms: [{ platform: "android", available: true }],
935 hubInstalled: true,
936 agentDeviceInstalled: false,
937 }),
938 platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
939 ensureReady: () => Effect.succeed(ready),
940 ensureAgentReady: () => Effect.die("Agent access is not used in this test"),
941 current: Effect.succeed(ready),
942 stop: Effect.void,
943 stopAgent: Effect.void,
944 };
945 const service = yield* DeviceService.makeWithHosts(new Map([[hostId, host]])).pipe(
946 Effect.provide(NodeCrypto.layer),
947 Effect.provideService(HttpClient.HttpClient, http),
948 );
949
950 const incomplete = yield* service.list;
951 expect(incomplete.devices).toEqual(hubDevices.map((device) => ({ ...device, hostId })));
952 expect(incomplete.hostStatuses[hostId]).toEqual({
953 status: "ready",
954 androidDiscoveryIncomplete: true,
955 detail:
956 "Could not list Android virtual devices (emulator -list-avds, exit code 1). Discovered devices remain available.",
957 });
958 if (hostId === LOCAL_DEVICE_HOST_ID) {
959 expect(incomplete.hostStatusDetail).toBe(incomplete.hostStatuses[hostId]?.detail);
960 }
961
962 enumeration = { code: 0, stdout: "Running_AVD\r\nStopped_AVD\nStopped_AVD\n", stderr: "" };
963 const recovered = yield* service.retryHost(hostId);
964 expect(recovered.devices).toEqual([
965 ...hubDevices.map((device) => ({ ...device, hostId })),
966 {
967 hostId,
968 id: "Stopped_AVD",
969 name: "Stopped_AVD",
970 platform: "android",
971 version: "Android",
972 booted: false,
973 physical: false,
974 },
975 ]);
976 expect(recovered.hostStatuses[hostId]).toEqual({ status: "ready" });
977 if (hostId === LOCAL_DEVICE_HOST_ID) expect(recovered.hostStatusDetail).toBeUndefined();
978 }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true })), Effect.scoped),
979);
980
981it.effect("retry keeps device and agent consent unchanged", () =>
982 Effect.gen(function* () {
983 const { service, starts, agentStarts } = yield* fixture();
984 yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
985 expect(starts).toEqual([]);
986 expect(agentStarts).toEqual([]);
987 yield* service.configure({ enabled: true });
988 yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
989 expect(agentStarts).toEqual([]);
990 yield* service.configure({ agentAccessEnabled: true });
991 const before = agentStarts.length;
992 yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
993 expect(agentStarts.length).toBe(before + 1);
994 }).pipe(Effect.scoped),
995);
996
997it.effect("failed read-only discovery preserves lifecycle status and installed inventory", () =>
998 Effect.gen(function* () {
999 const { service, starts } = yield* fixture(Effect.void, undefined, false, undefined, true);
1000 const state = yield* service.inspect;
1001 expect(state.supportsToolInspection).toBe(true);
1002 expect(state.hostStatus).toBe("disabled");
1003 expect(state.hosts[0]?.hubInstalled).toBe(true);
1004 expect(state.hosts[0]?.toolInspectionError).toContain("Reconnect the host");
1005 expect(starts).toEqual([]);
1006 }).pipe(Effect.scoped),
1007);
1008
1009it.effect(
1010 "manual updates install only the selected tool without enabling access or starting helpers",
1011 () =>
1012 Effect.gen(function* () {
1013 const installed: string[] = [];
1014 const { service, starts, agentStarts, requests } = yield* fixture(
1015 Effect.void,
1016 undefined,
1017 false,
1018 undefined,
1019 false,
1020 (tool) =>
1021 Effect.sync(() => {
1022 installed.push(tool);
1023 }),
1024 );
1025 const before = yield* service.state;
1026 const state = yield* service.updateTool("agent");
1027 expect(installed).toEqual(["agent"]);
1028 expect(state.supportsToolUpdate).toBe(true);
1029 expect(state.hostStatus).toBe(before.hostStatus);
1030 expect(state.agentAccessEnabled).toBe(before.agentAccessEnabled);
1031 expect(state.revision).toBeGreaterThan(before.revision);
1032 expect(starts).toEqual([]);
1033 expect(agentStarts).toEqual([]);
1034 expect(requests).toEqual([]);
1035 yield* service.updateTool("hub");
1036 expect(installed).toEqual(["agent", "hub"]);
1037 }).pipe(Effect.scoped),
1038);
1039
1040it.effect("failed manual installation leaves lifecycle state unchanged and can be retried", () =>
1041 Effect.gen(function* () {
1042 let attempts = 0;
1043 const { service, starts, agentStarts } = yield* fixture(
1044 Effect.void,
1045 undefined,
1046 false,
1047 undefined,
1048 false,
1049 () =>
1050 Effect.suspend(() =>
1051 ++attempts === 1
1052 ? Effect.fail(
1053 new DeviceOperationError({
1054 operation: "update device tool",
1055 reason: "command_failed",
1056 cause: new Error("offline"),
1057 }),
1058 )
1059 : Effect.void,
1060 ),
1061 );
1062 const before = yield* service.state;
1063 const result = yield* service.updateTool("agent").pipe(Effect.result);
1064 expect(result._tag).toBe("Failure");
1065 expect(yield* service.state).toEqual(before);
1066 yield* service.updateTool("agent");
1067 expect(attempts).toBe(2);
1068 expect(starts).toEqual([]);
1069 expect(agentStarts).toEqual([]);
1070 }).pipe(Effect.scoped),
1071);
1072
1073it.effect("reconciles SSH host settings without publishing no-op changes", () =>
1074 Effect.gen(function* () {
1075 const fs = yield* FileSystem.FileSystem;
1076 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-reconcile-" });
1077 const settings = yield* ServerSettings.ServerSettingsService;
1078 // Each change is acknowledged after reconciliation consumed it, so no-ops are observable.
1079 const changes = yield* Queue.unbounded<{ value: Settings; done: Deferred.Deferred<void> }>();
1080 const removedFiles: string[] = [];
1081 const localHost: DeviceHost.DeviceHost["Service"] = {
1082 id: LOCAL_DEVICE_HOST_ID,
1083 label: "This machine",
1084 summary: Effect.succeed({
1085 id: LOCAL_DEVICE_HOST_ID,
1086 label: "Local",
1087 kind: "local",
1088 platforms: [],
1089 hubInstalled: false,
1090 agentDeviceInstalled: false,
1091 }),
1092 platformAvailability: (platform) => Effect.succeed({ platform, available: false }),
1093 current: Effect.succeed(null),
1094 ensureReady: () => Effect.die("Unexpected device launch"),
1095 ensureAgentReady: () => Effect.die("Unexpected agent launch"),
1096 stop: Effect.void,
1097 stopAgent: Effect.void,
1098 };
1099 const service = yield* DeviceService.make.pipe(
1100 Effect.provideService(DeviceHost.DeviceHost, localHost),
1101 Effect.provideService(ServerSettings.ServerSettingsService, {
1102 ...settings,
1103 subscribeChanges: Effect.succeed(
1104 Stream.fromQueue(changes).pipe(
1105 Stream.flatMap(({ value, done }) =>
1106 Stream.make(value).pipe(
1107 Stream.concat(
1108 Stream.fromEffect(Deferred.succeed(done, undefined)).pipe(Stream.drain),
1109 ),
1110 ),
1111 ),
1112 ),
1113 ),
1114 }),
1115 Effect.provideService(
1116 FileSystem.FileSystem,
1117 FileSystem.makeNoop({
1118 remove: (file) => Effect.sync(() => void removedFiles.push(file)),
1119 }),
1120 ),
1121 Effect.provideService(ProcessRunner.ProcessRunner, {
1122 run: () => Effect.die("Unexpected helper launch"),
1123 }),
1124 Effect.provideService(
1125 HttpClient.HttpClient,
1126 HttpClient.make(() => Effect.die("Unexpected HTTP request")),
1127 ),
1128 Effect.provideService(
1129 ChildProcessSpawner.ChildProcessSpawner,
1130 ChildProcessSpawner.make(() =>
1131 Effect.succeed(
1132 ChildProcessSpawner.makeHandle({
1133 pid: ChildProcessSpawner.ProcessId(123),
1134 stdout: Stream.make(new TextEncoder().encode("hostname 192.0.2.1\nport 22\n")),
1135 stderr: Stream.empty,
1136 all: Stream.empty,
1137 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
1138 isRunning: Effect.succeed(false),
1139 kill: () => Effect.void,
1140 stdin: Sink.drain,
1141 getInputFd: () => Sink.drain,
1142 getOutputFd: () => Stream.empty,
1143 unref: Effect.succeed(Effect.void),
1144 }),
1145 ),
1146 ),
1147 ),
1148 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(baseDir, baseDir), NetService.layer)),
1149 );
1150 const update = Effect.fnUntraced(function* (deviceHosts: ReadonlyArray<SshDeviceHostConfig>) {
1151 const value = yield* settings.updateSettings({ deviceHosts: [...deviceHosts] });
1152 const done = yield* Deferred.make<void>();
1153 yield* Queue.offer(changes, { value, done });
1154 yield* Deferred.await(done);
1155 return yield* service.state;
1156 });
1157
1158 const initial = yield* service.state;
1159 expect(yield* update([])).toEqual(initial);
1160
1161 const host: SshDeviceHostConfig = {
1162 kind: "ssh",
1163 id: "remote",
1164 label: "Remote",
1165 target: "remote-fixture",
1166 };
1167 const added = yield* update([host]);
1168 expect(added.hosts.map((entry) => entry.id)).toEqual([LOCAL_DEVICE_HOST_ID, host.id]);
1169 expect(yield* update([{ ...host }])).toEqual(added);
1170
1171 yield* service.setHostStatus(host.id, { status: "failed", detail: "stale" });
1172 const removed = yield* update([]);
1173 expect(removed.hosts.map((entry) => entry.id)).toEqual([LOCAL_DEVICE_HOST_ID]);
1174 expect(removed.hostStatuses[host.id]).toBeUndefined();
1175 expect(removedFiles).toHaveLength(1);
1176 }).pipe(
1177 Effect.scoped,
1178 Effect.provide(Layer.mergeAll(ServerSettings.layerTest(), NodeServices.layer)),
1179 ),
1180);
1181
1182it.effect("a failed tool update reports npm's exit code but not its output", () =>
1183 Effect.gen(function* () {
1184 const host: DeviceHost.DeviceHost["Service"] = {
1185 id: LOCAL_DEVICE_HOST_ID,
1186 label: "This machine",
1187 summary: Effect.succeed({
1188 id: LOCAL_DEVICE_HOST_ID,
1189 kind: "local",
1190 label: "Test server",
1191 platforms: [],
1192 hubInstalled: false,
1193 agentDeviceInstalled: false,
1194 }),
1195 platformAvailability: (platform) => Effect.succeed({ platform, available: false }),
1196 ensureReady: () => Effect.die("Updating a tool does not start the hub"),
1197 ensureAgentReady: () => Effect.die("Updating a tool does not start the agent"),
1198 current: Effect.succeed(null),
1199 stopAgent: Effect.void,
1200 stop: Effect.void,
1201 };
1202 const npmFailure = {
1203 code: ChildProcessSpawner.ExitCode(243),
1204 stdout: "",
1205 stderr: "npm error EACCES https://private:credential@registry.example.test/expo-device-hub",
1206 timedOut: false,
1207 stdoutTruncated: false,
1208 stderrTruncated: false,
1209 stdoutInvalidUtf8: false,
1210 stderrInvalidUtf8: false,
1211 };
1212 const service = yield* DeviceService.make.pipe(
1213 Effect.provideService(DeviceHost.DeviceHost, host),
1214 Effect.provideService(ProcessRunner.ProcessRunner, {
1215 run: () => Effect.succeed(npmFailure),
1216 }),
1217 Effect.provideService(
1218 HttpClient.HttpClient,
1219 HttpClient.make(() => Effect.die("Updating a tool makes no hub requests")),
1220 ),
1221 );
1222
1223 const error = yield* service.updateTool("hub").pipe(Effect.flip);
1224 expect(error).toMatchObject({
1225 _tag: "DeviceOperationError",
1226 reason: "command_failed",
1227 exitCode: 243,
1228 });
1229 expect(error.message).toBe(
1230 "Device update device tool failed: The device command failed (exit code 243).",
1231 );
1232 }).pipe(
1233 Effect.provide(
1234 Layer.mergeAll(
1235 ServerSettings.layerTest({ enableDeviceSupport: true }),
1236 ServerConfig.layerTest(process.cwd(), { prefix: "t3-device-update-" }),
1237 NodeCrypto.layer,
1238 NetService.layer,
1239 ).pipe(Layer.provideMerge(NodeServices.layer)),
1240 ),
1241 Effect.scoped,
1242 ),
1243);
1244
1245describe("locating a device id across hosts", () => {
1246 const threadId = ThreadId.make("thread-locate");
1247 const thisMachine = { id: LOCAL_DEVICE_HOST_ID, label: "This machine" };
1248 const macMini = { id: "mac-mini", label: "Mac Mini" };
1249 const listingHost = (
1250 host: { readonly id: string; readonly label: string },
1251 ids: ReadonlyArray<string>,
1252 ): DeviceHost.DeviceHost["Service"] => {
1253 const devices = ids.map((id) => ({
1254 id,
1255 name: id,
1256 platform: id.startsWith("Pixel") ? ("android" as const) : ("ios" as const),
1257 version: "test",
1258 booted: true,
1259 physical: false,
1260 }));
1261 const ready: DeviceHost.DeviceHostReady = {
1262 nodePath: process.execPath,
1263 hub: { origin: "http://device.test" },
1264 devices: {
1265 list: Effect.succeed({ devices, detail: undefined }),
1266 boot: (device) => Effect.succeed(device.id),
1267 attach: () => Effect.void,
1268 shutdown: () => Effect.void,
1269 screenshot: () => Effect.succeed(new Uint8Array()),
1270 },
1271 // Opening an emulator checks its host for ffmpeg's H.264 encoder.
1272 run: () => Effect.succeed({ code: 0, stdout: " V....D libx264", stderr: "" }),
1273 helpers: { serveSimAxSettings: null, serveSimCli: null },
1274 };
1275 return {
1276 ...host,
1277 summary: Effect.succeed({
1278 ...host,
1279 kind: host.id === LOCAL_DEVICE_HOST_ID ? "local" : "ssh",
1280 platforms: [
1281 { platform: "ios", available: true },
1282 { platform: "android", available: true },
1283 ],
1284 hubInstalled: true,
1285 agentDeviceInstalled: false,
1286 }),
1287 platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
1288 ensureReady: () => Effect.succeed(ready),
1289 ensureAgentReady: () => Effect.die("Agent access is not used in this test"),
1290 current: Effect.succeed(ready),
1291 stopAgent: Effect.void,
1292 stop: Effect.void,
1293 };
1294 };
1295 // An Android AVD name, like Pixel_10 here, can exist on two hosts.
1296 const withTwoHosts = <A, E>(
1297 test: (service: DeviceService.DeviceService["Service"]) => Effect.Effect<A, E>,
1298 ) =>
1299 Effect.gen(function* () {
1300 const service = yield* DeviceService.makeWithHosts(
1301 new Map([
1302 [thisMachine.id, listingHost(thisMachine, ["Pixel_10"])],
1303 [macMini.id, listingHost(macMini, ["MAC-UDID", "Pixel_10"])],
1304 ]),
1305 ).pipe(Effect.provide(NodeCrypto.layer));
1306 yield* service.list;
1307 return yield* test(service);
1308 }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true })), Effect.scoped);
1309 const open = (
1310 service: DeviceService.DeviceService["Service"],
1311 hostId: string,
1312 deviceId: string,
1313 thread = threadId,
1314 ) =>
1315 service.open({
1316 threadId: thread,
1317 hostId,
1318 deviceId: DeviceId.make(deviceId),
1319 platform: deviceId.startsWith("Pixel") ? "android" : "ios",
1320 });
1321
1322 it.effect("finds a device id that exists only on another host", () =>
1323 withTwoHosts((service) =>
1324 Effect.gen(function* () {
1325 const located = yield* service.locateDevice({ deviceId: DeviceId.make("MAC-UDID") });
1326 expect(Option.getOrUndefined(located)).toMatchObject({
1327 hostId: "mac-mini",
1328 id: "MAC-UDID",
1329 });
1330 }),
1331 ),
1332 );
1333
1334 it.effect("refuses a device id that exists on two hosts and names both", () =>
1335 withTwoHosts((service) =>
1336 Effect.gen(function* () {
1337 const error = yield* service
1338 .locateDevice({ deviceId: DeviceId.make("Pixel_10") })
1339 .pipe(Effect.flip);
1340 expect(error).toMatchObject({ _tag: "DeviceHostAmbiguousError", deviceId: "Pixel_10" });
1341 expect(error.hosts).toHaveLength(2);
1342 expect(error.hosts).toEqual(expect.arrayContaining([thisMachine, macMini]));
1343 }),
1344 ),
1345 );
1346
1347 it.effect("keeps an explicit hostId and says which host has the device", () =>
1348 withTwoHosts((service) =>
1349 Effect.gen(function* () {
1350 const error = yield* service
1351 .locateDevice({ deviceId: DeviceId.make("MAC-UDID"), hostId: LOCAL_DEVICE_HOST_ID })
1352 .pipe(Effect.flip);
1353 expect(error).toMatchObject({
1354 _tag: "DeviceOnOtherHostError",
1355 deviceId: "MAC-UDID",
1356 host: thisMachine,
1357 hosts: [macMini],
1358 });
1359 const onMac = yield* service.locateDevice({
1360 deviceId: DeviceId.make("Pixel_10"),
1361 hostId: "mac-mini",
1362 });
1363 expect(Option.getOrUndefined(onMac)).toMatchObject({ hostId: "mac-mini", id: "Pixel_10" });
1364 }),
1365 ),
1366 );
1367
1368 it.effect("finds nothing for a device id that no host lists", () =>
1369 withTwoHosts((service) =>
1370 Effect.gen(function* () {
1371 const deviceId = DeviceId.make("Pixel_9");
1372 expect(yield* service.locateDevice({ deviceId })).toEqual(Option.none());
1373 expect(yield* service.locateDevice({ deviceId, hostId: "mac-mini" })).toEqual(
1374 Option.none(),
1375 );
1376 expect(yield* service.locateDevice({ deviceId, hostId: "unknown-host" })).toEqual(
1377 Option.none(),
1378 );
1379 }),
1380 ),
1381 );
1382
1383 it.effect("finds an open device by id on whichever host it is on", () =>
1384 withTwoHosts((service) =>
1385 Effect.gen(function* () {
1386 yield* open(service, "mac-mini", "MAC-UDID");
1387 const deviceId = DeviceId.make("MAC-UDID");
1388 expect(
1389 Option.getOrUndefined(yield* service.locateSession({ threadId, deviceId })),
1390 ).toMatchObject({ threadId, hostId: "mac-mini", deviceId });
1391 const error = yield* service
1392 .locateSession({ threadId, deviceId, hostId: LOCAL_DEVICE_HOST_ID })
1393 .pipe(Effect.flip);
1394 expect(error).toMatchObject({
1395 _tag: "DeviceOnOtherHostError",
1396 host: thisMachine,
1397 hosts: [macMini],
1398 });
1399 }),
1400 ),
1401 );
1402
1403 it.effect("refuses an id open on two hosts unless the hostId picks one", () =>
1404 withTwoHosts((service) =>
1405 Effect.gen(function* () {
1406 yield* open(service, LOCAL_DEVICE_HOST_ID, "Pixel_10");
1407 yield* open(service, "mac-mini", "Pixel_10");
1408 const deviceId = DeviceId.make("Pixel_10");
1409 const error = yield* service.locateSession({ threadId, deviceId }).pipe(Effect.flip);
1410 expect(error).toMatchObject({ _tag: "DeviceHostAmbiguousError", deviceId });
1411 expect(error.hosts).toEqual(expect.arrayContaining([thisMachine, macMini]));
1412 const onMac = yield* service.locateSession({ threadId, deviceId, hostId: "mac-mini" });
1413 expect(Option.getOrUndefined(onMac)).toMatchObject({ hostId: "mac-mini", deviceId });
1414 }),
1415 ),
1416 );
1417
1418 it.effect("finds no session for a device this thread has not opened", () =>
1419 withTwoHosts((service) =>
1420 Effect.gen(function* () {
1421 const deviceId = DeviceId.make("MAC-UDID");
1422 expect(yield* service.locateSession({ threadId, deviceId })).toEqual(Option.none());
1423 yield* open(service, "mac-mini", "MAC-UDID", ThreadId.make("thread-other"));
1424 expect(yield* service.locateSession({ threadId, deviceId })).toEqual(Option.none());
1425 expect(
1426 yield* service.locateSession({ threadId, deviceId, hostId: LOCAL_DEVICE_HOST_ID }),
1427 ).toEqual(Option.none());
1428 }),
1429 ),
1430 );
1431});