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

DeviceService.test.ts

471 lines18.0 KB

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