Open History to see the last commit
1import { describe, expect, it } from "@effect/vitest";
2import * as NodeServices from "@effect/platform-node/NodeServices";
3import { SecretProviderId, type SimlockDeviceHostConfig } from "@t3tools/contracts";
4import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
5import * as HostProcess from "@t3tools/shared/HostProcess";
6import * as Effect from "effect/Effect";
7import * as Clock from "effect/Clock";
8import * as Fiber from "effect/Fiber";
9import * as Deferred from "effect/Deferred";
10import * as Exit from "effect/Exit";
11import * as FileSystem from "effect/FileSystem";
12import * as Layer from "effect/Layer";
13import * as Path from "effect/Path";
14import * as Scope from "effect/Scope";
15import * as TestClock from "effect/testing/TestClock";
16import { HttpClient, HttpClientResponse } from "effect/http";
17import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
18
19import * as ServerConfig from "../config.ts";
20import * as ProcessRunner from "../processRunner.ts";
21import * as SimlockDeviceHost from "./SimlockDeviceHost.ts";
22
23const GATEWAY = "https://simlock.test:4700";
24
25const config = (overrides: Partial<SimlockDeviceHostConfig> = {}): SimlockDeviceHostConfig => ({
26 kind: "simlock",
27 id: "pool",
28 label: "Device pool",
29 gatewayUrl: `${GATEWAY}/`,
30 agentToken: "agent-token",
31 maxLeases: 2,
32 maxLeaseMinutes: 60,
33 ...overrides,
34});
35
36const CATALOG = {
37 platforms: [
38 {
39 platform: "ios",
40 modelRuntimes: { "iPhone 17 Pro": ["27.0"], "Apple TV 4K": ["27.0"], "iPhone 12": [] },
41 modelClasses: { "iPhone 17 Pro": "phone", "Apple TV 4K": "tv", "iPhone 12": "phone" },
42 },
43 {
44 platform: "android",
45 modelRuntimes: { "Pixel 9": ["36"], "Pixel 8": ["36"] },
46 modelWorkers: { "Pixel 9": ["worker-a"], "Pixel 8": [] },
47 },
48 ],
49};
50
51/** The gateway's HTTP API and T3's agent-device CLI, recording what was asked of them. */
52const fakePool = (
53 options: {
54 /** What the agent-device CLI prints before exiting 1 from `open`. */
55 readonly failOpen?: unknown;
56 readonly holdOpen?: {
57 readonly entered: Deferred.Deferred<void>;
58 readonly proceed: Deferred.Deferred<void>;
59 };
60 /** The gateway's `lease.maxTtlMs`: leases expire one TTL after their last renewal. */
61 readonly maxTtlMs?: number;
62 /** What `GET /v1/status` answers; no enrolled phones by default. */
63 readonly status?: unknown;
64 } = {},
65) =>
66 Effect.gen(function* () {
67 const fs = yield* FileSystem.FileSystem;
68 const path = yield* Path.Path;
69 const requests: Array<string> = [];
70 const commands: Array<{ readonly args: ReadonlyArray<string>; readonly cwd?: string }> = [];
71 let leases = 0;
72 let renewStatus = 200;
73 let statusCode = 200;
74 let catalog: unknown = CATALOG;
75 let leaseDeadline = Infinity;
76 const http = HttpClient.make((request) =>
77 Effect.gen(function* () {
78 const now = yield* Clock.currentTimeMillis;
79 const url = new URL(request.url);
80 requests.push(`${request.method} ${url.pathname}`);
81 const json = (body: unknown, status = 200) =>
82 HttpClientResponse.fromWeb(request, Response.json(body, { status }));
83 if (request.headers.authorization !== "Bearer agent-token")
84 return json({ error: { code: "UNAUTHENTICATED", message: "Unknown bearer token" } }, 401);
85 if (url.pathname === "/v1/catalog") return json(catalog);
86 if (url.pathname === "/v1/status") return json(options.status ?? {}, statusCode);
87 if (url.pathname.endsWith("/renew") && options.maxTtlMs !== undefined) {
88 if (now >= leaseDeadline) return json({}, 404);
89 const body =
90 request.body._tag === "Uint8Array"
91 ? (JSON.parse(new TextDecoder().decode(request.body.body)) as { ttlMs?: number })
92 : {};
93 if ((body.ttlMs ?? 0) > options.maxTtlMs)
94 return json({ error: { code: "BAD_REQUEST", message: "ttlMs exceeds maxTtlMs" } }, 400);
95 leaseDeadline = now + (body.ttlMs ?? options.maxTtlMs);
96 return json({});
97 }
98 if (url.pathname.endsWith("/renew")) return json({}, renewStatus);
99 if (request.method === "DELETE") return json({}, 202);
100 return json({}, 404);
101 }),
102 );
103 const runner = ProcessRunner.ProcessRunner.of({
104 run: (input) =>
105 Effect.gen(function* () {
106 const args = input.args.slice(1);
107 commands.push({ args, ...(input.cwd ? { cwd: input.cwd } : {}) });
108 const command = args[0];
109 const session = args[args.indexOf("--session") + 1]!;
110 const configFile = args[args.indexOf("--config") + 1]!;
111 const stateDir = (
112 JSON.parse(yield* fs.readFileString(configFile)) as { stateDir: string }
113 ).stateDir;
114 if (command === "open") {
115 if (options.failOpen) {
116 return {
117 stdout: JSON.stringify(options.failOpen),
118 stderr: "",
119 code: ChildProcessSpawner.ExitCode(1),
120 timedOut: false,
121 stdoutTruncated: false,
122 stderrTruncated: false,
123 stdoutInvalidUtf8: false,
124 stderrInvalidUtf8: false,
125 };
126 }
127 if (options.holdOpen) {
128 yield* Deferred.succeed(options.holdOpen.entered, undefined);
129 yield* Deferred.await(options.holdOpen.proceed);
130 }
131 const dir = path.join(stateDir, "remote-connections");
132 yield* fs.makeDirectory(dir, { recursive: true });
133 yield* fs.writeFileString(
134 path.join(dir, `${session}.json`),
135 JSON.stringify({ leaseId: `lease-${++leases}` }),
136 );
137 if (options.maxTtlMs !== undefined)
138 leaseDeadline = (yield* Clock.currentTimeMillis) + options.maxTtlMs;
139 }
140 if (command === "screenshot") yield* fs.writeFile(args[1]!, new Uint8Array([1, 2, 3]));
141 return {
142 stdout: "{}",
143 stderr: "",
144 code: ChildProcessSpawner.ExitCode(0),
145 timedOut: false,
146 stdoutTruncated: false,
147 stderrTruncated: false,
148 stdoutInvalidUtf8: false,
149 stderrInvalidUtf8: false,
150 };
151 }).pipe(Effect.orDie),
152 });
153 const ran = (command: string) => commands.filter(({ args }) => args[0] === command);
154 return {
155 http,
156 runner,
157 requests,
158 ran,
159 endLeases: () => {
160 renewStatus = 404;
161 },
162 setCatalog: (next: unknown) => {
163 catalog = next;
164 },
165 setStatusCode: (next: number) => {
166 statusCode = next;
167 },
168 };
169 });
170
171const makeSecretResolver = (values: Record<string, string> = {}) =>
172 Layer.succeed(SecretResolver.SecretResolver, {
173 read: (references) =>
174 Effect.succeed(references.map((reference) => values[reference.reference])),
175 invalidate: () => Effect.void,
176 label: (provider) => Effect.succeed(provider),
177 });
178
179const layerWith = (secrets: Layer.Layer<SecretResolver.SecretResolver>) =>
180 Layer.mergeAll(
181 ServerConfig.layerTest(process.cwd(), { prefix: "t3-simlock-host-" }),
182 secrets,
183 ).pipe(Layer.provideMerge(NodeServices.layer));
184
185const layer = layerWith(makeSecretResolver());
186
187const tokenSource = { provider: SecretProviderId.make("homelab"), reference: "simlock#token" };
188
189const makeHost = (
190 pool: Effect.Success<ReturnType<typeof fakePool>>,
191 hostConfig: SimlockDeviceHostConfig,
192 scope: Scope.Scope,
193) =>
194 SimlockDeviceHost.make(
195 hostConfig,
196 Effect.succeed({ nodePath: "node", entryPath: "/tools/agent-device.mjs" }),
197 ).pipe(
198 Effect.provideService(HttpClient.HttpClient, pool.http),
199 Effect.provideService(ProcessRunner.ProcessRunner, pool.runner),
200 Effect.provideService(Scope.Scope, scope),
201 );
202
203describe("Simlock device host", () => {
204 it.effect("leases a pool device for agents and serves its screen and input to the panel", () =>
205 Effect.gen(function* () {
206 const pool = yield* fakePool();
207 const fs = yield* FileSystem.FileSystem;
208 const workspace = yield* fs.makeTempDirectoryScoped();
209 const scope = yield* Scope.make();
210 const host = yield* makeHost(pool, config(), scope);
211 const ready = yield* host.ensureReady(() => Effect.void);
212
213 const catalog = (yield* ready.devices.list).devices;
214 // Only models a worker can make right now, and only phones and tablets.
215 expect(catalog.map((device) => [device.id, device.version])).toEqual([
216 ["simlock:ios:iPhone 17 Pro", "iOS 27.0"],
217 ["simlock:android:Pixel 9", "Android 36"],
218 ]);
219
220 const leaseId = yield* ready.devices.boot(catalog[1]!, { workspaceRoot: workspace });
221 expect(leaseId).toBe("lease-1");
222 const [open] = pool.ran("open");
223 expect(open?.args.slice(0, 5)).toEqual([
224 "open",
225 "--platform",
226 "android",
227 "--device",
228 "Pixel 9",
229 ]);
230 expect(open?.cwd).toBe(yield* fs.realPath(workspace));
231 expect(pool.ran("connect")[0]?.args).toContain(`${GATEWAY}/v1/agent-device`);
232
233 const binding = yield* ready.devices.agentEndpoint!(leaseId);
234 expect(binding).toMatchObject({
235 baseUrl: `${GATEWAY}/v1/agent-device`,
236 token: "agent-token",
237 agentDeviceId: null,
238 session: open?.args[open.args.indexOf("--session") + 1],
239 installDirectory: yield* fs.realPath(workspace),
240 });
241 expect((yield* ready.devices.list).devices.at(-1)).toMatchObject({
242 id: "lease-1",
243 name: "Pixel 9",
244 booted: true,
245 });
246
247 expect(
248 yield* ready.upstream!(
249 "/vendor/serve-sim/helper/lease-1/stream.avcc",
250 new URLSearchParams(),
251 ),
252 ).toEqual({
253 url: `${GATEWAY}/v1/leases/lease-1/stream`,
254 headers: { authorization: "Bearer agent-token" },
255 protocols: [],
256 });
257 expect(
258 yield* ready.upstream!(
259 "/vendor/serve-sim/helper/ws",
260 new URLSearchParams({ device: "lease-1" }),
261 ),
262 ).toEqual({
263 url: `${GATEWAY}/v1/leases/lease-1/input`,
264 headers: { authorization: "Bearer agent-token" },
265 protocols: [],
266 });
267 expect(
268 yield* ready.upstream!("/vendor/serve-sim/helper/lease-1/config", new URLSearchParams()),
269 ).toBeNull();
270 expect(
271 yield* ready.upstream!(
272 "/vendor/serve-sim/helper/ws",
273 new URLSearchParams({ device: "lease-2" }),
274 ),
275 ).toBeNull();
276 expect([...(yield* ready.devices.screenshot({ ...catalog[1]!, id: leaseId }))]).toEqual([
277 1, 2, 3,
278 ]);
279
280 yield* ready.devices.shutdown({ id: leaseId, platform: "android" });
281 expect(pool.ran("close")).toHaveLength(1);
282 expect((yield* ready.devices.list).devices.some((device) => device.booted)).toBe(false);
283 yield* Scope.close(scope, Exit.void);
284 expect(pool.ran("close")).toHaveLength(1);
285 }).pipe(Effect.scoped, Effect.provide(layer)),
286 );
287
288 it.effect("offers enrolled phones on usable workers and leases one as a physical device", () =>
289 Effect.gen(function* () {
290 const phone = (model: string, overrides: Record<string, unknown> = {}) => ({
291 spec: { platform: "ios", model, osVersion: "26.1" },
292 state: "ready",
293 physical: true,
294 class: "phone",
295 workerId: "worker-a",
296 ...overrides,
297 });
298 const pool = yield* fakePool({
299 status: {
300 workers: [
301 { id: "worker-a", connection: "connected", drained: false },
302 { id: "worker-b", connection: "connected", drained: true },
303 ],
304 devices: [
305 phone("iPhone 15", {
306 spec: { platform: "ios", model: "iPhone 15", osVersion: "18.6:beta" },
307 }),
308 phone("iPhone 13", { state: "absent" }),
309 phone("iPhone 14", { workerId: "worker-b" }),
310 phone("Apple Watch", { class: "watch" }),
311 ],
312 },
313 });
314 pool.setStatusCode(503);
315 const scope = yield* Scope.make();
316 const host = yield* makeHost(pool, config(), scope);
317 const ready = yield* host.ensureReady(() => Effect.void);
318 const names = (devices: ReadonlyArray<{ readonly name: string; readonly version: string }>) =>
319 devices.map((device) => `${device.name} ${device.version}`);
320
321 // A gateway that cannot list phones still offers its simulators, and the next listing retries.
322 expect(names((yield* ready.devices.list).devices)).toEqual([
323 "iPhone 17 Pro iOS 27.0",
324 "Pixel 9 Android 36",
325 ]);
326 pool.setStatusCode(200);
327 const devices = (yield* ready.devices.list).devices;
328 expect(names(devices)).toEqual([
329 "iPhone 17 Pro iOS 27.0",
330 "Pixel 9 Android 36",
331 "iPhone 15 iOS 18.6:beta",
332 ]);
333
334 yield* ready.devices.boot(devices.find((device) => device.physical)!);
335 expect(pool.ran("open")[0]?.args.slice(0, 8)).toEqual([
336 "open",
337 "--platform",
338 "ios",
339 "--device",
340 "iPhone 15",
341 "--physical",
342 "--os",
343 "18.6:beta",
344 ]);
345 expect((yield* ready.devices.list).devices.find((device) => device.booted)).toMatchObject({
346 name: "iPhone 15",
347 physical: true,
348 });
349 yield* Scope.close(scope, Exit.void);
350 }).pipe(Effect.scoped, Effect.provide(layer)),
351 );
352
353 it.effect("caps leases at the limit", () =>
354 Effect.gen(function* () {
355 const pool = yield* fakePool();
356 const scope = yield* Scope.make();
357 const host = yield* makeHost(pool, config({ maxLeases: 1 }), scope);
358 const ready = yield* host.ensureReady(() => Effect.void);
359 const [iphone] = (yield* ready.devices.list).devices;
360 yield* ready.devices.boot(iphone!);
361
362 const refused = yield* ready.devices.boot(iphone!).pipe(Effect.flip);
363 expect(refused.message).toContain("limited to 1 device");
364 expect(pool.ran("open")).toHaveLength(1);
365 yield* Scope.close(scope, Exit.void);
366 expect(pool.ran("close")).toHaveLength(1);
367 }).pipe(Effect.scoped, Effect.provide(layer)),
368 );
369
370 it.effect("reports its platforms unavailable when the gateway refuses the agent token", () =>
371 Effect.gen(function* () {
372 const pool = yield* fakePool();
373 const scope = yield* Scope.make();
374 const host = yield* makeHost(pool, config({ agentToken: "revoked" }), scope);
375 expect(yield* host.platformAvailability("ios")).toEqual({
376 platform: "ios",
377 available: false,
378 reason: "The Simlock gateway refused the agent token for Device pool.",
379 });
380 expect((yield* host.summary).platforms.every((platform) => !platform.available)).toBe(true);
381 yield* Scope.close(scope, Exit.void);
382 }).pipe(Effect.scoped, Effect.provide(layer)),
383 );
384
385 it.effect("sends saved and machine tokens only to the gateway each belongs to", () =>
386 Effect.gen(function* () {
387 const pool = yield* fakePool();
388 const availability = (baseUrl: string) =>
389 Effect.gen(function* () {
390 const scope = yield* Scope.make();
391 const host = yield* makeHost(pool, config({ agentToken: "" }), scope).pipe(
392 Effect.provideService(HostProcess.Environment, {
393 AGENT_DEVICE_DAEMON_BASE_URL: baseUrl,
394 AGENT_DEVICE_DAEMON_AUTH_TOKEN: "agent-token",
395 }),
396 );
397 const result = yield* host.platformAvailability("ios");
398 yield* Scope.close(scope, Exit.void);
399 return result;
400 });
401
402 expect(
403 yield* SimlockDeviceHost.resolveSimlockToken(
404 yield* SecretResolver.SecretResolver,
405 "https://elsewhere.example:4700",
406 config({ agentToken: "saved-token" }),
407 {},
408 ),
409 ).toBeNull();
410
411 expect(yield* availability(`${GATEWAY}/v1/agent-device`)).toEqual({
412 platform: "ios",
413 available: true,
414 });
415 const requests = pool.requests.length;
416 expect(yield* availability("https://elsewhere.example:4700/v1/agent-device")).toEqual({
417 platform: "ios",
418 available: false,
419 reason: "Add an agent token for Device pool in Settings.",
420 });
421 expect(pool.requests).toHaveLength(requests);
422 }).pipe(Effect.scoped, Effect.provide(layer)),
423 );
424
425 it.effect("reads its agent token from the secret provider the setting names", () =>
426 Effect.gen(function* () {
427 const pool = yield* fakePool();
428 const scope = yield* Scope.make();
429 const host = yield* makeHost(pool, config({ agentToken: tokenSource }), scope);
430 const ready = yield* host.ensureReady(() => Effect.void);
431 const [iphone] = (yield* ready.devices.list).devices;
432 const leaseId = yield* ready.devices.boot(iphone!);
433 expect(yield* ready.devices.agentEndpoint!(leaseId)).toMatchObject({ token: "agent-token" });
434 yield* Scope.close(scope, Exit.void);
435 expect(pool.ran("close")).toHaveLength(1);
436 }).pipe(
437 Effect.scoped,
438 Effect.provide(layerWith(makeSecretResolver({ "simlock#token": "agent-token" }))),
439 ),
440 );
441
442 it.effect("fails instead of using this machine's token when its secret cannot be read", () =>
443 Effect.gen(function* () {
444 const pool = yield* fakePool();
445 const scope = yield* Scope.make();
446 const host = yield* makeHost(pool, config({ agentToken: tokenSource }), scope).pipe(
447 Effect.provideService(HostProcess.Environment, {
448 AGENT_DEVICE_DAEMON_BASE_URL: `${GATEWAY}/v1/agent-device`,
449 AGENT_DEVICE_DAEMON_AUTH_TOKEN: "agent-token",
450 }),
451 );
452 const availability = yield* host.platformAvailability("ios");
453 expect(availability.available).toBe(false);
454 expect(availability.reason).toContain('secret provider "homelab"');
455 expect(pool.requests).toEqual([]);
456 yield* Scope.close(scope, Exit.void);
457 }).pipe(Effect.scoped, Effect.provide(layer)),
458 );
459
460 it.effect("lists a platform again as soon as its workers return", () =>
461 Effect.gen(function* () {
462 const pool = yield* fakePool();
463 const scope = yield* Scope.make();
464 const host = yield* makeHost(pool, config(), scope);
465 const ready = yield* host.ensureReady(() => Effect.void);
466 pool.setCatalog({ platforms: [] });
467 expect((yield* ready.devices.list).devices).toEqual([]);
468 // Mid-reconnect, the gateway knows the Android models but no worker that makes them.
469 pool.setCatalog({
470 platforms: [
471 CATALOG.platforms[0]!,
472 { ...CATALOG.platforms[1]!, modelWorkers: { "Pixel 9": [], "Pixel 8": [] } },
473 ],
474 });
475 const during = (yield* ready.devices.list).devices;
476 expect(during.some((device) => device.platform === "android")).toBe(false);
477 pool.setCatalog(CATALOG);
478 const after = (yield* ready.devices.list).devices;
479 expect(after.some((device) => device.platform === "android")).toBe(true);
480 yield* Scope.close(scope, Exit.void);
481 }).pipe(Effect.scoped, Effect.provide(layer)),
482 );
483
484 it.effect("closes the session of a failed open so no lease is left behind", () =>
485 Effect.gen(function* () {
486 const pool = yield* fakePool({
487 failOpen: { error: { message: "No device matches.", hint: "Retry." } },
488 });
489 const scope = yield* Scope.make();
490 const host = yield* makeHost(pool, config(), scope);
491 const ready = yield* host.ensureReady(() => Effect.void);
492 const [iphone] = (yield* ready.devices.list).devices;
493 const failure = yield* ready.devices.boot(iphone!).pipe(Effect.flip);
494 expect(String(failure.cause)).toContain("No device matches. Retry.");
495 expect(pool.ran("close")).toHaveLength(1);
496 // The failed open freed its slot.
497 expect(yield* ready.devices.boot(iphone!).pipe(Effect.flip)).toBeDefined();
498 yield* Scope.close(scope, Exit.void);
499 }).pipe(Effect.scoped, Effect.provide(layer)),
500 );
501
502 it.effect("tells the user what agent-device reported when a device fails to open", () =>
503 Effect.gen(function* () {
504 const pool = yield* fakePool({
505 failOpen: {
506 success: false,
507 error: {
508 code: "COMMAND_FAILED",
509 message: "Invalid daemon response",
510 cause: {
511 message: "Unexpected non-whitespace character after JSON at position 4",
512 },
513 hint: "Retry with --debug and inspect diagnostics log for details.",
514 details: { requestId: "22a6bf10a567b2a1", line: "404 Not Found" },
515 },
516 },
517 });
518 const scope = yield* Scope.make();
519 const host = yield* makeHost(pool, config(), scope);
520 const ready = yield* host.ensureReady(() => Effect.void);
521 const pixel = (yield* ready.devices.list).devices.find(({ name }) => name === "Pixel 9");
522 const failure = yield* ready.devices.boot(pixel!).pipe(Effect.flip);
523 expect(failure.message).not.toContain("The device host sent no details.");
524 expect(failure.message).toContain("Invalid daemon response");
525 expect(failure.message).toContain("404 Not Found");
526 yield* Scope.close(scope, Exit.void);
527
528 // A details bag without a usable response line still keeps agent-device's message.
529 const oddPool = yield* fakePool({
530 failOpen: { error: { message: "Invalid daemon response", details: { line: 17 } } },
531 });
532 const oddScope = yield* Scope.make();
533 const oddReady = yield* (yield* makeHost(oddPool, config(), oddScope)).ensureReady(
534 () => Effect.void,
535 );
536 const [oddDevice] = (yield* oddReady.devices.list).devices;
537 const oddFailure = yield* oddReady.devices.boot(oddDevice!).pipe(Effect.flip);
538 expect(oddFailure.message).toContain("Invalid daemon response");
539 yield* Scope.close(oddScope, Exit.void);
540 }).pipe(Effect.scoped, Effect.provide(layer)),
541 );
542
543 it.effect("keeps a watched lease renewed and stops listing it once Simlock ends it", () =>
544 Effect.gen(function* () {
545 const pool = yield* fakePool();
546 const scope = yield* Scope.make();
547 const host = yield* makeHost(pool, config(), scope);
548 const ready = yield* host.ensureReady(() => Effect.void);
549 const [iphone] = (yield* ready.devices.list).devices;
550 const leaseId = yield* ready.devices.boot(iphone!);
551
552 yield* TestClock.adjust("2 minutes");
553 expect(pool.requests).toContain(`POST /v1/leases/${leaseId}/renew`);
554 expect((yield* ready.devices.list).devices.some((device) => device.id === leaseId)).toBe(
555 true,
556 );
557
558 pool.endLeases();
559 yield* TestClock.adjust("2 minutes");
560 expect((yield* ready.devices.list).devices.some((device) => device.id === leaseId)).toBe(
561 false,
562 );
563 yield* Scope.close(scope, Exit.void);
564 expect(pool.ran("close")).toHaveLength(0);
565 }).pipe(Effect.scoped, Effect.provide(layer)),
566 );
567
568 it.effect("keeps a watched lease renewed when the gateway caps lease TTLs", () =>
569 Effect.gen(function* () {
570 const pool = yield* fakePool({ maxTtlMs: 5 * 60_000 });
571 const host = yield* makeHost(pool, config(), yield* Scope.make());
572 const ready = yield* host.ensureReady(() => Effect.void);
573 const [iphone] = (yield* ready.devices.list).devices;
574 const leaseId = yield* ready.devices.boot(iphone!);
575
576 yield* TestClock.adjust("6 minutes");
577 expect((yield* ready.devices.list).devices.some((device) => device.id === leaseId)).toBe(
578 true,
579 );
580 }).pipe(Effect.scoped, Effect.provide(layer)),
581 );
582
583 it.effect("returns a lease whose open finishes after the host stopped", () =>
584 Effect.gen(function* () {
585 const holdOpen = {
586 entered: yield* Deferred.make<void>(),
587 proceed: yield* Deferred.make<void>(),
588 };
589 const pool = yield* fakePool({ holdOpen });
590 const host = yield* makeHost(pool, config(), yield* Scope.make());
591 const ready = yield* host.ensureReady(() => Effect.void);
592 const [iphone] = (yield* ready.devices.list).devices;
593 const opening = yield* Effect.forkChild(ready.devices.boot(iphone!));
594 yield* Deferred.await(holdOpen.entered);
595 yield* host.stop;
596 yield* Deferred.succeed(holdOpen.proceed, undefined);
597 expect(Exit.isFailure(yield* Fiber.await(opening))).toBe(true);
598 expect(pool.ran("close")).toHaveLength(1);
599 expect((yield* ready.devices.list).devices.every((device) => !device.booted)).toBe(true);
600 }).pipe(Effect.scoped, Effect.provide(layer)),
601 );
602
603 it.effect("holds a lease for its full maximum age, then returns it", () =>
604 Effect.gen(function* () {
605 const pool = yield* fakePool();
606 const host = yield* makeHost(pool, config({ maxLeaseMinutes: 5 }), yield* Scope.make());
607 const ready = yield* host.ensureReady(() => Effect.void);
608 const [iphone] = (yield* ready.devices.list).devices;
609 yield* ready.devices.boot(iphone!);
610
611 yield* TestClock.adjust("299 seconds");
612 expect(pool.ran("close")).toHaveLength(0);
613 yield* TestClock.adjust("1 second");
614 expect(pool.ran("close")).toHaveLength(1);
615 }).pipe(Effect.scoped, Effect.provide(layer)),
616 );
617});