Open History to see the last commit
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("retry keeps device and agent consent unchanged", () =>
846 Effect.gen(function* () {
847 const { service, starts, agentStarts } = yield* fixture();
848 yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
849 expect(starts).toEqual([]);
850 expect(agentStarts).toEqual([]);
851 yield* service.configure({ enabled: true });
852 yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
853 expect(agentStarts).toEqual([]);
854 yield* service.configure({ agentAccessEnabled: true });
855 const before = agentStarts.length;
856 yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
857 expect(agentStarts.length).toBe(before + 1);
858 }).pipe(Effect.scoped),
859);
860
861it.effect("publishes update detail for the correct host", () =>
862 Effect.gen(function* () {
863 const { service } = yield* fixture();
864 const changes = yield* service.subscribe;
865 yield* service.configure({ enabled: true });
866 const states = yield* PubSub.takeAll(changes);
867 expect(
868 states.some(
869 (state) => state.hostStatuses.local?.detail === "Updating device hub from 0.9.0 to 0.10.1…",
870 ),
871 ).toBe(true);
872 }).pipe(Effect.scoped),
873);
874
875it.effect("host retry exposes actionable failure without internal IDs or diagnostics", () =>
876 Effect.gen(function* () {
877 const { service, settings } = yield* fixture(
878 Effect.void,
879 undefined,
880 false,
881 new DeviceHost.DeviceHostError({
882 hostId: LOCAL_DEVICE_HOST_ID,
883 step: "probe",
884 cause: "private diagnostics",
885 }),
886 );
887 yield* Ref.update(settings, (current) => ({ ...current, enableDeviceSupport: true }));
888 const state = yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
889 expect(state.supportsHostRetry).toBe(true);
890 expect(state.hostStatuses[LOCAL_DEVICE_HOST_ID]).toEqual({
891 status: "failed",
892 detail: "Could not connect to this host over SSH.",
893 });
894 }).pipe(Effect.scoped),
895);
896
897it.effect.each([
898 {
899 name: "missing Node among private diagnostic lines",
900 exitCode: 1,
901 stderr:
902 "private diagnostics\r\nNode is missing from the non-interactive SSH PATH\r\nprivate diagnostics",
903 expected:
904 "Connected over SSH, but Node is not on this host's PATH for non-interactive SSH commands.",
905 },
906 {
907 name: "another remote command failure",
908 exitCode: 2,
909 stderr: "private diagnostics",
910 expected: "Connected over SSH, but the device host check failed (exit code 2).",
911 },
912 {
913 name: "an unrecognized exit-one diagnostic",
914 exitCode: 1,
915 stderr: "private diagnostics: Node is missing from the non-interactive SSH PATH",
916 expected: "Connected over SSH, but the device host check failed (exit code 1).",
917 },
918 {
919 name: "a connection failure",
920 exitCode: 255,
921 stderr: "Node is missing from the non-interactive SSH PATH",
922 expected: "Could not connect to this host over SSH.",
923 },
924 {
925 name: "a command that could not start",
926 exitCode: null,
927 stderr: "private diagnostics",
928 expected: "Could not connect to this host over SSH.",
929 },
930 {
931 name: "an untyped offline cause",
932 exitCode: undefined,
933 stderr: "private diagnostics",
934 expected: "Could not connect to this host over SSH.",
935 },
936])("reports $name through manual and agent host readiness", ({ exitCode, stderr, expected }) =>
937 Effect.gen(function* () {
938 const failure = new DeviceHost.DeviceHostError({
939 hostId: LOCAL_DEVICE_HOST_ID,
940 step: "probe",
941 cause:
942 exitCode === undefined
943 ? "offline"
944 : new SshCommandError({
945 command: ["ssh", "private arguments"],
946 exitCode,
947 stderr,
948 stdout: "private output",
949 message: "private diagnostics",
950 }),
951 });
952 const { service, settings } = yield* fixture(Effect.void, undefined, false, failure);
953 yield* Ref.update(settings, (current) => ({
954 ...current,
955 enableDeviceSupport: true,
956 enableAgentDeviceAccess: true,
957 }));
958 for (const readiness of [service.readiness(), service.agentReadinessIfSupported()]) {
959 const error = yield* readiness.pipe(Effect.flip);
960 expect(error).toMatchObject({ reason: expected, cause: failure });
961 expect((yield* service.state).hostStatuses[LOCAL_DEVICE_HOST_ID]).toEqual({
962 status: "failed",
963 detail: expected,
964 });
965 }
966 for (const state of [yield* service.list, yield* service.retryHost(LOCAL_DEVICE_HOST_ID)]) {
967 expect(state.hostStatuses[LOCAL_DEVICE_HOST_ID]).toEqual({
968 status: "failed",
969 detail: expected,
970 });
971 }
972 }).pipe(Effect.scoped),
973);
974
975it.effect("version discovery does not grant consent or start device tools", () =>
976 Effect.gen(function* () {
977 const { service, starts, agentStarts, requests } = yield* fixture();
978 const state = yield* service.inspect;
979 expect(state.supportsToolInspection).toBe(true);
980 expect(state.hostStatus).toBe("disabled");
981 expect(state.hosts).toHaveLength(1);
982 expect(starts).toEqual([]);
983 expect(agentStarts).toEqual([]);
984 expect(requests).toEqual([]);
985 }).pipe(Effect.scoped),
986);
987
988it.effect("failed read-only discovery preserves lifecycle status and installed inventory", () =>
989 Effect.gen(function* () {
990 const { service, starts } = yield* fixture(Effect.void, undefined, false, undefined, true);
991 const state = yield* service.inspect;
992 expect(state.supportsToolInspection).toBe(true);
993 expect(state.hostStatus).toBe("disabled");
994 expect(state.hosts[0]?.hubInstalled).toBe(true);
995 expect(state.hosts[0]?.toolInspectionError).toContain("Reconnect the host");
996 expect(starts).toEqual([]);
997 }).pipe(Effect.scoped),
998);
999
1000it.effect(
1001 "manual updates install only the selected tool without enabling access or starting helpers",
1002 () =>
1003 Effect.gen(function* () {
1004 const installed: string[] = [];
1005 const { service, starts, agentStarts, requests } = yield* fixture(
1006 Effect.void,
1007 undefined,
1008 false,
1009 undefined,
1010 false,
1011 (tool) =>
1012 Effect.sync(() => {
1013 installed.push(tool);
1014 }),
1015 );
1016 const before = yield* service.state;
1017 const state = yield* service.updateTool("agent");
1018 expect(installed).toEqual(["agent"]);
1019 expect(state.supportsToolUpdate).toBe(true);
1020 expect(state.hostStatus).toBe(before.hostStatus);
1021 expect(state.agentAccessEnabled).toBe(before.agentAccessEnabled);
1022 expect(state.revision).toBeGreaterThan(before.revision);
1023 expect(starts).toEqual([]);
1024 expect(agentStarts).toEqual([]);
1025 expect(requests).toEqual([]);
1026 yield* service.updateTool("hub");
1027 expect(installed).toEqual(["agent", "hub"]);
1028 }).pipe(Effect.scoped),
1029);
1030
1031it.effect("failed manual installation leaves lifecycle state unchanged and can be retried", () =>
1032 Effect.gen(function* () {
1033 let attempts = 0;
1034 const { service, starts, agentStarts } = yield* fixture(
1035 Effect.void,
1036 undefined,
1037 false,
1038 undefined,
1039 false,
1040 () =>
1041 Effect.suspend(() =>
1042 ++attempts === 1
1043 ? Effect.fail(
1044 new DeviceOperationError({
1045 operation: "update device tool",
1046 reason: "command_failed",
1047 cause: new Error("offline"),
1048 }),
1049 )
1050 : Effect.void,
1051 ),
1052 );
1053 const before = yield* service.state;
1054 const result = yield* service.updateTool("agent").pipe(Effect.result);
1055 expect(result._tag).toBe("Failure");
1056 expect(yield* service.state).toEqual(before);
1057 yield* service.updateTool("agent");
1058 expect(attempts).toBe(2);
1059 expect(starts).toEqual([]);
1060 expect(agentStarts).toEqual([]);
1061 }).pipe(Effect.scoped),
1062);
1063
1064it.effect("reconciles SSH host settings without publishing no-op changes", () =>
1065 Effect.gen(function* () {
1066 const fs = yield* FileSystem.FileSystem;
1067 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-reconcile-" });
1068 const settings = yield* ServerSettings.ServerSettingsService;
1069 // Each change is acknowledged after reconciliation consumed it, so no-ops are observable.
1070 const changes = yield* Queue.unbounded<{ value: Settings; done: Deferred.Deferred<void> }>();
1071 const removedFiles: string[] = [];
1072 const localHost: DeviceHost.DeviceHost["Service"] = {
1073 id: LOCAL_DEVICE_HOST_ID,
1074 summary: Effect.succeed({
1075 id: LOCAL_DEVICE_HOST_ID,
1076 label: "Local",
1077 kind: "local",
1078 platforms: [],
1079 hubInstalled: false,
1080 agentDeviceInstalled: false,
1081 }),
1082 platformAvailability: (platform) => Effect.succeed({ platform, available: false }),
1083 current: Effect.succeed(null),
1084 ensureReady: () => Effect.die("Unexpected device launch"),
1085 ensureAgentReady: () => Effect.die("Unexpected agent launch"),
1086 stop: Effect.void,
1087 stopAgent: Effect.void,
1088 };
1089 const service = yield* DeviceService.make.pipe(
1090 Effect.provideService(DeviceHost.DeviceHost, localHost),
1091 Effect.provideService(ServerSettings.ServerSettingsService, {
1092 ...settings,
1093 subscribeChanges: Effect.succeed(
1094 Stream.fromQueue(changes).pipe(
1095 Stream.flatMap(({ value, done }) =>
1096 Stream.make(value).pipe(
1097 Stream.concat(
1098 Stream.fromEffect(Deferred.succeed(done, undefined)).pipe(Stream.drain),
1099 ),
1100 ),
1101 ),
1102 ),
1103 ),
1104 }),
1105 Effect.provideService(
1106 FileSystem.FileSystem,
1107 FileSystem.makeNoop({
1108 remove: (file) => Effect.sync(() => void removedFiles.push(file)),
1109 }),
1110 ),
1111 Effect.provideService(ProcessRunner.ProcessRunner, {
1112 run: () => Effect.die("Unexpected helper launch"),
1113 }),
1114 Effect.provideService(
1115 HttpClient.HttpClient,
1116 HttpClient.make(() => Effect.die("Unexpected HTTP request")),
1117 ),
1118 // `ssh -G` resolves the target to a non-local address.
1119 Effect.provideService(
1120 ChildProcessSpawner.ChildProcessSpawner,
1121 ChildProcessSpawner.make(() =>
1122 Effect.succeed(
1123 ChildProcessSpawner.makeHandle({
1124 pid: ChildProcessSpawner.ProcessId(123),
1125 stdout: Stream.make(new TextEncoder().encode("hostname 192.0.2.1\nport 22\n")),
1126 stderr: Stream.empty,
1127 all: Stream.empty,
1128 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
1129 isRunning: Effect.succeed(false),
1130 kill: () => Effect.void,
1131 stdin: Sink.drain,
1132 getInputFd: () => Sink.drain,
1133 getOutputFd: () => Stream.empty,
1134 unref: Effect.succeed(Effect.void),
1135 }),
1136 ),
1137 ),
1138 ),
1139 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(baseDir, baseDir), NetService.layer)),
1140 );
1141 const update = Effect.fnUntraced(function* (deviceHosts: ReadonlyArray<SshDeviceHostConfig>) {
1142 const value = yield* settings.updateSettings({ deviceHosts: [...deviceHosts] });
1143 const done = yield* Deferred.make<void>();
1144 yield* Queue.offer(changes, { value, done });
1145 yield* Deferred.await(done);
1146 return yield* service.state;
1147 });
1148
1149 const initial = yield* service.state;
1150 expect(yield* update([])).toEqual(initial);
1151
1152 const host: SshDeviceHostConfig = { id: "remote", label: "Remote", target: "remote-fixture" };
1153 const added = yield* update([host]);
1154 expect(added.hosts.map((entry) => entry.id)).toEqual([LOCAL_DEVICE_HOST_ID, host.id]);
1155 expect(yield* update([{ ...host }])).toEqual(added);
1156
1157 yield* service.setHostStatus(host.id, { status: "failed", detail: "stale" });
1158 const removed = yield* update([]);
1159 expect(removed.hosts.map((entry) => entry.id)).toEqual([LOCAL_DEVICE_HOST_ID]);
1160 expect(removed.hostStatuses[host.id]).toBeUndefined();
1161 expect(removedFiles).toHaveLength(1);
1162 }).pipe(
1163 Effect.scoped,
1164 Effect.provide(Layer.mergeAll(ServerSettings.layerTest(), NodeServices.layer)),
1165 ),
1166);
1167
1168it.effect("a failed tool update reports npm's exit code but not its output", () =>
1169 Effect.gen(function* () {
1170 const host: DeviceHost.DeviceHost["Service"] = {
1171 id: LOCAL_DEVICE_HOST_ID,
1172 summary: Effect.succeed({
1173 id: LOCAL_DEVICE_HOST_ID,
1174 kind: "local",
1175 label: "Test server",
1176 platforms: [],
1177 hubInstalled: false,
1178 agentDeviceInstalled: false,
1179 }),
1180 platformAvailability: (platform) => Effect.succeed({ platform, available: false }),
1181 ensureReady: () => Effect.die("Updating a tool does not start the hub"),
1182 ensureAgentReady: () => Effect.die("Updating a tool does not start the agent"),
1183 current: Effect.succeed(null),
1184 stopAgent: Effect.void,
1185 stop: Effect.void,
1186 };
1187 const npmFailure = {
1188 code: ChildProcessSpawner.ExitCode(243),
1189 stdout: "",
1190 stderr: "npm error EACCES https://private:credential@registry.example.test/expo-device-hub",
1191 timedOut: false,
1192 stdoutTruncated: false,
1193 stderrTruncated: false,
1194 stdoutInvalidUtf8: false,
1195 stderrInvalidUtf8: false,
1196 };
1197 const service = yield* DeviceService.make.pipe(
1198 Effect.provideService(DeviceHost.DeviceHost, host),
1199 Effect.provideService(ProcessRunner.ProcessRunner, {
1200 run: () => Effect.succeed(npmFailure),
1201 }),
1202 Effect.provideService(
1203 HttpClient.HttpClient,
1204 HttpClient.make(() => Effect.die("Updating a tool makes no hub requests")),
1205 ),
1206 );
1207
1208 const error = yield* service.updateTool("hub").pipe(Effect.flip);
1209 expect(error).toMatchObject({
1210 _tag: "DeviceOperationError",
1211 reason: "command_failed",
1212 exitCode: 243,
1213 });
1214 expect(error.message).toBe(
1215 "Device update device tool failed: The device command failed (exit code 243).",
1216 );
1217 }).pipe(
1218 Effect.provide(
1219 Layer.mergeAll(
1220 ServerSettings.layerTest({ enableDeviceSupport: true }),
1221 ServerConfig.layerTest(process.cwd(), { prefix: "t3-device-update-" }),
1222 NodeCrypto.layer,
1223 NetService.layer,
1224 ).pipe(Layer.provideMerge(NodeServices.layer)),
1225 ),
1226 Effect.scoped,
1227 ),
1228);