Skip to content

Commit 27ccbe9

Browse files
authored
fix(devices): skip Apple device discovery on non-Mac hosts (pingdotgg#18159)
1 parent 2e8d70b commit 27ccbe9

4 files changed

Lines changed: 76 additions & 6 deletions

File tree

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

Lines changed: 42 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import * as Stream from "effect/Stream";
1212
import * as LocalDeviceHost from "./LocalDeviceHost.ts";
1313
import * as NodeServices from "@effect/platform-node/NodeServices";
1414
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
15-
import { HttpClient, HttpClientResponse } from "effect/http";
15+
import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http";
1616
import * as NetService from "@t3tools/shared/Net";
1717
import * as ServerConfig from "../config.ts";
1818
import * as ProcessRunner from "../processRunner.ts";
@@ -461,6 +461,47 @@ it.effect(
461461
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
462462
);
463463

464+
it.live("limits hub discovery to Android unless the host is a Mac", () =>
465+
Effect.gen(function* () {
466+
if ((yield* HostProcess.Platform) === "win32") return;
467+
const fs = yield* FileSystem.FileSystem;
468+
const path = yield* Path.Path;
469+
const environment = yield* HostProcess.Environment;
470+
const hubArguments = Effect.fn(function* (platform: NodeJS.Platform) {
471+
const baseDir = yield* fs.makeTempDirectoryScoped({ prefix: "t3-device-hub-" });
472+
const installDir = path.join(baseDir, "tools/expo-device-hub", DEVICE_HUB_VERSION);
473+
const entryPath = path.join(installDir, "node_modules/expo-device-hub/dist/server/cli.mjs");
474+
const argumentsPath = path.join(baseDir, "hub-args.json");
475+
yield* fs.makeDirectory(path.dirname(entryPath), { recursive: true });
476+
yield* fs.writeFileString(path.join(installDir, ".install-complete"), DEVICE_HUB_VERSION);
477+
yield* fs.writeFileString(
478+
entryPath,
479+
`import http from 'node:http'; import fs from 'node:fs';
480+
const args=process.argv.slice(2); fs.writeFileSync(${JSON.stringify(argumentsPath)},JSON.stringify(args));
481+
http.createServer((req,res)=>res.end('ok')).listen(Number(args[args.indexOf('--port')+1]),'127.0.0.1');`,
482+
);
483+
const host = yield* LocalDeviceHost.make().pipe(
484+
Effect.provide(
485+
Layer.mergeAll(
486+
ServerConfig.layerTest(baseDir, baseDir),
487+
NetService.layer,
488+
ProcessRunner.layer,
489+
FetchHttpClient.layer,
490+
),
491+
),
492+
Effect.provideService(HostProcess.Environment, { ...environment, HOME: baseDir }),
493+
Effect.provideService(HostProcess.Platform, platform),
494+
);
495+
yield* host.ensureReady(() => Effect.void).pipe(Effect.ensuring(host.stop));
496+
return (yield* fs
497+
.readFileString(argumentsPath)
498+
.pipe(Effect.map((contents) => JSON.parse(contents)))) as ReadonlyArray<string>;
499+
});
500+
expect((yield* hubArguments("linux")).slice(-2)).toEqual(["--platform", "android"]);
501+
expect(yield* hubArguments("darwin")).not.toContain("--platform");
502+
}).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
503+
);
504+
464505
it.effect(
465506
"constructs and inspects an unconfigured host without installing or starting helpers",
466507
() =>

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

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

227+
/** Only a Mac can list Apple simulators; elsewhere the hub's attempt surfaces as an error. */
228+
const hubPlatformArguments = (hostPlatform: NodeJS.Platform) =>
229+
hostPlatform === "darwin" ? [] : ["--platform", "android"];
230+
227231
export const make = Effect.fn("LocalDeviceHost.make")(function* () {
228232
const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
229233
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),
@@ -134,6 +141,19 @@ else { const child=spawn(process.execPath,[path.join(path.dirname(process.argv[1
134141
]);
135142
expect(concurrent.hubPort).toBe(manual.hubPort);
136143
expect(manual.daemonPort).toBeUndefined();
144+
expect((await hubArgs("one")).slice(-2)).toEqual(["--platform", "android"]);
145+
// A hub started before discovery was filtered has no recorded platform.
146+
const hubFile = NodePath.join(root, "hosts/one/hub.json");
147+
const { platform: _platform, ...unfilteredHub } = JSON.parse(
148+
await NodeFSP.readFile(hubFile, "utf8"),
149+
);
150+
await NodeFSP.writeFile(hubFile, JSON.stringify(unfilteredHub));
151+
const filtered = await invoke("one", "start");
152+
expect(filtered.hubPort).not.toBe(manual.hubPort);
153+
expect(await NodeFSP.readFile(NodePath.join(home, "stops"), "utf8")).toContain(
154+
`${unfilteredHub.pid}\n`,
155+
);
156+
expect((await invoke("one", "start")).hubPort).toBe(filtered.hubPort);
137157
await expect(
138158
NodeFSP.stat(NodePath.join(root, "hosts/one/daemon.json")),
139159
).rejects.toThrow();
@@ -149,6 +169,8 @@ else { const child=spawn(process.execPath,[path.join(path.dirname(process.argv[1
149169
const second = await invoke("two", "agent-start");
150170
const reused = await invoke("one", "agent-start");
151171
expect(reused.hubPort).toBe(first.hubPort);
172+
expect(await hubArgs("two")).not.toContain("--platform");
173+
expect((await invoke("two", "start")).hubPort).toBe(second.hubPort);
152174
expect(reused.daemonPort).toBe(first.daemonPort);
153175
expect(second.hubPort).not.toBe(first.hubPort);
154176
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
@@ -164,19 +164,21 @@ async function install(name, version, entry) {
164164
if (!ios && !android) throw Error(platforms.map(p => p.reason).join(' '));
165165
fs.mkdirSync(state, { recursive: true, mode: 0o700 });
166166
const hubEntry = await install('expo-device-hub', hubVersion, 'dist/server/cli.mjs');
167+
// Only a Mac can list Apple simulators. Recording the filter replaces hubs started without it.
168+
const hubPlatform = process.platform === 'darwin' ? undefined : 'android';
167169
let hub = read(hubFile);
168-
if (!hub || hub.owner !== owner || hub.entryPath !== hubEntry || !await healthy(hub.port, '/readyz')) {
170+
if (!hub || hub.owner !== owner || hub.entryPath !== hubEntry || hub.platform !== hubPlatform || !await healthy(hub.port, '/readyz')) {
169171
stopHub(hub);
170172
for (let attempt = 0; attempt < 5; attempt++) {
171173
const hubPort = await port();
172174
const log = fs.openSync(path.join(state, 'hub.log'), 'a');
173-
const child = spawn(process.execPath, [hubEntry, '--port', String(hubPort), '--host', '127.0.0.1', '--hide-sidebar', '--hide-boot-device'], {
175+
const child = spawn(process.execPath, [hubEntry, '--port', String(hubPort), '--host', '127.0.0.1', '--hide-sidebar', '--hide-boot-device', ...(hubPlatform ? ['--platform', hubPlatform] : [])], {
174176
cwd: state, detached: true, stdio: ['ignore', log, log], env: { ...process.env, FORCE_COLOR: '0', NO_COLOR: '1' },
175177
});
176178
try { await new Promise((resolve, reject) => { child.once('spawn', resolve); child.once('error', reject); }); }
177179
finally { fs.closeSync(log); }
178180
child.unref();
179-
hub = { owner, pid: child.pid, port: hubPort, entryPath: hubEntry };
181+
hub = { owner, pid: child.pid, port: hubPort, entryPath: hubEntry, platform: hubPlatform };
180182
write(hubFile, hub);
181183
const deadline = Date.now() + 30000;
182184
let listening = false;

0 commit comments

Comments
 (0)