Open History to see the last commit
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
364it.effect.each([
365 {
366 diagnostic: "Insufficient disk space at /private/user/path",
367 reason: "disk_space",
368 message: "not enough free disk space",
369 },
370 {
371 diagnostic: "Timed out spawning /private/user/command",
372 reason: "timeout",
373 message: "did not become ready in time",
374 },
375 {
376 diagnostic: "Unexpected failure: secret-token",
377 reason: "launch_failed",
378 message: "could not start",
379 },
380] as const)("normalizes boot failure: $reason", ({ diagnostic, message }) =>
381 Effect.gen(function* () {
382 const { service } = yield* fixture(Effect.void, diagnostic);
383 yield* service.configure({ enabled: true });
384 const error = yield* service
385 .open({
386 threadId: ThreadId.make("boot-failure"),
387 deviceId: "Pixel_API_35",
388 platform: "android",
389 })
390 .pipe(Effect.flip);
391 expect(error._tag).toBe("DeviceBootError");
392 expect(error.message).toContain(message);
393 expect(error.message).not.toContain(diagnostic);
394 expect((yield* service.state).bootingDevices).toEqual([]);
395 }).pipe(Effect.scoped),
396);
397
398it.effect("keeps shutdown successful when subsequent discovery fails", () =>
399 Effect.gen(function* () {
400 const { service } = yield* fixture(Effect.void, undefined, true);
401 yield* service.configure({ enabled: true });
402 const threadId = ThreadId.make("shutdown-refresh");
403 const session = yield* service.open({
404 threadId,
405 deviceId: "Pixel_API_35",
406 platform: "android",
407 });
408 yield* service.close({ threadId, deviceId: session.deviceId, shutdown: true });
409 const state = yield* service.state;
410 expect(state.sessions).toEqual([]);
411 expect(state.devices.find((device) => device.id === session.deviceId)?.booted).toBe(false);
412 }).pipe(Effect.scoped),
413);
414
415it.effect.each(["shutdown", "close"] as const)(
416 "%s releases iOS capture so reopening uses a fresh session",
417 (operation) =>
418 Effect.gen(function* () {
419 const deviceId = DeviceId.make("11111111-1111-1111-1111-111111111111");
420 const threadId = ThreadId.make("capture-recovery");
421 let booted = true;
422 let capture: number | null = null;
423 let generation = 0;
424 const ready: DeviceHost.DeviceHostReady = {
425 nodePath: process.execPath,
426 hub: { origin: "http://device.test" },
427 helpers: { serveSimAxSettings: null, serveSimCli: null },
428 run: () => Effect.succeed({ code: 0, stdout: "", stderr: "" }),
429 };
430 const host: DeviceHost.DeviceHost["Service"] = {
431 id: LOCAL_DEVICE_HOST_ID,
432 summary: Effect.succeed({
433 id: LOCAL_DEVICE_HOST_ID,
434 kind: "local",
435 label: "Simulator host",
436 platforms: [{ platform: "ios", available: true }],
437 hubInstalled: true,
438 agentDeviceInstalled: false,
439 }),
440 platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
441 ensureReady: () => Effect.succeed(ready),
442 ensureAgentReady: () => Effect.die("Agent access is not used in this test"),
443 current: Effect.succeed(ready),
444 stopAgent: Effect.void,
445 stop: Effect.void,
446 };
447 const http = HttpClient.make((request) =>
448 Effect.sync(() => {
449 const path = new URL(request.url).pathname;
450 if (path === "/api/devices") {
451 return HttpClientResponse.fromWeb(
452 request,
453 Response.json({
454 emulators: [],
455 simulators: [
456 {
457 id: deviceId,
458 name: "iPhone",
459 platform: "ios",
460 version: "26",
461 physical: false,
462 booted,
463 },
464 ],
465 }),
466 );
467 }
468 if (path === "/vendor/serve-sim/grid/api/start") capture ??= ++generation;
469 else if (path === "/vendor/serve-sim/grid/api/shutdown") {
470 if (request.body._tag !== "Uint8Array") throw new Error("Missing shutdown body");
471 expect(decodeJson(new TextDecoder().decode(request.body.body))).toEqual({
472 udid: deviceId,
473 });
474 capture = null;
475 booted = false;
476 } else if (path === "/api/devices/shutdown") {
477 // This route powers off without releasing serve-sim's cached capture.
478 booted = false;
479 } else if (path === "/api/devices/boot") booted = true;
480 else throw new Error(`Unexpected hub path: ${path}`);
481 return HttpClientResponse.fromWeb(request, Response.json({ ok: true, id: deviceId }));
482 }),
483 );
484 const service = yield* DeviceService.makeWithHosts(new Map([[host.id, host]])).pipe(
485 Effect.provideService(HttpClient.HttpClient, http),
486 );
487 const input = { threadId, deviceId, platform: "ios" as const };
488 yield* service.open(input);
489 expect(capture).toBe(1);
490 if (operation === "shutdown") yield* service.shutdown(input);
491 else yield* service.close({ threadId, deviceId, shutdown: true });
492 expect(capture).toBeNull();
493 expect((yield* service.state).sessions).toEqual([]);
494 yield* service.open(input);
495 expect(capture).toBe(2);
496 expect((yield* service.state).sessions).toHaveLength(1);
497 }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true })), Effect.scoped),
498);
499
500it.effect.each([
501 { hubReports: "off", outcome: "succeeds" },
502 { hubReports: "booted", outcome: "fails" },
503 { hubReports: "missing", outcome: "fails" },
504] as const)(
505 "iOS shutdown $outcome when serve-sim rejects it and the hub reports the simulator $hubReports",
506 ({ hubReports, outcome }) =>
507 Effect.gen(function* () {
508 const deviceId = DeviceId.make("22222222-2222-2222-2222-222222222222");
509 const paths: string[] = [];
510 // The device list is stale until shutdown re-reads it from the hub.
511 let listed: "booted" | "off" | "missing" = "booted";
512 const ready: DeviceHost.DeviceHostReady = {
513 nodePath: process.execPath,
514 hub: { origin: "http://device.test" },
515 helpers: { serveSimAxSettings: null, serveSimCli: null },
516 run: () => Effect.succeed({ code: 0, stdout: "", stderr: "" }),
517 };
518 const host: DeviceHost.DeviceHost["Service"] = {
519 id: LOCAL_DEVICE_HOST_ID,
520 summary: Effect.succeed({
521 id: LOCAL_DEVICE_HOST_ID,
522 kind: "local",
523 label: "Simulator host",
524 platforms: [{ platform: "ios", available: true }],
525 hubInstalled: true,
526 agentDeviceInstalled: false,
527 }),
528 platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
529 ensureReady: () => Effect.succeed(ready),
530 ensureAgentReady: () => Effect.die("Agent access is not used in this test"),
531 current: Effect.succeed(ready),
532 stopAgent: Effect.void,
533 stop: Effect.void,
534 };
535 const http = HttpClient.make((request) =>
536 Effect.sync(() => {
537 const path = new URL(request.url).pathname;
538 paths.push(path);
539 if (path === "/api/devices") {
540 return HttpClientResponse.fromWeb(
541 request,
542 Response.json({
543 emulators: [],
544 simulators:
545 listed === "missing"
546 ? []
547 : [
548 {
549 id: deviceId,
550 name: "iPhone",
551 platform: "ios",
552 version: "26",
553 physical: false,
554 booted: listed === "booted",
555 },
556 ],
557 // A partial listing still decodes; it must not read as "off".
558 errors: listed === "missing" ? [{ message: "simctl list failed" }] : [],
559 }),
560 );
561 }
562 if (path === "/vendor/serve-sim/grid/api/shutdown") {
563 // serve-sim runs `simctl shutdown` bare and returns its failure as-is.
564 listed = hubReports;
565 return HttpClientResponse.fromWeb(
566 request,
567 Response.json(
568 { ok: false, error: "Unable to shutdown device in current state: Shutdown" },
569 { status: 500 },
570 ),
571 );
572 }
573 throw new Error(`Unexpected hub path: ${path}`);
574 }),
575 );
576 const service = yield* DeviceService.makeWithHosts(new Map([[host.id, host]])).pipe(
577 Effect.provideService(HttpClient.HttpClient, http),
578 );
579 yield* service.list;
580 const exit = yield* Effect.exit(service.shutdown({ deviceId, platform: "ios" }));
581 expect(paths.filter((path) => path.endsWith("shutdown"))).toEqual([
582 "/vendor/serve-sim/grid/api/shutdown",
583 ]);
584 if (outcome === "succeeds") {
585 expect(Exit.isSuccess(exit)).toBe(true);
586 expect(
587 (yield* service.state).devices.find((device) => device.id === deviceId)?.booted,
588 ).toBe(false);
589 } else {
590 expect(Exit.isFailure(exit)).toBe(true);
591 expect(
592 (yield* service.state).devices.find((device) => device.id === deviceId)?.booted,
593 ).toBe(true);
594 }
595 }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true })), Effect.scoped),
596);
597
598it.effect("retry keeps device and agent consent unchanged", () =>
599 Effect.gen(function* () {
600 const { service, starts, agentStarts } = yield* fixture();
601 yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
602 expect(starts).toEqual([]);
603 expect(agentStarts).toEqual([]);
604 yield* service.configure({ enabled: true });
605 yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
606 expect(agentStarts).toEqual([]);
607 yield* service.configure({ agentAccessEnabled: true });
608 const before = agentStarts.length;
609 yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
610 expect(agentStarts.length).toBe(before + 1);
611 }).pipe(Effect.scoped),
612);
613
614it.effect("publishes update detail for the correct host", () =>
615 Effect.gen(function* () {
616 const { service } = yield* fixture();
617 const changes = yield* service.subscribe;
618 yield* service.configure({ enabled: true });
619 const states = yield* PubSub.takeAll(changes);
620 expect(
621 states.some(
622 (state) => state.hostStatuses.local?.detail === "Updating device hub from 0.9.0 to 0.10.1…",
623 ),
624 ).toBe(true);
625 }).pipe(Effect.scoped),
626);
627
628it.effect("host retry exposes actionable failure without internal IDs or diagnostics", () =>
629 Effect.gen(function* () {
630 const { service, settings } = yield* fixture(
631 Effect.void,
632 undefined,
633 false,
634 new DeviceHost.DeviceHostError({
635 hostId: LOCAL_DEVICE_HOST_ID,
636 step: "probe",
637 cause: "private diagnostics",
638 }),
639 );
640 yield* Ref.update(settings, (current) => ({ ...current, enableDeviceSupport: true }));
641 const state = yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
642 expect(state.supportsHostRetry).toBe(true);
643 expect(state.hostStatuses[LOCAL_DEVICE_HOST_ID]).toEqual({
644 status: "failed",
645 detail: "Could not connect to this host over SSH.",
646 });
647 }).pipe(Effect.scoped),
648);
649
650it.effect("version discovery does not grant consent or start device tools", () =>
651 Effect.gen(function* () {
652 const { service, starts, agentStarts, requests } = yield* fixture();
653 const state = yield* service.inspect;
654 expect(state.supportsToolInspection).toBe(true);
655 expect(state.hostStatus).toBe("disabled");
656 expect(state.hosts).toHaveLength(1);
657 expect(starts).toEqual([]);
658 expect(agentStarts).toEqual([]);
659 expect(requests).toEqual([]);
660 }).pipe(Effect.scoped),
661);
662
663it.effect("failed read-only discovery preserves lifecycle status and installed inventory", () =>
664 Effect.gen(function* () {
665 const { service, starts } = yield* fixture(Effect.void, undefined, false, undefined, true);
666 const state = yield* service.inspect;
667 expect(state.supportsToolInspection).toBe(true);
668 expect(state.hostStatus).toBe("disabled");
669 expect(state.hosts[0]?.hubInstalled).toBe(true);
670 expect(state.hosts[0]?.toolInspectionError).toContain("Reconnect the host");
671 expect(starts).toEqual([]);
672 }).pipe(Effect.scoped),
673);
674
675it.effect(
676 "manual updates install only the selected tool without enabling access or starting helpers",
677 () =>
678 Effect.gen(function* () {
679 const installed: string[] = [];
680 const { service, starts, agentStarts, requests } = yield* fixture(
681 Effect.void,
682 undefined,
683 false,
684 undefined,
685 false,
686 (tool) =>
687 Effect.sync(() => {
688 installed.push(tool);
689 }),
690 );
691 const before = yield* service.state;
692 const state = yield* service.updateTool("agent");
693 expect(installed).toEqual(["agent"]);
694 expect(state.supportsToolUpdate).toBe(true);
695 expect(state.hostStatus).toBe(before.hostStatus);
696 expect(state.agentAccessEnabled).toBe(before.agentAccessEnabled);
697 expect(state.revision).toBeGreaterThan(before.revision);
698 expect(starts).toEqual([]);
699 expect(agentStarts).toEqual([]);
700 expect(requests).toEqual([]);
701 yield* service.updateTool("hub");
702 expect(installed).toEqual(["agent", "hub"]);
703 }).pipe(Effect.scoped),
704);
705
706it.effect("failed manual installation leaves lifecycle state unchanged and can be retried", () =>
707 Effect.gen(function* () {
708 let attempts = 0;
709 const { service, starts, agentStarts } = yield* fixture(
710 Effect.void,
711 undefined,
712 false,
713 undefined,
714 false,
715 () =>
716 Effect.suspend(() =>
717 ++attempts === 1
718 ? Effect.fail(
719 new DeviceOperationError({
720 operation: "update device tool",
721 reason: "command_failed",
722 cause: new Error("offline"),
723 }),
724 )
725 : Effect.void,
726 ),
727 );
728 const before = yield* service.state;
729 const result = yield* service.updateTool("agent").pipe(Effect.result);
730 expect(result._tag).toBe("Failure");
731 expect(yield* service.state).toEqual(before);
732 yield* service.updateTool("agent");
733 expect(attempts).toBe(2);
734 expect(starts).toEqual([]);
735 expect(agentStarts).toEqual([]);
736 }).pipe(Effect.scoped),
737);