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

DeviceService.test.ts

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