Skip to content

Commit 3eb66f2

Browse files
committed
fix(devices): skip Apple device discovery on non-Mac hosts
The device hub lists Apple simulators with `xcrun simctl` on every host, so opening device support on Linux or Windows shows an `[apple-utils] Failed to run xcrun simctl list devices --json` error. Start the hub with `--platform android` when the machine running it is not a Mac, for both local and SSH hosts. SSH hubs record the filter so a hub started without it is replaced instead of reused. Mac hosts are unchanged.
1 parent 8d199b4 commit 3eb66f2

4 files changed

Lines changed: 77 additions & 6 deletions

File tree

‎apps/server/src/device/LocalDeviceHost.test.ts‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,11 @@ import * as Option from "effect/Option";
77
import * as Path from "effect/Path";
88
import * as FileSystem from "effect/FileSystem";
99

10+
import { DEVICE_HUB_VERSION } from "./DeviceToolchain.ts";
1011
import * as LocalDeviceHost from "./LocalDeviceHost.ts";
1112
import * as NodeServices from "@effect/platform-node/NodeServices";
1213
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
13-
import { HttpClient } from "effect/http";
14+
import { FetchHttpClient, HttpClient } from "effect/http";
1415
import * as NetService from "@t3tools/shared/Net";
1516
import * as ServerConfig from "../config.ts";
1617
import * as ProcessRunner from "../processRunner.ts";
@@ -179,6 +180,47 @@ it.effect(
179180
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
180181
);
181182

