Skip to content
2 changes: 2 additions & 0 deletions packages/serve-sim/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,8 @@ serve-sim camera --stop-webcam

Multiple booted simulators are supported — pass several device names, or leave it empty to attach to all of them.

Helpers started by `--detach` or `--no-preview` exit after their target simulators remain shut down beyond the grace period. A failed check keeps the helper alive.

### Remote access (`--auth-token`)

Requests that don't come straight from this machine — LAN clients, tunnels, reverse proxies — are refused unless the server is started with `--auth-token <token>` (or `SERVE_SIM_AUTH_TOKEN`). CLI and scripted clients send `Authorization: Bearer <token>`. To share the preview with a browser, send the link with the token in the URL fragment:
Expand Down
19 changes: 1 addition & 18 deletions packages/serve-sim/src/__tests__/devtools-proxy.test.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,10 @@
import { afterEach, describe, expect, test } from "bun:test";
import { mkdirSync, rmSync, writeFileSync } from "fs";
import { createServer as createNetServer } from "net";
import { spawn, type ChildProcess } from "child_process";
import { simMiddleware, type ServeSimState, type WebKitBridge } from "../middleware";
import { servePreview, type PreviewServer } from "../runtime";
import { STATE_DIR, stateFileForDevice } from "../state";

async function freePort(): Promise<number> {
return new Promise((resolve, reject) => {
const server = createNetServer();
server.once("error", reject);
server.listen(0, "127.0.0.1", () => {
const addr = server.address();
if (!addr || typeof addr === "string") {
server.close();
reject(new Error("failed to allocate port"));
return;
}
const port = addr.port;
server.close(() => resolve(port));
});
});
}
import { freePort } from "./server-test-support";

