mirror of
https://github.com/expo/eas-cli.git
synced 2026-11-15 17:31:46 -10:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
92e1b01bd7 | ||
|
|
9adcdfab1c | ||
|
|
444c926bb8 | ||
|
|
3e73b077ce | ||
|
|
3350e5c6f3 | ||
|
|
3ffbbb2f45 | ||
|
|
4e453e5d9c | ||
|
|
4f7ba2d5a3 |
No files matched your search
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'@expo/build-tools': patch
|
||||
---
|
||||
|
||||
Explain missing background task identifiers reported by App Store Connect.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'@expo/build-tools': patch
|
||||
---
|
||||
|
||||
Explain App Store Connect NOT_AUTHORIZED responses in the shared API client.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'@expo/build-tools': patch
|
||||
---
|
||||
|
||||
Explain App Store Connect UNEXPECTED_ERROR responses in the shared API client.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'@expo/build-tools': patch
|
||||
---
|
||||
|
||||
Explain missing app icons reported by App Store Connect, including codes 90022 and 90023, while preserving Apple’s validation details.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'@expo/build-tools': minor
|
||||
---
|
||||
|
||||
Use single-device previews when the session already has a valid device ID.
|
||||
@@ -19,7 +19,9 @@
|
||||
"@expo/downloader",
|
||||
"@expo/turtle-spawn",
|
||||
"@expo/template-file",
|
||||
"create-eas-build-function"
|
||||
"create-eas-build-function",
|
||||
"@expo/vm-tools",
|
||||
"@expo/simulator-launcher"
|
||||
]
|
||||
],
|
||||
"linked": [],
|
||||
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'eas-cli': minor
|
||||
---
|
||||
|
||||
Add an experiment that suggests Expo Update to coding agents after a build when the Free plan account is within 5 builds of the platform limit.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'@expo/build-tools': patch
|
||||
---
|
||||
|
||||
List failed Google Play commit attempts in order, including network failures, when the outcome is uncertain.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'eas-cli': minor
|
||||
---
|
||||
|
||||
Add `eas observe:traces` to list request trace spans (or a summary of span names and counts), `eas observe:trace` to display one trace as a span tree, and span rows in the `eas observe:session` timeline.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'@expo/worker': patch
|
||||
---
|
||||
|
||||
Run package-manager version queries in parallel during worker preparation.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'@expo/worker': patch
|
||||
---
|
||||
|
||||
Start the Xcode version check in the background during worker tool preparation. Apply the Xcode 26.0 upload workaround when the query finishes, without delaying job startup.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'eas-cli': patch
|
||||
---
|
||||
|
||||
Remove the Free plan build limit guidance experiment for coding agents from `eas build`.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'eas-cli': minor
|
||||
---
|
||||
|
||||
Import ordered action configurations with `eas simulator:control --import` and show progress for each action.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'eas-cli': minor
|
||||
---
|
||||
|
||||
Add searchable interactive simulator controls with session and device details, guided parameters, and action results.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'eas-cli': minor
|
||||
---
|
||||
|
||||
Start simulator sessions from saved settings and apply control actions after readiness.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'@expo/worker': patch
|
||||
---
|
||||
|
||||
Allow jobs to skip installing the CocoaPods cache proxy with EAS_BUILD_DISABLE_COCOAPODS_CACHE_PLUGIN=1.
|
||||
@@ -1,5 +0,0 @@
|
||||
---
|
||||
'@expo/build-tools': patch
|
||||
---
|
||||
|
||||
Preserve indented and incomplete Xcode compiler errors in formatted build logs, including the final diagnostic when logging stops.
|
||||
@@ -2,6 +2,37 @@
|
||||
|
||||
This is the log of notable changes to EAS CLI and related packages.
|
||||
|
||||
## [27.2.0](https://github.com/expo/eas-cli/releases/tag/v27.2.0) - 2026-10-29
|
||||
|
||||
### 🎉 New features
|
||||
|
||||
- [build-tools] Use single-device previews when the session already has a valid device ID. ([#4733](https://github.com/expo/eas-cli/pull/4733) by [@gwdp](https://github.com/gwdp))
|
||||
- [eas-cli] Add an experiment that suggests Expo Update to coding agents after a build when the Free plan account is within 5 builds of the platform limit. ([#4758](https://github.com/expo/eas-cli/pull/4758) by [@williamgrosset](https://github.com/williamgrosset))
|
||||
- [eas-cli] Add `eas observe:traces` to list request trace spans (or a summary of span names and counts), `eas observe:trace` to display one trace as a span tree, and span rows in the `eas observe:session` timeline. ([#4772](https://github.com/expo/eas-cli/pull/4772) by [@kadikraman](https://github.com/kadikraman))
|
||||
- [simulator-launcher] Accept a comma-separated list of warm Simulators in `EXPO_SIMULATOR_DEVICE`; the first is the default. One serve-sim serves every listed device on one port. After the default device is ready, warmup preinstalls the latest stable Expo Go from one download and tries to disable apsd on the other devices, until a job claims one. A claim can select any listed device and reports its preinstalled Expo Go. ([#4764](https://github.com/expo/eas-cli/pull/4764) by [@gwdp](https://github.com/gwdp))
|
||||
- [simulator-launcher] Add `@expo/simulator-launcher`, which warms an iOS Simulator at VM boot and hands it to one EAS job (`start`, `claim`, `prepare-tools`, `stop`). ([#4722](https://github.com/expo/eas-cli/pull/4722) by [@gwdp](https://github.com/gwdp))
|
||||
- [eas-cli] Show a one-time Expo Simulators hint after a successful build. ([#4768](https://github.com/expo/eas-cli/pull/4768) by [@FiberJW](https://github.com/FiberJW))
|
||||
- [vm-tools] Add a macOS startup script loader that runs `/usr/local/share/vm-tools/startup.sh` once per VM boot. ([#4725](https://github.com/expo/eas-cli/pull/4725) by [@gwdp](https://github.com/gwdp))
|
||||
|
||||
### 🐛 Bug fixes
|
||||
|
||||
- [build-tools] Explain missing background task identifiers reported by App Store Connect. ([#3465](https://github.com/expo/eas-cli/pull/3465) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
- [build-tools] Explain App Store Connect NOT_AUTHORIZED responses in the shared API client. ([#3462](https://github.com/expo/eas-cli/pull/3462) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
- [build-tools] Explain App Store Connect UNEXPECTED_ERROR responses in the shared API client. ([#3467](https://github.com/expo/eas-cli/pull/3467) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
- [build-tools] Explain missing app icons reported by App Store Connect, including codes 90022 and 90023, while preserving Apple’s validation details. ([#3466](https://github.com/expo/eas-cli/pull/3466) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
- [build-tools] List failed Google Play commit attempts in order, including network failures, when the outcome is uncertain. ([#4660](https://github.com/expo/eas-cli/pull/4660) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
- [worker] Run package-manager version queries in parallel during worker preparation. ([#4710](https://github.com/expo/eas-cli/pull/4710) by [@gwdp](https://github.com/gwdp))
|
||||
- [worker] Start the Xcode version check in the background during worker tool preparation. Apply the Xcode 26.0 upload workaround when the query finishes, without delaying job startup. ([#4707](https://github.com/expo/eas-cli/pull/4707) by [@gwdp](https://github.com/gwdp))
|
||||
- [build-tools] Fix a five-minute cleanup delay when a device session is canceled during startup and its screen recorder fails before connecting. ([#4761](https://github.com/expo/eas-cli/pull/4761) by [@gwdp](https://github.com/gwdp))
|
||||
- [eas-cli] Remove the Free plan build limit guidance experiment for coding agents from `eas build`. ([#4757](https://github.com/expo/eas-cli/pull/4757) by [@williamgrosset](https://github.com/williamgrosset))
|
||||
- [worker] Allow jobs to skip installing the CocoaPods cache proxy with EAS_BUILD_DISABLE_COCOAPODS_CACHE_PLUGIN=1. ([#4709](https://github.com/expo/eas-cli/pull/4709) by [@gwdp](https://github.com/gwdp))
|
||||
- [build-tools] Handle TURN requests for a stopped device session without reporting a warning. ([#4762](https://github.com/expo/eas-cli/pull/4762) by [@gwdp](https://github.com/gwdp))
|
||||
- [build-tools] Preserve indented and incomplete Xcode compiler errors in formatted build logs, including the final diagnostic when logging stops. ([#4365](https://github.com/expo/eas-cli/pull/4365) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
|
||||
### 🧹 Chores
|
||||
|
||||
- [simulator-launcher] Add the state, request command and service helpers for the warm Simulator launcher. The package stays private until #4722 adds its CLI entry point. ([#4766](https://github.com/expo/eas-cli/pull/4766) by [@gwdp](https://github.com/gwdp))
|
||||
|
||||
## [27.1.0](https://github.com/expo/eas-cli/releases/tag/v27.1.0) - 2026-10-28
|
||||
|
||||
### 🎉 New features
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"npmClient": "yarn",
|
||||
"version": "27.1.0",
|
||||
"version": "27.2.0",
|
||||
"$schema": "node_modules/lerna/schemas/lerna-schema.json"
|
||||
}
|
||||
@@ -1,5 +1,22 @@
|
||||
# @expo/build-tools
|
||||
|
||||
## 27.2.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- Use single-device previews when the session already has a valid device ID. ([#4733](https://github.com/expo/eas-cli/pull/4733) by [@gwdp](https://github.com/gwdp))
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Explain missing background task identifiers reported by App Store Connect. ([#3465](https://github.com/expo/eas-cli/pull/3465) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
- Explain App Store Connect NOT_AUTHORIZED responses in the shared API client. ([#3462](https://github.com/expo/eas-cli/pull/3462) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
- Explain App Store Connect UNEXPECTED_ERROR responses in the shared API client. ([#3467](https://github.com/expo/eas-cli/pull/3467) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
- Explain missing app icons reported by App Store Connect, including codes 90022 and 90023, while preserving Apple’s validation details. ([#3466](https://github.com/expo/eas-cli/pull/3466) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
- List failed Google Play commit attempts in order, including network failures, when the outcome is uncertain. ([#4660](https://github.com/expo/eas-cli/pull/4660) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
- Fix a five-minute cleanup delay when a device session is canceled during startup and its screen recorder fails before connecting. ([#4761](https://github.com/expo/eas-cli/pull/4761) by [@gwdp](https://github.com/gwdp))
|
||||
- Handle TURN requests for a stopped device session without reporting a warning. ([#4762](https://github.com/expo/eas-cli/pull/4762) by [@gwdp](https://github.com/gwdp))
|
||||
- Preserve indented and incomplete Xcode compiler errors in formatted build logs, including the final diagnostic when logging stops. ([#4365](https://github.com/expo/eas-cli/pull/4365) by [@sjchmiela](https://github.com/sjchmiela))
|
||||
|
||||
## 27.1.0
|
||||
|
||||
### Patch Changes
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/build-tools",
|
||||
"version": "27.1.0",
|
||||
"version": "27.2.0",
|
||||
"bugs": "https://github.com/expo/eas-cli/issues",
|
||||
"license": "BUSL-1.1",
|
||||
"author": "Expo <[email protected]>",
|
||||
@@ -42,17 +42,17 @@
|
||||
"dependencies": {
|
||||
"@expo/config": "55.0.10",
|
||||
"@expo/config-plugins": "55.0.7",
|
||||
"@expo/downloader": "27.1.0",
|
||||
"@expo/eas-build-job": "27.1.0",
|
||||
"@expo/downloader": "27.2.0",
|
||||
"@expo/eas-build-job": "27.2.0",
|
||||
"@expo/env": "^0.4.0",
|
||||
"@expo/logger": "27.1.0",
|
||||
"@expo/logger": "27.2.0",
|
||||
"@expo/package-manager": "1.9.10",
|
||||
"@expo/plist": "^0.3.5",
|
||||
"@expo/results": "^1.0.0",
|
||||
"@expo/spawn-async": "1.7.2",
|
||||
"@expo/steps": "27.1.0",
|
||||
"@expo/template-file": "27.1.0",
|
||||
"@expo/turtle-spawn": "27.1.0",
|
||||
"@expo/steps": "27.2.0",
|
||||
"@expo/template-file": "27.2.0",
|
||||
"@expo/turtle-spawn": "27.2.0",
|
||||
"@expo/xcpretty": "^4.4.7",
|
||||
"@ngrok/ngrok": "1.7.0",
|
||||
"@sentry/node": "7.77.0",
|
||||
|
||||
@@ -36,7 +36,7 @@ const SERVE_SIM_LEASE_FINALIZE_TIMEOUT_MS =
|
||||
const SERVE_SIM_FINISH_TIMEOUT_MS =
|
||||
SERVE_SIM_CONTROL_REQUEST_TIMEOUT_MS + SERVE_SIM_LEASE_FINALIZE_TIMEOUT_MS;
|
||||
const SERVE_SIM_FORCE_STOP_TIMEOUT_MS = 5_000;
|
||||
const SERVE_SIM_RECORDING_STARTED = 'serve-sim:recording-started';
|
||||
const SERVE_SIM_RECORDING_STARTED_LINE = /(?:^|\n)serve-sim:recording-started\r?\n/;
|
||||
// The serve-sim package the session host started; every recorder runs `record-video` from it.
|
||||
let serveSimPackageSpec: string | null = null;
|
||||
|
||||
@@ -507,14 +507,19 @@ function captureProcessOutput(recordingProcess: ChildProcess): {
|
||||
} {
|
||||
let output = '';
|
||||
let started = false;
|
||||
const appendChunk = (chunk: Buffer | string): void => {
|
||||
output = `${output}${chunk.toString()}`;
|
||||
if (output.includes(SERVE_SIM_RECORDING_STARTED)) {
|
||||
started = true;
|
||||
}
|
||||
output = output.slice(-16_384);
|
||||
const captureStreamOutput = (stream: ChildProcess['stdout']): void => {
|
||||
let streamOutput = '';
|
||||
stream?.on('data', (chunk: Buffer | string) => {
|
||||
const text = chunk.toString();
|
||||
output = `${output}${text}`.slice(-16_384);
|
||||
streamOutput = `${streamOutput}${text}`;
|
||||
if (SERVE_SIM_RECORDING_STARTED_LINE.test(streamOutput)) {
|
||||
started = true;
|
||||
}
|
||||
streamOutput = streamOutput.slice(-16_384);
|
||||
});
|
||||
};
|
||||
recordingProcess.stdout?.on('data', appendChunk);
|
||||
recordingProcess.stderr?.on('data', appendChunk);
|
||||
captureStreamOutput(recordingProcess.stdout);
|
||||
captureStreamOutput(recordingProcess.stderr);
|
||||
return { getOutput: () => output, hasStarted: () => started };
|
||||
}
|
||||
@@ -144,7 +144,10 @@ test('starts serve-sim record-video and returns only a finalized recording', asy
|
||||
const finishing = IosSimulatorRecordingUtils.finishAsync({ logger });
|
||||
await setTimeout(20);
|
||||
expect(child.kill).not.toHaveBeenCalled();
|
||||
stderr.write('serve-sim:recording-started\n');
|
||||
child.stdout?.emit('data', 'Downloading');
|
||||
stderr.write('serve-sim:recording-');
|
||||
child.stdout?.emit('data', ' package');
|
||||
stderr.write('started\r\n');
|
||||
stderr.write('x'.repeat(17_000));
|
||||
const recordings = await finishing;
|
||||
|
||||
@@ -362,6 +365,32 @@ test('keeps a recorder active after its package-manager wrapper exits', async ()
|
||||
expect(recordings).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('does not mistake bundled source in an error for a recording start', async () => {
|
||||
let currentTime = Date.now();
|
||||
jest.spyOn(Date, 'now').mockImplementation(() => currentTime);
|
||||
jest
|
||||
.mocked(readServeSimServersAsync)
|
||||
.mockResolvedValue([{ udid, url: 'http://127.0.0.1:43563', token: 'session-token' }]);
|
||||
const recorder = mockRecorder();
|
||||
|
||||
await IosSimulatorRecordingUtils.startAsync({ env, logger });
|
||||
await waitForRecorderSpawnAsync();
|
||||
recorder.child.stderr?.emit(
|
||||
'data',
|
||||
'const marker = "serve-sim:recording-started";\nError: No running serve-sim session found.\n'
|
||||
);
|
||||
recorder.fail(new Error('recorder exited before connecting'));
|
||||
|
||||
const finishing = IosSimulatorRecordingUtils.finishAsync({ logger });
|
||||
try {
|
||||
expect(await Promise.race([finishing.then(() => true), setTimeout(250, false)])).toBe(true);
|
||||
} finally {
|
||||
currentTime += 311_000;
|
||||
await finishing;
|
||||
}
|
||||
expect(recorder.child.kill).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('does not signal a recorder that exits before it reports its start', async () => {
|
||||
let currentTime = Date.now();
|
||||
jest.spyOn(Date, 'now').mockImplementation(() => currentTime);
|
||||
|
||||
+43
@@ -7,6 +7,7 @@ import { setImmediate } from 'node:timers/promises';
|
||||
|
||||
import { type CustomBuildContext } from '../../../customBuildContext';
|
||||
import RemoteLoggerStream from '../../../logging/RemoteLoggerStream';
|
||||
import { Sentry } from '../../../sentry';
|
||||
import { turtleFetch } from '../../../utils/turtleFetch';
|
||||
import { downloadBuildAsync } from '../../functions/downloadBuild';
|
||||
import { uploadDeviceRunSessionArtifactAsync } from '../deviceRunSessionArtifacts';
|
||||
@@ -266,6 +267,48 @@ describe('with a device run session token', () => {
|
||||
expect(jest.mocked(turtleFetch)).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('handles a stopped-session TURN response without a warning or retry', async () => {
|
||||
const ctx = createCtx({ withToken: true });
|
||||
jest
|
||||
.mocked(turtleFetch)
|
||||
.mockResolvedValueOnce(
|
||||
jsonResponse(
|
||||
{ errors: [{ code: 'DEVICE_RUN_SESSION_ALREADY_STOPPED', message: 'Stopped.' }] },
|
||||
400
|
||||
)
|
||||
);
|
||||
|
||||
await expect(fetchWebPreviewTurnArgsAsync(ctx, { logger })).resolves.toEqual([]);
|
||||
|
||||
expect(logger.info).toHaveBeenCalledWith(
|
||||
'Device run session was stopped before TURN credentials were fetched.'
|
||||
);
|
||||
expect(logger.warn).not.toHaveBeenCalled();
|
||||
expect(Sentry.capture).not.toHaveBeenCalled();
|
||||
expect(turtleFetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each([undefined, 'VALIDATION_ERROR'])(
|
||||
'still warns on a TURN failure with code %s',
|
||||
async code => {
|
||||
const ctx = createCtx({ withToken: true });
|
||||
jest
|
||||
.mocked(turtleFetch)
|
||||
.mockResolvedValueOnce(
|
||||
jsonResponse(
|
||||
{ errors: [{ code, message: 'Device run session has already stopped.' }] },
|
||||
400
|
||||
)
|
||||
);
|
||||
|
||||
await expect(fetchWebPreviewTurnArgsAsync(ctx, { logger })).resolves.toEqual([]);
|
||||
|
||||
expect(logger.warn).toHaveBeenCalled();
|
||||
expect(Sentry.capture).toHaveBeenCalled();
|
||||
expect(turtleFetch).toHaveBeenCalledTimes(1);
|
||||
}
|
||||
);
|
||||
|
||||
it('creates artifact upload sessions through the worker API', async () => {
|
||||
const ctx = createCtx({ withToken: true });
|
||||
jest.mocked(turtleFetch).mockResolvedValueOnce(
|
||||
|
||||
@@ -524,6 +524,14 @@ export async function fetchWebPreviewTurnArgsAsync(
|
||||
}
|
||||
return args;
|
||||
} catch (err) {
|
||||
if (
|
||||
err instanceof DeviceRunSessionWorkerApiError &&
|
||||
err.code === 'DEVICE_RUN_SESSION_ALREADY_STOPPED'
|
||||
) {
|
||||
logger.info('Device run session was stopped before TURN credentials were fetched.');
|
||||
return [];
|
||||
}
|
||||
|
||||
const error = err instanceof Error ? err : new Error(String(err));
|
||||
Sentry.capture('Could not fetch Cloudflare TURN ICE servers', error, { level: 'warning' });
|
||||
logger.warn(
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
# create-eas-build-function
|
||||
|
||||
## 27.2.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
## 27.1.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "create-eas-build-function",
|
||||
"version": "27.1.0",
|
||||
"version": "27.2.0",
|
||||
"description": "Create functions for use in EAS Build custom builds.",
|
||||
"keywords": [
|
||||
"expo",
|
||||
@@ -35,7 +35,7 @@
|
||||
"clean": "rimraf ./build/ \"*.tsbuildinfo\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@expo/steps": "27.1.0"
|
||||
"@expo/steps": "27.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@expo/package-manager": "1.9.10",
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
# @expo/downloader
|
||||
|
||||
## 27.2.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
## 27.1.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/downloader",
|
||||
"version": "27.1.0",
|
||||
"version": "27.2.0",
|
||||
"bugs": "https://github.com/expo/eas-cli/issues",
|
||||
"license": "BUSL-1.1",
|
||||
"author": "Expo <[email protected]>",
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
# eas-build-cache-provider
|
||||
|
||||
## 27.2.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
## 27.1.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "eas-build-cache-provider",
|
||||
"version": "27.1.0",
|
||||
"version": "27.2.0",
|
||||
"description": "A build cache provider plugin for the Expo CLI",
|
||||
"homepage": "https://github.com/expo/eas-cli",
|
||||
"bugs": "https://github.com/expo/eas-cli/issues",
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
# @expo/eas-build-job
|
||||
|
||||
## 27.2.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
## 27.1.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/eas-build-job",
|
||||
"version": "27.1.0",
|
||||
"version": "27.2.0",
|
||||
"bugs": "https://github.com/expo/eas-cli/issues",
|
||||
"license": "MIT",
|
||||
"author": "Expo <[email protected]>",
|
||||
@@ -25,9 +25,9 @@
|
||||
"clean": "rimraf node_modules dist coverage \"*.tsbuildinfo\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@expo/logger": "27.1.0",
|
||||
"@expo/logger": "27.2.0",
|
||||
"@expo/results": "1.0.0",
|
||||
"@expo/turtle-spawn": "27.1.0",
|
||||
"@expo/turtle-spawn": "27.2.0",
|
||||
"joi": "^17.13.1",
|
||||
"semver": "^7.6.2",
|
||||
"zod": "^4.3.5"
|
||||
|
||||
@@ -1,5 +1,17 @@
|
||||
# eas-cli
|
||||
|
||||
## 27.2.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- Add an experiment that suggests Expo Update to coding agents after a build when the Free plan account is within 5 builds of the platform limit. ([#4758](https://github.com/expo/eas-cli/pull/4758) by [@williamgrosset](https://github.com/williamgrosset))
|
||||
- Add `eas observe:traces` to list request trace spans (or a summary of span names and counts), `eas observe:trace` to display one trace as a span tree, and span rows in the `eas observe:session` timeline. ([#4772](https://github.com/expo/eas-cli/pull/4772) by [@kadikraman](https://github.com/kadikraman))
|
||||
- Show a one-time Expo Simulators hint after a successful build. ([#4768](https://github.com/expo/eas-cli/pull/4768) by [@FiberJW](https://github.com/FiberJW))
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Remove the Free plan build limit guidance experiment for coding agents from `eas build`. ([#4757](https://github.com/expo/eas-cli/pull/4757) by [@williamgrosset](https://github.com/williamgrosset))
|
||||
|
||||
## 27.1.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
+221
-146
File diff suppressed because it is too large.
Load diff
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "eas-cli",
|
||||
"version": "27.1.0",
|
||||
"version": "27.2.0",
|
||||
"description": "EAS command line tool",
|
||||
"keywords": [
|
||||
"cli",
|
||||
@@ -48,12 +48,12 @@
|
||||
"@expo/code-signing-certificates": "0.0.5",
|
||||
"@expo/config": "55.0.10",
|
||||
"@expo/config-plugins": "55.0.7",
|
||||
"@expo/eas-build-job": "27.1.0",
|
||||
"@expo/eas-json": "27.1.0",
|
||||
"@expo/eas-build-job": "27.2.0",
|
||||
"@expo/eas-json": "27.2.0",
|
||||
"@expo/env": "^1.0.0",
|
||||
"@expo/experimentation": "0.0.5",
|
||||
"@expo/json-file": "8.3.3",
|
||||
"@expo/logger": "27.1.0",
|
||||
"@expo/logger": "27.2.0",
|
||||
"@expo/multipart-body-parser": "2.0.0",
|
||||
"@expo/osascript": "2.1.4",
|
||||
"@expo/package-manager": "1.9.10",
|
||||
@@ -65,7 +65,7 @@
|
||||
"@expo/results": "1.0.0",
|
||||
"@expo/rudder-sdk-node": "1.1.1",
|
||||
"@expo/spawn-async": "1.7.2",
|
||||
"@expo/steps": "27.1.0",
|
||||
"@expo/steps": "27.2.0",
|
||||
"@expo/timeago.js": "1.0.0",
|
||||
"@oclif/core": "^4.8.3",
|
||||
"@oclif/plugin-autocomplete": "^3.2.40",
|
||||
|
||||
@@ -71,6 +71,7 @@ export enum BuildEvent {
|
||||
BUILD_REQUEST_FAIL = 'build cli build request fail',
|
||||
FREE_TIER_LIMIT_CHECKOUT_PROMPT = 'build cli free tier limit checkout prompt',
|
||||
FREE_TIER_NEAR_LIMIT_AGENT_UPDATES_TIP = 'build cli free tier near limit agent updates tip',
|
||||
SIMULATORS_LAUNCH_HINT_SHOWN = 'build cli simulators launch hint shown',
|
||||
|
||||
BUILD_STATUS_COMMAND = 'build cli build status',
|
||||
|
||||
|
||||
@@ -143,6 +143,7 @@ export async function runBuildAndSubmitAsync({
|
||||
}): Promise<{
|
||||
buildIds: string[];
|
||||
buildProfiles?: ProfileData<'build'>[];
|
||||
builds?: MaybeBuildFragment[];
|
||||
}> {
|
||||
await vcsClient.ensureRepoExistsAsync();
|
||||
await ensureRepoIsCleanAsync(vcsClient, flags.nonInteractive);
|
||||
@@ -380,6 +381,7 @@ export async function runBuildAndSubmitAsync({
|
||||
return {
|
||||
buildIds: startedBuilds.map(({ build }) => build.id),
|
||||
buildProfiles,
|
||||
builds,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { boolish } from 'getenv';
|
||||
|
||||
import { Analytics, BuildEvent } from '../analytics/AnalyticsManager';
|
||||
import { createGraphqlClient } from '../commandUtils/context/contextUtils/createGraphqlClient';
|
||||
import { UserPreferenceMutation } from '../graphql/mutations/UserPreferenceMutation';
|
||||
import { UserPreferenceQuery } from '../graphql/queries/UserPreferenceQuery';
|
||||
import Log, { link } from '../log';
|
||||
import { LoggedInAuthenticationInfo } from '../user/SessionManager';
|
||||
import { Actor } from '../user/User';
|
||||
|
||||
const SIMULATORS_LAUNCH_AT = new Date('2026-11-05T18:00:00Z');
|
||||
const SIMULATORS_LAUNCH_HINT_PREFERENCE_KEY = 'simulators-launch-cli-hint-seen';
|
||||
const REQUEST_TIMEOUT_MS = 3000;
|
||||
const SIMULATORS_QUICKSTART_URL =
|
||||
'https://docs.expo.dev/preview/simulators/get-started/?utm_source=eas-cli&utm_medium=cli&utm_campaign=simulators-launch';
|
||||
|
||||
export async function maybeShowSimulatorsLaunchHintAsync(
|
||||
authenticationInfo: LoggedInAuthenticationInfo,
|
||||
analytics: Analytics,
|
||||
{ actor, nonInteractive }: { actor: Actor; nonInteractive: boolean }
|
||||
): Promise<void> {
|
||||
if (
|
||||
nonInteractive ||
|
||||
boolish('CI', false) ||
|
||||
Date.now() < SIMULATORS_LAUNCH_AT.getTime() ||
|
||||
(actor.__typename !== 'User' && actor.__typename !== 'SSOUser')
|
||||
) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const graphqlClient = createGraphqlClient(authenticationInfo, {
|
||||
requestTimeoutMs: REQUEST_TIMEOUT_MS,
|
||||
});
|
||||
const value = await UserPreferenceQuery.getValueAsync(
|
||||
graphqlClient,
|
||||
SIMULATORS_LAUNCH_HINT_PREFERENCE_KEY
|
||||
);
|
||||
if (value && typeof value === 'object' && 'isDismissed' in value && value.isDismissed) {
|
||||
return;
|
||||
}
|
||||
Log.newLine();
|
||||
Log.log(
|
||||
`✨ New: run your build in Expo Simulators, cloud Android and iOS simulators for you and your agents. ${link(SIMULATORS_QUICKSTART_URL)}`
|
||||
);
|
||||
analytics.logEvent(BuildEvent.SIMULATORS_LAUNCH_HINT_SHOWN, {});
|
||||
await UserPreferenceMutation.setAsync(graphqlClient, SIMULATORS_LAUNCH_HINT_PREFERENCE_KEY, {
|
||||
isDismissed: true,
|
||||
});
|
||||
} catch (error) {
|
||||
Log.debug('Failed to show the Expo Simulators hint', error);
|
||||
}
|
||||
}
|
||||
@@ -9,12 +9,13 @@ import path from 'path';
|
||||
|
||||
import { LocalBuildMode } from '../../build/local';
|
||||
import { BuildFlags, runBuildAndSubmitAsync } from '../../build/runBuildAndSubmit';
|
||||
import { maybeShowSimulatorsLaunchHintAsync } from '../../build/simulatorsLaunchHint';
|
||||
import EasCommand from '../../commandUtils/EasCommand';
|
||||
import {
|
||||
EasNonInteractiveAndJsonFlags,
|
||||
resolveNonInteractiveAndJsonFlags,
|
||||
} from '../../commandUtils/flags';
|
||||
import { StatuspageServiceName } from '../../graphql/generated';
|
||||
import { BuildStatus, StatuspageServiceName } from '../../graphql/generated';
|
||||
import Log, { link } from '../../log';
|
||||
import { RequestedPlatform, selectRequestedPlatformAsync } from '../../platform';
|
||||
import { selectAsync } from '../../prompts';
|
||||
@@ -176,7 +177,7 @@ export default class Build extends EasCommand {
|
||||
|
||||
const flagsWithPlatform = await this.ensurePlatformSelectedAsync(flags);
|
||||
|
||||
const { buildProfiles } = await runBuildAndSubmitAsync({
|
||||
const { buildProfiles, builds } = await runBuildAndSubmitAsync({
|
||||
graphqlClient,
|
||||
analytics,
|
||||
vcsClient,
|
||||
@@ -192,6 +193,13 @@ export default class Build extends EasCommand {
|
||||
buildProfiles,
|
||||
nonInteractive: flags.nonInteractive,
|
||||
});
|
||||
|
||||
if (builds?.some(build => build?.status === BuildStatus.Finished)) {
|
||||
await maybeShowSimulatorsLaunchHintAsync(authenticationInfo, analytics, {
|
||||
actor,
|
||||
nonInteractive: flags.nonInteractive,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private sanitizeFlags(
|
||||
|
||||
@@ -4,7 +4,6 @@ import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { ExpoGraphqlClient } from '../../../commandUtils/context/contextUtils/createGraphqlClient';
|
||||
import * as fetchModule from '../../../fetch';
|
||||
import {
|
||||
AppPlatform,
|
||||
DeviceRunSessionByIdQuery,
|
||||
@@ -14,16 +13,11 @@ import {
|
||||
} from '../../../graphql/generated';
|
||||
import { DeviceRunSessionQuery } from '../../../graphql/queries/DeviceRunSessionQuery';
|
||||
import Log from '../../../log';
|
||||
import { ora } from '../../../ora';
|
||||
import { EAS_SIMULATOR_SESSION_ID, loadSimulatorEnvAsync } from '../../../simulator/env';
|
||||
import * as controlSession from '../../../simulator/controlSession';
|
||||
import { runControlMenuAsync } from '../../../simulator/controlInteractive';
|
||||
import { ControlPromptCancelledError } from '../../../simulator/controlPrompts';
|
||||
import { loadSimulatorEnvAsync } from '../../../simulator/env';
|
||||
import {
|
||||
HostActionCatalog,
|
||||
HostActionResult,
|
||||
connectHostActionsAsync,
|
||||
fetchHostActionDeviceAsync,
|
||||
} from '../../../simulator/hostActions';
|
||||
import { enableJsonOutput, printJsonOnlyOutput } from '../../../utils/json';
|
||||
import SimulatorControl from '../control';
|
||||
@@ -37,7 +31,6 @@ jest.mock('../../../simulator/env', () => ({
|
||||
jest.mock('../../../simulator/hostActions', () => ({
|
||||
...jest.requireActual('../../../simulator/hostActions'),
|
||||
connectHostActionsAsync: jest.fn(),
|
||||
fetchHostActionDeviceAsync: jest.fn(),
|
||||
}));
|
||||
jest.mock('../../../ora', () => ({
|
||||
ora: jest.fn(() => {
|
||||
@@ -55,7 +48,6 @@ jest.mock('fs-extra', () => {
|
||||
const actual = jest.requireActual<typeof import('fs-extra')>('fs-extra');
|
||||
return { ...actual, stat: jest.fn(actual.stat) };
|
||||
});
|
||||
jest.mock('../../../simulator/controlInteractive');
|
||||
|
||||
type DeviceRunSessionById = DeviceRunSessionByIdQuery['deviceRunSessions']['byId'];
|
||||
|
||||
@@ -115,7 +107,6 @@ describe(SimulatorControl, () => {
|
||||
let actionResult: HostActionResult;
|
||||
let served: HostActionCatalog;
|
||||
let tmpDir: string;
|
||||
let connectionController: AbortController;
|
||||
const requestAsync = jest.fn(
|
||||
async (action: string, params: Record<string, unknown> = {}): Promise<HostActionResult> => {
|
||||
switch (action) {
|
||||
@@ -138,17 +129,7 @@ describe(SimulatorControl, () => {
|
||||
jest.clearAllMocks();
|
||||
jest.mocked(loadSimulatorEnvAsync).mockResolvedValue();
|
||||
mockByIdAsync.mockResolvedValue(makeDeviceRunSession());
|
||||
jest
|
||||
.mocked(fetchHostActionDeviceAsync)
|
||||
.mockResolvedValue({ udid: 'simulator-udid', name: 'iPhone 17 Pro', runtime: 'iOS-26-4' });
|
||||
connectionController = new AbortController();
|
||||
mockConnectHostActionsAsync.mockResolvedValue({
|
||||
requestAsync,
|
||||
close,
|
||||
udid: 'simulator-udid',
|
||||
signal: connectionController.signal,
|
||||
});
|
||||
jest.mocked(runControlMenuAsync).mockResolvedValue(undefined);
|
||||
mockConnectHostActionsAsync.mockResolvedValue({ requestAsync, close });
|
||||
actionResult = ok('off\n');
|
||||
served = catalog;
|
||||
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'simulator-control-'));
|
||||
@@ -172,194 +153,6 @@ describe(SimulatorControl, () => {
|
||||
return requestAsync.mock.calls.filter(([action]) => action !== 'actions.describe');
|
||||
}
|
||||
|
||||
async function writeImportAsync(actions: unknown[]): Promise<string> {
|
||||
const filePath = path.join(tmpDir, 'control.json');
|
||||
await fs.writeJson(filePath, { version: 1, actions });
|
||||
return filePath;
|
||||
}
|
||||
|
||||
it('imports an ordered config without prompts over the existing connection', async () => {
|
||||
const filePath = await writeImportAsync([
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'off' } },
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'on' } },
|
||||
]);
|
||||
await createCommand([
|
||||
'--import',
|
||||
filePath,
|
||||
'--id',
|
||||
'session-123',
|
||||
'--non-interactive',
|
||||
]).runAsync();
|
||||
expect(actionRequests()).toEqual([
|
||||
['hardwareKeyboard.set', { value: 'off' }],
|
||||
['hardwareKeyboard.set', { value: 'on' }],
|
||||
]);
|
||||
expect(mockConnectHostActionsAsync).toHaveBeenCalledTimes(1);
|
||||
expect(runControlMenuAsync).not.toHaveBeenCalled();
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
expect(Log.log).toHaveBeenCalledWith(expect.stringContaining('iPhone 17 Pro · iOS 26.4'));
|
||||
expect(Log.log).toHaveBeenCalledWith(' off');
|
||||
const spinner = jest.mocked(ora).mock.results[1].value;
|
||||
expect(spinner.start).toHaveBeenCalledWith('[1/2] hardwareKeyboard.set');
|
||||
expect(spinner.start).toHaveBeenCalledWith('[2/2] hardwareKeyboard.set');
|
||||
expect(Log.succeed).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Import complete · 2 actions')
|
||||
);
|
||||
});
|
||||
|
||||
it('prints one JSON result for a successful imported batch', async () => {
|
||||
const filePath = await writeImportAsync([
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'off' } },
|
||||
]);
|
||||
actionResult = ok('{"enabled":false}\n');
|
||||
await createCommand(['--import', filePath, '--id', 'session-123', '--json']).runAsync();
|
||||
expect(mockPrintJsonOnlyOutput).toHaveBeenCalledTimes(1);
|
||||
expect(mockPrintJsonOnlyOutput).toHaveBeenCalledWith({
|
||||
id: 'session-123',
|
||||
session: expect.objectContaining({
|
||||
id: 'session-123',
|
||||
device: { udid: 'simulator-udid', name: 'iPhone 17 Pro', runtime: 'iOS-26-4' },
|
||||
}),
|
||||
config: filePath,
|
||||
results: [{ action: 'hardwareKeyboard.set', output: { enabled: false }, file: null }],
|
||||
});
|
||||
expect(runControlMenuAsync).not.toHaveBeenCalled();
|
||||
expect(ora).toHaveBeenCalledTimes(1);
|
||||
expect(Log.log).not.toHaveBeenCalled();
|
||||
expect(Log.succeed).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('retains completed results and failure metadata in JSON and stops the imported batch', async () => {
|
||||
const filePath = await writeImportAsync([
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'off' } },
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'on' } },
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'off' } },
|
||||
]);
|
||||
requestAsync
|
||||
.mockImplementationOnce(async () => ok(JSON.stringify(served)))
|
||||
.mockResolvedValueOnce(ok('first completed'))
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: 'Permission denied', exitCode: 1 });
|
||||
const previous = process.exitCode;
|
||||
try {
|
||||
await createCommand(['--import', filePath, '--id', 'session-123', '--json']).runAsync();
|
||||
expect(process.exitCode).toBe(1);
|
||||
expect(mockPrintJsonOnlyOutput).toHaveBeenCalledWith({
|
||||
id: 'session-123',
|
||||
session: expect.objectContaining({
|
||||
id: 'session-123',
|
||||
device: { udid: 'simulator-udid', name: 'iPhone 17 Pro', runtime: 'iOS-26-4' },
|
||||
}),
|
||||
config: filePath,
|
||||
results: [{ action: 'hardwareKeyboard.set', output: 'first completed', file: null }],
|
||||
error: {
|
||||
step: 2,
|
||||
action: 'hardwareKeyboard.set',
|
||||
message: expect.stringContaining('Permission denied'),
|
||||
},
|
||||
});
|
||||
expect(actionRequests()).toHaveLength(2);
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
process.exitCode = previous;
|
||||
}
|
||||
});
|
||||
|
||||
it('preflights every imported step before running the first action', async () => {
|
||||
const filePath = await writeImportAsync([
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'off' } },
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'invalid' } },
|
||||
]);
|
||||
await expect(
|
||||
createCommand(['--import', filePath, '--id', 'session-123']).runAsync()
|
||||
).rejects.toThrow('Config step 2');
|
||||
expect(actionRequests()).toEqual([]);
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
expect(jest.mocked(ora).mock.results[1].value.fail).toHaveBeenCalledWith(
|
||||
'Validation failed. No actions were run.'
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ args: ['hardwareKeyboard.set', 'off'] },
|
||||
{ args: ['--list'] },
|
||||
{ args: ['--output', './out.png'] },
|
||||
])('rejects conflicting import options before connecting: %j', async ({ args }) => {
|
||||
await expect(
|
||||
createCommand(['--import', './control.json', '--id', 'session-123', ...args]).runAsync()
|
||||
).rejects.toThrow('--import cannot be combined');
|
||||
expect(mockByIdAsync).not.toHaveBeenCalled();
|
||||
expect(mockConnectHostActionsAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuses Android imports before connecting or reading the config file', async () => {
|
||||
mockByIdAsync.mockResolvedValue(makeDeviceRunSession({ platform: AppPlatform.Android }));
|
||||
await expect(
|
||||
createCommand(['--import', './missing.json', '--id', 'session-123']).runAsync()
|
||||
).rejects.toThrow('not supported yet');
|
||||
expect(mockConnectHostActionsAsync).not.toHaveBeenCalled();
|
||||
expect(runControlMenuAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('prints completed steps before a non-JSON import failure', async () => {
|
||||
const filePath = await writeImportAsync([
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'off' } },
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'on' } },
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'off' } },
|
||||
]);
|
||||
requestAsync
|
||||
.mockImplementationOnce(async () => ok(JSON.stringify(served)))
|
||||
.mockResolvedValueOnce(ok('first done'))
|
||||
.mockResolvedValueOnce({ stdout: '', stderr: 'Native action failed', exitCode: 1 });
|
||||
await expect(
|
||||
createCommand(['--import', filePath, '--id', 'session-123']).runAsync()
|
||||
).rejects.toThrow('Config step 2');
|
||||
expect(Log.log).toHaveBeenCalledWith(' first done');
|
||||
expect(Log.log).toHaveBeenCalledWith('1 completed · 1 failed · 1 skipped');
|
||||
expect(Log.gray).toHaveBeenCalledWith(' [3/3] hardwareKeyboard.set skipped');
|
||||
expect(actionRequests()).toHaveLength(2);
|
||||
expect(runControlMenuAsync).not.toHaveBeenCalled();
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('downloads config-relative outputs and reports each saved file', async () => {
|
||||
const filePath = await writeImportAsync([
|
||||
{ action: 'screenshot.capture', output: './shot.png' },
|
||||
]);
|
||||
actionResult = ok('/remote/screenshot.png');
|
||||
await createCommand(['--import', filePath, '--id', 'session-123']).runAsync();
|
||||
const savedPath = path.join(tmpDir, 'shot.png');
|
||||
expect(await fs.readFile(savedPath, 'utf8')).toBe('png bytes');
|
||||
expect(Log.log).toHaveBeenCalledWith(` Saved: ${savedPath}`);
|
||||
expect(Log.gray).toHaveBeenCalledWith(` Output: ${savedPath}`);
|
||||
expect(Log.gray).toHaveBeenCalledWith(
|
||||
'Explicit output files are overwritten; directory outputs use simulator filenames and fail if the file exists.'
|
||||
);
|
||||
expect(jest.mocked(Log.gray).mock.invocationCallOrder[0]).toBeLessThan(
|
||||
requestAsync.mock.invocationCallOrder[1]
|
||||
);
|
||||
});
|
||||
|
||||
it('reports completion for actions with empty output', async () => {
|
||||
const filePath = await writeImportAsync([
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'off' } },
|
||||
]);
|
||||
actionResult = ok('');
|
||||
await createCommand(['--import', filePath, '--id', 'session-123']).runAsync();
|
||||
expect(jest.mocked(ora).mock.results[1].value.succeed).toHaveBeenCalledWith(
|
||||
expect.stringMatching(/^\[1\/1\] hardwareKeyboard\.set /)
|
||||
);
|
||||
});
|
||||
|
||||
it('formats structured results without opening a picker', async () => {
|
||||
const filePath = await writeImportAsync([
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'off' } },
|
||||
]);
|
||||
actionResult = ok('{"text":"Imported text"}');
|
||||
await createCommand(['--import', filePath, '--id', 'session-123']).runAsync();
|
||||
expect(Log.log).toHaveBeenCalledWith(' {\n "text": "Imported text"\n }');
|
||||
expect(runControlMenuAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([['--id='], ['--id', '']])('refuses an empty session ID in %j', async (...flags) => {
|
||||
const env = jest.replaceProperty(process, 'env', {
|
||||
...process.env,
|
||||
@@ -393,7 +186,6 @@ describe(SimulatorControl, () => {
|
||||
it('runs an action from the catalog with its values and prints the output', async () => {
|
||||
await createCommand(['hardwareKeyboard.set', 'off', '--id', 'session-123']).runAsync();
|
||||
|
||||
expect(fetchHostActionDeviceAsync).not.toHaveBeenCalled();
|
||||
expect(mockByIdAsync).toHaveBeenCalledWith(graphqlClient, 'session-123');
|
||||
expect(mockConnectHostActionsAsync).toHaveBeenCalledWith({
|
||||
apiUrl: 'https://sim.example.test',
|
||||
@@ -404,8 +196,8 @@ describe(SimulatorControl, () => {
|
||||
expect(close).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('lists the actions of the session', async () => {
|
||||
await createCommand(['--list', '--id', 'session-123']).runAsync();
|
||||
it.each([false, true])('lists the actions of the session with --list=%s', async list => {
|
||||
await createCommand([...(list ? ['--list'] : []), '--id', 'session-123']).runAsync();
|
||||
|
||||
const lines = jest.mocked(Log.log).mock.calls.map(([line]) => String(line));
|
||||
expect(lines.pop()).toBe('For action usage: eas simulator:control <action> --help');
|
||||
@@ -413,7 +205,6 @@ describe(SimulatorControl, () => {
|
||||
Object.keys(catalog).sort()
|
||||
);
|
||||
expect(actionRequests()).toEqual([]);
|
||||
expect(fetchHostActionDeviceAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each(['--help', '-h'])('shows action help with %s without running the action', async help => {
|
||||
@@ -487,45 +278,12 @@ describe(SimulatorControl, () => {
|
||||
expect(mockEnableJsonOutput).toHaveBeenCalled();
|
||||
expect(mockPrintJsonOnlyOutput).toHaveBeenCalledWith({
|
||||
id: 'session-123',
|
||||
session: expect.objectContaining({
|
||||
id: 'session-123',
|
||||
device: expect.objectContaining({ udid: 'simulator-udid' }),
|
||||
}),
|
||||
action: 'permissions.list',
|
||||
output: { voiceover: 'off' },
|
||||
file: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('prints plain text as a JSON string and lists a catalog as JSON without opening the menu', async () => {
|
||||
await createCommand([
|
||||
'hardwareKeyboard.set',
|
||||
'off',
|
||||
'--id',
|
||||
'session-123',
|
||||
'--json',
|
||||
]).runAsync();
|
||||
expect(mockPrintJsonOnlyOutput).toHaveBeenCalledWith({
|
||||
id: 'session-123',
|
||||
session: expect.objectContaining({
|
||||
id: 'session-123',
|
||||
project: '@testuser/testapp',
|
||||
device: { udid: 'simulator-udid', name: 'iPhone 17 Pro', runtime: 'iOS-26-4' },
|
||||
}),
|
||||
action: 'hardwareKeyboard.set',
|
||||
output: 'off',
|
||||
file: null,
|
||||
});
|
||||
mockPrintJsonOnlyOutput.mockClear();
|
||||
jest.mocked(fetchHostActionDeviceAsync).mockClear();
|
||||
await createCommand(['--list', '--id', 'session-123', '--json']).runAsync();
|
||||
expect(mockPrintJsonOnlyOutput).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ 'hardwareKeyboard.set': catalog['hardwareKeyboard.set'] })
|
||||
);
|
||||
expect(fetchHostActionDeviceAsync).not.toHaveBeenCalled();
|
||||
expect(runControlMenuAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uploads a local file for an action that takes one and removes it after', async () => {
|
||||
const localFile = path.join(tmpDir, 'MyApp.ipa');
|
||||
await fs.writeFile(localFile, 'app bytes');
|
||||
@@ -764,54 +522,12 @@ describe(SimulatorControl, () => {
|
||||
|
||||
it('refuses an action that the session does not list', async () => {
|
||||
await expect(createCommand(['server.kill', '--id', 'session-123']).runAsync()).rejects.toThrow(
|
||||
'Unknown simulator action "server.kill". Run `eas simulator:control --list` to see the actions.'
|
||||
'Unknown simulator action "server.kill". Run `eas simulator:control` to see the actions.'
|
||||
);
|
||||
expect(actionRequests()).toEqual([]);
|
||||
expect(close).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('opens the interactive menu with one connection and catalog', async () => {
|
||||
await createCommand(['--id', 'session-123']).runAsync();
|
||||
expect(runControlMenuAsync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
catalog,
|
||||
runActionAsync: expect.any(Function),
|
||||
signal: expect.any(AbortSignal),
|
||||
})
|
||||
);
|
||||
expect(mockConnectHostActionsAsync).toHaveBeenCalledTimes(1);
|
||||
expect(requestAsync).toHaveBeenCalledTimes(1);
|
||||
expect(actionRequests()).toEqual([]);
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it.each(['--json', '--non-interactive'])('requires an action in scripted mode %s', async flag => {
|
||||
await expect(createCommand(['--id', 'session-123', flag]).runAsync()).rejects.toThrow(
|
||||
'No action provided.'
|
||||
);
|
||||
expect(mockByIdAsync).not.toHaveBeenCalled();
|
||||
expect(runControlMenuAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('requires an action without a TTY before it loads the session', async () => {
|
||||
process.stdin.isTTY = false;
|
||||
try {
|
||||
await expect(createCommand(['--id', 'session-123']).runAsync()).rejects.toThrow(
|
||||
'No action provided.'
|
||||
);
|
||||
expect(mockByIdAsync).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
process.stdin.isTTY = true;
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects --output without an action before connecting', async () => {
|
||||
await expect(
|
||||
createCommand(['--id', 'session-123', '--output', './out.png']).runAsync()
|
||||
).rejects.toThrow('--output requires an action');
|
||||
expect(mockConnectHostActionsAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('closes an established connection when catalog setup fails', async () => {
|
||||
requestAsync.mockImplementationOnce(async () => ok('not a catalog'));
|
||||
await expect(createCommand(['--list', '--id', 'session-123']).runAsync()).rejects.toThrow(
|
||||
@@ -820,159 +536,8 @@ describe(SimulatorControl, () => {
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('runs an interactive selection through the shared execution path', async () => {
|
||||
jest.mocked(runControlMenuAsync).mockImplementationOnce(async ({ runActionAsync }) => {
|
||||
await runActionAsync({ action: 'hardwareKeyboard.set', params: { value: 'off' } });
|
||||
});
|
||||
await createCommand(['--id', 'session-123']).runAsync();
|
||||
expect(actionRequests()).toEqual([['hardwareKeyboard.set', { value: 'off' }]]);
|
||||
expect(Log.log).toHaveBeenCalledWith('off');
|
||||
});
|
||||
|
||||
it('cleans up before returning Ctrl-C status', async () => {
|
||||
const previousExitCode = process.exitCode;
|
||||
jest.mocked(runControlMenuAsync).mockRejectedValueOnce(new ControlPromptCancelledError());
|
||||
try {
|
||||
await createCommand(['--id', 'session-123']).runAsync();
|
||||
expect(process.exitCode).toBe(130);
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
process.exitCode = previousExitCode;
|
||||
}
|
||||
});
|
||||
|
||||
it('detaches on SIGINT while the menu is idle and removes its handler', async () => {
|
||||
const previousExitCode = process.exitCode;
|
||||
const listeners = process.listenerCount('SIGINT');
|
||||
jest.mocked(runControlMenuAsync).mockImplementationOnce(async ({ signal }) => {
|
||||
const interrupted = new Promise<never>((_resolve, reject) => {
|
||||
signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
reject(signal.reason);
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
});
|
||||
process.emit('SIGINT');
|
||||
await interrupted;
|
||||
});
|
||||
try {
|
||||
await createCommand(['--id', 'session-123']).runAsync();
|
||||
expect(process.exitCode).toBe(130);
|
||||
expect(close).toHaveBeenCalled();
|
||||
expect(process.listenerCount('SIGINT')).toBe(listeners);
|
||||
expect(actionRequests()).toEqual([]);
|
||||
} finally {
|
||||
process.exitCode = previousExitCode;
|
||||
}
|
||||
});
|
||||
|
||||
it('reports connection loss while idle and restores its listeners', async () => {
|
||||
const listeners = process.listenerCount('SIGINT');
|
||||
const reason = new Error('Connection lost; the action may still have run.');
|
||||
jest.mocked(runControlMenuAsync).mockImplementationOnce(async ({ signal }) => {
|
||||
const lost = new Promise<never>((_resolve, reject) => {
|
||||
signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
reject(signal.reason);
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
});
|
||||
connectionController.abort(reason);
|
||||
await lost;
|
||||
});
|
||||
await expect(createCommand(['--id', 'session-123']).runAsync()).rejects.toBe(reason);
|
||||
expect(close).toHaveBeenCalled();
|
||||
expect(process.listenerCount('SIGINT')).toBe(listeners);
|
||||
expect(actionRequests()).toEqual([]);
|
||||
});
|
||||
|
||||
it('does not run an action when the socket closes immediately after catalog setup', async () => {
|
||||
const reason = new Error('Connection closed after catalog');
|
||||
requestAsync.mockImplementationOnce(async () => {
|
||||
queueMicrotask(() => {
|
||||
connectionController.abort(reason);
|
||||
});
|
||||
return ok(JSON.stringify(served));
|
||||
});
|
||||
jest.mocked(runControlMenuAsync).mockImplementationOnce(async ({ signal }) => {
|
||||
signal.throwIfAborted();
|
||||
});
|
||||
await expect(createCommand(['--id', 'session-123']).runAsync()).rejects.toBe(reason);
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
expect(actionRequests()).toEqual([]);
|
||||
});
|
||||
|
||||
it('ends the idle menu on confirmed session completion without stopping the remote session', async () => {
|
||||
const watcher = new AbortController();
|
||||
const dispose = jest.fn();
|
||||
const watch = jest
|
||||
.spyOn(controlSession, 'watchControlSession')
|
||||
.mockReturnValueOnce({ signal: watcher.signal, dispose });
|
||||
const listeners = process.listenerCount('SIGINT');
|
||||
jest.mocked(runControlMenuAsync).mockImplementationOnce(async ({ signal }) => {
|
||||
const ended = new Promise<never>((_resolve, reject) => {
|
||||
signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
reject(signal.reason);
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
});
|
||||
watcher.abort(new controlSession.ControlSessionEndedError('session-123'));
|
||||
await ended;
|
||||
});
|
||||
try {
|
||||
await createCommand(['--id', 'session-123']).runAsync();
|
||||
expect(Log.log).toHaveBeenCalledWith('Simulator session session-123 has ended.');
|
||||
expect(dispose).toHaveBeenCalledTimes(1);
|
||||
expect(close).toHaveBeenCalled();
|
||||
expect(process.listenerCount('SIGINT')).toBe(listeners);
|
||||
expect(actionRequests()).toEqual([]);
|
||||
expect(mockByIdAsync).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
watch.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('propagates an errored session instead of reporting a successful end', async () => {
|
||||
jest
|
||||
.mocked(runControlMenuAsync)
|
||||
.mockRejectedValueOnce(
|
||||
new controlSession.ControlSessionEndedError('session-123', /* failed */ true)
|
||||
);
|
||||
await expect(createCommand(['--id', 'session-123']).runAsync()).rejects.toThrow(
|
||||
'session-123 errored'
|
||||
);
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
expect(Log.log).not.toHaveBeenCalledWith('Simulator session session-123 has ended.');
|
||||
});
|
||||
|
||||
it('shows session and device details without terminal escape sequences', async () => {
|
||||
mockByIdAsync.mockResolvedValueOnce(
|
||||
makeDeviceRunSession({ name: '\x1b[31mCheckout QA\x1b[0m\nSpoofed\u202E' })
|
||||
);
|
||||
await createCommand(['--id', 'session-123']).runAsync();
|
||||
const text = jest
|
||||
.mocked(Log.log)
|
||||
.mock.calls.map(([value]) => String(value))
|
||||
.join('\n');
|
||||
expect(text).toContain('Checkout QA Spoofed');
|
||||
expect(text).toContain('@testuser/testapp');
|
||||
expect(text).toContain('iPhone 17 Pro · iOS 26.4');
|
||||
expect(text).toContain('session-123');
|
||||
expect(text).toContain('simulator-udid');
|
||||
expect(text).not.toContain('\x1b[31m');
|
||||
expect(text).not.toContain('\u202E');
|
||||
expect(text).not.toContain('preview-token');
|
||||
});
|
||||
|
||||
it('includes upload path help in the JSON action list', async () => {
|
||||
await createCommand(['--list', '--id', 'session-123', '--json']).runAsync();
|
||||
it('lists the actions as JSON when no action is provided', async () => {
|
||||
await createCommand(['--id', 'session-123', '--json']).runAsync();
|
||||
|
||||
expect(mockPrintJsonOnlyOutput).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
@@ -985,105 +550,6 @@ describe(SimulatorControl, () => {
|
||||
expect(actionRequests()).toEqual([]);
|
||||
});
|
||||
|
||||
it('shows fallback names when optional details are unavailable or blank', async () => {
|
||||
mockByIdAsync.mockResolvedValueOnce(makeDeviceRunSession({ name: ' \n ' }));
|
||||
jest.mocked(fetchHostActionDeviceAsync).mockResolvedValueOnce({ udid: 'simulator-udid' });
|
||||
await createCommand(['--id', 'session-123']).runAsync();
|
||||
expect(Log.log).toHaveBeenCalledWith(expect.stringContaining('Unnamed session'));
|
||||
expect(Log.log).toHaveBeenCalledWith(expect.stringContaining('Unavailable'));
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ importing: true, jsonFlag: false },
|
||||
{ importing: true, jsonFlag: true },
|
||||
{ importing: false, jsonFlag: true },
|
||||
])(
|
||||
'runs actions without display metadata (importing: $importing, json: $jsonFlag)',
|
||||
async ({ importing, jsonFlag }) => {
|
||||
jest
|
||||
.mocked(fetchHostActionDeviceAsync)
|
||||
.mockImplementationOnce(
|
||||
jest.requireActual('../../../simulator/hostActions').fetchHostActionDeviceAsync
|
||||
);
|
||||
const fetch = jest
|
||||
.spyOn(fetchModule, 'default')
|
||||
.mockRejectedValueOnce(new Error('Metadata request failed'));
|
||||
try {
|
||||
const filePath = await writeImportAsync([
|
||||
{ action: 'hardwareKeyboard.set', params: { value: 'off' } },
|
||||
]);
|
||||
await createCommand([
|
||||
...(importing ? ['--import', filePath] : ['hardwareKeyboard.set', 'off']),
|
||||
...(jsonFlag ? ['--json'] : []),
|
||||
'--id',
|
||||
'session-123',
|
||||
]).runAsync();
|
||||
expect(actionRequests()).toEqual([['hardwareKeyboard.set', { value: 'off' }]]);
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
if (jsonFlag) {
|
||||
expect(mockPrintJsonOnlyOutput).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
session: expect.objectContaining({ device: { udid: 'simulator-udid' } }),
|
||||
})
|
||||
);
|
||||
} else {
|
||||
expect(Log.log).toHaveBeenCalledWith(expect.stringContaining('Unavailable'));
|
||||
}
|
||||
} finally {
|
||||
fetch.mockRestore();
|
||||
}
|
||||
}
|
||||
);
|
||||
it('closes the connection if the interactive controller fails unexpectedly', async () => {
|
||||
const reason = new Error('Terminal output failed');
|
||||
jest.mocked(runControlMenuAsync).mockRejectedValueOnce(reason);
|
||||
await expect(createCommand(['--id', 'session-123']).runAsync()).rejects.toBe(reason);
|
||||
expect(close).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('requires a session ID before opening a connection', async () => {
|
||||
const previous = process.env[EAS_SIMULATOR_SESSION_ID];
|
||||
delete process.env[EAS_SIMULATOR_SESSION_ID];
|
||||
try {
|
||||
await expect(createCommand([]).runAsync()).rejects.toThrow(
|
||||
'No simulator session ID provided.'
|
||||
);
|
||||
expect(mockByIdAsync).not.toHaveBeenCalled();
|
||||
expect(mockConnectHostActionsAsync).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
if (previous === undefined) {
|
||||
delete process.env[EAS_SIMULATOR_SESSION_ID];
|
||||
} else {
|
||||
process.env[EAS_SIMULATOR_SESSION_ID] = previous;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('uses the session ID loaded into the simulator environment', async () => {
|
||||
const previous = process.env[EAS_SIMULATOR_SESSION_ID];
|
||||
process.env[EAS_SIMULATOR_SESSION_ID] = 'dotenv-session';
|
||||
try {
|
||||
await createCommand([]).runAsync();
|
||||
expect(mockByIdAsync).toHaveBeenCalledWith(graphqlClient, 'dotenv-session');
|
||||
expect(runControlMenuAsync).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
if (previous === undefined) {
|
||||
delete process.env[EAS_SIMULATOR_SESSION_ID];
|
||||
} else {
|
||||
process.env[EAS_SIMULATOR_SESSION_ID] = previous;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('refuses Android before an interactive prompt or connection', async () => {
|
||||
mockByIdAsync.mockResolvedValue(makeDeviceRunSession({ platform: AppPlatform.Android }));
|
||||
await expect(createCommand(['--id', 'session-123']).runAsync()).rejects.toThrow(
|
||||
'not supported yet'
|
||||
);
|
||||
expect(runControlMenuAsync).not.toHaveBeenCalled();
|
||||
expect(mockConnectHostActionsAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuses a session that is not running', async () => {
|
||||
mockByIdAsync.mockResolvedValue(
|
||||
makeDeviceRunSession({ status: DeviceRunSessionStatus.Stopped })
|
||||
|
||||
@@ -33,14 +33,11 @@ import {
|
||||
resetSimulatorEnvAsync,
|
||||
} from '../../../simulator/env';
|
||||
import { resolveExpoGoSdkVersionAsync } from '../../../simulator/expoGo';
|
||||
import { applyStartConfigAsync } from '../../../simulator/startSetup';
|
||||
import { ControlConfigExecutionError } from '../../../simulator/controlConfig';
|
||||
import * as promiseUtils from '../../../utils/promise';
|
||||
import { enableJsonOutput, printJsonOnlyOutput } from '../../../utils/json';
|
||||
import Simulator from '../index';
|
||||
|
||||
jest.mock('fs-extra');
|
||||
jest.mock('../../../simulator/startSetup');
|
||||
jest.mock('../../../analytics/AnalyticsManager', () => ({
|
||||
...jest.requireActual('../../../analytics/AnalyticsManager'),
|
||||
isAnalyticsOptedOutAsync: jest.fn(),
|
||||
@@ -198,7 +195,6 @@ describe(Simulator, () => {
|
||||
beforeEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
jest.clearAllMocks();
|
||||
jest.mocked(applyStartConfigAsync).mockReset().mockResolvedValue([]);
|
||||
delete process.env[EAS_SIMULATOR_SESSION_ID];
|
||||
mockJobRunErrorsByIdAsync.mockResolvedValue(null);
|
||||
mockAvailabilityByAppIdAsync.mockResolvedValue({ accountName: 'testuser', available: true });
|
||||
@@ -207,7 +203,7 @@ describe(Simulator, () => {
|
||||
id: 'session-123',
|
||||
status: DeviceRunSessionStatus.Stopped,
|
||||
});
|
||||
mockByIdAsync.mockReset().mockResolvedValue(makeDeviceRunSession());
|
||||
mockByIdAsync.mockResolvedValue(makeDeviceRunSession());
|
||||
mockLoadSimulatorEnvAsync.mockResolvedValue();
|
||||
mockResetSimulatorEnvAsync.mockResolvedValue();
|
||||
mockResolveExpoGoSdkVersionAsync.mockResolvedValue('55.0.0');
|
||||
@@ -242,804 +238,6 @@ describe(Simulator, () => {
|
||||
return { command, getContextAsync };
|
||||
}
|
||||
|
||||
describe('imported session configuration', () => {
|
||||
const configPath = '/test/simulator.json';
|
||||
const localEgressSession = makeDeviceRunSession({
|
||||
remoteConfig: {
|
||||
__typename: 'WebPreviewOnlyRunSessionRemoteConfig',
|
||||
previewUrl: 'https://expo.dev/preview',
|
||||
previewApiUrl: 'https://sim.example.test',
|
||||
previewToken: 'private-token',
|
||||
egressUrl: 'https://egress.example.com',
|
||||
egressToken: 'token',
|
||||
egressFingerprint: 'fp',
|
||||
egressPort: 8899,
|
||||
},
|
||||
});
|
||||
function config(start: object = { platform: 'ios' }, actions?: object[]): void {
|
||||
jest
|
||||
.mocked(fs.readJson)
|
||||
.mockResolvedValue({ version: 1, start, ...(actions ? { actions } : {}) } as never);
|
||||
mockByIdAsync.mockResolvedValue(
|
||||
makeDeviceRunSession({
|
||||
remoteConfig: {
|
||||
__typename: 'WebPreviewOnlyRunSessionRemoteConfig',
|
||||
previewUrl: 'https://expo.dev/preview',
|
||||
previewApiUrl: 'https://sim.example.test',
|
||||
previewToken: 'private-token',
|
||||
},
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
it('enables JSON output before import preflight can fail', async () => {
|
||||
config({ unknown: true });
|
||||
const { command, getContextAsync } = createCommand(['--import', configPath, '--json']);
|
||||
await expect(command.runAsync()).rejects.toThrow('Unknown or invocation-only');
|
||||
expect(mockEnableJsonOutput).toHaveBeenCalledTimes(1);
|
||||
expect(mockEnableJsonOutput.mock.invocationCallOrder[0]).toBeLessThan(
|
||||
jest.mocked(fs.readJson).mock.invocationCallOrder[0]
|
||||
);
|
||||
expect(getContextAsync).not.toHaveBeenCalled();
|
||||
expect(mockCreateDeviceRunSessionAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('creates from saved flags with explicit CLI overrides and unchanged output without actions', async () => {
|
||||
config({
|
||||
platform: 'ios',
|
||||
name: 'Saved name',
|
||||
type: 'web-preview-only',
|
||||
device: 'Saved phone',
|
||||
tag: ['saved'],
|
||||
});
|
||||
const { command } = createCommand(['--import', configPath, '--name', 'CLI name', '--json']);
|
||||
await command.runAsync();
|
||||
expect(mockCreateDeviceRunSessionAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
expect.objectContaining({
|
||||
name: 'CLI name',
|
||||
type: DeviceRunSessionType.WebPreviewOnly,
|
||||
ios: { deviceIdentifier: 'Saved phone' },
|
||||
tags: ['saved'],
|
||||
})
|
||||
);
|
||||
expect(applyStartConfigAsync).not.toHaveBeenCalled();
|
||||
expect(jest.mocked(printJsonOnlyOutput)).toHaveBeenCalledWith(
|
||||
expect.not.objectContaining({ setup: expect.anything() })
|
||||
);
|
||||
});
|
||||
|
||||
it.each(
|
||||
(['ios', 'android'] as const).flatMap(platform =>
|
||||
(['attached', 'detached', 'json'] as const).flatMap(mode =>
|
||||
(['env', 'dotenv'] as const).flatMap(output =>
|
||||
[false, true].map(egress => ({ platform, mode, output, egress }))
|
||||
)
|
||||
)
|
||||
)
|
||||
)(
|
||||
'preserves ordinary startup with saved settings: $platform/$mode/$output, egress=$egress',
|
||||
async ({ platform, mode, output, egress }) => {
|
||||
const listeners = process.listeners('SIGINT');
|
||||
const start = {
|
||||
platform,
|
||||
type: 'web-preview-only',
|
||||
name: 'Startup regression',
|
||||
device: platform === 'ios' ? 'iPhone 17 Pro' : 'pixel_7',
|
||||
'out-config-type': output,
|
||||
...(egress ? { egress: 'local' } : {}),
|
||||
};
|
||||
const ready = makeDeviceRunSession({
|
||||
platform: platform === 'ios' ? AppPlatform.Ios : AppPlatform.Android,
|
||||
remoteConfig: {
|
||||
__typename: 'WebPreviewOnlyRunSessionRemoteConfig',
|
||||
previewUrl: 'https://expo.dev/preview',
|
||||
previewApiUrl: 'https://sim.example.test',
|
||||
previewToken: 'private-token',
|
||||
...(egress
|
||||
? {
|
||||
egressUrl: 'https://egress.example.com',
|
||||
egressToken: 'token',
|
||||
egressFingerprint: 'fp',
|
||||
egressPort: 8899,
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
});
|
||||
const runAsync = async (saved: boolean): Promise<object> => {
|
||||
jest.clearAllMocks();
|
||||
jest.mocked(fs.readJson).mockResolvedValue({ version: 1, start } as never);
|
||||
mockByIdAsync
|
||||
.mockReset()
|
||||
.mockResolvedValueOnce(ready)
|
||||
.mockResolvedValue({ ...ready, status: DeviceRunSessionStatus.Stopped });
|
||||
jest.mocked(runLocalEgressAsync).mockImplementation(async ({ signal, onConnected }) => {
|
||||
onConnected?.();
|
||||
await new Promise<void>(resolve => {
|
||||
signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
resolve();
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
});
|
||||
});
|
||||
const argv = saved
|
||||
? ['--import', configPath]
|
||||
: Object.entries(start).flatMap(([name, value]) => [`--${name}`, value]);
|
||||
if (mode !== 'attached') {
|
||||
argv.push(mode === 'json' ? '--json' : '--non-interactive');
|
||||
}
|
||||
await createCommand(argv).command.runAsync();
|
||||
expect(applyStartConfigAsync).not.toHaveBeenCalled();
|
||||
expect(fs.readJson).toHaveBeenCalledTimes(saved ? 1 : 0);
|
||||
expect(runLocalEgressAsync).toHaveBeenCalledTimes(egress && mode === 'attached' ? 1 : 0);
|
||||
expect(fs.writeFile).toHaveBeenCalledTimes(
|
||||
output === 'dotenv' ? (mode === 'json' ? 1 : 2) : 0
|
||||
);
|
||||
expect(process.listeners('SIGINT')).toEqual(listeners);
|
||||
return {
|
||||
create: mockCreateDeviceRunSessionAsync.mock.calls,
|
||||
output: jest.mocked(Log.log).mock.calls,
|
||||
warnings: jest.mocked(Log.warn).mock.calls,
|
||||
newLines: jest.mocked(Log.newLine).mock.calls,
|
||||
json: mockPrintJsonOnlyOutput.mock.calls,
|
||||
writes: jest.mocked(fs.writeFile).mock.calls,
|
||||
cleanup: mockResetSimulatorEnvAsync.mock.calls,
|
||||
stop: mockEnsureDeviceRunSessionStoppedAsync.mock.calls,
|
||||
egress: jest.mocked(runLocalEgressAsync).mock.calls.map(([options]) => ({
|
||||
url: options.url,
|
||||
port: options.port,
|
||||
platform: options.platform,
|
||||
aborted: options.signal.aborted,
|
||||
})),
|
||||
};
|
||||
};
|
||||
const ordinary = await runAsync(false);
|
||||
expect(await runAsync(true)).toEqual(ordinary);
|
||||
}
|
||||
);
|
||||
|
||||
it('applies actions after readiness and includes parsed setup results in one JSON object', async () => {
|
||||
config(undefined, [{ action: 'appearance.set', params: { value: 'dark' } }]);
|
||||
jest.mocked(applyStartConfigAsync).mockImplementationOnce(async () => {
|
||||
expect(fs.writeFile).not.toHaveBeenCalled();
|
||||
return [{ action: 'appearance.set', output: '{"value":"dark"}', file: null }];
|
||||
});
|
||||
const { command } = createCommand(['--import', configPath, '--json']);
|
||||
await command.runAsync();
|
||||
expect(jest.mocked(applyStartConfigAsync).mock.invocationCallOrder[0]).toBeGreaterThan(
|
||||
mockByIdAsync.mock.invocationCallOrder[0]
|
||||
);
|
||||
expect(applyStartConfigAsync).toHaveBeenCalledWith(
|
||||
{ apiUrl: 'https://sim.example.test', token: 'private-token' },
|
||||
expect.objectContaining({ path: configPath }),
|
||||
{ signal: expect.any(AbortSignal), onProgress: undefined }
|
||||
);
|
||||
expect(printJsonOnlyOutput).toHaveBeenCalledTimes(1);
|
||||
expect(printJsonOnlyOutput).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
id: 'session-123',
|
||||
setup: {
|
||||
config: configPath,
|
||||
results: [{ action: 'appearance.set', output: { value: 'dark' }, file: null }],
|
||||
},
|
||||
})
|
||||
);
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).not.toHaveBeenCalled();
|
||||
expect(fs.writeFile).toHaveBeenCalledTimes(1);
|
||||
expect(fs.writeFile).toHaveBeenCalledWith(
|
||||
simulatorDotenvPath,
|
||||
SIMULATOR_DOTENV_FILE_HEADER + `${EAS_SIMULATOR_SESSION_ID}='session-123'\n`
|
||||
);
|
||||
});
|
||||
|
||||
it.each([false, true])(
|
||||
'prints normal ready output before importing, detached=%s',
|
||||
async detached => {
|
||||
config({ platform: 'ios' }, [{ action: 'tap', params: { x: 0.5, y: 0.5 } }]);
|
||||
const ready = makeDeviceRunSession({
|
||||
remoteConfig: {
|
||||
__typename: 'WebPreviewOnlyRunSessionRemoteConfig',
|
||||
previewUrl: 'https://expo.dev/preview',
|
||||
previewApiUrl: 'https://sim.example.test',
|
||||
previewToken: 'private-token',
|
||||
},
|
||||
});
|
||||
mockByIdAsync
|
||||
.mockResolvedValueOnce(ready)
|
||||
.mockResolvedValueOnce({ ...ready, status: DeviceRunSessionStatus.Stopped });
|
||||
jest
|
||||
.mocked(applyStartConfigAsync)
|
||||
.mockImplementationOnce(async (_access, _config, options) => {
|
||||
expect(fs.writeFile).not.toHaveBeenCalled();
|
||||
const output = jest.mocked(Log.log).mock.calls.map(([line]) => String(line));
|
||||
const preview = output.findIndex(line => line.includes(deviceRunSessionPreviewUrl));
|
||||
const importing = output.findIndex(line => line.includes('Importing 1 action from'));
|
||||
expect(preview).toBeGreaterThanOrEqual(0);
|
||||
expect(importing).toBeGreaterThan(preview);
|
||||
options.onProgress?.({ step: 1, total: 1, action: 'tap', status: 'running' });
|
||||
const result = { action: 'tap', output: '', file: null };
|
||||
options.onProgress?.({ step: 1, total: 1, action: 'tap', status: 'completed', result });
|
||||
return [result];
|
||||
});
|
||||
await createCommand([
|
||||
'--import',
|
||||
configPath,
|
||||
...(detached ? ['--non-interactive'] : []),
|
||||
]).command.runAsync();
|
||||
expect(fs.writeFile).toHaveBeenCalledWith(
|
||||
simulatorDotenvPath,
|
||||
expect.stringContaining(`${EAS_SIMULATOR_SESSION_ID}='session-123'`)
|
||||
);
|
||||
const spinners = jest.mocked(ora).mock.results.map(result => result.value);
|
||||
expect(
|
||||
spinners.some(spinner =>
|
||||
spinner.succeed.mock.calls.some(([text]: [string]) => text === '[1/1] tap completed')
|
||||
)
|
||||
).toBe(true);
|
||||
}
|
||||
);
|
||||
|
||||
it('identifies failed and skipped imported steps after printing the preview', async () => {
|
||||
config({ platform: 'ios' }, [
|
||||
{ action: 'appearance.get' },
|
||||
{ action: 'tap' },
|
||||
{ action: 'clipboard.read' },
|
||||
]);
|
||||
jest
|
||||
.mocked(applyStartConfigAsync)
|
||||
.mockRejectedValueOnce(
|
||||
new ControlConfigExecutionError(
|
||||
2,
|
||||
'tap',
|
||||
[{ action: 'appearance.get', output: 'dark', file: null }],
|
||||
new Error('refused')
|
||||
)
|
||||
);
|
||||
await expect(
|
||||
createCommand(['--import', configPath, '--non-interactive']).command.runAsync()
|
||||
).rejects.toThrow('refused');
|
||||
expect(jest.mocked(Log.log)).toHaveBeenCalledWith('1 completed · 1 failed · 1 skipped');
|
||||
expect(jest.mocked(Log.log)).toHaveBeenCalledWith(' [3/3] clipboard.read skipped');
|
||||
const spinners = jest.mocked(ora).mock.results.map(result => result.value);
|
||||
expect(
|
||||
spinners.some(spinner =>
|
||||
spinner.fail.mock.calls.some(([text]: [string]) => text === '[2/3] tap failed')
|
||||
)
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('prints imported text and saved files after the ready preview URL', async () => {
|
||||
config(undefined, [{ action: 'appearance.get' }, { action: 'screenshot.capture' }]);
|
||||
jest
|
||||
.mocked(applyStartConfigAsync)
|
||||
.mockImplementationOnce(async (_access, _config, options) => {
|
||||
const results = [
|
||||
{ action: 'appearance.get', output: 'dark', file: null },
|
||||
{ action: 'screenshot.capture', output: '', file: '/test/screenshot.png' },
|
||||
];
|
||||
for (const [index, result] of results.entries()) {
|
||||
options.onProgress?.({
|
||||
step: index + 1,
|
||||
total: results.length,
|
||||
action: result.action,
|
||||
status: 'completed',
|
||||
result,
|
||||
});
|
||||
}
|
||||
return results;
|
||||
});
|
||||
await createCommand(['--import', configPath, '--non-interactive']).command.runAsync();
|
||||
const output = jest.mocked(Log.log).mock.calls.map(([line]) => String(line));
|
||||
const preview = output.findIndex(line => line.includes(deviceRunSessionPreviewUrl));
|
||||
expect(preview).toBeGreaterThanOrEqual(0);
|
||||
expect(output.indexOf('dark')).toBeGreaterThan(preview);
|
||||
expect(output.indexOf('Saved /test/screenshot.png')).toBeGreaterThan(preview);
|
||||
});
|
||||
|
||||
it('preserves the setup error when the stopped session dotenv cannot be cleaned up', async () => {
|
||||
config(undefined, [{ action: 'appearance.get' }]);
|
||||
jest.mocked(applyStartConfigAsync).mockRejectedValueOnce(new Error('native action refused'));
|
||||
mockResetSimulatorEnvAsync.mockRejectedValueOnce(new Error('read-only file'));
|
||||
const listeners = process.listeners('SIGINT');
|
||||
await expect(
|
||||
createCommand(['--import', configPath, '--non-interactive']).command.runAsync()
|
||||
).rejects.toThrow('native action refused');
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
'session-123'
|
||||
);
|
||||
expect(Log.warn).toHaveBeenCalledWith(
|
||||
expect.stringContaining('could not be cleaned up: read-only file')
|
||||
);
|
||||
expect(process.listeners('SIGINT')).toEqual(listeners);
|
||||
});
|
||||
|
||||
it('stops only the newly created session on setup failure and retains completed JSON results', async () => {
|
||||
config(undefined, [{ action: 'appearance.set' }, { action: 'appearance.get' }]);
|
||||
process.env[EAS_SIMULATOR_SESSION_ID] = 'previous-session';
|
||||
jest
|
||||
.mocked(applyStartConfigAsync)
|
||||
.mockRejectedValue(
|
||||
new ControlConfigExecutionError(
|
||||
2,
|
||||
'appearance.get',
|
||||
[{ action: 'appearance.set', output: '"dark"', file: null }],
|
||||
new Error('refused')
|
||||
)
|
||||
);
|
||||
const prior = process.exitCode;
|
||||
const listeners = process.listenerCount('SIGINT');
|
||||
try {
|
||||
await createCommand(['--import', configPath, '--json']).command.runAsync();
|
||||
expect(process.exitCode).toBe(1);
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
'session-123'
|
||||
);
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledTimes(1);
|
||||
expect(fs.writeFile).not.toHaveBeenCalled();
|
||||
expect(mockResetSimulatorEnvAsync).toHaveBeenCalledWith(projectDir, 'session-123');
|
||||
expect(printJsonOnlyOutput).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
id: 'session-123',
|
||||
stopped: true,
|
||||
setup: expect.objectContaining({
|
||||
results: [{ action: 'appearance.set', output: 'dark', file: null }],
|
||||
error: expect.objectContaining({ step: 2, action: 'appearance.get' }),
|
||||
}),
|
||||
})
|
||||
);
|
||||
expect(process.listenerCount('SIGINT')).toBe(listeners);
|
||||
} finally {
|
||||
process.exitCode = prior;
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ imported: false, jsonFlag: true },
|
||||
{ imported: true, jsonFlag: true },
|
||||
{ imported: true, jsonFlag: false },
|
||||
])(
|
||||
'stops startup interrupted during its final dotenv write, imported=$imported, json=$jsonFlag',
|
||||
async ({ imported, jsonFlag }) => {
|
||||
jest.spyOn(process, 'exit').mockImplementation(code => {
|
||||
throw new Error(`process.exit(${code})`);
|
||||
});
|
||||
config(undefined, imported ? [{ action: 'appearance.get' }] : undefined);
|
||||
jest.mocked(fs.writeFile).mockImplementationOnce(async () => {
|
||||
process.emit('SIGINT');
|
||||
});
|
||||
const listeners = process.listeners('SIGINT');
|
||||
await expect(
|
||||
createCommand([
|
||||
'--import',
|
||||
configPath,
|
||||
...(jsonFlag ? ['--json'] : ['--non-interactive']),
|
||||
]).command.runAsync()
|
||||
).rejects.toThrow('process.exit(130)');
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
'session-123'
|
||||
);
|
||||
expect(mockResetSimulatorEnvAsync).toHaveBeenCalledWith(projectDir, 'session-123');
|
||||
expect(printJsonOnlyOutput).not.toHaveBeenCalled();
|
||||
expect(process.listeners('SIGINT')).toEqual(listeners);
|
||||
}
|
||||
);
|
||||
|
||||
it.each(
|
||||
['interactive', 'detached', 'json'].flatMap(mode =>
|
||||
['failure', 'interruption'].map(outcome => ({ mode, outcome }))
|
||||
)
|
||||
)(
|
||||
'keeps previous session credentials after imported $outcome in $mode mode',
|
||||
async ({ mode, outcome }) => {
|
||||
config(undefined, [{ action: 'appearance.set' }]);
|
||||
process.env[EAS_SIMULATOR_SESSION_ID] = 'previous-session';
|
||||
const previous =
|
||||
SIMULATOR_DOTENV_FILE_HEADER +
|
||||
"EAS_SIMULATOR_SESSION_ID='previous-session'\nEAS_SIMULATOR_EGRESS_TOKEN='previous-token'\n";
|
||||
let saved = previous;
|
||||
jest.mocked(fs.readFile).mockImplementation(async () => saved as never);
|
||||
jest.mocked(fs.writeFile).mockImplementation(async (_path, content) => {
|
||||
saved = String(content);
|
||||
});
|
||||
mockResetSimulatorEnvAsync.mockImplementationOnce(
|
||||
jest.requireActual('../../../simulator/env').resetSimulatorEnvAsync
|
||||
);
|
||||
jest
|
||||
.mocked(applyStartConfigAsync)
|
||||
.mockImplementationOnce(async (_access, _config, { signal }) => {
|
||||
if (outcome === 'interruption') {
|
||||
process.emit('SIGINT');
|
||||
signal.throwIfAborted();
|
||||
}
|
||||
throw new Error('setup failed');
|
||||
});
|
||||
jest.spyOn(process, 'exit').mockImplementation(() => {
|
||||
throw new Error('interrupted');
|
||||
});
|
||||
const priorExitCode = process.exitCode;
|
||||
const listeners = process.listeners('SIGINT');
|
||||
try {
|
||||
const command = createCommand([
|
||||
'--import',
|
||||
configPath,
|
||||
...(mode === 'json' ? ['--json'] : mode === 'detached' ? ['--non-interactive'] : []),
|
||||
]).command;
|
||||
if (mode === 'json' && outcome === 'failure') {
|
||||
await command.runAsync();
|
||||
expect(process.exitCode).toBe(1);
|
||||
} else {
|
||||
await expect(command.runAsync()).rejects.toThrow(
|
||||
outcome === 'interruption' ? 'interrupted' : 'setup failed'
|
||||
);
|
||||
}
|
||||
expect(saved).toBe(previous);
|
||||
expect(fs.writeFile).not.toHaveBeenCalled();
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledTimes(1);
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
'session-123'
|
||||
);
|
||||
expect(process.listeners('SIGINT')).toEqual(listeners);
|
||||
} finally {
|
||||
process.exitCode = priorExitCode;
|
||||
jest.mocked(fs.readFile).mockReset();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
it('reports unconfirmed cleanup rather than implying the session stopped', async () => {
|
||||
config(undefined, [{ action: 'appearance.set' }]);
|
||||
jest.mocked(applyStartConfigAsync).mockRejectedValue(new Error('setup failed'));
|
||||
mockEnsureDeviceRunSessionStoppedAsync.mockRejectedValue(new Error('network failed'));
|
||||
const prior = process.exitCode;
|
||||
try {
|
||||
await createCommand(['--import', configPath, '--json']).command.runAsync();
|
||||
expect(printJsonOnlyOutput).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ stopped: false })
|
||||
);
|
||||
expect(mockResetSimulatorEnvAsync).not.toHaveBeenCalled();
|
||||
expect(Log.warn).toHaveBeenCalledWith(
|
||||
expect.stringContaining('simulator:stop --id session-123')
|
||||
);
|
||||
} finally {
|
||||
process.exitCode = prior;
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects Android actions and invalid files before creating a session', async () => {
|
||||
config({ platform: 'android' }, [{ action: 'appearance.set' }]);
|
||||
await expect(
|
||||
createCommand(['--import', configPath, '--non-interactive']).command.runAsync()
|
||||
).rejects.toThrow('not supported on Android');
|
||||
expect(mockCreateDeviceRunSessionAsync).not.toHaveBeenCalled();
|
||||
config({ typo: 'value' });
|
||||
const { command, getContextAsync } = createCommand(['--import', configPath]);
|
||||
await expect(command.runAsync()).rejects.toThrow('Unknown or invocation-only');
|
||||
expect(getContextAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects explicit capture fields when the CLI disables saved capture', async () => {
|
||||
config({ platform: 'ios', 'network-capture': true });
|
||||
await expect(
|
||||
createCommand([
|
||||
'--import',
|
||||
configPath,
|
||||
'--no-network-capture',
|
||||
'--network-capture-field',
|
||||
'header',
|
||||
]).command.runAsync()
|
||||
).rejects.toThrow('--network-capture-field requires --network-capture');
|
||||
expect(mockCreateDeviceRunSessionAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('allows Android start settings without actions', async () => {
|
||||
config({ platform: 'android' });
|
||||
await createCommand(['--import', configPath, '--json']).command.runAsync();
|
||||
expect(mockCreateDeviceRunSessionAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
expect.objectContaining({ platform: AppPlatform.Android })
|
||||
);
|
||||
expect(applyStartConfigAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uses the existing platform prompt and attached-session lifecycle in interactive mode', async () => {
|
||||
config({}, [{ action: 'appearance.set' }]);
|
||||
const ready = makeDeviceRunSession({
|
||||
remoteConfig: {
|
||||
__typename: 'WebPreviewOnlyRunSessionRemoteConfig',
|
||||
previewUrl: 'https://expo.dev/preview',
|
||||
previewApiUrl: 'https://sim.example.test',
|
||||
previewToken: 'private-token',
|
||||
},
|
||||
});
|
||||
mockPromptAsync.mockResolvedValueOnce({ selectedPlatform: AppPlatform.Ios });
|
||||
mockByIdAsync
|
||||
.mockResolvedValueOnce(ready)
|
||||
.mockResolvedValueOnce({ ...ready, status: DeviceRunSessionStatus.Stopped });
|
||||
const listeners = process.listeners('SIGINT');
|
||||
await createCommand(['--import', configPath]).command.runAsync();
|
||||
expect(mockPromptAsync).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ message: 'Select platform' })
|
||||
);
|
||||
expect(applyStartConfigAsync).toHaveBeenCalledTimes(1);
|
||||
expect(mockByIdAsync).toHaveBeenCalledTimes(2);
|
||||
expect(mockResetSimulatorEnvAsync).toHaveBeenCalledWith(projectDir, 'session-123');
|
||||
expect(process.listeners('SIGINT')).toEqual(listeners);
|
||||
expect(printJsonOnlyOutput).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([['--non-interactive'], ['--json']])(
|
||||
'refuses an incomplete platform without prompting: %j',
|
||||
async mode => {
|
||||
config({}, [{ action: 'appearance.set' }]);
|
||||
await expect(
|
||||
createCommand(['--import', configPath, mode]).command.runAsync()
|
||||
).rejects.toThrow('platform flag must be set');
|
||||
expect(mockPromptAsync).not.toHaveBeenCalled();
|
||||
expect(mockCreateDeviceRunSessionAsync).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
|
||||
it.each(['CI', 'pipe'])('inherits non-interactive defaults for %s', async mode => {
|
||||
config({}, [{ action: 'appearance.set' }]);
|
||||
const priorCi = process.env.CI;
|
||||
const priorTty = process.stdin.isTTY;
|
||||
try {
|
||||
if (mode === 'CI') {
|
||||
process.env.CI = 'true';
|
||||
} else {
|
||||
Object.defineProperty(process.stdin, 'isTTY', { value: false, writable: true });
|
||||
}
|
||||
await expect(createCommand(['--import', configPath]).command.runAsync()).rejects.toThrow(
|
||||
'platform flag must be set'
|
||||
);
|
||||
expect(mockPromptAsync).not.toHaveBeenCalled();
|
||||
expect(mockCreateDeviceRunSessionAsync).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
if (priorCi === undefined) {
|
||||
delete process.env.CI;
|
||||
} else {
|
||||
process.env.CI = priorCi;
|
||||
}
|
||||
Object.defineProperty(process.stdin, 'isTTY', { value: priorTty, writable: true });
|
||||
}
|
||||
});
|
||||
|
||||
it('connects interactive local egress before applying imported actions and closes it on session end', async () => {
|
||||
config({ platform: 'ios', egress: 'local' }, [{ action: 'appearance.set' }]);
|
||||
const ready = localEgressSession;
|
||||
mockByIdAsync
|
||||
.mockResolvedValueOnce(ready)
|
||||
.mockResolvedValueOnce({ ...ready, status: DeviceRunSessionStatus.Stopped });
|
||||
let connected = false;
|
||||
let tunnelSignal: AbortSignal | undefined;
|
||||
jest.mocked(runLocalEgressAsync).mockImplementationOnce(async ({ signal, onConnected }) => {
|
||||
tunnelSignal = signal;
|
||||
await new Promise<void>(resolve => setImmediate(resolve));
|
||||
connected = true;
|
||||
onConnected?.();
|
||||
await new Promise<void>(resolve => {
|
||||
signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
resolve();
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
});
|
||||
});
|
||||
jest.mocked(applyStartConfigAsync).mockImplementationOnce(async () => {
|
||||
expect(connected).toBe(true);
|
||||
return [];
|
||||
});
|
||||
await createCommand(['--import', configPath]).command.runAsync();
|
||||
expect(tunnelSignal?.aborted).toBe(true);
|
||||
});
|
||||
|
||||
it.each([['--non-interactive'], ['--json']])(
|
||||
'rejects actions with detached local egress before creating a session: %j',
|
||||
async mode => {
|
||||
config({ platform: 'ios', egress: 'local' }, [{ action: 'appearance.get' }]);
|
||||
await expect(
|
||||
createCommand(['--import', configPath, mode]).command.runAsync()
|
||||
).rejects.toThrow('Imported actions with local egress require interactive mode');
|
||||
expect(mockCreateDeviceRunSessionAsync).not.toHaveBeenCalled();
|
||||
expect(applyStartConfigAsync).not.toHaveBeenCalled();
|
||||
expect(runLocalEgressAsync).not.toHaveBeenCalled();
|
||||
expect(mockPromptAsync).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
|
||||
it('cleans up and preserves an egress connection failure before setup', async () => {
|
||||
config({ platform: 'ios', egress: 'local' }, [{ action: 'appearance.get' }]);
|
||||
mockByIdAsync.mockResolvedValue(localEgressSession);
|
||||
const failure = new Error('egress could not bind');
|
||||
jest.mocked(runLocalEgressAsync).mockRejectedValueOnce(failure);
|
||||
const listeners = process.listeners('SIGINT');
|
||||
await expect(createCommand(['--import', configPath]).command.runAsync()).rejects.toBe(
|
||||
failure
|
||||
);
|
||||
expect(applyStartConfigAsync).not.toHaveBeenCalled();
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
'session-123'
|
||||
);
|
||||
expect(process.listeners('SIGINT')).toEqual(listeners);
|
||||
});
|
||||
|
||||
it('stops setup instead of running without requested local egress settings', async () => {
|
||||
config({ platform: 'ios', egress: 'local' }, [{ action: 'appearance.get' }]);
|
||||
await expect(createCommand(['--import', configPath]).command.runAsync()).rejects.toThrow(
|
||||
'did not provide local egress connection settings'
|
||||
);
|
||||
expect(applyStartConfigAsync).not.toHaveBeenCalled();
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
'session-123'
|
||||
);
|
||||
});
|
||||
|
||||
it.each(['action', 'egress'])(
|
||||
'preserves a %s failure during connected setup and closes the tunnel',
|
||||
async source => {
|
||||
config({ platform: 'ios', egress: 'local' }, [{ action: 'appearance.get' }]);
|
||||
mockByIdAsync.mockResolvedValue(localEgressSession);
|
||||
const failure = new Error(`${source} failed during setup`);
|
||||
let rejectTunnel: (error: Error) => void = () => {};
|
||||
let tunnelClosed = false;
|
||||
jest.mocked(runLocalEgressAsync).mockImplementationOnce(async ({ signal, onConnected }) => {
|
||||
onConnected?.();
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
rejectTunnel = reject;
|
||||
signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
resolve();
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
});
|
||||
} finally {
|
||||
tunnelClosed = true;
|
||||
}
|
||||
});
|
||||
jest
|
||||
.mocked(applyStartConfigAsync)
|
||||
.mockImplementationOnce(async (_access, _config, { signal }) => {
|
||||
if (source === 'action') {
|
||||
throw failure;
|
||||
}
|
||||
rejectTunnel(failure);
|
||||
await new Promise<void>((_resolve, reject) => {
|
||||
signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
reject(new Error('action aborted'));
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
});
|
||||
return [];
|
||||
});
|
||||
const listeners = process.listeners('SIGINT');
|
||||
await expect(createCommand(['--import', configPath]).command.runAsync()).rejects.toBe(
|
||||
failure
|
||||
);
|
||||
expect(tunnelClosed).toBe(true);
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
'session-123'
|
||||
);
|
||||
expect(mockResetSimulatorEnvAsync).toHaveBeenCalledWith(projectDir, 'session-123');
|
||||
expect(printJsonOnlyOutput).not.toHaveBeenCalled();
|
||||
expect(process.listeners('SIGINT')).toEqual(listeners);
|
||||
}
|
||||
);
|
||||
|
||||
it('bounds the wait for local egress and closes the tunnel on timeout', async () => {
|
||||
config({ platform: 'ios', egress: 'local' }, [{ action: 'appearance.get' }]);
|
||||
mockByIdAsync.mockResolvedValue(localEgressSession);
|
||||
let tunnelSignal: AbortSignal | undefined;
|
||||
jest.mocked(runLocalEgressAsync).mockImplementationOnce(async ({ signal }) => {
|
||||
tunnelSignal = signal;
|
||||
await new Promise<void>(resolve => {
|
||||
signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
resolve();
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
});
|
||||
});
|
||||
jest.useFakeTimers();
|
||||
try {
|
||||
const result = expect(
|
||||
createCommand(['--import', configPath]).command.runAsync()
|
||||
).rejects.toThrow('did not connect within 120 seconds');
|
||||
await jest.advanceTimersByTimeAsync(120_000);
|
||||
await result;
|
||||
expect(tunnelSignal?.aborted).toBe(true);
|
||||
expect(applyStartConfigAsync).not.toHaveBeenCalled();
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
'session-123'
|
||||
);
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('closes local egress and stops the session on Ctrl-C before the tunnel connects', async () => {
|
||||
config({ platform: 'ios', egress: 'local' }, [{ action: 'appearance.get' }]);
|
||||
mockByIdAsync.mockResolvedValue(localEgressSession);
|
||||
const interrupted = new Error('exit 130');
|
||||
jest.spyOn(process, 'exit').mockImplementation(() => {
|
||||
throw interrupted;
|
||||
});
|
||||
let tunnelClosed = false;
|
||||
jest.mocked(runLocalEgressAsync).mockImplementationOnce(async ({ signal }) => {
|
||||
await new Promise<void>(resolve => {
|
||||
signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
resolve();
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
setImmediate(() => {
|
||||
process.emit('SIGINT');
|
||||
});
|
||||
});
|
||||
tunnelClosed = true;
|
||||
});
|
||||
const listeners = process.listeners('SIGINT');
|
||||
await expect(createCommand(['--import', configPath]).command.runAsync()).rejects.toBe(
|
||||
interrupted
|
||||
);
|
||||
expect(tunnelClosed).toBe(true);
|
||||
expect(applyStartConfigAsync).not.toHaveBeenCalled();
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
'session-123'
|
||||
);
|
||||
expect(mockResetSimulatorEnvAsync).toHaveBeenCalledWith(projectDir, 'session-123');
|
||||
expect(process.listeners('SIGINT')).toEqual(listeners);
|
||||
});
|
||||
|
||||
it('stops on Ctrl-C during setup and removes the session handler', async () => {
|
||||
config(undefined, [{ action: 'appearance.set' }]);
|
||||
const interrupted = new Error('exit 130');
|
||||
const exit = jest.spyOn(process, 'exit').mockImplementation(() => {
|
||||
throw interrupted;
|
||||
});
|
||||
const listeners = process.listenerCount('SIGINT');
|
||||
jest
|
||||
.mocked(applyStartConfigAsync)
|
||||
.mockImplementation(async (_access, _config, { signal }) => {
|
||||
process.emit('SIGINT');
|
||||
signal.throwIfAborted();
|
||||
return [];
|
||||
});
|
||||
await expect(
|
||||
createCommand(['--import', configPath, '--non-interactive']).command.runAsync()
|
||||
).rejects.toBe(interrupted);
|
||||
expect(exit).toHaveBeenCalledWith(130);
|
||||
expect(mockEnsureDeviceRunSessionStoppedAsync).toHaveBeenCalledWith(
|
||||
graphqlClient,
|
||||
'session-123'
|
||||
);
|
||||
expect(process.listenerCount('SIGINT')).toBe(listeners);
|
||||
});
|
||||
});
|
||||
|
||||
it('fails with the waitlist link without creating a session when the account is gated', async () => {
|
||||
mockAvailabilityByAppIdAsync.mockResolvedValue({ accountName: 'testuser', available: false });
|
||||
|
||||
@@ -2633,14 +1831,7 @@ describe(Simulator, () => {
|
||||
'stops %s after an interactive egress failure and removes its interrupt handler',
|
||||
async (typeFlag, type, remoteConfig) => {
|
||||
const failure = new Error('listen EADDRINUSE');
|
||||
jest.mocked(runLocalEgressAsync).mockImplementationOnce(async () => {
|
||||
expect(fs.writeFile).toHaveBeenCalledWith(
|
||||
simulatorDotenvPath,
|
||||
expect.stringContaining("EAS_SIMULATOR_EGRESS_TOKEN='pw'")
|
||||
);
|
||||
expect(Log.log).toHaveBeenCalledWith(expect.stringContaining(deviceRunSessionUrl));
|
||||
throw failure;
|
||||
});
|
||||
jest.mocked(runLocalEgressAsync).mockRejectedValueOnce(failure);
|
||||
mockByIdAsync.mockResolvedValue(
|
||||
makeDeviceRunSession({
|
||||
type,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Args, Flags } from '@oclif/core';
|
||||
import chalk from 'chalk';
|
||||
import path from 'node:path';
|
||||
import { stripVTControlCharacters } from 'node:util';
|
||||
import * as fs from 'fs-extra';
|
||||
import path from 'path';
|
||||
|
||||
import EasCommand from '../../commandUtils/EasCommand';
|
||||
import {
|
||||
@@ -12,23 +12,6 @@ import { AppPlatform, DeviceRunSessionStatus } from '../../graphql/generated';
|
||||
import { DeviceRunSessionQuery } from '../../graphql/queries/DeviceRunSessionQuery';
|
||||
import Log from '../../log';
|
||||
import { ora } from '../../ora';
|
||||
import {
|
||||
ControlAction,
|
||||
executeControlActionAsync,
|
||||
parseControlActionOutput,
|
||||
prepareControlActionAsync,
|
||||
} from '../../simulator/controlActions';
|
||||
import {
|
||||
ControlConfigExecutionError,
|
||||
ControlConfigResult,
|
||||
PreparedControlConfig,
|
||||
executeControlConfigAsync,
|
||||
prepareControlConfigAsync,
|
||||
serializeControlConfigResults,
|
||||
} from '../../simulator/controlConfig';
|
||||
import { runControlMenuAsync } from '../../simulator/controlInteractive';
|
||||
import { ControlPromptCancelledError } from '../../simulator/controlPrompts';
|
||||
import { ControlSessionEndedError, watchControlSession } from '../../simulator/controlSession';
|
||||
import {
|
||||
EAS_SIMULATOR_SESSION_ID,
|
||||
SIMULATOR_DOTENV_FILE_NAME,
|
||||
@@ -38,53 +21,28 @@ import {
|
||||
HostActionCatalog,
|
||||
HostActionCatalogEntry,
|
||||
HostActionConnection,
|
||||
HostActionDevice,
|
||||
assertHostActionOutputAsync,
|
||||
buildHostActionParams,
|
||||
connectHostActionsAsync,
|
||||
fetchHostActionCatalogAsync,
|
||||
fetchHostActionDeviceAsync,
|
||||
formatHostActionUsage,
|
||||
saveHostActionOutputAsync,
|
||||
uploadFileAsync,
|
||||
} from '../../simulator/hostActions';
|
||||
import { PreviewApiAccess, getPreviewApiAccess } from '../../simulator/utils';
|
||||
import { enableJsonOutput, printJsonOnlyOutput } from '../../utils/json';
|
||||
import formatFields from '../../utils/formatFields';
|
||||
import { sanitizeTerminalText, truncate } from '../../utils/terminalText';
|
||||
import { formatMilliseconds } from '../../utils/timer';
|
||||
|
||||
type ControlSession = {
|
||||
id: string;
|
||||
name: string | null;
|
||||
project: string;
|
||||
status: DeviceRunSessionStatus;
|
||||
device: HostActionDevice;
|
||||
};
|
||||
|
||||
export default class SimulatorControl extends EasCommand {
|
||||
static override aliases = ['sim:control'];
|
||||
static override description = `[EXPERIMENTAL] control a remote iOS simulator session on EAS
|
||||
|
||||
Run without an action to open the menu, or use --list to see available actions. Use <action> --help for usage.
|
||||
|
||||
To save a screenshot locally, run \`eas simulator:control screenshot.capture --output ./screenshot.png\`.
|
||||
|
||||
Use --import to run saved actions from a JSON file:
|
||||
{
|
||||
"version": 1,
|
||||
"actions": [{"action": "appearance.set", "params": {"value": "dark"}}]
|
||||
}
|
||||
|
||||
The file is checked before any actions run. Actions run in order and stop on the first failure. Local paths are relative to the JSON file; paths in params refer to the simulator host.
|
||||
|
||||
Existing output files are overwritten. When saving to a directory, an existing file with the generated name causes the action to fail.`;
|
||||
static override description =
|
||||
'[EXPERIMENTAL] run a serve-sim action on a remote iOS simulator session on EAS. Run without an action to list the actions the session supports. To save a screenshot locally, run `eas simulator:control screenshot.capture --output ./screenshot.png`';
|
||||
static override strict = false;
|
||||
|
||||
static override examples = [
|
||||
'$ eas simulator:control',
|
||||
'$ eas simulator:control --list',
|
||||
'$ eas simulator:control --id <session-id>',
|
||||
'$ eas simulator:control screenshot.capture --help',
|
||||
'$ eas simulator:control clipboard.write -- --some-text',
|
||||
'$ eas simulator:control --import ./simulator-control.json',
|
||||
'$ eas simulator:control hardwareKeyboard.set off',
|
||||
'$ eas simulator:control permissions.set grant camera com.example.app',
|
||||
'$ eas simulator:control app.install ./MyApp.ipa',
|
||||
@@ -95,26 +53,24 @@ Existing output files are overwritten. When saving to a directory, an existing f
|
||||
static override args = {
|
||||
action: Args.string({
|
||||
description:
|
||||
'Action name, followed by values or name=value pairs. Omit to open the menu. Use -- before values starting with --.',
|
||||
'Action to run, followed by its values in order or as name=value. Omit to list the actions. Put -- before values that start with --.',
|
||||
}),
|
||||
};
|
||||
|
||||
static override flags = {
|
||||
help: Flags.boolean({
|
||||
char: 'h',
|
||||
description: 'Show help for this command or the selected action',
|
||||
description: 'Show command help, or usage for the selected action from the session.',
|
||||
}),
|
||||
id: Flags.string({
|
||||
description: `Simulator session ID. Defaults to ${SIMULATOR_DOTENV_FILE_NAME}.`,
|
||||
}),
|
||||
list: Flags.boolean({
|
||||
description: 'List available actions',
|
||||
description: 'List the actions the session supports.',
|
||||
}),
|
||||
output: Flags.string({
|
||||
description: 'Local file or existing directory for saved output',
|
||||
}),
|
||||
import: Flags.string({
|
||||
description: 'Run saved actions from a JSON file',
|
||||
description:
|
||||
'Local path to save a returned file. For screenshots, --output ./screenshot.png sets the local filename; omit it to save with a generated filename in the current directory.',
|
||||
}),
|
||||
...EasNonInteractiveAndJsonFlags,
|
||||
};
|
||||
@@ -135,21 +91,6 @@ Existing output files are overwritten. When saving to a directory, an existing f
|
||||
throw new Error('--id needs a simulator session ID.');
|
||||
}
|
||||
const action = flags.list && !flags.help ? undefined : args.action;
|
||||
const importing = flags.import !== undefined;
|
||||
if (importing && (args.action || flags.list || flags.output !== undefined)) {
|
||||
throw new Error('--import cannot be combined with an action, --list, or --output.');
|
||||
}
|
||||
const interactive = !flags.list && !action && !importing;
|
||||
if (!action && flags.output) {
|
||||
throw new Error(
|
||||
'--output requires an action. Choose an output path when selecting a file action in the interactive menu.'
|
||||
);
|
||||
}
|
||||
if (interactive && (nonInteractive || !process.stdin.isTTY)) {
|
||||
throw new Error(
|
||||
'No action provided. Run `eas simulator:control --list` to see the actions, then `eas simulator:control <action> [values...]`.'
|
||||
);
|
||||
}
|
||||
|
||||
const {
|
||||
projectDir,
|
||||
@@ -170,219 +111,41 @@ Existing output files are overwritten. When saving to a directory, an existing f
|
||||
let connection: HostActionConnection | undefined;
|
||||
try {
|
||||
let catalog: HostActionCatalog;
|
||||
let controlSession: ControlSession;
|
||||
try {
|
||||
const session = await DeviceRunSessionQuery.byIdAsync(graphqlClient, sessionId);
|
||||
const access = assertControllableSession(session);
|
||||
connection = await connectHostActionsAsync(access);
|
||||
connection = await connectHostActionsAsync(assertControllableSession(session));
|
||||
catalog = await fetchHostActionCatalogAsync(connection);
|
||||
controlSession = {
|
||||
id: session.id,
|
||||
name: session.name ?? null,
|
||||
project: `@${session.app.ownerAccount.name}/${session.app.slug}`,
|
||||
status: session.status,
|
||||
device:
|
||||
interactive || importing || (jsonFlag && !flags.list && !flags.help)
|
||||
? await fetchHostActionDeviceAsync(access, connection.udid)
|
||||
: { udid: connection.udid },
|
||||
};
|
||||
spinner.succeed(`Connected to simulator session ${sessionId}`);
|
||||
} catch (err) {
|
||||
spinner.fail(`Failed to connect to simulator session ${sessionId}`);
|
||||
throw err;
|
||||
}
|
||||
if (flags.list && !flags.help) {
|
||||
if (!action) {
|
||||
this.printCatalog(catalog, jsonFlag);
|
||||
return;
|
||||
}
|
||||
if (flags.help && action) {
|
||||
const entry = Object.hasOwn(catalog, action) ? catalog[action] : undefined;
|
||||
if (!entry) {
|
||||
throw new Error(
|
||||
`Unknown simulator action "${action}". Run \`eas simulator:control --list\` to see the actions.`
|
||||
);
|
||||
}
|
||||
const entry = Object.hasOwn(catalog, action) ? catalog[action] : undefined;
|
||||
if (!entry) {
|
||||
throw new Error(
|
||||
`Unknown simulator action "${action}". Run \`eas simulator:control\` to see the actions.`
|
||||
);
|
||||
}
|
||||
if (flags.help) {
|
||||
this.printActionHelp(action, entry, jsonFlag);
|
||||
return;
|
||||
}
|
||||
const activeConnection = connection;
|
||||
const runActionAsync = async (selection: ControlAction): Promise<void> => {
|
||||
await this.runActionAsync(activeConnection, catalog, selection, {
|
||||
session: controlSession,
|
||||
jsonFlag,
|
||||
interactive,
|
||||
});
|
||||
};
|
||||
if (interactive) {
|
||||
this.printSessionHeader(controlSession);
|
||||
const controller = new AbortController();
|
||||
const onConnectionLost = (): void => {
|
||||
controller.abort(activeConnection.signal.reason);
|
||||
};
|
||||
const onInterrupt = (): void => {
|
||||
controller.abort(new ControlPromptCancelledError());
|
||||
};
|
||||
activeConnection.signal.addEventListener('abort', onConnectionLost, { once: true });
|
||||
if (activeConnection.signal.aborted) {
|
||||
onConnectionLost();
|
||||
}
|
||||
process.on('SIGINT', onInterrupt);
|
||||
const session = watchControlSession(graphqlClient, sessionId, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
const detach = (): void => {
|
||||
activeConnection.close();
|
||||
};
|
||||
session.signal.addEventListener('abort', detach, { once: true });
|
||||
try {
|
||||
await runControlMenuAsync({
|
||||
catalog,
|
||||
signal: session.signal,
|
||||
runActionAsync,
|
||||
});
|
||||
} catch (error) {
|
||||
const reason: unknown = session.signal.aborted ? session.signal.reason : error;
|
||||
if (reason instanceof ControlPromptCancelledError) {
|
||||
process.exitCode = 130;
|
||||
} else if (reason instanceof ControlSessionEndedError) {
|
||||
if (reason.failed) {
|
||||
throw reason;
|
||||
}
|
||||
Log.log(reason.message);
|
||||
} else {
|
||||
throw reason;
|
||||
}
|
||||
} finally {
|
||||
session.signal.removeEventListener('abort', detach);
|
||||
session.dispose();
|
||||
activeConnection.signal.removeEventListener('abort', onConnectionLost);
|
||||
process.removeListener('SIGINT', onInterrupt);
|
||||
}
|
||||
} else if (importing) {
|
||||
await this.importConfigAsync(activeConnection, catalog, flags.import!, {
|
||||
session: controlSession,
|
||||
jsonFlag,
|
||||
});
|
||||
} else {
|
||||
const entry = Object.hasOwn(catalog, action!) ? catalog[action!] : undefined;
|
||||
await runActionAsync({
|
||||
action: action!,
|
||||
params: entry ? buildHostActionParams(action!, entry, argv.slice(1).map(String)) : {},
|
||||
outputPath: flags.output,
|
||||
});
|
||||
}
|
||||
await this.runActionAsync(connection, entry, {
|
||||
sessionId,
|
||||
action,
|
||||
values: argv.slice(1).map(String),
|
||||
outputPath: flags.output,
|
||||
jsonFlag,
|
||||
});
|
||||
} finally {
|
||||
connection?.close();
|
||||
}
|
||||
}
|
||||
|
||||
private async importConfigAsync(
|
||||
connection: HostActionConnection,
|
||||
catalog: HostActionCatalog,
|
||||
filePath: string,
|
||||
{ session, jsonFlag }: { session: ControlSession; jsonFlag: boolean }
|
||||
): Promise<void> {
|
||||
const spinner = jsonFlag ? undefined : ora(`Validating ${path.basename(filePath)}`).start();
|
||||
const startedAt = Date.now();
|
||||
let stepStartedAt = startedAt;
|
||||
let config: PreparedControlConfig | undefined;
|
||||
let results: ControlConfigResult[];
|
||||
try {
|
||||
config = await prepareControlConfigAsync(catalog, filePath, connection.udid);
|
||||
if (spinner) {
|
||||
spinner.succeed(`Validated ${formatActionCount(config.actions.length)}`);
|
||||
this.printSessionHeader(session);
|
||||
Log.log(chalk.bold(path.basename(config.path)));
|
||||
Log.gray(config.path);
|
||||
for (const { plan } of config.actions) {
|
||||
if (plan.localFile) {
|
||||
Log.gray(` Read: ${plan.localFile.path}`);
|
||||
}
|
||||
if (plan.outputPath) {
|
||||
Log.gray(` Output: ${plan.outputPath}`);
|
||||
}
|
||||
}
|
||||
if (config.actions.some(({ plan }) => plan.outputPath)) {
|
||||
Log.gray(
|
||||
'Explicit output files are overwritten; directory outputs use simulator filenames and fail if the file exists.'
|
||||
);
|
||||
}
|
||||
Log.newLine();
|
||||
}
|
||||
const prepared = config;
|
||||
results = await executeControlConfigAsync(connection, prepared, {
|
||||
onProgress: spinner
|
||||
? progress => {
|
||||
const label = `[${progress.step}/${progress.total}] ${progress.action}`;
|
||||
if (progress.status === 'running') {
|
||||
stepStartedAt = Date.now();
|
||||
spinner.start(label);
|
||||
} else {
|
||||
spinner.succeed(`${label} ${chalk.dim(formatElapsed(stepStartedAt))}`);
|
||||
this.printConfigResult(progress.result);
|
||||
}
|
||||
}
|
||||
: undefined,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof ControlConfigExecutionError && config) {
|
||||
spinner?.fail(
|
||||
`[${error.step}/${config.actions.length}] ${error.action} ${chalk.dim(formatElapsed(stepStartedAt))}`
|
||||
);
|
||||
if (jsonFlag) {
|
||||
printJsonOnlyOutput({
|
||||
id: session.id,
|
||||
session,
|
||||
config: config.path,
|
||||
results: serializeControlConfigResults(error.completed),
|
||||
error: { step: error.step, action: error.action, message: error.message },
|
||||
});
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
const skipped = config.actions.length - error.step;
|
||||
Log.newLine();
|
||||
Log.log(`${error.completed.length} completed · 1 failed · ${skipped} skipped`);
|
||||
for (const [index, { plan }] of config.actions.entries()) {
|
||||
if (index >= error.step) {
|
||||
Log.gray(` [${index + 1}/${config.actions.length}] ${plan.action} skipped`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
spinner?.fail(config ? 'Import failed' : 'Validation failed. No actions were run.');
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
if (jsonFlag) {
|
||||
printJsonOnlyOutput({
|
||||
id: session.id,
|
||||
session,
|
||||
config: config.path,
|
||||
results: serializeControlConfigResults(results),
|
||||
});
|
||||
} else {
|
||||
Log.newLine();
|
||||
Log.succeed(
|
||||
`Import complete · ${formatActionCount(results.length)} · ${formatElapsed(startedAt)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private printConfigResult(result: ControlConfigResult): void {
|
||||
if (result.file) {
|
||||
Log.log(` Saved: ${result.file}`);
|
||||
} else if (result.output) {
|
||||
const output = parseControlActionOutput(result.output);
|
||||
const text = typeof output === 'string' ? output : JSON.stringify(output, null, 2);
|
||||
Log.log(
|
||||
text
|
||||
.split('\n')
|
||||
.map(line => ` ${line}`)
|
||||
.join('\n')
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private printCatalog(catalog: HostActionCatalog, jsonFlag: boolean): void {
|
||||
if (jsonFlag) {
|
||||
printJsonOnlyOutput(
|
||||
@@ -447,86 +210,71 @@ Existing output files are overwritten. When saving to a directory, an existing f
|
||||
Log.newLine();
|
||||
}
|
||||
|
||||
private printSessionHeader(session: ControlSession): void {
|
||||
const clean = (value: string): string =>
|
||||
sanitizeTerminalText(
|
||||
stripVTControlCharacters(value).replace(/[\u202A-\u202E\u2066-\u2069]/g, '')
|
||||
);
|
||||
const runtime = clean(session.device.runtime ?? '')
|
||||
.replace(/^([A-Za-z]+)-/, '$1 ')
|
||||
.replaceAll('-', '.');
|
||||
Log.newLine();
|
||||
Log.log(chalk.bold('Simulator controls'));
|
||||
Log.log(
|
||||
formatFields([
|
||||
{ label: 'Session', value: truncate(clean(session.name ?? '') || 'Unnamed session', 80) },
|
||||
{ label: 'Project', value: clean(session.project) },
|
||||
{
|
||||
label: 'Device',
|
||||
value: [truncate(clean(session.device.name ?? '') || 'Unavailable', 80), runtime]
|
||||
.filter(Boolean)
|
||||
.join(' · '),
|
||||
},
|
||||
{ label: 'State', value: session.status.toLowerCase().replaceAll('_', ' ') },
|
||||
{ label: 'Session ID', value: clean(session.id) },
|
||||
{ label: 'Device ID', value: clean(session.device.udid) },
|
||||
])
|
||||
);
|
||||
Log.newLine();
|
||||
}
|
||||
|
||||
private async runActionAsync(
|
||||
connection: HostActionConnection,
|
||||
catalog: HostActionCatalog,
|
||||
selection: ControlAction,
|
||||
entry: HostActionCatalogEntry,
|
||||
{
|
||||
session,
|
||||
sessionId,
|
||||
action,
|
||||
values,
|
||||
outputPath,
|
||||
jsonFlag,
|
||||
interactive,
|
||||
}: { session: ControlSession; jsonFlag: boolean; interactive: boolean }
|
||||
}: {
|
||||
sessionId: string;
|
||||
action: string;
|
||||
values: string[];
|
||||
outputPath: string | undefined;
|
||||
jsonFlag: boolean;
|
||||
}
|
||||
): Promise<void> {
|
||||
const { action } = selection;
|
||||
const plan = await prepareControlActionAsync(catalog, selection);
|
||||
const startedAt = Date.now();
|
||||
const spinner = ora(
|
||||
interactive ? `Running ${action}` : `Running ${action} on simulator session ${session.id}`
|
||||
).start();
|
||||
const params = buildHostActionParams(action, entry, values);
|
||||
await assertHostActionOutputAsync(action, entry, outputPath);
|
||||
const localFile = await findLocalUploadAsync(entry, params);
|
||||
|
||||
const spinner = ora(`Running ${action} on simulator session ${sessionId}`).start();
|
||||
let uploadId: string | undefined;
|
||||
let succeeded = false;
|
||||
let output: string;
|
||||
let savedFile: string | null;
|
||||
try {
|
||||
({ output, file: savedFile } = await executeControlActionAsync(connection, plan));
|
||||
spinner.succeed(
|
||||
interactive
|
||||
? `${action} complete · ${formatElapsed(startedAt)}`
|
||||
: `Ran ${action} on simulator session ${session.id}`
|
||||
);
|
||||
if (localFile) {
|
||||
spinner.text = `Uploading ${localFile.path}`;
|
||||
const upload = await uploadFileAsync(connection, localFile.path);
|
||||
uploadId = upload.uploadId;
|
||||
params[localFile.param] = entry.uploadAs === 'id' ? upload.uploadId : upload.path;
|
||||
spinner.text = `Running ${action} on simulator session ${sessionId}`;
|
||||
}
|
||||
const result = await connection.requestAsync(action, params);
|
||||
if (result.exitCode !== 0) {
|
||||
const detail = (result.stderr || result.stdout).trim() || `exit code ${result.exitCode}`;
|
||||
throw new Error(`The simulator could not run ${action}: ${detail}`);
|
||||
}
|
||||
succeeded = true;
|
||||
savedFile = await saveHostActionOutputAsync(connection, entry, result.stdout, outputPath);
|
||||
output = savedFile ? '' : result.stdout.trim();
|
||||
spinner.succeed(`Ran ${action} on simulator session ${sessionId}`);
|
||||
} catch (err) {
|
||||
spinner.fail(
|
||||
interactive
|
||||
? `${action} failed`
|
||||
: `Failed to run ${action} on simulator session ${session.id}`
|
||||
);
|
||||
spinner.fail(`Failed to run ${action} on simulator session ${sessionId}`);
|
||||
throw err;
|
||||
} finally {
|
||||
if (uploadId && (!entry.keepUpload || !succeeded)) {
|
||||
await connection.requestAsync('upload.remove', { uploadId }).catch(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
if (jsonFlag) {
|
||||
printJsonOnlyOutput({
|
||||
id: session.id,
|
||||
session,
|
||||
id: sessionId,
|
||||
action,
|
||||
output: parseControlActionOutput(output),
|
||||
output: parseJsonOutput(output),
|
||||
file: savedFile,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (interactive && plan.localFile?.path) {
|
||||
Log.gray(`Source: ${plan.localFile.path}`);
|
||||
}
|
||||
if (savedFile) {
|
||||
Log.log(`Saved ${savedFile}`);
|
||||
} else if (output) {
|
||||
const parsed = parseControlActionOutput(output);
|
||||
Log.log(interactive && typeof parsed !== 'string' ? JSON.stringify(parsed, null, 2) : output);
|
||||
Log.log(output);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -547,12 +295,45 @@ function withUploadPathHelp(entry: HostActionCatalogEntry): HostActionCatalogEnt
|
||||
: entry;
|
||||
}
|
||||
|
||||
function formatElapsed(startedAt: number): string {
|
||||
return formatMilliseconds(Date.now() - startedAt) || '<1s';
|
||||
}
|
||||
|
||||
function formatActionCount(count: number): string {
|
||||
return `${count} action${count === 1 ? '' : 's'}`;
|
||||
async function findLocalUploadAsync(
|
||||
{ upload: param, uploadWhen = {}, uploadAs }: HostActionCatalogEntry,
|
||||
params: Record<string, unknown>
|
||||
): Promise<{ param: string; path: string } | null> {
|
||||
const value = param ? params[param] : undefined;
|
||||
const applies = Object.entries(uploadWhen).every(([name, expected]) => params[name] === expected);
|
||||
if (!param || typeof value !== 'string' || !applies) {
|
||||
return null;
|
||||
}
|
||||
if (value.startsWith('host:')) {
|
||||
if (uploadAs === 'id') {
|
||||
throw new Error(
|
||||
'This action requires a local file to upload; host: paths are not supported.'
|
||||
);
|
||||
}
|
||||
const hostPath = value.slice('host:'.length);
|
||||
if (!path.posix.isAbsolute(hostPath)) {
|
||||
throw new Error(
|
||||
`A host: path must be absolute, for example host:/tmp/app.tar.gz. For a local filename beginning with host:, use ./${value}.`
|
||||
);
|
||||
}
|
||||
params[param] = hostPath;
|
||||
return null;
|
||||
}
|
||||
const stat = await fs.stat(value).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code === 'ENOENT' || error.code === 'ENOTDIR') {
|
||||
return null;
|
||||
}
|
||||
throw error;
|
||||
});
|
||||
if (stat?.isDirectory()) {
|
||||
throw new Error(`${value} is a folder. Pass the path of a file.`);
|
||||
}
|
||||
if (!stat) {
|
||||
throw new Error(
|
||||
`${value} does not exist on this computer. Pass a local file, or prefix an absolute simulator-host path with host:.`
|
||||
);
|
||||
}
|
||||
return stat ? { param, path: value } : null;
|
||||
}
|
||||
|
||||
function assertControllableSession(
|
||||
@@ -565,7 +346,7 @@ function assertControllableSession(
|
||||
}
|
||||
if (session.platform !== AppPlatform.Ios) {
|
||||
throw new Error(
|
||||
`Simulator control on ${session.platform.toLowerCase()} is not supported yet. Simulator actions are available only for iOS sessions.`
|
||||
`Simulator session ${session.id} runs on ${session.platform.toLowerCase()}. Simulator actions are available only for iOS sessions.`
|
||||
);
|
||||
}
|
||||
const access = session.remoteConfig ? getPreviewApiAccess(session.remoteConfig) : null;
|
||||
@@ -576,3 +357,11 @@ function assertControllableSession(
|
||||
}
|
||||
return access;
|
||||
}
|
||||
|
||||
function parseJsonOutput(output: string): unknown {
|
||||
try {
|
||||
return JSON.parse(output);
|
||||
} catch {
|
||||
return output;
|
||||
}
|
||||
}
|
||||
@@ -30,12 +30,6 @@ import { DeviceRunSessionQuery } from '../../graphql/queries/DeviceRunSessionQue
|
||||
import Log, { link } from '../../log';
|
||||
import { Ora, ora } from '../../ora';
|
||||
import { promptAsync } from '../../prompts';
|
||||
import {
|
||||
ControlConfigExecutionError,
|
||||
serializeControlConfigResults,
|
||||
} from '../../simulator/controlConfig';
|
||||
import { resolveStartConfigAsync } from '../../simulator/startConfig';
|
||||
import { applyStartConfigAsync } from '../../simulator/startSetup';
|
||||
import { parseEgressAllowList, runLocalEgressAsync } from '../../simulator/egress';
|
||||
import { parseCorsOriginList, parseFrameAncestorList } from '../../simulator/frameAncestors';
|
||||
import { parseNetworkCaptureFields } from '../../simulator/networkCapture';
|
||||
@@ -65,15 +59,12 @@ import {
|
||||
formatRemoteSessionInstructions,
|
||||
formatSimulatorUnavailableMessage,
|
||||
getLocalEgressConfig,
|
||||
getPreviewApiAccess,
|
||||
getRemoteSessionEnvironmentVariables,
|
||||
sanitizeRemoteConfigForJson,
|
||||
} from '../../simulator/utils';
|
||||
import { enableJsonOutput, printJsonOnlyOutput } from '../../utils/json';
|
||||
import { sleepAsync } from '../../utils/promise';
|
||||
|
||||
// Allow the cold-cache client download (up to 60s) and a further minute to connect.
|
||||
const EGRESS_SETUP_TIMEOUT_MS = 120_000;
|
||||
const POLL_INTERVAL_MS = 5_000; // 5 seconds
|
||||
const STARTUP_TIMEOUT_MS = 15 * 60 * 1_000; // 15 minutes, excluding time in the queue
|
||||
const OUT_CONFIG_TYPE_VALUES = {
|
||||
@@ -91,30 +82,10 @@ const APP_PLATFORM_BY_FLAG_VALUE: Record<PlatformFlagValue, AppPlatform> = {
|
||||
export default class Simulator extends EasCommand {
|
||||
static override aliases = ['simulator:start', 'sim:start'];
|
||||
static override hiddenAliases = ['sim'];
|
||||
static override description = `[EXPERIMENTAL] start a remote simulator session on EAS
|
||||
|
||||
Preview links require sign-in by default.
|
||||
|
||||
Use --import to load saved start options and actions. CLI flags override saved options, including lists:
|
||||
{
|
||||
"version": 1,
|
||||
"start": {"platform": "ios"},
|
||||
"actions": [{"action": "appearance.set", "params": {"value": "dark"}}]
|
||||
}
|
||||
|
||||
The start object uses CLI flag names. Saved actions run after the session is ready. Local action paths are relative to the JSON file. If an action fails, the CLI tries to stop the new session. Android supports saved start options, but not actions yet.
|
||||
|
||||
With local egress, actions wait for the connection and require interactive mode. In scripts, connect with simulator:egress, then run simulator:control --import separately.`;
|
||||
|
||||
static override examples = [
|
||||
'$ eas simulator:start --import ./simulator.json',
|
||||
'$ eas simulator:start --import ./simulator.json --device "iPhone 17 Pro" --json',
|
||||
];
|
||||
static override description =
|
||||
'[EXPERIMENTAL] start a remote simulator session on EAS and get instructions to connect to it. The default browser preview link requires sign-in';
|
||||
|
||||
static override flags = {
|
||||
import: Flags.string({
|
||||
description: 'Load start options and actions from a JSON file',
|
||||
}),
|
||||
platform: Flags.option({
|
||||
char: 'p',
|
||||
description: 'Device platform',
|
||||
@@ -180,7 +151,6 @@ With local egress, actions wait for the connection and require interactive mode.
|
||||
'Version of the package backing the simulator session (e.g. "0.1.3-alpha.3"). Defaults to "latest" when omitted.',
|
||||
}),
|
||||
'network-capture': Flags.boolean({
|
||||
allowNo: true,
|
||||
description:
|
||||
'Record HTTP(S) traffic from apps on the device (iOS only). HTTPS is decrypted, so recordings contain credentials in cleartext and certificate-pinned apps fail to connect.',
|
||||
}),
|
||||
@@ -238,7 +208,6 @@ With local egress, actions wait for the connection and require interactive mode.
|
||||
default: OUT_CONFIG_TYPE_VALUES.Dotenv,
|
||||
})(),
|
||||
'public-link': Flags.boolean({
|
||||
allowNo: true,
|
||||
description:
|
||||
'Enable the simulator preview Share button and print a shareable link containing an access token. Anyone with the link can control the simulator. With --json, include previewApiUrl and its token for API clients when available.',
|
||||
}),
|
||||
@@ -253,13 +222,12 @@ With local egress, actions wait for the connection and require interactive mode.
|
||||
};
|
||||
|
||||
async runAsync(): Promise<void> {
|
||||
// Import preflight can fail before parsing; keep diagnostics off JSON stdout.
|
||||
if (this.argv.includes('--json')) {
|
||||
const { flags } = await this.parse(Simulator);
|
||||
const { json: jsonFlag, nonInteractive } = resolveNonInteractiveAndJsonFlags(flags);
|
||||
|
||||
if (jsonFlag) {
|
||||
enableJsonOutput();
|
||||
}
|
||||
const imported = await resolveStartConfigAsync(this.argv, Simulator.flags);
|
||||
const { flags } = await this.parse(Simulator, imported.argv);
|
||||
const { json: jsonFlag, nonInteractive } = resolveNonInteractiveAndJsonFlags(flags);
|
||||
|
||||
const {
|
||||
projectId,
|
||||
@@ -329,9 +297,6 @@ With local egress, actions wait for the connection and require interactive mode.
|
||||
} catch (err) {
|
||||
throw new EasCommandError(err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
if (networkCaptureFields.length && !flags['network-capture']) {
|
||||
throw new EasCommandError('--network-capture-field requires --network-capture.');
|
||||
}
|
||||
|
||||
const platform = await resolvePlatformAsync(flags.platform, nonInteractive);
|
||||
const egress = flags.egress === 'local' ? DeviceRunSessionEgress.Local : undefined;
|
||||
@@ -362,18 +327,6 @@ With local egress, actions wait for the connection and require interactive mode.
|
||||
);
|
||||
}
|
||||
|
||||
if (platform === AppPlatform.Android && imported.config?.actions?.length) {
|
||||
throw new EasCommandError(
|
||||
'Imported control actions are not supported on Android yet. Remove actions to import only start settings, or use --platform ios.'
|
||||
);
|
||||
}
|
||||
|
||||
if (nonInteractive && egress && imported.config?.actions?.length) {
|
||||
throw new EasCommandError(
|
||||
'Imported actions with local egress require interactive mode. Start without actions, connect eas simulator:egress, then run eas simulator:control --import with the same file.'
|
||||
);
|
||||
}
|
||||
|
||||
if (platform === AppPlatform.Android) {
|
||||
Log.warn(
|
||||
'Android emulator support in EAS Simulator is still in development. Some features available on iOS may not work on Android yet. Full parity with iOS is coming soon.'
|
||||
@@ -471,9 +424,7 @@ With local egress, actions wait for the connection and require interactive mode.
|
||||
);
|
||||
sessionInterrupt = registerSessionInterrupt(deviceRunSessionId);
|
||||
const simulatorEnvWritten =
|
||||
!jsonFlag &&
|
||||
!imported.config?.actions?.length &&
|
||||
flags['out-config-type'] === OUT_CONFIG_TYPE_VALUES.Dotenv
|
||||
!jsonFlag && flags['out-config-type'] === OUT_CONFIG_TYPE_VALUES.Dotenv
|
||||
? await writeSimulatorEnvSafelyAsync(projectDir, {
|
||||
[EAS_SIMULATOR_SESSION_ID]: deviceRunSessionId,
|
||||
})
|
||||
@@ -575,270 +526,101 @@ With local egress, actions wait for the connection and require interactive mode.
|
||||
);
|
||||
}
|
||||
|
||||
if (flags['out-config-type'] === OUT_CONFIG_TYPE_VALUES.Dotenv) {
|
||||
await writeSimulatorEnvSafelyAsync(projectDir, {
|
||||
...getRemoteSessionEnvironmentVariables(remoteConfig, { egressAllow, platform }),
|
||||
[EAS_SIMULATOR_SESSION_ID]: deviceRunSessionId,
|
||||
});
|
||||
}
|
||||
|
||||
if (sessionInterrupt.signal.aborted) {
|
||||
await stopDeviceRunSessionAfterInterruptAsync({
|
||||
graphqlClient,
|
||||
deviceRunSessionId,
|
||||
projectDir,
|
||||
spinner: pollSpinner,
|
||||
sessionInterrupt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (jsonFlag) {
|
||||
sessionInterrupt.dispose();
|
||||
printJsonOnlyOutput({
|
||||
id: deviceRunSessionId,
|
||||
name,
|
||||
type: flags.type,
|
||||
deviceRunSessionUrl,
|
||||
remoteConfig: sanitizeRemoteConfigForJson(
|
||||
remoteConfig,
|
||||
deviceRunSessionPreviewUrl,
|
||||
flags['public-link'],
|
||||
{ frameAncestors, corsOrigins }
|
||||
),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
Log.newLine();
|
||||
Log.log(
|
||||
formatRemoteSessionInstructions(remoteConfig, flags['out-config-type'], {
|
||||
egressAllow,
|
||||
egressClientRunsInline: !nonInteractive,
|
||||
sessionUrl: deviceRunSessionUrl,
|
||||
privatePreviewUrl: deviceRunSessionPreviewUrl,
|
||||
publicLink: flags['public-link'],
|
||||
frameAncestors,
|
||||
corsOrigins,
|
||||
platform,
|
||||
})
|
||||
);
|
||||
Log.newLine();
|
||||
|
||||
const localEgress = getLocalEgressConfig(remoteConfig, egressAllow, platform);
|
||||
|
||||
if (nonInteractive) {
|
||||
sessionInterrupt.dispose();
|
||||
// The instructions above already tell the reader to run eas simulator:egress.
|
||||
Log.log(
|
||||
`When you are done, stop the session with: eas simulator:stop --id ${deviceRunSessionId}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// In interactive mode the egress client runs right here, for as long as the
|
||||
// session does. A session with a disconnected tunnel still bills, so Ctrl+C stops both.
|
||||
let egressPromise: Promise<void> | undefined;
|
||||
let egressError: Error | undefined;
|
||||
const egressAbortController = new AbortController();
|
||||
let markEgressReady: () => void;
|
||||
const egressReady = new Promise<void>(resolve => {
|
||||
markEgressReady = resolve;
|
||||
});
|
||||
const onSessionAbort = (): void => {
|
||||
egressAbortController.abort();
|
||||
};
|
||||
const startLocalEgress = (): void => {
|
||||
if (localEgress && !nonInteractive) {
|
||||
sessionInterrupt.signal.addEventListener('abort', onSessionAbort, { once: true });
|
||||
egressPromise = runLocalEgressAsync({
|
||||
...localEgress,
|
||||
signal: egressAbortController.signal,
|
||||
onConnected: () => {
|
||||
markEgressReady();
|
||||
Log.succeed('Egress tunnel connected.');
|
||||
},
|
||||
onDisconnected: () => {
|
||||
Log.warn(
|
||||
'Egress tunnel disconnected; reconnecting. Proxied HTTP(S) requests are unavailable until it reconnects.'
|
||||
);
|
||||
},
|
||||
}).catch(err => {
|
||||
egressError = err instanceof Error ? err : new Error(String(err));
|
||||
Log.error(
|
||||
`${err instanceof Error ? err.message : String(err)} Stopping the simulator session.`
|
||||
);
|
||||
sessionInterrupt.abort();
|
||||
});
|
||||
}
|
||||
};
|
||||
const writeReadySimulatorEnvAsync = async (): Promise<void> => {
|
||||
if (flags['out-config-type'] === OUT_CONFIG_TYPE_VALUES.Dotenv) {
|
||||
await writeSimulatorEnvSafelyAsync(projectDir, {
|
||||
...getRemoteSessionEnvironmentVariables(remoteConfig, { egressAllow, platform }),
|
||||
[EAS_SIMULATOR_SESSION_ID]: deviceRunSessionId,
|
||||
});
|
||||
}
|
||||
};
|
||||
try {
|
||||
if (!jsonFlag && !imported.config?.actions?.length) {
|
||||
await writeReadySimulatorEnvAsync();
|
||||
}
|
||||
|
||||
if (sessionInterrupt.signal.aborted && !egressError) {
|
||||
await stopDeviceRunSessionAfterInterruptAsync({
|
||||
graphqlClient,
|
||||
deviceRunSessionId,
|
||||
projectDir,
|
||||
spinner: pollSpinner,
|
||||
sessionInterrupt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!jsonFlag) {
|
||||
Log.newLine();
|
||||
Log.log(
|
||||
formatRemoteSessionInstructions(remoteConfig, flags['out-config-type'], {
|
||||
egressAllow,
|
||||
egressClientRunsInline: !nonInteractive,
|
||||
sessionUrl: deviceRunSessionUrl,
|
||||
privatePreviewUrl: deviceRunSessionPreviewUrl,
|
||||
publicLink: flags['public-link'],
|
||||
frameAncestors,
|
||||
corsOrigins,
|
||||
platform,
|
||||
})
|
||||
);
|
||||
Log.newLine();
|
||||
if (nonInteractive) {
|
||||
Log.log(
|
||||
`When you are done, stop the session with: eas simulator:stop --id ${deviceRunSessionId}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let setup:
|
||||
| { config: string; results: ReturnType<typeof serializeControlConfigResults> }
|
||||
| undefined;
|
||||
if (imported.config?.actions?.length) {
|
||||
const total = imported.config.actions.length;
|
||||
if (!jsonFlag) {
|
||||
Log.newLine();
|
||||
Log.log(
|
||||
`Importing ${total} action${total === 1 ? '' : 's'} from ${imported.config.path}`
|
||||
);
|
||||
}
|
||||
startLocalEgress();
|
||||
const setupSpinner = ora('Importing simulator configuration').start();
|
||||
try {
|
||||
if (egress && !localEgress) {
|
||||
throw new Error('The ready session did not provide local egress connection settings.');
|
||||
}
|
||||
if (egressPromise) {
|
||||
setupSpinner.text = 'Waiting for local egress before applying configuration';
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
try {
|
||||
await Promise.race([
|
||||
egressReady,
|
||||
egressPromise,
|
||||
sessionInterrupt.abortPromise,
|
||||
new Promise<never>((_resolve, reject) => {
|
||||
timer = setTimeout(() => {
|
||||
reject(new Error('Local egress did not connect within 120 seconds.'));
|
||||
}, EGRESS_SETUP_TIMEOUT_MS);
|
||||
timer.unref();
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
if (egressError) {
|
||||
throw egressError;
|
||||
}
|
||||
sessionInterrupt.signal.throwIfAborted();
|
||||
}
|
||||
const access = getPreviewApiAccess(remoteConfig);
|
||||
if (!access) {
|
||||
throw new Error(
|
||||
'This session does not expose an authenticated preview API for control actions.'
|
||||
);
|
||||
}
|
||||
const results = await applyStartConfigAsync(access, imported.config, {
|
||||
signal: sessionInterrupt.signal,
|
||||
onProgress: jsonFlag
|
||||
? undefined
|
||||
: progress => {
|
||||
const label = `[${progress.step}/${progress.total}] ${progress.action}`;
|
||||
if (progress.status === 'running') {
|
||||
setupSpinner.start(label);
|
||||
} else {
|
||||
setupSpinner.succeed(`${label} completed`);
|
||||
if (progress.result.file) {
|
||||
Log.log(`Saved ${progress.result.file}`);
|
||||
} else if (progress.result.output) {
|
||||
Log.log(progress.result.output);
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
sessionInterrupt.signal.throwIfAborted();
|
||||
setup = { config: imported.config.path, results: serializeControlConfigResults(results) };
|
||||
setupSpinner.succeed(
|
||||
`Import complete: ${total} action${total === 1 ? '' : 's'} completed`
|
||||
);
|
||||
} catch (caught) {
|
||||
if (localEgress) {
|
||||
sessionInterrupt.signal.addEventListener(
|
||||
'abort',
|
||||
() => {
|
||||
egressAbortController.abort();
|
||||
await egressPromise;
|
||||
const error = egressError ?? caught;
|
||||
if (sessionInterrupt.signal.aborted && !egressError) {
|
||||
await stopDeviceRunSessionAfterInterruptAsync({
|
||||
graphqlClient,
|
||||
deviceRunSessionId,
|
||||
projectDir,
|
||||
spinner: setupSpinner,
|
||||
sessionInterrupt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (error instanceof ControlConfigExecutionError) {
|
||||
setupSpinner.fail(`[${error.step}/${total}] ${error.action} failed`);
|
||||
if (!jsonFlag) {
|
||||
const skipped = total - error.step;
|
||||
Log.log(`${error.completed.length} completed · 1 failed · ${skipped} skipped`);
|
||||
for (const [index, action] of imported.config.actions.entries()) {
|
||||
if (index >= error.step) {
|
||||
Log.log(` [${index + 1}/${total}] ${action.action} skipped`);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
setupSpinner.fail('Simulator configuration import failed');
|
||||
}
|
||||
const stopped = await ensureDeviceRunSessionStoppedSafelyAsync(
|
||||
graphqlClient,
|
||||
deviceRunSessionId
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
egressPromise = runLocalEgressAsync({
|
||||
...localEgress,
|
||||
signal: egressAbortController.signal,
|
||||
onConnected: () => {
|
||||
Log.succeed('Egress tunnel connected.');
|
||||
},
|
||||
onDisconnected: () => {
|
||||
Log.warn(
|
||||
'Egress tunnel disconnected; reconnecting. Proxied HTTP(S) requests are unavailable until it reconnects.'
|
||||
);
|
||||
if (stopped) {
|
||||
if (!jsonFlag) {
|
||||
Log.succeed('Stopped the simulator session after setup failed.');
|
||||
}
|
||||
await resetSimulatorEnvAsync(projectDir, deviceRunSessionId).catch(error => {
|
||||
Log.warn(
|
||||
`The session stopped, but ${SIMULATOR_DOTENV_FILE_NAME} could not be cleaned up: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
});
|
||||
} else {
|
||||
Log.warn(
|
||||
`Could not confirm cleanup. Run eas simulator:stop --id ${deviceRunSessionId} to stop the session.`
|
||||
);
|
||||
}
|
||||
sessionInterrupt.dispose();
|
||||
if (jsonFlag) {
|
||||
printJsonOnlyOutput({
|
||||
id: deviceRunSessionId,
|
||||
deviceRunSessionUrl,
|
||||
stopped,
|
||||
setup: {
|
||||
config: imported.config.path,
|
||||
results:
|
||||
error instanceof ControlConfigExecutionError
|
||||
? serializeControlConfigResults(error.completed)
|
||||
: [],
|
||||
error: {
|
||||
...(error instanceof ControlConfigExecutionError
|
||||
? { step: error.step, action: error.action }
|
||||
: {}),
|
||||
message: error instanceof Error ? error.message : String(error),
|
||||
},
|
||||
},
|
||||
});
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
if (jsonFlag || imported.config?.actions?.length) {
|
||||
// Keep the previous session's saved credentials until setup succeeds.
|
||||
await writeReadySimulatorEnvAsync();
|
||||
if (sessionInterrupt.signal.aborted) {
|
||||
await stopDeviceRunSessionAfterInterruptAsync({
|
||||
graphqlClient,
|
||||
deviceRunSessionId,
|
||||
projectDir,
|
||||
spinner: pollSpinner,
|
||||
sessionInterrupt,
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (jsonFlag) {
|
||||
sessionInterrupt.dispose();
|
||||
printJsonOnlyOutput({
|
||||
id: deviceRunSessionId,
|
||||
name,
|
||||
type: flags.type,
|
||||
deviceRunSessionUrl,
|
||||
...(setup ? { setup } : {}),
|
||||
remoteConfig: sanitizeRemoteConfigForJson(
|
||||
remoteConfig,
|
||||
deviceRunSessionPreviewUrl,
|
||||
flags['public-link'],
|
||||
{ frameAncestors, corsOrigins }
|
||||
),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (nonInteractive) {
|
||||
sessionInterrupt.dispose();
|
||||
return;
|
||||
}
|
||||
|
||||
if (!imported.config?.actions?.length) {
|
||||
startLocalEgress();
|
||||
}
|
||||
},
|
||||
}).catch(err => {
|
||||
egressError = err instanceof Error ? err : new Error(String(err));
|
||||
Log.error(
|
||||
`${err instanceof Error ? err.message : String(err)} Stopping the simulator session.`
|
||||
);
|
||||
sessionInterrupt.abort();
|
||||
});
|
||||
}
|
||||
|
||||
try {
|
||||
await waitForSessionEndOrInterruptAsync({
|
||||
graphqlClient,
|
||||
deviceRunSessionId,
|
||||
@@ -846,14 +628,13 @@ With local egress, actions wait for the connection and require interactive mode.
|
||||
projectDir,
|
||||
sessionInterrupt,
|
||||
});
|
||||
if (egressError) {
|
||||
throw egressError;
|
||||
}
|
||||
} finally {
|
||||
sessionInterrupt.signal.removeEventListener('abort', onSessionAbort);
|
||||
egressAbortController.abort();
|
||||
await egressPromise;
|
||||
}
|
||||
if (egressError) {
|
||||
throw egressError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { OperationContext, OperationResult, OperationResultSource } from '@urql/core';
|
||||
import { OperationResult, OperationResultSource } from '@urql/core';
|
||||
import gql from 'graphql-tag';
|
||||
|
||||
import { ExpoGraphqlClient } from '../../commandUtils/context/contextUtils/createGraphqlClient';
|
||||
@@ -96,114 +96,109 @@ export const DeviceRunSessionQuery = {
|
||||
deviceRunSessionId: string
|
||||
): Promise<DeviceRunSessionByIdQuery['deviceRunSessions']['byId']> {
|
||||
const data = await withErrorHandlingAsync(
|
||||
DeviceRunSessionQuery.byId(graphqlClient, deviceRunSessionId).toPromise()
|
||||
);
|
||||
return data.deviceRunSessions.byId;
|
||||
},
|
||||
byId(
|
||||
graphqlClient: ExpoGraphqlClient,
|
||||
deviceRunSessionId: string,
|
||||
context: Partial<OperationContext> = {}
|
||||
): OperationResultSource<OperationResult<DeviceRunSessionByIdQuery>> {
|
||||
return graphqlClient.query<DeviceRunSessionByIdQuery, DeviceRunSessionByIdQueryVariables>(
|
||||
gql`
|
||||
query DeviceRunSessionByIdQuery($deviceRunSessionId: ID!) {
|
||||
deviceRunSessions {
|
||||
byId(deviceRunSessionId: $deviceRunSessionId) {
|
||||
id
|
||||
name
|
||||
tags
|
||||
publicPreview
|
||||
status
|
||||
type
|
||||
platform
|
||||
createdAt
|
||||
startedAt
|
||||
finishedAt
|
||||
updatedAt
|
||||
app {
|
||||
id
|
||||
slug
|
||||
ownerAccount {
|
||||
graphqlClient
|
||||
.query<DeviceRunSessionByIdQuery, DeviceRunSessionByIdQueryVariables>(
|
||||
gql`
|
||||
query DeviceRunSessionByIdQuery($deviceRunSessionId: ID!) {
|
||||
deviceRunSessions {
|
||||
byId(deviceRunSessionId: $deviceRunSessionId) {
|
||||
id
|
||||
name
|
||||
tags
|
||||
publicPreview
|
||||
status
|
||||
type
|
||||
platform
|
||||
createdAt
|
||||
startedAt
|
||||
finishedAt
|
||||
updatedAt
|
||||
app {
|
||||
id
|
||||
slug
|
||||
ownerAccount {
|
||||
id
|
||||
name
|
||||
}
|
||||
}
|
||||
artifacts {
|
||||
id
|
||||
name
|
||||
filename
|
||||
downloadUrl
|
||||
fileSizeBytes
|
||||
metadata
|
||||
createdAt
|
||||
updatedAt
|
||||
}
|
||||
remoteConfig {
|
||||
__typename
|
||||
... on AgentDeviceRunSessionRemoteConfig {
|
||||
agentDeviceRemoteSessionUrl
|
||||
agentDeviceRemoteSessionToken
|
||||
webPreviewUrl
|
||||
webPreviewToken
|
||||
previewApiUrl
|
||||
egressUrl
|
||||
egressToken
|
||||
egressFingerprint
|
||||
egressPort
|
||||
}
|
||||
... on ArgentRunSessionRemoteConfig {
|
||||
egressUrl
|
||||
egressToken
|
||||
egressFingerprint
|
||||
egressPort
|
||||
toolsUrl
|
||||
toolsAuthToken
|
||||
webPreviewUrl
|
||||
webPreviewToken
|
||||
previewApiUrl
|
||||
}
|
||||
... on AppiumRunSessionRemoteConfig {
|
||||
egressUrl
|
||||
egressToken
|
||||
egressFingerprint
|
||||
egressPort
|
||||
appiumUrl
|
||||
capabilities
|
||||
webPreviewUrl
|
||||
webPreviewToken
|
||||
previewApiUrl
|
||||
}
|
||||
... on ServeSimRunSessionRemoteConfig {
|
||||
egressUrl
|
||||
egressToken
|
||||
egressFingerprint
|
||||
egressPort
|
||||
previewUrl
|
||||
previewToken
|
||||
previewApiUrl
|
||||
}
|
||||
... on WebPreviewOnlyRunSessionRemoteConfig {
|
||||
egressUrl
|
||||
egressToken
|
||||
egressFingerprint
|
||||
egressPort
|
||||
previewUrl: webPreviewUrl
|
||||
previewToken: webPreviewToken
|
||||
previewApiUrl
|
||||
}
|
||||
}
|
||||
turtleJobRun {
|
||||
id
|
||||
status
|
||||
}
|
||||
}
|
||||
}
|
||||
artifacts {
|
||||
id
|
||||
name
|
||||
filename
|
||||
downloadUrl
|
||||
fileSizeBytes
|
||||
metadata
|
||||
createdAt
|
||||
updatedAt
|
||||
}
|
||||
remoteConfig {
|
||||
__typename
|
||||
... on AgentDeviceRunSessionRemoteConfig {
|
||||
agentDeviceRemoteSessionUrl
|
||||
agentDeviceRemoteSessionToken
|
||||
webPreviewUrl
|
||||
webPreviewToken
|
||||
previewApiUrl
|
||||
egressUrl
|
||||
egressToken
|
||||
egressFingerprint
|
||||
egressPort
|
||||
}
|
||||
... on ArgentRunSessionRemoteConfig {
|
||||
egressUrl
|
||||
egressToken
|
||||
egressFingerprint
|
||||
egressPort
|
||||
toolsUrl
|
||||
toolsAuthToken
|
||||
webPreviewUrl
|
||||
webPreviewToken
|
||||
previewApiUrl
|
||||
}
|
||||
... on AppiumRunSessionRemoteConfig {
|
||||
egressUrl
|
||||
egressToken
|
||||
egressFingerprint
|
||||
egressPort
|
||||
appiumUrl
|
||||
capabilities
|
||||
webPreviewUrl
|
||||
webPreviewToken
|
||||
previewApiUrl
|
||||
}
|
||||
... on ServeSimRunSessionRemoteConfig {
|
||||
egressUrl
|
||||
egressToken
|
||||
egressFingerprint
|
||||
egressPort
|
||||
previewUrl
|
||||
previewToken
|
||||
previewApiUrl
|
||||
}
|
||||
... on WebPreviewOnlyRunSessionRemoteConfig {
|
||||
egressUrl
|
||||
egressToken
|
||||
egressFingerprint
|
||||
egressPort
|
||||
previewUrl: webPreviewUrl
|
||||
previewToken: webPreviewToken
|
||||
previewApiUrl
|
||||
}
|
||||
}
|
||||
turtleJobRun {
|
||||
id
|
||||
status
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
`,
|
||||
{ deviceRunSessionId },
|
||||
{ requestPolicy: 'network-only', ...context }
|
||||
`,
|
||||
{ deviceRunSessionId },
|
||||
{ requestPolicy: 'network-only' }
|
||||
)
|
||||
.toPromise()
|
||||
);
|
||||
return data.deviceRunSessions.byId;
|
||||
},
|
||||
async listByAppIdAsync(
|
||||
graphqlClient: ExpoGraphqlClient,
|
||||
|
||||
@@ -1,408 +0,0 @@
|
||||
import * as fs from 'fs-extra';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { executeControlActionAsync, prepareControlActionAsync } from '../controlActions';
|
||||
import { HostActionCatalog, HostActionConnection, HostActionResult } from '../hostActions';
|
||||
|
||||
const catalog: HostActionCatalog = {
|
||||
settings: { type: 'object' },
|
||||
install: { upload: 'uploadId', uploadAs: 'id' },
|
||||
media: { upload: 'path' },
|
||||
camera: { upload: 'target', uploadWhen: { source: 'file' }, keepUpload: true },
|
||||
screenshot: { output: 'path' },
|
||||
download: { output: 'base64' },
|
||||
};
|
||||
const ok = (stdout = ''): HostActionResult => ({ stdout, stderr: '', exitCode: 0 });
|
||||
|
||||
describe('control action preparation and execution', () => {
|
||||
let tmpDir: string;
|
||||
let controller: AbortController;
|
||||
let result: HostActionResult;
|
||||
let connection: HostActionConnection;
|
||||
let requestAsync: jest.Mock<Promise<HostActionResult>, [string, Record<string, unknown>?]>;
|
||||
|
||||
beforeEach(async () => {
|
||||
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'control-actions-'));
|
||||
controller = new AbortController();
|
||||
result = ok(' on\n');
|
||||
requestAsync = jest.fn(async (action: string, params: Record<string, unknown> = {}) => {
|
||||
if (action === 'upload.append') {
|
||||
return ok(`/remote/staging/${params.uploadId}\n`);
|
||||
}
|
||||
if (action === 'upload.remove') {
|
||||
return ok();
|
||||
}
|
||||
if (action === 'file.readBase64') {
|
||||
return ok(Buffer.from('download bytes').toString('base64'));
|
||||
}
|
||||
return result;
|
||||
});
|
||||
connection = {
|
||||
udid: '90858C9D-BC34-4A0A-93D4-E4939A681A72',
|
||||
signal: controller.signal,
|
||||
requestAsync,
|
||||
close: () => {
|
||||
controller.abort(new Error('closed'));
|
||||
},
|
||||
};
|
||||
await fs.writeFile(path.join(tmpDir, 'fixture.json'), 'file bytes');
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await fs.remove(tmpDir);
|
||||
});
|
||||
|
||||
it('copies typed and empty values without parsing stdout', async () => {
|
||||
const params = { enabled: false, count: 0, text: '', nested: { values: ['original'] } };
|
||||
const plan = await prepareControlActionAsync(catalog, { action: 'settings', params });
|
||||
params.text = 'changed';
|
||||
expect(plan.params).toEqual({
|
||||
enabled: false,
|
||||
count: 0,
|
||||
text: '',
|
||||
nested: { values: ['original'] },
|
||||
});
|
||||
result = ok(' {"value":0}\n');
|
||||
|
||||
await expect(executeControlActionAsync(connection, plan)).resolves.toEqual({
|
||||
output: '{"value":0}',
|
||||
file: null,
|
||||
});
|
||||
expect(requestAsync).toHaveBeenCalledWith('settings', plan.params);
|
||||
result = ok('');
|
||||
await expect(executeControlActionAsync(connection, plan)).resolves.toEqual({
|
||||
output: '',
|
||||
file: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects unknown actions and inapplicable output before execution', async () => {
|
||||
await expect(
|
||||
prepareControlActionAsync(catalog, { action: 'toString', params: {} })
|
||||
).rejects.toThrow('Unknown simulator action');
|
||||
await expect(
|
||||
prepareControlActionAsync(catalog, { action: 'settings', params: {}, outputPath: './out' })
|
||||
).rejects.toThrow('does not return a file');
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('resolves explicit local files and outputs against the supplied directory', async () => {
|
||||
const plan = await prepareControlActionAsync(
|
||||
catalog,
|
||||
{
|
||||
action: 'install',
|
||||
params: {},
|
||||
file: 'fixture.json',
|
||||
},
|
||||
{ localFileMode: 'explicit', baseDir: tmpDir }
|
||||
);
|
||||
expect(plan.localFile).toEqual({ param: 'uploadId', path: path.join(tmpDir, 'fixture.json') });
|
||||
const output = await prepareControlActionAsync(
|
||||
catalog,
|
||||
{
|
||||
action: 'download',
|
||||
params: {},
|
||||
outputPath: 'result.json',
|
||||
},
|
||||
{ baseDir: tmpDir }
|
||||
);
|
||||
expect(output.outputPath).toBe(path.join(tmpDir, 'result.json'));
|
||||
});
|
||||
|
||||
it('preserves an explicitly requested output directory when resolving relative paths', async () => {
|
||||
await expect(
|
||||
prepareControlActionAsync(
|
||||
catalog,
|
||||
{
|
||||
action: 'download',
|
||||
params: {},
|
||||
outputPath: 'missing/',
|
||||
},
|
||||
{ baseDir: tmpDir }
|
||||
)
|
||||
).rejects.toThrow('does not exist');
|
||||
});
|
||||
|
||||
it('rejects ambiguous or inapplicable explicit uploads', async () => {
|
||||
for (const action of [
|
||||
{ action: 'settings', params: {} },
|
||||
{ action: 'camera', params: { source: 'webcam' } },
|
||||
{ action: 'install', params: { uploadId: 'already-supplied' } },
|
||||
]) {
|
||||
await expect(
|
||||
prepareControlActionAsync(catalog, {
|
||||
...action,
|
||||
file: path.join(tmpDir, 'fixture.json'),
|
||||
})
|
||||
).rejects.toThrow();
|
||||
}
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects missing, empty and directory inputs before execution', async () => {
|
||||
await fs.writeFile(path.join(tmpDir, 'empty'), '');
|
||||
for (const file of ['missing', 'empty', '.']) {
|
||||
await expect(
|
||||
prepareControlActionAsync(
|
||||
catalog,
|
||||
{
|
||||
action: 'install',
|
||||
params: {},
|
||||
file,
|
||||
},
|
||||
{ baseDir: tmpDir }
|
||||
)
|
||||
).rejects.toThrow();
|
||||
}
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uses explicit host paths and does not infer uploads in explicit mode', async () => {
|
||||
const localFile = path.join(tmpDir, 'fixture.json');
|
||||
expect(
|
||||
(
|
||||
await prepareControlActionAsync(catalog, {
|
||||
action: 'media',
|
||||
params: { path: localFile },
|
||||
})
|
||||
).localFile?.path
|
||||
).toBe(localFile);
|
||||
const remotePath = path.join(tmpDir, 'remote-only');
|
||||
expect(
|
||||
(
|
||||
await prepareControlActionAsync(catalog, {
|
||||
action: 'media',
|
||||
params: { path: `host:${remotePath}` },
|
||||
})
|
||||
).localFile
|
||||
).toBeUndefined();
|
||||
await expect(
|
||||
prepareControlActionAsync(
|
||||
catalog,
|
||||
{
|
||||
action: 'media',
|
||||
params: { path: 'missing-relative' },
|
||||
},
|
||||
{ baseDir: tmpDir }
|
||||
)
|
||||
).rejects.toThrow('does not exist on this computer');
|
||||
expect(
|
||||
(
|
||||
await prepareControlActionAsync(
|
||||
catalog,
|
||||
{
|
||||
action: 'media',
|
||||
params: { path: localFile },
|
||||
},
|
||||
{ localFileMode: 'explicit' }
|
||||
)
|
||||
).localFile
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
(
|
||||
await prepareControlActionAsync(catalog, {
|
||||
action: 'camera',
|
||||
params: { source: 'webcam', target: 'Built-in Camera' },
|
||||
})
|
||||
).localFile
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it('resolves a direct relative upload against baseDir without rewriting caller parameters', async () => {
|
||||
const params = { path: './fixture.json' };
|
||||
const plan = await prepareControlActionAsync(
|
||||
catalog,
|
||||
{ action: 'media', params },
|
||||
{ baseDir: tmpDir }
|
||||
);
|
||||
expect(plan.localFile?.path).toBe(path.join(tmpDir, 'fixture.json'));
|
||||
await executeControlActionAsync(connection, plan);
|
||||
expect(requestAsync.mock.calls[1]).toEqual([
|
||||
'media',
|
||||
{ path: `/remote/staging/${requestAsync.mock.calls[0][1]?.uploadId}` },
|
||||
]);
|
||||
expect(params).toEqual({ path: './fixture.json' });
|
||||
});
|
||||
|
||||
(process.platform === 'win32' ? it.skip : it)(
|
||||
'rejects a named pipe before opening it for upload',
|
||||
async () => {
|
||||
const file = path.join(tmpDir, 'input.pipe');
|
||||
execFileSync('mkfifo', [file]);
|
||||
await expect(
|
||||
prepareControlActionAsync(catalog, {
|
||||
action: 'install',
|
||||
params: {},
|
||||
file,
|
||||
})
|
||||
).rejects.toThrow('not a regular file');
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
|
||||
(process.platform === 'win32' || process.getuid?.() === 0 ? it.skip : it)(
|
||||
'rejects a local file that cannot be read before upload',
|
||||
async () => {
|
||||
const file = path.join(tmpDir, 'fixture.json');
|
||||
await fs.chmod(file, 0);
|
||||
try {
|
||||
await expect(
|
||||
prepareControlActionAsync(catalog, {
|
||||
action: 'install',
|
||||
params: {},
|
||||
file,
|
||||
})
|
||||
).rejects.toMatchObject({ code: 'EACCES' });
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await fs.chmod(file, 0o600);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
it('substitutes an upload ID without changing the plan and removes staging after success', async () => {
|
||||
const plan = await prepareControlActionAsync(catalog, {
|
||||
action: 'install',
|
||||
params: {},
|
||||
file: path.join(tmpDir, 'fixture.json'),
|
||||
});
|
||||
await executeControlActionAsync(connection, plan);
|
||||
const uploadId = requestAsync.mock.calls[0][1]?.uploadId;
|
||||
expect(uploadId).toMatch(/^eas-cli-[0-9a-f-]{36}\.json$/);
|
||||
expect(requestAsync.mock.calls).toEqual([
|
||||
[
|
||||
'upload.append',
|
||||
{ uploadId, data: Buffer.from('file bytes').toString('base64'), first: true },
|
||||
],
|
||||
['install', { uploadId }],
|
||||
['upload.remove', { uploadId }],
|
||||
]);
|
||||
expect(plan.params).toEqual({});
|
||||
});
|
||||
|
||||
it('keeps a successful camera upload but cleans it after a failed action', async () => {
|
||||
const plan = await prepareControlActionAsync(catalog, {
|
||||
action: 'camera',
|
||||
params: { source: 'file' },
|
||||
file: path.join(tmpDir, 'fixture.json'),
|
||||
});
|
||||
await executeControlActionAsync(connection, plan);
|
||||
expect(requestAsync.mock.calls.map(([name]) => name)).toEqual(['upload.append', 'camera']);
|
||||
expect(requestAsync.mock.calls[1][1]).toEqual({
|
||||
source: 'file',
|
||||
target: `/remote/staging/${requestAsync.mock.calls[0][1]?.uploadId}`,
|
||||
});
|
||||
requestAsync.mockClear();
|
||||
result = { stdout: '', stderr: 'camera unavailable', exitCode: 1 };
|
||||
await expect(executeControlActionAsync(connection, plan)).rejects.toThrow('camera unavailable');
|
||||
expect(requestAsync.mock.calls.map(([name]) => name)).toEqual([
|
||||
'upload.append',
|
||||
'camera',
|
||||
'upload.remove',
|
||||
]);
|
||||
expect(controller.signal.aborted).toBe(false);
|
||||
});
|
||||
|
||||
it('cleans staging if validation rejects real uploaded parameters', async () => {
|
||||
const plan = await prepareControlActionAsync(catalog, {
|
||||
action: 'camera',
|
||||
params: { source: 'file' },
|
||||
file: path.join(tmpDir, 'fixture.json'),
|
||||
});
|
||||
const validateParams = jest.fn(() => {
|
||||
throw new Error('invalid uploaded path');
|
||||
});
|
||||
await expect(executeControlActionAsync(connection, plan, { validateParams })).rejects.toThrow(
|
||||
'invalid uploaded path'
|
||||
);
|
||||
expect(validateParams).toHaveBeenCalledWith({
|
||||
source: 'file',
|
||||
target: `/remote/staging/${requestAsync.mock.calls[0][1]?.uploadId}`,
|
||||
});
|
||||
expect(requestAsync.mock.calls.map(([name]) => name)).toEqual([
|
||||
'upload.append',
|
||||
'upload.remove',
|
||||
]);
|
||||
});
|
||||
|
||||
it('removes a failed upload without running the action', async () => {
|
||||
requestAsync.mockImplementation(async action =>
|
||||
action === 'upload.append' ? { stdout: '', stderr: 'staging full', exitCode: 1 } : ok()
|
||||
);
|
||||
const plan = await prepareControlActionAsync(catalog, {
|
||||
action: 'install',
|
||||
params: {},
|
||||
file: path.join(tmpDir, 'fixture.json'),
|
||||
});
|
||||
await expect(executeControlActionAsync(connection, plan)).rejects.toThrow('staging full');
|
||||
expect(requestAsync.mock.calls.map(([name]) => name)).toEqual([
|
||||
'upload.append',
|
||||
'upload.remove',
|
||||
]);
|
||||
});
|
||||
|
||||
it('saves an action output and returns the path instead of raw bytes', async () => {
|
||||
result = ok(Buffer.from('file content').toString('base64'));
|
||||
const outputPath = path.join(tmpDir, 'output');
|
||||
const plan = await prepareControlActionAsync(catalog, {
|
||||
action: 'download',
|
||||
params: {},
|
||||
outputPath,
|
||||
});
|
||||
await expect(executeControlActionAsync(connection, plan)).resolves.toEqual({
|
||||
output: '',
|
||||
file: outputPath,
|
||||
});
|
||||
expect(await fs.readFile(outputPath, 'utf8')).toBe('file content');
|
||||
});
|
||||
|
||||
it('removes staging if the output directory disappears after preparation', async () => {
|
||||
const outputDir = path.join(tmpDir, 'output');
|
||||
await fs.mkdir(outputDir);
|
||||
const plan = await prepareControlActionAsync(
|
||||
{
|
||||
snapshot: { upload: 'path', output: 'base64' },
|
||||
},
|
||||
{
|
||||
action: 'snapshot',
|
||||
params: {},
|
||||
file: path.join(tmpDir, 'fixture.json'),
|
||||
outputPath: path.join(outputDir, 'snapshot.png'),
|
||||
}
|
||||
);
|
||||
await fs.remove(outputDir);
|
||||
result = ok(Buffer.from('png').toString('base64'));
|
||||
await expect(executeControlActionAsync(connection, plan)).rejects.toMatchObject({
|
||||
code: 'ENOENT',
|
||||
});
|
||||
expect(requestAsync.mock.calls.map(([name]) => name)).toEqual([
|
||||
'upload.append',
|
||||
'snapshot',
|
||||
'upload.remove',
|
||||
]);
|
||||
expect(controller.signal.aborted).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ stdout: 'failure on stdout', stderr: '', exitCode: 1 }, 'failure on stdout'],
|
||||
[{ stdout: '', stderr: '', exitCode: 7 }, 'exit code 7'],
|
||||
])(
|
||||
'reports server failure details without closing a usable connection',
|
||||
async (failure, message) => {
|
||||
result = failure as HostActionResult;
|
||||
const plan = await prepareControlActionAsync(catalog, { action: 'settings', params: {} });
|
||||
await expect(executeControlActionAsync(connection, plan)).rejects.toThrow(message);
|
||||
expect(controller.signal.aborted).toBe(false);
|
||||
}
|
||||
);
|
||||
|
||||
it('does not send work after a terminal connection loss', async () => {
|
||||
const plan = await prepareControlActionAsync(catalog, { action: 'settings', params: {} });
|
||||
const error = new Error('connection lost');
|
||||
controller.abort(error);
|
||||
await expect(executeControlActionAsync(connection, plan)).rejects.toBe(error);
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,428 +0,0 @@
|
||||
import fs from 'fs-extra';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { executeControlConfigAsync, prepareControlConfigAsync } from '../controlConfig';
|
||||
import { HostActionCatalog, HostActionConnection, HostActionResult } from '../hostActions';
|
||||
|
||||
const itWithChmod = process.platform === 'win32' || process.geteuid?.() === 0 ? it.skip : it;
|
||||
|
||||
const catalog: HostActionCatalog = {
|
||||
'keyboard.set': {
|
||||
type: 'object',
|
||||
properties: { udid: { type: 'string' }, value: { enum: ['on', 'off'] } },
|
||||
required: ['udid', 'value'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
'file.push': {
|
||||
type: 'object',
|
||||
properties: {
|
||||
udid: { type: 'string' },
|
||||
uploadId: { type: 'string', pattern: '^[A-Za-z0-9._-]+$' },
|
||||
destination: { type: 'string' },
|
||||
},
|
||||
required: ['udid', 'uploadId', 'destination'],
|
||||
additionalProperties: false,
|
||||
upload: 'uploadId',
|
||||
uploadAs: 'id',
|
||||
},
|
||||
'camera.set': {
|
||||
type: 'object',
|
||||
properties: {
|
||||
udid: { type: 'string' },
|
||||
source: { enum: ['file', 'webcam'] },
|
||||
path: { type: 'string' },
|
||||
},
|
||||
required: ['udid', 'source', 'path'],
|
||||
upload: 'path',
|
||||
uploadWhen: { source: 'file' },
|
||||
keepUpload: true,
|
||||
},
|
||||
screenshot: {
|
||||
type: 'object',
|
||||
properties: { udid: { type: 'string' } },
|
||||
required: ['udid'],
|
||||
additionalProperties: false,
|
||||
output: 'base64',
|
||||
},
|
||||
echo: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
udid: { type: 'string' },
|
||||
text: { type: 'string' },
|
||||
enabled: { type: 'boolean' },
|
||||
count: { type: 'number' },
|
||||
items: { type: 'array', items: { type: 'string' } },
|
||||
},
|
||||
required: ['udid'],
|
||||
additionalProperties: false,
|
||||
},
|
||||
};
|
||||
|
||||
describe('simulator control configuration', () => {
|
||||
let folder: string;
|
||||
let filePath: string;
|
||||
const ok = (stdout = ''): HostActionResult => ({ stdout, stderr: '', exitCode: 0 });
|
||||
const requestAsync = jest.fn(async (action: string): Promise<HostActionResult> => {
|
||||
if (action === 'upload.append') {
|
||||
return ok('/remote/staged.txt\n');
|
||||
}
|
||||
if (action === 'screenshot') {
|
||||
return ok(Buffer.from('png').toString('base64'));
|
||||
}
|
||||
return ok('done\n');
|
||||
});
|
||||
const connection: HostActionConnection = {
|
||||
requestAsync,
|
||||
close: jest.fn(),
|
||||
signal: new AbortController().signal,
|
||||
udid: 'owned-udid',
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
jest.clearAllMocks();
|
||||
folder = await fs.mkdtemp(path.join(os.tmpdir(), 'control-config-'));
|
||||
filePath = path.join(folder, 'simulator.json');
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
await fs.remove(folder);
|
||||
});
|
||||
|
||||
async function writeConfig(actions: unknown[], rest = {}): Promise<void> {
|
||||
await fs.writeJson(filePath, { version: 1, actions, ...rest });
|
||||
}
|
||||
|
||||
it('preserves typed, omitted and empty values without changing the input', async () => {
|
||||
const params = { text: '', enabled: false, count: 0, items: ['first', 'second'] };
|
||||
await writeConfig([{ action: 'echo', params }, { action: 'echo' }]);
|
||||
const config = await prepareControlConfigAsync(catalog, filePath, connection.udid);
|
||||
const results = await executeControlConfigAsync(connection, config);
|
||||
expect(requestAsync.mock.calls).toEqual([
|
||||
['echo', params],
|
||||
['echo', {}],
|
||||
]);
|
||||
expect(results).toEqual([
|
||||
{ action: 'echo', output: 'done', file: null },
|
||||
{ action: 'echo', output: 'done', file: null },
|
||||
]);
|
||||
expect((await fs.readJson(filePath)).actions[0].params).toEqual(params);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ version: 2, actions: [{ action: 'echo' }] },
|
||||
{ version: 1, actions: [] },
|
||||
{ version: 1, actions: [{ action: 'echo', extra: true }] },
|
||||
{ version: 1, actions: [{ action: 'echo', params: [] }] },
|
||||
{ version: 1, actions: [{ action: 'echo', params: { udid: 'other-device' } }] },
|
||||
{ version: 1, actions: [{ action: 'echo' }], sessionId: 'other-session' },
|
||||
])('rejects an invalid config envelope: %j', async input => {
|
||||
await fs.writeJson(filePath, input);
|
||||
await expect(prepareControlConfigAsync(catalog, filePath, connection.udid)).rejects.toThrow();
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('reports invalid JSON with its config path', async () => {
|
||||
await fs.writeFile(filePath, '{ invalid');
|
||||
await expect(prepareControlConfigAsync(catalog, filePath, connection.udid)).rejects.toThrow(
|
||||
'simulator.json'
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects a missing config file', async () => {
|
||||
await expect(prepareControlConfigAsync(catalog, filePath, connection.udid)).rejects.toThrow();
|
||||
});
|
||||
|
||||
it('preflights later steps before running any action or upload', async () => {
|
||||
await fs.writeFile(path.join(folder, 'fixture.txt'), 'content');
|
||||
await writeConfig([
|
||||
{ action: 'file.push', params: { destination: 'data.txt' }, file: './fixture.txt' },
|
||||
{ action: 'keyboard.set', params: { value: 'invalid' } },
|
||||
]);
|
||||
await expect(prepareControlConfigAsync(catalog, filePath, connection.udid)).rejects.toThrow(
|
||||
/step 2.*keyboard\.set/i
|
||||
);
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects unknown actions before any execution', async () => {
|
||||
await writeConfig([{ action: 'echo' }, { action: 'missing' }]);
|
||||
await expect(prepareControlConfigAsync(catalog, filePath, connection.udid)).rejects.toThrow(
|
||||
/step 2.*missing/i
|
||||
);
|
||||
});
|
||||
|
||||
it('requires an explicit output for path downloads before executing earlier steps', async () => {
|
||||
const withDownload: HostActionCatalog = {
|
||||
...catalog,
|
||||
'screenshot.capture': { ...catalog.screenshot, output: 'path' },
|
||||
};
|
||||
await writeConfig([{ action: 'echo' }, { action: 'screenshot.capture' }]);
|
||||
await expect(
|
||||
prepareControlConfigAsync(withDownload, filePath, connection.udid)
|
||||
).rejects.toThrow(/step 2.*screenshot\.capture.*output/i);
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects mistyped parameters rather than coercing JSON', async () => {
|
||||
await writeConfig([{ action: 'echo', params: { count: '12' } }]);
|
||||
await expect(prepareControlConfigAsync(catalog, filePath, connection.udid)).rejects.toThrow(
|
||||
/count/i
|
||||
);
|
||||
});
|
||||
|
||||
it('uses JSON Schema 2020-12 and leaves schema defaults omitted', async () => {
|
||||
const withTuple: HostActionCatalog = {
|
||||
tuple: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
udid: { type: 'string' },
|
||||
value: {
|
||||
type: 'array',
|
||||
prefixItems: [{ type: 'number' }, { type: 'string' }],
|
||||
items: false,
|
||||
},
|
||||
enabled: { type: 'boolean', default: true },
|
||||
},
|
||||
required: ['udid', 'value'],
|
||||
},
|
||||
};
|
||||
await writeConfig([{ action: 'tuple', params: { value: [7, 'text'] } }]);
|
||||
const config = await prepareControlConfigAsync(withTuple, filePath, connection.udid);
|
||||
await executeControlConfigAsync(connection, config);
|
||||
expect(requestAsync).toHaveBeenCalledWith('tuple', { value: [7, 'text'] });
|
||||
await writeConfig([{ action: 'tuple', params: { value: ['wrong', 'text'] } }]);
|
||||
await expect(prepareControlConfigAsync(withTuple, filePath, connection.udid)).rejects.toThrow(
|
||||
/params\/value\/0/
|
||||
);
|
||||
});
|
||||
|
||||
it('refuses to execute a plan checked for another simulator', async () => {
|
||||
await writeConfig([{ action: 'echo' }]);
|
||||
const config = await prepareControlConfigAsync(catalog, filePath, 'another-udid');
|
||||
await expect(executeControlConfigAsync(connection, config)).rejects.toThrow(
|
||||
'simulator changed'
|
||||
);
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('resolves explicit local files relative to the config and substitutes upload IDs', async () => {
|
||||
await fs.writeFile(path.join(folder, 'fixture.txt'), 'content');
|
||||
await writeConfig([
|
||||
{ action: 'file.push', params: { destination: 'data.txt' }, file: './fixture.txt' },
|
||||
]);
|
||||
const config = await prepareControlConfigAsync(catalog, filePath, connection.udid);
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
await executeControlConfigAsync(connection, config);
|
||||
expect(requestAsync).toHaveBeenCalledWith('upload.append', {
|
||||
uploadId: expect.stringMatching(/^eas-cli-.+\.txt$/),
|
||||
data: Buffer.from('content').toString('base64'),
|
||||
first: true,
|
||||
});
|
||||
const call = requestAsync.mock.calls.find(([action]) => action === 'file.push');
|
||||
expect(call).toEqual([
|
||||
'file.push',
|
||||
{ destination: 'data.txt', uploadId: expect.stringMatching(/^eas-cli-.+\.txt$/) },
|
||||
]);
|
||||
expect(requestAsync).toHaveBeenLastCalledWith('upload.remove', {
|
||||
uploadId: expect.stringMatching(/^eas-cli-.+\.txt$/),
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps remote paths unchanged even when a similarly named local file exists', async () => {
|
||||
const localPath = path.join(folder, 'fixture.txt');
|
||||
await fs.writeFile(localPath, 'local content');
|
||||
await writeConfig([{ action: 'camera.set', params: { source: 'file', path: localPath } }]);
|
||||
const config = await prepareControlConfigAsync(catalog, filePath, connection.udid);
|
||||
await executeControlConfigAsync(connection, config);
|
||||
expect(requestAsync.mock.calls).toEqual([['camera.set', { source: 'file', path: localPath }]]);
|
||||
});
|
||||
|
||||
it('resolves output paths relative to the config', async () => {
|
||||
await writeConfig([{ action: 'screenshot', output: './screen.png' }]);
|
||||
const config = await prepareControlConfigAsync(catalog, filePath, connection.udid);
|
||||
const results = await executeControlConfigAsync(connection, config);
|
||||
expect(await fs.readFile(path.join(folder, 'screen.png'), 'utf8')).toBe('png');
|
||||
expect(results[0].file).toBe(path.join(folder, 'screen.png'));
|
||||
});
|
||||
|
||||
itWithChmod.each(['existing file', 'new file', 'download directory'])(
|
||||
'rejects an unwritable %s before running earlier actions',
|
||||
async kind => {
|
||||
const destination = path.join(folder, 'read-only');
|
||||
const output = kind === 'new file' ? path.join(destination, 'screen.png') : destination;
|
||||
if (kind === 'existing file') {
|
||||
await fs.writeFile(destination, 'existing image');
|
||||
await fs.chmod(destination, 0o444);
|
||||
} else {
|
||||
await fs.mkdir(destination);
|
||||
await fs.chmod(destination, 0o555);
|
||||
}
|
||||
const action = kind === 'download directory' ? 'download' : 'screenshot';
|
||||
const withDownload: HostActionCatalog = {
|
||||
...catalog,
|
||||
download: { ...catalog.screenshot, output: 'path' },
|
||||
};
|
||||
try {
|
||||
await writeConfig([{ action: 'echo' }, { action, output }]);
|
||||
await expect(
|
||||
prepareControlConfigAsync(withDownload, filePath, connection.udid)
|
||||
).rejects.toThrow(/step 2.*(EACCES|permission)/i);
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await fs.chmod(destination, 0o755);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
it.each(['app.install', 'media.add'])(
|
||||
'rejects an explicit file combined with another source for %s',
|
||||
async action => {
|
||||
const realCatalog: HostActionCatalog = require('./fixtures/hostActionCatalog.json');
|
||||
await fs.writeFile(path.join(folder, 'new.ipa'), 'new bytes');
|
||||
await writeConfig([{ action, params: { uploadId: 'old.ipa' }, file: './new.ipa' }]);
|
||||
await expect(
|
||||
prepareControlConfigAsync(realCatalog, filePath, connection.udid)
|
||||
).rejects.toThrow(/file.*source/i);
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
|
||||
itWithChmod(
|
||||
'rejects a new output in a write-only parent before running earlier actions',
|
||||
async () => {
|
||||
const destination = path.join(folder, 'write-only');
|
||||
await fs.mkdir(destination);
|
||||
await fs.chmod(destination, 0o222);
|
||||
try {
|
||||
await writeConfig([
|
||||
{ action: 'echo' },
|
||||
{ action: 'screenshot', output: path.join(destination, 'screen.png') },
|
||||
]);
|
||||
await expect(prepareControlConfigAsync(catalog, filePath, connection.udid)).rejects.toThrow(
|
||||
/step 2.*(EACCES|permission)/i
|
||||
);
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await fs.chmod(destination, 0o755);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
it('rejects a denied output permission check before running earlier actions', async () => {
|
||||
await writeConfig([
|
||||
{ action: 'echo' },
|
||||
{ action: 'screenshot', output: path.join(folder, 'screen.png') },
|
||||
]);
|
||||
const access = jest.spyOn(fs, 'access').mockImplementationOnce(async () => {
|
||||
throw Object.assign(new Error('Permission denied'), { code: 'EACCES' });
|
||||
});
|
||||
try {
|
||||
await expect(prepareControlConfigAsync(catalog, filePath, connection.udid)).rejects.toThrow(
|
||||
/step 2.*Permission denied/i
|
||||
);
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
access.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('accepts an explicit file as the only source of a union action', async () => {
|
||||
const realCatalog: HostActionCatalog = require('./fixtures/hostActionCatalog.json');
|
||||
await fs.writeFile(path.join(folder, 'new.ipa'), 'new bytes');
|
||||
await writeConfig([{ action: 'app.install', file: './new.ipa' }]);
|
||||
const config = await prepareControlConfigAsync(realCatalog, filePath, connection.udid);
|
||||
await executeControlConfigAsync(connection, config);
|
||||
expect(requestAsync).toHaveBeenCalledWith('app.install', { path: '/remote/staged.txt' });
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ action: 'echo', file: './fixture.txt' },
|
||||
{ action: 'file.push', params: { destination: 'data.txt' }, file: './missing.txt' },
|
||||
{ action: 'file.push', params: { destination: 'data.txt' }, file: '.' },
|
||||
{ action: 'camera.set', params: { source: 'webcam', path: 'camera' }, file: './fixture.txt' },
|
||||
{
|
||||
action: 'file.push',
|
||||
params: { destination: 'data.txt', uploadId: 'already-staged' },
|
||||
file: './fixture.txt',
|
||||
},
|
||||
{ action: 'screenshot', output: './missing/screen.png' },
|
||||
])('rejects invalid file/output plans before execution: %j', async action => {
|
||||
await fs.writeFile(path.join(folder, 'fixture.txt'), 'content');
|
||||
await writeConfig([action]);
|
||||
await expect(prepareControlConfigAsync(catalog, filePath, connection.udid)).rejects.toThrow();
|
||||
expect(requestAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('stops on the first runtime error and reports completed steps', async () => {
|
||||
await writeConfig([
|
||||
{ action: 'echo', params: { text: 'first' } },
|
||||
{ action: 'keyboard.set', params: { value: 'off' } },
|
||||
{ action: 'echo', params: { text: 'third' } },
|
||||
]);
|
||||
const config = await prepareControlConfigAsync(catalog, filePath, connection.udid);
|
||||
requestAsync.mockResolvedValueOnce(ok('first')).mockResolvedValueOnce({
|
||||
stdout: '',
|
||||
stderr: 'device stopped',
|
||||
exitCode: 1,
|
||||
});
|
||||
const onProgress = jest.fn();
|
||||
await expect(
|
||||
executeControlConfigAsync(connection, config, { onProgress })
|
||||
).rejects.toMatchObject({
|
||||
step: 2,
|
||||
action: 'keyboard.set',
|
||||
completed: [{ action: 'echo', output: 'first', file: null }],
|
||||
});
|
||||
expect(requestAsync.mock.calls).toEqual([
|
||||
['echo', { text: 'first' }],
|
||||
['keyboard.set', { value: 'off' }],
|
||||
]);
|
||||
expect(onProgress.mock.calls.map(([progress]) => progress)).toEqual([
|
||||
{ step: 1, total: 3, action: 'echo', status: 'running' },
|
||||
{
|
||||
step: 1,
|
||||
total: 3,
|
||||
action: 'echo',
|
||||
status: 'completed',
|
||||
result: { action: 'echo', output: 'first', file: null },
|
||||
},
|
||||
{ step: 2, total: 3, action: 'keyboard.set', status: 'running' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('preserves a non-Error failure without retrying the action', async () => {
|
||||
await writeConfig([{ action: 'echo' }]);
|
||||
const config = await prepareControlConfigAsync(catalog, filePath, connection.udid);
|
||||
requestAsync.mockRejectedValueOnce('connection lost');
|
||||
await expect(executeControlConfigAsync(connection, config)).rejects.toMatchObject({
|
||||
step: 1,
|
||||
completed: [],
|
||||
message: expect.stringContaining('connection lost'),
|
||||
});
|
||||
expect(requestAsync).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('validates the actual uploaded value before invoking an action', async () => {
|
||||
const strict: HostActionCatalog = {
|
||||
'file.push': {
|
||||
...catalog['file.push'],
|
||||
uploadAs: 'path',
|
||||
properties: {
|
||||
...catalog['file.push'].properties,
|
||||
uploadId: { type: 'string', pattern: '^/tmp/serve-sim-uploads/' },
|
||||
},
|
||||
},
|
||||
};
|
||||
await fs.writeFile(path.join(folder, 'fixture.txt'), 'content');
|
||||
await writeConfig([
|
||||
{ action: 'file.push', params: { destination: 'data.txt' }, file: './fixture.txt' },
|
||||
]);
|
||||
const config = await prepareControlConfigAsync(strict, filePath, connection.udid);
|
||||
await expect(executeControlConfigAsync(connection, config)).rejects.toThrow(/uploadId/);
|
||||
expect(requestAsync.mock.calls.map(([name]) => name)).toEqual([
|
||||
'upload.append',
|
||||
'upload.remove',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,441 +0,0 @@
|
||||
import { PassThrough } from 'node:stream';
|
||||
|
||||
import Log from '../../log';
|
||||
import { promptControlActionAsync, runControlMenuAsync } from '../controlInteractive';
|
||||
import { ControlPromptCancelledError, promptControlValueAsync } from '../controlPrompts';
|
||||
import { HostActionCatalog } from '../hostActions';
|
||||
|
||||
jest.mock('../controlPrompts', () => ({
|
||||
...jest.requireActual('../controlPrompts'),
|
||||
promptControlValueAsync: jest.fn(),
|
||||
}));
|
||||
jest.mock('../../log');
|
||||
jest.unmock('prompts');
|
||||
|
||||
const prompt = jest.mocked(promptControlValueAsync);
|
||||
const catalog: HostActionCatalog = require('./fixtures/hostActionCatalog.json');
|
||||
const signal = new AbortController().signal;
|
||||
|
||||
function useTerminalPrompts(): { enterAsync(value: string): Promise<void>; output(): string } {
|
||||
const input = Object.assign(new PassThrough(), { isTTY: true, setRawMode: jest.fn() });
|
||||
const output = Object.assign(new PassThrough(), { columns: 80 });
|
||||
let text = '';
|
||||
output.on('data', chunk => {
|
||||
text += String(chunk);
|
||||
});
|
||||
const actual = jest.requireActual<typeof import('../controlPrompts')>('../controlPrompts');
|
||||
prompt.mockImplementation(
|
||||
async (question, signal) =>
|
||||
await actual.promptControlValueAsync({ ...question, stdin: input, stdout: output }, signal)
|
||||
);
|
||||
return {
|
||||
async enterAsync(value) {
|
||||
input.write(`\u0007${value}\r`);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
},
|
||||
output: () => text,
|
||||
};
|
||||
}
|
||||
|
||||
describe('catalog-driven control prompts', () => {
|
||||
beforeEach(() => jest.resetAllMocks());
|
||||
|
||||
it('asks for enum values without hardcoding the action name', async () => {
|
||||
prompt.mockResolvedValueOnce('off');
|
||||
await expect(
|
||||
promptControlActionAsync('future.toggle', catalog['hardwareKeyboard.set'], signal)
|
||||
).resolves.toEqual({ action: 'future.toggle', params: { value: 'off' } });
|
||||
expect(prompt.mock.calls[0][0]).toMatchObject({
|
||||
type: 'select',
|
||||
choices: [
|
||||
{ title: 'on', value: 'on' },
|
||||
{ title: 'off', value: 'off' },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it('uses the exposed path branch instead of asking for an upload ID', async () => {
|
||||
prompt.mockResolvedValueOnce('./My App.ipa');
|
||||
await expect(
|
||||
promptControlActionAsync('app.install', catalog['app.install'], signal)
|
||||
).resolves.toEqual({ action: 'app.install', params: { path: './My App.ipa' } });
|
||||
expect(prompt).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('selects a discriminator branch and omits other branch fields', async () => {
|
||||
prompt.mockResolvedValueOnce('placeholder');
|
||||
await expect(
|
||||
promptControlActionAsync('camera.switch', catalog['camera.switch'], signal)
|
||||
).resolves.toEqual({ action: 'camera.switch', params: { source: 'placeholder' } });
|
||||
expect(prompt).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('leaves optional values omitted and preserves explicitly empty strings', async () => {
|
||||
const entry = {
|
||||
type: 'object',
|
||||
properties: { text: { type: 'string', default: 'server default' } },
|
||||
};
|
||||
prompt.mockResolvedValueOnce(false);
|
||||
await expect(promptControlActionAsync('clipboard.paste', entry, signal)).resolves.toEqual({
|
||||
action: 'clipboard.paste',
|
||||
params: {},
|
||||
});
|
||||
prompt.mockResolvedValueOnce(true).mockResolvedValueOnce('');
|
||||
await expect(promptControlActionAsync('clipboard.paste', entry, signal)).resolves.toEqual({
|
||||
action: 'clipboard.paste',
|
||||
params: { text: '' },
|
||||
});
|
||||
});
|
||||
|
||||
it('reads array values as JSON and prompts for file output before execution', async () => {
|
||||
const entry = {
|
||||
type: 'object',
|
||||
properties: { events: { type: 'array', items: { type: 'object' } } },
|
||||
required: ['events'],
|
||||
output: 'base64' as const,
|
||||
};
|
||||
prompt.mockResolvedValueOnce('[{"type":"begin"}]').mockResolvedValueOnce('./output.png');
|
||||
await expect(promptControlActionAsync('future.gesture', entry, signal)).resolves.toEqual({
|
||||
action: 'future.gesture',
|
||||
params: { events: [{ type: 'begin' }] },
|
||||
outputPath: './output.png',
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back to a JSON object when branches cannot be selected safely', async () => {
|
||||
const entry = {
|
||||
anyOf: [
|
||||
{ properties: { a: { type: 'string' } }, required: ['a'] },
|
||||
{ properties: { b: { type: 'string' } }, required: ['b'] },
|
||||
],
|
||||
};
|
||||
prompt.mockResolvedValueOnce('{"b":"value"}');
|
||||
await expect(promptControlActionAsync('future.union', entry, signal)).resolves.toEqual({
|
||||
action: 'future.union',
|
||||
params: { b: 'value' },
|
||||
});
|
||||
expect(prompt.mock.calls[0][0].message).toContain('JSON');
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ anyOf: [{ type: 'boolean' }, { type: 'null' }] }, 'false', false],
|
||||
[{ anyOf: [{ type: 'boolean' }, { type: 'null' }] }, 'null', null],
|
||||
[{ anyOf: [{ type: 'string' }, { type: 'object' }] }, '"hello"', 'hello'],
|
||||
])('accepts JSON values for mixed property unions %#', async (schema, input, expected) => {
|
||||
prompt.mockResolvedValueOnce(input);
|
||||
await expect(
|
||||
promptControlActionAsync(
|
||||
'future.union',
|
||||
{ type: 'object', properties: { value: schema }, required: ['value'] },
|
||||
signal
|
||||
)
|
||||
).resolves.toEqual({ action: 'future.union', params: { value: expected } });
|
||||
});
|
||||
|
||||
it('combines required fields from allOf and keeps optional defaults on the server', async () => {
|
||||
const entry = {
|
||||
type: 'object',
|
||||
properties: { precision: { type: 'integer', default: 4 } },
|
||||
allOf: [
|
||||
{ type: 'object', properties: { lat: { type: 'number' } }, required: ['lat'] },
|
||||
{ type: 'object', properties: { lng: { type: 'number' } }, required: ['lng'] },
|
||||
],
|
||||
args: ['lat', 'lng'],
|
||||
};
|
||||
prompt.mockResolvedValueOnce('37.5').mockResolvedValueOnce('-122').mockResolvedValueOnce(false);
|
||||
await expect(promptControlActionAsync('future.location', entry, signal)).resolves.toEqual({
|
||||
action: 'future.location',
|
||||
params: { lat: 37.5, lng: -122 },
|
||||
});
|
||||
expect(prompt.mock.calls[2][0]).toMatchObject({
|
||||
message: 'Set optional precision (default: 4)?',
|
||||
initial: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('uses a boolean toggle and supplies required constants without another question', async () => {
|
||||
const entry = {
|
||||
type: 'object',
|
||||
properties: { enabled: { type: 'boolean' }, mode: { const: 'fixed' } },
|
||||
required: ['enabled', 'mode'],
|
||||
};
|
||||
prompt.mockResolvedValueOnce(false);
|
||||
await expect(promptControlActionAsync('future.enabled', entry, signal)).resolves.toEqual({
|
||||
action: 'future.enabled',
|
||||
params: { enabled: false, mode: 'fixed' },
|
||||
});
|
||||
expect(prompt).toHaveBeenCalledTimes(1);
|
||||
expect(prompt.mock.calls[0][0]).toMatchObject({
|
||||
type: 'toggle',
|
||||
active: 'true',
|
||||
inactive: 'false',
|
||||
});
|
||||
});
|
||||
|
||||
it('accepts either a named pose or numeric angle for the existing scalar union', async () => {
|
||||
prompt.mockResolvedValueOnce('half').mockResolvedValueOnce('90');
|
||||
await expect(
|
||||
promptControlActionAsync('hinge.set', catalog['hinge.set'], signal)
|
||||
).resolves.toEqual({ action: 'hinge.set', params: { value: 'half' } });
|
||||
await expect(
|
||||
promptControlActionAsync('hinge.set', catalog['hinge.set'], signal)
|
||||
).resolves.toEqual({ action: 'hinge.set', params: { value: 90 } });
|
||||
});
|
||||
|
||||
it('uses a JSON object for nested alternatives it cannot guide safely', async () => {
|
||||
const entry = {
|
||||
allOf: [
|
||||
{ type: 'object', properties: { common: { type: 'string' } }, required: ['common'] },
|
||||
{
|
||||
anyOf: [
|
||||
{ properties: { file: { type: 'string' } } },
|
||||
{ properties: { url: { type: 'string' } } },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
prompt.mockResolvedValueOnce('{"common":"test","file":"./file.txt"}');
|
||||
await expect(promptControlActionAsync('future.nested', entry, signal)).resolves.toEqual({
|
||||
action: 'future.nested',
|
||||
params: { common: 'test', file: './file.txt' },
|
||||
});
|
||||
expect(prompt).toHaveBeenCalledTimes(1);
|
||||
expect(prompt.mock.calls[0][0].message).toContain('JSON object');
|
||||
});
|
||||
|
||||
it('does not guess between branches that share the same discriminator value', async () => {
|
||||
const entry = {
|
||||
oneOf: [
|
||||
{ properties: { source: { const: 'file' }, path: { type: 'string' } } },
|
||||
{ properties: { source: { const: 'file' }, uploadId: { type: 'string' } } },
|
||||
],
|
||||
};
|
||||
prompt.mockResolvedValueOnce('{"source":"file","path":"./test"}');
|
||||
await expect(
|
||||
promptControlActionAsync('future.ambiguous', entry, signal)
|
||||
).resolves.toMatchObject({ params: { source: 'file', path: './test' } });
|
||||
expect(prompt.mock.calls[0][0].message).toContain('JSON object');
|
||||
});
|
||||
|
||||
it('keeps an invalid number in the real prompt until the user corrects it', async () => {
|
||||
const terminal = useTerminalPrompts();
|
||||
const result = promptControlActionAsync('location.set', catalog['location.set'], signal);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
await terminal.enterAsync('not a number');
|
||||
expect(terminal.output()).toContain('Enter a valid number.');
|
||||
await terminal.enterAsync('37.5');
|
||||
await terminal.enterAsync('-122');
|
||||
await expect(result).resolves.toEqual({
|
||||
action: 'location.set',
|
||||
params: { lat: 37.5, lng: -122 },
|
||||
});
|
||||
});
|
||||
|
||||
it('requires valid JSON with the right container type before accepting a complex field', async () => {
|
||||
const terminal = useTerminalPrompts();
|
||||
const entry = {
|
||||
type: 'object',
|
||||
properties: { events: { type: 'array' } },
|
||||
required: ['events'],
|
||||
};
|
||||
const result = promptControlActionAsync('future.gesture', entry, signal);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
await terminal.enterAsync('[broken');
|
||||
await terminal.enterAsync('{}');
|
||||
expect(terminal.output()).toContain('Enter a JSON value matching this parameter.');
|
||||
await terminal.enterAsync('[{"type":"begin"}]');
|
||||
await expect(result).resolves.toMatchObject({ params: { events: [{ type: 'begin' }] } });
|
||||
});
|
||||
|
||||
it('rejects malformed and non-object fallback JSON before accepting corrected parameters', async () => {
|
||||
const terminal = useTerminalPrompts();
|
||||
const entry = {
|
||||
anyOf: [{ properties: { a: { type: 'string' } } }, { properties: { b: { type: 'string' } } }],
|
||||
};
|
||||
const result = promptControlActionAsync('future.fallback', entry, signal);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
await terminal.enterAsync('invalid');
|
||||
await terminal.enterAsync('[]');
|
||||
expect(terminal.output()).toContain('Enter a JSON object.');
|
||||
await terminal.enterAsync('{"b":"corrected"}');
|
||||
await expect(result).resolves.toMatchObject({ params: { b: 'corrected' } });
|
||||
});
|
||||
|
||||
it('requires an output destination before returning a file action', async () => {
|
||||
const terminal = useTerminalPrompts();
|
||||
const result = promptControlActionAsync(
|
||||
'future.screenshot',
|
||||
{ type: 'object', output: 'base64' },
|
||||
signal
|
||||
);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
await terminal.enterAsync(' ');
|
||||
expect(terminal.output()).toContain('Enter a local output path.');
|
||||
await terminal.enterAsync('./image.png');
|
||||
await expect(result).resolves.toEqual({
|
||||
action: 'future.screenshot',
|
||||
params: {},
|
||||
outputPath: './image.png',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('interactive control loop', () => {
|
||||
beforeEach(() => jest.resetAllMocks());
|
||||
|
||||
it('searches friendly labels, action names and descriptions without losing catalog entries', async () => {
|
||||
prompt.mockResolvedValueOnce({ kind: 'exit' });
|
||||
await runControlMenuAsync({
|
||||
catalog: {
|
||||
'hardwareKeyboard.set': { description: 'Connect the physical keyboard' },
|
||||
'future.newAction': { description: 'A newly discovered capability' },
|
||||
},
|
||||
signal,
|
||||
runActionAsync: jest.fn(),
|
||||
});
|
||||
const question = prompt.mock.calls[0][0];
|
||||
const suggest = question.suggest as (
|
||||
input: string,
|
||||
choices: unknown[]
|
||||
) => Promise<{ value: unknown }[]>;
|
||||
expect((await suggest('HARDWARE keyboard', [])).map(choice => choice.value)).toEqual([
|
||||
{ kind: 'action', name: 'hardwareKeyboard.set' },
|
||||
]);
|
||||
expect((await suggest('future.newAction', [])).map(choice => choice.value)).toEqual([
|
||||
{ kind: 'action', name: 'future.newAction' },
|
||||
]);
|
||||
expect((await suggest('newly discovered', [])).map(choice => choice.value)).toEqual([
|
||||
{ kind: 'action', name: 'future.newAction' },
|
||||
]);
|
||||
expect(await suggest('no match', [])).toEqual([]);
|
||||
expect(await suggest('', [])).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('runs one selection at a time and returns to the picker until Exit', async () => {
|
||||
const runActionAsync = jest.fn().mockResolvedValue(undefined);
|
||||
prompt
|
||||
.mockResolvedValueOnce({ kind: 'action', name: 'hardwareKeyboard.set' })
|
||||
.mockResolvedValueOnce('on')
|
||||
.mockResolvedValueOnce({ kind: 'action', name: 'hardwareKeyboard.set' })
|
||||
.mockResolvedValueOnce('off')
|
||||
.mockResolvedValueOnce({ kind: 'exit' });
|
||||
await runControlMenuAsync({ catalog, signal, runActionAsync });
|
||||
expect(runActionAsync.mock.calls).toEqual([
|
||||
[{ action: 'hardwareKeyboard.set', params: { value: 'on' } }],
|
||||
[{ action: 'hardwareKeyboard.set', params: { value: 'off' } }],
|
||||
]);
|
||||
});
|
||||
|
||||
it('returns to the picker after a normal action error without replay', async () => {
|
||||
const runActionAsync = jest.fn().mockRejectedValue(new Error('Permission denied'));
|
||||
prompt
|
||||
.mockResolvedValueOnce({ kind: 'action', name: 'future.action' })
|
||||
.mockResolvedValueOnce({ kind: 'exit' });
|
||||
await runControlMenuAsync({
|
||||
catalog: { 'future.action': { type: 'object' } },
|
||||
signal,
|
||||
runActionAsync,
|
||||
});
|
||||
expect(runActionAsync).toHaveBeenCalledTimes(1);
|
||||
expect(Log.error).toHaveBeenCalledWith('Permission denied');
|
||||
});
|
||||
|
||||
it('does not open another picker while an action is running', async () => {
|
||||
let complete!: () => void;
|
||||
const runActionAsync = jest.fn(
|
||||
() =>
|
||||
new Promise<void>(resolve => {
|
||||
complete = resolve;
|
||||
})
|
||||
);
|
||||
prompt
|
||||
.mockResolvedValueOnce({ kind: 'action', name: 'future.action' })
|
||||
.mockResolvedValueOnce({ kind: 'exit' });
|
||||
const running = runControlMenuAsync({
|
||||
catalog: { 'future.action': { type: 'object' } },
|
||||
signal,
|
||||
runActionAsync,
|
||||
});
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(runActionAsync).toHaveBeenCalledTimes(1);
|
||||
expect(prompt).toHaveBeenCalledTimes(1);
|
||||
complete();
|
||||
await running;
|
||||
expect(prompt).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('stops after ambiguous transport loss and never opens the next picker', async () => {
|
||||
const controller = new AbortController();
|
||||
const error = new Error('The action may still have run');
|
||||
const runActionAsync = jest.fn(async () => {
|
||||
controller.abort(error);
|
||||
throw error;
|
||||
});
|
||||
prompt.mockResolvedValueOnce({ kind: 'action', name: 'future.action' });
|
||||
await expect(
|
||||
runControlMenuAsync({
|
||||
catalog: { 'future.action': { type: 'object' } },
|
||||
signal: controller.signal,
|
||||
runActionAsync,
|
||||
})
|
||||
).rejects.toBe(error);
|
||||
expect(prompt).toHaveBeenCalledTimes(1);
|
||||
expect(runActionAsync).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('unwinds a user cancellation', async () => {
|
||||
prompt.mockRejectedValueOnce(new ControlPromptCancelledError());
|
||||
await expect(
|
||||
runControlMenuAsync({ catalog, signal, runActionAsync: jest.fn() })
|
||||
).rejects.toBeInstanceOf(ControlPromptCancelledError);
|
||||
});
|
||||
|
||||
it('keeps the menu open when autocomplete has no matching selection', async () => {
|
||||
const runActionAsync = jest.fn();
|
||||
prompt.mockResolvedValueOnce(undefined).mockResolvedValueOnce({ kind: 'exit' });
|
||||
await expect(runControlMenuAsync({ catalog, signal, runActionAsync })).resolves.toBeUndefined();
|
||||
expect(runActionAsync).not.toHaveBeenCalled();
|
||||
expect(prompt).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it('runs a different action after an ordinary rejection', async () => {
|
||||
const runActionAsync = jest
|
||||
.fn()
|
||||
.mockRejectedValueOnce(new Error('Permission denied'))
|
||||
.mockResolvedValueOnce(undefined);
|
||||
prompt
|
||||
.mockResolvedValueOnce({ kind: 'action', name: 'first' })
|
||||
.mockResolvedValueOnce({ kind: 'action', name: 'second' })
|
||||
.mockResolvedValueOnce({ kind: 'exit' });
|
||||
await runControlMenuAsync({
|
||||
catalog: { first: { type: 'object' }, second: { type: 'object' } },
|
||||
signal,
|
||||
runActionAsync,
|
||||
});
|
||||
expect(runActionAsync.mock.calls).toEqual([
|
||||
[{ action: 'first', params: {} }],
|
||||
[{ action: 'second', params: {} }],
|
||||
]);
|
||||
expect(Log.error).toHaveBeenCalledWith('Permission denied');
|
||||
});
|
||||
|
||||
it('does not send an action when Ctrl-C cancels its parameter prompt', async () => {
|
||||
const runActionAsync = jest.fn();
|
||||
prompt
|
||||
.mockResolvedValueOnce({ kind: 'action', name: 'hardwareKeyboard.set' })
|
||||
.mockRejectedValueOnce(new ControlPromptCancelledError());
|
||||
await expect(runControlMenuAsync({ catalog, signal, runActionAsync })).rejects.toBeInstanceOf(
|
||||
ControlPromptCancelledError
|
||||
);
|
||||
expect(runActionAsync).not.toHaveBeenCalled();
|
||||
expect(Log.error).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not open any prompt if initialization already lost the session', async () => {
|
||||
const error = new Error('Already disconnected');
|
||||
await expect(
|
||||
runControlMenuAsync({ catalog, signal: AbortSignal.abort(error), runActionAsync: jest.fn() })
|
||||
).rejects.toBe(error);
|
||||
expect(prompt).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,89 +0,0 @@
|
||||
import { PassThrough } from 'node:stream';
|
||||
|
||||
import { ControlPromptCancelledError, promptControlValueAsync } from '../controlPrompts';
|
||||
|
||||
jest.unmock('prompts');
|
||||
|
||||
function terminal(): {
|
||||
input: PassThrough & { isTTY: boolean; setRawMode: jest.Mock };
|
||||
output: PassThrough & { columns: number };
|
||||
} {
|
||||
const input = Object.assign(new PassThrough(), { isTTY: true, setRawMode: jest.fn() });
|
||||
const output = Object.assign(new PassThrough(), { columns: 80 });
|
||||
output.resume();
|
||||
return { input, output };
|
||||
}
|
||||
|
||||
describe('abortable simulator control prompts', () => {
|
||||
it('aborts the real idle prompt and restores the terminal', async () => {
|
||||
const { input, output } = terminal();
|
||||
const controller = new AbortController();
|
||||
const reason = new Error('Connection lost');
|
||||
const result = promptControlValueAsync(
|
||||
{ type: 'text', message: 'Value', stdin: input, stdout: output },
|
||||
controller.signal
|
||||
);
|
||||
controller.abort(reason);
|
||||
await expect(result).rejects.toBe(reason);
|
||||
expect(input.setRawMode.mock.calls).toEqual([[true], [false]]);
|
||||
expect(input.listenerCount('keypress')).toBe(0);
|
||||
});
|
||||
|
||||
it('handles cancellation during the first constructor render', async () => {
|
||||
const { input, output } = terminal();
|
||||
const controller = new AbortController();
|
||||
const reason = new Error('Session ended');
|
||||
await expect(
|
||||
promptControlValueAsync(
|
||||
{
|
||||
type: 'select',
|
||||
message: 'Action',
|
||||
choices: [{ title: 'Exit', value: null }],
|
||||
stdin: input,
|
||||
stdout: output,
|
||||
onRender() {
|
||||
controller.abort(reason);
|
||||
},
|
||||
},
|
||||
controller.signal
|
||||
)
|
||||
).rejects.toBe(reason);
|
||||
expect(input.listenerCount('keypress')).toBe(0);
|
||||
expect(input.setRawMode).toHaveBeenLastCalledWith(false);
|
||||
});
|
||||
|
||||
it('never opens a prompt for an already lost connection', async () => {
|
||||
const { input, output } = terminal();
|
||||
const signal = AbortSignal.abort(new Error('Already closed'));
|
||||
await expect(
|
||||
promptControlValueAsync(
|
||||
{ type: 'text', message: 'Value', stdin: input, stdout: output },
|
||||
signal
|
||||
)
|
||||
).rejects.toThrow('Already closed');
|
||||
expect(input.setRawMode).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('unwinds Ctrl-C instead of exiting the process', async () => {
|
||||
const { input, output } = terminal();
|
||||
const result = promptControlValueAsync(
|
||||
{ type: 'text', message: 'Value', stdin: input, stdout: output },
|
||||
new AbortController().signal
|
||||
);
|
||||
input.write('\u0003');
|
||||
await expect(result).rejects.toBeInstanceOf(ControlPromptCancelledError);
|
||||
expect(input.listenerCount('keypress')).toBe(0);
|
||||
expect(input.setRawMode).toHaveBeenLastCalledWith(false);
|
||||
});
|
||||
|
||||
it('preserves an explicitly empty string', async () => {
|
||||
const { input, output } = terminal();
|
||||
const result = promptControlValueAsync(
|
||||
{ type: 'text', message: 'Value', stdin: input, stdout: output },
|
||||
new AbortController().signal
|
||||
);
|
||||
input.write('\r');
|
||||
await expect(result).resolves.toBe('');
|
||||
expect(input.listenerCount('keypress')).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -1,453 +0,0 @@
|
||||
import { createClient, fetchExchange } from '@urql/core';
|
||||
import { getEventListeners } from 'node:events';
|
||||
|
||||
import { DeviceRunSessionStatus, JobRunStatus } from '../../graphql/generated';
|
||||
import { DeviceRunSessionQuery } from '../../graphql/queries/DeviceRunSessionQuery';
|
||||
import Log from '../../log';
|
||||
import { ControlSessionEndedError, watchControlSession } from '../controlSession';
|
||||
|
||||
type SessionStatus = {
|
||||
status: DeviceRunSessionStatus;
|
||||
turtleJobRun?: { id: string; status: JobRunStatus } | null;
|
||||
};
|
||||
|
||||
type StatusSource = ReturnType<typeof DeviceRunSessionQuery.byId>;
|
||||
type StatusObserver = Parameters<StatusSource['subscribe']>[0];
|
||||
type StatusResult = Parameters<StatusObserver>[0];
|
||||
|
||||
type StatusRequest = {
|
||||
signal: AbortSignal;
|
||||
respond: (body: unknown) => void;
|
||||
fail: (error: Error) => void;
|
||||
};
|
||||
|
||||
function createStatusClient(): {
|
||||
client: ReturnType<typeof createClient>;
|
||||
fetch: jest.Mock<
|
||||
Promise<Response>,
|
||||
[url: Parameters<typeof globalThis.fetch>[0], options?: RequestInit]
|
||||
>;
|
||||
requests: StatusRequest[];
|
||||
activeRequests(): number;
|
||||
} {
|
||||
const requests: StatusRequest[] = [];
|
||||
let activeRequests = 0;
|
||||
const fetch = jest.fn((_url: Parameters<typeof globalThis.fetch>[0], options?: RequestInit) => {
|
||||
const signal = options!.signal!;
|
||||
activeRequests++;
|
||||
return new Promise<Response>((resolve, reject) => {
|
||||
let finished = false;
|
||||
const finish = (): boolean => {
|
||||
if (finished) {
|
||||
return false;
|
||||
}
|
||||
finished = true;
|
||||
activeRequests--;
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
return true;
|
||||
};
|
||||
const onAbort = (): void => {
|
||||
if (finish()) {
|
||||
reject(new Error('Request aborted'));
|
||||
}
|
||||
};
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
requests.push({
|
||||
signal,
|
||||
respond: body => {
|
||||
if (finish()) {
|
||||
resolve(
|
||||
new Response(JSON.stringify(body), {
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
);
|
||||
}
|
||||
},
|
||||
fail: error => {
|
||||
if (finish()) {
|
||||
reject(error);
|
||||
}
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
const client = createClient({
|
||||
url: 'https://example.test/graphql',
|
||||
exchanges: [fetchExchange],
|
||||
fetch,
|
||||
fetchOptions: () => ({ headers: { authorization: 'Bearer session-token' } }),
|
||||
});
|
||||
return { client, fetch, requests, activeRequests: () => activeRequests };
|
||||
}
|
||||
|
||||
function sessionResponse(status: SessionStatus): unknown {
|
||||
return { data: { deviceRunSessions: { byId: { id: 'session-id', ...status } } } };
|
||||
}
|
||||
|
||||
describe(watchControlSession, () => {
|
||||
const disposers: (() => void)[] = [];
|
||||
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers();
|
||||
jest.spyOn(Log, 'debug').mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const dispose of disposers.splice(0)) {
|
||||
dispose();
|
||||
}
|
||||
jest.clearAllTimers();
|
||||
jest.useRealTimers();
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
function watch(
|
||||
client: ReturnType<typeof createStatusClient>['client'],
|
||||
options: Parameters<typeof watchControlSession>[2] = {
|
||||
signal: new AbortController().signal,
|
||||
}
|
||||
): ReturnType<typeof watchControlSession> {
|
||||
const watcher = watchControlSession(client, 'session-id', options);
|
||||
disposers.push(watcher.dispose);
|
||||
return watcher;
|
||||
}
|
||||
|
||||
it('polls serially after each completed request and preserves authentication', async () => {
|
||||
const observed = createStatusClient();
|
||||
const query = jest.spyOn(observed.client, 'query');
|
||||
watch(observed.client);
|
||||
|
||||
await jest.advanceTimersByTimeAsync(4999);
|
||||
expect(observed.fetch).not.toHaveBeenCalled();
|
||||
await jest.advanceTimersByTimeAsync(1);
|
||||
expect(observed.fetch).toHaveBeenCalledTimes(1);
|
||||
expect(query).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
{ deviceRunSessionId: 'session-id' },
|
||||
{ requestPolicy: 'network-only', noRetry: true }
|
||||
);
|
||||
expect(observed.fetch.mock.calls[0][1]?.headers).toEqual(
|
||||
expect.objectContaining({ authorization: 'Bearer session-token' })
|
||||
);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
expect(observed.fetch).toHaveBeenCalledTimes(1);
|
||||
expect(observed.activeRequests()).toBe(1);
|
||||
|
||||
observed.requests[0].respond(sessionResponse({ status: DeviceRunSessionStatus.InProgress }));
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
await jest.advanceTimersByTimeAsync(4999);
|
||||
expect(observed.fetch).toHaveBeenCalledTimes(1);
|
||||
await jest.advanceTimersByTimeAsync(1);
|
||||
expect(observed.fetch).toHaveBeenCalledTimes(2);
|
||||
expect(observed.activeRequests()).toBe(1);
|
||||
});
|
||||
|
||||
it.each([DeviceRunSessionStatus.Stopped, DeviceRunSessionStatus.Errored])(
|
||||
'ends control when an idle session becomes %s',
|
||||
async status => {
|
||||
const observed = createStatusClient();
|
||||
const watcher = watch(observed.client);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
observed.requests[0].respond(sessionResponse({ status }));
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
|
||||
expect(watcher.signal.aborted).toBe(true);
|
||||
expect(watcher.signal.reason).toBeInstanceOf(ControlSessionEndedError);
|
||||
expect(watcher.signal.reason.message).toContain('session-id');
|
||||
expect(watcher.signal.reason.failed).toBe(status === DeviceRunSessionStatus.Errored);
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
await jest.advanceTimersByTimeAsync(60_000);
|
||||
expect(observed.fetch).toHaveBeenCalledTimes(1);
|
||||
}
|
||||
);
|
||||
|
||||
it.each([JobRunStatus.Canceled, JobRunStatus.Finished, JobRunStatus.Errored])(
|
||||
'ends control when the worker job becomes %s before the session status catches up',
|
||||
async status => {
|
||||
const observed = createStatusClient();
|
||||
const watcher = watch(observed.client);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
observed.requests[0].respond(
|
||||
sessionResponse({
|
||||
status: DeviceRunSessionStatus.InProgress,
|
||||
turtleJobRun: { id: 'job-id', status },
|
||||
})
|
||||
);
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
|
||||
expect(watcher.signal.reason).toBeInstanceOf(ControlSessionEndedError);
|
||||
expect(watcher.signal.reason.failed).toBe(status === JobRunStatus.Errored);
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
}
|
||||
);
|
||||
|
||||
it('keeps watching a session without a job and a job whose cancellation is pending', async () => {
|
||||
const observed = createStatusClient();
|
||||
const watcher = watch(observed.client);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
observed.requests[0].respond(
|
||||
sessionResponse({ status: DeviceRunSessionStatus.InProgress, turtleJobRun: null })
|
||||
);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
observed.requests[1].respond(
|
||||
sessionResponse({
|
||||
status: DeviceRunSessionStatus.InProgress,
|
||||
turtleJobRun: { id: 'job-id', status: JobRunStatus.PendingCancel },
|
||||
})
|
||||
);
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
|
||||
expect(watcher.signal.aborted).toBe(false);
|
||||
expect(jest.getTimerCount()).toBe(1);
|
||||
});
|
||||
|
||||
it('logs network and GraphQL failures, then retries without ending control', async () => {
|
||||
const observed = createStatusClient();
|
||||
const watcher = watch(observed.client);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
observed.requests[0].fail(new Error('Connection reset'));
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
observed.requests[1].respond({ errors: [{ message: 'Temporarily unavailable' }] });
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
|
||||
expect(watcher.signal.aborted).toBe(false);
|
||||
expect(Log.debug).toHaveBeenCalledTimes(2);
|
||||
expect(observed.activeRequests()).toBe(1);
|
||||
observed.requests[2].respond(sessionResponse({ status: DeviceRunSessionStatus.Stopped }));
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect(watcher.signal.reason).toBeInstanceOf(ControlSessionEndedError);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ data: {} },
|
||||
{ data: { deviceRunSessions: null } },
|
||||
{ data: { deviceRunSessions: { byId: null } } },
|
||||
])('retries an empty session response %j without treating it as ended', async body => {
|
||||
const observed = createStatusClient();
|
||||
const watcher = watch(observed.client);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
observed.requests[0].respond(body);
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
|
||||
expect(watcher.signal.aborted).toBe(false);
|
||||
expect(Log.debug).toHaveBeenCalledWith(
|
||||
expect.stringContaining('session-id'),
|
||||
expect.objectContaining({ message: 'Session status response was empty.' })
|
||||
);
|
||||
expect(jest.getTimerCount()).toBe(1);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
expect(observed.fetch).toHaveBeenCalledTimes(2);
|
||||
observed.requests[1].respond(sessionResponse({ status: DeviceRunSessionStatus.Stopped }));
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect(watcher.signal.reason).toBeInstanceOf(ControlSessionEndedError);
|
||||
});
|
||||
|
||||
it('waits for a successful response when GraphQL returns partial terminal data with an error', async () => {
|
||||
const observed = createStatusClient();
|
||||
const watcher = watch(observed.client);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
observed.requests[0].respond({
|
||||
...(sessionResponse({ status: DeviceRunSessionStatus.Stopped }) as object),
|
||||
errors: [{ message: 'Status temporarily unavailable', extensions: { isTransient: true } }],
|
||||
});
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
|
||||
expect(watcher.signal.aborted).toBe(false);
|
||||
expect(Log.debug).toHaveBeenCalledTimes(1);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
observed.requests[1].respond(sessionResponse({ status: DeviceRunSessionStatus.InProgress }));
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect(watcher.signal.aborted).toBe(false);
|
||||
expect(jest.getTimerCount()).toBe(1);
|
||||
});
|
||||
|
||||
it('ignores stale and incomplete terminal results until the source confirms a final result', async () => {
|
||||
const observed = createStatusClient();
|
||||
const unsubscribe = jest.fn();
|
||||
let emit: StatusObserver | undefined;
|
||||
const subscribe = jest.fn((next: StatusObserver) => {
|
||||
emit = next;
|
||||
return { unsubscribe };
|
||||
});
|
||||
jest
|
||||
.spyOn(DeviceRunSessionQuery, 'byId')
|
||||
.mockReturnValue({ subscribe } as unknown as StatusSource);
|
||||
const watcher = watch(observed.client);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
const terminal = sessionResponse({ status: DeviceRunSessionStatus.Stopped }) as StatusResult;
|
||||
emit!({ ...terminal, stale: true, hasNext: false });
|
||||
emit!({ ...terminal, stale: false, hasNext: true });
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
|
||||
expect(watcher.signal.aborted).toBe(false);
|
||||
expect(subscribe).toHaveBeenCalledTimes(1);
|
||||
expect(unsubscribe).not.toHaveBeenCalled();
|
||||
expect(jest.getTimerCount()).toBe(1);
|
||||
emit!({ ...terminal, stale: false, hasNext: false });
|
||||
expect(watcher.signal.reason).toBeInstanceOf(ControlSessionEndedError);
|
||||
expect(unsubscribe).toHaveBeenCalledTimes(1);
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
expect(Log.debug).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([DeviceRunSessionStatus.InProgress, DeviceRunSessionStatus.Stopped])(
|
||||
'unsubscribes a synchronously emitted %s response after subscribe returns its handle',
|
||||
async status => {
|
||||
const observed = createStatusClient();
|
||||
const unsubscribe = jest.fn();
|
||||
const subscribe = jest.fn((next: StatusObserver) => {
|
||||
next({ ...(sessionResponse({ status }) as StatusResult), stale: false, hasNext: false });
|
||||
return { unsubscribe };
|
||||
});
|
||||
jest
|
||||
.spyOn(DeviceRunSessionQuery, 'byId')
|
||||
.mockReturnValue({ subscribe } as unknown as StatusSource);
|
||||
const controller = new AbortController();
|
||||
const watcher = watch(observed.client, { signal: controller.signal });
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
|
||||
expect(unsubscribe).toHaveBeenCalledTimes(1);
|
||||
expect(watcher.signal.aborted).toBe(status === DeviceRunSessionStatus.Stopped);
|
||||
expect(jest.getTimerCount()).toBe(status === DeviceRunSessionStatus.Stopped ? 0 : 1);
|
||||
watcher.dispose();
|
||||
expect(unsubscribe).toHaveBeenCalledTimes(1);
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
expect(getEventListeners(controller.signal, 'abort')).toHaveLength(0);
|
||||
expect(observed.fetch).not.toHaveBeenCalled();
|
||||
}
|
||||
);
|
||||
|
||||
it('recovers from a synchronous query setup failure without leaving its deadline running', async () => {
|
||||
const observed = createStatusClient();
|
||||
const failure = new Error('Could not initialize status request');
|
||||
jest.spyOn(DeviceRunSessionQuery, 'byId').mockImplementationOnce(() => {
|
||||
throw failure;
|
||||
});
|
||||
const watcher = watch(observed.client);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
|
||||
expect(watcher.signal.aborted).toBe(false);
|
||||
expect(Log.debug).toHaveBeenCalledWith(expect.stringContaining('session-id'), failure);
|
||||
expect(jest.getTimerCount()).toBe(1);
|
||||
expect(observed.fetch).not.toHaveBeenCalled();
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
expect(observed.fetch).toHaveBeenCalledTimes(1);
|
||||
observed.requests[0].respond(sessionResponse({ status: DeviceRunSessionStatus.InProgress }));
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect(jest.getTimerCount()).toBe(1);
|
||||
});
|
||||
|
||||
it('unsubscribes and aborts the fetch at the request deadline before retrying', async () => {
|
||||
const observed = createStatusClient();
|
||||
const watcher = watch(observed.client, {
|
||||
signal: new AbortController().signal,
|
||||
pollIntervalMs: 100,
|
||||
requestTimeoutMs: 200,
|
||||
});
|
||||
await jest.advanceTimersByTimeAsync(100);
|
||||
expect(observed.activeRequests()).toBe(1);
|
||||
await jest.advanceTimersByTimeAsync(199);
|
||||
expect(observed.requests[0].signal.aborted).toBe(false);
|
||||
await jest.advanceTimersByTimeAsync(1);
|
||||
|
||||
expect(observed.requests[0].signal.aborted).toBe(true);
|
||||
expect(observed.activeRequests()).toBe(0);
|
||||
expect(watcher.signal.aborted).toBe(false);
|
||||
expect(Log.debug).toHaveBeenCalledTimes(1);
|
||||
await jest.advanceTimersByTimeAsync(100);
|
||||
expect(observed.fetch).toHaveBeenCalledTimes(2);
|
||||
expect(observed.activeRequests()).toBe(1);
|
||||
});
|
||||
|
||||
it('disposes an in-flight fetch and all timers without sending a stop mutation', async () => {
|
||||
const observed = createStatusClient();
|
||||
const mutation = jest.spyOn(observed.client, 'mutation');
|
||||
const watcher = watch(observed.client);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
watcher.dispose();
|
||||
watcher.dispose();
|
||||
|
||||
expect(observed.requests[0].signal.aborted).toBe(true);
|
||||
expect(observed.activeRequests()).toBe(0);
|
||||
expect(watcher.signal.aborted).toBe(true);
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
await jest.advanceTimersByTimeAsync(60_000);
|
||||
expect(observed.fetch).toHaveBeenCalledTimes(1);
|
||||
expect(mutation).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('propagates parent cancellation and tears down an in-flight request', async () => {
|
||||
const observed = createStatusClient();
|
||||
const controller = new AbortController();
|
||||
const watcher = watch(observed.client, { signal: controller.signal });
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
const reason = new Error('Control connection lost');
|
||||
controller.abort(reason);
|
||||
|
||||
expect(watcher.signal.reason).toBe(reason);
|
||||
expect(observed.requests[0].signal.aborted).toBe(true);
|
||||
expect(observed.activeRequests()).toBe(0);
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
expect(Log.debug).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('clears an idle poll and never polls an already canceled parent', async () => {
|
||||
const observed = createStatusClient();
|
||||
const controller = new AbortController();
|
||||
const watcher = watch(observed.client, { signal: controller.signal });
|
||||
controller.abort();
|
||||
expect(watcher.signal.reason).toBe(controller.signal.reason);
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
const alreadyCanceled = watch(observed.client, { signal: controller.signal });
|
||||
expect(alreadyCanceled.signal.reason).toBe(controller.signal.reason);
|
||||
expect(getEventListeners(controller.signal, 'abort')).toHaveLength(0);
|
||||
await jest.advanceTimersByTimeAsync(60_000);
|
||||
expect(observed.fetch).not.toHaveBeenCalled();
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it('disposes an idle retry and removes its parent listener before the next poll', async () => {
|
||||
const observed = createStatusClient();
|
||||
const controller = new AbortController();
|
||||
const watcher = watch(observed.client, { signal: controller.signal });
|
||||
expect(getEventListeners(controller.signal, 'abort')).toHaveLength(1);
|
||||
await jest.advanceTimersByTimeAsync(5000);
|
||||
observed.requests[0].fail(new Error('Connection reset'));
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
expect(jest.getTimerCount()).toBe(1);
|
||||
watcher.dispose();
|
||||
|
||||
expect(watcher.signal.aborted).toBe(true);
|
||||
expect(getEventListeners(controller.signal, 'abort')).toHaveLength(0);
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
await jest.advanceTimersByTimeAsync(60_000);
|
||||
expect(observed.fetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('preserves the existing byIdAsync result and default query context', async () => {
|
||||
const observed = createStatusClient();
|
||||
const query = jest.spyOn(observed.client, 'query');
|
||||
const result = DeviceRunSessionQuery.byIdAsync(observed.client, 'session-id');
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
observed.requests[0].respond(sessionResponse({ status: DeviceRunSessionStatus.InProgress }));
|
||||
|
||||
await expect(result).resolves.toEqual({
|
||||
id: 'session-id',
|
||||
status: DeviceRunSessionStatus.InProgress,
|
||||
});
|
||||
expect(query).toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
{ deviceRunSessionId: 'session-id' },
|
||||
{ requestPolicy: 'network-only' }
|
||||
);
|
||||
});
|
||||
|
||||
it('preserves byIdAsync rejection for a GraphQL error', async () => {
|
||||
const observed = createStatusClient();
|
||||
const result = DeviceRunSessionQuery.byIdAsync(observed.client, 'session-id');
|
||||
const rejected = expect(result).rejects.toThrow('Permission denied');
|
||||
await jest.advanceTimersByTimeAsync(0);
|
||||
observed.requests[0].respond({ errors: [{ message: 'Permission denied' }] });
|
||||
await rejected;
|
||||
});
|
||||
});
|
||||
@@ -1,11 +1,11 @@
|
||||
import * as fs from 'fs-extra';
|
||||
import { getEventListeners, once } from 'node:events';
|
||||
import { once } from 'node:events';
|
||||
import http from 'node:http';
|
||||
import { AddressInfo } from 'node:net';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { Duplex } from 'node:stream';
|
||||
import WebSocket, { WebSocketServer } from 'ws';
|
||||
import { WebSocketServer } from 'ws';
|
||||
|
||||
import * as fetchModule from '../../fetch';
|
||||
import {
|
||||
@@ -15,7 +15,6 @@ import {
|
||||
buildHostActionParams,
|
||||
connectHostActionsAsync,
|
||||
fetchHostActionCatalogAsync,
|
||||
fetchHostActionDeviceAsync,
|
||||
formatHostActionUsage,
|
||||
saveHostActionOutputAsync,
|
||||
uploadFileAsync,
|
||||
@@ -174,108 +173,6 @@ describe(formatHostActionUsage, () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe(fetchHostActionDeviceAsync, () => {
|
||||
afterEach(() => jest.restoreAllMocks());
|
||||
|
||||
it('selects the connected device from the authenticated metadata catalog', async () => {
|
||||
const fetch = jest.spyOn(fetchModule, 'default').mockResolvedValueOnce(
|
||||
new fetchModule.Response(
|
||||
JSON.stringify({
|
||||
devices: [
|
||||
{ device: 'other-device', name: 'Other Simulator' },
|
||||
{ device: UDID, name: 'iPhone 17 Pro', runtime: 'iOS-26-4' },
|
||||
],
|
||||
})
|
||||
)
|
||||
);
|
||||
await expect(
|
||||
fetchHostActionDeviceAsync(
|
||||
{ apiUrl: 'https://sim.example.test/preview/', token: TOKEN },
|
||||
UDID
|
||||
)
|
||||
).resolves.toEqual({
|
||||
udid: UDID,
|
||||
name: 'iPhone 17 Pro',
|
||||
runtime: 'iOS-26-4',
|
||||
});
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
'https://sim.example.test/preview/grid/api/catalog',
|
||||
expect.objectContaining({
|
||||
headers: { Authorization: `Bearer ${TOKEN}` },
|
||||
redirect: 'error',
|
||||
signal: expect.any(AbortSignal),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it.each([
|
||||
new Error('Metadata request failed'),
|
||||
new fetchModule.RequestError(
|
||||
'Request failed: 404 (Not Found)',
|
||||
new fetchModule.Response(undefined, { status: 404 })
|
||||
),
|
||||
Object.assign(new Error('Request timed out'), { name: 'AbortError' }),
|
||||
])('keeps the connected device ID when metadata fails: %s', async error => {
|
||||
jest.spyOn(fetchModule, 'default').mockRejectedValueOnce(error);
|
||||
await expect(
|
||||
fetchHostActionDeviceAsync({ apiUrl: 'https://sim.example.test', token: TOKEN }, UDID)
|
||||
).resolves.toEqual({ udid: UDID });
|
||||
});
|
||||
|
||||
it.each(['not JSON', JSON.stringify({ devices: null })])(
|
||||
'keeps the connected device ID when metadata is invalid: %s',
|
||||
async body => {
|
||||
jest.spyOn(fetchModule, 'default').mockResolvedValueOnce(new fetchModule.Response(body));
|
||||
await expect(
|
||||
fetchHostActionDeviceAsync({ apiUrl: 'https://sim.example.test', token: TOKEN }, UDID)
|
||||
).resolves.toEqual({ udid: UDID });
|
||||
}
|
||||
);
|
||||
|
||||
it('rejects insecure metadata URLs before sending the session token', async () => {
|
||||
const fetch = jest.spyOn(fetchModule, 'default');
|
||||
await expect(
|
||||
fetchHostActionDeviceAsync({ apiUrl: 'http://sim.example.test', token: TOKEN }, UDID)
|
||||
).rejects.toThrow('Simulator actions require HTTPS');
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('allows a device catalog to take more than three seconds during cold startup', async () => {
|
||||
let responseTimer: NodeJS.Timeout | undefined;
|
||||
const server = http.createServer((_request, response) => {
|
||||
responseTimer = setTimeout(() => {
|
||||
response.end(JSON.stringify({ devices: [{ device: UDID, name: 'iPhone 17 Pro' }] }));
|
||||
}, 3500);
|
||||
});
|
||||
server.listen(0, '127.0.0.1');
|
||||
await once(server, 'listening');
|
||||
const { port } = server.address() as AddressInfo;
|
||||
try {
|
||||
await expect(
|
||||
fetchHostActionDeviceAsync({ apiUrl: `http://127.0.0.1:${port}`, token: TOKEN }, UDID)
|
||||
).resolves.toEqual({ udid: UDID, name: 'iPhone 17 Pro' });
|
||||
} finally {
|
||||
clearTimeout(responseTimer);
|
||||
server.closeAllConnections();
|
||||
server.close();
|
||||
await once(server, 'close');
|
||||
}
|
||||
});
|
||||
|
||||
it('does not borrow metadata from another device', async () => {
|
||||
jest
|
||||
.spyOn(fetchModule, 'default')
|
||||
.mockResolvedValueOnce(
|
||||
new fetchModule.Response(
|
||||
JSON.stringify({ devices: [{ device: 'other-device', name: 'Other Simulator' }] })
|
||||
)
|
||||
);
|
||||
await expect(
|
||||
fetchHostActionDeviceAsync({ apiUrl: 'https://sim.example.test', token: TOKEN }, UDID)
|
||||
).resolves.toEqual({ udid: UDID });
|
||||
});
|
||||
});
|
||||
|
||||
describe('host action transport policy', () => {
|
||||
afterEach(() => jest.restoreAllMocks());
|
||||
|
||||
@@ -326,7 +223,6 @@ describe('host action connection', () => {
|
||||
let received: { id: number; action: string; params: Record<string, unknown> }[];
|
||||
let requests: (string | undefined)[];
|
||||
let apiBody: string;
|
||||
let apiStatus: number;
|
||||
let uploads: Map<string, Buffer>;
|
||||
let reply: (message: {
|
||||
id: number;
|
||||
@@ -336,8 +232,6 @@ describe('host action connection', () => {
|
||||
let tmpDir: string;
|
||||
let connection: HostActionConnection | undefined;
|
||||
let closeBeforeReady: boolean;
|
||||
let sendReady: boolean;
|
||||
let refuseUpgrade: boolean;
|
||||
|
||||
function serveSim(message: {
|
||||
id: number;
|
||||
@@ -372,16 +266,13 @@ describe('host action connection', () => {
|
||||
requests = [];
|
||||
uploads = new Map();
|
||||
apiBody = JSON.stringify({ device: UDID });
|
||||
apiStatus = 200;
|
||||
reply = serveSim;
|
||||
closeBeforeReady = false;
|
||||
sendReady = true;
|
||||
refuseUpgrade = false;
|
||||
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'host-actions-'));
|
||||
server = http.createServer((req, res) => {
|
||||
requests.push(req.url);
|
||||
if (req.url === '/api' && req.headers.authorization === `Bearer ${TOKEN}`) {
|
||||
res.writeHead(apiStatus, { 'Content-Type': 'application/json' });
|
||||
res.writeHead(200, { 'Content-Type': 'application/json' });
|
||||
res.end(apiBody);
|
||||
return;
|
||||
}
|
||||
@@ -391,7 +282,6 @@ describe('host action connection', () => {
|
||||
wss = new WebSocketServer({
|
||||
server,
|
||||
path: '/exec-ws',
|
||||
verifyClient: () => !refuseUpgrade,
|
||||
handleProtocols: offered =>
|
||||
offered.has(`serve-sim.token.${TOKEN}`) ? `serve-sim.token.${TOKEN}` : false,
|
||||
});
|
||||
@@ -400,9 +290,7 @@ describe('host action connection', () => {
|
||||
ws.close();
|
||||
return;
|
||||
}
|
||||
if (sendReady) {
|
||||
ws.send(JSON.stringify({ ready: true }));
|
||||
}
|
||||
ws.send(JSON.stringify({ ready: true }));
|
||||
ws.on('message', data => {
|
||||
const message = JSON.parse(data.toString());
|
||||
received.push(message);
|
||||
@@ -417,51 +305,6 @@ describe('host action connection', () => {
|
||||
apiUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
||||
});
|
||||
|
||||
it('does not open a connection when already canceled', async () => {
|
||||
const controller = new AbortController();
|
||||
const reason = new Error('canceled before setup');
|
||||
controller.abort(reason);
|
||||
await expect(
|
||||
connectHostActionsAsync({ apiUrl, token: TOKEN }, { signal: controller.signal })
|
||||
).rejects.toBe(reason);
|
||||
expect(requests).toEqual([]);
|
||||
});
|
||||
|
||||
it('cancels an upgrade waiting for readiness and releases the abort listener', async () => {
|
||||
sendReady = false;
|
||||
const controller = new AbortController();
|
||||
const accepted = once(wss, 'connection');
|
||||
const pending = connectHostActionsAsync(
|
||||
{ apiUrl, token: TOKEN },
|
||||
{ signal: controller.signal }
|
||||
);
|
||||
const [socket] = await accepted;
|
||||
const closed = once(socket, 'close');
|
||||
const reason = new Error('canceled during setup');
|
||||
const rejected = expect(pending).rejects.toBe(reason);
|
||||
controller.abort(reason);
|
||||
await rejected;
|
||||
await closed;
|
||||
expect(getEventListeners(controller.signal, 'abort')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('cancels a pending action on an established connection', async () => {
|
||||
const controller = new AbortController();
|
||||
connection = await connectHostActionsAsync(
|
||||
{ apiUrl, token: TOKEN },
|
||||
{ signal: controller.signal }
|
||||
);
|
||||
reply = () => null;
|
||||
const receivedRequest = once([...wss.clients][0], 'message');
|
||||
const pending = connection.requestAsync('appearance.get');
|
||||
const reason = new Error('canceled during action');
|
||||
const rejected = expect(pending).rejects.toBe(reason);
|
||||
await receivedRequest;
|
||||
controller.abort(reason);
|
||||
await rejected;
|
||||
expect(connection.signal.aborted).toBe(true);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
connection?.close();
|
||||
connection = undefined;
|
||||
@@ -481,8 +324,6 @@ describe('host action connection', () => {
|
||||
|
||||
it('sends several requests over one connection with the simulator udid', async () => {
|
||||
const hostActions = await connectAsync();
|
||||
expect(hostActions.udid).toBe(UDID);
|
||||
expect(hostActions.signal.aborted).toBe(false);
|
||||
|
||||
const results = await Promise.all([
|
||||
hostActions.requestAsync('hardwareKeyboard.get'),
|
||||
@@ -546,69 +387,6 @@ describe('host action connection', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('makes a timeout terminal, rejects every pending request and never sends another', async () => {
|
||||
reply = () => null;
|
||||
const hostActions = await connectAsync(50);
|
||||
const requests = [
|
||||
hostActions.requestAsync('memoryWarning'),
|
||||
hostActions.requestAsync('hardwareKeyboard.get'),
|
||||
];
|
||||
const results = await Promise.allSettled(requests);
|
||||
|
||||
expect(hostActions.signal.aborted).toBe(true);
|
||||
expect(results).toEqual([
|
||||
{ status: 'rejected', reason: hostActions.signal.reason },
|
||||
{ status: 'rejected', reason: hostActions.signal.reason },
|
||||
]);
|
||||
await expect(hostActions.requestAsync('memoryWarning')).rejects.toBe(hostActions.signal.reason);
|
||||
expect(received).toHaveLength(2);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect([...wss.clients].every(client => client.readyState !== 1)).toBe(true);
|
||||
});
|
||||
|
||||
it('aborts when the server closes an idle connection', async () => {
|
||||
const hostActions = await connectAsync();
|
||||
const aborted = once(hostActions.signal, 'abort');
|
||||
for (const client of wss.clients) {
|
||||
client.terminate();
|
||||
}
|
||||
await aborted;
|
||||
|
||||
await expect(hostActions.requestAsync('memoryWarning')).rejects.toBe(hostActions.signal.reason);
|
||||
expect(received).toEqual([]);
|
||||
});
|
||||
|
||||
it('aborts and immediately rejects pending work when its owner closes it', async () => {
|
||||
reply = () => null;
|
||||
const hostActions = await connectAsync();
|
||||
const request = hostActions.requestAsync('memoryWarning');
|
||||
const rejected = expect(request).rejects.toThrow('closed');
|
||||
hostActions.close();
|
||||
expect(hostActions.signal.aborted).toBe(true);
|
||||
await rejected;
|
||||
});
|
||||
|
||||
it('makes a transport write failure terminal without retrying the request', async () => {
|
||||
const hostActions = await connectAsync();
|
||||
const failure = new Error('socket write failed');
|
||||
const send = jest
|
||||
.spyOn(WebSocket.prototype, 'send')
|
||||
.mockImplementation((_data, callback: unknown) => {
|
||||
if (typeof callback === 'function') {
|
||||
callback(failure);
|
||||
}
|
||||
});
|
||||
try {
|
||||
await expect(hostActions.requestAsync('memoryWarning')).rejects.toBe(failure);
|
||||
expect(hostActions.signal.aborted).toBe(true);
|
||||
await expect(hostActions.requestAsync('memoryWarning')).rejects.toBe(failure);
|
||||
expect(send).toHaveBeenCalledTimes(1);
|
||||
expect(received).toEqual([]);
|
||||
} finally {
|
||||
send.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps a path on the API URL and drops its query', async () => {
|
||||
await expect(
|
||||
connectHostActionsAsync({ apiUrl: `${apiUrl}/preview?token=${TOKEN}`, token: TOKEN })
|
||||
@@ -623,29 +401,6 @@ describe('host action connection', () => {
|
||||
expect(wss.clients.size).toBe(0);
|
||||
});
|
||||
|
||||
it('explains an unavailable preview server instead of a raw HTTP 404', async () => {
|
||||
apiStatus = 404;
|
||||
await expect(connectHostActionsAsync({ apiUrl, token: TOKEN })).rejects.toThrow(
|
||||
'The simulator preview server is unavailable. The session may have ended or expired.'
|
||||
);
|
||||
expect(requests).toEqual(['/api']);
|
||||
expect(wss.clients.size).toBe(0);
|
||||
});
|
||||
|
||||
it('cleans up a WebSocket upgrade refused after the API accepted its token', async () => {
|
||||
refuseUpgrade = true;
|
||||
const upgraded = once(server, 'upgrade');
|
||||
const rejected = expect(connectHostActionsAsync({ apiUrl, token: TOKEN })).rejects.toThrow(
|
||||
'refused the connection (HTTP 401)'
|
||||
);
|
||||
const [, socket] = await upgraded;
|
||||
const closed = once(socket, 'close');
|
||||
await rejected;
|
||||
await closed;
|
||||
expect(wss.clients.size).toBe(0);
|
||||
expect(requests).toEqual(['/api']);
|
||||
});
|
||||
|
||||
it('does not send the session token to an API redirect target', async () => {
|
||||
server.removeAllListeners('request');
|
||||
server.on('request', (req, res) => {
|
||||
@@ -668,30 +423,11 @@ describe('host action connection', () => {
|
||||
closeBeforeReady = true;
|
||||
|
||||
await expect(connectHostActionsAsync({ apiUrl, token: TOKEN })).rejects.toThrow(
|
||||
'closed the connection during setup'
|
||||
/closed the connection during setup.*token.*eas simulator:get/
|
||||
);
|
||||
});
|
||||
|
||||
it('terminates its owned socket when setup never becomes ready', async () => {
|
||||
sendReady = false;
|
||||
jest.useFakeTimers({ doNotFake: ['nextTick', 'setImmediate'] });
|
||||
try {
|
||||
const connected = once(wss, 'connection');
|
||||
const rejected = expect(connectHostActionsAsync({ apiUrl, token: TOKEN })).rejects.toThrow(
|
||||
'did not accept the connection within 30 seconds'
|
||||
);
|
||||
const [client] = await connected;
|
||||
const closed = once(client, 'close');
|
||||
jest.advanceTimersByTime(30_000);
|
||||
await rejected;
|
||||
await closed;
|
||||
expect(wss.clients.size).toBe(0);
|
||||
} finally {
|
||||
jest.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([401, 403, 404])(
|
||||
it.each([401, 403])(
|
||||
'closes a refused HTTP %i upgrade without waiting for its body',
|
||||
async status => {
|
||||
let rejectedSocket: Duplex | undefined;
|
||||
@@ -710,9 +446,7 @@ describe('host action connection', () => {
|
||||
|
||||
try {
|
||||
await expect(connectHostActionsAsync({ apiUrl, token: TOKEN })).rejects.toThrow(
|
||||
status === 404
|
||||
? 'The simulator preview server is unavailable. The session may have ended or expired.'
|
||||
: `refused the connection (HTTP ${status})`
|
||||
`refused the connection (HTTP ${status})`
|
||||
);
|
||||
await Promise.race([
|
||||
closed,
|
||||
|
||||
@@ -1,208 +0,0 @@
|
||||
import { Parser } from '@oclif/core';
|
||||
import fs from 'fs-extra';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import Simulator from '../../commands/simulator';
|
||||
import { prepareControlConfigAsync } from '../controlConfig';
|
||||
import { resolveStartConfigAsync } from '../startConfig';
|
||||
|
||||
describe('simulator start configuration', () => {
|
||||
let folder: string;
|
||||
let file: string;
|
||||
beforeEach(async () => {
|
||||
folder = await fs.mkdtemp(path.join(os.tmpdir(), 'simulator-start-config-'));
|
||||
file = path.join(folder, 'simulator.json');
|
||||
});
|
||||
afterEach(async () => fs.remove(folder));
|
||||
|
||||
async function resolve(
|
||||
start: object,
|
||||
argv: string[] = [],
|
||||
actions?: object[]
|
||||
): Promise<
|
||||
Awaited<ReturnType<typeof resolveStartConfigAsync>> & {
|
||||
parsed: Awaited<ReturnType<typeof Parser.parse>>;
|
||||
}
|
||||
> {
|
||||
await fs.writeJson(file, { version: 1, start, ...(actions ? { actions } : {}) });
|
||||
const resolved = await resolveStartConfigAsync(['--import', file, ...argv], Simulator.flags);
|
||||
return { ...resolved, parsed: await Parser.parse(resolved.argv, { flags: Simulator.flags }) };
|
||||
}
|
||||
|
||||
it('uses saved values rather than command defaults and preserves explicit CLI overrides', async () => {
|
||||
const { parsed } = await resolve(
|
||||
{
|
||||
platform: 'ios',
|
||||
type: 'web-preview-only',
|
||||
force: false,
|
||||
device: 'Saved phone',
|
||||
tag: ['saved'],
|
||||
'public-link': true,
|
||||
},
|
||||
['--device', 'CLI phone', '--tag', 'one', '--tag', 'two', '--json']
|
||||
);
|
||||
expect(parsed.flags).toMatchObject({
|
||||
platform: 'ios',
|
||||
type: 'web-preview-only',
|
||||
force: false,
|
||||
device: 'CLI phone',
|
||||
tag: ['one', 'two'],
|
||||
'public-link': true,
|
||||
json: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('lets explicit CLI defaults override different saved values', async () => {
|
||||
const { parsed } = await resolve({ type: 'web-preview-only', force: false }, [
|
||||
'--type',
|
||||
'agent-device',
|
||||
'--force',
|
||||
]);
|
||||
expect(parsed.flags.type).toBe('agent-device');
|
||||
expect(parsed.flags.force).toBe(true);
|
||||
});
|
||||
|
||||
it('lets the CLI disable saved public links and network capture with its saved fields', async () => {
|
||||
const { parsed } = await resolve(
|
||||
{ 'public-link': true, 'network-capture': true, 'network-capture-field': ['header'] },
|
||||
['--no-public-link', '--no-network-capture']
|
||||
);
|
||||
expect(parsed.flags['public-link']).toBe(false);
|
||||
expect(parsed.flags['network-capture']).toBe(false);
|
||||
expect(parsed.flags['network-capture-field']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('validates dependencies after merging and replaces array flags instead of appending', async () => {
|
||||
const { parsed } = await resolve(
|
||||
{ 'network-capture': true, 'network-capture-field': ['header'] },
|
||||
['--network-capture-field', 'request-body']
|
||||
);
|
||||
expect(parsed.flags['network-capture-field']).toEqual(['request-body']);
|
||||
});
|
||||
|
||||
it('lets an explicit app source replace a saved exclusive source and its Expo Go SDK', async () => {
|
||||
const expoGo = await resolve({ 'build-id': 'saved-build' }, ['--expo-go']);
|
||||
expect(expoGo.parsed.flags['expo-go']).toBe(true);
|
||||
expect(expoGo.parsed.flags['build-id']).toBeUndefined();
|
||||
const build = await resolve({ 'expo-go': true, 'sdk-version': '55.0.0' }, [
|
||||
'--build-id',
|
||||
'cli-build',
|
||||
]);
|
||||
expect(build.parsed.flags['build-id']).toBe('cli-build');
|
||||
expect(build.parsed.flags['expo-go']).toBeUndefined();
|
||||
expect(build.parsed.flags['sdk-version']).toBeUndefined();
|
||||
await expect(resolve({}, ['--build-id', 'cli-build', '--expo-go'])).rejects.toThrow(
|
||||
'cannot also be provided'
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects an empty import path instead of silently creating a default session', async () => {
|
||||
await expect(resolveStartConfigAsync(['--import='], Simulator.flags)).rejects.toThrow(
|
||||
'non-empty configuration file path'
|
||||
);
|
||||
});
|
||||
|
||||
it('honors short flags and negated CLI booleans', async () => {
|
||||
const { parsed } = await resolve({ platform: 'android', force: true }, [
|
||||
'-p',
|
||||
'ios',
|
||||
'--no-force',
|
||||
]);
|
||||
expect(parsed.flags.platform).toBe('ios');
|
||||
expect(parsed.flags.force).toBe(false);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ start: { unknown: 'x' }, message: 'Unknown or invocation-only' },
|
||||
{ start: { json: true }, message: 'invocation-only' },
|
||||
{ start: { 'non-interactive': true }, message: 'invocation-only' },
|
||||
{ start: { import: 'nested.json' }, message: 'invocation-only' },
|
||||
{ start: { 'expo-go': 'yes' }, message: 'must be a boolean' },
|
||||
{ start: { device: ['one', 'two'] }, message: 'multiple values' },
|
||||
{ start: { device: { name: 'phone' } }, message: 'string or number' },
|
||||
{ start: { platform: 'windows' }, message: 'ios' },
|
||||
{ start: { 'max-duration-minutes': -1 }, message: 'greater than or equal to 0' },
|
||||
{ start: { 'build-id': 'abc', 'expo-go': true }, message: 'cannot also be provided' },
|
||||
])('rejects invalid start values: $start', async ({ start, message }) => {
|
||||
await expect(resolve(start)).rejects.toThrow(message);
|
||||
});
|
||||
|
||||
it('rejects a missing local input before creating a session', async () => {
|
||||
await expect(
|
||||
resolve({ platform: 'ios' }, [], [{ action: 'app.install', file: './missing.ipa' }])
|
||||
).rejects.toThrow('does not exist on this computer');
|
||||
});
|
||||
|
||||
it('rejects invalid output parents and device overrides during local preflight', async () => {
|
||||
await expect(
|
||||
resolve({}, [], [{ action: 'screenshot.capture', output: './missing/shot.png' }])
|
||||
).rejects.toThrow('Config step 1');
|
||||
await expect(
|
||||
resolve({}, [], [{ action: 'appearance.get', params: { udid: 'other-device' } }])
|
||||
).rejects.toThrow('remove params.udid');
|
||||
});
|
||||
|
||||
it.each(['./missing/', './file.txt/'])(
|
||||
'rejects an output directory that does not exist: %s',
|
||||
async output => {
|
||||
await fs.writeFile(path.join(folder, 'file.txt'), 'existing file');
|
||||
await expect(resolve({}, [], [{ action: 'screenshot.capture', output }])).rejects.toThrow(
|
||||
'must be an existing directory'
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
it.each(['./screenshots/', './screen.png'])(
|
||||
'accepts an existing output directory or a new file: %s',
|
||||
async output => {
|
||||
await fs.mkdir(path.join(folder, 'screenshots'));
|
||||
await expect(
|
||||
resolve({}, [], [{ action: 'screenshot.capture', output }])
|
||||
).resolves.toBeDefined();
|
||||
}
|
||||
);
|
||||
|
||||
it('allows the same file in control import and resolves files relative to it', async () => {
|
||||
await fs.writeFile(path.join(folder, 'input.txt'), 'contents');
|
||||
const { config } = await resolve(
|
||||
{ platform: 'ios' },
|
||||
[],
|
||||
[{ action: 'upload', file: './input.txt' }]
|
||||
);
|
||||
const prepared = await prepareControlConfigAsync(
|
||||
{
|
||||
upload: {
|
||||
type: 'object',
|
||||
properties: { udid: { type: 'string' }, path: { type: 'string' } },
|
||||
required: ['udid', 'path'],
|
||||
upload: 'path',
|
||||
},
|
||||
},
|
||||
file,
|
||||
'device'
|
||||
);
|
||||
expect(prepared.actions[0].plan.localFile?.path).toBe(path.join(folder, 'input.txt'));
|
||||
expect(config?.actions?.[0].params).toEqual({});
|
||||
});
|
||||
|
||||
it('reports an unreadable file before trying to create a session', async () => {
|
||||
await expect(resolveStartConfigAsync(['--import', file], Simulator.flags)).rejects.toThrow(
|
||||
`Could not read simulator configuration ${file}`
|
||||
);
|
||||
});
|
||||
|
||||
it('preserves no-import argv and reports malformed or unknown config fields', async () => {
|
||||
expect(await resolveStartConfigAsync(['--platform', 'ios'], Simulator.flags)).toEqual({
|
||||
argv: ['--platform', 'ios'],
|
||||
});
|
||||
await fs.writeJson(file, { version: 2, start: {} });
|
||||
await expect(resolveStartConfigAsync(['--import', file], Simulator.flags)).rejects.toThrow(
|
||||
'Invalid simulator configuration'
|
||||
);
|
||||
await fs.writeJson(file, { version: 1, typo: {} });
|
||||
await expect(resolveStartConfigAsync(['--import', file], Simulator.flags)).rejects.toThrow(
|
||||
'Invalid simulator configuration'
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,124 +0,0 @@
|
||||
import fs from 'fs-extra';
|
||||
import { once } from 'node:events';
|
||||
import http from 'node:http';
|
||||
import { AddressInfo } from 'node:net';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { WebSocketServer } from 'ws';
|
||||
|
||||
import { readSimulatorSessionConfigAsync } from '../sessionConfig';
|
||||
import { applyStartConfigAsync } from '../startSetup';
|
||||
|
||||
// Real HTTP/WebSocket transport and file IO verify the shared runner wiring, not just mocks.
|
||||
describe(applyStartConfigAsync, () => {
|
||||
let server: http.Server;
|
||||
let sockets: WebSocketServer;
|
||||
let folder: string;
|
||||
let apiUrl: string;
|
||||
let actions: { action: string; params: Record<string, unknown> }[];
|
||||
const catalog = {
|
||||
set: {
|
||||
type: 'object',
|
||||
properties: { udid: { type: 'string' }, value: { type: 'string' } },
|
||||
required: ['udid', 'value'],
|
||||
},
|
||||
screenshot: {
|
||||
type: 'object',
|
||||
properties: { udid: { type: 'string' } },
|
||||
required: ['udid'],
|
||||
output: 'base64',
|
||||
},
|
||||
};
|
||||
beforeEach(async () => {
|
||||
actions = [];
|
||||
folder = await fs.mkdtemp(path.join(os.tmpdir(), 'start-setup-'));
|
||||
server = http.createServer((req, res) => {
|
||||
if (req.url !== '/api' || req.headers.authorization !== 'Bearer token') {
|
||||
res.writeHead(401).end();
|
||||
return;
|
||||
}
|
||||
res.setHeader('content-type', 'application/json');
|
||||
res.end(JSON.stringify({ device: 'owned-device' }));
|
||||
});
|
||||
sockets = new WebSocketServer({
|
||||
server,
|
||||
path: '/exec-ws',
|
||||
handleProtocols: protocols =>
|
||||
protocols.has('serve-sim.token.token') ? 'serve-sim.token.token' : false,
|
||||
});
|
||||
sockets.on('connection', socket => {
|
||||
socket.send(JSON.stringify({ ready: true }));
|
||||
socket.on('message', bytes => {
|
||||
const message = JSON.parse(bytes.toString());
|
||||
actions.push(message);
|
||||
const stdout =
|
||||
message.action === 'actions.describe'
|
||||
? JSON.stringify(catalog)
|
||||
: message.action === 'screenshot'
|
||||
? Buffer.from('image bytes').toString('base64')
|
||||
: 'done';
|
||||
socket.send(JSON.stringify({ id: message.id, stdout, stderr: '', exitCode: 0 }));
|
||||
});
|
||||
});
|
||||
server.listen(0, '127.0.0.1');
|
||||
await once(server, 'listening');
|
||||
apiUrl = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
|
||||
});
|
||||
afterEach(async () => {
|
||||
for (const socket of sockets.clients) {
|
||||
socket.terminate();
|
||||
}
|
||||
sockets.close();
|
||||
server.close();
|
||||
await once(server, 'close');
|
||||
await fs.remove(folder);
|
||||
});
|
||||
|
||||
it('runs the captured config after the file changes, writes outputs relative to it and closes transport', async () => {
|
||||
const file = path.join(folder, 'session.json');
|
||||
await fs.writeJson(file, {
|
||||
version: 1,
|
||||
start: { platform: 'ios' },
|
||||
actions: [
|
||||
{ action: 'set', params: { value: 'dark' } },
|
||||
{ action: 'screenshot', output: './screen.png' },
|
||||
],
|
||||
});
|
||||
const config = await readSimulatorSessionConfigAsync(file);
|
||||
await fs.writeJson(file, { version: 999 });
|
||||
const closed = new Promise<void>(resolve =>
|
||||
sockets.once('connection', socket => socket.once('close', resolve))
|
||||
);
|
||||
const progress = jest.fn();
|
||||
const results = await applyStartConfigAsync({ apiUrl, token: 'token' }, config, {
|
||||
signal: new AbortController().signal,
|
||||
onProgress: progress,
|
||||
});
|
||||
await closed;
|
||||
expect(results.map(result => result.action)).toEqual(['set', 'screenshot']);
|
||||
expect(await fs.readFile(path.join(folder, 'screen.png'), 'utf8')).toBe('image bytes');
|
||||
expect(actions.every(action => action.params.udid === 'owned-device')).toBe(true);
|
||||
expect(progress).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ step: 2, total: 2, status: 'completed' })
|
||||
);
|
||||
});
|
||||
|
||||
it('validates all actions before sending the first one and closes on validation failure', async () => {
|
||||
const file = path.join(folder, 'session.json');
|
||||
await fs.writeJson(file, {
|
||||
version: 1,
|
||||
actions: [{ action: 'set', params: { value: 'dark' } }, { action: 'unknown' }],
|
||||
});
|
||||
const config = await readSimulatorSessionConfigAsync(file);
|
||||
const closed = new Promise<void>(resolve =>
|
||||
sockets.once('connection', socket => socket.once('close', resolve))
|
||||
);
|
||||
await expect(
|
||||
applyStartConfigAsync({ apiUrl, token: 'token' }, config, {
|
||||
signal: new AbortController().signal,
|
||||
})
|
||||
).rejects.toThrow('Unknown simulator action');
|
||||
await closed;
|
||||
expect(actions.map(action => action.action)).toEqual(['actions.describe']);
|
||||
});
|
||||
});
|
||||
@@ -1,173 +0,0 @@
|
||||
import * as fs from 'fs-extra';
|
||||
import path from 'path';
|
||||
|
||||
import {
|
||||
HostActionCatalog,
|
||||
HostActionCatalogEntry,
|
||||
HostActionConnection,
|
||||
assertHostActionOutputAsync,
|
||||
saveHostActionOutputAsync,
|
||||
uploadFileAsync,
|
||||
} from './hostActions';
|
||||
|
||||
export type ControlAction = {
|
||||
action: string;
|
||||
params: Record<string, unknown>;
|
||||
outputPath?: string;
|
||||
file?: string;
|
||||
};
|
||||
|
||||
export type ControlActionResult = { output: string; file: string | null };
|
||||
|
||||
export type PreparedControlAction = Readonly<{
|
||||
action: string;
|
||||
entry: HostActionCatalogEntry;
|
||||
params: Readonly<Record<string, unknown>>;
|
||||
outputPath?: string;
|
||||
localFile?: Readonly<{ param: string; path: string }>;
|
||||
}>;
|
||||
|
||||
export function resolveControlActionPath(value: string, baseDir?: string): string {
|
||||
if (!baseDir) {
|
||||
return value;
|
||||
}
|
||||
const resolved = path.resolve(baseDir, value);
|
||||
return value.endsWith('/') || value.endsWith(path.sep) ? `${resolved}${path.sep}` : resolved;
|
||||
}
|
||||
|
||||
export async function prepareControlActionAsync(
|
||||
catalog: HostActionCatalog,
|
||||
action: ControlAction,
|
||||
{
|
||||
localFileMode = 'auto',
|
||||
baseDir,
|
||||
}: { localFileMode?: 'auto' | 'explicit'; baseDir?: string } = {}
|
||||
): Promise<PreparedControlAction> {
|
||||
const entry = Object.hasOwn(catalog, action.action) ? catalog[action.action] : undefined;
|
||||
if (!entry) {
|
||||
throw new Error(
|
||||
`Unknown simulator action "${action.action}". Run \`eas simulator:control --list\` to see the actions.`
|
||||
);
|
||||
}
|
||||
const params = { ...action.params };
|
||||
const outputPath = action.outputPath
|
||||
? resolveControlActionPath(action.outputPath, baseDir)
|
||||
: action.outputPath;
|
||||
await assertHostActionOutputAsync(action.action, entry, outputPath);
|
||||
|
||||
let localFile: PreparedControlAction['localFile'];
|
||||
const param = entry.upload;
|
||||
const applies = Object.entries(entry.uploadWhen ?? {}).every(
|
||||
([name, expected]) => params[name] === expected
|
||||
);
|
||||
if (action.file !== undefined) {
|
||||
if (!param || !applies) {
|
||||
throw new Error(`${action.action} does not accept a local file with these parameters.`);
|
||||
}
|
||||
if (Object.hasOwn(params, param)) {
|
||||
throw new Error(`${param} and file cannot both be supplied for ${action.action}.`);
|
||||
}
|
||||
localFile = { param, path: resolveControlActionPath(action.file, baseDir) };
|
||||
await assertLocalFileAsync(localFile.path);
|
||||
} else if (localFileMode === 'auto' && param && applies && typeof params[param] === 'string') {
|
||||
const value = params[param];
|
||||
if (value.startsWith('host:')) {
|
||||
if (entry.uploadAs === 'id') {
|
||||
throw new Error(
|
||||
'This action requires a local file to upload; host: paths are not supported.'
|
||||
);
|
||||
}
|
||||
const hostPath = value.slice('host:'.length);
|
||||
if (!path.posix.isAbsolute(hostPath)) {
|
||||
throw new Error(
|
||||
`A host: path must be absolute, for example host:/tmp/app.tar.gz. For a local filename beginning with host:, use ./${value}.`
|
||||
);
|
||||
}
|
||||
params[param] = hostPath;
|
||||
} else {
|
||||
const localPath = resolveControlActionPath(value, baseDir);
|
||||
const stat = await fs.stat(localPath).catch((error: NodeJS.ErrnoException) => {
|
||||
if (error.code === 'ENOENT' || error.code === 'ENOTDIR') {
|
||||
return null;
|
||||
}
|
||||
throw error;
|
||||
});
|
||||
if (!stat) {
|
||||
throw new Error(
|
||||
`${value} does not exist on this computer. Pass a local file, or prefix an absolute simulator-host path with host:.`
|
||||
);
|
||||
}
|
||||
await assertLocalFileAsync(localPath, stat);
|
||||
localFile = { param, path: localPath };
|
||||
}
|
||||
}
|
||||
return {
|
||||
action: action.action,
|
||||
entry,
|
||||
params,
|
||||
outputPath,
|
||||
...(localFile ? { localFile } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
export async function assertLocalFileAsync(localPath: string, stats?: fs.Stats): Promise<void> {
|
||||
const stat = stats ?? (await fs.stat(localPath).catch(() => null));
|
||||
if (!stat) {
|
||||
throw new Error(`${localPath} does not exist on this computer.`);
|
||||
}
|
||||
if (stat.isDirectory()) {
|
||||
throw new Error(`${localPath} is a folder. Pass the path of a file.`);
|
||||
}
|
||||
if (!stat.isFile()) {
|
||||
throw new Error(`${localPath} is not a regular file.`);
|
||||
}
|
||||
if (stat.size === 0) {
|
||||
throw new Error(`${localPath} is empty. Pass a file with content.`);
|
||||
}
|
||||
await fs.access(localPath, fs.constants.R_OK);
|
||||
}
|
||||
|
||||
export async function executeControlActionAsync(
|
||||
connection: HostActionConnection,
|
||||
plan: PreparedControlAction,
|
||||
{ validateParams }: { validateParams?: (params: Record<string, unknown>) => void } = {}
|
||||
): Promise<ControlActionResult> {
|
||||
connection.signal.throwIfAborted();
|
||||
const params: Record<string, unknown> = { ...plan.params };
|
||||
let uploadId: string | undefined;
|
||||
let succeeded = false;
|
||||
try {
|
||||
if (plan.localFile) {
|
||||
const upload = await uploadFileAsync(connection, plan.localFile.path);
|
||||
uploadId = upload.uploadId;
|
||||
params[plan.localFile.param] = plan.entry.uploadAs === 'id' ? upload.uploadId : upload.path;
|
||||
}
|
||||
connection.signal.throwIfAborted();
|
||||
validateParams?.(params);
|
||||
const result = await connection.requestAsync(plan.action, params);
|
||||
if (result.exitCode !== 0) {
|
||||
const detail = (result.stderr || result.stdout).trim() || `exit code ${result.exitCode}`;
|
||||
throw new Error(`The simulator could not run ${plan.action}: ${detail}`);
|
||||
}
|
||||
succeeded = true;
|
||||
const file = await saveHostActionOutputAsync(
|
||||
connection,
|
||||
plan.entry,
|
||||
result.stdout,
|
||||
plan.outputPath
|
||||
);
|
||||
return { output: file ? '' : result.stdout.trim(), file };
|
||||
} finally {
|
||||
if (uploadId && (!plan.entry.keepUpload || !succeeded)) {
|
||||
await connection.requestAsync('upload.remove', { uploadId }).catch(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function parseControlActionOutput(output: string): unknown {
|
||||
try {
|
||||
return JSON.parse(output);
|
||||
} catch {
|
||||
return output;
|
||||
}
|
||||
}
|
||||
@@ -1,214 +0,0 @@
|
||||
import Ajv2020, { AnySchema } from 'ajv/dist/2020';
|
||||
import addFormats from 'ajv-formats';
|
||||
import * as fs from 'fs-extra';
|
||||
import path from 'path';
|
||||
|
||||
import {
|
||||
ControlActionResult,
|
||||
PreparedControlAction,
|
||||
assertLocalFileAsync,
|
||||
executeControlActionAsync,
|
||||
parseControlActionOutput,
|
||||
prepareControlActionAsync,
|
||||
resolveControlActionPath,
|
||||
} from './controlActions';
|
||||
import { HostActionCatalog, HostActionConnection, createHostActionUploadId } from './hostActions';
|
||||
import { SimulatorSessionConfig, readSimulatorSessionConfigAsync } from './sessionConfig';
|
||||
|
||||
type ConfigAction = {
|
||||
readonly plan: PreparedControlAction;
|
||||
readonly validateParams: (params: Record<string, unknown>) => void;
|
||||
};
|
||||
|
||||
export type PreparedControlConfig = {
|
||||
readonly path: string;
|
||||
readonly udid: string;
|
||||
readonly actions: readonly ConfigAction[];
|
||||
};
|
||||
|
||||
export type ControlConfigResult = ControlActionResult & { action: string };
|
||||
|
||||
export type ControlConfigProgress = {
|
||||
step: number;
|
||||
total: number;
|
||||
action: string;
|
||||
} & ({ status: 'running' } | { status: 'completed'; result: ControlConfigResult });
|
||||
|
||||
export class ControlConfigExecutionError extends Error {
|
||||
constructor(
|
||||
readonly step: number,
|
||||
readonly action: string,
|
||||
readonly completed: readonly ControlConfigResult[],
|
||||
cause: unknown
|
||||
) {
|
||||
super(
|
||||
`Config step ${step} (${action}) failed after ${completed.length} completed actions: ${errorMessage(cause)}`,
|
||||
{ cause }
|
||||
);
|
||||
this.name = 'ControlConfigExecutionError';
|
||||
}
|
||||
}
|
||||
|
||||
export async function prepareControlConfigAsync(
|
||||
catalog: HostActionCatalog,
|
||||
filePath: string,
|
||||
udid: string,
|
||||
input?: SimulatorSessionConfig
|
||||
): Promise<PreparedControlConfig> {
|
||||
const config = input ?? (await readSimulatorSessionConfigAsync(filePath));
|
||||
const absolutePath = config.path;
|
||||
if (!config.actions?.length) {
|
||||
throw new Error(
|
||||
`Invalid simulator configuration ${absolutePath}: actions must contain at least one action.`
|
||||
);
|
||||
}
|
||||
|
||||
const ajv = addFormats(new Ajv2020({ strict: false, allErrors: true }));
|
||||
const actions: ConfigAction[] = [];
|
||||
for (const [index, action] of config.actions.entries()) {
|
||||
try {
|
||||
if (Object.hasOwn(action.params, 'udid')) {
|
||||
throw new Error('The simulator is selected by the session; remove params.udid.');
|
||||
}
|
||||
const plan = await prepareControlActionAsync(
|
||||
catalog,
|
||||
{ ...action, outputPath: action.output },
|
||||
{ localFileMode: 'explicit', baseDir: path.dirname(absolutePath) }
|
||||
);
|
||||
if (plan.entry.output) {
|
||||
if (!plan.outputPath) {
|
||||
throw new Error('Set output to a file or directory for this action.');
|
||||
}
|
||||
await assertWritableOutputAsync(plan.outputPath);
|
||||
}
|
||||
assertUnambiguousFileSource(ajv, plan, udid);
|
||||
const validate = ajv.compile(plan.entry as AnySchema);
|
||||
const validateParams = (params: Record<string, unknown>): void => {
|
||||
if (!validate({ ...params, udid })) {
|
||||
throw new Error(ajv.errorsText(validate.errors, { dataVar: 'params' }));
|
||||
}
|
||||
};
|
||||
const params = { ...plan.params };
|
||||
if (plan.localFile) {
|
||||
const uploadId = createHostActionUploadId(plan.localFile.path);
|
||||
params[plan.localFile.param] =
|
||||
plan.entry.uploadAs === 'id' ? uploadId : `/tmp/serve-sim-uploads/${uploadId}`;
|
||||
}
|
||||
validateParams(params);
|
||||
actions.push({ plan, validateParams });
|
||||
} catch (error) {
|
||||
throw new Error(`Config step ${index + 1} (${action.action}): ${errorMessage(error)}`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
return { path: absolutePath, udid, actions };
|
||||
}
|
||||
|
||||
/** Check local inputs before requesting a paid session; runtime validation still uses the live catalog. */
|
||||
export async function preflightControlConfigFilesAsync(
|
||||
config: SimulatorSessionConfig
|
||||
): Promise<void> {
|
||||
for (const [index, action] of (config.actions ?? []).entries()) {
|
||||
try {
|
||||
if (Object.hasOwn(action.params, 'udid')) {
|
||||
throw new Error('The simulator is selected by the session; remove params.udid.');
|
||||
}
|
||||
if (action.file) {
|
||||
await assertLocalFileAsync(path.resolve(path.dirname(config.path), action.file));
|
||||
}
|
||||
if (action.output) {
|
||||
await assertWritableOutputAsync(
|
||||
resolveControlActionPath(action.output, path.dirname(config.path))
|
||||
);
|
||||
}
|
||||
} catch (error) {
|
||||
throw new Error(`Config step ${index + 1} (${action.action}): ${errorMessage(error)}`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function assertWritableOutputAsync(outputPath: string): Promise<void> {
|
||||
const stat = await fs.stat(outputPath).catch(() => null);
|
||||
if ((outputPath.endsWith('/') || outputPath.endsWith(path.sep)) && !stat?.isDirectory()) {
|
||||
throw new Error(`${outputPath} must be an existing directory.`);
|
||||
}
|
||||
if (stat && !stat.isFile() && !stat.isDirectory()) {
|
||||
throw new Error(`${outputPath} must be a regular file or directory.`);
|
||||
}
|
||||
await fs.access(
|
||||
stat ? outputPath : path.dirname(outputPath),
|
||||
fs.constants.W_OK | (stat?.isFile() ? 0 : fs.constants.X_OK)
|
||||
);
|
||||
}
|
||||
|
||||
function declaresParameter(schema: unknown, name: string): boolean {
|
||||
if (typeof schema !== 'object' || schema === null || Array.isArray(schema)) {
|
||||
return false;
|
||||
}
|
||||
const { properties, allOf } = schema as { properties?: object; allOf?: unknown[] };
|
||||
return (
|
||||
(properties !== undefined && Object.hasOwn(properties, name)) ||
|
||||
(Array.isArray(allOf) && allOf.some(child => declaresParameter(child, name)))
|
||||
);
|
||||
}
|
||||
|
||||
function assertUnambiguousFileSource(
|
||||
ajv: Ajv2020,
|
||||
plan: PreparedControlAction,
|
||||
udid: string
|
||||
): void {
|
||||
if (!plan.localFile) {
|
||||
return;
|
||||
}
|
||||
const { anyOf, oneOf, ...common } = plan.entry;
|
||||
for (const branch of anyOf ?? oneOf ?? []) {
|
||||
if (declaresParameter(branch, plan.localFile.param)) {
|
||||
continue;
|
||||
}
|
||||
const validate = ajv.compile({
|
||||
...common,
|
||||
allOf: [...(common.allOf ?? []), branch],
|
||||
} as AnySchema);
|
||||
if (validate({ ...plan.params, udid })) {
|
||||
throw new Error('file conflicts with another source in params. Supply only one file source.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function executeControlConfigAsync(
|
||||
connection: HostActionConnection,
|
||||
config: PreparedControlConfig,
|
||||
{ onProgress }: { onProgress?: (progress: ControlConfigProgress) => void } = {}
|
||||
): Promise<ControlConfigResult[]> {
|
||||
if (config.udid !== connection.udid) {
|
||||
throw new Error('The simulator changed after this configuration was checked. Import it again.');
|
||||
}
|
||||
const completed: ControlConfigResult[] = [];
|
||||
for (const [index, { plan, validateParams }] of config.actions.entries()) {
|
||||
const progress = { step: index + 1, total: config.actions.length, action: plan.action };
|
||||
onProgress?.({ ...progress, status: 'running' });
|
||||
let result: ControlActionResult;
|
||||
try {
|
||||
result = await executeControlActionAsync(connection, plan, { validateParams });
|
||||
} catch (error) {
|
||||
throw new ControlConfigExecutionError(index + 1, plan.action, completed, error);
|
||||
}
|
||||
const entry = { action: plan.action, ...result };
|
||||
completed.push(entry);
|
||||
onProgress?.({ ...progress, status: 'completed', result: entry });
|
||||
}
|
||||
return completed;
|
||||
}
|
||||
|
||||
function errorMessage(error: unknown): string {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
export function serializeControlConfigResults(
|
||||
results: readonly ControlConfigResult[]
|
||||
): { action: string; output: unknown; file: string | null }[] {
|
||||
return results.map(result => ({ ...result, output: parseControlActionOutput(result.output) }));
|
||||
}
|
||||
@@ -1,343 +0,0 @@
|
||||
import chalk from 'chalk';
|
||||
|
||||
import { ControlAction } from './controlActions';
|
||||
import { ControlPromptCancelledError, promptControlValueAsync } from './controlPrompts';
|
||||
import { HostActionCatalog, HostActionCatalogEntry, NUMBER_PATTERN } from './hostActions';
|
||||
import Log from '../log';
|
||||
|
||||
type Schema = Record<string, unknown>;
|
||||
type Fields = { properties: Record<string, unknown>; required: Set<string> };
|
||||
|
||||
function isObject(value: unknown): value is Schema {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
function getObjectFields(schema: Schema): Fields | null {
|
||||
if (schema.anyOf || schema.oneOf || (schema.type && schema.type !== 'object')) {
|
||||
return null;
|
||||
}
|
||||
const result: Fields = {
|
||||
properties: isObject(schema.properties) ? { ...schema.properties } : {},
|
||||
required: new Set(Array.isArray(schema.required) ? (schema.required as string[]) : []),
|
||||
};
|
||||
for (const child of Array.isArray(schema.allOf) ? schema.allOf : []) {
|
||||
const nested = isObject(child) ? getObjectFields(child) : null;
|
||||
if (!nested) {
|
||||
return null;
|
||||
}
|
||||
Object.assign(result.properties, nested.properties);
|
||||
nested.required.forEach(name => result.required.add(name));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function selectFieldsAsync(
|
||||
entry: HostActionCatalogEntry,
|
||||
signal: AbortSignal
|
||||
): Promise<{ fields: Fields; params: Schema } | null> {
|
||||
const alternatives = entry.oneOf ?? entry.anyOf;
|
||||
if (!alternatives) {
|
||||
const result = getObjectFields(entry);
|
||||
return result && { fields: result, params: {} };
|
||||
}
|
||||
const branches = alternatives.map(branch => (isObject(branch) ? getObjectFields(branch) : null));
|
||||
if (branches.some(branch => !branch)) {
|
||||
return null;
|
||||
}
|
||||
const available = branches as Fields[];
|
||||
let selected: number | undefined;
|
||||
const params: Schema = {};
|
||||
for (const name of Object.keys(available[0]?.properties ?? {})) {
|
||||
if (name === 'udid') {
|
||||
continue;
|
||||
}
|
||||
const values = available.map(branch => branch.properties[name]);
|
||||
if (!values.every(schema => isObject(schema) && Object.hasOwn(schema, 'const'))) {
|
||||
continue;
|
||||
}
|
||||
const constants = values.map(schema => (schema as Schema).const);
|
||||
if (new Set(constants.map(value => JSON.stringify(value))).size !== constants.length) {
|
||||
continue;
|
||||
}
|
||||
const value = await promptControlValueAsync(
|
||||
{
|
||||
type: 'select',
|
||||
message: name,
|
||||
choices: constants.map(value => ({ title: String(value), value })),
|
||||
},
|
||||
signal
|
||||
);
|
||||
selected = constants.findIndex(constant => constant === value);
|
||||
params[name] = value;
|
||||
break;
|
||||
}
|
||||
if (selected === undefined) {
|
||||
// Some upload actions expose a path to users but also accept an internal upload ID.
|
||||
const exposed = entry.args ?? (entry.upload ? [entry.upload] : []);
|
||||
const candidates = available
|
||||
.map((branch, index) => ({ branch, index }))
|
||||
.filter(
|
||||
({ branch }) =>
|
||||
exposed.length > 0 && exposed.every(name => Object.hasOwn(branch.properties, name))
|
||||
);
|
||||
if (candidates.length !== 1) {
|
||||
return null;
|
||||
}
|
||||
selected = candidates[0].index;
|
||||
}
|
||||
const common = getObjectFields({ ...entry, anyOf: undefined, oneOf: undefined });
|
||||
if (!common || !available[selected]) {
|
||||
return null;
|
||||
}
|
||||
const chosen = available[selected];
|
||||
return {
|
||||
fields: {
|
||||
properties: { ...common.properties, ...chosen.properties },
|
||||
required: new Set([...common.required, ...chosen.required]),
|
||||
},
|
||||
params,
|
||||
};
|
||||
}
|
||||
|
||||
function getSchemaTypes(schema: Schema): string[] {
|
||||
return [
|
||||
schema.type ?? [],
|
||||
...(Array.isArray(schema.anyOf) ? schema.anyOf : []),
|
||||
...(Array.isArray(schema.oneOf) ? schema.oneOf : []),
|
||||
].flatMap(value =>
|
||||
typeof value === 'string'
|
||||
? [value]
|
||||
: Array.isArray(value)
|
||||
? value.filter((item): item is string => typeof item === 'string')
|
||||
: isObject(value)
|
||||
? getSchemaTypes(value)
|
||||
: []
|
||||
);
|
||||
}
|
||||
|
||||
function parseValue(value: string, schema: Schema): unknown {
|
||||
const accepted = getSchemaTypes(schema);
|
||||
if (usesJson(accepted)) {
|
||||
const parsed: unknown = JSON.parse(value);
|
||||
const type = parsed === null ? 'null' : Array.isArray(parsed) ? 'array' : typeof parsed;
|
||||
if (
|
||||
accepted.includes(type) ||
|
||||
(type === 'number' && accepted.includes('integer') && Number.isInteger(parsed))
|
||||
) {
|
||||
return parsed;
|
||||
}
|
||||
throw new Error('Enter a JSON value matching this parameter.');
|
||||
}
|
||||
if ((accepted.includes('number') || accepted.includes('integer')) && NUMBER_PATTERN.test(value)) {
|
||||
const number = Number(value);
|
||||
if (
|
||||
Number.isFinite(number) &&
|
||||
(!accepted.includes('integer') || accepted.includes('number') || Number.isInteger(number))
|
||||
) {
|
||||
return number;
|
||||
}
|
||||
}
|
||||
if (accepted.includes('string') || accepted.length === 0) {
|
||||
return value;
|
||||
}
|
||||
throw new Error('Enter a valid number.');
|
||||
}
|
||||
|
||||
function usesJson(accepted: string[]): boolean {
|
||||
return ['object', 'array', 'boolean', 'null'].some(type => accepted.includes(type));
|
||||
}
|
||||
|
||||
async function promptFieldAsync(name: string, raw: unknown, signal: AbortSignal): Promise<unknown> {
|
||||
const schema = isObject(raw) ? raw : {};
|
||||
if (Object.hasOwn(schema, 'const')) {
|
||||
return schema.const;
|
||||
}
|
||||
if (typeof schema.description === 'string') {
|
||||
Log.gray(schema.description);
|
||||
}
|
||||
if (Array.isArray(schema.enum)) {
|
||||
return await promptControlValueAsync(
|
||||
{
|
||||
type: 'select',
|
||||
message: name,
|
||||
choices: schema.enum.map(value => ({ title: String(value), value })),
|
||||
},
|
||||
signal
|
||||
);
|
||||
}
|
||||
const accepted = getSchemaTypes(schema);
|
||||
if (accepted.length === 1 && accepted[0] === 'boolean') {
|
||||
return await promptControlValueAsync(
|
||||
{ type: 'toggle', message: name, active: 'true', inactive: 'false', initial: false },
|
||||
signal
|
||||
);
|
||||
}
|
||||
const json = usesJson(accepted);
|
||||
const value = await promptControlValueAsync(
|
||||
{
|
||||
type: 'text',
|
||||
message: `${name}${json ? ' (JSON)' : ''}`,
|
||||
validate(value: string) {
|
||||
try {
|
||||
parseValue(value, schema);
|
||||
return true;
|
||||
} catch (error) {
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
},
|
||||
},
|
||||
signal
|
||||
);
|
||||
return parseValue(String(value), schema);
|
||||
}
|
||||
|
||||
export async function promptControlActionAsync(
|
||||
action: string,
|
||||
entry: HostActionCatalogEntry,
|
||||
signal: AbortSignal
|
||||
): Promise<ControlAction> {
|
||||
const selected = await selectFieldsAsync(entry, signal);
|
||||
let params: Record<string, unknown>;
|
||||
if (!selected) {
|
||||
const value = await promptControlValueAsync(
|
||||
{
|
||||
type: 'text',
|
||||
message: 'Parameters (JSON object, without udid)',
|
||||
validate(value: string) {
|
||||
try {
|
||||
return isObject(JSON.parse(value)) || 'Enter a JSON object.';
|
||||
} catch {
|
||||
return 'Enter a JSON object.';
|
||||
}
|
||||
},
|
||||
},
|
||||
signal
|
||||
);
|
||||
params = JSON.parse(String(value));
|
||||
} else {
|
||||
params = selected.params;
|
||||
const names = [...new Set([...(entry.args ?? []), ...Object.keys(selected.fields.properties)])];
|
||||
for (const name of names) {
|
||||
if (
|
||||
name === 'udid' ||
|
||||
Object.hasOwn(params, name) ||
|
||||
!Object.hasOwn(selected.fields.properties, name)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
const schema = selected.fields.properties[name];
|
||||
if (!selected.fields.required.has(name)) {
|
||||
const hint =
|
||||
isObject(schema) && Object.hasOwn(schema, 'default')
|
||||
? ` (default: ${JSON.stringify(schema.default)})`
|
||||
: '';
|
||||
const include = await promptControlValueAsync(
|
||||
{ type: 'confirm', message: `Set optional ${name}${hint}?`, initial: false },
|
||||
signal
|
||||
);
|
||||
if (!include) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
params[name] = await promptFieldAsync(name, schema, signal);
|
||||
}
|
||||
}
|
||||
const result: ControlAction = { action, params };
|
||||
if (entry.output) {
|
||||
const outputPath = await promptControlValueAsync(
|
||||
{
|
||||
type: 'text',
|
||||
message: 'Save file to',
|
||||
validate: (value: string) => value.trim().length > 0 || 'Enter a local output path.',
|
||||
},
|
||||
signal
|
||||
);
|
||||
result.outputPath = String(outputPath);
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function runControlMenuAsync({
|
||||
catalog,
|
||||
signal,
|
||||
runActionAsync,
|
||||
}: {
|
||||
catalog: HostActionCatalog;
|
||||
signal: AbortSignal;
|
||||
runActionAsync: (action: ControlAction) => Promise<void>;
|
||||
}): Promise<void> {
|
||||
const choices = [
|
||||
{ title: 'Exit', description: 'Close simulator controls', value: { kind: 'exit' as const } },
|
||||
...Object.keys(catalog)
|
||||
.sort()
|
||||
.map(name => ({
|
||||
title: name.split('.').map(actionLabel).join(' › '),
|
||||
description: name,
|
||||
value: { kind: 'action' as const, name },
|
||||
})),
|
||||
];
|
||||
signal.throwIfAborted();
|
||||
Log.gray(
|
||||
`${Object.keys(catalog).length} actions · Type to search · ↑/↓ to navigate · Enter to select · Ctrl-C to exit`
|
||||
);
|
||||
while (true) {
|
||||
signal.throwIfAborted();
|
||||
const choice = (await promptControlValueAsync(
|
||||
{
|
||||
type: 'autocomplete',
|
||||
message: 'Choose a simulator action',
|
||||
choices,
|
||||
limit: 8,
|
||||
suggest: (input: string) => {
|
||||
const words = input.toLowerCase().trim().split(/\s+/);
|
||||
return Promise.resolve(
|
||||
choices.filter(choice => {
|
||||
const description =
|
||||
choice.value.kind === 'action'
|
||||
? (catalog[choice.value.name].description ?? '')
|
||||
: '';
|
||||
const text = `${choice.title} ${choice.description} ${description}`.toLowerCase();
|
||||
return words.every(word => text.includes(word));
|
||||
})
|
||||
);
|
||||
},
|
||||
},
|
||||
signal
|
||||
)) as { kind: 'exit' } | { kind: 'action'; name: string };
|
||||
signal.throwIfAborted();
|
||||
if (!choice) {
|
||||
Log.error('Choose an action or Exit.');
|
||||
continue;
|
||||
}
|
||||
if (choice.kind === 'exit') {
|
||||
Log.gray('Simulator controls closed.');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
Log.newLine();
|
||||
Log.log(chalk.bold(choice.name));
|
||||
if (catalog[choice.name].description) {
|
||||
Log.gray(catalog[choice.name].description);
|
||||
}
|
||||
await runActionAsync(
|
||||
await promptControlActionAsync(choice.name, catalog[choice.name], signal)
|
||||
);
|
||||
} catch (error) {
|
||||
signal.throwIfAborted();
|
||||
if (error instanceof ControlPromptCancelledError) {
|
||||
throw error;
|
||||
}
|
||||
Log.error(error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
Log.newLine();
|
||||
}
|
||||
}
|
||||
|
||||
function actionLabel(value: string): string {
|
||||
const words = value
|
||||
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
|
||||
.replace(/[_-]/g, ' ')
|
||||
.toLowerCase();
|
||||
return words.charAt(0).toUpperCase() + words.slice(1);
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
import { Question, promptAsync } from '../prompts';
|
||||
|
||||
export class ControlPromptCancelledError extends Error {
|
||||
constructor() {
|
||||
super('Simulator control interrupted.');
|
||||
this.name = 'ControlPromptCancelledError';
|
||||
}
|
||||
}
|
||||
|
||||
type ActivePrompt = { abort(): void; closed?: boolean; done?: boolean };
|
||||
|
||||
/** Unlike the default prompt cancellation, this unwinds through the connection's cleanup. */
|
||||
export async function promptControlValueAsync(
|
||||
question: Omit<Question<'value'>, 'name'>,
|
||||
signal: AbortSignal
|
||||
): Promise<unknown> {
|
||||
signal.throwIfAborted();
|
||||
let active: ActivePrompt | undefined;
|
||||
let abortQueued = false;
|
||||
const abort = (): void => {
|
||||
if (abortQueued) {
|
||||
return;
|
||||
}
|
||||
abortQueued = true;
|
||||
// The first render happens inside the prompt constructor, before its abort listener exists.
|
||||
queueMicrotask(() => {
|
||||
abortQueued = false;
|
||||
if (active && !active.closed && !active.done) {
|
||||
active.abort();
|
||||
}
|
||||
});
|
||||
};
|
||||
signal.addEventListener('abort', abort, { once: true });
|
||||
try {
|
||||
const result = await promptAsync(
|
||||
{
|
||||
...question,
|
||||
name: 'value',
|
||||
onRender(this: ActivePrompt, kleur) {
|
||||
active = this;
|
||||
question.onRender?.call(this, kleur);
|
||||
if (signal.aborted) {
|
||||
abort();
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
onCancel() {
|
||||
signal.throwIfAborted();
|
||||
throw new ControlPromptCancelledError();
|
||||
},
|
||||
}
|
||||
);
|
||||
signal.throwIfAborted();
|
||||
return result.value;
|
||||
} finally {
|
||||
signal.removeEventListener('abort', abort);
|
||||
}
|
||||
}
|
||||
@@ -1,130 +0,0 @@
|
||||
import { ExpoGraphqlClient } from '../commandUtils/context/contextUtils/createGraphqlClient';
|
||||
import { DeviceRunSessionStatus, JobRunStatus } from '../graphql/generated';
|
||||
import { DeviceRunSessionQuery } from '../graphql/queries/DeviceRunSessionQuery';
|
||||
import Log from '../log';
|
||||
|
||||
export class ControlSessionEndedError extends Error {
|
||||
constructor(
|
||||
sessionId: string,
|
||||
readonly failed = false
|
||||
) {
|
||||
super(`Simulator session ${sessionId} ${failed ? 'errored' : 'has ended'}.`);
|
||||
this.name = 'ControlSessionEndedError';
|
||||
}
|
||||
}
|
||||
|
||||
/** Watches status without extending or stopping the remote session. */
|
||||
export function watchControlSession(
|
||||
graphqlClient: ExpoGraphqlClient,
|
||||
sessionId: string,
|
||||
{
|
||||
signal,
|
||||
pollIntervalMs = 5000,
|
||||
requestTimeoutMs = 30_000,
|
||||
}: { signal: AbortSignal; pollIntervalMs?: number; requestTimeoutMs?: number }
|
||||
): { signal: AbortSignal; dispose(): void } {
|
||||
const controller = new AbortController();
|
||||
let pollTimer: NodeJS.Timeout | undefined;
|
||||
let cancelRequest: (() => void) | undefined;
|
||||
|
||||
function stop(reason?: unknown): void {
|
||||
if (controller.signal.aborted) {
|
||||
return;
|
||||
}
|
||||
clearTimeout(pollTimer);
|
||||
cancelRequest?.();
|
||||
signal.removeEventListener('abort', onAbort);
|
||||
controller.abort(reason);
|
||||
}
|
||||
|
||||
function onAbort(): void {
|
||||
stop(signal.reason);
|
||||
}
|
||||
|
||||
function schedulePoll(): void {
|
||||
if (!controller.signal.aborted) {
|
||||
pollTimer = setTimeout(poll, pollIntervalMs);
|
||||
}
|
||||
}
|
||||
|
||||
function retry(error: unknown): void {
|
||||
Log.debug(`Could not check simulator session ${sessionId}:`, error);
|
||||
schedulePoll();
|
||||
}
|
||||
|
||||
function poll(): void {
|
||||
pollTimer = undefined;
|
||||
let subscription: { unsubscribe(): void } | undefined;
|
||||
let requestTimer: NodeJS.Timeout | undefined;
|
||||
let finished = false;
|
||||
|
||||
function finishRequest(): boolean {
|
||||
if (finished) {
|
||||
return false;
|
||||
}
|
||||
finished = true;
|
||||
clearTimeout(requestTimer);
|
||||
// urql tears down the operation and aborts the HTTP fetch on unsubscribe.
|
||||
subscription?.unsubscribe();
|
||||
cancelRequest = undefined;
|
||||
return true;
|
||||
}
|
||||
|
||||
cancelRequest = () => {
|
||||
finishRequest();
|
||||
};
|
||||
requestTimer = setTimeout(() => {
|
||||
if (finishRequest()) {
|
||||
retry(new Error('Session status request timed out.'));
|
||||
}
|
||||
}, requestTimeoutMs);
|
||||
|
||||
try {
|
||||
subscription = DeviceRunSessionQuery.byId(graphqlClient, sessionId, {
|
||||
requestPolicy: 'network-only',
|
||||
noRetry: true,
|
||||
}).subscribe(result => {
|
||||
if (result.stale || result.hasNext || !finishRequest()) {
|
||||
return;
|
||||
}
|
||||
const session = result.data?.deviceRunSessions?.byId;
|
||||
if (result.error || !session) {
|
||||
retry(result.error ?? new Error('Session status response was empty.'));
|
||||
return;
|
||||
}
|
||||
if (
|
||||
[DeviceRunSessionStatus.Stopped, DeviceRunSessionStatus.Errored].includes(
|
||||
session.status
|
||||
) ||
|
||||
(session.turtleJobRun &&
|
||||
[JobRunStatus.Canceled, JobRunStatus.Finished, JobRunStatus.Errored].includes(
|
||||
session.turtleJobRun.status
|
||||
))
|
||||
) {
|
||||
const failed =
|
||||
session.status === DeviceRunSessionStatus.Errored ||
|
||||
session.turtleJobRun?.status === JobRunStatus.Errored;
|
||||
stop(new ControlSessionEndedError(sessionId, failed));
|
||||
} else {
|
||||
schedulePoll();
|
||||
}
|
||||
});
|
||||
// A synchronous source may finish before subscribe returns its handle.
|
||||
if (finished) {
|
||||
subscription.unsubscribe();
|
||||
}
|
||||
} catch (error) {
|
||||
if (finishRequest()) {
|
||||
retry(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (signal.aborted) {
|
||||
stop(signal.reason);
|
||||
} else {
|
||||
signal.addEventListener('abort', onAbort, { once: true });
|
||||
schedulePoll();
|
||||
}
|
||||
return { signal: controller.signal, dispose: stop };
|
||||
}
|
||||
@@ -14,8 +14,6 @@ export type HostActionResult = {
|
||||
};
|
||||
|
||||
export type HostActionConnection = {
|
||||
readonly signal: AbortSignal;
|
||||
readonly udid: string;
|
||||
requestAsync(action: string, params?: Record<string, unknown>): Promise<HostActionResult>;
|
||||
close(): void;
|
||||
};
|
||||
@@ -44,8 +42,6 @@ const Catalog = z.record(z.string(), CatalogEntry);
|
||||
export type HostActionCatalog = z.infer<typeof Catalog>;
|
||||
export type HostActionCatalogEntry = z.infer<typeof CatalogEntry>;
|
||||
|
||||
export type HostActionDevice = { udid: string; name?: string; runtime?: string };
|
||||
|
||||
const PreviewConfig = z.object({ device: z.string().min(1) });
|
||||
|
||||
const ReplyId = z.object({ id: z.number() });
|
||||
@@ -63,11 +59,9 @@ const SocketMessage = z.union([
|
||||
|
||||
const HOST_ACTION_TIMEOUT_MS = 130_000;
|
||||
const PREVIEW_API_TIMEOUT_MS = 30_000;
|
||||
const PREVIEW_UNAVAILABLE_MESSAGE =
|
||||
'The simulator preview server is unavailable. The session may have ended or expired. Check it with `eas simulator:get`, or start a new session with `eas simulator:start`.';
|
||||
const UPLOAD_CHUNK_BYTES = 2 * 1024 * 1024;
|
||||
const NAMED_VALUE = /^([A-Za-z][A-Za-z0-9]*)=(.*)$/s;
|
||||
export const NUMBER_PATTERN = /^-?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/i;
|
||||
const NUMBER = /^-?(\d+\.?\d*|\.\d+)(e[+-]?\d+)?$/i;
|
||||
|
||||
function previewEndpoint(apiUrl: string, endpoint: string): URL {
|
||||
const base = new URL(apiUrl);
|
||||
@@ -88,25 +82,16 @@ function previewEndpoint(apiUrl: string, endpoint: string): URL {
|
||||
return new URL(endpoint, base);
|
||||
}
|
||||
|
||||
async function fetchSimulatorUdidAsync(
|
||||
{ apiUrl, token }: PreviewApiAccess,
|
||||
signal?: AbortSignal
|
||||
): Promise<string> {
|
||||
async function fetchSimulatorUdidAsync({ apiUrl, token }: PreviewApiAccess): Promise<string> {
|
||||
let text: string;
|
||||
try {
|
||||
const response = await fetch(previewEndpoint(apiUrl, 'api').toString(), {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
redirect: 'error',
|
||||
signal: signal
|
||||
? AbortSignal.any([signal, AbortSignal.timeout(PREVIEW_API_TIMEOUT_MS)])
|
||||
: AbortSignal.timeout(PREVIEW_API_TIMEOUT_MS),
|
||||
signal: AbortSignal.timeout(PREVIEW_API_TIMEOUT_MS),
|
||||
});
|
||||
text = await response.text();
|
||||
} catch (error) {
|
||||
signal?.throwIfAborted();
|
||||
if (error instanceof RequestError && error.response.status === 404) {
|
||||
throw new Error(PREVIEW_UNAVAILABLE_MESSAGE);
|
||||
}
|
||||
if (error instanceof RequestError && [401, 403].includes(error.response.status)) {
|
||||
throw new Error(
|
||||
`The simulator preview server refused the session token (HTTP ${error.response.status}). Run \`eas simulator:get\` to check that the session still runs, then try again.`
|
||||
@@ -132,31 +117,6 @@ async function fetchSimulatorUdidAsync(
|
||||
return config.data.device;
|
||||
}
|
||||
|
||||
export async function fetchHostActionDeviceAsync(
|
||||
{ apiUrl, token }: PreviewApiAccess,
|
||||
udid: string
|
||||
): Promise<HostActionDevice> {
|
||||
const url = previewEndpoint(apiUrl, 'grid/api/catalog').toString();
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
redirect: 'error',
|
||||
signal: AbortSignal.timeout(PREVIEW_API_TIMEOUT_MS),
|
||||
});
|
||||
const catalog = z
|
||||
.object({
|
||||
devices: z.array(
|
||||
z.object({ device: z.string(), name: z.string(), runtime: z.string().optional() })
|
||||
),
|
||||
})
|
||||
.parse(await response.json());
|
||||
const device = catalog.devices.find(device => device.device === udid);
|
||||
return device ? { udid, name: device.name, runtime: device.runtime } : { udid };
|
||||
} catch {
|
||||
return { udid };
|
||||
}
|
||||
}
|
||||
|
||||
function refusedError(error: string): Error {
|
||||
return error.startsWith('unknown action')
|
||||
? new Error(
|
||||
@@ -167,11 +127,9 @@ function refusedError(error: string): Error {
|
||||
|
||||
export async function connectHostActionsAsync(
|
||||
access: PreviewApiAccess,
|
||||
{ timeoutMs = HOST_ACTION_TIMEOUT_MS, signal }: { timeoutMs?: number; signal?: AbortSignal } = {}
|
||||
{ timeoutMs = HOST_ACTION_TIMEOUT_MS }: { timeoutMs?: number } = {}
|
||||
): Promise<HostActionConnection> {
|
||||
signal?.throwIfAborted();
|
||||
const udid = await fetchSimulatorUdidAsync(access, signal);
|
||||
signal?.throwIfAborted();
|
||||
const udid = await fetchSimulatorUdidAsync(access);
|
||||
const socketUrl = previewEndpoint(access.apiUrl, 'exec-ws');
|
||||
socketUrl.protocol = socketUrl.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
const ws = new WebSocket(
|
||||
@@ -186,7 +144,6 @@ export async function connectHostActionsAsync(
|
||||
timer: NodeJS.Timeout;
|
||||
};
|
||||
const pending = new Map<number, Pending>();
|
||||
const controller = new AbortController();
|
||||
let nextId = 1;
|
||||
let lost: Error | null = null;
|
||||
let ready = false;
|
||||
@@ -201,39 +158,30 @@ export async function connectHostActionsAsync(
|
||||
}
|
||||
|
||||
function loseConnection(error: Error): void {
|
||||
if (lost) {
|
||||
return;
|
||||
}
|
||||
lost = error;
|
||||
controller.abort(error);
|
||||
lost ??= error;
|
||||
for (const id of [...pending.keys()]) {
|
||||
settle(id)?.reject(error);
|
||||
}
|
||||
ws.terminate();
|
||||
}
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
fail(
|
||||
reject(
|
||||
new Error(
|
||||
`The simulator preview server did not accept the connection within ${PREVIEW_API_TIMEOUT_MS / 1000} seconds. Check that the session still runs with \`eas simulator:get\`, then try again.`
|
||||
)
|
||||
);
|
||||
ws.terminate();
|
||||
}, PREVIEW_API_TIMEOUT_MS);
|
||||
const fail = (error: Error): void => {
|
||||
clearTimeout(timer);
|
||||
reject(error);
|
||||
loseConnection(error);
|
||||
if (!ready) {
|
||||
ws.terminate();
|
||||
}
|
||||
};
|
||||
|
||||
const onAbort = (): void => {
|
||||
fail(
|
||||
signal?.reason instanceof Error ? signal.reason : new Error('Simulator setup canceled.')
|
||||
);
|
||||
};
|
||||
signal?.addEventListener('abort', onAbort, { once: true });
|
||||
ws.once('close', () => signal?.removeEventListener('abort', onAbort));
|
||||
|
||||
ws.on('message', data => {
|
||||
let message: unknown;
|
||||
try {
|
||||
@@ -272,9 +220,7 @@ export async function connectHostActionsAsync(
|
||||
res.destroy();
|
||||
fail(
|
||||
new Error(
|
||||
res.statusCode === 404
|
||||
? PREVIEW_UNAVAILABLE_MESSAGE
|
||||
: `The simulator preview server refused the connection (HTTP ${res.statusCode}). The session token may be out of date. Run \`eas simulator:get\` to check the session, then try again.`
|
||||
`The simulator preview server refused the connection (HTTP ${res.statusCode}). The session token may be out of date. Run \`eas simulator:get\` to check the session, then try again.`
|
||||
)
|
||||
);
|
||||
});
|
||||
@@ -294,42 +240,28 @@ export async function connectHostActionsAsync(
|
||||
)
|
||||
);
|
||||
});
|
||||
if (signal?.aborted) {
|
||||
onAbort();
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
signal: controller.signal,
|
||||
udid,
|
||||
async requestAsync(action, params = {}) {
|
||||
if (lost) {
|
||||
throw lost;
|
||||
}
|
||||
const id = nextId++;
|
||||
const message = JSON.stringify({ id, action, params: { ...params, udid } });
|
||||
return await new Promise<HostActionResult>((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
loseConnection(
|
||||
settle(id)?.reject(
|
||||
new Error(
|
||||
`The simulator did not answer within ${Math.round(timeoutMs / 1000)} seconds. The action may still have run. Check the session with \`eas simulator:get\` and the current state before you try again.`
|
||||
)
|
||||
);
|
||||
}, timeoutMs);
|
||||
pending.set(id, { resolve, reject, timer });
|
||||
try {
|
||||
ws.send(message, error => {
|
||||
if (error) {
|
||||
loseConnection(error);
|
||||
}
|
||||
});
|
||||
} catch (error) {
|
||||
loseConnection(error instanceof Error ? error : new Error(String(error)));
|
||||
}
|
||||
ws.send(JSON.stringify({ id, action, params: { ...params, udid } }));
|
||||
});
|
||||
},
|
||||
close() {
|
||||
loseConnection(new Error('The simulator action connection was closed.'));
|
||||
ws.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -418,10 +350,7 @@ function coerce(value: string, schemas: unknown[]): unknown {
|
||||
return value;
|
||||
}
|
||||
}
|
||||
if (
|
||||
NUMBER_PATTERN.test(value) &&
|
||||
schemas.some(schema => acceptsType(schema, ['number', 'integer']))
|
||||
) {
|
||||
if (NUMBER.test(value) && schemas.some(schema => acceptsType(schema, ['number', 'integer']))) {
|
||||
return Number(value);
|
||||
}
|
||||
if (
|
||||
@@ -518,16 +447,12 @@ export async function assertHostActionOutputAsync(
|
||||
}
|
||||
}
|
||||
|
||||
export function createHostActionUploadId(localPath: string): string {
|
||||
return `eas-cli-${randomUUID()}${path.extname(localPath).replace(/[^A-Za-z0-9.]/g, '')}`;
|
||||
}
|
||||
|
||||
export async function uploadFileAsync(
|
||||
connection: HostActionConnection,
|
||||
localPath: string,
|
||||
{ chunkBytes = UPLOAD_CHUNK_BYTES }: { chunkBytes?: number } = {}
|
||||
): Promise<{ uploadId: string; path: string }> {
|
||||
const uploadId = createHostActionUploadId(localPath);
|
||||
const uploadId = `eas-cli-${randomUUID()}${path.extname(localPath).replace(/[^A-Za-z0-9.]/g, '')}`;
|
||||
let remotePath = '';
|
||||
let first = true;
|
||||
try {
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
import * as fs from 'fs-extra';
|
||||
import path from 'path';
|
||||
import { z } from 'zod';
|
||||
|
||||
const Action = z.strictObject({
|
||||
action: z.string().min(1),
|
||||
params: z.record(z.string(), z.json()).default({}),
|
||||
file: z.string().min(1).optional(),
|
||||
output: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
const Config = z.strictObject({
|
||||
version: z.literal(1),
|
||||
start: z.record(z.string(), z.json()).optional(),
|
||||
actions: z.array(Action).min(1).optional(),
|
||||
});
|
||||
|
||||
export type SimulatorSessionConfig = z.infer<typeof Config> & { path: string };
|
||||
|
||||
export async function readSimulatorSessionConfigAsync(
|
||||
filePath: string
|
||||
): Promise<SimulatorSessionConfig> {
|
||||
const absolutePath = path.resolve(filePath);
|
||||
let input: unknown;
|
||||
try {
|
||||
input = await fs.readJson(absolutePath);
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Could not read simulator configuration ${absolutePath}: ${error instanceof Error ? error.message : String(error)}`,
|
||||
{ cause: error }
|
||||
);
|
||||
}
|
||||
const parsed = Config.safeParse(input);
|
||||
if (!parsed.success) {
|
||||
const detail = parsed.error.issues
|
||||
.map(issue => `${issue.path.join('.')}: ${issue.message}`)
|
||||
.join('; ');
|
||||
throw new Error(`Invalid simulator configuration ${absolutePath}: ${detail}`);
|
||||
}
|
||||
return { ...parsed.data, path: absolutePath };
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
import { Interfaces, Parser } from '@oclif/core';
|
||||
|
||||
import { preflightControlConfigFilesAsync } from './controlConfig';
|
||||
import { SimulatorSessionConfig, readSimulatorSessionConfigAsync } from './sessionConfig';
|
||||
|
||||
/** Reparse the effective values using the command's own validation, options and defaults. */
|
||||
export async function resolveStartConfigAsync(
|
||||
argv: string[],
|
||||
definitions: Interfaces.FlagInput
|
||||
): Promise<{ argv: string[]; config?: SimulatorSessionConfig }> {
|
||||
if (!argv.some(arg => arg === '--import' || arg.startsWith('--import='))) {
|
||||
return { argv };
|
||||
}
|
||||
// Relationships are checked after file values and explicit CLI overrides are combined.
|
||||
const relaxed = Object.fromEntries(
|
||||
Object.entries(definitions).map(([name, flag]) => [
|
||||
name,
|
||||
{
|
||||
...flag,
|
||||
dependsOn: undefined,
|
||||
exclusive: undefined,
|
||||
exactlyOne: undefined,
|
||||
atLeastOne: undefined,
|
||||
relationships: undefined,
|
||||
required: false,
|
||||
},
|
||||
])
|
||||
);
|
||||
const parsed = await Parser.parse(argv, { flags: relaxed });
|
||||
if (parsed.flags.import === undefined) {
|
||||
return { argv };
|
||||
}
|
||||
if (!parsed.flags.import.trim()) {
|
||||
throw new Error('--import requires a non-empty configuration file path.');
|
||||
}
|
||||
const config = await readSimulatorSessionConfigAsync(parsed.flags.import);
|
||||
const values: Record<string, unknown> = { ...config.start };
|
||||
for (const key of Object.keys(values)) {
|
||||
if (!Object.hasOwn(definitions, key) || ['import', 'json', 'non-interactive'].includes(key)) {
|
||||
throw new Error(`Unknown or invocation-only start setting "${key}" in ${config.path}.`);
|
||||
}
|
||||
}
|
||||
const explicit = Object.entries(parsed.flags).filter(
|
||||
([name, value]) => value !== undefined && !parsed.metadata.flags[name]?.setFromDefault
|
||||
);
|
||||
const explicitNames = new Set(explicit.map(([name]) => name));
|
||||
const removed = new Set<string>();
|
||||
for (const [name, value] of explicit) {
|
||||
for (const excluded of definitions[name].exclusive ?? []) {
|
||||
if (!explicitNames.has(excluded)) {
|
||||
delete values[excluded];
|
||||
removed.add(excluded);
|
||||
}
|
||||
}
|
||||
values[name] = value;
|
||||
}
|
||||
// SDK selection belongs to the saved Expo Go app source, not a replacement build.
|
||||
if (removed.has('expo-go') && !explicitNames.has('sdk-version')) {
|
||||
delete values['sdk-version'];
|
||||
}
|
||||
if (
|
||||
explicitNames.has('network-capture') &&
|
||||
values['network-capture'] === false &&
|
||||
!explicitNames.has('network-capture-field')
|
||||
) {
|
||||
delete values['network-capture-field'];
|
||||
}
|
||||
const effectiveArgv: string[] = [];
|
||||
for (const [name, value] of Object.entries(values)) {
|
||||
const flag = definitions[name];
|
||||
if (flag.type === 'boolean') {
|
||||
if (typeof value !== 'boolean') {
|
||||
throw new Error(`Start setting "${name}" must be a boolean.`);
|
||||
}
|
||||
if (value) {
|
||||
effectiveArgv.push(`--${name}`);
|
||||
} else if (flag.allowNo) {
|
||||
effectiveArgv.push(`--no-${name}`);
|
||||
}
|
||||
} else {
|
||||
const items = Array.isArray(value) ? value : [value];
|
||||
if (Array.isArray(value) && !flag.multiple) {
|
||||
throw new Error(`Start setting "${name}" does not accept multiple values.`);
|
||||
}
|
||||
for (const item of items) {
|
||||
if (typeof item !== 'string' && typeof item !== 'number') {
|
||||
throw new Error(`Start setting "${name}" must contain a string or number.`);
|
||||
}
|
||||
effectiveArgv.push(`--${name}=${item}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
await preflightControlConfigFilesAsync(config);
|
||||
return { argv: effectiveArgv, config };
|
||||
}
|
||||
@@ -1,28 +0,0 @@
|
||||
import {
|
||||
ControlConfigProgress,
|
||||
ControlConfigResult,
|
||||
executeControlConfigAsync,
|
||||
prepareControlConfigAsync,
|
||||
} from './controlConfig';
|
||||
import { connectHostActionsAsync, fetchHostActionCatalogAsync } from './hostActions';
|
||||
import { SimulatorSessionConfig } from './sessionConfig';
|
||||
import { PreviewApiAccess } from './utils';
|
||||
|
||||
export async function applyStartConfigAsync(
|
||||
access: PreviewApiAccess,
|
||||
config: SimulatorSessionConfig,
|
||||
{
|
||||
signal,
|
||||
onProgress,
|
||||
}: { signal: AbortSignal; onProgress?: (progress: ControlConfigProgress) => void }
|
||||
): Promise<ControlConfigResult[]> {
|
||||
const connection = await connectHostActionsAsync(access, { signal });
|
||||
try {
|
||||
const catalog = await fetchHostActionCatalogAsync(connection);
|
||||
const prepared = await prepareControlConfigAsync(catalog, config.path, connection.udid, config);
|
||||
signal.throwIfAborted();
|
||||
return await executeControlConfigAsync(connection, prepared, { onProgress });
|
||||
} finally {
|
||||
connection.close();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,9 @@
|
||||
# @expo/eas-json
|
||||
|
||||
## 27.2.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
## 27.1.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/eas-json",
|
||||
"version": "27.1.0",
|
||||
"version": "27.2.0",
|
||||
"description": "A library for interacting with eas.json",
|
||||
"homepage": "https://github.com/expo/eas-cli",
|
||||
"bugs": "https://github.com/expo/eas-cli/issues",
|
||||
@@ -32,7 +32,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "7.23.5",
|
||||
"@expo/eas-build-job": "27.1.0",
|
||||
"@expo/eas-build-job": "27.2.0",
|
||||
"chalk": "4.1.2",
|
||||
"env-string": "1.0.1",
|
||||
"fs-extra": "11.2.0",
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
# eas-cli-local-build-plugin
|
||||
|
||||
## 27.2.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
## 27.1.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "eas-cli-local-build-plugin",
|
||||
"version": "27.1.0",
|
||||
"version": "27.2.0",
|
||||
"description": "Tool for running EAS compatible builds on a local machine.",
|
||||
"bugs": "https://github.com/expo/eas-cli/issues",
|
||||
"license": "BUSL-1.1",
|
||||
@@ -26,12 +26,12 @@
|
||||
"clean": "rimraf node_modules dist coverage \"*.tsbuildinfo\""
|
||||
},
|
||||
"dependencies": {
|
||||
"@expo/build-tools": "27.1.0",
|
||||
"@expo/build-tools": "27.2.0",
|
||||
"@expo/bunyan": "^4.0.1",
|
||||
"@expo/eas-build-job": "27.1.0",
|
||||
"@expo/logger": "27.1.0",
|
||||
"@expo/eas-build-job": "27.2.0",
|
||||
"@expo/logger": "27.2.0",
|
||||
"@expo/spawn-async": "^1.7.2",
|
||||
"@expo/turtle-spawn": "27.1.0",
|
||||
"@expo/turtle-spawn": "27.2.0",
|
||||
"chalk": "4.1.2",
|
||||
"env-paths": "^2.2.1",
|
||||
"fs-extra": "^11.2.0",
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
# @expo/logger
|
||||
|
||||
## 27.2.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
## 27.1.0
|
||||
|
||||
No changes in this release.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/logger",
|
||||
"version": "27.1.0",
|
||||
"version": "27.2.0",
|
||||
"bugs": "https://github.com/expo/eas-cli/issues",
|
||||
"license": "BUSL-1.1",
|
||||
"author": "Expo <[email protected]>",
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
# @expo/simulator-launcher
|
||||
|
||||
## 27.2.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- Accept a comma-separated list of warm Simulators in `EXPO_SIMULATOR_DEVICE`; the first is the default. One serve-sim serves every listed device on one port. After the default device is ready, warmup preinstalls the latest stable Expo Go from one download and tries to disable apsd on the other devices, until a job claims one. A claim can select any listed device and reports its preinstalled Expo Go. ([#4764](https://github.com/expo/eas-cli/pull/4764) by [@gwdp](https://github.com/gwdp))
|
||||
- Add `@expo/simulator-launcher`, which warms an iOS Simulator at VM boot and hands it to one EAS job (`start`, `claim`, `prepare-tools`, `stop`). ([#4722](https://github.com/expo/eas-cli/pull/4722) by [@gwdp](https://github.com/gwdp))
|
||||
@@ -0,0 +1,80 @@
|
||||
# @expo/simulator-launcher
|
||||
|
||||
Warm iOS Simulators before an EAS job arrives. Requires macOS.
|
||||
The image installs vm-tools and writes its startup script at
|
||||
`/usr/local/share/vm-tools/startup.sh`:
|
||||
|
||||
```sh
|
||||
export EXPO_SIMULATOR_STARTUP=1
|
||||
export EXPO_SIMULATOR_DEVICE="iPhone Duo,iPhone 18"
|
||||
exec bunx @expo/simulator-launcher@latest start
|
||||
```
|
||||
|
||||
## Commands
|
||||
|
||||
- `start`: run one orphan serve-sim for the configured devices. Its default device becomes ready
|
||||
first; additional devices warm in the background. Argent and agent-device prestart on the default.
|
||||
- `claim ENGINE [DEVICE]`: reserve one job and return its selected device plus the existing server's
|
||||
identity, port and credentials. Engines: `serve-sim`, `agent-device`, `argent`.
|
||||
No DEVICE means the first configured device. Claim does not boot the selected device or wait for
|
||||
its tool. Build-tools privately adopts that device on the existing serve-sim port.
|
||||
- `prepare-tools`: continue the consumed claim after adoption. Keep global Argent, reuse the default
|
||||
agent-device runner or prepare a runner for the selected device.
|
||||
- `stop`: permanently end warmup for this boot and wait for all owned resources to be cleaned up.
|
||||
|
||||
```sh
|
||||
# Build-tools reads LAUNCHER_VERSION from the version recorded by start.
|
||||
bun x --no-install "@expo/simulator-launcher@$LAUNCHER_VERSION" claim serve-sim
|
||||
# After private serve-sim adoption confirms the selected device and native ACK:
|
||||
bun x --no-install "@expo/simulator-launcher@$LAUNCHER_VERSION" prepare-tools
|
||||
bun x --no-install "@expo/simulator-launcher@$LAUNCHER_VERSION" stop
|
||||
```
|
||||
|
||||
There is no copied launcher bundle. Build-tools uses the recorded package version for claim/stop;
|
||||
Warmup primes Bun’s exact-version cache before ready, with two attempts of up to 30 seconds. Its claim/stop calls use `--no-install`, retrying
|
||||
once with the registry only when Bun cannot find that cached binary. Priming failures warn.
|
||||
Before start has run,
|
||||
stop uses the normal package-manager path and still disables later warmup for this boot.
|
||||
|
||||
This flow requires the serve-sim release supporting port-based device adoption.
|
||||
|
||||
One durable state file, `/tmp/expo-simulator-startup.json`, holds the lifecycle, launcher version,
|
||||
selected device, server credentials, claim and native identity. It is independent of HOME/TMPDIR. A short boot-scoped lock
|
||||
serializes updates; an abandoned lock fails closed. This private format requires a fresh VM.
|
||||
|
||||
## Environment
|
||||
|
||||
- `EXPO_SIMULATOR_STARTUP=1` enables warmup.
|
||||
- `EXPO_SIMULATOR_PREINSTALL_EXPO_GO=0` turns off the Expo Go preinstall.
|
||||
- `EXPO_SIMULATOR_DEVICE` is a comma-separated list of exact device names or UDIDs. Entries are
|
||||
trimmed and must each identify one available device. The first is the default. Unset keeps
|
||||
the shortest available iPhone name, as does an empty or blank value. Empty list entries, missing,
|
||||
ambiguous or duplicate devices fail clearly.
|
||||
- `SERVE_SIM_VERSION`, `AGENT_DEVICE_VERSION`, `ARGENT_VERSION`: each defaults to `latest`.
|
||||
- `AGENT_DEVICE_STATE_DIR`, `ARGENT_EVENT_LOG`: tool state/output locations.
|
||||
- Agent-device idle timers default to off. Override with `AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS`
|
||||
and `AGENT_DEVICE_IOS_RUNNER_IDLE_STOP_MS` (milliseconds).
|
||||
|
||||
## Boundaries
|
||||
|
||||
- Ready means the default device booted and serve-sim answers. The apsd step and the Expo Go
|
||||
preinstall run in the background on every listed device. A claim does not wait for them; stop
|
||||
joins them.
|
||||
The second device may not have started yet. Its startup failure leaves the default available.
|
||||
Claim reserves a device; it does not report that device ready. Private adoption must confirm
|
||||
the same server PID/port, selected-device readiness and native video/capture before tool setup
|
||||
and app actions. Job-time version and authentication checks remain authoritative.
|
||||
- Agent-device prestarts on the default device only. A secondary claim prepares its runner after
|
||||
adoption and old-runner cleanup finish. One device-independent Argent server is reused for the claimed device.
|
||||
- Warmup downloads/extracts the latest stable Expo Go once and reuses it for the second device.
|
||||
Each initial device gets a preinstall attempt; ordinary failures warn. Claim prevents new
|
||||
preinstalls. `prepare-tools` waits for an install still running on the claimed device and
|
||||
reports its version, because the job installs its app next. Installs on other devices continue;
|
||||
adoption may shut such a device down, and its install then fails with a warning. Terminal stop
|
||||
drains them and the download cleanup. Job app installs remain
|
||||
authoritative. Replacements do not preinstall again. The VM image provides ffmpeg.
|
||||
- One start attempt and one accepted claim per boot. Failed cleanup never permits another session.
|
||||
Stop's caller timeout is not a global cleanup deadline or proof that teardown completed.
|
||||
A build-tools claim timeout uses normal startup only after confirmed terminal cleanup.
|
||||
|
||||
Claim and tool JSON include credentials; capture them rather than streaming them to job logs.
|
||||
+2
@@ -0,0 +1,2 @@
|
||||
#!/usr/bin/env node
|
||||
require('../dist/index').runCliAsync();
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { Config } from '@jest/types';
|
||||
|
||||
import baseConfig from '../../jest/jest.shared.config';
|
||||
|
||||
const config: Config.InitialOptions = {
|
||||
...baseConfig,
|
||||
rootDir: 'src',
|
||||
testMatch: ['**/__tests__/*.test.ts'],
|
||||
setupFiles: ['<rootDir>/__tests__/fixturePids.ts'],
|
||||
clearMocks: true,
|
||||
};
|
||||
|
||||
export default config;
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "@expo/simulator-launcher",
|
||||
"version": "27.2.0",
|
||||
"description": "Launch and claim Simulator sessions on EAS workers",
|
||||
"bugs": "https://github.com/expo/eas-cli/issues",
|
||||
"license": "BUSL-1.1",
|
||||
"author": "Expo <[email protected]>",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/expo/eas-cli.git",
|
||||
"directory": "packages/simulator-launcher"
|
||||
},
|
||||
"bin": "bin/simulator-launcher",
|
||||
"files": [
|
||||
"bin",
|
||||
"dist/index.js"
|
||||
],
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "jest --config jest.config.ts",
|
||||
"build": "ncc build src/main.ts -o dist --no-cache --no-source-map-register",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"prepack": "yarn build",
|
||||
"rebuild": "yarn build"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/jest": "^29.5.12",
|
||||
"@types/node": "22.20.5",
|
||||
"@vercel/ncc": "^0.38.1",
|
||||
"jest": "^29.7.0",
|
||||
"ts-jest": "^29.4.12",
|
||||
"typescript": "^6.0.3",
|
||||
"zod": "^4.3.5"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import { type ChildProcess } from 'node:child_process';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import fs from 'node:fs/promises';
|
||||
|
||||
import { createArgentTool } from '../utils/argent';
|
||||
import {
|
||||
commands,
|
||||
isProcessOwnedByServiceAsync,
|
||||
stopProcessAndDescendantsAsync,
|
||||
} from '../utils/processes';
|
||||
import { type WarmTool } from '../utils/tools';
|
||||
import { deferred, until } from './helpers';
|
||||
|
||||
jest.mock('node:fs/promises');
|
||||
jest.mock('../utils/processes');
|
||||
let child: ChildProcess;
|
||||
let result: ReturnType<typeof deferred<string>>;
|
||||
let controller: AbortController;
|
||||
let onFailure: jest.Mock;
|
||||
let tool: WarmTool;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
child = Object.assign(new EventEmitter(), {
|
||||
pid: 90001,
|
||||
exitCode: null,
|
||||
signalCode: null,
|
||||
}) as ChildProcess;
|
||||
result = deferred<string>();
|
||||
void result.promise.catch(() => {});
|
||||
controller = new AbortController();
|
||||
onFailure = jest.fn();
|
||||
// The old factory ignores this callback; its start also resolves without readiness.
|
||||
const createTool: (onFailure: (error: unknown) => void) => WarmTool = createArgentTool;
|
||||
tool = createTool(onFailure);
|
||||
jest.mocked(commands.start).mockReturnValue({ child, resultPromise: result.promise });
|
||||
jest.mocked(isProcessOwnedByServiceAsync).mockResolvedValue(true);
|
||||
jest.mocked(fs.readdir).mockResolvedValue(['tool-server.json'] as never);
|
||||
jest
|
||||
.mocked(fs.readFile)
|
||||
.mockResolvedValue(JSON.stringify({ pid: 90001, port: 3201, token: 'fixture-token' }));
|
||||
jest.spyOn(global, 'fetch').mockResolvedValue(new Response(JSON.stringify({ tools: [] })));
|
||||
jest.mocked(stopProcessAndDescendantsAsync).mockResolvedValue();
|
||||
});
|
||||
afterEach(() => {
|
||||
controller.abort();
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('does not report ready until its owned server answers the authenticated tools request', async () => {
|
||||
const response = deferred<Response>();
|
||||
jest.mocked(fetch).mockReturnValue(response.promise);
|
||||
let ready = false;
|
||||
const started = tool.startAsync('PHONE', controller.signal).then(() => {
|
||||
ready = true;
|
||||
});
|
||||
await until(() => jest.mocked(fetch).mock.calls.length > 0 || ready);
|
||||
expect(ready).toBe(false);
|
||||
response.resolve(new Response(JSON.stringify({ tools: [] })));
|
||||
await started;
|
||||
expect(commands.start).toHaveBeenCalledWith('bunx', expect.arrayContaining(['server', 'start']), {
|
||||
detached: true,
|
||||
});
|
||||
expect(fetch).toHaveBeenCalledWith('http://127.0.0.1:3201/tools', {
|
||||
headers: { Authorization: 'Bearer fixture-token' },
|
||||
signal: expect.any(AbortSignal),
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects an exit during the readiness request, even before the wrapper finishes closing', async () => {
|
||||
const response = deferred<Response>();
|
||||
jest.mocked(fetch).mockReturnValue(response.promise);
|
||||
const started = tool.startAsync('PHONE', controller.signal);
|
||||
await until(() => jest.mocked(fetch).mock.calls.length > 0);
|
||||
Object.assign(child, { exitCode: 1 });
|
||||
child.emit('exit', 1, null);
|
||||
response.resolve(new Response(JSON.stringify({ tools: [] })));
|
||||
await expect(started).rejects.toThrow('Argent exited before its server became ready');
|
||||
expect(onFailure).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('observes an unexpected exit after readiness exactly once', async () => {
|
||||
await tool.startAsync('PHONE', controller.signal);
|
||||
child.emit('exit', 1, null);
|
||||
result.reject(new Error('wrapper failed'));
|
||||
await Promise.resolve();
|
||||
expect(onFailure).toHaveBeenCalledTimes(1);
|
||||
expect(onFailure.mock.calls[0][0].message).toContain('Argent server exited unexpectedly');
|
||||
});
|
||||
|
||||
it('ignores a foreign state file without sending its token to the local port', async () => {
|
||||
jest.mocked(isProcessOwnedByServiceAsync).mockResolvedValue(false);
|
||||
const started = tool.startAsync('PHONE', controller.signal).catch(error => error);
|
||||
await until(() => jest.mocked(isProcessOwnedByServiceAsync).mock.calls.length > 0);
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
controller.abort(new Error('cancelled'));
|
||||
expect((await started).code).toBe('ABORT_ERR');
|
||||
});
|
||||
|
||||
it('retries an invalid tools response and does not notify for intentional stop', async () => {
|
||||
jest
|
||||
.mocked(fetch)
|
||||
.mockResolvedValueOnce(new Response('{}'))
|
||||
.mockImplementation(async () => new Response(JSON.stringify({ tools: [] })));
|
||||
await tool.startAsync('PHONE', controller.signal);
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
jest.mocked(stopProcessAndDescendantsAsync).mockImplementation(async () => {
|
||||
child.emit('exit', 0, null);
|
||||
});
|
||||
await tool.stopAsync();
|
||||
expect(onFailure).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not notify for cancelled tool teardown', async () => {
|
||||
await tool.startAsync('PHONE', controller.signal);
|
||||
controller.abort();
|
||||
child.emit('exit', 0, null);
|
||||
expect(onFailure).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('never publishes ready when cancellation arrives during the tools request', async () => {
|
||||
const response = deferred<Response>();
|
||||
jest.mocked(fetch).mockReturnValue(response.promise);
|
||||
const started = tool.startAsync('PHONE', controller.signal);
|
||||
await until(() => jest.mocked(fetch).mock.calls.length > 0);
|
||||
controller.abort(new Error('cancelled'));
|
||||
response.resolve(new Response(JSON.stringify({ tools: [] })));
|
||||
await expect(started).rejects.toThrow('cancelled');
|
||||
expect(onFailure).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('bounds readiness when the server never becomes available', async () => {
|
||||
const now = Date.now();
|
||||
jest
|
||||
.spyOn(Date, 'now')
|
||||
.mockReturnValueOnce(now)
|
||||
.mockReturnValue(now + 120_000);
|
||||
await expect(tool.startAsync('PHONE', controller.signal)).rejects.toThrow(
|
||||
'Timed out waiting for the Argent server'
|
||||
);
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('retries missing or incomplete state and transient HTTP failures before becoming ready', async () => {
|
||||
jest
|
||||
.mocked(fs.readdir)
|
||||
.mockRejectedValueOnce(
|
||||
Object.assign(new Error('state directory not written yet'), { code: 'ENOENT' })
|
||||
)
|
||||
.mockResolvedValue(['events.jsonl', 'tool-server-old.json', 'tool-server.json'] as never);
|
||||
jest
|
||||
.mocked(fs.readFile)
|
||||
.mockRejectedValueOnce(new Error('state disappeared during startup'))
|
||||
.mockResolvedValue(JSON.stringify({ pid: 90001, port: 3201, token: 'fixture-token' }));
|
||||
jest
|
||||
.mocked(fetch)
|
||||
.mockRejectedValueOnce(new Error('connection refused'))
|
||||
.mockResolvedValueOnce(new Response('unauthorized', { status: 401 }))
|
||||
.mockImplementation(async () => new Response(JSON.stringify({ tools: [] })));
|
||||
await tool.startAsync('PHONE', controller.signal);
|
||||
expect(fs.readdir).toHaveBeenCalledTimes(3);
|
||||
expect(fetch).toHaveBeenCalledTimes(3);
|
||||
expect(onFailure).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a successful wrapper exit while no state directory is available', async () => {
|
||||
jest.mocked(fs.readdir).mockImplementation(async () => {
|
||||
result.resolve('');
|
||||
throw new Error('state directory unavailable');
|
||||
});
|
||||
await expect(tool.startAsync('PHONE', controller.signal)).rejects.toThrow(
|
||||
'Argent exited before its server became ready'
|
||||
);
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
expect(onFailure).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects an exit during the final ownership check before publishing readiness', async () => {
|
||||
const owned = deferred<boolean>();
|
||||
jest
|
||||
.mocked(isProcessOwnedByServiceAsync)
|
||||
.mockResolvedValueOnce(true)
|
||||
.mockReturnValue(owned.promise);
|
||||
const started = tool.startAsync('PHONE', controller.signal);
|
||||
await until(() => jest.mocked(isProcessOwnedByServiceAsync).mock.calls.length === 2);
|
||||
child.emit('error', new Error('server failed during validation'));
|
||||
owned.resolve(true);
|
||||
await expect(started).rejects.toThrow('Argent exited before its server became ready');
|
||||
expect(onFailure).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
import { commands } from '../utils/processes';
|
||||
import { startOwnedWrapperAsync } from './fixtures/ownedWrapper';
|
||||
|
||||
it('an early claim survives unused-tool wrapper exit while the selected server and Simulator stay owned', async () => {
|
||||
const fixture = await startOwnedWrapperAsync();
|
||||
const environment = { ...process.env };
|
||||
let session:
|
||||
| ReturnType<typeof import('../commands/start').createWarmSimulatorSession>
|
||||
| undefined;
|
||||
try {
|
||||
const { createWarmSimulatorSession } = await import('../commands/start');
|
||||
const simulator = await import('../utils/simulator');
|
||||
const serveSim = await import('../utils/serveSim');
|
||||
const processes = await import('../utils/processes');
|
||||
const agentDevice = await import('../utils/agentDevice');
|
||||
const argent = await import('../utils/argent');
|
||||
const expoGo = await import('../utils/expoGo');
|
||||
const controller = new AbortController();
|
||||
const running = commands.runAsync.bind(commands);
|
||||
process.env.EXPO_SIMULATOR_DEVICE = 'DUO';
|
||||
process.env.AGENT_DEVICE_STATE_DIR = '/owned-wrapper-fixture/agent';
|
||||
process.env.ARGENT_EVENT_LOG = '/owned-wrapper-fixture/argent-events';
|
||||
jest
|
||||
.spyOn(commands, 'runAsync')
|
||||
.mockImplementation((file, args, signal) =>
|
||||
file === 'bun' || (file === 'ps' && args[1] === String(process.pid))
|
||||
? Promise.resolve('controller-start')
|
||||
: running(file, args, signal)
|
||||
);
|
||||
jest
|
||||
.spyOn(simulator, 'listAvailableSimulatorsAsync')
|
||||
.mockResolvedValue([{ udid: 'DUO', name: 'iPhone Duo' }]);
|
||||
jest.spyOn(simulator, 'waitForSimulatorBootAsync').mockResolvedValue();
|
||||
jest.spyOn(simulator, 'disableApsdAsync').mockResolvedValue();
|
||||
const shutdown = jest.spyOn(simulator, 'shutdownSimulatorAsync').mockResolvedValue();
|
||||
const stopServer = jest.spyOn(processes, 'stopProcessAndDescendantsAsync').mockResolvedValue();
|
||||
jest.spyOn(agentDevice, 'createAgentDeviceTool').mockReturnValue({
|
||||
name: 'agent-device',
|
||||
startAsync: async () => {},
|
||||
stopAsync: fixture.stopAsync,
|
||||
});
|
||||
jest
|
||||
.spyOn(argent, 'createArgentTool')
|
||||
.mockReturnValue({ name: 'argent', startAsync: async () => {}, stopAsync: async () => {} });
|
||||
jest.spyOn(expoGo, 'startExpoGoPreinstall').mockReturnValue({
|
||||
preinstallOnDeviceAsync: async () => {},
|
||||
claimAsync: async () => undefined,
|
||||
stopAsync: async () => {},
|
||||
});
|
||||
jest.spyOn(serveSim, 'startServeSim').mockReturnValue({
|
||||
child: { pid: 90001 } as import('node:child_process').ChildProcess,
|
||||
resultPromise: new Promise(() => {}),
|
||||
});
|
||||
jest.spyOn(serveSim, 'waitForServeSimReadyAsync').mockResolvedValue({
|
||||
startupDevice: 'DUO',
|
||||
pid: 90001,
|
||||
nativeStartTime: 'fixture-start',
|
||||
port: 3200,
|
||||
url: 'http://127.0.0.1:3200',
|
||||
token: 'fixture-token',
|
||||
});
|
||||
const onFailure = jest.fn(error => controller.abort(error));
|
||||
session = createWarmSimulatorSession({
|
||||
signal: controller.signal,
|
||||
throwIfStoppingAsync: async () => controller.signal.throwIfAborted(),
|
||||
onPreparationFailure: onFailure,
|
||||
});
|
||||
await session.prepareAsync();
|
||||
expect(await session.claimAsync({ engine: 'serve-sim' })).toMatchObject({
|
||||
device: { udid: 'DUO' },
|
||||
});
|
||||
await session.prepareToolsAsync();
|
||||
await fixture.stopAsync();
|
||||
expect(fixture.job.child.exitCode).toBe(23);
|
||||
expect(onFailure).not.toHaveBeenCalled();
|
||||
expect(controller.signal.aborted).toBe(false);
|
||||
expect(stopServer).not.toHaveBeenCalled();
|
||||
expect(shutdown).not.toHaveBeenCalled();
|
||||
await session.stopAsync();
|
||||
expect(shutdown).toHaveBeenCalledWith('DUO');
|
||||
} finally {
|
||||
await session?.stopAsync().catch(() => {});
|
||||
jest.restoreAllMocks();
|
||||
process.env = environment;
|
||||
await fixture.cleanupAsync();
|
||||
}
|
||||
}, 10_000);
|
||||
@@ -0,0 +1,636 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import { gzipSync } from 'node:zlib';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { startExpoGoPreinstall } from '../utils/expoGo';
|
||||
import { commands } from '../utils/processes';
|
||||
import { deferred, until } from './helpers';
|
||||
|
||||
const runCommandAsync = commands.runAsync.bind(commands);
|
||||
function createArchive(entries: { name: string; contents: Buffer }[]): Buffer {
|
||||
const blocks: Buffer[] = [];
|
||||
for (const { name, contents } of entries) {
|
||||
const header = Buffer.alloc(512);
|
||||
header.write(name);
|
||||
header.write('0000644\0', 100);
|
||||
header.write(contents.length.toString(8).padStart(11, '0') + '\0', 124);
|
||||
header.fill(32, 148, 156);
|
||||
header.write('0', 156);
|
||||
const checksum = header.reduce((sum, byte) => sum + byte, 0);
|
||||
header.write(checksum.toString(8).padStart(6, '0') + '\0 ', 148);
|
||||
blocks.push(header, contents, Buffer.alloc((512 - (contents.length % 512)) % 512));
|
||||
}
|
||||
return gzipSync(Buffer.concat([...blocks, Buffer.alloc(1024)]));
|
||||
}
|
||||
function installCalls() {
|
||||
return jest.mocked(commands.runAsync).mock.calls.filter(([file]) => file === 'xcrun');
|
||||
}
|
||||
|
||||
let directory: string;
|
||||
let archive: Buffer;
|
||||
let controller: AbortController;
|
||||
let warmup: ReturnType<typeof startOn> | undefined;
|
||||
const stableUrl = 'https://example.test/Expo-Go-stable.tar.gz';
|
||||
const sdkVersions = {
|
||||
'57.0.0': {
|
||||
releaseNoteUrl: 'https://example.test/57',
|
||||
iosClientUrl: 'https://example.test/old.tar.gz',
|
||||
},
|
||||
'58.0.0': { releaseNoteUrl: 'https://example.test/58', iosClientUrl: stableUrl },
|
||||
'59.0.0': {
|
||||
isBeta: true,
|
||||
releaseNoteUrl: 'https://example.test/beta',
|
||||
iosClientUrl: 'https://example.test/beta.tar.gz',
|
||||
},
|
||||
'60.0.0': { iosClientUrl: 'https://example.test/canary.tar.gz' },
|
||||
'61.1.0': {
|
||||
releaseNoteUrl: 'https://example.test/not-published',
|
||||
iosClientUrl: 'https://example.test/not-published.tar.gz',
|
||||
},
|
||||
};
|
||||
|
||||
/** Starts the shared download and preinstalls on one device, as warmup does for each device. */
|
||||
function startOn(udid: string, boot: Promise<unknown>) {
|
||||
const preinstall = startExpoGoPreinstall(controller.signal);
|
||||
return {
|
||||
...preinstall,
|
||||
resultPromise: preinstall.preinstallOnDeviceAsync(udid, boot, controller.signal),
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
directory = await fs.mkdtemp(path.join(os.tmpdir(), 'expo-go-unit-'));
|
||||
archive = createArchive([
|
||||
{ name: 'Info.plist', contents: Buffer.from('<plist>fixture</plist>') },
|
||||
]);
|
||||
jest.spyOn(os, 'tmpdir').mockReturnValue(directory);
|
||||
jest
|
||||
.spyOn(global, 'fetch')
|
||||
.mockImplementation(async url =>
|
||||
url === 'https://api.expo.dev/v2/versions'
|
||||
? Response.json({ iosUrl: 'https://example.test/legacy.tar.gz', sdkVersions })
|
||||
: new Response(Uint8Array.from(archive))
|
||||
);
|
||||
jest
|
||||
.spyOn(commands, 'runAsync')
|
||||
.mockImplementation(async (file, args, signal) =>
|
||||
file === '/usr/bin/tar' ? await runCommandAsync(file, args, signal) : ''
|
||||
);
|
||||
jest.spyOn(commands, 'throwIfCommandCloseTimedOut').mockImplementation(() => {});
|
||||
jest.spyOn(process.stderr, 'write').mockReturnValue(true);
|
||||
controller = new AbortController();
|
||||
warmup = undefined;
|
||||
});
|
||||
afterEach(async () => {
|
||||
controller.abort();
|
||||
await warmup?.stopAsync('UDID').catch(() => {});
|
||||
jest.restoreAllMocks();
|
||||
await fs.rm(directory, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('uses the website stable release policy, extracts flat contents as .app and installs only after boot', async () => {
|
||||
const boot = deferred();
|
||||
warmup = startOn('UDID', boot.promise);
|
||||
try {
|
||||
await until(() => jest.mocked(fetch).mock.calls.length === 2);
|
||||
expect(fetch).toHaveBeenLastCalledWith(
|
||||
stableUrl,
|
||||
expect.objectContaining({
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
'User-Agent': 'expo-simulator-launcher',
|
||||
},
|
||||
})
|
||||
);
|
||||
expect(installCalls()).toHaveLength(0);
|
||||
boot.resolve();
|
||||
await warmup.resultPromise;
|
||||
expect(installCalls()).toHaveLength(1);
|
||||
const [file, args, signal] = installCalls()[0];
|
||||
expect(file).toBe('xcrun');
|
||||
expect(args.slice(0, 3)).toEqual(['simctl', 'install', 'UDID']);
|
||||
expect(path.basename(args[3])).toBe('ExpoGo.app');
|
||||
expect(signal).toBeUndefined(); // Never cancel an in-flight installd transaction through simctl.
|
||||
// The shared download stays until a claim or stop releases it; stop waits for the removal.
|
||||
expect((await fs.stat(path.dirname(args[3]))).isDirectory()).toBe(true);
|
||||
await warmup.stopAsync('UDID');
|
||||
await expect(fs.stat(path.dirname(args[3]))).rejects.toMatchObject({ code: 'ENOENT' });
|
||||
} finally {
|
||||
boot.resolve();
|
||||
}
|
||||
});
|
||||
|
||||
it('claim aborts a pending download without waiting for it, and a late fetch cannot install', async () => {
|
||||
const pending = deferred<Response>();
|
||||
jest.mocked(fetch).mockReturnValueOnce(pending.promise);
|
||||
warmup = startOn('UDID', Promise.resolve());
|
||||
try {
|
||||
await until(() => jest.mocked(fetch).mock.calls.length > 0);
|
||||
await warmup.claimAsync('UDID');
|
||||
expect(jest.mocked(fetch).mock.calls[0][1]?.signal?.aborted).toBe(true);
|
||||
pending.resolve(Response.json({ sdkVersions })); // Even an uncooperative late fetch cannot install.
|
||||
await warmup.stopAsync('UDID');
|
||||
expect(installCalls()).toHaveLength(0);
|
||||
expect(
|
||||
(await fs.readdir(directory)).filter(name => name.startsWith('simulator-expo-go-'))
|
||||
).toEqual([]);
|
||||
} finally {
|
||||
pending.resolve(Response.json({ sdkVersions }));
|
||||
}
|
||||
});
|
||||
|
||||
it('claim only waits for the native install; terminal stop also drains temporary-file cleanup', async () => {
|
||||
const installation = deferred<string>();
|
||||
const cleanup = deferred();
|
||||
const remove = fs.rm.bind(fs);
|
||||
let cleanupStarted = false;
|
||||
jest.spyOn(fs, 'rm').mockImplementation(async (file, options) => {
|
||||
cleanupStarted = true;
|
||||
await cleanup.promise;
|
||||
return await remove(file, options);
|
||||
});
|
||||
jest
|
||||
.mocked(commands.runAsync)
|
||||
.mockImplementation(async (file, args) =>
|
||||
file === '/usr/bin/tar' ? await runCommandAsync(file, args) : await installation.promise
|
||||
);
|
||||
warmup = startOn('UDID', Promise.resolve());
|
||||
try {
|
||||
await until(() => installCalls().length > 0);
|
||||
let claimed = false;
|
||||
const claiming = warmup.claimAsync('UDID').then(() => {
|
||||
claimed = true;
|
||||
});
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(claimed).toBe(false);
|
||||
installation.resolve('');
|
||||
await claiming;
|
||||
expect(claimed).toBe(true);
|
||||
await until(() => cleanupStarted);
|
||||
let stopped = false;
|
||||
const stopping = warmup.stopAsync('UDID').then(() => {
|
||||
stopped = true;
|
||||
});
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(stopped).toBe(false);
|
||||
cleanup.resolve();
|
||||
await stopping;
|
||||
} finally {
|
||||
installation.resolve('');
|
||||
cleanup.resolve();
|
||||
}
|
||||
});
|
||||
|
||||
it('claim during extraction returns without waiting but cannot begin an install afterward', async () => {
|
||||
const extraction = deferred();
|
||||
let extracting = false;
|
||||
jest.mocked(commands.runAsync).mockImplementation(async (file, args) => {
|
||||
expect(file).toBe('/usr/bin/tar');
|
||||
extracting = true;
|
||||
await extraction.promise;
|
||||
return await runCommandAsync(file, args);
|
||||
});
|
||||
warmup = startOn('UDID', Promise.resolve());
|
||||
try {
|
||||
await until(() => extracting);
|
||||
await warmup.claimAsync('UDID');
|
||||
expect(installCalls()).toHaveLength(0);
|
||||
let stopped = false;
|
||||
const stopping = warmup.stopAsync('UDID').then(() => {
|
||||
stopped = true;
|
||||
});
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(stopped).toBe(false);
|
||||
extraction.resolve();
|
||||
await stopping;
|
||||
expect(installCalls()).toHaveLength(0);
|
||||
} finally {
|
||||
extraction.resolve();
|
||||
}
|
||||
});
|
||||
|
||||
it.each(['metadata', 'archive', 'install'])(
|
||||
'warns on an ordinary %s failure without failing warmup',
|
||||
async phase => {
|
||||
if (phase === 'metadata') {
|
||||
jest.mocked(fetch).mockResolvedValueOnce(new Response('', { status: 403 }));
|
||||
}
|
||||
if (phase === 'archive') {
|
||||
jest
|
||||
.mocked(fetch)
|
||||
.mockResolvedValueOnce(Response.json({ sdkVersions }))
|
||||
.mockResolvedValueOnce(new Response('', { status: 503 }));
|
||||
}
|
||||
if (phase === 'install') {
|
||||
jest.mocked(commands.runAsync).mockImplementation(async (file, args) => {
|
||||
if (file === '/usr/bin/tar') {
|
||||
return await runCommandAsync(file, args);
|
||||
}
|
||||
throw Object.assign(new Error('install failed'), { code: 1 });
|
||||
});
|
||||
}
|
||||
warmup = startOn('UDID', Promise.resolve());
|
||||
await warmup.resultPromise;
|
||||
await warmup.claimAsync('UDID');
|
||||
await warmup.stopAsync('UDID');
|
||||
expect(process.stderr.write).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Could not preinstall Expo Go')
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
it.each(['signal', 'close timeout', 'temp removal'])(
|
||||
'fails closed on %s instead of treating it as optional installation failure',
|
||||
async kind => {
|
||||
const error = Object.assign(new Error(`uncertain ${kind}`), {
|
||||
code: kind === 'signal' ? null : 1,
|
||||
});
|
||||
if (kind === 'temp removal') {
|
||||
jest.spyOn(fs, 'rm').mockRejectedValueOnce(error);
|
||||
} else {
|
||||
jest.mocked(commands.runAsync).mockImplementation(async (file, args) => {
|
||||
if (file === '/usr/bin/tar') {
|
||||
return await runCommandAsync(file, args);
|
||||
}
|
||||
if (kind === 'close timeout') {
|
||||
jest.mocked(commands.throwIfCommandCloseTimedOut).mockImplementation(() => {
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
});
|
||||
}
|
||||
warmup = startOn('UDID', Promise.resolve());
|
||||
await warmup.resultPromise.catch(() => {});
|
||||
// The claim does not wait for the removal; stop does, and never confirms a failed one.
|
||||
await warmup.claimAsync('UDID').catch(() => {});
|
||||
await expect(warmup.stopAsync('UDID')).rejects.toBe(error);
|
||||
}
|
||||
);
|
||||
|
||||
it.each(['valid', 'traversal', 'malformed'] as const)(
|
||||
'drains the real owned extractor for a %s archive before removing temp files or settling stop',
|
||||
async kind => {
|
||||
const contents = Buffer.alloc(4 * 1024 * 1024, 97);
|
||||
archive =
|
||||
kind === 'malformed'
|
||||
? Buffer.from('not a gzip or tar archive')
|
||||
: createArchive([
|
||||
...(kind === 'traversal'
|
||||
? [{ name: '../escaped', contents: Buffer.from('unsafe') }]
|
||||
: []),
|
||||
{ name: 'Info.plist', contents: Buffer.from('<plist>fixture</plist>') },
|
||||
{ name: 'ordinary-file', contents },
|
||||
]);
|
||||
const start = commands.start.bind(commands);
|
||||
let extractor: ReturnType<typeof commands.start> | undefined;
|
||||
let extractorClosed = false;
|
||||
const remove = fs.rm.bind(fs);
|
||||
const removing = jest.spyOn(fs, 'rm').mockImplementation(async (file, options) => {
|
||||
expect(extractorClosed).toBe(true);
|
||||
if (kind === 'traversal') {
|
||||
await expect(fs.access(path.join(String(file), 'escaped'))).rejects.toMatchObject({
|
||||
code: 'ENOENT',
|
||||
});
|
||||
}
|
||||
if (kind !== 'malformed') {
|
||||
expect(
|
||||
(await fs.readFile(path.join(String(file), 'ExpoGo.app', 'ordinary-file'))).equals(
|
||||
contents
|
||||
)
|
||||
).toBe(true);
|
||||
}
|
||||
return await remove(file, options);
|
||||
});
|
||||
jest.spyOn(commands, 'start').mockImplementation((file, args, options) => {
|
||||
expect(file).toBe('/usr/bin/tar');
|
||||
expect(args).toEqual([
|
||||
'-xzf',
|
||||
expect.stringMatching(/\/expo-go.tar.gz$/),
|
||||
'-C',
|
||||
expect.stringMatching(/\/ExpoGo.app$/),
|
||||
]);
|
||||
expect(options?.signal).toBeUndefined();
|
||||
extractor = start(file, args, options);
|
||||
extractor.child.once('close', () => {
|
||||
extractorClosed = true;
|
||||
});
|
||||
expect(extractor.child.kill('SIGSTOP')).toBe(true);
|
||||
return extractor;
|
||||
});
|
||||
warmup = startOn('UDID', Promise.resolve());
|
||||
try {
|
||||
await until(() => extractor !== undefined);
|
||||
await warmup.claimAsync('UDID'); // Only forbids new install; extraction remains owned and pending.
|
||||
expect(extractorClosed).toBe(false);
|
||||
let stopped = false;
|
||||
const stopping = warmup.stopAsync('UDID').then(() => {
|
||||
stopped = true;
|
||||
});
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(stopped).toBe(false);
|
||||
expect(removing).not.toHaveBeenCalled();
|
||||
extractor!.child.kill('SIGCONT');
|
||||
await stopping;
|
||||
expect(extractorClosed).toBe(true);
|
||||
expect(removing).toHaveBeenCalledTimes(1);
|
||||
expect(installCalls()).toHaveLength(0);
|
||||
expect(await fs.readdir(directory)).toEqual([]);
|
||||
if (kind !== 'valid') {
|
||||
const extractionError = await extractor!.resultPromise.catch(error => error);
|
||||
expect(extractionError.code).toBeGreaterThan(0);
|
||||
}
|
||||
} finally {
|
||||
// Reap only this test's owned child, including an assertion failure while it is stopped.
|
||||
if (extractor?.child.exitCode == null && extractor?.child.signalCode == null) {
|
||||
extractor?.child.kill('SIGCONT');
|
||||
extractor?.child.kill('SIGKILL');
|
||||
}
|
||||
await extractor?.resultPromise.catch(() => {});
|
||||
removing.mockRestore();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
it('keeps owned temp files and rejects terminal stop when extractor close is uncertain', async () => {
|
||||
const failure = new Error('extractor close not proved');
|
||||
const remove = jest.spyOn(fs, 'rm');
|
||||
jest.mocked(commands.runAsync).mockImplementationOnce(async file => {
|
||||
expect(file).toBe('/usr/bin/tar');
|
||||
jest.mocked(commands.throwIfCommandCloseTimedOut).mockImplementation(() => {
|
||||
throw failure;
|
||||
});
|
||||
throw failure;
|
||||
});
|
||||
warmup = startOn('UDID', Promise.resolve());
|
||||
await expect(warmup.resultPromise).rejects.toBe(failure);
|
||||
await expect(warmup.stopAsync('UDID')).rejects.toBe(failure);
|
||||
await expect(warmup.claimAsync('UDID')).rejects.toBe(failure);
|
||||
expect(remove).not.toHaveBeenCalled();
|
||||
expect((await fs.readdir(directory)).some(name => name.startsWith('simulator-expo-go-'))).toBe(
|
||||
true
|
||||
);
|
||||
expect(installCalls()).toHaveLength(0);
|
||||
});
|
||||
|
||||
it.each(['traversal', 'malformed'] as const)(
|
||||
'never installs after a real %s archive failure without a claim',
|
||||
async kind => {
|
||||
archive =
|
||||
kind === 'malformed'
|
||||
? Buffer.from('not an archive')
|
||||
: createArchive([
|
||||
{ name: '../escaped', contents: Buffer.from('unsafe') },
|
||||
{ name: 'Info.plist', contents: Buffer.from('<plist>fixture</plist>') },
|
||||
]);
|
||||
warmup = startOn('UDID', Promise.resolve());
|
||||
await warmup.resultPromise;
|
||||
expect(installCalls()).toHaveLength(0);
|
||||
expect(process.stderr.write).toHaveBeenCalledWith(
|
||||
expect.stringContaining('Could not preinstall Expo Go')
|
||||
);
|
||||
await warmup.stopAsync('UDID');
|
||||
expect(await fs.readdir(directory)).toEqual([]);
|
||||
}
|
||||
);
|
||||
|
||||
it('claim returns the identity read from the Expo Go it installed', async () => {
|
||||
const plist: Record<string, string> = {
|
||||
CFBundleIdentifier: 'host.exp.Exponent',
|
||||
CFBundleShortVersionString: '58.0.7',
|
||||
CFBundleVersion: '58.0.7',
|
||||
};
|
||||
jest
|
||||
.mocked(commands.runAsync)
|
||||
.mockImplementation(async (file, args, signal) =>
|
||||
file === '/usr/bin/tar'
|
||||
? await runCommandAsync(file, args, signal)
|
||||
: file === 'plutil'
|
||||
? `${plist[args[1]]}\n`
|
||||
: ''
|
||||
);
|
||||
warmup = startOn('UDID', Promise.resolve());
|
||||
await warmup.resultPromise;
|
||||
expect(await warmup.claimAsync('UDID')).toEqual({
|
||||
udid: 'UDID',
|
||||
bundleIdentifier: 'host.exp.Exponent',
|
||||
shortVersion: '58.0.7',
|
||||
version: '58.0.7',
|
||||
});
|
||||
const plistPath = jest
|
||||
.mocked(commands.runAsync)
|
||||
.mock.calls.find(([file]) => file === 'plutil')![1];
|
||||
expect(path.basename(path.dirname(plistPath[5]))).toBe('ExpoGo.app');
|
||||
});
|
||||
|
||||
it('claim returns no identity when the preinstall fails', async () => {
|
||||
jest
|
||||
.mocked(commands.runAsync)
|
||||
.mockImplementation(async (file, args, signal) =>
|
||||
file === '/usr/bin/tar'
|
||||
? await runCommandAsync(file, args, signal)
|
||||
: file === 'xcrun'
|
||||
? Promise.reject(Object.assign(new Error('install failed'), { code: 1 }))
|
||||
: ''
|
||||
);
|
||||
warmup = startOn('UDID', Promise.resolve());
|
||||
await warmup.resultPromise;
|
||||
expect(await warmup.claimAsync('UDID')).toBeUndefined();
|
||||
expect(jest.mocked(commands.runAsync).mock.calls.some(([file]) => file === 'plutil')).toBe(false);
|
||||
});
|
||||
|
||||
it('downloads and extracts once for two devices, then removes the shared app on stop', async () => {
|
||||
warmup = startOn('FIRST', Promise.resolve());
|
||||
await warmup.resultPromise;
|
||||
const app = installCalls()[0][1][3];
|
||||
expect((await fs.stat(app)).isDirectory()).toBe(true);
|
||||
await warmup.preinstallOnDeviceAsync('SECOND', Promise.resolve(), controller.signal);
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
expect(
|
||||
jest.mocked(commands.runAsync).mock.calls.filter(([file]) => file === '/usr/bin/tar')
|
||||
).toHaveLength(1);
|
||||
expect(installCalls().map(([, args]) => args.slice(2))).toEqual([
|
||||
['FIRST', app],
|
||||
['SECOND', app],
|
||||
]);
|
||||
const claimed = await warmup.claimAsync('SECOND');
|
||||
await warmup.stopAsync('SECOND');
|
||||
await expect(fs.stat(app)).rejects.toMatchObject({ code: 'ENOENT' });
|
||||
expect(claimed?.udid).toBe('SECOND');
|
||||
});
|
||||
it('a claim prevents secondary preinstall from starting and releases the retained archive', async () => {
|
||||
warmup = startOn('FIRST', Promise.resolve());
|
||||
await warmup.resultPromise;
|
||||
await warmup.claimAsync('FIRST');
|
||||
await warmup.preinstallOnDeviceAsync('SECOND', Promise.resolve(), controller.signal);
|
||||
await warmup.stopAsync('FIRST');
|
||||
expect(installCalls()).toHaveLength(1);
|
||||
expect(await fs.readdir(directory)).toEqual([]);
|
||||
});
|
||||
it('claim and stop drain a secondary native install without cancelling its transaction', async () => {
|
||||
const install = deferred<string>();
|
||||
const original = jest.mocked(commands.runAsync).getMockImplementation()!;
|
||||
warmup = startOn('FIRST', Promise.resolve());
|
||||
await warmup.resultPromise;
|
||||
jest
|
||||
.mocked(commands.runAsync)
|
||||
.mockImplementation((file, args, signal) =>
|
||||
file === 'xcrun' && args.includes('SECOND') ? install.promise : original(file, args, signal)
|
||||
);
|
||||
const secondary = warmup.preinstallOnDeviceAsync('SECOND', Promise.resolve(), controller.signal);
|
||||
let claimed = false;
|
||||
try {
|
||||
await until(() => installCalls().length === 2);
|
||||
const claiming = warmup.claimAsync('SECOND').then(() => {
|
||||
claimed = true;
|
||||
});
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(claimed).toBe(false);
|
||||
expect(installCalls()[1][2]).toBeUndefined();
|
||||
install.resolve('');
|
||||
await claiming;
|
||||
await secondary;
|
||||
await warmup.stopAsync('FIRST');
|
||||
expect(await fs.readdir(directory)).toEqual([]);
|
||||
} finally {
|
||||
install.resolve('');
|
||||
await secondary;
|
||||
}
|
||||
});
|
||||
|
||||
it.each(['signal', 'close timeout'])(
|
||||
'isolates a secondary %s failure from the already-installed default',
|
||||
async kind => {
|
||||
warmup = startOn('FIRST', Promise.resolve());
|
||||
await warmup.resultPromise;
|
||||
const failure = Object.assign(new Error('secondary install failed'), { code: null });
|
||||
const original = jest.mocked(commands.runAsync).getMockImplementation()!;
|
||||
jest.mocked(commands.runAsync).mockImplementation((file, args, signal) => {
|
||||
if (file === 'xcrun' && args.includes('SECOND')) {
|
||||
if (kind === 'close timeout') {
|
||||
jest.mocked(commands.throwIfCommandCloseTimedOut).mockImplementation(() => {
|
||||
throw failure;
|
||||
});
|
||||
}
|
||||
return Promise.reject(failure);
|
||||
}
|
||||
return original(file, args, signal);
|
||||
});
|
||||
await expect(
|
||||
warmup.preinstallOnDeviceAsync('SECOND', Promise.resolve(), controller.signal)
|
||||
).rejects.toBe(failure);
|
||||
expect((await warmup.claimAsync('FIRST'))?.udid).toBe('FIRST');
|
||||
await expect(warmup.claimAsync('SECOND')).rejects.toBe(failure);
|
||||
if (kind === 'close timeout') {
|
||||
await expect(warmup.stopAsync('FIRST')).rejects.toBe(failure);
|
||||
} else {
|
||||
await expect(warmup.stopAsync('FIRST')).resolves.toBeUndefined();
|
||||
}
|
||||
await expect(warmup.stopAsync('SECOND')).rejects.toBe(failure);
|
||||
}
|
||||
);
|
||||
it('a concurrent stop cannot miss a secondary install failure while shared cleanup drains', async () => {
|
||||
warmup = startOn('FIRST', Promise.resolve());
|
||||
await warmup.resultPromise;
|
||||
const installation = deferred<string>();
|
||||
const original = jest.mocked(commands.runAsync).getMockImplementation()!;
|
||||
jest
|
||||
.mocked(commands.runAsync)
|
||||
.mockImplementation((file, args, signal) =>
|
||||
file === 'xcrun' && args.includes('SECOND')
|
||||
? installation.promise
|
||||
: original(file, args, signal)
|
||||
);
|
||||
const secondary = warmup.preinstallOnDeviceAsync('SECOND', Promise.resolve(), controller.signal);
|
||||
void secondary.catch(() => {});
|
||||
try {
|
||||
await until(() => installCalls().length === 2);
|
||||
const stopping = warmup.stopAsync('SECOND');
|
||||
void stopping.catch(() => {});
|
||||
const failure = Object.assign(new Error('secondary killed'), { code: null });
|
||||
installation.reject(failure);
|
||||
await expect(stopping).rejects.toBe(failure);
|
||||
await expect(secondary).rejects.toBe(failure);
|
||||
} finally {
|
||||
installation.resolve('');
|
||||
await secondary.catch(() => {});
|
||||
}
|
||||
});
|
||||
|
||||
it('preinstalls all three configured devices from one shared archive through the session owner', async () => {
|
||||
const { createWarmSimulatorSession } = await import('../commands/start');
|
||||
const simulator = await import('../utils/simulator');
|
||||
const serveSim = await import('../utils/serveSim');
|
||||
const processes = await import('../utils/processes');
|
||||
const agentDevice = await import('../utils/agentDevice');
|
||||
const argent = await import('../utils/argent');
|
||||
const devices = ['FIRST', 'SECOND', 'THIRD'].map(udid => ({ udid, name: `iPhone ${udid}` }));
|
||||
const environment = { ...process.env };
|
||||
process.env.EXPO_SIMULATOR_DEVICE = devices.map(device => device.udid).join(',');
|
||||
process.env.AGENT_DEVICE_STATE_DIR = path.join(directory, 'agent');
|
||||
process.env.ARGENT_EVENT_LOG = path.join(directory, 'argent-events');
|
||||
jest.spyOn(simulator, 'listAvailableSimulatorsAsync').mockResolvedValue(devices);
|
||||
jest.spyOn(simulator, 'waitForSimulatorBootAsync').mockResolvedValue();
|
||||
jest.spyOn(simulator, 'disableApsdAsync').mockResolvedValue();
|
||||
jest.spyOn(simulator, 'shutdownSimulatorAsync').mockResolvedValue();
|
||||
jest.spyOn(processes, 'stopProcessAndDescendantsAsync').mockResolvedValue();
|
||||
jest.spyOn(agentDevice, 'createAgentDeviceTool').mockReturnValue({
|
||||
name: 'agent-device',
|
||||
startAsync: async () => {},
|
||||
stopAsync: async () => {},
|
||||
});
|
||||
jest
|
||||
.spyOn(argent, 'createArgentTool')
|
||||
.mockReturnValue({ name: 'argent', startAsync: async () => {}, stopAsync: async () => {} });
|
||||
jest.spyOn(serveSim, 'startServeSim').mockReturnValue({
|
||||
child: { pid: 90001 } as import('node:child_process').ChildProcess,
|
||||
resultPromise: new Promise(() => {}),
|
||||
});
|
||||
jest.spyOn(serveSim, 'waitForServeSimReadyAsync').mockResolvedValue({
|
||||
startupDevice: 'FIRST',
|
||||
pid: 90001,
|
||||
port: 3200,
|
||||
nativeStartTime: 'start-time',
|
||||
url: 'http://127.0.0.1:3200',
|
||||
token: 'fixture-token',
|
||||
});
|
||||
const original = jest.mocked(commands.runAsync).getMockImplementation()!;
|
||||
jest.mocked(commands.runAsync).mockImplementation(async (file, args, signal) => {
|
||||
if (file === 'ps') {
|
||||
return 'controller-start';
|
||||
}
|
||||
if (file === 'plutil') {
|
||||
return args.includes('CFBundleIdentifier') ? 'host.exp.Exponent' : '58.0.7';
|
||||
}
|
||||
return original(file, args, signal);
|
||||
});
|
||||
const onFailure = jest.fn();
|
||||
const session = createWarmSimulatorSession({
|
||||
signal: controller.signal,
|
||||
throwIfStoppingAsync: async () => controller.signal.throwIfAborted(),
|
||||
onPreparationFailure: onFailure,
|
||||
});
|
||||
try {
|
||||
await session.prepareAsync();
|
||||
await until(() => installCalls().length === 3);
|
||||
await session.claimAsync({ engine: 'serve-sim', requestedDevice: 'THIRD' });
|
||||
const prepared = await session.prepareToolsAsync();
|
||||
expect(prepared.preinstalledExpoGo).toEqual({
|
||||
udid: 'THIRD',
|
||||
bundleIdentifier: 'host.exp.Exponent',
|
||||
shortVersion: '58.0.7',
|
||||
version: '58.0.7',
|
||||
});
|
||||
expect(installCalls().map(([, args]) => args[2])).toEqual(['FIRST', 'SECOND', 'THIRD']);
|
||||
expect(new Set(installCalls().map(([, args]) => args[3])).size).toBe(1);
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
expect(
|
||||
jest.mocked(commands.runAsync).mock.calls.filter(([file]) => file === '/usr/bin/tar')
|
||||
).toHaveLength(1);
|
||||
expect(onFailure).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await session.stopAsync();
|
||||
process.env = environment;
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
// Test fixtures use these PIDs for fake child processes. Fail fast instead of letting a test
|
||||
// reach the real process.kill with one of them, where it could signal an unrelated process.
|
||||
const FIXTURE_PIDS = new Set([10, 11, 12, 20, 30, 40, 41]);
|
||||
const isFixturePid = (pid: number): boolean =>
|
||||
FIXTURE_PIDS.has(Math.abs(pid)) || (Math.abs(pid) >= 90000 && Math.abs(pid) < 90100);
|
||||
|
||||
const realKill = process.kill.bind(process);
|
||||
process.kill = ((pid: number, signal?: string | number) => {
|
||||
if (isFixturePid(pid)) {
|
||||
throw new Error(`A test tried to signal fixture PID ${pid} through the real process.kill.`);
|
||||
}
|
||||
return realKill(pid, signal);
|
||||
}) as typeof process.kill;
|
||||
@@ -0,0 +1,56 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { setTimeout as sleepAsync } from 'node:timers/promises';
|
||||
|
||||
import { commands, stopProcessAndDescendantsAsync } from '../../utils/processes';
|
||||
|
||||
export async function startOwnedWrapperAsync() {
|
||||
const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'launcher-owned-wrapper-'));
|
||||
const readyPath = path.join(directory, 'ready.json');
|
||||
const job = commands.start(
|
||||
process.execPath,
|
||||
[path.join(__dirname, 'stop-wrapper.cjs'), path.join(__dirname, 'stop-leaf.cjs'), readyPath],
|
||||
{ captureStdout: true, detached: true }
|
||||
);
|
||||
const realKill = process.kill.bind(process);
|
||||
const stop = stopProcessAndDescendantsAsync;
|
||||
let confirmed = false;
|
||||
let stopping: Promise<void> | undefined;
|
||||
const cleanupAsync = async () => {
|
||||
if (!confirmed && job.child.pid) {
|
||||
try {
|
||||
realKill(-job.child.pid, 'SIGKILL');
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ESRCH') throw error;
|
||||
}
|
||||
}
|
||||
await job.resultPromise.catch(() => {});
|
||||
await fs.rm(directory, { recursive: true, force: true });
|
||||
};
|
||||
try {
|
||||
let leaves: number[] = [];
|
||||
const deadline = Date.now() + 5_000;
|
||||
while (!leaves.length) {
|
||||
const ready = await fs.readFile(readyPath, 'utf8').catch(() => undefined);
|
||||
if (ready) leaves = JSON.parse(ready);
|
||||
else {
|
||||
if (Date.now() >= deadline) throw new Error('The disposable wrapper did not become ready.');
|
||||
await sleepAsync(10);
|
||||
}
|
||||
}
|
||||
return {
|
||||
job,
|
||||
leaves,
|
||||
realKill,
|
||||
cleanupAsync,
|
||||
stopAsync: () =>
|
||||
(stopping ??= stop(job).then(() => {
|
||||
confirmed = true;
|
||||
})),
|
||||
};
|
||||
} catch (error) {
|
||||
await cleanupAsync();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
process.on('SIGTERM', () => process.exit(23));
|
||||
setInterval(() => {}, 1000);
|
||||
process.send('ready');
|
||||
@@ -0,0 +1,20 @@
|
||||
const { spawn } = require('node:child_process');
|
||||
const fs = require('node:fs');
|
||||
const children = [0, 1].map(() =>
|
||||
spawn(process.execPath, [process.argv[2]], {
|
||||
stdio: ['ignore', 'inherit', 'inherit', 'ipc'],
|
||||
})
|
||||
);
|
||||
// Like a supervisor, forward parent termination and report the child's final status.
|
||||
process.on('SIGTERM', () => {
|
||||
for (const child of children) child.kill('SIGTERM');
|
||||
});
|
||||
let ready = 0;
|
||||
for (const child of children) {
|
||||
child.on('message', () => {
|
||||
if (++ready === children.length) {
|
||||
fs.writeFileSync(process.argv[3], JSON.stringify(children.map(child => child.pid)));
|
||||
}
|
||||
});
|
||||
child.on('exit', code => process.exit(code ?? 1));
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
export function deferred<T = void>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (error: unknown) => void;
|
||||
const promise = new Promise<T>((yes, no) => {
|
||||
resolve = yes;
|
||||
reject = no;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
|
||||
/** Polls `predicate` for up to 2 seconds, then asserts it. */
|
||||
export async function until(predicate: () => boolean): Promise<void> {
|
||||
for (let i = 0; i < 400 && !predicate(); i++) {
|
||||
await new Promise(resolve => setTimeout(resolve, 5));
|
||||
}
|
||||
expect(predicate()).toBe(true);
|
||||
}
|
||||
@@ -0,0 +1,475 @@
|
||||
import { type ChildProcess } from 'node:child_process';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { claimAsync, prepareToolsAsync } from '../commands/claim';
|
||||
import { runWarmSimulatorSessionAsync, startAsync } from '../commands/start';
|
||||
import { stopAsync } from '../commands/stop';
|
||||
import { mainAsync } from '../main';
|
||||
import { createArgentTool } from '../utils/argent';
|
||||
import { startExpoGoPreinstall } from '../utils/expoGo';
|
||||
import { type ChildProcessHandle, commands } from '../utils/processes';
|
||||
import * as processes from '../utils/processes';
|
||||
import * as serveSim from '../utils/serveSim';
|
||||
import { shutdownSimulatorAsync } from '../utils/simulator';
|
||||
import {
|
||||
LAUNCHER_STATE_FILE,
|
||||
readLauncherStateAsync,
|
||||
updateLauncherStateAsync,
|
||||
waitForLauncherStateAsync,
|
||||
} from '../utils/state';
|
||||
import { deferred, until } from './helpers';
|
||||
|
||||
jest.mock('../utils/expoGo');
|
||||
jest.mock('../utils/argent');
|
||||
const boot = 'boot-one';
|
||||
let root: string;
|
||||
let environment: NodeJS.ProcessEnv;
|
||||
let active: Promise<unknown>[];
|
||||
let jobs: ChildProcessHandle[];
|
||||
const platform = process.platform;
|
||||
const deviceList = {
|
||||
devices: {
|
||||
ios: [
|
||||
{ name: 'iPhone 17', udid: 'PHONE' },
|
||||
{ name: 'iPhone 17 Pro', udid: 'PRO' },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
const nativeFs = {
|
||||
readFile: fs.readFile.bind(fs),
|
||||
writeFile: fs.writeFile.bind(fs),
|
||||
rename: fs.rename.bind(fs),
|
||||
rm: fs.rm.bind(fs),
|
||||
mkdir: fs.mkdir.bind(fs),
|
||||
rmdir: fs.rmdir.bind(fs),
|
||||
stat: fs.stat.bind(fs),
|
||||
};
|
||||
const remap = (file: unknown): unknown =>
|
||||
typeof file === 'string' && file.startsWith(LAUNCHER_STATE_FILE)
|
||||
? path.join(root, 'control', path.basename(file))
|
||||
: file;
|
||||
|
||||
async function status(value: string) {
|
||||
return await waitForLauncherStateAsync(boot, state => state?.status === value, 2_000);
|
||||
}
|
||||
async function beginSession(): Promise<Promise<unknown>[]> {
|
||||
await updateLauncherStateAsync(boot, () => ({
|
||||
bootUuid: boot,
|
||||
status: 'starting',
|
||||
launcherVersion: require('../../package.json').version,
|
||||
controllerPid: process.pid,
|
||||
}));
|
||||
const completion = runWarmSimulatorSessionAsync(boot).catch(error => error);
|
||||
active.push(completion);
|
||||
return [completion];
|
||||
}
|
||||
beforeEach(async () => {
|
||||
root = await fs.mkdtemp(path.join(os.tmpdir(), 'launcher-session-'));
|
||||
jest.spyOn(os, 'homedir').mockReturnValue(root);
|
||||
await fs.mkdir(path.join(root, 'control'));
|
||||
await fs.mkdir(path.join(root, '.argent'));
|
||||
await fs.writeFile(
|
||||
path.join(root, '.argent/tool-server.json'),
|
||||
JSON.stringify({ pid: 90002, port: 3201, token: 'fixture-token' })
|
||||
);
|
||||
jest.spyOn(processes, 'isProcessOwnedByServiceAsync').mockResolvedValue(true);
|
||||
jest
|
||||
.spyOn(global, 'fetch')
|
||||
.mockImplementation(async () => new Response(JSON.stringify({ tools: [] })));
|
||||
for (const name of ['readFile', 'writeFile', 'rename', 'rm', 'mkdir', 'rmdir', 'stat'] as const) {
|
||||
jest.spyOn(fs, name).mockImplementation(((...args: unknown[]) => {
|
||||
args[0] = remap(args[0]);
|
||||
if (name === 'rename') {
|
||||
args[1] = remap(args[1]);
|
||||
}
|
||||
return (nativeFs[name] as (...args: unknown[]) => unknown)(...args);
|
||||
}) as never);
|
||||
}
|
||||
|
||||
Object.defineProperty(process, 'platform', { value: 'darwin' });
|
||||
environment = { ...process.env };
|
||||
process.env.EXPO_SIMULATOR_STARTUP = '1';
|
||||
process.env.ARGENT_EVENT_LOG = path.join(root, 'argent-events');
|
||||
active = [];
|
||||
jobs = [];
|
||||
jest
|
||||
.mocked(startExpoGoPreinstall)
|
||||
.mockReset()
|
||||
.mockReturnValue({
|
||||
preinstallOnDeviceAsync: jest.fn(async () => {}),
|
||||
claimAsync: jest.fn(async () => undefined),
|
||||
stopAsync: jest.fn(async () => {}),
|
||||
});
|
||||
jest.spyOn(commands, 'runAsync').mockImplementation(async (file, args) => {
|
||||
if (file === '/usr/sbin/sysctl') {
|
||||
return boot;
|
||||
}
|
||||
if (args.includes('lstart=')) {
|
||||
return 'Thu Oct 22 10:00:00 2026';
|
||||
}
|
||||
if (args.includes('devices')) {
|
||||
return JSON.stringify(deviceList);
|
||||
}
|
||||
if (args.includes('launchctl') && args.includes('list')) {
|
||||
throw Object.assign(new Error('apsd is not loaded'), { code: 113 });
|
||||
}
|
||||
return '';
|
||||
});
|
||||
jest.spyOn(commands, 'start').mockImplementation((_file, args) => {
|
||||
const job = {
|
||||
child: Object.assign(new EventEmitter(), {
|
||||
pid: 90000 + jobs.length,
|
||||
exitCode: null,
|
||||
signalCode: null,
|
||||
kill: jest.fn(),
|
||||
}) as unknown as ChildProcess,
|
||||
resultPromise: args.includes('server') ? new Promise<string>(() => {}) : Promise.resolve(''),
|
||||
};
|
||||
jobs.push(job);
|
||||
return job;
|
||||
});
|
||||
// Fixture PIDs are fake; never signal them.
|
||||
jest.spyOn(processes, 'stopProcessAndDescendantsAsync').mockResolvedValue();
|
||||
jest.spyOn(serveSim, 'waitForServeSimReadyAsync').mockResolvedValue({
|
||||
startupDevice: 'PHONE',
|
||||
pid: 90000,
|
||||
nativeStartTime: 'native-start',
|
||||
port: 3200,
|
||||
url: 'http://127.0.0.1:3200',
|
||||
token: 'fixture-token',
|
||||
});
|
||||
jest.mocked(createArgentTool).mockImplementation(() => ({
|
||||
name: 'argent',
|
||||
startAsync: async () => {},
|
||||
stopAsync: async () => {},
|
||||
}));
|
||||
});
|
||||
afterEach(async () => {
|
||||
if (active.length) {
|
||||
process.emit('SIGTERM', 'SIGTERM');
|
||||
}
|
||||
await Promise.allSettled(active);
|
||||
jest.restoreAllMocks();
|
||||
process.env = environment;
|
||||
Object.defineProperty(process, 'platform', { value: platform });
|
||||
await fs.rm(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test('concurrent starts acquire one session and record the exact package version', async () => {
|
||||
const results: unknown[] = [];
|
||||
const starts = [0, 1].map(() =>
|
||||
startAsync(boot).then(
|
||||
value => results.push(value),
|
||||
error => results.push(error)
|
||||
)
|
||||
);
|
||||
active.push(...starts);
|
||||
await status('ready');
|
||||
await until(() => results.length === 1);
|
||||
expect(results[0]).toBeInstanceOf(Error);
|
||||
expect((await readLauncherStateAsync(boot))?.launcherVersion).toBe(
|
||||
require('../../package.json').version
|
||||
);
|
||||
expect(jest.mocked(serveSim.waitForServeSimReadyAsync).mock.calls).toHaveLength(1);
|
||||
await stopAsync(boot);
|
||||
await Promise.all(starts);
|
||||
expect((await readLauncherStateAsync(boot))?.status).toBe('disabled');
|
||||
});
|
||||
|
||||
test('stop before start makes late startup a resource-free disabled no-op', async () => {
|
||||
expect(await stopAsync(boot)).toBe(0);
|
||||
expect(await startAsync(boot)).toBe(0);
|
||||
expect(commands.runAsync).not.toHaveBeenCalled();
|
||||
expect(commands.start).not.toHaveBeenCalled();
|
||||
expect(await readLauncherStateAsync(boot)).toEqual({ bootUuid: boot, status: 'disabled' });
|
||||
});
|
||||
|
||||
test('stop under different HOME and TMPDIR waits for the same active session cleanup', async () => {
|
||||
const [completion] = await beginSession();
|
||||
await status('ready');
|
||||
const drain = deferred();
|
||||
jest.mocked(processes.stopProcessAndDescendantsAsync).mockImplementation(async () => {
|
||||
await drain.promise;
|
||||
});
|
||||
process.env.HOME = path.join(root, 'other-home');
|
||||
process.env.TMPDIR = path.join(root, 'other-tmp');
|
||||
jest.mocked(os.homedir).mockReturnValue(process.env.HOME);
|
||||
let done = false;
|
||||
const stopping = mainAsync(['stop']).then(value => {
|
||||
done = true;
|
||||
return value;
|
||||
});
|
||||
try {
|
||||
await status('stopping');
|
||||
expect(done).toBe(false);
|
||||
drain.resolve();
|
||||
expect(await stopping).toBe(0);
|
||||
expect(await completion).toBeUndefined();
|
||||
expect((await readLauncherStateAsync(boot))?.status).toBe('disabled');
|
||||
} finally {
|
||||
drain.resolve();
|
||||
await stopping;
|
||||
}
|
||||
});
|
||||
|
||||
test('ready contains one server identity and effective paths in the single state file', async () => {
|
||||
const [completion] = await beginSession();
|
||||
const ready = await status('ready');
|
||||
expect(ready).toMatchObject({
|
||||
controllerPid: process.pid,
|
||||
device: { udid: 'PHONE' },
|
||||
server: { startupDevice: 'PHONE', pid: 90000, nativeStartTime: 'native-start', port: 3200 },
|
||||
});
|
||||
expect(ready?.agentDeviceStateDir).toContain(root);
|
||||
expect(await fs.readdir(path.join(root, 'control'))).toEqual([
|
||||
path.basename(LAUNCHER_STATE_FILE),
|
||||
]);
|
||||
await stopAsync(boot);
|
||||
expect(await completion).toBeUndefined();
|
||||
});
|
||||
|
||||
test.each([undefined, 'phone', 'iPhone 17 Pro'])(
|
||||
'claim reserves %s without changing the server or booting devices',
|
||||
async selector => {
|
||||
const [completion] = await beginSession();
|
||||
await status('ready');
|
||||
const output = jest.spyOn(process.stdout, 'write').mockReturnValue(true);
|
||||
await claimAsync(boot, 'serve-sim', selector);
|
||||
const result = JSON.parse(String(output.mock.calls.at(-1)![0]));
|
||||
expect(result).toMatchObject({
|
||||
status: 'claimed',
|
||||
engine: 'serve-sim',
|
||||
device: { udid: selector === 'iPhone 17 Pro' ? 'PRO' : 'PHONE' },
|
||||
server: { startupDevice: 'PHONE', port: 3200, pid: 90000 },
|
||||
});
|
||||
expect(result.device).not.toHaveProperty('port');
|
||||
expect(
|
||||
jest.mocked(commands.runAsync).mock.calls.filter(([, args]) => args.includes('bootstatus'))
|
||||
).toHaveLength(0);
|
||||
await expect(claimAsync(boot, 'argent')).rejects.toThrow('available');
|
||||
await stopAsync(boot);
|
||||
expect(await completion).toBeUndefined();
|
||||
}
|
||||
);
|
||||
|
||||
test.each([
|
||||
[undefined, undefined],
|
||||
['invalid', undefined],
|
||||
['serve-sim', ' '],
|
||||
])('invalid claim %s/%s does not acquire or mutate state', async (engine, device) => {
|
||||
const [completion] = await beginSession();
|
||||
await status('ready');
|
||||
const before = await readLauncherStateAsync(boot);
|
||||
await expect(claimAsync(boot, engine, device)).rejects.toThrow(
|
||||
'Invalid Simulator session request'
|
||||
);
|
||||
expect(await readLauncherStateAsync(boot)).toEqual(before);
|
||||
await stopAsync(boot);
|
||||
await completion;
|
||||
});
|
||||
|
||||
test('the post-adopt preparation command uses the consumed claim and returns toolsReady', async () => {
|
||||
const [completion] = await beginSession();
|
||||
await status('ready');
|
||||
const output = jest.spyOn(process.stdout, 'write').mockReturnValue(true);
|
||||
await expect(prepareToolsAsync(boot)).rejects.toThrow('Claim and adopt');
|
||||
await claimAsync(boot, 'agent-device');
|
||||
expect((await readLauncherStateAsync(boot))?.toolsReady).toBeUndefined();
|
||||
await prepareToolsAsync(boot);
|
||||
expect(JSON.parse(String(output.mock.calls.at(-1)![0]))).toMatchObject({
|
||||
status: 'claimed',
|
||||
engine: 'agent-device',
|
||||
toolsReady: true,
|
||||
prepareToolsRequested: true,
|
||||
});
|
||||
await stopAsync(boot);
|
||||
expect(await completion).toBeUndefined();
|
||||
});
|
||||
|
||||
test('prepare-tools returns the validated Argent identity past an earlier stale same-port record', async () => {
|
||||
jest
|
||||
.mocked(createArgentTool)
|
||||
.mockImplementation(jest.requireActual('../utils/argent').createArgentTool);
|
||||
await fs.writeFile(
|
||||
path.join(root, '.argent/tool-server-old.json'),
|
||||
JSON.stringify({ pid: 90099, port: 3201, token: 'stale-token' })
|
||||
);
|
||||
jest
|
||||
.spyOn(fs, 'readdir')
|
||||
.mockResolvedValue(['tool-server-old.json', 'tool-server.json'] as never);
|
||||
jest
|
||||
.mocked(processes.isProcessOwnedByServiceAsync)
|
||||
.mockImplementation(async pid => pid !== 90099);
|
||||
const [completion] = await beginSession();
|
||||
await status('ready');
|
||||
const output = jest.spyOn(process.stdout, 'write').mockReturnValue(true);
|
||||
await claimAsync(boot, 'argent');
|
||||
await prepareToolsAsync(boot);
|
||||
expect(JSON.parse(String(output.mock.calls.at(-1)?.[0]))).toMatchObject({
|
||||
toolsReady: true,
|
||||
tools: { pid: 90002, port: 3201, token: 'fixture-token' },
|
||||
});
|
||||
expect(fetch).not.toHaveBeenCalledWith(
|
||||
expect.anything(),
|
||||
expect.objectContaining({ headers: { Authorization: 'Bearer stale-token' } })
|
||||
);
|
||||
await stopAsync(boot);
|
||||
expect(await completion).toBeUndefined();
|
||||
});
|
||||
|
||||
test('stop during post-adopt preparation prevents toolsReady and waits for owned drain', async () => {
|
||||
const [completion] = await beginSession();
|
||||
await status('ready');
|
||||
jest.spyOn(process.stdout, 'write').mockReturnValue(true);
|
||||
await claimAsync(boot, 'serve-sim');
|
||||
const entered = deferred();
|
||||
const release = deferred();
|
||||
let preparationSignal: AbortSignal;
|
||||
jest
|
||||
.mocked(serveSim.waitForServeSimReadyAsync)
|
||||
.mockImplementationOnce(async (_device, _server, signal) => {
|
||||
preparationSignal = signal;
|
||||
entered.resolve();
|
||||
await release.promise;
|
||||
signal.throwIfAborted();
|
||||
throw new Error('unreachable');
|
||||
});
|
||||
const preparing = prepareToolsAsync(boot).catch(error => error);
|
||||
try {
|
||||
await entered.promise;
|
||||
const stopping = stopAsync(boot);
|
||||
await status('stopping');
|
||||
await until(() => preparationSignal.aborted);
|
||||
release.resolve();
|
||||
await stopping;
|
||||
expect(await preparing).toBeInstanceOf(Error);
|
||||
expect((await readLauncherStateAsync(boot))?.toolsReady).not.toBe(true);
|
||||
expect(await completion).toBeUndefined();
|
||||
} finally {
|
||||
release.resolve();
|
||||
}
|
||||
});
|
||||
|
||||
test('claim does not wait for the Expo Go install; prepare-tools does, and stop drains cleanup', async () => {
|
||||
const info = {
|
||||
udid: 'PHONE',
|
||||
bundleIdentifier: 'host.exp.Exponent',
|
||||
shortVersion: '58.0.7',
|
||||
version: '58.0.7',
|
||||
};
|
||||
const install = deferred<typeof info>();
|
||||
const cleanup = deferred();
|
||||
jest.mocked(startExpoGoPreinstall).mockReturnValue({
|
||||
// The default device's preinstall stays open until its cleanup finishes.
|
||||
preinstallOnDeviceAsync: jest.fn(() => cleanup.promise),
|
||||
claimAsync: jest.fn(() => install.promise),
|
||||
stopAsync: jest.fn(() => cleanup.promise),
|
||||
});
|
||||
const [completion] = await beginSession();
|
||||
await status('ready');
|
||||
jest.spyOn(process.stdout, 'write').mockReturnValue(true);
|
||||
try {
|
||||
await claimAsync(boot, 'serve-sim');
|
||||
expect(await readLauncherStateAsync(boot)).not.toHaveProperty('preinstalledExpoGo');
|
||||
let prepared = false;
|
||||
const preparing = prepareToolsAsync(boot).then(() => {
|
||||
prepared = true;
|
||||
});
|
||||
await new Promise(resolve => setTimeout(resolve, 300));
|
||||
expect(prepared).toBe(false);
|
||||
install.resolve(info);
|
||||
await preparing;
|
||||
expect(await readLauncherStateAsync(boot)).toMatchObject({
|
||||
toolsReady: true,
|
||||
preinstalledExpoGo: info,
|
||||
});
|
||||
const stopping = stopAsync(boot);
|
||||
await status('stopping');
|
||||
expect((await readLauncherStateAsync(boot))?.status).not.toBe('disabled');
|
||||
cleanup.resolve();
|
||||
await stopping;
|
||||
await completion;
|
||||
} finally {
|
||||
install.resolve(info);
|
||||
cleanup.resolve();
|
||||
}
|
||||
});
|
||||
|
||||
test('preparation failure confirms cleanup before publishing disabled with its cause', async () => {
|
||||
jest
|
||||
.mocked(serveSim.waitForServeSimReadyAsync)
|
||||
.mockRejectedValueOnce(new Error('native readiness failed'));
|
||||
const [completion] = await beginSession();
|
||||
expect(((await completion) as Error).message).toBe('native readiness failed');
|
||||
expect(processes.stopProcessAndDescendantsAsync).toHaveBeenCalled();
|
||||
expect(await readLauncherStateAsync(boot)).toMatchObject({
|
||||
status: 'disabled',
|
||||
error: 'native readiness failed',
|
||||
});
|
||||
});
|
||||
|
||||
test('cleanup failure leaves stopping with a cause and never publishes disabled', async () => {
|
||||
const [completion] = await beginSession();
|
||||
await status('ready');
|
||||
jest
|
||||
.mocked(processes.stopProcessAndDescendantsAsync)
|
||||
.mockRejectedValue(new Error('child not drained'));
|
||||
process.emit('SIGTERM', 'SIGTERM');
|
||||
expect(await completion).toBeInstanceOf(AggregateError);
|
||||
expect(await readLauncherStateAsync(boot)).toMatchObject({
|
||||
status: 'stopping',
|
||||
error: expect.stringContaining('cleanup could not be confirmed'),
|
||||
});
|
||||
});
|
||||
|
||||
test('stop waits on a versionless active state', async () => {
|
||||
await updateLauncherStateAsync(boot, () => ({
|
||||
bootUuid: boot,
|
||||
status: 'ready',
|
||||
controllerPid: 9000,
|
||||
}));
|
||||
const stopping = stopAsync(boot);
|
||||
await status('stopping');
|
||||
await updateLauncherStateAsync(boot, state => ({ ...state!, status: 'disabled' }));
|
||||
expect(await stopping).toBe(0);
|
||||
});
|
||||
|
||||
test('--version prints the exact package version without touching boot or state', async () => {
|
||||
const output = jest.spyOn(process.stdout, 'write').mockReturnValue(true);
|
||||
expect(await mainAsync(['--version'])).toBe(0);
|
||||
expect(output).toHaveBeenCalledWith(`${require('../../package.json').version}\n`);
|
||||
expect(commands.runAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test.each(['install', 'adopt', 'run'])('rejects removed command %s', async command => {
|
||||
await expect(mainAsync([command])).rejects.toThrow('Usage:');
|
||||
expect(commands.runAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
test.each(['linux', 'win32'])('rejects %s before state or native work', async target => {
|
||||
Object.defineProperty(process, 'platform', { value: target });
|
||||
await expect(mainAsync(['start'])).rejects.toThrow('requires macOS');
|
||||
expect(await fs.readdir(path.join(root, 'control'))).toEqual([]);
|
||||
});
|
||||
|
||||
test.each([
|
||||
['Shutdown', true],
|
||||
['Booted', false],
|
||||
])('native shutdown error for %s is confirmed done: %s', async (state, done) => {
|
||||
const failure = new Error('shutdown failed');
|
||||
jest.mocked(commands.runAsync).mockImplementation(async (_file, args) => {
|
||||
if (args.includes('shutdown')) {
|
||||
throw failure;
|
||||
}
|
||||
return JSON.stringify({ devices: { ios: [{ udid: 'OLD', state }] } });
|
||||
});
|
||||
const result = shutdownSimulatorAsync('OLD');
|
||||
if (done) {
|
||||
await expect(result).resolves.toBeUndefined();
|
||||
} else {
|
||||
await expect(result).rejects.toBe(failure);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import { startOwnedWrapperAsync } from './fixtures/ownedWrapper';
|
||||
|
||||
it('confirms cleanup when a real owned wrapper propagates intentionally stopped children as exit 23', async () => {
|
||||
const fixture = await startOwnedWrapperAsync();
|
||||
const { job, leaves, realKill } = fixture;
|
||||
try {
|
||||
const kill = jest.spyOn(process, 'kill').mockImplementation((pid, signal) => {
|
||||
if (pid === job.child.pid && (job.child.exitCode !== null || job.child.signalCode !== null)) {
|
||||
throw new Error('An exited wrapper PID must never be probed or signalled.');
|
||||
}
|
||||
return realKill(pid, signal);
|
||||
});
|
||||
await expect(fixture.stopAsync()).resolves.toBeUndefined();
|
||||
expect(job.child.exitCode).toBe(23);
|
||||
await expect(job.resultPromise).rejects.toMatchObject({ code: 23 });
|
||||
expect(
|
||||
kill.mock.calls.filter(([, signal]) => signal === 'SIGTERM').map(([pid]) => pid)
|
||||
).toEqual(expect.arrayContaining(leaves));
|
||||
for (const pid of leaves) {
|
||||
expect(() => realKill(pid, 0)).toThrow();
|
||||
}
|
||||
} finally {
|
||||
jest.restoreAllMocks();
|
||||
await fixture.cleanupAsync();
|
||||
}
|
||||
}, 10_000);
|
||||
@@ -0,0 +1,640 @@
|
||||
import { type ChildProcess, spawn } from 'node:child_process';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { PassThrough } from 'node:stream';
|
||||
|
||||
jest.mock('node:child_process', () => ({ spawn: jest.fn() }));
|
||||
let commands: typeof import('../utils/processes').commands;
|
||||
let stopProcessAndDescendantsAsync: typeof import('../utils/processes').stopProcessAndDescendantsAsync;
|
||||
let terminateProcessGroupAsync: typeof import('../utils/processes').terminateProcessGroupAsync;
|
||||
let child: ChildProcess;
|
||||
|
||||
beforeEach(() => {
|
||||
jest.useFakeTimers();
|
||||
jest.isolateModules(() => {
|
||||
({
|
||||
commands,
|
||||
stopProcessAndDescendantsAsync,
|
||||
terminateProcessGroupAsync,
|
||||
} = require('../utils/processes'));
|
||||
});
|
||||
child = Object.assign(new EventEmitter(), {
|
||||
pid: 90001,
|
||||
exitCode: null,
|
||||
signalCode: null,
|
||||
stdout: new PassThrough(),
|
||||
kill: jest.fn().mockReturnValue(true),
|
||||
unref: jest.fn(),
|
||||
}) as unknown as ChildProcess;
|
||||
jest.mocked(spawn).mockReturnValue(child);
|
||||
});
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
test('captures output and waits for close rather than wrapper exit', async () => {
|
||||
const job = commands.start('command', [], { captureStdout: true });
|
||||
let finished = false;
|
||||
const result = job.resultPromise.then(output => {
|
||||
finished = true;
|
||||
return output;
|
||||
});
|
||||
expect(child.listenerCount('close')).toBe(1);
|
||||
child.stdout!.emit('data', Buffer.from('output'));
|
||||
child.emit('exit', 0, null);
|
||||
await Promise.resolve();
|
||||
expect(finished).toBe(false);
|
||||
child.emit('close', 0, null);
|
||||
await expect(result).resolves.toBe('output');
|
||||
expect(() => commands.throwIfCommandCloseTimedOut()).not.toThrow();
|
||||
});
|
||||
|
||||
for (const code of ['ABORT_ERR', 'ENOENT']) {
|
||||
test(`preserves original ${code} error and observes close before awaiting`, async () => {
|
||||
const error = Object.assign(new Error('original failure'), { code });
|
||||
const job = commands.start('command', []);
|
||||
let finished = false;
|
||||
const result = job.resultPromise.catch(error => {
|
||||
finished = true;
|
||||
return error;
|
||||
});
|
||||
expect(child.listenerCount('close')).toBe(1);
|
||||
child.emit('error', error);
|
||||
await Promise.resolve();
|
||||
expect(finished).toBe(false);
|
||||
child.emit('close', null, null);
|
||||
await expect(result).resolves.toBe(error);
|
||||
});
|
||||
}
|
||||
|
||||
test('nonzero exits reject only after close and retain exit code', async () => {
|
||||
const job = commands.start('command', []);
|
||||
const result = job.resultPromise.catch(error => error);
|
||||
child.emit('exit', 7, null);
|
||||
child.emit('close', 7, null);
|
||||
expect((await result).code).toBe(7);
|
||||
});
|
||||
|
||||
for (const event of ['error', 'exit']) {
|
||||
test(`bounded close drain fails teardown even after late close: ${event}`, async () => {
|
||||
const original = new Error('original abort');
|
||||
const job = commands.start('command', []);
|
||||
const result = job.resultPromise.catch(error => error);
|
||||
if (event === 'error') {
|
||||
child.emit('error', original);
|
||||
} else {
|
||||
child.emit('exit', 0, null);
|
||||
}
|
||||
await jest.advanceTimersByTimeAsync(130_000);
|
||||
const failure = await result;
|
||||
if (event === 'error') {
|
||||
expect(failure).toBe(original);
|
||||
} else {
|
||||
expect(failure.message).toContain('did not finish closing');
|
||||
}
|
||||
expect(child.kill).toHaveBeenCalledWith('SIGKILL');
|
||||
expect(child.unref).toHaveBeenCalled();
|
||||
expect(() => commands.throwIfCommandCloseTimedOut()).toThrow('did not finish closing');
|
||||
child.emit('close', 0, null);
|
||||
expect(() => commands.throwIfCommandCloseTimedOut()).toThrow('did not finish closing');
|
||||
});
|
||||
}
|
||||
|
||||
test('descendants drain before their parent, then the owned child close is awaited', async () => {
|
||||
const alive = new Set([90001, 90002]);
|
||||
const signals: number[] = [];
|
||||
jest
|
||||
.mocked(child.kill)
|
||||
.mockImplementation(signal => process.kill(child.pid!, signal ?? 'SIGTERM'));
|
||||
jest.spyOn(process, 'kill').mockImplementation((pid, signal) => {
|
||||
if (!alive.has(pid)) {
|
||||
throw Object.assign(new Error('gone'), { code: 'ESRCH' });
|
||||
}
|
||||
if (signal === 'SIGTERM') {
|
||||
signals.push(pid);
|
||||
alive.delete(pid);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
jest
|
||||
.spyOn(commands, 'runAsync')
|
||||
.mockImplementation(async (file, args) =>
|
||||
file === 'pgrep' && args[1] === '90001' ? '90002\n' : ''
|
||||
);
|
||||
let closed!: () => void;
|
||||
const resultPromise = new Promise<string>(resolve => {
|
||||
closed = () => resolve('');
|
||||
});
|
||||
let finished = false;
|
||||
const stopping = stopProcessAndDescendantsAsync({ child, resultPromise }).then(() => {
|
||||
finished = true;
|
||||
});
|
||||
await jest.advanceTimersByTimeAsync(1);
|
||||
expect(signals).toEqual([90002, 90001]);
|
||||
expect(finished).toBe(false);
|
||||
closed();
|
||||
await stopping;
|
||||
expect(finished).toBe(true);
|
||||
});
|
||||
|
||||
test('an exited foreground wrapper is failed teardown; never inspect its possibly reused PID', async () => {
|
||||
Object.defineProperty(child, 'exitCode', { value: 0 });
|
||||
const kill = jest.spyOn(process, 'kill');
|
||||
await expect(
|
||||
stopProcessAndDescendantsAsync({ child, resultPromise: Promise.resolve('') })
|
||||
).rejects.toThrow('child processes');
|
||||
expect(kill).not.toHaveBeenCalled();
|
||||
await expect(
|
||||
stopProcessAndDescendantsAsync({ child, resultPromise: Promise.resolve('') }, true)
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
test('a descendant that ignores TERM prevents stop success at the deadline', async () => {
|
||||
jest.spyOn(process, 'kill').mockImplementation((_pid, signal) => {
|
||||
if (signal === 'SIGTERM') {
|
||||
Object.defineProperty(child, 'exitCode', { value: 0 });
|
||||
}
|
||||
return true;
|
||||
});
|
||||
jest
|
||||
.spyOn(commands, 'runAsync')
|
||||
.mockImplementation(async (file, args) =>
|
||||
file === 'pgrep' ? (args[1] === '90001' ? '90002' : '') : 'S'
|
||||
);
|
||||
const result = stopProcessAndDescendantsAsync({
|
||||
child,
|
||||
resultPromise: Promise.resolve(''),
|
||||
}).catch(error => error);
|
||||
await jest.advanceTimersByTimeAsync(130_100);
|
||||
expect((await result).message).toContain('90002 is still running');
|
||||
expect(jest.mocked(process.kill).mock.calls.filter(([, signal]) => signal === 'SIGTERM')).toEqual(
|
||||
[[90002, 'SIGTERM']]
|
||||
);
|
||||
});
|
||||
|
||||
test('ps failure cannot fabricate descendant teardown', async () => {
|
||||
jest.spyOn(process, 'kill').mockReturnValue(true);
|
||||
jest.spyOn(commands, 'runAsync').mockImplementation(async file => {
|
||||
if (file === 'pgrep') {
|
||||
return '';
|
||||
}
|
||||
throw new Error('ps failed');
|
||||
});
|
||||
await expect(
|
||||
stopProcessAndDescendantsAsync({ child, resultPromise: Promise.resolve('') })
|
||||
).rejects.toThrow('ps failed');
|
||||
});
|
||||
|
||||
test('normal wrapper exit during drain still drains every known child and awaits owned close without probing its reused PID', async () => {
|
||||
const job = commands.start('wrapper', []);
|
||||
const signals: number[] = [];
|
||||
jest.spyOn(process, 'kill').mockImplementation((pid, signal) => {
|
||||
if (pid === child.pid) {
|
||||
throw new Error('Possibly reused wrapper PID must not be probed or signalled.');
|
||||
}
|
||||
if (signal === 'SIGTERM') {
|
||||
signals.push(pid);
|
||||
Object.defineProperty(child, 'exitCode', { value: 0 });
|
||||
child.emit('exit', 0, null);
|
||||
return true;
|
||||
}
|
||||
if (signals.includes(pid)) {
|
||||
throw Object.assign(new Error('gone'), { code: 'ESRCH' });
|
||||
}
|
||||
return true;
|
||||
});
|
||||
jest
|
||||
.spyOn(commands, 'runAsync')
|
||||
.mockImplementation(async (file, args) =>
|
||||
file === 'pgrep' && args[1] === '90001' ? '90002\n90003' : ''
|
||||
);
|
||||
let finished = false;
|
||||
const stopping = stopProcessAndDescendantsAsync(job).then(() => {
|
||||
finished = true;
|
||||
});
|
||||
await jest.advanceTimersByTimeAsync(1);
|
||||
expect(signals).toEqual([90002, 90003]);
|
||||
expect(child.kill).not.toHaveBeenCalled();
|
||||
expect(finished).toBe(false);
|
||||
child.emit('close', 0, null);
|
||||
await stopping;
|
||||
expect(finished).toBe(true);
|
||||
});
|
||||
|
||||
test('wrapper exit before completed descendant discovery fails without inspecting discovered PIDs', async () => {
|
||||
const kill = jest.spyOn(process, 'kill');
|
||||
jest.spyOn(commands, 'runAsync').mockImplementation(async () => {
|
||||
Object.defineProperty(child, 'exitCode', { value: 0 });
|
||||
return '90002';
|
||||
});
|
||||
await expect(
|
||||
stopProcessAndDescendantsAsync({ child, resultPromise: Promise.resolve('') })
|
||||
).rejects.toThrow('before its child processes could be identified');
|
||||
expect(commands.runAsync).toHaveBeenCalledTimes(1);
|
||||
expect(kill).not.toHaveBeenCalled();
|
||||
expect(child.kill).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ exitCode: 1, signalCode: null },
|
||||
{ exitCode: null, signalCode: 'SIGTERM' },
|
||||
])('unexpected wrapper exit during drain fails closed: %j', async exit => {
|
||||
const signals: number[] = [];
|
||||
jest.spyOn(process, 'kill').mockImplementation((pid, signal) => {
|
||||
if (signal === 'SIGTERM') {
|
||||
signals.push(pid);
|
||||
Object.assign(child, exit);
|
||||
}
|
||||
if (!signal && signals.includes(pid)) {
|
||||
throw Object.assign(new Error('gone'), { code: 'ESRCH' });
|
||||
}
|
||||
return true;
|
||||
});
|
||||
jest
|
||||
.spyOn(commands, 'runAsync')
|
||||
.mockImplementation(async (file, args) =>
|
||||
file === 'pgrep' && args[1] === '90001' ? '90002' : ''
|
||||
);
|
||||
await expect(
|
||||
stopProcessAndDescendantsAsync({ child, resultPromise: Promise.resolve('') })
|
||||
).rejects.toThrow('exited unexpectedly while its child processes were stopping');
|
||||
expect(signals).toEqual([90002]);
|
||||
expect(child.kill).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('normal wrapper exit after draining does not bypass a missing close timeout', async () => {
|
||||
const job = commands.start('wrapper', []);
|
||||
let descendantAlive = true;
|
||||
jest.spyOn(process, 'kill').mockImplementation((pid, signal) => {
|
||||
if (pid !== 90002) {
|
||||
throw new Error('Possibly reused wrapper PID must not be probed or signalled.');
|
||||
}
|
||||
if (signal === 'SIGTERM') {
|
||||
descendantAlive = false;
|
||||
Object.defineProperty(child, 'exitCode', { value: 0 });
|
||||
child.emit('exit', 0, null);
|
||||
} else if (!descendantAlive) {
|
||||
throw Object.assign(new Error('gone'), { code: 'ESRCH' });
|
||||
}
|
||||
return true;
|
||||
});
|
||||
jest
|
||||
.spyOn(commands, 'runAsync')
|
||||
.mockImplementation(async (file, args) =>
|
||||
file === 'pgrep' && args[1] === '90001' ? '90002' : ''
|
||||
);
|
||||
const stopping = stopProcessAndDescendantsAsync(job).catch(error => error);
|
||||
await jest.advanceTimersByTimeAsync(130_001);
|
||||
expect((await stopping).message).toContain('did not finish closing');
|
||||
child.emit('close', 0, null);
|
||||
expect(() => commands.throwIfCommandCloseTimedOut()).toThrow('did not finish closing');
|
||||
});
|
||||
|
||||
describe('terminateProcessGroupAsync', () => {
|
||||
/** Models the group led by 90001; `members` are its live processes. */
|
||||
function group(members: Set<number>, { ignoresTerm = false, survivesKill = false } = {}) {
|
||||
const signals: [number, string | number | undefined][] = [];
|
||||
jest.spyOn(process, 'kill').mockImplementation((pid, signal) => {
|
||||
if (pid !== -90001) {
|
||||
throw new Error(`Only the process group may be signalled, not ${pid}.`);
|
||||
}
|
||||
if (members.size === 0) {
|
||||
throw Object.assign(new Error('gone'), { code: 'ESRCH' });
|
||||
}
|
||||
if (signal) {
|
||||
signals.push([pid, signal]);
|
||||
}
|
||||
if ((signal === 'SIGTERM' && !ignoresTerm) || (signal === 'SIGKILL' && !survivesKill)) {
|
||||
members.clear();
|
||||
}
|
||||
return true;
|
||||
});
|
||||
return signals;
|
||||
}
|
||||
|
||||
it('signals the whole group once and waits for it to empty', async () => {
|
||||
const signals = group(new Set([90001, 90002, 90003]));
|
||||
await terminateProcessGroupAsync({ child, resultPromise: Promise.resolve('') });
|
||||
expect(signals).toEqual([[-90001, 'SIGTERM']]);
|
||||
});
|
||||
|
||||
it('kills a group that ignores TERM after the grace period', async () => {
|
||||
jest.useRealTimers();
|
||||
const signals = group(new Set([90001, 90004]), { ignoresTerm: true });
|
||||
await terminateProcessGroupAsync({ child, resultPromise: Promise.resolve('') }, 50);
|
||||
expect(signals).toEqual([
|
||||
[-90001, 'SIGTERM'],
|
||||
[-90001, 'SIGKILL'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('fails when the group survives SIGKILL', async () => {
|
||||
jest.useRealTimers();
|
||||
group(new Set([90001, 90004]), { ignoresTerm: true, survivesKill: true });
|
||||
const stopping = terminateProcessGroupAsync(
|
||||
{ child, resultPromise: Promise.resolve('') },
|
||||
50
|
||||
).catch(error => error);
|
||||
expect((await stopping).message).toContain('process group 90001 is still running');
|
||||
});
|
||||
|
||||
it('never signals a reused PID after its group has exited', async () => {
|
||||
jest.useRealTimers();
|
||||
const members = new Set([90001, 90002]);
|
||||
const signals = group(members);
|
||||
const groupKill = jest.mocked(process.kill).getMockImplementation()!;
|
||||
// After TERM empties the group, 90001's number belongs to an unrelated live process.
|
||||
jest
|
||||
.mocked(process.kill)
|
||||
.mockImplementation((pid, signal) => (pid === 90001 ? true : groupKill(pid, signal)));
|
||||
await terminateProcessGroupAsync({ child, resultPromise: Promise.resolve('') }, 50);
|
||||
expect(signals).toEqual([[-90001, 'SIGTERM']]);
|
||||
expect(jest.mocked(process.kill).mock.calls.some(([pid]) => pid > 0)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('EPERM from exited processes awaiting reap', () => {
|
||||
const eperm = (): never => {
|
||||
throw Object.assign(new Error('kill EPERM'), { code: 'EPERM' });
|
||||
};
|
||||
|
||||
it('treats a group with only zombie members as stopped', async () => {
|
||||
jest.useRealTimers();
|
||||
let terminated = false;
|
||||
jest.spyOn(process, 'kill').mockImplementation((pid, signal) => {
|
||||
expect(pid).toBe(-90001);
|
||||
if (signal === 'SIGTERM') {
|
||||
terminated = true;
|
||||
return true;
|
||||
}
|
||||
// After TERM, the only member left is the leader awaiting reap.
|
||||
return terminated ? eperm() : true;
|
||||
});
|
||||
jest
|
||||
.spyOn(commands, 'runAsync')
|
||||
.mockImplementation(async file => (file === 'ps' ? ' 90001 Z\n 412 Ss\n' : ''));
|
||||
await terminateProcessGroupAsync({ child, resultPromise: Promise.resolve('') }, 50);
|
||||
expect(
|
||||
jest.mocked(process.kill).mock.calls.filter(([, signal]) => signal === 'SIGKILL')
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it('still fails closed when a live member cannot be signalled', async () => {
|
||||
jest.useRealTimers();
|
||||
jest.spyOn(process, 'kill').mockImplementation(() => eperm());
|
||||
jest
|
||||
.spyOn(commands, 'runAsync')
|
||||
.mockImplementation(async file => (file === 'ps' ? ' 90001 S\n' : ''));
|
||||
const stopping = terminateProcessGroupAsync(
|
||||
{ child, resultPromise: Promise.resolve('') },
|
||||
50
|
||||
).catch(error => error);
|
||||
expect((await stopping).message).toContain('process group 90001 is still running');
|
||||
});
|
||||
|
||||
it('lets the tree stop finish a descendant that exited before its signal', async () => {
|
||||
jest
|
||||
.spyOn(process, 'kill')
|
||||
.mockImplementation((pid, signal) =>
|
||||
pid === 90002 && signal === 'SIGTERM' ? eperm() : pid === 90002 ? eperm() : true
|
||||
);
|
||||
jest.mocked(child.kill).mockImplementation(() => {
|
||||
Object.defineProperty(child, 'exitCode', { value: 0 });
|
||||
return true;
|
||||
});
|
||||
jest
|
||||
.spyOn(commands, 'runAsync')
|
||||
.mockImplementation(async (file, args) =>
|
||||
file === 'pgrep' ? (args[1] === '90001' ? '90002\n' : '') : file === 'ps' ? 'Z\n' : ''
|
||||
);
|
||||
await expect(
|
||||
stopProcessAndDescendantsAsync({ child, resultPromise: Promise.resolve('') })
|
||||
).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
test('serve-sim leads its own process group', () => {
|
||||
const { startServeSim } = require('../utils/serveSim');
|
||||
startServeSim(['PHONE'], new AbortController().signal);
|
||||
expect(spawn).toHaveBeenCalledWith(
|
||||
'bunx',
|
||||
expect.arrayContaining(['PHONE', '--port', '3200']),
|
||||
expect.objectContaining({ detached: true })
|
||||
);
|
||||
});
|
||||
|
||||
test('the fixture PID guard keeps tests away from the real process.kill', () => {
|
||||
expect(() => process.kill(90002, 0)).toThrow('fixture PID 90002');
|
||||
expect(() => process.kill(-90001, 'SIGKILL')).toThrow('fixture PID -90001');
|
||||
expect(() => process.kill(11, 0)).toThrow('fixture PID 11');
|
||||
});
|
||||
|
||||
test.each([
|
||||
{ exitCode: 23, signalCode: null },
|
||||
{ exitCode: 143, signalCode: null },
|
||||
{ exitCode: null, signalCode: 'SIGTERM' },
|
||||
])(
|
||||
'owned-group wrapper exit after intentional child stop still drains siblings and owned close: %j',
|
||||
async exit => {
|
||||
const job = commands.start('wrapper', [], { captureStdout: true, detached: true });
|
||||
const signalled = new Set<number>();
|
||||
jest.spyOn(process, 'kill').mockImplementation((pid, signal) => {
|
||||
if (pid === -90001 || signalled.has(pid)) {
|
||||
throw Object.assign(new Error('gone'), { code: 'ESRCH' });
|
||||
}
|
||||
if (pid === child.pid) {
|
||||
throw new Error('An exited wrapper PID must not be probed.');
|
||||
}
|
||||
if (signal === 'SIGTERM') {
|
||||
signalled.add(pid);
|
||||
Object.assign(child, exit);
|
||||
child.emit('exit', exit.exitCode, exit.signalCode);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
jest
|
||||
.spyOn(commands, 'runAsync')
|
||||
.mockImplementation(async (file, args) =>
|
||||
file === 'pgrep' && args[1] === '90001' ? '90002 90003' : ''
|
||||
);
|
||||
let finished = false;
|
||||
const stopping = stopProcessAndDescendantsAsync(job).then(() => {
|
||||
finished = true;
|
||||
});
|
||||
await jest.advanceTimersByTimeAsync(1);
|
||||
expect([...signalled]).toEqual([90002, 90003]);
|
||||
expect(finished).toBe(false);
|
||||
expect(child.kill).not.toHaveBeenCalled();
|
||||
child.emit('close', exit.exitCode, exit.signalCode);
|
||||
await stopping;
|
||||
expect(finished).toBe(true);
|
||||
}
|
||||
);
|
||||
|
||||
test('an owned group cannot excuse wrapper exit before descendant discovery or intentional signals', async () => {
|
||||
const job = commands.start('wrapper', [], { captureStdout: true, detached: true });
|
||||
const kill = jest.spyOn(process, 'kill');
|
||||
jest.spyOn(commands, 'runAsync').mockImplementation(async () => {
|
||||
Object.assign(child, { exitCode: 143 });
|
||||
child.emit('exit', 143, null);
|
||||
return '90002';
|
||||
});
|
||||
await expect(stopProcessAndDescendantsAsync(job)).rejects.toThrow(
|
||||
'before its child processes could be identified'
|
||||
);
|
||||
expect(kill).not.toHaveBeenCalled();
|
||||
child.emit('close', 143, null);
|
||||
});
|
||||
|
||||
test.each([0, 143])(
|
||||
'wrapper exit %s before the first intentional signal remains a failure even for an owned group',
|
||||
async exitCode => {
|
||||
const job = commands.start('wrapper', [], { captureStdout: true, detached: true });
|
||||
let signalled = false;
|
||||
const kill = jest.spyOn(process, 'kill').mockImplementation((pid, signal) => {
|
||||
if (pid === 90001 || pid === -90001) {
|
||||
throw new Error('Exited wrapper must not be probed or signalled.');
|
||||
}
|
||||
if (signal === 'SIGTERM') {
|
||||
signalled = true;
|
||||
return true;
|
||||
}
|
||||
if (signalled) {
|
||||
throw Object.assign(new Error('gone'), { code: 'ESRCH' });
|
||||
}
|
||||
Object.assign(child, { exitCode });
|
||||
child.emit('exit', exitCode, null);
|
||||
return true;
|
||||
});
|
||||
jest
|
||||
.spyOn(commands, 'runAsync')
|
||||
.mockImplementation(async (file, args) =>
|
||||
file === 'pgrep' && args[1] === '90001' ? '90002' : ''
|
||||
);
|
||||
await expect(stopProcessAndDescendantsAsync(job)).rejects.toThrow('exited unexpectedly');
|
||||
expect(kill.mock.calls.filter(([, signal]) => signal === 'SIGTERM')).toEqual([
|
||||
[90002, 'SIGTERM'],
|
||||
]);
|
||||
child.emit('close', exitCode, null);
|
||||
}
|
||||
);
|
||||
|
||||
test('owned group retirement drains a child respawned outside the initial snapshot before close', async () => {
|
||||
const job = commands.start('wrapper', [], { captureStdout: true, detached: true });
|
||||
let oldChild = true;
|
||||
let respawn = false;
|
||||
const kill = jest.spyOn(process, 'kill').mockImplementation((pid, signal) => {
|
||||
if (pid === 90001 || pid === 90003) {
|
||||
throw new Error('Do not probe an exited wrapper or guess a respawned PID.');
|
||||
}
|
||||
if (pid === -90001) {
|
||||
if (!respawn) {
|
||||
throw Object.assign(new Error('gone'), { code: 'ESRCH' });
|
||||
}
|
||||
if (signal === 'SIGTERM') {
|
||||
respawn = false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (!oldChild) {
|
||||
throw Object.assign(new Error('gone'), { code: 'ESRCH' });
|
||||
}
|
||||
if (signal === 'SIGTERM') {
|
||||
oldChild = false;
|
||||
respawn = true;
|
||||
Object.assign(child, { exitCode: 143 });
|
||||
child.emit('exit', 143, null);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
jest
|
||||
.spyOn(commands, 'runAsync')
|
||||
.mockImplementation(async (file, args) =>
|
||||
file === 'pgrep' && args[1] === '90001' ? '90002' : ''
|
||||
);
|
||||
let finished = false;
|
||||
const stopping = stopProcessAndDescendantsAsync(job).then(() => {
|
||||
finished = true;
|
||||
});
|
||||
await jest.advanceTimersByTimeAsync(1);
|
||||
expect(respawn).toBe(false);
|
||||
expect(finished).toBe(false);
|
||||
expect(kill.mock.calls.filter(([, signal]) => signal === 'SIGTERM')).toEqual([
|
||||
[90002, 'SIGTERM'],
|
||||
[-90001, 'SIGTERM'],
|
||||
]);
|
||||
child.emit('close', 143, null);
|
||||
await stopping;
|
||||
});
|
||||
|
||||
test('expected owned wrapper termination cannot bypass the sticky close timeout', async () => {
|
||||
const job = commands.start('wrapper', [], { captureStdout: true, detached: true });
|
||||
let stopped = false;
|
||||
jest.spyOn(process, 'kill').mockImplementation((pid, signal) => {
|
||||
if (pid === -90001 || stopped) {
|
||||
throw Object.assign(new Error('gone'), { code: 'ESRCH' });
|
||||
}
|
||||
if (pid !== 90002) {
|
||||
throw new Error('The exited wrapper must not be probed.');
|
||||
}
|
||||
if (signal === 'SIGTERM') {
|
||||
stopped = true;
|
||||
Object.assign(child, { exitCode: 143 });
|
||||
child.emit('exit', 143, null);
|
||||
}
|
||||
return true;
|
||||
});
|
||||
jest
|
||||
.spyOn(commands, 'runAsync')
|
||||
.mockImplementation(async (file, args) =>
|
||||
file === 'pgrep' && args[1] === '90001' ? '90002' : ''
|
||||
);
|
||||
const stopping = stopProcessAndDescendantsAsync(job).catch(error => error);
|
||||
await jest.advanceTimersByTimeAsync(130_001);
|
||||
expect((await stopping).message).toContain('did not finish closing');
|
||||
child.emit('close', 143, null);
|
||||
expect(() => commands.throwIfCommandCloseTimedOut()).toThrow('did not finish closing');
|
||||
});
|
||||
|
||||
test('tries every known sibling before reporting a descendant drain failure', async () => {
|
||||
const failure = new Error('first child could not be verified');
|
||||
const signalled = new Set<number>();
|
||||
jest.spyOn(process, 'kill').mockImplementation((pid, signal) => {
|
||||
if (signal === 'SIGTERM') {
|
||||
signalled.add(pid);
|
||||
return true;
|
||||
}
|
||||
if (pid === 90003 && signalled.has(pid)) {
|
||||
throw Object.assign(new Error('gone'), { code: 'ESRCH' });
|
||||
}
|
||||
return true;
|
||||
});
|
||||
jest.spyOn(commands, 'runAsync').mockImplementation(async (file, args) => {
|
||||
if (file === 'pgrep') {
|
||||
return args[1] === '90001' ? '90002 90003' : '';
|
||||
}
|
||||
if (args[1] === '90002') {
|
||||
throw failure;
|
||||
}
|
||||
return '';
|
||||
});
|
||||
await expect(
|
||||
stopProcessAndDescendantsAsync({ child, resultPromise: Promise.resolve('') })
|
||||
).rejects.toBe(failure);
|
||||
expect([...signalled]).toEqual([90002, 90003]);
|
||||
expect(child.kill).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('rejects a process-group ID that does not belong to its owned child before any native probe', async () => {
|
||||
const kill = jest.spyOn(process, 'kill');
|
||||
const run = jest.spyOn(commands, 'runAsync');
|
||||
await expect(
|
||||
stopProcessAndDescendantsAsync({
|
||||
child,
|
||||
resultPromise: Promise.resolve(''),
|
||||
processGroupId: 90002,
|
||||
})
|
||||
).rejects.toThrow('does not belong');
|
||||
expect(kill).not.toHaveBeenCalled();
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
import { type ChildProcess } from 'node:child_process';
|
||||
import fs from 'node:fs/promises';
|
||||
|
||||
import {
|
||||
type ChildProcessHandle,
|
||||
commands,
|
||||
isProcessOwnedByServiceAsync,
|
||||
} from '../utils/processes';
|
||||
import { waitForServeSimReadyAsync } from '../utils/serveSim';
|
||||
import { deferred, until } from './helpers';
|
||||
|
||||
jest.mock('node:fs/promises');
|
||||
jest.mock('../utils/processes');
|
||||
let child: ChildProcess;
|
||||
let server: ChildProcessHandle;
|
||||
let controller: AbortController;
|
||||
const state = {
|
||||
pid: 90002,
|
||||
port: 3202,
|
||||
device: 'PHONE',
|
||||
url: 'http://127.0.0.1:3202',
|
||||
token: 'fixture-token',
|
||||
};
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
jest.mocked(commands.runAsync).mockResolvedValue('native-start');
|
||||
child = { pid: 90001, exitCode: null, signalCode: null } as ChildProcess;
|
||||
server = { child, resultPromise: new Promise<string>(() => {}) };
|
||||
controller = new AbortController();
|
||||
jest.mocked(fs.readFile).mockResolvedValue(JSON.stringify(state));
|
||||
jest.mocked(isProcessOwnedByServiceAsync).mockResolvedValue(true);
|
||||
jest
|
||||
.spyOn(global, 'fetch')
|
||||
.mockImplementation(
|
||||
async () => new Response(JSON.stringify({ status: 'ready', device: 'PHONE' }))
|
||||
);
|
||||
});
|
||||
afterEach(() => {
|
||||
controller.abort();
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('ignores a matching old server until the new launch owns the registered process', async () => {
|
||||
jest.mocked(isProcessOwnedByServiceAsync).mockResolvedValue(false);
|
||||
let ready = false;
|
||||
const waiting = waitForServeSimReadyAsync('PHONE', server, controller.signal, 3202).then(() => {
|
||||
ready = true;
|
||||
});
|
||||
await until(() => jest.mocked(fs.readFile).mock.calls.length > 0);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(ready).toBe(false);
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
jest.mocked(isProcessOwnedByServiceAsync).mockResolvedValue(true);
|
||||
await waiting;
|
||||
expect(fetch).toHaveBeenCalledWith('http://127.0.0.1:3202/readyz', {
|
||||
signal: expect.any(AbortSignal),
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects the launch exiting during a successful readiness response without waiting for close', async () => {
|
||||
const response = deferred<Response>();
|
||||
jest.mocked(fetch).mockReturnValue(response.promise);
|
||||
const waiting = waitForServeSimReadyAsync('PHONE', server, controller.signal, 3202);
|
||||
await until(() => jest.mocked(fetch).mock.calls.length > 0);
|
||||
Object.assign(child, { exitCode: 1 });
|
||||
response.resolve(new Response(JSON.stringify({ status: 'ready', device: 'PHONE' })));
|
||||
await expect(waiting).rejects.toThrow('serve-sim exited before PHONE became ready');
|
||||
});
|
||||
|
||||
it('does not probe a state file without a process identity', async () => {
|
||||
jest.mocked(fs.readFile).mockResolvedValue(JSON.stringify({ ...state, pid: undefined }));
|
||||
const waiting = waitForServeSimReadyAsync('PHONE', server, controller.signal, 3202).catch(
|
||||
error => error
|
||||
);
|
||||
await until(() => jest.mocked(fs.readFile).mock.calls.length > 0);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
expect(isProcessOwnedByServiceAsync).not.toHaveBeenCalled();
|
||||
controller.abort();
|
||||
expect((await waiting).code).toBe('ABORT_ERR');
|
||||
});
|
||||
|
||||
it('cannot report ready after cancellation during the response', async () => {
|
||||
const response = deferred<Response>();
|
||||
jest.mocked(fetch).mockReturnValue(response.promise);
|
||||
const waiting = waitForServeSimReadyAsync('PHONE', server, controller.signal, 3202);
|
||||
await until(() => jest.mocked(fetch).mock.calls.length > 0);
|
||||
controller.abort(new Error('cancelled'));
|
||||
response.resolve(new Response(JSON.stringify({ status: 'ready', device: 'PHONE' })));
|
||||
await expect(waiting).rejects.toThrow('cancelled');
|
||||
});
|
||||
|
||||
it('times out rather than accepting a server that never becomes ready', async () => {
|
||||
const now = Date.now();
|
||||
jest
|
||||
.spyOn(Date, 'now')
|
||||
.mockReturnValueOnce(now)
|
||||
.mockReturnValue(now + 120_000);
|
||||
await expect(waitForServeSimReadyAsync('PHONE', server, controller.signal, 3202)).rejects.toThrow(
|
||||
'Timed out waiting for serve-sim on PHONE'
|
||||
);
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('retries HTTP errors, a refused connection and readiness for another device', async () => {
|
||||
jest
|
||||
.mocked(fetch)
|
||||
.mockResolvedValueOnce(new Response('unavailable', { status: 503 }))
|
||||
.mockRejectedValueOnce(new Error('connection refused'))
|
||||
.mockResolvedValueOnce(new Response(JSON.stringify({ status: 'ready', device: 'OTHER' })))
|
||||
.mockImplementation(
|
||||
async () => new Response(JSON.stringify({ status: 'ready', device: 'PHONE' }))
|
||||
);
|
||||
await waitForServeSimReadyAsync('PHONE', server, controller.signal, 3202);
|
||||
expect(fetch).toHaveBeenCalledTimes(4);
|
||||
});
|
||||
@@ -0,0 +1,62 @@
|
||||
import { type ChildProcess } from 'node:child_process';
|
||||
|
||||
import { commands, isProcessOwnedByServiceAsync } from '../utils/processes';
|
||||
import { deferred } from './helpers';
|
||||
|
||||
let child: ChildProcess;
|
||||
let controller: AbortController;
|
||||
beforeEach(() => {
|
||||
child = { pid: 90001, exitCode: null, signalCode: null } as ChildProcess;
|
||||
controller = new AbortController();
|
||||
jest.spyOn(commands, 'runAsync');
|
||||
});
|
||||
afterEach(() => jest.restoreAllMocks());
|
||||
|
||||
it('accepts its live owned root without probing a PID', async () => {
|
||||
await expect(isProcessOwnedByServiceAsync(90001, child, controller.signal)).resolves.toBe(true);
|
||||
expect(commands.runAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
it('walks a descendant to its owned root and rejects a foreign tree', async () => {
|
||||
jest.mocked(commands.runAsync).mockResolvedValueOnce('90003').mockResolvedValueOnce('90001');
|
||||
await expect(isProcessOwnedByServiceAsync(90002, child, controller.signal)).resolves.toBe(true);
|
||||
expect(commands.runAsync).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
'ps',
|
||||
['-p', '90002', '-o', 'ppid='],
|
||||
controller.signal
|
||||
);
|
||||
jest.mocked(commands.runAsync).mockResolvedValue('1');
|
||||
await expect(isProcessOwnedByServiceAsync(90004, child, controller.signal)).resolves.toBe(false);
|
||||
});
|
||||
it('rejects a root that exits during ancestry discovery without probing its reused PID', async () => {
|
||||
const parent = deferred<string>();
|
||||
jest.mocked(commands.runAsync).mockReturnValue(parent.promise);
|
||||
const owned = isProcessOwnedByServiceAsync(90002, child, controller.signal);
|
||||
Object.assign(child, { exitCode: 1 });
|
||||
parent.resolve('90001');
|
||||
await expect(owned).resolves.toBe(false);
|
||||
expect(commands.runAsync).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
it('stops at a cycle, a gone process, or cancellation', async () => {
|
||||
jest.mocked(commands.runAsync).mockResolvedValue('90002');
|
||||
await expect(isProcessOwnedByServiceAsync(90002, child, controller.signal)).resolves.toBe(false);
|
||||
jest.mocked(commands.runAsync).mockRejectedValue(Object.assign(new Error('gone'), { code: 1 }));
|
||||
await expect(isProcessOwnedByServiceAsync(90002, child, controller.signal)).resolves.toBe(false);
|
||||
controller.abort(new Error('cancelled'));
|
||||
await expect(isProcessOwnedByServiceAsync(90001, child, controller.signal)).rejects.toThrow(
|
||||
'cancelled'
|
||||
);
|
||||
});
|
||||
it('preserves unexpected process-query failures', async () => {
|
||||
jest.mocked(commands.runAsync).mockRejectedValue(new Error('ps failed'));
|
||||
await expect(isProcessOwnedByServiceAsync(90002, child, controller.signal)).rejects.toThrow(
|
||||
'ps failed'
|
||||
);
|
||||
});
|
||||
|
||||
it('bounds ancestry discovery even when every parent exists but none belongs to this service', async () => {
|
||||
let parent = 90100;
|
||||
jest.mocked(commands.runAsync).mockImplementation(async () => String(parent++));
|
||||
await expect(isProcessOwnedByServiceAsync(90002, child, controller.signal)).resolves.toBe(false);
|
||||
expect(commands.runAsync).toHaveBeenCalledTimes(32);
|
||||
});
|
||||
@@ -0,0 +1,73 @@
|
||||
import { selectWarmupSimulators } from '../utils/simulator';
|
||||
|
||||
const devices = [
|
||||
{ udid: 'DUO', name: 'iPhone Duo' },
|
||||
{ udid: 'PHONE18', name: 'iPhone 18' },
|
||||
{ udid: 'PRO18', name: 'iPhone 18 Pro' },
|
||||
];
|
||||
|
||||
test('keeps the shortest available iPhone as the default when unset', () => {
|
||||
expect(selectWarmupSimulators(devices)).toEqual([devices[1]]);
|
||||
});
|
||||
test('splits and trims a list, preserving its default and accepting case-insensitive UDIDs', () => {
|
||||
expect(selectWarmupSimulators(devices, ' iPhone 18 , duo ')).toEqual([devices[1], devices[0]]);
|
||||
});
|
||||
test.each(['iPhone Duo,', ',iPhone 18', 'iPhone Duo, ,iPhone 18'])(
|
||||
'rejects an empty entry in %j',
|
||||
selectors => {
|
||||
expect(() => selectWarmupSimulators(devices, selectors)).toThrow('nonempty');
|
||||
}
|
||||
);
|
||||
test('rejects a missing or ambiguous device instead of choosing arbitrarily', () => {
|
||||
expect(() => selectWarmupSimulators(devices, 'missing')).toThrow('found 0');
|
||||
expect(() =>
|
||||
selectWarmupSimulators([...devices, { udid: 'OTHER', name: 'iPhone Duo' }], 'iPhone Duo')
|
||||
).toThrow('found 2');
|
||||
});
|
||||
test('rejects two selectors for the same device', () => {
|
||||
expect(() => selectWarmupSimulators(devices, 'iPhone Duo,duo')).toThrow('more than once');
|
||||
});
|
||||
test.each(['', ' ', '\n'])('keeps the default iPhone for blank configuration %j', selectors => {
|
||||
expect(selectWarmupSimulators(devices, selectors)).toEqual([devices[1]]);
|
||||
});
|
||||
|
||||
test('observes an orphan-owned boot without requesting a new boot', async () => {
|
||||
const { commands } = await import('../utils/processes');
|
||||
const { waitForSimulatorBootAsync } = await import('../utils/simulator');
|
||||
const run = jest
|
||||
.spyOn(commands, 'runAsync')
|
||||
.mockImplementation(async (_file, args) =>
|
||||
args.includes('devices')
|
||||
? JSON.stringify({ devices: { ios: [{ udid: 'DUO', state: 'Booted' }] } })
|
||||
: ''
|
||||
);
|
||||
try {
|
||||
await waitForSimulatorBootAsync('DUO', new AbortController().signal);
|
||||
expect(run).toHaveBeenCalledWith(
|
||||
'xcrun',
|
||||
['simctl', 'bootstatus', 'DUO'],
|
||||
expect.any(AbortSignal)
|
||||
);
|
||||
expect(run.mock.calls.some(([, args]) => args.includes('-b') || args.includes('boot'))).toBe(
|
||||
false
|
||||
);
|
||||
} finally {
|
||||
run.mockRestore();
|
||||
}
|
||||
});
|
||||
|
||||
test('a claim can cancel boot observation without issuing a native command', async () => {
|
||||
const { commands } = await import('../utils/processes');
|
||||
const { waitForSimulatorBootAsync } = await import('../utils/simulator');
|
||||
const run = jest
|
||||
.spyOn(commands, 'runAsync')
|
||||
.mockRejectedValue(new Error('unexpected native command'));
|
||||
const cancel = new AbortController();
|
||||
cancel.abort(new Error('claimed'));
|
||||
try {
|
||||
await expect(waitForSimulatorBootAsync('DUO', cancel.signal)).rejects.toThrow('claimed');
|
||||
expect(run).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
run.mockRestore();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,556 @@
|
||||
import { type ChildProcess } from 'node:child_process';
|
||||
|
||||
import { createWarmSimulatorSession } from '../commands/start';
|
||||
import { createArgentTool } from '../utils/argent';
|
||||
import { startExpoGoPreinstall } from '../utils/expoGo';
|
||||
import {
|
||||
type ChildProcessHandle,
|
||||
commands,
|
||||
stopProcessAndDescendantsAsync,
|
||||
} from '../utils/processes';
|
||||
import { startServeSim, waitForServeSimReadyAsync } from '../utils/serveSim';
|
||||
import {
|
||||
disableApsdAsync,
|
||||
shutdownSimulatorAsync,
|
||||
waitForSimulatorBootAsync,
|
||||
} from '../utils/simulator';
|
||||
import { deferred, until } from './helpers';
|
||||
|
||||
jest.mock('../utils/expoGo');
|
||||
jest.mock('../utils/argent');
|
||||
jest.mock('../utils/processes');
|
||||
jest.mock('../utils/serveSim');
|
||||
jest.mock('../utils/simulator', () => ({
|
||||
...jest.requireActual('../utils/simulator'),
|
||||
shutdownSimulatorAsync: jest.fn(),
|
||||
disableApsdAsync: jest.fn(),
|
||||
waitForSimulatorBootAsync: jest.fn(),
|
||||
}));
|
||||
|
||||
const defaultDevice = { udid: 'DUO', name: 'iPhone Duo' };
|
||||
const secondary = { udid: 'PHONE18', name: 'iPhone 18' };
|
||||
const otherDevice = { udid: 'OTHER', name: 'iPhone Pro' };
|
||||
const serverInfo = {
|
||||
startupDevice: 'DUO',
|
||||
pid: 10,
|
||||
nativeStartTime: 'server-start',
|
||||
port: 3200,
|
||||
url: 'http://127.0.0.1:3200',
|
||||
token: 'fixture-token',
|
||||
};
|
||||
function handle(pid: number): ChildProcessHandle {
|
||||
return { child: { pid } as ChildProcess, resultPromise: Promise.resolve('') };
|
||||
}
|
||||
const server = handle(10);
|
||||
const agent = handle(11);
|
||||
const argent = handle(12);
|
||||
let controller: AbortController;
|
||||
let env: NodeJS.ProcessEnv;
|
||||
let onPreparationFailure: jest.Mock;
|
||||
const starts = (word: string) =>
|
||||
jest.mocked(commands.start).mock.calls.filter(([, args]) => args.includes(word));
|
||||
function createSession() {
|
||||
return createWarmSimulatorSession({
|
||||
signal: controller.signal,
|
||||
throwIfStoppingAsync: async () => controller.signal.throwIfAborted(),
|
||||
onPreparationFailure,
|
||||
});
|
||||
}
|
||||
|
||||
/** The default device's Expo Go preinstall finishes with `install`; later devices finish at once. */
|
||||
function mockDefaultExpoGoInstall(install: Promise<void>) {
|
||||
const preinstall = {
|
||||
preinstallOnDeviceAsync: jest.fn().mockReturnValueOnce(install).mockResolvedValue(undefined),
|
||||
claimAsync: jest.fn(async () => undefined),
|
||||
stopAsync: jest.fn(async () => {}),
|
||||
};
|
||||
jest.mocked(startExpoGoPreinstall).mockReturnValue(preinstall);
|
||||
return preinstall;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
env = { ...process.env };
|
||||
process.env.EXPO_SIMULATOR_DEVICE = 'iPhone Duo,iPhone 18';
|
||||
process.env.AGENT_DEVICE_STATE_DIR = '/fixture/agent';
|
||||
process.env.ARGENT_EVENT_LOG = '/fixture/argent-events';
|
||||
controller = new AbortController();
|
||||
onPreparationFailure = jest.fn(error => controller.abort(error));
|
||||
jest.mocked(commands.runAsync).mockImplementation(async (_file, args) => {
|
||||
if (args.includes('devices')) {
|
||||
return JSON.stringify({ devices: { ios: [defaultDevice, secondary, otherDevice] } });
|
||||
}
|
||||
if (args.includes('launchctl') && args.includes('list')) {
|
||||
throw Object.assign(new Error('not loaded'), { code: 113 });
|
||||
}
|
||||
return 'controller-start';
|
||||
});
|
||||
jest
|
||||
.mocked(commands.start)
|
||||
.mockImplementation((_file, args) => (args.includes('prepare') ? agent : argent));
|
||||
jest.mocked(createArgentTool).mockImplementation(() => ({
|
||||
name: 'argent',
|
||||
startAsync: async () => {
|
||||
commands.start('bunx', ['argent', 'server']);
|
||||
},
|
||||
stopAsync: async () => {
|
||||
await stopProcessAndDescendantsAsync(argent);
|
||||
},
|
||||
}));
|
||||
jest.mocked(startServeSim).mockReturnValue(server);
|
||||
jest.mocked(waitForServeSimReadyAsync).mockResolvedValue(serverInfo);
|
||||
jest.mocked(waitForSimulatorBootAsync).mockResolvedValue();
|
||||
jest.mocked(stopProcessAndDescendantsAsync).mockResolvedValue();
|
||||
jest.mocked(shutdownSimulatorAsync).mockResolvedValue();
|
||||
jest
|
||||
.mocked(disableApsdAsync)
|
||||
.mockImplementation(jest.requireActual('../utils/simulator').disableApsdAsync);
|
||||
jest.mocked(startExpoGoPreinstall).mockReturnValue({
|
||||
preinstallOnDeviceAsync: jest.fn(async () => {}),
|
||||
claimAsync: jest.fn(async () => undefined),
|
||||
stopAsync: jest.fn(async () => {}),
|
||||
});
|
||||
});
|
||||
afterEach(() => {
|
||||
process.env = env;
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('creates a stoppable owner before any native work and does not start after stop', async () => {
|
||||
const session = createSession();
|
||||
expect(commands.runAsync).not.toHaveBeenCalled();
|
||||
await session.stopAsync();
|
||||
await expect(session.prepareAsync()).rejects.toThrow();
|
||||
expect(startServeSim).not.toHaveBeenCalled();
|
||||
expect(shutdownSimulatorAsync).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('stop joins pending device selection without starting a late server', async () => {
|
||||
const listing = deferred<string>();
|
||||
jest.mocked(commands.runAsync).mockReturnValueOnce(listing.promise);
|
||||
const session = createSession();
|
||||
const preparing = session.prepareAsync();
|
||||
void preparing.catch(() => {});
|
||||
let stopped = false;
|
||||
const stopping = session.stopAsync().then(() => {
|
||||
stopped = true;
|
||||
});
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(stopped).toBe(false);
|
||||
listing.resolve(JSON.stringify({ devices: { ios: [defaultDevice] } }));
|
||||
await stopping;
|
||||
await expect(preparing).rejects.toThrow();
|
||||
expect(startServeSim).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('starts one orphan with all configured devices and keeps its identity separate from selection', async () => {
|
||||
const session = createSession();
|
||||
const info = await session.prepareAsync();
|
||||
expect(startServeSim).toHaveBeenCalledWith(['DUO', 'PHONE18'], expect.any(AbortSignal));
|
||||
expect(info).toMatchObject({
|
||||
device: defaultDevice,
|
||||
server: serverInfo,
|
||||
controllerPid: process.pid,
|
||||
controllerStartTime: 'controller-start',
|
||||
});
|
||||
const selected = await session.claimAsync({ engine: 'serve-sim', requestedDevice: 'OTHER' });
|
||||
expect(selected.device).toEqual(otherDevice);
|
||||
expect(startServeSim).toHaveBeenCalledTimes(1);
|
||||
expect(commands.runAsync).not.toHaveBeenCalledWith(
|
||||
'xcrun',
|
||||
expect.arrayContaining(['bootstatus']),
|
||||
expect.anything()
|
||||
);
|
||||
await session.stopAsync();
|
||||
expect(shutdownSimulatorAsync).toHaveBeenCalledWith('DUO');
|
||||
expect(shutdownSimulatorAsync).toHaveBeenCalledWith('PHONE18');
|
||||
expect(shutdownSimulatorAsync).toHaveBeenCalledWith('OTHER');
|
||||
});
|
||||
|
||||
it('publishes default readiness without joining Expo Go or requested-tool startup', async () => {
|
||||
const install = deferred();
|
||||
const preparing = deferred<string>();
|
||||
mockDefaultExpoGoInstall(install.promise);
|
||||
jest
|
||||
.mocked(commands.start)
|
||||
.mockImplementation((_file, args) =>
|
||||
args.includes('prepare') ? { ...agent, resultPromise: preparing.promise } : argent
|
||||
);
|
||||
const session = createSession();
|
||||
try {
|
||||
await session.prepareAsync();
|
||||
await expect(session.claimAsync({ engine: 'agent-device' })).resolves.toMatchObject({
|
||||
device: defaultDevice,
|
||||
});
|
||||
expect(starts('prepare')).toHaveLength(1);
|
||||
} finally {
|
||||
preparing.resolve('');
|
||||
install.resolve();
|
||||
await session.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('primes the exact version once before readiness', async () => {
|
||||
const priming = deferred<string>();
|
||||
const run = jest.mocked(commands.runAsync).getMockImplementation()!;
|
||||
jest
|
||||
.mocked(commands.runAsync)
|
||||
.mockImplementation((file, args, signal) =>
|
||||
file === 'bun' ? priming.promise : run(file, args, signal)
|
||||
);
|
||||
const session = createSession();
|
||||
let ready = false;
|
||||
const preparing = session.prepareAsync().then(() => {
|
||||
ready = true;
|
||||
});
|
||||
await until(() => jest.mocked(commands.runAsync).mock.calls.some(([file]) => file === 'bun'));
|
||||
expect(ready).toBe(false);
|
||||
expect(jest.mocked(commands.runAsync).mock.calls.filter(([file]) => file === 'bun')).toHaveLength(
|
||||
1
|
||||
);
|
||||
priming.resolve('25.3.0');
|
||||
await preparing;
|
||||
await session.stopAsync();
|
||||
});
|
||||
|
||||
it('consumed claim forbids the secondary preinstall of a device still booting', async () => {
|
||||
const preinstall = mockDefaultExpoGoInstall(Promise.resolve());
|
||||
jest.mocked(waitForSimulatorBootAsync).mockImplementation(async (udid, signal) => {
|
||||
if (udid === 'PHONE18') {
|
||||
await new Promise((_resolve, reject) =>
|
||||
signal.addEventListener('abort', () => reject(signal.reason), { once: true })
|
||||
);
|
||||
}
|
||||
});
|
||||
const session = createSession();
|
||||
await session.prepareAsync();
|
||||
await until(() => jest.mocked(waitForSimulatorBootAsync).mock.calls.length === 1);
|
||||
await session.claimAsync({ engine: 'serve-sim' });
|
||||
await session.stopAsync();
|
||||
expect(preinstall.preinstallOnDeviceAsync).not.toHaveBeenCalledWith(
|
||||
'PHONE18',
|
||||
expect.anything(),
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
|
||||
it('a secondary boot observation failure leaves the claimed default usable', async () => {
|
||||
jest
|
||||
.mocked(waitForSimulatorBootAsync)
|
||||
.mockImplementation(async udid =>
|
||||
udid === 'PHONE18' ? Promise.reject(new Error('optional boot failed')) : undefined
|
||||
);
|
||||
const session = createSession();
|
||||
await session.prepareAsync();
|
||||
// serve-sim's ready covers the default device's boot; only the second device is checked.
|
||||
await until(() => jest.mocked(waitForSimulatorBootAsync).mock.calls.length === 1);
|
||||
expect(waitForSimulatorBootAsync).toHaveBeenCalledWith('PHONE18', expect.any(AbortSignal));
|
||||
await expect(session.claimAsync({ engine: 'serve-sim' })).resolves.toMatchObject({
|
||||
device: defaultDevice,
|
||||
});
|
||||
expect(onPreparationFailure).not.toHaveBeenCalled();
|
||||
await session.stopAsync();
|
||||
});
|
||||
|
||||
it('claim latches preinstalls before async selection; prepare-tools waits for the selected install', async () => {
|
||||
const installation = deferred<undefined>();
|
||||
const preinstall = startExpoGoPreinstall(controller.signal);
|
||||
jest
|
||||
.mocked(preinstall.claimAsync)
|
||||
.mockImplementation(udid =>
|
||||
udid === 'PHONE18' ? installation.promise : Promise.resolve(undefined)
|
||||
);
|
||||
const session = createSession();
|
||||
await session.prepareAsync();
|
||||
const claiming = session.claimAsync({ engine: 'serve-sim', requestedDevice: 'iPhone 18' });
|
||||
expect(preinstall.claimAsync).toHaveBeenCalledWith('DUO');
|
||||
expect(preinstall.claimAsync).toHaveBeenCalledWith('PHONE18');
|
||||
expect((await claiming).device).toEqual(secondary);
|
||||
let prepared = false;
|
||||
const preparing = session.prepareToolsAsync().then(() => {
|
||||
prepared = true;
|
||||
});
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(prepared).toBe(false);
|
||||
installation.resolve(undefined);
|
||||
await preparing;
|
||||
await session.stopAsync();
|
||||
});
|
||||
|
||||
it('unused preinstall failure does not reject a default claim, but terminal stop retains uncertainty', async () => {
|
||||
const failure = new Error('unused install not drained');
|
||||
const preinstall = startExpoGoPreinstall(controller.signal);
|
||||
jest.mocked(preinstall.claimAsync).mockImplementation(async udid => {
|
||||
if (udid === 'PHONE18') {
|
||||
throw failure;
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
jest.mocked(preinstall.stopAsync).mockImplementation(async udid => {
|
||||
if (udid === 'PHONE18') {
|
||||
throw failure;
|
||||
}
|
||||
});
|
||||
const session = createSession();
|
||||
await session.prepareAsync();
|
||||
await expect(session.claimAsync({ engine: 'serve-sim' })).resolves.toMatchObject({
|
||||
device: defaultDevice,
|
||||
});
|
||||
await expect(session.stopAsync()).rejects.toMatchObject({ errors: [failure] });
|
||||
expect(shutdownSimulatorAsync).toHaveBeenCalledWith('DUO');
|
||||
});
|
||||
|
||||
it('EXPO_SIMULATOR_PREINSTALL_EXPO_GO=0 skips the Expo Go preinstall', async () => {
|
||||
process.env.EXPO_SIMULATOR_PREINSTALL_EXPO_GO = '0';
|
||||
const session = createSession();
|
||||
await session.prepareAsync();
|
||||
await session.claimAsync({ engine: 'serve-sim' });
|
||||
await expect(session.prepareToolsAsync()).resolves.toEqual({});
|
||||
expect(startExpoGoPreinstall).not.toHaveBeenCalled();
|
||||
await session.stopAsync();
|
||||
});
|
||||
|
||||
it('retains selected preinstall failure instead of handing over an uncertain install', async () => {
|
||||
const failure = new Error('selected install failed');
|
||||
const preinstall = startExpoGoPreinstall(controller.signal);
|
||||
jest.mocked(preinstall.claimAsync).mockRejectedValue(failure);
|
||||
const session = createSession();
|
||||
await session.prepareAsync();
|
||||
await session.claimAsync({ engine: 'serve-sim' });
|
||||
await expect(session.prepareToolsAsync()).rejects.toBe(failure);
|
||||
await session.stopAsync();
|
||||
});
|
||||
|
||||
it('reuses the default runner after adoption without preparing it twice', async () => {
|
||||
const preparation = deferred<string>();
|
||||
jest
|
||||
.mocked(commands.start)
|
||||
.mockImplementation((_file, args) =>
|
||||
args.includes('prepare') ? { ...agent, resultPromise: preparation.promise } : argent
|
||||
);
|
||||
const session = createSession();
|
||||
await session.prepareAsync();
|
||||
await session.claimAsync({ engine: 'agent-device' });
|
||||
let ready = false;
|
||||
const tools = session.prepareToolsAsync().then(() => {
|
||||
ready = true;
|
||||
});
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(ready).toBe(false);
|
||||
preparation.resolve('');
|
||||
await tools;
|
||||
expect(starts('prepare')).toHaveLength(1);
|
||||
await session.stopAsync();
|
||||
});
|
||||
|
||||
it('starts the selected runner only in the post-adopt phase, after old runner retirement', async () => {
|
||||
const retirement = deferred();
|
||||
jest.mocked(stopProcessAndDescendantsAsync).mockImplementation(async handle => {
|
||||
if (handle === agent) {
|
||||
await retirement.promise;
|
||||
}
|
||||
});
|
||||
const session = createSession();
|
||||
await session.prepareAsync();
|
||||
await session.claimAsync({ engine: 'agent-device', requestedDevice: 'PHONE18' });
|
||||
expect(starts('prepare')).toHaveLength(1);
|
||||
let finished = false;
|
||||
const tools = session.prepareToolsAsync().then(() => {
|
||||
finished = true;
|
||||
});
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(finished).toBe(false);
|
||||
expect(starts('prepare')).toHaveLength(1);
|
||||
retirement.resolve();
|
||||
await tools;
|
||||
expect(starts('prepare')[1][1]).toEqual(expect.arrayContaining(['--udid', 'PHONE18']));
|
||||
await session.stopAsync();
|
||||
});
|
||||
|
||||
it('keeps global Argent when selecting another device', async () => {
|
||||
const session = createSession();
|
||||
await session.prepareAsync();
|
||||
await session.claimAsync({ engine: 'argent', requestedDevice: 'PHONE18' });
|
||||
await session.prepareToolsAsync();
|
||||
expect(starts('server')).toHaveLength(1);
|
||||
expect(stopProcessAndDescendantsAsync).not.toHaveBeenCalledWith(argent);
|
||||
await session.stopAsync();
|
||||
});
|
||||
|
||||
it('rejects a changed server identity before starting the selected runner', async () => {
|
||||
const session = createSession();
|
||||
await session.prepareAsync();
|
||||
await session.claimAsync({ engine: 'agent-device', requestedDevice: 'PHONE18' });
|
||||
jest.mocked(waitForServeSimReadyAsync).mockResolvedValueOnce({ ...serverInfo, pid: 99 });
|
||||
await expect(session.prepareToolsAsync()).rejects.toThrow('does not match');
|
||||
expect(starts('prepare')).toHaveLength(1);
|
||||
await session.stopAsync();
|
||||
});
|
||||
|
||||
it('drains partial preparation, all shutdowns and sibling failures before rejecting cleanup', async () => {
|
||||
const readyFailure = new Error('server not ready');
|
||||
jest.mocked(waitForServeSimReadyAsync).mockRejectedValue(readyFailure);
|
||||
const failure = new Error('server stop failed');
|
||||
jest.mocked(stopProcessAndDescendantsAsync).mockImplementation(async handle => {
|
||||
if (handle === server) {
|
||||
throw failure;
|
||||
}
|
||||
});
|
||||
const delayed = deferred();
|
||||
jest.mocked(shutdownSimulatorAsync).mockImplementation(async udid => {
|
||||
if (udid === 'PHONE18') {
|
||||
await delayed.promise;
|
||||
}
|
||||
});
|
||||
const session = createSession();
|
||||
await expect(session.prepareAsync()).rejects.toBe(readyFailure);
|
||||
let finished = false;
|
||||
const stopping = session.stopAsync().finally(() => {
|
||||
finished = true;
|
||||
});
|
||||
void stopping.catch(() => {});
|
||||
await until(() => jest.mocked(shutdownSimulatorAsync).mock.calls.length === 2);
|
||||
expect(finished).toBe(false);
|
||||
delayed.resolve();
|
||||
await expect(stopping).rejects.toMatchObject({ errors: [failure] });
|
||||
});
|
||||
|
||||
it('serve-sim tool preparation does not gate on unused tool stops, but terminal cleanup drains them', async () => {
|
||||
const retirement = deferred();
|
||||
jest.mocked(stopProcessAndDescendantsAsync).mockImplementation(async handle => {
|
||||
if (handle === agent) {
|
||||
await retirement.promise;
|
||||
}
|
||||
});
|
||||
const session = createSession();
|
||||
await session.prepareAsync();
|
||||
await session.claimAsync({ engine: 'serve-sim' });
|
||||
await session.prepareToolsAsync();
|
||||
let stopped = false;
|
||||
const stopping = session.stopAsync().then(() => {
|
||||
stopped = true;
|
||||
});
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(stopped).toBe(false);
|
||||
retirement.resolve();
|
||||
await stopping;
|
||||
});
|
||||
|
||||
it('a failed unused-tool stop after the claim keeps the session and the stop retries it', async () => {
|
||||
const failure = new Error('Argent is still running');
|
||||
const stop = jest.mocked(stopProcessAndDescendantsAsync).mockImplementation(async handle => {
|
||||
if (handle === argent) {
|
||||
throw failure;
|
||||
}
|
||||
});
|
||||
const warning = jest.spyOn(process.stderr, 'write').mockReturnValue(true);
|
||||
const session = createSession();
|
||||
await session.prepareAsync();
|
||||
await session.claimAsync({ engine: 'serve-sim' });
|
||||
await until(() => warning.mock.calls.some(([text]) => String(text).includes('retrying at stop')));
|
||||
await session.prepareToolsAsync();
|
||||
expect(controller.signal.aborted).toBe(false);
|
||||
// The retry fails too, so the stop reports it.
|
||||
await expect(session.stopAsync()).rejects.toMatchObject({ errors: [failure] });
|
||||
expect(stop.mock.calls.filter(([handle]) => handle === argent)).toHaveLength(2);
|
||||
expect(shutdownSimulatorAsync).toHaveBeenCalledWith('DUO');
|
||||
});
|
||||
|
||||
it('starts an owned nonblocking apsd attempt after selected adoption and drains it before shutdown', async () => {
|
||||
const session = createSession();
|
||||
await session.prepareAsync();
|
||||
await session.claimAsync({ engine: 'serve-sim', requestedDevice: 'OTHER' });
|
||||
const setup = deferred();
|
||||
const disable = jest.mocked(disableApsdAsync).mockImplementation(() => setup.promise);
|
||||
try {
|
||||
await session.prepareToolsAsync();
|
||||
// The setup runs in the background.
|
||||
await until(() => disable.mock.calls.some(([udid]) => udid === 'OTHER'));
|
||||
expect(disable).toHaveBeenCalledWith('OTHER', expect.any(AbortSignal));
|
||||
let stopped = false;
|
||||
const stopping = session.stopAsync().then(() => {
|
||||
stopped = true;
|
||||
});
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(stopped).toBe(false);
|
||||
expect(shutdownSimulatorAsync).not.toHaveBeenCalled();
|
||||
setup.resolve();
|
||||
await stopping;
|
||||
expect(shutdownSimulatorAsync).toHaveBeenCalledWith('OTHER');
|
||||
} finally {
|
||||
setup.resolve();
|
||||
await session.stopAsync();
|
||||
}
|
||||
});
|
||||
|
||||
it('does not repeat completed default-device setup after adoption', async () => {
|
||||
const session = createSession();
|
||||
await session.prepareAsync();
|
||||
jest.mocked(disableApsdAsync).mockClear();
|
||||
await session.claimAsync({ engine: 'serve-sim' });
|
||||
await session.prepareToolsAsync();
|
||||
expect(disableApsdAsync).not.toHaveBeenCalled();
|
||||
await session.stopAsync();
|
||||
});
|
||||
|
||||
it('reports ready before apsd finishes; the claim does not wait for it and stop joins it', async () => {
|
||||
const disabled = deferred();
|
||||
const signals = new Map<string, AbortSignal>();
|
||||
const disable = jest.mocked(disableApsdAsync).mockImplementation(
|
||||
(udid, signal) =>
|
||||
new Promise((resolve, reject) => {
|
||||
signals.set(udid, signal);
|
||||
if (udid === 'DUO') {
|
||||
void disabled.promise.then(resolve);
|
||||
}
|
||||
signal.addEventListener('abort', () => reject(signal.reason), { once: true });
|
||||
})
|
||||
);
|
||||
const session = createSession();
|
||||
await session.prepareAsync();
|
||||
await until(() => signals.has('DUO') && signals.has('PHONE18'));
|
||||
// The claim returns while both apsd steps still run; stop cancels and joins them.
|
||||
await session.claimAsync({ engine: 'serve-sim' });
|
||||
expect(signals.get('DUO')!.aborted).toBe(false);
|
||||
expect(signals.get('PHONE18')!.aborted).toBe(false);
|
||||
await session.stopAsync();
|
||||
expect(disable.mock.calls.filter(([udid]) => udid === 'DUO')).toHaveLength(1);
|
||||
expect(signals.get('DUO')!.aborted).toBe(true);
|
||||
expect(signals.get('PHONE18')!.aborted).toBe(true);
|
||||
disabled.resolve();
|
||||
});
|
||||
|
||||
it('does not report a background failure when a stop aborts the default setup', async () => {
|
||||
const disable = jest
|
||||
.mocked(disableApsdAsync)
|
||||
.mockImplementation(
|
||||
(_udid, signal) =>
|
||||
new Promise((_resolve, reject) =>
|
||||
signal.addEventListener('abort', () => reject(signal.reason), { once: true })
|
||||
)
|
||||
);
|
||||
const session = createSession();
|
||||
const preparing = session.prepareAsync().catch(() => {});
|
||||
await until(() => disable.mock.calls.length > 0);
|
||||
await session.stopAsync();
|
||||
await preparing;
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
});
|
||||
|
||||
it('warns on ordinary adopted-device apsd failure without failing the claimed session', async () => {
|
||||
const session = createSession();
|
||||
await session.prepareAsync();
|
||||
await session.claimAsync({ engine: 'serve-sim', requestedDevice: 'OTHER' });
|
||||
jest.mocked(disableApsdAsync).mockRejectedValue(new Error('apsd remains loaded'));
|
||||
const warning = jest.spyOn(process.stderr, 'write').mockReturnValue(true);
|
||||
await session.prepareToolsAsync();
|
||||
// The setup runs in the background; wait for its warning before stopping.
|
||||
await until(() =>
|
||||
warning.mock.calls.some(([text]) => String(text).includes('Could not disable apsd on OTHER'))
|
||||
);
|
||||
await session.stopAsync();
|
||||
expect(onPreparationFailure).not.toHaveBeenCalled();
|
||||
expect(warning.mock.calls.map(([text]) => text).join('')).toContain(
|
||||
'Could not disable apsd on OTHER; continuing'
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,265 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { claimAsync } from '../commands/claim';
|
||||
import { stopAsync } from '../commands/stop';
|
||||
import {
|
||||
LAUNCHER_STATE_FILE,
|
||||
readLauncherStateAsync,
|
||||
updateLauncherStateAsync,
|
||||
waitForLauncherStateAsync,
|
||||
} from '../utils/state';
|
||||
import { deferred } from './helpers';
|
||||
|
||||
const boot = 'boot-one';
|
||||
let root: string;
|
||||
const info = {
|
||||
device: { udid: 'PHONE', name: 'iPhone 17' },
|
||||
server: {
|
||||
startupDevice: 'PHONE',
|
||||
pid: 9001,
|
||||
nativeStartTime: 'native-start',
|
||||
port: 3200,
|
||||
url: 'http://127.0.0.1:3200',
|
||||
token: 'fixture-token',
|
||||
},
|
||||
controllerPid: 9000,
|
||||
controllerStartTime: 'Thu Oct 22 10:00:00 2026',
|
||||
agentDeviceStateDir: '/agent',
|
||||
argentEventLogPath: '/argent/events',
|
||||
};
|
||||
const directory = () => path.join(root, 'control');
|
||||
|
||||
const nativeFs = {
|
||||
readFile: fs.readFile.bind(fs),
|
||||
writeFile: fs.writeFile.bind(fs),
|
||||
rename: fs.rename.bind(fs),
|
||||
rm: fs.rm.bind(fs),
|
||||
mkdir: fs.mkdir.bind(fs),
|
||||
rmdir: fs.rmdir.bind(fs),
|
||||
stat: fs.stat.bind(fs),
|
||||
};
|
||||
const remap = (file: unknown): unknown =>
|
||||
typeof file === 'string' && file.startsWith(LAUNCHER_STATE_FILE)
|
||||
? path.join(root, 'control', path.basename(file))
|
||||
: file;
|
||||
|
||||
beforeEach(async () => {
|
||||
root = await fs.mkdtemp(path.join(os.tmpdir(), 'launcher-state-'));
|
||||
jest.spyOn(os, 'homedir').mockReturnValue(root);
|
||||
await fs.mkdir(path.join(root, 'control'));
|
||||
for (const name of ['readFile', 'writeFile', 'rename', 'rm', 'mkdir', 'rmdir', 'stat'] as const) {
|
||||
jest.spyOn(fs, name).mockImplementation(((...args: unknown[]) => {
|
||||
args[0] = remap(args[0]);
|
||||
if (name === 'rename') {
|
||||
args[1] = remap(args[1]);
|
||||
}
|
||||
return (nativeFs[name] as (...args: unknown[]) => unknown)(...args);
|
||||
}) as never);
|
||||
}
|
||||
});
|
||||
afterEach(async () => {
|
||||
jest.restoreAllMocks();
|
||||
await fs.rm(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test('missing and old-boot state are unavailable, while access errors propagate', async () => {
|
||||
expect(await readLauncherStateAsync(boot)).toBeUndefined();
|
||||
await updateLauncherStateAsync('old-boot', () => ({ bootUuid: 'old-boot', status: 'disabled' }));
|
||||
expect(await readLauncherStateAsync(boot)).toBeUndefined();
|
||||
const error = Object.assign(new Error('state inaccessible'), { code: 'EACCES' });
|
||||
jest.spyOn(fs, 'readFile').mockRejectedValueOnce(error);
|
||||
await expect(readLauncherStateAsync(boot)).rejects.toBe(error);
|
||||
});
|
||||
|
||||
test('old-boot locks are ignored without being removed or stolen', async () => {
|
||||
await fs.mkdir(`${LAUNCHER_STATE_FILE}.old-boot.lock`, { recursive: true });
|
||||
await stopAsync(boot);
|
||||
expect(await readLauncherStateAsync(boot)).toEqual({ bootUuid: boot, status: 'disabled' });
|
||||
expect((await fs.stat(`${LAUNCHER_STATE_FILE}.old-boot.lock`)).isDirectory()).toBe(true);
|
||||
});
|
||||
|
||||
test('a current-boot crash lock times out fail-closed and remains untouched', async () => {
|
||||
const lock = `${LAUNCHER_STATE_FILE}.${boot}.lock`;
|
||||
await fs.mkdir(lock, { recursive: true });
|
||||
let calls = 0;
|
||||
jest.spyOn(Date, 'now').mockImplementation(() => (calls++ ? 5_001 : 0));
|
||||
await expect(stopAsync(boot)).rejects.toThrow('state is locked');
|
||||
expect((await fs.stat(lock)).isDirectory()).toBe(true);
|
||||
expect(await readLauncherStateAsync(boot)).toBeUndefined();
|
||||
});
|
||||
|
||||
for (const operation of ['callback', 'writeFile', 'rename'] as const) {
|
||||
test(`${operation} failure preserves old state and releases only the owned temporary files/lock`, async () => {
|
||||
await updateLauncherStateAsync(boot, () => ({ bootUuid: boot, status: 'starting' }));
|
||||
const error = Object.assign(new Error('disk error'), { code: 'EIO' });
|
||||
if (operation !== 'callback') {
|
||||
jest.spyOn(fs, operation).mockRejectedValueOnce(error);
|
||||
}
|
||||
await expect(
|
||||
updateLauncherStateAsync(boot, state => {
|
||||
if (operation === 'callback') {
|
||||
throw error;
|
||||
}
|
||||
return { ...state!, status: 'ready' };
|
||||
})
|
||||
).rejects.toBe(error);
|
||||
expect((await readLauncherStateAsync(boot))?.status).toBe('starting');
|
||||
expect(await fs.readdir(directory())).toEqual([path.basename(LAUNCHER_STATE_FILE)]);
|
||||
});
|
||||
}
|
||||
|
||||
test('cancellation after the temporary write cannot publish the next state', async () => {
|
||||
await updateLauncherStateAsync(boot, () => ({ bootUuid: boot, status: 'starting' }));
|
||||
const abort = new AbortController();
|
||||
const write = nativeFs.writeFile;
|
||||
jest.spyOn(fs, 'writeFile').mockImplementation((async (file, data, ...args) => {
|
||||
await write(remap(file) as string, data, ...args);
|
||||
abort.abort(new Error('cancelled'));
|
||||
}) as typeof fs.writeFile);
|
||||
await expect(
|
||||
updateLauncherStateAsync(boot, state => ({ ...state!, status: 'ready' }), abort.signal)
|
||||
).rejects.toThrow('cancelled');
|
||||
expect((await readLauncherStateAsync(boot))?.status).toBe('starting');
|
||||
expect(await fs.readdir(directory())).toEqual([path.basename(LAUNCHER_STATE_FILE)]);
|
||||
});
|
||||
|
||||
test.each(['ready', 'claimed'] as const)(
|
||||
'a pending %s writer publishes complete JSON before a stop, which cannot be overwritten',
|
||||
async publication => {
|
||||
await updateLauncherStateAsync(boot, () => ({
|
||||
bootUuid: boot,
|
||||
status: publication === 'ready' ? 'starting' : 'claiming',
|
||||
engine: 'serve-sim',
|
||||
...info,
|
||||
}));
|
||||
const writing = deferred();
|
||||
const release = deferred();
|
||||
const write = nativeFs.writeFile;
|
||||
jest.spyOn(fs, 'writeFile').mockImplementation((async (file, data, ...args) => {
|
||||
if (JSON.parse(String(data)).status === publication) {
|
||||
await write(remap(file) as string, '{"bootUuid":');
|
||||
writing.resolve();
|
||||
await release.promise;
|
||||
await write(remap(file) as string, data);
|
||||
return;
|
||||
}
|
||||
await write(remap(file) as string, data, ...args);
|
||||
}) as typeof fs.writeFile);
|
||||
const ready = updateLauncherStateAsync(boot, state => ({ ...state!, status: publication }));
|
||||
try {
|
||||
await writing.promise;
|
||||
expect((await readLauncherStateAsync(boot))?.status).toBe(
|
||||
publication === 'ready' ? 'starting' : 'claiming'
|
||||
);
|
||||
const stopping = stopAsync(boot);
|
||||
release.resolve();
|
||||
await ready;
|
||||
await waitForLauncherStateAsync(boot, state => state?.status === 'stopping', 1_000);
|
||||
await expect(
|
||||
updateLauncherStateAsync(boot, state => {
|
||||
if (state?.status !== 'ready') {
|
||||
throw new Error('stop already won');
|
||||
}
|
||||
return { ...state, status: 'claimed' };
|
||||
})
|
||||
).rejects.toThrow('stop already won');
|
||||
await updateLauncherStateAsync(boot, state => ({ ...state!, status: 'disabled' }));
|
||||
expect(await stopping).toBe(0);
|
||||
} finally {
|
||||
release.resolve();
|
||||
await ready;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
test('two job claims acquire only one ready session and the result includes its metadata', async () => {
|
||||
await updateLauncherStateAsync(boot, () => ({ bootUuid: boot, status: 'ready', ...info }));
|
||||
const output = jest.spyOn(process.stdout, 'write').mockReturnValue(true);
|
||||
const results: unknown[] = [];
|
||||
const claims = ['serve-sim', 'argent'].map(engine =>
|
||||
claimAsync(boot, engine).then(
|
||||
value => results.push(value),
|
||||
error => results.push(error)
|
||||
)
|
||||
);
|
||||
await waitForLauncherStateAsync(boot, state => state?.status === 'claiming', 1_000);
|
||||
for (let i = 0; i < 100 && results.length === 0; i++) {
|
||||
await new Promise(resolve => setTimeout(resolve, 5));
|
||||
}
|
||||
expect(results[0]).toBeInstanceOf(Error);
|
||||
await updateLauncherStateAsync(boot, state => ({ ...state!, status: 'claimed' }));
|
||||
await Promise.all(claims);
|
||||
expect(results.filter(value => value === 0)).toHaveLength(1);
|
||||
expect(JSON.parse(String(output.mock.calls[0][0]))).toMatchObject({
|
||||
...info,
|
||||
status: 'claimed',
|
||||
bootUuid: boot,
|
||||
});
|
||||
await expect(claimAsync(boot, 'serve-sim')).rejects.toThrow('available');
|
||||
});
|
||||
|
||||
test('a claim fails when the launcher hands over a different device than requested', async () => {
|
||||
await updateLauncherStateAsync(boot, () => ({ bootUuid: boot, status: 'ready', ...info }));
|
||||
const claim = expect(claimAsync(boot, 'serve-sim', 'iPad Pro')).rejects.toThrow(
|
||||
'claimed iPhone 17, not iPad Pro'
|
||||
);
|
||||
await waitForLauncherStateAsync(boot, state => state?.status === 'claiming', 1_000);
|
||||
await updateLauncherStateAsync(boot, state => ({ ...state!, status: 'claimed' }));
|
||||
await claim;
|
||||
});
|
||||
|
||||
test('an interrupted claim reports the launcher error', async () => {
|
||||
await updateLauncherStateAsync(boot, () => ({ bootUuid: boot, status: 'ready', ...info }));
|
||||
const claim = expect(claimAsync(boot, 'serve-sim')).rejects.toThrow(
|
||||
'cleanup may still be running. serve-sim exited'
|
||||
);
|
||||
await waitForLauncherStateAsync(boot, state => state?.status === 'claiming', 1_000);
|
||||
await updateLauncherStateAsync(boot, state => ({
|
||||
...state!,
|
||||
status: 'stopping',
|
||||
error: 'serve-sim exited',
|
||||
}));
|
||||
await claim;
|
||||
});
|
||||
|
||||
test.each([
|
||||
[undefined, undefined],
|
||||
['unsupported', undefined],
|
||||
['serve-sim', ' '],
|
||||
])(
|
||||
'invalid claim engine/selector %s/%s cannot mutate or acquire ready state',
|
||||
async (engine, selector) => {
|
||||
await updateLauncherStateAsync(boot, () => ({ bootUuid: boot, status: 'ready', ...info }));
|
||||
const before = await readLauncherStateAsync(boot);
|
||||
await expect(claimAsync(boot, engine, selector)).rejects.toThrow(
|
||||
'Invalid Simulator session request'
|
||||
);
|
||||
expect(await readLauncherStateAsync(boot)).toEqual(before);
|
||||
expect(await fs.readdir(directory())).toEqual([path.basename(LAUNCHER_STATE_FILE)]);
|
||||
}
|
||||
);
|
||||
|
||||
test('concurrent resource-free stops leave one disabled record without extra ownership files', async () => {
|
||||
expect(await Promise.all([stopAsync(boot), stopAsync(boot)])).toEqual([0, 0]);
|
||||
expect(await fs.readdir(directory())).toEqual([path.basename(LAUNCHER_STATE_FILE)]);
|
||||
expect(await readLauncherStateAsync(boot)).toEqual({ bootUuid: boot, status: 'disabled' });
|
||||
});
|
||||
|
||||
test('stopping is not cleanup completion and polling stays bounded', async () => {
|
||||
await updateLauncherStateAsync(boot, () => ({
|
||||
bootUuid: boot,
|
||||
status: 'stopping',
|
||||
error: 'cleanup incomplete',
|
||||
}));
|
||||
await expect(
|
||||
waitForLauncherStateAsync(boot, state => state?.status === 'disabled', 1)
|
||||
).rejects.toThrow('cleanup may still be running');
|
||||
expect((await readLauncherStateAsync(boot))?.status).toBe('stopping');
|
||||
});
|
||||
|
||||
test('the single state record keeps server credentials private to its OS user', async () => {
|
||||
await updateLauncherStateAsync(boot, () => ({ bootUuid: boot, status: 'ready', ...info }));
|
||||
expect((await fs.stat(LAUNCHER_STATE_FILE)).mode & 0o777).toBe(0o600);
|
||||
});
|
||||
@@ -0,0 +1,162 @@
|
||||
import { type ChildProcess } from 'node:child_process';
|
||||
|
||||
import { createAgentDeviceTool } from '../utils/agentDevice';
|
||||
import { commands, stopProcessAndDescendantsAsync } from '../utils/processes';
|
||||
import { type WarmTool, startTool } from '../utils/tools';
|
||||
import { deferred } from './helpers';
|
||||
|
||||
jest.mock('../utils/processes');
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
jest.mocked(commands.runAsync).mockResolvedValue('');
|
||||
jest.mocked(stopProcessAndDescendantsAsync).mockResolvedValue();
|
||||
});
|
||||
|
||||
it('prepares at once, starts after serve-sim, and reports a failure before cancellation', async () => {
|
||||
const serveSimReady = deferred();
|
||||
const failure = new Error('start failed');
|
||||
const tool: WarmTool = {
|
||||
name: 'argent',
|
||||
prepareAsync: jest.fn(async () => {}),
|
||||
startAsync: jest.fn(async () => {
|
||||
throw failure;
|
||||
}),
|
||||
stopAsync: jest.fn(async () => {}),
|
||||
};
|
||||
const onFailure = jest.fn();
|
||||
const started = startTool(
|
||||
tool,
|
||||
'PHONE',
|
||||
serveSimReady.promise,
|
||||
new AbortController().signal,
|
||||
onFailure
|
||||
);
|
||||
expect(tool.prepareAsync).toHaveBeenCalledTimes(1);
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(tool.startAsync).not.toHaveBeenCalled();
|
||||
serveSimReady.resolve();
|
||||
await expect(started.ready).rejects.toBe(failure);
|
||||
expect(tool.startAsync).toHaveBeenCalledWith('PHONE', expect.any(AbortSignal));
|
||||
expect(onFailure).toHaveBeenCalledWith(failure);
|
||||
});
|
||||
|
||||
it('stops agent-device mid-prepare without reporting it, and stops the daemon', async () => {
|
||||
const preparing = deferred<string>();
|
||||
const prepare = { child: { pid: 11 } as ChildProcess, resultPromise: preparing.promise };
|
||||
jest.mocked(commands.start).mockReturnValue(prepare);
|
||||
const onFailure = jest.fn();
|
||||
const started = startTool(
|
||||
createAgentDeviceTool(),
|
||||
'PHONE',
|
||||
Promise.resolve(),
|
||||
new AbortController().signal,
|
||||
onFailure
|
||||
);
|
||||
try {
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(commands.start).toHaveBeenCalledTimes(1);
|
||||
expect(commands.start).toHaveBeenCalledWith(
|
||||
'bunx',
|
||||
expect.arrayContaining(['prepare', 'ios-runner']),
|
||||
{ detached: true }
|
||||
);
|
||||
// The prepare process is still running; the stop does not wait for it to exit by itself.
|
||||
await started.stopAsync();
|
||||
expect(stopProcessAndDescendantsAsync).toHaveBeenCalledWith(prepare, true);
|
||||
expect(commands.runAsync).toHaveBeenCalledWith(
|
||||
'bunx',
|
||||
expect.arrayContaining(['daemon', 'stop']),
|
||||
expect.any(AbortSignal)
|
||||
);
|
||||
expect(onFailure).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
preparing.resolve('');
|
||||
}
|
||||
});
|
||||
|
||||
it('stops the agent-device daemon even when the prepare process cannot be stopped', async () => {
|
||||
const prepare = { child: { pid: 11 } as ChildProcess, resultPromise: Promise.resolve('') };
|
||||
const failure = new Error('prepare stop failed');
|
||||
jest.mocked(commands.start).mockReturnValue(prepare);
|
||||
jest.mocked(stopProcessAndDescendantsAsync).mockRejectedValueOnce(failure);
|
||||
const tool = createAgentDeviceTool();
|
||||
await tool.startAsync('PHONE', new AbortController().signal);
|
||||
await expect(tool.stopAsync()).rejects.toBe(failure);
|
||||
expect(commands.runAsync).toHaveBeenCalledWith(
|
||||
'bunx',
|
||||
expect.arrayContaining(['daemon', 'stop']),
|
||||
expect.any(AbortSignal)
|
||||
);
|
||||
// The prepare process stays owned, so a later stop tries it again.
|
||||
await tool.stopAsync();
|
||||
expect(jest.mocked(stopProcessAndDescendantsAsync).mock.calls).toEqual([
|
||||
[prepare, true],
|
||||
[prepare, true],
|
||||
]);
|
||||
});
|
||||
|
||||
it('reports a synchronous prepare throw through ready instead of throwing from startTool', async () => {
|
||||
const failure = new Error('prepare threw');
|
||||
const tool: WarmTool = {
|
||||
name: 'argent',
|
||||
prepareAsync: () => {
|
||||
throw failure;
|
||||
},
|
||||
startAsync: jest.fn(async () => {}),
|
||||
stopAsync: jest.fn(async () => {}),
|
||||
};
|
||||
const onFailure = jest.fn();
|
||||
const started = startTool(
|
||||
tool,
|
||||
'PHONE',
|
||||
Promise.resolve(),
|
||||
new AbortController().signal,
|
||||
onFailure
|
||||
);
|
||||
await expect(started.ready).rejects.toBe(failure);
|
||||
expect(tool.startAsync).not.toHaveBeenCalled();
|
||||
expect(onFailure).toHaveBeenCalledWith(failure);
|
||||
});
|
||||
|
||||
it('keeps both errors when the agent-device prepare and daemon stops fail', async () => {
|
||||
const prepare = { child: { pid: 11 } as ChildProcess, resultPromise: Promise.resolve('') };
|
||||
const prepareFailure = new Error('prepare stop failed');
|
||||
const daemonFailure = new Error('daemon stop failed');
|
||||
jest.mocked(commands.start).mockReturnValue(prepare);
|
||||
jest.mocked(stopProcessAndDescendantsAsync).mockRejectedValueOnce(prepareFailure);
|
||||
jest.mocked(commands.runAsync).mockRejectedValueOnce(daemonFailure);
|
||||
const tool = createAgentDeviceTool();
|
||||
await tool.startAsync('PHONE', new AbortController().signal);
|
||||
await expect(tool.stopAsync()).rejects.toMatchObject({ errors: [prepareFailure, daemonFailure] });
|
||||
});
|
||||
|
||||
it('drains independent tool preparation after serve-sim readiness rejects', async () => {
|
||||
const prepared = deferred();
|
||||
const failure = new Error('serve-sim readiness failed');
|
||||
const tool: WarmTool = {
|
||||
name: 'argent',
|
||||
prepareAsync: () => prepared.promise,
|
||||
startAsync: jest.fn(async () => {}),
|
||||
stopAsync: jest.fn(async () => {}),
|
||||
};
|
||||
const started = startTool(
|
||||
tool,
|
||||
'PHONE',
|
||||
Promise.reject(failure),
|
||||
new AbortController().signal,
|
||||
jest.fn()
|
||||
);
|
||||
await expect(started.ready).rejects.toBe(failure);
|
||||
let stopped = false;
|
||||
const stopping = started.stopAsync().then(() => {
|
||||
stopped = true;
|
||||
});
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(stopped).toBe(false);
|
||||
expect(tool.stopAsync).not.toHaveBeenCalled();
|
||||
prepared.resolve();
|
||||
await stopping;
|
||||
expect(tool.startAsync).not.toHaveBeenCalled();
|
||||
expect(tool.stopAsync).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
import {
|
||||
ClaimInputSchema,
|
||||
WarmSessionInfoSchema,
|
||||
updateLauncherStateAsync,
|
||||
waitForLauncherStateAsync,
|
||||
} from '../utils/state';
|
||||
|
||||
export async function claimAsync(
|
||||
bootUuid: string,
|
||||
engine?: string,
|
||||
requestedDevice?: string
|
||||
): Promise<number> {
|
||||
const input = ClaimInputSchema.safeParse({ engine, requestedDevice });
|
||||
if (!input.success) {
|
||||
throw new Error(
|
||||
`Invalid Simulator session request. Choose ${ClaimInputSchema.shape.engine.options.join(', ')} and an optional device name or UDID.`
|
||||
);
|
||||
}
|
||||
const acquired = await updateLauncherStateAsync(bootUuid, state => {
|
||||
if (state?.status !== 'ready') {
|
||||
throw new Error('No warm Simulator session is available to claim on this VM.');
|
||||
}
|
||||
WarmSessionInfoSchema.parse(state);
|
||||
return { ...state, ...input.data, status: 'claiming' };
|
||||
});
|
||||
const claimed = await waitForLauncherStateAsync(
|
||||
bootUuid,
|
||||
state => {
|
||||
if (!state || state.status === 'stopping' || state.status === 'disabled') {
|
||||
throw new Error(
|
||||
`Simulator preparation was interrupted; cleanup may still be running.${state?.error ? ` ${state.error}` : ''}`
|
||||
);
|
||||
}
|
||||
if (
|
||||
state.controllerPid !== acquired.controllerPid ||
|
||||
state.controllerStartTime !== acquired.controllerStartTime ||
|
||||
state.engine !== engine
|
||||
) {
|
||||
throw new Error('The Simulator launcher returned a different session or engine.');
|
||||
}
|
||||
return state.status === 'claimed';
|
||||
},
|
||||
420_000
|
||||
);
|
||||
const { device } = WarmSessionInfoSchema.parse(claimed);
|
||||
if (
|
||||
requestedDevice &&
|
||||
device.name !== requestedDevice &&
|
||||
device.udid.toLowerCase() !== requestedDevice.toLowerCase()
|
||||
) {
|
||||
throw new Error(`The Simulator launcher claimed ${device.name}, not ${requestedDevice}.`);
|
||||
}
|
||||
process.stdout.write(`${JSON.stringify(claimed)}\n`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Continue the consumed claim after private serve-sim adoption, without acquiring another job. */
|
||||
export async function prepareToolsAsync(bootUuid: string): Promise<number> {
|
||||
const acquired = await updateLauncherStateAsync(bootUuid, state => {
|
||||
if (state?.status !== 'claimed') {
|
||||
throw new Error('Claim and adopt the warm Simulator session before preparing its tools.');
|
||||
}
|
||||
WarmSessionInfoSchema.parse(state);
|
||||
return { ...state, prepareToolsRequested: true };
|
||||
});
|
||||
const ready = await waitForLauncherStateAsync(
|
||||
bootUuid,
|
||||
state => {
|
||||
if (
|
||||
!state ||
|
||||
state.status !== 'claimed' ||
|
||||
state.controllerPid !== acquired.controllerPid ||
|
||||
state.controllerStartTime !== acquired.controllerStartTime ||
|
||||
state.device?.udid !== acquired.device?.udid ||
|
||||
state.engine !== acquired.engine
|
||||
) {
|
||||
throw new Error(
|
||||
'Warm Simulator tool preparation was interrupted; cleanup may still be running.'
|
||||
);
|
||||
}
|
||||
return state.toolsReady === true;
|
||||
},
|
||||
420_000
|
||||
);
|
||||
process.stdout.write(`${JSON.stringify(ready)}\n`);
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,557 @@
|
||||
import { once } from 'node:events';
|
||||
import { setTimeout as sleepAsync } from 'node:timers/promises';
|
||||
|
||||
import { createAgentDeviceTool } from '../utils/agentDevice';
|
||||
import { createArgentTool } from '../utils/argent';
|
||||
import { startExpoGoPreinstall } from '../utils/expoGo';
|
||||
import {
|
||||
type ChildProcessHandle,
|
||||
commands,
|
||||
stopProcessAndDescendantsAsync,
|
||||
} from '../utils/processes';
|
||||
import { startServeSim, waitForServeSimReadyAsync } from '../utils/serveSim';
|
||||
import {
|
||||
disableApsdAsync,
|
||||
listAvailableSimulatorsAsync,
|
||||
selectSimulators,
|
||||
selectWarmupSimulators,
|
||||
shutdownSimulatorAsync,
|
||||
waitForSimulatorBootAsync,
|
||||
} from '../utils/simulator';
|
||||
import {
|
||||
type ClaimInput,
|
||||
ClaimInputSchema,
|
||||
type LauncherState,
|
||||
type PreinstalledApp,
|
||||
type SimulatorDevice,
|
||||
type ToolServer,
|
||||
type WarmSessionInfo,
|
||||
readLauncherStateAsync,
|
||||
updateLauncherStateAsync,
|
||||
} from '../utils/state';
|
||||
import { type StartedTool, type WarmTool, startTool } from '../utils/tools';
|
||||
|
||||
const LAUNCHER_VERSION: string = require('../../package.json').version;
|
||||
|
||||
type WarmSimulatorSession = {
|
||||
prepareAsync(): Promise<WarmSessionInfo>;
|
||||
claimAsync(request: ClaimInput): Promise<{ device: SimulatorDevice }>;
|
||||
prepareToolsAsync(): Promise<{ preinstalledExpoGo?: PreinstalledApp; tools?: ToolServer }>;
|
||||
stopAsync(): Promise<void>;
|
||||
};
|
||||
|
||||
export async function startAsync(bootUuid: string): Promise<number> {
|
||||
const initial = await updateLauncherStateAsync(bootUuid, state => {
|
||||
if (state?.status === 'disabled') {
|
||||
return state;
|
||||
}
|
||||
if (state) {
|
||||
throw new Error(
|
||||
'Simulator preparation has already been started or disabled for this VM boot.'
|
||||
);
|
||||
}
|
||||
return {
|
||||
bootUuid,
|
||||
status: 'starting',
|
||||
controllerPid: process.pid,
|
||||
launcherVersion: LAUNCHER_VERSION,
|
||||
};
|
||||
});
|
||||
if (initial.status === 'disabled') {
|
||||
return 0;
|
||||
}
|
||||
await runWarmSimulatorSessionAsync(bootUuid);
|
||||
return 0;
|
||||
}
|
||||
|
||||
export async function runWarmSimulatorSessionAsync(bootUuid: string): Promise<void> {
|
||||
const shutdown = new AbortController();
|
||||
const signal = shutdown.signal;
|
||||
const interruption = new Error(
|
||||
'Simulator preparation was interrupted; cleanup may still be running.'
|
||||
);
|
||||
const requestShutdown = (): void => shutdown.abort(interruption);
|
||||
process.on('SIGTERM', requestShutdown);
|
||||
process.on('SIGINT', requestShutdown);
|
||||
const watcherAbort = new AbortController();
|
||||
let sessionError: unknown;
|
||||
let warm: WarmSessionInfo | undefined;
|
||||
function requireOwnedState(
|
||||
state: LauncherState | undefined,
|
||||
expected?: LauncherState['status']
|
||||
): LauncherState {
|
||||
if (state?.status === 'stopping' || state?.status === 'disabled') {
|
||||
requestShutdown();
|
||||
}
|
||||
if (
|
||||
!state ||
|
||||
state.controllerPid !== process.pid ||
|
||||
(expected && state.status !== expected) ||
|
||||
(warm && state.controllerStartTime && state.controllerStartTime !== warm.controllerStartTime)
|
||||
) {
|
||||
throw interruption;
|
||||
}
|
||||
return state;
|
||||
}
|
||||
async function throwIfStoppingAsync(): Promise<void> {
|
||||
signal.throwIfAborted();
|
||||
requireOwnedState(await readLauncherStateAsync(bootUuid));
|
||||
signal.throwIfAborted();
|
||||
}
|
||||
const session = createWarmSimulatorSession({
|
||||
signal,
|
||||
throwIfStoppingAsync,
|
||||
onPreparationFailure(error) {
|
||||
if (!signal.aborted) {
|
||||
sessionError = error;
|
||||
}
|
||||
shutdown.abort(error);
|
||||
},
|
||||
});
|
||||
const watcher = (async () => {
|
||||
while (!watcherAbort.signal.aborted) {
|
||||
await throwIfStoppingAsync();
|
||||
await sleepAsync(100, undefined, { signal: watcherAbort.signal });
|
||||
}
|
||||
})().catch(error => {
|
||||
if (!watcherAbort.signal.aborted && !signal.aborted) {
|
||||
sessionError ??= error;
|
||||
requestShutdown();
|
||||
}
|
||||
});
|
||||
async function prepareDefaultDeviceAsync(): Promise<void> {
|
||||
await throwIfStoppingAsync();
|
||||
const prepared = await session.prepareAsync();
|
||||
warm = prepared;
|
||||
await updateLauncherStateAsync(
|
||||
bootUuid,
|
||||
state => ({
|
||||
...requireOwnedState(state, 'starting'),
|
||||
...prepared,
|
||||
status: 'ready',
|
||||
}),
|
||||
signal
|
||||
);
|
||||
}
|
||||
|
||||
async function handleOneClaimAsync(): Promise<void> {
|
||||
while (!signal.aborted) {
|
||||
const state = requireOwnedState(await readLauncherStateAsync(bootUuid));
|
||||
if (state.status === 'claiming') {
|
||||
const request = ClaimInputSchema.parse(state);
|
||||
const { device } = await session.claimAsync(request);
|
||||
// Stop can arrive during native work; recheck ownership under the state lock.
|
||||
await updateLauncherStateAsync(
|
||||
bootUuid,
|
||||
current => {
|
||||
const owned = requireOwnedState(current, 'claiming');
|
||||
if (
|
||||
owned.engine !== request.engine ||
|
||||
owned.requestedDevice !== request.requestedDevice
|
||||
) {
|
||||
throw interruption;
|
||||
}
|
||||
return {
|
||||
...owned,
|
||||
status: 'claimed',
|
||||
device,
|
||||
};
|
||||
},
|
||||
signal
|
||||
);
|
||||
return;
|
||||
}
|
||||
await sleepAsync(100, undefined, { signal });
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
}
|
||||
|
||||
async function finishSessionAsync(): Promise<void> {
|
||||
await updateLauncherStateAsync(bootUuid, state => ({
|
||||
...requireOwnedState(state),
|
||||
status: 'stopping',
|
||||
...(sessionError !== undefined
|
||||
? { error: sessionError instanceof Error ? sessionError.message : String(sessionError) }
|
||||
: {}),
|
||||
})).catch(error => {
|
||||
sessionError ??= error;
|
||||
});
|
||||
try {
|
||||
await session.stopAsync();
|
||||
} catch (error) {
|
||||
await updateLauncherStateAsync(bootUuid, state => ({
|
||||
...requireOwnedState(state),
|
||||
status: 'stopping',
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
})).catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
// Only confirmed cleanup may publish disabled, which lets a job safely start cold.
|
||||
await updateLauncherStateAsync(bootUuid, state => ({
|
||||
...requireOwnedState(state, 'stopping'),
|
||||
status: 'disabled',
|
||||
}));
|
||||
if (sessionError) {
|
||||
throw sessionError;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
try {
|
||||
if (process.env.EXPO_SIMULATOR_STARTUP !== '1') {
|
||||
process.stderr.write('EXPO_SIMULATOR_STARTUP is not 1; Simulator warmup is disabled.\n');
|
||||
requestShutdown();
|
||||
}
|
||||
await prepareDefaultDeviceAsync();
|
||||
await handleOneClaimAsync();
|
||||
while (!signal.aborted) {
|
||||
const state = requireOwnedState(await readLauncherStateAsync(bootUuid), 'claimed');
|
||||
if (state.prepareToolsRequested && !state.toolsReady) {
|
||||
const prepared = await session.prepareToolsAsync();
|
||||
await updateLauncherStateAsync(
|
||||
bootUuid,
|
||||
current => ({
|
||||
...requireOwnedState(current, 'claimed'),
|
||||
...prepared,
|
||||
toolsReady: true,
|
||||
}),
|
||||
signal
|
||||
);
|
||||
break;
|
||||
}
|
||||
await sleepAsync(100, undefined, { signal });
|
||||
}
|
||||
if (!signal.aborted) {
|
||||
await once(signal, 'abort');
|
||||
}
|
||||
} catch (error) {
|
||||
if (!signal.aborted) {
|
||||
sessionError ??= error;
|
||||
}
|
||||
}
|
||||
|
||||
await finishSessionAsync();
|
||||
} finally {
|
||||
watcherAbort.abort();
|
||||
await watcher;
|
||||
process.off('SIGTERM', requestShutdown);
|
||||
process.off('SIGINT', requestShutdown);
|
||||
}
|
||||
}
|
||||
|
||||
/** Own one orphan process and its tool/preinstall work before any preparation awaits. */
|
||||
export function createWarmSimulatorSession({
|
||||
signal: parentSignal,
|
||||
throwIfStoppingAsync,
|
||||
onPreparationFailure,
|
||||
}: {
|
||||
signal: AbortSignal;
|
||||
throwIfStoppingAsync(): Promise<void>;
|
||||
onPreparationFailure(error: unknown): void;
|
||||
}): WarmSimulatorSession {
|
||||
const lifetime = new AbortController();
|
||||
const signal = AbortSignal.any([parentSignal, lifetime.signal]);
|
||||
const warmTools = [createAgentDeviceTool(), createArgentTool(onPreparationFailure)];
|
||||
const startedTools = new Map<WarmTool, StartedTool>();
|
||||
const ownedDevices = new Set<string>();
|
||||
// Each device's apsd step; only the terminal stop joins them.
|
||||
const simulatorSetups = new Map<string, Promise<void>>();
|
||||
let preparation: Promise<WarmSessionInfo> | undefined;
|
||||
let server: ChildProcessHandle | undefined;
|
||||
let info: WarmSessionInfo;
|
||||
let availableDevices: SimulatorDevice[];
|
||||
let warmDevices: SimulatorDevice[] = [];
|
||||
let request: ClaimInput | undefined;
|
||||
let stopping = false;
|
||||
let expoGo: ReturnType<typeof startExpoGoPreinstall> | undefined;
|
||||
let selectedPreinstall: Promise<PreinstalledApp | undefined> = Promise.resolve(undefined);
|
||||
let launcherCachePriming: Promise<void> = Promise.resolve();
|
||||
let toolRetirement: Promise<PromiseSettledResult<void>[]> = Promise.resolve([]);
|
||||
|
||||
/**
|
||||
* Sets up each device once `ready` settles and the device booted: disable apsd and preinstall
|
||||
* Expo Go in parallel. Claim does not wait for this; stop joins it.
|
||||
*/
|
||||
async function startSimulatorsSetupAsync(
|
||||
udids: string[],
|
||||
ready: Promise<unknown>
|
||||
): Promise<void> {
|
||||
await Promise.all(
|
||||
udids.map(async udid => {
|
||||
if (simulatorSetups.has(udid)) {
|
||||
return;
|
||||
}
|
||||
// serve-sim boots every device; its ready already covers the default device's boot.
|
||||
const booted =
|
||||
udid === warmDevices[0]?.udid
|
||||
? ready
|
||||
: ready.then(() => waitForSimulatorBootAsync(udid, signal));
|
||||
const apsd = booted.then(() =>
|
||||
disableApsdAsync(udid, signal).catch(error => {
|
||||
signal.throwIfAborted();
|
||||
process.stderr.write(`Could not disable apsd on ${udid}; continuing: ${error}\n`);
|
||||
})
|
||||
);
|
||||
simulatorSetups.set(udid, apsd);
|
||||
void apsd.catch(() => {
|
||||
if (simulatorSetups.get(udid) === apsd) {
|
||||
simulatorSetups.delete(udid);
|
||||
}
|
||||
});
|
||||
await Promise.all([
|
||||
apsd,
|
||||
booted.then(() => expoGo?.preinstallOnDeviceAsync(udid, Promise.resolve(), signal)),
|
||||
]);
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
async function resolveDeviceAsync(selector: string): Promise<SimulatorDevice> {
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
const matches = selectSimulators(availableDevices, selector);
|
||||
if (matches.length === 1) {
|
||||
return matches[0];
|
||||
}
|
||||
if (matches.length > 1 || attempt === 1) {
|
||||
throw new Error(
|
||||
`Could not select one available Simulator for ${selector}. Use an exact available device name or UDID.`
|
||||
);
|
||||
}
|
||||
await throwIfStoppingAsync();
|
||||
availableDevices = await listAvailableSimulatorsAsync(signal);
|
||||
}
|
||||
}
|
||||
|
||||
async function primeLauncherCacheAsync(): Promise<void> {
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
try {
|
||||
await commands.runAsync(
|
||||
'bun',
|
||||
['x', `@expo/simulator-launcher@${LAUNCHER_VERSION}`, '--version'],
|
||||
AbortSignal.any([signal, AbortSignal.timeout(30_000)])
|
||||
);
|
||||
return;
|
||||
} catch (error) {
|
||||
signal.throwIfAborted();
|
||||
if (attempt === 1) {
|
||||
process.stderr.write(
|
||||
`Could not cache the Simulator launcher version; claim/stop may need the registry: ${error}\n`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function prepareDefaultAsync(): Promise<WarmSessionInfo> {
|
||||
signal.throwIfAborted();
|
||||
availableDevices = await listAvailableSimulatorsAsync(signal);
|
||||
signal.throwIfAborted();
|
||||
warmDevices = selectWarmupSimulators(availableDevices, process.env.EXPO_SIMULATOR_DEVICE);
|
||||
const controllerStartTime = (
|
||||
await commands.runAsync('ps', ['-p', String(process.pid), '-o', 'lstart='], signal)
|
||||
).trim();
|
||||
signal.throwIfAborted();
|
||||
if (!controllerStartTime) {
|
||||
throw new Error(
|
||||
'Could not read the Simulator launcher process start time; the warm session cannot be verified.'
|
||||
);
|
||||
}
|
||||
const first = warmDevices[0];
|
||||
// serve-sim owns all boot/selection work, including partial boots during failed adoption.
|
||||
server = startServeSim(
|
||||
warmDevices.map(device => device.udid),
|
||||
signal
|
||||
);
|
||||
for (const device of warmDevices) {
|
||||
ownedDevices.add(device.udid);
|
||||
}
|
||||
const ready = waitForServeSimReadyAsync(first.udid, server, signal);
|
||||
void ready.catch(() => {});
|
||||
if (process.env.EXPO_SIMULATOR_PREINSTALL_EXPO_GO !== '0') {
|
||||
expoGo = startExpoGoPreinstall(signal);
|
||||
}
|
||||
for (const tool of warmTools) {
|
||||
startedTools.set(tool, startTool(tool, first.udid, ready, signal, onPreparationFailure));
|
||||
}
|
||||
startSimulatorsSetupAsync(
|
||||
warmDevices.map(device => device.udid),
|
||||
ready
|
||||
).catch(error => {
|
||||
if (!signal.aborted) {
|
||||
process.stderr.write(`Could not finish Simulator warmup; continuing: ${error}\n`);
|
||||
}
|
||||
});
|
||||
launcherCachePriming = primeLauncherCacheAsync();
|
||||
const [serverInfo] = await Promise.all([ready, launcherCachePriming]);
|
||||
const agentDeviceStateDir = process.env.AGENT_DEVICE_STATE_DIR;
|
||||
const argentEventLogPath = process.env.ARGENT_EVENT_LOG;
|
||||
if (!agentDeviceStateDir || !argentEventLogPath) {
|
||||
throw new Error('The warm Simulator tool paths are not configured.');
|
||||
}
|
||||
info = {
|
||||
device: first,
|
||||
server: serverInfo,
|
||||
controllerPid: process.pid,
|
||||
controllerStartTime,
|
||||
agentDeviceStateDir,
|
||||
argentEventLogPath,
|
||||
};
|
||||
return info;
|
||||
}
|
||||
|
||||
return {
|
||||
async prepareAsync() {
|
||||
return await (preparation ??= prepareDefaultAsync());
|
||||
},
|
||||
async claimAsync(input) {
|
||||
if (request || stopping) {
|
||||
throw new Error('This warm Simulator session has already been claimed or is stopping.');
|
||||
}
|
||||
request = input;
|
||||
// Latch every installation before any asynchronous selection, so no new one starts.
|
||||
// Installs already running continue. Adoption may shut down an unused device during its
|
||||
// install, which then fails with a warning; stop joins them all.
|
||||
const preinstalls = new Map(
|
||||
warmDevices.map(device => {
|
||||
const result = expoGo?.claimAsync(device.udid) ?? Promise.resolve(undefined);
|
||||
void result.catch(() => {});
|
||||
return [device.udid, result] as const;
|
||||
})
|
||||
);
|
||||
await throwIfStoppingAsync();
|
||||
const selected = input.requestedDevice
|
||||
? await resolveDeviceAsync(input.requestedDevice)
|
||||
: warmDevices[0];
|
||||
ownedDevices.add(selected.udid);
|
||||
const requestedTool = warmTools.find(tool => tool.name === input.engine);
|
||||
const sameDevice = selected.udid === warmDevices[0].udid;
|
||||
toolRetirement = Promise.allSettled(
|
||||
[...startedTools]
|
||||
.filter(
|
||||
([tool]) => tool !== requestedTool || (tool.name === 'agent-device' && !sameDevice)
|
||||
)
|
||||
.map(([tool, started]) => {
|
||||
startedTools.delete(tool);
|
||||
// The job owns the device now; the terminal stop retries this tool.
|
||||
return started.stopAsync().catch(error => {
|
||||
process.stderr.write(`Could not stop ${tool.name}; retrying at stop: ${error}\n`);
|
||||
throw error;
|
||||
});
|
||||
})
|
||||
);
|
||||
// The claim does not wait for warmup work; prepare-tools waits for this device's install.
|
||||
selectedPreinstall = preinstalls.get(selected.udid) ?? Promise.resolve(undefined);
|
||||
info = { ...info, device: selected };
|
||||
return { device: selected };
|
||||
},
|
||||
async prepareToolsAsync() {
|
||||
if (!request || stopping || !server) {
|
||||
throw new Error('Claim a warm Simulator session before preparing its tools.');
|
||||
}
|
||||
const { engine } = request;
|
||||
// This phase cannot start a runner against the old device before private adoption finishes.
|
||||
const adopted = await waitForServeSimReadyAsync(
|
||||
info.device.udid,
|
||||
server,
|
||||
signal,
|
||||
info.server.port
|
||||
);
|
||||
if (
|
||||
adopted.pid !== info.server.pid ||
|
||||
adopted.nativeStartTime !== info.server.nativeStartTime ||
|
||||
adopted.url !== info.server.url ||
|
||||
adopted.token !== info.server.token
|
||||
) {
|
||||
throw new Error('The adopted serve-sim process does not match the claimed warm server.');
|
||||
}
|
||||
// A device outside the warm list still needs its setup. A started setup is reused. This
|
||||
// runs in the background but is joined before teardown.
|
||||
startSimulatorsSetupAsync([info.device.udid], Promise.resolve()).catch(() => {});
|
||||
const tool = warmTools.find(tool => tool.name === engine);
|
||||
if (tool?.name === 'agent-device' && !startedTools.has(tool)) {
|
||||
const results = await toolRetirement;
|
||||
const failed = results.find(result => result.status === 'rejected');
|
||||
if (failed?.status === 'rejected') {
|
||||
throw failed.reason;
|
||||
}
|
||||
}
|
||||
await throwIfStoppingAsync();
|
||||
let tools: ToolServer | void = undefined;
|
||||
if (tool) {
|
||||
let started = startedTools.get(tool);
|
||||
if (!started) {
|
||||
started = startTool(
|
||||
tool,
|
||||
info.device.udid,
|
||||
Promise.resolve(),
|
||||
signal,
|
||||
onPreparationFailure
|
||||
);
|
||||
startedTools.set(tool, started);
|
||||
}
|
||||
tools = await started.ready;
|
||||
}
|
||||
// The job installs its app after this, so a running Expo Go install must finish first.
|
||||
const preinstalledExpoGo = await selectedPreinstall;
|
||||
return {
|
||||
...(preinstalledExpoGo ? { preinstalledExpoGo } : {}),
|
||||
...(tools ? { tools } : {}),
|
||||
};
|
||||
},
|
||||
async stopAsync() {
|
||||
stopping = true;
|
||||
const cancellations = [...startedTools.values()].map(tool => tool.cancelAsync());
|
||||
lifetime.abort();
|
||||
await Promise.allSettled(cancellations);
|
||||
await preparation?.catch(() => {});
|
||||
await Promise.allSettled(simulatorSetups.values());
|
||||
const preinstall = await Promise.allSettled(
|
||||
warmDevices.map(device => expoGo?.stopAsync(device.udid))
|
||||
);
|
||||
await toolRetirement;
|
||||
await launcherCachePriming.catch(() => {});
|
||||
const errors = preinstall.flatMap(result =>
|
||||
result.status === 'rejected' ? [result.reason] : []
|
||||
);
|
||||
const attemptAsync = async (operation: Promise<void>) => {
|
||||
await operation.catch(error => errors.push(error));
|
||||
};
|
||||
// Keep handles after failure so terminal cleanup never mistakes wrapper exit for drain.
|
||||
for (const started of startedTools.values()) {
|
||||
await attemptAsync(started.stopAsync());
|
||||
}
|
||||
for (const tool of warmTools) {
|
||||
if (!startedTools.has(tool) && server) {
|
||||
await attemptAsync(tool.stopAsync());
|
||||
}
|
||||
}
|
||||
if (server) {
|
||||
await attemptAsync(
|
||||
stopProcessAndDescendantsAsync(server).then(() => {
|
||||
server = undefined;
|
||||
})
|
||||
);
|
||||
}
|
||||
await Promise.all(
|
||||
[...ownedDevices].map(udid =>
|
||||
attemptAsync(
|
||||
shutdownSimulatorAsync(udid).then(() => {
|
||||
ownedDevices.delete(udid);
|
||||
})
|
||||
)
|
||||
)
|
||||
);
|
||||
try {
|
||||
commands.throwIfCommandCloseTimedOut();
|
||||
} catch (error) {
|
||||
errors.push(error);
|
||||
}
|
||||
if (errors.length) {
|
||||
throw new AggregateError(
|
||||
errors,
|
||||
'Warm Simulator cleanup could not be confirmed; services or devices may still be running.'
|
||||
);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { updateLauncherStateAsync, waitForLauncherStateAsync } from '../utils/state';
|
||||
|
||||
export async function stopAsync(bootUuid: string): Promise<number> {
|
||||
const state = await updateLauncherStateAsync(bootUuid, current =>
|
||||
!current || current.status === 'disabled'
|
||||
? { ...current, bootUuid, status: 'disabled' }
|
||||
: { ...current, status: 'stopping' }
|
||||
);
|
||||
if (state.status !== 'disabled') {
|
||||
await waitForLauncherStateAsync(bootUuid, current => current?.status === 'disabled', 140_000);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import path from 'node:path';
|
||||
|
||||
import { claimAsync, prepareToolsAsync } from './commands/claim';
|
||||
import { startAsync } from './commands/start';
|
||||
import { stopAsync } from './commands/stop';
|
||||
import { commands } from './utils/processes';
|
||||
|
||||
export async function mainAsync(args = process.argv.slice(2)): Promise<number> {
|
||||
if (process.platform !== 'darwin') {
|
||||
throw new Error('simulator-launcher requires macOS (darwin).');
|
||||
}
|
||||
if (args.length === 1 && args[0] === '--version') {
|
||||
process.stdout.write(`${require('../package.json').version}\n`);
|
||||
return 0;
|
||||
}
|
||||
const [command, engine, requestedDevice] = args;
|
||||
if (
|
||||
command !== 'start' &&
|
||||
command !== 'stop' &&
|
||||
command !== 'claim' &&
|
||||
command !== 'prepare-tools'
|
||||
) {
|
||||
throw new Error('Usage: simulator-launcher <start|stop|claim ENGINE [DEVICE]|prepare-tools>');
|
||||
}
|
||||
const bootUuid = (
|
||||
await commands.runAsync('/usr/sbin/sysctl', ['-n', 'kern.bootsessionuuid'])
|
||||
).trim();
|
||||
if (!bootUuid) {
|
||||
throw new Error(
|
||||
'Could not read the VM boot identifier (kern.bootsessionuuid); startup cannot continue.'
|
||||
);
|
||||
}
|
||||
switch (command) {
|
||||
case 'start':
|
||||
return await startAsync(bootUuid);
|
||||
case 'stop':
|
||||
return await stopAsync(bootUuid);
|
||||
case 'claim':
|
||||
return await claimAsync(bootUuid, engine, requestedDevice);
|
||||
case 'prepare-tools':
|
||||
return await prepareToolsAsync(bootUuid);
|
||||
}
|
||||
}
|
||||
|
||||
export async function runCliAsync(): Promise<void> {
|
||||
try {
|
||||
process.exitCode = await mainAsync();
|
||||
} catch (error) {
|
||||
process.stderr.write(`${error instanceof Error ? error.message : error}\n`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === path.resolve(__filename)) {
|
||||
void runCliAsync();
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { type ChildProcessHandle, commands, stopProcessAndDescendantsAsync } from './processes';
|
||||
import { type WarmTool, untilAbortedAsync } from './tools';
|
||||
|
||||
const packageSpec = (): string => `agent-device@${process.env.AGENT_DEVICE_VERSION || 'latest'}`;
|
||||
|
||||
/** `prepare ios-runner` builds and starts the runner and its daemon; it exits once both are up. */
|
||||
export function createAgentDeviceTool(): WarmTool {
|
||||
const stateDir = (process.env.AGENT_DEVICE_STATE_DIR ||= path.join(
|
||||
os.homedir(),
|
||||
'Library/Caches/expo-simulator-startup/agent-device'
|
||||
));
|
||||
process.env.AGENT_DEVICE_RETAIN_ARTIFACTS ||= '1';
|
||||
process.env.AGENT_DEVICE_DAEMON_IDLE_TIMEOUT_MS ||= '0';
|
||||
process.env.AGENT_DEVICE_IOS_RUNNER_IDLE_STOP_MS ||= '0';
|
||||
process.env.AGENT_DEVICE_IOS_RUNNER_DETACH ||= '0';
|
||||
let prepareProcess: ChildProcessHandle | undefined;
|
||||
return {
|
||||
name: 'agent-device',
|
||||
async startAsync(udid, signal) {
|
||||
signal.throwIfAborted();
|
||||
prepareProcess = commands.start(
|
||||
'bunx',
|
||||
[
|
||||
packageSpec(),
|
||||
'prepare',
|
||||
'ios-runner',
|
||||
'--platform',
|
||||
'ios',
|
||||
'--udid',
|
||||
udid,
|
||||
'--daemon-server-mode',
|
||||
'http',
|
||||
'--daemon-transport',
|
||||
'http',
|
||||
'--timeout',
|
||||
'240000',
|
||||
'--json',
|
||||
],
|
||||
{ detached: true }
|
||||
);
|
||||
await untilAbortedAsync(prepareProcess.resultPromise, signal);
|
||||
},
|
||||
async stopAsync() {
|
||||
const errors: unknown[] = [];
|
||||
if (prepareProcess) {
|
||||
await stopProcessAndDescendantsAsync(prepareProcess, /* allowCompletedProcess */ true).then(
|
||||
() => (prepareProcess = undefined),
|
||||
error => errors.push(error)
|
||||
);
|
||||
}
|
||||
// The daemon outlives the prepare process, so it stops even if the prepare stop failed.
|
||||
// A stop that cannot finish fails instead of blocking cleanup forever.
|
||||
await commands
|
||||
.runAsync(
|
||||
'bunx',
|
||||
[packageSpec(), 'daemon', 'stop', '--clean', '--state-dir', stateDir],
|
||||
AbortSignal.timeout(120_000)
|
||||
)
|
||||
.catch(error => errors.push(error));
|
||||
if (errors.length > 1) {
|
||||
throw new AggregateError(errors, 'agent-device could not be stopped.');
|
||||
}
|
||||
if (errors.length) {
|
||||
throw errors[0];
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { setTimeout as sleepAsync } from 'node:timers/promises';
|
||||
import { z } from 'zod';
|
||||
|
||||
import {
|
||||
type ChildProcessHandle,
|
||||
commands,
|
||||
isProcessOwnedByServiceAsync,
|
||||
stopProcessAndDescendantsAsync,
|
||||
} from './processes';
|
||||
import { type WarmTool } from './tools';
|
||||
|
||||
const packageSpec = (): string => `@swmansion/argent@${process.env.ARGENT_VERSION || 'latest'}`;
|
||||
|
||||
const ArgentStateSchema = z.object({
|
||||
pid: z.number().int().min(2),
|
||||
port: z.literal(3201),
|
||||
token: z.string().min(1),
|
||||
});
|
||||
const ToolsSchema = z.object({ tools: z.array(z.unknown()) });
|
||||
|
||||
export function createArgentTool(onUnexpectedExit: (error: unknown) => void): WarmTool {
|
||||
process.env.ARGENT_EVENT_LOG ||= path.join(os.homedir(), '.argent/tool-server-events.jsonl');
|
||||
process.env.ARGENT_EMULATOR_NO_WINDOW ||= '1';
|
||||
let serverProcess: ChildProcessHandle | undefined;
|
||||
let stopping = false;
|
||||
return {
|
||||
name: 'argent',
|
||||
async prepareAsync(signal) {
|
||||
signal.throwIfAborted();
|
||||
// The VM image provides ffmpeg; installing it here would delay every warm session.
|
||||
await commands.runAsync('ffmpeg', ['-version'], signal).catch(error => {
|
||||
signal.throwIfAborted();
|
||||
process.stderr.write(`ffmpeg is unavailable; Argent video tools may not work: ${error}\n`);
|
||||
});
|
||||
commands.throwIfCommandCloseTimedOut();
|
||||
|
||||
for (const [verb, flag] of [
|
||||
['enable', 'artifacts-list-endpoint'],
|
||||
['enable', 'tool-server-event-log'],
|
||||
['disable', 'video-watermark'],
|
||||
]) {
|
||||
signal.throwIfAborted();
|
||||
await commands.runAsync('bunx', [packageSpec(), verb, flag], signal).catch(error => {
|
||||
if (verb !== 'disable') {
|
||||
throw error;
|
||||
}
|
||||
});
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
},
|
||||
async startAsync(_udid, signal) {
|
||||
signal.throwIfAborted();
|
||||
stopping = false;
|
||||
serverProcess = commands.start(
|
||||
'bunx',
|
||||
[
|
||||
packageSpec(),
|
||||
'server',
|
||||
'start',
|
||||
'--host',
|
||||
'127.0.0.1',
|
||||
'--port',
|
||||
'3201',
|
||||
'--idle-timeout',
|
||||
'0',
|
||||
],
|
||||
{ detached: true }
|
||||
);
|
||||
const server = serverProcess;
|
||||
let ready = false;
|
||||
let failure: Error | undefined;
|
||||
const recordExit = (cause?: unknown): void => {
|
||||
if (failure) {
|
||||
return;
|
||||
}
|
||||
failure = new Error(
|
||||
ready
|
||||
? 'Argent server exited unexpectedly.'
|
||||
: 'Argent exited before its server became ready.',
|
||||
{ cause }
|
||||
);
|
||||
if (ready && !stopping && !signal.aborted) {
|
||||
onUnexpectedExit(failure);
|
||||
}
|
||||
};
|
||||
server.child.once('exit', () => recordExit());
|
||||
server.child.once('error', recordExit);
|
||||
void server.resultPromise.then(() => recordExit(), recordExit);
|
||||
const stateDirectory = path.join(os.homedir(), '.argent');
|
||||
const deadline = Date.now() + 120_000;
|
||||
for (;;) {
|
||||
signal.throwIfAborted();
|
||||
if (failure) {
|
||||
throw failure;
|
||||
}
|
||||
if (Date.now() >= deadline) {
|
||||
throw new Error('Timed out waiting for the Argent server on port 3201 to become ready.');
|
||||
}
|
||||
const entries = await fs.readdir(stateDirectory).catch(() => []);
|
||||
for (const entry of entries) {
|
||||
if (!/^tool-server.*\.json$/.test(entry)) {
|
||||
continue;
|
||||
}
|
||||
const state = await fs
|
||||
.readFile(path.join(stateDirectory, entry), 'utf8')
|
||||
.then(contents => ArgentStateSchema.parse(JSON.parse(contents)))
|
||||
.catch(() => undefined);
|
||||
if (!state || !(await isProcessOwnedByServiceAsync(state.pid, server.child, signal))) {
|
||||
continue;
|
||||
}
|
||||
const tools = await fetch('http://127.0.0.1:3201/tools', {
|
||||
headers: { Authorization: `Bearer ${state.token}` },
|
||||
signal: AbortSignal.any([signal, AbortSignal.timeout(2_000)]),
|
||||
})
|
||||
.then(async response =>
|
||||
response.ok ? ToolsSchema.safeParse(await response.json()).success : false
|
||||
)
|
||||
.catch(() => false);
|
||||
signal.throwIfAborted();
|
||||
if (failure) {
|
||||
throw failure;
|
||||
}
|
||||
if (tools && (await isProcessOwnedByServiceAsync(state.pid, server.child, signal))) {
|
||||
signal.throwIfAborted();
|
||||
if (failure) {
|
||||
throw failure;
|
||||
}
|
||||
ready = true;
|
||||
return state;
|
||||
}
|
||||
}
|
||||
await sleepAsync(250, undefined, { signal });
|
||||
}
|
||||
},
|
||||
async stopAsync() {
|
||||
stopping = true;
|
||||
if (serverProcess) {
|
||||
await stopProcessAndDescendantsAsync(serverProcess);
|
||||
serverProcess = undefined;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import { createWriteStream } from 'node:fs';
|
||||
import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { Writable } from 'node:stream';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { commands } from './processes';
|
||||
import { type PreinstalledApp } from './state';
|
||||
|
||||
const VERSIONS_URL = 'https://api.expo.dev/v2/versions';
|
||||
const HEADERS = { Accept: 'application/json', 'User-Agent': 'expo-simulator-launcher' };
|
||||
const VersionsSchema = z.object({
|
||||
sdkVersions: z.record(
|
||||
z.string(),
|
||||
z.object({
|
||||
releaseNoteUrl: z.string().optional(),
|
||||
isBeta: z.boolean().optional(),
|
||||
iosClientUrl: z.string().optional(),
|
||||
})
|
||||
),
|
||||
});
|
||||
|
||||
/**
|
||||
* Downloads the latest stable Expo Go once, for every warm device. Claim forbids later installs;
|
||||
* started native installs and the shared archive stay owned until claim or stop releases them.
|
||||
*/
|
||||
export function startExpoGoPreinstall(signal: AbortSignal): {
|
||||
claimAsync(selectedUdid: string): Promise<PreinstalledApp | undefined>;
|
||||
preinstallOnDeviceAsync(udid: string, boot: Promise<unknown>, signal: AbortSignal): Promise<void>;
|
||||
stopAsync(selectedUdid: string): Promise<void>;
|
||||
} {
|
||||
const downloadController = new AbortController();
|
||||
const downloadSignal = AbortSignal.any([
|
||||
signal,
|
||||
downloadController.signal,
|
||||
AbortSignal.timeout(120_000),
|
||||
]);
|
||||
const directory = fs.mkdtemp(path.join(os.tmpdir(), 'simulator-expo-go-'));
|
||||
const installations = new Map<string, Promise<void>>();
|
||||
const installed = new Map<string, PreinstalledApp>();
|
||||
const operations = new Set<Promise<void>>();
|
||||
const failures = new Map<string, unknown>();
|
||||
let cleanup: Promise<void> | undefined;
|
||||
const archive = (async () => {
|
||||
const directoryPath = await directory;
|
||||
const response = await fetch(VERSIONS_URL, { headers: HEADERS, signal: downloadSignal });
|
||||
if (!response.ok) {
|
||||
throw new Error(`Expo Go versions returned HTTP ${response.status}.`);
|
||||
}
|
||||
const { sdkVersions } = VersionsSchema.parse(await response.json());
|
||||
// Same latest stable release policy as expo.dev/go (GoScene/utils.ts).
|
||||
const sdk = Object.keys(sdkVersions)
|
||||
.filter(sdk => /\b(\d*)\.0\.0/.test(sdk))
|
||||
.slice(-10)
|
||||
.reverse()
|
||||
.find(sdk => sdkVersions[sdk].releaseNoteUrl && !sdkVersions[sdk].isBeta);
|
||||
const url = sdk && sdkVersions[sdk].iosClientUrl;
|
||||
if (!url || new URL(url).protocol !== 'https:') {
|
||||
throw new Error('No stable Expo Go Simulator archive is available.');
|
||||
}
|
||||
const archive = await fetch(url, { headers: HEADERS, signal: downloadSignal });
|
||||
if (!archive.ok || !archive.body) {
|
||||
throw new Error(`Expo Go archive returned HTTP ${archive.status}.`);
|
||||
}
|
||||
const archivePath = path.join(directoryPath, 'expo-go.tar.gz');
|
||||
await archive.body.pipeTo(Writable.toWeb(createWriteStream(archivePath)), {
|
||||
signal: downloadSignal,
|
||||
});
|
||||
downloadSignal.throwIfAborted();
|
||||
// Wait for the owned extractor to close, including on bad archives and claim/stop.
|
||||
const appPath = path.join(directoryPath, 'ExpoGo.app');
|
||||
await fs.mkdir(appPath);
|
||||
await commands.runAsync('/usr/bin/tar', ['-xzf', archivePath, '-C', appPath]);
|
||||
downloadSignal.throwIfAborted();
|
||||
await fs.access(path.join(appPath, 'Info.plist'));
|
||||
|
||||
return { appPath, sdk };
|
||||
})();
|
||||
void archive.catch(() => {});
|
||||
|
||||
async function preinstallAsync(
|
||||
target: string,
|
||||
boot: Promise<unknown>,
|
||||
deviceSignal: AbortSignal
|
||||
): Promise<void> {
|
||||
void boot.catch(() => {});
|
||||
let installation: Promise<void> | undefined;
|
||||
const installSignal = AbortSignal.any([signal, deviceSignal, downloadController.signal]);
|
||||
try {
|
||||
const { appPath, sdk } = await archive;
|
||||
await boot;
|
||||
installSignal.throwIfAborted();
|
||||
// No await between checking the claim latch and registering the native install.
|
||||
process.stderr.write(`Preinstalling Expo Go for SDK ${sdk} on Simulator ${target}.\n`);
|
||||
installation = commands.runAsync('xcrun', ['simctl', 'install', target, appPath]).then(
|
||||
async () => {
|
||||
process.stderr.write('Expo Go preinstall finished.\n');
|
||||
const info = await readPreinstalledAppAsync(target, appPath).catch(error => {
|
||||
process.stderr.write(`Could not read the preinstalled Expo Go version: ${error}\n`);
|
||||
return undefined;
|
||||
});
|
||||
if (info) {
|
||||
installed.set(target, info);
|
||||
}
|
||||
},
|
||||
error => {
|
||||
commands.throwIfCommandCloseTimedOut();
|
||||
if (error.code === null) {
|
||||
throw error;
|
||||
}
|
||||
process.stderr.write(`Could not preinstall Expo Go on ${target}: ${error}\n`);
|
||||
}
|
||||
);
|
||||
installations.set(target, installation);
|
||||
await installation;
|
||||
} catch (error) {
|
||||
commands.throwIfCommandCloseTimedOut();
|
||||
if (installation) {
|
||||
throw error;
|
||||
}
|
||||
if (!installSignal.aborted) {
|
||||
process.stderr.write(`Could not preinstall Expo Go on ${target}: ${error}\n`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function cleanUpAsync(): Promise<void> {
|
||||
return await (cleanup ??= (async () => {
|
||||
// Install failures belong to a device; cleanup still drains every operation.
|
||||
await Promise.allSettled([...operations]);
|
||||
await archive.catch(() => {});
|
||||
// Unproved close never permits temporary-file removal or a stopped acknowledgement.
|
||||
commands.throwIfCommandCloseTimedOut();
|
||||
await fs.rm(await directory, { recursive: true, force: true });
|
||||
})());
|
||||
}
|
||||
return {
|
||||
async preinstallOnDeviceAsync(target, boot, deviceSignal) {
|
||||
if (downloadController.signal.aborted || cleanup) {
|
||||
return;
|
||||
}
|
||||
const operation = preinstallAsync(target, boot, deviceSignal).catch(error => {
|
||||
failures.set(target, error);
|
||||
throw error;
|
||||
});
|
||||
operations.add(operation);
|
||||
await operation;
|
||||
},
|
||||
async claimAsync(selectedUdid) {
|
||||
downloadController.abort();
|
||||
void cleanUpAsync().catch(() => {});
|
||||
await installations.get(selectedUdid);
|
||||
if (failures.has(selectedUdid)) {
|
||||
throw failures.get(selectedUdid);
|
||||
}
|
||||
return installed.get(selectedUdid);
|
||||
},
|
||||
async stopAsync(selectedUdid) {
|
||||
// The session owner must still confirm Simulator shutdown before publishing disabled.
|
||||
downloadController.abort();
|
||||
await cleanUpAsync();
|
||||
commands.throwIfCommandCloseTimedOut();
|
||||
if (failures.has(selectedUdid)) {
|
||||
throw failures.get(selectedUdid);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function readPreinstalledAppAsync(udid: string, appPath: string): Promise<PreinstalledApp> {
|
||||
const infoPlistPath = path.join(appPath, 'Info.plist');
|
||||
const [bundleIdentifier, shortVersion, version] = await Promise.all(
|
||||
['CFBundleIdentifier', 'CFBundleShortVersionString', 'CFBundleVersion'].map(async key =>
|
||||
(await commands.runAsync('plutil', ['-extract', key, 'raw', '-o', '-', infoPlistPath])).trim()
|
||||
)
|
||||
);
|
||||
return { udid, bundleIdentifier, shortVersion, version };
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
import { type ChildProcess, spawn } from 'node:child_process';
|
||||
import { setTimeout as sleepAsync } from 'node:timers/promises';
|
||||
|
||||
export type ChildProcessHandle = {
|
||||
child: ChildProcess;
|
||||
resultPromise: Promise<string>;
|
||||
/** Present only when this child was started as the leader of its own process group. */
|
||||
processGroupId?: number;
|
||||
};
|
||||
let commandCloseDrainError: Error | undefined;
|
||||
|
||||
export const commands = {
|
||||
start(
|
||||
file: string,
|
||||
args: string[],
|
||||
{
|
||||
signal,
|
||||
captureStdout = false,
|
||||
detached = false,
|
||||
}: {
|
||||
signal?: AbortSignal;
|
||||
captureStdout?: boolean;
|
||||
/** Lead a new process group so cleanup can stop children that respawn. */
|
||||
detached?: boolean;
|
||||
} = {}
|
||||
): ChildProcessHandle {
|
||||
const child = spawn(file, args, {
|
||||
stdio: captureStdout ? ['ignore', 'pipe', 'inherit'] : 'inherit',
|
||||
signal,
|
||||
detached,
|
||||
});
|
||||
let stdout = '';
|
||||
let error: Error | undefined;
|
||||
let closeDrainTimer: NodeJS.Timeout | undefined;
|
||||
const resultPromise = new Promise<string>((resolve, reject) => {
|
||||
const startCloseDrainTimeout = (): void => {
|
||||
closeDrainTimer ??= setTimeout(() => {
|
||||
commandCloseDrainError ||= new Error(
|
||||
`${file} did not finish closing within 130 seconds after exit or error; Simulator cleanup could not be confirmed.`,
|
||||
{
|
||||
cause: error,
|
||||
}
|
||||
);
|
||||
try {
|
||||
child.kill('SIGKILL');
|
||||
} catch {
|
||||
/* Teardown remains failed. */
|
||||
}
|
||||
child.stdout?.destroy();
|
||||
child.unref();
|
||||
reject(error ?? commandCloseDrainError);
|
||||
}, 130_000);
|
||||
};
|
||||
child.stdout?.on('data', data => {
|
||||
stdout += data;
|
||||
});
|
||||
child.once('error', failure => {
|
||||
error = failure;
|
||||
startCloseDrainTimeout();
|
||||
});
|
||||
child.once('exit', (code, signal) => {
|
||||
if (code !== 0) {
|
||||
error ||= Object.assign(new Error(`${file} exited with ${signal ?? code}.`), { code });
|
||||
}
|
||||
startCloseDrainTimeout();
|
||||
});
|
||||
child.once('close', () => {
|
||||
clearTimeout(closeDrainTimer);
|
||||
error ? reject(error) : resolve(stdout);
|
||||
});
|
||||
});
|
||||
void resultPromise.catch(() => {}); // Observe long-lived launches before startup joins or cleanup await them.
|
||||
return {
|
||||
child,
|
||||
resultPromise,
|
||||
...(detached && child.pid ? { processGroupId: child.pid } : {}),
|
||||
};
|
||||
},
|
||||
async runAsync(file: string, args: string[], signal?: AbortSignal): Promise<string> {
|
||||
return await commands.start(file, args, { signal, captureStdout: true }).resultPromise;
|
||||
},
|
||||
throwIfCommandCloseTimedOut(): void {
|
||||
if (commandCloseDrainError) {
|
||||
throw commandCloseDrainError;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
/** Checks ancestry only while the service's owned child is still alive. */
|
||||
export async function isProcessOwnedByServiceAsync(
|
||||
pid: number,
|
||||
child: ChildProcess,
|
||||
signal: AbortSignal
|
||||
): Promise<boolean> {
|
||||
const seen = new Set<number>();
|
||||
for (let depth = 0; depth < 32; depth++) {
|
||||
signal.throwIfAborted();
|
||||
if (
|
||||
!Number.isSafeInteger(pid) ||
|
||||
pid <= 1 ||
|
||||
!child.pid ||
|
||||
child.exitCode != null ||
|
||||
child.signalCode != null ||
|
||||
seen.has(pid)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (pid === child.pid) {
|
||||
return true;
|
||||
}
|
||||
seen.add(pid);
|
||||
try {
|
||||
pid = Number(
|
||||
(await commands.runAsync('ps', ['-p', String(pid), '-o', 'ppid='], signal)).trim()
|
||||
);
|
||||
} catch (error) {
|
||||
signal.throwIfAborted();
|
||||
if ((error as { code?: unknown }).code === 1) {
|
||||
return false;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** EPERM means the process exists but cannot be signalled, as for an exited one awaiting reap. */
|
||||
function isProcessRunning(pid: number): boolean {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
return true;
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (code === 'ESRCH') {
|
||||
return false;
|
||||
}
|
||||
if (code === 'EPERM') {
|
||||
return true;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
/** Signals a process; false when it is gone, true when it was signalled or cannot be. */
|
||||
function signalProcess(pid: number, signal: NodeJS.Signals): boolean {
|
||||
try {
|
||||
process.kill(pid, signal);
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (code === 'ESRCH') {
|
||||
return false;
|
||||
}
|
||||
if (code !== 'EPERM') {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* macOS reports EPERM for a group whose only members have exited and await reaping, so EPERM
|
||||
* is resolved by checking for a member that is not a zombie.
|
||||
*/
|
||||
async function isProcessGroupRunningAsync(groupId: number): Promise<boolean> {
|
||||
try {
|
||||
process.kill(-groupId, 0);
|
||||
return true;
|
||||
} catch (error) {
|
||||
const code = (error as NodeJS.ErrnoException).code;
|
||||
if (code === 'ESRCH') {
|
||||
return false;
|
||||
}
|
||||
if (code !== 'EPERM') {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
const members = await commands.runAsync('ps', ['-A', '-o', 'pgid=,stat=']);
|
||||
return members
|
||||
.trim()
|
||||
.split('\n')
|
||||
.some(line => {
|
||||
const [pgid, stat = ''] = line.trim().split(/\s+/);
|
||||
return Number(pgid) === groupId && !stat.startsWith('Z');
|
||||
});
|
||||
}
|
||||
|
||||
async function stopProcessTreeAsync(
|
||||
pid: number,
|
||||
deadlineMs: number,
|
||||
ownedChildProcess?: ChildProcess,
|
||||
stopIntent?: { child: ChildProcess; descendantSignalled: boolean }
|
||||
): Promise<void> {
|
||||
const children = await commands.runAsync('pgrep', ['-P', String(pid)]).catch(error => {
|
||||
if (error.code !== 1) {
|
||||
throw error;
|
||||
}
|
||||
return '';
|
||||
});
|
||||
if (
|
||||
ownedChildProcess &&
|
||||
(ownedChildProcess.exitCode != null || ownedChildProcess.signalCode != null)
|
||||
) {
|
||||
throw new Error(
|
||||
'A Simulator service launcher exited before its child processes could be identified; cleanup could not be confirmed.'
|
||||
);
|
||||
}
|
||||
const descendants = await Promise.allSettled(
|
||||
children
|
||||
.trim()
|
||||
.split(/\s+/)
|
||||
.filter(Boolean)
|
||||
.map(child => stopProcessTreeAsync(Number(child), deadlineMs, undefined, stopIntent))
|
||||
);
|
||||
const failedDescendant = descendants.find(result => result.status === 'rejected');
|
||||
if (failedDescendant?.status === 'rejected') {
|
||||
throw failedDescendant.reason;
|
||||
}
|
||||
if (
|
||||
ownedChildProcess &&
|
||||
(ownedChildProcess.exitCode != null || ownedChildProcess.signalCode != null)
|
||||
) {
|
||||
// A wrapper can propagate its deliberately stopped child's nonzero status. The caller still
|
||||
// requires the owned group to drain and the owned close event; never probe this PID again.
|
||||
if (stopIntent ? stopIntent.descendantSignalled : ownedChildProcess.exitCode === 0) {
|
||||
return;
|
||||
}
|
||||
throw new Error(
|
||||
'A Simulator service launcher exited unexpectedly while its child processes were stopping; cleanup could not be confirmed.'
|
||||
);
|
||||
}
|
||||
if (!isProcessRunning(pid)) {
|
||||
return;
|
||||
}
|
||||
const wrapperWasRunning =
|
||||
stopIntent && stopIntent.child.exitCode == null && stopIntent.child.signalCode == null;
|
||||
try {
|
||||
if (ownedChildProcess) {
|
||||
if (!ownedChildProcess.kill('SIGTERM')) {
|
||||
throw new Error(
|
||||
'A Simulator service launcher exited before it could be stopped safely; cleanup could not be confirmed.'
|
||||
);
|
||||
}
|
||||
} else {
|
||||
if (!signalProcess(pid, 'SIGTERM')) {
|
||||
return;
|
||||
}
|
||||
if (stopIntent && wrapperWasRunning) {
|
||||
stopIntent.descendantSignalled = true;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ESRCH') {
|
||||
throw error;
|
||||
}
|
||||
return;
|
||||
}
|
||||
// ChildProcess is authoritative once its exit is observed; the numeric PID could be reused.
|
||||
const hasExited = (): boolean =>
|
||||
ownedChildProcess !== undefined &&
|
||||
(ownedChildProcess.exitCode != null || ownedChildProcess.signalCode != null);
|
||||
while (!hasExited() && isProcessRunning(pid)) {
|
||||
const state = await commands
|
||||
.runAsync('ps', ['-p', String(pid), '-o', 'state='])
|
||||
.catch(error => {
|
||||
if (error.code === 1 && (hasExited() || !isProcessRunning(pid))) {
|
||||
return '';
|
||||
}
|
||||
throw error;
|
||||
});
|
||||
if (hasExited() || state.trim().startsWith('Z') || !isProcessRunning(pid)) {
|
||||
return;
|
||||
}
|
||||
if (Date.now() >= deadlineMs) {
|
||||
throw new Error(
|
||||
`Simulator service process ${pid} is still running; cleanup could not be confirmed.`
|
||||
);
|
||||
}
|
||||
await sleepAsync(100);
|
||||
}
|
||||
}
|
||||
|
||||
export async function stopProcessAndDescendantsAsync(
|
||||
processHandle: ChildProcessHandle,
|
||||
allowCompletedProcess = false
|
||||
): Promise<void> {
|
||||
const { child } = processHandle;
|
||||
const groupId = processHandle.processGroupId;
|
||||
if (groupId !== undefined && groupId !== child.pid) {
|
||||
throw new Error('The Simulator service process group does not belong to its owned launcher.');
|
||||
}
|
||||
if (child.pid && child.exitCode == null && child.signalCode == null) {
|
||||
await stopProcessTreeAsync(
|
||||
child.pid,
|
||||
Date.now() + 130_000,
|
||||
child,
|
||||
groupId === undefined ? undefined : { child, descendantSignalled: false }
|
||||
);
|
||||
if (groupId !== undefined) {
|
||||
// A supervisor can respawn children after the initial snapshot. Its exclusive group must
|
||||
// also be empty; draining only the children we discovered is not sufficient.
|
||||
await terminateProcessGroupAsync(processHandle);
|
||||
}
|
||||
} else if (child.pid && !allowCompletedProcess) {
|
||||
// Never inspect a reused wrapper PID or infer that its descendants have also exited.
|
||||
throw new Error(
|
||||
'A Simulator service exited before its child processes could be stopped; cleanup could not be confirmed.'
|
||||
);
|
||||
}
|
||||
await processHandle.resultPromise.catch(() => {});
|
||||
commands.throwIfCommandCloseTimedOut();
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops a process group that has nothing to finalize. The handle must lead its own group
|
||||
* (`commands.start(..., { detached: true })`), so children spawned or respawned during the stop are
|
||||
* signalled too, and the group ID cannot be reused while any member is alive.
|
||||
*/
|
||||
export async function terminateProcessGroupAsync(
|
||||
processHandle: ChildProcessHandle,
|
||||
graceMs = 5_000
|
||||
): Promise<void> {
|
||||
const groupId = processHandle.child.pid;
|
||||
if (!groupId) {
|
||||
throw new Error('A Simulator service has no process group; cleanup could not be confirmed.');
|
||||
}
|
||||
for (const signal of ['SIGTERM', 'SIGKILL'] as const) {
|
||||
if (!(await isProcessGroupRunningAsync(groupId)) || !signalProcess(-groupId, signal)) {
|
||||
break;
|
||||
}
|
||||
const deadline = Date.now() + graceMs;
|
||||
while ((await isProcessGroupRunningAsync(groupId)) && Date.now() < deadline) {
|
||||
await sleepAsync(100);
|
||||
}
|
||||
}
|
||||
if (await isProcessGroupRunningAsync(groupId)) {
|
||||
throw new Error(
|
||||
`Simulator service process group ${groupId} is still running; cleanup could not be confirmed.`
|
||||
);
|
||||
}
|
||||
await processHandle.resultPromise.catch(() => {});
|
||||
commands.throwIfCommandCloseTimedOut();
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import fs from 'node:fs/promises';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { setTimeout as sleepAsync } from 'node:timers/promises';
|
||||
import { z } from 'zod';
|
||||
|
||||
import { type ChildProcessHandle, commands, isProcessOwnedByServiceAsync } from './processes';
|
||||
import { type WarmServer } from './state';
|
||||
|
||||
const SERVE_SIM_READY_TIMEOUT_MS = 120_000;
|
||||
// The job needs the token from this file; /readyz itself is not token-gated.
|
||||
const ServeSimStateSchema = z.object({
|
||||
pid: z.number().int().min(2),
|
||||
port: z.number().int().min(1).max(65535),
|
||||
device: z.string(),
|
||||
url: z.string(),
|
||||
token: z.string().min(1),
|
||||
});
|
||||
|
||||
export function startServeSim(
|
||||
devices: string[],
|
||||
signal: AbortSignal,
|
||||
port = 3200
|
||||
): ChildProcessHandle {
|
||||
signal.throwIfAborted();
|
||||
return commands.start(
|
||||
'bunx',
|
||||
[
|
||||
`@expo/serve-sim@${process.env.SERVE_SIM_VERSION || 'latest'}`,
|
||||
...devices,
|
||||
'--host',
|
||||
'127.0.0.1',
|
||||
'--port',
|
||||
String(port),
|
||||
'--require-token',
|
||||
'--orphan',
|
||||
'--transport',
|
||||
'webrtc',
|
||||
'--webrtc-codec',
|
||||
'h264',
|
||||
'--max-dimension',
|
||||
'1600',
|
||||
'--mjpeg-quality',
|
||||
'0.55',
|
||||
'--video-bitrate',
|
||||
'10000000',
|
||||
'--video-fps',
|
||||
'60',
|
||||
'--disable-share',
|
||||
'--quiet',
|
||||
],
|
||||
// The orphan owns boot, device selection and its native children for this VM's job.
|
||||
{ detached: true }
|
||||
);
|
||||
}
|
||||
|
||||
/** A job reads serve-sim's state and calls /readyz as soon as its claim returns. */
|
||||
export async function waitForServeSimReadyAsync(
|
||||
udid: string,
|
||||
server: ChildProcessHandle,
|
||||
signal: AbortSignal,
|
||||
port = 3200
|
||||
): Promise<WarmServer> {
|
||||
const url = `http://127.0.0.1:${port}`;
|
||||
let exited = false;
|
||||
// Handle both outcomes: a rejection here would otherwise be unhandled and end the launcher.
|
||||
const markExited = (): void => {
|
||||
exited = true;
|
||||
};
|
||||
void server.resultPromise.then(markExited, markExited);
|
||||
const throwIfExited = (): void => {
|
||||
if (exited || server.child.exitCode != null || server.child.signalCode != null) {
|
||||
throw new Error(`serve-sim exited before ${udid} became ready.`);
|
||||
}
|
||||
};
|
||||
const stateDirectory = process.env.SERVE_SIM_STATE_DIR || path.join(os.tmpdir(), 'serve-sim');
|
||||
const stateFile = path.join(stateDirectory, `server-${udid}.json`);
|
||||
const deadline = Date.now() + SERVE_SIM_READY_TIMEOUT_MS;
|
||||
for (;;) {
|
||||
signal.throwIfAborted();
|
||||
throwIfExited();
|
||||
if (Date.now() >= deadline) {
|
||||
throw new Error(`Timed out waiting for serve-sim on ${udid} to become ready.`);
|
||||
}
|
||||
const state = await fs
|
||||
.readFile(stateFile, 'utf8')
|
||||
.then(contents => ServeSimStateSchema.parse(JSON.parse(contents)))
|
||||
.catch(() => undefined);
|
||||
// Only the local serve-sim this launcher started may be probed; the job checks the same.
|
||||
if (state && state.url !== url) {
|
||||
throw new Error(`serve-sim on ${udid} reports ${state.url}, not ${url}.`);
|
||||
}
|
||||
if (state && (state.port !== port || state.device.toUpperCase() !== udid.toUpperCase())) {
|
||||
throw new Error('The warm serve-sim registration reports a different device or port.');
|
||||
}
|
||||
let readyForDevice = false;
|
||||
if (state && (await isProcessOwnedByServiceAsync(state.pid, server.child, signal))) {
|
||||
try {
|
||||
const response = await fetch(`${url}/readyz`, {
|
||||
signal: AbortSignal.any([signal, AbortSignal.timeout(2_000)]),
|
||||
});
|
||||
const ready = response.ok
|
||||
? ((await response.json()) as { status?: string; device?: string })
|
||||
: {};
|
||||
readyForDevice =
|
||||
ready.status === 'ready' && ready.device?.toUpperCase() === udid.toUpperCase();
|
||||
} catch {
|
||||
// serve-sim writes its state and answers /readyz only once it is listening.
|
||||
}
|
||||
}
|
||||
signal.throwIfAborted();
|
||||
throwIfExited();
|
||||
if (
|
||||
readyForDevice &&
|
||||
state &&
|
||||
(await isProcessOwnedByServiceAsync(state.pid, server.child, signal))
|
||||
) {
|
||||
signal.throwIfAborted();
|
||||
throwIfExited();
|
||||
const nativeStartTime = (
|
||||
await commands.runAsync('ps', ['-p', String(state.pid), '-o', 'lstart='], signal)
|
||||
).trim();
|
||||
signal.throwIfAborted();
|
||||
throwIfExited();
|
||||
if (
|
||||
!nativeStartTime ||
|
||||
!(await isProcessOwnedByServiceAsync(state.pid, server.child, signal))
|
||||
) {
|
||||
throw new Error('The warm serve-sim process identity could not be confirmed.');
|
||||
}
|
||||
return {
|
||||
startupDevice: udid,
|
||||
pid: state.pid,
|
||||
nativeStartTime,
|
||||
port,
|
||||
url,
|
||||
token: state.token,
|
||||
};
|
||||
}
|
||||
await sleepAsync(250, undefined, { signal });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
import { z } from 'zod';
|
||||
import { setTimeout as sleepAsync } from 'node:timers/promises';
|
||||
|
||||
import { commands } from './processes';
|
||||
import { type SimulatorDevice, SimulatorDeviceSchema } from './state';
|
||||
|
||||
const AvailableSimulatorsSchema = z.object({
|
||||
devices: z.record(
|
||||
z.string(),
|
||||
z.array(SimulatorDeviceSchema.extend({ isAvailable: z.boolean().optional() }))
|
||||
),
|
||||
});
|
||||
const SimulatorStatesSchema = z.object({
|
||||
devices: z.record(z.string(), z.array(z.object({ udid: z.string(), state: z.string() }))),
|
||||
});
|
||||
|
||||
export async function listAvailableSimulatorsAsync(
|
||||
signal: AbortSignal
|
||||
): Promise<SimulatorDevice[]> {
|
||||
const { devices } = AvailableSimulatorsSchema.parse(
|
||||
JSON.parse(
|
||||
await commands.runAsync('xcrun', ['simctl', 'list', 'devices', 'available', '--json'], signal)
|
||||
)
|
||||
);
|
||||
return Object.values(devices)
|
||||
.flat()
|
||||
.filter(device => device.isAvailable !== false);
|
||||
}
|
||||
|
||||
/** Devices matching an exact name or UDID, or else the available iPhone with the shortest name. */
|
||||
export function selectSimulators(devices: SimulatorDevice[], selector?: string): SimulatorDevice[] {
|
||||
return selector
|
||||
? devices.filter(
|
||||
device => device.name === selector || device.udid.toLowerCase() === selector.toLowerCase()
|
||||
)
|
||||
: devices
|
||||
.filter(device => device.name.startsWith('iPhone'))
|
||||
.sort((a, b) => a.name.length - b.name.length)
|
||||
.slice(0, 1);
|
||||
}
|
||||
|
||||
/** Resolve every configured warm device before native work; the first is the claim default. */
|
||||
export function selectWarmupSimulators(
|
||||
devices: SimulatorDevice[],
|
||||
selectors?: string
|
||||
): SimulatorDevice[] {
|
||||
const entries = !selectors?.trim()
|
||||
? [undefined]
|
||||
: selectors.split(',').map(value => value.trim());
|
||||
const selected = new Set<string>();
|
||||
return entries.map(selector => {
|
||||
if (selector === '') {
|
||||
throw new Error('EXPO_SIMULATOR_DEVICE must contain nonempty device names or UDIDs.');
|
||||
}
|
||||
const matches = selectSimulators(devices, selector);
|
||||
if (matches.length !== 1) {
|
||||
throw new Error(
|
||||
`Expected one available Simulator for ${selector ?? 'the default iPhone'}, found ${matches.length}. Use an exact device name or UDID.`
|
||||
);
|
||||
}
|
||||
const device = matches[0];
|
||||
const udid = device.udid.toLowerCase();
|
||||
if (selected.has(udid)) {
|
||||
throw new Error(
|
||||
`Simulator ${device.name} (${device.udid}) appears more than once in EXPO_SIMULATOR_DEVICE.`
|
||||
);
|
||||
}
|
||||
selected.add(udid);
|
||||
return device;
|
||||
});
|
||||
}
|
||||
|
||||
/** Observe an orphan-owned warm boot without starting another boot or killing it on claim. */
|
||||
export async function waitForSimulatorBootAsync(udid: string, signal: AbortSignal): Promise<void> {
|
||||
const deadline = Date.now() + 120_000;
|
||||
while (Date.now() < deadline) {
|
||||
signal.throwIfAborted();
|
||||
const { devices } = SimulatorStatesSchema.parse(
|
||||
JSON.parse(await commands.runAsync('xcrun', ['simctl', 'list', 'devices', '--json'], signal))
|
||||
);
|
||||
if (
|
||||
Object.values(devices)
|
||||
.flat()
|
||||
.some(device => device.udid === udid && device.state === 'Booted')
|
||||
) {
|
||||
await commands.runAsync('xcrun', ['simctl', 'bootstatus', udid], signal);
|
||||
return;
|
||||
}
|
||||
await sleepAsync(250, undefined, { signal });
|
||||
}
|
||||
throw new Error(`Timed out waiting for serve-sim to boot Simulator ${udid}.`);
|
||||
}
|
||||
|
||||
/** `simctl shutdown` fails for a device that is already shut down; that device is done. */
|
||||
export async function shutdownSimulatorAsync(udid: string): Promise<void> {
|
||||
// A shutdown that cannot finish fails instead of blocking cleanup forever.
|
||||
const signal = AbortSignal.timeout(120_000);
|
||||
try {
|
||||
await commands.runAsync('xcrun', ['simctl', 'shutdown', udid], signal);
|
||||
} catch (error) {
|
||||
const { devices } = SimulatorStatesSchema.parse(
|
||||
JSON.parse(await commands.runAsync('xcrun', ['simctl', 'list', 'devices', '--json'], signal))
|
||||
);
|
||||
if (
|
||||
Object.values(devices)
|
||||
.flat()
|
||||
.find(device => device.udid === udid)?.state !== 'Shutdown'
|
||||
) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Push notifications are not used in warm sessions, and apsd's work competes with app installs. */
|
||||
export async function disableApsdAsync(udid: string, signal: AbortSignal): Promise<void> {
|
||||
const launchctl = (...args: string[]): Promise<string> =>
|
||||
commands.runAsync('xcrun', ['simctl', 'spawn', udid, 'launchctl', ...args], signal);
|
||||
let lastError: unknown;
|
||||
for (const domain of ['user/foreground', 'system']) {
|
||||
const service = `${domain}/com.apple.apsd`;
|
||||
try {
|
||||
await launchctl('disable', service);
|
||||
// bootout fails when apsd is already gone; the list check below decides.
|
||||
await launchctl('bootout', service).catch(error => {
|
||||
lastError = error;
|
||||
});
|
||||
// launchctl list exits 113 for a service that is not loaded.
|
||||
const loaded = await launchctl('list', 'com.apple.apsd').then(
|
||||
() => true,
|
||||
error => (error.code === 113 ? false : Promise.reject(error))
|
||||
);
|
||||
if (!loaded) {
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
signal.throwIfAborted();
|
||||
lastError = error;
|
||||
}
|
||||
}
|
||||
throw lastError ?? new Error('apsd is still loaded in the Simulator.');
|
||||
}
|
||||
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user