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