describe("devtools proxy", () => {
const udid = "DEVTOOLS-PROXY-DEVICE";
Expand Down
9 changes: 1 addition & 8 deletions packages/serve-sim/src/__tests__/duo-preview-stream.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type { ServerResponse } from "http";
import { join } from "node:path";
import { DuoPreview, DUO_SETTLE_MS } from "../duo-preview";
import type { DuoProjection } from "../duo-renderer";
import { waitFor } from "./server-test-support";

class FakeResponse {
writableLength = 0;
Expand Down Expand Up @@ -42,14 +43,6 @@ function harness() {
return { preview, calls };
}

async function waitFor(predicate: () => boolean): Promise<void> {
const deadline = Date.now() + 1_000;
while (!predicate()) {
if (Date.now() >= deadline) throw new Error("condition not reached");
await new Promise((resolve) => setTimeout(resolve, 5));
}
}

describe("Duo live preview stream", () => {
test("motion uses the fast target and sharpens once after settle", async () => {
const { preview, calls } = harness();
Expand Down
19 changes: 19 additions & 0 deletions packages/serve-sim/src/__tests__/fixtures/shutdown-watch-xcrun.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#!/bin/sh
set -eu

case "$*" in
"simctl list devices booted -j")
printf started > "$SERVE_SIM_TEST_QUERY_DIR/query-started"
while [ ! -e "$SERVE_SIM_TEST_QUERY_DIR/release-query" ]; do
sleep 0.02
done
printf finished > "$SERVE_SIM_TEST_QUERY_DIR/query-finished"
;;
"simctl list devices -j") ;;
*)
printf 'Refusing unexpected simulator command: %s\n' "$*" >&2
exit 88
;;
esac

printf '{"devices":{"test":[{"udid":"%s","state":"Booted"}]}}\n' "$SERVE_SIM_TEST_UDID"
24 changes: 24 additions & 0 deletions packages/serve-sim/src/__tests__/server-test-support.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { createServer } from "net";
import { setTimeout as delay } from "timers/promises";

export async function freePort(): Promise<number> {
const server = createServer();
const ready = Promise.withResolvers<void>();
server.once("error", ready.reject);
server.listen(0, "127.0.0.1", ready.resolve);
await ready.promise;
const address = server.address();
const closed = Promise.withResolvers<void>();
server.close((error) => error ? closed.reject(error) : closed.resolve());
await closed.promise;
if (!address || typeof address === "string") throw new Error("failed to allocate port");
return address.port;
}

export async function waitFor(predicate: () => boolean, timeoutMs = 1_000, intervalMs = 5): Promise<void> {
const deadline = Date.now() + timeoutMs;
while (!predicate()) {
if (Date.now() >= deadline) throw new Error("condition not reached");
await delay(intervalMs);
}
}
88 changes: 88 additions & 0 deletions packages/serve-sim/src/__tests__/shutdown-watch-responsive.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import { expect, test } from "bun:test";
import { spawn, type ChildProcess } from "child_process";
import { chmodSync, copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "fs";
import { tmpdir } from "os";
import { delimiter, join } from "path";
import { freePort, waitFor } from "./server-test-support";

const udid = "00000000-0000-4000-8000-000000000102";

// The real CLI subprocess's watchdog cannot use the test process's fake clock.
test.skipIf(process.platform === "win32")("serves HTTP while the shutdown boot-state query is pending", async () => {
const root = mkdtempSync(join(tmpdir(), "serve-sim-shutdown-watch-"));
const bin = join(root, "bin");
const started = join(root, "query-started");
const finished = join(root, "query-finished");
const release = join(root, "release-query");
let child: ChildProcess | undefined;
let stderr = "";
let exited = false;
const { promise: closed, resolve: resolveClosed } = Promise.withResolvers<void>();
const waitClosed = async (ms: number) => {
const timeout = Promise.withResolvers<void>();
const timer = setTimeout(timeout.resolve, ms);
try {
await Promise.race([closed, timeout.promise]);
} finally {
clearTimeout(timer);
}
};
try {
mkdirSync(bin);
const xcrun = join(bin, "xcrun");
copyFileSync(join(import.meta.dir, "fixtures/shutdown-watch-xcrun.sh"), xcrun);
chmodSync(xcrun, 0o700);
writeFileSync(join(bin, "open"), "#!/bin/sh\nexit 88\n", { mode: 0o700 });
const env: NodeJS.ProcessEnv = { ...process.env, PATH: `${bin}${delimiter}${process.env.PATH ?? ""}`, TMPDIR: root, TMP: root, TEMP: root };
for (const key of Object.keys(env)) {
if (key.startsWith("SERVE_SIM_") || ["NODE_OPTIONS", "NODE_PATH", "DEBUG"].includes(key)) delete env[key];
}
env.SERVE_SIM_TEST_QUERY_DIR = root;
env.SERVE_SIM_TEST_UDID = udid;
const port = await freePort();
child = spawn(process.execPath, [join(import.meta.dir, "../index.ts"), udid,
"--port", String(port), "--host", "127.0.0.1", "--exit-on-simulator-shutdown"], {
env, stdio: ["ignore", "ignore", "pipe"],
});
child.stderr?.on("data", (data) => { stderr += data; });
child.once("close", () => { exited = true; resolveClosed(); });
child.once("error", () => { exited = true; resolveClosed(); });
const stateFile = join(root, "serve-sim", `server-${udid}.json`);
await waitFor(() => {
if (exited) throw new Error("CLI exited before readiness: " + stderr);
return existsSync(stateFile);
}, 10_000, 20);
const state = JSON.parse(readFileSync(stateFile, "utf8"));
expect(state.pid).toBe(child.pid);
expect(state.port).toBe(port);
await waitFor(() => {
if (exited) throw new Error("CLI exited before its boot query: " + stderr);
return existsSync(started);
}, 10_000, 20);
expect(existsSync(finished)).toBe(false);
const response = await fetch(`http://127.0.0.1:${port}/__shutdown_watch_probe__`, { signal: AbortSignal.timeout(1_500) });
await response.arrayBuffer();
expect(response.status).toBe(404);
expect(existsSync(finished)).toBe(false);
} catch (error) {
throw new Error("CLI shutdown-watch probe failed: " + stderr, { cause: error });
} finally {
try {
if (child) {
writeFileSync(release, "release");
if (existsSync(started) && !exited) await waitFor(() => existsSync(finished), 3_500, 20);
}
} finally {
try {
if (child) {
if (!exited) child.kill("SIGTERM");
await waitClosed(2_000);
if (!exited) child.kill("SIGKILL");
await closed;
}
} finally {
rmSync(root, { recursive: true, force: true });
}
}
}
}, 20_000);
52 changes: 33 additions & 19 deletions packages/serve-sim/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
#!/usr/bin/env node
import WebSocket from "ws";
import { Command, InvalidArgumentError } from "commander";
import { execFileSync, execSync, spawn as nodeSpawn, type ChildProcess } from "child_process";
import { execFile, execFileSync, execSync, spawn as nodeSpawn, type ChildProcess } from "child_process";
import { existsSync, mkdirSync, openSync, closeSync, readSync, readFileSync, statSync, unlinkSync, writeFileSync } from "fs";
import { createHash, randomBytes } from "crypto";
import { networkInterfaces } from "os";
import { dirname, join, resolve } from "path";
import { promisify } from "util";
import {
STATE_DIR,
stateFileForDevice,
Expand Down Expand Up @@ -93,6 +94,7 @@ import { redactHome } from "./diagnostics-redact";
// `import.meta.dir` is Bun-only; resolve once via fileURLToPath so the bundled
// CLI works under plain `node` too.
const __dirname = dirnameOf(import.meta.url);
const execFileAsync = promisify(execFile);

// Stamped in at build time (see build.ts), mirroring __PREVIEW_HTML_B64__. In
// the un-bundled dev run the define is absent, so fall back to reading the
Expand Down Expand Up @@ -135,18 +137,11 @@ function readState(udid?: string): ServerState | null {

/**
* Snapshot simctl's boot state for `--detach` reuse and the shutdown watch.
* Cached for 1 second so a flurry of lookups shares one `simctl` call.
*/
let bootedSnapshot: { at: number; booted: Set<string> | null } = { at: 0, booted: null };
function getBootedUdids(): Set<string> | null {
const now = Date.now();
if (bootedSnapshot.booted && now - bootedSnapshot.at < 1000) {
return bootedSnapshot.booted;
}
async function queryBootedUdids(): Promise<Set<string> | null> {
try {
const output = execSync("xcrun simctl list devices booted -j", {
const { stdout: output } = await execFileAsync("xcrun", ["simctl", "list", "devices", "booted", "-j"], {
encoding: "utf-8",
stdio: ["ignore", "pipe", "pipe"],
timeout: 3_000,
});
const data = JSON.parse(output) as {
Expand All @@ -158,7 +153,6 @@ function getBootedUdids(): Set<string> | null {
if (device.state === "Booted") booted.add(device.udid);
}
}
bootedSnapshot = { at: now, booted };
return booted;
} catch {
// simctl lookup failed (Xcode offline, etc.) — we can't prove the device
Expand All @@ -168,6 +162,29 @@ function getBootedUdids(): Set<string> | null {
}
}

let bootedSnapshot: Promise<Set<string> | null> | null = null;
let bootedSnapshotAt: number | null = null;

/** Share in-flight lookups, then cache successful snapshots for 1 second. */
function getBootedUdids(): Promise<Set<string> | null> {
if (
bootedSnapshot &&
(bootedSnapshotAt === null || Date.now() - bootedSnapshotAt < 1000)
) {
return bootedSnapshot;
}
bootedSnapshotAt = null;
bootedSnapshot = queryBootedUdids().then((booted) => {
if (booted) {
bootedSnapshotAt = Date.now();
} else {
bootedSnapshot = null;
}
return booted;
});
return bootedSnapshot;
}

function readStateFile(file: string): ServerState | null {
try {
if (!existsSync(file)) {
Expand Down Expand Up @@ -202,10 +219,10 @@ function readStateFile(file: string): ServerState | null {
* different `--auth-token` (or none), or a different `--allow-exec` opt-in,
* is never reused: that is an error.
*/
function readReusableState(udid: string, allowExec: boolean): ServerState | null {
async function readReusableState(udid: string, allowExec: boolean): Promise<ServerState | null> {
const state = readState(udid);
if (!state) return null;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const action = classifyStaleState(state, getBootedUdids(), process.pid);
const action = classifyStaleState(state, await getBootedUdids(), process.pid);
if (action === "keep") {
const mismatch =
reuseAuthMismatch(state, resolveAuthToken(undefined)) ?? reuseExecMismatch(state, allowExec);
Expand Down Expand Up @@ -477,7 +494,7 @@ async function follow(devices: string[], startPort: number, quiet: boolean, allo

for (const udid of udids) {
// Return existing server if already running (and still bound to a booted sim)
const existing = readReusableState(udid, allowExec);
const existing = await readReusableState(udid, allowExec);
if (existing) {
if (!quiet) {
const name = getDeviceName(udid) ?? udid;
Expand Down Expand Up @@ -594,7 +611,7 @@ async function detach(devices: string[], startPort: number, allowExec: boolean):
let port = startPort;

for (const udid of udids) {
const existing = readReusableState(udid, allowExec);
const existing = await readReusableState(udid, allowExec);
if (existing) {
states.push(existing);
continue;
Expand Down Expand Up @@ -2091,10 +2108,7 @@ async function serve(
// grid can boot another device without tearing down the HTTP server.
if (exitOnSimulatorShutdown) {
startSimulatorShutdownWatch(targetDevices, {
checkBooted: async () => {
bootedSnapshot = { at: 0, booted: null };
return getBootedUdids();
},
checkBooted: queryBootedUdids,
onExit: () => {
const label = targetDevices.join(", ");
console.error(
Expand Down