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

DeviceService.test.ts

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