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