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

DeviceService.test.ts

1,374 lines51.4 KB

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