Skip to content
TypeScript

fix(devices): skip Apple device discovery on non-Mac hosts (#18159)

Tristan Knight27ccbe9dd542
diff --git a/apps/server/src/device/LocalDeviceHost.test.ts b/apps/server/src/device/LocalDeviceHost.test.ts
index 3a0fa3094fc..6b921aaad97 100644
--- a/apps/server/src/device/LocalDeviceHost.test.ts
+++ b/apps/server/src/device/LocalDeviceHost.test.ts
@@ -12,7 +12,7 @@ import * as Stream from "effect/Stream";
import * as LocalDeviceHost from "./LocalDeviceHost.ts";
import * as NodeServices from "@effect/platform-node/NodeServices";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
-import { HttpClient, HttpClientResponse } from "effect/http";
+import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";
import * as NetService from "@t3tools/shared/Net";
import * as ServerConfig from "../config.ts";
import * as ProcessRunner from "../processRunner.ts";
@@ -461,6 +461,47 @@ it.effect(
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
);
+it.live("limits hub discovery to Android unless the host is a Mac", () =>
+ Effect.gen(function* () {
+ if ((yield* HostProcess.Platform) === "win32") return;
+ const fs = yield* FileSystem.FileSystem;
+ const path = yield* Path.Path;
+ const environment = yield* HostProcess.Environment;
+ const hubArguments = Effect.fn(function* (platform: NodeJS.Platform) {
+ const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-hub-" });
+ const installDir = path.join(baseDir, "tools/expo-device-hub", DEVICE_HUB_VERSION);
+ const entryPath = path.join(installDir, "node_modules/expo-device-hub/dist/server/cli.mjs");
+ const argumentsPath = path.join(baseDir, "hub-args.json");
+ yield* fs.makeDirectory(path.dirname(entryPath), { recursive: true });
+ yield* fs.writeFileString(path.join(installDir, ".install-complete"), DEVICE_HUB_VERSION);
+ yield* fs.writeFileString(
+ entryPath,
+ `import http from 'node:http'; import fs from 'node:fs';
+const args=process.argv.slice(2); fs.writeFileSync(${JSON.stringify(argumentsPath)},JSON.stringify(args));
+http.createServer((req,res)=>res.end('ok')).listen(Number(args[args.indexOf('--port')+1]),'127.0.0.1');`,
+ );
+ const host = yield* LocalDeviceHost.make().pipe(
+ Effect.provide(
+ Layer.mergeAll(
+ ServerConfig.layerTest(baseDir, baseDir),
+ NetService.layer,
+ ProcessRunner.layer,
+ FetchHttpClient.layer,
+ ),
+ ),
+ Effect.provideService(HostProcess.Environment, { ...environment, HOME: baseDir }),
+ Effect.provideService(HostProcess.Platform, platform),
+ );
+ yield* host.ensureReady(() => Effect.void).pipe(Effect.ensuring(host.stop));
+ return (yield* fs
+ .readFileString(argumentsPath)
+ .pipe(Effect.map((contents) => JSON.parse(contents)))) as ReadonlyArray<string>;
+ });
+ expect((yield* hubArguments("linux")).slice(-2)).toEqual(["--platform", "android"]);
+ expect(yield* hubArguments("darwin")).not.toContain("--platform");
+ }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
+);
+
it.effect(
"constructs and inspects an unconfigured host without installing or starting helpers",
() =>
diff --git a/apps/server/src/device/LocalDeviceHost.ts b/apps/server/src/device/LocalDeviceHost.ts
index 35927300690..f5aa43e13a7 100644
--- a/apps/server/src/device/LocalDeviceHost.ts
+++ b/apps/server/src/device/LocalDeviceHost.ts
@@ -224,6 +224,10 @@ const hubEnvironment = Effect.fn("LocalDeviceHost.hubEnvironment")(function* (
return env;
});
+/** Only a Mac can list Apple simulators; elsewhere the hub's attempt surfaces as an error. */
+const hubPlatformArguments = (hostPlatform: NodeJS.Platform) =>
+ hostPlatform === "darwin" ? [] : ["--platform", "android"];
+
export const make = Effect.fn("LocalDeviceHost.make")(function* () {
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
const config = yield* ServerConfig.ServerConfig;
@@ -394,6 +398,7 @@ export const make = Effect.fn("LocalDeviceHost.make")(function* () {
"127.0.0.1",
"--hide-sidebar",
"--hide-boot-device",
+ ...hubPlatformArguments(hostPlatform),
],
{
detached: false,
diff --git a/apps/server/src/device/sshDeviceScript.test.ts b/apps/server/src/device/sshDeviceScript.test.ts
index e69a3dd7cde..ffff2c9cfe6 100644
--- a/apps/server/src/device/sshDeviceScript.test.ts
+++ b/apps/server/src/device/sshDeviceScript.test.ts
@@ -73,7 +73,7 @@ describe("remote helper lifecycle", () => {
hub,
`import http from 'node:http'; import fs from 'node:fs';
if(fs.existsSync('fail-start-once')) {fs.unlinkSync('fail-start-once');process.exit(1);}
-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');`,
+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');`,
);
await NodeFSP.writeFile(
agent,
@@ -89,6 +89,12 @@ else { const child=spawn(process.execPath,[path.join(path.dirname(process.argv[1
await NodeFSP.copyFile(agent, NodePath.join(NodePath.dirname(agent), "daemon.mjs"));
const nextHubVersion = DEVICE_HUB_VERSION + "-upgrade";
const nextAgentVersion = AGENT_DEVICE_VERSION + "-upgrade";
+ // Each owner stands in for a host on a different platform.
+ const hostPlatforms: Record<string, NodeJS.Platform> = { one: "linux", two: "darwin" };
+ const hubArgs = async (owner: string): Promise<ReadonlyArray<string>> =>
+ JSON.parse(
+ await NodeFSP.readFile(NodePath.join(root, `hosts/${owner}/hub-args.json`), "utf8"),
+ );
let invocation = 0;
const invoke = async (
owner: string,
@@ -98,7 +104,8 @@ else { const child=spawn(process.execPath,[path.join(path.dirname(process.argv[1
const file = NodePath.join(home, `${owner}-${mode}-${invocation++}.cjs`);
await NodeFSP.writeFile(
file,
- `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` +
+ `Object.defineProperty(process, 'platform', { value: ${JSON.stringify(hostPlatforms[owner])} });\n` +
+ `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` +
remoteDeviceScript(owner, mode)
.replace(DEVICE_HUB_VERSION, upgraded ? nextHubVersion : DEVICE_HUB_VERSION)
.replace(AGENT_DEVICE_VERSION, upgraded ? nextAgentVersion : AGENT_DEVICE_VERSION),
@@ -134,6 +141,19 @@ else { const child=spawn(process.execPath,[path.join(path.dirname(process.argv[1
]);
expect(concurrent.hubPort).toBe(manual.hubPort);
expect(manual.daemonPort).toBeUndefined();
+ expect((await hubArgs("one")).slice(-2)).toEqual(["--platform", "android"]);
+ // A hub started before discovery was filtered has no recorded platform.
+ const hubFile = NodePath.join(root, "hosts/one/hub.json");
+ const { platform: _platform, ...unfilteredHub } = JSON.parse(
+ await NodeFSP.readFile(hubFile, "utf8"),
+ );
+ await NodeFSP.writeFile(hubFile, JSON.stringify(unfilteredHub));
+ const filtered = await invoke("one", "start");
+ expect(filtered.hubPort).not.toBe(manual.hubPort);
+ expect(await NodeFSP.readFile(NodePath.join(home, "stops"), "utf8")).toContain(
+ `${unfilteredHub.pid}\n`,
+ );
+ expect((await invoke("one", "start")).hubPort).toBe(filtered.hubPort);
await expect(
NodeFSP.stat(NodePath.join(root, "hosts/one/daemon.json")),
).rejects.toThrow();
@@ -149,6 +169,8 @@ else { const child=spawn(process.execPath,[path.join(path.dirname(process.argv[1
const second = await invoke("two", "agent-start");
const reused = await invoke("one", "agent-start");
expect(reused.hubPort).toBe(first.hubPort);
+ expect(await hubArgs("two")).not.toContain("--platform");
+ expect((await invoke("two", "start")).hubPort).toBe(second.hubPort);
expect(reused.daemonPort).toBe(first.daemonPort);
expect(second.hubPort).not.toBe(first.hubPort);
expect(second.daemonPort).not.toBe(first.daemonPort);
diff --git a/apps/server/src/device/sshDeviceScript.ts b/apps/server/src/device/sshDeviceScript.ts
index 6a39bc78700..3df4677d25b 100644
--- a/apps/server/src/device/sshDeviceScript.ts
+++ b/apps/server/src/device/sshDeviceScript.ts
@@ -164,19 +164,21 @@ async function install(name, version, entry) {
if (!ios && !android) throw Error(platforms.map(p => p.reason).join(' '));
fs.mkdirSync(state, { recursive: true, mode: 0o700 });
const hubEntry = await install('expo-device-hub', hubVersion, 'dist/server/cli.mjs');
+ // Only a Mac can list Apple simulators. Recording the filter replaces hubs started without it.
+ const hubPlatform = process.platform === 'darwin' ? undefined : 'android';
let hub = read(hubFile);
- if (!hub || hub.owner !== owner || hub.entryPath !== hubEntry || !await healthy(hub.port, '/readyz')) {
+ if (!hub || hub.owner !== owner || hub.entryPath !== hubEntry || hub.platform !== hubPlatform || !await healthy(hub.port, '/readyz')) {
stopHub(hub);
for (let attempt = 0; attempt < 5; attempt++) {
const hubPort = await port();
const log = fs.openSync(path.join(state, 'hub.log'), 'a');
- const child = spawn(process.execPath, [hubEntry, '--port', String(hubPort), '--host', '127.0.0.1', '--hide-sidebar', '--hide-boot-device'], {
+ const child = spawn(process.execPath, [hubEntry, '--port', String(hubPort), '--host', '127.0.0.1', '--hide-sidebar', '--hide-boot-device', ...(hubPlatform ? ['--platform', hubPlatform] : [])], {
cwd: state, detached: true, stdio: ['ignore', log, log], env: { ...process.env, FORCE_COLOR: '0', NO_COLOR: '1' },
});
try { await new Promise((resolve, reject) => { child.once('spawn', resolve); child.once('error', reject); }); }
finally { fs.closeSync(log); }
child.unref();
- hub = { owner, pid: child.pid, port: hubPort, entryPath: hubEntry };
+ hub = { owner, pid: child.pid, port: hubPort, entryPath: hubEntry, platform: hubPlatform };
write(hubFile, hub);
const deadline = Date.now() + 30000;
let listening = false;