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

DeviceService.test.ts

888 lines33.7 KB

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