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

DeviceService.test.ts

1,126 lines42.2 KB

1import { describe, expect, it } from "@effect/vitest";
2import {
3 DEFAULT_SERVER_SETTINGS,
4 DeviceId,
5 DeviceOperationError,
6 LOCAL_DEVICE_HOST_ID,
7 ThreadId,
8 type DeviceSummary,
9 type DeviceServiceState,
10 type ServerSettings as Settings,
11 type SshDeviceHostConfig,
12} from "@t3tools/contracts";
13import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
14import * as NodeServices from "@effect/platform-node/NodeServices";
15import * as NetService from "@t3tools/shared/Net";
16import { SshCommandError } from "@t3tools/ssh/errors";
17import * as Effect from "effect/Effect";
18import * as Exit from "effect/Exit";
19import * as Deferred from "effect/Deferred";
20import * as Fiber from "effect/Fiber";
21import * as FileSystem from "effect/FileSystem";
22import * as Layer from "effect/Layer";
23import * as PubSub from "effect/PubSub";
24import * as Queue from "effect/Queue";
25import * as Ref from "effect/Ref";
26import * as Schema from "effect/Schema";
27import * as Sink from "effect/Sink";
28import * as Stream from "effect/Stream";
29import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
30import { HttpClient, HttpClientResponse } from "effect/http";
31import * as ServerConfig from "../config.ts";
32import * as ProcessRunner from "../processRunner.ts";
33import * as ServerSettings from "../serverSettings.ts";
34import * as DeviceHost from "./DeviceHost.ts";
35import { NodeRuntimeUnavailableError } from "@t3tools/shared/nodeRuntime";
36​
37import * as DeviceService from "./DeviceService.ts";
38​
39const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
40​
41const baseState: DeviceServiceState = {
42 hosts: [],
43 hostStatus: "idle",
44 hostStatuses: {},
45 devices: [],
46 sessions: [],
47 onboardingCompleted: false,
48 agentAccessEnabled: false,
49 hubBasePath: "/api/device-hub",
50 revision: 0,
51};
52​
53describe("DeviceService.stateStream", () => {
54 it.effect("emits the current snapshot and then every published change", () =>
55 Effect.gen(function* () {
56 const pubsub = yield* PubSub.unbounded<DeviceServiceState>();
57 const current = yield* Ref.make(baseState);
58 const service: Pick<DeviceService.DeviceService["Service"], "state" | "subscribe"> = {
59 state: Ref.get(current),
60 subscribe: PubSub.subscribe(pubsub),
61 };
62​
63 const collected = yield* DeviceService.stateStream(
64 service as DeviceService.DeviceService["Service"],
65 ).pipe(Stream.take(3), Stream.runCollect, Effect.forkChild);
66 yield* Effect.yieldNow;
67 for (const revision of [1, 2]) {
68 const next = { ...baseState, revision, hostStatus: "ready" as const };
69 yield* Ref.set(current, next);
70 yield* PubSub.publish(pubsub, next);
71 }
72 const seen = yield* Fiber.join(collected);
73 expect(seen.map((state) => state.revision)).toEqual([0, 1, 2]);
74 }),
75 );
76});
77​
78const fixture = Effect.fn("fixture")(function* (
79 onBoot: Effect.Effect<void> = Effect.void,
80 bootError?: string,
81 failListAfterShutdown = false,
82 runtimeFailure?:
83 | NodeRuntimeUnavailableError
84 | DeviceHost.DeviceHostError
85 | DeviceHost.AgentDeviceStartError,
86 inspectError = false,
87 installTool?: Parameters<typeof DeviceService.makeWithHosts>[3],
88) {
89 const settings = yield* Ref.make(DEFAULT_SERVER_SETTINGS);
90 const starts: string[] = [];
91 const agentStarts: string[] = [];
92 const agentStops: string[] = [];
93 const requests: string[] = [];
94 const devices: Array<Omit<DeviceSummary, "hostId">> = [];
95 const encoderResult = yield* Ref.make({ code: 0, stdout: " V....D libx264", stderr: "" });
96 let booted = false;
97 let shutDown = false;
98 const ready: DeviceHost.DeviceHostReady = {
99 nodePath: process.execPath,
100 hub: { origin: "http://device.test" },
101 helpers: { serveSimAxSettings: null, serveSimCli: null },
102 run: (command) =>
103 command === "emulator"
104 ? Effect.succeed({ code: 0, stdout: "Pixel_API_35\n", stderr: "" })
105 : Ref.get(encoderResult),
106 };
107 const host: DeviceHost.DeviceHost["Service"] = {
108 ...(inspectError
109 ? {
110 inspect: Effect.fail(
111 new DeviceHost.DeviceHostError({
112 hostId: LOCAL_DEVICE_HOST_ID,
113 step: "probe",
114 cause: new Error("offline"),
115 }),
116 ),
117 }
118 : {}),
119 id: LOCAL_DEVICE_HOST_ID,
120 summary: Effect.succeed({
121 id: LOCAL_DEVICE_HOST_ID,
122 kind: "local",
123 label: "Test server",
124 platforms: [
125 { platform: "android", available: true },
126 { platform: "ios", available: true },
127 ],
128 hubInstalled: true,
129 agentDeviceInstalled: false,
130 }),
131 platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
132 ensureReady: (onPhase) =>
133 Effect.gen(function* () {
134 if (runtimeFailure && runtimeFailure._tag !== "AgentDeviceStartError")
135 return yield* runtimeFailure;
136 starts.push("start");
137 yield* onPhase("installing", "Updating device hub from 0.9.0 to 0.10.1…");
138 return ready;
139 }),
140 ensureAgentReady: (onPhase) =>
141 Effect.gen(function* () {
142 if (runtimeFailure) return yield* runtimeFailure;
143 agentStarts.push("start");
144 yield* onPhase("starting");
145 return {
146 ...ready,
147 agentDevice: { baseUrl: "http://agent.test", token: "test", entryPath: "/agent" },
148 };
149 }),
150 current: Effect.succeed(null),
151 stopAgent: Effect.sync(() => {
152 agentStops.push("stop");
153 }),
154 stop: Effect.sync(() => {
155 starts.push("stop");
156 }),
157 };
158 const service = yield* DeviceService.makeWithHosts(
159 new Map([[host.id, host]]),
160 undefined,
161 undefined,
162 installTool,
163 ).pipe(
164 Effect.provide(NodeCrypto.layer),
165 Effect.provideService(DeviceHost.DeviceHost, host),
166 Effect.provideService(
167 ServerSettings.ServerSettingsService,
168 ServerSettings.ServerSettingsService.of({
169 updateProviderInstance: () => Effect.die("Unexpected provider mutation"),
170 withSettingsSnapshot: (use) => Effect.flatMap(Ref.get(settings), use),
171 start: Effect.void,
172 ready: Effect.void,
173 getSettings: Ref.get(settings),
174 updateSettings: (patch) =>
175 Ref.updateAndGet(settings, (current) => ({
176 ...current,
177 enableDeviceSupport: patch.enableDeviceSupport ?? current.enableDeviceSupport,
178 enableAgentDeviceAccess:
179 patch.enableAgentDeviceAccess ?? current.enableAgentDeviceAccess,
180 deviceOnboardingCompleted:
181 patch.deviceOnboardingCompleted ?? current.deviceOnboardingCompleted,
182 })),
183 streamChanges: Stream.empty,
184 subscribeChanges: Effect.succeed(Stream.empty),
185 }),
186 ),
187 Effect.provideService(
188 HttpClient.HttpClient,
189 HttpClient.make((request) =>
190 Effect.gen(function* () {
191 requests.push(request.url);
192 if (request.url.includes("/api/screenshot")) {
193 return HttpClientResponse.fromWeb(
194 request,
195 new Response(new Uint8Array([137, 80, 78, 71])),
196 );
197 }
198 if (request.url.endsWith("/shutdown")) {
199 shutDown = true;
200 booted = false;
201 return HttpClientResponse.fromWeb(request, Response.json({ ok: true }));
202 }
203 if (shutDown && failListAfterShutdown) {
204 return HttpClientResponse.fromWeb(
205 request,
206 new Response("Discovery busy", { status: 503 }),
207 );
208 }
209 if (request.url.endsWith("/boot")) {
210 yield* onBoot;
211 booted = true;
212 return HttpClientResponse.fromWeb(
213 request,
214 Response.json(
215 bootError ? { ok: false, error: bootError } : { ok: true, serial: "emulator-5554" },
216 ),
217 );
218 }
219 if (request.url.endsWith("/grid/api/start")) {
220 return HttpClientResponse.fromWeb(request, Response.json({ ok: true }));
221 }
222 return HttpClientResponse.fromWeb(
223 request,
224 Response.json({
225 simulators: devices.filter((device) => device.platform === "ios"),
226 emulators: [
227 ...devices.filter((device) => device.platform === "android"),
228 ...(booted
229 ? [
230 {
231 id: "emulator-5554",
232 name: "Pixel_API_35",
233 platform: "android",
234 version: "Android 15",
235 booted: true,
236 physical: false,
237 },
238 ]
239 : []),
240 ],
241 }),
242 );
243 }),
244 ),
245 ),
246 );
247 return { service, starts, agentStarts, agentStops, requests, settings, devices, encoderResult };
248});
249​
250describe("device setup consent", () => {
251 it.effect("exposes daemon startup diagnostics through agent readiness and host status", () =>
252 Effect.gen(function* () {
253 const startupError = new DeviceHost.AgentDeviceStartError({
254 hostId: LOCAL_DEVICE_HOST_ID,
255 stateDir: "/test/device/agent-device",
256 exitCode: 1,
257 reason: "daemon_lock_not_directory",
258 cause: { stdout: "private startup diagnostics", code: 1 },
259 });
260 const { service, settings } = yield* fixture(Effect.void, undefined, false, startupError);
261 yield* Ref.update(settings, (current) => ({
262 ...current,
263 enableDeviceSupport: true,
264 enableAgentDeviceAccess: true,
265 }));
266 const error = yield* service.agentReadinessIfSupported().pipe(Effect.flip);
267 expect(error).toMatchObject({
268 _tag: "DeviceHostUnavailableError",
269 reason: startupError.message,
270 cause: startupError,
271 });
272 expect(error.message).toContain("daemon.lock is not a directory");
273 expect(error.message).not.toContain("private startup diagnostics");
274 expect((yield* service.state).hostStatuses[LOCAL_DEVICE_HOST_ID]).toEqual({
275 status: "failed",
276 detail: startupError.message,
277 });
278 }).pipe(Effect.scoped),
279 );
280​
281 it.effect(
282 "preserves missing-runtime guidance and causes through manual and agent readiness",
283 () =>
284 Effect.gen(function* () {
285 const underlying = new Error("private lookup diagnostics");
286 const runtimeFailure = new NodeRuntimeUnavailableError({
287 feature: "Local device support",
288 cause: underlying,
289 });
290 const { service, settings, requests } = yield* fixture(
291 Effect.void,
292 undefined,
293 false,
294 runtimeFailure,
295 );
296 yield* Ref.update(settings, (current) => ({
297 ...current,
298 enableDeviceSupport: true,
299 enableAgentDeviceAccess: true,
300 }));
301 for (const readiness of [service.readiness(), service.agentReadinessIfSupported()]) {
302 const error = yield* readiness.pipe(Effect.flip);
303 expect(error).toMatchObject({
304 _tag: "DeviceHostUnavailableError",
305 reason: expect.stringContaining("Install Node.js"),
306 cause: runtimeFailure,
307 });
308 expect(error.message).not.toContain(underlying.message);
309 }
310 expect((yield* service.state).hostStatuses[LOCAL_DEVICE_HOST_ID]).toMatchObject({
311 status: "failed",
312 detail: expect.stringContaining("Install Node.js"),
313 });
314 expect(requests).toEqual([]);
315 }).pipe(Effect.scoped),
316 );
317​
318 it.effect("listing and provider startup do not start helpers before consent", () =>
319 Effect.gen(function* () {
320 const { service, starts, requests } = yield* fixture();
321 expect((yield* service.list).hostStatus).toBe("disabled");
322 expect(yield* service.readinessIfSupported()).toBeNull();
323 const readiness = yield* service.readiness().pipe(Effect.result);
324 expect(readiness._tag).toBe("Failure");
325 expect(starts).toEqual([]);
326 expect(requests).toEqual([]);
327 }).pipe(Effect.scoped),
328 );
329​
330 it.effect(
331 "explicit setup discovers never-booted AVDs; disabling stops helpers and blocks agents",
332 () =>
333 Effect.gen(function* () {
334 const { service, starts, settings } = yield* fixture();
335 const state = yield* service.configure({ enabled: true });
336 expect((yield* Ref.get(settings)).enableDeviceSupport).toBe(true);
337 expect(state.devices.map((device) => [device.id, device.booted])).toEqual([
338 ["Pixel_API_35", false],
339 ]);
340 expect(starts).toEqual(["start"]);
341 const disabled = yield* service.configure({ enabled: false });
342 expect(disabled.hostStatus).toBe("disabled");
343 expect(disabled.devices).toEqual([]);
344 expect((yield* Ref.get(settings)).enableDeviceSupport).toBe(false);
345 expect(yield* service.readinessIfSupported()).toBeNull();
346 expect(starts).toEqual(["start", "stop"]);
347 }).pipe(Effect.scoped),
348 );
349​
350 it.effect("boots a stopped Android AVD and uses its emulator serial without duplicating it", () =>
351 Effect.gen(function* () {
352 const { service, requests } = yield* fixture();
353 yield* service.configure({ enabled: true });
354 const session = yield* service.open({
355 threadId: ThreadId.make("thread-1"),
356 deviceId: "Pixel_API_35",
357 platform: "android",
358 });
359 expect(session.deviceId).toBe("emulator-5554");
360 expect(requests.filter((url) => url.endsWith("/boot"))).toHaveLength(1);
361 const state = yield* service.state;
362 expect(state.devices.map((device) => device.id)).toEqual(["emulator-5554"]);
363 expect(state.bootingDevices).toEqual([]);
364 }).pipe(Effect.scoped),
365 );
366​
367 it.effect("blocks only emulator video until ffmpeg is usable, then allows retry", () =>
368 Effect.gen(function* () {
369 const { service, requests, devices, encoderResult } = yield* fixture();
370 devices.push(
371 {
372 id: DeviceId.make("physical-android"),
373 name: "Pixel",
374 platform: "android",
375 version: "Android 15",
376 booted: true,
377 physical: true,
378 },
379 {
380 id: DeviceId.make("ios-simulator"),
381 name: "iPhone",
382 platform: "ios",
383 version: "iOS 18",
384 booted: true,
385 physical: false,
386 },
387 );
388 yield* Ref.set(encoderResult, { code: 127, stdout: "", stderr: "spawn ffmpeg ENOENT" });
389 const state = yield* service.configure({ enabled: true });
390 expect(state.devices.map((device) => device.id)).toEqual([
391 "ios-simulator",
392 "physical-android",
393 "Pixel_API_35",
394 ]);
395 const threadId = ThreadId.make("emulator-video-readiness");
396 const physical = yield* service.open({
397 threadId,
398 deviceId: "physical-android",
399 platform: "android",
400 });
401 const ios = yield* service.open({ threadId, deviceId: "ios-simulator", platform: "ios" });
402 expect(physical.deviceId).toBe("physical-android");
403 expect(ios.deviceId).toBe("ios-simulator");
404​
405 const openEmulator = service.open({
406 threadId,
407 deviceId: "Pixel_API_35",
408 platform: "android",
409 });
410 const missing = yield* openEmulator.pipe(Effect.flip);
411 expect(missing.message).toMatch(/ffmpeg/i);
412 expect(missing.message).toMatch(/emulator/i);
413 expect(requests.filter((url) => url.endsWith("/boot"))).toEqual([]);
414 expect((yield* service.state).sessions).toEqual([physical, ios]);
415 expect((yield* service.state).bootingDevices ?? []).toEqual([]);
416​
417 yield* Ref.set(encoderResult, { code: 1, stdout: "", stderr: "cannot execute ffmpeg" });
418 expect((yield* openEmulator.pipe(Effect.flip)).message).toMatch(/ffmpeg/i);
419 yield* Ref.set(encoderResult, {
420 code: 0,
421 stdout: " V....D libx264rgb libx264 H.264 / AVC RGB (codec h264)",
422 stderr: "",
423 });
424 expect((yield* openEmulator.pipe(Effect.flip)).message).toMatch(/libx264/i);
425 expect(requests.filter((url) => url.endsWith("/boot"))).toEqual([]);
426 expect((yield* service.state).sessions).toEqual([physical, ios]);
427​
428 devices.push({
429 id: DeviceId.make("emulator-5556"),
430 name: "Already_booted",
431 platform: "android",
432 version: "Android 15",
433 booted: true,
434 physical: false,
435 });
436 expect(
437 (yield* service
438 .open({ threadId, deviceId: "emulator-5556", platform: "android" })
439 .pipe(Effect.flip)).message,
440 ).toMatch(/libx264/i);
441​
442 yield* Ref.set(encoderResult, { code: 0, stdout: " V....D libx264", stderr: "" });
443 const emulator = yield* openEmulator;
444 expect(emulator.deviceId).toBe("emulator-5554");
445 expect(requests.filter((url) => url.endsWith("/boot"))).toHaveLength(1);
446 }).pipe(Effect.scoped),
447 );
448​
449 it.effect("installs agent support only after the separate agent permission", () =>
450 Effect.gen(function* () {
451 const { service, agentStarts, agentStops, settings } = yield* fixture();
452 yield* service.configure({ enabled: true });
453 expect(agentStarts).toEqual([]);
454 expect(yield* service.agentReadinessIfSupported()).toBeNull();
455​
456 yield* service.configure({ agentAccessEnabled: true });
457 expect(agentStarts).toEqual(["start"]);
458 expect((yield* Ref.get(settings)).enableAgentDeviceAccess).toBe(true);
459 expect((yield* service.state).agentAccessEnabled).toBe(true);
460​
461 yield* service.configure({ agentAccessEnabled: false, onboardingCompleted: true });
462 expect(agentStops).toEqual(["stop"]);
463 expect((yield* service.state).onboardingCompleted).toBe(true);
464 expect((yield* Ref.get(settings)).deviceOnboardingCompleted).toBe(true);
465 }).pipe(Effect.scoped),
466 );
467});
468​
469it.effect("publishes boot progress and does not restore sessions after support is disabled", () =>
470 Effect.gen(function* () {
471 const started = yield* Deferred.make<void>();
472 const finish = yield* Deferred.make<void>();
473 const { service } = yield* fixture(
474 Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(finish))),
475 );
476 yield* service.configure({ enabled: true });
477 const opening = yield* service
478 .open({ threadId: ThreadId.make("thread-1"), deviceId: "Pixel_API_35", platform: "android" })
479 .pipe(Effect.result, Effect.forkChild);
480 yield* Deferred.await(started);
481 expect((yield* service.state).bootingDevices?.map((device) => device.name)).toEqual([
482 "Pixel_API_35",
483 ]);
484 yield* service.configure({ enabled: false });
485 yield* Deferred.succeed(finish, undefined);
486 expect((yield* Fiber.join(opening))._tag).toBe("Failure");
487 const state = yield* service.state;
488 expect(state.hostStatus).toBe("disabled");
489 expect(state.devices).toEqual([]);
490 expect(state.sessions).toEqual([]);
491 expect(state.bootingDevices).toEqual([]);
492 }).pipe(Effect.scoped),
493);
494​
495describe("device discovery after server restart", () => {
496 it.effect("captures an explicit device before any client lists devices", () =>
497 Effect.gen(function* () {
498 const { service, settings, requests } = yield* fixture();
499 yield* Ref.update(settings, (current) => ({ ...current, enableDeviceSupport: true }));
500 expect((yield* service.state).devices).toEqual([]);
501 const capture = yield* service.screenshot({ deviceId: DeviceId.make("Pixel_API_35") });
502 expect(capture.device.id).toBe("Pixel_API_35");
503 expect(Array.from(capture.png)).toEqual([137, 80, 78, 71]);
504 expect(requests.some((url) => url.endsWith("/api/devices"))).toBe(true);
505 }).pipe(Effect.scoped),
506 );
507});
508​
509it.effect.each([
510 {
511 diagnostic: "Insufficient disk space at /private/user/path",
512 reason: "disk_space",
513 message: "not enough free disk space",
514 },
515 {
516 diagnostic: "Timed out spawning /private/user/command",
517 reason: "timeout",
518 message: "did not become ready in time",
519 },
520 {
521 diagnostic: "Unexpected failure: secret-token",
522 reason: "launch_failed",
523 message: "could not start",
524 },
525] as const)("normalizes boot failure: $reason", ({ diagnostic, message }) =>
526 Effect.gen(function* () {
527 const { service } = yield* fixture(Effect.void, diagnostic);
528 yield* service.configure({ enabled: true });
529 const error = yield* service
530 .open({
531 threadId: ThreadId.make("boot-failure"),
532 deviceId: "Pixel_API_35",
533 platform: "android",
534 })
535 .pipe(Effect.flip);
536 expect(error._tag).toBe("DeviceBootError");
537 expect(error.message).toContain(message);
538 expect(error.message).not.toContain(diagnostic);
539 expect((yield* service.state).bootingDevices).toEqual([]);
540 }).pipe(Effect.scoped),
541);
542​
543it.effect("keeps shutdown successful when subsequent discovery fails", () =>
544 Effect.gen(function* () {
545 const { service } = yield* fixture(Effect.void, undefined, true);
546 yield* service.configure({ enabled: true });
547 const threadId = ThreadId.make("shutdown-refresh");
548 const session = yield* service.open({
549 threadId,
550 deviceId: "Pixel_API_35",
551 platform: "android",
552 });
553 yield* service.close({ threadId, deviceId: session.deviceId, shutdown: true });
554 const state = yield* service.state;
555 expect(state.sessions).toEqual([]);
556 expect(state.devices.find((device) => device.id === session.deviceId)?.booted).toBe(false);
557 }).pipe(Effect.scoped),
558);
559​
560it.effect.each(["shutdown", "close"] as const)(
561 "%s releases iOS capture so reopening uses a fresh session",
562 (operation) =>
563 Effect.gen(function* () {
564 const deviceId = DeviceId.make("11111111-1111-1111-1111-111111111111");
565 const threadId = ThreadId.make("capture-recovery");
566 let booted = true;
567 let capture: number | null = null;
568 let generation = 0;
569 const ready: DeviceHost.DeviceHostReady = {
570 nodePath: process.execPath,
571 hub: { origin: "http://device.test" },
572 helpers: { serveSimAxSettings: null, serveSimCli: null },
573 run: () => Effect.succeed({ code: 0, stdout: "", stderr: "" }),
574 };
575 const host: DeviceHost.DeviceHost["Service"] = {
576 id: LOCAL_DEVICE_HOST_ID,
577 summary: Effect.succeed({
578 id: LOCAL_DEVICE_HOST_ID,
579 kind: "local",
580 label: "Simulator host",
581 platforms: [{ platform: "ios", available: true }],
582 hubInstalled: true,
583 agentDeviceInstalled: false,
584 }),
585 platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
586 ensureReady: () => Effect.succeed(ready),
587 ensureAgentReady: () => Effect.die("Agent access is not used in this test"),
588 current: Effect.succeed(ready),
589 stopAgent: Effect.void,
590 stop: Effect.void,
591 };
592 const http = HttpClient.make((request) =>
593 Effect.sync(() => {
594 const path = new URL(request.url).pathname;
595 if (path === "/api/devices") {
596 return HttpClientResponse.fromWeb(
597 request,
598 Response.json({
599 emulators: [],
600 simulators: [
601 {
602 id: deviceId,
603 name: "iPhone",
604 platform: "ios",
605 version: "26",
606 physical: false,
607 booted,
608 },
609 ],
610 }),
611 );
612 }
613 if (path === "/vendor/serve-sim/grid/api/start") capture ??= ++generation;
614 else if (path === "/vendor/serve-sim/grid/api/shutdown") {
615 if (request.body._tag !== "Uint8Array") throw new Error("Missing shutdown body");
616 expect(decodeJson(new TextDecoder().decode(request.body.body))).toEqual({
617 udid: deviceId,
618 });
619 capture = null;
620 booted = false;
621 } else if (path === "/api/devices/shutdown") {
622 // This route powers off without releasing serve-sim's cached capture.
623 booted = false;
624 } else if (path === "/api/devices/boot") booted = true;
625 else throw new Error(`Unexpected hub path: ${path}`);
626 return HttpClientResponse.fromWeb(request, Response.json({ ok: true, id: deviceId }));
627 }),
628 );
629 const service = yield* DeviceService.makeWithHosts(new Map([[host.id, host]])).pipe(
630 Effect.provide(NodeCrypto.layer),
631 Effect.provideService(HttpClient.HttpClient, http),
632 );
633 const input = { threadId, deviceId, platform: "ios" as const };
634 yield* service.open(input);
635 expect(capture).toBe(1);
636 if (operation === "shutdown") yield* service.shutdown(input);
637 else yield* service.close({ threadId, deviceId, shutdown: true });
638 expect(capture).toBeNull();
639 expect((yield* service.state).sessions).toEqual([]);
640 yield* service.open(input);
641 expect(capture).toBe(2);
642 expect((yield* service.state).sessions).toHaveLength(1);
643 }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true })), Effect.scoped),
644);
645​
646it.effect.each([
647 { hubReports: "off", outcome: "succeeds" },
648 { hubReports: "booted", outcome: "fails" },
649 { hubReports: "missing", outcome: "fails" },
650] as const)(
651 "iOS shutdown $outcome when serve-sim rejects it and the hub reports the simulator $hubReports",
652 ({ hubReports, outcome }) =>
653 Effect.gen(function* () {
654 const deviceId = DeviceId.make("22222222-2222-2222-2222-222222222222");
655 const paths: string[] = [];
656 let listed: "booted" | "off" | "missing" = "booted";
657 const ready: DeviceHost.DeviceHostReady = {
658 nodePath: process.execPath,
659 hub: { origin: "http://device.test" },
660 helpers: { serveSimAxSettings: null, serveSimCli: null },
661 run: () => Effect.succeed({ code: 0, stdout: "", stderr: "" }),
662 };
663 const host: DeviceHost.DeviceHost["Service"] = {
664 id: LOCAL_DEVICE_HOST_ID,
665 summary: Effect.succeed({
666 id: LOCAL_DEVICE_HOST_ID,
667 kind: "local",
668 label: "Simulator host",
669 platforms: [{ platform: "ios", available: true }],
670 hubInstalled: true,
671 agentDeviceInstalled: false,
672 }),
673 platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
674 ensureReady: () => Effect.succeed(ready),
675 ensureAgentReady: () => Effect.die("Agent access is not used in this test"),
676 current: Effect.succeed(ready),
677 stopAgent: Effect.void,
678 stop: Effect.void,
679 };
680 const http = HttpClient.make((request) =>
681 Effect.sync(() => {
682 const path = new URL(request.url).pathname;
683 paths.push(path);
684 if (path === "/api/devices") {
685 return HttpClientResponse.fromWeb(
686 request,
687 Response.json({
688 emulators: [],
689 simulators:
690 listed === "missing"
691 ? []
692 : [
693 {
694 id: deviceId,
695 name: "iPhone",
696 platform: "ios",
697 version: "26",
698 physical: false,
699 booted: listed === "booted",
700 },
701 ],
702 errors: listed === "missing" ? [{ message: "simctl list failed" }] : [],
703 }),
704 );
705 }
706 if (path === "/vendor/serve-sim/grid/api/shutdown") {
707 // serve-sim runs `simctl shutdown` bare and returns its failure as-is.
708 listed = hubReports;
709 return HttpClientResponse.fromWeb(
710 request,
711 Response.json(
712 { ok: false, error: "Unable to shutdown device in current state: Shutdown" },
713 { status: 500 },
714 ),
715 );
716 }
717 throw new Error(`Unexpected hub path: ${path}`);
718 }),
719 );
720 const service = yield* DeviceService.makeWithHosts(new Map([[host.id, host]])).pipe(
721 Effect.provide(NodeCrypto.layer),
722 Effect.provideService(HttpClient.HttpClient, http),
723 );
724 yield* service.list;
725 const exit = yield* Effect.exit(service.shutdown({ deviceId, platform: "ios" }));
726 expect(paths.filter((path) => path.endsWith("shutdown"))).toEqual([
727 "/vendor/serve-sim/grid/api/shutdown",
728 ]);
729 if (outcome === "succeeds") {
730 expect(Exit.isSuccess(exit)).toBe(true);
731 expect(
732 (yield* service.state).devices.find((device) => device.id === deviceId)?.booted,
733 ).toBe(false);
734 } else {
735 expect(Exit.isFailure(exit)).toBe(true);
736 expect(
737 (yield* service.state).devices.find((device) => device.id === deviceId)?.booted,
738 ).toBe(true);
739 }
740 }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true })), Effect.scoped),
741);
742​
743it.effect("retry keeps device and agent consent unchanged", () =>
744 Effect.gen(function* () {
745 const { service, starts, agentStarts } = yield* fixture();
746 yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
747 expect(starts).toEqual([]);
748 expect(agentStarts).toEqual([]);
749 yield* service.configure({ enabled: true });
750 yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
751 expect(agentStarts).toEqual([]);
752 yield* service.configure({ agentAccessEnabled: true });
753 const before = agentStarts.length;
754 yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
755 expect(agentStarts.length).toBe(before + 1);
756 }).pipe(Effect.scoped),
757);
758​
759it.effect("publishes update detail for the correct host", () =>
760 Effect.gen(function* () {
761 const { service } = yield* fixture();
762 const changes = yield* service.subscribe;
763 yield* service.configure({ enabled: true });
764 const states = yield* PubSub.takeAll(changes);
765 expect(
766 states.some(
767 (state) => state.hostStatuses.local?.detail === "Updating device hub from 0.9.0 to 0.10.1…",
768 ),
769 ).toBe(true);
770 }).pipe(Effect.scoped),
771);
772​
773it.effect("host retry exposes actionable failure without internal IDs or diagnostics", () =>
774 Effect.gen(function* () {
775 const { service, settings } = yield* fixture(
776 Effect.void,
777 undefined,
778 false,
779 new DeviceHost.DeviceHostError({
780 hostId: LOCAL_DEVICE_HOST_ID,
781 step: "probe",
782 cause: "private diagnostics",
783 }),
784 );
785 yield* Ref.update(settings, (current) => ({ ...current, enableDeviceSupport: true }));
786 const state = yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
787 expect(state.supportsHostRetry).toBe(true);
788 expect(state.hostStatuses[LOCAL_DEVICE_HOST_ID]).toEqual({
789 status: "failed",
790 detail: "Could not connect to this host over SSH.",
791 });
792 }).pipe(Effect.scoped),
793);
794​
795it.effect.each([
796 {
797 name: "missing Node among private diagnostic lines",
798 exitCode: 1,
799 stderr:
800 "private diagnostics\r\nNode is missing from the non-interactive SSH PATH\r\nprivate diagnostics",
801 expected:
802 "Connected over SSH, but Node is not on this host's PATH for non-interactive SSH commands.",
803 },
804 {
805 name: "another remote command failure",
806 exitCode: 2,
807 stderr: "private diagnostics",
808 expected: "Connected over SSH, but the device host check failed (exit code 2).",
809 },
810 {
811 name: "an unrecognized exit-one diagnostic",
812 exitCode: 1,
813 stderr: "private diagnostics: Node is missing from the non-interactive SSH PATH",
814 expected: "Connected over SSH, but the device host check failed (exit code 1).",
815 },
816 {
817 name: "a connection failure",
818 exitCode: 255,
819 stderr: "Node is missing from the non-interactive SSH PATH",
820 expected: "Could not connect to this host over SSH.",
821 },
822 {
823 name: "a command that could not start",
824 exitCode: null,
825 stderr: "private diagnostics",
826 expected: "Could not connect to this host over SSH.",
827 },
828 {
829 name: "an untyped offline cause",
830 exitCode: undefined,
831 stderr: "private diagnostics",
832 expected: "Could not connect to this host over SSH.",
833 },
834])("reports $name through manual and agent host readiness", ({ exitCode, stderr, expected }) =>
835 Effect.gen(function* () {
836 const failure = new DeviceHost.DeviceHostError({
837 hostId: LOCAL_DEVICE_HOST_ID,
838 step: "probe",
839 cause:
840 exitCode === undefined
841 ? "offline"
842 : new SshCommandError({
843 command: ["ssh", "private arguments"],
844 exitCode,
845 stderr,
846 stdout: "private output",
847 message: "private diagnostics",
848 }),
849 });
850 const { service, settings } = yield* fixture(Effect.void, undefined, false, failure);
851 yield* Ref.update(settings, (current) => ({
852 ...current,
853 enableDeviceSupport: true,
854 enableAgentDeviceAccess: true,
855 }));
856 for (const readiness of [service.readiness(), service.agentReadinessIfSupported()]) {
857 const error = yield* readiness.pipe(Effect.flip);
858 expect(error).toMatchObject({ reason: expected, cause: failure });
859 expect((yield* service.state).hostStatuses[LOCAL_DEVICE_HOST_ID]).toEqual({
860 status: "failed",
861 detail: expected,
862 });
863 }
864 for (const state of [yield* service.list, yield* service.retryHost(LOCAL_DEVICE_HOST_ID)]) {
865 expect(state.hostStatuses[LOCAL_DEVICE_HOST_ID]).toEqual({
866 status: "failed",
867 detail: expected,
868 });
869 }
870 }).pipe(Effect.scoped),
871);
872​
873it.effect("version discovery does not grant consent or start device tools", () =>
874 Effect.gen(function* () {
875 const { service, starts, agentStarts, requests } = yield* fixture();
876 const state = yield* service.inspect;
877 expect(state.supportsToolInspection).toBe(true);
878 expect(state.hostStatus).toBe("disabled");
879 expect(state.hosts).toHaveLength(1);
880 expect(starts).toEqual([]);
881 expect(agentStarts).toEqual([]);
882 expect(requests).toEqual([]);
883 }).pipe(Effect.scoped),
884);
885​
886it.effect("failed read-only discovery preserves lifecycle status and installed inventory", () =>
887 Effect.gen(function* () {
888 const { service, starts } = yield* fixture(Effect.void, undefined, false, undefined, true);
889 const state = yield* service.inspect;
890 expect(state.supportsToolInspection).toBe(true);
891 expect(state.hostStatus).toBe("disabled");
892 expect(state.hosts[0]?.hubInstalled).toBe(true);
893 expect(state.hosts[0]?.toolInspectionError).toContain("Reconnect the host");
894 expect(starts).toEqual([]);
895 }).pipe(Effect.scoped),
896);
897​
898it.effect(
899 "manual updates install only the selected tool without enabling access or starting helpers",
900 () =>
901 Effect.gen(function* () {
902 const installed: string[] = [];
903 const { service, starts, agentStarts, requests } = yield* fixture(
904 Effect.void,
905 undefined,
906 false,
907 undefined,
908 false,
909 (tool) =>
910 Effect.sync(() => {
911 installed.push(tool);
912 }),
913 );
914 const before = yield* service.state;
915 const state = yield* service.updateTool("agent");
916 expect(installed).toEqual(["agent"]);
917 expect(state.supportsToolUpdate).toBe(true);
918 expect(state.hostStatus).toBe(before.hostStatus);
919 expect(state.agentAccessEnabled).toBe(before.agentAccessEnabled);
920 expect(state.revision).toBeGreaterThan(before.revision);
921 expect(starts).toEqual([]);
922 expect(agentStarts).toEqual([]);
923 expect(requests).toEqual([]);
924 yield* service.updateTool("hub");
925 expect(installed).toEqual(["agent", "hub"]);
926 }).pipe(Effect.scoped),
927);
928​
929it.effect("failed manual installation leaves lifecycle state unchanged and can be retried", () =>
930 Effect.gen(function* () {
931 let attempts = 0;
932 const { service, starts, agentStarts } = yield* fixture(
933 Effect.void,
934 undefined,
935 false,
936 undefined,
937 false,
938 () =>
939 Effect.suspend(() =>
940 ++attempts === 1
941 ? Effect.fail(
942 new DeviceOperationError({
943 operation: "update device tool",
944 reason: "command_failed",
945 cause: new Error("offline"),
946 }),
947 )
948 : Effect.void,
949 ),
950 );
951 const before = yield* service.state;
952 const result = yield* service.updateTool("agent").pipe(Effect.result);
953 expect(result._tag).toBe("Failure");
954 expect(yield* service.state).toEqual(before);
955 yield* service.updateTool("agent");
956 expect(attempts).toBe(2);
957 expect(starts).toEqual([]);
958 expect(agentStarts).toEqual([]);
959 }).pipe(Effect.scoped),
960);
961​
962it.effect("reconciles SSH host settings without publishing no-op changes", () =>
963 Effect.gen(function* () {
964 const fs = yield* FileSystem.FileSystem;
965 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-reconcile-" });
966 const settings = yield* ServerSettings.ServerSettingsService;
967 // Each change is acknowledged after reconciliation consumed it, so no-ops are observable.
968 const changes = yield* Queue.unbounded<{ value: Settings; done: Deferred.Deferred<void> }>();
969 const removedFiles: string[] = [];
970 const localHost: DeviceHost.DeviceHost["Service"] = {
971 id: LOCAL_DEVICE_HOST_ID,
972 summary: Effect.succeed({
973 id: LOCAL_DEVICE_HOST_ID,
974 label: "Local",
975 kind: "local",
976 platforms: [],
977 hubInstalled: false,
978 agentDeviceInstalled: false,
979 }),
980 platformAvailability: (platform) => Effect.succeed({ platform, available: false }),
981 current: Effect.succeed(null),
982 ensureReady: () => Effect.die("Unexpected device launch"),
983 ensureAgentReady: () => Effect.die("Unexpected agent launch"),
984 stop: Effect.void,
985 stopAgent: Effect.void,
986 };
987 const service = yield* DeviceService.make.pipe(
988 Effect.provideService(DeviceHost.DeviceHost, localHost),
989 Effect.provideService(ServerSettings.ServerSettingsService, {
990 ...settings,
991 subscribeChanges: Effect.succeed(
992 Stream.fromQueue(changes).pipe(
993 Stream.flatMap(({ value, done }) =>
994 Stream.make(value).pipe(
995 Stream.concat(
996 Stream.fromEffect(Deferred.succeed(done, undefined)).pipe(Stream.drain),
997 ),
998 ),
999 ),
1000 ),
1001 ),
1002 }),
1003 Effect.provideService(
1004 FileSystem.FileSystem,
1005 FileSystem.makeNoop({
1006 remove: (file) => Effect.sync(() => void removedFiles.push(file)),
1007 }),
1008 ),
1009 Effect.provideService(ProcessRunner.ProcessRunner, {
1010 run: () => Effect.die("Unexpected helper launch"),
1011 }),
1012 Effect.provideService(
1013 HttpClient.HttpClient,
1014 HttpClient.make(() => Effect.die("Unexpected HTTP request")),
1015 ),
1016 // `ssh -G` resolves the target to a non-local address.
1017 Effect.provideService(
1018 ChildProcessSpawner.ChildProcessSpawner,
1019 ChildProcessSpawner.make(() =>
1020 Effect.succeed(
1021 ChildProcessSpawner.makeHandle({
1022 pid: ChildProcessSpawner.ProcessId(123),
1023 stdout: Stream.make(new TextEncoder().encode("hostname 192.0.2.1\nport 22\n")),
1024 stderr: Stream.empty,
1025 all: Stream.empty,
1026 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
1027 isRunning: Effect.succeed(false),
1028 kill: () => Effect.void,
1029 stdin: Sink.drain,
1030 getInputFd: () => Sink.drain,
1031 getOutputFd: () => Stream.empty,
1032 unref: Effect.succeed(Effect.void),
1033 }),
1034 ),
1035 ),
1036 ),
1037 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(baseDir, baseDir), NetService.layer)),
1038 );
1039 const update = Effect.fnUntraced(function* (deviceHosts: ReadonlyArray<SshDeviceHostConfig>) {
1040 const value = yield* settings.updateSettings({ deviceHosts: [...deviceHosts] });
1041 const done = yield* Deferred.make<void>();
1042 yield* Queue.offer(changes, { value, done });
1043 yield* Deferred.await(done);
1044 return yield* service.state;
1045 });
1046​
1047 const initial = yield* service.state;
1048 expect(yield* update([])).toEqual(initial);
1049​
1050 const host: SshDeviceHostConfig = { id: "remote", label: "Remote", target: "remote-fixture" };
1051 const added = yield* update([host]);
1052 expect(added.hosts.map((entry) => entry.id)).toEqual([LOCAL_DEVICE_HOST_ID, host.id]);
1053 expect(yield* update([{ ...host }])).toEqual(added);
1054​
1055 yield* service.setHostStatus(host.id, { status: "failed", detail: "stale" });
1056 const removed = yield* update([]);
1057 expect(removed.hosts.map((entry) => entry.id)).toEqual([LOCAL_DEVICE_HOST_ID]);
1058 expect(removed.hostStatuses[host.id]).toBeUndefined();
1059 expect(removedFiles).toHaveLength(1);
1060 }).pipe(
1061 Effect.scoped,
1062 Effect.provide(Layer.mergeAll(ServerSettings.layerTest(), NodeServices.layer)),
1063 ),
1065​
1066it.effect("a failed tool update reports npm's exit code but not its output", () =>
1067 Effect.gen(function* () {
1068 const host: DeviceHost.DeviceHost["Service"] = {
1069 id: LOCAL_DEVICE_HOST_ID,
1070 summary: Effect.succeed({
1071 id: LOCAL_DEVICE_HOST_ID,
1072 kind: "local",
1073 label: "Test server",
1074 platforms: [],
1075 hubInstalled: false,
1076 agentDeviceInstalled: false,
1077 }),
1078 platformAvailability: (platform) => Effect.succeed({ platform, available: false }),
1079 ensureReady: () => Effect.die("Updating a tool does not start the hub"),
1080 ensureAgentReady: () => Effect.die("Updating a tool does not start the agent"),
1081 current: Effect.succeed(null),
1082 stopAgent: Effect.void,
1083 stop: Effect.void,
1084 };
1085 const npmFailure = {
1086 code: ChildProcessSpawner.ExitCode(243),
1087 stdout: "",
1088 stderr: "npm error EACCES https://private:credential@registry.example.test/expo-device-hub",
1089 timedOut: false,
1090 stdoutTruncated: false,
1091 stderrTruncated: false,
1092 stdoutInvalidUtf8: false,
1093 stderrInvalidUtf8: false,
1094 };
1095 const service = yield* DeviceService.make.pipe(
1096 Effect.provideService(DeviceHost.DeviceHost, host),
1097 Effect.provideService(ProcessRunner.ProcessRunner, {
1098 run: () => Effect.succeed(npmFailure),
1099 }),
1100 Effect.provideService(
1101 HttpClient.HttpClient,
1102 HttpClient.make(() => Effect.die("Updating a tool makes no hub requests")),
1103 ),
1104 );
1105​
1106 const error = yield* service.updateTool("hub").pipe(Effect.flip);
1107 expect(error).toMatchObject({
1108 _tag: "DeviceOperationError",
1109 reason: "command_failed",
1110 exitCode: 243,
1111 });
1112 expect(error.message).toBe(
1113 "Device update device tool failed: The device command failed (exit code 243).",
1114 );
1115 }).pipe(
1116 Effect.provide(
1117 Layer.mergeAll(
1118 ServerSettings.layerTest({ enableDeviceSupport: true }),
1119 ServerConfig.layerTest(process.cwd(), { prefix: "t3-device-update-" }),
1120 NodeCrypto.layer,
1121 NetService.layer,
1122 ).pipe(Layer.provideMerge(NodeServices.layer)),
1123 ),
1124 Effect.scoped,
1125 ),