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

DeviceService.test.ts

733 lines27.3 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 { ServerSettingsService } from "../serverSettings.ts";
20import * as DeviceHost from "./DeviceHost.ts";
21import { NodeRuntimeUnavailableError } from "@t3tools/shared/nodeRuntime";
22​
23import { type DeviceService, makeWithHosts, stateStream } 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["Service"], "state" | "subscribe"> = {
45 state: Ref.get(current),
46 subscribe: PubSub.subscribe(pubsub),
47 };
48​
49 const collected = yield* stateStream(service as DeviceService["Service"]).pipe(
50 Stream.take(3),
51 Stream.runCollect,
52 Effect.forkChild,
53 );
54 yield* Effect.yieldNow;
55 for (const revision of [1, 2]) {
56 const next = { ...baseState, revision, hostStatus: "ready" as const };
57 yield* Ref.set(current, next);
58 yield* PubSub.publish(pubsub, next);
59 }
60 const seen = yield* Fiber.join(collected);
61 expect(seen.map((state) => state.revision)).toEqual([0, 1, 2]);
62 }),
63 );
64});
65​
66const fixture = Effect.fn("fixture")(function* (
67 onBoot: Effect.Effect<void> = Effect.void,
68 bootError?: string,
69 failListAfterShutdown = false,
70 runtimeFailure?: NodeRuntimeUnavailableError | DeviceHost.DeviceHostError,
71 inspectError = false,
72 installTool?: Parameters<typeof makeWithHosts>[3],
73) {
74 const settings = yield* Ref.make(DEFAULT_SERVER_SETTINGS);
75 const starts: string[] = [];
76 const agentStarts: string[] = [];
77 const agentStops: string[] = [];
78 const requests: string[] = [];
79 let booted = false;
80 let shutDown = false;
81 const ready: DeviceHost.DeviceHostReady = {
82 nodePath: process.execPath,
83 hub: { origin: "http://device.test" },
84 helpers: { serveSimAxSettings: null, serveSimCli: null },
85 run: () => Effect.succeed({ code: 0, stdout: "Pixel_API_35\n", stderr: "" }),
86 };
87 const host: DeviceHost.DeviceHost["Service"] = {
88 ...(inspectError
89 ? {
90 inspect: Effect.fail(
91 new DeviceHost.DeviceHostError({
92 hostId: LOCAL_DEVICE_HOST_ID,
93 step: "probe",
94 cause: new Error("offline"),
95 }),
96 ),
97 }
98 : {}),
99 id: LOCAL_DEVICE_HOST_ID,
100 summary: Effect.succeed({
101 id: LOCAL_DEVICE_HOST_ID,
102 kind: "local",
103 label: "Test server",
104 platforms: [{ platform: "android", available: true }],
105 hubInstalled: true,
106 agentDeviceInstalled: false,
107 }),
108 platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
109 ensureReady: (onPhase) =>
110 Effect.gen(function* () {
111 if (runtimeFailure) return yield* runtimeFailure;
112 starts.push("start");
113 yield* onPhase("installing", "Updating device hub from 0.9.0 to 0.10.1…");
114 return ready;
115 }),
116 ensureAgentReady: (onPhase) =>
117 Effect.gen(function* () {
118 if (runtimeFailure) return yield* runtimeFailure;
119 agentStarts.push("start");
120 yield* onPhase("starting");
121 return {
122 ...ready,
123 agentDevice: { baseUrl: "http://agent.test", token: "test", entryPath: "/agent" },
124 };
125 }),
126 current: Effect.succeed(null),
127 stopAgent: Effect.sync(() => {
128 agentStops.push("stop");
129 }),
130 stop: Effect.sync(() => {
131 starts.push("stop");
132 }),
133 };
134 const service = yield* makeWithHosts(
135 new Map([[host.id, host]]),
136 undefined,
137 undefined,
138 installTool,
139 ).pipe(
140 Effect.provideService(DeviceHost.DeviceHost, host),
141 Effect.provideService(
142 ServerSettingsService,
143 ServerSettingsService.of({
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* 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(
488 Effect.provide(ServerSettingsService.layerTest({ enableDeviceSupport: true })),
489 Effect.scoped,
490 ),
491);
492​
493it.effect.each([
494 { hubReports: "off", outcome: "succeeds" },
495 { hubReports: "booted", outcome: "fails" },
496 { hubReports: "missing", outcome: "fails" },
497] as const)(
498 "iOS shutdown $outcome when serve-sim rejects it and the hub reports the simulator $hubReports",
499 ({ hubReports, outcome }) =>
500 Effect.gen(function* () {
501 const deviceId = DeviceId.make("22222222-2222-2222-2222-222222222222");
502 const paths: string[] = [];
503 // The device list is stale until shutdown re-reads it from the hub.
504 let listed: "booted" | "off" | "missing" = "booted";
505 const ready: DeviceHost.DeviceHostReady = {
506 nodePath: process.execPath,
507 hub: { origin: "http://device.test" },
508 helpers: { serveSimAxSettings: null, serveSimCli: null },
509 run: () => Effect.succeed({ code: 0, stdout: "", stderr: "" }),
510 };
511 const host: DeviceHost.DeviceHost["Service"] = {
512 id: LOCAL_DEVICE_HOST_ID,
513 summary: Effect.succeed({
514 id: LOCAL_DEVICE_HOST_ID,
515 kind: "local",
516 label: "Simulator host",
517 platforms: [{ platform: "ios", available: true }],
518 hubInstalled: true,
519 agentDeviceInstalled: false,
520 }),
521 platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
522 ensureReady: () => Effect.succeed(ready),
523 ensureAgentReady: () => Effect.die("Agent access is not used in this test"),
524 current: Effect.succeed(ready),
525 stopAgent: Effect.void,
526 stop: Effect.void,
527 };
528 const http = HttpClient.make((request) =>
529 Effect.sync(() => {
530 const path = new URL(request.url).pathname;
531 paths.push(path);
532 if (path === "/api/devices") {
533 return HttpClientResponse.fromWeb(
534 request,
535 Response.json({
536 emulators: [],
537 simulators:
538 listed === "missing"
539 ? []
540 : [
541 {
542 id: deviceId,
543 name: "iPhone",
544 platform: "ios",
545 version: "26",
546 physical: false,
547 booted: listed === "booted",
548 },
549 ],
550 // A partial listing still decodes; it must not read as "off".
551 errors: listed === "missing" ? [{ message: "simctl list failed" }] : [],
552 }),
553 );
554 }
555 if (path === "/vendor/serve-sim/grid/api/shutdown") {
556 // serve-sim runs `simctl shutdown` bare and returns its failure as-is.
557 listed = hubReports;
558 return HttpClientResponse.fromWeb(
559 request,
560 Response.json(
561 { ok: false, error: "Unable to shutdown device in current state: Shutdown" },
562 { status: 500 },
563 ),
564 );
565 }
566 throw new Error(`Unexpected hub path: ${path}`);
567 }),
568 );
569 const service = yield* makeWithHosts(new Map([[host.id, host]])).pipe(
570 Effect.provideService(HttpClient.HttpClient, http),
571 );
572 yield* service.list;
573 const exit = yield* Effect.exit(service.shutdown({ deviceId, platform: "ios" }));
574 expect(paths.filter((path) => path.endsWith("shutdown"))).toEqual([
575 "/vendor/serve-sim/grid/api/shutdown",
576 ]);
577 if (outcome === "succeeds") {
578 expect(Exit.isSuccess(exit)).toBe(true);
579 expect(
580 (yield* service.state).devices.find((device) => device.id === deviceId)?.booted,
581 ).toBe(false);
582 } else {
583 expect(Exit.isFailure(exit)).toBe(true);
584 expect(
585 (yield* service.state).devices.find((device) => device.id === deviceId)?.booted,
586 ).toBe(true);
587 }
588 }).pipe(
589 Effect.provide(ServerSettingsService.layerTest({ enableDeviceSupport: true })),
590 Effect.scoped,
591 ),
592);
593​
594it.effect("retry keeps device and agent consent unchanged", () =>
595 Effect.gen(function* () {
596 const { service, starts, agentStarts } = yield* fixture();
597 yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
598 expect(starts).toEqual([]);
599 expect(agentStarts).toEqual([]);
600 yield* service.configure({ enabled: true });
601 yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
602 expect(agentStarts).toEqual([]);
603 yield* service.configure({ agentAccessEnabled: true });
604 const before = agentStarts.length;
605 yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
606 expect(agentStarts.length).toBe(before + 1);
607 }).pipe(Effect.scoped),
608);
609​
610it.effect("publishes update detail for the correct host", () =>
611 Effect.gen(function* () {
612 const { service } = yield* fixture();
613 const changes = yield* service.subscribe;
614 yield* service.configure({ enabled: true });
615 const states = yield* PubSub.takeAll(changes);
616 expect(
617 states.some(
618 (state) => state.hostStatuses.local?.detail === "Updating device hub from 0.9.0 to 0.10.1…",
619 ),
620 ).toBe(true);
621 }).pipe(Effect.scoped),
622);
623​
624it.effect("host retry exposes actionable failure without internal IDs or diagnostics", () =>
625 Effect.gen(function* () {
626 const { service, settings } = yield* fixture(
627 Effect.void,
628 undefined,
629 false,
630 new DeviceHost.DeviceHostError({
631 hostId: LOCAL_DEVICE_HOST_ID,
632 step: "probe",
633 cause: "private diagnostics",
634 }),
635 );
636 yield* Ref.update(settings, (current) => ({ ...current, enableDeviceSupport: true }));
637 const state = yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
638 expect(state.supportsHostRetry).toBe(true);
639 expect(state.hostStatuses[LOCAL_DEVICE_HOST_ID]).toEqual({
640 status: "failed",
641 detail: "Could not connect to this host over SSH.",
642 });
643 }).pipe(Effect.scoped),
644);
645​
646it.effect("version discovery does not grant consent or start device tools", () =>
647 Effect.gen(function* () {
648 const { service, starts, agentStarts, requests } = yield* fixture();
649 const state = yield* service.inspect;
650 expect(state.supportsToolInspection).toBe(true);
651 expect(state.hostStatus).toBe("disabled");
652 expect(state.hosts).toHaveLength(1);
653 expect(starts).toEqual([]);
654 expect(agentStarts).toEqual([]);
655 expect(requests).toEqual([]);
656 }).pipe(Effect.scoped),
657);
658​
659it.effect("failed read-only discovery preserves lifecycle status and installed inventory", () =>
660 Effect.gen(function* () {
661 const { service, starts } = yield* fixture(Effect.void, undefined, false, undefined, true);
662 const state = yield* service.inspect;
663 expect(state.supportsToolInspection).toBe(true);
664 expect(state.hostStatus).toBe("disabled");
665 expect(state.hosts[0]?.hubInstalled).toBe(true);
666 expect(state.hosts[0]?.toolInspectionError).toContain("Reconnect the host");
667 expect(starts).toEqual([]);
668 }).pipe(Effect.scoped),
669);
670​
671it.effect(
672 "manual updates install only the selected tool without enabling access or starting helpers",
673 () =>
674 Effect.gen(function* () {
675 const installed: string[] = [];
676 const { service, starts, agentStarts, requests } = yield* fixture(
677 Effect.void,
678 undefined,
679 false,
680 undefined,
681 false,
682 (tool) =>
683 Effect.sync(() => {
684 installed.push(tool);
685 }),
686 );
687 const before = yield* service.state;
688 const state = yield* service.updateTool("agent");
689 expect(installed).toEqual(["agent"]);
690 expect(state.supportsToolUpdate).toBe(true);
691 expect(state.hostStatus).toBe(before.hostStatus);
692 expect(state.agentAccessEnabled).toBe(before.agentAccessEnabled);
693 expect(state.revision).toBeGreaterThan(before.revision);
694 expect(starts).toEqual([]);
695 expect(agentStarts).toEqual([]);
696 expect(requests).toEqual([]);
697 yield* service.updateTool("hub");
698 expect(installed).toEqual(["agent", "hub"]);
699 }).pipe(Effect.scoped),
700);
701​
702it.effect("failed manual installation leaves lifecycle state unchanged and can be retried", () =>
703 Effect.gen(function* () {
704 let attempts = 0;
705 const { service, starts, agentStarts } = yield* fixture(
706 Effect.void,
707 undefined,
708 false,
709 undefined,
710 false,
711 () =>
712 Effect.suspend(() =>
713 ++attempts === 1
714 ? Effect.fail(
715 new DeviceOperationError({
716 operation: "update device tool",
717 reason: "command_failed",
718 cause: new Error("offline"),
719 }),
720 )
721 : Effect.void,
722 ),
723 );
724 const before = yield* service.state;
725 const result = yield* service.updateTool("agent").pipe(Effect.result);
726 expect(result._tag).toBe("Failure");
727 expect(yield* service.state).toEqual(before);
728 yield* service.updateTool("agent");
729 expect(attempts).toBe(2);
730 expect(starts).toEqual([]);
731 expect(agentStarts).toEqual([]);
732 }).pipe(Effect.scoped),
733);