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