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

DeviceService.test.ts

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