Open History to see the last commit
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>;
41}
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 read: (references) =>
235 Effect.succeed(references.map((reference) => values[reference.reference])),
236 invalidate: () => Effect.void,
237 });
238
239const layerWith = (secrets: Layer.Layer<SecretResolver.SecretResolver>) =>
240 Layer.mergeAll(
241 ProcessRunner.layer,
242 ServerConfig.layerTest(process.cwd(), { prefix: "t3-eas-host-" }),
243 secrets,
244 ).pipe(Layer.provideMerge(NodeServices.layer));
245
246const layer = Layer.mergeAll(
247 ProcessRunner.layer,
248 ServerConfig.layerTest(process.cwd(), { prefix: "t3-eas-host-" }),
249 makeSecretResolver(),
250).pipe(Layer.provideMerge(NodeServices.layer));
251
252const makeHost = (
253 expo: ReturnType<typeof fakeExpo>,
254 hostConfig: EasDeviceHostConfig,
255 scope: Scope.Scope,
256) =>
257 EasDeviceHost.make(hostConfig).pipe(
258 Effect.provideService(HttpClient.HttpClient, expo.http),
259 Effect.provideService(Scope.Scope, scope),
260 );
261
262describe("EAS Simulator host", () => {
263 it.effect("starts a bounded session and routes its stream and agent to that session", () =>
264 Effect.gen(function* () {
265 const expo = fakeExpo();
266 const scope = yield* Scope.make();
267 const host = yield* makeHost(expo, config(), scope);
268 const ready = yield* host.ensureReady(() => Effect.void);
269 const catalog = (yield* ready.devices.list).devices;
270 expect(catalog.map((device) => [device.id, device.booted])).toEqual([
271 ["eas-ios", false],
272 ["eas-android", false],
273 ]);
274
275 expect(yield* ready.devices.boot(catalog[0]!)).toBe("session-1");
276 expect(expo.named("T3CreateEasSimulatorSession")[0]?.variables.input).toMatchObject({
277 appId: APP_ID,
278 platform: "IOS",
279 type: "AGENT_DEVICE",
280 maxRunTimeMinutes: 25,
281 maxIdleTimeMinutes: 5,
282 });
283 const listed = (yield* ready.devices.list).devices;
284 expect(listed.find((device) => device.id === "session-1")?.booted).toBe(true);
285 expect(yield* ready.devices.agentEndpoint!("session-1")).toEqual({
286 baseUrl: "https://agent.test",
287 token: "agent-token",
288 agentDeviceId: "UDID-1",
289 });
290
291 const routed = yield* ready.upstream!(
292 "/vendor/serve-sim/helper/session-1/webrtc/offer",
293 new URLSearchParams("hostId=eas"),
294 );
295 expect(routed).toEqual({
296 url: "https://preview.test/helper/UDID-1/webrtc/offer?hostId=eas",
297 headers: { authorization: "Bearer preview-token" },
298 protocols: ["serve-sim.token.preview-token"],
299 });
300 expect(
301 yield* ready.upstream!(
302 "/vendor/serve-sim/helper/ws",
303 new URLSearchParams("device=session-1"),
304 ),
305 ).toMatchObject({ url: "https://preview.test/helper/ws?device=UDID-1" });
306 expect(yield* ready.upstream!("/vendor/serve-emu/ws", new URLSearchParams())).toBeNull();
307 expect(
308 yield* ready.upstream!("/vendor/serve-sim/helper/%E0/config", new URLSearchParams()),
309 ).toBeNull();
310
311 yield* Scope.close(scope, Exit.void);
312 expect(expo.named("T3StopEasSimulatorSession").map((call) => call.variables.id)).toEqual([
313 "session-1",
314 ]);
315 }).pipe(Effect.scoped, Effect.provide(layer)),
316 );
317
318 it.effect("reads its token from the secret provider the setting names", () =>
319 Effect.gen(function* () {
320 const expo = fakeExpo();
321 const source = { provider: SecretProviderId.make("homelab"), reference: "expo#token" };
322 const host = yield* makeHost(expo, config({ accessToken: source }), yield* Scope.make());
323 const ready = yield* host.ensureReady(() => Effect.void);
324 const [catalogDevice] = (yield* ready.devices.list).devices;
325 expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");
326 }).pipe(
327 Effect.scoped,
328 Effect.provide(layerWith(makeSecretResolver({ "expo#token": "expo-token" }))),
329 ),
330 );
331
332 it.effect("fails instead of using another Expo login when its secret cannot be read", () =>
333 Effect.gen(function* () {
334 const expo = fakeExpo();
335 const source = { provider: SecretProviderId.make("homelab"), reference: "expo#token" };
336 const host = yield* makeHost(expo, config({ accessToken: source }), yield* Scope.make()).pipe(
337 Effect.provideService(HostProcess.Environment, { EXPO_TOKEN: "expo-token" }),
338 );
339 const ready = yield* host.ensureReady(() => Effect.void);
340 const [catalogDevice] = (yield* ready.devices.list).devices;
341 const failure = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
342 expect(failure.message).toContain('secret provider "homelab"');
343 expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(0);
344 }).pipe(Effect.scoped, Effect.provide(layer)),
345 );
346
347 it.effect("still stops its sessions when the secret becomes unreadable after they start", () => {
348 const readable = { value: true };
349 return Effect.gen(function* () {
350 const expo = fakeExpo();
351 const source = { provider: SecretProviderId.make("homelab"), reference: "expo#token" };
352 const scope = yield* Scope.make();
353 const host = yield* makeHost(expo, config({ accessToken: source }), scope);
354 const ready = yield* host.ensureReady(() => Effect.void);
355 const [catalogDevice] = (yield* ready.devices.list).devices;
356 expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");
357
358 readable.value = false;
359 yield* ready.devices.shutdown({ ...catalogDevice!, id: "session-1" });
360 expect(expo.stopped()).toEqual(["session-1"]);
361 yield* Scope.close(scope, Exit.void);
362 }).pipe(
363 Effect.scoped,
364 Effect.provide(
365 layerWith(
366 Layer.succeed(SecretResolver.SecretResolver, {
367 read: (references) =>
368 Effect.succeed(references.map(() => (readable.value ? "expo-token" : undefined))),
369 invalidate: () => Effect.void,
370 }),
371 ),
372 ),
373 );
374 });
375
376 it.effect("runs an Android session through serve-emu beside an iOS one", () =>
377 Effect.gen(function* () {
378 const expo = fakeExpo();
379 const scope = yield* Scope.make();
380 const host = yield* makeHost(expo, config(), scope);
381 expect(yield* host.platformAvailability("android")).toEqual({
382 platform: "android",
383 available: true,
384 });
385 const ready = yield* host.ensureReady(() => Effect.void);
386 const [ios, android] = (yield* ready.devices.list).devices;
387 expect(yield* ready.devices.boot(ios!)).toBe("session-1");
388 expect(yield* ready.devices.boot(android!)).toBe("session-2");
389 expect(expo.named("T3CreateEasSimulatorSession")[1]?.variables.input).toMatchObject({
390 platform: "ANDROID",
391 });
392 const running = (yield* ready.devices.list).devices.find(
393 (device) => device.id === "session-2",
394 );
395 expect(running).toMatchObject({ platform: "android", booted: true });
396
397 expect(yield* ready.devices.agentEndpoint!("session-2")).toMatchObject({
398 agentDeviceId: "emulator-5554",
399 });
400 expect(Array.from(yield* ready.devices.screenshot(running!))).toEqual([137, 80, 78, 71]);
401 expect(expo.previews.slice(-2)).toEqual([
402 "/vendor/serve-emu/api",
403 "/vendor/serve-emu/api/screenshot?device=emulator-5554",
404 ]);
405 expect(
406 yield* ready.upstream!(
407 "/vendor/serve-emu/webrtc/offer",
408 new URLSearchParams("device=session-2&hostId=eas"),
409 ),
410 ).toEqual({
411 url: "https://preview.test/vendor/serve-emu/webrtc/offer?device=emulator-5554&hostId=eas",
412 headers: { authorization: "Bearer preview-token" },
413 protocols: ["serve-emu.token.preview-token"],
414 });
415 // Each session answers only on its own platform's stream.
416 expect(
417 yield* ready.upstream!("/vendor/serve-emu/api", new URLSearchParams("device=session-1")),
418 ).toBeNull();
419 expect(
420 yield* ready.upstream!("/vendor/serve-sim/api", new URLSearchParams("device=session-2")),
421 ).toBeNull();
422 }).pipe(Effect.scoped, Effect.provide(layer)),
423 );
424
425 it.effect("refuses to start past its session limit", () =>
426 Effect.gen(function* () {
427 const expo = fakeExpo();
428 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
429 const ready = yield* host.ensureReady(() => Effect.void);
430 const [catalogDevice] = (yield* ready.devices.list).devices;
431 yield* ready.devices.boot(catalogDevice!);
432 const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
433 expect(refused.message).toBe(
434 "EAS Simulator is unavailable: EAS Simulator is limited to 1 running session. Close one in the Device panel first.",
435 );
436 expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(1);
437 }).pipe(Effect.scoped, Effect.provide(layer)),
438 );
439
440 it.effect("tells concurrent sessions apart although EAS gives each the same UDID", () =>
441 Effect.gen(function* () {
442 const expo = fakeExpo();
443 const scope = yield* Scope.make();
444 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 2 }), scope);
445 const ready = yield* host.ensureReady(() => Effect.void);
446 const [catalogDevice] = (yield* ready.devices.list).devices;
447 expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");
448 expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-2");
449 expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual([
450 "eas-ios",
451 "eas-android",
452 "session-1",
453 "session-2",
454 ]);
455 expect(
456 yield* ready.upstream!(
457 "/vendor/serve-sim/api",
458 new URLSearchParams("device=session-2&hostId=eas"),
459 ),
460 ).toMatchObject({ url: "https://preview.test/api?device=UDID-1&hostId=eas" });
461
462 yield* ready.devices.shutdown({ id: "session-1", platform: "ios" });
463 expect(expo.stopped()).toEqual(["session-1"]);
464 expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual([
465 "eas-ios",
466 "eas-android",
467 "session-2",
468 ]);
469 yield* Scope.close(scope, Exit.void);
470 expect(expo.stopped()).toEqual(["session-1", "session-2"]);
471 }).pipe(Effect.scoped, Effect.provide(layer)),
472 );
473
474 it.effect(
475 "keeps a refused create's record for the reaper without counting it after a restart",
476 () =>
477 Effect.gen(function* () {
478 const fs = yield* FileSystem.FileSystem;
479 const path = yield* Path.Path;
480 const server = yield* ServerConfig.ServerConfig;
481 const ledger = path.join(server.stateDir, "device", "eas", "eas.json");
482 // Expo refuses the create and lists nothing.
483 const expo = fakeExpo({ rejectCreate: true, omitCreatedFromActive: true });
484 const first = yield* Scope.make();
485 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), first);
486 const ready = yield* host.ensureReady(() => Effect.void);
487 const [catalogDevice] = (yield* ready.devices.list).devices;
488 yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
489 const entries = JSON.parse(yield* fs.readFileString(ledger)) as Array<{
490 refused?: boolean;
491 }>;
492 expect(entries.map((entry) => entry.refused)).toEqual([true]);
493 yield* Scope.close(first, Exit.void);
494 // A later server cannot even list the app: the record must not hold a slot.
495 const later = fakeExpo({ failList: () => true });
496 const restarted = yield* makeHost(
497 later,
498 config({ maxConcurrentSessions: 1 }),
499 yield* Scope.make(),
500 );
501 const readyAgain = yield* restarted.ensureReady(() => Effect.void);
502 const [device] = (yield* readyAgain.devices.list).devices;
503 expect(yield* readyAgain.devices.boot(device!)).toBe("session-1");
504 }).pipe(Effect.scoped, Effect.provide(layer)),
505 );
506
507 it.effect(
508 "does not sweep a replacement's session from a listing in flight when its scope closes",
509 () =>
510 Effect.gen(function* () {
511 const gate = yield* makeGate;
512 let armed = false;
513 const expo = fakeExpo({ sessionGate: () => (armed ? gate : undefined) });
514 const first = yield* Scope.make();
515 const old = yield* makeHost(expo, config(), first);
516 const oldReady = yield* old.ensureReady(() => Effect.void);
517 const [catalogDevice] = (yield* oldReady.devices.list).devices;
518 expect(yield* oldReady.devices.boot(catalogDevice!)).toBe("session-1");
519 // Long enough that the listing reads the session's status and a sweep is due.
520 yield* TestClock.adjust("2 minutes");
521 armed = true;
522 const listing = yield* oldReady.devices.list.pipe(Effect.forkChild);
523 yield* Deferred.await(gate.requested);
524 // Settings saved while the old listing waits on Expo.
525 yield* Scope.close(first, Exit.void);
526 const replacement = yield* makeHost(expo, config(), yield* Scope.make());
527 const ready = yield* replacement.ensureReady(() => Effect.void);
528 const [device] = (yield* ready.devices.list).devices;
529 expect(yield* ready.devices.boot(device!)).toBe("session-2");
530 yield* Deferred.succeed(gate.release, undefined);
531 yield* Fiber.join(listing);
532 expect(expo.stopped()).toEqual(["session-1"]);
533 }).pipe(Effect.scoped, Effect.provide(layer)),
534 );
535
536 it.effect("stops the session a refused create made anyway", () =>
537 Effect.gen(function* () {
538 // Expo refuses the create but lists a session by its name.
539 const expo = fakeExpo({ rejectCreate: true });
540 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
541 const ready = yield* host.ensureReady(() => Effect.void);
542 const [catalogDevice] = (yield* ready.devices.list).devices;
543 const failure = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
544 expect(failure.message).toContain("Not allowed");
545 expect(expo.stopped()).toEqual(["orphan"]);
546 }).pipe(Effect.scoped, Effect.provide(layer)),
547 );
548
549 it.effect("records a session before creating it and refuses to start without the record", () =>
550 Effect.gen(function* () {
551 const fs = yield* FileSystem.FileSystem;
552 const path = yield* Path.Path;
553 const server = yield* ServerConfig.ServerConfig;
554 // A directory where the ledger file should be: it can be neither read nor written.
555 yield* fs.makeDirectory(path.join(server.stateDir, "device", "eas", "eas.json"), {
556 recursive: true,
557 });
558 const expo = fakeExpo();
559 const host = yield* makeHost(expo, config(), yield* Scope.make());
560 const ready = yield* host.ensureReady(() => Effect.void);
561 const [catalogDevice] = (yield* ready.devices.list).devices;
562 const failure = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
563 expect(failure.message).toContain("could not be read");
564 expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(0);
565 }).pipe(Effect.scoped, Effect.provide(layer)),
566 );
567
568 it.effect("keeps a session it could not stop counted, listed, and retried", () =>
569 Effect.gen(function* () {
570 let stopFails = true;
571 const expo = fakeExpo({ failStop: () => stopFails });
572 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
573 const ready = yield* host.ensureReady(() => Effect.void);
574 const [catalogDevice] = (yield* ready.devices.list).devices;
575 yield* ready.devices.boot(catalogDevice!);
576 yield* ready.devices.shutdown({ id: "session-1", platform: "ios" }).pipe(Effect.flip);
577 expect((yield* ready.devices.list).devices.map((device) => device.id)).toContain("session-1");
578 const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
579 expect(refused.message).toContain("limited to 1 running session");
580 stopFails = false;
581 yield* ready.devices.list;
582 expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual([
583 "eas-ios",
584 "eas-android",
585 ]);
586 expect(expo.stopped().filter((id) => id === "session-1").length).toBeGreaterThanOrEqual(2);
587 }).pipe(Effect.scoped, Effect.provide(layer)),
588 );
589
590 it.effect("lets go of a stopping session Expo has ended although its stop keeps failing", () =>
591 Effect.gen(function* () {
592 let status = "IN_PROGRESS";
593 const expo = fakeExpo({ failStop: () => true, status: () => status });
594 const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
595 const ready = yield* host.ensureReady(() => Effect.void);
596 const [catalogDevice] = (yield* ready.devices.list).devices;
597 yield* ready.devices.boot(catalogDevice!);
598 yield* ready.devices.shutdown({ id: "session-1", platform: "ios" }).pipe(Effect.flip);
599 expect((yield* ready.devices.list).devices.map((device) => device.id)).toContain("session-1");
600 // Expo ended it by itself: the stop keeps failing, but the status says so.
601 status = "STOPPED";
602 expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual([
603 "eas-ios",
604 "eas-android",
605 ]);
606 status = "IN_PROGRESS";
607 expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-2");
608 }).pipe(Effect.scoped, Effect.provide(layer)),
609 );
610
611 it.effect("asks for an EAS project before starting anything when none can be found", () =>
612 Effect.gen(function* () {
613 const expo = fakeExpo();
614 const host = yield* makeHost(expo, config({ appId: undefined }), yield* Scope.make());
615 const ready = yield* host.ensureReady(() => Effect.void);
616 const [catalogDevice] = (yield* ready.devices.list).devices;
617 const failure = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
618 expect(failure.message).toContain("Choose one for this host in Settings");
619 expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(0);
620 }).pipe(Effect.scoped, Effect.provide(layer)),
621 );
622
623 it.effect("reports iOS unavailable on a server with no Expo credential", () =>
624 Effect.gen(function* () {
625 const fs = yield* FileSystem.FileSystem;
626 const home = yield* fs.makeTempDirectoryScoped({ prefix: "t3-expo-home-" });
627 const host = yield* makeHost(
628 fakeExpo(),
629 config({ accessToken: "" }),
630 yield* Scope.make(),
631 ).pipe(
632 Effect.provideService(HostProcess.HomeDirectory, home),
633 Effect.provideService(HostProcess.Environment, {}),
634 );
635 const [ios] = (yield* host.summary).platforms;
636 expect(ios).toMatchObject({ platform: "ios", available: false });
637 expect(ios?.reason).toContain("No Expo credential on the server");
638 }).pipe(Effect.scoped, Effect.provide(layer)),
639 );
640
641 it.effect("stops a session that is still starting when the host stops", () =>
642 Effect.gen(function* () {
643 const previewGate = yield* makeGate;
644 const expo = fakeExpo({ previewGate });
645 const host = yield* makeHost(expo, config(), yield* Scope.make());
646 const ready = yield* host.ensureReady(() => Effect.void);
647 const [catalogDevice] = (yield* ready.devices.list).devices;
648 const booting = yield* ready.devices.boot(catalogDevice!).pipe(Effect.forkChild);
649 yield* Deferred.await(previewGate.requested);
650 // Never released: stopping must not wait for the session to become ready.
651 yield* host.stop;
652 expect(expo.stopped()).toEqual(["session-1"]);
653 const failure = yield* Fiber.join(booting).pipe(Effect.flip);
654 expect(failure.message).toContain("was stopped while the session started");
655 expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual([
656 "eas-ios",
657 "eas-android",
658 ]);
659 }).pipe(Effect.scoped, Effect.provide(layer)),
660 );
661
662 it.effect("releases each thread's agent session on close and keeps the session running", () =>
663 Effect.gen(function* () {
664 let agentFails = false;
665 const expo = fakeExpo({ failAgent: () => agentFails });
666 const host = yield* makeHost(expo, config(), yield* Scope.make());
667 const service = yield* DeviceService.makeWithHosts(new Map([["eas", host]]), undefined, () =>
668 Effect.succeed("/eas-agent.json"),
669 );
670 const first = ThreadId.make("first");
671 const second = ThreadId.make("second");
672 const opened = yield* service.open({
673 threadId: first,
674 hostId: "eas",
675 deviceId: "eas-ios",
676 platform: "ios",
677 });
678 expect(opened.deviceId).toBe("session-1");
679 yield* service.open({
680 threadId: second,
681 hostId: "eas",
682 deviceId: opened.deviceId,
683 platform: "ios",
684 });
685 const sessionOf = (threadId: ThreadId) =>
686 service
687 .agentTarget({ threadId, hostId: "eas", deviceId: opened.deviceId })
688 .pipe(Effect.map((target) => target.args[3]));
689 const firstSession = yield* sessionOf(first);
690 const secondSession = yield* sessionOf(second);
691
692 yield* service.close({ threadId: first });
693 expect(expo.releases).toEqual([firstSession]);
694 expect((yield* service.state).sessions.map((entry) => entry.threadId)).toEqual([second]);
695
696 agentFails = true;
697 const failed = yield* Effect.exit(service.close({ threadId: second, shutdown: false }));
698 expect(Exit.isFailure(failed)).toBe(true);
699 expect((yield* service.state).sessions.map((entry) => entry.threadId)).toEqual([second]);
700
701 agentFails = false;
702 yield* service.close({ threadId: second, shutdown: false });
703 expect(expo.releases).toEqual([firstSession, secondSession, secondSession]);
704 expect((yield* service.state).sessions).toEqual([]);
705 expect(expo.stopped()).not.toContain("session-1");
706 expect(
707 (yield* service.state).devices.find((device) => device.id === "session-1")?.booted,
708 ).toBe(true);
709 }).pipe(
710 Effect.scoped,
711 Effect.provide(
712 Layer.mergeAll(
713 layer,
714 NodeCrypto.layer,
715 ServerSettings.layerTest({ enableDeviceSupport: true, enableAgentDeviceAccess: true }),
716 ),
717 ),
718 ),
719 );
720});