mirror of
https://github.com/expo/explore.git
synced 2026-11-15 17:32:23 -10:00
Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0352b3e5fc | ||
|
|
7bf12bcf42 | ||
|
|
f904120f78 | ||
|
|
9a548cf2e8 | ||
|
|
40b581d385 | ||
|
|
c7f7dc800d | ||
|
|
8e576c5f57 | ||
|
|
deed8e9cc1 | ||
|
|
a3f1ad2ffa | ||
|
|
91b2b49d61 | ||
|
|
490123d380 | ||
|
|
87106f6672 |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
# Expo Explore
|
||||
|
||||
Explore maps your app: a screenshot of every screen, connected by the taps between them. On each pull request it captures the screens the PR changes, before and after, on EAS Simulator, and posts a visual review. On your Mac it can also run on a local simulator.
|
||||
Explore maps your app: a screenshot of every screen, connected by the taps between them. On each pull request it captures the screens the PR changes, before and after, on EAS Simulator, and posts a visual review.
|
||||
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/readme-hero-dark.png">
|
||||
@@ -53,76 +53,52 @@ which look like regressions. For each regression, name the source file to fix.
|
||||
<details>
|
||||
<summary><strong>Requirements</strong></summary>
|
||||
|
||||
- To review a change: Expo SDK 57 or newer, with Expo Router (57 or newer) or React Navigation (6 or newer), and an Expo account, since Explore builds the app on EAS. An EAS build profile per platform: `ios.simulator: true` for iOS, `android.buildType: apk` (not a development build) for Android. Its EAS environment cannot have secret-visibility or file variables.
|
||||
- To explore a build: a simulator build of any app, and a Claude Code or Codex login (or an API key). On a local simulator it needs no Expo account.
|
||||
- Somewhere to run the app: EAS Simulator (in preview, [join the waitlist](https://expo.dev/services/simulators)), which CI uses; or a [local simulator](#simulator) on your Mac: Xcode 26 or newer for iOS (the default devices are iPhone 17 models) and, for Android, the Android SDK with `ANDROID_HOME` set (emulator, platform-tools, cmdline-tools and a system image; to review a change, also build-tools and a JDK 17).
|
||||
- Node.js 24.12 or newer. For CI, admin access to the GitHub repository.
|
||||
- An iOS app, an Android app, or both. Explore is in v0; Android capture is newer than iOS.
|
||||
- Expo SDK 57 or newer, with Expo Router (57 or newer) or React Navigation (6 or newer).
|
||||
- An EAS build profile per platform: `ios.simulator: true` for iOS, `android.buildType: apk` for Android. Its EAS environment cannot have secret-visibility variables.
|
||||
- EAS Simulator access (in preview, [join the waitlist](https://expo.dev/services/simulators)).
|
||||
- Node.js 24.12 or newer, and admin access to the GitHub repository.
|
||||
|
||||
</details>
|
||||
|
||||
## Quick start
|
||||
|
||||
Paste this into Claude Code or Codex from your app's directory. It reviews a change to your app, before and after, or, if you point it to a build, maps every screen of that build:
|
||||
Review a change to your own app, on your machine. You need an Expo SDK 57+ app with Expo Router or React Navigation, Node.js 24.12+, and EAS Simulator access ([join the waitlist](https://expo.dev/services/simulators)). No API keys, no CI.
|
||||
|
||||
```text
|
||||
Show me Expo Explore working on this app, with npx @expo/explore. If I point you to a
|
||||
build (.app, .tar.gz, simulator .ipa, or .apk), explore it: follow
|
||||
https://unpkg.com/@expo/explore/skills/explore-binary/SKILL.md. If this is not an Expo
|
||||
project, ask me for a simulator build and explore that. Otherwise review a change to
|
||||
this app: follow the "Review a change on this machine" section of
|
||||
https://unpkg.com/@expo/explore/skills/explore-setup/SKILL.md. If the app cannot build
|
||||
for the iOS Simulator on EAS yet, set that up (an EAS project, ios.bundleIdentifier, an
|
||||
"explore" profile with ios.simulator: true) and ask me before you commit it. If I have
|
||||
no EAS Simulator access, pass --simulator local (it needs Xcode; exploring an .apk needs
|
||||
the Android SDK instead). If I have no uncommitted changes, change some text near the
|
||||
top of a screen. If the app needs a sign-in, ask me for a test account the way the skill
|
||||
describes, never for a password in chat. Open the report, and if I need to log in to
|
||||
something first, tell me the command.
|
||||
```
|
||||
From your app's directory:
|
||||
|
||||
You need Node.js 24.12+. Reviewing a change needs an Expo account and an Expo SDK 57+ app with Expo Router or React Navigation: it is built on EAS and captured on EAS Simulator ([join the waitlist](https://expo.dev/services/simulators)) or, with Xcode, on a simulator on your Mac. Exploring a build needs a Claude Code or Codex login, and EAS Simulator or a simulator on your Mac; on your Mac, no Expo account. No API keys, no CI.
|
||||
|
||||
<details>
|
||||
<summary><strong>Run it yourself</strong></summary>
|
||||
|
||||
There are two ways to use Explore: review a change to your Expo app, which needs an Expo account, or explore an iOS or Android build of any app directly, which needs no Expo account when it runs on your Mac.
|
||||
|
||||
**Review a change**, from your app's directory:
|
||||
|
||||
1. Make the app buildable on EAS, if it is not yet:
|
||||
1. **Make the app buildable on EAS, if it is not yet.**
|
||||
|
||||
```sh
|
||||
npx eas-cli@latest login
|
||||
npx eas-cli@latest init
|
||||
```
|
||||
|
||||
Then set `ios.bundleIdentifier` in your app config, add a simulator profile to `eas.json`, and commit. The "before" is where your branch left the default branch: on the default branch, your last commit.
|
||||
Then set `ios.bundleIdentifier` in your app config, add a simulator profile to `eas.json`, and commit. The review builds your last commit as the "before".
|
||||
|
||||
```json
|
||||
{ "build": { "explore": { "ios": { "simulator": true } } } }
|
||||
```
|
||||
|
||||
2. Edit some text near the top of a screen (Explore captures the first screenful) and run:
|
||||
2. **Change a screen, then review the change.** Edit some text near the top of a screen (Explore captures the first screenful) and run:
|
||||
|
||||
```sh
|
||||
npx @expo/explore capture # on EAS Simulator
|
||||
npx @expo/explore capture --simulator local # or on a simulator on your Mac
|
||||
npx @expo/explore capture
|
||||
```
|
||||
|
||||
Explore builds your last commit and your uncommitted changes on EAS, captures the screens the changes can affect, before and after, and opens the report in your browser. The first run waits for an EAS build; later runs reuse it while your native code is unchanged. A [local simulator](#simulator) is one Explore creates on your Mac and removes afterwards.
|
||||
Explore builds your last commit and your uncommitted changes on EAS, captures the screens the changes can affect, before and after, on EAS Simulator, and opens the report in your browser. The first run waits for an EAS build; later runs reuse it while your native code is unchanged.
|
||||
|
||||
**Explore a build:**
|
||||
Or paste this into Claude Code or Codex from your app's directory:
|
||||
|
||||
```sh
|
||||
npx @expo/explore explore:binary ./my-app.apk # Android APK
|
||||
npx @expo/explore explore:binary ./my-app.app # iOS simulator build (.app, .tar.gz, or simulator .ipa)
|
||||
npx @expo/explore explore:binary ./my-app.app --simulator local # on a simulator on your Mac
|
||||
```text
|
||||
Show me an Expo Explore review of a change to this app. Follow the "Review a change on
|
||||
this machine" section of https://unpkg.com/@expo/explore/skills/explore-setup/SKILL.md.
|
||||
If the app cannot build for the iOS Simulator on EAS yet, set that up (an EAS project,
|
||||
ios.bundleIdentifier, an "explore" profile with ios.simulator: true) and ask me before
|
||||
you commit it. If I have no uncommitted changes, change some text near the top of a
|
||||
screen. Then run npx @expo/explore capture and open the report.
|
||||
```
|
||||
|
||||
Explore starts an EAS Simulator, installs the build, taps through the app with your Claude Code or Codex login, and prints a link to the hosted report. With `--simulator local` it runs on a simulator or emulator it creates on your Mac, needs no Expo account, and opens the report in your browser. Its [options](#options) are below.
|
||||
|
||||
</details>
|
||||
|
||||
Every run is kept on your machine for 30 days. `npx @expo/explore reports` lists your local reviews, explorations and uploaded reports with their commits, and reopens or hosts one without capturing again:
|
||||
|
||||
<picture>
|
||||
@@ -139,12 +115,12 @@ npx @expo/explore capture --committed # HEAD alone
|
||||
npx @expo/explore capture --base v1.3.0 --head v1.4.0 --scope all --upload
|
||||
```
|
||||
|
||||
- It checks out both commits as temporary worktrees, installs their dependencies, captures every configured platform or [target](#targets) on EAS Simulator or a [local simulator](#simulator), and opens the report in a local Viewer. `--target` or `--platform` picks some; they run at once, at most `--parallel N` at a time. `--upload` hosts it for 30 days (`--expires-in` changes that) and prints the link; `report:upload <report.zip>` hosts one you already have.
|
||||
- It checks out both commits as temporary worktrees, installs their dependencies, captures every configured platform on EAS Simulator (`--platform` picks one), and opens the report in a local Viewer. `--upload` hosts it and prints the link; `report:upload <report.zip>` hosts one you already have.
|
||||
- Your checkout, index and branches are never touched. Your uncommitted changes, untracked files included, are reviewed as `eas build` would upload them; `--committed`, or `cli.requireCommit: true` in `eas.json`, leaves them out.
|
||||
- It runs both commits' code on your machine, as you: installing their dependencies, evaluating the app config, and bundling the JavaScript. That is what checking them out and running them would do, so review only commits you would run, and someone else's branch only if you trust it.
|
||||
- Installs run without credential environment variables, which keeps tokens out of reach of a registry a commit's `.npmrc` names; that is not a sandbox. A registry that needs `${NPM_TOKEN}` in the project's `.npmrc` must be authenticated in your own `~/.npmrc`.
|
||||
- Captures are cached in `~/.cache/expo-explore`, so the same base is not captured twice (`--no-cache` skips it); a capture unused for 30 days goes, and the cache stays under 2 GB. Ctrl+C stops the run's simulator sessions and local devices; when a run is stopped harder than that, the next local run stops what it left running.
|
||||
- Like a CI review, it builds on EAS (reusing a matching build) and, unless it captures on a local simulator, runs EAS Simulator sessions: expect several minutes and EAS usage.
|
||||
- Captures are cached in `~/.cache/expo-explore`, so the same base is not captured twice (`--no-cache` skips it); a capture unused for 30 days goes, and the cache stays under 2 GB. Ctrl+C stops the run's simulator sessions.
|
||||
- Like a CI review, it builds on EAS (reusing a matching build) and runs simulator sessions: expect several minutes and EAS usage.
|
||||
- Saved runs take up to 2 GB in all, the oldest going first. `reports add <report.zip>` keeps a report you downloaded, such as a PR's `explore-review` artifact.
|
||||
|
||||
</details>
|
||||
@@ -153,22 +129,44 @@ Explore uses its defaults until you run `npx @expo/explore setup`, which writes
|
||||
|
||||
## Map every screen of any app
|
||||
|
||||
Pointed to a build, the [quick start](#quick-start) maps every screen of it, with no source and no config: one card per screen it reached, connected by the taps between them. For apps behind a sign-in, see [Sign-in and other app state](#sign-in-and-other-app-state).
|
||||
To map every screen of an app instead, with no config, paste this into Claude Code or Codex from your app's directory. It explores a build you point to, or an Expo project straight from its source:
|
||||
|
||||
```text
|
||||
Show me Expo Explore working on this app. Follow
|
||||
https://unpkg.com/@expo/explore/skills/explore-binary/SKILL.md and run Explore with
|
||||
npx @expo/explore. If I point you to a build, explore that. Otherwise, if this is an
|
||||
Expo project, run it from source without making a new build; if it is not, get a
|
||||
simulator build of it. If the app needs a sign-in, ask me for a test account the way
|
||||
the skill describes, never for a password in chat. Give me the report link, and if I
|
||||
need to log in to something first, tell me the command.
|
||||
```
|
||||
|
||||
For apps behind a sign-in, see [Sign-in and other app state](#sign-in-and-other-app-state).
|
||||
|
||||
<details>
|
||||
<summary><strong>Run it yourself</strong></summary>
|
||||
|
||||
```sh
|
||||
npx @expo/explore explore:binary ./my-app.apk # Android APK
|
||||
npx @expo/explore explore:binary ./my-app.app # iOS simulator build (.app, .tar.gz, or simulator .ipa)
|
||||
```
|
||||
|
||||
Explore starts an EAS Simulator, installs the build, taps through the app with your Claude Code or Codex login, and prints a link to the hosted report.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary id="options"><strong>What it needs, and its options</strong></summary>
|
||||
|
||||
- A `claude` or `codex` login, or `ANTHROPIC_API_KEY` / `OPENAI_API_KEY`.
|
||||
- EAS Simulator access and an EAS login (`eas whoami`), or `--simulator local` to run on a [local simulator](#simulator) with no EAS login.
|
||||
- A simulator build. A device `.ipa`, an `.aab`, an unsigned APK, or an APK without native libraries for the emulator (x86_64 on EAS Simulator, `arm64-v8a` locally on Apple silicon; a universal APK has both) is rejected before a device starts.
|
||||
- An EAS login (`eas whoami`) and a `claude` or `codex` login, or `ANTHROPIC_API_KEY` / `OPENAI_API_KEY`.
|
||||
- A simulator build. A device `.ipa` or an `.aab` is rejected before a session starts.
|
||||
- Platform, bundle id, name, and version are read from the build; you pass nothing else.
|
||||
- A run stops after 15 minutes, 40 screens, or 150 actions (`--max-duration-minutes`, `--max-screens`, `--max-actions`).
|
||||
- Buttons that delete, pay, sign out, send, or leave the app are never tapped. `--allow-destructive "Reset filters"` allows one by its exact label.
|
||||
- Buttons that delete, pay, sign out, send, or leave the app are never tapped. `--allow-destructive "Clear cache"` allows one by label.
|
||||
- `--hints "…"` tells the model what to focus on or how to sign in ([details](#sign-in-and-other-app-state)).
|
||||
- On EAS Simulator the report is hosted, and the link lasts 7 days (`--expires-in` takes 1d to 90d, or never); `--no-upload` keeps it local. On a local simulator it opens in the local Viewer (`--no-open` or `--json` skips that; `view --dir <folder>` opens it later), and `--upload` hosts it, which needs an EAS login. `--json` prints the result for scripts.
|
||||
- For a link that stays the same from run to run, pass `--alias NAME` and set `EXPLORE_PREVIEW_TOKEN` to a fixed token of 32 characters from a–z and 2–7 (`LC_ALL=C tr -dc a-z2-7 </dev/urandom | head -c 32`).
|
||||
- EAS Simulator sessions and hosted reports run under an EAS project named `expo-explore` in your account, created on first use (`--owner` and `--project` pick another).
|
||||
- Read a local result with `npx @expo/explore view --dir <folder>`, `screen:list`, or `gap:list`.
|
||||
- The hosted link lasts 7 days (`--expires-in 30d|never`). `--no-upload` keeps the report local, and `--json` prints the result for scripts.
|
||||
- For a link that stays the same from run to run, pass `--alias NAME` and set `EXPLORE_PREVIEW_TOKEN` to a fixed 32-character token.
|
||||
- Read a local result with `expo-explore view --dir <folder>`, `screen:list`, or `gap:list`.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -190,7 +188,7 @@ npx @expo/explore explore:session <session-id> --env-file path/.env.eas-simulato
|
||||
<details>
|
||||
<summary><strong>What a run without source shows</strong></summary>
|
||||
|
||||
One card per screen the run reached, laid out by how many taps it took, with the tapped control on each edge. There is no before and after; that needs the app's source: [`capture`](#quick-start) on your machine, or [CI](#set-up-ci).
|
||||
One card per screen the run reached, laid out by how many taps it took, with the tapped control on each edge. There is no before and after; that needs [CI](#set-up-ci).
|
||||
|
||||

|
||||
|
||||
@@ -202,7 +200,7 @@ Explore runs in your repository's GitHub Actions in two ways, both from the same
|
||||
|
||||
### Review on every PR
|
||||
|
||||
Each pull request gets a comment linking its report: the screens it added, removed or changed, before and after, on each platform or device ([target](#targets)) you capture. Paste this into Claude Code or Codex from your app's repository:
|
||||
Each pull request gets a comment linking its report: the screens it added, removed or changed, before and after, on each platform you capture. Paste this into Claude Code or Codex from your app's repository:
|
||||
|
||||
```text
|
||||
Set up this app for Expo Explore CI reviews. Follow
|
||||
@@ -226,9 +224,9 @@ report:
|
||||
# project: acme-explore # default <repository name>-explore, created on first run
|
||||
```
|
||||
|
||||
- The generated workflows already have the `deploy` job; it runs once `hosting: eas` is set.
|
||||
- Run `expo-explore setup --workflows` after enabling it to add the `deploy` job.
|
||||
- A [comparison of two commits](#compare-any-two-commits) links its hosted report from the run's summary instead of a PR comment. `capture --upload` on your machine deploys to the same project with your `eas login`.
|
||||
- `expo-explore report:upload <report.zip>...` hosts reports already on your machine the same way: a review's reports (one per platform or target, from `capture --output` or a downloaded `explore-review` artifact) or an `explore:binary` report.
|
||||
- `expo-explore report:upload <report.zip>...` hosts reports already on your machine the same way: a review's reports (one per platform, from `capture --output` or a downloaded `explore-review` artifact) or an `explore:binary` report.
|
||||
- `EXPO_TOKEN` must be able to create the EAS project, so use a [robot user's](https://docs.expo.dev/accounts/programmatic-access/) token.
|
||||
- The report is encrypted, and only a request carrying the link's token can open it. Treat the link like a shared file link; see [report access](docs/private-review.md#hosted-previews).
|
||||
|
||||
@@ -240,11 +238,11 @@ report:
|
||||
The prompt above walks through these steps with you. To do them yourself:
|
||||
|
||||
1. Run `npx @expo/explore setup` in your app's directory (in a monorepo, add `--project apps/mobile`). It writes `.expo-explore/config.yaml` and the workflows.
|
||||
2. Run `npx @expo/explore doctor` and fix each problem it reports, until it exits 0. `doctor --capture` captures the committed app once, to check every screen before your first PR (with several targets, pass `--target`).
|
||||
2. Run `npx @expo/explore doctor` and fix each problem it reports, until it exits 0. `doctor --capture` captures the committed app on EAS once, to check every screen before your first PR.
|
||||
3. Set the repository secrets `doctor` lists:
|
||||
- `EXPO_TOKEN`: create it in [Expo access tokens](https://expo.dev/settings/access-tokens). For [hosted previews](#hosted-previews), use a [robot user](https://docs.expo.dev/accounts/programmatic-access/) that can create projects.
|
||||
- A secret for each `{{secret:NAME}}` in your setup steps. Run `npx @expo/explore setup --workflows` after you add one.
|
||||
4. Commit and merge to the default branch. **Expo Explore baseline** runs on that push (or run it from GitHub Actions).
|
||||
4. Commit, merge to the default branch, and run **Expo Explore baseline** from GitHub Actions.
|
||||
5. Open a PR. **Expo Explore review** runs and posts a comment with the report. To see a whole review of your branch first, run `npx @expo/explore capture` on your machine.
|
||||
|
||||
A failed run shows an error code and a next action in the PR comment; see [CI troubleshooting](docs/quickstart-ci.md#diagnose-a-failed-run).
|
||||
@@ -266,7 +264,7 @@ Both modes use the same comparison rules and report. You can change modes later.
|
||||
**To use agent mode:**
|
||||
|
||||
1. Create an [Anthropic](https://platform.claude.com/settings/keys) or [OpenAI](https://platform.openai.com/api-keys) API key.
|
||||
2. Set `mode: agent`, `agent.provider` (`anthropic` or `openai`), an `agent.model` your account can use, and `agent.instructions`: the path of a file in the repository that tells the agent how to use the app.
|
||||
2. Set `mode: agent` and an `agent.model` your account can use.
|
||||
3. Store the key as the repository secret `ANTHROPIC_API_KEY` or `OPENAI_API_KEY`. A key that is not workspace-scoped also needs the `ANTHROPIC_WORKSPACE_ID` variable.
|
||||
4. Export the key and run `expo-explore doctor --check-model`.
|
||||
|
||||
@@ -313,19 +311,17 @@ targets:
|
||||
android: { platform: android, device: pixel_7, bundleId: com.example.myapp, easProfile: explore-android }
|
||||
```
|
||||
|
||||
- A target takes the `app` fields it does not set, and `device.name` when it is of `app.platform`; a target of another platform sets its own `bundleId` and `easProfile` (an Android one's device defaults to `pixel_7`). `pose` is `closed`, `half-open` or `open`. `label` names it in reports (by default its device and pose).
|
||||
- Ids are up to 32 lowercase letters, digits and dashes, start with a letter, and are not `base`, `head` or `report`. A config names at most 8 targets. A config with `platforms` has one target per platform, named `ios` and `android`.
|
||||
- A target takes the flat `app` and `device` fields it does not set; a target of another platform than `app.platform` sets its own `bundleId` and `easProfile`. `label` names it in reports (by default its device and pose).
|
||||
- Ids are lowercase letters, digits and dashes. A config with `platforms` has one target per platform, named `ios` and `android`.
|
||||
- The workflows run one capture job per target, the PR comment has a section per target, and each report links its sibling targets' reports.
|
||||
- A target can also set its own `controller` and `simulator` over `capture`'s, such as Android on agent-device beside iOS targets on Argent. `--controller` and `--simulator` override every target's for one run.
|
||||
- `capture --target duo-open` reviews one target on this machine; `--platform ios` the iOS ones. On your machine a review's targets run at once (at most `--parallel N`), and targets of one platform and EAS profile share each commit's build; in CI each target is its own job. A target that fails outright costs only its own report.
|
||||
- A device controller that stops answering on one screen costs that route, up to three times per capture: Explore restarts the app, goes on with the next route, and records what happened in `capture-diagnostics/controller-recoveries.jsonl`.
|
||||
- `capture --target duo-open` reviews one target on this machine; `--platform ios` the iOS ones.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary id="controller"><strong>Device controller: agent-device or Argent</strong></summary>
|
||||
|
||||
Explore drives the simulator with [agent-device](https://github.com/callstackincubator/agent-device) by default. To use [Argent](https://github.com/software-mansion/argent) instead, set it in the config or pass it for one run:
|
||||
Explore drives EAS Simulator with [agent-device](https://github.com/callstackincubator/agent-device) by default. To use [Argent](https://github.com/software-mansion/argent) instead, set it in the config or pass it for one run:
|
||||
|
||||
```yaml
|
||||
capture:
|
||||
@@ -339,16 +335,16 @@ npx @expo/explore explore:binary ./app.apk --controller argent
|
||||
|
||||
Explore pins each controller's version and starts the EAS session with it. Reports and baselines record the controller, and a review compares captures made with the same one.
|
||||
|
||||
Neither controller is installed with Explore. The first run that needs one downloads its pinned npm release (agent-device 1.6 MB, Argent 27 MB), checks it against the integrity hash Explore pins, and keeps it in `~/.cache/expo-explore/controllers` (`EXPLORE_CONTROLLER_CACHE` moves it). Behind a private registry, set `EXPLORE_NPM_REGISTRY` to a mirror of it.
|
||||
Neither controller is installed with Explore. The first run that needs one downloads its pinned npm release (agent-device 1.4 MB, Argent 27 MB), checks it against the integrity hash Explore pins, and keeps it in `~/.cache/expo-explore/controllers` (`EXPLORE_CONTROLLER_CACHE` moves it). Behind a private registry, set `EXPLORE_NPM_REGISTRY` to a mirror of it.
|
||||
|
||||
Argent cannot switch the simulator's appearance yet ([software-mansion/argent#1509](https://github.com/software-mansion/argent/pull/1509)), so the host switches it: on an iOS EAS Simulator session (`eas simulator:control appearance.set`) and on a [local simulator](#simulator), every appearance the config asks for is captured. An Argent capture on an Android EAS Simulator session records one appearance: the one the app forces, else light. Explore warns when it skips one.
|
||||
Argent cannot switch the simulator's appearance yet ([software-mansion/argent#1509](https://github.com/software-mansion/argent/pull/1509)), so an Argent capture on EAS Simulator records one appearance: the one the app forces, else light. Explore warns when it skips one. On a [local simulator](#simulator) the host switches it, so both are captured.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary id="simulator"><strong>Local simulator instead of EAS Simulator</strong></summary>
|
||||
|
||||
To capture on your Mac instead of EAS Simulator, pass it for one run, or set it in a config you use only on your Mac:
|
||||
To capture on your Mac instead of EAS Simulator, set it in the config or pass it for one run:
|
||||
|
||||
```yaml
|
||||
capture:
|
||||
@@ -359,22 +355,16 @@ capture:
|
||||
npx @expo/explore capture --simulator local
|
||||
```
|
||||
|
||||
CI runs on GitHub's Ubuntu runners and captures on EAS Simulator, so keep `simulator: local` out of the config you commit.
|
||||
|
||||
For each commit, Explore starts a device of its own and removes it afterwards; head and base each get one:
|
||||
|
||||
- **iOS:** a simulator of the configured device with Xcode's newest runtime that runs it. `DEVELOPER_DIR` picks another Xcode, such as one that adds iPhone Duo. Explore approves the app's URL scheme on it, so links open without iOS asking "Open in …?", and checks a foldable's pose by the shape of its lit display.
|
||||
- **Android:** an emulator of the configured device profile (such as `pixel_7`), from the newest Google APIs system image installed for this machine (`arm64-v8a` on Apple silicon), in a private AVD folder. The APK must ship native libraries for that ABI; a universal build does. It needs the SDK's emulator, platform-tools and cmdline-tools, with `ANDROID_HOME` set.
|
||||
- **Android:** an emulator of the configured device profile (such as `pixel_7`), from the newest Google APIs system image installed for this machine (`arm64-v8a` on Apple silicon), in a private AVD folder. The APK must ship native libraries for that ABI; a universal build does.
|
||||
|
||||
`explore:binary --simulator local` starts one the same way for the build it explores, needs no EAS login, and opens the report in the local Viewer (`--upload` hosts it).
|
||||
Builds still run on EAS. The app is repacked with the route observer on your machine as well, so it is never uploaded; on Android that needs the SDK's build-tools and a JDK. `capture.repack: eas` (or `--repack eas`) keeps the repack in a hosted EAS job. `doctor --simulator local` checks that Xcode and the Android SDK can start each device, and that Android can be repacked locally.
|
||||
|
||||
For a review, builds still run on EAS. The app is repacked with the route observer on your machine as well, so it is never uploaded; on Android that needs the SDK's build-tools and a JDK. `capture.repack: eas` (or `--repack eas`) keeps the repack in a hosted EAS job. `doctor --simulator local` checks that Xcode and the Android SDK can start each device, and that Android can be repacked locally.
|
||||
With `--controller argent`, Explore installs Argent's tool-server on first use (with its dependencies, about 165 MB, in the controller cache) and starts one per device. The host switches the appearance, so a local Argent capture records light and dark. Reports record where they were captured, and a baseline is reused only by a review captured the same way.
|
||||
|
||||
With `--controller argent`, Explore installs Argent's tool-server on first use with `npm ci` from a lockfile Explore ships, so every dependency is pinned (about 160 MB, in the controller cache), and starts one per device. The host switches the appearance, so a local Argent capture records every appearance the config asks for. Reports record where they were captured, and a baseline is reused only by a review captured the same way.
|
||||
|
||||
A foldable folds before the app first opens (`pose` on a [target](#targets)); with agent-device on a local simulator it folds just after, since agent-device folds only inside a session. With Argent, an opened iPhone Duo is captured upright, in landscape. After a fold, Argent's reader can stay on the panel that went dark, so Explore checks that the lit panel is read. If it isn't, Explore restarts the tool-server on a local simulator. On EAS Simulator, where the tool-server is the session's, it resets Argent's device helpers, then restarts SpringBoard and folds again. On EAS Simulator, an opened iPhone Duo usually needs that SpringBoard restart, which adds about a minute.
|
||||
|
||||
Each capture records what it starts on your Mac (simulators, emulators, controller daemons, tool-servers) and removes it when it ends. If a review or a local `explore:binary` run is stopped hard, the next local one stops what it left running; nothing Explore did not record is touched.
|
||||
A review's targets run at once, the targets of a platform sharing each commit's build; `--parallel N` runs at most N at a time. A device controller that stops answering on one screen costs that route: Explore restarts the app, goes on with the next route, and records what happened in `capture-diagnostics/controller-recoveries.jsonl`. A target that fails outright costs its own report; the others still open.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -444,10 +434,10 @@ jobs:
|
||||
|
||||
- Pick whatever `base` the event calls for: `main` for a release branch, yesterday's tag for a nightly, the last stable tag for a release candidate.
|
||||
- `scope` and `expires-in` are optional and override `exploration.scope` and `report.preview.expiresAfter` for that run. Without them a comparison captures what a PR review would (`scope: changes` captures only screens whose source changed), and the hosted link expires like a PR's.
|
||||
- The run summary links each target's report (**Open** and **zip**, like a PR comment) and, with hosting, the hosted report.
|
||||
- The run summary links each platform's report (**Open** and **zip**, like a PR comment) and, with hosting, the hosted report.
|
||||
- `setup --workflows` installs it from 0.19.0; `npx @expo/explore@latest setup --workflows` adds it to an existing setup. The caller grants `contents: read` and `actions: read`; `secrets: inherit` passes `EXPO_TOKEN` and any app-test secrets.
|
||||
- Call it once per workflow run. A called workflow runs inside its caller's run, so a second call in the same run would reuse the first one's artifact names; use separate workflows instead.
|
||||
- When the baseline workflow captured `base` in the last 30 days, with the same config and Explore version, that capture is reused and only `head` is captured. The report artifact is kept 30 days; only a hosted link with `expires-in: never` lasts longer.
|
||||
- When the baseline workflow captured `base` in the last 30 days, that capture is reused and only `head` is captured. The report artifact is kept 30 days; only a hosted link with `expires-in: never` lasts longer.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -475,7 +465,7 @@ If the sign-in can't be typed (one-time codes, email links, Sign in with Apple o
|
||||
| Needs data to show a screen | A test account that has it, and a hint saying where ("open the first project") |
|
||||
| Asks for a permission | Explore denies it. Allow it by hand on a session, then run `explore:session` |
|
||||
| Has a paywall | An account that already has the entitlement; purchase buttons are never tapped |
|
||||
| Has a safe button that looks destructive | `--allow-destructive "Reset filters"` |
|
||||
| Has a safe button that looks destructive | `--allow-destructive "Clear cache"` |
|
||||
| Is large | [Raise the budgets](#options) (15 minutes, 40 screens, 150 actions by default) and use `--hints` to set priorities |
|
||||
|
||||
When a run stops early, `gap:list --dir <output>` says what blocked it.
|
||||
@@ -501,7 +491,7 @@ The same link answers differently depending on who asks. It already carries the
|
||||
- Anything that does not ask for HTML (`curl`, `fetch`, agents' URL tools) gets a Markdown index of the report, also at `/llms.txt`.
|
||||
- The index links to a read-only JSON API under `/api/v1`: `/screens?status=modified,accessibility-only,added,removed`, `/screens/<id>`, `/transitions`, and `/raw` for the report file.
|
||||
- Reports without source also expose `/journeys`, `/gaps`, and `/frontier`.
|
||||
- A link to several targets takes `?target=<id>` and serves the first without it; `/reports.json` lists them (`?platform=ios|android` from older links still works). Expired links' report and API routes answer `410`.
|
||||
- Multi-platform reports take `?platform=ios|android`. Expired links answer `410`.
|
||||
|
||||
```sh
|
||||
curl -s "$LINK/api/v1/screens?status=modified" | jq '.items[] | {route, status, review}'
|
||||
@@ -514,7 +504,7 @@ curl -s "$LINK/api/v1/screens?status=modified" | jq '.items[] | {route, status,
|
||||
|
||||
1. The review workflow runs on open, non-draft PRs from the repository whose author has write access. Bots such as Devin go under `ci.trustedAuthors` in `.expo-explore/config.yaml`.
|
||||
2. Explore reads the diff and your router source to pick the affected screens.
|
||||
3. It builds both revisions on EAS (reusing a build with the same native fingerprint) and captures each screen on EAS Simulator (or, on your machine, a local simulator), reusing a baseline of the base commit when one exists. If EAS fails to start a session, Explore starts a new one, up to five times within 30 minutes.
|
||||
3. It builds both revisions and captures each screen on EAS Simulator, reusing a baseline of the base commit when one exists.
|
||||
4. It compares the captures. A screen with a source change is **Modified** if its captures differ.
|
||||
5. It uploads the report to GitHub Actions and posts a PR comment.
|
||||
|
||||
@@ -527,15 +517,13 @@ Reports and baselines are kept for 30 days and diagnostics for 7. Hosted deploym
|
||||
<details>
|
||||
<summary><strong>Known limitations</strong></summary>
|
||||
|
||||
- Android capture has had less use than iOS. The default Android device is `pixel_7`.
|
||||
- Android capture has had less use than iOS. The first Android device is `pixel_7`.
|
||||
- PRs from forks are not reviewed.
|
||||
- Each route gets one capture per appearance (`capture.appearance: auto`, the default, captures light and dark when the app's `userInterfaceStyle` is `automatic`). Other states, such as modals, are planned.
|
||||
- Each route gets one capture per appearance (light and dark with `capture.appearance: auto`). Other states, such as modals, are planned.
|
||||
- The launch is captured once per appearance and compared like any screen. The comment says how long the splash stayed as it first appeared, when it first changed (a native launch screen handing over to an app-drawn one, an animation starting on it), and when the first screen settled. `capture.launch: video` adds a recording; a launch too fast to observe is reported as "no splash observed".
|
||||
- On Android the splash usually shows only in the recording, which needs `ffmpeg`. The generated workflows install it.
|
||||
- Hosted acceptance of agent mode with an API key is incomplete.
|
||||
- With `capture.controller: argent` on an Android EAS Simulator session, each capture records one appearance (see [device controller](#controller)).
|
||||
- A local simulator runs only on your machine; the CI workflows capture on EAS Simulator.
|
||||
- `explore:session` explores EAS Simulator sessions only.
|
||||
- With `capture.controller: argent` on EAS Simulator, each capture records one appearance (see [device controller](#controller)).
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
@@ -12,11 +12,11 @@ The Viewer reads the ZIP supplied by the reviewer; it has no hosted artifact dow
|
||||
|
||||
## Hosted previews
|
||||
|
||||
Hosted previews are off by default. When `report.preview.hosting: eas` is set, the review workflow's `deploy` job uploads each run's reports (one per captured platform or target) to an [EAS Hosting](https://docs.expo.dev/eas/hosting/introduction/) deployment in your Expo account, and the comment shows an **Explore report** link that opens it directly, in place of the **Open** drop page. The GitHub artifact and **zip** stay as they are.
|
||||
Hosted previews are off by default. When `report.preview.hosting: eas` is set, the review workflow's `deploy` job uploads each run's reports (one per captured platform) to an [EAS Hosting](https://docs.expo.dev/eas/hosting/introduction/) deployment in your Expo account, and the comment shows an **Explore report** link that opens it directly, in place of the **Open** drop page. The GitHub artifact and **zip** stay as they are.
|
||||
|
||||
**What a reviewer needs.** Only the link. It looks like `https://acme-explore--k7f3z0d1q8.expo.app/p/f6r2…` and carries a 160-bit token generated for that run. It opens the Viewer and the report for one PR revision; it does not show the repository, other runs, or anything else in the Expo account.
|
||||
|
||||
**Several platforms or targets.** One deployment holds every target's report (a config without `targets` has one per platform). The link opens the first one (`?target=<id>` selects another, and `?platform=ios` or `?platform=android` from older links still works); the Viewer's menu lists the others from `/p/<token>/reports.json`, which names each target, its platform, label, device, and change count and nothing else. Every report and the listing sit behind the same token and expiry.
|
||||
**Several platforms.** One deployment holds every platform's report. The link opens the primary platform's report (`?platform=ios` or `?platform=android` selects one); the Viewer's platform menu lists the others from `/p/<token>/reports.json`, which names each platform, its device, and its change count and nothing else. Every report and the listing sit behind the same token and expiry.
|
||||
|
||||
**What is protected, and how.**
|
||||
|
||||
|
||||
@@ -105,7 +105,7 @@ device:
|
||||
exploration:
|
||||
scope: changes # changes | all
|
||||
capture:
|
||||
# controller: agent-device # agent-device (default) | argent (one appearance per capture on Android EAS Simulator until Argent can switch it; --controller overrides it for one run)
|
||||
# controller: agent-device # agent-device (default) | argent (one appearance per capture on EAS Simulator until Argent can switch it; --controller overrides it for one run)
|
||||
# simulator: eas # eas (EAS Simulator, default) | local (a simulator or emulator Explore starts on this machine with Xcode or the Android SDK; --simulator overrides it for one run)
|
||||
maxMinutes: 30
|
||||
maxActions: 500
|
||||
@@ -144,7 +144,7 @@ targets:
|
||||
android: { platform: android, device: pixel_7, bundleId: com.example.myapp, easProfile: explore-android }
|
||||
```
|
||||
|
||||
A target's id (up to 32 lowercase letters, digits and dashes, starting with a letter; not `base`, `head`, `report` or `install-…`; at most 8 per config) takes the place of the platform everywhere a capture is named: `--target duo-open`, `explore-capture-<run>-<attempt>-duo-open`, `explore-baseline-<sha>-duo-open`. `expo-explore config:targets` prints the list the workflows use as their matrix. Fields a target leaves out come from `app` and `device`; a target of another platform than `app.platform` sets its own `bundleId` and `easProfile`. A config with `platforms` has one target per platform, named `ios` and `android`, so its names do not change. `--platform` still selects a target when only one has that platform.
|
||||
A target's id (lowercase letters, digits and dashes; not `base`, `head` or `report`) takes the place of the platform everywhere a capture is named: `--target duo-open`, `explore-capture-<run>-<attempt>-duo-open`, `explore-baseline-<sha>-duo-open`. `expo-explore config:targets` prints the list the workflows use as their matrix. Fields a target leaves out come from `app` and `device`; a target of another platform than `app.platform` sets its own `bundleId` and `easProfile`. A config with `platforms` has one target per platform, named `ios` and `android`, so its names do not change. `--platform` still selects a target when only one has that platform.
|
||||
|
||||
Use the actual bundle identifier, scheme, profile, and available simulator device name. `scheme` is optional when static app configuration supplies it. `navigation.entry` resolves ambiguous entry modules; it does not list screens.
|
||||
|
||||
@@ -286,7 +286,7 @@ The provider selects the runtime that owns the navigation loop:
|
||||
| `anthropic` | Claude Code through `@anthropic-ai/claude-agent-sdk` 0.3.285 and its platform-native package | `ANTHROPIC_API_KEY` |
|
||||
| `openai` | Codex app-server from `@openai/codex` 0.159.2 and its platform-native package | `OPENAI_API_KEY` |
|
||||
|
||||
Both runtimes use Explore's device tools to operate the existing EAS Simulator through official `agent-device` 0.21.29-nightly.20261018.74. The runtime and native binaries come from the pinned tools installation. CI does not use the development-only `node_modules/.bin/claude` executable or an interactive subscription login.
|
||||
Both runtimes use Explore's device tools to operate the existing EAS Simulator through official `agent-device` 0.21.28. The runtime and native binaries come from the pinned tools installation. CI does not use the development-only `node_modules/.bin/claude` executable or an interactive subscription login.
|
||||
|
||||
Create and commit the nonempty English prose file named by `agent.instructions`. The shared setup skill authors it from source and asks for missing test data or environment inputs. Describe how to reach the app's screens, necessary prerequisites, the representative state to use on both revisions, readiness signals, and actions to avoid. This file guides the runtime agent; it is not a list of mandatory YAML steps or a second screen inventory.
|
||||
|
||||
|
||||
Generated
+35
-49
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@expo/explore",
|
||||
"version": "0.19.6",
|
||||
"version": "0.19.5",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@expo/explore",
|
||||
"version": "0.19.6",
|
||||
"version": "0.19.5",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@expo/repack-app": "0.10.1",
|
||||
@@ -29,7 +29,7 @@
|
||||
"@types/react-dom": "^19.2.4",
|
||||
"@vitejs/plugin-react": "^4.7.0",
|
||||
"@xyflow/react": "^12.11.3",
|
||||
"agent-device": "0.21.29-nightly.20261018.74",
|
||||
"agent-device": "0.21.28",
|
||||
"babel-plugin-react-compiler": "^1.0.0",
|
||||
"eslint": "^10.12.0",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
@@ -48,7 +48,7 @@
|
||||
"optionalDependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.285",
|
||||
"@openai/codex": "0.159.2",
|
||||
"eas-cli": "25.2.0"
|
||||
"eas-cli": "25.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@0no-co/graphql.web": {
|
||||
@@ -1600,15 +1600,15 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@expo/eas-build-job": {
|
||||
"version": "25.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@expo/eas-build-job/-/eas-build-job-25.2.0.tgz",
|
||||
"integrity": "sha512-RUp8sZniYWCiLQLGJrnMeAx8094BoejS6lm7EdSUs4nKkm6TtxyydRutGtoHlvBpvXOw3+OgimemqXUpmU5R8Q==",
|
||||
"version": "25.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@expo/eas-build-job/-/eas-build-job-25.0.0.tgz",
|
||||
"integrity": "sha512-Vuai42tVopKuK2KFyTWUsW9cL1YMY1dWhFAKz+evUV5AKaMCk4dYxOYZ6tBWNhIJ15bGK3p4N0YUomlAqubFWg==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"@expo/logger": "25.2.0",
|
||||
"@expo/logger": "25.0.0",
|
||||
"@expo/results": "1.0.0",
|
||||
"@expo/turtle-spawn": "25.2.0",
|
||||
"@expo/turtle-spawn": "25.0.0",
|
||||
"joi": "^17.13.1",
|
||||
"semver": "^7.6.2",
|
||||
"zod": "^4.3.5"
|
||||
@@ -1642,14 +1642,14 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@expo/eas-json": {
|
||||
"version": "25.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@expo/eas-json/-/eas-json-25.2.0.tgz",
|
||||
"integrity": "sha512-ZikfZLZHadl5gzq5UZ7qWMTWFZNAO4K6NJC6iF8JmVh3kR1Blv+Zo2AolC0CYzSYOCyaRCZx+v2ZlJZeiVCf8w==",
|
||||
"version": "25.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@expo/eas-json/-/eas-json-25.0.0.tgz",
|
||||
"integrity": "sha512-ilPw4O0Lnce/6lbu1GPwega8KF2GqTio9vuNFjNaGL78pfxz7GdktBsJ9JRaGtiM0LYdPa09W2FYb7DcMY8xWA==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "7.23.5",
|
||||
"@expo/eas-build-job": "25.2.0",
|
||||
"@expo/eas-build-job": "25.0.0",
|
||||
"chalk": "4.1.2",
|
||||
"env-string": "1.0.1",
|
||||
"fs-extra": "11.2.0",
|
||||
@@ -1836,19 +1836,6 @@
|
||||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/@expo/experimentation": {
|
||||
"version": "0.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@expo/experimentation/-/experimentation-0.0.5.tgz",
|
||||
"integrity": "sha512-eQtx5f7tUDZLeq2EXYOkBX+KivYa73CjUMkrEFh5sNMOpCWynisbdSiaSdSLHALWzYKz3uc0QlgWTz3V/6JESQ==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"nullthrows": "^1.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
}
|
||||
},
|
||||
"node_modules/@expo/image-utils": {
|
||||
"version": "0.7.6",
|
||||
"resolved": "https://registry.npmjs.org/@expo/image-utils/-/image-utils-0.7.6.tgz",
|
||||
@@ -1913,9 +1900,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@expo/logger": {
|
||||
"version": "25.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@expo/logger/-/logger-25.2.0.tgz",
|
||||
"integrity": "sha512-gtf/Lk9zE3k2wfEalAwioxDwvse69A2e/OhoDT7IRjlorRgcNJghr6V4FvDAZckQUkFR1IEHz2+FXvLKf9kjgg==",
|
||||
"version": "25.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@expo/logger/-/logger-25.0.0.tgz",
|
||||
"integrity": "sha512-KcNOYmeJH8GESYEjbiewg+LU98XH/yBs368XlPqmEHVZekkbOONpIzPd5AFcFRWO1BW0c2nl/58BUI876UFT8A==",
|
||||
"license": "BUSL-1.1",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
@@ -2605,14 +2592,14 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@expo/steps": {
|
||||
"version": "25.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@expo/steps/-/steps-25.2.0.tgz",
|
||||
"integrity": "sha512-KKM8STsb0dAdI6lyN7WHfczvDdQlCx+vF4unq/qFk6PZgZMvE9+IT8mh25fqgwxNcpR7Ti+xFCip2hhvpK2yng==",
|
||||
"version": "25.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@expo/steps/-/steps-25.0.0.tgz",
|
||||
"integrity": "sha512-+o04mm5akQJRX0j9TwwkdZiuNM9swLxw9DsDPtFhbWceg95gky/vc/0qF200kjZL4DEMfd/WhzngBW9aqJ0JQg==",
|
||||
"license": "BUSL-1.1",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"@expo/eas-build-job": "25.2.0",
|
||||
"@expo/logger": "25.2.0",
|
||||
"@expo/eas-build-job": "25.0.0",
|
||||
"@expo/logger": "25.0.0",
|
||||
"@expo/spawn-async": "^1.7.2",
|
||||
"arg": "^5.0.2",
|
||||
"fast-glob": "^3.3.2",
|
||||
@@ -2650,13 +2637,13 @@
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/@expo/turtle-spawn": {
|
||||
"version": "25.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@expo/turtle-spawn/-/turtle-spawn-25.2.0.tgz",
|
||||
"integrity": "sha512-1Lor7/+4T1JEb6kqu0dHstD+xOWTGbwA7QqWTBKYx4qtgtJ4Wbor17bzlp87KENAYDeWuX+7VHKxT66170m9wg==",
|
||||
"version": "25.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@expo/turtle-spawn/-/turtle-spawn-25.0.0.tgz",
|
||||
"integrity": "sha512-XBQZ2azxh0IWozO5hCxIJt150LjIGbk6VZakeyA6UXPHp1ESenm97o0JIHOvzQNOgBV481muV88KmIWHGt0yIA==",
|
||||
"license": "BUSL-1.1",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"@expo/logger": "25.2.0",
|
||||
"@expo/logger": "25.0.0",
|
||||
"@expo/spawn-async": "^1.7.2"
|
||||
}
|
||||
},
|
||||
@@ -4593,9 +4580,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/agent-device": {
|
||||
"version": "0.21.29-nightly.20261018.74",
|
||||
"resolved": "https://registry.npmjs.org/agent-device/-/agent-device-0.21.29-nightly.20261018.74.tgz",
|
||||
"integrity": "sha512-7+ajWLr0J+8iLZ9q11ERbj6U14mC20umBK5BQQdw5aERA79yeXc3Ze6KmtvnILnWjEtoVkYQsXQasL8RL6Uatw==",
|
||||
"version": "0.21.28",
|
||||
"resolved": "https://registry.npmjs.org/agent-device/-/agent-device-0.21.28.tgz",
|
||||
"integrity": "sha512-uGEENVhPzSpIACrVlt16O1mloODWJyAemTCT0boDb4L006JXN2rG747u1TRoQJudOpdP/Pm2urxNRHeECLMLfg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
@@ -5735,9 +5722,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/eas-cli": {
|
||||
"version": "25.2.0",
|
||||
"resolved": "https://registry.npmjs.org/eas-cli/-/eas-cli-25.2.0.tgz",
|
||||
"integrity": "sha512-FFA6fSl2bPet9D3Eslupig3icXjyBzAbrsLE5r67wbEbh/CPDZQ+Q4W5TrpRui0uqfF16w58EGsFUQoQ0te0KQ==",
|
||||
"version": "25.0.0",
|
||||
"resolved": "https://registry.npmjs.org/eas-cli/-/eas-cli-25.0.0.tgz",
|
||||
"integrity": "sha512-FBY3pIo/3L0s+8KK5ZpMKzlLrA5jOmr5kOpoOwkAXsxMrI4vo+LNoEsciRcOxjce9efc08GqEEPc/CxLRAWIvA==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
@@ -5745,12 +5732,11 @@
|
||||
"@expo/code-signing-certificates": "0.0.5",
|
||||
"@expo/config": "55.0.10",
|
||||
"@expo/config-plugins": "55.0.7",
|
||||
"@expo/eas-build-job": "25.2.0",
|
||||
"@expo/eas-json": "25.2.0",
|
||||
"@expo/eas-build-job": "25.0.0",
|
||||
"@expo/eas-json": "25.0.0",
|
||||
"@expo/env": "^1.0.0",
|
||||
"@expo/experimentation": "0.0.5",
|
||||
"@expo/json-file": "8.3.3",
|
||||
"@expo/logger": "25.2.0",
|
||||
"@expo/logger": "25.0.0",
|
||||
"@expo/multipart-body-parser": "2.0.0",
|
||||
"@expo/osascript": "2.1.4",
|
||||
"@expo/package-manager": "1.9.10",
|
||||
@@ -5762,7 +5748,7 @@
|
||||
"@expo/results": "1.0.0",
|
||||
"@expo/rudder-sdk-node": "1.1.1",
|
||||
"@expo/spawn-async": "1.7.2",
|
||||
"@expo/steps": "25.2.0",
|
||||
"@expo/steps": "25.0.0",
|
||||
"@expo/timeago.js": "1.0.0",
|
||||
"@oclif/core": "^4.8.3",
|
||||
"@oclif/plugin-autocomplete": "^3.2.40",
|
||||
|
||||
+3
-3
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/explore",
|
||||
"version": "0.19.6",
|
||||
"version": "0.19.5",
|
||||
"description": "Source-driven mobile app maps, deterministic CI capture, and visual reviews",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
@@ -73,7 +73,7 @@
|
||||
"optionalDependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.285",
|
||||
"@openai/codex": "0.159.2",
|
||||
"eas-cli": "25.2.0"
|
||||
"eas-cli": "25.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@anthropic-ai/claude-code": "2.1.285",
|
||||
@@ -83,7 +83,7 @@
|
||||
"@types/react-dom": "^19.2.4",
|
||||
"@vitejs/plugin-react": "^4.7.0",
|
||||
"@xyflow/react": "^12.11.3",
|
||||
"agent-device": "0.21.29-nightly.20261018.74",
|
||||
"agent-device": "0.21.28",
|
||||
"babel-plugin-react-compiler": "^1.0.0",
|
||||
"eslint": "^10.12.0",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: explore-binary
|
||||
description: Explore a prebuilt mobile app archive (Android .apk, iOS simulator .app, .tar.gz, or simulator .ipa) with Expo Explore. Runs `expo-explore explore:binary`, which installs the archive in a fresh EAS Simulator session (or, with `--simulator local`, on a simulator or emulator it starts on this Mac, with no EAS login), drives it with the local claude or codex login, writes an exploration map and report, and hosts the report on EAS Hosting or opens it in the local Viewer. Use when asked to "run @expo/explore for some.app/.apk", to map or smoke-test an app you only have as a build, or to get screenshots of every screen of a binary. `expo-explore explore:session` does the exploration half alone against an EAS Simulator session you already started (app already installed; result opens in the local Viewer). Also explores an Expo project from its source with no new build: its development build (or Expo Go) on an EAS Simulator, loading JavaScript from a tunneled local dev server. Not for device .ipa files.
|
||||
description: Explore a prebuilt mobile app archive (Android .apk, iOS simulator .app, .tar.gz, or simulator .ipa) with Expo Explore. Runs `expo-explore explore:binary`, which installs the archive in a fresh EAS Simulator session, drives it with the local claude or codex login, writes an exploration map and report, hosts the report on EAS Hosting, and prints the link. Use when asked to "run @expo/explore for some.app/.apk", to map or smoke-test an app you only have as a build, or to get screenshots of every screen of a binary. `expo-explore explore:session` does the exploration half alone against an EAS Simulator session you already started (app already installed; result opens in the local Viewer). Also explores an Expo project from its source with no new build: its development build (or Expo Go) on an EAS Simulator, loading JavaScript from a tunneled local dev server. Not for device .ipa files.
|
||||
---
|
||||
|
||||
# Explore a prebuilt app
|
||||
@@ -11,25 +11,25 @@ One command, run from any directory:
|
||||
npx @expo/explore explore:binary ./path/to/app.apk --json
|
||||
```
|
||||
|
||||
Accepted inputs: Android `.apk`; iOS simulator builds as a `.app` directory, a `.tar.gz`/`.tgz` of one, or an `.ipa` that contains a simulator build. An iOS device `.ipa` and an Android `.aab` are rejected before any device starts (`ARCHIVE_NOT_SIMULATOR`, `ARCHIVE_AAB_UNSUPPORTED`); ask for a simulator build or a universal APK instead.
|
||||
Accepted inputs: Android `.apk`; iOS simulator builds as a `.app` directory, a `.tar.gz`/`.tgz` of one, or an `.ipa` that contains a simulator build. An iOS device `.ipa` and an Android `.aab` are rejected before any session starts (`ARCHIVE_NOT_SIMULATOR`, `ARCHIVE_AAB_UNSUPPORTED`); ask for a simulator build or a universal/x86_64 APK instead.
|
||||
|
||||
Platform, bundle id, app name and version are read from the archive; do not pass them unless Explore asks.
|
||||
|
||||
## Before running
|
||||
|
||||
- Where it runs. By default on EAS Simulator, which needs an EAS login: `eas whoami` succeeds, or `EXPO_TOKEN` is set. The session and the hosted report live under that account (`--owner` picks one when the login has several, `--project` renames the default `expo-explore` project). Without EAS Simulator access, or without an Expo account, pass `--simulator local`: Explore creates a simulator (iOS, needs Xcode) or an emulator (Android, needs the Android SDK with platform-tools, cmdline-tools, the emulator and a system image for this Mac, and `ANDROID_HOME`) and removes it afterwards. An APK must then ship native libraries for this Mac's ABI (`arm64-v8a` on Apple silicon); a universal one does.
|
||||
- EAS login: `eas whoami` succeeds, or `EXPO_TOKEN` is set. The session and the hosted report live under that account (`--owner` picks one when the login has several, `--project` renames the default `expo-explore` project).
|
||||
- A model: Explore tries `ANTHROPIC_API_KEY` / `OPENAI_API_KEY` when set, then the local `claude` login (Claude Code), then the local `codex` login, and uses the first that passes a preflight request. `--provider` or `--model` limits it to that one choice. If none passes, the run stops before a simulator is started.
|
||||
- Node 24.12 or newer.
|
||||
|
||||
## What happens
|
||||
|
||||
1. Archive inspection and compatibility checks (size, simulator build, emulator ABI, sha256).
|
||||
2. `eas simulator:start` of an empty agent-device session (an `argent` one with `--controller argent`), verified by exact session id before use. With `--simulator local`: a new simulator or emulator on this Mac instead, with the app's URL schemes approved so its links open without a prompt.
|
||||
3. `agent-device install` of the archive straight into the session (Argent: `reinstall-app`; locally `simctl install` or `adb install`), then `open <bundle id>`.
|
||||
2. `eas simulator:start` of an empty agent-device session (an `argent` one with `--controller argent`), verified by exact session id before use.
|
||||
3. `agent-device install` of the archive straight into the session (Argent: `reinstall-app`), then `open <bundle id>`.
|
||||
4. The model explores through a small tool set (observe, act, capture, finish); app text is treated as untrusted and destructive controls (delete, reset, sign out, purchase, send, share) are blocked outside the model.
|
||||
5. The map and screenshots are written under `--output` (default `./explore-<archive>-<timestamp>`), plus `report/` for the Viewer.
|
||||
6. The report is sealed and deployed to EAS Hosting (`--no-upload` skips this; `--expires-in 7d|30d|never`). With `--simulator local` it opens in the local Viewer instead, which keeps running until stopped; `--json` and `--no-open` skip it, so with `--json` open it afterwards with `view --dir <output>` (in the background, since it serves until stopped). `--upload` hosts it, and that needs an EAS login.
|
||||
7. The exact session is stopped, or the local device deleted; a failure to stop reports `SESSION_CLEANUP_FAILED` with the command to stop it by hand. A local device a hard-stopped run left behind is removed by the next local run.
|
||||
6. The report is sealed and deployed to EAS Hosting (`--no-upload` skips this; `--expires-in 7d|30d|never`).
|
||||
7. The exact session is stopped; a failure to stop reports `SESSION_CLEANUP_FAILED` with the id to stop by hand.
|
||||
|
||||
Budgets default to 15 minutes, 40 screens, 150 actions (`--max-duration-minutes`, `--max-screens`, `--max-actions`). Steer the model with `--hints "focus on the onboarding and settings"`, skip onboarding with `--launch-url myapp://home`, and allow a specific risky control with `--allow-destructive "Clear cache"`.
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ description: Set up Expo Explore CI reviews in deterministic or agent mode. Star
|
||||
|
||||
# Set up Expo Explore
|
||||
|
||||
Make the app ready for CI capture in the user's chosen mode, using its real configuration and source. This is the shared **local authoring skill** for both modes.
|
||||
Make the app ready for CI capture in the user's chosen mode, using its real configuration and source. This is the shared **local authoring skill** for both modes. Android capture is not available yet.
|
||||
|
||||
Explore's tools are app-agnostic: `expo-explore setup` and `expo-explore doctor` know routes, parameters, links and source redirects, but not what the app means by them. **Your job is the app-specific part**: read this app's source to learn which flows (sign-in, onboarding, a subscription, a feature flag, a permission, a record that must exist, …) each screen needs, and write that into this app's `config.yaml` or instructions. Look for what the app actually has; do not assume the flows of another app, and do not impose an account or persona schema.
|
||||
|
||||
@@ -164,12 +164,11 @@ npx @expo/explore capture --base v1.3.0 --head v1.4.0 --scope all
|
||||
- It runs both commits' code as the user (dependency installs, the app config, bundling). Before reviewing a branch the user did not write, say so and ask; credential-free installs are not a sandbox.
|
||||
- Logins: `EXPO_TOKEN` and the provider's API key when they are set; otherwise the user's `eas login` and their local `claude` or `codex` login for the configured provider. If `eas whoami` fails, tell them to run `eas login`.
|
||||
- Without `--head`, the head is HEAD plus the working tree's changes, untracked non-ignored files included, which is what `eas build` uploads. It lists them; check that list for secrets the user would not want built. `--committed` reviews HEAD alone, and an `eas.json` with `cli.requireCommit: true` leaves the changes out unless `--uncommitted` is passed.
|
||||
- Every configured platform or target is reviewed, at once, unless `--target` or `--platform` picks some (`--parallel N` caps how many run together). It opens the report in a local Viewer; `--upload` hosts it instead and prints the link, `--no-open` or `--json` only prints the report paths.
|
||||
- Without EAS Simulator access, add `--simulator local` (or `capture.simulator: local`): each commit is captured on a simulator Explore creates on this Mac (Xcode) or an emulator (Android SDK), and the app is repacked there too. The native build still comes from EAS. `npx @expo/explore doctor --simulator local` checks that this machine can start each device.
|
||||
- Every configured platform is reviewed unless `--platform` picks one. It opens the report in a local Viewer; `--upload` hosts it instead and prints the link, `--no-open` or `--json` only prints the report paths.
|
||||
- Every run is kept on this machine for 30 days: `npx @expo/explore reports list` (or `--json`) shows them, `reports open <id|latest>` reopens one in the local Viewer, and `reports upload <id>` hosts it without capturing again. Run bare in a terminal, `reports` is an arrow-key picker for the user.
|
||||
- To host a report after the fact, run `npx @expo/explore report:upload <report.zip>...` with the paths it printed (or the `--output` directory's `<target>/report.zip`), one per platform or target. It uses the same project as `--upload` and does not capture again.
|
||||
- Captures are cached in `~/.cache/expo-explore`, so a second review of the same base does not capture it again (`--no-cache` skips the cache). Ctrl+C stops the simulator sessions and local devices the review started; after a harder stop, the next local review stops what was left running.
|
||||
- It builds on EAS and, unless it captures locally, runs EAS Simulator sessions, like a CI review: expect several minutes and EAS usage per run.
|
||||
- To host a report after the fact, run `npx @expo/explore report:upload <report.zip>...` with the paths it printed (or the `--output` directory's `<platform>/report.zip`), one per platform. It uses the same project as `--upload` and does not capture again.
|
||||
- Captures are cached in `~/.cache/expo-explore`, so a second review of the same base does not capture it again (`--no-cache` skips the cache). Ctrl+C stops the EAS Simulator sessions the review started.
|
||||
- It builds on EAS and runs simulator sessions, like a CI review: expect several minutes and EAS usage per run.
|
||||
|
||||
## Compare any two commits
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
name: readme-refresh
|
||||
description: Refresh Expo Explore's README.md with euxy (github.com/brentvatne/euxy) as the reference app. Regenerate every screenshot in docs/screenshots from a current euxy review report and PR comment, then re-read the README as a first-time user: the top level only says what Explore does, links the live euxy example, gives one quick-start prompt to copy that reviews a change to your own app or explores a build you point it to, and one for setting up CI; everything else lives in collapsibles. Use after a Viewer or PR-comment change that the README shows, a new command or setting, or a release that made a README claim stale. Not for the docs/ guides or the shipped skills.
|
||||
description: Refresh Expo Explore's README.md with euxy (github.com/brentvatne/euxy) as the reference app. Regenerate every screenshot in docs/screenshots from a current euxy review report and PR comment, then re-read the README as a first-time user: the top level only says what Explore does, links the live euxy example, gives numbered quick-start steps for reviewing a change to your own app, a prompt to copy for exploring any build, and one for setting up CI; everything else lives in collapsibles. Use after a Viewer or PR-comment change that the README shows, a new command or setting, or a release that made a README claim stale. Not for the docs/ guides or the shipped skills.
|
||||
---
|
||||
|
||||
# Refresh the README
|
||||
@@ -60,8 +60,8 @@ Look at every PNG you produced before committing, light and dark: the selected s
|
||||
Read the README top to bottom once without opening a collapsible. At that level it may only answer, in this order:
|
||||
|
||||
1. What Explore is (one short paragraph), the hero image, and the link to the live euxy example (`explore-example--euxy.expo.app`, redeployed on every merge to main by `.github/workflows/example-report.yml`). Under it, one table row of three pictures with a one-line caption each: Compare, Screens, and the PR comment (which says it needs CI), then the agent prompt collapsed as **Ask an agent about a report**. The hero is a zoomed Map framed as a window on a stage (`stagedWindow` in the script); the three below are plain.
|
||||
2. **Quick start**: one path. A single prompt to paste into Claude Code or Codex that reviews a change to the reader's own Expo app through the explore-setup skill's "Review a change on this machine" section, or, when they point it to a build (or the app is not an Expo project), explores a simulator build through the explore-binary skill. Then one sentence on what each case needs (a review needs an Expo account, is built on EAS, and is captured on EAS Simulator or a local simulator; exploring a build needs a Claude Code or Codex login and EAS Simulator or a local simulator, and no Expo account locally). Then one **Run it yourself** collapsible with both by hand: the numbered steps for a review, with nothing optional in them (make the app buildable on EAS: login, init, bundle identifier, a simulator profile named `explore`, and commit, since the before build is the last commit; then edit a screen near its top and run `capture`, or `capture --simulator local`), and the `explore:binary` commands, including `--simulator local`. Then the `reports` picker image (`readme-reports-*.png`) with one sentence on saved runs, at the top level, and one collapsible for other commits (`--committed`, `--base`/`--head`) and what a review does on the machine. Run the steps on a fresh `create-expo-app` before changing them.
|
||||
3. **Map every screen of any app**: one sentence on what exploring a build shows (pointing back to the quick start, which runs it), then its collapsibles: its options, exploring a session already started, and what a run without source shows.
|
||||
2. **Quick start**: the smallest set of steps to see a review of the reader's own Expo app on their machine, numbered and with nothing optional in them: make the app buildable on EAS (login, init, bundle identifier, a simulator profile named `explore`) and commit (the before build is the last commit), then edit a screen near its top and run `capture`, which reviews uncommitted changes as `eas build` would upload them and uses setup's defaults when there is no config. After the steps, a prompt that has Claude Code or Codex do the same through the explore-setup skill's "Review a change on this machine" section. Then the `reports` picker image (`readme-reports-*.png`) with one sentence on saved runs, at the top level, and one collapsible for other commits (`--committed`, `--base`/`--head`) and what a review does on the machine. Run the steps on a fresh `create-expo-app` before changing them.
|
||||
3. **Map every screen of any app**: one sentence and a prompt to paste into Claude Code or Codex that gets a simulator build of any app (Expo or not, or just a build) and runs `explore:binary` on it. Each section keeps its own "Run it yourself"; never put one section between another's prompt and its collapsibles.
|
||||
4. **Set up CI**: one sentence, then two subsections, each a sentence on what it gives and a prompt to paste: **Review on every PR** (the setup prompt, then a few grouped collapsibles: Hosted previews first, then Manual setup (the setup prompt's steps done by hand, in order: setup, doctor, secrets, baseline, first PR), Capture modes: deterministic or agent, iOS, Android, or both, Keep your setup current) and **Compare any two commits** (a prompt that follows the explore-setup skill's "Compare any two commits" section, the ways to snapshot a release as bullets, then the comparison workflow collapsed).
|
||||
|
||||
Lead with prompts, not explanations: a reader should be able to copy something and see Explore work. Everything else, the manual commands, requirements, options, the manual setup, capture modes, hosted previews, iOS and Android, agent mode, repository settings, how agents read a report, how it works, limitations, contributing, goes into a `<details>` block under the section it belongs to, with a `<summary>` that says what the reader will find. Keep bullets to one or two sentences. Group related collapsibles rather than adding one per topic, so a section shows a handful, not nine. Requirements sit collapsed right under the example report link. Keep the collapsibles' `id` attributes that other docs link to (`#hosted-previews`, `#platforms`, `#compare`, `#agents`); the Terms and How agents read a report collapsibles live under Additional information, and keep the Inspiration section (screenmap and Revyl's Atlas).
|
||||
|
||||
@@ -164,13 +164,10 @@ export async function readArchiveIcon(archive: InspectedArchive): Promise<Buffer
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Explore's EAS Android emulator is x86_64 with no 32-bit support, and a local one runs this Mac's ABI; an APK that
|
||||
* ships native libraries only for other ABIs fails to install there.
|
||||
*/
|
||||
/** Explore's EAS Android emulator is x86_64 with no 32-bit support; an APK that ships only ARM or x86 libraries fails to install there. */
|
||||
export function assertEmulatorCompatible(archive: InspectedArchive, emulatorAbis: readonly string[] = ["x86_64"]): void {
|
||||
if (archive.platform === "ios") {
|
||||
if (!archive.simulator) throw archiveError("ARCHIVE_NOT_SIMULATOR", `${basename(archive.path)} is an iOS device build; it cannot run on a simulator.`,
|
||||
if (!archive.simulator) throw archiveError("ARCHIVE_NOT_SIMULATOR", `${basename(archive.path)} is an iOS device build; it cannot run on the EAS Simulator.`,
|
||||
"Build for the simulator (an EAS profile with ios.simulator: true) and pass that .app, .tar.gz, or simulator .ipa.");
|
||||
return;
|
||||
}
|
||||
@@ -180,7 +177,7 @@ export function assertEmulatorCompatible(archive: InspectedArchive, emulatorAbis
|
||||
}
|
||||
if (archive.abis.length && !archive.abis.some(abi => emulatorAbis.includes(abi))) {
|
||||
throw archiveError("ARCHIVE_ABI_UNSUPPORTED", `The APK ships native libraries only for ${archive.abis.join(", ")}; the emulator needs ${emulatorAbis.join(" or ")}.`,
|
||||
`Build a universal APK or one that includes ${emulatorAbis[0]} native libraries.`, { abis: archive.abis, emulatorAbis: [...emulatorAbis] });
|
||||
"Build a universal APK or one that includes x86_64 native libraries.", { abis: archive.abis, emulatorAbis: [...emulatorAbis] });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+76
-185
@@ -1,4 +1,5 @@
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { createRequire } from "node:module";
|
||||
import { lstat, mkdir, mkdtemp, readFile, realpath, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
@@ -12,18 +13,14 @@ import { executeCaptureSetup } from "../capture/setup-actions.js";
|
||||
import { SIMULATOR_DOTENV_FILE_NAME, SIMULATOR_DOTENV_HEADER, assertSimulatorSessionIdentity, assertSimulatorStopped, readSimulatorDotenvHandoff,
|
||||
assertAttachedSimulatorSession, connectionController, controllerVersion, resolveAttachedSimulatorSession, simulatorOsVersion, simulatorStartFailure, type ActiveSimulatorRuntime, type SimulatorConnection } from "../capture/simulator.js";
|
||||
import { argentControllerInvocation } from "../capture/controller-invocation.js";
|
||||
import { agentDeviceLauncher, ensureArgentToolServer, ensureController } from "../shared/controller-cache.js";
|
||||
import { agentDeviceClaims, approveLinkScheme, createLocalSimulator, deleteLocalEmulator, deleteLocalSimulator, hostEmulatorAbi, installOnLocalEmulator, installOnLocalSimulator, startLocalArgentServer,
|
||||
startLocalEmulator, stopLocalAgentDevice, stopLocalArgentServer, waitForLocalEmulator, waitForLocalSimulator, type LocalArgentServer } from "../capture/local-simulator.js";
|
||||
import { openLocalCaptureRecord, sweepLocalCaptures } from "../capture/local-registry.js";
|
||||
import { approveSessionUrlSchemes, simulatorControlActions, type EasCommand } from "../capture/simulator-control.js";
|
||||
import { agentDeviceLauncher, ensureController } from "../shared/controller-cache.js";
|
||||
import { DEFAULT_ANDROID_DEVICE } from "../config/explore-config.js";
|
||||
import { createExplorationInputs } from "../config/exploration-inputs.js";
|
||||
import { ExploreStore, getCoverage } from "../map/store.js";
|
||||
import { whoamiAccounts } from "../report/preview-deploy.js";
|
||||
import { CiError, serializeCiError, toCiError } from "../shared/ci-errors.js";
|
||||
import { packageBin } from "../shared/package-paths.js";
|
||||
import { assertDecodedPng, solidColour } from "../shared/png-evidence.js";
|
||||
import { assertDecodedPng, type DecodedFrame } from "../shared/png-evidence.js";
|
||||
import { CONTRACT, type ExploreMap, type Platform } from "../types.js";
|
||||
import { assertEmulatorCompatible, extractIosBundle, inspectArchive, type ArchiveKind, type InspectedArchive, readArchiveIcon } from "./archive.js";
|
||||
import { runBlackBoxExploration, type BlackBoxExplorerResult, type BlackBoxFrame, SYSTEM_DIALOG_PACKAGES } from "./explorer.js";
|
||||
@@ -53,8 +50,6 @@ export type BinaryExploreOptions = {
|
||||
project?: string;
|
||||
/** The session's device controller; agent-device unless Argent is chosen. explore:session takes it from the session. */
|
||||
controller?: "agent-device" | "argent";
|
||||
/** Where the app runs: an EAS Simulator session (the default), or a simulator or emulator this run starts on this machine, with no EAS login. */
|
||||
simulator?: "eas" | "local";
|
||||
environment?: NodeJS.ProcessEnv;
|
||||
runner?: typeof defaultRunner;
|
||||
createSession?: (config: CiAgentSessionConfig, options: { env: NodeJS.ProcessEnv; auth: ModelAuth }) => CiAgentSession;
|
||||
@@ -76,8 +71,8 @@ export type BinaryExploreResult = {
|
||||
/** The command and environment that reach a session's controller: agent-device's CLI with its daemon, or the Argent bridge. */
|
||||
type ControllerInvocation = { command: string; environment: NodeJS.ProcessEnv };
|
||||
|
||||
async function argentInvocation(connection: SimulatorConnection, work: string, platform: Platform, environment: NodeJS.ProcessEnv, bundleId?: string, device?: string): Promise<ControllerInvocation> {
|
||||
return argentControllerInvocation({ directory: work, connection, platform, environment: baseEnvironment(environment), sourceEnvironment: environment, ...(bundleId ? { bundleId } : {}), ...(device ? { device } : {}) });
|
||||
async function argentInvocation(connection: SimulatorConnection, work: string, platform: Platform, environment: NodeJS.ProcessEnv, bundleId?: string): Promise<ControllerInvocation> {
|
||||
return argentControllerInvocation({ directory: work, connection, platform, environment: baseEnvironment(environment), sourceEnvironment: environment, ...(bundleId ? { bundleId } : {}) });
|
||||
}
|
||||
|
||||
/** The daemon refuses a second session on a busy device; the caller's own `agent-device` session (from install/open) is reused instead. */
|
||||
@@ -272,18 +267,11 @@ export type ConnectedSessionExploration = {
|
||||
urlSchemes?: readonly string[];
|
||||
/** The app's icon from the archive for the Viewer header. */
|
||||
appIcon?: Buffer;
|
||||
/**
|
||||
* A simulator or emulator on this machine instead of an EAS session: the controller drives it by its UDID or adb
|
||||
* serial (agent-device with a daemon of its own in `stateDirectory`, or a local Argent tool-server pinned to it).
|
||||
*/
|
||||
local?: { deviceId: string; osVersion: string; stateDirectory: string };
|
||||
/** Runs once the app is installed and before anything opens it, as an EAS session's link approval must. */
|
||||
afterInstall?: () => void;
|
||||
};
|
||||
|
||||
/** Drives an agent-device daemon we already hold a connection to: optional install, open, then the model-led exploration. */
|
||||
export async function exploreConnectedSession(ctx: ConnectedSessionExploration): Promise<{ runtime: ActiveSimulatorRuntime; exploration: BlackBoxExplorerResult }> {
|
||||
const { connection, platform, device, bundleId, app, install, work, runner, environment, secrets, inputs, say, now, limits, store, map, model, sessionJson, launchUrl, hints, allowDestructive, local } = ctx;
|
||||
const { connection, platform, device, bundleId, app, install, work, runner, environment, secrets, inputs, say, now, limits, store, map, model, sessionJson, launchUrl, hints, allowDestructive } = ctx;
|
||||
const controllerSession = ctx.controllerSession ?? CONTROLLER_SESSION;
|
||||
const controllerKind = connectionController(connection);
|
||||
const controllerName = controllerKind === "argent" ? "Argent" : "agent-device";
|
||||
@@ -291,18 +279,15 @@ export async function exploreConnectedSession(ctx: ConnectedSessionExploration):
|
||||
let agentDevice: string;
|
||||
let controllerEnvironment: NodeJS.ProcessEnv;
|
||||
if (controllerKind === "argent") {
|
||||
({ command: agentDevice, environment: controllerEnvironment } = await argentInvocation(connection, work, platform, environment, bundleId, local?.deviceId));
|
||||
({ command: agentDevice, environment: controllerEnvironment } = await argentInvocation(connection, work, platform, environment, bundleId));
|
||||
} else {
|
||||
const controllerConfig = join(work, "agent-device.json");
|
||||
await writeFile(controllerConfig, "{}\n", { flag: "wx", mode: 0o400 });
|
||||
// A local device has no EAS daemon: agent-device runs its own, in a state directory of this run's.
|
||||
controllerEnvironment = { ...baseEnvironment(environment), AGENT_DEVICE_CONFIG: controllerConfig,
|
||||
...(local ? { AGENT_DEVICE_STATE_DIR: local.stateDirectory } : { AGENT_DEVICE_DAEMON_BASE_URL: connection.daemonBaseUrl, AGENT_DEVICE_DAEMON_AUTH_TOKEN: connection.daemonAuthToken }),
|
||||
AGENT_DEVICE_SESSION: controllerSession, AGENT_DEVICE_SESSION_LOCK: "reject", AGENT_DEVICE_PLATFORM: platform };
|
||||
controllerEnvironment = { ...baseEnvironment(environment), AGENT_DEVICE_CONFIG: controllerConfig, AGENT_DEVICE_DAEMON_BASE_URL: connection.daemonBaseUrl,
|
||||
AGENT_DEVICE_DAEMON_AUTH_TOKEN: connection.daemonAuthToken, AGENT_DEVICE_SESSION: controllerSession, AGENT_DEVICE_SESSION_LOCK: "reject", AGENT_DEVICE_PLATFORM: platform };
|
||||
agentDevice = agentDeviceLauncher(environment);
|
||||
}
|
||||
// A local device is named for Explore, so it is picked by its UDID or serial rather than its model name.
|
||||
const deviceArgs = local ? [platform === "ios" ? "--udid" : "--serial", local.deviceId] : platform === "ios" ? ["--device", device] : [];
|
||||
const deviceArgs = platform === "ios" ? ["--device", device] : [];
|
||||
const controller = (args: string[], timeoutMs = 90_000): CommandResult => {
|
||||
// Session flags go before a `--` separator so model-chosen text (`type -h`, a URL, a label) is never read as a flag.
|
||||
const separator = args.indexOf("--");
|
||||
@@ -319,18 +304,16 @@ export async function exploreConnectedSession(ctx: ConnectedSessionExploration):
|
||||
try { controller(["install", install.path, "--json"], 15 * 60_000); }
|
||||
catch (error) { throw binaryError("APP_INSTALL_FAILED", `${controllerName} could not install the app: ${failureText(error)}`, "Check that the archive is a simulator build for this platform and under the size limit, then rerun.", { sessionId: connection.sessionId }); }
|
||||
}
|
||||
ctx.afterInstall?.();
|
||||
// On a local device, the first open also builds agent-device's iOS runner.
|
||||
const opened = controller(["open", bundleId, "--level", "full", "--json"], local ? 15 * 60_000 : 2 * 60_000);
|
||||
const opened = controller(["open", bundleId, "--level", "full", "--json"], 2 * 60_000);
|
||||
const openedDevice = openedSimulatorDevice(opened.stdout, bundleId, "initial app open", platform, controllerSession);
|
||||
const data = controllerData(opened.stdout, "initial app open");
|
||||
const deviceData = data.device && typeof data.device === "object" ? data.device as Record<string, unknown> : {};
|
||||
const observed = (key: string): string => { const value = deviceData[key] ?? data[key]; return typeof value === "string" && value.trim() ? value : "unknown"; };
|
||||
const runtime = { provider: local ? "local-simulator" : "eas-simulator", controller: controllerKind, controllerPackageVersion: controllerVersion(controllerKind), easCliVersion: "unknown", platform, controllerDeviceId: openedDevice.deviceId,
|
||||
deviceModel: local ? device : openedDevice.deviceModel, osVersion: local ? local.osVersion : observed("osVersion"), locale: observed("locale"), orientation: observed("orientation") === "landscape" ? "landscape" : "portrait",
|
||||
const runtime = { provider: "eas-simulator", controller: controllerKind, controllerPackageVersion: controllerVersion(controllerKind), easCliVersion: "unknown", platform, controllerDeviceId: openedDevice.deviceId,
|
||||
deviceModel: openedDevice.deviceModel, osVersion: observed("osVersion"), locale: observed("locale"), orientation: observed("orientation") === "landscape" ? "landscape" : "portrait",
|
||||
colorScheme: observed("colorScheme") === "dark" ? "dark" : "light" } as ActiveSimulatorRuntime;
|
||||
// Argent's `open` reports the OS version itself (list-devices); agent-device's comes from the session's preview.
|
||||
if (!local && (runtime.osVersion === "unknown" || controllerKind !== "argent")) try { runtime.osVersion = await simulatorOsVersion(sessionJson(), runtime.controllerDeviceId, fetch, platform); } catch { /* descriptive only */ }
|
||||
if (runtime.osVersion === "unknown" || controllerKind !== "argent") try { runtime.osVersion = await simulatorOsVersion(sessionJson(), runtime.controllerDeviceId, fetch, platform); } catch { /* descriptive only */ }
|
||||
map.run.deviceId = runtime.controllerDeviceId;
|
||||
map.run.environment = { deviceModel: runtime.deviceModel, osVersion: runtime.osVersion, locale: runtime.locale, orientation: runtime.orientation, colorScheme: runtime.colorScheme };
|
||||
map.run.status = "exploring";
|
||||
@@ -589,75 +572,6 @@ export async function runSessionExploration(options: SessionExploreOptions): Pro
|
||||
}
|
||||
}
|
||||
|
||||
type LocalDevice = NonNullable<ConnectedSessionExploration["local"]>;
|
||||
|
||||
/**
|
||||
* Starts a simulator or emulator on this machine for one run, installs the app, and hands the explorer a connection
|
||||
* to it; everything is stopped afterwards. They are the devices `capture --simulator local` starts, recorded the same
|
||||
* way, so the next local run stops what a run stopped hard left behind.
|
||||
*/
|
||||
async function withLocalDevice(options: { archive: InspectedArchive; installPath: string; platform: Platform; device: string; bundleId: string;
|
||||
controller: "agent-device" | "argent"; tag: string; work: string; runner: typeof defaultRunner; environment: NodeJS.ProcessEnv; secrets: readonly string[]; say: (message: string) => void; now?: () => number },
|
||||
explore: (connection: SimulatorConnection, local: LocalDevice) => Promise<void>): Promise<void> {
|
||||
const { archive, installPath, platform, device, bundleId, controller, tag, work, runner, say } = options;
|
||||
const environment = baseEnvironment(options.environment);
|
||||
const agentDevice = agentDeviceLauncher(options.environment);
|
||||
const stateDirectory = join(work, "agent-device-state");
|
||||
const record = await openLocalCaptureRecord(options.environment, work);
|
||||
let udid: string | undefined, serial: string | undefined, argent: LocalArgentServer | undefined;
|
||||
let primaryError: unknown;
|
||||
try {
|
||||
let osVersion: string;
|
||||
if (platform === "ios") {
|
||||
say(`starting a local ${device} simulator`);
|
||||
const created = await createLocalSimulator({ runner, device, name: `Explore ${device} (binary ${tag})`, cwd: work, environment,
|
||||
created: async id => { udid = id; await record.update({ udid: id }); } });
|
||||
osVersion = created.osVersion;
|
||||
waitForLocalSimulator({ runner, udid: created.udid, cwd: work, environment });
|
||||
// Links in the app's own schemes open without iOS asking first.
|
||||
for (const scheme of archive.urlSchemes) approveLinkScheme({ runner, udid: created.udid, scheme, bundleId, cwd: work, environment });
|
||||
say("installing the app");
|
||||
installOnLocalSimulator({ runner, udid: created.udid, app: installPath, cwd: work, environment });
|
||||
} else {
|
||||
say(`starting a local ${device} emulator`);
|
||||
const name = `explore-binary-${tag}`;
|
||||
const started = await startLocalEmulator({ runner, device, name, directory: work, cwd: work, environment,
|
||||
...(controller === "agent-device" ? { claimed: (candidate: string) => agentDeviceClaims({ runner, agentDevice, serial: candidate, cwd: work, environment }) } : {}),
|
||||
started: async id => { serial = id; await record.update({ serial: id, avd: name }); } });
|
||||
osVersion = waitForLocalEmulator({ runner, serial: started.serial, device, apiLevel: started.apiLevel, directory: work, cwd: work, environment, ...(options.now ? { now: options.now } : {}) });
|
||||
say("installing the APK");
|
||||
installOnLocalEmulator({ runner, serial: started.serial, apk: installPath, cwd: work, environment });
|
||||
}
|
||||
const deviceId = (udid ?? serial)!;
|
||||
let connection: SimulatorConnection = { sessionId: `local-${deviceId}`, daemonBaseUrl: "", daemonAuthToken: "" };
|
||||
if (controller === "argent") {
|
||||
// Argent drives the device through a tool-server of this run's own.
|
||||
const cli = await ensureArgentToolServer({ environment: options.environment, progress: say });
|
||||
argent = await startLocalArgentServer({ runner, cli, directory: work, cwd: work, environment, ...(options.now ? { now: options.now } : {}) });
|
||||
await record.update({ argent: { pid: argent.pid, cli: argent.cli, home: argent.home } });
|
||||
connection = { ...connection, daemonBaseUrl: argent.url, daemonAuthToken: argent.token, controller: "argent" };
|
||||
}
|
||||
await explore(connection, { deviceId, osVersion, stateDirectory });
|
||||
} catch (error) { primaryError = error; throw error; }
|
||||
finally {
|
||||
try {
|
||||
if (argent) stopLocalArgentServer(argent);
|
||||
// Its own agent-device daemon lets go of the device before it goes.
|
||||
if (controller === "agent-device") runner({ command: agentDevice, args: ["close", "--session", CONTROLLER_SESSION, "--json"], cwd: work,
|
||||
environment: { ...environment, AGENT_DEVICE_STATE_DIR: stateDirectory }, timeoutMs: 60_000, allowFailure: true });
|
||||
await stopLocalAgentDevice(stateDirectory);
|
||||
if (serial) { say(`stopping the local emulator ${serial}`); await deleteLocalEmulator({ runner, serial, cwd: work, environment }); }
|
||||
if (udid) { say(`deleting the local simulator ${udid}`); deleteLocalSimulator({ runner, udid, cwd: work, environment }); }
|
||||
// Everything is stopped; a cleanup that threw leaves the record for the next run's sweep.
|
||||
await record.close();
|
||||
} catch (error) {
|
||||
throw new CiError({ code: "SESSION_CLEANUP_FAILED", stage: "cleanup", message: `The local ${serial ? "emulator" : "simulator"} Explore started could not be stopped.`,
|
||||
nextAction: serial ? `Stop it with: adb -s ${serial} emu kill` : udid ? `Delete it with: xcrun simctl delete ${udid}` : "Rerun explore:binary --simulator local; it stops what this run left.",
|
||||
details: { ...(serial ? { serial } : {}), ...(udid ? { udid } : {}), ...(primaryError ? { originalFailure: serializeCiError(primaryError, { secrets: options.secrets }) } : {}) }, cause: error });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function runBinaryExploration(options: BinaryExploreOptions): Promise<BinaryExploreResult> {
|
||||
const startedAt = Date.now();
|
||||
const now = options.now ?? Date.now;
|
||||
@@ -666,21 +580,18 @@ export async function runBinaryExploration(options: BinaryExploreOptions): Promi
|
||||
const runner = options.runner ?? defaultRunner;
|
||||
const limits = validatedLimits(options);
|
||||
const inputs = hintInputs(options.hints, environment);
|
||||
const local = options.simulator === "local";
|
||||
// A local emulator runs this Mac's ABI (arm64-v8a on Apple silicon); EAS's runs x86_64.
|
||||
const emulatorAbi = local ? hostEmulatorAbi() : "x86_64";
|
||||
say("inspecting the archive");
|
||||
const archive = await inspectArchive(options.archive);
|
||||
assertEmulatorCompatible(archive, [emulatorAbi]);
|
||||
assertEmulatorCompatible(archive);
|
||||
if (options.platform && options.platform !== archive.platform) throw binaryError("ARCHIVE_PLATFORM_MISMATCH", `The archive is an ${archive.platform} build but --platform ${options.platform} was requested.`, "Drop --platform or pass a matching archive.");
|
||||
if (!local && !environment.EXPO_TOKEN?.trim() && !environment.EXPO_SESSION_SECRET?.trim() && !(await easLoggedIn(runner, environment))) {
|
||||
if (!environment.EXPO_TOKEN?.trim() && !environment.EXPO_SESSION_SECRET?.trim() && !(await easLoggedIn(runner, environment))) {
|
||||
throw binaryError("EXPO_LOGIN_REQUIRED", "No EAS login was found.", "Run `eas login` or set EXPO_TOKEN, then rerun explore:binary.");
|
||||
}
|
||||
const platform = archive.platform;
|
||||
const bundleId = options.bundleId ?? archive.bundleId;
|
||||
const device = options.device ?? (platform === "ios" ? DEFAULT_IOS_DEVICE : DEFAULT_ANDROID_DEVICE);
|
||||
say(`${archive.appName} ${archive.version ?? ""} (${bundleId}, ${platform}, ${(archive.bytes / 1048576).toFixed(0)} MB, sha256 ${archive.sha256.slice(0, 12)})`);
|
||||
if (archive.missingLibs?.length && emulatorAbi === "x86_64") say(`warning: lib/x86_64 lacks ${archive.missingLibs.slice(0, 4).join(", ")}${archive.missingLibs.length > 4 ? ` and ${archive.missingLibs.length - 4} more` : ""} that another ABI ships; the app may stop with UnsatisfiedLinkError on the emulator`);
|
||||
if (archive.missingLibs?.length) say(`warning: lib/x86_64 lacks ${archive.missingLibs.slice(0, 4).join(", ")}${archive.missingLibs.length > 4 ? ` and ${archive.missingLibs.length - 4} more` : ""} that another ABI ships; the app may stop with UnsatisfiedLinkError on the emulator`);
|
||||
|
||||
const model = await preflightModelSession(options, environment, say);
|
||||
|
||||
@@ -690,7 +601,7 @@ export async function runBinaryExploration(options: BinaryExploreOptions): Promi
|
||||
const work = await realpath(await mkdtemp(join(tmpdir(), "expo-explore-binary-")));
|
||||
const easEnvironment = { ...baseEnvironment(environment), ...(environment.EXPO_TOKEN ? { EXPO_TOKEN: environment.EXPO_TOKEN } : {}), ...(environment.HOME ? { HOME: environment.HOME } : {}), CI: "1", EXPO_NO_TELEMETRY: "1" };
|
||||
const easBin = packageBin("eas-cli", "eas");
|
||||
if (!local) await lstat(easBin).catch(() => { throw binaryError("EXPLORE_TOOLS_MISSING", "The EAS CLI that Explore pins is not installed.", "Reinstall @expo/explore with optional dependencies."); });
|
||||
await lstat(easBin).catch(() => { throw binaryError("EXPLORE_TOOLS_MISSING", "The EAS CLI that Explore pins is not installed.", "Reinstall @expo/explore with optional dependencies."); });
|
||||
const eas = (args: string[], timeoutMs = 5 * 60_000): CommandResult & { status: number } => {
|
||||
try { return { ...runner({ command: process.execPath, args: [easBin, ...args], cwd: work, environment: easEnvironment, timeoutMs }), status: 0 }; }
|
||||
catch (error) { return { stdout: "", stderr: error instanceof Error ? error.message : String(error), status: 1 }; }
|
||||
@@ -704,11 +615,6 @@ export async function runBinaryExploration(options: BinaryExploreOptions): Promi
|
||||
const controller = options.controller ?? "agent-device";
|
||||
// Fetched before the paid session starts, so a blocked download costs nothing.
|
||||
if (!options.runner) await ensureController(controller, { environment, progress: say });
|
||||
if (local) {
|
||||
// What an earlier local run stopped hard left running (a simulator, an emulator, a daemon) goes first.
|
||||
const swept = await sweepLocalCaptures({ environment, runner, cwd: work }).catch(() => [] as string[]);
|
||||
if (swept.length) say(`stopped what an interrupted local run left running: ${swept.join(", ")}`);
|
||||
}
|
||||
const map: ExploreMap = { contract: CONTRACT, revision: 0, run: { id: randomUUID(), name: archive.appName, platform, controller, exploration: "black-box", bundleId, status: "draft",
|
||||
createdAt: new Date(now()).toISOString(), updatedAt: new Date(now()).toISOString(),
|
||||
build: { ...(archive.version ? { version: archive.version } : {}), ...(archive.buildNumber ? { number: archive.buildNumber } : {}), hash: archive.sha256, source: "local" },
|
||||
@@ -716,83 +622,57 @@ export async function runBinaryExploration(options: BinaryExploreOptions): Promi
|
||||
try {
|
||||
let installPath = archive.path;
|
||||
if (archive.kind === "ios-tgz" || archive.kind === "ios-ipa") { say("unpacking the iOS bundle"); installPath = await extractIosBundle(archive, join(work, "bundle")); }
|
||||
const appIcon = await readArchiveIcon(archive);
|
||||
const exploreOn = (connection: SimulatorConnection, sessionJson: () => string, localDevice?: LocalDevice, afterInstall?: () => void) => exploreConnectedSession({ connection, platform, device, bundleId,
|
||||
...(afterInstall ? { afterInstall } : {}),
|
||||
...(appIcon ? { appIcon } : {}), app: { name: archive.appName, ...(archive.version ? { version: archive.version } : {}) },
|
||||
// A local device has the app installed by simctl or adb before the controller starts.
|
||||
...(localDevice ? { local: localDevice } : { install: { path: installPath, kind: archive.kind } }),
|
||||
work, runner, environment, secrets: [environment.EXPO_TOKEN ?? "", connection.daemonAuthToken, ...inputs.values].filter(Boolean), inputs, say, now, limits, store, map, model,
|
||||
urlSchemes: archive.urlSchemes, sessionJson,
|
||||
...(options.launchUrl ? { launchUrl: options.launchUrl } : {}), ...(options.hints ? { hints: options.hints } : {}), ...(options.allowDestructive ? { allowDestructive: options.allowDestructive } : {}) });
|
||||
if (local) {
|
||||
const tag = map.run.id.replace(/-/g, "").slice(0, 8);
|
||||
await withLocalDevice({ archive, installPath, platform, device, bundleId, controller, tag, work, runner, environment, say, secrets: inputs.values, ...(options.now ? { now: options.now } : {}) },
|
||||
async (connection, localDevice) => {
|
||||
sessionId = connection.sessionId;
|
||||
({ runtime, exploration } = await exploreOn(connection, () => "", localDevice));
|
||||
});
|
||||
} else {
|
||||
if (!owner) {
|
||||
const who = eas(["whoami"], 60_000);
|
||||
owner = who.status === 0 ? whoamiAccounts(who.stdout)[0] ?? "" : "";
|
||||
if (!owner) throw binaryError("EXPO_LOGIN_REQUIRED", "EAS did not report an account for this login.", "Run `eas login` (or set EXPO_TOKEN) and rerun, or pass --owner.");
|
||||
}
|
||||
await writeFile(join(work, "package.json"), JSON.stringify({ name: project, version: "0.0.0", private: true }), { mode: 0o600 });
|
||||
await writeFile(join(work, "app.json"), JSON.stringify({ expo: { name: project, slug: project, owner, web: { output: "server" } } }), { mode: 0o600 });
|
||||
const init = eas(["init", "--force", "--non-interactive", "--json"], 2 * 60_000);
|
||||
const appJson = JSON.parse(await readFile(join(work, "app.json"), "utf8")) as { expo?: { extra?: { eas?: { projectId?: string } } } };
|
||||
const projectId = appJson.expo?.extra?.eas?.projectId;
|
||||
if (init.status !== 0 || !projectId) throw binaryError("EXPLORE_PROJECT_FAILED", `EAS could not create or link @${owner}/${project}: ${lastLine(init.stderr || init.stdout)}`,
|
||||
"Give this login permission to create projects under the owner, or pass --project with an existing slug.", { owner, project });
|
||||
const projectIdentity = { name: project, slug: project, owner, projectId };
|
||||
|
||||
say(`starting an EAS Simulator session (${device}, ${limits.maxDurationMinutes} min)`);
|
||||
const sessionName = `explore-binary-${createHash("sha256").update(`${archive.sha256}:${map.run.id}`).digest("hex").slice(0, 16)}`;
|
||||
const dotenvPath = join(work, SIMULATOR_DOTENV_FILE_NAME);
|
||||
await writeFile(dotenvPath, SIMULATOR_DOTENV_HEADER, { flag: "wx", mode: 0o600 });
|
||||
let startError: unknown;
|
||||
try {
|
||||
const started = eas(["simulator:start", "--name", sessionName, "--platform", platform, "--device", device, "--type", controller, "--package-version", controllerVersion(controller), "--public-link",
|
||||
"--max-duration-minutes", String(limits.maxDurationMinutes + 5), "--out-config-type", "dotenv", "--non-interactive"], 20 * 60_000);
|
||||
if (started.status !== 0) throw new Error(started.stderr || started.stdout || "eas simulator:start failed");
|
||||
} catch (error) { startError = error; }
|
||||
const handoff = await readSimulatorDotenvHandoff(dotenvPath);
|
||||
const secrets = [environment.EXPO_TOKEN ?? "", ...(handoff.connection ? [handoff.connection.daemonAuthToken] : []), ...inputs.values].filter(Boolean);
|
||||
const startFailure = startError ? simulatorStartFailure(startError, secrets) : undefined;
|
||||
if (handoff.sessionId) {
|
||||
try { assertSimulatorSessionIdentity(eas(["simulator:get", "--id", handoff.sessionId, "--json", "--non-interactive"], 2 * 60_000).stdout, handoff.sessionId, sessionName, projectIdentity, handoff.connection, platform); }
|
||||
catch (error) { throw new CiError({ code: "SESSION_HANDOFF_UNVERIFIED", stage: "session", message: "The EAS handoff could not prove ownership of the exact simulator session. The private handoff was preserved.",
|
||||
nextAction: "Inspect the EAS session list; confirm ownership before stopping the reported session.", details: { handoffDirectory: work, reportedSessionId: handoff.sessionId, ...(startFailure ? { startFailure } : {}) }, cause: error }); }
|
||||
sessionId = handoff.sessionId;
|
||||
}
|
||||
if (!sessionId) throw new CiError({ code: startFailure ? "SIMULATOR_START_FAILED" : "SESSION_HANDOFF_UNVERIFIED", stage: "session",
|
||||
message: startFailure ? `EAS simulator:start failed: ${startFailure.message}` : "EAS did not provide a verifiable simulator session.",
|
||||
nextAction: "Inspect the EAS start failure and session list; verify a session's exact ID and ownership before cleanup.", details: { handoffDirectory: work, ...(startFailure ? { startFailure } : {}) }, cause: startError });
|
||||
if (startFailure) throw new CiError({ code: "SIMULATOR_START_FAILED", stage: "session", message: `EAS simulator:start failed after the session was verified: ${startFailure.message}`,
|
||||
nextAction: "Inspect the start failure; Explore stops the verified session before returning.", details: { sessionId, startFailure }, cause: startError });
|
||||
if (handoff.validationError) throw handoff.validationError;
|
||||
if (!handoff.connection) throw new Error("Simulator handoff is missing its controller connection");
|
||||
await rm(dotenvPath, { force: true });
|
||||
// The app's own links open without iOS asking first, when the session's host can approve them (serve-sim 0.10.0).
|
||||
const verifiedSession = sessionId;
|
||||
const sessionEas: EasCommand = (args, commandOptions) => {
|
||||
const result = eas(args, commandOptions?.timeoutMs);
|
||||
if (result.status !== 0 && !commandOptions?.allowFailure) throw new Error(lastLine(result.stderr || result.stdout) || `eas ${args[0]} failed`);
|
||||
return result;
|
||||
};
|
||||
const afterInstall = platform === "ios" && archive.urlSchemes.length ? () => {
|
||||
const approved = approveSessionUrlSchemes(sessionEas, verifiedSession, simulatorControlActions(sessionEas, verifiedSession), bundleId, archive.urlSchemes);
|
||||
if (approved.length) say(`approved ${approved.map(item => `${item}://`).join(", ")} links on the session`);
|
||||
} : undefined;
|
||||
({ runtime, exploration } = await exploreOn(handoff.connection, () => eas(["simulator:get", "--id", handoff.connection!.sessionId, "--json", "--non-interactive"], 2 * 60_000).stdout, undefined, afterInstall));
|
||||
if (!owner) {
|
||||
const who = eas(["whoami"], 60_000);
|
||||
owner = who.status === 0 ? whoamiAccounts(who.stdout)[0] ?? "" : "";
|
||||
if (!owner) throw binaryError("EXPO_LOGIN_REQUIRED", "EAS did not report an account for this login.", "Run `eas login` (or set EXPO_TOKEN) and rerun, or pass --owner.");
|
||||
}
|
||||
await writeFile(join(work, "package.json"), JSON.stringify({ name: project, version: "0.0.0", private: true }), { mode: 0o600 });
|
||||
await writeFile(join(work, "app.json"), JSON.stringify({ expo: { name: project, slug: project, owner, web: { output: "server" } } }), { mode: 0o600 });
|
||||
const init = eas(["init", "--force", "--non-interactive", "--json"], 2 * 60_000);
|
||||
const appJson = JSON.parse(await readFile(join(work, "app.json"), "utf8")) as { expo?: { extra?: { eas?: { projectId?: string } } } };
|
||||
const projectId = appJson.expo?.extra?.eas?.projectId;
|
||||
if (init.status !== 0 || !projectId) throw binaryError("EXPLORE_PROJECT_FAILED", `EAS could not create or link @${owner}/${project}: ${lastLine(init.stderr || init.stdout)}`,
|
||||
"Give this login permission to create projects under the owner, or pass --project with an existing slug.", { owner, project });
|
||||
const projectIdentity = { name: project, slug: project, owner, projectId };
|
||||
|
||||
say(`starting an EAS Simulator session (${device}, ${limits.maxDurationMinutes} min)`);
|
||||
const sessionName = `explore-binary-${createHash("sha256").update(`${archive.sha256}:${map.run.id}`).digest("hex").slice(0, 16)}`;
|
||||
const dotenvPath = join(work, SIMULATOR_DOTENV_FILE_NAME);
|
||||
await writeFile(dotenvPath, SIMULATOR_DOTENV_HEADER, { flag: "wx", mode: 0o600 });
|
||||
let startError: unknown;
|
||||
try {
|
||||
const started = eas(["simulator:start", "--name", sessionName, "--platform", platform, "--device", device, "--type", controller, "--package-version", controllerVersion(controller), "--public-link",
|
||||
"--max-duration-minutes", String(limits.maxDurationMinutes + 5), "--out-config-type", "dotenv", "--non-interactive"], 20 * 60_000);
|
||||
if (started.status !== 0) throw new Error(started.stderr || started.stdout || "eas simulator:start failed");
|
||||
} catch (error) { startError = error; }
|
||||
const handoff = await readSimulatorDotenvHandoff(dotenvPath);
|
||||
const secrets = [environment.EXPO_TOKEN ?? "", ...(handoff.connection ? [handoff.connection.daemonAuthToken] : []), ...inputs.values].filter(Boolean);
|
||||
const startFailure = startError ? simulatorStartFailure(startError, secrets) : undefined;
|
||||
if (handoff.sessionId) {
|
||||
try { assertSimulatorSessionIdentity(eas(["simulator:get", "--id", handoff.sessionId, "--json", "--non-interactive"], 2 * 60_000).stdout, handoff.sessionId, sessionName, projectIdentity, handoff.connection, platform); }
|
||||
catch (error) { throw new CiError({ code: "SESSION_HANDOFF_UNVERIFIED", stage: "session", message: "The EAS handoff could not prove ownership of the exact simulator session. The private handoff was preserved.",
|
||||
nextAction: "Inspect the EAS session list; confirm ownership before stopping the reported session.", details: { handoffDirectory: work, reportedSessionId: handoff.sessionId, ...(startFailure ? { startFailure } : {}) }, cause: error }); }
|
||||
sessionId = handoff.sessionId;
|
||||
}
|
||||
if (!sessionId) throw new CiError({ code: startFailure ? "SIMULATOR_START_FAILED" : "SESSION_HANDOFF_UNVERIFIED", stage: "session",
|
||||
message: startFailure ? `EAS simulator:start failed: ${startFailure.message}` : "EAS did not provide a verifiable simulator session.",
|
||||
nextAction: "Inspect the EAS start failure and session list; verify a session's exact ID and ownership before cleanup.", details: { handoffDirectory: work, ...(startFailure ? { startFailure } : {}) }, cause: startError });
|
||||
if (startFailure) throw new CiError({ code: "SIMULATOR_START_FAILED", stage: "session", message: `EAS simulator:start failed after the session was verified: ${startFailure.message}`,
|
||||
nextAction: "Inspect the start failure; Explore stops the verified session before returning.", details: { sessionId, startFailure }, cause: startError });
|
||||
if (handoff.validationError) throw handoff.validationError;
|
||||
if (!handoff.connection) throw new Error("Simulator handoff is missing its controller connection");
|
||||
await rm(dotenvPath, { force: true });
|
||||
const appIcon = await readArchiveIcon(archive);
|
||||
({ runtime, exploration } = await exploreConnectedSession({ connection: handoff.connection, platform, device, bundleId, ...(appIcon ? { appIcon } : {}), app: { name: archive.appName, ...(archive.version ? { version: archive.version } : {}) },
|
||||
install: { path: installPath, kind: archive.kind }, work, runner, environment, secrets, inputs, say, now, limits, store, map, model, urlSchemes: archive.urlSchemes,
|
||||
sessionJson: () => eas(["simulator:get", "--id", handoff.connection!.sessionId, "--json", "--non-interactive"], 2 * 60_000).stdout,
|
||||
...(options.launchUrl ? { launchUrl: options.launchUrl } : {}), ...(options.hints ? { hints: options.hints } : {}), ...(options.allowDestructive ? { allowDestructive: options.allowDestructive } : {}) }));
|
||||
} catch (error) {
|
||||
primaryError = toCiError(error, { code: "EXPLORE_BINARY_FAILED", stage: "exploration", nextAction: "Inspect the diagnostic, correct the failing prerequisite, and rerun explore:binary." });
|
||||
} finally {
|
||||
// A local device is stopped by withLocalDevice; only the work directory is left.
|
||||
if (local) await rm(work, { recursive: true, force: true });
|
||||
else if (sessionId) {
|
||||
if (sessionId) {
|
||||
try {
|
||||
say(`stopping simulator session ${sessionId}`);
|
||||
assertSimulatorStopped(eas(["simulator:stop", "--id", sessionId, "--json", "--non-interactive"], 2 * 60_000).stdout, sessionId);
|
||||
@@ -854,7 +734,18 @@ export function assertAppUrl(url: string, appSchemes: readonly string[] = []): v
|
||||
|
||||
export const BLANK_SCREENSHOT_MESSAGE = "The app blocks screen capture on this screen (Android FLAG_SECURE), so its screenshot came back blank.";
|
||||
|
||||
export { solidColour };
|
||||
/** A capture-protected screen comes back as a single flat colour (black on Android); every 97th pixel is enough to tell. */
|
||||
export function solidColour(png: Buffer): boolean {
|
||||
let frame: DecodedFrame;
|
||||
try { frame = createRequire(import.meta.url.replace(/\?.*$/, ""))("pngjs").PNG.sync.read(png, { checkCRC: false }) as DecodedFrame; }
|
||||
catch { return false; }
|
||||
const { data } = frame;
|
||||
if (data.length < 4) return false;
|
||||
for (let offset = 0; offset + 3 < data.length; offset += 4 * 97) {
|
||||
if (data[offset] !== data[0] || data[offset + 1] !== data[1] || data[offset + 2] !== data[2]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Setup commands whose last positional is free text (`fill <ref> <text>`, `type <text>`): move the flags ahead of a `--` separator. */
|
||||
export function guardPositionals(args: readonly string[]): string[] {
|
||||
|
||||
@@ -301,8 +301,7 @@ export async function runBridgeCommand(argv: readonly string[], context: ArgentB
|
||||
|
||||
/** Reads are resent after a transport failure (they change nothing); a UI action is sent once, after a health check. */
|
||||
const call = async (tool: string, args: Record<string, unknown> = {}, options?: { out?: string }): Promise<Record<string, unknown>> => {
|
||||
// Tools that name devices their own way (or none) take no udid.
|
||||
const withDevice = tool === "list-devices" || tool === "stop-all-simulator-servers" ? args : { udid: state.udid, ...args };
|
||||
const withDevice = tool === "list-devices" ? args : { udid: state.udid, ...args };
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
try { return record(await context.call(tool, withDevice, options)); }
|
||||
catch (error) {
|
||||
@@ -620,10 +619,6 @@ export async function runBridgeCommand(argv: readonly string[], context: ArgentB
|
||||
const posture = positional[0];
|
||||
if (posture !== "closed" && posture !== "half-open" && posture !== "open") throw new BridgeFailure("INVALID_ARGS", "fold needs closed, half-open or open.");
|
||||
await beforeAction();
|
||||
// Helpers the tool-server started before a fold can leave the panel it lights black and unread: on a fresh EAS
|
||||
// session, whose tool-server started them at boot, the first fold opened to a black inner panel every time
|
||||
// without this, and read the panel at once with it. A local tool-server is Explore's own and starts clean.
|
||||
await call("stop-all-simulator-servers", { devices: [state.udid] });
|
||||
const folded = await call("fold", { posture });
|
||||
// The other panel lights at another size: every stored coordinate and element reference is stale.
|
||||
delete state.screen;
|
||||
@@ -635,33 +630,16 @@ export async function runBridgeCommand(argv: readonly string[], context: ArgentB
|
||||
const lit = record(folded.screen);
|
||||
if (finite(lit.width) && finite(lit.height) && lit.height > 0) {
|
||||
const litRatio = lit.width / lit.height;
|
||||
const follows = async () => {
|
||||
for (let poll = 0; poll < 10; poll++) {
|
||||
const shape = (await tree()).screen;
|
||||
if (shape && shape.height > 0 && Math.abs(shape.width / shape.height - litRatio) < 0.004) return true;
|
||||
await context.sleep(1_000);
|
||||
}
|
||||
return false;
|
||||
};
|
||||
// A reader still stuck on the dark panel is reset once more (the device's helpers, as reset-reader does): it is
|
||||
// cheap and leaves the app alone. If that is not enough, capture restarts SpringBoard and folds again.
|
||||
if (!await follows() && !await call("stop-all-simulator-servers", { devices: [state.udid] }).then(follows, () => false)) {
|
||||
throw new BridgeFailure("CONTROLLER_FOLD_UNVERIFIED", `Argent kept reading the other panel after folding the device ${posture}, and after its device helpers were reset.`);
|
||||
let followed = false;
|
||||
for (let poll = 0; poll < 10 && !followed; poll++) {
|
||||
const shape = (await tree()).screen;
|
||||
followed = !!shape && shape.height > 0 && Math.abs(shape.width / shape.height - litRatio) < 0.004;
|
||||
if (!followed) await context.sleep(1_000);
|
||||
}
|
||||
if (!followed) throw new BridgeFailure("CONTROLLER_FOLD_UNVERIFIED", `Argent kept reading the other panel after folding the device ${posture}.`);
|
||||
}
|
||||
return success({ action: "fold", pose: posture, ...(folded.panel !== undefined ? { panel: folded.panel } : {}) });
|
||||
}
|
||||
case "reset-reader": {
|
||||
// Stops the device's Argent helpers, among them the accessibility service describe reads through; the
|
||||
// tool-server starts fresh ones on the next call. It is how a reader stuck on the panel a fold turned off is
|
||||
// reset where the tool-server itself cannot be restarted, as on EAS (it started it; never stop it there).
|
||||
await ensureDevice();
|
||||
const stopped = await call("stop-all-simulator-servers", { devices: [state.udid] });
|
||||
delete state.screen;
|
||||
delete state.refs;
|
||||
state.generation += 1;
|
||||
return success({ action: "reset-reader", stopped: Array.isArray(stopped.stopped) ? stopped.stopped.filter(item => typeof item === "string") : [] });
|
||||
}
|
||||
case "apps": return success({ apps: [] });
|
||||
case "session": return success({ sessions: [] });
|
||||
// TODO(argent#1509): map `settings appearance <scheme>` to Argent's `set-appearance` once a release with it is pinned.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { CiError } from "../shared/ci-errors.js";
|
||||
|
||||
export const EAS_CLI_VERSION = "25.2.0";
|
||||
export const EAS_CLI_VERSION = "25.0.0";
|
||||
export { AGENT_DEVICE_VERSION } from "../shared/agent-device-version.js";
|
||||
|
||||
export const CONTROLLER_SESSION = "expo-explore-runtime";
|
||||
|
||||
@@ -92,7 +92,7 @@ export function approveLinkScheme(options: { runner: CommandRunner; udid: string
|
||||
}
|
||||
|
||||
/** The pixel size of a PNG, from its header. */
|
||||
export function pngSize(bytes: Buffer): { width: number; height: number } | undefined {
|
||||
function pngSize(bytes: Buffer): { width: number; height: number } | undefined {
|
||||
if (bytes.length < 24 || bytes.toString("latin1", 12, 16) !== "IHDR") return undefined;
|
||||
return { width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20) };
|
||||
}
|
||||
@@ -186,18 +186,6 @@ export async function assertLocalEmulatorCompatible(apk: string, abi: string): P
|
||||
nextAction: `Build an APK that includes ${abi} (a universal build does), or capture Android on EAS Simulator with --simulator eas.` });
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether agent-device still holds a claim on an emulator serial, one an interrupted run left behind: it refuses
|
||||
* such a serial even when it reports the claim as stale, so startLocalEmulator skips that port.
|
||||
*/
|
||||
export function agentDeviceClaims(options: { runner: CommandRunner; agentDevice: string; serial: string; cwd: string; environment: NodeJS.ProcessEnv }): boolean {
|
||||
const status = options.runner({ command: options.agentDevice, args: ["device", "status", "--platform", "android", "--serial", options.serial, "--json"],
|
||||
cwd: options.cwd, environment: options.environment, timeoutMs: 30_000, allowFailure: true });
|
||||
let data: { claims?: unknown[]; hiddenStaleClaims?: number } | undefined;
|
||||
try { data = (JSON.parse(status.stdout) as { data?: typeof data }).data; } catch { return false; }
|
||||
return (data?.claims?.length ?? 0) + (data?.hiddenStaleClaims ?? 0) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates an AVD of the configured device profile (such as pixel_7) and starts it without a window. It boots in the
|
||||
* background while a capture repacks the app; waitForLocalEmulator waits for it afterwards.
|
||||
|
||||
+29
-206
@@ -22,16 +22,14 @@ import { loadAppIcon, loadCachedAppIcon, storeAppIcon } from "./app-icon.js";
|
||||
import { defaultRunner, runAgentControllerCommand } from "./controller.js";
|
||||
import { silentProgress, type Progress } from "../shared/progress.js";
|
||||
import { assertCaptureEasProfile, assertSimulatorAvailable, fingerprintFrom, hasEasEnvironmentFetchFailure, nativeBuildFrom, existingBuild, repackProfileFrom, prepareExactSourceBuild, type RepackMode } from "./eas-build.js";
|
||||
import { SIMULATOR_DOTENV_FILE_NAME, SIMULATOR_DOTENV_HEADER, endedOwnSimulatorSession, liveSimulatorSessionsNamed, simulatorSessionName, simulatorStartFailure, readSimulatorDotenvHandoff, assertSimulatorSessionIdentity, assertSimulatorStopped, collectRuntime, controllerVersion, simulatorOsVersion, type ActiveSimulatorRuntime, type SimulatorConnection } from "./simulator.js";
|
||||
import { SIMULATOR_DOTENV_FILE_NAME, SIMULATOR_DOTENV_HEADER, simulatorSessionName, simulatorStartFailure, readSimulatorDotenvHandoff, assertSimulatorSessionIdentity, assertSimulatorStopped, collectRuntime, controllerVersion, simulatorOsVersion, type ActiveSimulatorRuntime, type SimulatorConnection } from "./simulator.js";
|
||||
import { argentControllerInvocation } from "./controller-invocation.js";
|
||||
import { sharedBuild } from "./shared-build.js";
|
||||
import { LOCAL_EMULATOR_STATE_PREFIX, LOCAL_SIMULATOR_STATE_PREFIX, agentDeviceClaims, assertLocalEmulatorCompatible, createLocalSimulator, startLocalEmulator, waitForLocalEmulator, waitForLocalSimulator, deleteLocalEmulator,
|
||||
import { LOCAL_EMULATOR_STATE_PREFIX, LOCAL_SIMULATOR_STATE_PREFIX, assertLocalEmulatorCompatible, createLocalSimulator, startLocalEmulator, waitForLocalEmulator, waitForLocalSimulator, deleteLocalEmulator,
|
||||
deleteLocalSimulator, hostEmulatorAbi, installOnLocalEmulator, installOnLocalSimulator, approveLinkScheme, localPoseShown,
|
||||
pngSize, setLocalEmulatorAppearance, setLocalSimulatorAppearance, startLocalArgentServer, stopLocalAgentDevice, stopLocalArgentServer, type LocalArgentServer } from "./local-simulator.js";
|
||||
setLocalEmulatorAppearance, setLocalSimulatorAppearance, startLocalArgentServer, stopLocalAgentDevice, stopLocalArgentServer, type LocalArgentServer } from "./local-simulator.js";
|
||||
import { ensureArgentToolServer } from "../shared/controller-cache.js";
|
||||
import { openLocalCaptureRecord } from "./local-registry.js";
|
||||
import { approveSessionUrlSchemes, simulatorControl, simulatorControlActions, type EasCommand } from "./simulator-control.js";
|
||||
import { solidColour } from "../shared/png-evidence.js";
|
||||
import { type UnattributedSetting } from "./unattributed.js";
|
||||
import { appScheme, hasConcreteRoutePath, unavailableRoute, capturePlannedRoutes, deviceArgs } from "./route-capture.js";
|
||||
|
||||
@@ -100,18 +98,8 @@ export type CiMapResult = {
|
||||
};
|
||||
|
||||
|
||||
/** New EAS sessions a capture starts in place of one EAS failed to start (ERRORED while booting, or never named). */
|
||||
const SESSION_START_RETRIES = 5;
|
||||
/**
|
||||
* The most time, from the first failed start, that replacement sessions may take, waits included. It keeps a review
|
||||
* inside its CI job (90 minutes for a baseline) with a native build, a repack and both captures still to run.
|
||||
*/
|
||||
const SESSION_RETRY_BUDGET_MS = 30 * 60_000;
|
||||
/** How long one `eas simulator:start` may take: eas-cli waits up to 15 minutes for a session, not counting the queue. */
|
||||
const SESSION_START_TIMEOUT_MS = 20 * 60_000;
|
||||
/** The wait before each of them: 10 s, doubling, at most 2 minutes. */
|
||||
export function sessionRetryDelayMs(retry: number): number {
|
||||
return Math.min(10_000 * 2 ** (retry - 1), 120_000);
|
||||
function parseJsonOrUndefined(text: string): unknown {
|
||||
try { return JSON.parse(text); } catch { return undefined; }
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -129,17 +117,6 @@ function sessionDurationLimit(error: unknown): number | undefined {
|
||||
return match ? Math.floor(Number(match[1])) : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* A start failure EAS may not repeat on the next try: a failed request, a dropped connection, a timeout, or no capacity
|
||||
* right now. An account's quota, plan or permissions are not, and fail at once rather than after every retry.
|
||||
*/
|
||||
function transientSessionStartFailure(error: unknown): boolean {
|
||||
if (error instanceof CiError && error.code === "CONTROLLER_REQUEST_TIMEOUT") return true;
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
if (/not authori[sz]ed|unauthori[sz]ed|forbidden|permission|quota|billing|max duration/i.test(message)) return false;
|
||||
return /GraphQL request failed|ECONNRESET|ETIMEDOUT|EAI_AGAIN|socket hang up|timed out|\b50[234]\b|capacity/i.test(message);
|
||||
}
|
||||
|
||||
function positiveInteger(value: number, name: string): number {
|
||||
if (!Number.isInteger(value) || value <= 0) {
|
||||
throw new Error(`${name} must be a positive integer`);
|
||||
@@ -438,26 +415,17 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
|
||||
say(`reading EAS build profile ${options.easProfile}`);
|
||||
const eas = (args: string[], timeoutMs = 5 * 60_000, cwd = project) => runner({ command: options.easCommand, args,
|
||||
cwd, environment: easEnvironment, timeoutMs });
|
||||
// `eas simulator:control` names the session by id, from the session's own project directory.
|
||||
const sessionEas: EasCommand = (args, commandOptions) => runner({ command: options.easCommand, args, cwd: simulatorProject, environment: easEnvironment,
|
||||
timeoutMs: commandOptions?.timeoutMs ?? 5 * 60_000, ...(commandOptions?.allowFailure ? { allowFailure: true } : {}) });
|
||||
// What the EAS session's host can do through simulator:control (iOS sessions on serve-sim 0.10.0 or later).
|
||||
let controlActions = new Set<string>();
|
||||
const configResult = eas(["config", "--platform", options.platform, "--profile", options.easProfile, "--json", "--non-interactive"]);
|
||||
const profile = repackProfileFrom(configResult.stdout);
|
||||
const configValue = parseJson(configResult.stdout, "eas config") as { appConfig: Record<string, unknown>; buildProfile: Record<string, unknown> };
|
||||
scheme ??= appScheme(configValue.appConfig.scheme);
|
||||
colorSchemes = resolveColorSchemes(options.appearance ?? "auto", configValue.appConfig, options.platform);
|
||||
// Argent cannot switch the appearance itself. On a local device the host switches it (simctl, adb); on an EAS iOS
|
||||
// session serve-sim does (appearance.set), which is known once the session starts; otherwise one appearance is captured.
|
||||
let argentSchemes = controller === "argent" && !local ? argentColorSchemes(colorSchemes, configValue.appConfig, options.platform) : undefined;
|
||||
const narrowToArgentScheme = () => {
|
||||
if (!argentSchemes) return;
|
||||
if (argentSchemes.skipped.length) say(`Argent cannot switch appearance on this session; capturing ${argentSchemes.schemes[0]} only, skipped ${argentSchemes.skipped.join(", ")}`);
|
||||
colorSchemes = argentSchemes.schemes;
|
||||
argentSchemes = undefined;
|
||||
};
|
||||
if (options.platform !== "ios") narrowToArgentScheme();
|
||||
// Argent cannot switch the appearance itself; on a local device the host switches it (simctl, adb), so it is kept.
|
||||
if (controller === "argent" && !local) {
|
||||
const single = argentColorSchemes(colorSchemes, configValue.appConfig, options.platform);
|
||||
if (single.skipped.length) say(`Argent cannot switch appearance yet (software-mansion/argent#1509); capturing ${single.schemes[0]} only, skipped ${single.skipped.join(", ")}`);
|
||||
colorSchemes = single.schemes;
|
||||
}
|
||||
app = { name: profile.projectIdentity.name, ...(profile.projectIdentity.version ? { version: profile.projectIdentity.version } : {}),
|
||||
...(profile.projectIdentity.buildNumber ? { buildNumber: profile.projectIdentity.buildNumber } : {}) };
|
||||
projectId = profile.projectIdentity.projectId;
|
||||
@@ -507,7 +475,13 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
|
||||
say(`starting a local ${options.device} emulator`);
|
||||
localEmulatorStart = await startLocalEmulator({ runner, device: options.device, name: `explore-${side}-${options.gitCommit.slice(0, 8)}`, directory: simulatorProject,
|
||||
cwd: simulatorProject, environment: restrictedEnvironment,
|
||||
...(controller === "agent-device" ? { claimed: (serial: string) => agentDeviceClaims({ runner, agentDevice: options.agentDeviceCommand, serial, cwd: simulatorProject, environment: restrictedEnvironment }) } : {}),
|
||||
// agent-device refuses a serial an interrupted run still claims, even one it reports as stale, so that port is skipped.
|
||||
...(controller === "agent-device" ? { claimed: (serial: string) => {
|
||||
const status = runner({ command: options.agentDeviceCommand, args: ["device", "status", "--platform", "android", "--serial", serial, "--json"],
|
||||
cwd: simulatorProject, environment: restrictedEnvironment, timeoutMs: 30_000, allowFailure: true });
|
||||
const data = (parseJsonOrUndefined(status.stdout) as { data?: { claims?: unknown[]; hiddenStaleClaims?: number } } | undefined)?.data;
|
||||
return (data?.claims?.length ?? 0) + (data?.hiddenStaleClaims ?? 0) > 0;
|
||||
} } : {}),
|
||||
// Recorded as soon as it starts, so an interrupted review stops it too.
|
||||
started: async serial => {
|
||||
localEmulator = serial;
|
||||
@@ -527,23 +501,19 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
|
||||
}
|
||||
} catch (error) { await stopEarlyDevice().catch(() => undefined); throw error; }
|
||||
// The session is named before its app exists: an EAS session starts while the app is repacked (startSession).
|
||||
// A session EAS failed to start is replaced once (see the session block), under a name of its own.
|
||||
const sessionNameFor = (retry: number) => simulatorSessionName({ mapName: options.name, mapId: options.buildId, gitCommit: options.gitCommit, easBuildId: local ? "local" : "installed",
|
||||
runIdentity: JSON.stringify({ mapDirectory, outputDirectory, run: sourceEnvironment.GITHUB_RUN_ID, attempt: sourceEnvironment.GITHUB_RUN_ATTEMPT, ...(retry ? { sessionRetry: retry } : {}) }) });
|
||||
let sessionRetries = 0;
|
||||
let sessionName = sessionNameFor(0);
|
||||
const sessionName = simulatorSessionName({ mapName: options.name, mapId: options.buildId, gitCommit: options.gitCommit, easBuildId: local ? "local" : "installed",
|
||||
runIdentity: JSON.stringify({ mapDirectory, outputDirectory, run: sourceEnvironment.GITHUB_RUN_ID, attempt: sourceEnvironment.GITHUB_RUN_ATTEMPT }) });
|
||||
/**
|
||||
* Starts the EAS Simulator session in the background, empty, once the build to repack is known (not while a native
|
||||
* build runs, which can take most of an hour of session time). The app is installed through the controller when both
|
||||
* are ready. Resolves with the start command's failure, if any; the session block verifies what EAS handed over.
|
||||
*/
|
||||
const startSession = (retry?: { timeoutMs: number }) => {
|
||||
const startSession = () => {
|
||||
if (local || sessionStart) return;
|
||||
if (!retry) say(`starting an EAS Simulator session (${options.device}) while the app is repacked`);
|
||||
say(`starting an EAS Simulator session (${options.device}) while the app is repacked`);
|
||||
const request = (minutes: number) => ({ command: options.easCommand, args: ["simulator:start", "--name", sessionName, "--platform", options.platform, "--device", options.device,
|
||||
"--type", controller, "--package-version", controllerVersion(controller), "--public-link",
|
||||
"--max-duration-minutes", String(minutes), "--out-config-type", "dotenv", "--non-interactive"], cwd: simulatorProject, environment: easEnvironment,
|
||||
timeoutMs: retry?.timeoutMs ?? SESSION_START_TIMEOUT_MS });
|
||||
"--max-duration-minutes", String(minutes), "--out-config-type", "dotenv", "--non-interactive"], cwd: simulatorProject, environment: easEnvironment, timeoutMs: 20 * 60_000 });
|
||||
// An injected runner (tests) answers synchronously; a real start runs beside the repack.
|
||||
const start = async (minutes: number) => options.runner ? options.runner(request(minutes)) : runAgentControllerCommand(request(minutes), options.signal ?? new AbortController().signal);
|
||||
sessionStart = writeFile(dotenvPath, SIMULATOR_DOTENV_HEADER, { flag: "wx", mode: 0o600 })
|
||||
@@ -637,72 +607,8 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
|
||||
throw new Error("The local device did not start before capture");
|
||||
} else {
|
||||
if (!localApp || !sessionStart) throw new Error("An EAS Simulator session needs the instrumented app on this machine");
|
||||
let startError = await sessionStart;
|
||||
let handoff = await readSimulatorDotenvHandoff(dotenvPath);
|
||||
// EAS sometimes fails to start a session: it errors while booting, or the start request fails before a session is
|
||||
// named. After every failed start, whatever it may have left running is accounted for; then, when the failure is
|
||||
// provably EAS's, a new session replaces it, up to SESSION_START_RETRIES times within SESSION_RETRY_BUDGET_MS, with
|
||||
// a growing wait. A session Explore cannot prove is its own is never replaced or stopped: that stays a handoff
|
||||
// failure below, as does a lookup that fails.
|
||||
const clock = options.now ?? Date.now;
|
||||
const endedSessions: string[] = [];
|
||||
let ended: { sessionId: string; status: string } | undefined;
|
||||
let retryDeadline: number | undefined;
|
||||
for (;;) {
|
||||
const easRead = (args: string[]) => {
|
||||
try { return runner({ command: options.easCommand, args, cwd: project, environment: easEnvironment, timeoutMs: 2 * 60_000, allowFailure: true }).stdout; }
|
||||
catch { return ""; }
|
||||
};
|
||||
let reason: string | undefined;
|
||||
ended = undefined;
|
||||
if (handoff.sessionId) {
|
||||
const status = endedOwnSimulatorSession(easRead(["simulator:get", "--id", handoff.sessionId, "--json", "--non-interactive"]),
|
||||
{ sessionId: handoff.sessionId, sessionName, project: profile.projectIdentity, type: controller, platform: options.platform });
|
||||
if (status) {
|
||||
ended = { sessionId: handoff.sessionId, status };
|
||||
endedSessions.push(handoff.sessionId);
|
||||
reason = `EAS ended simulator session ${handoff.sessionId} (${status}) before it was ready`;
|
||||
}
|
||||
} else if (startError && transientSessionStartFailure(startError)) {
|
||||
// The failed request may still have created a session: any by this exact name is stopped, so none is left running.
|
||||
const live = liveSimulatorSessionsNamed(easRead(["simulator:list", "--name", sessionName, "--status", "new", "--status", "queued", "--status", "starting",
|
||||
"--status", "in-progress", "--limit", "100", "--json", "--non-interactive"]), sessionName, profile.projectIdentity);
|
||||
if (live) {
|
||||
for (const id of live) assertSimulatorStopped(eas(["simulator:stop", "--id", id, "--json", "--non-interactive"], 2 * 60_000).stdout, id);
|
||||
reason = `EAS could not start the simulator session (${simulatorStartFailure(startError, [options.expoToken]).message})`;
|
||||
}
|
||||
}
|
||||
if (!reason || sessionRetries >= SESSION_START_RETRIES) break;
|
||||
retryDeadline ??= clock() + SESSION_RETRY_BUDGET_MS;
|
||||
const delayMs = sessionRetryDelayMs(sessionRetries + 1);
|
||||
// A new start needs at least a minute of the budget after its wait; one started later could not finish in it.
|
||||
const startTimeoutMs = Math.min(SESSION_START_TIMEOUT_MS, retryDeadline - clock() - delayMs);
|
||||
if (startTimeoutMs < 60_000) break;
|
||||
sessionRetries += 1;
|
||||
say(`${reason}; starting a new EAS Simulator session in ${Math.round(delayMs / 1000)} s (${sessionRetries}/${SESSION_START_RETRIES})`);
|
||||
options.signal?.throwIfAborted();
|
||||
// Asynchronous and cancellable, so targets capturing beside this one keep running and Ctrl+C stops the wait.
|
||||
if (options.sleep) options.sleep(delayMs);
|
||||
else await new Promise<void>((resolve, reject) => {
|
||||
const timer = setTimeout(() => { options.signal?.removeEventListener("abort", abort); resolve(); }, delayMs);
|
||||
const abort = () => { clearTimeout(timer); reject(options.signal!.reason); };
|
||||
options.signal?.addEventListener("abort", abort, { once: true });
|
||||
});
|
||||
options.signal?.throwIfAborted();
|
||||
await rm(dotenvPath, { force: true });
|
||||
sessionName = sessionNameFor(sessionRetries);
|
||||
sessionStart = undefined;
|
||||
startSession({ timeoutMs: startTimeoutMs });
|
||||
startError = await sessionStart;
|
||||
handoff = await readSimulatorDotenvHandoff(dotenvPath);
|
||||
}
|
||||
// Every session EAS ended is its own failure to start, never a question of ownership.
|
||||
if (ended) throw new CiError({ code: "SIMULATOR_START_FAILED", stage: "session",
|
||||
message: `EAS could not start a simulator session: ${endedSessions.length === 1 ? `session ${ended.sessionId} ended (${ended.status}) before it was ready`
|
||||
: `${endedSessions.length} sessions ended before they were ready (the last, ${ended.sessionId}, ${ended.status})`}.`,
|
||||
nextAction: "Rerun Explore. If sessions keep failing to start, check the EAS Simulator status and the sessions' logs on expo.dev.",
|
||||
retryable: true, details: { attempts: sessionRetries + 1, endedSessions, ...(startError ? { startFailure: simulatorStartFailure(startError, [options.expoToken]) } : {}) },
|
||||
...(startError ? { cause: startError } : {}) });
|
||||
const startError = await sessionStart;
|
||||
const handoff = await readSimulatorDotenvHandoff(dotenvPath);
|
||||
const startSecrets = [options.expoToken, ...(handoff.connection ? [handoff.connection.daemonAuthToken] : [])];
|
||||
const startFailure = startError ? simulatorStartFailure(startError, startSecrets) : undefined;
|
||||
if (handoff.sessionId) {
|
||||
@@ -732,8 +638,6 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
|
||||
if (!handoff.connection) throw new Error("Simulator handoff is missing its controller connection");
|
||||
connection = handoff.connection;
|
||||
await rm(dotenvPath, { force: true });
|
||||
if (options.platform === "ios") controlActions = simulatorControlActions(sessionEas, sessionId);
|
||||
if (!controlActions.has("appearance.set")) narrowToArgentScheme();
|
||||
}
|
||||
const controllerConfig = join(simulatorProject, "agent-device.json");
|
||||
await writeFile(controllerConfig, "{}\n", { flag: "wx", mode: 0o400 });
|
||||
@@ -761,22 +665,14 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
|
||||
say(`installing the app on session ${sessionId}`);
|
||||
runner({ command: controllerCommand, args: ["install", localApp, "--session", CONTROLLER_SESSION, ...deviceArgs({ platform: options.platform, deviceModel: options.device }),
|
||||
"--platform", options.platform, "--json"], cwd: simulatorProject, environment: controllerEnvironment, timeoutMs: 15 * 60_000 });
|
||||
// Before any link opens, as a local capture does with simctl: the app's own links then open without the prompt.
|
||||
if (sessionId && scheme) {
|
||||
const approved = approveSessionUrlSchemes(sessionEas, sessionId, controlActions, options.bundleId, [scheme]);
|
||||
if (approved.length) say(`approved ${approved.map(item => `${item}://`).join(", ")} links on session ${sessionId}`);
|
||||
}
|
||||
}
|
||||
if (options.devicePose) {
|
||||
// A fold relights the other panel and resizes the window. It comes before the app is first opened or read, so the
|
||||
// controller's accessibility reader starts on the lit panel: Argent's, started on the outer panel, can stay there.
|
||||
say(`folding ${options.device} ${options.devicePose}`);
|
||||
const target = deviceArgs({ platform: options.platform, deviceModel: options.device, ...(localDevice() ? { provider: "local-simulator" as const, controllerDeviceId: localDevice()! } : {}) });
|
||||
// agent-device reads the hinge back after folding and fails to (locally and on EAS); its display is checked instead.
|
||||
const easAgentDevice = !!sessionId && controller === "agent-device";
|
||||
const fold = () => runner({ command: controllerCommand, args: ["fold", options.devicePose!, "--session", CONTROLLER_SESSION, ...target, "--platform", options.platform, "--json"],
|
||||
cwd: simulatorProject, environment: controllerEnvironment, timeoutMs: 2 * 60_000, ...(localSimulator || easAgentDevice ? { allowFailure: true } : {}) });
|
||||
const pause = options.sleep ?? (milliseconds => { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds); });
|
||||
cwd: simulatorProject, environment: controllerEnvironment, timeoutMs: 2 * 60_000, ...(localSimulator ? { allowFailure: true } : {}) });
|
||||
if (localSimulator && controller === "argent") {
|
||||
// Argent folds without a session and checks the fold against its own reader; this machine also checks the display.
|
||||
fold();
|
||||
@@ -794,59 +690,6 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
|
||||
...(options.sleep ? { sleep: options.sleep } : {}) })) throw new CiError({ code: "CONTROLLER_FOLD_UNVERIFIED", stage: "session",
|
||||
message: `${options.device} did not show the ${options.devicePose} display after folding: ${(folded.stderr || folded.stdout).trim().split("\n").at(-1) ?? ""}`.trim(),
|
||||
nextAction: "Rerun; if it persists, check that this Xcode's simulator supports folding the device." });
|
||||
} else if (easAgentDevice && sessionId) {
|
||||
// On EAS, agent-device also folds only inside a session, so the app opens first. The first fold of a fresh session
|
||||
// can leave the panel it lights black, as it does for Argent: the controller then reads the old panel and a
|
||||
// relaunch draws nothing. The display is the check, through the controller's own screenshot: in the pose's shape
|
||||
// and drawn. If it is not, SpringBoard is restarted, the app reopened and the device folded again, once.
|
||||
const open = (relaunch: boolean) => runner({ command: controllerCommand, args: ["open", options.bundleId, ...(relaunch ? ["--relaunch"] : []), "--session", CONTROLLER_SESSION,
|
||||
...target, "--platform", options.platform, "--json"], cwd: simulatorProject, environment: controllerEnvironment, timeoutMs: 15 * 60_000 });
|
||||
const shown = async () => {
|
||||
if (options.devicePose !== "open" && options.devicePose !== "closed") return true;
|
||||
const file = join(simulatorProject, "pose.png");
|
||||
// The display relights and resizes over a moment after the hinge moves.
|
||||
for (let attempt = 0; attempt < 10; attempt += 1) {
|
||||
if (attempt) pause(1_000);
|
||||
runner({ command: controllerCommand, args: ["screenshot", file, "--session", CONTROLLER_SESSION, ...target, "--platform", options.platform, "--json"],
|
||||
cwd: simulatorProject, environment: controllerEnvironment, timeoutMs: 2 * 60_000, allowFailure: true });
|
||||
const png = await readFile(file).catch(() => Buffer.alloc(0));
|
||||
await rm(file, { force: true });
|
||||
const size = pngSize(png);
|
||||
if (size && (options.devicePose === "open" ? size.width > size.height : size.height > size.width) && !solidColour(png)) return true;
|
||||
}
|
||||
return false;
|
||||
};
|
||||
open(false);
|
||||
fold();
|
||||
if (!await shown()) {
|
||||
if (!controlActions.has("springboard.restart")) throw new CiError({ code: "CONTROLLER_FOLD_UNVERIFIED", stage: "session",
|
||||
message: `${options.device} did not show the ${options.devicePose} display after folding.`, nextAction: "Rerun the capture on a new session." });
|
||||
say(`${options.device} did not draw the ${options.devicePose} display after the fold; restarting SpringBoard and folding ${options.devicePose} again`);
|
||||
simulatorControl(sessionEas, sessionId, "springboard.restart");
|
||||
pause(8_000);
|
||||
open(true);
|
||||
fold();
|
||||
if (!await shown()) throw new CiError({ code: "CONTROLLER_READER_STUCK", stage: "session",
|
||||
message: `${options.device} did not draw the ${options.devicePose} display after folding, nor after SpringBoard was restarted and it was folded again.`,
|
||||
nextAction: "Rerun the capture; if it keeps happening, report it to Explore with the session's link." });
|
||||
}
|
||||
} else if (controller === "argent" && sessionId && controlActions.has("springboard.restart")) {
|
||||
// The bridge has already reset Argent's device helpers once when its reader stayed on the dark panel. On EAS the
|
||||
// tool-server cannot be restarted, so the next step is SpringBoard, then the same fold and check again.
|
||||
try { fold(); }
|
||||
catch (error) {
|
||||
if (toCiError(error).code !== "CONTROLLER_FOLD_UNVERIFIED") throw error;
|
||||
say(`Argent kept reading the other panel after the fold; restarting SpringBoard and folding ${options.devicePose} again`);
|
||||
simulatorControl(sessionEas, sessionId, "springboard.restart");
|
||||
pause(8_000);
|
||||
try { fold(); }
|
||||
catch (retry) {
|
||||
if (toCiError(retry).code !== "CONTROLLER_FOLD_UNVERIFIED") throw retry;
|
||||
throw new CiError({ code: "CONTROLLER_READER_STUCK", stage: "session",
|
||||
message: `Argent's accessibility reader kept reading the panel the fold turned off, after its device helpers were reset and SpringBoard was restarted.`,
|
||||
nextAction: "Rerun the capture; if it keeps happening, report it to Explore: this session's Argent tool-server needs a restart that EAS cannot do yet.", cause: retry });
|
||||
}
|
||||
}
|
||||
} else fold();
|
||||
}
|
||||
runtimeStage = "runtime";
|
||||
@@ -857,28 +700,9 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
|
||||
// (APP_NOT_READY). On this machine the capture runs that reader, so it recovers in two steps, each followed by one more
|
||||
// open: a fresh tool-server, whose reader starts on the lit panel; then, as XcodeBuildMCP#537 found for this panel,
|
||||
// SpringBoard restarted as well. The bridge's cached view of the device goes with the old server.
|
||||
// On EAS the tool-server is the session's and must never be stopped, so the recovery there resets Argent's device
|
||||
// helpers (reset-reader), then restarts SpringBoard as well, and then gives up with a reason rather than retrying.
|
||||
const easArgentRecovery = !local && controller === "argent" && !!sessionId && options.platform === "ios";
|
||||
for (let recovery = 0; ; recovery += 1) try { runtime = collect(); break; }
|
||||
catch (error) {
|
||||
if (toCiError(error).code !== "APP_NOT_READY") throw error;
|
||||
if (easArgentRecovery && sessionId) {
|
||||
if (recovery === 2 || recovery === 1 && !controlActions.has("springboard.restart")) throw new CiError({ code: "CONTROLLER_READER_STUCK", stage: "session",
|
||||
message: "Argent's accessibility reader kept reading the panel the fold turned off, after its device helpers were reset"
|
||||
+ `${recovery === 2 ? " and SpringBoard was restarted" : ""}.`,
|
||||
nextAction: "Rerun the capture; if it keeps happening, report it to Explore: this session's Argent tool-server needs a restart that EAS cannot do yet.", cause: error });
|
||||
if (recovery === 1) {
|
||||
say("Argent still did not read the app; restarting SpringBoard, then resetting Argent's device helpers and opening the app again");
|
||||
simulatorControl(sessionEas, sessionId, "springboard.restart");
|
||||
// SpringBoard takes a moment to come back, and sends the app to the background; the next open brings it back.
|
||||
(options.sleep ?? (milliseconds => { Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds); }))(8_000);
|
||||
} else say("Argent did not read the app after starting it; resetting Argent's device helpers and opening the app again");
|
||||
runner({ command: controllerCommand, args: ["reset-reader", "--session", CONTROLLER_SESSION, "--platform", options.platform, "--json"],
|
||||
cwd: simulatorProject, environment: controllerEnvironment, timeoutMs: 2 * 60_000 });
|
||||
continue;
|
||||
}
|
||||
if (!localArgent || recovery === 2) throw error;
|
||||
if (!localArgent || recovery === 2 || toCiError(error).code !== "APP_NOT_READY") throw error;
|
||||
say(recovery === 0 ? "Argent did not read the app after starting it; restarting Argent's tool-server and opening the app again"
|
||||
: "Argent still did not read the app; restarting SpringBoard and Argent's tool-server and opening the app again");
|
||||
stopLocalArgentServer(localArgent);
|
||||
@@ -915,11 +739,10 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
|
||||
const passes: CaptureBundle["outcomes"][] = [];
|
||||
const recordingTools = launchSetting === "off" ? undefined : options.recordingTools === undefined ? ffmpegRecordingTools() : options.recordingTools ?? undefined;
|
||||
for (const [index, colorScheme] of colorSchemes.entries()) {
|
||||
// Argent cannot switch the appearance yet (software-mansion/argent#1509): the host does, simctl or adb on this
|
||||
// machine and serve-sim on an EAS iOS session; elsewhere its single pass runs as the device starts.
|
||||
// Argent cannot switch the appearance yet (software-mansion/argent#1509): on EAS its single pass runs as the device
|
||||
// starts, and on this machine the host switches it.
|
||||
if (controller !== "argent") runner({ command: controllerCommand, args: [...appearanceArgs(colorScheme), "--session", CONTROLLER_SESSION, ...deviceArgs(runtime), "--platform", options.platform],
|
||||
cwd: simulatorProject, environment: controllerEnvironment, timeoutMs: 60_000 });
|
||||
else if (sessionId && controlActions.has("appearance.set")) simulatorControl(sessionEas, sessionId, "appearance.set", [colorScheme]);
|
||||
else if (localSimulator) setLocalSimulatorAppearance({ runner, udid: localSimulator, scheme: colorScheme, cwd: simulatorProject, environment: restrictedEnvironment });
|
||||
else if (localEmulator) setLocalEmulatorAppearance({ runner, serial: localEmulator, scheme: colorScheme, cwd: simulatorProject, environment: restrictedEnvironment });
|
||||
// A scheme change recreates the Android activity in place, and the sheets it re-presents lose their inset; a
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
import { isRecord } from "./common.js";
|
||||
|
||||
/** Runs the pinned EAS CLI with these arguments; throws when it exits non-zero unless `allowFailure` is set. */
|
||||
export type EasCommand = (args: string[], options?: { timeoutMs?: number; allowFailure?: boolean }) => { stdout: string; stderr?: string };
|
||||
|
||||
/**
|
||||
* The host actions an EAS Simulator iOS session offers through `eas simulator:control` (serve-sim's actions, 0.10.0 and
|
||||
* later for the ones Explore uses): an empty set when the session or the EAS CLI offers none, so a caller falls back to
|
||||
* what it did before them. The session is always named by id, never taken from a `.env.eas-simulator` beside it.
|
||||
*
|
||||
* These are a fallback: what the session's controller can do itself (agent-device or Argent: fold, appearance, a
|
||||
* reader reset) goes through the controller. Explore uses an action here only for what neither controller offers —
|
||||
* approving a link scheme, restarting SpringBoard, and Argent's appearance (software-mansion/argent#1509).
|
||||
*/
|
||||
export function simulatorControlActions(eas: EasCommand, sessionId: string): Set<string> {
|
||||
try {
|
||||
const listed = eas(["simulator:control", "--list", "--id", sessionId, "--json", "--non-interactive"], { timeoutMs: 2 * 60_000, allowFailure: true });
|
||||
const actions = JSON.parse(listed.stdout) as unknown;
|
||||
return new Set(isRecord(actions) ? Object.keys(actions) : []);
|
||||
} catch { return new Set(); }
|
||||
}
|
||||
|
||||
/** Runs one `eas simulator:control` action on the session; eas-cli fills in the device. Throws with EAS's reason. */
|
||||
export function simulatorControl(eas: EasCommand, sessionId: string, action: string, values: readonly string[] = []): void {
|
||||
// Values follow `--` so one that starts with a dash is never read as a flag.
|
||||
eas(["simulator:control", action, "--id", sessionId, "--json", "--non-interactive", "--", ...values], { timeoutMs: 2 * 60_000 });
|
||||
}
|
||||
|
||||
/**
|
||||
* Lets the app open its own links without iOS asking "Open in “App”?" first, like local captures do with simctl. A
|
||||
* session without the action keeps the controllers' prompt handling; http and https never prompt and are skipped.
|
||||
*/
|
||||
export function approveSessionUrlSchemes(eas: EasCommand, sessionId: string, actions: ReadonlySet<string>, bundleId: string, schemes: readonly string[]): string[] {
|
||||
if (!actions.has("app.approveUrlScheme")) return [];
|
||||
const approved: string[] = [];
|
||||
for (const scheme of new Set(schemes.map(value => value.toLowerCase()))) {
|
||||
if (scheme === "http" || scheme === "https" || !/^[a-z][a-z0-9+.-]*$/.test(scheme)) continue;
|
||||
simulatorControl(eas, sessionId, "app.approveUrlScheme", [bundleId, scheme]);
|
||||
approved.push(scheme);
|
||||
}
|
||||
return approved;
|
||||
}
|
||||
+11
-41
@@ -237,7 +237,17 @@ export function assertSimulatorSessionIdentity(
|
||||
) {
|
||||
throw new Error("eas simulator:get did not prove the exact expected simulator session");
|
||||
}
|
||||
if (!sessionProjectProven(value, expectedSessionId, expectedProject)) {
|
||||
// eas-cli 22.4.0 omits the `app` record; its `deviceRunSessionUrl` still binds the session
|
||||
// to one exact owner and slug, so accept either proof but never neither.
|
||||
const expectedSessionUrl = `https://expo.dev/accounts/${expectedProject.owner}`
|
||||
+ `/projects/${expectedProject.slug}/simulator-sessions/${expectedSessionId}`;
|
||||
const projectProven = isRecord(value.app)
|
||||
? value.app.id === expectedProject.projectId
|
||||
&& value.app.slug === expectedProject.slug
|
||||
&& isRecord(value.app.ownerAccount)
|
||||
&& value.app.ownerAccount.name === expectedProject.owner
|
||||
: value.deviceRunSessionUrl === expectedSessionUrl;
|
||||
if (!projectProven) {
|
||||
throw new Error("eas simulator:get did not prove the exact expected simulator session");
|
||||
}
|
||||
if (expectedConnection && !remoteConfigMatches(value.remoteConfig, expectedConnection)) {
|
||||
@@ -245,46 +255,6 @@ export function assertSimulatorSessionIdentity(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* eas-cli 22.4.0 omits the `app` record; its `deviceRunSessionUrl` still binds the session to one exact owner and
|
||||
* slug, so either proof is accepted but never neither.
|
||||
*/
|
||||
function sessionProjectProven(value: Record<string, unknown>, sessionId: string, project: RepackProfile["projectIdentity"]): boolean {
|
||||
const expectedSessionUrl = `https://expo.dev/accounts/${project.owner}/projects/${project.slug}/simulator-sessions/${sessionId}`;
|
||||
return isRecord(value.app)
|
||||
? value.app.id === project.projectId && value.app.slug === project.slug && isRecord(value.app.ownerAccount) && value.app.ownerAccount.name === project.owner
|
||||
: value.deviceRunSessionUrl === expectedSessionUrl;
|
||||
}
|
||||
|
||||
/**
|
||||
* The status (ERRORED or STOPPED) of a session `eas simulator:get` shows EAS ended before Explore could use it, when it
|
||||
* is provably this capture's own: the exact id, name, type, platform and project. Only such a session is replaced by a
|
||||
* new one; anything less certain (undefined here) stays a handoff failure.
|
||||
*/
|
||||
export function endedOwnSimulatorSession(stdout: string, expected: { sessionId: string; sessionName: string; project: RepackProfile["projectIdentity"];
|
||||
type: "agent-device" | "argent"; platform: Platform }): "ERRORED" | "STOPPED" | undefined {
|
||||
let value: unknown;
|
||||
try { value = JSON.parse(stdout); } catch { return undefined; }
|
||||
return isRecord(value) && value.id === expected.sessionId && value.name === expected.sessionName && value.type === expected.type
|
||||
&& value.platform === expected.platform.toUpperCase() && (value.status === "ERRORED" || value.status === "STOPPED")
|
||||
&& sessionProjectProven(value, expected.sessionId, expected.project) ? value.status : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* This project's sessions with exactly this name that EAS may still be starting or running, from
|
||||
* `eas simulator:list --json`: their ids when every one is provably this project's, or undefined when the listing
|
||||
* cannot be read or a session by that name cannot be proven Explore's, so a caller never assumes none exist.
|
||||
*/
|
||||
export function liveSimulatorSessionsNamed(stdout: string, sessionName: string, project: RepackProfile["projectIdentity"]): string[] | undefined {
|
||||
let value: unknown;
|
||||
try { value = JSON.parse(stdout); } catch { return undefined; }
|
||||
if (!isRecord(value) || !Array.isArray(value.sessions)) return undefined;
|
||||
const live = new Set(["NEW", "QUEUED", "STARTING", "IN_PROGRESS"]);
|
||||
const named = value.sessions.filter((session): session is Record<string, unknown> => isRecord(session) && session.name === sessionName && live.has(String(session.status)));
|
||||
if (named.some(session => typeof session.id !== "string" || !/^[A-Za-z0-9._-]{1,256}$/.test(session.id) || !sessionProjectProven(session, session.id, project))) return undefined;
|
||||
return named.map(session => session.id as string);
|
||||
}
|
||||
|
||||
/** The session's published controller endpoint is the one Explore holds: agent-device's daemon, or Argent's tool-server. */
|
||||
function remoteConfigMatches(remoteConfig: unknown, connection: SimulatorConnection): boolean {
|
||||
if (!isRecord(remoteConfig)) return false;
|
||||
|
||||
+7
-15
@@ -474,8 +474,7 @@ export async function runDoctor(options: DoctorOptions): Promise<DoctorReport> {
|
||||
checks.push(config.mode === "agent"
|
||||
? { step: 3, id: "mode", status: "pass", message: `Agent mode with ${config.agent!.provider} ${config.agent!.model}. Capture navigation uses the model and is billed to your ${config.agent!.provider} account.` }
|
||||
: { step: 3, id: "mode", status: "pass", message: "Deterministic mode: capture replays config.yaml without a model, so it needs no API key and has no AI charges." });
|
||||
const argentTargets = runTargets(config, { controller: options.controller }).filter(target => target.capture.controller === "argent");
|
||||
if (argentTargets.length) checks.push(argentCheck(environment, argentTargets.some(target => target.app.platform === "android" && target.capture.simulator !== "local")));
|
||||
if (runTargets(config, { controller: options.controller }).some(target => target.capture.controller === "argent")) checks.push(argentCheck(environment));
|
||||
if (config.capture.launch !== "off") {
|
||||
const ffmpeg = run("ffmpeg", ["-version"], project);
|
||||
checks.push(ffmpeg.status === 0
|
||||
@@ -631,20 +630,13 @@ export function summarizeCaptureCheck(plan: SourceCapturePlan, bundle: CaptureBu
|
||||
* Capture the committed HEAD the way the baseline workflow does, with the local EAS login. This is
|
||||
* the only doctor step that starts an EAS build and a simulator session.
|
||||
*/
|
||||
/**
|
||||
* Argent fetches its pinned release on first use, and cannot switch the appearance itself (software-mansion/argent#1509):
|
||||
* the host does, through `simulator:control` on an iOS EAS session or simctl and adb on this Mac. Only an Android EAS
|
||||
* session has no host to ask, so its captures record one appearance. agent-device, the default, is not reported.
|
||||
*/
|
||||
function argentCheck(environment: NodeJS.ProcessEnv, androidOnEas: boolean): DoctorCheck {
|
||||
/** An Argent capture records one appearance, and fetches the pinned Argent release on first use. agent-device, the default, is not reported. */
|
||||
function argentCheck(environment: NodeJS.ProcessEnv): DoctorCheck {
|
||||
const cached = controllerCached("argent", environment);
|
||||
const release = `Device controller: Argent ${ARGENT_VERSION} (${cached ? "cached on this machine" : "fetched from npm on the first capture, about 27 MB"}). `;
|
||||
return androidOnEas
|
||||
? { step: 3, id: "controller", status: "warn", code: "CONTROLLER_APPEARANCE_FIXED",
|
||||
message: `${release}Argent cannot switch the appearance on an Android EAS Simulator session yet (software-mansion/argent#1509), so those captures record one appearance: the app's forced one, else light.`,
|
||||
nextAction: "Nothing to do unless you need dark-mode screenshots on Android; use agent-device (the default) for those." }
|
||||
: { step: 3, id: "controller", status: "pass",
|
||||
message: `${release}The simulator's host switches the appearance, so every appearance the config asks for is captured.` };
|
||||
return { step: 3, id: "controller", status: "warn", code: "CONTROLLER_APPEARANCE_FIXED",
|
||||
message: `Device controller: Argent ${ARGENT_VERSION} (${cached ? "cached on this machine" : "fetched from npm on the first capture, about 27 MB"}). `
|
||||
+ "Argent cannot switch the simulator's appearance yet (software-mansion/argent#1509), so each capture records one appearance: the app's forced one, else light.",
|
||||
nextAction: "Nothing to do unless you need dark-mode screenshots; use agent-device (the default) for those." };
|
||||
}
|
||||
|
||||
export async function runCaptureCheck(options: { project: string; output: string; platform?: ExplorePlatform; controller?: string | undefined; simulator?: string | undefined; repack?: string | undefined; target?: string | undefined; environment?: NodeJS.ProcessEnv; runner?: CommandRunner; progress?: Progress }): Promise<CaptureCheckResult> {
|
||||
|
||||
+2
-2
@@ -90,9 +90,9 @@ const flagKinds: Record<string, Record<string, "value" | "boolean">> = {
|
||||
|
||||
|
||||
|
||||
"explore:binary": { archive:"value", output:"value", platform:"value", controller:"value", simulator:"value", device:"value", "bundle-id":"value", "launch-url":"value", hints:"value", "allow-destructive":"value",
|
||||
"explore:binary": { archive:"value", output:"value", platform:"value", controller:"value", device:"value", "bundle-id":"value", "launch-url":"value", hints:"value", "allow-destructive":"value",
|
||||
"max-duration-minutes":"value", "max-screens":"value", "max-actions":"value", provider:"value", model:"value", owner:"value", project:"value",
|
||||
upload:"boolean", "no-upload":"boolean", "expires-in":"value", alias:"value", "no-open":"boolean", port:"value" },
|
||||
upload:"boolean", "no-upload":"boolean", "expires-in":"value", alias:"value" },
|
||||
"explore:session": { session:"value", "env-file":"value", "bundle-id":"value", "app-name":"value", "app-version":"value", output:"value", platform:"value", controller:"value", device:"value", "launch-url":"value", hints:"value",
|
||||
"allow-destructive":"value", "max-duration-minutes":"value", "max-screens":"value", "max-actions":"value", provider:"value", model:"value", owner:"value", project:"value",
|
||||
upload:"boolean", "expires-in":"value", alias:"value", "no-open":"boolean", port:"value" },
|
||||
|
||||
@@ -39,17 +39,12 @@ export async function exploreBinary(): Promise<void> {
|
||||
const platform = flag("platform") === undefined ? undefined : oneOf("platform", ["ios", "android"] as const);
|
||||
const provider = flag("provider") === undefined ? undefined : oneOf("provider", ["anthropic", "openai"] as const);
|
||||
const controller = flag("controller") === undefined ? undefined : oneOf("controller", ["agent-device", "argent"] as const);
|
||||
const simulator = flag("simulator") === undefined ? "eas" : oneOf("simulator", ["eas", "local"] as const);
|
||||
// On EAS Simulator the report is hosted unless --no-upload; locally it opens in the Viewer unless --upload, so a
|
||||
// local run needs no Expo account at all.
|
||||
const upload = simulator === "local" ? has("upload") : !has("no-upload");
|
||||
const port = flag("port") === undefined ? undefined : nonNegativeInteger("port");
|
||||
const started = Date.now();
|
||||
const say = (message: string) => { process.stderr.write(`[explore ${Math.round((Date.now() - started) / 1000)}s] ${message}\n`); };
|
||||
const allowDestructive = flags("allow-destructive").flatMap(value => value.split(",")).map(value => value.trim()).filter(Boolean);
|
||||
if (upload) await assertHostingExport();
|
||||
if (!has("no-upload")) await assertHostingExport();
|
||||
const result = await runBinaryExploration({
|
||||
archive: resolve(process.cwd(), archive), output: outputDirectory, progress: say, simulator,
|
||||
archive: resolve(process.cwd(), archive), output: outputDirectory, progress: say,
|
||||
...(platform ? { platform } : {}), ...(provider ? { provider } : {}), ...(controller ? { controller } : {}),
|
||||
...(flag("device") ? { device: flag("device")! } : {}), ...(flag("bundle-id") ? { bundleId: flag("bundle-id")! } : {}),
|
||||
...(flag("launch-url") ? { launchUrl: flag("launch-url")! } : {}), ...(flag("hints") ? { hints: flag("hints")! } : {}),
|
||||
@@ -63,16 +58,15 @@ export async function exploreBinary(): Promise<void> {
|
||||
const report = await writeExplorationReport(result, join(outputDirectory, "report"));
|
||||
await keepReports(async () => [{ platform: result.archive.platform, zip: await zipReportDirectory(report.reportPath) }]);
|
||||
let hosted: Awaited<ReturnType<typeof deployExplorationReport>> | undefined;
|
||||
if (upload) {
|
||||
if (!has("no-upload")) {
|
||||
say("hosting the report on EAS Hosting");
|
||||
const owner = result.session.owner || flag("owner");
|
||||
hosted = await deployExplorationReport({ reportPath: report.reportPath, platform: result.archive.platform, project: flag("project") ?? DEFAULT_BINARY_PROJECT, ...(owner ? { owner } : {}), expiresAfterDays, ...stableLinkOptions() });
|
||||
hosted = await deployExplorationReport({ reportPath: report.reportPath, platform: result.archive.platform, project: flag("project") ?? DEFAULT_BINARY_PROJECT, owner: result.session.owner, expiresAfterDays, ...stableLinkOptions() });
|
||||
say(`report: ${hosted.previewUrl}${hosted.expiresAt ? ` (expires ${hosted.expiresAt})` : ""}`);
|
||||
}
|
||||
const summary = { ok: true,
|
||||
app: { name: result.archive.appName, bundleId: result.archive.bundleId, platform: result.archive.platform, ...(result.archive.version ? { version: result.archive.version } : {}) },
|
||||
archive: { path: result.archive.path, kind: result.archive.kind, sha256: result.archive.sha256, bytes: result.archive.bytes },
|
||||
device: { model: result.runtime.deviceModel, osVersion: result.runtime.osVersion }, session: { id: result.session.id, simulator, ...(simulator === "eas" ? { owner: result.session.owner, project: result.session.project } : {}) },
|
||||
device: { model: result.runtime.deviceModel, osVersion: result.runtime.osVersion }, session: { id: result.session.id, owner: result.session.owner, project: result.session.project },
|
||||
model: result.model, exploration: { stopReason: result.exploration.stopReason, ...(result.exploration.summary ? { summary: result.exploration.summary } : {}),
|
||||
screens: result.exploration.screens, observations: result.exploration.observations, actions: result.exploration.actions, durationMs: result.durationMs },
|
||||
map: result.mapPath, report: report.reportPath, ...(hosted ? { url: hosted.previewUrl, expiresAt: hosted.expiresAt, deploymentUrl: hosted.deploymentUrl, ...(hosted.aliasUrl ? { aliasUrl: hosted.aliasUrl } : {}) } : {}),
|
||||
@@ -81,11 +75,7 @@ export async function exploreBinary(): Promise<void> {
|
||||
console.log(`${summary.app.name} (${summary.app.bundleId}, ${summary.app.platform}) explored on ${summary.device.model} ${summary.device.osVersion}: ${summary.exploration.screens} screens, ${summary.exploration.actions} actions, stopped because ${summary.exploration.stopReason}.`);
|
||||
if (hosted) console.log(`Hosted report: ${hosted.previewUrl}${hosted.expiresAt ? ` (expires ${hosted.expiresAt})` : ""}`);
|
||||
console.log(`Local report: ${report.reportPath}`);
|
||||
if (simulator === "eas" || hosted || has("no-open")) { console.log(`Next: ${summary.next.join(" | ")}`); return; }
|
||||
const viewer = await startViewerServer({ root: outputDirectory, ...(port === undefined ? {} : { port }) });
|
||||
console.log(`Viewer: ${viewer.url} (Ctrl+C to stop)`);
|
||||
openViewerInBrowser(viewer.url);
|
||||
await waitForViewerShutdown(viewer);
|
||||
console.log(`Next: ${summary.next.join(" | ")}`);
|
||||
}
|
||||
|
||||
/** `--env-file` wins; otherwise the `.env.eas-simulator` that `eas simulator:start --out-config-type dotenv` wrote in the current directory, unless the environment already carries a session. */
|
||||
|
||||
+6
-9
@@ -19,8 +19,8 @@ const GET_STARTED = `Get started (run these in the Expo app's directory):
|
||||
(captures the committed HEAD like the baseline workflow, with your eas login, and reports each route)
|
||||
capture [--base REF] [--head REF | --committed] [--target ID | --platform ios|android] [--parallel N] [--scope all|changes]
|
||||
[--controller agent-device|argent] [--simulator eas|local] [--repack eas|local] [--upload [--expires-in 7d|30d|never]] [--no-open] [--no-cache] [--output DIRECTORY] [--project DIRECTORY]
|
||||
(on this machine: checks out both commits in temporary worktrees, captures them with your eas login (in agent
|
||||
mode, also your local claude or codex login), and opens the report; the head is HEAD with your uncommitted changes, as eas build
|
||||
(on this machine: checks out both commits in temporary worktrees, captures them with your eas login and your
|
||||
local claude or codex login, and opens the report; the head is HEAD with your uncommitted changes, as eas build
|
||||
uploads them (--committed, or cli.requireCommit in eas.json, leaves them out); the base defaults to where HEAD
|
||||
left the default branch;
|
||||
without .expo-explore/config.yaml it uses the defaults setup would write;
|
||||
@@ -43,22 +43,19 @@ const GET_STARTED = `Get started (run these in the Expo app's directory):
|
||||
(hosts reports already on this machine on EAS Hosting behind one link, with your eas login: one per platform
|
||||
of the same review, from capture:review --output or a downloaded explore-review artifact, or one explore:binary report)`;
|
||||
|
||||
const BINARY = `Prebuilt apps (no source needed; runs with your local claude or codex login):
|
||||
explore:binary <app.apk | app.app | app.tar.gz | simulator .ipa> [--output DIRECTORY] [--simulator eas|local] [--no-upload] [--json]
|
||||
const BINARY = `Prebuilt apps (no source needed; runs on EAS Simulator with your local claude or codex login):
|
||||
explore:binary <app.apk | app.app | app.tar.gz | simulator .ipa> [--output DIRECTORY] [--no-upload] [--json]
|
||||
(installs the archive in a fresh EAS Simulator session, lets the model explore it, writes a map
|
||||
and report under --output, hosts the report on EAS Hosting, and prints the link)
|
||||
--simulator local runs it on a simulator or emulator it starts on this machine instead, with no EAS login,
|
||||
and opens the report in the local Viewer (--upload hosts it instead, --no-open skips the Viewer, --port N);
|
||||
iOS needs Xcode, Android the SDK (ANDROID_HOME) with platform-tools, cmdline-tools, the emulator and a system image for this Mac
|
||||
Flags, all optional: --device NAME --bundle-id ID --launch-url URL --hints "what to focus on"
|
||||
--controller agent-device|argent (the device controller; agent-device by default)
|
||||
--controller agent-device|argent (the session's device controller; agent-device by default)
|
||||
(a sign-in in --hints is written as {{secret:NAME}}: Explore types the value of the environment variable NAME,
|
||||
and the model and the report only see the reference)
|
||||
--max-duration-minutes N --max-screens N --max-actions N --provider anthropic|openai --model ID
|
||||
--owner ACCOUNT --project SLUG --expires-in 7d|30d|never --allow-destructive "Label,Other label"
|
||||
--alias NAME (one EAS Hosting host per app that always serves the newest run; with EXPLORE_PREVIEW_TOKEN
|
||||
set to a fixed 32-character token, the hosted link is the same every run)
|
||||
(iOS needs a simulator build; a device .ipa and Android .aab are rejected before any device starts)
|
||||
(iOS needs a simulator build; a device .ipa and Android .aab are rejected before any session starts)
|
||||
explore:session [SESSION_ID] [--bundle-id ID] [--output DIRECTORY] [--upload] [--json]
|
||||
(explores an app that is already installed on an EAS Simulator session you started — run it where
|
||||
"eas simulator:start --type agent-device --out-config-type dotenv" (or --type argent) wrote .env.eas-simulator,
|
||||
|
||||
@@ -577,7 +577,7 @@ export async function deployExplorationReport(options: ExplorationDeployOptions)
|
||||
message: "An EAS login is required to host the report", nextAction: "Run `eas login` or set EXPO_TOKEN, then rerun with --upload." });
|
||||
if (!/^[a-z0-9][a-z0-9-]{0,38}[a-z0-9]$/.test(options.project)) throw previewError("PREVIEW_PROJECT_INVALID", `Invalid EAS project slug: ${options.project}`, "Pass --project as a lowercase slug such as expo-explore.");
|
||||
if (options.alias !== undefined && !HOSTING_ALIAS.test(options.alias)) throw previewError("PREVIEW_ALIAS_INVALID", `Invalid EAS Hosting alias: ${options.alias}`, "Pass --alias as a lowercase slug such as bluesky.");
|
||||
if (options.token !== undefined && !HOSTED_TOKEN.test(options.token)) throw previewError("PREVIEW_TOKEN_INVALID", "EXPLORE_PREVIEW_TOKEN must be 32 characters of a-z and 2-7.", "Generate one with `LC_ALL=C tr -dc a-z2-7 </dev/urandom | head -c 32` and set EXPLORE_PREVIEW_TOKEN, or unset it for a random token.");
|
||||
if (options.token !== undefined && !HOSTED_TOKEN.test(options.token)) throw previewError("PREVIEW_TOKEN_INVALID", "EXPLORE_PREVIEW_TOKEN must be 32 characters of a-z and 2-7.", "Generate one with `openssl rand 20 | base32 | tr A-Z a-z` and set EXPLORE_PREVIEW_TOKEN, or unset it for a random token.");
|
||||
const exportPath = resolve(options.exportPath ?? PREVIEW_EXPORT_PATH);
|
||||
await assertExport(exportPath);
|
||||
let zip: Uint8Array;
|
||||
@@ -765,40 +765,16 @@ async function verifyDeployment(check: { origin: string; token: string; reports:
|
||||
"Check EAS Hosting availability and rerun the deploy job.", { retryable: true, cause: error });
|
||||
}
|
||||
};
|
||||
// What the token serves differs from what was deployed: a listing or report that does not match, or undefined.
|
||||
const mismatch = async (): Promise<CiError | undefined> => {
|
||||
for (const expected of check.reports) {
|
||||
const report = await get(`/p/${check.token}/report.zip${expected.query}`);
|
||||
const bytes = report.status === 200 ? new Uint8Array(await report.arrayBuffer()) : new Uint8Array();
|
||||
if (report.status !== 200 || bytes.byteLength !== expected.bytes || createHash("sha256").update(bytes).digest("hex") !== expected.sha256) {
|
||||
return deployError("PREVIEW_VERIFY_FAILED", "The hosted preview did not serve the exact report that was deployed.",
|
||||
"Rerun the deploy job; the deployment's sealed key or ciphertext did not match.", { details: { status: report.status, report: expected.query } });
|
||||
}
|
||||
}
|
||||
if (check.listing !== undefined) {
|
||||
const list = await get(`/p/${check.token}/reports.json`);
|
||||
const body = list.status === 200 ? await list.text() : "";
|
||||
if (list.status !== 200 || body !== check.listing) return deployError("PREVIEW_VERIFY_FAILED", "The hosted preview did not list the targets that were deployed.",
|
||||
"Rerun the deploy job; the deployment's report listing did not match.", { details: { status: list.status } });
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
const started = check.now();
|
||||
let liveAfterMs = 0;
|
||||
for (;;) {
|
||||
// A browser's request: the token page negotiates, and anything that does not ask for HTML gets the Markdown index.
|
||||
const shell = await get(`/p/${check.token}`, "text/html");
|
||||
const serving = shell.status === 200 && (shell.headers.get("content-type") ?? "").startsWith("text/html");
|
||||
// An alias with a fixed token (the example report) serves the token page from the deployment it still points at, so
|
||||
// it has moved only once it serves this deployment's listing and reports as well.
|
||||
const stale = serving && check.alias ? await mismatch() : undefined;
|
||||
if (serving && !stale) { liveAfterMs = check.now() - started; break; }
|
||||
if (shell.status === 200 && (shell.headers.get("content-type") ?? "").startsWith("text/html")) { liveAfterMs = check.now() - started; break; }
|
||||
const waitedMs = check.now() - started;
|
||||
if (waitedMs > check.timeoutMs) {
|
||||
// An alias that does not serve the token page yet still points at an earlier deployment; the deployment itself not serving is a failed deployment.
|
||||
if (check.alias) throw deployError("PREVIEW_ALIAS_BEHIND", stale
|
||||
? `The alias ${check.origin} still serves an earlier deployment ${Math.round(waitedMs / 1000)} s after eas deploy returned.`
|
||||
: `The alias ${check.origin} still answers HTTP ${shell.status} ${Math.round(waitedMs / 1000)} s after eas deploy returned.`,
|
||||
if (check.alias) throw deployError("PREVIEW_ALIAS_BEHIND", `The alias ${check.origin} still answers HTTP ${shell.status} ${Math.round(waitedMs / 1000)} s after eas deploy returned.`,
|
||||
"Nothing to do: the alias catches up on its own, and the next push verifies it again.", { retryable: true, details: { origin: check.origin, status: shell.status, waitedMs } });
|
||||
throw deployError("PREVIEW_VERIFY_FAILED", `The hosted preview did not become available (HTTP ${shell.status}).`,
|
||||
"Rerun the deploy job; if the deployment keeps failing verification, inspect it in the EAS Hosting dashboard.", { retryable: true, details: { origin: check.origin, status: shell.status, waitedMs } });
|
||||
@@ -809,8 +785,20 @@ async function verifyDeployment(check: { origin: string; token: string; reports:
|
||||
if (api.status !== 200 || !(api.headers.get("content-type") ?? "").startsWith("application/json")) {
|
||||
throw deployError("PREVIEW_VERIFY_FAILED", `The hosted preview did not answer the agent API (HTTP ${api.status}).`, "Rerun the deploy job; if the deployment keeps failing verification, inspect it in the EAS Hosting dashboard.", { retryable: true });
|
||||
}
|
||||
// The deployment itself serves exactly what was deployed or it failed; the alias was checked while it was polled.
|
||||
if (!check.alias) { const failure = await mismatch(); if (failure) throw failure; }
|
||||
for (const expected of check.reports) {
|
||||
const report = await get(`/p/${check.token}/report.zip${expected.query}`);
|
||||
const bytes = report.status === 200 ? new Uint8Array(await report.arrayBuffer()) : new Uint8Array();
|
||||
if (report.status !== 200 || bytes.byteLength !== expected.bytes || createHash("sha256").update(bytes).digest("hex") !== expected.sha256) {
|
||||
throw deployError("PREVIEW_VERIFY_FAILED", "The hosted preview did not serve the exact report that was deployed.",
|
||||
"Rerun the deploy job; the deployment's sealed key or ciphertext did not match.", { details: { status: report.status, report: expected.query } });
|
||||
}
|
||||
}
|
||||
if (check.listing !== undefined) {
|
||||
const list = await get(`/p/${check.token}/reports.json`);
|
||||
const body = list.status === 200 ? await list.text() : "";
|
||||
if (list.status !== 200 || body !== check.listing) throw deployError("PREVIEW_VERIFY_FAILED", "The hosted preview did not list the targets that were deployed.",
|
||||
"Rerun the deploy job; the deployment's report listing did not match.", { details: { status: list.status } });
|
||||
}
|
||||
const other = check.token.endsWith("a") ? `${check.token.slice(0, -1)}b` : `${check.token.slice(0, -1)}a`;
|
||||
// Errors name each probe by its shape: the near-miss token differs from the real one in its last character only.
|
||||
for (const [path, shape] of [["/", "/"], [`/p/${other}`, "/p/<wrong token>"], [`/p/${other}/report.zip`, "/p/<wrong token>/report.zip"],
|
||||
|
||||
@@ -3,4 +3,4 @@
|
||||
* controller (`--package-version`), the daemon health check, and the screenshot diff tool must
|
||||
* all be this version; each caller checks it by exact equality.
|
||||
*/
|
||||
export const AGENT_DEVICE_VERSION = "0.21.29-nightly.20261018.74";
|
||||
export const AGENT_DEVICE_VERSION = "0.21.28";
|
||||
@@ -21,7 +21,7 @@ export type ControllerName = "agent-device" | "argent";
|
||||
/** Each controller's npm release, the file Explore runs from it, and the integrity npm publishes for it. */
|
||||
export const CONTROLLER_PACKAGES: Record<ControllerName, { name: string; version: string; bin: string; integrity: string }> = {
|
||||
"agent-device": { name: "agent-device", version: AGENT_DEVICE_VERSION, bin: "bin/agent-device.mjs",
|
||||
integrity: "sha512-7+ajWLr0J+8iLZ9q11ERbj6U14mC20umBK5BQQdw5aERA79yeXc3Ze6KmtvnILnWjEtoVkYQsXQasL8RL6Uatw==" },
|
||||
integrity: "sha512-uGEENVhPzSpIACrVlt16O1mloODWJyAemTCT0boDb4L006JXN2rG747u1TRoQJudOpdP/Pm2urxNRHeECLMLfg==" },
|
||||
argent: { name: "@swmansion/argent", version: ARGENT_VERSION, bin: "dist/cli.js",
|
||||
integrity: "sha512-XXWlWZJlHKqnAvNx3RDhuiVFQOPqh5EDB76+mFAyqC2mutC6irzw03+M/6S/WQ+Dzz2IYOkEfOzQnOOdhrGgJg==" },
|
||||
};
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { Buffer } from "node:buffer";
|
||||
import { createRequire } from "node:module";
|
||||
import { inflateSync } from "node:zlib";
|
||||
import { STATUS_BAR_BAND_PERCENT } from "../contracts/capture.js";
|
||||
|
||||
@@ -8,22 +7,6 @@ export { STATUS_BAR_BAND_PERCENT };
|
||||
/** Decoded RGBA pixels of one frame, as pngjs returns them (four bytes per pixel, row by row). */
|
||||
export type DecodedFrame = { width: number; height: number; data: Buffer };
|
||||
|
||||
/**
|
||||
* Whether a screenshot is a single flat colour: a capture-protected screen (black on Android), or a display that is lit
|
||||
* but not drawn (an iPhone Duo's inner panel after its first fold on EAS). Every 97th pixel is enough to tell.
|
||||
*/
|
||||
export function solidColour(png: Buffer): boolean {
|
||||
let frame: DecodedFrame;
|
||||
try { frame = createRequire(import.meta.url.replace(/\?.*$/, ""))("pngjs").PNG.sync.read(png, { checkCRC: false }) as DecodedFrame; }
|
||||
catch { return false; }
|
||||
const { data } = frame;
|
||||
if (data.length < 4) return false;
|
||||
for (let offset = 0; offset + 3 < data.length; offset += 4 * 97) {
|
||||
if (data[offset] !== data[0] || data[offset + 1] !== data[1] || data[offset + 2] !== data[2]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a coordinate tap at normalized height `y` would act on a changed frame. Differences inside
|
||||
* the status-bar band are ignored only when the tap lands below the band: a tap inside it acts on
|
||||
|
||||
+9
-130
@@ -1491,19 +1491,8 @@ test("Esc closes the Inspector first, then deselects; arrows and hjkl walk the m
|
||||
await expect(selected).toHaveCount(0);
|
||||
await expect(page).toHaveURL(/\/map$/);
|
||||
|
||||
// Nothing selected: ↓ enters the map at its top, as → enters Screens at its first card; held, it
|
||||
// keeps walking down from there and stops where it is on release.
|
||||
await page.keyboard.down("ArrowDown");
|
||||
await expect(selected).toHaveCount(1);
|
||||
const entered = await selected.getAttribute("data-id");
|
||||
await expect.poll(() => selected.getAttribute("data-id"), { timeout: 4000 }).not.toBe(entered);
|
||||
await page.keyboard.up("ArrowDown");
|
||||
const walkedTo = await selected.getAttribute("data-id");
|
||||
await page.waitForTimeout(500);
|
||||
await expect(selected).toHaveAttribute("data-id", walkedTo!);
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(page.locator(".right-panel")).toHaveCount(0);
|
||||
await page.keyboard.press("Escape");
|
||||
// Nothing selected: the arrows are not map moves.
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await expect(selected).toHaveCount(0);
|
||||
|
||||
await page.locator(".map-canvas .react-flow__node-screen .screen-screenshot-target").first().click();
|
||||
@@ -1519,67 +1508,6 @@ test("Esc closes the Inspector first, then deselects; arrows and hjkl walk the m
|
||||
await expect(selected).toHaveAttribute("data-id", child!);
|
||||
});
|
||||
|
||||
test("a held key stops when Esc, another key or a dialog takes the keyboard; a menu keeps its own arrows", async ({ page }) => {
|
||||
await page.goto("/map");
|
||||
const selected = page.locator(".map-canvas .react-flow__node-screen.selected");
|
||||
const inspector = page.locator(".right-panel");
|
||||
const search = page.getByRole("dialog", { name: "Search Explore" });
|
||||
const viewport = page.locator(".map-canvas .react-flow__viewport");
|
||||
const mod = process.platform === "darwin" ? "Meta" : "Control";
|
||||
|
||||
// Nothing selected and a menu open: ← and → on its item are the menu's, not the map's.
|
||||
await expect(selected).toHaveCount(0);
|
||||
await page.locator(".zoom-button").click();
|
||||
await expect(page.getByRole("menu")).toBeVisible();
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
await page.keyboard.press("ArrowRight");
|
||||
await expect(selected).toHaveCount(0);
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(page.getByRole("menu")).toHaveCount(0);
|
||||
|
||||
// Esc mid-walk closes the Inspector, and the walk does not reopen it on its next step.
|
||||
await page.locator(".map-canvas .react-flow__node-screen .screen-screenshot-target").first().click();
|
||||
await expect(inspector).toBeVisible();
|
||||
await page.keyboard.down("ArrowDown");
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(inspector).toHaveCount(0);
|
||||
await page.waitForTimeout(800);
|
||||
await expect(inspector).toHaveCount(0);
|
||||
await page.keyboard.up("ArrowDown");
|
||||
|
||||
// ⌘K mid-walk opens Search, and the selection behind it stays where it was.
|
||||
await page.keyboard.down("ArrowDown");
|
||||
await page.keyboard.press(`${mod}+k`);
|
||||
await expect(search).toBeVisible();
|
||||
const behind = await selected.getAttribute("data-id");
|
||||
await page.waitForTimeout(800);
|
||||
await expect(selected).toHaveAttribute("data-id", behind!);
|
||||
await page.keyboard.up("ArrowDown");
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(search).toHaveCount(0);
|
||||
|
||||
// A held + glides past the tap's one step and stops where it is on release.
|
||||
const zoomNow = async () => (await readCanvasCamera(viewport)).zoom;
|
||||
const before = await zoomNow();
|
||||
await page.keyboard.down("Equal");
|
||||
await expect.poll(zoomNow, { timeout: 4000 }).toBeGreaterThan(before * 1.2 * 1.2);
|
||||
await page.keyboard.up("Equal");
|
||||
const released = await zoomNow();
|
||||
await page.waitForTimeout(300);
|
||||
expect(await zoomNow()).toBeCloseTo(released, 3);
|
||||
|
||||
// Held −, then a click opens Search: the glide stops rather than zoom behind the dialog.
|
||||
await page.keyboard.down("Minus");
|
||||
await page.getByRole("button", { name: "Search", exact: true }).click();
|
||||
await expect(search).toBeVisible();
|
||||
await page.waitForTimeout(400);
|
||||
const atOpen = await zoomNow();
|
||||
await page.waitForTimeout(800);
|
||||
expect(await zoomNow()).toBeCloseTo(atOpen, 3);
|
||||
await page.keyboard.up("Minus");
|
||||
});
|
||||
|
||||
test("a drag that starts on a transition edge pans the map", async ({ page }) => {
|
||||
await page.goto("/map");
|
||||
const viewport = page.locator(".map-canvas .react-flow__viewport");
|
||||
@@ -2112,12 +2040,16 @@ test("canonicalizes the legacy Workspace route to Changes and reports the exact
|
||||
if (entry.status === "unchanged") return total;
|
||||
return total + (entry.currentScreenIds.length || entry.baselineScreenIds.length);
|
||||
}, 0);
|
||||
// The bottom bar's Compare button carries the count.
|
||||
const badge = page.locator(".canvas-toolbar .toolbar-badge");
|
||||
await expect(badge).toHaveText(String(expectedChanges));
|
||||
const menu = await openChangesMenu(page);
|
||||
await expect(menu.locator(".changes-panel-title .changes-panel-count")).toHaveText(String(expectedChanges));
|
||||
|
||||
// Without a baseline there is nothing to count. Compare still opens, and the view says why it is empty.
|
||||
await page.goto("/map?baseline=none");
|
||||
await expect(page).toHaveURL(/baseline=none/);
|
||||
await expect(badge).toHaveCount(0);
|
||||
const compare = page.getByRole("toolbar", { name: "Canvas tools" }).getByRole("button", { name: "Compare", exact: true });
|
||||
await expect(compare).not.toHaveAttribute("aria-disabled", "true");
|
||||
await compare.click();
|
||||
@@ -2768,31 +2700,6 @@ test("drives the shell from the keyboard, and says so on hover", async ({ page }
|
||||
}
|
||||
await expect(page.getByRole("button", { name: "Comments", exact: true })).toHaveCount(0);
|
||||
|
||||
// A held modifier shows, on each button it makes a chord with, the key that completes it: ⇧ puts
|
||||
// 1 on Fit canvas, ⌘ (Ctrl elsewhere) puts K on Search. Released, the hints go.
|
||||
const hints = page.locator(".key-hint");
|
||||
await expect(hints).toHaveCount(0);
|
||||
await page.keyboard.down("Shift");
|
||||
await expect(page.getByRole("button", { name: "Fit canvas" }).locator(".key-hint")).toHaveText("1");
|
||||
await expect(page.getByRole("button", { name: "Center canvas" }).locator(".key-hint")).toHaveText("2");
|
||||
await expect(page.getByRole("button", { name: "Search", exact: true }).locator(".key-hint")).toHaveCount(0);
|
||||
await page.keyboard.up("Shift");
|
||||
await expect(hints).toHaveCount(0);
|
||||
await page.keyboard.down(mod);
|
||||
await expect(page.getByRole("button", { name: "Search", exact: true }).locator(".key-hint")).toHaveText("K");
|
||||
await expect(page.getByRole("button", { name: "Fit canvas" }).locator(".key-hint")).toHaveCount(0);
|
||||
await page.keyboard.up(mod);
|
||||
await expect(hints).toHaveCount(0);
|
||||
// Focus that moves into a field by mouse, with ⇧ still down, takes the hints with it.
|
||||
await page.keyboard.down("Shift");
|
||||
await expect(page.getByRole("button", { name: "Fit canvas" }).locator(".key-hint")).toHaveText("1");
|
||||
await page.getByRole("button", { name: "Search", exact: true }).click();
|
||||
await expect(page.getByRole("dialog", { name: "Search Explore" })).toBeVisible();
|
||||
await expect(hints).toHaveCount(0);
|
||||
await page.keyboard.up("Shift");
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(page.getByRole("dialog", { name: "Search Explore" })).toHaveCount(0);
|
||||
|
||||
// ⌘B opens and closes the Changes menu.
|
||||
await page.keyboard.press(`${mod}+b`);
|
||||
await expect(page.locator(".changes-menu")).toBeVisible();
|
||||
@@ -2825,23 +2732,14 @@ test("drives the shell from the keyboard, and says so on hover", async ({ page }
|
||||
await expect(page.locator(".tooltip-key")).toHaveText("C");
|
||||
await page.getByRole("button", { name: "Expand inspector" }).hover();
|
||||
await expect(page.locator(".tooltip-key")).toHaveText("I");
|
||||
// The theme button names the mode in force, and T is its key.
|
||||
// The theme button has no key: it names the mode in force and nothing else.
|
||||
const themeButton = page.getByRole("button", { name: "Toggle theme" });
|
||||
await themeButton.hover();
|
||||
await expect(page.locator(".tooltip-content")).toContainText("Theme: Auto");
|
||||
await expect(page.locator(".tooltip-key")).toHaveText("T");
|
||||
await expect(page.locator(".tooltip-content")).toContainText("Theme:");
|
||||
await expect(page.locator(".tooltip-key")).toHaveCount(0);
|
||||
await page.mouse.move(0, 0);
|
||||
const initialTheme = await page.locator("html").getAttribute("data-theme");
|
||||
expect(initialTheme === "light" || initialTheme === "dark").toBe(true);
|
||||
const otherTheme = initialTheme === "dark" ? "light" : "dark";
|
||||
// T flips between dark and light from whatever Auto showed, and never steps back to Auto.
|
||||
await page.keyboard.press("t");
|
||||
await expect(page.locator("html")).toHaveAttribute("data-theme", otherTheme);
|
||||
await page.keyboard.press("t");
|
||||
await expect(page.locator("html")).toHaveAttribute("data-theme", initialTheme!);
|
||||
await themeButton.hover();
|
||||
await expect(page.locator(".tooltip-content")).toContainText(initialTheme === "dark" ? "Theme: Dark" : "Theme: Light");
|
||||
await page.mouse.move(0, 0);
|
||||
// The retired theme and inspector chords no longer answer.
|
||||
await page.keyboard.press(`${mod}+Alt+t`);
|
||||
await expect(page.locator("html")).toHaveAttribute("data-theme", initialTheme!);
|
||||
@@ -4304,25 +4202,6 @@ test("desktop Compare: one command bar with the modes in it, even gaps to both b
|
||||
for (let step = 1; step < before; step += 1) await page.keyboard.press("ArrowRight");
|
||||
await expect(position).toHaveText(new RegExp(`^${before} of `));
|
||||
|
||||
// In Swipe, [ and ] nudge the divider; held, ] keeps going until it is released or at the edge.
|
||||
await page.keyboard.press("2");
|
||||
const divider = compare.getByRole("slider");
|
||||
await expect(divider).toHaveAttribute("aria-valuenow", "50");
|
||||
await page.keyboard.press("BracketLeft");
|
||||
await expect(divider).toHaveAttribute("aria-valuenow", "45");
|
||||
const dividerAt = async () => Number(await divider.getAttribute("aria-valuenow"));
|
||||
await page.keyboard.down("BracketRight");
|
||||
await expect(divider).toHaveAttribute("aria-valuenow", "50");
|
||||
await expect.poll(dividerAt, { timeout: 4000 }).toBeGreaterThanOrEqual(65);
|
||||
await page.keyboard.up("BracketRight");
|
||||
const dividerHeld = await dividerAt();
|
||||
await page.waitForTimeout(600);
|
||||
expect(await dividerAt()).toBe(dividerHeld);
|
||||
await page.keyboard.down("BracketRight");
|
||||
await expect.poll(dividerAt, { timeout: 8000 }).toBe(100);
|
||||
await page.keyboard.up("BracketRight");
|
||||
await page.keyboard.press("1");
|
||||
|
||||
// The bar keeps one size whatever the route, so Next stays under the pointer: it can be clicked
|
||||
// again and again through screens whose routes differ in length.
|
||||
const nextButton = bar.getByRole("button", { name: "Next changed screen" });
|
||||
|
||||
@@ -179,14 +179,7 @@ const Navigation=createStaticNavigation(Root); export default function App(){ret
|
||||
}
|
||||
return ok(identity(device));
|
||||
}
|
||||
if (command === 'fold') { device.pose = request.args[1]; return ok({ action: 'fold', pose: request.args[1] }); }
|
||||
// The display a fold lit, as a pose check reads it: landscape when opened, and drawn.
|
||||
if (command === 'screenshot' && request.args[1].endsWith('/pose.png')) {
|
||||
const display = new PNG(device.pose === 'open' ? { width: 24, height: 16 } : { width: 16, height: 24 });
|
||||
display.data[0] = 255;
|
||||
writeFileSync(request.args[1], PNG.sync.write(display));
|
||||
return ok({ path: request.args[1] });
|
||||
}
|
||||
if (command === 'fold') return ok({ action: 'fold', pose: request.args[1] });
|
||||
if (command === 'install') {
|
||||
const app = request.args[1];
|
||||
device.build = platform === 'android' ? readFileSync(app, 'utf8') : readFileSync(join(app, 'build-id'), 'utf8');
|
||||
|
||||
@@ -395,18 +395,9 @@ test("when Argent reads nothing while the prompt is up, Open is tapped from a sc
|
||||
assert.equal(context.state.deepLinkPromptAccepted, true);
|
||||
});
|
||||
|
||||
test("reset-reader stops the device's Argent helpers by its UDID and forgets what the old reader saw", async () => {
|
||||
const state = { generation: 3, udid: UDID, screen: { width: 402, height: 874 }, refs: { e1: {} } };
|
||||
const { calls, run } = harness("ios", { "stop-all-simulator-servers": { stopped: [`NativeDevtools:${UDID}`, `AXService:${UDID}`] } }, { state });
|
||||
const reset = await run(["reset-reader", ...flags("ios")]);
|
||||
assert.deepEqual(reset.json.data, { action: "reset-reader", stopped: [`NativeDevtools:${UDID}`, `AXService:${UDID}`] });
|
||||
assert.deepEqual(calls, [{ tool: "stop-all-simulator-servers", args: { devices: [UDID] } }]);
|
||||
assert.equal(state.screen, undefined); assert.equal(state.refs, undefined); assert.equal(state.generation, 4);
|
||||
});
|
||||
|
||||
test("fold moves a foldable to a pose and forgets the old panel's geometry", async () => {
|
||||
// Argent's fold answers with the panel it lit, in pixels; the inner panel is 2007 × 2853 (669 × 951 points).
|
||||
const { run, calls, context } = harness("ios", { "list-devices": DUO_DEVICES, "ui-tree": [DUO_HOME, DUO_OPEN_EDIT_LANE], "stop-all-simulator-servers": { stopped: [] },
|
||||
const { run, calls, context } = harness("ios", { "list-devices": DUO_DEVICES, "ui-tree": [DUO_HOME, DUO_OPEN_EDIT_LANE],
|
||||
fold: { activeScreen: 3, screen: { id: 3, panel: "inner panel", width: 2007, height: 2853 }, posture: "open", hingeAngle: 180 } });
|
||||
await run(["snapshot", ...flags("ios")]);
|
||||
const generation = context.state.generation;
|
||||
@@ -416,29 +407,12 @@ test("fold moves a foldable to a pose and forgets the old panel's geometry", asy
|
||||
const fold = calls.findIndex(call => call.tool === "fold");
|
||||
assert.equal(calls.slice(0, fold).filter(call => call.tool === "ui-tree").length, reads, "nothing is read between the command and the fold");
|
||||
assert.deepEqual(calls[fold].args, { udid: "74195B53-4DBC-4EAA-9991-F98E5BB86BA8", posture: "open" });
|
||||
// The device's helpers are reset just before the fold, so the panel it lights is read by fresh ones.
|
||||
assert.deepEqual(calls[fold - 1], { tool: "stop-all-simulator-servers", args: { devices: ["74195B53-4DBC-4EAA-9991-F98E5BB86BA8"] } });
|
||||
assert.equal(context.state.screen, undefined);
|
||||
assert.equal(context.state.refs, undefined);
|
||||
assert.equal(context.state.generation, generation + 1);
|
||||
assert.equal((await run(["fold", "sideways", ...flags("ios")])).json.error.code, "INVALID_ARGS");
|
||||
});
|
||||
|
||||
test("a reader stuck on the dark panel after a fold is reset once more before the fold is called unverified", async () => {
|
||||
const fold = { activeScreen: 3, screen: { id: 3, panel: "inner panel", width: 2007, height: 2853 }, posture: "open", hingeAngle: 180 };
|
||||
const stopped = { stopped: ["AXService:74195B53-4DBC-4EAA-9991-F98E5BB86BA8"] };
|
||||
// Ten reads still in the cover panel's shape (as on EAS, 2026-10-17), then the inner panel once the helpers restart.
|
||||
const recovers = harness("ios", { "list-devices": DUO_DEVICES, fold, "stop-all-simulator-servers": stopped, "ui-tree": [...Array(10).fill(DUO_HOME), DUO_OPEN_EDIT_LANE] });
|
||||
assert.deepEqual((await recovers.run(["fold", "open", ...flags("ios")])).json.data, { action: "fold", pose: "open" });
|
||||
assert.deepEqual(recovers.calls.filter(call => call.tool === "stop-all-simulator-servers").map(call => call.args), Array(2).fill({ devices: ["74195B53-4DBC-4EAA-9991-F98E5BB86BA8"] }));
|
||||
|
||||
const stuck = harness("ios", { "list-devices": DUO_DEVICES, fold, "stop-all-simulator-servers": stopped, "ui-tree": DUO_HOME });
|
||||
const failed = await stuck.run(["fold", "open", ...flags("ios")]);
|
||||
assert.equal(failed.json.error.code, "CONTROLLER_FOLD_UNVERIFIED");
|
||||
assert.match(failed.json.error.message, /after its device helpers were reset/);
|
||||
assert.equal(stuck.calls.filter(call => call.tool === "stop-all-simulator-servers").length, 2, "before the fold and once after, not in a loop");
|
||||
});
|
||||
|
||||
test("an alert that is not the link prompt is left for capture to answer", async () => {
|
||||
const other = { ...IOS_HOME, alertVisible: true, foregroundApp: "com.apple.springboard",
|
||||
roots: [{ type: "Alert", label: "Delete all data?", frame: { x: 0.1, y: 0.4, width: 0.8, height: 0.2 }, children: [
|
||||
@@ -560,9 +534,9 @@ test("a node its ancestor clips away is still reported hidden on iOS", () => {
|
||||
test("a fold whose panel Argent never reads fails clearly instead of capturing the dark panel", async () => {
|
||||
const lit = { activeScreen: 3, screen: { id: 3, panel: "inner panel", width: 2007, height: 2853 }, posture: "open", hingeAngle: 180 };
|
||||
const blindClosed = { ...DUO_HOME, foregroundApp: undefined, roots: [{ role: "AXGroup", children: [] }] };
|
||||
const late = harness("ios", { "list-devices": DUO_DEVICES, fold: lit, "stop-all-simulator-servers": { stopped: [] }, "ui-tree": [blindClosed, blindClosed, DUO_OPEN_EDIT_LANE] });
|
||||
const late = harness("ios", { "list-devices": DUO_DEVICES, fold: lit, "ui-tree": [blindClosed, blindClosed, DUO_OPEN_EDIT_LANE] });
|
||||
assert.equal((await late.run(["fold", "open", ...flags("ios")])).exitCode, 0, "a reader that catches up within the wait is fine");
|
||||
const stuck = harness("ios", { "list-devices": DUO_DEVICES, fold: lit, "stop-all-simulator-servers": { stopped: [] }, "ui-tree": blindClosed });
|
||||
const stuck = harness("ios", { "list-devices": DUO_DEVICES, fold: lit, "ui-tree": blindClosed });
|
||||
const failed = await stuck.run(["fold", "open", ...flags("ios")]);
|
||||
assert.equal(failed.json.error.code, "CONTROLLER_FOLD_UNVERIFIED");
|
||||
assert.equal(stuck.calls.filter(call => call.tool === "fold").length, 1, "the session is not folded back and forth");
|
||||
|
||||
@@ -22,7 +22,7 @@ function fail(args) {
|
||||
test("explore:binary is in the short help with its archive kinds and --no-upload", () => {
|
||||
const help = spawnSync(process.execPath, [cli, "help"], { cwd: root, encoding: "utf8" });
|
||||
assert.equal(help.status, 0, help.stderr);
|
||||
assert.match(help.stdout, /explore:binary <app\.apk \| app\.app \| app\.tar\.gz \| simulator \.ipa>.*--simulator eas\|local.*--no-upload/);
|
||||
assert.match(help.stdout, /explore:binary <app\.apk \| app\.app \| app\.tar\.gz \| simulator \.ipa>.*--no-upload/);
|
||||
});
|
||||
|
||||
test("explore:binary validates its arguments before touching EAS or a model", () => {
|
||||
@@ -30,9 +30,6 @@ test("explore:binary validates its arguments before touching EAS or a model", ()
|
||||
assert.match(fail(["./app.apk", "--upload", "--no-upload"]), /either --upload or --no-upload/);
|
||||
assert.match(fail(["./app.apk", "--expires-in", "400d"]), /--expires-in must be 1d to 90d, or never/);
|
||||
assert.match(fail(["./app.apk", "--platform", "web"]), /platform/);
|
||||
assert.match(fail(["./app.apk", "--simulator", "cloud"]), /simulator/);
|
||||
// A local run needs no EAS login, so the archive is the first thing it checks.
|
||||
assert.match(fail(["./does-not-exist.apk", "--simulator", "local"]), /Archive not found: .*does-not-exist\.apk/);
|
||||
assert.match(fail(["./does-not-exist.apk", "--no-upload"]), /Archive not found: .*does-not-exist\.apk/);
|
||||
assert.match(fail(["./package.json", "--no-upload"]), /Unsupported archive: package\.json/);
|
||||
const human = spawnSync(process.execPath, [cli, "explore:binary", "./does-not-exist.apk", "--no-upload"], { cwd: root, encoding: "utf8", env: { ...process.env, EXPO_TOKEN: "", EXPO_SESSION_SECRET: "" } });
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { writeFileSync } from "node:fs";
|
||||
import { mkdir, mkdtemp, readdir, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import test from "node:test";
|
||||
import { tsImport } from "tsx/esm/api";
|
||||
|
||||
const { runBinaryExploration } = await tsImport("../../src/binary/run.ts", import.meta.url);
|
||||
const { controllerVersion } = await tsImport("../../src/capture/simulator.ts", import.meta.url);
|
||||
const { CONTROLLER_SESSION } = await tsImport("../../src/capture/common.ts", import.meta.url);
|
||||
|
||||
const UDID = "0A1B2C3D-4E5F-4A6B-8C7D-9E0F1A2B3C4D";
|
||||
const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==", "base64");
|
||||
const DEVICE_TYPE = "com.apple.CoreSimulator.SimDeviceType.iPhone-17-Pro";
|
||||
|
||||
async function simulatorApp(root) {
|
||||
const app = join(root, "Example.app");
|
||||
await mkdir(app, { recursive: true });
|
||||
await writeFile(join(app, "Info.plist"), `<?xml version="1.0" encoding="UTF-8"?>
|
||||
<plist version="1.0"><dict>
|
||||
<key>CFBundleIdentifier</key><string>dev.example.app</string>
|
||||
<key>CFBundleDisplayName</key><string>Example</string>
|
||||
<key>DTPlatformName</key><string>iphonesimulator</string>
|
||||
<key>CFBundleURLTypes</key><array><dict><key>CFBundleURLSchemes</key><array><string>example</string></array></dict></array>
|
||||
</dict></plist>`);
|
||||
await writeFile(join(app, "Example"), "binary");
|
||||
return app;
|
||||
}
|
||||
|
||||
/** simctl and agent-device on a Mac with one iPhone 17 Pro runtime; the app shows a single screen. */
|
||||
function localRunner() {
|
||||
const requests = [];
|
||||
const ok = data => ({ stdout: JSON.stringify({ success: true, data }), stderr: "" });
|
||||
const runner = request => {
|
||||
requests.push(request);
|
||||
const [first, second, third] = request.args;
|
||||
if (request.command === "xcrun") {
|
||||
if (second === "list" && third === "devicetypes") return { stdout: JSON.stringify({ devicetypes: [{ name: "iPhone 17 Pro", identifier: DEVICE_TYPE }] }), stderr: "" };
|
||||
if (second === "list" && third === "runtimes") return { stdout: JSON.stringify({ runtimes: [{ isAvailable: true, platform: "iOS", identifier: "com.apple.CoreSimulator.SimRuntime.iOS-27-0",
|
||||
version: "27.0", supportedDeviceTypes: [{ identifier: DEVICE_TYPE }] }] }), stderr: "" };
|
||||
if (second === "create") return { stdout: `${UDID}\n`, stderr: "" };
|
||||
return { stdout: "", stderr: "" };
|
||||
}
|
||||
if (first === "--version") return { stdout: `${controllerVersion("agent-device")}\n`, stderr: "" };
|
||||
if (first === "open") return ok({ session: CONTROLLER_SESSION, appBundleId: "dev.example.app", device: { platform: "ios", target: "mobile", name: "Explore iPhone 17 Pro", id: UDID },
|
||||
identifiers: { session: CONTROLLER_SESSION, appBundleId: "dev.example.app", deviceName: "Explore iPhone 17 Pro", deviceId: UDID } });
|
||||
if (first === "snapshot") return ok({ nodes: [{ type: "StaticText", label: "Welcome" }, { type: "Button", label: "Settings" }] });
|
||||
if (first === "appstate") return ok({ platform: "ios", appBundleId: "dev.example.app", state: "runningForeground", surface: "app" });
|
||||
if (first === "screenshot") { writeFileSync(request.args[1], PNG); return ok({}); }
|
||||
return ok({});
|
||||
};
|
||||
return { requests, runner };
|
||||
}
|
||||
|
||||
test("explore:binary --simulator local runs on a simulator it creates, with no EAS login, and deletes it afterwards", async t => {
|
||||
const root = await mkdtemp(join(tmpdir(), "explore-binary-local-"));
|
||||
t.after(() => rm(root, { recursive: true, force: true }));
|
||||
const { requests, runner } = localRunner();
|
||||
const session = { provider: "anthropic", model: "test", async preflight() {}, async run() { return { stopReason: "done" }; } };
|
||||
const result = await runBinaryExploration({ archive: await simulatorApp(root), output: join(root, "out"), simulator: "local", provider: "anthropic", runner,
|
||||
createSession: () => session, environment: { PATH: process.env.PATH, HOME: root, ANTHROPIC_API_KEY: "key" } });
|
||||
|
||||
// No EAS: no login check, project, or session.
|
||||
assert.equal(requests.some(request => request.args.some(arg => /^(whoami|init|simulator:)/.test(arg))), false);
|
||||
const simctl = requests.filter(request => request.command === "xcrun").map(request => request.args.slice(1).join(" "));
|
||||
assert.ok(simctl.some(command => command.startsWith(`create Explore iPhone 17 Pro (binary `)));
|
||||
assert.ok(simctl.includes(`spawn ${UDID} defaults write com.apple.launchservices.schemeapproval com.apple.CoreSimulator.CoreSimulatorBridge-->example -string dev.example.app`),
|
||||
"the app's own scheme opens without a prompt");
|
||||
assert.ok(simctl.some(command => command.startsWith(`install ${UDID} `)), "simctl installs the app");
|
||||
assert.equal(simctl.at(-1), `delete ${UDID}`, "and the simulator goes last");
|
||||
|
||||
// agent-device runs its own daemon in the run's directory and is pointed at the simulator by its UDID.
|
||||
const controller = requests.filter(request => request.command !== "xcrun" && request.args[0] !== "--version" && request.args[0] !== "close");
|
||||
assert.ok(controller.length > 0);
|
||||
for (const request of controller) {
|
||||
assert.deepEqual(request.args.slice(request.args.indexOf("--udid"), request.args.indexOf("--udid") + 2), ["--udid", UDID]);
|
||||
assert.match(request.environment.AGENT_DEVICE_STATE_DIR, /agent-device-state$/);
|
||||
assert.equal(request.environment.AGENT_DEVICE_DAEMON_BASE_URL, undefined);
|
||||
}
|
||||
assert.equal(controller.some(request => request.args[0] === "install"), false, "the controller does not install it again");
|
||||
|
||||
assert.equal(result.runtime.provider, "local-simulator");
|
||||
assert.equal(result.runtime.osVersion, "27.0");
|
||||
assert.equal(result.session.id, `local-${UDID}`);
|
||||
assert.deepEqual(await readdir(join(root, ".cache", "expo-explore", "local-captures")), [], "nothing is left for a sweep");
|
||||
});
|
||||
+17
-221
@@ -112,10 +112,6 @@ async function fixture(t, settings = {}) {
|
||||
const requests = [];
|
||||
let current = '/'; let snapshots = 0; let sessionName; let screenshotAttempts = 0; let splashLeft = 0; let recordingPath = ''; let alert = null; let appearance = 'light'; let alertReads = 0;
|
||||
let enteredName = false; let scrolledToContinue = false; let finishHidden = false; let wedgeCleared = false; let deviceLost = false; let relaunchedAfterForeign = false; let serverStarts = 0; let unreadableLeft = settings.unreadableAfterFold ?? 0;
|
||||
// startsErrored / startsUnnamed: how many session starts EAS fails, after naming the session (it ERRORS) or before.
|
||||
let starts = 0; let currentSession = 'session-1'; const erroredSessions = new Set(); let foldUnverifiedLeft = settings.foldUnverified ?? 0;
|
||||
// blackAfterFold: the first so many folds of an EAS agent-device session light the panel but draw nothing.
|
||||
let folds = 0;
|
||||
const deviceName = settings.android ? 'Pixel 7' : 'iPhone 17 Pro';
|
||||
const platform = settings.android ? 'android' : 'ios';
|
||||
// A local simulator is the one the capture created, named for Explore.
|
||||
@@ -186,14 +182,6 @@ async function fixture(t, settings = {}) {
|
||||
appConfig: { name: 'Example', slug: 'example', owner: 'acme', ...(settings.userInterfaceStyle ? { userInterfaceStyle: settings.userInterfaceStyle } : {}), scheme: settings.noScheme ? undefined : 'sample',
|
||||
...(settings.android ? { android: { package: 'com.example.app' } } : { ios: { bundleIdentifier: 'com.example.app' } }), extra: { eas: { projectId: PROJECT_ID } } } });
|
||||
if (command === 'simulator:availability') return json({ available: settings.available !== false });
|
||||
// controlActions: what the session's serve-sim offers through simulator:control (none unless a test names them).
|
||||
if (command === 'simulator:control') {
|
||||
assert.equal(value(request, '--id'), currentSession, 'simulator:control names the session');
|
||||
if (request.args.includes('--list')) return json(Object.fromEntries((settings.controlActions ?? []).map(action => [action, { type: 'object' }])));
|
||||
assert.ok((settings.controlActions ?? []).includes(request.args[1]), `${request.args[1]} is offered by the session`);
|
||||
if (request.args[1] === 'appearance.set') appearance = request.args.at(-1);
|
||||
return json({ id: currentSession, action: request.args[1], output: '' });
|
||||
}
|
||||
if (command === 'fingerprint:generate') return json({ hash: 'source-fingerprint' });
|
||||
const buildMetadata = settings.buildMetadata ? { appVersion: '2.1.0', appBuildVersion: '42' } : {};
|
||||
if (command === 'build:list') return json(settings.reuse ? [{ id: 'native-build', ...buildMetadata }] : []);
|
||||
@@ -223,23 +211,13 @@ async function fixture(t, settings = {}) {
|
||||
}
|
||||
if (command === 'simulator:start') {
|
||||
sessionName = value(request, '--name');
|
||||
starts += 1; currentSession = `session-${starts}`;
|
||||
if (starts <= (settings.startsUnnamed ?? 0)) { writeFileSync(join(request.cwd, '.env.eas-simulator'), HEADER); throw new Error('GraphQL request failed.'); }
|
||||
if (starts <= (settings.startsErrored ?? 0)) erroredSessions.add(currentSession);
|
||||
writeFileSync(join(request.cwd, '.env.eas-simulator'), HEADER + `EAS_SIMULATOR_SESSION_ID='${currentSession}'\n` + (settings.argent
|
||||
writeFileSync(join(request.cwd, '.env.eas-simulator'), HEADER + "EAS_SIMULATOR_SESSION_ID='session-1'\n" + (settings.argent
|
||||
? "ARGENT_TOOLS_URL='https://controller.example/session'\nARGENT_AUTH_TOKEN='" + DAEMON_TOKEN + "'\n"
|
||||
: "AGENT_DEVICE_DAEMON_BASE_URL='https://controller.example/session'\nAGENT_DEVICE_DAEMON_AUTH_TOKEN='" + DAEMON_TOKEN + "'\n"));
|
||||
if (settings.startFailure) throw new Error('start reported failure after allocation');
|
||||
if (erroredSessions.has(currentSession)) throw new Error('Simulator session errored while starting');
|
||||
return { stdout: 'ready', stderr: '' };
|
||||
}
|
||||
// orphanFromFailedStart: a start that failed before naming the session had still created one.
|
||||
if (command === 'simulator:list') return json({ sessions: settings.orphanFromFailedStart && value(request, '--name') === sessionName ? [{ id: 'orphan-1', name: sessionName,
|
||||
type: settings.argent ? 'argent' : 'agent-device', status: 'STARTING', platform: 'IOS',
|
||||
// orphanUnproven: the session by that name does not show it belongs to this project.
|
||||
deviceRunSessionUrl: `https://expo.dev/accounts/${settings.orphanUnproven ? 'someone-else' : 'acme'}/projects/example/simulator-sessions/orphan-1` }] : [], pageInfo: {} });
|
||||
if (command === 'simulator:get') return json({ id: value(request, '--id'), name: sessionName, type: settings.argent ? 'argent' : 'agent-device', platform: settings.android ? 'ANDROID' : 'IOS',
|
||||
status: erroredSessions.has(value(request, '--id')) ? 'ERRORED' : 'IN_PROGRESS',
|
||||
if (command === 'simulator:get') return json({ id: 'session-1', name: sessionName, type: settings.argent ? 'argent' : 'agent-device', platform: settings.android ? 'ANDROID' : 'IOS', status: 'IN_PROGRESS',
|
||||
app: { id: settings.wrongProject ? 'foreign-project' : PROJECT_ID, slug: 'example', ownerAccount: { name: 'acme' } },
|
||||
remoteConfig: { ...(settings.argent ? { toolsUrl: 'https://controller.example/session', toolsAuthToken: DAEMON_TOKEN }
|
||||
: { agentDeviceRemoteSessionUrl: 'https://controller.example/session', agentDeviceRemoteSessionToken: DAEMON_TOKEN }),
|
||||
@@ -248,7 +226,7 @@ async function fixture(t, settings = {}) {
|
||||
...(settings.previewApiUrl ? { previewApiUrl: settings.previewApiUrl } : {}) } });
|
||||
if (command === 'simulator:stop') {
|
||||
if (settings.stopFailure) throw new Error('stop unavailable');
|
||||
return json({ id: value(request, '--id'), status: 'STOPPED' });
|
||||
return json({ id: 'session-1', status: 'STOPPED' });
|
||||
}
|
||||
}
|
||||
if (request.command === 'fake-repack') {
|
||||
@@ -263,7 +241,6 @@ async function fixture(t, settings = {}) {
|
||||
// An Argent capture runs its per-run bridge in place of agent-device; the bridge answers in agent-device's envelopes.
|
||||
if (request.command === 'fake-controller' || (settings.argent && request.command.endsWith('/argent-controller'))) {
|
||||
if (command === '--version') return { stdout: settings.argent ? '0.29.0' : AGENT_DEVICE_VERSION, stderr: '' };
|
||||
if (command === 'reset-reader') return json({ success: true, data: { action: 'reset-reader', stopped: ['AXService:device'] } });
|
||||
if (command === 'open') {
|
||||
// unreadableAfterFold: Argent's reader stayed on the outer panel, so the first app opens find no readable app.
|
||||
if (unreadableLeft > 0 && !request.args[2]?.startsWith('sample://')) { unreadableLeft -= 1;
|
||||
@@ -297,11 +274,6 @@ async function fixture(t, settings = {}) {
|
||||
// An EAS session starts empty while the app is repacked; the controller installs the app from this machine.
|
||||
if (command === 'install') { assert.ok(existsSync(request.args[1]), 'the repacked app is on this machine'); return ok({ installed: true, appBundleId: 'com.example.app' }); }
|
||||
// agent-device 0.21.15 cannot read Xcode 27.1's hinge angle back, so a local fold reports a failure after folding.
|
||||
// foldUnverified: the bridge's reader stayed on the dark panel through its own reset, for that many folds.
|
||||
// The bridge exits non-zero, and the runner throws its structured error, as defaultRunner does.
|
||||
if (command === 'fold') folds += 1;
|
||||
if (command === 'fold' && foldUnverifiedLeft > 0) { foldUnverifiedLeft -= 1;
|
||||
throw controllerCommandFailure(json({ success: false, error: { code: 'CONTROLLER_FOLD_UNVERIFIED', message: 'Argent kept reading the other panel after folding the device open, and after its device helpers were reset.' } }).stdout, 'fold'); }
|
||||
if (command === 'fold') return settings.local ? json({ success: false, error: { code: 'COMMAND_FAILED', message: "CoreDevice reported no hinge angle sample: Unknown option '--device'" } })
|
||||
: ok({ action: 'fold', pose: request.args[1] });
|
||||
if (command === 'record' && settings.recording) {
|
||||
@@ -375,13 +347,6 @@ async function fixture(t, settings = {}) {
|
||||
if (request.args[1] === 'appearance') appearance = request.args[2];
|
||||
return ok({ setting: request.args[1], value: request.args[2] });
|
||||
}
|
||||
// The display after a fold, as agent-device's screenshot shows it on EAS: in the pose's shape, drawn or black.
|
||||
if (command === 'screenshot' && request.args[1]?.endsWith('/pose.png')) {
|
||||
const display = new PNG(settings.devicePose === 'open' ? { width: 30, height: 20 } : { width: 20, height: 30 });
|
||||
if (folds > (settings.blackAfterFold ?? 0)) display.data[0] = 255;
|
||||
writeFileSync(request.args[1], PNG.sync.write(display));
|
||||
return ok({ path: request.args[1] });
|
||||
}
|
||||
if (command === 'screenshot') {
|
||||
screenshotAttempts += 1;
|
||||
if (settings.firstScreenshotFails && screenshotAttempts === 1) throw new Error('temporary screenshot transport error');
|
||||
@@ -503,7 +468,7 @@ test('an Argent capture starts an argent session, drives it through the bridge,
|
||||
}
|
||||
// Argent cannot switch appearance yet: one pass, no `settings appearance`, and a warning naming what was skipped.
|
||||
assert.equal(f.requests.some(request => request.args[0] === 'settings'), false);
|
||||
assert.ok(lines.some(line => /Argent cannot switch appearance on this session; capturing light only, skipped dark/.test(line)), lines.join('\n'));
|
||||
assert.ok(lines.some(line => /Argent cannot switch appearance yet .*capturing light only, skipped dark/.test(line)), lines.join('\n'));
|
||||
const map = JSON.parse(await readFile(join(f.options.outputDirectory, 'screen-map.json'), 'utf8'));
|
||||
assert.equal(map.run.controller, 'argent');
|
||||
assert.equal(map.run.environment.colorSchemes, undefined);
|
||||
@@ -515,150 +480,6 @@ test('an Argent capture starts an argent session, drives it through the bridge,
|
||||
assert.equal(execution.controllerPackageVersion, '0.29.0');
|
||||
});
|
||||
|
||||
test('on an EAS iOS session with serve-sim\'s appearance.set, an Argent capture records every appearance', async t => {
|
||||
const f = await fixture(t, { argent: true, userInterfaceStyle: 'automatic', controlActions: ['appearance.set'] });
|
||||
const lines = [];
|
||||
assert.equal((await runCiMap({ ...f.options, progress: line => lines.push(line) })).runStatus, 'complete');
|
||||
assert.equal(lines.some(line => /Argent cannot switch appearance/.test(line)), false, lines.join('\n'));
|
||||
assert.deepEqual(f.requests.filter(request => request.args[0] === 'simulator:control' && request.args[1] === 'appearance.set').map(request => request.args.at(-1)), ['light', 'dark']);
|
||||
const map = JSON.parse(await readFile(join(f.options.outputDirectory, 'screen-map.json'), 'utf8'));
|
||||
assert.deepEqual(map.run.environment.colorSchemes, ['light', 'dark']);
|
||||
});
|
||||
|
||||
test('an EAS iOS session approves the app\'s link scheme after installing it and before any link opens', async t => {
|
||||
for (const argent of [false, true]) {
|
||||
const f = await fixture(t, { argent, controlActions: ['app.approveUrlScheme'] });
|
||||
assert.equal((await runCiMap(f.options)).runStatus, 'complete');
|
||||
const approve = f.requests.findIndex(request => request.args[0] === 'simulator:control' && request.args[1] === 'app.approveUrlScheme');
|
||||
assert.ok(approve >= 0, argent ? 'Argent' : 'agent-device');
|
||||
assert.deepEqual(f.requests[approve].args.slice(f.requests[approve].args.indexOf('--') + 1), ['com.example.app', 'sample']);
|
||||
const controller = f.requests.map((request, index) => ({ request, index })).filter(({ request }) => request.command === 'fake-controller' || request.command.endsWith('/argent-controller'));
|
||||
const install = controller.find(({ request }) => request.args[0] === 'install');
|
||||
const firstLink = controller.find(({ request }) => request.args[0] === 'open' && request.args[2]?.startsWith('sample://'));
|
||||
assert.ok(install.index < approve && approve < firstLink.index, 'installed, then approved, then the first link');
|
||||
}
|
||||
// A session whose serve-sim predates the action keeps the controllers' prompt handling, and is not asked.
|
||||
const older = await fixture(t, { argent: true });
|
||||
assert.equal((await runCiMap(older.options)).runStatus, 'complete');
|
||||
assert.equal(older.requests.some(request => request.args[0] === 'simulator:control' && !request.args.includes('--list')), false);
|
||||
});
|
||||
|
||||
test('when Argent cannot read the app after a fold on EAS, the capture resets its device helpers, then restarts SpringBoard, and never stops the tool-server', async t => {
|
||||
const actions = ['springboard.restart'];
|
||||
for (const [unreadable, completes, resets, restarts] of [[1, true, 1, 0], [2, true, 2, 1], [3, false, 2, 1]]) {
|
||||
const f = await fixture(t, { argent: true, devicePose: 'open', unreadableAfterFold: unreadable, controlActions: actions });
|
||||
const lines = [];
|
||||
const run = runCiMap({ ...f.options, progress: line => lines.push(line), sleep: () => {} });
|
||||
if (completes) assert.equal((await run).runStatus, 'complete', `${unreadable} unreadable opens`);
|
||||
else await assert.rejects(run, error => JSON.stringify(error).includes('CONTROLLER_READER_STUCK'));
|
||||
assert.equal(f.requests.filter(request => request.command.endsWith('/argent-controller') && request.args[0] === 'reset-reader').length, resets);
|
||||
assert.equal(f.requests.filter(request => request.args[0] === 'simulator:control' && request.args[1] === 'springboard.restart').length, restarts);
|
||||
assert.equal(f.requests.some(request => request.args.join(' ').includes('server stop')), false, 'the session\'s tool-server is never stopped');
|
||||
assert.ok(lines.some(line => /resetting Argent's device helpers/.test(line)), lines.join('\n'));
|
||||
}
|
||||
// Without springboard.restart (an older serve-sim), a second unreadable open is reported after the reset alone.
|
||||
const older = await fixture(t, { argent: true, devicePose: 'open', unreadableAfterFold: 2 });
|
||||
await assert.rejects(runCiMap({ ...older.options, sleep: () => {} }), error => JSON.stringify(error).includes('CONTROLLER_READER_STUCK'));
|
||||
});
|
||||
|
||||
test('when a fold on EAS leaves Argent reading the dark panel, the capture restarts SpringBoard and folds again, once', async t => {
|
||||
for (const [unverified, completes] of [[1, true], [2, false]]) {
|
||||
const f = await fixture(t, { argent: true, devicePose: 'open', foldUnverified: unverified, controlActions: ['springboard.restart'] });
|
||||
const run = runCiMap({ ...f.options, sleep: () => {} });
|
||||
if (completes) assert.equal((await run).runStatus, 'complete');
|
||||
else await assert.rejects(run, error => JSON.stringify(error).includes('CONTROLLER_READER_STUCK'));
|
||||
assert.equal(f.requests.filter(request => request.command.endsWith('/argent-controller') && request.args[0] === 'fold').length, 2);
|
||||
assert.equal(f.requests.filter(request => request.args[0] === 'simulator:control' && request.args[1] === 'springboard.restart').length, 1);
|
||||
}
|
||||
});
|
||||
|
||||
test('a session EAS ends while starting is replaced by a new one, under a name of its own, up to five times with a growing wait', async t => {
|
||||
const f = await fixture(t, { startsErrored: 1 });
|
||||
const lines = []; const waits = [];
|
||||
const result = await runCiMap({ ...f.options, progress: line => lines.push(line), sleep: ms => { waits.push(ms); } });
|
||||
assert.equal(result.runStatus, 'complete');
|
||||
const started = f.requests.filter(request => request.args[0] === 'simulator:start').map(request => value(request, '--name'));
|
||||
assert.equal(started.length, 2);
|
||||
assert.notEqual(started[0], started[1], 'the new session has a name of its own');
|
||||
assert.ok(lines.some(line => /EAS ended simulator session session-1 \(ERRORED\) before it was ready; starting a new EAS Simulator session in 10 s \(1\/5\)/.test(line)), lines.join('\n'));
|
||||
assert.equal(lines.filter(line => /while the app is repacked/.test(line)).length, 1, 'only the first start runs beside the repack');
|
||||
assert.equal(result.simulatorSessionId, 'session-2');
|
||||
assert.ok(waits.includes(10_000));
|
||||
// Five new sessions at most, waiting 10 s, 20 s, 40 s, 80 s and 120 s before them; then the failure to start is reported as one.
|
||||
const always = await fixture(t, { startsErrored: 6 });
|
||||
const backoff = [];
|
||||
await assert.rejects(runCiMap({ ...always.options, sleep: ms => { if (ms >= 10_000) backoff.push(ms); } }),
|
||||
error => error.code === 'SIMULATOR_START_FAILED' && /6 sessions ended before they were ready \(the last, session-6, ERRORED\)/.test(error.message)
|
||||
&& error.details.endedSessions.length === 6 && error.details.attempts === 6);
|
||||
assert.equal(always.requests.filter(request => request.args[0] === 'simulator:start').length, 6);
|
||||
assert.deepEqual(backoff, [10_000, 20_000, 40_000, 80_000, 120_000]);
|
||||
assert.equal(new Set(always.requests.filter(request => request.args[0] === 'simulator:start').map(request => value(request, '--name'))).size, 6, 'every session has its own name');
|
||||
// One session that ended is a failure to start too, not a question of ownership.
|
||||
const once = await fixture(t, { startsErrored: 6 });
|
||||
await assert.rejects(runCiMap({ ...once.options, sleep: () => {}, runner: request => {
|
||||
if (request.args[0] === 'simulator:start' && once.requests.filter(r => r.args[0] === 'simulator:start').length >= 1) throw new Error('Controller simulator:start exited with status 1: quota exhausted');
|
||||
return once.options.runner(request);
|
||||
} }), error => error.code === 'SIMULATOR_START_FAILED');
|
||||
});
|
||||
|
||||
test('new sessions stay within 30 minutes of the first failed start, each start capped by what is left', async t => {
|
||||
const f = await fixture(t, { startsErrored: 6 });
|
||||
let clock = Date.parse('2026-10-18T00:00:00Z');
|
||||
const timeouts = [];
|
||||
await assert.rejects(runCiMap({ ...f.options, now: () => clock, sleep: ms => { clock += ms; }, runner: request => {
|
||||
// Each start takes 10 minutes before EAS ends the session.
|
||||
if (request.args[0] === 'simulator:start') { timeouts.push(request.timeoutMs); clock += 10 * 60_000; }
|
||||
return f.options.runner(request);
|
||||
} }), error => error.code === 'SIMULATOR_START_FAILED');
|
||||
// The budget runs from the first failure, at 10:00, to 40:00. The start at 10:10 fits whole; those at 20:30 and 31:10
|
||||
// get only what is left (19:30, then 8:50); after 41:10 none starts.
|
||||
assert.deepEqual(timeouts, [20 * 60_000, 20 * 60_000, 19.5 * 60_000, (8 * 60 + 50) * 1000]);
|
||||
});
|
||||
|
||||
test('Ctrl+C while waiting for a new session stops the review instead of starting one', async t => {
|
||||
const f = await fixture(t, { startsErrored: 6 });
|
||||
const controller = new AbortController();
|
||||
await assert.rejects(runCiMap({ ...f.options, signal: controller.signal, sleep: () => controller.abort(new Error('interrupted')) }));
|
||||
assert.equal(f.requests.filter(request => request.args[0] === 'simulator:start').length, 1);
|
||||
});
|
||||
|
||||
test('a start that fails before naming a session stops any session of that name first, then starts a new one', async t => {
|
||||
const f = await fixture(t, { startsUnnamed: 1, orphanFromFailedStart: true });
|
||||
assert.equal((await runCiMap({ ...f.options, sleep: () => {} })).runStatus, 'complete');
|
||||
const order = f.requests.map(request => request.args[0] === 'simulator:stop' && value(request, '--id') === 'orphan-1' ? 'stop-orphan' : request.args[0] === 'simulator:start' ? 'start' : undefined).filter(Boolean);
|
||||
assert.deepEqual(order, ['start', 'stop-orphan', 'start']);
|
||||
// The last failed start is accounted for as well, though no new session follows it.
|
||||
const always = await fixture(t, { startsUnnamed: 6, orphanFromFailedStart: true });
|
||||
await assert.rejects(runCiMap({ ...always.options, sleep: () => {} }), error => error.code === 'SIMULATOR_START_FAILED');
|
||||
assert.equal(always.requests.filter(request => request.args[0] === 'simulator:stop' && value(request, '--id') === 'orphan-1').length, 6);
|
||||
});
|
||||
|
||||
test('a session of that name Explore cannot prove is its own is never stopped or replaced', async t => {
|
||||
const f = await fixture(t, { startsUnnamed: 1, orphanFromFailedStart: true, orphanUnproven: true });
|
||||
await assert.rejects(runCiMap({ ...f.options, sleep: () => {} }), error => error.code === 'SIMULATOR_START_FAILED');
|
||||
assert.equal(f.requests.filter(request => request.args[0] === 'simulator:start').length, 1);
|
||||
assert.equal(f.requests.some(request => request.args[0] === 'simulator:stop'), false);
|
||||
});
|
||||
|
||||
test('a session Explore cannot prove is its own is never replaced, even one that ERRORED', async t => {
|
||||
const f = await fixture(t, { wrongProject: true, startsErrored: 1 });
|
||||
await assert.rejects(runCiMap(f.options), error => /SESSION_HANDOFF_UNVERIFIED/.test(JSON.stringify(error)));
|
||||
assert.equal(f.requests.filter(request => request.args[0] === 'simulator:start').length, 1);
|
||||
});
|
||||
|
||||
test('account failures to start are not retried; temporary ones and timeouts are', async t => {
|
||||
for (const [message, retried] of [['GraphQL request failed: not authorized', false], ['quota exhausted', false], ['GraphQL request failed.', true], ['No simulator capacity for iPhone Duo', true]]) {
|
||||
const f = await fixture(t);
|
||||
let starts = 0;
|
||||
const run = runCiMap({ ...f.options, sleep: () => {}, runner: request => {
|
||||
if (request.args[0] === 'simulator:start' && ++starts === 1) { writeFileSync(join(request.cwd, '.env.eas-simulator'), HEADER); throw new Error(`Controller simulator:start exited with status 1: ${message}`); }
|
||||
return f.options.runner(request);
|
||||
} });
|
||||
if (retried) assert.equal((await run).runStatus, 'complete', message); else await assert.rejects(run, error => error.code === 'SIMULATOR_START_FAILED', message);
|
||||
assert.equal(starts, retried ? 2 : 1, message);
|
||||
}
|
||||
});
|
||||
|
||||
test('an Argent capture of an app pinned to dark is labelled dark and is not warned about', async t => {
|
||||
const f = await fixture(t, { argent: true, userInterfaceStyle: 'dark' });
|
||||
const lines = [];
|
||||
@@ -668,45 +489,20 @@ test('an Argent capture of an app pinned to dark is labelled dark and is not war
|
||||
assert.equal(execution.colorScheme, 'dark');
|
||||
});
|
||||
|
||||
test('device.pose with Argent folds the device first, before the app is opened, read or captured', async t => {
|
||||
const f = await fixture(t, { devicePose: 'open', argent: true });
|
||||
assert.equal((await runCiMap(f.options)).runStatus, 'complete');
|
||||
const controller = f.requests.filter(request => request.command.endsWith('/argent-controller'));
|
||||
const folds = controller.filter(request => request.args[0] === 'fold');
|
||||
assert.equal(folds.length, 1);
|
||||
assert.deepEqual(folds[0].args.slice(0, 2), ['fold', 'open']);
|
||||
const foldAt = controller.indexOf(folds[0]);
|
||||
// The fold comes first: the app is installed but not opened, read or captured before it, so the controller starts on the lit panel.
|
||||
assert.deepEqual(controller.slice(0, foldAt).map(request => request.args[0]).filter(command => command !== '--version' && command !== 'install'), []);
|
||||
// Argent's bridge is told the pose, so it captures the opened panel's landscape UI upright.
|
||||
for (const request of controller) assert.equal(request.environment.EXPLORE_ARGENT_POSE, 'open');
|
||||
});
|
||||
|
||||
test('device.pose with agent-device on EAS opens the app, folds, and checks the display it lit', async t => {
|
||||
const f = await fixture(t, { devicePose: 'open' });
|
||||
assert.equal((await runCiMap({ ...f.options, sleep: () => {} })).runStatus, 'complete');
|
||||
const controller = f.requests.filter(request => request.command === 'fake-controller').map(request => request.args[0] === 'screenshot' && request.args[1].endsWith('/pose.png') ? 'pose' : request.args[0]);
|
||||
// agent-device folds only inside a session, so the app opens first; the fold's hinge readback is not trusted, the display is.
|
||||
assert.deepEqual(controller.filter(command => command !== '--version' && command !== 'install').slice(0, 3), ['open', 'fold', 'pose']);
|
||||
assert.equal(f.requests.some(request => request.args[0] === 'simulator:control' && request.args[1] === 'springboard.restart'), false);
|
||||
});
|
||||
|
||||
test('when an agent-device fold on EAS lights a black panel, the capture restarts SpringBoard, reopens the app and folds again, once', async t => {
|
||||
for (const [black, completes] of [[1, true], [2, false]]) {
|
||||
const f = await fixture(t, { devicePose: 'open', blackAfterFold: black, controlActions: ['springboard.restart'] });
|
||||
const lines = [];
|
||||
const run = runCiMap({ ...f.options, sleep: () => {}, progress: line => lines.push(line) });
|
||||
if (completes) assert.equal((await run).runStatus, 'complete');
|
||||
else await assert.rejects(run, error => JSON.stringify(error).includes('CONTROLLER_READER_STUCK'));
|
||||
const controller = f.requests.filter(request => request.command === 'fake-controller');
|
||||
assert.equal(controller.filter(request => request.args[0] === 'fold').length, 2);
|
||||
assert.ok(controller.some(request => request.args[0] === 'open' && request.args.includes('--relaunch')), 'the app is reopened after SpringBoard');
|
||||
assert.equal(f.requests.filter(request => request.args[0] === 'simulator:control' && request.args[1] === 'springboard.restart').length, 1);
|
||||
assert.ok(lines.some(line => /did not draw the open display after the fold; restarting SpringBoard/.test(line)), lines.join('\n'));
|
||||
test('device.pose folds the device first, before the app is opened, read or captured', async t => {
|
||||
for (const argent of [false, true]) {
|
||||
const f = await fixture(t, { devicePose: 'open', argent });
|
||||
assert.equal((await runCiMap(f.options)).runStatus, 'complete');
|
||||
const controller = f.requests.filter(request => request.command === 'fake-controller' || request.command.endsWith('/argent-controller'));
|
||||
const folds = controller.filter(request => request.args[0] === 'fold');
|
||||
assert.equal(folds.length, 1);
|
||||
assert.deepEqual(folds[0].args.slice(0, 2), ['fold', 'open']);
|
||||
const foldAt = controller.indexOf(folds[0]);
|
||||
// The fold comes first: the app is installed but not opened, read or captured before it, so the controller starts on the lit panel.
|
||||
assert.deepEqual(controller.slice(0, foldAt).map(request => request.args[0]).filter(command => command !== '--version' && command !== 'install'), []);
|
||||
// Argent's bridge is told the pose, so it captures the opened panel's landscape UI upright.
|
||||
if (argent) for (const request of controller) assert.equal(request.environment.EXPLORE_ARGENT_POSE, 'open');
|
||||
}
|
||||
// Without springboard.restart (an older serve-sim), a black panel is reported at once.
|
||||
const older = await fixture(t, { devicePose: 'open', blackAfterFold: 1 });
|
||||
await assert.rejects(runCiMap({ ...older.options, sleep: () => {} }), error => JSON.stringify(error).includes('CONTROLLER_FOLD_UNVERIFIED'));
|
||||
});
|
||||
|
||||
test('a local simulator capture creates its own iOS simulator, installs the repacked app there, and deletes the simulator', async t => {
|
||||
|
||||
@@ -639,12 +639,8 @@ test("doctor checks each target where it runs: local tools for local targets, EA
|
||||
targets: { phone: { platform: "ios" }, cloud: { platform: "ios", device: "iPhone 17 Pro", simulator: "eas", controller: "argent" } } });
|
||||
assert.deepEqual(devices(mixed), ["iPhone 17"]);
|
||||
assert.equal(check(mixed, "eas-simulator")[0].status, "pass");
|
||||
// The target's Argent is reported as a top-level one would be: on an iOS EAS session the host switches its appearance.
|
||||
assert.equal(check(mixed, "controller")[0].status, "pass");
|
||||
// Only Argent on an Android EAS session records a single appearance.
|
||||
const android = await doctor({ ...baseConfig, targets: { phone: { platform: "ios" },
|
||||
droid: { platform: "android", device: "pixel_7", bundleId: "com.example.app", easProfile: "explore-android", controller: "argent" } } });
|
||||
assert.equal(check(android, "controller")[0].code, "CONTROLLER_APPEARANCE_FIXED");
|
||||
// The target's Argent is reported as a top-level one would be.
|
||||
assert.equal(check(mixed, "controller")[0].code, "CONTROLLER_APPEARANCE_FIXED");
|
||||
// --simulator and --controller decide for every target, as they do in a capture.
|
||||
const forced = await doctor({ ...baseConfig, targets: { phone: { platform: "ios", simulator: "local", controller: "argent" } } }, { simulator: "eas", controller: "agent-device" });
|
||||
assert.deepEqual(devices(forced), []);
|
||||
|
||||
@@ -130,7 +130,7 @@ function runtimeFor(side, map, expectedSamples = 3, capturedSamples = expectedSa
|
||||
observationId: observation.id,
|
||||
expectedSampleCount: expectedSamples,
|
||||
controllerPackageVersion: "0.20.2",
|
||||
easCliVersion: "25.2.0",
|
||||
easCliVersion: "25.0.0",
|
||||
},
|
||||
runtime: {
|
||||
kind: "eas-agent-device-raw",
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const { tsImport } = await import("tsx/esm/api");
|
||||
const { heldKeyHint, shortcutModifiers } = await tsImport("../../viewer/src/utils/held-modifiers.ts", import.meta.url);
|
||||
const { SHORTCUTS } = await tsImport("../../viewer/src/utils/shortcuts.ts", import.meta.url);
|
||||
|
||||
const held = (keys) => ({ shift: false, ctrl: false, meta: false, alt: false, ...keys });
|
||||
|
||||
test("holding a chord's modifiers shows the key that completes it; anything else shows nothing", () => {
|
||||
assert.equal(heldKeyHint(SHORTCUTS.canvasByNumber.map, held({ ctrl: true }), true), "1");
|
||||
assert.equal(heldKeyHint(SHORTCUTS.canvasByNumber.compare, held({ ctrl: true }), true), "3");
|
||||
assert.equal(heldKeyHint(SHORTCUTS.camera.fit, held({ shift: true }), true), "1");
|
||||
assert.equal(heldKeyHint(SHORTCUTS.appearance.app, held({ shift: true }), true), "T");
|
||||
assert.equal(heldKeyHint(SHORTCUTS.canvasByNumber.map, held({ shift: true }), true), undefined, "the wrong modifier");
|
||||
assert.equal(heldKeyHint(SHORTCUTS.canvasByNumber.map, held({ ctrl: true, shift: true }), true), undefined, "an extra modifier");
|
||||
assert.equal(heldKeyHint(SHORTCUTS.canvas.map, held({ ctrl: true }), true), undefined, "a plain key has no chord");
|
||||
assert.equal(heldKeyHint(SHORTCUTS.canvasByNumber.map, held({}), true), undefined, "nothing held");
|
||||
});
|
||||
|
||||
test("mod is ⌘ on Apple keyboards and Ctrl elsewhere", () => {
|
||||
assert.equal(heldKeyHint(SHORTCUTS.app.search, held({ meta: true }), true), "K");
|
||||
assert.equal(heldKeyHint(SHORTCUTS.app.search, held({ ctrl: true }), true), undefined);
|
||||
assert.equal(heldKeyHint(SHORTCUTS.app.search, held({ ctrl: true }), false), "K");
|
||||
assert.equal(heldKeyHint(SHORTCUTS.app.search, held({ meta: true }), false), undefined);
|
||||
assert.deepEqual(shortcutModifiers(SHORTCUTS.app.search, true), held({ meta: true }));
|
||||
assert.deepEqual(shortcutModifiers(SHORTCUTS.app.search, false), held({ ctrl: true }));
|
||||
});
|
||||
@@ -2,7 +2,7 @@ import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const { tsImport } = await import("tsx/esm/api");
|
||||
const { HOLD_INITIAL_DELAY_MS, HOLD_FIRST_INTERVAL_MS, HOLD_FLOOR_INTERVAL_MS, createKeyHold, glideRate, holdIntervalMs, holdSchedule } =
|
||||
const { HOLD_INITIAL_DELAY_MS, HOLD_FIRST_INTERVAL_MS, HOLD_FLOOR_INTERVAL_MS, holdIntervalMs, holdSchedule } =
|
||||
await tsImport("../../viewer/src/utils/key-hold.ts", import.meta.url);
|
||||
|
||||
test("a held paging key waits, then steps sooner and sooner down to a floor", () => {
|
||||
@@ -16,70 +16,3 @@ test("a held paging key waits, then steps sooner and sooner down to a floor", ()
|
||||
assert.ok(schedule.at(-1) < 2000, "six held steps fit in two seconds");
|
||||
assert.ok(HOLD_INITIAL_DELAY_MS > HOLD_FIRST_INTERVAL_MS, "the hold begins slower than it repeats");
|
||||
});
|
||||
|
||||
test("a held key steps on the schedule from its first step, and ends when a step finds nothing", (t) => {
|
||||
t.mock.timers.enable({ apis: ["setTimeout"] });
|
||||
const hold = createKeyHold();
|
||||
let steps = 0;
|
||||
hold.begin("ArrowRight", () => (steps += 1) < 3);
|
||||
assert.ok(hold.holding("ArrowRight"));
|
||||
assert.ok(!hold.holding("ArrowLeft"));
|
||||
t.mock.timers.tick(HOLD_INITIAL_DELAY_MS - 1);
|
||||
assert.equal(steps, 0, "nothing before the initial delay");
|
||||
t.mock.timers.tick(1);
|
||||
assert.equal(steps, 1, "the second step lands after the initial delay");
|
||||
t.mock.timers.tick(holdIntervalMs(1));
|
||||
assert.equal(steps, 2);
|
||||
t.mock.timers.tick(holdIntervalMs(2));
|
||||
assert.equal(steps, 3, "the third attempt finds nothing");
|
||||
assert.ok(!hold.holding("ArrowRight"), "and the hold ends by itself");
|
||||
t.mock.timers.tick(10_000);
|
||||
assert.equal(steps, 3, "no further steps");
|
||||
});
|
||||
|
||||
test("ending a hold, or beginning another key, stops the first", (t) => {
|
||||
t.mock.timers.enable({ apis: ["setTimeout"] });
|
||||
const hold = createKeyHold();
|
||||
let right = 0;
|
||||
let left = 0;
|
||||
hold.begin("ArrowRight", () => { right += 1; return true; });
|
||||
t.mock.timers.tick(HOLD_INITIAL_DELAY_MS);
|
||||
assert.equal(right, 1);
|
||||
hold.begin("ArrowLeft", () => { left += 1; return true; });
|
||||
assert.ok(!hold.holding("ArrowRight"));
|
||||
assert.ok(hold.holding("ArrowLeft"));
|
||||
// Mock timers run one scheduled round per tick; a hold schedules the next step from each step.
|
||||
t.mock.timers.tick(HOLD_INITIAL_DELAY_MS);
|
||||
t.mock.timers.tick(holdIntervalMs(1));
|
||||
assert.equal(right, 1, "the first key stopped stepping");
|
||||
assert.equal(left, 2);
|
||||
hold.end();
|
||||
assert.ok(!hold.holding("ArrowLeft"));
|
||||
t.mock.timers.tick(holdIntervalMs(2));
|
||||
t.mock.timers.tick(1000);
|
||||
assert.equal(left, 2);
|
||||
});
|
||||
|
||||
test("another key ends a hold, as the OS's own repeat stops; its own repeats and a modifier do not", () => {
|
||||
const key = (code, key = code, repeat = false) => ({ code, key, repeat });
|
||||
const hold = createKeyHold();
|
||||
hold.begin("ArrowDown", () => true);
|
||||
hold.interrupt(key("ArrowDown", "ArrowDown", true));
|
||||
hold.interrupt(key("ShiftLeft", "Shift"));
|
||||
hold.interrupt(key("MetaLeft", "Meta"));
|
||||
assert.ok(hold.holding("ArrowDown"), "its own repeat and a modifier leave it held");
|
||||
hold.interrupt(key("Escape"));
|
||||
assert.ok(!hold.holding("ArrowDown"), "Esc ends it");
|
||||
hold.begin("ArrowDown", () => true);
|
||||
hold.interrupt(key("KeyK", "k"));
|
||||
assert.ok(!hold.holding("ArrowDown"), "so does the K of ⌘K");
|
||||
hold.end();
|
||||
});
|
||||
|
||||
test("a glide picks up from rest, then eases from the stepped hold's first speed up to its top speed", () => {
|
||||
assert.equal(glideRate(0), 0, "it starts at rest, where the tap's step ended");
|
||||
assert.ok(Math.abs(glideRate(80) - 1000 / HOLD_FIRST_INTERVAL_MS) < 0.2, "within a few frames it moves a step per first interval");
|
||||
for (let at = 10; at <= 1200; at += 10) assert.ok(glideRate(at) >= glideRate(at - 10), `never slows, at ${at}ms`);
|
||||
assert.equal(glideRate(1000), 1000 / HOLD_FLOOR_INTERVAL_MS, "after a second, a step per floor interval");
|
||||
assert.equal(glideRate(5000), glideRate(1000), "and no faster");
|
||||
});
|
||||
@@ -2,7 +2,7 @@ import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const { tsImport } = await import("tsx/esm/api");
|
||||
const { mapKeyDirection, mapKeyEntry, mapKeyTarget } = await tsImport("../../viewer/src/utils/map-keyboard.ts", import.meta.url);
|
||||
const { mapKeyDirection, mapKeyTarget } = await tsImport("../../viewer/src/utils/map-keyboard.ts", import.meta.url);
|
||||
|
||||
// A top-to-bottom map: root fans out to a, b, c on one rank; b leads on to d; e is a stray rank with no edges.
|
||||
// root
|
||||
@@ -100,11 +100,3 @@ test("a left-to-right map needs no special case: the keys read positions", () =>
|
||||
assert.equal(mapKeyTarget(rotated, "a", "down"), "b");
|
||||
assert.equal(mapKeyTarget(rotated, "c", "up"), "b");
|
||||
});
|
||||
|
||||
test("with nothing selected, an arrow enters the map at the edge it moves away from, as Screens' arrows do", () => {
|
||||
assert.equal(mapKeyEntry(structure, "down"), "root", "down starts at the top");
|
||||
assert.equal(mapKeyEntry(structure, "up"), "d", "up starts at the bottom; the leftmost of that rank");
|
||||
assert.equal(mapKeyEntry(structure, "right"), "a", "right starts at the left edge");
|
||||
assert.equal(mapKeyEntry(structure, "left"), "e", "left starts at the right edge");
|
||||
assert.equal(mapKeyEntry({ positions: new Map() }, "down"), undefined, "an empty map has no entry");
|
||||
});
|
||||
@@ -66,7 +66,7 @@ async function exportFixture(t, options) {
|
||||
}
|
||||
|
||||
/** A fake EAS CLI plus a fake deployment: `deploy` captures the sealed report and .env, then serves them like the Worker would. */
|
||||
function easFixture({ origin = "https://acme-explore--1lcbdcpwn3.expo.app", aliasOrigin = "https://acme-explore--bluesky.expo.app", accounts = ["brent-org"], failDeploy = false, aliasServes = true, aliasListing, existingComment } = {}) {
|
||||
function easFixture({ origin = "https://acme-explore--1lcbdcpwn3.expo.app", aliasOrigin = "https://acme-explore--bluesky.expo.app", accounts = ["brent-org"], failDeploy = false, aliasServes = true, existingComment } = {}) {
|
||||
let deploys = 0;
|
||||
let latestComment = existingComment;
|
||||
const calls = []; const captured = {};
|
||||
@@ -107,8 +107,6 @@ function easFixture({ origin = "https://acme-explore--1lcbdcpwn3.expo.app", alia
|
||||
? new Response("<!doctype html>", { status: 200, headers: { "content-type": "text/html; charset=utf-8" } })
|
||||
: new Response("# Expo Explore report", { status: 200, headers: { "content-type": "text/markdown; charset=utf-8" } });
|
||||
if (match[2] === "api/v1") return new Response(JSON.stringify({ kind: "pr-review" }), { status: 200, headers: { "content-type": "application/json; charset=utf-8" } });
|
||||
// aliasListing: the alias still points at an earlier deployment of the same token and reports, listed the old way.
|
||||
if (match[2] === "reports.json" && aliasListing && url.origin === aliasOrigin) return new Response(aliasListing, { status: 200, headers: { "content-type": "application/json; charset=utf-8" } });
|
||||
if (match[2] === "reports.json") return new Response(JSON.stringify(captured.listing.map(({ path: _path, ...rest }) => rest)), { status: 200, headers: { "content-type": "application/json; charset=utf-8" } });
|
||||
// Selection as the Worker does it: ?target= by id, ?platform= by id and then by platform, else the first.
|
||||
const target = url.searchParams.get("target"), platform = url.searchParams.get("platform");
|
||||
@@ -476,18 +474,6 @@ test("a fixture preview seals each platform's ZIP as is behind one alias and lis
|
||||
assert.equal(logged.filter(line => /^::warning::The alias https:\/\/explore-viewer-pr--pr-12\.expo\.app still answers HTTP 404 \d+ s after eas deploy returned\. The pull request links the deployment https:\/\/acme-explore--1lcbdcpwn3\.expo\.app instead\./.test(line)).length, 1);
|
||||
assert.ok(behind.requests.some(request => request.url.origin === "https://explore-viewer-pr--pr-12.expo.app"), "the alias was polled");
|
||||
|
||||
// The example report keeps one token and the same fixtures, so an alias still on the previous deployment serves the
|
||||
// token page and the same report: only its listing (an older Viewer's) gives it away. That is an alias behind too.
|
||||
const stale = easFixture({ aliasOrigin: "https://explore-viewer-pr--pr-12.expo.app", aliasListing: JSON.stringify([{ platform: "ios" }]) });
|
||||
clock = now; logged.length = 0;
|
||||
process.stderr.write = chunk => { logged.push(String(chunk)); return true; };
|
||||
try {
|
||||
linked = await deployFixturePreview({ reports: [{ platform: "ios", zipPath: join(root, "ios.zip") }], project: "explore-viewer-pr", owner: "brent-org", alias: "pr-12", token,
|
||||
exportPath, environment: deployEnvironment, transport: stale.transport, run: stale.run, now: ticking, verifyTimeoutMs: 60_000 });
|
||||
} finally { process.stderr.write = quiet; }
|
||||
assert.equal(linked.previewUrl, `https://acme-explore--1lcbdcpwn3.expo.app/p/${token}`);
|
||||
assert.equal(logged.filter(line => /^::warning::The alias https:\/\/explore-viewer-pr--pr-12\.expo\.app still serves an earlier deployment \d+ s after eas deploy returned\./.test(line)).length, 1);
|
||||
|
||||
await assert.rejects(deployFixturePreview({ reports: [{ platform: "ios", zipPath: join(root, "ios.zip") }, { platform: "ios", zipPath: join(root, "ios.zip") }],
|
||||
project: "explore-viewer-pr", alias: "pr-12", exportPath, environment: deployEnvironment, transport: eas.transport, run: eas.run, verifyTimeoutMs: 1 }),
|
||||
error => error.code === "PREVIEW_REPORTS_INVALID");
|
||||
|
||||
@@ -60,7 +60,7 @@ function state(overrides = {}) {
|
||||
phase: 'ready', pullRequest, mode: 'changes', executionMode: 'deterministic', configPath: '.expo-explore/config.yaml', links,
|
||||
startedAt: Date.parse('2026-09-11T03:00:48Z'), updatedAt: Date.parse('2026-09-11T03:07:00Z'),
|
||||
build: { appName: 'Example', appVersion: '1.4.0', appBuildNumber: '27', platform: 'ios', easProfile: 'explore', easBuildId: 'eas-build', reusedEasBuild: true },
|
||||
runtime: { provider: 'eas-simulator', controller: 'agent-device', controllerPackageVersion: '0.20.2', easCliVersion: '25.2.0', platform: 'ios', deviceModel: 'iPhone 17', osVersion: '26.5', locale: 'en-US', orientation: 'portrait', colorScheme: 'light', sessionLifecycle: 'stopped' },
|
||||
runtime: { provider: 'eas-simulator', controller: 'agent-device', controllerPackageVersion: '0.20.2', easCliVersion: '25.0.0', platform: 'ios', deviceModel: 'iPhone 17', osVersion: '26.5', locale: 'en-US', orientation: 'portrait', colorScheme: 'light', sessionLifecycle: 'stopped' },
|
||||
capture: { planned: { base: 3, head: 3 }, done: { base: 3, head: 3 }, baseFromCache: true },
|
||||
review: evidenceReview(),
|
||||
evidence: {
|
||||
|
||||
@@ -13,7 +13,7 @@ const BASE_SHA = "a".repeat(40);
|
||||
const HEAD_SHA = "b".repeat(40);
|
||||
const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=", "base64");
|
||||
const EXECUTION = {
|
||||
provider: "eas-simulator", controller: "agent-device", controllerPackageVersion: AGENT_DEVICE_VERSION, easCliVersion: "25.2.0",
|
||||
provider: "eas-simulator", controller: "agent-device", controllerPackageVersion: AGENT_DEVICE_VERSION, easCliVersion: "25.0.0",
|
||||
platform: "ios", deviceModel: "iPhone 17", osVersion: "26.0", locale: "en-US", orientation: "portrait",
|
||||
colorScheme: "light", sessionLifecycle: "stopped",
|
||||
};
|
||||
|
||||
@@ -16,7 +16,7 @@ function execution(overrides = {}) {
|
||||
provider: "eas-simulator",
|
||||
controller: "agent-device",
|
||||
controllerPackageVersion: AGENT_DEVICE_VERSION,
|
||||
easCliVersion: "25.2.0",
|
||||
easCliVersion: "25.0.0",
|
||||
platform: "ios",
|
||||
deviceModel: "iPhone 17",
|
||||
osVersion: "26.0",
|
||||
@@ -189,7 +189,7 @@ test("projects one map surface into the five runtime evidence groups", () => {
|
||||
assert.equal(result.groups.interaction.transitionCount.value, 1);
|
||||
assert.equal(result.groups.ui.landmarks.value.length, 0);
|
||||
assert.equal(result.groups.environment.controllerPackageVersion?.value, AGENT_DEVICE_VERSION);
|
||||
assert.equal(result.groups.environment.easCliVersion?.value, "25.2.0");
|
||||
assert.equal(result.groups.environment.easCliVersion?.value, "25.0.0");
|
||||
});
|
||||
|
||||
test("normalizes multi-line labels and treats only open parser gaps as truncation", () => {
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { tsImport } from "tsx/esm/api";
|
||||
|
||||
const { approveSessionUrlSchemes, simulatorControl, simulatorControlActions } = await tsImport("../../src/capture/simulator-control.ts", import.meta.url);
|
||||
|
||||
function easFake(listed) {
|
||||
const calls = [];
|
||||
const eas = (args, options) => {
|
||||
calls.push({ args, options });
|
||||
if (args.includes("--list")) { if (listed instanceof Error) throw listed; return { stdout: listed }; }
|
||||
return { stdout: "{}" };
|
||||
};
|
||||
return { calls, eas };
|
||||
}
|
||||
|
||||
test("a session's control actions come from --list, by session id; an older session or CLI has none", () => {
|
||||
const { calls, eas } = easFake(JSON.stringify({ "appearance.set": {}, "springboard.restart": {} }));
|
||||
assert.deepEqual([...simulatorControlActions(eas, "session-1")], ["appearance.set", "springboard.restart"]);
|
||||
assert.deepEqual(calls[0].args, ["simulator:control", "--list", "--id", "session-1", "--json", "--non-interactive"]);
|
||||
assert.equal(calls[0].options.allowFailure, true);
|
||||
assert.equal(simulatorControlActions(easFake("Unknown command simulator:control").eas, "session-1").size, 0);
|
||||
assert.equal(simulatorControlActions(easFake(new Error("eas exited 1")).eas, "session-1").size, 0);
|
||||
});
|
||||
|
||||
test("an action's values follow --, so one that starts with a dash is never read as a flag", () => {
|
||||
const { calls, eas } = easFake("{}");
|
||||
simulatorControl(eas, "session-1", "clipboard.write", ["--not-a-flag"]);
|
||||
assert.deepEqual(calls[0].args, ["simulator:control", "clipboard.write", "--id", "session-1", "--json", "--non-interactive", "--", "--not-a-flag"]);
|
||||
});
|
||||
|
||||
test("link schemes are approved once each, lowercased, never http or https, and only when the session offers it", () => {
|
||||
const { calls, eas } = easFake("{}");
|
||||
const approved = approveSessionUrlSchemes(eas, "session-1", new Set(["app.approveUrlScheme"]), "dev.example.app", ["Example", "example", "https", "exp+example", "not a scheme"]);
|
||||
assert.deepEqual(approved, ["example", "exp+example"]);
|
||||
assert.deepEqual(calls.map(call => call.args.slice(-2)), [["dev.example.app", "example"], ["dev.example.app", "exp+example"]]);
|
||||
const none = easFake("{}");
|
||||
assert.deepEqual(approveSessionUrlSchemes(none.eas, "session-1", new Set(), "dev.example.app", ["example"]), []);
|
||||
assert.equal(none.calls.length, 0);
|
||||
});
|
||||
+3
-17
@@ -306,8 +306,6 @@ function ViewerApp() {
|
||||
const [mapProjectionFitKey, setMapProjectionFitKey] = useState(0);
|
||||
// A report captured in several appearances shows one at a time; the primary (first captured) is the default.
|
||||
const [appearanceChoice, setAppearanceChoice] = useState<Appearance | undefined>();
|
||||
// For the ⇧T shortcut, which steps to the next captured appearance; set once they are known.
|
||||
const appearanceRef = useRef<{ options: readonly Appearance[]; current: Appearance | undefined }>({ options: [], current: undefined });
|
||||
const [handoffOpen, setHandoffOpen] = useState(false);
|
||||
/** Whether this page can hand the report off (a hosted preview); the A key reads it. */
|
||||
const handoffAvailableRef = useRef(false);
|
||||
@@ -373,10 +371,6 @@ function ViewerApp() {
|
||||
const toggleTheme = useCallback(() => {
|
||||
setThemePreference(current => current === "system" ? "dark" : current === "dark" ? "light" : "system");
|
||||
}, []);
|
||||
// The T key flips what is on screen, dark to light and back; only the button returns to Auto.
|
||||
const flipTheme = useCallback(() => {
|
||||
setThemePreference(current => (current === "system" ? preferredSystemTheme : current) === "dark" ? "light" : "dark");
|
||||
}, [preferredSystemTheme]);
|
||||
|
||||
const load = useCallback(async (silent = false) => {
|
||||
void silent;
|
||||
@@ -1000,14 +994,6 @@ function ViewerApp() {
|
||||
if (matchesShortcut(event, SHORTCUTS.app.handoff)) {
|
||||
if (!handoffAvailableRef.current) return;
|
||||
setHandoffOpen(true);
|
||||
} else if (matchesShortcut(event, SHORTCUTS.appearance.theme)) {
|
||||
flipTheme();
|
||||
} else if (matchesShortcut(event, SHORTCUTS.appearance.app)) {
|
||||
// Only a report captured in both schemes has another appearance to show.
|
||||
const { options, current } = appearanceRef.current;
|
||||
if (options.length < 2) return;
|
||||
const index = current ? options.indexOf(current) : -1;
|
||||
setAppearanceChoice(options[(index + 1) % options.length]);
|
||||
} else if (matchesShortcut(event, SHORTCUTS.app.changes)) {
|
||||
setChangesOpen((open) => !open);
|
||||
} else if (matchesShortcut(event, SHORTCUTS.panel.right)) {
|
||||
@@ -1023,7 +1009,7 @@ function ViewerApp() {
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onKeyDown);
|
||||
};
|
||||
}, [clearSelectedScreen, flipTheme, navigate, searchOpen, selectCanvas, toggleRightPanel]);
|
||||
}, [clearSelectedScreen, navigate, searchOpen, selectCanvas, toggleRightPanel]);
|
||||
|
||||
// A side-panel row or a deep link is a "go to": the camera fits that screen and the step is
|
||||
// kept. Screens inventory clicks only select in place; Map clicks also focus the chosen screen. Repeating a selected target refits it without adding history.
|
||||
@@ -1116,7 +1102,6 @@ function ViewerApp() {
|
||||
const baseline = builds.find((build) => build.id === route.baseline);
|
||||
const appearances = useMemo(() => appearanceOptions(payload?.map), [payload]);
|
||||
const appearance = appearanceChoice && appearances.includes(appearanceChoice) ? appearanceChoice : appearances[0];
|
||||
appearanceRef.current = { options: appearances, current: appearance };
|
||||
const appearanceMap = useMemo(() => payload ? filterMapAppearance(payload.map, appearance) : undefined, [appearance, payload]);
|
||||
const currentMap = useMemo(() => (
|
||||
appearanceMap && workspace && currentBuild
|
||||
@@ -1620,6 +1605,7 @@ function ViewerApp() {
|
||||
) : <CanvasToolbar
|
||||
canvas={route.canvas}
|
||||
searchOpen={searchOpen}
|
||||
compareCount={compareOrder.length}
|
||||
{...(handoffAction ? { actions: handoffAction } : {})}
|
||||
onOpenShortcuts={() => setShortcutsOpen(true)}
|
||||
onSelectCanvas={selectCanvas}
|
||||
@@ -1628,7 +1614,7 @@ function ViewerApp() {
|
||||
</CanvasVisibleFrameProvider>
|
||||
{shortcutsOpen ? (
|
||||
<ShortcutsDialog
|
||||
context={{ canvas: route.canvas, review: reviewingInSidebar, hasChanges: compareOrder.length > 0, handoff: Boolean(handoffInput), appearances: appearances.length > 1 }}
|
||||
context={{ canvas: route.canvas, review: reviewingInSidebar, hasChanges: compareOrder.length > 0, handoff: Boolean(handoffInput) }}
|
||||
onClose={() => setShortcutsOpen(false)}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
@@ -3,7 +3,6 @@ import { Fullscreen, LocateFixed } from "lucide-react";
|
||||
import { runCanvasZoomCommand } from "../../utils/canvas-zoom";
|
||||
import { useCanvasZoom } from "../../hooks/use-canvas-zoom";
|
||||
import { formatShortcut, SHORTCUTS } from "../../utils/shortcuts";
|
||||
import { KeyHint } from "../shared/key-hint";
|
||||
import { Menu, type MenuItem } from "../shared/menu";
|
||||
import { Tooltip } from "../shared/tooltip";
|
||||
import { FullscreenToggleButton, ThemeToggleButton, type ShellActionsProps, type ShellTheme } from "../panels/shell-actions";
|
||||
@@ -87,7 +86,6 @@ function FitControl() {
|
||||
disabled={!camera}
|
||||
onClick={() => runCanvasZoomCommand(camera?.hasSelection() ? "selection" : "fit")}>
|
||||
<Fullscreen aria-hidden="true" />
|
||||
<KeyHint shortcut={SHORTCUTS.camera.fit} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
);
|
||||
@@ -107,7 +105,6 @@ function RecenterControl() {
|
||||
disabled={!camera}
|
||||
onClick={() => runCanvasZoomCommand("recenter")}>
|
||||
<LocateFixed aria-hidden="true" />
|
||||
<KeyHint shortcut={SHORTCUTS.camera.center} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
);
|
||||
|
||||
@@ -2,8 +2,7 @@ import { GitCompareArrows, Keyboard, LayoutGrid, Map, Search } from "lucide-reac
|
||||
import { type CSSProperties } from "react";
|
||||
import { Tooltip } from "../shared/tooltip";
|
||||
import { useCanvasVisibleFrame } from "./visible-frame-provider";
|
||||
import { CANVAS_NUMBER_KEYS, formatShortcut, SHORTCUTS } from "../../utils/shortcuts";
|
||||
import { KeyHint } from "../shared/key-hint";
|
||||
import { formatShortcut, SHORTCUTS } from "../../utils/shortcuts";
|
||||
import {
|
||||
CANVAS_DESCRIPTIONS,
|
||||
CANVAS_LABELS,
|
||||
@@ -22,6 +21,9 @@ const TOOLBAR_MINIMUM_FRAME_WIDTH = 220;
|
||||
type CanvasToolbarProps = {
|
||||
canvas: CanvasView;
|
||||
searchOpen: boolean;
|
||||
/** How many changed screens Compare holds, shown as a badge on its button. Compare's own header
|
||||
steps through them. */
|
||||
compareCount?: number;
|
||||
/** Page-wide actions beside Search (Hand off to AI). */
|
||||
actions?: React.ReactNode;
|
||||
onSelectCanvas: (canvas: CanvasView) => void;
|
||||
@@ -58,7 +60,6 @@ export function CanvasToolbar(props: CanvasToolbarProps) {
|
||||
aria-expanded={props.searchOpen}
|
||||
onClick={props.onOpenSearch}>
|
||||
<Search />
|
||||
<KeyHint shortcut={SHORTCUTS.app.search} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
{props.actions}
|
||||
@@ -87,7 +88,9 @@ export function CanvasToolbar(props: CanvasToolbarProps) {
|
||||
onClick={() => props.onSelectCanvas(id)}>
|
||||
{VIEW_ICONS[id]}
|
||||
<span className="toolbar-view-label" aria-hidden="true"><span>{CANVAS_LABELS[id]}</span></span>
|
||||
{CANVAS_NUMBER_KEYS ? <KeyHint shortcut={SHORTCUTS.canvasByNumber[id]} /> : null}
|
||||
{id === "compare" && props.compareCount ? (
|
||||
<span className="toolbar-badge" aria-hidden="true">{props.compareCount}</span>
|
||||
) : null}
|
||||
</button>
|
||||
</Tooltip>
|
||||
);
|
||||
|
||||
@@ -3,7 +3,6 @@ import { useReactFlow, useStore } from "@xyflow/react";
|
||||
import { publishZoom, registerZoomApi, runCanvasZoomCommand } from "../../utils/canvas-zoom";
|
||||
import { isTyping, matchesShortcut, SHORTCUTS } from "../../utils/shortcuts";
|
||||
import { useCanvasVisibleFrame } from "./visible-frame-provider";
|
||||
import { createKeyHold, glideWhileHeld, type KeyHold } from "../../utils/key-hold";
|
||||
import {
|
||||
canvasBoundsViewport,
|
||||
canvasPriorityProjectionBounds,
|
||||
@@ -16,8 +15,6 @@ import {
|
||||
} from "./camera";
|
||||
|
||||
const DURATION = 160;
|
||||
/** React Flow's zoomIn/zoomOut step, which a tap of + or − takes. */
|
||||
const KEY_ZOOM_STEP = 1.2;
|
||||
const PIXEL_WHEEL_ZOOM_RATE = 0.002;
|
||||
const LINE_WHEEL_ZOOM_RATE = 0.05;
|
||||
const PAGE_WHEEL_ZOOM_RATE = 1;
|
||||
@@ -39,12 +36,6 @@ function canvasOwnsKeyboardEvent(event: KeyboardEvent, canvas: HTMLElement): boo
|
||||
return focusOwned || canvas.matches(":hover");
|
||||
}
|
||||
|
||||
function plainZoomDirection(event: KeyboardEvent): 1 | -1 | undefined {
|
||||
if (event.key === "+" || event.key === "=") return 1;
|
||||
if (event.key === "-" || event.key === "_") return -1;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function modifiedZoomCommand(event: KeyboardEvent): "in" | "out" | "100" | undefined {
|
||||
if (event.code === "Equal" || event.code === "NumpadAdd") return "in";
|
||||
if (event.code === "Minus" || event.code === "NumpadSubtract") return "out";
|
||||
@@ -69,12 +60,6 @@ export function ZoomBridge(props: {
|
||||
fitMaxZoom?: number;
|
||||
}) {
|
||||
const { visibleFrame } = useCanvasVisibleFrame();
|
||||
// Outlives the effect below, which re-runs as the camera moves: a held key must not end just
|
||||
// because its own zoom step re-registered the listeners.
|
||||
const holdRef = useRef<KeyHold>(undefined);
|
||||
holdRef.current ??= createKeyHold();
|
||||
const hold = holdRef.current;
|
||||
useEffect(() => () => hold.end(), [hold]);
|
||||
const {
|
||||
zoomIn,
|
||||
zoomOut,
|
||||
@@ -216,37 +201,8 @@ export function ZoomBridge(props: {
|
||||
};
|
||||
registerZoomApi(api);
|
||||
|
||||
// A tap of + or − takes one eased step. Held, the OS key repeat is ignored (each repeat
|
||||
// restarting the easing made holding slower than tapping); once the tap's step has landed the
|
||||
// camera glides instead, frame by frame about the pane's centre, as zoomIn does, until the key
|
||||
// is released, the hold is interrupted, or the zoom reaches its limit.
|
||||
const zoomStep = (direction: 1 | -1): boolean => {
|
||||
const viewport = getViewport();
|
||||
const next = Math.min(maxZoom, Math.max(minZoom, viewport.zoom * KEY_ZOOM_STEP ** direction));
|
||||
if (next === viewport.zoom) return false;
|
||||
if (direction === 1) void zoomIn({ duration: DURATION });
|
||||
else void zoomOut({ duration: DURATION });
|
||||
return true;
|
||||
};
|
||||
const zoomGlide = (direction: 1 | -1) => (steps: number): boolean => {
|
||||
const viewport = getViewport();
|
||||
const zoom = Math.min(maxZoom, Math.max(minZoom, viewport.zoom * KEY_ZOOM_STEP ** (direction * steps)));
|
||||
if (zoom === viewport.zoom) return false;
|
||||
const scale = zoom / viewport.zoom;
|
||||
const centerX = canvasWidth / 2;
|
||||
const centerY = canvasHeight / 2;
|
||||
void setViewport({ zoom, x: centerX - (centerX - viewport.x) * scale, y: centerY - (centerY - viewport.y) * scale });
|
||||
return true;
|
||||
};
|
||||
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
hold.interrupt(event);
|
||||
// Typing comes first: a held key's repeats belong to a field that took focus mid-hold.
|
||||
if (isTyping(event.target)) return;
|
||||
if (event.repeat && hold.holding(event.code)) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
|
||||
// Browser zoom and canvas zoom use the same familiar chord. The pointer/focus boundary
|
||||
// decides who owns it: canvas-owned events reset its camera; a focused panel or field keeps
|
||||
@@ -269,18 +225,10 @@ export function ZoomBridge(props: {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
const direction = plainZoomDirection(event);
|
||||
if (!direction) return;
|
||||
if (event.key === "+" || event.key === "=") runCanvasZoomCommand("in");
|
||||
else if (event.key === "-" || event.key === "_") runCanvasZoomCommand("out");
|
||||
else return;
|
||||
event.preventDefault();
|
||||
onCameraGestureStart.current?.();
|
||||
if (!zoomStep(direction)) return;
|
||||
// The hold only tracks the key (released, interrupted, a field or dialog taking over); the
|
||||
// glide reads it every frame and stops with it.
|
||||
hold.begin(event.code, () => true);
|
||||
glideWhileHeld(hold, event.code, DURATION, zoomGlide(direction));
|
||||
};
|
||||
const onKeyUp = (event: KeyboardEvent) => {
|
||||
if (hold.holding(event.code)) hold.end();
|
||||
};
|
||||
|
||||
const onModifierWheel = (event: WheelEvent) => {
|
||||
@@ -344,13 +292,9 @@ export function ZoomBridge(props: {
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
window.addEventListener("keyup", onKeyUp);
|
||||
window.addEventListener("blur", hold.end);
|
||||
canvas?.addEventListener("wheel", onModifierWheel, { capture: true, passive: false });
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onKeyDown);
|
||||
window.removeEventListener("keyup", onKeyUp);
|
||||
window.removeEventListener("blur", hold.end);
|
||||
canvas?.removeEventListener("wheel", onModifierWheel, { capture: true });
|
||||
if (wheelFrame.current !== undefined) cancelAnimationFrame(wheelFrame.current);
|
||||
wheelFrame.current = undefined;
|
||||
@@ -364,7 +308,6 @@ export function ZoomBridge(props: {
|
||||
getNodes,
|
||||
getNodesBounds,
|
||||
getViewport,
|
||||
hold,
|
||||
maxZoom,
|
||||
minZoom,
|
||||
props.fitPadding,
|
||||
|
||||
@@ -5,7 +5,6 @@ import { StatusGlyph } from "../shared/status-icon";
|
||||
import { Tooltip } from "../shared/tooltip";
|
||||
import { DIFF_LABELS, type DiffStatus } from "../../utils/build-diff";
|
||||
import { formatShortcut, SHORTCUTS } from "../../utils/shortcuts";
|
||||
import { KeyHint } from "../shared/key-hint";
|
||||
import { setMeasurementsShown, useMeasurementsShown } from "../../utils/measurements-setting";
|
||||
|
||||
/** A screen whose every changed area only moved: how far, per direction, and whether no other finding remains. */
|
||||
@@ -49,7 +48,6 @@ export function CompareNav(props: {
|
||||
<StatusGlyph status={props.status} accessibilityOnly={props.accessibilityOnly} label={props.statusLabel ?? DIFF_LABELS[props.status]} />
|
||||
{/* A route that does not fit loses its start, not the end that names the screen. */}
|
||||
<code className="compare-nav-route" title={props.title}><bdi>{props.route}</bdi></code>
|
||||
<KeyHint shortcut={SHORTCUTS.app.changes} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
{props.stepsApart ? null : <CompareSteps {...props} />}
|
||||
|
||||
@@ -6,7 +6,7 @@ import type { MapIndex } from "../../utils/model";
|
||||
import type { ChangedScreen } from "../../utils/changed-screens";
|
||||
import { groupVisualRegions, layoutShiftSummary, type VisualChange } from "../../utils/visual-diff";
|
||||
import { formatShortcut, matchesShortcut, SHORTCUTS, shortcutsLive } from "../../utils/shortcuts";
|
||||
import { createKeyHold, glideWhileHeld, HOLD_INITIAL_DELAY_MS, type KeyHold } from "../../utils/key-hold";
|
||||
import { HOLD_INITIAL_DELAY_MS, holdIntervalMs } from "../../utils/key-hold";
|
||||
import { optionalStorage } from "../../utils/embedded-report";
|
||||
import { usePhoneLayout } from "../../utils/phone-layout";
|
||||
import { ToggleGroup } from "../shared/toggle-group";
|
||||
@@ -160,12 +160,11 @@ export function useCompareController(options: CompareControllerOptions) {
|
||||
};
|
||||
const flip = () => setFlipSide((side) => (side === "after" ? "before" : "after"));
|
||||
|
||||
const keyState = useRef({ previous, next, mode, activeArea, options, swipePosition });
|
||||
keyState.current = { previous, next, mode, activeArea, options, swipePosition };
|
||||
const keyState = useRef({ previous, next, mode, activeArea, options });
|
||||
keyState.current = { previous, next, mode, activeArea, options };
|
||||
|
||||
// Stepping to the previous or next changed screen; a held key keeps stepping, accelerating, until
|
||||
// it is released, the window loses focus, or the end is reached. The Swipe divider is continuous,
|
||||
// so a tap of [ or ] nudges it one step and a held one glides. Both read the latest state.
|
||||
// it is released, the window loses focus, or the list ends. Reads the latest neighbours on each step.
|
||||
const stepScreen = (direction: 1 | -1): boolean => {
|
||||
const state = keyState.current;
|
||||
const target = direction === 1 ? state.next : state.previous;
|
||||
@@ -173,38 +172,34 @@ export function useCompareController(options: CompareControllerOptions) {
|
||||
state.options.onSelectScreen(target.id);
|
||||
return true;
|
||||
};
|
||||
const moveDivider = (direction: 1 | -1, steps = 1): boolean => {
|
||||
const state = keyState.current;
|
||||
if (state.mode !== "swipe") return false;
|
||||
const position = Math.max(0, Math.min(100, state.swipePosition + direction * SWIPE_STEP * steps));
|
||||
if (position === state.swipePosition) return false;
|
||||
state.swipePosition = position;
|
||||
setSwipePosition(position);
|
||||
return true;
|
||||
const hold = useRef<{ code: string; timer: ReturnType<typeof setTimeout> } | undefined>(undefined);
|
||||
const endHold = () => {
|
||||
if (!hold.current) return;
|
||||
clearTimeout(hold.current.timer);
|
||||
hold.current = undefined;
|
||||
};
|
||||
const holdRef = useRef<KeyHold>(undefined);
|
||||
holdRef.current ??= createKeyHold();
|
||||
const hold = holdRef.current;
|
||||
useEffect(() => hold.end, [hold]);
|
||||
// The hold only tracks the key; the glide reads it every frame and stops with it.
|
||||
const glideDivider = (code: string, direction: 1 | -1) => {
|
||||
hold.begin(code, () => true);
|
||||
glideWhileHeld(hold, code, HOLD_INITIAL_DELAY_MS, (steps) => moveDivider(direction, steps));
|
||||
const beginHold = (code: string, direction: 1 | -1) => {
|
||||
endHold();
|
||||
let step = 1;
|
||||
const tick = () => {
|
||||
if (!stepScreen(direction)) { endHold(); return; }
|
||||
hold.current = { code, timer: setTimeout(tick, holdIntervalMs(step)) };
|
||||
step += 1;
|
||||
};
|
||||
hold.current = { code, timer: setTimeout(tick, HOLD_INITIAL_DELAY_MS) };
|
||||
};
|
||||
useEffect(() => endHold, []);
|
||||
|
||||
useEffect(() => {
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
hold.interrupt(event);
|
||||
// The browser's own repeat of the held key is not a step; it must not scroll either.
|
||||
if (event.repeat && hold.holding(event.code)) { event.preventDefault(); return; }
|
||||
if (event.defaultPrevented || !shortcutsLive(event)) return;
|
||||
const state = keyState.current;
|
||||
const keys = SHORTCUTS.compare;
|
||||
const stepScreens = state.options.stepScreens !== false;
|
||||
if (stepScreens && matchesShortcut(event, keys.previousScreen)) {
|
||||
if (stepScreen(-1)) hold.begin(event.code, () => stepScreen(-1));
|
||||
if (stepScreen(-1)) beginHold(event.code, -1);
|
||||
} else if (stepScreens && matchesShortcut(event, keys.nextScreen)) {
|
||||
if (stepScreen(1)) hold.begin(event.code, () => stepScreen(1));
|
||||
if (stepScreen(1)) beginHold(event.code, 1);
|
||||
} else if (matchesShortcut(event, keys.nextArea)) {
|
||||
stepArea(1);
|
||||
} else if (matchesShortcut(event, keys.previousArea)) {
|
||||
@@ -225,10 +220,10 @@ export function useCompareController(options: CompareControllerOptions) {
|
||||
flip();
|
||||
} else if (matchesShortcut(event, keys.dividerLeft)) {
|
||||
if (state.mode !== "swipe") return;
|
||||
if (moveDivider(-1)) glideDivider(event.code, -1);
|
||||
setSwipePosition((value) => Math.max(0, value - SWIPE_STEP));
|
||||
} else if (matchesShortcut(event, keys.dividerRight)) {
|
||||
if (state.mode !== "swipe") return;
|
||||
if (moveDivider(1)) glideDivider(event.code, 1);
|
||||
setSwipePosition((value) => Math.min(100, value + SWIPE_STEP));
|
||||
} else if (matchesShortcut(event, keys.outlines)) {
|
||||
toggleOutlines();
|
||||
} else if (matchesShortcut(event, keys.whatChanged)) {
|
||||
@@ -239,15 +234,15 @@ export function useCompareController(options: CompareControllerOptions) {
|
||||
event.preventDefault();
|
||||
};
|
||||
const onKeyUp = (event: KeyboardEvent) => {
|
||||
if (hold.holding(event.code)) hold.end();
|
||||
if (hold.current && event.code === hold.current.code) endHold();
|
||||
};
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
window.addEventListener("keyup", onKeyUp);
|
||||
window.addEventListener("blur", hold.end);
|
||||
window.addEventListener("blur", endHold);
|
||||
return () => {
|
||||
window.removeEventListener("keydown", onKeyDown);
|
||||
window.removeEventListener("keyup", onKeyUp);
|
||||
window.removeEventListener("blur", hold.end);
|
||||
window.removeEventListener("blur", endHold);
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
@@ -17,8 +17,6 @@ export type ShortcutContext = {
|
||||
hasChanges: boolean;
|
||||
/** The report can be handed off to an agent (a hosted preview). */
|
||||
handoff?: boolean;
|
||||
/** The report was captured in both light and dark, so the app's appearance can be switched. */
|
||||
appearances?: boolean;
|
||||
};
|
||||
|
||||
const COMPARE = SHORTCUTS.compare;
|
||||
@@ -77,15 +75,13 @@ export function shortcutGroups(context: ShortcutContext): Group[][] {
|
||||
title: "View",
|
||||
rows: [
|
||||
...(context.canvas === "compare" ? [] : [{ label: "Show or hide the inspector", keys: [SHORTCUTS.panel.right] }]),
|
||||
{ label: "Viewer theme: dark or light", keys: [SHORTCUTS.appearance.theme] },
|
||||
...(context.appearances ? [{ label: "The app's appearance: light or dark", keys: [SHORTCUTS.appearance.app] }] : []),
|
||||
{ label: "Show this list", keys: ["?"] },
|
||||
],
|
||||
};
|
||||
const mapGroup: Group = {
|
||||
title: "Map",
|
||||
rows: [
|
||||
{ label: "Walk the map, or enter it at an edge", keys: ["↑", "↓", "←", "→", "H J K L"] },
|
||||
{ label: "Walk the map from the selected screen", keys: ["↑", "↓", "←", "→", "H J K L"] },
|
||||
{ label: "Undo or redo moving a card", keys: [SHORTCUTS.edit.undo, SHORTCUTS.edit.redo] },
|
||||
{ label: "Close the inspector, then deselect", keys: ["Esc"] },
|
||||
],
|
||||
|
||||
@@ -7,8 +7,6 @@ import { isPreviewPath, isReportTargetId, previewReportsUrl, targetQuery } from
|
||||
import { ScreenshotImage } from "../shared/screenshot-image";
|
||||
import { artifactUrl } from "../../utils/model";
|
||||
import { Tooltip } from "../shared/tooltip";
|
||||
import { KeyHint } from "../shared/key-hint";
|
||||
import { formatShortcut, SHORTCUTS } from "../../utils/shortcuts";
|
||||
import { ChangesMenu } from "./changes-menu";
|
||||
import type { FocusStatus } from "../../utils/navigation";
|
||||
import type { ExploreMap, MapIndex } from "../../utils/model";
|
||||
@@ -194,13 +192,12 @@ export function AppPill(props: AppPillProps) {
|
||||
) : null}
|
||||
{props.appearance ? (
|
||||
<>
|
||||
<Tooltip label="Appearance · the same screens captured in the other scheme" shortcut={formatShortcut(SHORTCUTS.appearance.app)} placement="bottom">
|
||||
<Tooltip label="Appearance · the same screens captured in the other scheme" placement="bottom">
|
||||
<button ref={appearanceRef} type="button" className="collapsed-platform" aria-haspopup="menu" aria-expanded={appearanceOpen}
|
||||
aria-label={`Appearance: ${appearanceLabel(props.appearance.current)}. Show the other appearance`}
|
||||
onClick={() => setAppearanceOpen(open => !open)}>
|
||||
{appearanceLabel(props.appearance.current)}
|
||||
<svg aria-hidden="true" width="8" height="8" viewBox="0 0 8 8"><path d="M1 2.5 4 5.5 7 2.5" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" /></svg>
|
||||
<KeyHint shortcut={SHORTCUTS.appearance.app} />
|
||||
</button>
|
||||
</Tooltip>
|
||||
<Menu items={appearanceItems} open={appearanceOpen} anchorRef={appearanceRef} ariaLabel="Appearance" onDismiss={() => setAppearanceOpen(false)} />
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import { Maximize, Minimize, Moon, Sun, SunMoon } from "lucide-react";
|
||||
import { Tooltip } from "../shared/tooltip";
|
||||
import { formatShortcut, SHORTCUTS } from "../../utils/shortcuts";
|
||||
import type { ThemePreference } from "../../utils/navigation";
|
||||
|
||||
export type ShellTheme = "light" | "dark";
|
||||
@@ -52,7 +51,7 @@ const THEME_LABELS: Record<ThemePreference, string> = {
|
||||
export function ThemeToggleButton(props: ShellActionsProps) {
|
||||
const Icon = props.themePreference === "system" ? SunMoon : props.themePreference === "dark" ? Moon : Sun;
|
||||
return (
|
||||
<Tooltip label={THEME_LABELS[props.themePreference]} shortcut={formatShortcut(SHORTCUTS.appearance.theme)} placement="bottom">
|
||||
<Tooltip label={THEME_LABELS[props.themePreference]} placement="bottom">
|
||||
<button
|
||||
type="button"
|
||||
className={props.className ?? "icon-button"}
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
import { heldKeyHint, useHeldModifiers } from "../../utils/held-modifiers";
|
||||
import type { Shortcut } from "../../utils/shortcuts";
|
||||
|
||||
/**
|
||||
* The key that completes a chord, shown on a button's corner while the chord's modifiers are
|
||||
* held. Hold ⌃ and the toolbar's sections show 1, 2 and 3; release it and they are gone.
|
||||
* Nothing renders for a plain key or while nothing is held.
|
||||
*/
|
||||
export function KeyHint({ shortcut }: { shortcut: Shortcut }) {
|
||||
const held = useHeldModifiers();
|
||||
const key = heldKeyHint(shortcut, held);
|
||||
if (!key) return null;
|
||||
return <kbd className="key-hint" aria-hidden="true">{key}</kbd>;
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import { screenTree, treeIndex, treeNodeKey, treeScreenOrder, type ScreenTree, t
|
||||
import type { Appearance } from "../../utils/appearance";
|
||||
import type { FocusRequest, FocusStatus } from "../../utils/navigation";
|
||||
import { shortcutsLive } from "../../utils/shortcuts";
|
||||
import { createKeyHold } from "../../utils/key-hold";
|
||||
import { HOLD_INITIAL_DELAY_MS, holdIntervalMs } from "../../utils/key-hold";
|
||||
import { placeholderScreen } from "../../utils/map-frame";
|
||||
import { ScreenScreenshotCard } from "../canvas/screen-screenshot-card";
|
||||
import { useCanvasVisibleFrame } from "../canvas/visible-frame-provider";
|
||||
@@ -393,23 +393,28 @@ export function ScreensView(props: ScreensViewProps) {
|
||||
pickRef.current(id);
|
||||
requestAnimationFrame(() => document.getElementById(cardId(id))?.querySelector<HTMLElement>(".screen-screenshot-target")?.focus({ preventScroll: true }));
|
||||
};
|
||||
// A held arrow keeps stepping from the card the last step landed on, not the lagging pick.
|
||||
const hold = createKeyHold();
|
||||
let hold: { code: string; at: string; timer: ReturnType<typeof setTimeout> } | undefined;
|
||||
const endHold = () => {
|
||||
if (hold) clearTimeout(hold.timer);
|
||||
hold = undefined;
|
||||
};
|
||||
const beginHold = (code: string, at: string) => {
|
||||
hold.begin(code, () => {
|
||||
const id = next(code, at);
|
||||
if (!id) return false;
|
||||
at = id;
|
||||
endHold();
|
||||
let step = 1;
|
||||
const tick = () => {
|
||||
const id = hold && next(code, hold.at);
|
||||
if (!hold || !id) { endHold(); return; }
|
||||
go(id);
|
||||
return true;
|
||||
});
|
||||
hold = { code, at: id, timer: setTimeout(tick, holdIntervalMs(step)) };
|
||||
step += 1;
|
||||
};
|
||||
hold = { code, at, timer: setTimeout(tick, HOLD_INITIAL_DELAY_MS) };
|
||||
};
|
||||
const onKeyDown = (event: globalThis.KeyboardEvent) => {
|
||||
hold.interrupt(event);
|
||||
const arrow = ["ArrowLeft", "ArrowRight", "ArrowUp", "ArrowDown"].includes(event.code);
|
||||
if (!arrow && event.key !== "Enter") return;
|
||||
// The browser's own repeat of a held arrow would scroll the page under the hold.
|
||||
if (event.repeat && hold.holding(event.code)) { event.preventDefault(); return; }
|
||||
if (event.repeat && hold?.code === event.code) { event.preventDefault(); return; }
|
||||
if (event.metaKey || event.ctrlKey || event.altKey || event.shiftKey || event.defaultPrevented || !shortcutsLive(event)) return;
|
||||
const target = event.target instanceof Element ? event.target : null;
|
||||
if (!arrow) {
|
||||
@@ -431,9 +436,8 @@ export function ScreensView(props: ScreensViewProps) {
|
||||
beginHold(event.code, id);
|
||||
};
|
||||
const onKeyUp = (event: globalThis.KeyboardEvent) => {
|
||||
if (hold.holding(event.code)) hold.end();
|
||||
if (hold && event.code === hold.code) endHold();
|
||||
};
|
||||
const endHold = hold.end;
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
window.addEventListener("keyup", onKeyUp);
|
||||
window.addEventListener("blur", endHold);
|
||||
|
||||
@@ -27,8 +27,7 @@ import type { FocusBehavior, FocusRequest, FocusStatus, MapDirection } from "../
|
||||
import { focusStatusOf } from "../../utils/changed-screens";
|
||||
import { displayPathForScreen } from "../../utils/screen-path";
|
||||
import { shortcutsLive } from "../../utils/shortcuts";
|
||||
import { arrowsOwnedBy, mapKeyDirection, mapKeyEntry, mapKeyTarget, type MapKeyDirection } from "../../utils/map-keyboard";
|
||||
import { createKeyHold } from "../../utils/key-hold";
|
||||
import { mapKeyDirection, mapKeyTarget } from "../../utils/map-keyboard";
|
||||
|
||||
const HOVER_CLEAR_DELAY = 180;
|
||||
const MAP_LAYOUT_REVISION = "flat-v1";
|
||||
@@ -553,51 +552,24 @@ function ConnectionCanvas(props: MapViewProps) {
|
||||
if (hoverClearTimer.current !== undefined) window.clearTimeout(hoverClearTimer.current);
|
||||
applyHover(undefined);
|
||||
}, [applyHover]);
|
||||
// The arrow keys (or h j k l) walk the map from the selected screen: along an edge in the
|
||||
// layout's flow, across to the neighbour on the same rank otherwise. With nothing selected they
|
||||
// enter the map at its edge, as on the Screens page. A held key keeps walking.
|
||||
// With a screen selected, the arrow keys (or h j k l) walk the map: along an edge in the
|
||||
// layout's flow, across to the neighbour on the same rank otherwise.
|
||||
const { selectedScreenId } = props;
|
||||
const selectedRef = useRef(selectedScreenId);
|
||||
selectedRef.current = selectedScreenId;
|
||||
useEffect(() => {
|
||||
const hold = createKeyHold();
|
||||
const move = (direction: MapKeyDirection, from: string | undefined): string | undefined => {
|
||||
const structure = structureRef.current;
|
||||
if (!structure) return undefined;
|
||||
return from ? mapKeyTarget(structure, from, direction) : mapKeyEntry(structure, direction);
|
||||
};
|
||||
if (!selectedScreenId) return;
|
||||
const onKeyDown = (event: KeyboardEvent) => {
|
||||
hold.interrupt(event);
|
||||
if (event.repeat && hold.holding(event.code)) { event.preventDefault(); return; }
|
||||
if (event.defaultPrevented || !shortcutsLive(event) || arrowsOwnedBy(event.target)) return;
|
||||
if (event.defaultPrevented || !shortcutsLive(event)) return;
|
||||
const direction = mapKeyDirection(event);
|
||||
if (!direction) return;
|
||||
if (!structureRef.current) return;
|
||||
const structure = structureRef.current;
|
||||
if (!structure) return;
|
||||
event.preventDefault();
|
||||
let at = move(direction, selectedRef.current);
|
||||
if (!at) return;
|
||||
selectScreen(at);
|
||||
hold.begin(event.code, () => {
|
||||
const target = move(direction, at);
|
||||
if (!target) return false;
|
||||
at = target;
|
||||
selectScreen(target);
|
||||
return true;
|
||||
});
|
||||
};
|
||||
const onKeyUp = (event: KeyboardEvent) => {
|
||||
if (hold.holding(event.code)) hold.end();
|
||||
const target = mapKeyTarget(structure, selectedScreenId, direction);
|
||||
if (target) selectScreen(target);
|
||||
};
|
||||
window.addEventListener("keydown", onKeyDown);
|
||||
window.addEventListener("keyup", onKeyUp);
|
||||
window.addEventListener("blur", hold.end);
|
||||
return () => {
|
||||
hold.end();
|
||||
window.removeEventListener("keydown", onKeyDown);
|
||||
window.removeEventListener("keyup", onKeyUp);
|
||||
window.removeEventListener("blur", hold.end);
|
||||
};
|
||||
}, [selectScreen]);
|
||||
return () => window.removeEventListener("keydown", onKeyDown);
|
||||
}, [selectScreen, selectedScreenId]);
|
||||
|
||||
const onViewportChange = useCallback((event: CanvasViewportChangeEvent) => {
|
||||
viewportChangeHandler.current?.(event);
|
||||
|
||||
+15
-20
@@ -1064,36 +1064,30 @@ code {
|
||||
opacity 170ms ease-in-out calc(var(--toolbar-motion) * 0.35),
|
||||
filter 170ms ease-in-out calc(var(--toolbar-motion) * 0.35);
|
||||
}
|
||||
/* The key that completes a chord, on a button's corner while its modifier is held: hold ⌃ and
|
||||
the toolbar's sections show 1, 2 and 3. Quiet: a small key in the element colour. */
|
||||
.toolbar-button:has(> .key-hint), .camera-action-button:has(> .key-hint), .collapsed-platform:has(> .key-hint), .compare-nav-picker:has(> .key-hint) { position: relative; }
|
||||
.key-hint {
|
||||
/* Compare's count of changed screens rides on its button's corner. */
|
||||
.toolbar-button:has(> .toolbar-badge) { position: relative; }
|
||||
.toolbar-badge {
|
||||
position: absolute;
|
||||
top: -6px;
|
||||
right: -6px;
|
||||
display: flex;
|
||||
min-width: 16px;
|
||||
height: 16px;
|
||||
min-width: 18px;
|
||||
height: 18px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0 4px;
|
||||
border-radius: 5px;
|
||||
color: var(--text);
|
||||
background: var(--element);
|
||||
box-shadow: 0 0 0 2px var(--surface), 0 1px 2px rgb(0 0 0 / 0.12);
|
||||
font: inherit;
|
||||
padding: 0 5px;
|
||||
border-radius: 9px;
|
||||
/* Light theme's deep orange takes white text, as the Modified pill does; dark theme's light
|
||||
orange takes dark text. */
|
||||
color: #fff;
|
||||
background: var(--modified);
|
||||
box-shadow: 0 0 0 2px var(--surface);
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
line-height: 1;
|
||||
font-weight: 700;
|
||||
font-variant-numeric: tabular-nums;
|
||||
pointer-events: none;
|
||||
animation: key-hint-in 100ms ease-out;
|
||||
}
|
||||
@keyframes key-hint-in {
|
||||
from { opacity: 0; transform: translateY(2px); }
|
||||
to { opacity: 1; transform: none; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { .key-hint { animation: none; } }
|
||||
:root[data-theme="dark"] .toolbar-badge { color: #0c0d0e; }
|
||||
/* Reduced motion: the bar takes its new width at once; only the names fade, without the blur. */
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.toolbar-view-label,
|
||||
@@ -2392,6 +2386,7 @@ html [data-sonner-toaster][data-sonner-theme] {
|
||||
background: #000;
|
||||
}
|
||||
|
||||
|
||||
.image-placeholder-reason {
|
||||
display: block;
|
||||
max-width: 80%;
|
||||
|
||||
@@ -1,84 +0,0 @@
|
||||
// Which modifier keys are down right now, so a button can show the key that completes a chord
|
||||
// with them: hold ⌃ and the toolbar's Map, Screens and Compare show 1, 2 and 3. One listener for
|
||||
// the window; components subscribe and re-render only when the set of held modifiers changes.
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { APPLE, isTyping, type Shortcut } from "./shortcuts";
|
||||
|
||||
export type HeldModifiers = { shift: boolean; ctrl: boolean; meta: boolean; alt: boolean };
|
||||
|
||||
const NONE: HeldModifiers = { shift: false, ctrl: false, meta: false, alt: false };
|
||||
// The modifiers physically down, and the ones the hints show: none while focus is in a field,
|
||||
// where a held Shift is for a capital letter, not for a chord. Focus can move by mouse with a
|
||||
// modifier still down, so the shown set is worked out again on every focus change too.
|
||||
let physical: HeldModifiers = NONE;
|
||||
let held: HeldModifiers = NONE;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function same(left: HeldModifiers, right: HeldModifiers): boolean {
|
||||
return left.shift === right.shift && left.ctrl === right.ctrl && left.meta === right.meta && left.alt === right.alt;
|
||||
}
|
||||
|
||||
function publish() {
|
||||
const next = isTyping(document.activeElement) ? NONE : physical;
|
||||
if (same(held, next)) return;
|
||||
held = same(next, NONE) ? NONE : next;
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
|
||||
function onKey(event: KeyboardEvent) {
|
||||
physical = { shift: event.shiftKey, ctrl: event.ctrlKey, meta: event.metaKey, alt: event.altKey };
|
||||
publish();
|
||||
}
|
||||
|
||||
function clear() {
|
||||
physical = NONE;
|
||||
publish();
|
||||
}
|
||||
|
||||
function subscribe(listener: () => void) {
|
||||
if (listeners.size === 0) {
|
||||
window.addEventListener("keydown", onKey, true);
|
||||
window.addEventListener("keyup", onKey, true);
|
||||
// A chord that leaves the page (⌘Tab, a browser shortcut) never sends its key up here.
|
||||
window.addEventListener("blur", clear);
|
||||
document.addEventListener("visibilitychange", clear);
|
||||
document.addEventListener("focusin", publish);
|
||||
document.addEventListener("focusout", publish);
|
||||
}
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
if (listeners.size > 0) return;
|
||||
window.removeEventListener("keydown", onKey, true);
|
||||
window.removeEventListener("keyup", onKey, true);
|
||||
window.removeEventListener("blur", clear);
|
||||
document.removeEventListener("visibilitychange", clear);
|
||||
document.removeEventListener("focusin", publish);
|
||||
document.removeEventListener("focusout", publish);
|
||||
physical = NONE;
|
||||
held = NONE;
|
||||
};
|
||||
}
|
||||
|
||||
export function useHeldModifiers(): HeldModifiers {
|
||||
return useSyncExternalStore(subscribe, () => held, () => NONE);
|
||||
}
|
||||
|
||||
/** The modifiers a shortcut needs, on this keyboard: ⌘ for `mod` on Apple keyboards, Ctrl elsewhere. */
|
||||
export function shortcutModifiers(shortcut: Shortcut, apple = APPLE): HeldModifiers {
|
||||
return {
|
||||
shift: Boolean(shortcut.shift),
|
||||
ctrl: Boolean(shortcut.ctrl) || (Boolean(shortcut.mod) && !apple),
|
||||
meta: Boolean(shortcut.mod) && apple,
|
||||
alt: Boolean(shortcut.alt),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The key that completes `shortcut` with exactly the modifiers held, or nothing: a plain key has no
|
||||
* chord to complete, and a held modifier that is not the shortcut's shows nothing for it.
|
||||
*/
|
||||
export function heldKeyHint(shortcut: Shortcut, held: HeldModifiers, apple = APPLE): string | undefined {
|
||||
if (same(held, NONE)) return undefined;
|
||||
return same(held, shortcutModifiers(shortcut, apple)) ? shortcut.key : undefined;
|
||||
}
|
||||
@@ -2,11 +2,8 @@
|
||||
* Paging by holding a key. The first step lands on key down; holding past the initial delay keeps
|
||||
* stepping, each step a little sooner than the last until the floor, the way a held scrollbar arrow
|
||||
* or a spinner accelerates. The browser's own key repeat is ignored (its rate is a fixed OS setting),
|
||||
* so the hold is timed here and ends on key up, another key, blur, a field or dialog taking the
|
||||
* keyboard, or the end of the list.
|
||||
* so the hold is timed here and ends on key up, blur, or the end of the list.
|
||||
*/
|
||||
import { isTyping, modalOpen } from "./shortcuts";
|
||||
|
||||
export const HOLD_INITIAL_DELAY_MS = 250;
|
||||
export const HOLD_FIRST_INTERVAL_MS = 200;
|
||||
export const HOLD_FLOOR_INTERVAL_MS = 70;
|
||||
@@ -27,93 +24,3 @@ export function holdSchedule(count: number): number[] {
|
||||
}
|
||||
return times;
|
||||
}
|
||||
|
||||
export type KeyHold = {
|
||||
/**
|
||||
* Starts holding `code` after its first step already landed. `step` takes the next step and
|
||||
* says whether there was one; the hold ends by itself when there is not.
|
||||
*/
|
||||
begin: (code: string, step: () => boolean) => void;
|
||||
end: () => void;
|
||||
/**
|
||||
* Ends the hold when another key goes down, as the OS's own key repeat stops. A modifier does
|
||||
* not end it, so ⇧ or ⌘ can join a held key. Call it first in the listener, before any guard.
|
||||
*/
|
||||
interrupt: (event: KeyboardEvent) => void;
|
||||
/** Whether `code` is the key being held. */
|
||||
holding: (code: string) => boolean;
|
||||
};
|
||||
|
||||
const MODIFIER_KEYS = new Set(["Shift", "Control", "Alt", "Meta"]);
|
||||
|
||||
/** Whether the keyboard is still the page's: nothing is being typed into and no dialog is open. */
|
||||
function keyboardFree(): boolean {
|
||||
if (typeof document === "undefined") return true;
|
||||
return !isTyping(document.activeElement) && !modalOpen();
|
||||
}
|
||||
|
||||
// A glide moves at the stepped hold's speeds, in tap steps per second: one step per first
|
||||
// interval at first, easing up to one per floor interval.
|
||||
const GLIDE_START_RATE = 1000 / HOLD_FIRST_INTERVAL_MS;
|
||||
const GLIDE_TOP_RATE = 1000 / HOLD_FLOOR_INTERVAL_MS;
|
||||
const GLIDE_RAMP_MS = 1000;
|
||||
/** A glide picks up from rest over this long, so it does not lurch out of the tap's step. */
|
||||
const GLIDE_PICKUP_MS = 80;
|
||||
|
||||
/** How fast a glide moves `elapsed` milliseconds after it began, in tap steps per second. */
|
||||
export function glideRate(elapsed: number): number {
|
||||
const ramp = Math.min(1, elapsed / GLIDE_RAMP_MS);
|
||||
return GLIDE_START_RATE * Math.min(1, elapsed / GLIDE_PICKUP_MS)
|
||||
+ (GLIDE_TOP_RATE - GLIDE_START_RATE) * ramp * ramp * (3 - 2 * ramp);
|
||||
}
|
||||
|
||||
/**
|
||||
* For a continuous value (a zoom, a divider) a held key glides instead of stepping: from `delayMs`
|
||||
* on, `move` is called every frame with how far to go, in tap steps (fractions of one), until the
|
||||
* hold ends. `move` says whether it moved; at a limit it does not, and the hold ends there.
|
||||
*/
|
||||
export function glideWhileHeld(hold: KeyHold, code: string, delayMs: number, move: (steps: number) => boolean): void {
|
||||
const start = performance.now() + delayMs;
|
||||
let last = start;
|
||||
const frame = (now: number) => {
|
||||
if (!hold.holding(code)) return;
|
||||
if (now > start) {
|
||||
const steps = glideRate(now - start) * (now - Math.max(last, start)) / 1000;
|
||||
last = now;
|
||||
if (!move(steps)) {
|
||||
hold.end();
|
||||
return;
|
||||
}
|
||||
}
|
||||
requestAnimationFrame(frame);
|
||||
};
|
||||
requestAnimationFrame(frame);
|
||||
}
|
||||
|
||||
/** One held key at a time, timed on the schedule above. */
|
||||
export function createKeyHold(): KeyHold {
|
||||
let current: { code: string; timer: ReturnType<typeof setTimeout> } | undefined;
|
||||
const end = () => {
|
||||
if (current) clearTimeout(current.timer);
|
||||
current = undefined;
|
||||
};
|
||||
return {
|
||||
begin(code, step) {
|
||||
end();
|
||||
let count = 1;
|
||||
const tick = () => {
|
||||
const next = holdIntervalMs(count);
|
||||
// A field or a dialog took the keyboard mid-hold: end, rather than step behind it.
|
||||
if (!current || !keyboardFree() || !step()) { end(); return; }
|
||||
current = { code, timer: setTimeout(tick, next) };
|
||||
count += 1;
|
||||
};
|
||||
current = { code, timer: setTimeout(tick, HOLD_INITIAL_DELAY_MS) };
|
||||
},
|
||||
end,
|
||||
interrupt(event) {
|
||||
if (current && !event.repeat && event.code !== current.code && !MODIFIER_KEYS.has(event.key)) end();
|
||||
},
|
||||
holding: (code) => current?.code === code,
|
||||
};
|
||||
}
|
||||
@@ -3,13 +3,6 @@ import type { ConnectionGroup } from "./graph-model";
|
||||
export type MapKeyDirection = "up" | "down" | "left" | "right";
|
||||
type Point = { x: number; y: number };
|
||||
|
||||
const ARROW_WIDGETS = '[role="menu"], [role="menubar"], [role="listbox"], [role="tree"], [role="tablist"], [role="radiogroup"], [role="slider"]';
|
||||
|
||||
/** Whether the key's target is a widget whose arrows are its own (a menu item, a list, tabs); the map leaves those keys to it. */
|
||||
export function arrowsOwnedBy(target: EventTarget | null): boolean {
|
||||
return target instanceof Element && target.closest(ARROW_WIDGETS) !== null;
|
||||
}
|
||||
|
||||
/** Arrow keys and their Vim twins; anything else is not a map move. */
|
||||
export function mapKeyDirection(event: Pick<KeyboardEvent, "key" | "altKey" | "ctrlKey" | "metaKey" | "shiftKey">): MapKeyDirection | undefined {
|
||||
if (event.altKey || event.ctrlKey || event.metaKey || event.shiftKey) return undefined;
|
||||
@@ -59,23 +52,3 @@ export function mapKeyTarget(
|
||||
}
|
||||
return best?.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* The screen an arrow selects when nothing is: the one at the edge the key moves away from, as
|
||||
* the Screens page's arrows enter at the first or last card. ↓ takes the topmost screen, ↑ the
|
||||
* bottom one, → the leftmost, ← the rightmost; ties go to the screen nearest the other axis's start.
|
||||
*/
|
||||
export function mapKeyEntry(
|
||||
structure: { positions: Map<string, Point> },
|
||||
direction: MapKeyDirection,
|
||||
): string | undefined {
|
||||
const vertical = direction === "up" || direction === "down";
|
||||
const sign = direction === "down" || direction === "right" ? 1 : -1;
|
||||
let best: { id: string; along: number; across: number } | undefined;
|
||||
for (const [id, point] of structure.positions) {
|
||||
const along = sign * (vertical ? point.y : point.x);
|
||||
const across = vertical ? point.x : point.y;
|
||||
if (!best || along < best.along || (along === best.along && across < best.across)) best = { id, along, across };
|
||||
}
|
||||
return best?.id;
|
||||
}
|
||||
@@ -16,7 +16,7 @@ export type Shortcut = {
|
||||
key: string;
|
||||
};
|
||||
|
||||
export const APPLE = typeof navigator !== "undefined"
|
||||
const APPLE = typeof navigator !== "undefined"
|
||||
&& /Mac|iPhone|iPad|iPod/.test(navigator.platform || navigator.userAgent);
|
||||
|
||||
/**
|
||||
@@ -61,11 +61,6 @@ export const SHORTCUTS = {
|
||||
panel: {
|
||||
right: plain("KeyI", "I"),
|
||||
},
|
||||
/** T is the Viewer's own light or dark theme; ⇧T is the captured app's appearance, in a report that has both. */
|
||||
appearance: {
|
||||
theme: plain("KeyT", "T"),
|
||||
app: shift("KeyT", "T"),
|
||||
},
|
||||
/** Canvas edits follow the platform-standard history keys. */
|
||||
edit: {
|
||||
undo: mod("KeyZ", "Z"),
|
||||
|
||||
Reference in new issue
Block a user