The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 22:00 UTC
feat(server): EAS Simulator device hosts (#21844)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 20, 2026 at 00:57 UTC
aee25acd17aa9e3e56db319f71b31f82744bc54b
20 files changed
+2309
-175
apps/server/src/device/AgentDeviceTarget.test.ts
+5
-2
@@ -94,7 +94,6 @@ if (process.env.AGENT_DEVICE_DAEMON_BASE_URL) process.exit(2);`,
94
yield* writeAgentDeviceConfig(file, {
95
baseUrl: `http://127.0.0.1:${1000 + index}`,
96
token: `token-${index}`,
97
- entryPath,
97
});
98
const invoke = (file: string) =>
99
exec(
@@ -117,10 +116,14 @@ if (process.env.AGENT_DEVICE_DAEMON_BASE_URL) process.exit(2);`,
116
yield* writeAgentDeviceConfig(files[0]!, {
117
baseUrl: "http://127.0.0.1:2000",
118
token: "new",
120
- entryPath,
119
});
120
expect((yield* Effect.promise(() => invoke(files[0]!))).daemonAuthToken).toBe("new");
121
expect(yield* fs.readFileString(files[1]!)).toBe(second);
122
+ // Hosts with a daemon per device get a file per device, apart from the host's own.
123
+ const perDevice = yield* Effect.forEach(["udid-1", "udid-2"], (device) =>
124
+ agentDeviceConfigPath(dir, "eas", path, device),
125
+ );
126
+ expect(new Set([...perDevice, yield* agentDeviceConfigPath(dir, "eas", path)]).size).toBe(3);
127
expect(yield* agentDeviceSession("thread", "mini", "same-id")).not.toBe(
128
yield* agentDeviceSession("thread", "android", "same-id"),
129
);
apps/server/src/device/AgentDeviceTarget.ts
+15
-5
@@ -5,7 +5,7 @@ import * as Schema from "effect/Schema";
5
import * as FileSystem from "effect/FileSystem";
6
import * as Path from "effect/Path";
7
8
-import type { AgentDeviceEndpoint } from "./DeviceHost.ts";
8
+import type { AgentDaemonEndpoint } from "./DeviceHost.ts";
9
10
const encodeEndpoint = Schema.encodeEffect(
11
Schema.fromJsonString(
@@ -21,16 +21,26 @@ const key = Effect.fn("AgentDeviceTarget.key")(function* (value: string) {
21
return Hex.encode(digest).slice(0, 24);
22
});
23
24
-/** A stable file per host lets forwarded endpoints change without retargeting other commands. */
25
-export const agentDeviceConfigPath = (stateDir: string, hostId: string, path: Path.Path) =>
26
- key(hostId).pipe(Effect.map((hash) => path.join(stateDir, "device", "hosts", `${hash}.json`)));
24
+/**
25
+ * A stable file per host lets forwarded endpoints change without retargeting
26
+ * other commands. Hosts with a daemon per device get a file per device.
27
+ */
28
+export const agentDeviceConfigPath = (
29
+ stateDir: string,
30
+ hostId: string,
31
+ path: Path.Path,
32
+ deviceId?: string,
33
+) =>
34
+ key(deviceId === undefined ? hostId : JSON.stringify([hostId, deviceId])).pipe(
35
+ Effect.map((hash) => path.join(stateDir, "device", "hosts", `${hash}.json`)),
36
+ );
37
38
export const agentDeviceSession = (threadId: string, hostId: string, deviceId: string) =>
39
key(JSON.stringify([threadId, hostId, deviceId])).pipe(Effect.map((hash) => `t3-${hash}`));
40
41
export const writeAgentDeviceConfig = Effect.fn("AgentDeviceTarget.writeConfig")(function* (
42
file: string,
33
- endpoint: AgentDeviceEndpoint,
43
+ endpoint: AgentDaemonEndpoint,
44
) {
45
const fs = yield* FileSystem.FileSystem;
46
const path = yield* Path.Path;
apps/server/src/device/DeviceHost.ts
+42
-2
@@ -1,6 +1,7 @@
1
import type {
2
DeviceBootError,
3
DeviceHostId,
4
+ DeviceHostUnavailableError,
5
DeviceHostSummary,
6
DeviceOperationError,
7
DevicePlatform,
@@ -76,6 +77,20 @@ export interface AgentDeviceEndpoint {
77
78
export type HostDevice = Omit<DeviceSummary, "hostId">;
79
80
+/** Where a device is being opened from, for hosts whose devices depend on the project. */
81
+export interface DeviceOpenContext {
82
+ readonly workspaceRoot?: string | undefined;
83
+}
84
+
85
+export type AgentDaemonEndpoint = Pick<AgentDeviceEndpoint, "baseUrl" | "token">;
86
+
87
+/** Where the proxy sends a device hub request, for hosts that serve several upstreams. */
88
+export interface HubUpstream {
89
+ readonly url: string;
90
+ readonly headers: Readonly<Record<string, string>>;
91
+ readonly protocols: ReadonlyArray<string>;
92
+}
93
+
94
/** Discovery and lifecycle for the devices a ready host can run. */
95
export interface DeviceOperations {
96
readonly list: Effect.Effect<
@@ -93,7 +108,8 @@ export interface DeviceOperations {
108
*/
109
readonly boot: (
110
device: HostDevice,
96
- ) => Effect.Effect<string, DeviceOperationError | DeviceBootError>;
111
+ context?: DeviceOpenContext,
112
+ ) => Effect.Effect<string, DeviceOperationError | DeviceBootError | DeviceHostUnavailableError>;
113
/** Prepares the stream of a device that is already booted. */
114
readonly attach: (device: HostDevice) => Effect.Effect<void, DeviceOperationError>;
115
readonly shutdown: (device: {
@@ -101,6 +117,22 @@ export interface DeviceOperations {
117
readonly platform: DevicePlatform;
118
}) => Effect.Effect<void, DeviceOperationError>;
119
readonly screenshot: (device: HostDevice) => Effect.Effect<Uint8Array, DeviceOperationError>;
120
+ /**
121
+ * For hosts that run one agent-device daemon per device instead of one per
122
+ * host. `agentDeviceId` is the id agent-device selects the device by, when
123
+ * it differs from the host's device id.
124
+ */
125
+ readonly agentEndpoint?: (
126
+ deviceId: string,
127
+ ) => Effect.Effect<
128
+ AgentDaemonEndpoint & { readonly agentDeviceId: string },
129
+ DeviceHostUnavailableError
130
+ >;
131
+ /**
132
+ * Set by hosts that end devices on their own (EAS stops sessions at their
133
+ * limits), so a session on a device the host stops listing is dropped.
134
+ */
135
+ readonly endsDevices?: boolean;
136
}
137
138
export interface DeviceHostReady {
@@ -116,16 +148,24 @@ export interface DeviceHostReady {
148
readonly serveSimAxSettings: string | null;
149
readonly serveSimCli: string | null;
150
};
151
+ /** Routes proxied hub requests itself; otherwise they go to `hub.origin`. */
152
+ readonly upstream?: (
153
+ hubPath: string,
154
+ search: URLSearchParams,
155
+ ) => Effect.Effect<HubUpstream | null>;
156
}
157
158
export interface DeviceHostAgentReady extends DeviceHostReady {
122
- readonly agentDevice: AgentDeviceEndpoint;
159
+ /** Null when each device has its own daemon; see `DeviceOperations.agentEndpoint`. */
160
+ readonly agentDevice: AgentDeviceEndpoint | null;
161
}
162
163
export class DeviceHost extends Context.Service<
164
DeviceHost,
165
{
166
readonly id: DeviceHostId;
167
+ /** The name errors and the Device panel show for this host. */
168
+ readonly label: string;
169
readonly summary: Effect.Effect<DeviceHostSummary>;
170
readonly inspect?: Effect.Effect<DeviceHostSummary, DeviceHostError>;
171
readonly platformAvailability: (
apps/server/src/device/DeviceHubProxy.test.ts
+44
-2
@@ -10,6 +10,7 @@ import * as Effect from "effect/Effect";
10
import * as Layer from "effect/Layer";
11
import { HttpClient, HttpClientResponse, HttpRouter } from "effect/http";
12
import * as EnvironmentAuth from "../auth/EnvironmentAuth.ts";
13
+import type * as DeviceHost from "./DeviceHost.ts";
14
import * as DeviceService from "./DeviceService.ts";
15
import * as DeviceHubProxy from "./DeviceHubProxy.ts";
16
@@ -22,6 +23,7 @@ const fixture = (
23
scopes: ReadonlyArray<AuthEnvironmentScope>,
24
fail = false,
25
authError?: EnvironmentAuth.ServerAuthCredentialError | EnvironmentAuth.ServerAuthInternalError,
26
+ upstream?: DeviceHost.DeviceHostReady["upstream"],
27
) => {
28
let finalized = 0;
29
const requests: string[] = [];
@@ -34,7 +36,10 @@ const fixture = (
36
finalized++;
37
});
38
if (fail) return yield* Effect.die(new Error("upstream failed"));
37
- return HttpClientResponse.fromWeb(request, new Response("frame"));
39
+ return HttpClientResponse.fromWeb(
40
+ request,
41
+ new Response("frame", { headers: { "set-cookie": "upstream=1" } }),
42
+ );
43
}),
44
);
45
const { handler, dispose } = HttpRouter.toWebHandler(
@@ -55,7 +60,11 @@ const fixture = (
60
Layer.provideMerge(
61
Layer.succeed(DeviceService.DeviceService, {
62
currentReadiness: () =>
58
- Effect.succeed({ hostId: LOCAL_DEVICE_HOST_ID, hub: { origin: "http://hub.test" } }),
63
+ Effect.succeed({
64
+ hostId: LOCAL_DEVICE_HOST_ID,
65
+ hub: { origin: "http://hub.test" },
66
+ ...(upstream ? { upstream } : {}),
67
+ }),
68
} as DeviceService.DeviceService["Service"]),
69
),
70
Layer.provideMerge(Layer.succeed(HttpClient.HttpClient, client)),
@@ -167,6 +176,39 @@ describe("device hub proxy", () => {
176
expect(headers[0]?.["content-type"]).toBe("application/json");
177
});
178
179
+ it("sends requests a host routes itself to its upstream with its credentials", async () => {
180
+ const { handler, requests, headers } = fixture(
181
+ [AuthOrchestrationReadScope],
182
+ false,
183
+ undefined,
184
+ (hubPath, search) =>
185
+ Effect.succeed(
186
+ hubPath === "/vendor/serve-sim/api"
187
+ ? {
188
+ url: `https://session.test${hubPath.slice("/vendor/serve-sim".length)}?${search}`,
189
+ headers: { authorization: "Bearer session-token" },
190
+ protocols: [],
191
+ }
192
+ : null,
193
+ ),
194
+ );
195
+ const routed = await handler(
196
+ new Request("http://t3.test/api/device-hub/vendor/serve-sim/api?device=udid-1&hostId=eas", {
197
+ headers: { authorization: "Bearer environment-token" },
198
+ }),
199
+ );
200
+ expect(routed.status).toBe(200);
201
+ expect(routed.headers.get("set-cookie")).toBeNull();
202
+ await routed.text();
203
+ expect(requests).toEqual(["https://session.test/api?device=udid-1"]);
204
+ expect(headers[0]?.authorization).toBe("Bearer session-token");
205
+ const unrouted = await handler(
206
+ new Request("http://t3.test/api/device-hub/vendor/serve-sim/helper/udid-2/stream.mjpeg"),
207
+ );
208
+ expect(unrouted.status).toBe(404);
209
+ expect(requests).toHaveLength(1);
210
+ });
211
+
212
it("never forwards the vendor shell endpoint", async () => {
213
const { handler, requests } = fixture([AuthOrchestrationOperateScope]);
214
expect(
apps/server/src/device/DeviceHubProxy.ts
+22
-9
@@ -83,10 +83,12 @@ const forwardHeaders = (request: HttpServerRequest.HttpServerRequest, origin: st
83
const proxyWebSocket = Effect.fn("DeviceHubProxy.proxyWebSocket")(function* (
84
request: HttpServerRequest.HttpServerRequest,
85
upstreamUrl: string,
86
+ protocols: ReadonlyArray<string> = [],
87
) {
88
const client = yield* request.upgrade;
89
const upstream = yield* Socket.makeWebSocket(upstreamUrl, {
90
openTimeout: "10 seconds",
91
+ ...(protocols.length > 0 ? { protocols: [...protocols] } : {}),
92
}).pipe(Effect.provide(NodeSocket.layerWebSocketConstructor));
93
yield* Effect.scoped(
94
Effect.gen(function* () {
@@ -115,12 +117,15 @@ const pumpFrames =
117
const proxyHttp = Effect.fn("DeviceHubProxy.proxyHttp")(function* (
118
request: HttpServerRequest.HttpServerRequest,
119
upstreamUrl: string,
118
- hubOrigin: string,
120
+ extraHeaders: Readonly<Record<string, string>> = {},
121
) {
122
const httpClient = HttpClient.withScope(yield* HttpClient.HttpClient);
123
const method = request.method;
124
const upstreamRequest = HttpClientRequest.make(method)(upstreamUrl).pipe(
123
- HttpClientRequest.setHeaders(forwardHeaders(request, hubOrigin)),
125
+ HttpClientRequest.setHeaders({
126
+ ...forwardHeaders(request, new URL(upstreamUrl).origin),
127
+ ...extraHeaders,
128
+ }),
129
method === "GET" || method === "HEAD"
130
? (self) => self
131
: // A bare stream body is sent as octet-stream; serve-sim refuses WebRTC
@@ -132,7 +137,13 @@ const proxyHttp = Effect.fn("DeviceHubProxy.proxyHttp")(function* (
137
const response = yield* httpClient.execute(upstreamRequest);
138
const headers: Record<string, string> = {};
139
for (const [name, value] of Object.entries(response.headers)) {
135
- if (name === "content-encoding" || name === "transfer-encoding" || name === "connection") {
140
+ // A cookie from an upstream such as an EAS session's preview host would land on T3's origin.
141
+ if (
142
+ name === "content-encoding" ||
143
+ name === "transfer-encoding" ||
144
+ name === "connection" ||
145
+ name === "set-cookie"
146
+ ) {
147
continue;
148
}
149
if (value !== undefined) headers[name] = value;
@@ -183,14 +194,16 @@ const handler = Effect.gen(function* () {
194
upstreamSearch.delete("wsTicket");
195
upstreamSearch.delete("hostId");
196
const search = upstreamSearch.size > 0 ? `?${upstreamSearch.toString()}` : "";
186
- const upstreamPath = `${hubPath}${search}`;
197
+ // Hosts with several upstreams (one per cloud session) route and authenticate requests themselves.
198
+ const routed = ready.upstream ? yield* ready.upstream(hubPath, upstreamSearch) : undefined;
199
+ if (routed === null) {
200
+ return HttpServerResponse.text("Not Found", { status: 404 });
201
+ }
202
+ const upstreamUrl = routed?.url ?? `${ready.hub.origin}${hubPath}${search}`;
203
if (upgrade) {
188
- return yield* proxyWebSocket(
189
- request,
190
- `${ready.hub.origin.replace(/^http/, "ws")}${upstreamPath}`,
191
- );
204
+ return yield* proxyWebSocket(request, upstreamUrl.replace(/^http/, "ws"), routed?.protocols);
205
}
193
- return yield* proxyHttp(request, `${ready.hub.origin}${upstreamPath}`, ready.hub.origin);
206
+ return yield* proxyHttp(request, upstreamUrl, routed?.headers);
207
});
208
209
export const layer = HttpRouter.add("*", `${DeviceService.DEVICE_HUB_ROUTE_PREFIX}/*`, handler);
apps/server/src/device/DeviceMultiHost.test.ts
+1
@@ -55,6 +55,7 @@ it.effect("keeps hosts independent when serials collide and another host fails",
55
};
56
return {
57
id,
58
+ label: id,
59
summary: Effect.succeed({
60
id,
61
label: id,
apps/server/src/device/DeviceService.test.ts
+52
-7
@@ -89,6 +89,7 @@ const fixture = Effect.fn("fixture")(function* (
89
| DeviceHost.AgentDeviceStartError,
90
inspectError = false,
91
installTool?: Parameters<typeof DeviceService.makeWithHosts>[3],
92
+ options: { readonly endsDevices?: boolean } = {},
93
) {
94
const settings = yield* Ref.make(DEFAULT_SERVER_SETTINGS);
95
const starts: string[] = [];
@@ -160,13 +161,16 @@ const fixture = Effect.fn("fixture")(function* (
161
const ready: DeviceHost.DeviceHostReady = {
162
nodePath: process.execPath,
163
hub: { origin: "http://device.test" },
163
- devices: makeDeviceHubOperations({
164
- hostId: LOCAL_DEVICE_HOST_ID,
165
- origin: "http://device.test",
166
- http,
167
- run,
168
- androidAvailable: Effect.succeed(true),
169
- }),
164
+ devices: {
165
+ ...makeDeviceHubOperations({
166
+ hostId: LOCAL_DEVICE_HOST_ID,
167
+ origin: "http://device.test",
168
+ http,
169
+ run,
170
+ androidAvailable: Effect.succeed(true),
171
+ }),
172
+ ...(options.endsDevices ? { endsDevices: true } : {}),
173
+ },
174
helpers: { serveSimAxSettings: null, serveSimCli: null },
175
run,
176
};
@@ -183,6 +187,7 @@ const fixture = Effect.fn("fixture")(function* (
187
}
188
: {}),
189
id: LOCAL_DEVICE_HOST_ID,
190
+ label: "This machine",
191
summary: Effect.succeed({
192
id: LOCAL_DEVICE_HOST_ID,
193
kind: "local",
@@ -251,6 +256,10 @@ const fixture = Effect.fn("fixture")(function* (
256
}),
257
),
258
);
259
+ // The host ending a device on its own, as EAS does at a session's limits.
260
+ const endDevice = () => {
261
+ booted = false;
262
+ };
263
return {
264
service,
265
starts,
@@ -261,6 +270,7 @@ const fixture = Effect.fn("fixture")(function* (
270
devices,
271
encoderResult,
272
discoveryErrors,
273
+ endDevice,
274
};
275
});
276
@@ -509,6 +519,36 @@ it.effect("publishes boot progress and does not restore sessions after support i
519
}).pipe(Effect.scoped),
520
);
521
522
+it.effect.each([
523
+ { case: "drops it on a host that ends devices itself", endsDevices: true, kept: 0 },
524
+ {
525
+ case: "keeps it on a host that can miss a device for one listing",
526
+ endsDevices: false,
527
+ kept: 1,
528
+ },
529
+])("when a host stops listing a session's device, $case", ({ endsDevices, kept }) =>
530
+ Effect.gen(function* () {
531
+ const { service, endDevice } = yield* fixture(
532
+ Effect.void,
533
+ undefined,
534
+ false,
535
+ undefined,
536
+ false,
537
+ undefined,
538
+ { endsDevices },
539
+ );
540
+ yield* service.configure({ enabled: true });
541
+ const threadId = ThreadId.make("ended-by-host");
542
+ yield* service.open({ threadId, deviceId: "Pixel_API_35", platform: "android" });
543
+ expect((yield* service.state).sessions.map((session) => session.deviceId)).toEqual([
544
+ "emulator-5554",
545
+ ]);
546
+ endDevice();
547
+ yield* service.list;
548
+ expect((yield* service.state).sessions).toHaveLength(kept);
549
+ }).pipe(Effect.scoped),
550
+);
551
+
552
describe("device discovery after server restart", () => {
553
it.effect("captures an explicit device before any client lists devices", () =>
554
Effect.gen(function* () {
@@ -718,6 +758,7 @@ it.effect.each(["shutdown", "close"] as const)(
758
};
759
const host: DeviceHost.DeviceHost["Service"] = {
760
id: LOCAL_DEVICE_HOST_ID,
761
+ label: "This machine",
762
summary: Effect.succeed({
763
id: LOCAL_DEVICE_HOST_ID,
764
kind: "local",
@@ -816,6 +857,7 @@ it.effect.each([
857
};
858
const host: DeviceHost.DeviceHost["Service"] = {
859
id: LOCAL_DEVICE_HOST_ID,
860
+ label: "This machine",
861
summary: Effect.succeed({
862
id: LOCAL_DEVICE_HOST_ID,
863
kind: "local",
@@ -887,6 +929,7 @@ it.effect.each([LOCAL_DEVICE_HOST_ID, "ssh-fixture"])(
929
};
930
const host: DeviceHost.DeviceHost["Service"] = {
931
id: hostId,
932
+ label: "Test device host",
933
summary: Effect.succeed({
934
id: hostId,
935
kind: hostId === LOCAL_DEVICE_HOST_ID ? "local" : "ssh",
@@ -1167,6 +1210,7 @@ it.effect("reconciles SSH host settings without publishing no-op changes", () =>
1210
const removedFiles: string[] = [];
1211
const localHost: DeviceHost.DeviceHost["Service"] = {
1212
id: LOCAL_DEVICE_HOST_ID,
1213
+ label: "This machine",
1214
summary: Effect.succeed({
1215
id: LOCAL_DEVICE_HOST_ID,
1216
label: "Local",
@@ -1270,6 +1314,7 @@ it.effect("a failed tool update reports npm's exit code but not its output", ()
1314
Effect.gen(function* () {
1315
const host: DeviceHost.DeviceHost["Service"] = {
1316
id: LOCAL_DEVICE_HOST_ID,
1317
+ label: "This machine",
1318
summary: Effect.succeed({
1319
id: LOCAL_DEVICE_HOST_ID,
1320
kind: "local",
apps/server/src/device/DeviceService.ts
+198
-124
@@ -22,6 +22,7 @@ import {
22
type SshDeviceHostConfig,
23
type DeviceHostSummary,
24
LOCAL_DEVICE_HOST_ID,
25
+ LOCAL_DEVICE_HOST_LABEL,
26
type ThreadId,
27
} from "@t3tools/contracts";
28
import { SshCommandError } from "@t3tools/ssh/errors";
@@ -53,6 +54,7 @@ import { readDeviceDetail, runDeviceAction } from "./DeviceActions.ts";
54
import * as ProcessRunner from "../processRunner.ts";
55
import * as DeviceHost from "./DeviceHost.ts";
56
import * as SshDeviceHost from "./SshDeviceHost.ts";
57
+import * as EasDeviceHost from "./EasDeviceHost.ts";
58
import * as Exit from "effect/Exit";
59
import * as LocalDeviceHost from "./LocalDeviceHost.ts";
60
@@ -90,7 +92,8 @@ export interface DeviceReadiness extends DeviceHost.DeviceHostReady {
92
}
93
94
export interface DeviceAgentReadiness extends DeviceReadiness {
93
- readonly agentDevice: DeviceHost.AgentDeviceEndpoint;
95
+ /** Null when each device has its own daemon; see `DeviceOperations.agentEndpoint`. */
96
+ readonly agentDevice: DeviceHost.AgentDeviceEndpoint | null;
97
}
98
99
export class DeviceService extends Context.Service<
@@ -100,11 +103,18 @@ export class DeviceService extends Context.Service<
103
readonly testHost: (
104
config: SshDeviceHostConfig,
105
) => Effect.Effect<DeviceHostSummary, DeviceError>;
106
+ /**
107
+ * The agent-device flags that reach the device: its config and session,
108
+ * and the id agent-device selects it by, which can differ from its id here.
109
+ */
110
readonly agentTarget: (input: {
111
threadId: ThreadId;
112
hostId: DeviceHostId;
113
deviceId: DeviceId;
107
- }) => Effect.Effect<ReadonlyArray<string>, DeviceError>;
114
+ }) => Effect.Effect<
115
+ { readonly agentDeviceId: string; readonly args: ReadonlyArray<string> },
116
+ DeviceError
117
+ >;
118
readonly state: Effect.Effect<DeviceServiceState>;
119
readonly subscribe: Effect.Effect<PubSub.Subscription<DeviceServiceState>, never, Scope.Scope>;
120
readonly configure: (
@@ -114,7 +124,10 @@ export class DeviceService extends Context.Service<
124
readonly updateTool: (tool: "hub" | "agent") => Effect.Effect<DeviceServiceState, DeviceError>;
125
readonly inspect: Effect.Effect<DeviceServiceState>;
126
readonly retryHost: (hostId: DeviceHostId) => Effect.Effect<DeviceServiceState, DeviceError>;
117
- readonly open: (input: DeviceOpenInput) => Effect.Effect<DeviceSession, DeviceError>;
127
+ readonly open: (
128
+ input: DeviceOpenInput,
129
+ context?: DeviceHost.DeviceOpenContext,
130
+ ) => Effect.Effect<DeviceSession, DeviceError>;
131
readonly close: (input: DeviceCloseInput) => Effect.Effect<void, DeviceError>;
132
readonly shutdown: (input: DeviceShutdownInput) => Effect.Effect<void, DeviceError>;
133
readonly detail: (input: DeviceDetailInput) => Effect.Effect<DeviceDetail, DeviceError>;
@@ -145,12 +158,14 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
158
Effect.fail(
159
new DeviceHostUnavailableError({
160
hostId: host.id,
161
+ hostLabel: host.label,
162
reason: "SSH probing is unavailable in this device service.",
163
}),
164
),
165
configureAgent: (
166
hostId: DeviceHostId,
153
- ready: DeviceHost.DeviceHostAgentReady,
167
+ endpoint: DeviceHost.AgentDaemonEndpoint,
168
+ deviceId?: DeviceId,
169
) => Effect.Effect<string, DeviceError> = (hostId) =>
170
Effect.fail(
171
new DeviceHostUnavailableError({
@@ -243,6 +258,7 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
258
if (!(yield* readDeviceSettings).enabled) {
259
return yield* new DeviceHostUnavailableError({
260
hostId: host.id,
261
+ hostLabel: host.label,
262
reason:
263
"Device support is off. Enable it in the Device panel before installing or starting device tools.",
264
});
@@ -265,6 +281,7 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
281
(error) =>
282
new DeviceHostUnavailableError({
283
hostId: host.id,
284
+ hostLabel: host.label,
285
reason:
286
error._tag === "NodeRuntimeUnavailableError"
287
? nodeRuntimeUnavailableMessage("Local device support")
@@ -278,6 +295,7 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
295
if (hosts.get(host.id) !== host)
296
return yield* new DeviceHostUnavailableError({
297
hostId: host.id,
298
+ hostLabel: host.label,
299
reason: "Host configuration changed. Retry the operation.",
300
});
301
const { state } = yield* SynchronizedRef.get(stateRef);
@@ -326,6 +344,7 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
344
(error) =>
345
new DeviceHostUnavailableError({
346
hostId: host.id,
347
+ hostLabel: host.label,
348
reason:
349
error._tag === "NodeRuntimeUnavailableError"
350
? nodeRuntimeUnavailableMessage("Local device support")
@@ -365,6 +384,11 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
384
385
const refresh = Effect.fn("DeviceService.refresh")(function* (ready: DeviceReadiness) {
386
const host = hosts.get(ready.hostId);
387
+ // A session opened while the listing ran is on a device the listing could
388
+ // not have seen yet; only sessions from before it can be pruned by it.
389
+ const sessionKey = (session: DeviceSession) =>
390
+ `${session.hostId}\u0000${session.deviceId}\u0000${session.threadId}\u0000${session.openedAt}`;
391
+ const before = new Set((yield* SynchronizedRef.get(stateRef)).state.sessions.map(sessionKey));
392
const { devices, detail, androidDiscoveryIncomplete } = yield* fetchDevices(ready);
393
const hostSummaries = yield* Effect.forEach(hosts.values(), (host) => host.summary);
394
return yield* lifecycleLock.withPermit(
@@ -379,6 +403,17 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
403
...state.devices.filter((device) => device.hostId !== ready.hostId),
404
...devices,
405
],
406
+ // A host that ends devices itself (EAS stops sessions at their limits)
407
+ // leaves sessions on devices it no longer lists with nothing to stream.
408
+ // Other hosts can miss a device for one listing, so theirs stay.
409
+ sessions: ready.devices.endsDevices
410
+ ? state.sessions.filter(
411
+ (session) =>
412
+ session.hostId !== ready.hostId ||
413
+ !before.has(sessionKey(session)) ||
414
+ devices.some((device) => device.id === session.deviceId),
415
+ )
416
+ : state.sessions,
417
hostStatuses: {
418
...state.hostStatuses,
419
[ready.hostId]: {
@@ -538,109 +573,113 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
573
}
574
});
575
541
- const open: DeviceService["Service"]["open"] = Effect.fn("DeviceService.open")(function* (input) {
542
- const host = yield* resolveHost(input.hostId);
543
- yield* ensurePlatform(host, input.platform);
544
- const ready = yield* readiness(host.id);
545
- let state = yield* refresh(ready);
546
- let device = findDevice(state, host.id, input.deviceId);
547
- if (!device) {
548
- return yield* new DeviceNotFoundError({ hostId: host.id, deviceId: input.deviceId });
549
- }
550
- if (device.platform === "android" && !device.physical) {
551
- // Resolve the override on the device host the way its hub does.
552
- const encoders = yield* ready.run(ready.nodePath, [
553
- "-e",
554
- `const { spawnSync } = require("node:child_process");
555
-const result = spawnSync(process.env.SERVE_EMU_FFMPEG?.trim() || "ffmpeg", ["-hide_banner", "-encoders"], {
556
- stdio: "inherit", timeout: 10000, killSignal: "SIGKILL",
557
-});
558
-process.exitCode = result.error ? 1 : (result.status ?? 1);`,
559
- ]);
560
- if (encoders.code !== 0) {
561
- return yield* new DevicePlatformUnavailableError({
562
- hostId: host.id,
563
- platform: "android",
564
- reason:
565
- "Android emulator video needs working ffmpeg with the libx264 encoder. Install it on the device host's PATH or set SERVE_EMU_FFMPEG there, then retry opening the emulator. After changing PATH or SERVE_EMU_FFMPEG, turn device support off and on for SSH hosts, or restart the local environment server.",
566
- });
567
- }
568
- if (!/^\s*V\S*[ \t]+libx264(?:[ \t]|$)/m.test(`${encoders.stdout}\n${encoders.stderr}`)) {
569
- return yield* new DevicePlatformUnavailableError({
570
- hostId: host.id,
571
- platform: "android",
572
- reason:
573
- "Android emulator video needs the libx264 encoder. Install an ffmpeg build that includes libx264 on the device host, then retry opening the emulator. After changing PATH or SERVE_EMU_FFMPEG, turn device support off and on for SSH hosts, or restart the local environment server.",
574
- });
575
- }
576
- }
577
- if (!device.booted && input.boot !== false) {
578
- const booting = { ...device, threadId: input.threadId };
579
- yield* publish((current) => ({
580
- ...current,
581
- bootingDevices: [
582
- ...(current.bootingDevices ?? []).filter(
583
- (entry) => entry.hostId !== booting.hostId || entry.id !== booting.id,
584
- ),
585
- booting,
586
- ],
587
- }));
588
- const bootedId = yield* ready.devices.boot(device).pipe(
589
- Effect.ensuring(
590
- publish((current) => ({
591
- ...current,
592
- bootingDevices: (current.bootingDevices ?? []).filter(
593
- (entry) => entry.hostId !== booting.hostId || entry.id !== booting.id,
594
- ),
595
- })),
596
- ),
597
- );
598
- state = yield* refresh(ready);
599
- device = findDevice(state, host.id, bootedId) ?? findDevice(state, host.id, device.id);
576
+ const open: DeviceService["Service"]["open"] = Effect.fn("DeviceService.open")(
577
+ function* (input, context) {
578
+ const host = yield* resolveHost(input.hostId);
579
+ yield* ensurePlatform(host, input.platform);
580
+ const ready = yield* readiness(host.id);
581
+ let state = yield* refresh(ready);
582
+ let device = findDevice(state, host.id, input.deviceId);
583
if (!device) {
601
- return yield* new DeviceNotFoundError({ hostId: host.id, deviceId: bootedId });
584
+ return yield* new DeviceNotFoundError({ hostId: host.id, deviceId: input.deviceId });
585
}
603
- } else if (device.booted) {
604
- yield* ready.devices.attach(device);
605
- }
606
- if (hosts.get(host.id) !== host)
607
- return yield* new DeviceHostUnavailableError({
608
- hostId: host.id,
609
- reason: "Host configuration changed. Retry the operation.",
610
- });
611
- const openedAt = DateTime.formatIso(yield* DateTime.now);
612
- const session: DeviceSession = {
613
- threadId: input.threadId,
614
- hostId: host.id,
615
- deviceId: device.id,
616
- platform: device.platform,
617
- openedAt,
618
- };
619
- yield* lifecycleLock.withPermit(
620
- Effect.gen(function* () {
621
- if (!(yield* readDeviceSettings).enabled)
622
- return yield* new DeviceHostUnavailableError({
586
+ if (device.platform === "android" && !device.physical) {
587
+ // Resolve the override on the device host the way its hub does.
588
+ const encoders = yield* ready.run(ready.nodePath, [
589
+ "-e",
590
+ `const { spawnSync } = require("node:child_process");
591
+ const result = spawnSync(process.env.SERVE_EMU_FFMPEG?.trim() || "ffmpeg", ["-hide_banner", "-encoders"], {
592
+ stdio: "inherit", timeout: 10000, killSignal: "SIGKILL",
593
+ });
594
+ process.exitCode = result.error ? 1 : (result.status ?? 1);`,
595
+ ]);
596
+ if (encoders.code !== 0) {
597
+ return yield* new DevicePlatformUnavailableError({
598
hostId: host.id,
624
- reason: "Device support was turned off while the device was opening.",
599
+ platform: "android",
600
+ reason:
601
+ "Android emulator video needs working ffmpeg with the libx264 encoder. Install it on the device host's PATH or set SERVE_EMU_FFMPEG there, then retry opening the emulator. After changing PATH or SERVE_EMU_FFMPEG, turn device support off and on for SSH hosts, or restart the local environment server.",
602
});
603
+ }
604
+ if (!/^\s*V\S*[ \t]+libx264(?:[ \t]|$)/m.test(`${encoders.stdout}\n${encoders.stderr}`)) {
605
+ return yield* new DevicePlatformUnavailableError({
606
+ hostId: host.id,
607
+ platform: "android",
608
+ reason:
609
+ "Android emulator video needs the libx264 encoder. Install an ffmpeg build that includes libx264 on the device host, then retry opening the emulator. After changing PATH or SERVE_EMU_FFMPEG, turn device support off and on for SSH hosts, or restart the local environment server.",
610
+ });
611
+ }
612
+ }
613
+ if (!device.booted && input.boot !== false) {
614
+ const booting = { ...device, threadId: input.threadId };
615
yield* publish((current) => ({
616
...current,
628
- sessions: [
629
- ...current.sessions.filter(
630
- (existing) =>
631
- !(
632
- existing.threadId === session.threadId &&
633
- existing.hostId === session.hostId &&
634
- existing.deviceId === session.deviceId
635
- ),
617
+ bootingDevices: [
618
+ ...(current.bootingDevices ?? []).filter(
619
+ (entry) => entry.hostId !== booting.hostId || entry.id !== booting.id,
620
),
637
- session,
621
+ booting,
622
],
623
}));
640
- }),
641
- );
642
- return session;
643
- });
624
+ const bootedId = yield* ready.devices.boot(device, context).pipe(
625
+ Effect.ensuring(
626
+ publish((current) => ({
627
+ ...current,
628
+ bootingDevices: (current.bootingDevices ?? []).filter(
629
+ (entry) => entry.hostId !== booting.hostId || entry.id !== booting.id,
630
+ ),
631
+ })),
632
+ ),
633
+ );
634
+ state = yield* refresh(ready);
635
+ device = findDevice(state, host.id, bootedId) ?? findDevice(state, host.id, device.id);
636
+ if (!device) {
637
+ return yield* new DeviceNotFoundError({ hostId: host.id, deviceId: bootedId });
638
+ }
639
+ } else if (device.booted) {
640
+ yield* ready.devices.attach(device);
641
+ }
642
+ if (hosts.get(host.id) !== host)
643
+ return yield* new DeviceHostUnavailableError({
644
+ hostId: host.id,
645
+ hostLabel: host.label,
646
+ reason: "Host configuration changed. Retry the operation.",
647
+ });
648
+ const openedAt = DateTime.formatIso(yield* DateTime.now);
649
+ const session: DeviceSession = {
650
+ threadId: input.threadId,
651
+ hostId: host.id,
652
+ deviceId: device.id,
653
+ platform: device.platform,
654
+ openedAt,
655
+ };
656
+ yield* lifecycleLock.withPermit(
657
+ Effect.gen(function* () {
658
+ if (!(yield* readDeviceSettings).enabled)
659
+ return yield* new DeviceHostUnavailableError({
660
+ hostId: host.id,
661
+ hostLabel: host.label,
662
+ reason: "Device support was turned off while the device was opening.",
663
+ });
664
+ yield* publish((current) => ({
665
+ ...current,
666
+ sessions: [
667
+ ...current.sessions.filter(
668
+ (existing) =>
669
+ !(
670
+ existing.threadId === session.threadId &&
671
+ existing.hostId === session.hostId &&
672
+ existing.deviceId === session.deviceId
673
+ ),
674
+ ),
675
+ session,
676
+ ],
677
+ }));
678
+ }),
679
+ );
680
+ return session;
681
+ },
682
+ );
683
684
const shutdownDevice = Effect.fn("DeviceService.shutdownDevice")(function* (
685
hostId: DeviceHostId,
@@ -782,18 +821,36 @@ process.exitCode = result.error ? 1 : (result.status ?? 1);`,
821
const ready = yield* agentReadinessIfSupported(input.hostId);
822
if (!ready)
823
return yield* new DeviceHostUnavailableError({
785
- hostId: input.hostId,
824
+ hostId: host.id,
825
+ hostLabel: host.label,
826
reason:
827
"Agent device access requires enabled device support, agent access, and an available simulator platform on this host.",
828
});
789
- const configPath = yield* lifecycleLock.withPermit(
829
+ const { configPath, agentDeviceId } = yield* lifecycleLock.withPermit(
830
Effect.gen(function* () {
831
if (hosts.get(host.id) !== host)
832
return yield* new DeviceHostUnavailableError({
833
hostId: host.id,
834
+ hostLabel: host.label,
835
reason: "Host configuration changed. Retry the operation.",
836
});
796
- return yield* configureAgent(input.hostId, ready);
837
+ if (ready.devices.agentEndpoint) {
838
+ const endpoint = yield* ready.devices.agentEndpoint(input.deviceId);
839
+ return {
840
+ configPath: yield* configureAgent(input.hostId, endpoint, input.deviceId),
841
+ agentDeviceId: endpoint.agentDeviceId,
842
+ };
843
+ }
844
+ if (!ready.agentDevice)
845
+ return yield* new DeviceHostUnavailableError({
846
+ hostId: host.id,
847
+ hostLabel: host.label,
848
+ reason: "This host has no agent-device daemon.",
849
+ });
850
+ return {
851
+ configPath: yield* configureAgent(input.hostId, ready.agentDevice),
852
+ agentDeviceId: input.deviceId,
853
+ };
854
}),
855
);
856
const session = yield* agentDeviceSession(
@@ -801,7 +858,7 @@ process.exitCode = result.error ? 1 : (result.status ?? 1);`,
858
input.hostId,
859
input.deviceId,
860
).pipe(Effect.provideService(Crypto.Crypto, crypto));
804
- return ["--config", configPath, "--session", session];
861
+ return { agentDeviceId, args: ["--config", configPath, "--session", session] };
862
}),
863
state: SynchronizedRef.get(stateRef).pipe(Effect.map(({ state }) => state)),
864
subscribe: PubSub.subscribe(statePubSub),
@@ -853,14 +910,18 @@ export const make = Effect.gen(function* () {
910
[localHost.id, localHost],
911
]);
912
const crypto = yield* Crypto.Crypto;
856
- const configPath = (hostId: DeviceHostId) =>
857
- agentDeviceConfigPath(config.stateDir, hostId, path).pipe(
913
+ const configPath = (hostId: DeviceHostId, deviceId?: DeviceId) =>
914
+ agentDeviceConfigPath(config.stateDir, hostId, path, deviceId).pipe(
915
Effect.provideService(Crypto.Crypto, crypto),
916
);
917
const configureAgent = Effect.fn("DeviceService.configureAgent")(
861
- function* (hostId: DeviceHostId, ready: DeviceHost.DeviceHostAgentReady) {
862
- const file = yield* configPath(hostId);
863
- yield* writeAgentDeviceConfig(file, ready.agentDevice);
918
+ function* (
919
+ hostId: DeviceHostId,
920
+ endpoint: DeviceHost.AgentDaemonEndpoint,
921
+ deviceId?: DeviceId,
922
+ ) {
923
+ const file = yield* configPath(hostId, deviceId);
924
+ yield* writeAgentDeviceConfig(file, endpoint);
925
return file;
926
},
927
Effect.provideService(FileSystem.FileSystem, fs),
@@ -916,28 +977,27 @@ export const make = Effect.gen(function* () {
977
);
978
const hostContext =
979
yield* Effect.context<Effect.Services<ReturnType<typeof SshDeviceHost.make>>>();
919
- const configured = new Map<string, { config: SshDeviceHostConfig; scope: Scope.Closeable }>();
980
+ const easContext =
981
+ yield* Effect.context<Effect.Services<ReturnType<typeof EasDeviceHost.make>>>();
982
+ const configured = new Map<string, { config: DeviceHostConfig; scope: Scope.Closeable }>();
983
+ const unchanged = (current: DeviceHostConfig, previous: DeviceHostConfig) =>
984
+ current.kind === "ssh" && previous.kind === "ssh"
985
+ ? current.label === previous.label &&
986
+ current.target === previous.target &&
987
+ current.port === previous.port &&
988
+ current.identityFile === previous.identityFile
989
+ : JSON.stringify(current) === JSON.stringify(previous);
990
const reconcile = Effect.fn("DeviceService.reconcile")(function* (
991
configuredHosts: ReadonlyArray<DeviceHostConfig>,
992
) {
923
- const next = yield* remoteSshDeviceHosts(
924
- configuredHosts.filter((host): host is SshDeviceHostConfig => host.kind === "ssh"),
925
- ).pipe(Effect.provide(localTargetContext));
993
+ const next = yield* remoteSshDeviceHosts(configuredHosts).pipe(
994
+ Effect.provide(localTargetContext),
995
+ );
996
const removed = yield* service.withLifecycleLock(
997
Effect.gen(function* () {
998
const removed: Array<{ id: string; scope: Scope.Closeable }> = [];
999
for (const [id, previous] of configured) {
930
- if (
931
- next.some(
932
- (host) =>
933
- host.id === id &&
934
- host.label === previous.config.label &&
935
- host.target === previous.config.target &&
936
- host.port === previous.config.port &&
937
- host.identityFile === previous.config.identityFile,
938
- )
939
- )
940
- continue;
1000
+ if (next.some((host) => host.id === id && unchanged(host, previous.config))) continue;
1001
hosts.delete(id);
1002
configured.delete(id);
1003
removed.push({ id, scope: previous.scope });
@@ -963,11 +1023,24 @@ export const make = Effect.gen(function* () {
1023
if (configured.has(host.id)) continue;
1024
added = true;
1025
const hostScope = yield* Scope.fork(scope);
1026
+ if (host.kind === "eas") {
1027
+ // Closing this scope stops the host's running sessions, so a changed
1028
+ // limit or token never leaves a billed session behind.
1029
+ const instance = yield* EasDeviceHost.make(host).pipe(
1030
+ Effect.provideService(Scope.Scope, hostScope),
1031
+ Effect.provide(easContext),
1032
+ );
1033
+ hosts.set(host.id, instance);
1034
+ configured.set(host.id, { config: host, scope: hostScope });
1035
+ continue;
1036
+ }
1037
const instance = yield* SshDeviceHost.make(
1038
host,
1039
(ready) =>
969
- configureAgent(host.id, ready).pipe(
970
- Effect.asVoid,
1040
+ (ready.agentDevice
1041
+ ? configureAgent(host.id, ready.agentDevice).pipe(Effect.asVoid)
1042
+ : Effect.void
1043
+ ).pipe(
1044
Effect.mapError(
1045
(error) =>
1046
new DeviceHost.DeviceHostError({
@@ -1022,6 +1095,7 @@ export const make = Effect.gen(function* () {
1095
error._tag === "NodeRuntimeUnavailableError"
1096
? new DeviceHostUnavailableError({
1097
hostId: LOCAL_DEVICE_HOST_ID,
1098
+ hostLabel: LOCAL_DEVICE_HOST_LABEL,
1099
reason: nodeRuntimeUnavailableMessage("Device automation"),
1100
cause: error,
1101
})
apps/server/src/device/EasDeviceHost.test.ts
new
+907
@@ -0,0 +1,907 @@
1
+import { describe, expect, it } from "@effect/vitest";
2
+import * as NodeServices from "@effect/platform-node/NodeServices";
3
+import type { EasDeviceHostConfig } from "@t3tools/contracts";
4
+import * as Deferred from "effect/Deferred";
5
+import * as Effect from "effect/Effect";
6
+import * as Fiber from "effect/Fiber";
7
+import * as Exit from "effect/Exit";
8
+import * as FileSystem from "effect/FileSystem";
9
+import * as Layer from "effect/Layer";
10
+import * as Path from "effect/Path";
11
+import * as Scope from "effect/Scope";
12
+import * as TestClock from "effect/testing/TestClock";
13
+import { HttpClient, HttpClientResponse } from "effect/http";
14
+
15
+import * as ServerConfig from "../config.ts";
16
+import * as ProcessRunner from "../processRunner.ts";
17
+import * as EasDeviceHost from "./EasDeviceHost.ts";
18
+
19
+const APP_ID = "d763fcb8-d37c-41ea-a773-b54a0ab4a454";
20
+
21
+const config = (overrides: Partial<EasDeviceHostConfig> = {}): EasDeviceHostConfig => ({
22
+ kind: "eas",
23
+ id: "eas",
24
+ label: "EAS Simulator",
25
+ appId: APP_ID,
26
+ accessToken: "expo-token",
27
+ maxSessionMinutes: 25,
28
+ idleMinutes: 5,
29
+ maxConcurrentSessions: 2,
30
+ ...overrides,
31
+});
32
+
33
+interface Gate {
34
+ readonly requested: Deferred.Deferred<void>;
35
+ readonly release: Deferred.Deferred<void>;
36
+}
37
+const makeGate = Effect.all({
38
+ requested: Deferred.make<void>(),
39
+ release: Deferred.make<void>(),
40
+});
41
+
42
+/** Expo's API and one session's preview host, recording what was asked of them. */
43
+const fakeExpo = (
44
+ options: {
45
+ readonly status?: () => string;
46
+ readonly failCreate?: boolean;
47
+ /** Expo answers the create with GraphQL errors: a refusal. */
48
+ readonly rejectCreate?: boolean;
49
+ readonly failStop?: () => boolean;
50
+ readonly failList?: () => boolean;
51
+ readonly active?: ReadonlyArray<{ id: string; status: string; name: string }>;
52
+ readonly previewGate?: Gate;
53
+ readonly createGate?: Gate;
54
+ /** Holds the first session read it answers with a gate. */
55
+ readonly sessionGate?: () => Gate | undefined;
56
+ readonly activeIncludesCreated?: boolean;
57
+ readonly failPreview?: boolean;
58
+ readonly omitCreatedFromActive?: boolean;
59
+ } = {},
60
+) => {
61
+ const calls: Array<{ operation: string; variables: Record<string, unknown> }> = [];
62
+ let created = 0;
63
+ let createdName = "";
64
+ let previewFails = options.failPreview ?? false;
65
+ let createFails = options.failCreate ?? false;
66
+ let sessionGated = false;
67
+ const http = HttpClient.make((request) =>
68
+ Effect.gen(function* () {
69
+ const url = new URL(request.url);
70
+ if (url.origin === "https://preview.test") {
71
+ expect(request.headers.authorization).toBe("Bearer preview-token");
72
+ if (options.previewGate) {
73
+ yield* Deferred.succeed(options.previewGate.requested, undefined);
74
+ yield* Deferred.await(options.previewGate.release);
75
+ }
76
+ if (previewFails) {
77
+ return HttpClientResponse.fromWeb(request, new Response("bad gateway", { status: 502 }));
78
+ }
79
+ return HttpClientResponse.fromWeb(request, Response.json({ device: "UDID-1" }));
80
+ }
81
+ const body =
82
+ request.body._tag === "Uint8Array"
83
+ ? (JSON.parse(new TextDecoder().decode(request.body.body)) as {
84
+ query: string;
85
+ variables: Record<string, { name?: string } & Record<string, unknown>>;
86
+ })
87
+ : { query: "", variables: {} };
88
+ expect(request.headers.authorization).toBe("Bearer expo-token");
89
+ const operation = /(?:query|mutation) (\w+)/.exec(body.query)?.[1] ?? "unknown";
90
+ calls.push({ operation, variables: body.variables });
91
+ if (operation === "T3CreateEasSimulatorSession") {
92
+ createdName = body.variables.input?.name ?? "";
93
+ if (options.createGate) {
94
+ yield* Deferred.succeed(options.createGate.requested, undefined);
95
+ yield* Deferred.await(options.createGate.release);
96
+ }
97
+ if (createFails)
98
+ return HttpClientResponse.fromWeb(request, new Response("bad gateway", { status: 502 }));
99
+ if (options.rejectCreate)
100
+ return HttpClientResponse.fromWeb(
101
+ request,
102
+ Response.json({ errors: [{ message: "Not allowed" }] }),
103
+ );
104
+ }
105
+ if (operation === "T3StopEasSimulatorSession" && options.failStop?.()) {
106
+ return HttpClientResponse.fromWeb(request, new Response("bad gateway", { status: 502 }));
107
+ }
108
+ if (operation === "T3ActiveEasSimulatorSessions" && options.failList?.()) {
109
+ return HttpClientResponse.fromWeb(request, new Response("bad gateway", { status: 502 }));
110
+ }
111
+ const sessionGate =
112
+ operation === "T3EasSimulatorSession" ? options.sessionGate?.() : undefined;
113
+ if (sessionGate && !sessionGated) {
114
+ sessionGated = true;
115
+ yield* Deferred.succeed(sessionGate.requested, undefined);
116
+ yield* Deferred.await(sessionGate.release);
117
+ }
118
+ const data =
119
+ operation === "T3EasSimulatorAvailability"
120
+ ? {
121
+ app: {
122
+ byId: {
123
+ ownerAccount: {
124
+ name: "pingdotgg",
125
+ accountFeatureGates: { "device-run-sessions": true },
126
+ },
127
+ },
128
+ },
129
+ }
130
+ : operation === "T3CreateEasSimulatorSession"
131
+ ? { deviceRunSession: { createDeviceRunSession: { id: `session-${++created}` } } }
132
+ : operation === "T3ActiveEasSimulatorSessions"
133
+ ? {
134
+ app: {
135
+ byId: {
136
+ deviceRunSessionsPaginated: {
137
+ edges: [
138
+ ...(options.omitCreatedFromActive
139
+ ? []
140
+ : [{ node: { id: "orphan", status: "NEW", name: createdName } }]),
141
+ {
142
+ node: {
143
+ id: "someone-else",
144
+ status: "IN_PROGRESS",
145
+ name: "T3 Code · EAS Simulator · 000000",
146
+ },
147
+ },
148
+ ...(options.active ?? []).map((node) => ({ node })),
149
+ ...(options.activeIncludesCreated && created > 0
150
+ ? [
151
+ {
152
+ node: {
153
+ id: `session-${created}`,
154
+ status: "STARTING",
155
+ name: createdName,
156
+ },
157
+ },
158
+ ]
159
+ : []),
160
+ ],
161
+ },
162
+ },
163
+ },
164
+ }
165
+ : operation === "T3EasSimulatorSession"
166
+ ? {
167
+ deviceRunSessions: {
168
+ byId: {
169
+ id: body.variables.id,
170
+ status: options.status?.() ?? "IN_PROGRESS",
171
+ remoteConfig: {
172
+ __typename: "AgentDeviceRunSessionRemoteConfig",
173
+ agentDeviceRemoteSessionUrl: "https://agent.test",
174
+ agentDeviceRemoteSessionToken: "agent-token",
175
+ webPreviewToken: "preview-token",
176
+ previewApiUrl: "https://preview.test?token=preview-token",
177
+ },
178
+ },
179
+ },
180
+ }
181
+ : {
182
+ deviceRunSession: {
183
+ ensureDeviceRunSessionStopped: { id: body.variables.id, status: "STOPPED" },
184
+ },
185
+ };
186
+ return HttpClientResponse.fromWeb(request, Response.json({ data }));
187
+ }),
188
+ );
189
+ const named = (operation: string) => calls.filter((call) => call.operation === operation);
190
+ const stopped = () => named("T3StopEasSimulatorSession").map((call) => call.variables.id);
191
+ const allowPreview = () => {
192
+ previewFails = false;
193
+ };
194
+ const allowCreate = () => {
195
+ createFails = false;
196
+ };
197
+ return { http, named, stopped, allowPreview, allowCreate };
198
+};
199
+
200
+const layer = Layer.mergeAll(
201
+ ProcessRunner.layer,
202
+ ServerConfig.layerTest(process.cwd(), { prefix: "t3-eas-host-" }),
203
+).pipe(Layer.provideMerge(NodeServices.layer));
204
+
205
+const makeHost = (
206
+ expo: ReturnType<typeof fakeExpo>,
207
+ hostConfig: EasDeviceHostConfig,
208
+ scope: Scope.Scope,
209
+) =>
210
+ EasDeviceHost.make(hostConfig).pipe(
211
+ Effect.provideService(HttpClient.HttpClient, expo.http),
212
+ Effect.provideService(Scope.Scope, scope),
213
+ );
214
+
215
+describe("EAS Simulator host", () => {
216
+ it.effect("starts a bounded session and routes its stream and agent to that session", () =>
217
+ Effect.gen(function* () {
218
+ const expo = fakeExpo();
219
+ const scope = yield* Scope.make();
220
+ const host = yield* makeHost(expo, config(), scope);
221
+ const ready = yield* host.ensureReady(() => Effect.void);
222
+ const catalog = (yield* ready.devices.list).devices;
223
+ expect(catalog.map((device) => [device.id, device.booted])).toEqual([["eas-ios", false]]);
224
+
225
+ expect(yield* ready.devices.boot(catalog[0]!)).toBe("session-1");
226
+ expect(expo.named("T3CreateEasSimulatorSession")[0]?.variables.input).toMatchObject({
227
+ appId: APP_ID,
228
+ platform: "IOS",
229
+ type: "AGENT_DEVICE",
230
+ maxRunTimeMinutes: 25,
231
+ maxIdleTimeMinutes: 5,
232
+ });
233
+ const listed = (yield* ready.devices.list).devices;
234
+ expect(listed.find((device) => device.id === "session-1")?.booted).toBe(true);
235
+ expect(yield* ready.devices.agentEndpoint!("session-1")).toEqual({
236
+ baseUrl: "https://agent.test",
237
+ token: "agent-token",
238
+ agentDeviceId: "UDID-1",
239
+ });
240
+
241
+ const routed = yield* ready.upstream!(
242
+ "/vendor/serve-sim/helper/session-1/webrtc/offer",
243
+ new URLSearchParams("hostId=eas"),
244
+ );
245
+ expect(routed).toEqual({
246
+ url: "https://preview.test/helper/UDID-1/webrtc/offer?hostId=eas",
247
+ headers: { authorization: "Bearer preview-token" },
248
+ protocols: ["serve-sim.token.preview-token"],
249
+ });
250
+ expect(
251
+ yield* ready.upstream!(
252
+ "/vendor/serve-sim/helper/ws",
253
+ new URLSearchParams("device=session-1"),
254
+ ),
255
+ ).toMatchObject({ url: "https://preview.test/helper/ws?device=UDID-1" });
256
+ expect(yield* ready.upstream!("/vendor/serve-emu/ws", new URLSearchParams())).toBeNull();
257
+ expect(
258
+ yield* ready.upstream!("/vendor/serve-sim/helper/%E0/config", new URLSearchParams()),
259
+ ).toBeNull();
260
+
261
+ yield* Scope.close(scope, Exit.void);
262
+ expect(expo.named("T3StopEasSimulatorSession").map((call) => call.variables.id)).toEqual([
263
+ "session-1",
264
+ ]);
265
+ }).pipe(Effect.scoped, Effect.provide(layer)),
266
+ );
267
+
268
+ it.effect("refuses to start past its session limit", () =>
269
+ Effect.gen(function* () {
270
+ const expo = fakeExpo();
271
+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
272
+ const ready = yield* host.ensureReady(() => Effect.void);
273
+ const [catalogDevice] = (yield* ready.devices.list).devices;
274
+ yield* ready.devices.boot(catalogDevice!);
275
+ const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
276
+ expect(refused.message).toBe(
277
+ "EAS Simulator is unavailable: EAS Simulator is limited to 1 running session. Close one in the Device panel first.",
278
+ );
279
+ expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(1);
280
+ }).pipe(Effect.scoped, Effect.provide(layer)),
281
+ );
282
+
283
+ it.effect("tells concurrent sessions apart although EAS gives each the same UDID", () =>
284
+ Effect.gen(function* () {
285
+ const expo = fakeExpo();
286
+ const scope = yield* Scope.make();
287
+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 2 }), scope);
288
+ const ready = yield* host.ensureReady(() => Effect.void);
289
+ const [catalogDevice] = (yield* ready.devices.list).devices;
290
+ expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");
291
+ expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-2");
292
+ expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual([
293
+ "eas-ios",
294
+ "session-1",
295
+ "session-2",
296
+ ]);
297
+ expect(
298
+ yield* ready.upstream!(
299
+ "/vendor/serve-sim/api",
300
+ new URLSearchParams("device=session-2&hostId=eas"),
301
+ ),
302
+ ).toMatchObject({ url: "https://preview.test/api?device=UDID-1&hostId=eas" });
303
+
304
+ yield* ready.devices.shutdown({ id: "session-1", platform: "ios" });
305
+ expect(expo.stopped()).toEqual(["session-1"]);
306
+ expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual([
307
+ "eas-ios",
308
+ "session-2",
309
+ ]);
310
+ yield* Scope.close(scope, Exit.void);
311
+ expect(expo.stopped()).toEqual(["session-1", "session-2"]);
312
+ }).pipe(Effect.scoped, Effect.provide(layer)),
313
+ );
314
+
315
+ it.effect("stops only the sessions a previous server recorded, found by name", () =>
316
+ Effect.gen(function* () {
317
+ const fs = yield* FileSystem.FileSystem;
318
+ const path = yield* Path.Path;
319
+ const server = yield* ServerConfig.ServerConfig;
320
+ const ledger = path.join(server.stateDir, "device", "eas", "eas.json");
321
+ yield* fs.makeDirectory(path.dirname(ledger), { recursive: true });
322
+ yield* fs.writeFileString(
323
+ ledger,
324
+ JSON.stringify([
325
+ { name: "T3 Code · EAS Simulator · left", appId: APP_ID, recordedAt: 0 },
326
+ // Recorded long enough ago that Expo has ended it, so the record goes.
327
+ { name: "T3 Code · EAS Simulator · gone", appId: APP_ID, recordedAt: -181 * 60_000 },
328
+ // Recorded just now and not listed yet: kept for a later sweep.
329
+ { name: "T3 Code · EAS Simulator · new", appId: APP_ID, recordedAt: 0 },
330
+ ]),
331
+ );
332
+ const expo = fakeExpo({
333
+ active: [
334
+ { id: "left-behind", status: "IN_PROGRESS", name: "T3 Code · EAS Simulator · left" },
335
+ ],
336
+ });
337
+ const host = yield* makeHost(expo, config(), yield* Scope.make());
338
+ yield* host.ensureReady(() => Effect.void);
339
+ // The sweep runs in the background, so readiness does not wait on Expo.
340
+ const ledgerNames = Effect.map(
341
+ Effect.flatMap(fs.readFileString(ledger), (text) =>
342
+ Effect.try(() => JSON.parse(text) as ReadonlyArray<{ name: string }>),
343
+ ),
344
+ (entries) => entries.map((entry) => entry.name),
345
+ );
346
+ yield* Effect.eventually(
347
+ Effect.flatMap(ledgerNames, (names) =>
348
+ names.length === 1 ? Effect.void : Effect.fail("not swept yet"),
349
+ ),
350
+ );
351
+ expect(expo.stopped()).toEqual(["left-behind"]);
352
+ expect(yield* ledgerNames).toEqual(["T3 Code · EAS Simulator · new"]);
353
+ }).pipe(Effect.scoped, Effect.provide(layer)),
354
+ );
355
+
356
+ it.effect("counts a fresh record a previous server left until Expo lists it or would have", () =>
357
+ Effect.gen(function* () {
358
+ const fs = yield* FileSystem.FileSystem;
359
+ const path = yield* Path.Path;
360
+ const server = yield* ServerConfig.ServerConfig;
361
+ const ledger = path.join(server.stateDir, "device", "eas", "eas.json");
362
+ yield* fs.makeDirectory(path.dirname(ledger), { recursive: true });
363
+ yield* fs.writeFileString(
364
+ ledger,
365
+ JSON.stringify([{ name: "T3 Code · EAS Simulator · new", appId: APP_ID, recordedAt: 0 }]),
366
+ );
367
+ const expo = fakeExpo();
368
+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
369
+ const ready = yield* host.ensureReady(() => Effect.void);
370
+ const [catalogDevice] = (yield* ready.devices.list).devices;
371
+ // The record is fresh and Expo does not list it yet: it holds the slot.
372
+ const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
373
+ expect(refused.message).toContain("still being cleaned up");
374
+ yield* TestClock.adjust("6 minutes");
375
+ yield* ready.devices.list;
376
+ expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");
377
+ }).pipe(Effect.scoped, Effect.provide(layer)),
378
+ );
379
+
380
+ it.effect("counts an old record a previous server left until a sweep stops its session", () =>
381
+ Effect.gen(function* () {
382
+ const fs = yield* FileSystem.FileSystem;
383
+ const path = yield* Path.Path;
384
+ const server = yield* ServerConfig.ServerConfig;
385
+ const ledger = path.join(server.stateDir, "device", "eas", "eas.json");
386
+ yield* fs.makeDirectory(path.dirname(ledger), { recursive: true });
387
+ yield* fs.writeFileString(
388
+ ledger,
389
+ JSON.stringify([
390
+ { name: "T3 Code · EAS Simulator · old", appId: APP_ID, recordedAt: -10 * 60_000 },
391
+ ]),
392
+ );
393
+ const expo = fakeExpo({
394
+ active: [
395
+ { id: "old-session", status: "IN_PROGRESS", name: "T3 Code · EAS Simulator · old" },
396
+ ],
397
+ });
398
+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
399
+ const ready = yield* host.ensureReady(() => Effect.void);
400
+ // Listing sweeps before anything starts, so the old session is stopped first.
401
+ const [catalogDevice] = (yield* ready.devices.list).devices;
402
+ expect(expo.stopped()).toContain("old-session");
403
+ expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");
404
+ }).pipe(Effect.scoped, Effect.provide(layer)),
405
+ );
406
+
407
+ it.effect("keeps an old record counted while the listing that would find it fails", () =>
408
+ Effect.gen(function* () {
409
+ const fs = yield* FileSystem.FileSystem;
410
+ const path = yield* Path.Path;
411
+ const server = yield* ServerConfig.ServerConfig;
412
+ const ledger = path.join(server.stateDir, "device", "eas", "eas.json");
413
+ yield* fs.makeDirectory(path.dirname(ledger), { recursive: true });
414
+ yield* fs.writeFileString(
415
+ ledger,
416
+ JSON.stringify([
417
+ { name: "T3 Code · EAS Simulator · old", appId: APP_ID, recordedAt: -10 * 60_000 },
418
+ ]),
419
+ );
420
+ let listFails = true;
421
+ const expo = fakeExpo({
422
+ active: [
423
+ { id: "old-session", status: "IN_PROGRESS", name: "T3 Code · EAS Simulator · old" },
424
+ ],
425
+ failList: () => listFails,
426
+ });
427
+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
428
+ const ready = yield* host.ensureReady(() => Effect.void);
429
+ const [catalogDevice] = (yield* ready.devices.list).devices;
430
+ // The sweep could not look, so the record still holds the slot.
431
+ const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
432
+ expect(refused.message).toContain("still being cleaned up");
433
+ listFails = false;
434
+ yield* ready.devices.list;
435
+ expect(expo.stopped()).toContain("old-session");
436
+ expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");
437
+ }).pipe(Effect.scoped, Effect.provide(layer)),
438
+ );
439
+
440
+ it.effect(
441
+ "frees the slot of a record Expo has ended by now, but keeps it until a listing confirms",
442
+ () =>
443
+ Effect.gen(function* () {
444
+ const fs = yield* FileSystem.FileSystem;
445
+ const path = yield* Path.Path;
446
+ const server = yield* ServerConfig.ServerConfig;
447
+ const ledger = path.join(server.stateDir, "device", "eas", "eas.json");
448
+ yield* fs.makeDirectory(path.dirname(ledger), { recursive: true });
449
+ yield* fs.writeFileString(
450
+ ledger,
451
+ JSON.stringify([
452
+ { name: "T3 Code · EAS Simulator · gone", appId: APP_ID, recordedAt: -181 * 60_000 },
453
+ {
454
+ name: "T3 Code · EAS Simulator · refused",
455
+ appId: APP_ID,
456
+ recordedAt: -181 * 60_000,
457
+ refused: true,
458
+ },
459
+ // No queue holds a session for a day: forgotten unconfirmed.
460
+ {
461
+ name: "T3 Code · EAS Simulator · ancient",
462
+ appId: APP_ID,
463
+ recordedAt: -25 * 60 * 60_000,
464
+ },
465
+ ]),
466
+ );
467
+ // The app is gone, say: listing it fails for good.
468
+ const expo = fakeExpo({ failList: () => true });
469
+ const host = yield* makeHost(
470
+ expo,
471
+ config({ maxConcurrentSessions: 1 }),
472
+ yield* Scope.make(),
473
+ );
474
+ const ready = yield* host.ensureReady(() => Effect.void);
475
+ const [catalogDevice] = (yield* ready.devices.list).devices;
476
+ expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");
477
+ const names = (JSON.parse(yield* fs.readFileString(ledger)) as Array<{ name: string }>).map(
478
+ (entry) => entry.name,
479
+ );
480
+ // The listing never confirmed the two: a queued session could still be
481
+ // running, so their records stay for the reaper.
482
+ expect(names.filter((name) => !/[0-9a-f]{6}$/.test(name))).toEqual([
483
+ "T3 Code · EAS Simulator · gone",
484
+ "T3 Code · EAS Simulator · refused",
485
+ ]);
486
+ }).pipe(Effect.scoped, Effect.provide(layer)),
487
+ );
488
+
489
+ it.effect(
490
+ "keeps a refused create's record for the reaper without counting it after a restart",
491
+ () =>
492
+ Effect.gen(function* () {
493
+ const fs = yield* FileSystem.FileSystem;
494
+ const path = yield* Path.Path;
495
+ const server = yield* ServerConfig.ServerConfig;
496
+ const ledger = path.join(server.stateDir, "device", "eas", "eas.json");
497
+ // Expo refuses the create and lists nothing.
498
+ const expo = fakeExpo({ rejectCreate: true, omitCreatedFromActive: true });
499
+ const first = yield* Scope.make();
500
+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), first);
501
+ const ready = yield* host.ensureReady(() => Effect.void);
502
+ const [catalogDevice] = (yield* ready.devices.list).devices;
503
+ yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
504
+ const entries = JSON.parse(yield* fs.readFileString(ledger)) as Array<{
505
+ refused?: boolean;
506
+ }>;
507
+ expect(entries.map((entry) => entry.refused)).toEqual([true]);
508
+ yield* Scope.close(first, Exit.void);
509
+ // A later server cannot even list the app: the record must not hold a slot.
510
+ const later = fakeExpo({ failList: () => true });
511
+ const restarted = yield* makeHost(
512
+ later,
513
+ config({ maxConcurrentSessions: 1 }),
514
+ yield* Scope.make(),
515
+ );
516
+ const readyAgain = yield* restarted.ensureReady(() => Effect.void);
517
+ const [device] = (yield* readyAgain.devices.list).devices;
518
+ expect(yield* readyAgain.devices.boot(device!)).toBe("session-1");
519
+ }).pipe(Effect.scoped, Effect.provide(layer)),
520
+ );
521
+
522
+ it.effect("leaves a replacement's session alone once its own scope has closed", () =>
523
+ Effect.gen(function* () {
524
+ // One Expo for both instances: they share the record and the account.
525
+ const expo = fakeExpo();
526
+ const first = yield* Scope.make();
527
+ const old = yield* makeHost(expo, config(), first);
528
+ const oldReady = yield* old.ensureReady(() => Effect.void);
529
+ const [catalogDevice] = (yield* oldReady.devices.list).devices;
530
+ expect(yield* oldReady.devices.boot(catalogDevice!)).toBe("session-1");
531
+ // Settings saved: the old instance goes, a replacement takes its id.
532
+ yield* Scope.close(first, Exit.void);
533
+ expect(expo.stopped()).toEqual(["session-1"]);
534
+ const replacement = yield* makeHost(expo, config(), yield* Scope.make());
535
+ const ready = yield* replacement.ensureReady(() => Effect.void);
536
+ const [device] = (yield* ready.devices.list).devices;
537
+ expect(yield* ready.devices.boot(device!)).toBe("session-2");
538
+ // A listing still running on the old instance must not sweep the new
539
+ // session, which it does not own but its replacement does.
540
+ yield* TestClock.adjust("2 minutes");
541
+ yield* oldReady.devices.list;
542
+ expect(expo.stopped()).toEqual(["session-1"]);
543
+ }).pipe(Effect.scoped, Effect.provide(layer)),
544
+ );
545
+
546
+ it.effect(
547
+ "does not sweep a replacement's session from a listing in flight when its scope closes",
548
+ () =>
549
+ Effect.gen(function* () {
550
+ const gate = yield* makeGate;
551
+ let armed = false;
552
+ const expo = fakeExpo({ sessionGate: () => (armed ? gate : undefined) });
553
+ const first = yield* Scope.make();
554
+ const old = yield* makeHost(expo, config(), first);
555
+ const oldReady = yield* old.ensureReady(() => Effect.void);
556
+ const [catalogDevice] = (yield* oldReady.devices.list).devices;
557
+ expect(yield* oldReady.devices.boot(catalogDevice!)).toBe("session-1");
558
+ // Long enough that the listing reads the session's status and a sweep is due.
559
+ yield* TestClock.adjust("2 minutes");
560
+ armed = true;
561
+ const listing = yield* oldReady.devices.list.pipe(Effect.forkChild);
562
+ yield* Deferred.await(gate.requested);
563
+ // Settings saved while the old listing waits on Expo.
564
+ yield* Scope.close(first, Exit.void);
565
+ const replacement = yield* makeHost(expo, config(), yield* Scope.make());
566
+ const ready = yield* replacement.ensureReady(() => Effect.void);
567
+ const [device] = (yield* ready.devices.list).devices;
568
+ expect(yield* ready.devices.boot(device!)).toBe("session-2");
569
+ yield* Deferred.succeed(gate.release, undefined);
570
+ yield* Fiber.join(listing);
571
+ expect(expo.stopped()).toEqual(["session-1"]);
572
+ }).pipe(Effect.scoped, Effect.provide(layer)),
573
+ );
574
+
575
+ it.effect("waits for a record write in flight before its scope closes", () =>
576
+ Effect.gen(function* () {
577
+ const fs = yield* FileSystem.FileSystem;
578
+ const gate = yield* makeGate;
579
+ let armed = false;
580
+ // The ledger read inside a write waits on the gate once armed.
581
+ const gatedFs: FileSystem.FileSystem = {
582
+ ...fs,
583
+ readFileString: (path, encoding) =>
584
+ Effect.gen(function* () {
585
+ if (armed && path.endsWith("eas.json")) {
586
+ armed = false;
587
+ yield* Deferred.succeed(gate.requested, undefined);
588
+ yield* Deferred.await(gate.release);
589
+ }
590
+ return yield* fs.readFileString(path, encoding);
591
+ }),
592
+ };
593
+ let status = "IN_PROGRESS";
594
+ // Nothing is listed, so the close's own sweep writes nothing: only the
595
+ // write in flight can hold the close.
596
+ const expo = fakeExpo({ status: () => status, omitCreatedFromActive: true });
597
+ const first = yield* Scope.make();
598
+ const old = yield* makeHost(expo, config(), first).pipe(
599
+ Effect.provideService(FileSystem.FileSystem, gatedFs),
600
+ );
601
+ const oldReady = yield* old.ensureReady(() => Effect.void);
602
+ const [catalogDevice] = (yield* oldReady.devices.list).devices;
603
+ expect(yield* oldReady.devices.boot(catalogDevice!)).toBe("session-1");
604
+ // Expo ended the session; the next listing forgets its record.
605
+ status = "STOPPED";
606
+ yield* TestClock.adjust("20 seconds");
607
+ armed = true;
608
+ const listing = yield* oldReady.devices.list.pipe(Effect.forkChild);
609
+ yield* Deferred.await(gate.requested);
610
+ // Settings saved while that write is in flight: closing waits for it.
611
+ const listingsBefore = expo.named("T3ActiveEasSimulatorSessions").length;
612
+ const closing = yield* Scope.close(first, Exit.void).pipe(Effect.forkChild);
613
+ // The close reads the record and lists sessions in real time: yield until
614
+ // its sweep has listed, then a good deal more, before looking at it.
615
+ while (expo.named("T3ActiveEasSimulatorSessions").length === listingsBefore) {
616
+ yield* Effect.yieldNow;
617
+ }
618
+ for (let i = 0; i < 200; i++) yield* Effect.yieldNow;
619
+ expect(closing.pollUnsafe()).toBeUndefined();
620
+ yield* Deferred.succeed(gate.release, undefined);
621
+ yield* Fiber.join(listing);
622
+ yield* Fiber.join(closing);
623
+ const replacement = yield* makeHost(expo, config(), yield* Scope.make());
624
+ const ready = yield* replacement.ensureReady(() => Effect.void);
625
+ const [device] = (yield* ready.devices.list).devices;
626
+ status = "IN_PROGRESS";
627
+ expect(yield* ready.devices.boot(device!)).toBe("session-2");
628
+ // The old write landed first, so the replacement's record is intact.
629
+ const path = yield* Path.Path;
630
+ const server = yield* ServerConfig.ServerConfig;
631
+ const entries = JSON.parse(
632
+ yield* fs.readFileString(path.join(server.stateDir, "device", "eas", "eas.json")),
633
+ ) as Array<{ name: string }>;
634
+ expect(entries).toHaveLength(1);
635
+ }).pipe(Effect.scoped, Effect.provide(layer)),
636
+ );
637
+
638
+ it.effect("keeps an old record whose session is listed but cannot be stopped", () =>
639
+ Effect.gen(function* () {
640
+ const fs = yield* FileSystem.FileSystem;
641
+ const path = yield* Path.Path;
642
+ const server = yield* ServerConfig.ServerConfig;
643
+ const ledger = path.join(server.stateDir, "device", "eas", "eas.json");
644
+ yield* fs.makeDirectory(path.dirname(ledger), { recursive: true });
645
+ yield* fs.writeFileString(
646
+ ledger,
647
+ JSON.stringify([
648
+ { name: "T3 Code · EAS Simulator · old", appId: APP_ID, recordedAt: -181 * 60_000 },
649
+ ]),
650
+ );
651
+ // Expo still lists it (queued for hours, say) and refuses to stop it.
652
+ const expo = fakeExpo({
653
+ active: [
654
+ { id: "old-session", status: "IN_PROGRESS", name: "T3 Code · EAS Simulator · old" },
655
+ ],
656
+ failStop: () => true,
657
+ });
658
+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
659
+ const ready = yield* host.ensureReady(() => Effect.void);
660
+ const [catalogDevice] = (yield* ready.devices.list).devices;
661
+ // Found and still running: its slot stays taken and its record stays.
662
+ const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
663
+ expect(refused.message).toContain("still being cleaned up");
664
+ const names = (JSON.parse(yield* fs.readFileString(ledger)) as Array<{ name: string }>).map(
665
+ (entry) => entry.name,
666
+ );
667
+ expect(names).toContain("T3 Code · EAS Simulator · old");
668
+ }).pipe(Effect.scoped, Effect.provide(layer)),
669
+ );
670
+
671
+ it.effect("stops the session a refused create made anyway", () =>
672
+ Effect.gen(function* () {
673
+ // Expo refuses the create but lists a session by its name.
674
+ const expo = fakeExpo({ rejectCreate: true });
675
+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
676
+ const ready = yield* host.ensureReady(() => Effect.void);
677
+ const [catalogDevice] = (yield* ready.devices.list).devices;
678
+ const failure = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
679
+ expect(failure.message).toContain("Not allowed");
680
+ expect(expo.stopped()).toEqual(["orphan"]);
681
+ }).pipe(Effect.scoped, Effect.provide(layer)),
682
+ );
683
+
684
+ it.effect("records a session before creating it and refuses to start without the record", () =>
685
+ Effect.gen(function* () {
686
+ const fs = yield* FileSystem.FileSystem;
687
+ const path = yield* Path.Path;
688
+ const server = yield* ServerConfig.ServerConfig;
689
+ // A directory where the ledger file should be: it can be neither read nor written.
690
+ yield* fs.makeDirectory(path.join(server.stateDir, "device", "eas", "eas.json"), {
691
+ recursive: true,
692
+ });
693
+ const expo = fakeExpo();
694
+ const host = yield* makeHost(expo, config(), yield* Scope.make());
695
+ const ready = yield* host.ensureReady(() => Effect.void);
696
+ const [catalogDevice] = (yield* ready.devices.list).devices;
697
+ const failure = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
698
+ expect(failure.message).toContain("could not be read");
699
+ expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(0);
700
+ }).pipe(Effect.scoped, Effect.provide(layer)),
701
+ );
702
+
703
+ it.effect("keeps a session tracked when the open that started it is interrupted", () =>
704
+ Effect.gen(function* () {
705
+ const createGate = yield* makeGate;
706
+ const expo = fakeExpo({ createGate });
707
+ const scope = yield* Scope.make();
708
+ const host = yield* makeHost(expo, config(), scope);
709
+ const ready = yield* host.ensureReady(() => Effect.void);
710
+ const [catalogDevice] = (yield* ready.devices.list).devices;
711
+ const opening = yield* ready.devices.boot(catalogDevice!).pipe(Effect.forkChild);
712
+ yield* Deferred.await(createGate.requested);
713
+ yield* Fiber.interrupt(opening);
714
+ yield* Deferred.succeed(createGate.release, undefined);
715
+ // The start goes on in the host and tracks its session.
716
+ yield* Effect.eventually(
717
+ ready.devices.list.pipe(
718
+ Effect.flatMap(({ devices }) =>
719
+ devices.some((device) => device.id === "session-1")
720
+ ? Effect.void
721
+ : Effect.fail("not tracked yet"),
722
+ ),
723
+ ),
724
+ );
725
+ yield* Scope.close(scope, Exit.void);
726
+ expect(expo.stopped()).toEqual(["session-1"]);
727
+ }).pipe(Effect.scoped, Effect.provide(layer)),
728
+ );
729
+
730
+ it.effect("keeps a session it could not stop counted, listed, and retried", () =>
731
+ Effect.gen(function* () {
732
+ let stopFails = true;
733
+ const expo = fakeExpo({ failStop: () => stopFails });
734
+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
735
+ const ready = yield* host.ensureReady(() => Effect.void);
736
+ const [catalogDevice] = (yield* ready.devices.list).devices;
737
+ yield* ready.devices.boot(catalogDevice!);
738
+ yield* ready.devices.shutdown({ id: "session-1", platform: "ios" }).pipe(Effect.flip);
739
+ expect((yield* ready.devices.list).devices.map((device) => device.id)).toContain("session-1");
740
+ const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
741
+ expect(refused.message).toContain("limited to 1 running session");
742
+ stopFails = false;
743
+ yield* ready.devices.list;
744
+ expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual(["eas-ios"]);
745
+ expect(expo.stopped().filter((id) => id === "session-1").length).toBeGreaterThanOrEqual(2);
746
+ }).pipe(Effect.scoped, Effect.provide(layer)),
747
+ );
748
+
749
+ it.effect("lets go of a stopping session Expo has ended although its stop keeps failing", () =>
750
+ Effect.gen(function* () {
751
+ let status = "IN_PROGRESS";
752
+ const expo = fakeExpo({ failStop: () => true, status: () => status });
753
+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
754
+ const ready = yield* host.ensureReady(() => Effect.void);
755
+ const [catalogDevice] = (yield* ready.devices.list).devices;
756
+ yield* ready.devices.boot(catalogDevice!);
757
+ yield* ready.devices.shutdown({ id: "session-1", platform: "ios" }).pipe(Effect.flip);
758
+ expect((yield* ready.devices.list).devices.map((device) => device.id)).toContain("session-1");
759
+ // Expo ended it by itself: the stop keeps failing, but the status says so.
760
+ status = "STOPPED";
761
+ expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual(["eas-ios"]);
762
+ status = "IN_PROGRESS";
763
+ expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-2");
764
+ }).pipe(Effect.scoped, Effect.provide(layer)),
765
+ );
766
+
767
+ it.effect("asks for an EAS project before starting anything when none can be found", () =>
768
+ Effect.gen(function* () {
769
+ const expo = fakeExpo();
770
+ const host = yield* makeHost(expo, config({ appId: undefined }), yield* Scope.make());
771
+ const ready = yield* host.ensureReady(() => Effect.void);
772
+ const [catalogDevice] = (yield* ready.devices.list).devices;
773
+ const failure = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
774
+ expect(failure.message).toContain("Choose one for this host in Settings");
775
+ expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(0);
776
+ }).pipe(Effect.scoped, Effect.provide(layer)),
777
+ );
778
+ it.effect("stops listing sessions Expo already ended", () =>
779
+ Effect.gen(function* () {
780
+ let status = "IN_PROGRESS";
781
+ const expo = fakeExpo({ status: () => status });
782
+ const host = yield* makeHost(expo, config(), yield* Scope.make());
783
+ const ready = yield* host.ensureReady(() => Effect.void);
784
+ const [catalogDevice] = (yield* ready.devices.list).devices;
785
+ yield* ready.devices.boot(catalogDevice!);
786
+ status = "STOPPED";
787
+ yield* TestClock.adjust("20 seconds");
788
+ expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual(["eas-ios"]);
789
+ expect(yield* ready.devices.agentEndpoint!("session-1").pipe(Effect.flip)).toMatchObject({
790
+ reason: "This EAS Simulator device is no longer running.",
791
+ });
792
+ }).pipe(Effect.scoped, Effect.provide(layer)),
793
+ );
794
+
795
+ it.effect("stops a session that is still starting when the host stops", () =>
796
+ Effect.gen(function* () {
797
+ const previewGate = yield* makeGate;
798
+ const expo = fakeExpo({ previewGate });
799
+ const host = yield* makeHost(expo, config(), yield* Scope.make());
800
+ const ready = yield* host.ensureReady(() => Effect.void);
801
+ const [catalogDevice] = (yield* ready.devices.list).devices;
802
+ const booting = yield* ready.devices.boot(catalogDevice!).pipe(Effect.forkChild);
803
+ yield* Deferred.await(previewGate.requested);
804
+ // Never released: stopping must not wait for the session to become ready.
805
+ yield* host.stop;
806
+ expect(expo.stopped()).toEqual(["session-1"]);
807
+ const failure = yield* Fiber.join(booting).pipe(Effect.flip);
808
+ expect(failure.message).toContain("was stopped while the session started");
809
+ expect((yield* ready.devices.list).devices.map((device) => device.id)).toEqual(["eas-ios"]);
810
+ }).pipe(Effect.scoped, Effect.provide(layer)),
811
+ );
812
+
813
+ it.effect("leaves a start in progress to its owner when the sweep runs", () =>
814
+ Effect.gen(function* () {
815
+ const previewGate = yield* makeGate;
816
+ // Expo lists the starting session by name, as it does while it boots.
817
+ const expo = fakeExpo({ previewGate, activeIncludesCreated: true });
818
+ const fs = yield* FileSystem.FileSystem;
819
+ const path = yield* Path.Path;
820
+ const server = yield* ServerConfig.ServerConfig;
821
+ const host = yield* makeHost(expo, config(), yield* Scope.make());
822
+ const ready = yield* host.ensureReady(() => Effect.void);
823
+ const [catalogDevice] = (yield* ready.devices.list).devices;
824
+ const booting = yield* ready.devices.boot(catalogDevice!).pipe(Effect.forkChild);
825
+ yield* Deferred.await(previewGate.requested);
826
+ yield* TestClock.adjust("61 seconds");
827
+ yield* ready.devices.list;
828
+ expect(expo.stopped()).toEqual([]);
829
+ const ledger = path.join(server.stateDir, "device", "eas", "eas.json");
830
+ expect(JSON.parse(yield* fs.readFileString(ledger))).toHaveLength(1);
831
+ yield* Deferred.succeed(previewGate.release, undefined);
832
+ expect(yield* Fiber.join(booting)).toBe("session-1");
833
+ }).pipe(Effect.scoped, Effect.provide(layer)),
834
+ );
835
+
836
+ it.effect("keeps a session counted when its start fails and stopping it fails too", () =>
837
+ Effect.gen(function* () {
838
+ let stopFails = true;
839
+ const expo = fakeExpo({ failPreview: true, failStop: () => stopFails });
840
+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
841
+ const ready = yield* host.ensureReady(() => Effect.void);
842
+ const [catalogDevice] = (yield* ready.devices.list).devices;
843
+ // The preview probe is retried a few seconds apart before the start gives up.
844
+ const failing = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip, Effect.forkChild);
845
+ while (failing.pollUnsafe() === undefined) yield* TestClock.adjust("1 second");
846
+ yield* Fiber.join(failing);
847
+ const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
848
+ expect(refused.message).toContain("still being cleaned up");
849
+ expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(1);
850
+ stopFails = false;
851
+ yield* ready.devices.list;
852
+ expect(expo.stopped().at(-1)).toBe("session-1");
853
+ expo.allowPreview();
854
+ expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-2");
855
+ }).pipe(Effect.scoped, Effect.provide(layer)),
856
+ );
857
+
858
+ it.effect("stops only its own session when creating one fails after Expo made it", () =>
859
+ Effect.gen(function* () {
860
+ const expo = fakeExpo({ failCreate: true });
861
+ const host = yield* makeHost(expo, config(), yield* Scope.make());
862
+ const ready = yield* host.ensureReady(() => Effect.void);
863
+ const [catalogDevice] = (yield* ready.devices.list).devices;
864
+ yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
865
+ expect(expo.stopped()).toEqual(["orphan"]);
866
+ }).pipe(Effect.scoped, Effect.provide(layer)),
867
+ );
868
+
869
+ it.effect("counts a create whose outcome is unknown against the limit, then frees it", () =>
870
+ Effect.gen(function* () {
871
+ // Create fails and the session is not listed yet, so the outcome is unknown.
872
+ const expo = fakeExpo({ failCreate: true, omitCreatedFromActive: true });
873
+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
874
+ const ready = yield* host.ensureReady(() => Effect.void);
875
+ const [catalogDevice] = (yield* ready.devices.list).devices;
876
+ yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
877
+ // The slot is held: Expo may have made the session.
878
+ const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
879
+ expect(refused.message).toContain("still being cleaned up");
880
+ expect(expo.named("T3CreateEasSimulatorSession")).toHaveLength(1);
881
+ // After Expo would have listed it, the slot frees and a new start runs.
882
+ yield* TestClock.adjust("6 minutes");
883
+ yield* ready.devices.list;
884
+ expo.allowCreate();
885
+ expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");
886
+ }).pipe(Effect.scoped, Effect.provide(layer)),
887
+ );
888
+
889
+ it.effect("holds the slot when a failed create’s session is listed but its stop fails", () =>
890
+ Effect.gen(function* () {
891
+ let stopFails = true;
892
+ // Create fails, Expo lists the session by name, and stopping it fails too.
893
+ const expo = fakeExpo({ failCreate: true, failStop: () => stopFails });
894
+ const host = yield* makeHost(expo, config({ maxConcurrentSessions: 1 }), yield* Scope.make());
895
+ const ready = yield* host.ensureReady(() => Effect.void);
896
+ const [catalogDevice] = (yield* ready.devices.list).devices;
897
+ yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
898
+ const refused = yield* ready.devices.boot(catalogDevice!).pipe(Effect.flip);
899
+ expect(refused.message).toContain("still being cleaned up");
900
+ stopFails = false;
901
+ yield* ready.devices.list;
902
+ expect(expo.stopped()).toContain("orphan");
903
+ expo.allowCreate();
904
+ expect(yield* ready.devices.boot(catalogDevice!)).toBe("session-1");
905
+ }).pipe(Effect.scoped, Effect.provide(layer)),
906
+ );
907
+});
apps/server/src/device/EasDeviceHost.ts
new
+875
@@ -0,0 +1,875 @@
1
+/**
2
+ * Cloud simulators from EAS Simulator. A device exists only while a session
3
+ * runs, and every session bills the Expo account until it stops, so this host
4
+ * bounds each one, stops all of them when it stops, and stops sessions a
5
+ * previous server left behind. It never touches sessions it did not start.
6
+ */
7
+import {
8
+ DeviceBootError,
9
+ type DeviceHostSummary,
10
+ DeviceHostUnavailableError,
11
+ DeviceOperationError,
12
+ type DevicePlatform,
13
+ type EasDeviceHostConfig,
14
+} from "@t3tools/contracts";
15
+import * as Cause from "effect/Cause";
16
+import * as Clock from "effect/Clock";
17
+import * as Duration from "effect/Duration";
18
+import * as Effect from "effect/Effect";
19
+import * as Exit from "effect/Exit";
20
+import * as Fiber from "effect/Fiber";
21
+import * as FiberSet from "effect/FiberSet";
22
+import * as FileSystem from "effect/FileSystem";
23
+import * as Option from "effect/Option";
24
+import * as Path from "effect/Path";
25
+import * as Random from "effect/Random";
26
+import * as Redacted from "effect/Redacted";
27
+import * as Schedule from "effect/Schedule";
28
+import * as Schema from "effect/Schema";
29
+import * as Semaphore from "effect/Semaphore";
30
+import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
31
+import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
32
+import * as HostProcess from "@t3tools/shared/HostProcess";
33
+
34
+import * as ServerConfig from "../config.ts";
35
+import * as DeviceHost from "./DeviceHost.ts";
36
+import { findEasProjectId } from "./easProjectId.ts";
37
+import { type ExpoApi, makeExpoApi, resolveExpoCredential } from "./ExpoApi.ts";
38
+
39
+const POLL_INTERVAL = Duration.seconds(5);
40
+// How stale a running session's status may get before listing rechecks it.
41
+const STATUS_TTL_MS = 15_000;
42
+// Expo's own CLI waits this long once a worker picks the session up.
43
+const START_TIMEOUT = Duration.minutes(15);
44
+const PREVIEW_TIMEOUT = Duration.seconds(20);
45
+const SERVE_SIM_PREFIX = "/vendor/serve-sim";
46
+
47
+/** EAS picks the simulator model; one entry starts a session. */
48
+const CATALOG: ReadonlyArray<DeviceHost.HostDevice> = [
49
+ {
50
+ id: "eas-ios",
51
+ platform: "ios",
52
+ name: "iPhone (EAS Simulator)",
53
+ version: "Cloud",
54
+ booted: false,
55
+ physical: false,
56
+ },
57
+];
58
+
59
+interface RunningSession {
60
+ readonly sessionId: string;
61
+ readonly name: string;
62
+ readonly udid: string;
63
+ readonly preview: { readonly origin: string; readonly token: Redacted.Redacted<string> };
64
+ readonly agent: DeviceHost.AgentDaemonEndpoint;
65
+ /** Set once a stop has been asked for but Expo has not confirmed it. */
66
+ stopping: boolean;
67
+}
68
+
69
+/**
70
+ * Every session this host may have started, recorded by its unique name before
71
+ * Expo is asked to create it, so a server that crashes at any point can still
72
+ * find and stop the session on its next start.
73
+ */
74
+const LedgerEntry = Schema.Struct({
75
+ name: Schema.String,
76
+ appId: Schema.String,
77
+ recordedAt: Schema.Number,
78
+ /** Expo refused the create: nothing should run, but the reaper still looks. */
79
+ refused: Schema.optional(Schema.Boolean),
80
+});
81
+type LedgerEntry = typeof LedgerEntry.Type;
82
+const Ledger = Schema.fromJsonString(Schema.Array(LedgerEntry));
83
+const decodeLedger = Schema.decodeUnknownEffect(Ledger);
84
+const encodeLedger = Schema.encodeSync(Ledger);
85
+// How often listing looks for recorded sessions this host no longer tracks.
86
+const REAP_INTERVAL_MS = 60_000;
87
+// Expo's longest session runs 115 minutes from when it is ready, plus five
88
+// minutes of cleanup. A recorded session Expo does not list (not showing
89
+// yet, or past the first page) stops counting against the limit after this
90
+// long, and its record is forgotten once a listing confirms it is not
91
+// running. Being ready can wait on Expo's queue, which has no bound, so the
92
+// record outlives the slot: only after a day is it forgotten unconfirmed.
93
+const RECORD_LIFETIME_MS = 180 * 60_000;
94
+const RECORD_MAX_AGE_MS = 24 * 60 * 60_000;
95
+// Expo lists a session it made within seconds; a create with an unknown
96
+// outcome stops counting against the limit once it has had this long.
97
+const UNCERTAIN_CREATE_MS = 5 * 60_000;
98
+// One failed request to Expo during a minutes-long start does not end the start.
99
+const TRANSIENT_RETRY = { times: 3, schedule: Schedule.spaced("2 seconds") } as const;
100
+const decodePreviewApi = Schema.decodeUnknownEffect(Schema.Struct({ device: Schema.String }));
101
+
102
+/** A malformed escape names no device, so the proxy answers 404 instead of failing. */
103
+const decodePathSegment = (segment: string): string | null => {
104
+ try {
105
+ return decodeURIComponent(segment);
106
+ } catch {
107
+ return null;
108
+ }
109
+};
110
+
111
+export const make = Effect.fn("EasDeviceHost.make")(function* (config: EasDeviceHostConfig) {
112
+ const http = yield* HttpClient.HttpClient;
113
+ const fs = yield* FileSystem.FileSystem;
114
+ const path = yield* Path.Path;
115
+ const server = yield* ServerConfig.ServerConfig;
116
+ const services = yield* Effect.context<
117
+ FileSystem.FileSystem | Path.Path | Effect.Services<ReturnType<typeof findEasProjectId>>
118
+ >();
119
+ const hostId = config.id;
120
+ const ledgerPath = path.join(server.stateDir, "device", "eas", `${hostId}.json`);
121
+ // Keyed by Expo's session id, which is also the device id: every EAS
122
+ // simulator reports the same UDID, so the UDID cannot tell sessions apart.
123
+ const sessions = new Map<string, RunningSession>();
124
+ const checkedAt = new Map<string, number>();
125
+ const startLock = yield* Semaphore.make(1);
126
+ const ledgerLock = yield* Semaphore.make(1);
127
+ // One sweep at a time: two would stop the same session twice.
128
+ const reapLock = yield* Semaphore.make(1);
129
+ // Starts run in the host rather than the caller: a client that disconnects
130
+ // while a session boots leaves it running and tracked, and stopping or
131
+ // closing the host interrupts the start, which then stops its session.
132
+ const starts = yield* FiberSet.make<string, unknown>();
133
+ // The startup sweep for recorded leftovers.
134
+ const background = yield* FiberSet.make<void, never>();
135
+ // Sessions this host owns that `sessions` does not hold: starts in progress,
136
+ // and sessions whose stop after a failed start failed too. The reaper leaves
137
+ // them alone and they count against the limit.
138
+ const starting = new Set<string>();
139
+ const unresolved = new Map<string, { readonly sessionId: string }>();
140
+ // Creates whose outcome is unknown (no answer, or a server error), and
141
+ // fresh records a previous server left: Expo may have made the session.
142
+ // Each listing looks for it, and it counts against the limit until found
143
+ // or until Expo would have listed it by now. The reaper handles these.
144
+ const uncertain = new Map<string, { readonly entry: LedgerEntry; readonly until: number }>();
145
+ const ownedNames = () =>
146
+ new Set([
147
+ ...[...sessions.values()].map((session) => session.name),
148
+ ...starting,
149
+ ...unresolved.keys(),
150
+ ]);
151
+ // Bumped whenever the host stops its sessions, so a start that finishes
152
+ // afterwards stops its own session instead of leaving it untracked.
153
+ let epoch = 0;
154
+ // Set once the host's scope closes. A listing still running on this
155
+ // instance then neither sweeps nor writes the ledger: a replacement with
156
+ // the same id owns the sessions and the record now.
157
+ let closed = false;
158
+ let reapedAt = 0;
159
+ let ready: DeviceHost.DeviceHostReady | null = null;
160
+
161
+ const unavailable = (reason: string, cause?: unknown) =>
162
+ new DeviceHostUnavailableError({
163
+ hostId,
164
+ hostLabel: config.label,
165
+ reason,
166
+ ...(cause === undefined ? {} : { cause }),
167
+ });
168
+
169
+ const api: Effect.Effect<ExpoApi, DeviceHostUnavailableError> = resolveExpoCredential(
170
+ config.accessToken,
171
+ ).pipe(
172
+ Effect.map((credential) => makeExpoApi(http, credential)),
173
+ Effect.provide(services),
174
+ Effect.mapError((error) => unavailable(error.message, error)),
175
+ );
176
+
177
+ /** A missing ledger is empty; an unreadable one is an error, never an empty list. */
178
+ const readLedger = fs.readFileString(ledgerPath).pipe(
179
+ Effect.catchIf(
180
+ (error) => error.reason._tag === "NotFound",
181
+ () => Effect.succeed("[]"),
182
+ ),
183
+ Effect.flatMap(decodeLedger),
184
+ Effect.mapError((cause) =>
185
+ unavailable(
186
+ `The record of running EAS sessions at ${ledgerPath} could not be read. Fix or remove it.`,
187
+ cause,
188
+ ),
189
+ ),
190
+ );
191
+ const writeLedger = Effect.fn("EasDeviceHost.writeLedger")(function* (
192
+ update: (entries: ReadonlyArray<LedgerEntry>) => ReadonlyArray<LedgerEntry>,
193
+ ) {
194
+ if (closed) return yield* unavailable(`${config.label} was replaced or removed.`);
195
+ const entries = update(yield* readLedger);
196
+ yield* writeFileStringAtomically({
197
+ filePath: ledgerPath,
198
+ contents: encodeLedger(entries),
199
+ }).pipe(
200
+ Effect.provide(services),
201
+ Effect.mapError((cause) =>
202
+ unavailable(
203
+ `The record of running EAS sessions at ${ledgerPath} could not be written.`,
204
+ cause,
205
+ ),
206
+ ),
207
+ );
208
+ }, ledgerLock.withPermit);
209
+ const markRefused = (name: string) =>
210
+ writeLedger((entries) =>
211
+ entries.map((entry) => (entry.name === name ? { ...entry, refused: true } : entry)),
212
+ ).pipe(
213
+ Effect.catch((cause) =>
214
+ Effect.logWarning("Could not update the EAS session record", { name, cause }),
215
+ ),
216
+ );
217
+ const forgetEntry = (name: string) =>
218
+ writeLedger((entries) => entries.filter((entry) => entry.name !== name)).pipe(
219
+ Effect.catch((cause) =>
220
+ Effect.logWarning("Could not update the EAS session record", { name, cause }),
221
+ ),
222
+ );
223
+
224
+ /** Stops a session and, once Expo confirms it, drops it from the ledger. */
225
+ const stopSession = (expo: ExpoApi, sessionId: string, name: string) =>
226
+ expo.stop(sessionId).pipe(
227
+ Effect.andThen(forgetEntry(name)),
228
+ Effect.tapError((cause) =>
229
+ Effect.logWarning("Could not stop EAS Simulator session", { sessionId, cause }),
230
+ ),
231
+ );
232
+
233
+ /** Finds recorded sessions by name, so a session whose id never arrived is found too. */
234
+ const stopRecorded = (expo: ExpoApi, entries: ReadonlyArray<LedgerEntry>) => {
235
+ const found = new Set<string>();
236
+ const listed = new Set<string>();
237
+ return Effect.forEach(
238
+ [...new Set(entries.map((entry) => entry.appId))],
239
+ (appId) =>
240
+ expo.activeSessions(appId).pipe(
241
+ Effect.flatMap((active) =>
242
+ Effect.forEach(
243
+ entries.filter((entry) => entry.appId === appId),
244
+ (entry) =>
245
+ Effect.gen(function* () {
246
+ const running = active.filter((session) => session.name === entry.name);
247
+ if (running.length > 0) {
248
+ found.add(entry.name);
249
+ return yield* Effect.forEach(
250
+ running,
251
+ (session) =>
252
+ stopSession(expo, session.id, entry.name).pipe(
253
+ // Still running and billed: owned, counted, and retried by listing.
254
+ Effect.catch(() =>
255
+ Effect.sync(
256
+ () => void unresolved.set(entry.name, { sessionId: session.id }),
257
+ ),
258
+ ),
259
+ ),
260
+ { discard: true },
261
+ );
262
+ }
263
+ }),
264
+ { discard: true },
265
+ ),
266
+ ),
267
+ Effect.tap(() => Effect.sync(() => void listed.add(appId))),
268
+ Effect.ignore,
269
+ ),
270
+ { discard: true, concurrency: 4 },
271
+ ).pipe(
272
+ Effect.as({ found, listed } as {
273
+ readonly found: ReadonlySet<string>;
274
+ /** The apps whose listing succeeded; a failed one rules nothing out. */
275
+ readonly listed: ReadonlySet<string>;
276
+ }),
277
+ );
278
+ };
279
+
280
+ /**
281
+ * Retries the stop of a session whose stop failed. A session Expo already
282
+ * ended is let go even if stopping it keeps failing.
283
+ */
284
+ const retryUnresolved = (expo: ExpoApi, name: string, sessionId: string) =>
285
+ stopSession(expo, sessionId, name).pipe(
286
+ Effect.catch(() =>
287
+ expo
288
+ .session(sessionId)
289
+ .pipe(
290
+ Effect.flatMap((current) =>
291
+ current.status === "STOPPED" || current.status === "ERRORED"
292
+ ? forgetEntry(name)
293
+ : Effect.fail(current.status),
294
+ ),
295
+ ),
296
+ ),
297
+ Effect.andThen(Effect.sync(() => void unresolved.delete(name))),
298
+ Effect.ignore,
299
+ );
300
+
301
+ /**
302
+ * Records a previous server left count against the limit until a sweep
303
+ * finds them (a fresh one until Expo would have listed it by now), so a
304
+ * restart cannot start past it.
305
+ */
306
+ const adoptRecorded = Effect.gen(function* () {
307
+ const now = yield* Clock.currentTimeMillis;
308
+ const owned = ownedNames();
309
+ for (const entry of yield* readLedger) {
310
+ const until = Math.max(entry.recordedAt + UNCERTAIN_CREATE_MS, now);
311
+ // A refused create made nothing: its record is for the reaper only.
312
+ if (!owned.has(entry.name) && !entry.refused) uncertain.set(entry.name, { entry, until });
313
+ }
314
+ }).pipe(Effect.ignore);
315
+
316
+ /**
317
+ * Stops recorded sessions this host does not own: a previous server's, or
318
+ * a failed or uncertain start's. An uncertain one found (stopped, or
319
+ * unresolved if that failed) or long enough unlisted frees its slot; its
320
+ * record stays until it expires.
321
+ */
322
+ const reapLeftovers = Effect.fn("EasDeviceHost.reapLeftovers")(
323
+ function* (expo: ExpoApi) {
324
+ if (closed) return;
325
+ reapedAt = yield* Clock.currentTimeMillis;
326
+ const entries = yield* readLedger;
327
+ const owned = ownedNames();
328
+ const leftovers = entries.filter((entry) => !owned.has(entry.name));
329
+ const { found, listed } = yield* stopRecorded(expo, leftovers);
330
+ for (const [name, { entry, until }] of uncertain) {
331
+ if (found.has(name) || (reapedAt >= until && listed.has(entry.appId))) {
332
+ uncertain.delete(name);
333
+ }
334
+ }
335
+ // Expo has ended these by now unless they waited in its queue: the slot
336
+ // goes whatever the listing says (the app may be gone, or belong to
337
+ // another account); the record goes once a listing confirms Expo does
338
+ // not run it, or once no queue could have held it.
339
+ for (const entry of leftovers) {
340
+ const age = reapedAt - entry.recordedAt;
341
+ if (age > RECORD_LIFETIME_MS) uncertain.delete(entry.name);
342
+ if (found.has(entry.name)) continue;
343
+ if ((age > RECORD_LIFETIME_MS && listed.has(entry.appId)) || age > RECORD_MAX_AGE_MS) {
344
+ yield* forgetEntry(entry.name);
345
+ }
346
+ }
347
+ },
348
+ reapLock.withPermit,
349
+ Effect.catch((cause) =>
350
+ Effect.logWarning("Could not stop recorded EAS Simulator sessions", { cause }),
351
+ ),
352
+ );
353
+
354
+ const previewDevice = (origin: string, token: Redacted.Redacted<string>) =>
355
+ http
356
+ .execute(
357
+ HttpClientRequest.get(`${origin}/api`).pipe(
358
+ HttpClientRequest.bearerToken(Redacted.value(token)),
359
+ ),
360
+ )
361
+ .pipe(
362
+ Effect.flatMap(HttpClientResponse.filterStatusOk),
363
+ Effect.flatMap((response) => response.json),
364
+ Effect.flatMap(decodePreviewApi),
365
+ Effect.map((api) => api.device),
366
+ Effect.scoped,
367
+ Effect.timeout(PREVIEW_TIMEOUT),
368
+ Effect.retry(TRANSIENT_RETRY),
369
+ );
370
+
371
+ const awaitRunning = Effect.fn("EasDeviceHost.awaitRunning")(
372
+ function* (expo: ExpoApi, sessionId: string) {
373
+ for (;;) {
374
+ const session = yield* expo.session(sessionId).pipe(
375
+ Effect.retry(TRANSIENT_RETRY),
376
+ Effect.mapError((error) => unavailable(error.message, error)),
377
+ );
378
+ if (session.status === "STOPPED" || session.status === "ERRORED") {
379
+ return yield* new DeviceBootError({
380
+ hostId,
381
+ deviceId: sessionId,
382
+ reason: "launch_failed",
383
+ cause: new Error(`EAS Simulator session ended (${session.status}) before it was ready`),
384
+ });
385
+ }
386
+ if (session.status === "IN_PROGRESS" && session.endpoints) return session.endpoints;
387
+ yield* Effect.sleep(POLL_INTERVAL);
388
+ }
389
+ },
390
+ (poll, _expo, sessionId) =>
391
+ poll.pipe(
392
+ Effect.timeoutOrElse({
393
+ duration: START_TIMEOUT,
394
+ orElse: () =>
395
+ Effect.fail(
396
+ new DeviceBootError({
397
+ hostId,
398
+ deviceId: sessionId,
399
+ reason: "timeout",
400
+ cause: new Error("EAS Simulator session did not start in time"),
401
+ }),
402
+ ),
403
+ }),
404
+ ),
405
+ );
406
+
407
+ const reserveSlot = (name: string) =>
408
+ startLock.withPermit(
409
+ Effect.suspend(() => {
410
+ const pending = unresolved.size + uncertain.size;
411
+ if (sessions.size + starting.size + pending >= config.maxConcurrentSessions) {
412
+ const limit = `${config.label} is limited to ${config.maxConcurrentSessions} running ${config.maxConcurrentSessions === 1 ? "session" : "sessions"}.`;
413
+ return Effect.fail(
414
+ unavailable(
415
+ pending > 0
416
+ ? `${limit} ${pending === 1 ? "A session" : `${pending} sessions`} that failed to start or stop ${pending === 1 ? "is" : "are"} still being cleaned up; try again shortly.`
417
+ : `${limit} Close one in the Device panel first.`,
418
+ ),
419
+ );
420
+ }
421
+ starting.add(name);
422
+ return Effect.void;
423
+ }),
424
+ );
425
+
426
+ const startSession = Effect.fn("EasDeviceHost.startSession")(function* (
427
+ device: DeviceHost.HostDevice,
428
+ context: DeviceHost.DeviceOpenContext | undefined,
429
+ startedIn: number,
430
+ ) {
431
+ const name = `T3 Code · ${config.label} · ${(yield* Random.nextIntBetween(0, 0xffffff)).toString(16).padStart(6, "0")}`;
432
+ // The credential comes first: without one, the answer is how to sign in,
433
+ // not that the limit is reached.
434
+ const expo = yield* api;
435
+ return yield* Effect.acquireUseRelease(
436
+ reserveSlot(name),
437
+ () =>
438
+ Effect.gen(function* () {
439
+ const appId =
440
+ config.appId ??
441
+ Option.getOrUndefined(
442
+ context?.workspaceRoot
443
+ ? yield* findEasProjectId(context.workspaceRoot).pipe(Effect.provide(services))
444
+ : Option.none<string>(),
445
+ );
446
+ if (!appId) {
447
+ return yield* unavailable(
448
+ "No EAS project to run the session under. Choose one for this host in Settings, or open the device from a thread whose project names extra.eas.projectId in app.json or its app config.",
449
+ );
450
+ }
451
+ const access = yield* expo
452
+ .availability(appId)
453
+ .pipe(Effect.mapError((error) => unavailable(error.message, error)));
454
+ if (!access.available) {
455
+ return yield* unavailable(
456
+ `EAS Simulator is not enabled for the ${access.account} Expo account.`,
457
+ );
458
+ }
459
+ const entry = { name, appId, recordedAt: yield* Clock.currentTimeMillis };
460
+ // Recorded first: a session the ledger cannot hold is never started.
461
+ yield* writeLedger((entries) => [...entries, entry]);
462
+ if (epoch !== startedIn) {
463
+ yield* forgetEntry(name);
464
+ return yield* unavailable(`${config.label} was stopped while the session started.`);
465
+ }
466
+ // Create runs uninterrupted (Expo's API answers within 30 seconds) and
467
+ // the stop below is in place before anything can interrupt the start,
468
+ // so a session Expo made is always either tracked or stopped.
469
+ return yield* Effect.uninterruptibleMask((restore) =>
470
+ Effect.gen(function* () {
471
+ const sessionId = yield* expo
472
+ .create({
473
+ appId,
474
+ platform: device.platform,
475
+ name,
476
+ maxRunTimeMinutes: config.maxSessionMinutes,
477
+ maxIdleTimeMinutes: config.idleMinutes,
478
+ })
479
+ .pipe(
480
+ // Unless Expo refused, it may have made the session before
481
+ // failing to answer. Unlisted, it stays counted for a while.
482
+ // Refused, it made nothing: the slot frees, but the record
483
+ // stays for the reaper in case the refusal was misread.
484
+ Effect.tapError((error) =>
485
+ error.rejected
486
+ ? stopRecorded(expo, [entry]).pipe(
487
+ Effect.flatMap(({ found }) =>
488
+ found.has(name) ? Effect.void : markRefused(name),
489
+ ),
490
+ )
491
+ : stopRecorded(expo, [entry]).pipe(
492
+ Effect.flatMap(({ found }) =>
493
+ found.has(name)
494
+ ? Effect.void
495
+ : Effect.map(Clock.currentTimeMillis, (now) => {
496
+ uncertain.set(name, {
497
+ entry,
498
+ until: now + UNCERTAIN_CREATE_MS,
499
+ });
500
+ }),
501
+ ),
502
+ ),
503
+ ),
504
+ Effect.mapError((error) => unavailable(error.message, error)),
505
+ );
506
+ return yield* restore(trackSession(expo, sessionId, name, startedIn)).pipe(
507
+ Effect.onError(() =>
508
+ stopSession(expo, sessionId, name).pipe(
509
+ // Still running and billed: owned, counted, and retried by listing.
510
+ Effect.catch(() => Effect.sync(() => void unresolved.set(name, { sessionId }))),
511
+ ),
512
+ ),
513
+ );
514
+ }),
515
+ );
516
+ }),
517
+ () => Effect.sync(() => void starting.delete(name)),
518
+ );
519
+ });
520
+
521
+ /** Waits for a created session and starts tracking it. */
522
+ const trackSession = Effect.fn("EasDeviceHost.trackSession")(function* (
523
+ expo: ExpoApi,
524
+ sessionId: string,
525
+ name: string,
526
+ startedIn: number,
527
+ ) {
528
+ const endpoints = yield* awaitRunning(expo, sessionId);
529
+ if (!endpoints.preview) {
530
+ return yield* new DeviceBootError({
531
+ hostId,
532
+ deviceId: sessionId,
533
+ reason: "launch_failed",
534
+ cause: new Error("EAS Simulator returned no preview endpoint"),
535
+ });
536
+ }
537
+ const origin = new URL(endpoints.preview.url).origin;
538
+ const udid = yield* previewDevice(origin, endpoints.preview.token).pipe(
539
+ Effect.mapError(
540
+ (cause) =>
541
+ new DeviceBootError({
542
+ hostId,
543
+ deviceId: sessionId,
544
+ reason: "launch_failed",
545
+ cause,
546
+ }),
547
+ ),
548
+ );
549
+ if (epoch !== startedIn) {
550
+ return yield* unavailable(`${config.label} was stopped while the session started.`);
551
+ }
552
+ sessions.set(sessionId, {
553
+ sessionId,
554
+ name,
555
+ udid,
556
+ preview: { origin, token: endpoints.preview.token },
557
+ agent: {
558
+ baseUrl: endpoints.agentDevice.url,
559
+ token: Redacted.value(endpoints.agentDevice.token),
560
+ },
561
+ stopping: false,
562
+ });
563
+ return sessionId;
564
+ });
565
+
566
+ const sessionFor = (deviceId: string) => Option.fromNullishOr(sessions.get(deviceId));
567
+
568
+ const forget = (session: RunningSession) =>
569
+ Effect.sync(() => {
570
+ sessions.delete(session.sessionId);
571
+ checkedAt.delete(session.sessionId);
572
+ });
573
+
574
+ /**
575
+ * Expo ends sessions on its own at their run or idle limit; stop listing
576
+ * those. A stop that failed earlier is retried, and recorded sessions nothing
577
+ * tracks are reaped now and then.
578
+ */
579
+ const dropEnded = Effect.gen(function* () {
580
+ if (closed) return;
581
+ const now = yield* Clock.currentTimeMillis;
582
+ const stale = [...sessions.values()].filter(
583
+ (session) =>
584
+ session.stopping || now - (checkedAt.get(session.sessionId) ?? 0) > STATUS_TTL_MS,
585
+ );
586
+ const reapDue = now - reapedAt > REAP_INTERVAL_MS;
587
+ if (stale.length === 0 && unresolved.size === 0 && uncertain.size === 0 && !reapDue) return;
588
+ const reap = reapDue || uncertain.size > 0;
589
+ if (reap) reapedAt = now;
590
+ const expo = yield* api.pipe(
591
+ // Without a credential no sweep can look; a record Expo would have
592
+ // listed by now still stops counting, so the limit is not held forever.
593
+ Effect.tapError(() =>
594
+ Effect.sync(() => {
595
+ for (const [name, { until }] of uncertain) if (now >= until) uncertain.delete(name);
596
+ }),
597
+ ),
598
+ );
599
+ yield* Effect.forEach(
600
+ [...unresolved],
601
+ ([name, { sessionId }]) => retryUnresolved(expo, name, sessionId),
602
+ { discard: true, concurrency: 4 },
603
+ );
604
+ yield* Effect.forEach(
605
+ stale,
606
+ (session) =>
607
+ (session.stopping
608
+ ? stopSession(expo, session.sessionId, session.name).pipe(
609
+ Effect.andThen(forget(session)),
610
+ // A session Expo already ended is let go even if stopping it keeps failing.
611
+ Effect.catch(() =>
612
+ expo
613
+ .session(session.sessionId)
614
+ .pipe(
615
+ Effect.flatMap((current) =>
616
+ current.status === "STOPPED" || current.status === "ERRORED"
617
+ ? forget(session).pipe(Effect.andThen(forgetEntry(session.name)))
618
+ : Effect.fail(current.status),
619
+ ),
620
+ ),
621
+ ),
622
+ )
623
+ : expo
624
+ .session(session.sessionId)
625
+ .pipe(
626
+ Effect.flatMap((current) =>
627
+ current.status === "STOPPED" || current.status === "ERRORED"
628
+ ? forget(session).pipe(Effect.andThen(forgetEntry(session.name)))
629
+ : Effect.sync(() => void checkedAt.set(session.sessionId, now)),
630
+ ),
631
+ )
632
+ ).pipe(Effect.ignore),
633
+ { discard: true, concurrency: 4 },
634
+ );
635
+ if (reap) yield* reapLeftovers(expo);
636
+ }).pipe(Effect.ignore);
637
+
638
+ /**
639
+ * Stops a tracked session. Until Expo confirms, it stays tracked: listed,
640
+ * counted against the limit, and retried by the next listing.
641
+ */
642
+ const stopTracked = (expo: ExpoApi, session: RunningSession) =>
643
+ Effect.suspend(() => {
644
+ session.stopping = true;
645
+ return stopSession(expo, session.sessionId, session.name);
646
+ }).pipe(Effect.andThen(forget(session)));
647
+
648
+ const devices: DeviceHost.DeviceOperations = {
649
+ list: dropEnded.pipe(
650
+ Effect.andThen(
651
+ Effect.sync(() => ({
652
+ devices: [
653
+ ...CATALOG,
654
+ ...[...sessions.values()].map((session): DeviceHost.HostDevice => ({
655
+ id: session.sessionId,
656
+ platform: "ios",
657
+ name: "iPhone (EAS Simulator)",
658
+ version: "Cloud",
659
+ booted: true,
660
+ physical: false,
661
+ })),
662
+ ],
663
+ detail: undefined,
664
+ })),
665
+ ),
666
+ ),
667
+ boot: (device, context) => {
668
+ if (sessions.has(device.id)) return Effect.succeed(device.id);
669
+ // Read before anything yields, so a stop that lands while the start
670
+ // reads settings or files is seen.
671
+ const startedIn = epoch;
672
+ return startSession(device, context, startedIn).pipe(
673
+ FiberSet.run(starts),
674
+ Effect.flatMap(Fiber.await),
675
+ Effect.flatMap((exit) =>
676
+ Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)
677
+ ? Effect.fail(unavailable(`${config.label} was stopped while the session started.`))
678
+ : exit,
679
+ ),
680
+ );
681
+ },
682
+ attach: () => Effect.void,
683
+ shutdown: (device) =>
684
+ Option.match(sessionFor(device.id), {
685
+ onNone: () => Effect.void,
686
+ onSome: (session) =>
687
+ api.pipe(
688
+ Effect.flatMap((expo) => stopTracked(expo, session)),
689
+ Effect.asVoid,
690
+ Effect.mapError(
691
+ (cause) =>
692
+ new DeviceOperationError({
693
+ operation: "shutdown",
694
+ reason: "request_failed",
695
+ cause,
696
+ }),
697
+ ),
698
+ ),
699
+ }),
700
+ screenshot: (device) =>
701
+ Option.match(sessionFor(device.id), {
702
+ onNone: () =>
703
+ Effect.fail(
704
+ new DeviceOperationError({
705
+ operation: "screenshot",
706
+ reason: "request_failed",
707
+ cause: new Error("The EAS Simulator session is not running"),
708
+ }),
709
+ ),
710
+ onSome: (session) =>
711
+ http
712
+ .execute(
713
+ HttpClientRequest.post(
714
+ `${session.preview.origin}/api/screenshot?device=${encodeURIComponent(session.udid)}`,
715
+ ).pipe(HttpClientRequest.bearerToken(Redacted.value(session.preview.token))),
716
+ )
717
+ .pipe(
718
+ Effect.flatMap(HttpClientResponse.filterStatusOk),
719
+ Effect.flatMap((response) => response.arrayBuffer),
720
+ Effect.map((buffer) => new Uint8Array(buffer)),
721
+ Effect.scoped,
722
+ Effect.timeout(PREVIEW_TIMEOUT),
723
+ Effect.mapError(
724
+ (cause) =>
725
+ new DeviceOperationError({
726
+ operation: "screenshot",
727
+ reason: "request_failed",
728
+ cause,
729
+ }),
730
+ ),
731
+ ),
732
+ }),
733
+ agentEndpoint: (deviceId) =>
734
+ Option.match(sessionFor(deviceId), {
735
+ onNone: () => Effect.fail(unavailable("This EAS Simulator device is no longer running.")),
736
+ // agent-device selects the simulator by its UDID, not the session id T3 shows.
737
+ onSome: (session) => Effect.succeed({ ...session.agent, agentDeviceId: session.udid }),
738
+ }),
739
+ endsDevices: true,
740
+ };
741
+
742
+ /**
743
+ * serve-sim runs at the root of each session's preview host and wants its
744
+ * token on every request. Clients name the device by its session id; serve-sim
745
+ * knows it by its UDID, so the id is swapped for the UDID in the path and in
746
+ * the `device` parameter.
747
+ */
748
+ const upstream: NonNullable<DeviceHost.DeviceHostReady["upstream"]> = (hubPath, search) =>
749
+ Effect.sync(() => {
750
+ if (!hubPath.startsWith(`${SERVE_SIM_PREFIX}/`)) return null;
751
+ const helper = /^\/vendor\/serve-sim\/helper\/([^/]+)\//.exec(hubPath);
752
+ const deviceId = helper ? decodePathSegment(helper[1]!) : search.get("device");
753
+ if (helper && deviceId === null) return null;
754
+ const session =
755
+ deviceId !== null && deviceId !== undefined
756
+ ? sessions.get(deviceId)
757
+ : sessions.size === 1
758
+ ? [...sessions.values()][0]
759
+ : undefined;
760
+ if (!session) return null;
761
+ const path = helper
762
+ ? `/helper/${encodeURIComponent(session.udid)}${hubPath.slice(helper[0].length - 1)}`
763
+ : hubPath.slice(SERVE_SIM_PREFIX.length);
764
+ const params = new URLSearchParams(search);
765
+ if (params.has("device")) params.set("device", session.udid);
766
+ const query = params.size > 0 ? `?${params.toString()}` : "";
767
+ const token = Redacted.value(session.preview.token);
768
+ return {
769
+ url: `${session.preview.origin}${path}${query}`,
770
+ headers: { authorization: `Bearer ${token}` },
771
+ protocols: [`serve-sim.token.${token}`],
772
+ };
773
+ });
774
+
775
+ const nodePath = yield* HostProcess.ExecutablePath;
776
+ const ensureReady: DeviceHost.DeviceHost["Service"]["ensureReady"] = Effect.fn(
777
+ "EasDeviceHost.ensureReady",
778
+ )(function* () {
779
+ if (ready) return ready;
780
+ yield* adoptRecorded;
781
+ // Without a credential the host is still ready: opening a device then
782
+ // says how to sign in, and listing reaps once one is there.
783
+ yield* FiberSet.run(background)(api.pipe(Effect.flatMap(reapLeftovers), Effect.ignore));
784
+ ready = {
785
+ nodePath,
786
+ hub: { origin: "https://api.expo.dev" },
787
+ devices,
788
+ upstream,
789
+ // Device settings run simctl on the simulator's own machine, which EAS does not expose.
790
+ run: () =>
791
+ Effect.succeed({
792
+ stdout: "",
793
+ stderr: "EAS Simulator devices cannot run host commands.",
794
+ code: 127,
795
+ }),
796
+ helpers: { serveSimAxSettings: null, serveSimCli: null },
797
+ };
798
+ return ready;
799
+ });
800
+
801
+ // A session whose stop fails stays tracked for the next listing to retry,
802
+ // and stays in the ledger for the next server if this one closes first.
803
+ const stopAll = Effect.gen(function* () {
804
+ epoch++;
805
+ // Interrupted starts stop the sessions they created before this returns.
806
+ yield* FiberSet.clear(starts);
807
+ yield* FiberSet.clear(background);
808
+ const expo = yield* api;
809
+ yield* Effect.forEach(
810
+ [...sessions.values()],
811
+ (session) => stopTracked(expo, session).pipe(Effect.ignore),
812
+ { discard: true, concurrency: 4 },
813
+ );
814
+ yield* Effect.forEach(
815
+ [...unresolved],
816
+ ([name, { sessionId }]) => retryUnresolved(expo, name, sessionId),
817
+ { discard: true, concurrency: 4 },
818
+ );
819
+ // Also stop a recorded session a create with an unknown outcome made after all.
820
+ yield* reapLeftovers(expo);
821
+ }).pipe(Effect.ignore);
822
+ yield* Effect.addFinalizer(() =>
823
+ stopAll.pipe(
824
+ // Under the ledger lock, so a write still in flight lands before a
825
+ // replacement writes its own, which that write would overwrite.
826
+ Effect.andThen(
827
+ ledgerLock.withPermit(
828
+ Effect.sync(() => {
829
+ closed = true;
830
+ }),
831
+ ),
832
+ ),
833
+ ),
834
+ );
835
+
836
+ const platformAvailability = (platform: DevicePlatform) =>
837
+ Effect.succeed(
838
+ platform === "ios"
839
+ ? { platform, available: true }
840
+ : {
841
+ platform,
842
+ available: false,
843
+ reason: "EAS Simulator Android emulators are not supported yet.",
844
+ },
845
+ );
846
+
847
+ const summary: Effect.Effect<DeviceHostSummary> = Effect.all([
848
+ platformAvailability("ios"),
849
+ platformAvailability("android"),
850
+ ]).pipe(
851
+ Effect.map((platforms) => ({
852
+ id: hostId,
853
+ label: config.label,
854
+ kind: "eas" as const,
855
+ platforms,
856
+ // Nothing to install: the hub and agent-device daemon run in each session.
857
+ hubInstalled: true,
858
+ agentDeviceInstalled: true,
859
+ })),
860
+ );
861
+
862
+ return DeviceHost.DeviceHost.of({
863
+ id: hostId,
864
+ label: config.label,
865
+ summary,
866
+ platformAvailability,
867
+ ensureReady,
868
+ ensureAgentReady: (onPhase) =>
869
+ ensureReady(onPhase).pipe(Effect.map((value) => ({ ...value, agentDevice: null }))),
870
+ current: Effect.sync(() => ready),
871
+ stopAgent: Effect.void,
872
+ // Unlike machines the user owns, every running session here is billed.
873
+ stop: stopAll,
874
+ });
875
+});
apps/server/src/device/LocalDeviceHost.ts
+3
-1
@@ -10,6 +10,7 @@ import {
10
type DevicePlatform,
11
type DevicePlatformAvailability,
12
LOCAL_DEVICE_HOST_ID,
13
+ LOCAL_DEVICE_HOST_LABEL,
14
} from "@t3tools/contracts";
15
import { waitForHttpReady } from "@t3tools/shared/httpReadiness";
16
import * as HostProcess from "@t3tools/shared/HostProcess";
@@ -325,7 +326,7 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {
326
tools,
327
id: hostId,
328
kind: "local",
328
- label: "This machine",
329
+ label: LOCAL_DEVICE_HOST_LABEL,
330
platforms,
331
hubInstalled,
332
agentDeviceInstalled,
@@ -864,6 +865,7 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {
865
866
const host: DeviceHost.DeviceHost["Service"] = {
867
id: hostId,
868
+ label: LOCAL_DEVICE_HOST_LABEL,
869
summary,
870
platformAvailability,
871
ensureReady,
apps/server/src/device/SshDeviceHost.ts
+1
@@ -472,6 +472,7 @@ export const make = Effect.fn("SshDeviceHost.make")(function* (
472
yield* Effect.addFinalizer(() => stop);
473
return {
474
id: config.id,
475
+ label: config.label,
476
summary: Effect.sync(() => summary),
477
inspect: provide(probe(config, owner)).pipe(
478
Effect.tap((value) =>
apps/server/src/mcp/McpDeviceToolkit.test.ts
+36
-4
@@ -10,10 +10,12 @@ import {
10
} from "@t3tools/contracts";
11
import * as Effect from "effect/Effect";
12
import * as Layer from "effect/Layer";
13
+import * as Option from "effect/Option";
14
import { McpSchema, McpServer } from "effect/ai";
15
16
import * as ServerConfig from "../config.ts";
17
import * as DeviceService from "../device/DeviceService.ts";
18
+import * as ProjectService from "../project/ProjectService.ts";
19
import * as McpHttpServer from "./McpHttpServer.ts";
20
import * as McpInvocationContext from "./McpInvocationContext.ts";
21
import * as McpToolAccessTestkit from "./McpToolAccess.testkit.ts";
@@ -84,9 +86,30 @@ new DataView(png.buffer).setUint32(12, 0x49484452);
86
new DataView(png.buffer).setUint32(16, 1206);
87
new DataView(png.buffer).setUint32(20, 2622);
88
89
+const unused = Effect.die("not used");
90
+const readiness = {
91
+ hostId: "local",
92
+ nodePath: process.execPath,
93
+ hub: { origin: "http://hub.test" },
94
+ devices: {
95
+ list: unused,
96
+ boot: () => unused,
97
+ attach: () => unused,
98
+ shutdown: () => unused,
99
+ screenshot: () => unused,
100
+ },
101
+ run: () => unused,
102
+ helpers: { serveSimAxSettings: null, serveSimCli: null },
103
+ agentDevice: null,
104
+};
105
+const layerProjectsMock = Layer.mock(ProjectService.ProjectService)({
106
+ getById: () => Effect.succeed(Option.none()),
107
+});
108
+
109
const layerDeviceServiceMock = Layer.mock(DeviceService.DeviceService)({
110
state: Effect.succeed(state),
111
list: Effect.succeed(state),
112
+ agentReadinessIfSupported: () => Effect.succeed(readiness),
113
open: (input) =>
114
Effect.succeed({
115
threadId: input.threadId,
@@ -114,13 +137,19 @@ const layerDeviceServiceMock = Layer.mock(DeviceService.DeviceService)({
137
close: () => Effect.void,
138
agentCli: Effect.succeed("/cli"),
139
testHost: () => Effect.die("not used"),
117
- agentTarget: () => Effect.succeed(["--config", "/host.json", "--session", "thread-device"]),
140
+ // As for an EAS device, agent-device knows the device by a different id than T3.
141
+ agentTarget: () =>
142
+ Effect.succeed({
143
+ agentDeviceId: "SIM-UDID",
144
+ args: ["--config", "/host.json", "--session", "thread-device"],
145
+ }),
146
});
147
148
const layerTest = McpHttpServer.layerDeviceToolkit.pipe(
149
Layer.provideMerge(McpServer.McpServer.layer),
150
Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),
151
Layer.provideMerge(layerDeviceServiceMock),
152
+ Layer.provide(layerProjectsMock),
153
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-device-toolkit-test-" })),
154
Layer.provide(NodeServices.layer),
155
);
@@ -137,7 +166,8 @@ it.effect("returns the complete bounded launch diagnostics to the agent", () =>
166
});
167
const failedDevices = Layer.mock(DeviceService.DeviceService)({
168
list: Effect.succeed(state),
140
- agentTarget: () => Effect.succeed([]),
169
+ agentReadinessIfSupported: () => Effect.succeed(readiness),
170
+ agentTarget: () => Effect.succeed({ agentDeviceId: "UDID-1", args: [] }),
171
open: () => Effect.fail(failure),
172
});
173
return Effect.gen(function* () {
@@ -157,6 +187,7 @@ it.effect("returns the complete bounded launch diagnostics to the agent", () =>
187
Layer.provideMerge(McpServer.McpServer.layer),
188
Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),
189
Layer.provide(failedDevices),
190
+ Layer.provide(layerProjectsMock),
191
Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-boot-error-test-" })),
192
Layer.provide(NodeServices.layer),
193
),
@@ -179,7 +210,7 @@ it.effect("registers the device tools and returns the screenshot as image conten
210
.pipe(callWith(["device"]), Effect.provideService(McpSchema.McpServerClient, client));
211
expect(opened.isError).toBe(false);
212
const openedContent = opened.structuredContent as { quickStart: string };
182
- expect(openedContent.quickStart).toContain("--udid UDID-1");
213
+ expect(openedContent.quickStart).toContain("--udid SIM-UDID");
214
215
const shot = yield* server
216
.callTool({ name: "device_screenshot", arguments: { deviceId: "UDID-1" } })
@@ -207,7 +238,7 @@ it.effect("registers the device tools and returns the screenshot as image conten
238
it.effect("rejects unavailable agent access before booting or opening a device", () => {
239
const layerUnavailable = Layer.mock(DeviceService.DeviceService)({
240
list: Effect.succeed(state),
210
- agentTarget: () =>
241
+ agentReadinessIfSupported: () =>
242
Effect.fail(
243
new DeviceHostUnavailableError({ hostId: "local", reason: "Agent access is disabled." }),
244
),
@@ -237,6 +268,7 @@ it.effect("rejects unavailable agent access before booting or opening a device",
268
Layer.provideMerge(McpServer.McpServer.layer),
269
Layer.provideMerge(McpToolAccessTestkit.liveThreadsLayer),
270
Layer.provide(layerUnavailable),
271
+ Layer.provide(layerProjectsMock),
272
Layer.provide(
273
ServerConfig.layerTest(process.cwd(), { prefix: "t3-mcp-device-toolkit-test-" }),
274
),
apps/server/src/mcp/toolkits/device/handlers.ts
+33
-15
@@ -15,6 +15,7 @@ import { ensureAgentDeviceShim } from "../../../device/AgentDeviceShim.ts";
15
import { nodeRuntimeUnavailableMessage } from "@t3tools/shared/nodeRuntime";
16
17
import * as DeviceService from "../../../device/DeviceService.ts";
18
+import { threadWorkspaceRoot } from "../../../project/threadWorkspaceRoot.ts";
19
import * as McpInvocationContext from "../../McpInvocationContext.ts";
20
import * as McpToolAccess from "../../McpToolAccess.ts";
21
import { DeviceScreenshotToolkit, DeviceStandardToolkit, DeviceToolkit } from "./tools.ts";
@@ -29,6 +30,7 @@ export function agentDeviceQuickStart(
30
device: DeviceSummary,
31
targetArgs = agentDeviceTargetArgs(device),
32
command = "agent-device",
33
+ cloud = false,
34
): string {
35
const executable = /^[a-zA-Z0-9_./:-]+$/.test(command)
36
? command
@@ -38,8 +40,9 @@ export function agentDeviceQuickStart(
40
/^[a-zA-Z0-9_./:-]+$/.test(arg) ? arg : "'" + arg.replaceAll("'", "'\"'\"'") + "'",
41
)
42
.join(" ");
41
- const platformNotes =
42
- device.platform === "ios"
43
+ const platformNotes = cloud
44
+ ? "This is an EAS Simulator session in the cloud. It bills the Expo account per minute until it stops, so call device_close with shutdown: true when you are done. It starts with no apps installed: install-from-source <url> installs a build from a URL (iOS needs a .tar.gz containing a .app), and install uploads one from this machine."
45
+ : device.platform === "ios"
46
? "First use builds an XCTest runner and can take a couple of minutes; later commands are fast."
47
: "The Android snapshot helper installs itself on first use.";
48
return [
@@ -152,23 +155,38 @@ const handlers = {
155
}
156
const target = yield* pickDevice(state.devices, input);
157
// Resolve consent and agent connectivity before booting or registering a session.
155
- const agentArgs = yield* devices.agentTarget({
156
- threadId: scope.thread.threadId,
157
- hostId: target.hostId,
158
- deviceId: target.id,
159
- });
160
- const session = yield* devices.open({
161
- threadId: scope.thread.threadId,
162
- hostId: target.hostId,
163
- deviceId: target.id,
164
- platform: target.platform,
165
- });
158
+ if (!(yield* devices.agentReadinessIfSupported(target.hostId))) {
159
+ return yield* new DeviceToolUnavailableError({
160
+ reason:
161
+ "Agent device access requires enabled device support, agent access, and an available simulator platform on this host.",
162
+ });
163
+ }
164
+ const session = yield* devices.open(
165
+ {
166
+ threadId: scope.thread.threadId,
167
+ hostId: target.hostId,
168
+ deviceId: target.id,
169
+ platform: target.platform,
170
+ },
171
+ { workspaceRoot: yield* threadWorkspaceRoot(scope.thread.threadId) },
172
+ );
173
const after = yield* devices.state;
174
const device =
175
after.devices.find(
176
(candidate) => candidate.hostId === session.hostId && candidate.id === session.deviceId,
177
) ?? target;
171
- const targetArgs = [...agentDeviceTargetArgs(device), ...agentArgs];
178
+ // Target the opened device: an EAS device and its agent-device daemon
179
+ // exist only once its session runs, and Android ids change on boot.
180
+ const agent = yield* devices.agentTarget({
181
+ threadId: scope.thread.threadId,
182
+ hostId: device.hostId,
183
+ deviceId: device.id,
184
+ });
185
+ const cloud = after.hosts.some((host) => host.id === device.hostId && host.kind === "eas");
186
+ const targetArgs = [
187
+ ...agentDeviceTargetArgs({ ...device, id: agent.agentDeviceId }),
188
+ ...agent.args,
189
+ ];
190
const config = yield* ServerConfig.ServerConfig;
191
const path = yield* Path.Path;
192
const platform = yield* HostProcess.Platform;
@@ -194,7 +212,7 @@ const handlers = {
212
return {
213
device,
214
agentDevice: { command, targetArgs },
197
- quickStart: agentDeviceQuickStart(device, targetArgs, command),
215
+ quickStart: agentDeviceQuickStart(device, targetArgs, command, cloud),
216
};
217
}).pipe(Effect.mapError(toolError)),
218
),
apps/server/src/mcp/toolkits/device/tools.ts
+9
-1
@@ -17,6 +17,7 @@ import { Tool, Toolkit } from "effect/ai";
17
import * as McpInvocationContext from "../../McpInvocationContext.ts";
18
import * as DeviceService from "../../../device/DeviceService.ts";
19
import * as ThreadManagementService from "../../../orchestration-v2/ThreadManagementService.ts";
20
+import * as ProjectService from "../../../project/ProjectService.ts";
21
22
const dependencies = [
23
McpInvocationContext.McpInvocationContext,
@@ -52,7 +53,14 @@ const DeviceOpenTool = Tool.make("device_open", {
53
parameters: DeviceToolOpenInput,
54
success: DeviceToolOpenResult,
55
failure: DeviceToolFailure,
55
- dependencies: [...dependencies, FileSystem.FileSystem, Path.Path, ServerConfig.ServerConfig],
56
+ dependencies: [
57
+ ...dependencies,
58
+ FileSystem.FileSystem,
59
+ Path.Path,
60
+ ServerConfig.ServerConfig,
61
+ // The thread's project can name the EAS project a cloud device runs under.
62
+ ProjectService.ProjectService,
63
+ ],
64
})
65
.annotate(Tool.Title, "Open device")
66
.annotate(Tool.Readonly, false)
apps/server/src/project/threadWorkspaceRoot.ts
new
+19
@@ -0,0 +1,19 @@
1
+import type { ThreadId } from "@t3tools/contracts";
2
+import * as Effect from "effect/Effect";
3
+import * as Option from "effect/Option";
4
+
5
+import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts";
6
+import * as ProjectService from "./ProjectService.ts";
7
+
8
+/** The directory a thread works in, or undefined when the thread or its project is gone. */
9
+export const threadWorkspaceRoot = Effect.fn("threadWorkspaceRoot")(
10
+ function* (threadId: ThreadId) {
11
+ const threads = yield* ThreadManagementService.ThreadManagementService;
12
+ const projects = yield* ProjectService.ProjectService;
13
+ const shell = yield* threads.getThreadShell(threadId);
14
+ if (shell === null) return undefined;
15
+ if (shell.worktreePath) return shell.worktreePath;
16
+ return Option.getOrUndefined(yield* projects.getById(shell.projectId))?.workspaceRoot;
17
+ },
18
+ Effect.orElseSucceed(() => undefined),
19
+);
apps/server/src/ws.ts
+5
-1
@@ -203,6 +203,7 @@ import { linkCreatedPullRequest } from "./git/linkCreatedPullRequest.ts";
203
import * as ReviewService from "./review/ReviewService.ts";
204
import * as ProjectEnrichmentService from "./project/ProjectEnrichmentService.ts";
205
import * as ProjectService from "./project/ProjectService.ts";
206
+import { threadWorkspaceRoot } from "./project/threadWorkspaceRoot.ts";
207
import * as ManagedProjectFolders from "./project/ManagedProjectFolders.ts";
208
import { projectMutationOperation } from "./project/ProjectMutation.ts";
209
import * as ProjectSetupScriptRunner from "./project/ProjectSetupScriptRunner.ts";
@@ -2914,7 +2915,10 @@ export const layerWsRpc = (
2915
? deviceService.retryHost(input.retryHostId)
2916
: deviceService.list,
2917
),
2917
- [WS_METHODS.deviceOpen]: (input) => deviceService.open(input),
2918
+ [WS_METHODS.deviceOpen]: (input) =>
2919
+ threadWorkspaceRoot(input.threadId).pipe(
2920
+ Effect.flatMap((workspaceRoot) => deviceService.open(input, { workspaceRoot })),
2921
+ ),
2922
[WS_METHODS.deviceClose]: (input) => deviceService.close(input),
2923
[WS_METHODS.deviceShutdown]: (input) => deviceService.shutdown(input),
2924
[WS_METHODS.deviceDetail]: (input) => deviceService.detail(input),
docs/internals/devices.md
+18
@@ -26,6 +26,24 @@ operations, so a host whose devices live elsewhere only replaces them.
26
SSH hosts forward both endpoints to server loopback. Every proxied request
27
also carries the host id; device ids alone are not unique across hosts.
28
29
+## EAS Simulator hosts are billed sessions
30
+
31
+An [EAS host](../../apps/server/src/device/EasDeviceHost.ts) has no machine:
32
+each opened device is an EAS Simulator session that bills the Expo account
33
+until it stops. Every session is created with the host's run and idle limits,
34
+the host refuses to start past its session limit, and closing the host stops
35
+its sessions. Sessions it starts are recorded under the state directory and
36
+stopped by the next server if this one dies; sessions other tools started on
37
+the same account are never touched.
38
+
39
+Each session brings its own serve-sim preview host and agent-device daemon,
40
+with their own tokens. The proxy asks the host to route each request
41
+(`DeviceHostReady.upstream`) and adds the session token server-side, so
42
+clients never hold it. Agent config files are written per device
43
+(`DeviceOperations.agentEndpoint`), which is why `device_open` opens the
44
+device before targeting it. Device settings run `simctl` on the simulator's
45
+machine, which EAS does not expose, so they are unavailable there.
46
+
47
## The hub is never exposed
48
49
serve-sim has a shell-exec route whose token is readable from its own
packages/client-runtime/src/state/device.ts
+20
-1
@@ -16,6 +16,25 @@ export function createDeviceEnvironmentAtoms<R, E>(
16
mode: "serial" as const,
17
key: ({ environmentId }: { environmentId: string }) => environmentId,
18
};
19
+ // An EAS Simulator start can take minutes; it must not hold up powering off
20
+ // another device or turning device support off, so each device opens in its
21
+ // own lane. Every EAS start opens the same catalog device, so the thread is
22
+ // part of the lane too.
23
+ const openConcurrency = {
24
+ mode: "serial" as const,
25
+ key: ({
26
+ environmentId,
27
+ input,
28
+ }: {
29
+ environmentId: string;
30
+ input: {
31
+ readonly threadId: string;
32
+ readonly hostId?: string | undefined;
33
+ readonly deviceId: string;
34
+ };
35
+ }) =>
36
+ JSON.stringify([environmentId, "open", input.threadId, input.hostId ?? null, input.deviceId]),
37
+ };
38
return {
39
state: createEnvironmentRpcSubscriptionAtomFamily(runtime, {
40
label: "environment-data:device:state",
@@ -41,7 +60,7 @@ export function createDeviceEnvironmentAtoms<R, E>(
60
label: "environment-data:device:open",
61
tag: WS_METHODS.deviceOpen,
62
scheduler,
44
- concurrency,
63
+ concurrency: openConcurrency,
64
}),
65
close: createEnvironmentRpcCommand(runtime, {
66
label: "environment-data:device:close",
packages/contracts/src/device.ts
+4
-1
@@ -11,6 +11,7 @@ export const DeviceHostId = TrimmedNonEmptyString.check(Schema.isMaxLength(128))
11
export type DeviceHostId = typeof DeviceHostId.Type;
12
13
export const LOCAL_DEVICE_HOST_ID = "local" as DeviceHostId;
14
+export const LOCAL_DEVICE_HOST_LABEL = "This machine";
15
16
const ConfiguredDeviceHostId = DeviceHostId.check(
17
Schema.isPattern(/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/),
@@ -419,12 +420,14 @@ export class DeviceHostUnavailableError extends Schema.TaggedError<DeviceHostUna
420
"DeviceHostUnavailableError",
421
{
422
hostId: DeviceHostId,
423
+ /** The host's name in Settings, which the message shows instead of its id. */
424
+ hostLabel: Schema.optional(Schema.String),
425
reason: Schema.String,
426
cause: Schema.optional(Schema.Defect()),
427
},
428
) {
429
override get message(): string {
427
- return `Device host ${this.hostId} is unavailable: ${this.reason}`;
430
+ return `${this.hostLabel ?? `Device host ${this.hostId}`} is unavailable: ${this.reason}`;
431
}
432
}
433