183+
it.live("limits hub discovery to Android unless the host is a Mac", () =>
184+
Effect.gen(function* () {
185+
if ((yield* HostProcess.Platform) === "win32") return;
186+
const fs = yield* FileSystem.FileSystem;
187+
const path = yield* Path.Path;
188+
const environment = yield* HostProcess.Environment;
189+
const hubArguments = Effect.fn(function* (platform: NodeJS.Platform) {
190+
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-hub-" });
191+
const installDir = path.join(baseDir, "tools/expo-device-hub", DEVICE_HUB_VERSION);
192+
const entryPath = path.join(installDir, "node_modules/expo-device-hub/dist/server/cli.mjs");
193+
const argumentsPath = path.join(baseDir, "hub-args.json");
194+
yield* fs.makeDirectory(path.dirname(entryPath), { recursive: true });
195+
yield* fs.writeFileString(path.join(installDir, ".install-complete"), DEVICE_HUB_VERSION);
196+
yield* fs.writeFileString(
197+
entryPath,
198+
`import http from 'node:http'; import fs from 'node:fs';
199+
const args=process.argv.slice(2); fs.writeFileSync(${JSON.stringify(argumentsPath)},JSON.stringify(args));
200+
http.createServer((req,res)=>res.end('ok')).listen(Number(args[args.indexOf('--port')+1]),'127.0.0.1');`,
201+
);
202+
const host = yield* LocalDeviceHost.make().pipe(
203+
Effect.provide(
204+
Layer.mergeAll(
205+
ServerConfig.layerTest(baseDir, baseDir),
206+
NetService.layer,
207+
ProcessRunner.layer,
208+
FetchHttpClient.layer,
209+
),
210+
),
211+
Effect.provideService(HostProcess.Environment, { ...environment, HOME: baseDir }),
212+
Effect.provideService(HostProcess.Platform, platform),
213+
);
214+
yield* host.ensureReady(() => Effect.void).pipe(Effect.ensuring(host.stop));
215+
return (yield* fs
216+
.readFileString(argumentsPath)
217+
.pipe(Effect.map((contents) => JSON.parse(contents)))) as ReadonlyArray<string>;
218+
});
219+
expect((yield* hubArguments("linux")).slice(-2)).toEqual(["--platform", "android"]);
220+
expect(yield* hubArguments("darwin")).not.toContain("--platform");
221+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
222+
);
223+
182224
it.effect(
183225
"constructs and inspects an unconfigured host without installing or starting helpers",
184226
() =>

‎apps/server/src/device/LocalDeviceHost.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -222,6 +222,10 @@ const hubEnvironment = Effect.fn("LocalDeviceHost.hubEnvironment")(function* (
222222
return env;
223223
});
224224

225+
/** Only a Mac can list Apple simulators; elsewhere the hub's attempt surfaces as an error. */
226+
const hubPlatformArguments = (hostPlatform: NodeJS.Platform) =>
227+
hostPlatform === "darwin" ? [] : ["--platform", "android"];
228+
225229
export const make = Effect.fn("LocalDeviceHost.make")(function* () {
226230
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
227231
const config = yield* ServerConfig.ServerConfig;
@@ -394,6 +398,7 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {
394398
"127.0.0.1",
395399
"--hide-sidebar",
396400
"--hide-boot-device",
401+
...hubPlatformArguments(hostPlatform),
397402
],
398403
{
399404
detached: false,

‎apps/server/src/device/sshDeviceScript.test.ts‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ describe("remote helper lifecycle", () => {
7373
hub,
7474
`import http from 'node:http'; import fs from 'node:fs';
7575
if(fs.existsSync('fail-start-once')) {fs.unlinkSync('fail-start-once');process.exit(1);}
76-
const args=process.argv.slice(2); http.createServer((req,res)=>{res.statusCode=fs.existsSync('unhealthy-'+process.pid)?503:200;res.end('ok');}).listen(Number(args[args.indexOf('--port')+1]),'127.0.0.1');`,
76+
const args=process.argv.slice(2); fs.writeFileSync('hub-args.json',JSON.stringify(args)); http.createServer((req,res)=>{res.statusCode=fs.existsSync('unhealthy-'+process.pid)?503:200;res.end('ok');}).listen(Number(args[args.indexOf('--port')+1]),'127.0.0.1');`,
7777
);
7878
await NodeFSP.writeFile(
7979
agent,
@@ -89,6 +89,12 @@ else { const child=spawn(process.execPath,[path.join(path.dirname(process.argv[1
8989
await NodeFSP.copyFile(agent, NodePath.join(NodePath.dirname(agent), "daemon.mjs"));
9090
const nextHubVersion = DEVICE_HUB_VERSION + "-upgrade";
9191
const nextAgentVersion = AGENT_DEVICE_VERSION + "-upgrade";
92+
// Each owner stands in for a host on a different platform.
93+
const hostPlatforms: Record<string, NodeJS.Platform> = { one: "linux", two: "darwin" };
94+
const hubArgs = async (owner: string): Promise<ReadonlyArray<string>> =>
95+
JSON.parse(
96+
await NodeFSP.readFile(NodePath.join(root, `hosts/${owner}/hub-args.json`), "utf8"),
97+
);
9298
let invocation = 0;
9399
const invoke = async (
94100
owner: string,
@@ -98,7 +104,8 @@ else { const child=spawn(process.execPath,[path.join(path.dirname(process.argv[1
98104
const file = NodePath.join(home, `${owner}-${mode}-${invocation++}.cjs`);
99105
await NodeFSP.writeFile(
100106
file,
101-
`const originalKill = process.kill; process.kill = (pid, signal) => { if (signal === 'SIGTERM') require('node:fs').appendFileSync(${JSON.stringify(NodePath.join(home, "stops"))}, pid+'\\n'); return originalKill(pid, signal); };\n` +
107+
`Object.defineProperty(process, 'platform', { value: ${JSON.stringify(hostPlatforms[owner])} });\n` +
108+
`const originalKill = process.kill; process.kill = (pid, signal) => { if (signal === 'SIGTERM') require('node:fs').appendFileSync(${JSON.stringify(NodePath.join(home, "stops"))}, pid+'\\n'); return originalKill(pid, signal); };\n` +
102109
remoteDeviceScript(owner, mode)
103110
.replace(DEVICE_HUB_VERSION, upgraded ? nextHubVersion : DEVICE_HUB_VERSION)
104111
.replace(AGENT_DEVICE_VERSION, upgraded ? nextAgentVersion : AGENT_DEVICE_VERSION),
@@ -135,6 +142,19 @@ else { const child=spawn(process.execPath,[path.join(path.dirname(process.argv[1
135142
]);
136143
expect(concurrent.hubPort).toBe(manual.hubPort);
137144
expect(manual.daemonPort).toBeUndefined();
145+
expect((await hubArgs("one")).slice(-2)).toEqual(["--platform", "android"]);
146+
// A hub started before discovery was filtered has no recorded platform.
147+
const hubFile = NodePath.join(root, "hosts/one/hub.json");
148+
const { platform: _platform, ...unfilteredHub } = JSON.parse(
149+
await NodeFSP.readFile(hubFile, "utf8"),
150+
);
151+
await NodeFSP.writeFile(hubFile, JSON.stringify(unfilteredHub));
152+
const filtered = await invoke("one", "start");
153+
expect(filtered.hubPort).not.toBe(manual.hubPort);
154+
expect(await NodeFSP.readFile(NodePath.join(home, "stops"), "utf8")).toContain(
155+
`${unfilteredHub.pid}\n`,
156+
);
157+
expect((await invoke("one", "start")).hubPort).toBe(filtered.hubPort);
138158
await expect(
139159
NodeFSP.stat(NodePath.join(root, "hosts/one/daemon.json")),
140160
).rejects.toThrow();
@@ -150,6 +170,8 @@ else { const child=spawn(process.execPath,[path.join(path.dirname(process.argv[1
150170
const second = await invoke("two", "agent-start");
151171
const reused = await invoke("one", "agent-start");
152172
expect(reused.hubPort).toBe(first.hubPort);
173+
expect(await hubArgs("two")).not.toContain("--platform");
174+
expect((await invoke("two", "start")).hubPort).toBe(second.hubPort);
153175
expect(reused.daemonPort).toBe(first.daemonPort);
154176
expect(second.hubPort).not.toBe(first.hubPort);
155177
expect(second.daemonPort).not.toBe(first.daemonPort);

‎apps/server/src/device/sshDeviceScript.ts‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -165,19 +165,21 @@ async function install(name, version, entry) {
165165
if (!ios && !android) throw Error(platforms.map(p => p.reason).join(' '));
166166
fs.mkdirSync(state, { recursive: true, mode: 0o700 });
167167
const hubEntry = await install('expo-device-hub', hubVersion, 'dist/server/cli.mjs');
168+
// Only a Mac can list Apple simulators. Recording the filter replaces hubs started without it.
169+
const hubPlatform = process.platform === 'darwin' ? undefined : 'android';
168170
let hub = read(hubFile);
169-
if (!hub || hub.owner !== owner || hub.entryPath !== hubEntry || !await healthy(hub.port, '/readyz')) {
171+
if (!hub || hub.owner !== owner || hub.entryPath !== hubEntry || hub.platform !== hubPlatform || !await healthy(hub.port, '/readyz')) {
170172
stopHub(hub);
171173
for (let attempt = 0; attempt < 5; attempt++) {
172174
const hubPort = await port();
173175
const log = fs.openSync(path.join(state, 'hub.log'), 'a');
174-
const child = spawn(process.execPath, [hubEntry, '--port', String(hubPort), '--host', '127.0.0.1', '--hide-sidebar', '--hide-boot-device'], {
176+
const child = spawn(process.execPath, [hubEntry, '--port', String(hubPort), '--host', '127.0.0.1', '--hide-sidebar', '--hide-boot-device', ...(hubPlatform ? ['--platform', hubPlatform] : [])], {
175177
cwd: state, detached: true, stdio: ['ignore', log, log], env: { ...process.env, FORCE_COLOR: '0', NO_COLOR: '1' },
176178
});
177179
try { await new Promise((resolve, reject) => { child.once('spawn', resolve); child.once('error', reject); }); }
178180
finally { fs.closeSync(log); }
179181
child.unref();
180-
hub = { owner, pid: child.pid, port: hubPort, entryPath: hubEntry };
182+
hub = { owner, pid: child.pid, port: hubPort, entryPath: hubEntry, platform: hubPlatform };
181183
write(hubFile, hub);
182184
const deadline = Date.now() + 30000;
183185
let listening = false;

0 commit comments

Comments
 (0)