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
refactor(server): device hosts own their device operations (#21835)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 20, 2026 at 00:57 UTC
83e0f7a822ecc280624b43bbb22b3debc43c138d
9 files changed
+528
-413
apps/server/src/device/DeviceActions.test.ts
+8
@@ -15,9 +15,17 @@ const makeReady = (
15
},
16
) => {
17
const calls: Call[] = [];
18
+ const unused = Effect.die("Device actions run host commands, never device operations");
19
const ready: DeviceHostReady = {
20
nodePath: process.execPath,
21
hub: { origin: "http://127.0.0.1:1" },
22
+ devices: {
23
+ list: unused,
24
+ boot: () => unused,
25
+ attach: () => unused,
26
+ shutdown: () => unused,
27
+ screenshot: () => unused,
28
+ },
29
helpers,
30
run: (command, args, options) => {
31
const call = { command, args, ...(options?.stdin ? { stdin: options.stdin } : {}) };
apps/server/src/device/DeviceHost.ts
+33
@@ -1,8 +1,11 @@
1
import type {
2
+ DeviceBootError,
3
DeviceHostId,
4
DeviceHostSummary,
5
+ DeviceOperationError,
6
DevicePlatform,
7
DevicePlatformAvailability,
8
+ DeviceSummary,
9
} from "@t3tools/contracts";
10
import * as Context from "effect/Context";
11
import * as Effect from "effect/Effect";
@@ -71,9 +74,39 @@ export interface AgentDeviceEndpoint {
74
readonly entryPath: string;
75
}
76
77
+export type HostDevice = Omit<DeviceSummary, "hostId">;
78
+
79
+/** Discovery and lifecycle for the devices a ready host can run. */
80
+export interface DeviceOperations {
81
+ readonly list: Effect.Effect<
82
+ {
83
+ readonly devices: ReadonlyArray<HostDevice>;
84
+ readonly detail: string | undefined;
85
+ /** Some Android virtual devices could not be listed; the rest are. */
86
+ readonly androidDiscoveryIncomplete?: boolean;
87
+ },
88
+ DeviceOperationError
89
+ >;
90
+ /**
91
+ * Boots the device and prepares its stream. Android AVDs change id when they
92
+ * boot (AVD name to emulator serial), so the returned id is authoritative.
93
+ */
94
+ readonly boot: (
95
+ device: HostDevice,
96
+ ) => Effect.Effect<string, DeviceOperationError | DeviceBootError>;
97
+ /** Prepares the stream of a device that is already booted. */
98
+ readonly attach: (device: HostDevice) => Effect.Effect<void, DeviceOperationError>;
99
+ readonly shutdown: (device: {
100
+ readonly id: string;
101
+ readonly platform: DevicePlatform;
102
+ }) => Effect.Effect<void, DeviceOperationError>;
103
+ readonly screenshot: (device: HostDevice) => Effect.Effect<Uint8Array, DeviceOperationError>;
104
+}
105
+
106
export interface DeviceHostReady {
107
readonly nodePath: string;
108
readonly hub: DeviceHubEndpoint;
109
+ readonly devices: DeviceOperations;
110
readonly run: (
111
command: string,
112
args: ReadonlyArray<string>,
apps/server/src/device/DeviceHubOperations.ts
new
+247
@@ -0,0 +1,247 @@
1
+import {
2
+ DeviceBootError,
3
+ type DeviceHostId,
4
+ DeviceOperationError,
5
+ type DevicePlatform,
6
+} from "@t3tools/contracts";
7
+import * as Duration from "effect/Duration";
8
+import * as Effect from "effect/Effect";
9
+import * as Schema from "effect/Schema";
10
+import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
11
+
12
+import type { DeviceHostReady, DeviceOperations, HostDevice } from "./DeviceHost.ts";
13
+
14
+const BOOT_TIMEOUT = Duration.minutes(3);
15
+const SCREENSHOT_TIMEOUT = Duration.seconds(20);
16
+
17
+const HubDevice = Schema.Struct({
18
+ id: Schema.String,
19
+ name: Schema.String,
20
+ version: Schema.String,
21
+ platform: Schema.Literals(["ios", "android"]),
22
+ booted: Schema.Boolean,
23
+ physical: Schema.Boolean,
24
+});
25
+const HubDeviceList = Schema.Struct({
26
+ simulators: Schema.Array(HubDevice),
27
+ emulators: Schema.Array(HubDevice),
28
+ errors: Schema.optional(
29
+ Schema.Array(Schema.Struct({ message: Schema.String, error: Schema.optional(Schema.String) })),
30
+ ),
31
+});
32
+const HubActionResult = Schema.Struct({
33
+ ok: Schema.Boolean,
34
+ id: Schema.optional(Schema.String),
35
+ serial: Schema.optional(Schema.String),
36
+ error: Schema.optional(Schema.String),
37
+ errors: Schema.optional(
38
+ Schema.Array(Schema.Struct({ message: Schema.String, error: Schema.optional(Schema.String) })),
39
+ ),
40
+});
41
+
42
+const vendorPrefix = (platform: DevicePlatform) =>
43
+ platform === "ios" ? "/vendor/serve-sim" : "/vendor/serve-emu";
44
+
45
+/** Device operations for a host that runs expo-device-hub at `origin`. */
46
+export const makeDeviceHubOperations = (options: {
47
+ readonly hostId: DeviceHostId;
48
+ readonly origin: string;
49
+ readonly http: HttpClient.HttpClient;
50
+ readonly run: DeviceHostReady["run"];
51
+ /** Whether to list AVDs, which the hub does not report until they boot. */
52
+ readonly androidAvailable: Effect.Effect<boolean>;
53
+}): DeviceOperations => {
54
+ const { hostId, origin, run } = options;
55
+ const httpClient = options.http.pipe(HttpClient.withScope);
56
+
57
+ const hubJson = <A, I>(
58
+ request: HttpClientRequest.HttpClientRequest,
59
+ schema: Schema.Codec<A, I>,
60
+ operation: string,
61
+ timeout: Duration.Input = Duration.seconds(15),
62
+ ) =>
63
+ httpClient.execute(request).pipe(
64
+ Effect.flatMap(HttpClientResponse.filterStatusOk),
65
+ Effect.flatMap(HttpClientResponse.schemaBodyJson(schema)),
66
+ Effect.scoped,
67
+ Effect.timeout(timeout),
68
+ Effect.mapError(
69
+ (cause) =>
70
+ new DeviceOperationError({
71
+ operation,
72
+ reason: "request_failed",
73
+ cause,
74
+ }),
75
+ ),
76
+ );
77
+
78
+ const postJson = (path: string, body: Record<string, string>, operation: string) =>
79
+ HttpClientRequest.post(`${origin}${path}`).pipe(
80
+ HttpClientRequest.bodyJson(body),
81
+ Effect.mapError(
82
+ (cause) => new DeviceOperationError({ operation, reason: "invalid_payload", cause }),
83
+ ),
84
+ );
85
+
86
+ // Booting alone does not attach a serve-sim helper; the grid start does both
87
+ // and is idempotent for a booted simulator.
88
+ const attachIosStream = (udid: string, operation: string) =>
89
+ postJson(`${vendorPrefix("ios")}/grid/api/start`, { udid }, operation).pipe(
90
+ Effect.flatMap((request) => hubJson(request, HubActionResult, "attach stream", BOOT_TIMEOUT)),
91
+ );
92
+
93
+ const list: DeviceOperations["list"] = Effect.gen(function* () {
94
+ const hubList = yield* hubJson(
95
+ HttpClientRequest.get(`${origin}/api/devices`),
96
+ HubDeviceList,
97
+ "list",
98
+ );
99
+ const devices: Array<HostDevice> = [...hubList.simulators, ...hubList.emulators];
100
+ const warnings = hubList.errors?.filter(
101
+ (error) =>
102
+ // CoreSimulator can retain deleted devices; their optional usage timestamps are absent.
103
+ !(
104
+ error.message.startsWith("[apple-utils] Failed to read CoreSimulator plist at ") &&
105
+ /\/CoreSimulator\/Devices\/[^/]+\/device\.plist:$/.test(error.message) &&
106
+ /(?:^Error:\s*ENOENT:|\bcode:\s*['"]ENOENT['"])/.test(error.error ?? "")
107
+ ),
108
+ );
109
+ const details = warnings?.map((error) => error.message) ?? [];
110
+ let androidDiscoveryIncomplete = false;
111
+ if (yield* options.androidAvailable) {
112
+ const avds = yield* run("emulator", ["-list-avds"]);
113
+ // Discovered devices stay listed; the AVDs that could not be listed are a warning.
114
+ if (avds.code !== 0) {
115
+ androidDiscoveryIncomplete = true;
116
+ details.push(
117
+ `Could not list Android virtual devices (emulator -list-avds, exit code ${avds.code}). Discovered devices remain available.`,
118
+ );
119
+ }
120
+ for (const name of (avds.code === 0 ? avds.stdout : "")
121
+ .split(/\r?\n/)
122
+ .map((line) => line.trim())
123
+ .filter(Boolean)) {
124
+ if (!devices.some((device) => device.platform === "android" && device.name === name)) {
125
+ devices.push({
126
+ id: name,
127
+ name,
128
+ platform: "android",
129
+ version: "Android",
130
+ booted: false,
131
+ physical: false,
132
+ });
133
+ }
134
+ }
135
+ }
136
+ return {
137
+ devices,
138
+ detail: details.join("\n") || undefined,
139
+ androidDiscoveryIncomplete,
140
+ };
141
+ }).pipe(Effect.withSpan("DeviceHubOperations.list"));
142
+
143
+ const boot: DeviceOperations["boot"] = Effect.fn("DeviceHubOperations.boot")(function* (device) {
144
+ const result = yield* postJson(
145
+ "/api/devices/boot",
146
+ { platform: device.platform, id: device.id, name: device.name },
147
+ "boot",
148
+ ).pipe(Effect.flatMap((request) => hubJson(request, HubActionResult, "boot", BOOT_TIMEOUT)));
149
+ if (!result.ok) {
150
+ // Keep the hub's launch command and nested failure available to agents for recovery.
151
+ const diagnostics = [
152
+ result.error,
153
+ ...(result.errors ?? []).flatMap((error) => [error.message, error.error]),
154
+ ]
155
+ .filter((text) => text?.trim())
156
+ .join("\n\n");
157
+ return yield* new DeviceBootError({
158
+ hostId,
159
+ deviceId: device.id,
160
+ reason: /insufficient.*(?:disk|space)|not enough.*(?:disk|space)|no space left/i.test(
161
+ diagnostics,
162
+ )
163
+ ? "disk_space"
164
+ : /timed? out|timeout/i.test(diagnostics)
165
+ ? "timeout"
166
+ : "launch_failed",
167
+ ...(diagnostics
168
+ ? {
169
+ diagnostics:
170
+ diagnostics.length > 2_000 ? `${diagnostics.slice(0, 1_999)}…` : diagnostics,
171
+ }
172
+ : {}),
173
+ cause: result,
174
+ });
175
+ }
176
+ if (device.platform === "ios") yield* attachIosStream(device.id, "boot");
177
+ return result.serial ?? result.id ?? device.id;
178
+ });
179
+
180
+ const attach: DeviceOperations["attach"] = (device) =>
181
+ device.platform === "ios"
182
+ ? attachIosStream(device.id, "open").pipe(Effect.asVoid)
183
+ : Effect.void;
184
+
185
+ const shutdown: DeviceOperations["shutdown"] = Effect.fn("DeviceHubOperations.shutdown")(
186
+ function* (device) {
187
+ const postShutdown = (path: string, body: Record<string, string>) =>
188
+ postJson(path, body, "shutdown").pipe(
189
+ Effect.flatMap((request) => hubJson(request, HubActionResult, "shutdown")),
190
+ Effect.flatMap((result) =>
191
+ result.ok
192
+ ? Effect.void
193
+ : Effect.fail(
194
+ new DeviceOperationError({
195
+ operation: "shutdown",
196
+ reason: "hub_rejected",
197
+ cause: result,
198
+ }),
199
+ ),
200
+ ),
201
+ );
202
+ // serve-sim's shutdown closes its in-process capture session before it
203
+ // runs `simctl shutdown`; the hub's generic shutdown can leave that
204
+ // session cached across a reboot. serve-sim runs simctl bare, though, so
205
+ // a simulator that is already off fails there.
206
+ yield* device.platform === "ios"
207
+ ? postShutdown(`${vendorPrefix("ios")}/grid/api/shutdown`, { udid: device.id }).pipe(
208
+ Effect.catch((cause) =>
209
+ list.pipe(
210
+ Effect.flatMap(({ devices }) =>
211
+ devices.find((candidate) => candidate.id === device.id)?.booted === false
212
+ ? Effect.logInfo("iOS simulator was already shut down", { deviceId: device.id })
213
+ : Effect.fail(cause),
214
+ ),
215
+ ),
216
+ ),
217
+ )
218
+ : postShutdown("/api/devices/shutdown", { platform: device.platform, id: device.id });
219
+ },
220
+ );
221
+
222
+ const screenshot: DeviceOperations["screenshot"] = (device) =>
223
+ httpClient
224
+ .execute(
225
+ HttpClientRequest.post(
226
+ `${origin}${vendorPrefix(device.platform)}/api/screenshot?device=${encodeURIComponent(device.id)}`,
227
+ ),
228
+ )
229
+ .pipe(
230
+ Effect.flatMap(HttpClientResponse.filterStatusOk),
231
+ Effect.flatMap((response) => response.arrayBuffer),
232
+ Effect.map((buffer) => new Uint8Array(buffer)),
233
+ Effect.scoped,
234
+ Effect.timeout(SCREENSHOT_TIMEOUT),
235
+ Effect.mapError(
236
+ (cause) =>
237
+ new DeviceOperationError({
238
+ operation: "screenshot",
239
+ reason: "request_failed",
240
+ cause,
241
+ }),
242
+ ),
243
+ Effect.withSpan("DeviceHubOperations.screenshot"),
244
+ );
245
+
246
+ return { list, boot, attach, shutdown, screenshot };
247
+};
apps/server/src/device/DeviceMultiHost.test.ts
+36
-27
@@ -7,21 +7,50 @@ import * as Effect from "effect/Effect";
7
import { HttpClient, HttpClientResponse } from "effect/http";
8
import * as ServerSettings from "../serverSettings.ts";
9
import * as DeviceHost from "./DeviceHost.ts";
10
+import { makeDeviceHubOperations } from "./DeviceHubOperations.ts";
11
import * as DeviceService from "./DeviceService.ts";
12
13
it.effect("keeps hosts independent when serials collide and another host fails", () =>
14
Effect.gen(function* () {
15
+ const http = HttpClient.make((request) =>
16
+ Effect.succeed(
17
+ HttpClientResponse.fromWeb(
18
+ request,
19
+ Response.json({
20
+ simulators: [],
21
+ emulators: [
22
+ {
23
+ id: "emulator-5554",
24
+ name: "Pixel",
25
+ version: "36",
26
+ platform: "android",
27
+ booted: true,
28
+ physical: false,
29
+ },
30
+ ],
31
+ }),
32
+ ),
33
+ ),
34
+ );
35
const host = (id: string, failed = false): DeviceHost.DeviceHost["Service"] => {
36
+ const run = (command: string) =>
37
+ Effect.succeed({
38
+ stdout: command === "emulator" ? "" : " V....D libx264",
39
+ stderr: "",
40
+ code: 0,
41
+ });
42
const ready: DeviceHost.DeviceHostAgentReady = {
43
nodePath: process.execPath,
44
hub: { origin: `http://${id}` },
45
+ devices: makeDeviceHubOperations({
46
+ hostId: id,
47
+ origin: `http://${id}`,
48
+ http,
49
+ run,
50
+ androidAvailable: Effect.succeed(true),
51
+ }),
52
agentDevice: { baseUrl: `http://${id}`, token: "test", entryPath: "/agent-device" },
19
- run: (command) =>
20
- Effect.succeed({
21
- stdout: command === "emulator" ? "" : " V....D libx264",
22
- stderr: "",
23
- code: 0,
24
- }),
53
+ run,
54
helpers: { serveSimAxSettings: null, serveSimCli: null },
55
};
56
return {
@@ -51,26 +80,6 @@ it.effect("keeps hosts independent when serials collide and another host fails",
80
stop: Effect.void,
81
};
82
};
54
- const http = HttpClient.make((request) =>
55
- Effect.succeed(
56
- HttpClientResponse.fromWeb(
57
- request,
58
- Response.json({
59
- simulators: [],
60
- emulators: [
61
- {
62
- id: "emulator-5554",
63
- name: "Pixel",
64
- version: "36",
65
- platform: "android",
66
- booted: true,
67
- physical: false,
68
- },
69
- ],
70
- }),
71
- ),
72
- ),
73
- );
83
const hosts = new Map(["a", "b", "offline"].map((id) => [id, host(id, id === "offline")]));
84
const writeStarted = yield* Deferred.make<void>();
85
const finishWrite = yield* Deferred.make<void>();
@@ -83,7 +92,7 @@ it.effect("keeps hosts independent when serials collide and another host fails",
92
order.push("write finished");
93
return "/host-config.json";
94
}),
86
- ).pipe(Effect.provide(NodeCrypto.layer), Effect.provideService(HttpClient.HttpClient, http));
95
+ ).pipe(Effect.provide(NodeCrypto.layer));
96
expect(yield* service.agentReadinessIfSupported("b")).not.toBeNull();
97
const listed = yield* service.list;
98
expect(listed.devices.map((device) => device.hostId).sort()).toEqual(["a", "b"]);
apps/server/src/device/DeviceService.test.ts
+150
-131
@@ -33,6 +33,7 @@ import * as ServerConfig from "../config.ts";
33
import * as ProcessRunner from "../processRunner.ts";
34
import * as ServerSettings from "../serverSettings.ts";
35
import * as DeviceHost from "./DeviceHost.ts";
36
+import { makeDeviceHubOperations } from "./DeviceHubOperations.ts";
37
import { NodeRuntimeUnavailableError } from "@t3tools/shared/nodeRuntime";
38
39
import * as DeviceService from "./DeviceService.ts";
@@ -99,14 +100,75 @@ const fixture = Effect.fn("fixture")(function* (
100
const encoderResult = yield* Ref.make({ code: 0, stdout: " V....D libx264", stderr: "" });
101
let booted = false;
102
let shutDown = false;
103
+ const http = HttpClient.make((request) =>
104
+ Effect.gen(function* () {
105
+ requests.push(request.url);
106
+ if (request.url.includes("/api/screenshot")) {
107
+ return HttpClientResponse.fromWeb(request, new Response(new Uint8Array([137, 80, 78, 71])));
108
+ }
109
+ if (request.url.endsWith("/shutdown")) {
110
+ shutDown = true;
111
+ booted = false;
112
+ return HttpClientResponse.fromWeb(request, Response.json({ ok: true }));
113
+ }
114
+ if (shutDown && failListAfterShutdown) {
115
+ return HttpClientResponse.fromWeb(request, new Response("Discovery busy", { status: 503 }));
116
+ }
117
+ if (request.url.endsWith("/boot")) {
118
+ yield* onBoot;
119
+ booted = true;
120
+ return HttpClientResponse.fromWeb(
121
+ request,
122
+ Response.json(
123
+ bootError
124
+ ? { ok: false, ...(typeof bootError === "string" ? { error: bootError } : bootError) }
125
+ : { ok: true, serial: "emulator-5554" },
126
+ ),
127
+ );
128
+ }
129
+ if (request.url.endsWith("/grid/api/start")) {
130
+ return HttpClientResponse.fromWeb(request, Response.json({ ok: true }));
131
+ }
132
+ return HttpClientResponse.fromWeb(
133
+ request,
134
+ Response.json({
135
+ errors: yield* Ref.get(discoveryErrors),
136
+ simulators: devices.filter((device) => device.platform === "ios"),
137
+ emulators: [
138
+ ...devices.filter((device) => device.platform === "android"),
139
+ ...(booted
140
+ ? [
141
+ {
142
+ id: "emulator-5554",
143
+ name: "Pixel_API_35",
144
+ platform: "android",
145
+ version: "Android 15",
146
+ booted: true,
147
+ physical: false,
148
+ },
149
+ ]
150
+ : []),
151
+ ],
152
+ }),
153
+ );
154
+ }),
155
+ );
156
+ const run = (command: string) =>
157
+ command === "emulator"
158
+ ? Effect.succeed({ code: 0, stdout: "Pixel_API_35\n", stderr: "" })
159
+ : Ref.get(encoderResult);
160
const ready: DeviceHost.DeviceHostReady = {
161
nodePath: process.execPath,
162
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
+ }),
170
helpers: { serveSimAxSettings: null, serveSimCli: null },
106
- run: (command) =>
107
- command === "emulator"
108
- ? Effect.succeed({ code: 0, stdout: "Pixel_API_35\n", stderr: "" })
109
- : Ref.get(encoderResult),
171
+ run,
172
};
173
const host: DeviceHost.DeviceHost["Service"] = {
174
...(inspectError
@@ -188,71 +250,6 @@ const fixture = Effect.fn("fixture")(function* (
250
subscribeChanges: Effect.succeed(Stream.empty),
251
}),
252
),
191
- Effect.provideService(
192
- HttpClient.HttpClient,
193
- HttpClient.make((request) =>
194
- Effect.gen(function* () {
195
- requests.push(request.url);
196
- if (request.url.includes("/api/screenshot")) {
197
- return HttpClientResponse.fromWeb(
198
- request,
199
- new Response(new Uint8Array([137, 80, 78, 71])),
200
- );
201
- }
202
- if (request.url.endsWith("/shutdown")) {
203
- shutDown = true;
204
- booted = false;
205
- return HttpClientResponse.fromWeb(request, Response.json({ ok: true }));
206
- }
207
- if (shutDown && failListAfterShutdown) {
208
- return HttpClientResponse.fromWeb(
209
- request,
210
- new Response("Discovery busy", { status: 503 }),
211
- );
212
- }
213
- if (request.url.endsWith("/boot")) {
214
- yield* onBoot;
215
- booted = true;
216
- return HttpClientResponse.fromWeb(
217
- request,
218
- Response.json(
219
- bootError
220
- ? {
221
- ok: false,
222
- ...(typeof bootError === "string" ? { error: bootError } : bootError),
223
- }
224
- : { ok: true, serial: "emulator-5554" },
225
- ),
226
- );
227
- }
228
- if (request.url.endsWith("/grid/api/start")) {
229
- return HttpClientResponse.fromWeb(request, Response.json({ ok: true }));
230
- }
231
- return HttpClientResponse.fromWeb(
232
- request,
233
- Response.json({
234
- errors: yield* Ref.get(discoveryErrors),
235
- simulators: devices.filter((device) => device.platform === "ios"),
236
- emulators: [
237
- ...devices.filter((device) => device.platform === "android"),
238
- ...(booted
239
- ? [
240
- {
241
- id: "emulator-5554",
242
- name: "Pixel_API_35",
243
- platform: "android",
244
- version: "Android 15",
245
- booted: true,
246
- physical: false,
247
- },
248
- ]
249
- : []),
250
- ],
251
- }),
252
- );
253
- }),
254
- ),
255
- ),
253
);
254
return {
255
service,
@@ -668,29 +665,6 @@ it.effect.each(["shutdown", "close"] as const)(
665
let booted = true;
666
let capture: number | null = null;
667
let generation = 0;
671
- const ready: DeviceHost.DeviceHostReady = {
672
- nodePath: process.execPath,
673
- hub: { origin: "http://device.test" },
674
- helpers: { serveSimAxSettings: null, serveSimCli: null },
675
- run: () => Effect.succeed({ code: 0, stdout: "", stderr: "" }),
676
- };
677
- const host: DeviceHost.DeviceHost["Service"] = {
678
- id: LOCAL_DEVICE_HOST_ID,
679
- summary: Effect.succeed({
680
- id: LOCAL_DEVICE_HOST_ID,
681
- kind: "local",
682
- label: "Simulator host",
683
- platforms: [{ platform: "ios", available: true }],
684
- hubInstalled: true,
685
- agentDeviceInstalled: false,
686
- }),
687
- platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
688
- ensureReady: () => Effect.succeed(ready),
689
- ensureAgentReady: () => Effect.die("Agent access is not used in this test"),
690
- current: Effect.succeed(ready),
691
- stopAgent: Effect.void,
692
- stop: Effect.void,
693
- };
668
const http = HttpClient.make((request) =>
669
Effect.sync(() => {
670
const path = new URL(request.url).pathname;
@@ -728,9 +702,39 @@ it.effect.each(["shutdown", "close"] as const)(
702
return HttpClientResponse.fromWeb(request, Response.json({ ok: true, id: deviceId }));
703
}),
704
);
705
+ const run = () => Effect.succeed({ code: 0, stdout: "", stderr: "" });
706
+ const ready: DeviceHost.DeviceHostReady = {
707
+ nodePath: process.execPath,
708
+ hub: { origin: "http://device.test" },
709
+ devices: makeDeviceHubOperations({
710
+ hostId: LOCAL_DEVICE_HOST_ID,
711
+ origin: "http://device.test",
712
+ http,
713
+ run,
714
+ androidAvailable: Effect.succeed(true),
715
+ }),
716
+ helpers: { serveSimAxSettings: null, serveSimCli: null },
717
+ run,
718
+ };
719
+ const host: DeviceHost.DeviceHost["Service"] = {
720
+ id: LOCAL_DEVICE_HOST_ID,
721
+ summary: Effect.succeed({
722
+ id: LOCAL_DEVICE_HOST_ID,
723
+ kind: "local",
724
+ label: "Simulator host",
725
+ platforms: [{ platform: "ios", available: true }],
726
+ hubInstalled: true,
727
+ agentDeviceInstalled: false,
728
+ }),
729
+ platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
730
+ ensureReady: () => Effect.succeed(ready),
731
+ ensureAgentReady: () => Effect.die("Agent access is not used in this test"),
732
+ current: Effect.succeed(ready),
733
+ stopAgent: Effect.void,
734
+ stop: Effect.void,
735
+ };
736
const service = yield* DeviceService.makeWithHosts(new Map([[host.id, host]])).pipe(
737
Effect.provide(NodeCrypto.layer),
733
- Effect.provideService(HttpClient.HttpClient, http),
738
);
739
const input = { threadId, deviceId, platform: "ios" as const };
740
yield* service.open(input);
@@ -756,29 +760,6 @@ it.effect.each([
760
const deviceId = DeviceId.make("22222222-2222-2222-2222-222222222222");
761
const paths: string[] = [];
762
let listed: "booted" | "off" | "missing" = "booted";
759
- const ready: DeviceHost.DeviceHostReady = {
760
- nodePath: process.execPath,
761
- hub: { origin: "http://device.test" },
762
- helpers: { serveSimAxSettings: null, serveSimCli: null },
763
- run: () => Effect.succeed({ code: 0, stdout: "", stderr: "" }),
764
- };
765
- const host: DeviceHost.DeviceHost["Service"] = {
766
- id: LOCAL_DEVICE_HOST_ID,
767
- summary: Effect.succeed({
768
- id: LOCAL_DEVICE_HOST_ID,
769
- kind: "local",
770
- label: "Simulator host",
771
- platforms: [{ platform: "ios", available: true }],
772
- hubInstalled: true,
773
- agentDeviceInstalled: false,
774
- }),
775
- platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
776
- ensureReady: () => Effect.succeed(ready),
777
- ensureAgentReady: () => Effect.die("Agent access is not used in this test"),
778
- current: Effect.succeed(ready),
779
- stopAgent: Effect.void,
780
- stop: Effect.void,
781
- };
763
const http = HttpClient.make((request) =>
764
Effect.sync(() => {
765
const path = new URL(request.url).pathname;
@@ -819,9 +800,39 @@ it.effect.each([
800
throw new Error(`Unexpected hub path: ${path}`);
801
}),
802
);
803
+ const run = () => Effect.succeed({ code: 0, stdout: "", stderr: "" });
804
+ const ready: DeviceHost.DeviceHostReady = {
805
+ nodePath: process.execPath,
806
+ hub: { origin: "http://device.test" },
807
+ devices: makeDeviceHubOperations({
808
+ hostId: LOCAL_DEVICE_HOST_ID,
809
+ origin: "http://device.test",
810
+ http,
811
+ run,
812
+ androidAvailable: Effect.succeed(true),
813
+ }),
814
+ helpers: { serveSimAxSettings: null, serveSimCli: null },
815
+ run,
816
+ };
817
+ const host: DeviceHost.DeviceHost["Service"] = {
818
+ id: LOCAL_DEVICE_HOST_ID,
819
+ summary: Effect.succeed({
820
+ id: LOCAL_DEVICE_HOST_ID,
821
+ kind: "local",
822
+ label: "Simulator host",
823
+ platforms: [{ platform: "ios", available: true }],
824
+ hubInstalled: true,
825
+ agentDeviceInstalled: false,
826
+ }),
827
+ platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
828
+ ensureReady: () => Effect.succeed(ready),
829
+ ensureAgentReady: () => Effect.die("Agent access is not used in this test"),
830
+ current: Effect.succeed(ready),
831
+ stopAgent: Effect.void,
832
+ stop: Effect.void,
833
+ };
834
const service = yield* DeviceService.makeWithHosts(new Map([[host.id, host]])).pipe(
835
Effect.provide(NodeCrypto.layer),
824
- Effect.provideService(HttpClient.HttpClient, http),
836
);
837
yield* service.list;
838
const exit = yield* Effect.exit(service.shutdown({ deviceId, platform: "ios" }));
@@ -847,11 +858,32 @@ it.effect.each([LOCAL_DEVICE_HOST_ID, "ssh-fixture"])(
858
(hostId) =>
859
Effect.gen(function* () {
860
let enumeration = { code: 1, stdout: "private stdout", stderr: "private stderr" };
861
+ const run = () => Effect.sync(() => enumeration);
862
+ const hubDevices = [
863
+ { id: "iphone", name: "iPhone", platform: "ios", physical: false },
864
+ { id: "phone", name: "Pixel", platform: "android", physical: true },
865
+ { id: "emulator-5554", name: "Running_AVD", platform: "android", physical: false },
866
+ ].map((device) => ({ ...device, booted: true, version: "test" }));
867
+ const http = HttpClient.make((request) =>
868
+ Effect.succeed(
869
+ HttpClientResponse.fromWeb(
870
+ request,
871
+ Response.json({ simulators: hubDevices.slice(0, 1), emulators: hubDevices.slice(1) }),
872
+ ),
873
+ ),
874
+ );
875
const ready: DeviceHost.DeviceHostReady = {
876
nodePath: process.execPath,
877
hub: { origin: "http://device.test" },
878
+ devices: makeDeviceHubOperations({
879
+ hostId,
880
+ origin: "http://device.test",
881
+ http,
882
+ run,
883
+ androidAvailable: Effect.succeed(true),
884
+ }),
885
helpers: { serveSimAxSettings: null, serveSimCli: null },
854
- run: () => Effect.sync(() => enumeration),
886
+ run,
887
};
888
const host: DeviceHost.DeviceHost["Service"] = {
889
id: hostId,
@@ -870,19 +902,6 @@ it.effect.each([LOCAL_DEVICE_HOST_ID, "ssh-fixture"])(
902
stop: Effect.void,
903
stopAgent: Effect.void,
904
};
873
- const hubDevices = [
874
- { id: "iphone", name: "iPhone", platform: "ios", physical: false },
875
- { id: "phone", name: "Pixel", platform: "android", physical: true },
876
- { id: "emulator-5554", name: "Running_AVD", platform: "android", physical: false },
877
- ].map((device) => ({ ...device, booted: true, version: "test" }));
878
- const http = HttpClient.make((request) =>
879
- Effect.succeed(
880
- HttpClientResponse.fromWeb(
881
- request,
882
- Response.json({ simulators: hubDevices.slice(0, 1), emulators: hubDevices.slice(1) }),
883
- ),
884
- ),
885
- );
905
const service = yield* DeviceService.makeWithHosts(new Map([[hostId, host]])).pipe(
906
Effect.provide(NodeCrypto.layer),
907
Effect.provideService(HttpClient.HttpClient, http),
apps/server/src/device/DeviceService.ts
+11
-240
@@ -7,7 +7,6 @@ import {
7
type DeviceError,
8
type DeviceHostId,
9
type DeviceId,
10
- DeviceBootError,
10
DeviceHostUnavailableError,
11
DeviceNotFoundError,
12
DeviceOperationError,
@@ -37,16 +36,13 @@ import {
36
import * as Context from "effect/Context";
37
import * as Crypto from "effect/Crypto";
38
import * as DateTime from "effect/DateTime";
40
-import * as Duration from "effect/Duration";
39
import * as Effect from "effect/Effect";
40
import * as Layer from "effect/Layer";
41
import * as PubSub from "effect/PubSub";
44
-import * as Schema from "effect/Schema";
42
import * as Scope from "effect/Scope";
43
import * as Semaphore from "effect/Semaphore";
44
import * as Stream from "effect/Stream";
45
import * as SynchronizedRef from "effect/SynchronizedRef";
49
-import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http";
46
47
import * as ServerSettings from "../serverSettings.ts";
48
import { isLocalSshDeviceHost, remoteSshDeviceHosts } from "./localSshDeviceHost.ts";
@@ -82,34 +78,6 @@ const sshProbeFailureMessage = (error: DeviceHost.DeviceHostError): string => {
78
return `Connected over SSH, but the device host check failed (exit code ${cause.exitCode}).`;
79
};
80
85
-const BOOT_TIMEOUT = Duration.minutes(3);
86
-const SCREENSHOT_TIMEOUT = Duration.seconds(20);
87
-
88
-const HubDevice = Schema.Struct({
89
- id: Schema.String,
90
- name: Schema.String,
91
- version: Schema.String,
92
- platform: Schema.Literals(["ios", "android"]),
93
- booted: Schema.Boolean,
94
- physical: Schema.Boolean,
95
-});
96
-const HubDeviceList = Schema.Struct({
97
- simulators: Schema.Array(HubDevice),
98
- emulators: Schema.Array(HubDevice),
99
- errors: Schema.optional(
100
- Schema.Array(Schema.Struct({ message: Schema.String, error: Schema.optional(Schema.String) })),
101
- ),
102
-});
103
-const HubActionResult = Schema.Struct({
104
- ok: Schema.Boolean,
105
- id: Schema.optional(Schema.String),
106
- serial: Schema.optional(Schema.String),
107
- error: Schema.optional(Schema.String),
108
- errors: Schema.optional(
109
- Schema.Array(Schema.Struct({ message: Schema.String, error: Schema.optional(Schema.String) })),
110
- ),
111
-});
112
-
81
export interface DeviceScreenshot {
82
readonly device: DeviceSummary;
83
readonly png: Uint8Array;
@@ -169,9 +137,6 @@ interface ServiceState {
137
readonly state: DeviceServiceState;
138
}
139
172
-const vendorPrefix = (platform: DevicePlatform) =>
173
- platform === "ios" ? "/vendor/serve-sim" : "/vendor/serve-emu";
174
-
140
export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function* (
141
hosts: ReadonlyMap<DeviceHostId, DeviceHost.DeviceHost["Service"]>,
142
testHost: DeviceService["Service"]["testHost"] = (host) =>
@@ -209,7 +174,6 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
174
);
175
const initialSettings = yield* readDeviceSettings;
176
212
- const httpClient = (yield* HttpClient.HttpClient).pipe(HttpClient.withScope);
177
const statePubSub = yield* PubSub.unbounded<DeviceServiceState>();
178
const initialHosts = yield* Effect.forEach(hosts.values(), (host) => host.summary);
179
let publishedHosts = new Map(hosts);
@@ -388,81 +352,13 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
352
Effect.orElseSucceed(() => null),
353
);
354
391
- const hubJson = <A, I>(
392
- request: HttpClientRequest.HttpClientRequest,
393
- schema: Schema.Codec<A, I>,
394
- operation: string,
395
- timeout: Duration.Input = Duration.seconds(15),
396
- ) =>
397
- httpClient.execute(request).pipe(
398
- Effect.flatMap(HttpClientResponse.filterStatusOk),
399
- Effect.flatMap(HttpClientResponse.schemaBodyJson(schema)),
400
- Effect.scoped,
401
- Effect.timeout(timeout),
402
- Effect.mapError(
403
- (cause) =>
404
- new DeviceOperationError({
405
- operation,
406
- reason: "request_failed",
407
- cause,
408
- }),
409
- ),
410
- );
411
-
355
const fetchDevices = Effect.fn("DeviceService.fetchDevices")(function* (ready: DeviceReadiness) {
413
- const list = yield* hubJson(
414
- HttpClientRequest.get(`${ready.hub.origin}/api/devices`),
415
- HubDeviceList,
416
- "list",
417
- );
418
- const toSummary = (device: typeof HubDevice.Type): DeviceSummary => ({
419
- hostId: ready.hostId,
420
- id: device.id,
421
- platform: device.platform,
422
- name: device.name,
423
- version: device.version,
424
- booted: device.booted,
425
- physical: device.physical,
426
- });
427
- const devices = [...list.simulators, ...list.emulators].map(toSummary);
428
- const warnings = list.errors?.filter(
429
- (error) =>
430
- // CoreSimulator can retain deleted devices; their optional usage timestamps are absent.
431
- !(
432
- error.message.startsWith("[apple-utils] Failed to read CoreSimulator plist at ") &&
433
- /\/CoreSimulator\/Devices\/[^/]+\/device\.plist:$/.test(error.message) &&
434
- /(?:^Error:\s*ENOENT:|\bcode:\s*['"]ENOENT['"])/.test(error.error ?? "")
435
- ),
436
- );
437
- const details = warnings?.map((error) => error.message) ?? [];
438
- let androidDiscoveryIncomplete = false;
439
- const host = yield* resolveHost(ready.hostId);
440
- if ((yield* host.platformAvailability("android")).available) {
441
- const avds = yield* ready.run("emulator", ["-list-avds"]);
442
- if (avds.code !== 0) {
443
- androidDiscoveryIncomplete = true;
444
- details.push(
445
- `Could not list Android virtual devices (emulator -list-avds, exit code ${avds.code}). Discovered devices remain available.`,
446
- );
447
- }
448
- for (const name of (avds.code === 0 ? avds.stdout : "")
449
- .split(/\r?\n/)
450
- .map((line) => line.trim())
451
- .filter(Boolean)) {
452
- if (!devices.some((device) => device.platform === "android" && device.name === name)) {
453
- devices.push({
454
- hostId: ready.hostId,
455
- id: name,
456
- name,
457
- platform: "android",
458
- version: "Android",
459
- booted: false,
460
- physical: false,
461
- });
462
- }
463
- }
464
- }
465
- return { devices, detail: details.join("\n") || undefined, androidDiscoveryIncomplete };
356
+ const { devices, detail, androidDiscoveryIncomplete } = yield* ready.devices.list;
357
+ return {
358
+ devices: devices.map((device): DeviceSummary => ({ ...device, hostId: ready.hostId })),
359
+ detail,
360
+ androidDiscoveryIncomplete,
361
+ };
362
});
363
364
const refresh = Effect.fn("DeviceService.refresh")(function* (ready: DeviceReadiness) {
@@ -640,68 +536,6 @@ export const makeWithHosts = Effect.fn("DeviceService.makeWithHosts")(function*
536
}
537
});
538
643
- /**
644
- * Android AVDs change id when they boot (AVD name to emulator serial), so the
645
- * returned id is authoritative.
646
- */
647
- const boot = Effect.fn("DeviceService.boot")(function* (
648
- ready: DeviceReadiness,
649
- device: DeviceSummary,
650
- ) {
651
- const result = yield* HttpClientRequest.post(`${ready.hub.origin}/api/devices/boot`).pipe(
652
- HttpClientRequest.bodyJson({ platform: device.platform, id: device.id, name: device.name }),
653
- Effect.mapError(
654
- (cause) =>
655
- new DeviceOperationError({ operation: "boot", reason: "invalid_payload", cause }),
656
- ),
657
- Effect.flatMap((request) => hubJson(request, HubActionResult, "boot", BOOT_TIMEOUT)),
658
- );
659
- if (!result.ok) {
660
- // Keep the hub's launch command and nested failure available to agents for recovery.
661
- const diagnostics = [
662
- result.error,
663
- ...(result.errors ?? []).flatMap((error) => [error.message, error.error]),
664
- ]
665
- .filter((text) => text?.trim())
666
- .join("\n\n");
667
- return yield* new DeviceBootError({
668
- hostId: ready.hostId,
669
- deviceId: device.id,
670
- reason: /insufficient.*(?:disk|space)|not enough.*(?:disk|space)|no space left/i.test(
671
- diagnostics,
672
- )
673
- ? "disk_space"
674
- : /timed? out|timeout/i.test(diagnostics)
675
- ? "timeout"
676
- : "launch_failed",
677
- ...(diagnostics
678
- ? {
679
- diagnostics:
680
- diagnostics.length > 2_000 ? `${diagnostics.slice(0, 1_999)}…` : diagnostics,
681
- }
682
- : {}),
683
- cause: result,
684
- });
685
- }
686
- if (device.platform === "ios") {
687
- // Booting alone does not attach a serve-sim helper; the grid start
688
- // does both and is idempotent for a booted simulator.
689
- yield* HttpClientRequest.post(
690
- `${ready.hub.origin}${vendorPrefix("ios")}/grid/api/start`,
691
- ).pipe(
692
- HttpClientRequest.bodyJson({ udid: device.id }),
693
- Effect.mapError(
694
- (cause) =>
695
- new DeviceOperationError({ operation: "boot", reason: "invalid_payload", cause }),
696
- ),
697
- Effect.flatMap((request) =>
698
- hubJson(request, HubActionResult, "attach stream", BOOT_TIMEOUT),
699
- ),
700
- );
701
- }
702
- return result.serial ?? result.id ?? device.id;
703
- });
704
-
539
const open: DeviceService["Service"]["open"] = Effect.fn("DeviceService.open")(function* (input) {
540
const host = yield* resolveHost(input.hostId);
541
yield* ensurePlatform(host, input.platform);
@@ -749,7 +583,7 @@ process.exitCode = result.error ? 1 : (result.status ?? 1);`,
583
booting,
584
],
585
}));
752
- const bootedId = yield* boot(ready, device).pipe(
586
+ const bootedId = yield* ready.devices.boot(device).pipe(
587
Effect.ensuring(
588
publish((current) => ({
589
...current,
@@ -764,19 +598,8 @@ process.exitCode = result.error ? 1 : (result.status ?? 1);`,
598
if (!device) {
599
return yield* new DeviceNotFoundError({ hostId: host.id, deviceId: bootedId });
600
}
767
- } else if (device.platform === "ios" && device.booted) {
768
- yield* HttpClientRequest.post(
769
- `${ready.hub.origin}${vendorPrefix("ios")}/grid/api/start`,
770
- ).pipe(
771
- HttpClientRequest.bodyJson({ udid: device.id }),
772
- Effect.mapError(
773
- (cause) =>
774
- new DeviceOperationError({ operation: "open", reason: "invalid_payload", cause }),
775
- ),
776
- Effect.flatMap((request) =>
777
- hubJson(request, HubActionResult, "attach stream", BOOT_TIMEOUT),
778
- ),
779
- );
601
+ } else if (device.booted) {
602
+ yield* ready.devices.attach(device);
603
}
604
if (hosts.get(host.id) !== host)
605
return yield* new DeviceHostUnavailableError({
@@ -823,43 +646,7 @@ process.exitCode = result.error ? 1 : (result.status ?? 1);`,
646
platform: DevicePlatform,
647
) {
648
const ready = yield* readiness(hostId);
826
- const postShutdown = (path: string, body: Record<string, string>) =>
827
- HttpClientRequest.post(`${ready.hub.origin}${path}`).pipe(
828
- HttpClientRequest.bodyJson(body),
829
- Effect.mapError(
830
- (cause) =>
831
- new DeviceOperationError({ operation: "shutdown", reason: "invalid_payload", cause }),
832
- ),
833
- Effect.flatMap((request) => hubJson(request, HubActionResult, "shutdown")),
834
- Effect.flatMap((result) =>
835
- result.ok
836
- ? Effect.void
837
- : Effect.fail(
838
- new DeviceOperationError({
839
- operation: "shutdown",
840
- reason: "hub_rejected",
841
- cause: result,
842
- }),
843
- ),
844
- ),
845
- );
846
- // serve-sim's shutdown closes its in-process capture session before it runs
847
- // `simctl shutdown`; the hub's generic shutdown can leave that session cached
848
- // across a reboot. serve-sim runs simctl bare, though, so a simulator that is
849
- // already off fails there.
850
- yield* platform === "ios"
851
- ? postShutdown(`${vendorPrefix("ios")}/grid/api/shutdown`, { udid: deviceId }).pipe(
852
- Effect.catch((cause) =>
853
- fetchDevices(ready).pipe(
854
- Effect.flatMap(({ devices }) =>
855
- devices.find((device) => device.id === deviceId)?.booted === false
856
- ? Effect.logInfo("iOS simulator was already shut down", { deviceId })
857
- : Effect.fail(cause),
858
- ),
859
- ),
860
- ),
861
- )
862
- : postShutdown("/api/devices/shutdown", { platform, id: deviceId });
649
+ yield* ready.devices.shutdown({ id: deviceId, platform });
650
yield* publish((state) => ({
651
...state,
652
devices: state.devices.map((device) =>
@@ -920,23 +707,7 @@ process.exitCode = result.error ? 1 : (result.status ?? 1);`,
707
const screenshot: DeviceService["Service"]["screenshot"] = Effect.fn("DeviceService.screenshot")(
708
function* (input) {
709
const { ready, device } = yield* resolveDevice(input.hostId, input.deviceId);
923
- const url = `${ready.hub.origin}${vendorPrefix(device.platform)}/api/screenshot?device=${encodeURIComponent(device.id)}`;
924
- const png = yield* httpClient.execute(HttpClientRequest.post(url)).pipe(
925
- Effect.flatMap(HttpClientResponse.filterStatusOk),
926
- Effect.flatMap((response) => response.arrayBuffer),
927
- Effect.map((buffer) => new Uint8Array(buffer)),
928
- Effect.scoped,
929
- Effect.timeout(SCREENSHOT_TIMEOUT),
930
- Effect.mapError(
931
- (cause) =>
932
- new DeviceOperationError({
933
- operation: "screenshot",
934
- reason: "request_failed",
935
- cause,
936
- }),
937
- ),
938
- );
939
- return { device, png };
710
+ return { device, png: yield* ready.devices.screenshot(device) };
711
},
712
);
713
apps/server/src/device/LocalDeviceHost.ts
+10
@@ -40,6 +40,7 @@ import { writeFileStringAtomically } from "@t3tools/shared/atomicWrite";
40
import * as ServerConfig from "../config.ts";
41
import * as ProcessRunner from "../processRunner.ts";
42
import * as DeviceHost from "./DeviceHost.ts";
43
+import { makeDeviceHubOperations } from "./DeviceHubOperations.ts";
44
import {
45
agentDeviceStateDir,
46
type DeviceToolPaths,
@@ -823,6 +824,15 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {
824
825
const toReady = (running: RunningHost): DeviceHost.DeviceHostReady => ({
826
hub: { origin: running.hub.origin } satisfies DeviceHost.DeviceHubEndpoint,
827
+ devices: makeDeviceHubOperations({
828
+ hostId,
829
+ origin: running.hub.origin,
830
+ http: httpClient,
831
+ run,
832
+ androidAvailable: platformAvailability("android").pipe(
833
+ Effect.map((availability) => availability.available),
834
+ ),
835
+ }),
836
nodePath: running.hub.nodePath,
837
run,
838
helpers: running.helpers,
apps/server/src/device/SshDeviceHost.ts
+28
-13
@@ -23,6 +23,7 @@ import * as ChildProcess from "effect/process/ChildProcess";
23
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
24
import * as ServerConfig from "../config.ts";
25
import * as DeviceHost from "./DeviceHost.ts";
26
+import { makeDeviceHubOperations } from "./DeviceHubOperations.ts";
27
import { quoteRemoteArg, remoteDeviceEnvironment, remoteDeviceScript } from "./sshDeviceScript.ts";
28
29
const Probe = Schema.Struct({
@@ -191,6 +192,21 @@ export const make = Effect.fn("SshDeviceHost.make")(function* (
192
),
193
);
194
195
+ const platformAvailability: DeviceHost.DeviceHost["Service"]["platformAvailability"] = (
196
+ platform,
197
+ ) =>
198
+ provide(probe(config, owner)).pipe(
199
+ Effect.map((value) => {
200
+ summary = { ...summary, platforms: value.platforms };
201
+ return value.platforms.find((p) => p.platform === platform)!;
202
+ }),
203
+ Effect.orElseSucceed(() => ({
204
+ platform,
205
+ available: false,
206
+ reason: "Cannot reach device host. Test its SSH connection in Settings.",
207
+ })),
208
+ );
209
+
210
const connectOnce = Effect.fn("SshDeviceHost.connectOnce")(function* (): Effect.fn.Return<
211
DeviceHost.DeviceHostReady & { agentDevice?: DeviceHost.DeviceHostAgentReady["agentDevice"] },
212
DeviceHost.DeviceHostError
@@ -292,9 +308,19 @@ export const make = Effect.fn("SshDeviceHost.make")(function* (
308
),
309
Effect.forkIn(scope),
310
);
311
+ const hubOrigin = `http://127.0.0.1:${hubPort}`;
312
const next = {
313
nodePath: remote.nodePath,
297
- hub: { origin: `http://127.0.0.1:${hubPort}` },
314
+ hub: { origin: hubOrigin },
315
+ devices: makeDeviceHubOperations({
316
+ hostId: config.id,
317
+ origin: hubOrigin,
318
+ http,
319
+ run,
320
+ androidAvailable: platformAvailability("android").pipe(
321
+ Effect.map((availability) => availability.available),
322
+ ),
323
+ }),
324
...(remote.daemonPort !== undefined &&
325
remote.token !== undefined &&
326
remote.entryPath !== undefined
@@ -481,17 +507,6 @@ export const make = Effect.fn("SshDeviceHost.make")(function* (
507
),
508
stopAgent: changeAgent(false).pipe(Effect.asVoid, Effect.ignore),
509
stop,
484
- platformAvailability: (platform) =>
485
- provide(probe(config, owner)).pipe(
486
- Effect.map((value) => {
487
- summary = { ...summary, platforms: value.platforms };
488
- return value.platforms.find((p) => p.platform === platform)!;
489
- }),
490
- Effect.orElseSucceed(() => ({
491
- platform,
492
- available: false,
493
- reason: "Cannot reach device host. Test its SSH connection in Settings.",
494
- })),
495
- ),
510
+ platformAvailability,
511
} satisfies DeviceHost.DeviceHost["Service"];
512
});
docs/internals/devices.md
+5
-2
@@ -18,8 +18,11 @@ middleware because serve-sim loads private CoreSimulator frameworks through a
18
native addon, and a crash there must not take the server down.
19
20
Everything platform-specific sits behind
21
-[`DeviceHost`](../../apps/server/src/device/DeviceHost.ts). The service, the
22
-proxy, and the MCP tools only see a hub origin and an agent-device endpoint.
21
+[`DeviceHost`](../../apps/server/src/device/DeviceHost.ts). The service lists,
22
+boots, and shuts down devices through the host's device operations, and the
23
+proxy and the MCP tools only see a hub origin and an agent-device endpoint.
24
+Hosts that run expo-device-hub share one hub-backed implementation of those
25
+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