Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DeviceService.test.ts

1,152 lines44.0 KB

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