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

DeviceService.test.ts

380 lines14.3 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 start: Effect.void,
122 ready: Effect.void,
123 getSettings: Ref.get(settings),
124 updateSettings: (patch) =>
125 Ref.updateAndGet(settings, (current) => ({
126 ...current,
127 enableDeviceSupport: patch.enableDeviceSupport ?? current.enableDeviceSupport,
128 enableAgentDeviceAccess:
129 patch.enableAgentDeviceAccess ?? current.enableAgentDeviceAccess,
130 deviceOnboardingCompleted:
131 patch.deviceOnboardingCompleted ?? current.deviceOnboardingCompleted,
132 })),
133 streamChanges: Stream.empty,
134 subscribeChanges: Effect.succeed(Stream.empty),
135 }),
136 ),
137 Effect.provideService(
138 HttpClient.HttpClient,
139 HttpClient.make((request) =>
140 Effect.gen(function* () {
141 requests.push(request.url);
142 if (request.url.includes("/api/screenshot")) {
143 return HttpClientResponse.fromWeb(
144 request,
145 new Response(new Uint8Array([137, 80, 78, 71])),
146 );
147 }
148 if (request.url.endsWith("/shutdown")) {
149 shutDown = true;
150 booted = false;
151 return HttpClientResponse.fromWeb(request, Response.json({ ok: true }));
152 }
153 if (shutDown && failListAfterShutdown) {
154 return HttpClientResponse.fromWeb(
155 request,
156 new Response("Discovery busy", { status: 503 }),
157 );
158 }
159 if (request.url.endsWith("/boot")) {
160 yield* onBoot;
161 booted = true;
162 return HttpClientResponse.fromWeb(
163 request,
164 Response.json(
165 bootError ? { ok: false, error: bootError } : { ok: true, serial: "emulator-5554" },
166 ),
167 );
168 }
169 return HttpClientResponse.fromWeb(
170 request,
171 Response.json({
172 simulators: [],
173 emulators: booted
174 ? [
175 {
176 id: "emulator-5554",
177 name: "Pixel_API_35",
178 platform: "android",
179 version: "Android 15",
180 booted: true,
181 physical: false,
182 },
183 ]
184 : [],
185 }),
186 );
187 }),
188 ),
189 ),
190 );
191 return { service, starts, agentStarts, agentStops, requests, settings };
192});
193​
194describe("device setup consent", () => {
195 it.effect(
196 "preserves missing-runtime guidance and causes through manual and agent readiness",
197 () =>
198 Effect.gen(function* () {
199 const underlying = new Error("private lookup diagnostics");
200 const runtimeFailure = new NodeRuntimeUnavailableError({
201 feature: "Local device support",
202 cause: underlying,
203 });
204 const { service, settings, requests } = yield* fixture(
205 Effect.void,
206 undefined,
207 false,
208 runtimeFailure,
209 );
210 yield* Ref.update(settings, (current) => ({
211 ...current,
212 enableDeviceSupport: true,
213 enableAgentDeviceAccess: true,
214 }));
215 for (const readiness of [service.readiness(), service.agentReadinessIfSupported()]) {
216 const error = yield* readiness.pipe(Effect.flip);
217 expect(error).toMatchObject({
218 _tag: "DeviceHostUnavailableError",
219 reason: expect.stringContaining("Install Node.js"),
220 cause: runtimeFailure,
221 });
222 expect(error.message).not.toContain(underlying.message);
223 }
224 expect((yield* service.state).hostStatuses[LOCAL_DEVICE_HOST_ID]).toMatchObject({
225 status: "failed",
226 detail: expect.stringContaining("Install Node.js"),
227 });
228 expect(requests).toEqual([]);
229 }).pipe(Effect.scoped),
230 );
231​
232 it.effect("listing and provider startup do not start helpers before consent", () =>
233 Effect.gen(function* () {
234 const { service, starts, requests } = yield* fixture();
235 expect((yield* service.list).hostStatus).toBe("disabled");
236 expect(yield* service.readinessIfSupported()).toBeNull();
237 const readiness = yield* service.readiness().pipe(Effect.result);
238 expect(readiness._tag).toBe("Failure");
239 expect(starts).toEqual([]);
240 expect(requests).toEqual([]);
241 }).pipe(Effect.scoped),
242 );
243​
244 it.effect(
245 "explicit setup discovers never-booted AVDs; disabling stops helpers and blocks agents",
246 () =>
247 Effect.gen(function* () {
248 const { service, starts, settings } = yield* fixture();
249 const state = yield* service.configure({ enabled: true });
250 expect((yield* Ref.get(settings)).enableDeviceSupport).toBe(true);
251 expect(state.devices.map((device) => [device.id, device.booted])).toEqual([
252 ["Pixel_API_35", false],
253 ]);
254 expect(starts).toEqual(["start"]);
255 const disabled = yield* service.configure({ enabled: false });
256 expect(disabled.hostStatus).toBe("disabled");
257 expect(disabled.devices).toEqual([]);
258 expect((yield* Ref.get(settings)).enableDeviceSupport).toBe(false);
259 expect(yield* service.readinessIfSupported()).toBeNull();
260 expect(starts).toEqual(["start", "stop"]);
261 }).pipe(Effect.scoped),
262 );
263​
264 it.effect("boots a stopped Android AVD and uses its emulator serial without duplicating it", () =>
265 Effect.gen(function* () {
266 const { service, requests } = yield* fixture();
267 yield* service.configure({ enabled: true });
268 const session = yield* service.open({
269 threadId: ThreadId.make("thread-1"),
270 deviceId: "Pixel_API_35",
271 platform: "android",
272 });
273 expect(session.deviceId).toBe("emulator-5554");
274 expect(requests.filter((url) => url.endsWith("/boot"))).toHaveLength(1);
275 const state = yield* service.state;
276 expect(state.devices.map((device) => device.id)).toEqual(["emulator-5554"]);
277 expect(state.bootingDevices).toEqual([]);
278 }).pipe(Effect.scoped),
279 );
280​
281 it.effect("installs agent support only after the separate agent permission", () =>
282 Effect.gen(function* () {
283 const { service, agentStarts, agentStops, settings } = yield* fixture();
284 yield* service.configure({ enabled: true });
285 expect(agentStarts).toEqual([]);
286 expect(yield* service.agentReadinessIfSupported()).toBeNull();
287​
288 yield* service.configure({ agentAccessEnabled: true });
289 expect(agentStarts).toEqual(["start"]);
290 expect((yield* Ref.get(settings)).enableAgentDeviceAccess).toBe(true);
291 expect((yield* service.state).agentAccessEnabled).toBe(true);
292​
293 yield* service.configure({ agentAccessEnabled: false, onboardingCompleted: true });
294 expect(agentStops).toEqual(["stop"]);
295 expect((yield* service.state).onboardingCompleted).toBe(true);
296 expect((yield* Ref.get(settings)).deviceOnboardingCompleted).toBe(true);
297 }).pipe(Effect.scoped),
298 );
299});
300​
301it.effect("publishes boot progress and does not restore sessions after support is disabled", () =>
302 Effect.gen(function* () {
303 const started = yield* Deferred.make<void>();
304 const finish = yield* Deferred.make<void>();
305 const { service } = yield* fixture(
306 Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(finish))),
307 );
308 yield* service.configure({ enabled: true });
309 const opening = yield* service
310 .open({ threadId: ThreadId.make("thread-1"), deviceId: "Pixel_API_35", platform: "android" })
311 .pipe(Effect.result, Effect.forkChild);
312 yield* Deferred.await(started);
313 expect((yield* service.state).bootingDevices?.map((device) => device.name)).toEqual([
314 "Pixel_API_35",
315 ]);
316 yield* service.configure({ enabled: false });
317 yield* Deferred.succeed(finish, undefined);
318 expect((yield* Fiber.join(opening))._tag).toBe("Failure");
319 const state = yield* service.state;
320 expect(state.hostStatus).toBe("disabled");
321 expect(state.devices).toEqual([]);
322 expect(state.sessions).toEqual([]);
323 expect(state.bootingDevices).toEqual([]);
324 }).pipe(Effect.scoped),
325);
326​
327describe("device discovery after server restart", () => {
328 it.effect("captures an explicit device before any client lists devices", () =>
329 Effect.gen(function* () {
330 const { service, settings, requests } = yield* fixture();
331 yield* Ref.update(settings, (current) => ({ ...current, enableDeviceSupport: true }));
332 expect((yield* service.state).devices).toEqual([]);
333 const capture = yield* service.screenshot({ deviceId: DeviceId.make("Pixel_API_35") });
334 expect(capture.device.id).toBe("Pixel_API_35");
335 expect(Array.from(capture.png)).toEqual([137, 80, 78, 71]);
336 expect(requests.some((url) => url.endsWith("/api/devices"))).toBe(true);
337 }).pipe(Effect.scoped),
338 );
339});
340​
341for (const [diagnostic, reason, message] of [
342 ["Insufficient disk space at /private/user/path", "disk_space", "not enough free disk space"],
343 ["Timed out spawning /private/user/command", "timeout", "did not become ready in time"],
344 ["Unexpected failure: secret-token", "launch_failed", "could not start"],
345] as const) {
346 it.effect(`normalizes boot failure: ${reason}`, () =>
347 Effect.gen(function* () {
348 const { service } = yield* fixture(Effect.void, diagnostic);
349 yield* service.configure({ enabled: true });
350 const error = yield* service
351 .open({
352 threadId: ThreadId.make("boot-failure"),
353 deviceId: "Pixel_API_35",
354 platform: "android",
355 })
356 .pipe(Effect.flip);
357 expect(error._tag).toBe("DeviceBootError");
358 expect(error.message).toContain(message);
359 expect(error.message).not.toContain(diagnostic);
360 expect((yield* service.state).bootingDevices).toEqual([]);
361 }).pipe(Effect.scoped),
362 );
364​
365it.effect("keeps shutdown successful when subsequent discovery fails", () =>
366 Effect.gen(function* () {
367 const { service } = yield* fixture(Effect.void, undefined, true);
368 yield* service.configure({ enabled: true });
369 const threadId = ThreadId.make("shutdown-refresh");
370 const session = yield* service.open({
371 threadId,
372 deviceId: "Pixel_API_35",
373 platform: "android",
374 });
375 yield* service.close({ threadId, deviceId: session.deviceId, shutdown: true });
376 const state = yield* service.state;
377 expect(state.sessions).toEqual([]);
378 expect(state.devices.find((device) => device.id === session.deviceId)?.booted).toBe(false);
379 }).pipe(Effect.scoped),
380);