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 type ServerSettings as Settings,
10 type SshDeviceHostConfig,
11} from "@t3tools/contracts";
12import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
13import * as NodeServices from "@effect/platform-node/NodeServices";
14import * as NetService from "@t3tools/shared/Net";
15import { SshCommandError } from "@t3tools/ssh/errors";
16import * as Effect from "effect/Effect";
17import * as Exit from "effect/Exit";
18import * as Deferred from "effect/Deferred";
19import * as Fiber from "effect/Fiber";
20import * as FileSystem from "effect/FileSystem";
21import * as Layer from "effect/Layer";
22import * as PubSub from "effect/PubSub";
23import * as Queue from "effect/Queue";
24import * as Ref from "effect/Ref";
25import * as Schema from "effect/Schema";
26import * as Sink from "effect/Sink";
27import * as Stream from "effect/Stream";
28import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
29import { HttpClient, HttpClientResponse } from "effect/http";
30import * as ServerConfig from "../config.ts";
31import * as ProcessRunner from "../processRunner.ts";
32import * as ServerSettings from "../serverSettings.ts";
33import * as DeviceHost from "./DeviceHost.ts";
34import { NodeRuntimeUnavailableError } from "@t3tools/shared/nodeRuntime";
35
36import * as DeviceService from "./DeviceService.ts";
37
38const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
39
40const baseState: DeviceServiceState = {
41 hosts: [],
42 hostStatus: "idle",
43 hostStatuses: {},
44 devices: [],
45 sessions: [],
46 onboardingCompleted: false,
47 agentAccessEnabled: false,
48 hubBasePath: "/api/device-hub",
49 revision: 0,
50};
51
52describe("DeviceService.stateStream", () => {
53 it.effect("emits the current snapshot and then every published change", () =>
54 Effect.gen(function* () {
55 const pubsub = yield* PubSub.unbounded<DeviceServiceState>();
56 const current = yield* Ref.make(baseState);
57 const service: Pick<DeviceService.DeviceService["Service"], "state" | "subscribe"> = {
58 state: Ref.get(current),
59 subscribe: PubSub.subscribe(pubsub),
60 };
61
62 const collected = yield* DeviceService.stateStream(
63 service as DeviceService.DeviceService["Service"],
64 ).pipe(Stream.take(3), Stream.runCollect, Effect.forkChild);
65 yield* Effect.yieldNow;
66 for (const revision of [1, 2]) {
67 const next = { ...baseState, revision, hostStatus: "ready" as const };
68 yield* Ref.set(current, next);
69 yield* PubSub.publish(pubsub, next);
70 }
71 const seen = yield* Fiber.join(collected);
72 expect(seen.map((state) => state.revision)).toEqual([0, 1, 2]);
73 }),
74 );
75});
76
77const fixture = Effect.fn("fixture")(function* (
78 onBoot: Effect.Effect<void> = Effect.void,
79 bootError?: string,
80 failListAfterShutdown = false,
81 runtimeFailure?:
82 | NodeRuntimeUnavailableError
83 | DeviceHost.DeviceHostError
84 | DeviceHost.AgentDeviceStartError,
85 inspectError = false,
86 installTool?: Parameters<typeof DeviceService.makeWithHosts>[3],
87) {
88 const settings = yield* Ref.make(DEFAULT_SERVER_SETTINGS);
89 const starts: string[] = [];
90 const agentStarts: string[] = [];
91 const agentStops: string[] = [];
92 const requests: string[] = [];
93 let booted = false;
94 let shutDown = false;
95 const ready: DeviceHost.DeviceHostReady = {
96 nodePath: process.execPath,
97 hub: { origin: "http://device.test" },
98 helpers: { serveSimAxSettings: null, serveSimCli: null },
99 run: () => Effect.succeed({ code: 0, stdout: "Pixel_API_35\n", stderr: "" }),
100 };
101 const host: DeviceHost.DeviceHost["Service"] = {
102 ...(inspectError
103 ? {
104 inspect: Effect.fail(
105 new DeviceHost.DeviceHostError({
106 hostId: LOCAL_DEVICE_HOST_ID,
107 step: "probe",
108 cause: new Error("offline"),
109 }),
110 ),
111 }
112 : {}),
113 id: LOCAL_DEVICE_HOST_ID,
114 summary: Effect.succeed({
115 id: LOCAL_DEVICE_HOST_ID,
116 kind: "local",
117 label: "Test server",
118 platforms: [{ platform: "android", available: true }],
119 hubInstalled: true,
120 agentDeviceInstalled: false,
121 }),
122 platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
123 ensureReady: (onPhase) =>
124 Effect.gen(function* () {
125 if (runtimeFailure && runtimeFailure._tag !== "AgentDeviceStartError")
126 return yield* runtimeFailure;
127 starts.push("start");
128 yield* onPhase("installing", "Updating device hub from 0.9.0 to 0.10.1…");
129 return ready;
130 }),
131 ensureAgentReady: (onPhase) =>
132 Effect.gen(function* () {
133 if (runtimeFailure) return yield* runtimeFailure;
134 agentStarts.push("start");
135 yield* onPhase("starting");
136 return {
137 ...ready,
138 agentDevice: { baseUrl: "http://agent.test", token: "test", entryPath: "/agent" },
139 };
140 }),
141 current: Effect.succeed(null),
142 stopAgent: Effect.sync(() => {
143 agentStops.push("stop");
144 }),
145 stop: Effect.sync(() => {
146 starts.push("stop");
147 }),
148 };
149 const service = yield* DeviceService.makeWithHosts(
150 new Map([[host.id, host]]),
151 undefined,
152 undefined,
153 installTool,
154 ).pipe(
155 Effect.provide(NodeCrypto.layer),
156 Effect.provideService(DeviceHost.DeviceHost, host),
157 Effect.provideService(
158 ServerSettings.ServerSettingsService,
159 ServerSettings.ServerSettingsService.of({
160 updateProviderInstance: () => Effect.die("Unexpected provider mutation"),
161 withSettingsSnapshot: (use) => Effect.flatMap(Ref.get(settings), use),
162 start: Effect.void,
163 ready: Effect.void,
164 getSettings: Ref.get(settings),
165 updateSettings: (patch) =>
166 Ref.updateAndGet(settings, (current) => ({
167 ...current,
168 enableDeviceSupport: patch.enableDeviceSupport ?? current.enableDeviceSupport,
169 enableAgentDeviceAccess:
170 patch.enableAgentDeviceAccess ?? current.enableAgentDeviceAccess,
171 deviceOnboardingCompleted:
172 patch.deviceOnboardingCompleted ?? current.deviceOnboardingCompleted,
173 })),
174 streamChanges: Stream.empty,
175 subscribeChanges: Effect.succeed(Stream.empty),
176 }),
177 ),
178 Effect.provideService(
179 HttpClient.HttpClient,
180 HttpClient.make((request) =>
181 Effect.gen(function* () {
182 requests.push(request.url);
183 if (request.url.includes("/api/screenshot")) {
184 return HttpClientResponse.fromWeb(
185 request,
186 new Response(new Uint8Array([137, 80, 78, 71])),
187 );
188 }
189 if (request.url.endsWith("/shutdown")) {
190 shutDown = true;
191 booted = false;
192 return HttpClientResponse.fromWeb(request, Response.json({ ok: true }));
193 }
194 if (shutDown && failListAfterShutdown) {
195 return HttpClientResponse.fromWeb(
196 request,
197 new Response("Discovery busy", { status: 503 }),
198 );
199 }
200 if (request.url.endsWith("/boot")) {
201 yield* onBoot;
202 booted = true;
203 return HttpClientResponse.fromWeb(
204 request,
205 Response.json(
206 bootError ? { ok: false, error: bootError } : { ok: true, serial: "emulator-5554" },
207 ),
208 );
209 }
210 return HttpClientResponse.fromWeb(
211 request,
212 Response.json({
213 simulators: [],
214 emulators: booted
215 ? [
216 {
217 id: "emulator-5554",
218 name: "Pixel_API_35",
219 platform: "android",
220 version: "Android 15",
221 booted: true,
222 physical: false,
223 },
224 ]
225 : [],
226 }),
227 );
228 }),
229 ),
230 ),
231 );
232 return { service, starts, agentStarts, agentStops, requests, settings };
233});
234
235describe("device setup consent", () => {
236 it.effect("exposes daemon startup diagnostics through agent readiness and host status", () =>
237 Effect.gen(function* () {
238 const startupError = new DeviceHost.AgentDeviceStartError({
239 hostId: LOCAL_DEVICE_HOST_ID,
240 stateDir: "/test/device/agent-device",
241 exitCode: 1,
242 reason: "daemon_lock_not_directory",
243 cause: { stdout: "private startup diagnostics", code: 1 },
244 });
245 const { service, settings } = yield* fixture(Effect.void, undefined, false, startupError);
246 yield* Ref.update(settings, (current) => ({
247 ...current,
248 enableDeviceSupport: true,
249 enableAgentDeviceAccess: true,
250 }));
251 const error = yield* service.agentReadinessIfSupported().pipe(Effect.flip);
252 expect(error).toMatchObject({
253 _tag: "DeviceHostUnavailableError",
254 reason: startupError.message,
255 cause: startupError,
256 });
257 expect(error.message).toContain("daemon.lock is not a directory");
258 expect(error.message).not.toContain("private startup diagnostics");
259 expect((yield* service.state).hostStatuses[LOCAL_DEVICE_HOST_ID]).toEqual({
260 status: "failed",
261 detail: startupError.message,
262 });
263 }).pipe(Effect.scoped),
264 );
265
266 it.effect(
267 "preserves missing-runtime guidance and causes through manual and agent readiness",
268 () =>
269 Effect.gen(function* () {
270 const underlying = new Error("private lookup diagnostics");
271 const runtimeFailure = new NodeRuntimeUnavailableError({
272 feature: "Local device support",
273 cause: underlying,
274 });
275 const { service, settings, requests } = yield* fixture(
276 Effect.void,
277 undefined,
278 false,
279 runtimeFailure,
280 );
281 yield* Ref.update(settings, (current) => ({
282 ...current,
283 enableDeviceSupport: true,
284 enableAgentDeviceAccess: true,
285 }));
286 for (const readiness of [service.readiness(), service.agentReadinessIfSupported()]) {
287 const error = yield* readiness.pipe(Effect.flip);
288 expect(error).toMatchObject({
289 _tag: "DeviceHostUnavailableError",
290 reason: expect.stringContaining("Install Node.js"),
291 cause: runtimeFailure,
292 });
293 expect(error.message).not.toContain(underlying.message);
294 }
295 expect((yield* service.state).hostStatuses[LOCAL_DEVICE_HOST_ID]).toMatchObject({
296 status: "failed",
297 detail: expect.stringContaining("Install Node.js"),
298 });
299 expect(requests).toEqual([]);
300 }).pipe(Effect.scoped),
301 );
302
303 it.effect("listing and provider startup do not start helpers before consent", () =>
304 Effect.gen(function* () {
305 const { service, starts, requests } = yield* fixture();
306 expect((yield* service.list).hostStatus).toBe("disabled");
307 expect(yield* service.readinessIfSupported()).toBeNull();
308 const readiness = yield* service.readiness().pipe(Effect.result);
309 expect(readiness._tag).toBe("Failure");
310 expect(starts).toEqual([]);
311 expect(requests).toEqual([]);
312 }).pipe(Effect.scoped),
313 );
314
315 it.effect(
316 "explicit setup discovers never-booted AVDs; disabling stops helpers and blocks agents",
317 () =>
318 Effect.gen(function* () {
319 const { service, starts, settings } = yield* fixture();
320 const state = yield* service.configure({ enabled: true });
321 expect((yield* Ref.get(settings)).enableDeviceSupport).toBe(true);
322 expect(state.devices.map((device) => [device.id, device.booted])).toEqual([
323 ["Pixel_API_35", false],
324 ]);
325 expect(starts).toEqual(["start"]);
326 const disabled = yield* service.configure({ enabled: false });
327 expect(disabled.hostStatus).toBe("disabled");
328 expect(disabled.devices).toEqual([]);
329 expect((yield* Ref.get(settings)).enableDeviceSupport).toBe(false);
330 expect(yield* service.readinessIfSupported()).toBeNull();
331 expect(starts).toEqual(["start", "stop"]);
332 }).pipe(Effect.scoped),
333 );
334
335 it.effect("boots a stopped Android AVD and uses its emulator serial without duplicating it", () =>
336 Effect.gen(function* () {
337 const { service, requests } = yield* fixture();
338 yield* service.configure({ enabled: true });
339 const session = yield* service.open({
340 threadId: ThreadId.make("thread-1"),
341 deviceId: "Pixel_API_35",
342 platform: "android",
343 });
344 expect(session.deviceId).toBe("emulator-5554");
345 expect(requests.filter((url) => url.endsWith("/boot"))).toHaveLength(1);
346 const state = yield* service.state;
347 expect(state.devices.map((device) => device.id)).toEqual(["emulator-5554"]);
348 expect(state.bootingDevices).toEqual([]);
349 }).pipe(Effect.scoped),
350 );
351
352 it.effect("installs agent support only after the separate agent permission", () =>
353 Effect.gen(function* () {
354 const { service, agentStarts, agentStops, settings } = yield* fixture();
355 yield* service.configure({ enabled: true });
356 expect(agentStarts).toEqual([]);
357 expect(yield* service.agentReadinessIfSupported()).toBeNull();
358
359 yield* service.configure({ agentAccessEnabled: true });
360 expect(agentStarts).toEqual(["start"]);
361 expect((yield* Ref.get(settings)).enableAgentDeviceAccess).toBe(true);
362 expect((yield* service.state).agentAccessEnabled).toBe(true);
363
364 yield* service.configure({ agentAccessEnabled: false, onboardingCompleted: true });
365 expect(agentStops).toEqual(["stop"]);
366 expect((yield* service.state).onboardingCompleted).toBe(true);
367 expect((yield* Ref.get(settings)).deviceOnboardingCompleted).toBe(true);
368 }).pipe(Effect.scoped),
369 );
370});
371
372it.effect("publishes boot progress and does not restore sessions after support is disabled", () =>
373 Effect.gen(function* () {
374 const started = yield* Deferred.make<void>();
375 const finish = yield* Deferred.make<void>();
376 const { service } = yield* fixture(
377 Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(finish))),
378 );
379 yield* service.configure({ enabled: true });
380 const opening = yield* service
381 .open({ threadId: ThreadId.make("thread-1"), deviceId: "Pixel_API_35", platform: "android" })
382 .pipe(Effect.result, Effect.forkChild);
383 yield* Deferred.await(started);
384 expect((yield* service.state).bootingDevices?.map((device) => device.name)).toEqual([
385 "Pixel_API_35",
386 ]);
387 yield* service.configure({ enabled: false });
388 yield* Deferred.succeed(finish, undefined);
389 expect((yield* Fiber.join(opening))._tag).toBe("Failure");
390 const state = yield* service.state;
391 expect(state.hostStatus).toBe("disabled");
392 expect(state.devices).toEqual([]);
393 expect(state.sessions).toEqual([]);
394 expect(state.bootingDevices).toEqual([]);
395 }).pipe(Effect.scoped),
396);
397
398describe("device discovery after server restart", () => {
399 it.effect("captures an explicit device before any client lists devices", () =>
400 Effect.gen(function* () {
401 const { service, settings, requests } = yield* fixture();
402 yield* Ref.update(settings, (current) => ({ ...current, enableDeviceSupport: true }));
403 expect((yield* service.state).devices).toEqual([]);
404 const capture = yield* service.screenshot({ deviceId: DeviceId.make("Pixel_API_35") });
405 expect(capture.device.id).toBe("Pixel_API_35");
406 expect(Array.from(capture.png)).toEqual([137, 80, 78, 71]);
407 expect(requests.some((url) => url.endsWith("/api/devices"))).toBe(true);
408 }).pipe(Effect.scoped),
409 );
410});
411
412it.effect.each([
413 {
414 diagnostic: "Insufficient disk space at /private/user/path",
415 reason: "disk_space",
416 message: "not enough free disk space",
417 },
418 {
419 diagnostic: "Timed out spawning /private/user/command",
420 reason: "timeout",
421 message: "did not become ready in time",
422 },
423 {
424 diagnostic: "Unexpected failure: secret-token",
425 reason: "launch_failed",
426 message: "could not start",
427 },
428] as const)("normalizes boot failure: $reason", ({ diagnostic, message }) =>
429 Effect.gen(function* () {
430 const { service } = yield* fixture(Effect.void, diagnostic);
431 yield* service.configure({ enabled: true });
432 const error = yield* service
433 .open({
434 threadId: ThreadId.make("boot-failure"),
435 deviceId: "Pixel_API_35",
436 platform: "android",
437 })
438 .pipe(Effect.flip);
439 expect(error._tag).toBe("DeviceBootError");
440 expect(error.message).toContain(message);
441 expect(error.message).not.toContain(diagnostic);
442 expect((yield* service.state).bootingDevices).toEqual([]);
443 }).pipe(Effect.scoped),
444);
445
446it.effect("keeps shutdown successful when subsequent discovery fails", () =>
447 Effect.gen(function* () {
448 const { service } = yield* fixture(Effect.void, undefined, true);
449 yield* service.configure({ enabled: true });
450 const threadId = ThreadId.make("shutdown-refresh");
451 const session = yield* service.open({
452 threadId,
453 deviceId: "Pixel_API_35",
454 platform: "android",
455 });
456 yield* service.close({ threadId, deviceId: session.deviceId, shutdown: true });
457 const state = yield* service.state;
458 expect(state.sessions).toEqual([]);
459 expect(state.devices.find((device) => device.id === session.deviceId)?.booted).toBe(false);
460 }).pipe(Effect.scoped),
461);
462
463it.effect.each(["shutdown", "close"] as const)(
464 "%s releases iOS capture so reopening uses a fresh session",
465 (operation) =>
466 Effect.gen(function* () {
467 const deviceId = DeviceId.make("11111111-1111-1111-1111-111111111111");
468 const threadId = ThreadId.make("capture-recovery");
469 let booted = true;
470 let capture: number | null = null;
471 let generation = 0;
472 const ready: DeviceHost.DeviceHostReady = {
473 nodePath: process.execPath,
474 hub: { origin: "http://device.test" },
475 helpers: { serveSimAxSettings: null, serveSimCli: null },
476 run: () => Effect.succeed({ code: 0, stdout: "", stderr: "" }),
477 };
478 const host: DeviceHost.DeviceHost["Service"] = {
479 id: LOCAL_DEVICE_HOST_ID,
480 summary: Effect.succeed({
481 id: LOCAL_DEVICE_HOST_ID,
482 kind: "local",
483 label: "Simulator host",
484 platforms: [{ platform: "ios", available: true }],
485 hubInstalled: true,
486 agentDeviceInstalled: false,
487 }),
488 platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
489 ensureReady: () => Effect.succeed(ready),
490 ensureAgentReady: () => Effect.die("Agent access is not used in this test"),
491 current: Effect.succeed(ready),
492 stopAgent: Effect.void,
493 stop: Effect.void,
494 };
495 const http = HttpClient.make((request) =>
496 Effect.sync(() => {
497 const path = new URL(request.url).pathname;
498 if (path === "/api/devices") {
499 return HttpClientResponse.fromWeb(
500 request,
501 Response.json({
502 emulators: [],
503 simulators: [
504 {
505 id: deviceId,
506 name: "iPhone",
507 platform: "ios",
508 version: "26",
509 physical: false,
510 booted,
511 },
512 ],
513 }),
514 );
515 }
516 if (path === "/vendor/serve-sim/grid/api/start") capture ??= ++generation;
517 else if (path === "/vendor/serve-sim/grid/api/shutdown") {
518 if (request.body._tag !== "Uint8Array") throw new Error("Missing shutdown body");
519 expect(decodeJson(new TextDecoder().decode(request.body.body))).toEqual({
520 udid: deviceId,
521 });
522 capture = null;
523 booted = false;
524 } else if (path === "/api/devices/shutdown") {
525 // This route powers off without releasing serve-sim's cached capture.
526 booted = false;
527 } else if (path === "/api/devices/boot") booted = true;
528 else throw new Error(`Unexpected hub path: ${path}`);
529 return HttpClientResponse.fromWeb(request, Response.json({ ok: true, id: deviceId }));
530 }),
531 );
532 const service = yield* DeviceService.makeWithHosts(new Map([[host.id, host]])).pipe(
533 Effect.provide(NodeCrypto.layer),
534 Effect.provideService(HttpClient.HttpClient, http),
535 );
536 const input = { threadId, deviceId, platform: "ios" as const };
537 yield* service.open(input);
538 expect(capture).toBe(1);
539 if (operation === "shutdown") yield* service.shutdown(input);
540 else yield* service.close({ threadId, deviceId, shutdown: true });
541 expect(capture).toBeNull();
542 expect((yield* service.state).sessions).toEqual([]);
543 yield* service.open(input);
544 expect(capture).toBe(2);
545 expect((yield* service.state).sessions).toHaveLength(1);
546 }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true })), Effect.scoped),
547);
548
549it.effect.each([
550 { hubReports: "off", outcome: "succeeds" },
551 { hubReports: "booted", outcome: "fails" },
552 { hubReports: "missing", outcome: "fails" },
553] as const)(
554 "iOS shutdown $outcome when serve-sim rejects it and the hub reports the simulator $hubReports",
555 ({ hubReports, outcome }) =>
556 Effect.gen(function* () {
557 const deviceId = DeviceId.make("22222222-2222-2222-2222-222222222222");
558 const paths: string[] = [];
559 let listed: "booted" | "off" | "missing" = "booted";
560 const ready: DeviceHost.DeviceHostReady = {
561 nodePath: process.execPath,
562 hub: { origin: "http://device.test" },
563 helpers: { serveSimAxSettings: null, serveSimCli: null },
564 run: () => Effect.succeed({ code: 0, stdout: "", stderr: "" }),
565 };
566 const host: DeviceHost.DeviceHost["Service"] = {
567 id: LOCAL_DEVICE_HOST_ID,
568 summary: Effect.succeed({
569 id: LOCAL_DEVICE_HOST_ID,
570 kind: "local",
571 label: "Simulator host",
572 platforms: [{ platform: "ios", available: true }],
573 hubInstalled: true,
574 agentDeviceInstalled: false,
575 }),
576 platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
577 ensureReady: () => Effect.succeed(ready),
578 ensureAgentReady: () => Effect.die("Agent access is not used in this test"),
579 current: Effect.succeed(ready),
580 stopAgent: Effect.void,
581 stop: Effect.void,
582 };
583 const http = HttpClient.make((request) =>
584 Effect.sync(() => {
585 const path = new URL(request.url).pathname;
586 paths.push(path);
587 if (path === "/api/devices") {
588 return HttpClientResponse.fromWeb(
589 request,
590 Response.json({
591 emulators: [],
592 simulators:
593 listed === "missing"
594 ? []
595 : [
596 {
597 id: deviceId,
598 name: "iPhone",
599 platform: "ios",
600 version: "26",
601 physical: false,
602 booted: listed === "booted",
603 },
604 ],
605 errors: listed === "missing" ? [{ message: "simctl list failed" }] : [],
606 }),
607 );
608 }
609 if (path === "/vendor/serve-sim/grid/api/shutdown") {
610 // serve-sim runs `simctl shutdown` bare and returns its failure as-is.
611 listed = hubReports;
612 return HttpClientResponse.fromWeb(
613 request,
614 Response.json(
615 { ok: false, error: "Unable to shutdown device in current state: Shutdown" },
616 { status: 500 },
617 ),
618 );
619 }
620 throw new Error(`Unexpected hub path: ${path}`);
621 }),
622 );
623 const service = yield* DeviceService.makeWithHosts(new Map([[host.id, host]])).pipe(
624 Effect.provide(NodeCrypto.layer),
625 Effect.provideService(HttpClient.HttpClient, http),
626 );
627 yield* service.list;
628 const exit = yield* Effect.exit(service.shutdown({ deviceId, platform: "ios" }));
629 expect(paths.filter((path) => path.endsWith("shutdown"))).toEqual([
630 "/vendor/serve-sim/grid/api/shutdown",
631 ]);
632 if (outcome === "succeeds") {
633 expect(Exit.isSuccess(exit)).toBe(true);
634 expect(
635 (yield* service.state).devices.find((device) => device.id === deviceId)?.booted,
636 ).toBe(false);
637 } else {
638 expect(Exit.isFailure(exit)).toBe(true);
639 expect(
640 (yield* service.state).devices.find((device) => device.id === deviceId)?.booted,
641 ).toBe(true);
642 }
643 }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true })), Effect.scoped),
644);
645
646it.effect("retry keeps device and agent consent unchanged", () =>
647 Effect.gen(function* () {
648 const { service, starts, agentStarts } = yield* fixture();
649 yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
650 expect(starts).toEqual([]);
651 expect(agentStarts).toEqual([]);
652 yield* service.configure({ enabled: true });
653 yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
654 expect(agentStarts).toEqual([]);
655 yield* service.configure({ agentAccessEnabled: true });
656 const before = agentStarts.length;
657 yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
658 expect(agentStarts.length).toBe(before + 1);
659 }).pipe(Effect.scoped),
660);
661
662it.effect("publishes update detail for the correct host", () =>
663 Effect.gen(function* () {
664 const { service } = yield* fixture();
665 const changes = yield* service.subscribe;
666 yield* service.configure({ enabled: true });
667 const states = yield* PubSub.takeAll(changes);
668 expect(
669 states.some(
670 (state) => state.hostStatuses.local?.detail === "Updating device hub from 0.9.0 to 0.10.1…",
671 ),
672 ).toBe(true);
673 }).pipe(Effect.scoped),
674);
675
676it.effect("host retry exposes actionable failure without internal IDs or diagnostics", () =>
677 Effect.gen(function* () {
678 const { service, settings } = yield* fixture(
679 Effect.void,
680 undefined,
681 false,
682 new DeviceHost.DeviceHostError({
683 hostId: LOCAL_DEVICE_HOST_ID,
684 step: "probe",
685 cause: "private diagnostics",
686 }),
687 );
688 yield* Ref.update(settings, (current) => ({ ...current, enableDeviceSupport: true }));
689 const state = yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
690 expect(state.supportsHostRetry).toBe(true);
691 expect(state.hostStatuses[LOCAL_DEVICE_HOST_ID]).toEqual({
692 status: "failed",
693 detail: "Could not connect to this host over SSH.",
694 });
695 }).pipe(Effect.scoped),
696);
697
698it.effect.each([
699 {
700 name: "missing Node among private diagnostic lines",
701 exitCode: 1,
702 stderr:
703 "private diagnostics\r\nNode is missing from the non-interactive SSH PATH\r\nprivate diagnostics",
704 expected:
705 "Connected over SSH, but Node is not on this host's PATH for non-interactive SSH commands.",
706 },
707 {
708 name: "another remote command failure",
709 exitCode: 2,
710 stderr: "private diagnostics",
711 expected: "Connected over SSH, but the device host check failed (exit code 2).",
712 },
713 {
714 name: "an unrecognized exit-one diagnostic",
715 exitCode: 1,
716 stderr: "private diagnostics: Node is missing from the non-interactive SSH PATH",
717 expected: "Connected over SSH, but the device host check failed (exit code 1).",
718 },
719 {
720 name: "a connection failure",
721 exitCode: 255,
722 stderr: "Node is missing from the non-interactive SSH PATH",
723 expected: "Could not connect to this host over SSH.",
724 },
725 {
726 name: "a command that could not start",
727 exitCode: null,
728 stderr: "private diagnostics",
729 expected: "Could not connect to this host over SSH.",
730 },
731 {
732 name: "an untyped offline cause",
733 exitCode: undefined,
734 stderr: "private diagnostics",
735 expected: "Could not connect to this host over SSH.",
736 },
737])("reports $name through manual and agent host readiness", ({ exitCode, stderr, expected }) =>
738 Effect.gen(function* () {
739 const failure = new DeviceHost.DeviceHostError({
740 hostId: LOCAL_DEVICE_HOST_ID,
741 step: "probe",
742 cause:
743 exitCode === undefined
744 ? "offline"
745 : new SshCommandError({
746 command: ["ssh", "private arguments"],
747 exitCode,
748 stderr,
749 stdout: "private output",
750 message: "private diagnostics",
751 }),
752 });
753 const { service, settings } = yield* fixture(Effect.void, undefined, false, failure);
754 yield* Ref.update(settings, (current) => ({
755 ...current,
756 enableDeviceSupport: true,
757 enableAgentDeviceAccess: true,
758 }));
759 for (const readiness of [service.readiness(), service.agentReadinessIfSupported()]) {
760 const error = yield* readiness.pipe(Effect.flip);
761 expect(error).toMatchObject({ reason: expected, cause: failure });
762 expect((yield* service.state).hostStatuses[LOCAL_DEVICE_HOST_ID]).toEqual({
763 status: "failed",
764 detail: expected,
765 });
766 }
767 for (const state of [yield* service.list, yield* service.retryHost(LOCAL_DEVICE_HOST_ID)]) {
768 expect(state.hostStatuses[LOCAL_DEVICE_HOST_ID]).toEqual({
769 status: "failed",
770 detail: expected,
771 });
772 }
773 }).pipe(Effect.scoped),
774);
775
776it.effect("version discovery does not grant consent or start device tools", () =>
777 Effect.gen(function* () {
778 const { service, starts, agentStarts, requests } = yield* fixture();
779 const state = yield* service.inspect;
780 expect(state.supportsToolInspection).toBe(true);
781 expect(state.hostStatus).toBe("disabled");
782 expect(state.hosts).toHaveLength(1);
783 expect(starts).toEqual([]);
784 expect(agentStarts).toEqual([]);
785 expect(requests).toEqual([]);
786 }).pipe(Effect.scoped),
787);
788
789it.effect("failed read-only discovery preserves lifecycle status and installed inventory", () =>
790 Effect.gen(function* () {
791 const { service, starts } = yield* fixture(Effect.void, undefined, false, undefined, true);
792 const state = yield* service.inspect;
793 expect(state.supportsToolInspection).toBe(true);
794 expect(state.hostStatus).toBe("disabled");
795 expect(state.hosts[0]?.hubInstalled).toBe(true);
796 expect(state.hosts[0]?.toolInspectionError).toContain("Reconnect the host");
797 expect(starts).toEqual([]);
798 }).pipe(Effect.scoped),
799);
800
801it.effect(
802 "manual updates install only the selected tool without enabling access or starting helpers",
803 () =>
804 Effect.gen(function* () {
805 const installed: string[] = [];
806 const { service, starts, agentStarts, requests } = yield* fixture(
807 Effect.void,
808 undefined,
809 false,
810 undefined,
811 false,
812 (tool) =>
813 Effect.sync(() => {
814 installed.push(tool);
815 }),
816 );
817 const before = yield* service.state;
818 const state = yield* service.updateTool("agent");
819 expect(installed).toEqual(["agent"]);
820 expect(state.supportsToolUpdate).toBe(true);
821 expect(state.hostStatus).toBe(before.hostStatus);
822 expect(state.agentAccessEnabled).toBe(before.agentAccessEnabled);
823 expect(state.revision).toBeGreaterThan(before.revision);
824 expect(starts).toEqual([]);
825 expect(agentStarts).toEqual([]);
826 expect(requests).toEqual([]);
827 yield* service.updateTool("hub");
828 expect(installed).toEqual(["agent", "hub"]);
829 }).pipe(Effect.scoped),
830);
831
832it.effect("failed manual installation leaves lifecycle state unchanged and can be retried", () =>
833 Effect.gen(function* () {
834 let attempts = 0;
835 const { service, starts, agentStarts } = yield* fixture(
836 Effect.void,
837 undefined,
838 false,
839 undefined,
840 false,
841 () =>
842 Effect.suspend(() =>
843 ++attempts === 1
844 ? Effect.fail(
845 new DeviceOperationError({
846 operation: "update device tool",
847 reason: "command_failed",
848 cause: new Error("offline"),
849 }),
850 )
851 : Effect.void,
852 ),
853 );
854 const before = yield* service.state;
855 const result = yield* service.updateTool("agent").pipe(Effect.result);
856 expect(result._tag).toBe("Failure");
857 expect(yield* service.state).toEqual(before);
858 yield* service.updateTool("agent");
859 expect(attempts).toBe(2);
860 expect(starts).toEqual([]);
861 expect(agentStarts).toEqual([]);
862 }).pipe(Effect.scoped),
863);
864
865it.effect("reconciles SSH host settings without publishing no-op changes", () =>
866 Effect.gen(function* () {
867 const fs = yield* FileSystem.FileSystem;
868 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-reconcile-" });
869 const settings = yield* ServerSettings.ServerSettingsService;
870 // Each change is acknowledged after reconciliation consumed it, so no-ops are observable.
871 const changes = yield* Queue.unbounded<{ value: Settings; done: Deferred.Deferred<void> }>();
872 const removedFiles: string[] = [];
873 const localHost: DeviceHost.DeviceHost["Service"] = {
874 id: LOCAL_DEVICE_HOST_ID,
875 summary: Effect.succeed({
876 id: LOCAL_DEVICE_HOST_ID,
877 label: "Local",
878 kind: "local",
879 platforms: [],
880 hubInstalled: false,
881 agentDeviceInstalled: false,
882 }),
883 platformAvailability: (platform) => Effect.succeed({ platform, available: false }),
884 current: Effect.succeed(null),
885 ensureReady: () => Effect.die("Unexpected device launch"),
886 ensureAgentReady: () => Effect.die("Unexpected agent launch"),
887 stop: Effect.void,
888 stopAgent: Effect.void,
889 };
890 const service = yield* DeviceService.make.pipe(
891 Effect.provideService(DeviceHost.DeviceHost, localHost),
892 Effect.provideService(ServerSettings.ServerSettingsService, {
893 ...settings,
894 subscribeChanges: Effect.succeed(
895 Stream.fromQueue(changes).pipe(
896 Stream.flatMap(({ value, done }) =>
897 Stream.make(value).pipe(
898 Stream.concat(
899 Stream.fromEffect(Deferred.succeed(done, undefined)).pipe(Stream.drain),
900 ),
901 ),
902 ),
903 ),
904 ),
905 }),
906 Effect.provideService(
907 FileSystem.FileSystem,
908 FileSystem.makeNoop({
909 remove: (file) => Effect.sync(() => void removedFiles.push(file)),
910 }),
911 ),
912 Effect.provideService(ProcessRunner.ProcessRunner, {
913 run: () => Effect.die("Unexpected helper launch"),
914 }),
915 Effect.provideService(
916 HttpClient.HttpClient,
917 HttpClient.make(() => Effect.die("Unexpected HTTP request")),
918 ),
919 // `ssh -G` resolves the target to a non-local address.
920 Effect.provideService(
921 ChildProcessSpawner.ChildProcessSpawner,
922 ChildProcessSpawner.make(() =>
923 Effect.succeed(
924 ChildProcessSpawner.makeHandle({
925 pid: ChildProcessSpawner.ProcessId(123),
926 stdout: Stream.make(new TextEncoder().encode("hostname 192.0.2.1\nport 22\n")),
927 stderr: Stream.empty,
928 all: Stream.empty,
929 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
930 isRunning: Effect.succeed(false),
931 kill: () => Effect.void,
932 stdin: Sink.drain,
933 getInputFd: () => Sink.drain,
934 getOutputFd: () => Stream.empty,
935 unref: Effect.succeed(Effect.void),
936 }),
937 ),
938 ),
939 ),
940 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(baseDir, baseDir), NetService.layer)),
941 );
942 const update = Effect.fnUntraced(function* (deviceHosts: ReadonlyArray<SshDeviceHostConfig>) {
943 const value = yield* settings.updateSettings({ deviceHosts: [...deviceHosts] });
944 const done = yield* Deferred.make<void>();
945 yield* Queue.offer(changes, { value, done });
946 yield* Deferred.await(done);
947 return yield* service.state;
948 });
949
950 const initial = yield* service.state;
951 expect(yield* update([])).toEqual(initial);
952
953 const host: SshDeviceHostConfig = { id: "remote", label: "Remote", target: "remote-fixture" };
954 const added = yield* update([host]);
955 expect(added.hosts.map((entry) => entry.id)).toEqual([LOCAL_DEVICE_HOST_ID, host.id]);
956 expect(yield* update([{ ...host }])).toEqual(added);
957
958 yield* service.setHostStatus(host.id, { status: "failed", detail: "stale" });
959 const removed = yield* update([]);
960 expect(removed.hosts.map((entry) => entry.id)).toEqual([LOCAL_DEVICE_HOST_ID]);
961 expect(removed.hostStatuses[host.id]).toBeUndefined();
962 expect(removedFiles).toHaveLength(1);
963 }).pipe(
964 Effect.scoped,
965 Effect.provide(Layer.mergeAll(ServerSettings.layerTest(), NodeServices.layer)),
966 ),
967);
968
969it.effect("a failed tool update reports npm's exit code but not its output", () =>
970 Effect.gen(function* () {
971 const host: DeviceHost.DeviceHost["Service"] = {
972 id: LOCAL_DEVICE_HOST_ID,
973 summary: Effect.succeed({
974 id: LOCAL_DEVICE_HOST_ID,
975 kind: "local",
976 label: "Test server",
977 platforms: [],
978 hubInstalled: false,
979 agentDeviceInstalled: false,
980 }),
981 platformAvailability: (platform) => Effect.succeed({ platform, available: false }),
982 ensureReady: () => Effect.die("Updating a tool does not start the hub"),
983 ensureAgentReady: () => Effect.die("Updating a tool does not start the agent"),
984 current: Effect.succeed(null),
985 stopAgent: Effect.void,
986 stop: Effect.void,
987 };
988 const npmFailure = {
989 code: ChildProcessSpawner.ExitCode(243),
990 stdout: "",
991 stderr: "npm error EACCES https://private:credential@registry.example.test/expo-device-hub",
992 timedOut: false,
993 stdoutTruncated: false,
994 stderrTruncated: false,
995 stdoutInvalidUtf8: false,
996 stderrInvalidUtf8: false,
997 };
998 const service = yield* DeviceService.make.pipe(
999 Effect.provideService(DeviceHost.DeviceHost, host),
1000 Effect.provideService(ProcessRunner.ProcessRunner, {
1001 run: () => Effect.succeed(npmFailure),
1002 }),
1003 Effect.provideService(
1004 HttpClient.HttpClient,
1005 HttpClient.make(() => Effect.die("Updating a tool makes no hub requests")),
1006 ),
1007 );
1008
1009 const error = yield* service.updateTool("hub").pipe(Effect.flip);
1010 expect(error).toMatchObject({
1011 _tag: "DeviceOperationError",
1012 reason: "command_failed",
1013 exitCode: 243,
1014 });
1015 expect(error.message).toBe(
1016 "Device update device tool failed: The device command failed (exit code 243).",
1017 );
1018 }).pipe(
1019 Effect.provide(
1020 Layer.mergeAll(
1021 ServerSettings.layerTest({ enableDeviceSupport: true }),
1022 ServerConfig.layerTest(process.cwd(), { prefix: "t3-device-update-" }),
1023 NodeCrypto.layer,
1024 NetService.layer,
1025 ).pipe(Layer.provideMerge(NodeServices.layer)),
1026 ),
1027 Effect.scoped,
1028 ),
1029);