Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import {
3 DEFAULT_SERVER_SETTINGS,
4 DeviceId,
5 LOCAL_DEVICE_HOST_ID,
6 ThreadId,
7 type DeviceServiceState,
8} from "@t3tools/contracts";
9import * as Effect from "effect/Effect";
10import * as Exit from "effect/Exit";
11import * as Deferred from "effect/Deferred";
12import * as Fiber from "effect/Fiber";
13import * as PubSub from "effect/PubSub";
14import * as Ref from "effect/Ref";
15import * as Schema from "effect/Schema";
16import * as Stream from "effect/Stream";
17import { HttpClient, HttpClientResponse } from "effect/unstable/http";
18import { ServerSettingsService } from "../serverSettings.ts";
19import * as DeviceHost from "./DeviceHost.ts";
20import { NodeRuntimeUnavailableError } from "@t3tools/shared/nodeRuntime";
21
22import { type DeviceService, makeWithHosts, stateStream } from "./DeviceService.ts";
23
24const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
25
26const baseState: DeviceServiceState = {
27 hosts: [],
28 hostStatus: "idle",
29 hostStatuses: {},
30 devices: [],
31 sessions: [],
32 onboardingCompleted: false,
33 agentAccessEnabled: false,
34 hubBasePath: "/api/device-hub",
35 revision: 0,
36};
37
38describe("DeviceService.stateStream", () => {
39 it.effect("emits the current snapshot and then every published change", () =>
40 Effect.gen(function* () {
41 const pubsub = yield* PubSub.unbounded<DeviceServiceState>();
42 const current = yield* Ref.make(baseState);
43 const service: Pick<DeviceService["Service"], "state" | "subscribe"> = {
44 state: Ref.get(current),
45 subscribe: PubSub.subscribe(pubsub),
46 };
47
48 const collected = yield* stateStream(service as DeviceService["Service"]).pipe(
49 Stream.take(3),
50 Stream.runCollect,
51 Effect.forkChild,
52 );
53 yield* Effect.yieldNow;
54 for (const revision of [1, 2]) {
55 const next = { ...baseState, revision, hostStatus: "ready" as const };
56 yield* Ref.set(current, next);
57 yield* PubSub.publish(pubsub, next);
58 }
59 const seen = yield* Fiber.join(collected);
60 expect(seen.map((state) => state.revision)).toEqual([0, 1, 2]);
61 }),
62 );
63});
64
65const fixture = Effect.fn("fixture")(function* (
66 onBoot: Effect.Effect<void> = Effect.void,
67 bootError?: string,
68 failListAfterShutdown = false,
69 runtimeFailure?: NodeRuntimeUnavailableError,
70) {
71 const settings = yield* Ref.make(DEFAULT_SERVER_SETTINGS);
72 const starts: string[] = [];
73 const agentStarts: string[] = [];
74 const agentStops: string[] = [];
75 const requests: string[] = [];
76 let booted = false;
77 let shutDown = false;
78 const ready: DeviceHost.DeviceHostReady = {
79 nodePath: process.execPath,
80 hub: { origin: "http://device.test" },
81 helpers: { serveSimAxSettings: null, serveSimCli: null },
82 run: () => Effect.succeed({ code: 0, stdout: "Pixel_API_35\n", stderr: "" }),
83 };
84 const host: DeviceHost.DeviceHost["Service"] = {
85 id: LOCAL_DEVICE_HOST_ID,
86 summary: Effect.succeed({
87 id: LOCAL_DEVICE_HOST_ID,
88 kind: "local",
89 label: "Test server",
90 platforms: [{ platform: "android", available: true }],
91 hubInstalled: true,
92 agentDeviceInstalled: false,
93 }),
94 platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
95 ensureReady: (onPhase) =>
96 Effect.gen(function* () {
97 if (runtimeFailure) return yield* runtimeFailure;
98 starts.push("start");
99 yield* onPhase("starting");
100 return ready;
101 }),
102 ensureAgentReady: (onPhase) =>
103 Effect.gen(function* () {
104 if (runtimeFailure) return yield* runtimeFailure;
105 agentStarts.push("start");
106 yield* onPhase("starting");
107 return {
108 ...ready,
109 agentDevice: { baseUrl: "http://agent.test", token: "test", entryPath: "/agent" },
110 };
111 }),
112 current: Effect.succeed(null),
113 stopAgent: Effect.sync(() => {
114 agentStops.push("stop");
115 }),
116 stop: Effect.sync(() => {
117 starts.push("stop");
118 }),
119 };
120 const service = yield* makeWithHosts(new Map([[host.id, host]])).pipe(
121 Effect.provideService(DeviceHost.DeviceHost, host),
122 Effect.provideService(
123 ServerSettingsService,
124 ServerSettingsService.of({
125 updateProviderInstance: () => Effect.die("Unexpected provider mutation"),
126 withSettingsSnapshot: (use) => Effect.flatMap(Ref.get(settings), use),
127 start: Effect.void,
128 ready: Effect.void,
129 getSettings: Ref.get(settings),
130 updateSettings: (patch) =>
131 Ref.updateAndGet(settings, (current) => ({
132 ...current,
133 enableDeviceSupport: patch.enableDeviceSupport ?? current.enableDeviceSupport,
134 enableAgentDeviceAccess:
135 patch.enableAgentDeviceAccess ?? current.enableAgentDeviceAccess,
136 deviceOnboardingCompleted:
137 patch.deviceOnboardingCompleted ?? current.deviceOnboardingCompleted,
138 })),
139 streamChanges: Stream.empty,
140 subscribeChanges: Effect.succeed(Stream.empty),
141 }),
142 ),
143 Effect.provideService(
144 HttpClient.HttpClient,
145 HttpClient.make((request) =>
146 Effect.gen(function* () {
147 requests.push(request.url);
148 if (request.url.includes("/api/screenshot")) {
149 return HttpClientResponse.fromWeb(
150 request,
151 new Response(new Uint8Array([137, 80, 78, 71])),
152 );
153 }
154 if (request.url.endsWith("/shutdown")) {
155 shutDown = true;
156 booted = false;
157 return HttpClientResponse.fromWeb(request, Response.json({ ok: true }));
158 }
159 if (shutDown && failListAfterShutdown) {
160 return HttpClientResponse.fromWeb(
161 request,
162 new Response("Discovery busy", { status: 503 }),
163 );
164 }
165 if (request.url.endsWith("/boot")) {
166 yield* onBoot;
167 booted = true;
168 return HttpClientResponse.fromWeb(
169 request,
170 Response.json(
171 bootError ? { ok: false, error: bootError } : { ok: true, serial: "emulator-5554" },
172 ),
173 );
174 }
175 return HttpClientResponse.fromWeb(
176 request,
177 Response.json({
178 simulators: [],
179 emulators: booted
180 ? [
181 {
182 id: "emulator-5554",
183 name: "Pixel_API_35",
184 platform: "android",
185 version: "Android 15",
186 booted: true,
187 physical: false,
188 },
189 ]
190 : [],
191 }),
192 );
193 }),
194 ),
195 ),
196 );
197 return { service, starts, agentStarts, agentStops, requests, settings };
198});
199
200describe("device setup consent", () => {
201 it.effect(
202 "preserves missing-runtime guidance and causes through manual and agent readiness",
203 () =>
204 Effect.gen(function* () {
205 const underlying = new Error("private lookup diagnostics");
206 const runtimeFailure = new NodeRuntimeUnavailableError({
207 feature: "Local device support",
208 cause: underlying,
209 });
210 const { service, settings, requests } = yield* fixture(
211 Effect.void,
212 undefined,
213 false,
214 runtimeFailure,
215 );
216 yield* Ref.update(settings, (current) => ({
217 ...current,
218 enableDeviceSupport: true,
219 enableAgentDeviceAccess: true,
220 }));
221 for (const readiness of [service.readiness(), service.agentReadinessIfSupported()]) {
222 const error = yield* readiness.pipe(Effect.flip);
223 expect(error).toMatchObject({
224 _tag: "DeviceHostUnavailableError",
225 reason: expect.stringContaining("Install Node.js"),
226 cause: runtimeFailure,
227 });
228 expect(error.message).not.toContain(underlying.message);
229 }
230 expect((yield* service.state).hostStatuses[LOCAL_DEVICE_HOST_ID]).toMatchObject({
231 status: "failed",
232 detail: expect.stringContaining("Install Node.js"),
233 });
234 expect(requests).toEqual([]);
235 }).pipe(Effect.scoped),
236 );
237
238 it.effect("listing and provider startup do not start helpers before consent", () =>
239 Effect.gen(function* () {
240 const { service, starts, requests } = yield* fixture();
241 expect((yield* service.list).hostStatus).toBe("disabled");
242 expect(yield* service.readinessIfSupported()).toBeNull();
243 const readiness = yield* service.readiness().pipe(Effect.result);
244 expect(readiness._tag).toBe("Failure");
245 expect(starts).toEqual([]);
246 expect(requests).toEqual([]);
247 }).pipe(Effect.scoped),
248 );
249
250 it.effect(
251 "explicit setup discovers never-booted AVDs; disabling stops helpers and blocks agents",
252 () =>
253 Effect.gen(function* () {
254 const { service, starts, settings } = yield* fixture();
255 const state = yield* service.configure({ enabled: true });
256 expect((yield* Ref.get(settings)).enableDeviceSupport).toBe(true);
257 expect(state.devices.map((device) => [device.id, device.booted])).toEqual([
258 ["Pixel_API_35", false],
259 ]);
260 expect(starts).toEqual(["start"]);
261 const disabled = yield* service.configure({ enabled: false });
262 expect(disabled.hostStatus).toBe("disabled");
263 expect(disabled.devices).toEqual([]);
264 expect((yield* Ref.get(settings)).enableDeviceSupport).toBe(false);
265 expect(yield* service.readinessIfSupported()).toBeNull();
266 expect(starts).toEqual(["start", "stop"]);
267 }).pipe(Effect.scoped),
268 );
269
270 it.effect("boots a stopped Android AVD and uses its emulator serial without duplicating it", () =>
271 Effect.gen(function* () {
272 const { service, requests } = yield* fixture();
273 yield* service.configure({ enabled: true });
274 const session = yield* service.open({
275 threadId: ThreadId.make("thread-1"),
276 deviceId: "Pixel_API_35",
277 platform: "android",
278 });
279 expect(session.deviceId).toBe("emulator-5554");
280 expect(requests.filter((url) => url.endsWith("/boot"))).toHaveLength(1);
281 const state = yield* service.state;
282 expect(state.devices.map((device) => device.id)).toEqual(["emulator-5554"]);
283 expect(state.bootingDevices).toEqual([]);
284 }).pipe(Effect.scoped),
285 );
286
287 it.effect("installs agent support only after the separate agent permission", () =>
288 Effect.gen(function* () {
289 const { service, agentStarts, agentStops, settings } = yield* fixture();
290 yield* service.configure({ enabled: true });
291 expect(agentStarts).toEqual([]);
292 expect(yield* service.agentReadinessIfSupported()).toBeNull();
293
294 yield* service.configure({ agentAccessEnabled: true });
295 expect(agentStarts).toEqual(["start"]);
296 expect((yield* Ref.get(settings)).enableAgentDeviceAccess).toBe(true);
297 expect((yield* service.state).agentAccessEnabled).toBe(true);
298
299 yield* service.configure({ agentAccessEnabled: false, onboardingCompleted: true });
300 expect(agentStops).toEqual(["stop"]);
301 expect((yield* service.state).onboardingCompleted).toBe(true);
302 expect((yield* Ref.get(settings)).deviceOnboardingCompleted).toBe(true);
303 }).pipe(Effect.scoped),
304 );
305});
306
307it.effect("publishes boot progress and does not restore sessions after support is disabled", () =>
308 Effect.gen(function* () {
309 const started = yield* Deferred.make<void>();
310 const finish = yield* Deferred.make<void>();
311 const { service } = yield* fixture(
312 Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(finish))),
313 );
314 yield* service.configure({ enabled: true });
315 const opening = yield* service
316 .open({ threadId: ThreadId.make("thread-1"), deviceId: "Pixel_API_35", platform: "android" })
317 .pipe(Effect.result, Effect.forkChild);
318 yield* Deferred.await(started);
319 expect((yield* service.state).bootingDevices?.map((device) => device.name)).toEqual([
320 "Pixel_API_35",
321 ]);
322 yield* service.configure({ enabled: false });
323 yield* Deferred.succeed(finish, undefined);
324 expect((yield* Fiber.join(opening))._tag).toBe("Failure");
325 const state = yield* service.state;
326 expect(state.hostStatus).toBe("disabled");
327 expect(state.devices).toEqual([]);
328 expect(state.sessions).toEqual([]);
329 expect(state.bootingDevices).toEqual([]);
330 }).pipe(Effect.scoped),
331);
332
333describe("device discovery after server restart", () => {
334 it.effect("captures an explicit device before any client lists devices", () =>
335 Effect.gen(function* () {
336 const { service, settings, requests } = yield* fixture();
337 yield* Ref.update(settings, (current) => ({ ...current, enableDeviceSupport: true }));
338 expect((yield* service.state).devices).toEqual([]);
339 const capture = yield* service.screenshot({ deviceId: DeviceId.make("Pixel_API_35") });
340 expect(capture.device.id).toBe("Pixel_API_35");
341 expect(Array.from(capture.png)).toEqual([137, 80, 78, 71]);
342 expect(requests.some((url) => url.endsWith("/api/devices"))).toBe(true);
343 }).pipe(Effect.scoped),
344 );
345});
346
347for (const [diagnostic, reason, message] of [
348 ["Insufficient disk space at /private/user/path", "disk_space", "not enough free disk space"],
349 ["Timed out spawning /private/user/command", "timeout", "did not become ready in time"],
350 ["Unexpected failure: secret-token", "launch_failed", "could not start"],
351] as const) {
352 it.effect(`normalizes boot failure: ${reason}`, () =>
353 Effect.gen(function* () {
354 const { service } = yield* fixture(Effect.void, diagnostic);
355 yield* service.configure({ enabled: true });
356 const error = yield* service
357 .open({
358 threadId: ThreadId.make("boot-failure"),
359 deviceId: "Pixel_API_35",
360 platform: "android",
361 })
362 .pipe(Effect.flip);
363 expect(error._tag).toBe("DeviceBootError");
364 expect(error.message).toContain(message);
365 expect(error.message).not.toContain(diagnostic);
366 expect((yield* service.state).bootingDevices).toEqual([]);
367 }).pipe(Effect.scoped),
368 );
369}
370
371it.effect("keeps shutdown successful when subsequent discovery fails", () =>
372 Effect.gen(function* () {
373 const { service } = yield* fixture(Effect.void, undefined, true);
374 yield* service.configure({ enabled: true });
375 const threadId = ThreadId.make("shutdown-refresh");
376 const session = yield* service.open({
377 threadId,
378 deviceId: "Pixel_API_35",
379 platform: "android",
380 });
381 yield* service.close({ threadId, deviceId: session.deviceId, shutdown: true });
382 const state = yield* service.state;
383 expect(state.sessions).toEqual([]);
384 expect(state.devices.find((device) => device.id === session.deviceId)?.booted).toBe(false);
385 }).pipe(Effect.scoped),
386);
387
388it.effect.each(["shutdown", "close"] as const)(
389 "%s releases iOS capture so reopening uses a fresh session",
390 (operation) =>
391 Effect.gen(function* () {
392 const deviceId = DeviceId.make("11111111-1111-1111-1111-111111111111");
393 const threadId = ThreadId.make("capture-recovery");
394 let booted = true;
395 let capture: number | null = null;
396 let generation = 0;
397 const ready: DeviceHost.DeviceHostReady = {
398 nodePath: process.execPath,
399 hub: { origin: "http://device.test" },
400 helpers: { serveSimAxSettings: null, serveSimCli: null },
401 run: () => Effect.succeed({ code: 0, stdout: "", stderr: "" }),
402 };
403 const host: DeviceHost.DeviceHost["Service"] = {
404 id: LOCAL_DEVICE_HOST_ID,
405 summary: Effect.succeed({
406 id: LOCAL_DEVICE_HOST_ID,
407 kind: "local",
408 label: "Simulator host",
409 platforms: [{ platform: "ios", available: true }],
410 hubInstalled: true,
411 agentDeviceInstalled: false,
412 }),
413 platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
414 ensureReady: () => Effect.succeed(ready),
415 ensureAgentReady: () => Effect.die("Agent access is not used in this test"),
416 current: Effect.succeed(ready),
417 stopAgent: Effect.void,
418 stop: Effect.void,
419 };
420 const http = HttpClient.make((request) =>
421 Effect.sync(() => {
422 const path = new URL(request.url).pathname;
423 if (path === "/api/devices") {
424 return HttpClientResponse.fromWeb(
425 request,
426 Response.json({
427 emulators: [],
428 simulators: [
429 {
430 id: deviceId,
431 name: "iPhone",
432 platform: "ios",
433 version: "26",
434 physical: false,
435 booted,
436 },
437 ],
438 }),
439 );
440 }
441 if (path === "/vendor/serve-sim/grid/api/start") capture ??= ++generation;
442 else if (path === "/vendor/serve-sim/grid/api/shutdown") {
443 if (request.body._tag !== "Uint8Array") throw new Error("Missing shutdown body");
444 expect(decodeJson(new TextDecoder().decode(request.body.body))).toEqual({
445 udid: deviceId,
446 });
447 capture = null;
448 booted = false;
449 } else if (path === "/api/devices/shutdown") {
450 // This route powers off without releasing serve-sim's cached capture.
451 booted = false;
452 } else if (path === "/api/devices/boot") booted = true;
453 else throw new Error(`Unexpected hub path: ${path}`);
454 return HttpClientResponse.fromWeb(request, Response.json({ ok: true, id: deviceId }));
455 }),
456 );
457 const service = yield* makeWithHosts(new Map([[host.id, host]])).pipe(
458 Effect.provideService(HttpClient.HttpClient, http),
459 );
460 const input = { threadId, deviceId, platform: "ios" as const };
461 yield* service.open(input);
462 expect(capture).toBe(1);
463 if (operation === "shutdown") yield* service.shutdown(input);
464 else yield* service.close({ threadId, deviceId, shutdown: true });
465 expect(capture).toBeNull();
466 expect((yield* service.state).sessions).toEqual([]);
467 yield* service.open(input);
468 expect(capture).toBe(2);
469 expect((yield* service.state).sessions).toHaveLength(1);
470 }).pipe(
471 Effect.provide(ServerSettingsService.layerTest({ enableDeviceSupport: true })),
472 Effect.scoped,
473 ),
474);
475
476it.effect.each([
477 { hubReports: "off", outcome: "succeeds" },
478 { hubReports: "booted", outcome: "fails" },
479 { hubReports: "missing", outcome: "fails" },
480] as const)(
481 "iOS shutdown $outcome when serve-sim rejects it and the hub reports the simulator $hubReports",
482 ({ hubReports, outcome }) =>
483 Effect.gen(function* () {
484 const deviceId = DeviceId.make("22222222-2222-2222-2222-222222222222");
485 const paths: string[] = [];
486 // The device list is stale until shutdown re-reads it from the hub.
487 let listed: "booted" | "off" | "missing" = "booted";
488 const ready: DeviceHost.DeviceHostReady = {
489 nodePath: process.execPath,
490 hub: { origin: "http://device.test" },
491 helpers: { serveSimAxSettings: null, serveSimCli: null },
492 run: () => Effect.succeed({ code: 0, stdout: "", stderr: "" }),
493 };
494 const host: DeviceHost.DeviceHost["Service"] = {
495 id: LOCAL_DEVICE_HOST_ID,
496 summary: Effect.succeed({
497 id: LOCAL_DEVICE_HOST_ID,
498 kind: "local",
499 label: "Simulator host",
500 platforms: [{ platform: "ios", available: true }],
501 hubInstalled: true,
502 agentDeviceInstalled: false,
503 }),
504 platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
505 ensureReady: () => Effect.succeed(ready),
506 ensureAgentReady: () => Effect.die("Agent access is not used in this test"),
507 current: Effect.succeed(ready),
508 stopAgent: Effect.void,
509 stop: Effect.void,
510 };
511 const http = HttpClient.make((request) =>
512 Effect.sync(() => {
513 const path = new URL(request.url).pathname;
514 paths.push(path);
515 if (path === "/api/devices") {
516 return HttpClientResponse.fromWeb(
517 request,
518 Response.json({
519 emulators: [],
520 simulators:
521 listed === "missing"
522 ? []
523 : [
524 {
525 id: deviceId,
526 name: "iPhone",
527 platform: "ios",
528 version: "26",
529 physical: false,
530 booted: listed === "booted",
531 },
532 ],
533 // A partial listing still decodes; it must not read as "off".
534 errors: listed === "missing" ? [{ message: "simctl list failed" }] : [],
535 }),
536 );
537 }
538 if (path === "/vendor/serve-sim/grid/api/shutdown") {
539 // serve-sim runs `simctl shutdown` bare and returns its failure as-is.
540 listed = hubReports;
541 return HttpClientResponse.fromWeb(
542 request,
543 Response.json(
544 { ok: false, error: "Unable to shutdown device in current state: Shutdown" },
545 { status: 500 },
546 ),
547 );
548 }
549 throw new Error(`Unexpected hub path: ${path}`);
550 }),
551 );
552 const service = yield* makeWithHosts(new Map([[host.id, host]])).pipe(
553 Effect.provideService(HttpClient.HttpClient, http),
554 );
555 yield* service.list;
556 const exit = yield* Effect.exit(service.shutdown({ deviceId, platform: "ios" }));
557 expect(paths.filter((path) => path.endsWith("shutdown"))).toEqual([
558 "/vendor/serve-sim/grid/api/shutdown",
559 ]);
560 if (outcome === "succeeds") {
561 expect(Exit.isSuccess(exit)).toBe(true);
562 expect(
563 (yield* service.state).devices.find((device) => device.id === deviceId)?.booted,
564 ).toBe(false);
565 } else {
566 expect(Exit.isFailure(exit)).toBe(true);
567 expect(
568 (yield* service.state).devices.find((device) => device.id === deviceId)?.booted,
569 ).toBe(true);
570 }
571 }).pipe(
572 Effect.provide(ServerSettingsService.layerTest({ enableDeviceSupport: true })),
573 Effect.scoped,
574 ),
575);