The best way to control Claude Code, Codex and more from any computer or phone

main
ts 2,360 lines 89.8 KB
Raw
1 import { describe, expect, it } from "@effect/vitest";
2 import {
3 DEFAULT_SERVER_SETTINGS,
4 DeviceBootError,
5 DeviceError,
6 DeviceId,
7 DeviceOperationError,
8 LOCAL_DEVICE_HOST_ID,
9 ThreadId,
10 type DeviceSummary,
11 type ServerSettings as Settings,
12 type SshDeviceHostConfig,
13 } from "@t3tools/contracts";
14 import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
15 import * as NodeServices from "@effect/platform-node/NodeServices";
16 import * as NetService from "@t3tools/shared/Net";
17 import { SshCommandError } from "@t3tools/ssh/errors";
18 import * as Effect from "effect/Effect";
19 import * as Exit from "effect/Exit";
20 import * as Deferred from "effect/Deferred";
21 import * as Fiber from "effect/Fiber";
22 import * as FileSystem from "effect/FileSystem";
23 import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
24 import * as Layer from "effect/Layer";
25 import * as Option from "effect/Option";
26 import * as PlatformError from "effect/PlatformError";
27 import * as PubSub from "effect/PubSub";
28 import * as Queue from "effect/Queue";
29 import * as Ref from "effect/Ref";
30 import * as Schema from "effect/Schema";
31 import * as Sink from "effect/Sink";
32 import * as Stream from "effect/Stream";
33 import * as TestClock from "effect/testing/TestClock";
34 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
35 import { HttpClient, HttpClientResponse } from "effect/http";
36 import * as ServerConfig from "../config.ts";
37 import * as ProcessRunner from "../processRunner.ts";
38 import * as ServerSettings from "../serverSettings.ts";
39 import * as DeviceHost from "./DeviceHost.ts";
40 import { makeDeviceHubOperations } from "./DeviceHubOperations.ts";
41 import { NodeRuntimeUnavailableError } from "@t3tools/shared/nodeRuntime";
42
43 import * as DeviceService from "./DeviceService.ts";
44 import * as SshDeviceHost from "./SshDeviceHost.ts";
45 import { agentDeviceSession, releaseAgentDeviceSession } from "./AgentDeviceTarget.ts";
46 import { ensureDeviceHub } from "./DeviceToolchain.ts";
47
48 const decodeJson = Schema.decodeUnknownSync(Schema.fromJsonString(Schema.Unknown));
49 const decodeBootError = Schema.decodeUnknownSync(Schema.fromJsonString(DeviceBootError));
50 const encodeBootError = Schema.encodeSync(Schema.fromJsonString(DeviceBootError));
51
52 const pngChunk = (type: string, length: number) => {
53 const chunk = new Uint8Array(12 + length);
54 new DataView(chunk.buffer).setUint32(0, length);
55 chunk.set(new TextEncoder().encode(type), 4);
56 return chunk;
57 };
58 const minimalPng = Uint8Array.from([
59 137,
60 80,
61 78,
62 71,
63 13,
64 10,
65 26,
66 10,
67 ...pngChunk("IHDR", 13),
68 ...pngChunk("IEND", 0),
69 ]);
70
71 it.effect.each([400, 500])(
72 "retries a hub-rejected (%s) screenshot with simctl only on iOS 26 and older",
73 (status) =>
74 Effect.gen(function* () {
75 const operations = makeDeviceHubOperations({
76 hostId: LOCAL_DEVICE_HOST_ID,
77 origin: "http://device.test",
78 http: HttpClient.make((request) =>
79 Effect.succeed(
80 HttpClientResponse.fromWeb(request, new Response("private hub output", { status })),
81 ),
82 ),
83 run: () => Effect.succeed({ code: 0, stdout: "iVBORw==", stderr: "" }),
84 platformAvailable: () => Effect.succeed(false),
85 });
86 const screenshot = (version: string) =>
87 operations
88 .screenshot({
89 id: "phone",
90 name: "Phone",
91 version,
92 platform: "ios",
93 booted: true,
94 physical: false,
95 })
96 .pipe(Effect.result);
97 expect(yield* screenshot("iOS 27.0")).toMatchObject({
98 failure: { _tag: "DeviceOperationError", reason: "hub_rejected" },
99 });
100 expect(yield* screenshot("iOS 26.3")).toMatchObject({
101 success: new Uint8Array([137, 80, 78, 71]),
102 });
103 }),
104 );
105
106 it.effect("lists adb-attached physical devices when the hub cannot run avdmanager", () =>
107 Effect.gen(function* () {
108 // expo-device-hub returns no Android devices at all once `avdmanager list avd` fails.
109 const operations = makeDeviceHubOperations({
110 hostId: LOCAL_DEVICE_HOST_ID,
111 origin: "http://device.test",
112 http: HttpClient.make((request) =>
113 Effect.succeed(
114 HttpClientResponse.fromWeb(
115 request,
116 Response.json({
117 simulators: [],
118 emulators: [],
119 errors: [
120 {
121 id: "avd",
122 message: "[android-utils] Failed to run `avdmanager list avd`:",
123 error:
124 "Error: Command failed: avdmanager list avd\nThe operation couldn’t be completed. Unable to locate a Java Runtime.",
125 },
126 ],
127 }),
128 ),
129 ),
130 ),
131 run: (command, args) =>
132 Effect.succeed(
133 command === "adb" && args.includes("devices")
134 ? {
135 code: 0,
136 stdout:
137 "List of devices attached\nR52T10ABCDE device usb:1-1 product:gts9wifi model:SM_X710 device:gts9wifi transport_id:1\n\n",
138 stderr: "",
139 }
140 : command === "adb" && args.includes("getprop")
141 ? {
142 code: 0,
143 stdout:
144 "[ro.product.manufacturer]: [samsung]\n[ro.product.model]: [SM-X710]\n[ro.build.version.release]: [15]\n",
145 stderr: "",
146 }
147 : { code: 0, stdout: "", stderr: "" },
148 ),
149 platformAvailable: (platform) => Effect.succeed(platform === "android"),
150 });
151 const listed = yield* operations.list;
152 expect(listed.devices).toContainEqual(
153 expect.objectContaining({
154 id: "R52T10ABCDE",
155 platform: "android",
156 booted: true,
157 physical: true,
158 }),
159 );
160 }),
161 );
162
163 const fixture = Effect.fn("fixture")(function* (
164 onBoot: Effect.Effect<void> = Effect.void,
165 bootError?: string | { error?: string; errors?: Array<{ message: string; error?: string }> },
166 failListAfterShutdown = false,
167 runtimeFailure?:
168 | NodeRuntimeUnavailableError
169 | DeviceHost.DeviceHostError
170 | DeviceHost.AgentDeviceStartError,
171 inspectError = false,
172 installTool?: Parameters<typeof DeviceService.makeWithHosts>[3],
173 options: {
174 readonly endsDevices?: boolean;
175 readonly routesStreams?: boolean;
176 readonly onClose?: Effect.Effect<"ok" | "missing" | "reject" | "http_error" | "malformed">;
177 readonly onPlatformAvailability?: Effect.Effect<void>;
178 } = {},
179 ) {
180 const settings = yield* Ref.make(DEFAULT_SERVER_SETTINGS);
181 const starts: string[] = [];
182 const agentStarts: string[] = [];
183 const agentStops: string[] = [];
184 const requests: string[] = [];
185 const closedSessions: unknown[] = [];
186 const devices: Array<Omit<DeviceSummary, "hostId">> = [];
187 const discoveryErrors = yield* Ref.make<Array<{ message: string; error?: string }>>([]);
188 const androidAvailable = yield* Ref.make(true);
189 const iosAvailable = yield* Ref.make(true);
190 const encoderResult = yield* Ref.make({ code: 0, stdout: " V....D libx264", stderr: "" });
191 const screenshotBody = yield* Ref.make(minimalPng);
192 const listing = { hangs: false, requested: yield* Deferred.make<void>() };
193 let booted = false;
194 let shutDown = false;
195 const connection = { online: true, kind: "local" as "local" | "ssh", failShutdown: false };
196 const http = HttpClient.make((request) =>
197 Effect.gen(function* () {
198 requests.push(request.url);
199 if (request.url === "http://agent.test/rpc") {
200 if (request.body._tag !== "Uint8Array") throw new Error("Missing close body");
201 const body = decodeJson(new TextDecoder().decode(request.body.body));
202 closedSessions.push(body);
203 expect(request.headers.authorization).toBe("Bearer test");
204 const outcome = yield* options.onClose ?? Effect.succeed("ok");
205 return HttpClientResponse.fromWeb(
206 request,
207 outcome === "missing"
208 ? Response.json(
209 {
210 error: {
211 code: -32000,
212 message: "No active session",
213 data: { code: "SESSION_NOT_FOUND" },
214 },
215 },
216 { status: 404 },
217 )
218 : outcome === "http_error"
219 ? new Response("Offline", { status: 503 })
220 : outcome === "malformed"
221 ? new Response("not JSON")
222 : Response.json(
223 outcome === "ok"
224 ? { result: { ok: true } }
225 : { error: { code: -32000, message: "offline" } },
226 ),
227 );
228 }
229 if (request.url.includes("/api/screenshot")) {
230 return HttpClientResponse.fromWeb(request, new Response(yield* Ref.get(screenshotBody)));
231 }
232 if (request.url.endsWith("/shutdown")) {
233 if (connection.failShutdown)
234 return HttpClientResponse.fromWeb(request, Response.json({ ok: false }));
235 shutDown = true;
236 booted = false;
237 return HttpClientResponse.fromWeb(request, Response.json({ ok: true }));
238 }
239 if (shutDown && failListAfterShutdown) {
240 return HttpClientResponse.fromWeb(request, new Response("Discovery busy", { status: 503 }));
241 }
242 if (request.url.endsWith("/boot")) {
243 yield* onBoot;
244 booted = true;
245 return HttpClientResponse.fromWeb(
246 request,
247 Response.json(
248 bootError
249 ? { ok: false, ...(typeof bootError === "string" ? { error: bootError } : bootError) }
250 : { ok: true, serial: "emulator-5554" },
251 ),
252 );
253 }
254 if (request.url.endsWith("/grid/api/start")) {
255 return HttpClientResponse.fromWeb(request, Response.json({ ok: true }));
256 }
257 if (listing.hangs) {
258 return yield* Deferred.succeed(listing.requested, undefined).pipe(
259 Effect.andThen(Effect.never),
260 );
261 }
262 return HttpClientResponse.fromWeb(
263 request,
264 Response.json({
265 errors: yield* Ref.get(discoveryErrors),
266 simulators: devices.filter((device) => device.platform === "ios"),
267 emulators: [
268 ...devices.filter((device) => device.platform === "android"),
269 ...(booted
270 ? [
271 {
272 id: "emulator-5554",
273 name: "Pixel_API_35",
274 platform: "android",
275 version: "Android 15",
276 booted: true,
277 physical: false,
278 },
279 ]
280 : []),
281 ],
282 }),
283 );
284 }),
285 );
286 const run = (command: string) =>
287 command === "emulator"
288 ? Effect.succeed({ code: 0, stdout: "Pixel_API_35\n", stderr: "" })
289 : Ref.get(encoderResult);
290 const ready: DeviceHost.DeviceHostReady = {
291 nodePath: process.execPath,
292 hub: { origin: "http://device.test" },
293 devices: {
294 ...makeDeviceHubOperations({
295 hostId: LOCAL_DEVICE_HOST_ID,
296 origin: "http://device.test",
297 http,
298 run,
299 platformAvailable: (platform) =>
300 Ref.get(platform === "ios" ? iosAvailable : androidAvailable),
301 }),
302 ...(options.endsDevices ? { endsDevices: true } : {}),
303 },
304 helpers: { serveSimAxSettings: null, serveSimCli: null },
305 run,
306 ...(options.routesStreams ? { upstream: () => Effect.succeed(null) } : {}),
307 };
308 const host: DeviceHost.DeviceHost["Service"] = {
309 ...(inspectError
310 ? {
311 inspect: Effect.fail(
312 new DeviceHost.DeviceHostError({
313 hostId: LOCAL_DEVICE_HOST_ID,
314 step: "probe",
315 cause: new Error("offline"),
316 }),
317 ),
318 }
319 : {}),
320 id: LOCAL_DEVICE_HOST_ID,
321 label: "This machine",
322 summary: Effect.sync(() => ({
323 id: LOCAL_DEVICE_HOST_ID,
324 kind: connection.kind,
325 label: "Test server",
326 platforms: [
327 { platform: "android", available: true },
328 { platform: "ios", available: true },
329 ],
330 hubInstalled: true,
331 agentDeviceInstalled: false,
332 })),
333 platformAvailability: (platform) =>
334 (options.onPlatformAvailability ?? Effect.void).pipe(
335 Effect.as({ platform, available: true }),
336 ),
337 ensureReady: (onPhase) =>
338 Effect.gen(function* () {
339 if (runtimeFailure && runtimeFailure._tag !== "AgentDeviceStartError")
340 return yield* runtimeFailure;
341 starts.push("start");
342 yield* onPhase("installing", "Updating device hub from 0.9.0 to 0.10.1…");
343 return ready;
344 }),
345 ensureAgentReady: (onPhase) =>
346 Effect.gen(function* () {
347 if (runtimeFailure) return yield* runtimeFailure;
348 agentStarts.push("start");
349 yield* onPhase("starting");
350 return {
351 ...ready,
352 agentDevice: { baseUrl: "http://agent.test", token: "test", entryPath: "/agent" },
353 };
354 }),
355 current: Effect.sync(() =>
356 connection.online
357 ? {
358 ...ready,
359 ...(agentStarts.length > agentStops.length
360 ? {
361 releaseAgentSession: releaseAgentDeviceSession(http, {
362 baseUrl: "http://agent.test",
363 token: "test",
364 }),
365 }
366 : {}),
367 }
368 : null,
369 ),
370 stopAgent: Effect.sync(() => {
371 agentStops.push("stop");
372 }),
373 stop: Effect.sync(() => {
374 starts.push("stop");
375 }),
376 };
377 const service = yield* DeviceService.makeWithHosts(
378 new Map([[host.id, host]]),
379 undefined,
380 () => Effect.succeed("/host.json"),
381 installTool,
382 ).pipe(
383 Effect.provide(NodeCrypto.layer),
384 Effect.provideService(DeviceHost.DeviceHost, host),
385 Effect.provideService(
386 ServerSettings.ServerSettingsService,
387 ServerSettings.ServerSettingsService.of({
388 updateProviderInstance: () => Effect.die("Unexpected provider mutation"),
389 withSettingsSnapshot: (use) => Effect.flatMap(Ref.get(settings), use),
390 start: Effect.void,
391 ready: Effect.void,
392 getSettings: Ref.get(settings),
393 updateSettings: (patch) =>
394 Ref.updateAndGet(settings, (current) => ({
395 ...current,
396 enableDeviceSupport: patch.enableDeviceSupport ?? current.enableDeviceSupport,
397 enableAgentDeviceAccess:
398 patch.enableAgentDeviceAccess ?? current.enableAgentDeviceAccess,
399 deviceOnboardingCompleted:
400 patch.deviceOnboardingCompleted ?? current.deviceOnboardingCompleted,
401 })),
402 streamChanges: Stream.empty,
403 subscribeChanges: Effect.succeed(Stream.empty),
404 }),
405 ),
406 );
407 // The host ending a device on its own, as Expo does at a session's limits.
408 const endDevice = () => {
409 booted = false;
410 };
411 return {
412 service,
413 host,
414 starts,
415 agentStarts,
416 agentStops,
417 requests,
418 settings,
419 closedSessions,
420 connection,
421 devices,
422 encoderResult,
423 screenshotBody,
424 discoveryErrors,
425 androidAvailable,
426 iosAvailable,
427 listing,
428 endDevice,
429 };
430 });
431
432 describe("device setup consent", () => {
433 it.effect("exposes daemon startup diagnostics through agent readiness and host status", () =>
434 Effect.gen(function* () {
435 const startupError = new DeviceHost.AgentDeviceStartError({
436 hostId: LOCAL_DEVICE_HOST_ID,
437 stateDir: "/test/device/agent-device",
438 exitCode: 1,
439 reason: "daemon_lock_not_directory",
440 cause: { stdout: "private startup diagnostics", code: 1 },
441 });
442 const { service, settings } = yield* fixture(Effect.void, undefined, false, startupError);
443 yield* Ref.update(settings, (current) => ({
444 ...current,
445 enableDeviceSupport: true,
446 enableAgentDeviceAccess: true,
447 }));
448 const error = yield* service.agentReadinessIfSupported().pipe(Effect.flip);
449 expect(error).toMatchObject({
450 _tag: "DeviceHostUnavailableError",
451 reason: startupError.message,
452 cause: startupError,
453 });
454 expect(error.message).toContain("daemon.lock is not a directory");
455 expect(error.message).not.toContain("private startup diagnostics");
456 expect((yield* service.state).hostStatuses[LOCAL_DEVICE_HOST_ID]).toEqual({
457 status: "failed",
458 detail: startupError.message,
459 });
460 }),
461 );
462
463 it.effect("names the missing npm in the host status when device support cannot install", () =>
464 Effect.gen(function* () {
465 const fs = yield* FileSystem.FileSystem;
466 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-no-npm-" });
467 const installError = yield* ensureDeviceHub(baseDir).pipe(
468 Effect.provideService(ProcessRunner.ProcessRunner, {
469 run: (input) =>
470 Effect.fail(
471 new ProcessRunner.ProcessSpawnError({
472 command: input.command,
473 argumentCount: input.args.length,
474 cause: PlatformError.systemError({
475 _tag: "NotFound",
476 module: "ChildProcess",
477 method: "spawn",
478 description: `spawn ${input.command} ENOENT`,
479 }),
480 }),
481 ),
482 }),
483 Effect.flip,
484 );
485 const { service, settings } = yield* fixture(
486 Effect.void,
487 undefined,
488 false,
489 new DeviceHost.DeviceHostError({
490 hostId: LOCAL_DEVICE_HOST_ID,
491 step: "installing device support",
492 cause: installError,
493 }),
494 );
495 yield* Ref.update(settings, (current) => ({ ...current, enableDeviceSupport: true }));
496 const detail = (yield* service.list).hostStatuses[LOCAL_DEVICE_HOST_ID]?.detail;
497 expect(detail).toMatch(/\bnpm\b/);
498 expect(detail).toMatch(/Node\.js/);
499 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
500 );
501
502 it.effect.each([
503 {
504 name: "a Windows host",
505 exitCode: 1,
506 stderr: "private diagnostics",
507 expected:
508 "Connected over SSH, but this host runs Windows, and SSH device hosts currently need macOS or Linux. To use this machine's devices, run T3 Code on it and connect to that environment.",
509 },
510 {
511 name: "a Windows host returning 9009",
512 exitCode: 9009,
513 stderr: "private diagnostics",
514 expected:
515 "Connected over SSH, but this host runs Windows, and SSH device hosts currently need macOS or Linux. To use this machine's devices, run T3 Code on it and connect to that environment.",
516 },
517 {
518 name: "missing Node on a Windows host with a POSIX shell",
519 exitCode: 1,
520 stderr: "private diagnostics\nNode is missing from the non-interactive SSH PATH",
521 expected:
522 "Connected over SSH, but Node is not on this host's PATH for non-interactive SSH commands.",
523 },
524 ])(
525 "reports SSH probe failure on $name through readiness and host status",
526 ({ exitCode, stderr, expected }) =>
527 Effect.gen(function* () {
528 const failure = new DeviceHost.DeviceHostError({
529 hostId: LOCAL_DEVICE_HOST_ID,
530 step: "probe",
531 cause: new SshDeviceHost.SshWindowsHostError({
532 cause: new SshCommandError({
533 command: ["ssh", "private arguments"],
534 exitCode,
535 stderr,
536 message: "private diagnostics",
537 }),
538 }),
539 });
540 const { service, settings } = yield* fixture(Effect.void, undefined, false, failure);
541 yield* Ref.update(settings, (current) => ({
542 ...current,
543 enableDeviceSupport: true,
544 enableAgentDeviceAccess: true,
545 }));
546 for (const readiness of [service.readiness(), service.agentReadinessIfSupported()]) {
547 const error = yield* readiness.pipe(Effect.flip);
548 expect(error).toMatchObject({ reason: expected, cause: failure });
549 expect((yield* service.state).hostStatuses[LOCAL_DEVICE_HOST_ID]).toEqual({
550 status: "failed",
551 detail: expected,
552 });
553 }
554 }),
555 );
556
557 it.effect("listing and provider startup do not start helpers before consent", () =>
558 Effect.gen(function* () {
559 const { service, starts, requests } = yield* fixture();
560 expect((yield* service.list).hostStatus).toBe("disabled");
561 expect(yield* service.readinessIfSupported()).toBeNull();
562 const readiness = yield* service.readiness().pipe(Effect.result);
563 expect(readiness._tag).toBe("Failure");
564 expect(starts).toEqual([]);
565 expect(requests).toEqual([]);
566 }),
567 );
568
569 it.effect(
570 "explicit setup discovers never-booted AVDs; disabling stops helpers and blocks agents",
571 () =>
572 Effect.gen(function* () {
573 const { service, starts, settings } = yield* fixture();
574 const state = yield* service.configure({ enabled: true });
575 expect((yield* Ref.get(settings)).enableDeviceSupport).toBe(true);
576 expect(state.devices.map((device) => [device.id, device.booted])).toEqual([
577 ["Pixel_API_35", false],
578 ]);
579 expect(starts).toEqual(["start"]);
580 const disabled = yield* service.configure({ enabled: false });
581 expect(disabled.hostStatus).toBe("disabled");
582 expect(disabled.devices).toEqual([]);
583 expect((yield* Ref.get(settings)).enableDeviceSupport).toBe(false);
584 expect(yield* service.readinessIfSupported()).toBeNull();
585 expect(starts).toEqual(["start", "stop"]);
586 }),
587 );
588
589 it.effect("boots a stopped Android AVD and uses its emulator serial without duplicating it", () =>
590 Effect.gen(function* () {
591 const { service, requests } = yield* fixture();
592 yield* service.configure({ enabled: true });
593 const session = yield* service.open({
594 threadId: ThreadId.make("thread-1"),
595 deviceId: "Pixel_API_35",
596 platform: "android",
597 });
598 expect(session.deviceId).toBe("emulator-5554");
599 expect(requests.filter((url) => url.endsWith("/boot"))).toHaveLength(1);
600 const state = yield* service.state;
601 expect(state.devices.map((device) => device.id)).toEqual(["emulator-5554"]);
602 expect(state.bootingDevices).toEqual([]);
603 }),
604 );
605
606 it.effect("blocks only emulator video until ffmpeg is usable, then allows retry", () =>
607 Effect.gen(function* () {
608 const { service, requests, devices, encoderResult } = yield* fixture();
609 devices.push(
610 {
611 id: DeviceId.make("physical-android"),
612 name: "Pixel",
613 platform: "android",
614 version: "Android 15",
615 booted: true,
616 physical: true,
617 },
618 {
619 id: DeviceId.make("ios-simulator"),
620 name: "iPhone",
621 platform: "ios",
622 version: "iOS 18",
623 booted: true,
624 physical: false,
625 },
626 );
627 yield* Ref.set(encoderResult, { code: 127, stdout: "", stderr: "spawn ffmpeg ENOENT" });
628 const state = yield* service.configure({ enabled: true });
629 expect(state.devices.map((device) => device.id)).toEqual([
630 "ios-simulator",
631 "physical-android",
632 "Pixel_API_35",
633 ]);
634 const threadId = ThreadId.make("emulator-video-readiness");
635 const physical = yield* service.open({
636 threadId,
637 deviceId: "physical-android",
638 platform: "android",
639 });
640 const ios = yield* service.open({ threadId, deviceId: "ios-simulator", platform: "ios" });
641 expect(physical.deviceId).toBe("physical-android");
642 expect(ios.deviceId).toBe("ios-simulator");
643
644 const openEmulator = service.open({
645 threadId,
646 deviceId: "Pixel_API_35",
647 platform: "android",
648 });
649 const missing = yield* openEmulator.pipe(Effect.flip);
650 expect(missing.message).toMatch(/ffmpeg/i);
651 expect(missing.message).toMatch(/emulator/i);
652 expect(requests.filter((url) => url.endsWith("/boot"))).toEqual([]);
653 expect((yield* service.state).sessions).toEqual([physical, ios]);
654 expect((yield* service.state).bootingDevices ?? []).toEqual([]);
655
656 yield* Ref.set(encoderResult, { code: 1, stdout: "", stderr: "cannot execute ffmpeg" });
657 expect((yield* openEmulator.pipe(Effect.flip)).message).toMatch(/ffmpeg/i);
658 yield* Ref.set(encoderResult, {
659 code: 0,
660 stdout: " V....D libx264rgb libx264 H.264 / AVC RGB (codec h264)",
661 stderr: "",
662 });
663 expect((yield* openEmulator.pipe(Effect.flip)).message).toMatch(/libx264/i);
664 expect(requests.filter((url) => url.endsWith("/boot"))).toEqual([]);
665 expect((yield* service.state).sessions).toEqual([physical, ios]);
666
667 devices.push({
668 id: DeviceId.make("emulator-5556"),
669 name: "Already_booted",
670 platform: "android",
671 version: "Android 15",
672 booted: true,
673 physical: false,
674 });
675 expect(
676 (yield* service
677 .open({ threadId, deviceId: "emulator-5556", platform: "android" })
678 .pipe(Effect.flip)).message,
679 ).toMatch(/libx264/i);
680
681 yield* Ref.set(encoderResult, { code: 0, stdout: " V....D libx264", stderr: "" });
682 const emulator = yield* openEmulator;
683 expect(emulator.deviceId).toBe("emulator-5554");
684 expect(requests.filter((url) => url.endsWith("/boot"))).toHaveLength(1);
685 }),
686 );
687
688 it.effect("opens emulators on hosts that route their own streams without ffmpeg", () =>
689 Effect.gen(function* () {
690 const { service, requests, encoderResult } = yield* fixture(
691 Effect.void,
692 undefined,
693 false,
694 undefined,
695 false,
696 undefined,
697 { routesStreams: true },
698 );
699 yield* Ref.set(encoderResult, { code: 127, stdout: "", stderr: "host commands unavailable" });
700 yield* service.configure({ enabled: true });
701 const session = yield* service.open({
702 threadId: ThreadId.make("pool-emulator"),
703 deviceId: "Pixel_API_35",
704 platform: "android",
705 });
706 expect(session.deviceId).toBe("emulator-5554");
707 expect(requests.filter((url) => url.endsWith("/boot"))).toHaveLength(1);
708 }),
709 );
710
711 it.effect("installs agent support only after the separate agent permission", () =>
712 Effect.gen(function* () {
713 const { service, agentStarts, agentStops, settings } = yield* fixture();
714 yield* service.configure({ enabled: true });
715 expect(agentStarts).toEqual([]);
716 expect(yield* service.agentReadinessIfSupported()).toBeNull();
717
718 yield* service.configure({ agentAccessEnabled: true });
719 expect(agentStarts).toEqual(["start"]);
720 expect((yield* Ref.get(settings)).enableAgentDeviceAccess).toBe(true);
721 expect((yield* service.state).agentAccessEnabled).toBe(true);
722
723 yield* service.configure({ agentAccessEnabled: false, onboardingCompleted: true });
724 expect(agentStops).toEqual(["stop"]);
725 expect((yield* service.state).onboardingCompleted).toBe(true);
726 expect((yield* Ref.get(settings)).deviceOnboardingCompleted).toBe(true);
727 }),
728 );
729 });
730
731 const layerSecretResolver = Layer.succeed(SecretResolver.SecretResolver, {
732 label: (provider) => Effect.succeed(provider),
733 read: (references) => Effect.succeed(references.map(() => undefined)),
734 invalidate: () => Effect.void,
735 });
736
737 const WINDOWS_HOST_GUIDANCE = new SshDeviceHost.SshWindowsHostError({ cause: null }).message;
738
739 it.effect.each([
740 {
741 name: "Windows exit 1",
742 exitCode: 1,
743 stderr: "private SSH diagnostics",
744 reason: WINDOWS_HOST_GUIDANCE,
745 },
746 {
747 name: "Windows exit 9009",
748 exitCode: 9009,
749 stderr: "private SSH diagnostics",
750 reason: WINDOWS_HOST_GUIDANCE,
751 },
752 {
753 name: "untrusted host key",
754 exitCode: 255,
755 stderr: "Host key verification failed.\r\n",
756 reason:
757 "SSH encountered an untrusted host key while connecting to probe.test from the machine running this T3 Code server. Connect once with ssh from there to identify the host and verify its key before accepting it.",
758 },
759 {
760 name: "unrecognized SSH failure",
761 exitCode: 255,
762 stderr: "private SSH diagnostics",
763 reason: "Could not connect to this host over SSH.",
764 },
765 ])("Test connection preserves $name guidance across the wire", ({ exitCode, stderr, reason }) =>
766 Effect.gen(function* () {
767 const { host } = yield* fixture();
768 const service = yield* DeviceService.make.pipe(
769 Effect.provideService(DeviceHost.DeviceHost, host),
770 Effect.provideService(ProcessRunner.ProcessRunner, {
771 run: () => Effect.die("Testing SSH does not install local tools"),
772 }),
773 Effect.provideService(
774 HttpClient.HttpClient,
775 HttpClient.make(() => Effect.die("Testing SSH makes no hub requests")),
776 ),
777 Effect.provideService(
778 ChildProcessSpawner.ChildProcessSpawner,
779 ChildProcessSpawner.make((command) => {
780 if (command._tag !== "StandardCommand") return Effect.die("Unexpected command");
781 const config = command.args.includes("-G");
782 const windows = command.args.includes("echo %OS% $env:OS");
783 return Effect.succeed(
784 ChildProcessSpawner.makeHandle({
785 pid: ChildProcessSpawner.ProcessId(123),
786 stdout: Stream.make(
787 new TextEncoder().encode(
788 config ? "hostname 192.0.2.1\nport 22\n" : windows ? "Windows_NT\r\n" : "",
789 ),
790 ),
791 stderr: Stream.make(new TextEncoder().encode(stderr)),
792 all: Stream.empty,
793 exitCode: Effect.succeed(
794 ChildProcessSpawner.ExitCode(config || windows ? 0 : exitCode),
795 ),
796 isRunning: Effect.succeed(false),
797 kill: () => Effect.void,
798 stdin: Sink.drain,
799 getInputFd: () => Sink.drain,
800 getOutputFd: () => Stream.empty,
801 unref: Effect.succeed(Effect.void),
802 }),
803 );
804 }),
805 ),
806 );
807 const error = yield* service
808 .testHost({
809 kind: "ssh",
810 id: "probe",
811 label: "Probe test",
812 target: "probe.test",
813 port: 2222,
814 })
815 .pipe(Effect.flip);
816 expect(error).toMatchObject({
817 _tag: "DeviceHostUnavailableError",
818 hostId: "probe",
819 hostLabel: "Probe test",
820 reason,
821 });
822 const codec = Schema.fromJsonString(DeviceError);
823 const decoded = yield* Schema.decodeEffect(codec)(yield* Schema.encodeEffect(codec)(error));
824 expect(decoded.message).toBe(`Probe test is unavailable: ${reason}`);
825 expect(decoded.message).not.toContain("private SSH diagnostics");
826 }).pipe(
827 Effect.provide(
828 Layer.mergeAll(
829 ServerSettings.layerTest(),
830 layerSecretResolver,
831 ServerConfig.layerTest(process.cwd(), { prefix: "t3-device-probe-" }),
832 NodeCrypto.layer,
833 NetService.layer,
834 ).pipe(Layer.provideMerge(NodeServices.layer)),
835 ),
836 ),
837 );
838
839 it.effect("publishes boot progress and does not restore sessions after support is disabled", () =>
840 Effect.gen(function* () {
841 const started = yield* Deferred.make<void>();
842 const finish = yield* Deferred.make<void>();
843 const { service } = yield* fixture(
844 Deferred.succeed(started, undefined).pipe(Effect.andThen(Deferred.await(finish))),
845 );
846 yield* service.configure({ enabled: true });
847 const opening = yield* service
848 .open({ threadId: ThreadId.make("thread-1"), deviceId: "Pixel_API_35", platform: "android" })
849 .pipe(Effect.result, Effect.forkChild);
850 yield* Deferred.await(started);
851 expect((yield* service.state).bootingDevices?.map((device) => device.name)).toEqual([
852 "Pixel_API_35",
853 ]);
854 yield* service.configure({ enabled: false });
855 yield* Deferred.succeed(finish, undefined);
856 expect((yield* Fiber.join(opening))._tag).toBe("Failure");
857 const state = yield* service.state;
858 expect(state.hostStatus).toBe("disabled");
859 expect(state.devices).toEqual([]);
860 expect(state.sessions).toEqual([]);
861 expect(state.bootingDevices).toEqual([]);
862 }),
863 );
864
865 it.effect.each([
866 { case: "drops it on a host that ends devices itself", endsDevices: true, kept: 0 },
867 {
868 case: "keeps it on a host that can miss a device for one listing",
869 endsDevices: false,
870 kept: 1,
871 },
872 ])("when a host stops listing a session's device, $case", ({ endsDevices, kept }) =>
873 Effect.gen(function* () {
874 const { service, endDevice } = yield* fixture(
875 Effect.void,
876 undefined,
877 false,
878 undefined,
879 false,
880 undefined,
881 { endsDevices },
882 );
883 yield* service.configure({ enabled: true });
884 const threadId = ThreadId.make("ended-by-host");
885 yield* service.open({ threadId, deviceId: "Pixel_API_35", platform: "android" });
886 expect((yield* service.state).sessions.map((session) => session.deviceId)).toEqual([
887 "emulator-5554",
888 ]);
889 endDevice();
890 yield* service.list;
891 expect((yield* service.state).sessions).toHaveLength(kept);
892 }),
893 );
894
895 describe("device discovery after server restart", () => {
896 it.effect("captures an explicit device before any client lists devices", () =>
897 Effect.gen(function* () {
898 const { service, settings, requests } = yield* fixture();
899 yield* Ref.update(settings, (current) => ({ ...current, enableDeviceSupport: true }));
900 expect((yield* service.state).devices).toEqual([]);
901 const capture = yield* service.screenshot({ deviceId: DeviceId.make("Pixel_API_35") });
902 expect(capture.device.id).toBe("Pixel_API_35");
903 expect(capture.png).toEqual(minimalPng);
904 expect(requests.some((url) => url.endsWith("/api/devices"))).toBe(true);
905 }),
906 );
907 });
908
909 describe("device screenshots", () => {
910 it.effect("drops text that adb prints around the PNG", () =>
911 Effect.gen(function* () {
912 const { service, settings, screenshotBody } = yield* fixture();
913 yield* Ref.update(settings, (current) => ({ ...current, enableDeviceSupport: true }));
914 const warning = new TextEncoder().encode("[Warning] Multiple displays were found\n");
915 yield* Ref.set(screenshotBody, Uint8Array.from([...warning, ...minimalPng, 10]));
916 const capture = yield* service.screenshot({ deviceId: DeviceId.make("Pixel_API_35") });
917 expect(capture.png).toEqual(minimalPng);
918 }),
919 );
920
921 it.effect("fails instead of returning bytes that hold no complete PNG", () =>
922 Effect.gen(function* () {
923 const { service, settings, screenshotBody } = yield* fixture();
924 yield* Ref.update(settings, (current) => ({ ...current, enableDeviceSupport: true }));
925 yield* Ref.set(screenshotBody, minimalPng.subarray(0, 30));
926 const error = yield* Effect.flip(
927 service.screenshot({ deviceId: DeviceId.make("Pixel_API_35") }),
928 );
929 expect(error).toMatchObject({ _tag: "DeviceOperationError", reason: "hub_rejected" });
930 }),
931 );
932 });
933
934 const missingPlistMessage =
935 "[apple-utils] Failed to read CoreSimulator plist at /Users/test/Library/Developer/CoreSimulator/Devices/deleted-simulator/device.plist:";
936
937 it.effect("keeps other discovery warnings and clears them when only a deleted plist remains", () =>
938 Effect.gen(function* () {
939 const { service, discoveryErrors } = yield* fixture();
940 const missing = {
941 message: missingPlistMessage,
942 error: "Error: ENOENT: no such file or directory",
943 };
944 yield* Ref.set(discoveryErrors, [missing, { message: "Android discovery failed." }]);
945 const initial = yield* service.configure({ enabled: true });
946 expect(initial.hostStatusDetail).toBe("Android discovery failed.");
947 yield* Ref.set(discoveryErrors, [missing]);
948 const refreshed = yield* service.list;
949 expect(refreshed.hostStatusDetail).toBeUndefined();
950 expect(refreshed.hostStatuses.local?.detail).toBeUndefined();
951 }),
952 );
953
954 it.effect("hides Android discovery failures when the host has no Android SDK", () =>
955 Effect.gen(function* () {
956 const { service, discoveryErrors, androidAvailable } = yield* fixture();
957 const avdmanagerFailure = { message: "[android-utils] Failed to run `avdmanager list avd`:" };
958 yield* Ref.set(discoveryErrors, [avdmanagerFailure, { message: "iOS discovery failed." }]);
959 yield* Ref.set(androidAvailable, false);
960 const withoutSdk = yield* service.configure({ enabled: true });
961 expect(withoutSdk.hostStatusDetail).toBe("iOS discovery failed.");
962 yield* Ref.set(androidAvailable, true);
963 const withSdk = yield* service.list;
964 expect(withSdk.hostStatusDetail).toBe(`${avdmanagerFailure.message}\niOS discovery failed.`);
965 }),
966 );
967
968 // The hub reports `error` as a util.inspect of Node's exec error.
969 const simctlMessage = "[apple-utils] Failed to run `xcrun simctl list devices --json`:";
970 const simctlCause =
971 "An error was encountered processing the command (domain=NSPOSIXErrorDomain, code=60): Unable to connect to CoreSimulatorService [xcrun shim fail mode]";
972 const simctlError = `Error: Command failed: xcrun simctl list devices --json
973 ${simctlCause}
974
975 at genericNodeError (node:internal/errors:986:15)
976 at wrappedFn (node:internal/errors:540:14)
977 at ChildProcess.exithandler (node:child_process:417:12)
978 at ChildProcess._handle.onexit (node:internal/child_process:335:5) {
979 code: 1,
980 killed: false,
981 signal: null,
982 cmd: 'xcrun simctl list devices --json',
983 stdout: '',
984 stderr: '${simctlCause}\\n'
985 }`;
986 const avdmanager = "/Users/test/Library/Android/sdk/cmdline-tools/latest/bin/avdmanager";
987 const avdmanagerError = `Error: spawn ${avdmanager} ENOENT
988 at ChildProcess._handle.onexit (node:internal/child_process:316:19)
989 at onErrorNT (node:internal/child_process:524:16) {
990 errno: -2,
991 code: 'ENOENT',
992 syscall: 'spawn ${avdmanager}',
993 path: '${avdmanager}',
994 spawnargs: [ 'list', 'avd' ],
995 cmd: '${avdmanager} list avd',
996 stdout: '',
997 stderr: ''
998 }`;
999
1000 it.effect("keeps the cause from the hub's error in discovery warnings, without the stack", () =>
1001 Effect.gen(function* () {
1002 const { service, discoveryErrors } = yield* fixture();
1003 yield* Ref.set(discoveryErrors, [
1004 { message: simctlMessage, error: simctlError },
1005 { message: "[android-utils] Failed to run `avdmanager list avd`:", error: avdmanagerError },
1006 ]);
1007 const state = yield* service.configure({ enabled: true });
1008 expect(state.hostStatusDetail).toBe(
1009 [
1010 `${simctlMessage} Error: Command failed: xcrun simctl list devices --json ${simctlCause}`,
1011 `[android-utils] Failed to run \`avdmanager list avd\`: Error: spawn ${avdmanager} ENOENT`,
1012 ].join("\n"),
1013 );
1014 expect(state.hostStatusDetail).not.toContain(" at ");
1015 expect(state.hostStatusDetail).not.toContain("stderr:");
1016 }),
1017 );
1018
1019 it.effect(
1020 "keeps the last simulators while simctl cannot list them, and drops them once it can",
1021 () =>
1022 Effect.gen(function* () {
1023 const { service, devices, discoveryErrors } = yield* fixture();
1024 const simulator = {
1025 id: DeviceId.make("iphone"),
1026 name: "iPhone",
1027 platform: "ios",
1028 version: "iOS 26",
1029 booted: true,
1030 physical: false,
1031 } as const;
1032 devices.push(simulator, { ...simulator, id: DeviceId.make("pixel"), platform: "android" });
1033 yield* service.configure({ enabled: true, agentAccessEnabled: true });
1034 yield* service.agentReadinessIfSupported();
1035 devices.length = 0;
1036 yield* Ref.set(discoveryErrors, [{ message: simctlMessage }]);
1037 const failed = yield* service.list;
1038 expect(failed.devices.map((device) => device.id)).toEqual(["iphone", "Pixel_API_35"]);
1039 expect(failed.hostStatuses.local).toEqual({
1040 status: "ready",
1041 detail: simctlMessage,
1042 incompletePlatforms: ["ios"],
1043 });
1044 yield* service.agentReadinessIfSupported();
1045 expect((yield* service.state).hostStatuses.local).toEqual(failed.hostStatuses.local);
1046 yield* Ref.set(discoveryErrors, []);
1047 const recovered = yield* service.list;
1048 expect(recovered.devices.map((device) => device.id)).toEqual(["Pixel_API_35"]);
1049 expect(recovered.hostStatuses.local).toEqual({ status: "ready" });
1050 }),
1051 );
1052
1053 it.effect.each([
1054 {
1055 ios: true,
1056 android: true,
1057 incompletePlatforms: ["ios", "android"],
1058 kept: ["iphone", "Pixel_API_35"],
1059 },
1060 { ios: true, android: false, incompletePlatforms: ["ios"], kept: ["iphone"] },
1061 { ios: false, android: true, incompletePlatforms: ["android"], kept: ["Pixel_API_35"] },
1062 ] as const)(
1063 "keeps the devices of listable platforms when the hub does not answer within 40 seconds (iOS: $ios, Android SDK: $android)",
1064 ({ ios, android, incompletePlatforms, kept }) =>
1065 Effect.gen(function* () {
1066 const { service, devices, listing, androidAvailable, iosAvailable } = yield* fixture();
1067 yield* Ref.set(androidAvailable, android);
1068 yield* Ref.set(iosAvailable, ios);
1069 devices.push({
1070 id: DeviceId.make("iphone"),
1071 name: "iPhone",
1072 platform: "ios",
1073 version: "iOS 26",
1074 booted: true,
1075 physical: false,
1076 });
1077 yield* service.configure({ enabled: true });
1078 listing.hangs = true;
1079 const listed = yield* service.list.pipe(Effect.forkScoped);
1080 yield* Deferred.await(listing.requested);
1081 yield* TestClock.adjust("40 seconds");
1082 const timedOut = yield* Fiber.join(listed);
1083 expect(timedOut.devices.map((device) => device.id)).toEqual(kept);
1084 expect(timedOut.hostStatuses.local).toEqual({
1085 status: "ready",
1086 detail: "The device hub did not answer within 40 seconds.",
1087 incompletePlatforms,
1088 });
1089 }),
1090 );
1091
1092 it.effect("does not open a retained pre-boot entry when the post-boot listing is incomplete", () =>
1093 Effect.gen(function* () {
1094 const afterBoot = { run: Effect.void as Effect.Effect<void> };
1095 const android = yield* fixture(Effect.suspend(() => afterBoot.run));
1096 afterBoot.run = Effect.sync(() => {
1097 android.listing.hangs = true;
1098 });
1099 yield* android.service.configure({ enabled: true });
1100 const opening = yield* android.service
1101 .open({
1102 threadId: ThreadId.make("boot-timeout"),
1103 deviceId: "Pixel_API_35",
1104 platform: "android",
1105 })
1106 .pipe(Effect.flip, Effect.forkScoped);
1107 yield* Deferred.await(android.listing.requested);
1108 yield* TestClock.adjust("40 seconds");
1109 expect((yield* Fiber.join(opening))._tag).toBe("DeviceNotFoundError");
1110 expect((yield* android.service.state).sessions).toEqual([]);
1111 }),
1112 );
1113
1114 it.effect.each([
1115 {
1116 diagnostic: "Insufficient disk space at /private/user/path",
1117 reason: "disk_space",
1118 message: "not enough free disk space",
1119 },
1120 {
1121 diagnostic: "Timed out spawning /private/user/command",
1122 reason: "timeout",
1123 message: "did not become ready in time",
1124 },
1125 {
1126 diagnostic:
1127 "The emulator process exited with code 1.\nTry manually: emulator -avd Pixel_API_35",
1128 reason: "launch_failed",
1129 message: "could not start",
1130 },
1131 ] as const)("normalizes boot failure: $reason", ({ diagnostic, message }) =>
1132 Effect.gen(function* () {
1133 const { service } = yield* fixture(Effect.void, diagnostic);
1134 yield* service.configure({ enabled: true });
1135 const error = yield* service
1136 .open({
1137 threadId: ThreadId.make("boot-failure"),
1138 deviceId: "Pixel_API_35",
1139 platform: "android",
1140 })
1141 .pipe(Effect.flip);
1142 expect(error._tag).toBe("DeviceBootError");
1143 expect(error.message).toContain(message);
1144 expect(error.message).toContain(diagnostic);
1145 expect((yield* service.state).bootingDevices).toEqual([]);
1146 }),
1147 );
1148
1149 // regression: #22012 report Android emulator boot failures
1150 it.effect("includes nested hub boot diagnostics and bounds them to 2,000 characters", () =>
1151 Effect.gen(function* () {
1152 const diagnostic = "Error: emulator binary missing\n" + "diagnostic output\n".repeat(200);
1153 const { service } = yield* fixture(Effect.void, {
1154 error: "Failed to spawn emulator",
1155 errors: [{ message: "Failed to launch emulator binary", error: diagnostic }],
1156 });
1157 yield* service.configure({ enabled: true });
1158 const error = yield* service
1159 .open({
1160 threadId: ThreadId.make("nested-boot-failure"),
1161 deviceId: "Pixel_API_35",
1162 platform: "android",
1163 })
1164 .pipe(Effect.flip);
1165 expect(error._tag).toBe("DeviceBootError");
1166 if (error._tag !== "DeviceBootError") return;
1167 const expected = `Failed to spawn emulator\n\nFailed to launch emulator binary\n\n${diagnostic}`;
1168 expect(error.diagnostics).toBe(`${expected.slice(0, 1_999)}…`);
1169 expect(error.diagnostics).toHaveLength(2_000);
1170 expect(error.message).toContain(error.diagnostics);
1171 const roundTrip = decodeBootError(encodeBootError(error));
1172 expect(roundTrip.message).toBe(error.message);
1173 expect((yield* service.state).bootingDevices).toEqual([]);
1174 }),
1175 );
1176
1177 it.effect("keeps shutdown successful when subsequent discovery fails", () =>
1178 Effect.gen(function* () {
1179 const { service } = yield* fixture(Effect.void, undefined, true);
1180 yield* service.configure({ enabled: true });
1181 const threadId = ThreadId.make("shutdown-refresh");
1182 const session = yield* service.open({
1183 threadId,
1184 deviceId: "Pixel_API_35",
1185 platform: "android",
1186 });
1187 yield* service.close({ threadId, deviceId: session.deviceId, shutdown: true });
1188 const state = yield* service.state;
1189 expect(state.sessions).toEqual([]);
1190 expect(state.devices.find((device) => device.id === session.deviceId)?.booted).toBe(false);
1191 }),
1192 );
1193
1194 it.effect.each(["shutdown", "close"] as const)(
1195 "%s releases iOS capture and the session's launcher so reopening uses a fresh session",
1196 (operation) =>
1197 Effect.gen(function* () {
1198 const deviceId = DeviceId.make("11111111-1111-1111-1111-111111111111");
1199 const threadId = ThreadId.make("capture-recovery");
1200 let booted = true;
1201 let capture: number | null = null;
1202 let generation = 0;
1203 const http = HttpClient.make((request) =>
1204 Effect.sync(() => {
1205 const path = new URL(request.url).pathname;
1206 if (path === "/api/devices") {
1207 return HttpClientResponse.fromWeb(
1208 request,
1209 Response.json({
1210 emulators: [],
1211 simulators: [
1212 {
1213 id: deviceId,
1214 name: "iPhone",
1215 platform: "ios",
1216 version: "26",
1217 physical: false,
1218 booted,
1219 },
1220 ],
1221 }),
1222 );
1223 }
1224 if (path === "/vendor/serve-sim/grid/api/start") capture ??= ++generation;
1225 else if (path === "/vendor/serve-sim/grid/api/shutdown") {
1226 if (request.body._tag !== "Uint8Array") throw new Error("Missing shutdown body");
1227 expect(decodeJson(new TextDecoder().decode(request.body.body))).toEqual({
1228 udid: deviceId,
1229 });
1230 capture = null;
1231 booted = false;
1232 } else if (path === "/api/devices/shutdown") {
1233 // This route powers off without releasing serve-sim's cached capture.
1234 booted = false;
1235 } else if (path === "/api/devices/boot") booted = true;
1236 else throw new Error(`Unexpected hub path: ${path}`);
1237 return HttpClientResponse.fromWeb(request, Response.json({ ok: true, id: deviceId }));
1238 }),
1239 );
1240 const run = () => Effect.succeed({ code: 0, stdout: "", stderr: "" });
1241 const ready: DeviceHost.DeviceHostReady = {
1242 nodePath: process.execPath,
1243 hub: { origin: "http://device.test" },
1244 devices: makeDeviceHubOperations({
1245 hostId: LOCAL_DEVICE_HOST_ID,
1246 origin: "http://device.test",
1247 http,
1248 run,
1249 platformAvailable: () => Effect.succeed(true),
1250 }),
1251 helpers: { serveSimAxSettings: null, serveSimCli: null },
1252 run,
1253 };
1254 const host: DeviceHost.DeviceHost["Service"] = {
1255 id: LOCAL_DEVICE_HOST_ID,
1256 label: "This machine",
1257 summary: Effect.succeed({
1258 id: LOCAL_DEVICE_HOST_ID,
1259 kind: "local",
1260 label: "Simulator host",
1261 platforms: [{ platform: "ios", available: true }],
1262 hubInstalled: true,
1263 agentDeviceInstalled: false,
1264 }),
1265 platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
1266 ensureReady: () => Effect.succeed(ready),
1267 ensureAgentReady: () => Effect.die("Agent access is not used in this test"),
1268 current: Effect.succeed(ready),
1269 stopAgent: Effect.void,
1270 stop: Effect.void,
1271 };
1272 const launchers = new Set(["t3-from-a-previous-run"]);
1273 const released: Array<[string, boolean]> = [];
1274 // Whether the device was still on when each session was released.
1275 const releasedWhileBooted: Array<boolean> = [];
1276 let pauseBind: { entered: Deferred.Deferred<void>; proceed: Deferred.Deferred<void> } | null =
1277 null;
1278 const service = yield* DeviceService.makeWithHosts(
1279 new Map([[host.id, host]]),
1280 undefined,
1281 undefined,
1282 undefined,
1283 {
1284 bind: ({ session }) =>
1285 Effect.gen(function* () {
1286 if (pauseBind) {
1287 yield* Deferred.succeed(pauseBind.entered, undefined);
1288 yield* Deferred.await(pauseBind.proceed);
1289 }
1290 launchers.add(session);
1291 return session;
1292 }),
1293 prune: (live) =>
1294 Effect.sync(() => {
1295 for (const session of launchers) if (!live.has(session)) launchers.delete(session);
1296 }),
1297 // Records whether the launcher still existed, since its close runs through it.
1298 release: (launcher) =>
1299 Effect.sync(() => {
1300 released.push([launcher, launchers.has(launcher)]);
1301 releasedWhileBooted.push(booted);
1302 }),
1303 },
1304 ).pipe(Effect.provide(NodeCrypto.layer));
1305 expect(launchers).toEqual(new Set());
1306 const input = { threadId, deviceId, platform: "ios" as const };
1307 const other = { ...input, threadId: ThreadId.make("capture-recovery-other") };
1308 const target = (thread: ThreadId) => ({
1309 threadId: thread,
1310 hostId: LOCAL_DEVICE_HOST_ID,
1311 deviceId,
1312 });
1313 const bind = Effect.fnUntraced(function* (open: typeof input) {
1314 yield* service.open(open);
1315 yield* service.agentLauncher({ ...target(open.threadId), targetArgs: [] });
1316 return yield* agentDeviceSession(open.threadId, LOCAL_DEVICE_HOST_ID, deviceId);
1317 }, Effect.provide(NodeCrypto.layer));
1318 const session = yield* bind(input);
1319 yield* bind(other);
1320 expect(capture).toBe(1);
1321 expect(launchers.size).toBe(2);
1322 if (operation === "shutdown") yield* service.shutdown(input);
1323 else yield* service.close({ threadId, deviceId, shutdown: true });
1324 expect(capture).toBeNull();
1325 expect((yield* service.state).sessions).toEqual([]);
1326 expect(launchers).toEqual(new Set());
1327 // Retiring a session ends its agent-device session too, which releases the device claim.
1328 // Powering the device off retires the other thread's session on it as well.
1329 const firstOther = yield* agentDeviceSession(
1330 other.threadId,
1331 LOCAL_DEVICE_HOST_ID,
1332 deviceId,
1333 ).pipe(Effect.provide(NodeCrypto.layer));
1334 expect(new Set(released.map(([launcher]) => launcher))).toEqual(
1335 new Set([session, firstOther]),
1336 );
1337 expect(released.every(([, existed]) => existed)).toBe(true);
1338 // agent-device can close the session's app only while the device is on.
1339 expect(releasedWhileBooted).toEqual([true, true]);
1340 // A device_open that was still preparing when the close landed.
1341 expect(yield* service.agentLauncher({ ...target(threadId), targetArgs: [] })).toEqual(
1342 Option.none(),
1343 );
1344 expect(launchers).toEqual(new Set());
1345 expect(yield* bind(input)).toBe(session);
1346 // Reopening the same device ends nothing.
1347 expect(released).toHaveLength(2);
1348 expect(capture).toBe(2);
1349 expect((yield* service.state).sessions).toHaveLength(1);
1350 const otherSession = yield* bind(other);
1351 yield* service.close({ threadId: other.threadId });
1352 expect(launchers).toEqual(new Set([session]));
1353 expect(released.slice(2)).toEqual([[otherSession, true]]);
1354 expect(otherSession).not.toBe(session);
1355 // A caller interrupted after retirement committed, while a bind holds the launcher lock.
1356 pauseBind = { entered: yield* Deferred.make<void>(), proceed: yield* Deferred.make<void>() };
1357 const binding = yield* Effect.forkChild(
1358 service.agentLauncher({ ...target(threadId), targetArgs: [] }),
1359 );
1360 yield* Deferred.await(pauseBind.entered);
1361 const updates = yield* service.subscribe;
1362 const retiring = yield* Effect.forkChild(
1363 operation === "shutdown" ? service.shutdown(input) : service.close({ threadId }),
1364 );
1365 expect((yield* PubSub.take(updates)).sessions).toEqual([]);
1366 yield* service.refreshHosts;
1367 expect((yield* service.state).sessions).toEqual([]);
1368 yield* Effect.sync(() => retiring.interruptUnsafe());
1369 yield* Deferred.succeed(pauseBind.proceed, undefined);
1370 yield* Fiber.join(binding);
1371 yield* Fiber.await(retiring);
1372 expect(launchers).toEqual(new Set());
1373 }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true }))),
1374 );
1375
1376 it.effect("leaves a session its host leases to every thread open when one thread closes", () =>
1377 Effect.gen(function* () {
1378 const deviceId = DeviceId.make("33333333-3333-3333-3333-333333333333");
1379 const http = HttpClient.make((request) =>
1380 Effect.sync(() =>
1381 new URL(request.url).pathname === "/api/devices"
1382 ? HttpClientResponse.fromWeb(
1383 request,
1384 Response.json({
1385 emulators: [],
1386 simulators: [
1387 {
1388 id: deviceId,
1389 name: "iPhone",
1390 platform: "ios",
1391 version: "26",
1392 physical: false,
1393 booted: true,
1394 },
1395 ],
1396 }),
1397 )
1398 : HttpClientResponse.fromWeb(request, Response.json({ ok: true, id: deviceId })),
1399 ),
1400 );
1401 const run = () => Effect.succeed({ code: 0, stdout: "", stderr: "" });
1402 const ready: DeviceHost.DeviceHostAgentReady = {
1403 nodePath: process.execPath,
1404 hub: { origin: "http://device.test" },
1405 devices: {
1406 ...makeDeviceHubOperations({
1407 hostId: LOCAL_DEVICE_HOST_ID,
1408 origin: "http://device.test",
1409 http,
1410 run,
1411 platformAvailable: () => Effect.succeed(true),
1412 }),
1413 agentEndpoint: () =>
1414 Effect.succeed({
1415 baseUrl: "http://agent.test",
1416 token: "agent-token",
1417 agentDeviceId: null,
1418 session: "lease-session",
1419 }),
1420 },
1421 helpers: { serveSimAxSettings: null, serveSimCli: null },
1422 run,
1423 agentDevice: null,
1424 };
1425 const host: DeviceHost.DeviceHost["Service"] = {
1426 id: LOCAL_DEVICE_HOST_ID,
1427 label: "Pool",
1428 summary: Effect.succeed({
1429 id: LOCAL_DEVICE_HOST_ID,
1430 kind: "local",
1431 label: "Pool",
1432 platforms: [{ platform: "ios", available: true }],
1433 hubInstalled: true,
1434 agentDeviceInstalled: true,
1435 }),
1436 platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
1437 ensureReady: () => Effect.succeed(ready),
1438 ensureAgentReady: () => Effect.succeed(ready),
1439 current: Effect.succeed(ready),
1440 stopAgent: Effect.void,
1441 stop: Effect.void,
1442 };
1443 const released: string[] = [];
1444 const service = yield* DeviceService.makeWithHosts(
1445 new Map([[host.id, host]]),
1446 undefined,
1447 () => Effect.succeed("agent-device.json"),
1448 undefined,
1449 {
1450 bind: ({ session }) => Effect.succeed(session),
1451 prune: () => Effect.void,
1452 release: (launcher) => Effect.sync(() => void released.push(launcher)),
1453 },
1454 ).pipe(Effect.provide(NodeCrypto.layer));
1455 const threads = [ThreadId.make("pool-a"), ThreadId.make("pool-b")];
1456 for (const threadId of threads) {
1457 yield* service.open({ threadId, deviceId, platform: "ios" });
1458 const target = { threadId, hostId: LOCAL_DEVICE_HOST_ID, deviceId };
1459 const agent = yield* service.agentTarget(target);
1460 expect(agent.session).toBe("lease-session");
1461 yield* service.agentLauncher({ ...target, targetArgs: agent.args });
1462 }
1463 yield* service.close({ threadId: threads[0]! });
1464 expect(released).toEqual([]);
1465 }).pipe(
1466 Effect.provide(
1467 ServerSettings.layerTest({ enableDeviceSupport: true, enableAgentDeviceAccess: true }),
1468 ),
1469 ),
1470 );
1471
1472 it.effect.each([
1473 { hubReports: "off", outcome: "succeeds" },
1474 { hubReports: "booted", outcome: "fails" },
1475 { hubReports: "missing", outcome: "fails" },
1476 ] as const)(
1477 "iOS shutdown $outcome when serve-sim rejects it and the hub reports the simulator $hubReports",
1478 ({ hubReports, outcome }) =>
1479 Effect.gen(function* () {
1480 const deviceId = DeviceId.make("22222222-2222-2222-2222-222222222222");
1481 const paths: string[] = [];
1482 let listed: "booted" | "off" | "missing" = "booted";
1483 const http = HttpClient.make((request) =>
1484 Effect.sync(() => {
1485 const path = new URL(request.url).pathname;
1486 paths.push(path);
1487 if (path === "/api/devices") {
1488 return HttpClientResponse.fromWeb(
1489 request,
1490 Response.json({
1491 emulators: [],
1492 simulators:
1493 listed === "missing"
1494 ? []
1495 : [
1496 {
1497 id: deviceId,
1498 name: "iPhone",
1499 platform: "ios",
1500 version: "26",
1501 physical: false,
1502 booted: listed === "booted",
1503 },
1504 ],
1505 errors: listed === "missing" ? [{ message: "simctl list failed" }] : [],
1506 }),
1507 );
1508 }
1509 if (path === "/vendor/serve-sim/grid/api/shutdown") {
1510 // serve-sim runs `simctl shutdown` bare and returns its failure as-is.
1511 listed = hubReports;
1512 return HttpClientResponse.fromWeb(
1513 request,
1514 Response.json(
1515 { ok: false, error: "Unable to shutdown device in current state: Shutdown" },
1516 { status: 500 },
1517 ),
1518 );
1519 }
1520 throw new Error(`Unexpected hub path: ${path}`);
1521 }),
1522 );
1523 const run = () => Effect.succeed({ code: 0, stdout: "", stderr: "" });
1524 const ready: DeviceHost.DeviceHostReady = {
1525 nodePath: process.execPath,
1526 hub: { origin: "http://device.test" },
1527 devices: makeDeviceHubOperations({
1528 hostId: LOCAL_DEVICE_HOST_ID,
1529 origin: "http://device.test",
1530 http,
1531 run,
1532 platformAvailable: () => Effect.succeed(true),
1533 }),
1534 helpers: { serveSimAxSettings: null, serveSimCli: null },
1535 run,
1536 };
1537 const host: DeviceHost.DeviceHost["Service"] = {
1538 id: LOCAL_DEVICE_HOST_ID,
1539 label: "This machine",
1540 summary: Effect.succeed({
1541 id: LOCAL_DEVICE_HOST_ID,
1542 kind: "local",
1543 label: "Simulator host",
1544 platforms: [{ platform: "ios", available: true }],
1545 hubInstalled: true,
1546 agentDeviceInstalled: false,
1547 }),
1548 platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
1549 ensureReady: () => Effect.succeed(ready),
1550 ensureAgentReady: () => Effect.die("Agent access is not used in this test"),
1551 current: Effect.succeed(ready),
1552 stopAgent: Effect.void,
1553 stop: Effect.void,
1554 };
1555 const service = yield* DeviceService.makeWithHosts(new Map([[host.id, host]])).pipe(
1556 Effect.provide(NodeCrypto.layer),
1557 );
1558 yield* service.list;
1559 const exit = yield* Effect.exit(service.shutdown({ deviceId, platform: "ios" }));
1560 expect(paths.filter((path) => path.endsWith("shutdown"))).toEqual([
1561 "/vendor/serve-sim/grid/api/shutdown",
1562 ]);
1563 if (outcome === "succeeds") {
1564 expect(Exit.isSuccess(exit)).toBe(true);
1565 expect(
1566 (yield* service.state).devices.find((device) => device.id === deviceId)?.booted,
1567 ).toBe(false);
1568 } else {
1569 expect(Exit.isFailure(exit)).toBe(true);
1570 expect(
1571 (yield* service.state).devices.find((device) => device.id === deviceId)?.booted,
1572 ).toBe(true);
1573 }
1574 }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true }))),
1575 );
1576
1577 it.effect.each([LOCAL_DEVICE_HOST_ID, "ssh-fixture"])(
1578 "retains hub inventory on %s when AVD enumeration fails and recovers on retry",
1579 (hostId) =>
1580 Effect.gen(function* () {
1581 let enumeration = { code: 1, stdout: "private stdout", stderr: "private stderr" };
1582 const run = () => Effect.sync(() => enumeration);
1583 const hubDevices = [
1584 { id: "iphone", name: "iPhone", platform: "ios", physical: false },
1585 { id: "phone", name: "Pixel", platform: "android", physical: true },
1586 { id: "emulator-5554", name: "Running_AVD", platform: "android", physical: false },
1587 ].map((device) => ({ ...device, booted: true, version: "test" }));
1588 const http = HttpClient.make((request) =>
1589 Effect.succeed(
1590 HttpClientResponse.fromWeb(
1591 request,
1592 Response.json({ simulators: hubDevices.slice(0, 1), emulators: hubDevices.slice(1) }),
1593 ),
1594 ),
1595 );
1596 const ready: DeviceHost.DeviceHostReady = {
1597 nodePath: process.execPath,
1598 hub: { origin: "http://device.test" },
1599 devices: makeDeviceHubOperations({
1600 hostId,
1601 origin: "http://device.test",
1602 http,
1603 run,
1604 platformAvailable: () => Effect.succeed(true),
1605 }),
1606 helpers: { serveSimAxSettings: null, serveSimCli: null },
1607 run,
1608 };
1609 const host: DeviceHost.DeviceHost["Service"] = {
1610 id: hostId,
1611 label: "Test device host",
1612 summary: Effect.succeed({
1613 id: hostId,
1614 kind: hostId === LOCAL_DEVICE_HOST_ID ? "local" : "ssh",
1615 label: "Test device host",
1616 platforms: [{ platform: "android", available: true }],
1617 hubInstalled: true,
1618 agentDeviceInstalled: false,
1619 }),
1620 platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
1621 ensureReady: () => Effect.succeed(ready),
1622 ensureAgentReady: () => Effect.die("Agent access is not used in this test"),
1623 current: Effect.succeed(ready),
1624 stop: Effect.void,
1625 stopAgent: Effect.void,
1626 };
1627 const service = yield* DeviceService.makeWithHosts(new Map([[hostId, host]])).pipe(
1628 Effect.provide(NodeCrypto.layer),
1629 Effect.provideService(HttpClient.HttpClient, http),
1630 );
1631
1632 const incomplete = yield* service.list;
1633 expect(incomplete.devices).toEqual(hubDevices.map((device) => ({ ...device, hostId })));
1634 expect(incomplete.hostStatuses[hostId]).toEqual({
1635 status: "ready",
1636 androidDiscoveryIncomplete: true,
1637 detail:
1638 "Could not list Android virtual devices (emulator -list-avds, exit code 1). Discovered devices remain available.",
1639 });
1640 if (hostId === LOCAL_DEVICE_HOST_ID) {
1641 expect(incomplete.hostStatusDetail).toBe(incomplete.hostStatuses[hostId]?.detail);
1642 }
1643
1644 enumeration = { code: 0, stdout: "Running_AVD\r\nStopped_AVD\nStopped_AVD\n", stderr: "" };
1645 const recovered = yield* service.retryHost(hostId);
1646 expect(recovered.devices).toEqual([
1647 ...hubDevices.map((device) => ({ ...device, hostId })),
1648 {
1649 hostId,
1650 id: "Stopped_AVD",
1651 name: "Stopped_AVD",
1652 platform: "android",
1653 version: "Android",
1654 booted: false,
1655 physical: false,
1656 },
1657 ]);
1658 expect(recovered.hostStatuses[hostId]).toEqual({ status: "ready" });
1659 if (hostId === LOCAL_DEVICE_HOST_ID) expect(recovered.hostStatusDetail).toBeUndefined();
1660 }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true }))),
1661 );
1662
1663 it.effect("retry keeps device and agent consent unchanged", () =>
1664 Effect.gen(function* () {
1665 const { service, starts, agentStarts } = yield* fixture();
1666 yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
1667 expect(starts).toEqual([]);
1668 expect(agentStarts).toEqual([]);
1669 yield* service.configure({ enabled: true });
1670 yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
1671 expect(agentStarts).toEqual([]);
1672 yield* service.configure({ agentAccessEnabled: true });
1673 const before = agentStarts.length;
1674 yield* service.retryHost(LOCAL_DEVICE_HOST_ID);
1675 expect(agentStarts.length).toBe(before + 1);
1676 }),
1677 );
1678
1679 it.effect("failed read-only discovery preserves lifecycle status and installed inventory", () =>
1680 Effect.gen(function* () {
1681 const { service, starts } = yield* fixture(Effect.void, undefined, false, undefined, true);
1682 const state = yield* service.inspect;
1683 expect(state.supportsToolInspection).toBe(true);
1684 expect(state.hostStatus).toBe("disabled");
1685 expect(state.hosts[0]?.hubInstalled).toBe(true);
1686 expect(state.hosts[0]?.toolInspectionError).toContain("Reconnect the host");
1687 expect(starts).toEqual([]);
1688 }),
1689 );
1690
1691 it.effect(
1692 "manual updates install only the selected tool without enabling access or starting helpers",
1693 () =>
1694 Effect.gen(function* () {
1695 const installed: string[] = [];
1696 const { service, starts, agentStarts, requests } = yield* fixture(
1697 Effect.void,
1698 undefined,
1699 false,
1700 undefined,
1701 false,
1702 (tool) =>
1703 Effect.sync(() => {
1704 installed.push(tool);
1705 }),
1706 );
1707 const before = yield* service.state;
1708 const state = yield* service.updateTool("agent");
1709 expect(installed).toEqual(["agent"]);
1710 expect(state.supportsToolUpdate).toBe(true);
1711 expect(state.hostStatus).toBe(before.hostStatus);
1712 expect(state.agentAccessEnabled).toBe(before.agentAccessEnabled);
1713 expect(state.revision).toBeGreaterThan(before.revision);
1714 expect(starts).toEqual([]);
1715 expect(agentStarts).toEqual([]);
1716 expect(requests).toEqual([]);
1717 yield* service.updateTool("hub");
1718 expect(installed).toEqual(["agent", "hub"]);
1719 }),
1720 );
1721
1722 it.effect("failed manual installation leaves lifecycle state unchanged and can be retried", () =>
1723 Effect.gen(function* () {
1724 let attempts = 0;
1725 const { service, starts, agentStarts } = yield* fixture(
1726 Effect.void,
1727 undefined,
1728 false,
1729 undefined,
1730 false,
1731 () =>
1732 Effect.suspend(() =>
1733 ++attempts === 1
1734 ? Effect.fail(
1735 new DeviceOperationError({
1736 operation: "update device tool",
1737 reason: "command_failed",
1738 cause: new Error("offline"),
1739 }),
1740 )
1741 : Effect.void,
1742 ),
1743 );
1744 const before = yield* service.state;
1745 const result = yield* service.updateTool("agent").pipe(Effect.result);
1746 expect(result._tag).toBe("Failure");
1747 expect(yield* service.state).toEqual(before);
1748 yield* service.updateTool("agent");
1749 expect(attempts).toBe(2);
1750 expect(starts).toEqual([]);
1751 expect(agentStarts).toEqual([]);
1752 }),
1753 );
1754
1755 it.effect("reconciles SSH host settings without publishing no-op changes", () =>
1756 Effect.gen(function* () {
1757 const fs = yield* FileSystem.FileSystem;
1758 const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-reconcile-" });
1759 const settings = yield* ServerSettings.ServerSettingsService;
1760 // Each change is acknowledged after reconciliation consumed it, so no-ops are observable.
1761 const changes = yield* Queue.unbounded<{ value: Settings; done: Deferred.Deferred<void> }>();
1762 const removedFiles: string[] = [];
1763 const localHost: DeviceHost.DeviceHost["Service"] = {
1764 id: LOCAL_DEVICE_HOST_ID,
1765 label: "This machine",
1766 summary: Effect.succeed({
1767 id: LOCAL_DEVICE_HOST_ID,
1768 label: "Local",
1769 kind: "local",
1770 platforms: [],
1771 hubInstalled: false,
1772 agentDeviceInstalled: false,
1773 }),
1774 platformAvailability: (platform) => Effect.succeed({ platform, available: false }),
1775 current: Effect.succeed(null),
1776 ensureReady: () => Effect.die("Unexpected device launch"),
1777 ensureAgentReady: () => Effect.die("Unexpected agent launch"),
1778 stop: Effect.void,
1779 stopAgent: Effect.void,
1780 };
1781 const service = yield* DeviceService.make.pipe(
1782 Effect.provideService(DeviceHost.DeviceHost, localHost),
1783 Effect.provideService(ServerSettings.ServerSettingsService, {
1784 ...settings,
1785 subscribeChanges: Effect.succeed(
1786 Stream.fromQueue(changes).pipe(
1787 Stream.flatMap(({ value, done }) =>
1788 Stream.make(value).pipe(
1789 Stream.concat(
1790 Stream.fromEffect(Deferred.succeed(done, undefined)).pipe(Stream.drain),
1791 ),
1792 ),
1793 ),
1794 ),
1795 ),
1796 }),
1797 Effect.provideService(
1798 FileSystem.FileSystem,
1799 FileSystem.makeNoop({
1800 remove: (file) => Effect.sync(() => void removedFiles.push(file)),
1801 }),
1802 ),
1803 Effect.provideService(ProcessRunner.ProcessRunner, {
1804 run: () => Effect.die("Unexpected helper launch"),
1805 }),
1806 Effect.provideService(
1807 HttpClient.HttpClient,
1808 HttpClient.make(() => Effect.die("Unexpected HTTP request")),
1809 ),
1810 Effect.provideService(
1811 ChildProcessSpawner.ChildProcessSpawner,
1812 ChildProcessSpawner.make(() =>
1813 Effect.succeed(
1814 ChildProcessSpawner.makeHandle({
1815 pid: ChildProcessSpawner.ProcessId(123),
1816 stdout: Stream.make(new TextEncoder().encode("hostname 192.0.2.1\nport 22\n")),
1817 stderr: Stream.empty,
1818 all: Stream.empty,
1819 exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
1820 isRunning: Effect.succeed(false),
1821 kill: () => Effect.void,
1822 stdin: Sink.drain,
1823 getInputFd: () => Sink.drain,
1824 getOutputFd: () => Stream.empty,
1825 unref: Effect.succeed(Effect.void),
1826 }),
1827 ),
1828 ),
1829 ),
1830 Effect.provide(Layer.mergeAll(ServerConfig.layerTest(baseDir, baseDir), NetService.layer)),
1831 );
1832 const update = Effect.fnUntraced(function* (deviceHosts: ReadonlyArray<SshDeviceHostConfig>) {
1833 const value = yield* settings.updateSettings({ deviceHosts: [...deviceHosts] });
1834 const done = yield* Deferred.make<void>();
1835 yield* Queue.offer(changes, { value, done });
1836 yield* Deferred.await(done);
1837 return yield* service.state;
1838 });
1839
1840 const initial = yield* service.state;
1841 expect(yield* update([])).toEqual(initial);
1842
1843 const host: SshDeviceHostConfig = {
1844 kind: "ssh",
1845 id: "remote",
1846 label: "Remote",
1847 target: "remote-fixture",
1848 };
1849 const added = yield* update([host]);
1850 expect(added.hosts.map((entry) => entry.id)).toEqual([LOCAL_DEVICE_HOST_ID, host.id]);
1851 expect(yield* update([{ ...host }])).toEqual(added);
1852
1853 yield* service.setHostStatus(host.id, { status: "failed", detail: "stale" });
1854 const removed = yield* update([]);
1855 expect(removed.hosts.map((entry) => entry.id)).toEqual([LOCAL_DEVICE_HOST_ID]);
1856 expect(removed.hostStatuses[host.id]).toBeUndefined();
1857 expect(removedFiles).toHaveLength(1);
1858 }).pipe(
1859 Effect.scoped,
1860 Effect.provide(
1861 Layer.mergeAll(
1862 ServerSettings.layerTest(),
1863 layerSecretResolver,
1864 NodeServices.layer,
1865 NodeCrypto.layer,
1866 ),
1867 ),
1868 ),
1869 );
1870
1871 it.effect.each(["exit", "missing"] as const)(
1872 "a failed tool update reports a safe %s failure",
1873 (failure) =>
1874 Effect.gen(function* () {
1875 const host: DeviceHost.DeviceHost["Service"] = {
1876 id: LOCAL_DEVICE_HOST_ID,
1877 label: "This machine",
1878 summary: Effect.succeed({
1879 id: LOCAL_DEVICE_HOST_ID,
1880 kind: "local",
1881 label: "Test server",
1882 platforms: [],
1883 hubInstalled: false,
1884 agentDeviceInstalled: false,
1885 }),
1886 platformAvailability: (platform) => Effect.succeed({ platform, available: false }),
1887 ensureReady: () => Effect.die("Updating a tool does not start the hub"),
1888 ensureAgentReady: () => Effect.die("Updating a tool does not start the agent"),
1889 current: Effect.succeed(null),
1890 stopAgent: Effect.void,
1891 stop: Effect.void,
1892 };
1893 const npmFailure = {
1894 code: ChildProcessSpawner.ExitCode(243),
1895 stdout: "",
1896 stderr: "npm error EACCES https://private:credential@registry.example.test/expo-device-hub",
1897 timedOut: false,
1898 stdoutTruncated: false,
1899 stderrTruncated: false,
1900 stdoutInvalidUtf8: false,
1901 stderrInvalidUtf8: false,
1902 };
1903 const service = yield* DeviceService.make.pipe(
1904 Effect.provideService(DeviceHost.DeviceHost, host),
1905 Effect.provideService(ProcessRunner.ProcessRunner, {
1906 run: ({ command, args }) =>
1907 failure === "exit"
1908 ? Effect.succeed(npmFailure)
1909 : Effect.fail(
1910 new ProcessRunner.ProcessSpawnError({
1911 command,
1912 argumentCount: args.length,
1913 cause: PlatformError.systemError({
1914 _tag: "NotFound",
1915 module: "ChildProcess",
1916 method: "spawn",
1917 description: "private diagnostic text",
1918 }),
1919 }),
1920 ),
1921 }),
1922 Effect.provideService(
1923 HttpClient.HttpClient,
1924 HttpClient.make(() => Effect.die("Updating a tool makes no hub requests")),
1925 ),
1926 );
1927
1928 const error = yield* service.updateTool("hub").pipe(Effect.flip);
1929 expect(error).toMatchObject({
1930 _tag: "DeviceOperationError",
1931 reason: failure === "exit" ? "command_failed" : "package_manager_missing",
1932 });
1933 expect(error.message).toBe(
1934 failure === "exit"
1935 ? "Device update device tool failed: The device command failed (exit code 243)."
1936 : "Device update device tool failed: Device support needs npm, which is not on the T3 server's PATH. Install npm (it comes with Node.js from nodejs.org), restart T3 Code, then retry.",
1937 );
1938 }).pipe(
1939 Effect.provide(
1940 Layer.mergeAll(
1941 ServerSettings.layerTest({ enableDeviceSupport: true }),
1942 layerSecretResolver,
1943 ServerConfig.layerTest(process.cwd(), { prefix: "t3-device-update-" }),
1944 NodeCrypto.layer,
1945 NetService.layer,
1946 ).pipe(Layer.provideMerge(NodeServices.layer)),
1947 ),
1948 ),
1949 );
1950
1951 describe("agent session release on close", () => {
1952 const openClaim = (
1953 service: DeviceService.DeviceService["Service"],
1954 threadId: ThreadId,
1955 deviceId = "Pixel_API_35",
1956 ) => service.open({ threadId, deviceId, platform: "android" });
1957
1958 it.effect("releases only the caller's session, keeps the device booted, and is idempotent", () =>
1959 Effect.gen(function* () {
1960 const { service, closedSessions, requests } = yield* fixture();
1961 yield* service.configure({ enabled: true, agentAccessEnabled: true });
1962 const threadId = ThreadId.make("closing");
1963 const other = ThreadId.make("other");
1964 const session = yield* openClaim(service, threadId);
1965 yield* openClaim(service, other, session.deviceId);
1966 yield* service.close({ threadId, deviceId: session.deviceId });
1967 yield* service.close({ threadId, deviceId: session.deviceId });
1968 const name = yield* agentDeviceSession(threadId, session.hostId, session.deviceId).pipe(
1969 Effect.provide(NodeCrypto.layer),
1970 );
1971 expect(closedSessions).toEqual([
1972 {
1973 jsonrpc: "2.0",
1974 id: name,
1975 method: "agent_device.command",
1976 params: { command: "close", session: name, positionals: [], flags: {} },
1977 },
1978 ]);
1979 const state = yield* service.state;
1980 expect(state.sessions.map((entry) => entry.threadId)).toEqual([other]);
1981 expect(state.devices.find((entry) => entry.id === session.deviceId)?.booted).toBe(true);
1982 expect(requests.some((url) => url.endsWith("/shutdown"))).toBe(false);
1983 }),
1984 );
1985
1986 it.effect.each(["reject", "http_error", "malformed"] as const)(
1987 "retains retryable state on %s",
1988 (failure) =>
1989 Effect.gen(function* () {
1990 let fail = true;
1991 const { service, requests, closedSessions } = yield* fixture(
1992 Effect.void,
1993 undefined,
1994 false,
1995 undefined,
1996 false,
1997 undefined,
1998 { onClose: Effect.sync(() => (fail ? failure : "ok")) },
1999 );
2000 yield* service.configure({ enabled: true, agentAccessEnabled: true });
2001 const threadId = ThreadId.make("retry");
2002 yield* openClaim(service, threadId);
2003 const exit = yield* Effect.exit(service.close({ threadId, shutdown: true }));
2004 expect(Exit.isFailure(exit)).toBe(true);
2005 expect((yield* service.state).sessions).toHaveLength(1);
2006 expect(requests.some((url) => url.endsWith("/shutdown"))).toBe(false);
2007 fail = false;
2008 yield* service.close({ threadId });
2009 expect((yield* service.state).sessions).toHaveLength(0);
2010 expect(closedSessions).toHaveLength(2);
2011 }),
2012 );
2013
2014 it.effect.each([false, true])("accepts a missing agent session, shutdown=%s", (shutdown) =>
2015 Effect.gen(function* () {
2016 const { service, requests } = yield* fixture(
2017 Effect.void,
2018 undefined,
2019 false,
2020 undefined,
2021 false,
2022 undefined,
2023 { onClose: Effect.succeed("missing") },
2024 );
2025 yield* service.configure({ enabled: true, agentAccessEnabled: true });
2026 const threadId = ThreadId.make("no-claim");
2027 yield* openClaim(service, threadId);
2028 yield* service.close({ threadId, shutdown });
2029 expect((yield* service.state).sessions).toHaveLength(0);
2030 expect(requests.some((url) => url.endsWith("/shutdown"))).toBe(shutdown);
2031 }),
2032 );
2033
2034 it.effect("retries shutdown after the first attempt already released the agent session", () =>
2035 Effect.gen(function* () {
2036 let released = false;
2037 const { service, connection } = yield* fixture(
2038 Effect.void,
2039 undefined,
2040 false,
2041 undefined,
2042 false,
2043 undefined,
2044 {
2045 onClose: Effect.sync(() => {
2046 const result = released ? "missing" : "ok";
2047 released = true;
2048 return result;
2049 }),
2050 },
2051 );
2052 yield* service.configure({ enabled: true, agentAccessEnabled: true });
2053 const threadId = ThreadId.make("retry-shutdown");
2054 yield* openClaim(service, threadId);
2055 connection.failShutdown = true;
2056 expect(Exit.isFailure(yield* Effect.exit(service.close({ threadId, shutdown: true })))).toBe(
2057 true,
2058 );
2059 expect((yield* service.state).sessions).toHaveLength(1);
2060 connection.failShutdown = false;
2061 yield* service.close({ threadId, shutdown: true });
2062 expect((yield* service.state).sessions).toHaveLength(0);
2063 }),
2064 );
2065
2066 it.effect("releases the post-boot agentTarget session for a cold Android AVD", () =>
2067 Effect.gen(function* () {
2068 const { service, closedSessions } = yield* fixture();
2069 yield* service.configure({ enabled: true, agentAccessEnabled: true });
2070 const threadId = ThreadId.make("cold-avd");
2071 const before = yield* service.agentTarget({
2072 threadId,
2073 hostId: "local",
2074 deviceId: "Pixel_API_35",
2075 });
2076 const session = yield* openClaim(service, threadId);
2077 const after = yield* service.agentTarget({
2078 threadId,
2079 hostId: session.hostId,
2080 deviceId: session.deviceId,
2081 });
2082 expect(session.deviceId).toBe("emulator-5554");
2083 expect(after.args[3]).not.toBe(before.args[3]);
2084 yield* service.close({ threadId });
2085 expect(closedSessions).toEqual([
2086 expect.objectContaining({ params: expect.objectContaining({ session: after.args[3] }) }),
2087 ]);
2088 }),
2089 );
2090
2091 it.effect("retains an SSH record during reconnect and releases it on retry", () =>
2092 Effect.gen(function* () {
2093 const { service, connection, closedSessions, agentStarts } = yield* fixture();
2094 connection.kind = "ssh";
2095 yield* service.configure({ enabled: true, agentAccessEnabled: true });
2096 const threadId = ThreadId.make("ssh-reconnect");
2097 yield* openClaim(service, threadId);
2098 const starts = agentStarts.length;
2099 connection.online = false;
2100 expect(Exit.isFailure(yield* Effect.exit(service.close({ threadId })))).toBe(true);
2101 expect((yield* service.state).sessions).toHaveLength(1);
2102 expect(closedSessions).toHaveLength(0);
2103 expect(agentStarts).toHaveLength(starts);
2104 connection.online = true;
2105 yield* service.close({ threadId });
2106 expect((yield* service.state).sessions).toHaveLength(0);
2107 expect(closedSessions).toHaveLength(1);
2108 }),
2109 );
2110 it.effect("releases peer claims before a close shuts down", () =>
2111 Effect.gen(function* () {
2112 const { service, closedSessions } = yield* fixture();
2113 yield* service.configure({ enabled: true, agentAccessEnabled: true });
2114 const threadId = ThreadId.make("shutting-down");
2115 const other = ThreadId.make("peer");
2116 const session = yield* openClaim(service, threadId);
2117 yield* openClaim(service, other, session.deviceId);
2118 yield* service.close({ threadId, shutdown: true });
2119 expect((yield* service.state).sessions).toHaveLength(0);
2120 yield* service.close({ threadId: other });
2121 expect((yield* service.state).sessions).toHaveLength(0);
2122 const names = yield* Effect.forEach([threadId, other], (thread) =>
2123 agentDeviceSession(thread, session.hostId, session.deviceId),
2124 ).pipe(Effect.provide(NodeCrypto.layer));
2125 expect(
2126 closedSessions.map((body) => (body as { params: { session: string } }).params.session),
2127 ).toEqual(names);
2128 }),
2129 );
2130
2131 it.effect("publishes a reopened session only after the old claim is released and removed", () =>
2132 Effect.gen(function* () {
2133 const entered = yield* Queue.unbounded<void>();
2134 const releasing = yield* Deferred.make<void>();
2135 const finish = yield* Deferred.make<void>();
2136 const { service } = yield* fixture(
2137 Effect.void,
2138 undefined,
2139 false,
2140 undefined,
2141 false,
2142 undefined,
2143 {
2144 onClose: Effect.gen(function* () {
2145 yield* Deferred.succeed(releasing, undefined);
2146 yield* Deferred.await(finish);
2147 return "ok" as const;
2148 }),
2149 onPlatformAvailability: Queue.offer(entered, undefined),
2150 },
2151 );
2152 yield* service.configure({ enabled: true, agentAccessEnabled: true });
2153 const threadId = ThreadId.make("reopen");
2154 const session = yield* openClaim(service, threadId);
2155 yield* Queue.take(entered);
2156 const publications = yield* service.subscribe;
2157 const closing = yield* service.close({ threadId }).pipe(Effect.forkChild);
2158 yield* Deferred.await(releasing);
2159 const opening = yield* openClaim(service, threadId, session.deviceId).pipe(Effect.forkChild);
2160 yield* Queue.take(entered);
2161 yield* Deferred.succeed(finish, undefined);
2162 yield* Fiber.join(closing);
2163 const reopened = yield* Fiber.join(opening);
2164 const published = (yield* PubSub.takeAll(publications))
2165 .map(({ sessions }) =>
2166 sessions.includes(session) ? "old" : sessions.includes(reopened) ? "reopened" : "none",
2167 )
2168 .filter((label, index, labels) => label !== labels[index - 1]);
2169 expect(published).toEqual(["none", "reopened"]);
2170 }),
2171 );
2172 });
2173
2174 describe("locating a device id across hosts", () => {
2175 const threadId = ThreadId.make("thread-locate");
2176 const thisMachine = { id: LOCAL_DEVICE_HOST_ID, label: "This machine" };
2177 const macMini = { id: "mac-mini", label: "Mac Mini" };
2178 const listingHost = (
2179 host: { readonly id: string; readonly label: string },
2180 ids: ReadonlyArray<string>,
2181 ): DeviceHost.DeviceHost["Service"] => {
2182 const devices = ids.map((id) => ({
2183 id,
2184 name: id,
2185 platform: id.startsWith("Pixel") ? ("android" as const) : ("ios" as const),
2186 version: "test",
2187 booted: true,
2188 physical: false,
2189 }));
2190 const ready: DeviceHost.DeviceHostReady = {
2191 nodePath: process.execPath,
2192 hub: { origin: "http://device.test" },
2193 devices: {
2194 list: Effect.succeed({ devices, detail: undefined }),
2195 boot: (device) => Effect.succeed(device.id),
2196 attach: () => Effect.void,
2197 shutdown: () => Effect.void,
2198 screenshot: () => Effect.succeed(new Uint8Array()),
2199 },
2200 // Opening an emulator checks its host for ffmpeg's H.264 encoder.
2201 run: () => Effect.succeed({ code: 0, stdout: " V....D libx264", stderr: "" }),
2202 helpers: { serveSimAxSettings: null, serveSimCli: null },
2203 };
2204 return {
2205 ...host,
2206 summary: Effect.succeed({
2207 ...host,
2208 kind: host.id === LOCAL_DEVICE_HOST_ID ? "local" : "ssh",
2209 platforms: [
2210 { platform: "ios", available: true },
2211 { platform: "android", available: true },
2212 ],
2213 hubInstalled: true,
2214 agentDeviceInstalled: false,
2215 }),
2216 platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
2217 ensureReady: () => Effect.succeed(ready),
2218 ensureAgentReady: () => Effect.die("Agent access is not used in this test"),
2219 current: Effect.succeed(ready),
2220 stopAgent: Effect.void,
2221 stop: Effect.void,
2222 };
2223 };
2224 // An Android AVD name, like Pixel_10 here, can exist on two hosts.
2225 const withTwoHosts = <A, E>(
2226 test: (service: DeviceService.DeviceService["Service"]) => Effect.Effect<A, E>,
2227 ) =>
2228 Effect.gen(function* () {
2229 const service = yield* DeviceService.makeWithHosts(
2230 new Map([
2231 [thisMachine.id, listingHost(thisMachine, ["Pixel_10"])],
2232 [macMini.id, listingHost(macMini, ["MAC-UDID", "Pixel_10"])],
2233 ]),
2234 ).pipe(Effect.provide(NodeCrypto.layer));
2235 yield* service.list;
2236 return yield* test(service);
2237 }).pipe(Effect.provide(ServerSettings.layerTest({ enableDeviceSupport: true })), Effect.scoped);
2238 const open = (
2239 service: DeviceService.DeviceService["Service"],
2240 hostId: string,
2241 deviceId: string,
2242 thread = threadId,
2243 ) =>
2244 service.open({
2245 threadId: thread,
2246 hostId,
2247 deviceId: DeviceId.make(deviceId),
2248 platform: deviceId.startsWith("Pixel") ? "android" : "ios",
2249 });
2250
2251 it.effect("finds a device id that exists only on another host", () =>
2252 withTwoHosts((service) =>
2253 Effect.gen(function* () {
2254 const located = yield* service.locateDevice({ deviceId: DeviceId.make("MAC-UDID") });
2255 expect(Option.getOrUndefined(located)).toMatchObject({
2256 hostId: "mac-mini",
2257 id: "MAC-UDID",
2258 });
2259 }),
2260 ),
2261 );
2262
2263 it.effect("refuses a device id that exists on two hosts and names both", () =>
2264 withTwoHosts((service) =>
2265 Effect.gen(function* () {
2266 const error = yield* service
2267 .locateDevice({ deviceId: DeviceId.make("Pixel_10") })
2268 .pipe(Effect.flip);
2269 expect(error).toMatchObject({ _tag: "DeviceHostAmbiguousError", deviceId: "Pixel_10" });
2270 expect(error.hosts).toHaveLength(2);
2271 expect(error.hosts).toEqual(expect.arrayContaining([thisMachine, macMini]));
2272 }),
2273 ),
2274 );
2275
2276 it.effect("keeps an explicit hostId and says which host has the device", () =>
2277 withTwoHosts((service) =>
2278 Effect.gen(function* () {
2279 const error = yield* service
2280 .locateDevice({ deviceId: DeviceId.make("MAC-UDID"), hostId: LOCAL_DEVICE_HOST_ID })
2281 .pipe(Effect.flip);
2282 expect(error).toMatchObject({
2283 _tag: "DeviceOnOtherHostError",
2284 deviceId: "MAC-UDID",
2285 host: thisMachine,
2286 hosts: [macMini],
2287 });
2288 const onMac = yield* service.locateDevice({
2289 deviceId: DeviceId.make("Pixel_10"),
2290 hostId: "mac-mini",
2291 });
2292 expect(Option.getOrUndefined(onMac)).toMatchObject({ hostId: "mac-mini", id: "Pixel_10" });
2293 }),
2294 ),
2295 );
2296
2297 it.effect("finds nothing for a device id that no host lists", () =>
2298 withTwoHosts((service) =>
2299 Effect.gen(function* () {
2300 const deviceId = DeviceId.make("Pixel_9");
2301 expect(yield* service.locateDevice({ deviceId })).toEqual(Option.none());
2302 expect(yield* service.locateDevice({ deviceId, hostId: "mac-mini" })).toEqual(
2303 Option.none(),
2304 );
2305 expect(yield* service.locateDevice({ deviceId, hostId: "unknown-host" })).toEqual(
2306 Option.none(),
2307 );
2308 }),
2309 ),
2310 );
2311
2312 it.effect("finds an open device by id on whichever host it is on", () =>
2313 withTwoHosts((service) =>
2314 Effect.gen(function* () {
2315 yield* open(service, "mac-mini", "MAC-UDID");
2316 const deviceId = DeviceId.make("MAC-UDID");
2317 expect(
2318 Option.getOrUndefined(yield* service.locateSession({ threadId, deviceId })),
2319 ).toMatchObject({ threadId, hostId: "mac-mini", deviceId });
2320 const error = yield* service
2321 .locateSession({ threadId, deviceId, hostId: LOCAL_DEVICE_HOST_ID })
2322 .pipe(Effect.flip);
2323 expect(error).toMatchObject({
2324 _tag: "DeviceOnOtherHostError",
2325 host: thisMachine,
2326 hosts: [macMini],
2327 });
2328 }),
2329 ),
2330 );
2331
2332 it.effect("refuses an id open on two hosts unless the hostId picks one", () =>
2333 withTwoHosts((service) =>
2334 Effect.gen(function* () {
2335 yield* open(service, LOCAL_DEVICE_HOST_ID, "Pixel_10");
2336 yield* open(service, "mac-mini", "Pixel_10");
2337 const deviceId = DeviceId.make("Pixel_10");
2338 const error = yield* service.locateSession({ threadId, deviceId }).pipe(Effect.flip);
2339 expect(error).toMatchObject({ _tag: "DeviceHostAmbiguousError", deviceId });
2340 expect(error.hosts).toEqual(expect.arrayContaining([thisMachine, macMini]));
2341 const onMac = yield* service.locateSession({ threadId, deviceId, hostId: "mac-mini" });
2342 expect(Option.getOrUndefined(onMac)).toMatchObject({ hostId: "mac-mini", deviceId });
2343 }),
2344 ),
2345 );
2346
2347 it.effect("finds no session for a device this thread has not opened", () =>
2348 withTwoHosts((service) =>
2349 Effect.gen(function* () {
2350 const deviceId = DeviceId.make("MAC-UDID");
2351 expect(yield* service.locateSession({ threadId, deviceId })).toEqual(Option.none());
2352 yield* open(service, "mac-mini", "MAC-UDID", ThreadId.make("thread-other"));
2353 expect(yield* service.locateSession({ threadId, deviceId })).toEqual(Option.none());
2354 expect(
2355 yield* service.locateSession({ threadId, deviceId, hostId: LOCAL_DEVICE_HOST_ID }),
2356 ).toEqual(Option.none());
2357 }),
2358 ),
2359 );
2360 });