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

DeviceService.test.ts

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