Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

EasDeviceHost.test.ts

722 lines31.4 KB

1import { describe, expect, it } from "@effect/vitest";
2import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { type EasDeviceHostConfig, SecretProviderId, ThreadId } from "@t3tools/contracts";
5import * as SecretResolver from "@t3tools/secret-provider-core/server/SecretResolver";
6import * as Deferred from "effect/Deferred";
7import * as Effect from "effect/Effect";
8import * as Fiber from "effect/Fiber";
9import * as Exit from "effect/Exit";
10import * as FileSystem from "effect/FileSystem";
11import * as Layer from "effect/Layer";
12import * as Path from "effect/Path";
13import * as Scope from "effect/Scope";
14import * as TestClock from "effect/testing/TestClock";
15import { HttpClient, HttpClientResponse } from "effect/http";
16import * as HostProcess from "@t3tools/shared/HostProcess";
17​
18import * as ServerConfig from "../config.ts";
19import * as ProcessRunner from "../processRunner.ts";
20import * as ServerSettings from "../serverSettings.ts";
21import * as DeviceService from "./DeviceService.ts";
22import * as EasDeviceHost from "./EasDeviceHost.ts";
23​
24const APP_ID = "d763fcb8-d37c-41ea-a773-b54a0ab4a454";
25​
26const config = (overrides: Partial<EasDeviceHostConfig> = {}): EasDeviceHostConfig => ({
27 kind: "eas",
28 id: "eas",
29 label: "EAS Simulator",
30 appId: APP_ID,
31 accessToken: "expo-token",
32 maxSessionMinutes: 25,
33 idleMinutes: 5,
34 maxConcurrentSessions: 2,
35 ...overrides,
36});
37​
38interface Gate {
39 readonly requested: Deferred.Deferred<void>;
40 readonly release: Deferred.Deferred<void>;
42const makeGate = Effect.all({
43 requested: Deferred.make<void>(),
44 release: Deferred.make<void>(),
45});
46​
47/** Expo's API and one session's preview host, recording what was asked of them. */
48const fakeExpo = (
49 options: {
50 readonly status?: () => string;
51 readonly failCreate?: boolean;
52 /** Expo answers the create with GraphQL errors: a refusal. */
53 readonly rejectCreate?: boolean;
54 readonly failStop?: () => boolean;
55 readonly failList?: () => boolean;
56 readonly active?: ReadonlyArray<{ id: string; status: string; name: string }>;
57 readonly previewGate?: Gate;
58 readonly createGate?: Gate;
59 /** Holds the first session read it answers with a gate. */
60 readonly sessionGate?: () => Gate | undefined;
61 readonly activeIncludesCreated?: boolean;
62 readonly failPreview?: boolean;
63 readonly omitCreatedFromActive?: boolean;
64 /** The session's agent-device daemon answers with a server error. */
65 readonly failAgent?: () => boolean;
66 } = {},
67) => {
68 const calls: Array<{ operation: string; variables: Record<string, unknown> }> = [];
69 const releases: Array<unknown> = [];
70 let created = 0;
71 let createdName = "";
72 const previews: string[] = [];
73 let previewFails = options.failPreview ?? false;
74 let createFails = options.failCreate ?? false;
75 let sessionGated = false;
76 const http = HttpClient.make((request) =>
77 Effect.gen(function* () {
78 const url = new URL(request.url);
79 if (url.origin === "https://preview.test") {
80 previews.push(`${url.pathname}${url.search}`);
81 expect(request.headers.authorization).toBe("Bearer preview-token");
82 if (options.previewGate) {
83 yield* Deferred.succeed(options.previewGate.requested, undefined);
84 yield* Deferred.await(options.previewGate.release);
85 }
86 if (previewFails) {
87 return HttpClientResponse.fromWeb(request, new Response("bad gateway", { status: 502 }));
88 }
89 if (url.pathname.endsWith("/api/screenshot")) {
90 return HttpClientResponse.fromWeb(request, new Response(Uint8Array.of(137, 80, 78, 71)));
91 }
92 return HttpClientResponse.fromWeb(
93 request,
94 Response.json(
95 url.pathname === "/vendor/serve-emu/api"
96 ? { serial: "emulator-5554" }
97 : { device: "UDID-1" },
98 ),
99 );
100 }
101 if (url.origin === "https://agent.test") {
102 expect(request.headers.authorization).toBe("Bearer agent-token");
103 if (request.body._tag === "Uint8Array") {
104 const rpc = JSON.parse(new TextDecoder().decode(request.body.body)) as {
105 params: { command: string; session: string };
106 };
107 if (rpc.params.command === "close") releases.push(rpc.params.session);
108 }
109 if (options.failAgent?.())
110 return HttpClientResponse.fromWeb(request, new Response("bad gateway", { status: 502 }));
111 return HttpClientResponse.fromWeb(request, Response.json({ result: { ok: true } }));
112 }
113 const body =
114 request.body._tag === "Uint8Array"
115 ? (JSON.parse(new TextDecoder().decode(request.body.body)) as {
116 query: string;
117 variables: Record<string, { name?: string } & Record<string, unknown>>;
118 })
119 : { query: "", variables: {} };
120 expect(request.headers.authorization).toBe("Bearer expo-token");
121 const operation = /(?:query|mutation) (\w+)/.exec(body.query)?.[1] ?? "unknown";
122 calls.push({ operation, variables: body.variables });
123 if (operation === "T3CreateEasSimulatorSession") {
124 createdName = body.variables.input?.name ?? "";
125 if (options.createGate) {
126 yield* Deferred.succeed(options.createGate.requested, undefined);
127 yield* Deferred.await(options.createGate.release);
128 }
129 if (createFails)
130 return HttpClientResponse.fromWeb(request, new Response("bad gateway", { status: 502 }));
131 if (options.rejectCreate)
132 return HttpClientResponse.fromWeb(
133 request,
134 Response.json({ errors: [{ message: "Not allowed" }] }),
135 );
136 }
137 if (operation === "T3StopEasSimulatorSession" && options.failStop?.()) {
138 return HttpClientResponse.fromWeb(request, new Response("bad gateway", { status: 502 }));
139 }
140 if (operation === "T3ActiveEasSimulatorSessions" && options.failList?.()) {
141 return HttpClientResponse.fromWeb(request, new Response("bad gateway", { status: 502 }));
142 }
143 const sessionGate =
144 operation === "T3EasSimulatorSession" ? options.sessionGate?.() : undefined;
145 if (sessionGate && !sessionGated) {
146 sessionGated = true;
147 yield* Deferred.succeed(sessionGate.requested, undefined);
148 yield* Deferred.await(sessionGate.release);
149 }
150 const data =
151 operation === "T3EasSimulatorAvailability"
152 ? {
153 app: {
154 byId: {
155 ownerAccount: {
156 name: "pingdotgg",
157 accountFeatureGates: { "device-run-sessions": true },
158 },
159 },
160 },
161 }
162 : operation === "T3CreateEasSimulatorSession"
163 ? { deviceRunSession: { createDeviceRunSession: { id: `session-${++created}` } } }
164 : operation === "T3ActiveEasSimulatorSessions"
165 ? {
166 app: {
167 byId: {
168 deviceRunSessionsPaginated: {
169 edges: [
170 ...(options.omitCreatedFromActive
171 ? []
172 : [{ node: { id: "orphan", status: "NEW", name: createdName } }]),
173 {
174 node: {
175 id: "someone-else",
176 status: "IN_PROGRESS",
177 name: "T3 Code · EAS Simulator · 000000",
178 },
179 },
180 ...(options.active ?? []).map((node) => ({ node })),
181 ...(options.activeIncludesCreated && created > 0
182 ? [
183 {
184 node: {
185 id: `session-${created}`,
186 status: "STARTING",
187 name: createdName,
188 },
189 },
190 ]
191 : []),
192 ],
193 },
194 },
195 },
196 }
197 : operation === "T3EasSimulatorSession"
198 ? {
199 deviceRunSessions: {
200 byId: {
201 id: body.variables.id,
202 status: options.status?.() ?? "IN_PROGRESS",
203 remoteConfig: {
204 __typename: "AgentDeviceRunSessionRemoteConfig",
205 agentDeviceRemoteSessionUrl: "https://agent.test",
206 agentDeviceRemoteSessionToken: "agent-token",
207 webPreviewToken: "preview-token",
208 previewApiUrl: "https://preview.test?token=preview-token",
209 },
210 },
211 },
212 }
213 : {
214 deviceRunSession: {
215 ensureDeviceRunSessionStopped: { id: body.variables.id, status: "STOPPED" },
216 },
217 };
218 return HttpClientResponse.fromWeb(request, Response.json({ data }));
219 }),
220 );
221 const named = (operation: string) => calls.filter((call) => call.operation === operation);
222 const stopped = () => named("T3StopEasSimulatorSession").map((call) => call.variables.id);
223 const allowPreview = () => {
224 previewFails = false;
225 };
226 const allowCreate = () => {
227 createFails = false;
228 };
229 return { http, named, stopped, allowPreview, allowCreate, releases, previews };
230};
231​
232const makeSecretResolver = (values: Record<string, string> = {}) =>
233 Layer.succeed(SecretResolver.SecretResolver, {
234 label: (provider) => Effect.succeed(provider),
235 read: (references) =>
236 Effect.succeed(references.map((reference) => values[reference.reference])),
237 invalidate: () => Effect.void,
238 });
239​
240const layerWith = (secrets: Layer.Layer<SecretResolver.SecretResolver>) =>
241 Layer.mergeAll(
242 ProcessRunner.layer,
243 ServerConfig.layerTest(process.cwd(), { prefix: "t3-eas-host-" }),
244 secrets,
245 ).pipe(Layer.provideMerge(NodeServices.layer));
246​
247const layer = Layer.mergeAll(
248 ProcessRunner.layer,
249 ServerConfig.layerTest(process.cwd(), { prefix: "t3-eas-host-" }),
250 makeSecretResolver(),
251).pipe(Layer.provideMerge(NodeServices.layer));
252​
253const makeHost = (
254 expo: ReturnType<typeof fakeExpo>,
255 hostConfig: EasDeviceHostConfig,
256 scope: Scope.Scope,
257) =>
258 EasDeviceHost.make(hostConfig).pipe(
259 Effect.provideService(HttpClient.HttpClient, expo.http),
260 Effect.provideService(Scope.Scope, scope),
261 );
262​
263describe("EAS Simulator host", () => {
264 it.effect("starts a bounded session and routes its stream and agent to that session", () =>
265 Effect.gen(function* () {
266 const expo = fakeExpo();
267 const scope = yield* Scope.make();
268 const host = yield* makeHost(expo, config(), scope);
269 const ready = yield* host.ensureReady(() => Effect.void);
270 const catalog = (yield* ready.devices.list).devices;
271 expect(catalog.map((device) => [device.id, device.booted])).toEqual([
272 ["eas-ios", false],
273 ["eas-android", false],
274 ]);
275​
276 expect(yield* ready.devices.boot(catalog[0]!)).toBe("session-1");
277 expect(expo.named("T3CreateEasSimulatorSession")[0]?.variables.input).toMatchObject({
278 appId: APP_ID,
279 platform: "IOS",
280 type: "AGENT_DEVICE",
281 maxRunTimeMinutes: 25,
282 maxIdleTimeMinutes: 5,
283 });
284 const listed = (yield* ready.devices.list).devices;
285 expect(listed.find((device) => device.id === "session-1")?.booted).toBe(true);
286 expect(yield* ready.devices.agentEndpoint!("session-1")).toEqual({
287 baseUrl: "https://agent.test",
288 token: "agent-token",
289 agentDeviceId: "UDID-1",
290 });
291​
292 const routed = yield* ready.upstream!(
293 "/vendor/serve-sim/helper/session-1/webrtc/offer",
294 new URLSearchParams("hostId=eas"),
295 );
296 expect(routed).toEqual({
297 url: "https://preview.test/helper/UDID-1/webrtc/offer?hostId=eas",
298 headers: { authorization: "Bearer preview-token" },
299 protocols: ["serve-sim.token.preview-token"],
300 });
301 expect(
302 yield* ready.upstream!(
303 "/vendor/serve-sim/helper/ws",
304 new URLSearchParams("device=session-1"),
305 ),
306 ).toMatchObject({ url: "https://preview.test/helper/ws?device=UDID-1" });
307 expect(yield* ready.upstream!("/vendor/serve-emu/ws", new URLSearchParams())).toBeNull();
308 expect(
309 yield* ready.upstream!("/vendor/serve-sim/helper/%E0/config", new URLSearchParams()),
310 ).toBeNull();
311​
312 yield* Scope.close(scope, Exit.void);
313 expect(expo.named("T3StopEasSimulatorSession").map((call) => call.variables.id)).toEqual([
314 "session-1",
315 ]);
316 }).pipe(Effect.scoped, Effect.provide(layer)),
317 );
318​
319 it.effect("reads its token from the secret provider the setting names", () =>
320 Effect.gen(function* () {
321 const expo = fakeExpo();
322 const source = { provider: SecretProviderId.make("homelab"), reference: "expo#token" };
323 const host = yield* makeHost(expo, config({ accessToken: source }), yield* Scope.make());
324 const ready = yield* host.ensureReady(() => Effect.void);
325 const [catalogDevice] = (yield* ready.devices.list).devices;
326 expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");
327 }).pipe(
328 Effect.scoped,
329 Effect.provide(layerWith(makeSecretResolver({ "expo#token": "expo-token" }))),
330 ),
331 );
332​
333 it.effect("fails instead of using another Expo login when its secret cannot be read", () =>
334 Effect.gen(function* () {
335 const expo = fakeExpo();
336 const source = { provider: SecretProviderId.make("homelab"), reference: "expo#token" };
337 const host = yield* makeHost(expo, config({ accessToken: source }), yield* Scope.make()).pipe(
338 Effect.provideService(HostProcess.Environment, { EXPO_TOKEN: "expo-token" }),
339 );
340 const ready = yield* host.ensureReady(() => Effect.void);
341 const [catalogDevice] = (yield* ready.devices.list).devices;
342 const failure = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
343 expect(failure.message).toContain('secret provider "homelab"');
344 expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(0);
345 }).pipe(Effect.scoped, Effect.provide(layer)),
346 );
347​
348 it.effect("still stops its sessions when the secret becomes unreadable after they start", () => {
349 const readable = { value: true };
350 return Effect.gen(function* () {
351 const expo = fakeExpo();
352 const source = { provider: SecretProviderId.make("homelab"), reference: "expo#token" };
353 const scope = yield* Scope.make();
354 const host = yield* makeHost(expo, config({ accessToken: source }), scope);
355 const ready = yield* host.ensureReady(() => Effect.void);
356 const [catalogDevice] = (yield* ready.devices.list).devices;
357 expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");
358​
359 readable.value = false;
360 yield* ready.devices.shutdown({ ...catalogDevice!, id: "session-1" });
361 expect(expo.stopped()).toEqual(["session-1"]);
362 yield* Scope.close(scope, Exit.void);
363 }).pipe(
364 Effect.scoped,
365 Effect.provide(
366 layerWith(
367 Layer.succeed(SecretResolver.SecretResolver, {
368 label: (provider) => Effect.succeed(provider),
369 read: (references) =>
370 Effect.succeed(references.map(() => (readable.value ? "expo-token" : undefined))),
371 invalidate: () => Effect.void,
372 }),
373 ),
374 ),
375 );
376 });
377​
378 it.effect("runs an Android session through serve-emu beside an iOS one", () =>
379 Effect.gen(function* () {
380 const expo = fakeExpo();
381 const scope = yield* Scope.make();
382 const host = yield* makeHost(expo, config(), scope);
383 expect(yield* host.platformAvailability("android")).toEqual({
384 platform: "android",
385 available: true,
386 });
387 const ready = yield* host.ensureReady(() => Effect.void);
388 const [ios, android] = (yield* ready.devices.list).devices;
389 expect(yield* ready.devices.boot(ios!)).toBe("session-1");
390 expect(yield* ready.devices.boot(android!)).toBe("session-2");
391 expect(expo.named("T3CreateEasSimulatorSession")[1]?.variables.input).toMatchObject({
392 platform: "ANDROID",
393 });
394 const running = (yield* ready.devices.list).devices.find(
395 (device) => device.id === "session-2",
396 );
397 expect(running).toMatchObject({ platform: "android", booted: true });
398​
399 expect(yield* ready.devices.agentEndpoint!("session-2")).toMatchObject({
400 agentDeviceId: "emulator-5554",
401 });
402 expect(Array.from(yield* ready.devices.screenshot(running!))).toEqual([137, 80, 78, 71]);
403 expect(expo.previews.slice(-2)).toEqual([
404 "/vendor/serve-emu/api",
405 "/vendor/serve-emu/api/screenshot?device=emulator-5554",
406 ]);
407 expect(
408 yield* ready.upstream!(
409 "/vendor/serve-emu/webrtc/offer",
410 new URLSearchParams("device=session-2&hostId=eas"),
411 ),
412 ).toEqual({
413 url: "https://preview.test/vendor/serve-emu/webrtc/offer?device=emulator-5554&hostId=eas",
414 headers: { authorization: "Bearer preview-token" },
415 protocols: ["serve-emu.token.preview-token"],
416 });
417 // Each session answers only on its own platform's stream.
418 expect(
419 yield* ready.upstream!("/vendor/serve-emu/api", new URLSearchParams("device=session-1")),
420 ).toBeNull();
421 expect(
422 yield* ready.upstream!("/vendor/serve-sim/api", new URLSearchParams("device=session-2")),
423 ).toBeNull();
424 }).pipe(Effect.scoped, Effect.provide(layer)),
425 );
426​
427 it.effect("refuses to start past its session limit", () =>
428 Effect.gen(function* () {
429 const expo = fakeExpo();
430 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
431 const ready = yield* host.ensureReady(() => Effect.void);
432 const [catalogDevice] = (yield* ready.devices.list).devices;
433 yield* ready.devices.boot(catalogDevice!);
434 const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
435 expect(refused.message).toBe(
436 "EAS Simulator is unavailable: EAS Simulator is limited to 1 running session. Close one in the Device panel first.",
437 );
438 expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(1);
439 }).pipe(Effect.scoped, Effect.provide(layer)),
440 );
441​
442 it.effect("tells concurrent sessions apart although EAS gives each the same UDID", () =>
443 Effect.gen(function* () {
444 const expo = fakeExpo();
445 const scope = yield* Scope.make();
446 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 2 }), scope);
447 const ready = yield* host.ensureReady(() => Effect.void);
448 const [catalogDevice] = (yield* ready.devices.list).devices;
449 expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");
450 expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-2");
451 expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual([
452 "eas-ios",
453 "eas-android",
454 "session-1",
455 "session-2",
456 ]);
457 expect(
458 yield* ready.upstream!(
459 "/vendor/serve-sim/api",
460 new URLSearchParams("device=session-2&hostId=eas"),
461 ),
462 ).toMatchObject({ url: "https://preview.test/api?device=UDID-1&hostId=eas" });
463​
464 yield* ready.devices.shutdown({ id: "session-1", platform: "ios" });
465 expect(expo.stopped()).toEqual(["session-1"]);
466 expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual([
467 "eas-ios",
468 "eas-android",
469 "session-2",
470 ]);
471 yield* Scope.close(scope, Exit.void);
472 expect(expo.stopped()).toEqual(["session-1", "session-2"]);
473 }).pipe(Effect.scoped, Effect.provide(layer)),
474 );
475​
476 it.effect(
477 "keeps a refused create's record for the reaper without counting it after a restart",
478 () =>
479 Effect.gen(function* () {
480 const fs = yield* FileSystem.FileSystem;
481 const path = yield* Path.Path;
482 const server = yield* ServerConfig.ServerConfig;
483 const ledger = path.join(server.stateDir, "device", "eas", "eas.json");
484 // Expo refuses the create and lists nothing.
485 const expo = fakeExpo({ rejectCreate: true, omitCreatedFromActive: true });
486 const first = yield* Scope.make();
487 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), first);
488 const ready = yield* host.ensureReady(() => Effect.void);
489 const [catalogDevice] = (yield* ready.devices.list).devices;
490 yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
491 const entries = JSON.parse(yield* fs.readFileString(ledger)) as Array<{
492 refused?: boolean;
493 }>;
494 expect(entries.map((entry) => entry.refused)).toEqual([true]);
495 yield* Scope.close(first, Exit.void);
496 // A later server cannot even list the app: the record must not hold a slot.
497 const later = fakeExpo({ failList: () => true });
498 const restarted = yield* makeHost(
499 later,
500 config({ maxConcurrentSessions: 1 }),
501 yield* Scope.make(),
502 );
503 const readyAgain = yield* restarted.ensureReady(() => Effect.void);
504 const [device] = (yield* readyAgain.devices.list).devices;
505 expect(yield* readyAgain.devices.boot(device!)).toBe("session-1");
506 }).pipe(Effect.scoped, Effect.provide(layer)),
507 );
508​
509 it.effect(
510 "does not sweep a replacement's session from a listing in flight when its scope closes",
511 () =>
512 Effect.gen(function* () {
513 const gate = yield* makeGate;
514 let armed = false;
515 const expo = fakeExpo({ sessionGate: () => (armed ? gate : undefined) });
516 const first = yield* Scope.make();
517 const old = yield* makeHost(expo, config(), first);
518 const oldReady = yield* old.ensureReady(() => Effect.void);
519 const [catalogDevice] = (yield* oldReady.devices.list).devices;
520 expect(yield* oldReady.devices.boot(catalogDevice!)).toBe("session-1");
521 // Long enough that the listing reads the session's status and a sweep is due.
522 yield* TestClock.adjust("2 minutes");
523 armed = true;
524 const listing = yield* oldReady.devices.list.pipe(Effect.forkChild);
525 yield* Deferred.await(gate.requested);
526 // Settings saved while the old listing waits on Expo.
527 yield* Scope.close(first, Exit.void);
528 const replacement = yield* makeHost(expo, config(), yield* Scope.make());
529 const ready = yield* replacement.ensureReady(() => Effect.void);
530 const [device] = (yield* ready.devices.list).devices;
531 expect(yield* ready.devices.boot(device!)).toBe("session-2");
532 yield* Deferred.succeed(gate.release, undefined);
533 yield* Fiber.join(listing);
534 expect(expo.stopped()).toEqual(["session-1"]);
535 }).pipe(Effect.scoped, Effect.provide(layer)),
536 );
537​
538 it.effect("stops the session a refused create made anyway", () =>
539 Effect.gen(function* () {
540 // Expo refuses the create but lists a session by its name.
541 const expo = fakeExpo({ rejectCreate: true });
542 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
543 const ready = yield* host.ensureReady(() => Effect.void);
544 const [catalogDevice] = (yield* ready.devices.list).devices;
545 const failure = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
546 expect(failure.message).toContain("Not allowed");
547 expect(expo.stopped()).toEqual(["orphan"]);
548 }).pipe(Effect.scoped, Effect.provide(layer)),
549 );
550​
551 it.effect("records a session before creating it and refuses to start without the record", () =>
552 Effect.gen(function* () {
553 const fs = yield* FileSystem.FileSystem;
554 const path = yield* Path.Path;
555 const server = yield* ServerConfig.ServerConfig;
556 // A directory where the ledger file should be: it can be neither read nor written.
557 yield* fs.makeDirectory(path.join(server.stateDir, "device", "eas", "eas.json"), {
558 recursive: true,
559 });
560 const expo = fakeExpo();
561 const host = yield* makeHost(expo, config(), yield* Scope.make());
562 const ready = yield* host.ensureReady(() => Effect.void);
563 const [catalogDevice] = (yield* ready.devices.list).devices;
564 const failure = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
565 expect(failure.message).toContain("could not be read");
566 expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(0);
567 }).pipe(Effect.scoped, Effect.provide(layer)),
568 );
569​
570 it.effect("keeps a session it could not stop counted, listed, and retried", () =>
571 Effect.gen(function* () {
572 let stopFails = true;
573 const expo = fakeExpo({ failStop: () => stopFails });
574 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
575 const ready = yield* host.ensureReady(() => Effect.void);
576 const [catalogDevice] = (yield* ready.devices.list).devices;
577 yield* ready.devices.boot(catalogDevice!);
578 yield* ready.devices.shutdown({ id: "session-1", platform: "ios" }).pipe(Effect.flip);
579 expect((yield* ready.devices.list).devices.map((device) => device.id)).toContain("session-1");
580 const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
581 expect(refused.message).toContain("limited to 1 running session");
582 stopFails = false;
583 yield* ready.devices.list;
584 expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual([
585 "eas-ios",
586 "eas-android",
587 ]);
588 expect(expo.stopped().filter((id) => id === "session-1").length).toBeGreaterThanOrEqual(2);
589 }).pipe(Effect.scoped, Effect.provide(layer)),
590 );
591​
592 it.effect("lets go of a stopping session Expo has ended although its stop keeps failing", () =>
593 Effect.gen(function* () {
594 let status = "IN_PROGRESS";
595 const expo = fakeExpo({ failStop: () => true, status: () => status });
596 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
597 const ready = yield* host.ensureReady(() => Effect.void);
598 const [catalogDevice] = (yield* ready.devices.list).devices;
599 yield* ready.devices.boot(catalogDevice!);
600 yield* ready.devices.shutdown({ id: "session-1", platform: "ios" }).pipe(Effect.flip);
601 expect((yield* ready.devices.list).devices.map((device) => device.id)).toContain("session-1");
602 // Expo ended it by itself: the stop keeps failing, but the status says so.
603 status = "STOPPED";
604 expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual([
605 "eas-ios",
606 "eas-android",
607 ]);
608 status = "IN_PROGRESS";
609 expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-2");
610 }).pipe(Effect.scoped, Effect.provide(layer)),
611 );
612​
613 it.effect("asks for an EAS project before starting anything when none can be found", () =>
614 Effect.gen(function* () {
615 const expo = fakeExpo();
616 const host = yield* makeHost(expo, config({ appId: undefined }), yield* Scope.make());
617 const ready = yield* host.ensureReady(() => Effect.void);
618 const [catalogDevice] = (yield* ready.devices.list).devices;
619 const failure = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
620 expect(failure.message).toContain("Choose one for this host in Settings");
621 expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(0);
622 }).pipe(Effect.scoped, Effect.provide(layer)),
623 );
624​
625 it.effect("reports iOS unavailable on a server with no Expo credential", () =>
626 Effect.gen(function* () {
627 const fs = yield* FileSystem.FileSystem;
628 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-expo-home-" });
629 const host = yield* makeHost(
630 fakeExpo(),
631 config({ accessToken: "" }),
632 yield* Scope.make(),
633 ).pipe(
634 Effect.provideService(HostProcess.HomeDirectory, home),
635 Effect.provideService(HostProcess.Environment, {}),
636 );
637 const [ios] = (yield* host.summary).platforms;
638 expect(ios).toMatchObject({ platform: "ios", available: false });
639 expect(ios?.reason).toContain("No Expo credential on the server");
640 }).pipe(Effect.scoped, Effect.provide(layer)),
641 );
642​
643 it.effect("stops a session that is still starting when the host stops", () =>
644 Effect.gen(function* () {
645 const previewGate = yield* makeGate;
646 const expo = fakeExpo({ previewGate });
647 const host = yield* makeHost(expo, config(), yield* Scope.make());
648 const ready = yield* host.ensureReady(() => Effect.void);
649 const [catalogDevice] = (yield* ready.devices.list).devices;
650 const booting = yield* ready.devices.boot(catalogDevice!).pipe(Effect.forkChild);
651 yield* Deferred.await(previewGate.requested);
652 // Never released: stopping must not wait for the session to become ready.
653 yield* host.stop;
654 expect(expo.stopped()).toEqual(["session-1"]);
655 const failure = yield* Fiber.join(booting).pipe(Effect.flip);
656 expect(failure.message).toContain("was stopped while the session started");
657 expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual([
658 "eas-ios",
659 "eas-android",
660 ]);
661 }).pipe(Effect.scoped, Effect.provide(layer)),
662 );
663​
664 it.effect("releases each thread's agent session on close and keeps the session running", () =>
665 Effect.gen(function* () {
666 let agentFails = false;
667 const expo = fakeExpo({ failAgent: () => agentFails });
668 const host = yield* makeHost(expo, config(), yield* Scope.make());
669 const service = yield* DeviceService.makeWithHosts(new Map([["eas", host]]), undefined, () =>
670 Effect.succeed("/eas-agent.json"),
671 );
672 const first = ThreadId.make("first");
673 const second = ThreadId.make("second");
674 const opened = yield* service.open({
675 threadId: first,
676 hostId: "eas",
677 deviceId: "eas-ios",
678 platform: "ios",
679 });
680 expect(opened.deviceId).toBe("session-1");
681 yield* service.open({
682 threadId: second,
683 hostId: "eas",
684 deviceId: opened.deviceId,
685 platform: "ios",
686 });
687 const sessionOf = (threadId: ThreadId) =>
688 service
689 .agentTarget({ threadId, hostId: "eas", deviceId: opened.deviceId })
690 .pipe(Effect.map((target) => target.args[3]));
691 const firstSession = yield* sessionOf(first);
692 const secondSession = yield* sessionOf(second);
693​
694 yield* service.close({ threadId: first });
695 expect(expo.releases).toEqual([firstSession]);
696 expect((yield* service.state).sessions.map((entry) => entry.threadId)).toEqual([second]);
697​
698 agentFails = true;
699 const failed = yield* Effect.exit(service.close({ threadId: second, shutdown: false }));
700 expect(Exit.isFailure(failed)).toBe(true);
701 expect((yield* service.state).sessions.map((entry) => entry.threadId)).toEqual([second]);
702​
703 agentFails = false;
704 yield* service.close({ threadId: second, shutdown: false });
705 expect(expo.releases).toEqual([firstSession, secondSession, secondSession]);
706 expect((yield* service.state).sessions).toEqual([]);
707 expect(expo.stopped()).not.toContain("session-1");
708 expect(
709 (yield* service.state).devices.find((device) => device.id === "session-1")?.booted,
710 ).toBe(true);
711 }).pipe(
712 Effect.scoped,
713 Effect.provide(
714 Layer.mergeAll(
715 layer,
716 NodeCrypto.layer,
717 ServerSettings.layerTest({ enableDeviceSupport: true, enableAgentDeviceAccess: true }),
718 ),
719 ),
720 ),
721 );
722});