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