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

DeviceService.test.ts

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