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

DeviceService.test.ts

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