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

DeviceService.test.ts

890 lines33.8 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 // The device list is stale until shutdown re-reads it from the hub.
559 let listed: "booted" | "off" | "missing" = "booted";
560 const ready: DeviceHost.DeviceHostReady = {
561 nodePath: process.execPath,
562 hub: { origin: "http://device.test" },
563 helpers: { serveSimAxSettings: null, serveSimCli: null },
564 run: () => Effect.succeed({ code: 0, stdout: "", stderr: "" }),
565 };
566 const host: DeviceHost.DeviceHost["Service"] = {
567 id: LOCAL_DEVICE_HOST_ID,
568 summary: Effect.succeed({
569 id: LOCAL_DEVICE_HOST_ID,
570 kind: "local",
571 label: "Simulator host",
572 platforms: [{ platform: "ios", available: true }],
573 hubInstalled: true,
574 agentDeviceInstalled: false,
575 }),
576 platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
577 ensureReady: () => Effect.succeed(ready),
578 ensureAgentReady: () => Effect.die("Agent access is not used in this test"),
579 current: Effect.succeed(ready),
580 stopAgent: Effect.void,
581 stop: Effect.void,
582 };
583 const http = HttpClient.make((request) =>
584 Effect.sync(() => {
585 const path = new URL(request.url).pathname;
586 paths.push(path);
587 if (path === "/api/devices") {
588 return HttpClientResponse.fromWeb(
589 request,
590 Response.json({
591 emulators: [],
592 simulators:
593 listed === "missing"
594 ? []
595 : [
596 {
597 id: deviceId,
598 name: "iPhone",
599 platform: "ios",
600 version: "26",
601 physical: false,
602 booted: listed === "booted",
603 },
604 ],
605 // A partial listing still decodes; it must not read as "off".
606 errors: listed === "missing" ? [{ message: "simctl list failed" }] : [],
607 }),
608 );
609 }
610 if (path === "/vendor/serve-sim/grid/api/shutdown") {
611 // serve-sim runs `simctl shutdown` bare and returns its failure as-is.
612 listed = hubReports;
613 return HttpClientResponse.fromWeb(
614 request,
615 Response.json(
616 { ok: false, error: "Unable to shutdown device in current state: Shutdown" },
617 { status: 500 },
618 ),
619 );
620 }
621 throw new Error(`Unexpected hub path: ${path}`);
622 }),
623 );
624 const service = yield* DeviceService.makeWithHosts(new Map([[host.id, host]])).pipe(
625 Effect.provide(NodeCrypto.layer),
626 Effect.provideService(HttpClient.HttpClient, http),
627 );
628 yield* service.list;
629 const exit = yield* Effect.exit(service.shutdown({ deviceId, platform: "ios" }));
630 expect(paths.filter((path) => path.endsWith("shutdown"))).toEqual([
631 "/vendor/serve-sim/grid/api/shutdown",
632 ]);
633 if (outcome === "succeeds") {
634 expect(Exit.isSuccess(exit)).toBe(true);
635 expect(
636 (yield* service.state).devices.find((device) => device.id === deviceId)?.booted,
637 ).toBe(false);
638 } else {
639 expect(Exit.isFailure(exit)).toBe(true);
640 expect(
641 (yield* service.state).devices.find((device) => device.id === deviceId)?.booted,
642 ).toBe(true);
643 }
644 }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true })), Effect.scoped),
645);
646​
647it.effect("retry keeps device and agent consent unchanged", () =>
648 Effect.gen(function* () {
649 const { service, starts, agentStarts } = yield* fixture();
650 yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
651 expect(starts).toEqual([]);
652 expect(agentStarts).toEqual([]);
653 yield* service.configure({ enabled: true });
654 yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
655 expect(agentStarts).toEqual([]);
656 yield* service.configure({ agentAccessEnabled: true });
657 const before = agentStarts.length;
658 yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
659 expect(agentStarts.length).toBe(before + 1);
660 }).pipe(Effect.scoped),
661);
662​
663it.effect("publishes update detail for the correct host", () =>
664 Effect.gen(function* () {
665 const { service } = yield* fixture();
666 const changes = yield* service.subscribe;
667 yield* service.configure({ enabled: true });
668 const states = yield* PubSub.takeAll(changes);
669 expect(
670 states.some(
671 (state) => state.hostStatuses.local?.detail === "Updating device hub from 0.9.0 to 0.10.1…",
672 ),
673 ).toBe(true);
674 }).pipe(Effect.scoped),
675);
676​
677it.effect("host retry exposes actionable failure without internal IDs or diagnostics", () =>
678 Effect.gen(function* () {
679 const { service, settings } = yield* fixture(
680 Effect.void,
681 undefined,
682 false,
683 new DeviceHost.DeviceHostError({
684 hostId: LOCAL_DEVICE_HOST_ID,
685 step: "probe",
686 cause: "private diagnostics",
687 }),
688 );
689 yield* Ref.update(settings, (current) => ({ ...current, enableDeviceSupport: true }));
690 const state = yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
691 expect(state.supportsHostRetry).toBe(true);
692 expect(state.hostStatuses[LOCAL_DEVICE_HOST_ID]).toEqual({
693 status: "failed",
694 detail: "Could not connect to this host over SSH.",
695 });
696 }).pipe(Effect.scoped),
697);
698​
699it.effect("version discovery does not grant consent or start device tools", () =>
700 Effect.gen(function* () {
701 const { service, starts, agentStarts, requests } = yield* fixture();
702 const state = yield* service.inspect;
703 expect(state.supportsToolInspection).toBe(true);
704 expect(state.hostStatus).toBe("disabled");
705 expect(state.hosts).toHaveLength(1);
706 expect(starts).toEqual([]);
707 expect(agentStarts).toEqual([]);
708 expect(requests).toEqual([]);
709 }).pipe(Effect.scoped),
710);
711​
712it.effect("failed read-only discovery preserves lifecycle status and installed inventory", () =>
713 Effect.gen(function* () {
714 const { service, starts } = yield* fixture(Effect.void, undefined, false, undefined, true);
715 const state = yield* service.inspect;
716 expect(state.supportsToolInspection).toBe(true);
717 expect(state.hostStatus).toBe("disabled");
718 expect(state.hosts[0]?.hubInstalled).toBe(true);
719 expect(state.hosts[0]?.toolInspectionError).toContain("Reconnect the host");
720 expect(starts).toEqual([]);
721 }).pipe(Effect.scoped),
722);
723​
724it.effect(
725 "manual updates install only the selected tool without enabling access or starting helpers",
726 () =>
727 Effect.gen(function* () {
728 const installed: string[] = [];
729 const { service, starts, agentStarts, requests } = yield* fixture(
730 Effect.void,
731 undefined,
732 false,
733 undefined,
734 false,
735 (tool) =>
736 Effect.sync(() => {
737 installed.push(tool);
738 }),
739 );
740 const before = yield* service.state;
741 const state = yield* service.updateTool("agent");
742 expect(installed).toEqual(["agent"]);
743 expect(state.supportsToolUpdate).toBe(true);
744 expect(state.hostStatus).toBe(before.hostStatus);
745 expect(state.agentAccessEnabled).toBe(before.agentAccessEnabled);
746 expect(state.revision).toBeGreaterThan(before.revision);
747 expect(starts).toEqual([]);
748 expect(agentStarts).toEqual([]);
749 expect(requests).toEqual([]);
750 yield* service.updateTool("hub");
751 expect(installed).toEqual(["agent", "hub"]);
752 }).pipe(Effect.scoped),
753);
754​
755it.effect("failed manual installation leaves lifecycle state unchanged and can be retried", () =>
756 Effect.gen(function* () {
757 let attempts = 0;
758 const { service, starts, agentStarts } = yield* fixture(
759 Effect.void,
760 undefined,
761 false,
762 undefined,
763 false,
764 () =>
765 Effect.suspend(() =>
766 ++attempts === 1
767 ? Effect.fail(
768 new DeviceOperationError({
769 operation: "update device tool",
770 reason: "command_failed",
771 cause: new Error("offline"),
772 }),
773 )
774 : Effect.void,
775 ),
776 );
777 const before = yield* service.state;
778 const result = yield* service.updateTool("agent").pipe(Effect.result);
779 expect(result._tag).toBe("Failure");
780 expect(yield* service.state).toEqual(before);
781 yield* service.updateTool("agent");
782 expect(attempts).toBe(2);
783 expect(starts).toEqual([]);
784 expect(agentStarts).toEqual([]);
785 }).pipe(Effect.scoped),
786);
787​
788it.effect("reconciles SSH host settings without publishing no-op changes", () =>
789 Effect.gen(function* () {
790 const fs = yield* FileSystem.FileSystem;
791 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-reconcile-" });
792 const settings = yield* ServerSettings.ServerSettingsService;
793 // Each change is acknowledged after reconciliation consumed it, so no-ops are observable.
794 const changes = yield* Queue.unbounded<{ value: Settings; done: Deferred.Deferred<void> }>();
795 const removedFiles: string[] = [];
796 const localHost: DeviceHost.DeviceHost["Service"] = {
797 id: LOCAL_DEVICE_HOST_ID,
798 summary: Effect.succeed({
799 id: LOCAL_DEVICE_HOST_ID,
800 label: "Local",
801 kind: "local",
802 platforms: [],
803 hubInstalled: false,
804 agentDeviceInstalled: false,
805 }),
806 platformAvailability: (platform) => Effect.succeed({ platform, available: false }),
807 current: Effect.succeed(null),
808 ensureReady: () => Effect.die("Unexpected device launch"),
809 ensureAgentReady: () => Effect.die("Unexpected agent launch"),
810 stop: Effect.void,
811 stopAgent: Effect.void,
812 };
813 const service = yield* DeviceService.make.pipe(
814 Effect.provideService(DeviceHost.DeviceHost, localHost),
815 Effect.provideService(ServerSettings.ServerSettingsService, {
816 ...settings,
817 subscribeChanges: Effect.succeed(
818 Stream.fromQueue(changes).pipe(
819 Stream.flatMap(({ value, done }) =>
820 Stream.make(value).pipe(
821 Stream.concat(
822 Stream.fromEffect(Deferred.succeed(done, undefined)).pipe(Stream.drain),
823 ),
824 ),
825 ),
826 ),
827 ),
828 }),
829 Effect.provideService(
830 FileSystem.FileSystem,
831 FileSystem.makeNoop({
832 remove: (file) => Effect.sync(() => void removedFiles.push(file)),
833 }),
834 ),
835 Effect.provideService(ProcessRunner.ProcessRunner, {
836 run: () => Effect.die("Unexpected helper launch"),
837 }),
838 Effect.provideService(
839 HttpClient.HttpClient,
840 HttpClient.make(() => Effect.die("Unexpected HTTP request")),
841 ),
842 // `ssh -G` resolves the target to a non-local address.
843 Effect.provideService(
844 ChildProcessSpawner.ChildProcessSpawner,
845 ChildProcessSpawner.make(() =>
846 Effect.succeed(
847 ChildProcessSpawner.makeHandle({
848 pid: ChildProcessSpawner.ProcessId(123),
849 stdout: Stream.make(new TextEncoder().encode("hostname 192.0.2.1\nport 22\n")),
850 stderr: Stream.empty,
851 all: Stream.empty,
852 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
853 isRunning: Effect.succeed(false),
854 kill: () => Effect.void,
855 stdin: Sink.drain,
856 getInputFd: () => Sink.drain,
857 getOutputFd: () => Stream.empty,
858 unref: Effect.succeed(Effect.void),
859 }),
860 ),
861 ),
862 ),
863 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(baseDir, baseDir), NetService.layer)),
864 );
865 const update = Effect.fnUntraced(function* (deviceHosts: ReadonlyArray<SshDeviceHostConfig>) {
866 const value = yield* settings.updateSettings({ deviceHosts: [...deviceHosts] });
867 const done = yield* Deferred.make<void>();
868 yield* Queue.offer(changes, { value, done });
869 yield* Deferred.await(done);
870 return yield* service.state;
871 });
872​
873 const initial = yield* service.state;
874 expect(yield* update([])).toEqual(initial);
875​
876 const host: SshDeviceHostConfig = { id: "remote", label: "Remote", target: "remote-fixture" };
877 const added = yield* update([host]);
878 expect(added.hosts.map((entry) => entry.id)).toEqual([LOCAL_DEVICE_HOST_ID, host.id]);
879 expect(yield* update([{ ...host }])).toEqual(added);
880​
881 yield* service.setHostStatus(host.id, { status: "failed", detail: "stale" });
882 const removed = yield* update([]);
883 expect(removed.hosts.map((entry) => entry.id)).toEqual([LOCAL_DEVICE_HOST_ID]);
884 expect(removed.hostStatuses[host.id]).toBeUndefined();
885 expect(removedFiles).toHaveLength(1);
886 }).pipe(
887 Effect.scoped,
888 Effect.provide(Layer.mergeAll(ServerSettings.layerTest(), NodeServices.layer)),
889 ),
890);