Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ee0e86fe56 | ||
|
|
8bb985a9d2 | ||
|
|
766f268ea6 | ||
|
|
01f32fdb33 | ||
|
|
43aed26c80 | ||
|
|
e84a4a19d0 | ||
|
|
a40ef9e9a5 | ||
|
|
0beef676a9 | ||
|
|
f90ab1f480 | ||
|
|
6a8dbfb5a3 | ||
|
|
e3afc2a00c | ||
|
|
a60ae5c6d8 | ||
|
|
d26e65db47 | ||
|
|
47f37988a5 | ||
|
|
1a5a95af63 | ||
|
|
fc5b465513 | ||
|
|
09b9f34e33 | ||
|
|
d61d9b9fc5 | ||
|
|
e8a03a362e | ||
|
|
bdd2d8349c | ||
|
|
4d0eddd811 | ||
|
|
02f470dde4 | ||
|
|
a0f192b1d7 | ||
|
|
d9137f1647 | ||
|
|
4481b50fc7 |
No files matched your search
@@ -2,7 +2,7 @@
|
||||
|
||||
How a review runs, from the pull request event to the Viewer link, and how the same pipeline runs locally. Readers who want the user-facing instructions should start with the [CI quick start](docs/quickstart-ci.md); this file is the map of the implementation.
|
||||
|
||||
Source of truth: `templates/explore-review.yml`, `templates/explore-baseline.yml`, `action.yml`, `src/ci/pipeline.ts`, `src/ci/verified-plan.ts`, `src/capture/run.ts`, `src/capture/route-capture.ts`, `src/capture/agent/*`, `test/ci/run.mjs`.
|
||||
Source of truth: `templates/explore-review.yml`, `templates/explore-baseline.yml`, `templates/explore-compare.yml`, `action.yml`, `src/ci/pipeline.ts`, `src/ci/verified-plan.ts`, `src/capture/run.ts`, `src/capture/route-capture.ts`, `src/capture/agent/*`, `test/ci/run.mjs`.
|
||||
|
||||
## At a glance
|
||||
|
||||
@@ -35,22 +35,23 @@ Older setups vendored the tools into `.github/vendor/expo-explore` and pinned th
|
||||
| --- | --- | --- | --- |
|
||||
| `explore-review.yml` | `pull_request_target` (opened, synchronize, reopened, ready_for_review), `workflow_dispatch` with `pr=N` | Open, non-draft, same-repository PR whose author has write access or is listed in `ci.trustedAuthors` | Captures base and head, compares, packages a report, comments on the PR |
|
||||
| `explore-baseline.yml` | `push` to the default branch, `workflow_dispatch` | Default branch only | Captures every route of one commit per configured platform and uploads `explore-baseline-<sha>-<platform>` for later PRs to reuse |
|
||||
| `explore-compare.yml` | `workflow_dispatch` or `workflow_call` with `base` and `head` (branch, tag or SHA) | Whoever can run or call workflows (write access) | Captures base and head, compares, packages a report like a PR review (`capture:review --compare`), and links it from the run summary; no PR comment |
|
||||
|
||||
Both workflows start with a `platforms` job: it installs the pinned CLI and runs `expo-explore config:platforms`, whose JSON list (`["ios"]`, `["ios","android"]`) becomes the matrix of the capture, report, and baseline jobs (`fail-fast: false`). Every matrix job passes `--platform ${{ matrix.platform }}`, so one platform's failure neither cancels nor hides the other's report.
|
||||
Each workflow starts with a `platforms` job: it installs the pinned CLI and runs `expo-explore config:platforms`, whose JSON list (`["ios"]`, `["ios","android"]`) becomes the matrix of the capture, report, and baseline jobs (`fail-fast: false`). Every matrix job passes `--platform ${{ matrix.platform }}`, so one platform's failure neither cancels nor hides the other's report.
|
||||
|
||||
### 2.2 `explore-review.yml`
|
||||
|
||||
| Job | Step | What it does |
|
||||
| --- | --- | --- |
|
||||
| capture (matrix: platform) | Resolve the live pull request and authorize its source | Reads the PR through the API. Forks, drafts and authors without write access (unless listed in `ci.trustedAuthors` of the default branch's `config.yaml`, read through the API) fail with `SOURCE_NOT_TRUSTED`. Writes `explore-pr.json` (repository, number, base/head ref and SHA). |
|
||||
| platforms | Install Explore, resolve and authorize the live pull request | As in the capture job below; it exports the PR's number and commits so the failure job can comment even when a capture job fails before resolving the PR itself. Then checks out head and lists the platforms. |
|
||||
| capture (matrix: platform) | Install Explore | Validates `EXPLORE_VERSION`, `npm pack`s that release into `$TOOLS_PREFIX`, then `npm ci --omit=dev --include=optional --ignore-scripts` against the release's shrinkwrap. The agent runtimes and `eas-cli` are optional dependencies, so `--include=optional` is what makes capture possible. The step is defined once per workflow file (a YAML anchor) and reused in every job. |
|
||||
| | Resolve and authorize the live pull request | `ci:pr` reads the PR through the API. Forks, drafts and authors without write access (unless listed in `ci.trustedAuthors` of the default branch's `config.yaml`, read through the API) fail with `SOURCE_NOT_TRUSTED`. Writes `explore-pr.json` (repository, number, base/head ref and SHA) and the step outputs. Runs before any PR code is checked out. |
|
||||
| | checkout `app-base`, `app-head` | Checks out the exact base and head SHAs with full history and without persisted credentials. |
|
||||
| | Install Explore | Validates `EXPLORE_VERSION`, `npm pack`s that release into `$TOOLS_PREFIX`, then `npm ci --omit=dev --include=optional --ignore-scripts` against the release's shrinkwrap. The agent runtimes and `eas-cli` are optional dependencies, so `--include=optional` is what makes capture possible. |
|
||||
| | Verify deterministic source planning | `source:verify` builds the capture plan from source alone in two fresh processes and compares the bytes. Runs before any build or simulator work and needs no credentials. |
|
||||
| | Install app dependencies | `npm ci --ignore-scripts` in both checkouts (`APP_INSTALL_DIR` for monorepos). |
|
||||
| | Find / Download optional exact-base evidence | Looks for a successful `explore-baseline-<base sha>-<platform>` artifact (iOS also accepts the older unsuffixed `explore-baseline-<base sha>`) from the baseline workflow on the default branch and downloads it as `EXPLORE_CAPTURE_CACHE`. Missing evidence is not an error. |
|
||||
| | Capture review | `capture:review` (§3). `EXPO_TOKEN`, the provider key and the app's `{{secret:NAME}}` values reach only this step. The sticky PR comment is updated while it runs. |
|
||||
| | Stop retained capture sessions | `always()`: stops the EAS Simulator sessions named in `head-session` / `base-session`, nothing else. |
|
||||
| | Verify application checkouts remain clean | A capture that modified an app checkout fails with `CHECKOUT_MODIFIED`. |
|
||||
| | Find / Download optional exact-base evidence | `ci:find-baseline` looks for a successful `explore-baseline-<base sha>-<platform>` artifact (iOS also accepts the older unsuffixed `explore-baseline-<base sha>`) from the baseline workflow on the default branch and downloads it as `EXPLORE_CAPTURE_CACHE`. Missing evidence is not an error. |
|
||||
| | Capture review | `capture:review` (§3). `EXPO_TOKEN`, the provider key and the app's `{{secret:NAME}}` values reach only this step. The sticky PR comment is updated while it runs. It writes `preview=<hosting>` to the step outputs, which decides whether the deploy job runs. |
|
||||
| | Stop capture sessions and check the checkouts | `ci:after-capture`, whenever the PR was resolved, success or not: stops the EAS Simulator sessions named in `head-session` / `base-session`, nothing else, then fails with `CHECKOUT_MODIFIED` if capture modified an app checkout. |
|
||||
| | Upload captured review / diagnostics | `explore-capture-<run>-<attempt>-<platform>` feeds the report job. On failure `explore-diagnostics-<run>-<attempt>-<platform>` keeps plans, exports and agent diagnostics for 7 days. |
|
||||
| report (matrix: platform) | Install Explore, download the capture | Runs without Expo or model credentials. |
|
||||
| | Package hosted review bundle | `ci:report` writes the report directory. |
|
||||
@@ -63,7 +64,11 @@ A reviewer downloads the report ZIP and drops it on the hosted Viewer; downloadi
|
||||
|
||||
### 2.3 `explore-baseline.yml`
|
||||
|
||||
Validate baseline source → Install Explore → Verify deterministic source planning (base = head = this SHA) → Install app dependencies → Capture complete single-commit baseline (`capture:baseline`; any missing route fails the job) → Stop retained baseline session → Verify application checkout remains clean → Upload exact-commit baseline evidence (`explore-baseline-<sha>`, 30 days) and, on failure, `explore-baseline-diagnostics-<run>-<attempt>`.
|
||||
Validate baseline source → Install Explore → Verify deterministic source planning (base = head = this SHA) → Install app dependencies → Capture complete single-commit baseline (`capture:baseline`; any missing route fails the job) → Stop the capture session and check the checkout (`ci:after-capture`) → Upload exact-commit baseline evidence (`explore-baseline-<sha>`, 30 days) and, on failure, `explore-baseline-diagnostics-<run>-<attempt>`.
|
||||
|
||||
### 2.4 `explore-compare.yml`
|
||||
|
||||
The same jobs as a PR review, for any `base` and `head` without a pull request. The `platforms` job resolves both refs once with `ci:compare-refs` (a tag wins over a branch of the same name; the same commit twice fails with `COMPARE_SAME_COMMIT`) and passes the comparison to the capture jobs, which run `capture:review --compare` with no GitHub requests. The optional `scope` and `expires-in` inputs override `exploration.scope` and `report.preview.expiresAfter` for that run. The report job's `ci:publish` writes each platform's **Open** and **zip** links to the run summary, and the deploy job adds the hosted link there; nothing comments on a pull request.
|
||||
|
||||
## 3. Inside `capture:review` (`runCiReview`)
|
||||
|
||||
@@ -134,12 +139,43 @@ A failure at any stage is recorded in `state.failure`, a partial report is writt
|
||||
| Source change \ evidence | Differs | Same | Not comparable |
|
||||
| --- | --- | --- | --- |
|
||||
| Route added / removed | Added / Removed | Added / Removed | Added / Removed |
|
||||
| Screen source changed (`screen`) | Modified | Needs review | Needs review |
|
||||
| Screen source changed (`screen`) | Modified | Unchanged (not counted as a change) | Needs review |
|
||||
| Only app-wide inputs changed (`app-wide`) | Modified | Unchanged (one line in the PR comment) | Needs review |
|
||||
| No source change (`none`) | Screen variant (listed apart from Changes) | Unchanged | Unchanged |
|
||||
|
||||
A screen whose source changed but whose screenshots were not compared (it is outside the capture scope) has no
|
||||
verdict: the PR comment does not list it, the agent API reports `not-compared`, and the Viewer marks it Not compared.
|
||||
Earlier versions listed it as Source-affected. A planned capture that failed is counted as unavailable and named under
|
||||
Validation.
|
||||
|
||||
"Differs" means the screenshots differ or the accessibility tree does. A Modified screen whose screenshots match is
|
||||
**Accessibility only**: what screen readers and voice control read changed (a label, a role, an element added to the tree)
|
||||
but nothing shows in the capture. It is still a change: the PR comment counts it apart ("3 visual changes · 12
|
||||
accessibility only") under 🟦 Accessibility only, the Viewer marks it blue and Compare steps through it, and the agent API
|
||||
reports `status: "accessibility-only"` with `sourceStatus: "modified"`. The report contract is unchanged (its review
|
||||
status stays `modified`), so earlier reports read the same way. The accessibility tree can include content outside the
|
||||
screenshot, such as rows scrolled below the fold or elements under a sheet, so an accessibility-only change is not always
|
||||
invisible on a device.
|
||||
|
||||
A pixel mismatch that rounds to 0.00% is noise and counts as "same". Diff regions inside the status-bar band are excluded from the verdict and reported as `ignoredStatusBarRegions`; the Viewer marks that band in Compare.
|
||||
|
||||
Each changed region also records whether its content only moved. CI searches for the shift (up to 20 screenshot
|
||||
pixels vertically and 4 horizontally, whole pixels and then sixths of one) that best lines Before up with After inside
|
||||
the region; near-ties go to the smallest move, and a second fit nearly as good two or more pixels away (repeating
|
||||
content) or a best fit at the edge of the search leaves the region unmeasured. When the shift explains most of the
|
||||
region's difference (a quarter for a move of half a pixel or less, where text re-rasterizes rather than moves; 60%
|
||||
above that) and, aligned by it, no more than two pixels still differ by over 140 in any channel, the region gets
|
||||
`shift: { x, y }` in screenshot pixels (right and down positive). New text, another colour or a caret is not a move.
|
||||
Every region the comparison found is measured, not only the eight it publishes, and `allRegionsMoved: true` says all
|
||||
of them moved. Moves are measured while the comparison's time budget lasts.
|
||||
|
||||
The Viewer draws moved areas dashed, at each side's own position, labelled with how far they moved to a tenth
|
||||
("↑4.1pt"); areas whose moves are within a third of each other merge into one outline, never around a changed area.
|
||||
When every region moved, What changed says how far per direction in place of the generic visual finding, and adds
|
||||
"Nothing on this screen changed content" when no other finding remains. A switch there turns the labels off. iOS
|
||||
screenshots are one pixel per point, so labels read in points; Android's are labelled in screenshot pixels, since the
|
||||
report does not know the screen's density.
|
||||
|
||||
## 7. Local CI test
|
||||
|
||||
`test/ci/run.mjs` runs the production pipeline against an app folder in this repository (`test/ci/apps/wallet`) and a scenario (`test/ci/scenarios/<app>/<name>/`: `scenario.json`, `overlay/`, `expected.json`, optional `setup.yaml`). The [local CI test harness README](test/ci/README.md) covers prerequisites, scenarios, expectations, the matrix runner and how to revisit a result. In outline:
|
||||
|
||||
@@ -4,14 +4,132 @@ Explore maps your app: a screenshot of every screen, connected by the taps betwe
|
||||
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/readme-hero-dark.png">
|
||||
<img alt="Explore's Map of the euxy app with the new About screen selected: every screen as a card laid out by distance from the launch screen, and the Inspector on the right showing the About capture as an added screen with its transitions" src="docs/screenshots/readme-hero-light.png">
|
||||
<img alt="Explore's Map of a euxy pull request, zoomed in on the new About screen, marked Added among the modified Patterns screens, with its transitions highlighted and the Inspector open on it, shown as a window on a soft stage" src="docs/screenshots/readme-hero-light.png">
|
||||
</picture>
|
||||
|
||||
**See a real report:** [euxy](https://explore-example--euxy.expo.app/p/rfcoic27ccgnrmzgijubxkmuzmptcrva?platform=ios), a MIDI sequencer, reviewed by Explore. It is redeployed with the current Viewer on every merge to main.
|
||||
|
||||
## Try it on your app
|
||||
<table>
|
||||
<tr>
|
||||
<td width="33%" valign="top">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/readme-compare-dark.png">
|
||||
<img width="100%" alt="The Compare view with the euxy Patterns screen's before and after captures side by side: each pattern row's tempo moved out of the subtitle into its own column on the right, the changed subtitles outlined in both" src="docs/screenshots/readme-compare-light.png">
|
||||
</picture>
|
||||
<strong>Compare</strong>: each changed screen before and after, with the changed regions outlined.
|
||||
</td>
|
||||
<td width="33%" valign="top">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/readme-screens-dark.png">
|
||||
<img width="100%" alt="The Screens view of a euxy review: the app/ route tree on the left under Changed 9 and All 19, and a grid of screen cards beside it in the same order, each with its route below the screenshot and a dot before it: green for the new /about, orange for modified screens such as /activity-log, /settings and /patterns, red for the removed /channel-surf" src="docs/screenshots/readme-screens-light.png">
|
||||
</picture>
|
||||
<strong>Screens</strong>: every capture in one grid, beside the route tree, with a dot for what changed.
|
||||
</td>
|
||||
<td width="33%" valign="top">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/readme-pr-comment-dark.png">
|
||||
<img width="100%" alt="Explore's GitHub PR comment on a euxy PR: the heading links to the iOS and Android reports, a table with one row per platform giving device, result and an Open link, the Added, Removed, Modified, Needs review and Source-affected screens as collapsed lists, fading out below them" src="docs/screenshots/readme-pr-comment-light.png">
|
||||
</picture>
|
||||
<strong>A comment on every PR</strong>: with <a href="#set-up-ci">CI</a>, the report links and the added, removed and modified screens.
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
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:
|
||||
<details>
|
||||
<summary><strong>Ask an agent about a report</strong></summary>
|
||||
|
||||
Paste this into Claude Code, Codex, Cursor, or any tool that can fetch a URL. In the Viewer, **Hand off to AI** fills it in for you:
|
||||
|
||||
```text
|
||||
Review the visual changes in this PR. Expo Explore report: <report link>
|
||||
|
||||
Fetch the link first. It explains the report's JSON API. Go through the changed screens,
|
||||
compare the before and after screenshots, and tell me which changes look intended and
|
||||
which look like regressions. For each regression, name the source file to fix.
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>Requirements</strong></summary>
|
||||
|
||||
- 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
|
||||
|
||||
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.
|
||||
|
||||
From your app's directory:
|
||||
|
||||
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 review builds your last commit as the "before".
|
||||
|
||||
```json
|
||||
{ "build": { "explore": { "ios": { "simulator": true } } } }
|
||||
```
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
Or paste this into Claude Code or Codex from your app's directory:
|
||||
|
||||
```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.
|
||||
```
|
||||
|
||||
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>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/readme-reports-dark.png">
|
||||
<img alt="npx @expo/explore reports in a terminal: the Expo Explore wordmark, then one line per saved run (a local review of HEAD vs main selected, an exploration of an app, and PR #1), and below them the selected run's head and base commits with their messages and its 13 modified, 2 added, 2 removed and 17 need-review screens" src="docs/screenshots/readme-reports-light.png">
|
||||
</picture>
|
||||
|
||||
<details>
|
||||
<summary><strong>Other commits, and what a review does</strong></summary>
|
||||
|
||||
```sh
|
||||
npx @expo/explore capture # HEAD and your uncommitted changes, against where HEAD left the default branch
|
||||
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 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.
|
||||
- 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>
|
||||
|
||||
Explore uses its defaults until you run `npx @expo/explore setup`, which writes `.expo-explore/config.yaml` for you to change. Next: [review every pull request](#set-up-ci).
|
||||
|
||||
## Map every screen of any app
|
||||
|
||||
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
|
||||
@@ -55,7 +173,7 @@ Explore starts an EAS Simulator, installs the build, taps through the app with y
|
||||
<details>
|
||||
<summary><strong>Explore a simulator session you already started</strong></summary>
|
||||
|
||||
If the app is already running on an `agent-device` EAS Simulator session, Explore can start from there. It leaves your session running.
|
||||
If the app is already running on an EAS Simulator session (`--type agent-device` or `--type argent`), Explore can start from there, with the session's controller. It leaves your session running.
|
||||
|
||||
```sh
|
||||
eas simulator:start --type agent-device --out-config-type dotenv # then agent-device install / open
|
||||
@@ -70,15 +188,19 @@ 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 [CI](#set-up-ci-reviews-on-every-pr).
|
||||
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).
|
||||
|
||||

|
||||
|
||||
</details>
|
||||
|
||||
## Set up CI: reviews on every PR
|
||||
## Set up CI
|
||||
|
||||
Paste this into Claude Code or Codex from your app's repository:
|
||||
Explore runs in your repository's GitHub Actions in two ways, both from the same setup: a review on every pull request, and a comparison of any two commits, such as a release against the last one.
|
||||
|
||||
### 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 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
|
||||
@@ -90,44 +212,45 @@ what to merge and how to start the first review.
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary><strong>Requirements</strong></summary>
|
||||
<summary id="hosted-previews"><strong>Hosted previews</strong></summary>
|
||||
|
||||
- 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.
|
||||
By default reviewers download the report from GitHub. With hosted previews, the comment's **Explore report** link opens it in one click, even in private repositories.
|
||||
|
||||
```yaml
|
||||
report:
|
||||
preview:
|
||||
hosting: eas # default: off
|
||||
expiresAfter: 30d # default 30d, max 365d, or never
|
||||
# project: acme-explore # default <repository name>-explore, created on first run
|
||||
```
|
||||
|
||||
- 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, 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).
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>After setup: your first review</strong></summary>
|
||||
<summary><strong>Manual setup</strong></summary>
|
||||
|
||||
1. Set the repository secrets that `expo-explore doctor` lists, such as `EXPO_TOKEN`.
|
||||
2. Merge the setup to the default branch and run **Expo Explore baseline** from GitHub Actions.
|
||||
3. Open a PR. **Expo Explore review** runs and posts a comment with the report.
|
||||
The prompt above walks through these steps with you. To do them yourself:
|
||||
|
||||
```sh
|
||||
expo-explore doctor # check every step; exits 1 until ready
|
||||
expo-explore doctor --capture # capture the committed app on EAS once, before the first PR
|
||||
```
|
||||
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 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, 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).
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>Set up without a coding agent</strong></summary>
|
||||
|
||||
```sh
|
||||
npx @expo/explore setup # writes .expo-explore/config.yaml and the two workflows; in a monorepo: --project apps/mobile
|
||||
npx @expo/explore doctor # fix each problem it reports, then commit
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>Choose a capture mode</strong></summary>
|
||||
<summary><strong>Capture modes: deterministic or agent</strong></summary>
|
||||
|
||||
| | **Deterministic** (recommended to start) | **Agent** |
|
||||
| --- | --- | --- |
|
||||
@@ -138,10 +261,7 @@ npx @expo/explore doctor # fix each problem it reports, then commit
|
||||
|
||||
Both modes use the same comparison rules and report. You can change modes later.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>Configure agent mode</strong></summary>
|
||||
**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` and an `agent.model` your account can use.
|
||||
@@ -153,15 +273,7 @@ The model navigates and recovers on each uncaptured revision; see [agent usage](
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary><strong>Repository settings</strong></summary>
|
||||
|
||||
- `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 `expo-explore setup --workflows` after you add one.
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary id="platforms"><strong>Android and several platforms</strong></summary>
|
||||
<summary id="platforms"><strong>iOS, Android, or both</strong></summary>
|
||||
|
||||
`app.platform` names the primary platform, and a `platforms` map adds the other. Each entry can set its own `device`, `bundleId`, and `easProfile`.
|
||||
|
||||
@@ -187,21 +299,25 @@ platforms:
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary id="hosted-previews"><strong>Hosted previews</strong></summary>
|
||||
<summary id="controller"><strong>Device controller: agent-device or Argent</strong></summary>
|
||||
|
||||
By default reviewers download the report from GitHub. With hosted previews, the comment's **Explore report** link opens it in one click, even in private repositories.
|
||||
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
|
||||
report:
|
||||
preview:
|
||||
hosting: eas # default: off
|
||||
expiresAfter: 30d # default 30d, max 365d, or never
|
||||
# project: acme-explore # default <repository name>-explore, created on first run
|
||||
capture:
|
||||
controller: argent # agent-device (default) | argent
|
||||
```
|
||||
|
||||
- Run `expo-explore setup --workflows` after enabling it to add the `deploy` job.
|
||||
- `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).
|
||||
```sh
|
||||
npx @expo/explore capture --controller argent
|
||||
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.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 an Argent capture records one appearance: the one the app forces, else light. Explore warns when it skips one.
|
||||
|
||||
</details>
|
||||
|
||||
@@ -210,7 +326,71 @@ report:
|
||||
|
||||
- A PR that adds a guarded screen or a dynamic route should also update `config.yaml`.
|
||||
- Renamed identifiers or labels break deterministic setup steps.
|
||||
- To update Explore, run `npx @expo/explore@latest setup --workflows` and commit the new version.
|
||||
- To update Explore, run `npx @expo/explore@latest setup --workflows` and commit the new version. It also adds `explore-compare.yml` if you don't have it, and `doctor` warns when it is missing.
|
||||
|
||||
</details>
|
||||
|
||||
### Compare any two commits
|
||||
|
||||
A release, a release candidate, a nightly: any two branches, tags or commits, reviewed like a PR without one, with the report linked from the run's summary. Once CI reviews PRs, paste this into Claude Code or Codex:
|
||||
|
||||
```text
|
||||
Set up Expo Explore to review this app's releases. Follow the "Compare any two commits"
|
||||
section of https://unpkg.com/@expo/explore/skills/explore-setup/SKILL.md: make sure
|
||||
explore-compare.yml is installed, add a workflow that compares each release tag (and
|
||||
release candidate) with the last stable release, then run it once on the latest tag and
|
||||
give me the report link.
|
||||
```
|
||||
|
||||
There are a few ways to snapshot a release:
|
||||
|
||||
- **On demand:** in your repository's Actions tab, open **Expo Explore compare**, choose **Run workflow**, and set `base` to the last release's tag (`v1.3.0`), `head` to the new tag or release candidate (`v1.4.0-rc.1`), `scope` to `all` and `expires-in` to `never`. The run's summary links the report.
|
||||
- **Automatically, on every tag:** add the `release-review.yml` in [The comparison workflow](#compare) below. It compares each tag, release candidates included, with the last stable tag, so a release candidate is reviewed against what people have now.
|
||||
- **On your machine, without CI:** `npx @expo/explore capture --base v1.3.0 --head v1.4.0 --scope all --upload`, with your `eas login`. `npx @expo/explore reports` lists the runs you have kept.
|
||||
|
||||
`scope: all` captures every screen, not only those whose source changed, so the report shows the whole release with what changed since the last one marked; `expires-in: never` keeps its link.
|
||||
|
||||
<details>
|
||||
<summary id="compare"><strong>The comparison workflow</strong></summary>
|
||||
|
||||
`.github/workflows/explore-compare.yml` reviews a `head` against a `base`, each a branch, tag or commit SHA, with no pull request. It captures, compares and reports exactly like a PR review, and links the report from the run's summary.
|
||||
|
||||
Run it from the Actions tab, or call it from a workflow on any event:
|
||||
|
||||
```yaml
|
||||
# .github/workflows/release-review.yml: each release tag (or release candidate) against the last stable release
|
||||
on:
|
||||
push:
|
||||
tags: ['v*']
|
||||
jobs:
|
||||
previous:
|
||||
runs-on: ubuntu-latest
|
||||
outputs: { tag: '${{ steps.tag.outputs.tag }}' }
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with: { fetch-depth: 0 }
|
||||
# The newest earlier tag that is not a prerelease (v1.4.0-rc.1 has a "-"); none for the first release.
|
||||
- id: tag
|
||||
run: echo "tag=$(git describe --tags --abbrev=0 --exclude '*-*' "$GITHUB_REF_NAME^" 2>/dev/null || true)" >> "$GITHUB_OUTPUT"
|
||||
explore:
|
||||
needs: previous
|
||||
if: needs.previous.outputs.tag != ''
|
||||
permissions: { contents: read, actions: read }
|
||||
uses: ./.github/workflows/explore-compare.yml
|
||||
with:
|
||||
base: '${{ needs.previous.outputs.tag }}'
|
||||
head: '${{ github.ref_name }}'
|
||||
scope: all # every screen, not only those whose source changed
|
||||
expires-in: never # keep the hosted link (with report.preview.hosting: eas)
|
||||
secrets: inherit
|
||||
```
|
||||
|
||||
- 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 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, 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>
|
||||
|
||||
@@ -243,46 +423,7 @@ If the sign-in can't be typed (one-time codes, email links, Sign in with Apple o
|
||||
|
||||
When a run stops early, `gap:list --dir <output>` says what blocked it.
|
||||
|
||||
## What you get
|
||||
|
||||
### A comment on every PR
|
||||
|
||||
The report links, a row per platform, and the added, removed and modified screens.
|
||||
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/readme-pr-comment-dark.png">
|
||||
<img alt="Explore's GitHub PR comment on a euxy PR: the heading links to the iOS and Android reports, a table with one row per platform giving device, result and an Open link, the Added, Removed, Modified, Needs review and Source-affected screens as collapsed lists, fading out below them" src="docs/screenshots/readme-pr-comment-light.png">
|
||||
</picture>
|
||||
|
||||
### Compare
|
||||
|
||||
Each changed screen before and after, with the changed regions outlined.
|
||||
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/readme-compare-dark.png">
|
||||
<img alt="The Compare view with the euxy Patterns screen's before and after captures side by side: each pattern row's tempo moved out of the subtitle into its own column on the right, the changed subtitles outlined in both" src="docs/screenshots/readme-compare-light.png">
|
||||
</picture>
|
||||
|
||||
### Screens
|
||||
|
||||
Every capture, in a section per route folder, with a route tree whose folders fold away and a **Changed** / **All** filter.
|
||||
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="docs/screenshots/readme-screens-dark.png">
|
||||
<img alt="The Screens view of a euxy review: a foldable route tree on the left with Changed and All above it, and the screens in sections named after their app/ folder (Launch, Sequencer, Settings, Patterns) with each folder path beneath, the new About screen marked Added, Activity Log and Settings marked Modified, and the Sequencer marked No visible change" src="docs/screenshots/readme-screens-light.png">
|
||||
</picture>
|
||||
|
||||
### Ask an agent about it
|
||||
|
||||
Paste this into Claude Code, Codex, Cursor, or any tool that can fetch a URL. In the Viewer, **Hand off to AI** fills it in for you:
|
||||
|
||||
```text
|
||||
Review the visual changes in this PR. Expo Explore report: <report link>
|
||||
|
||||
Fetch the link first. It explains the report's JSON API. Go through the changed screens,
|
||||
compare the before and after screenshots, and tell me which changes look intended and
|
||||
which look like regressions. For each regression, name the source file to fix.
|
||||
```
|
||||
## Additional information
|
||||
|
||||
<details>
|
||||
<summary><strong>Terms in the report</strong></summary>
|
||||
@@ -301,7 +442,7 @@ The same link answers differently depending on who asks. It already carries the
|
||||
|
||||
- A browser gets the Viewer.
|
||||
- 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,added,removed`, `/screens/<id>`, `/transitions`, and `/raw` for the report file.
|
||||
- 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`.
|
||||
- Multi-platform reports take `?platform=ios|android`. Expired links answer `410`.
|
||||
|
||||
@@ -311,8 +452,6 @@ curl -s "$LINK/api/v1/screens?status=modified" | jq '.items[] | {route, status,
|
||||
|
||||
</details>
|
||||
|
||||
## More
|
||||
|
||||
<details>
|
||||
<summary><strong>How it works</strong></summary>
|
||||
|
||||
@@ -322,6 +461,8 @@ curl -s "$LINK/api/v1/screens?status=modified" | jq '.items[] | {route, status,
|
||||
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.
|
||||
|
||||
The same review runs for any two commits without a PR ([`explore-compare.yml`](#compare-any-two-commits), linking the report from the run summary) and on your machine (`capture`, [above](#quick-start)). The workflows' logic lives in `expo-explore ci:*` commands, so a fix reaches CI with the `@expo/explore` version the workflows pin.
|
||||
|
||||
Reports and baselines are kept for 30 days and diagnostics for 7. Hosted deployments are never deleted automatically; see [report access](docs/private-review.md).
|
||||
|
||||
</details>
|
||||
@@ -335,6 +476,7 @@ Reports and baselines are kept for 30 days and diagnostics for 7. Hosted deploym
|
||||
- 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`, each capture records one appearance (see [device controller](#controller)).
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
@@ -164,7 +164,7 @@ imported source changed), `app-wide` (only app-wide inputs such as dependencies,
|
||||
| Source \ Evidence | Differs | No visible difference | Inconclusive |
|
||||
| --- | --- | --- | --- |
|
||||
| Added / removed route | Added / Removed | Added / Removed | Added / Removed |
|
||||
| Screen source changed | Modified | Needs review | Needs review |
|
||||
| Screen source changed | Modified | Unchanged (not counted as a change) | Needs review |
|
||||
| Only app-wide inputs changed | Modified | Unchanged (the PR comment names the app-wide change once) | Needs review |
|
||||
| Source unchanged | Screen variant | Unchanged | Unchanged |
|
||||
|
||||
@@ -172,13 +172,20 @@ imported source changed), `app-wide` (only app-wide inputs such as dependencies,
|
||||
| --- | --- |
|
||||
| Added / Removed | Route presence differs between source inventories |
|
||||
| Modified | The screen's source changed and comparable evidence differs |
|
||||
| Needs review | The screen's source changed but no visible difference was captured, or its evidence is inconclusive; still a review target |
|
||||
| Accessibility only | Modified, but the screenshots match: only the accessibility tree (what screen readers and voice control read) differs. Counted as a change and listed apart from the visual ones |
|
||||
| Needs review | The screen's source changed and the comparison could not tell whether it looks different; a review target |
|
||||
| Screen variant | No source change reaches the screen, but its captures differ in runtime UI state (balances, timestamps, loaded content). Listed apart from changes |
|
||||
| Source-affected | Source impact without a comparison |
|
||||
| Unchanged | No visible difference and no screen-specific source change |
|
||||
| Not compared | No comparison was performed |
|
||||
| Unchanged | No visible difference, whether or not the screen's source changed. Explore reports visual changes; reports before 0.19.1 called a source change with no visible difference Needs review |
|
||||
| Not compared | No comparison was performed, including for a screen whose source changed. Not counted as a change: Explore reports what the captures show, not what the code might do. Earlier versions listed these as Source-affected |
|
||||
|
||||
A difference that rounds to 0.00% of pixels is rendering noise and counts as no difference.
|
||||
A changed region whose content only moved (a layout that grew by a device pixel, a sheet that is taller) carries
|
||||
`shift`, how far it moved in screenshot pixels, and `allRegionsMoved: true` says every region CI found moved (it
|
||||
publishes the largest eight); the Viewer labels each outline with its move. A shift does not change the verdict: a
|
||||
moved screen is still Modified.
|
||||
Accessibility only is how readers present a `modified` verdict whose visual verdict is `unchanged`; the contract has no
|
||||
separate status for it, so reports from earlier versions show it too. The accessibility tree can include content outside
|
||||
the screenshot (rows below the fold, elements under a sheet), so such a change may still be visible on a device.
|
||||
A runtime difference is not proof that the code change caused it. Deterministic mode uses template notes and evidence facts. Agent mode adds AI explanations from the captured evidence and source changes through a separate CLI session; those explanations cannot override fixed verdicts. Structural flows describe possible source navigation; semantic business grouping remains deferred.
|
||||
|
||||
## Artifacts and cache
|
||||
|
||||
@@ -101,9 +101,11 @@ navigation:
|
||||
# entry: src/navigation/RootNavigator.tsx
|
||||
device:
|
||||
name: iPhone 17 # Android: an AVD profile id such as pixel_7
|
||||
# pose: open # a foldable (iPhone Duo): closed (the outer display, how a session starts) | half-open | open (the inner display)
|
||||
exploration:
|
||||
scope: changes # changes | all
|
||||
capture:
|
||||
# controller: agent-device # agent-device (default) | argent (one appearance per capture until Argent can switch it; --controller overrides it for one run)
|
||||
maxMinutes: 30
|
||||
maxActions: 500
|
||||
repack: eas # eas (hosted EAS workflow job, default) | local (repack-app + eas upload on the runner)
|
||||
@@ -319,13 +321,13 @@ The capture and publishing jobs use Expo and GitHub credentials. The review work
|
||||
|
||||
Older setups committed a copy of the tools to `.github/vendor/expo-explore` and pinned it with an `EXPLORE_TOOLS_COMMIT` repository variable. `expo-explore doctor` reports these: delete the directory and both workflows, rerun `expo-explore setup --workflows`, and delete the variable.
|
||||
|
||||
## 3. Install the two workflows
|
||||
## 3. Install the workflows
|
||||
|
||||
```sh
|
||||
expo-explore setup --workflows
|
||||
```
|
||||
|
||||
Install these on the default branch. Remove superseded Explore workflows to prevent duplicate captures and comments.
|
||||
This writes `explore-review.yml` (pull requests), `explore-baseline.yml` (the default branch) and `explore-compare.yml` (any two commits, from the Actions tab or another workflow; see [Review any two commits](../README.md#compare)). Install these on the default branch. Remove superseded Explore workflows to prevent duplicate captures and comments.
|
||||
|
||||
Both templates use `APP_PROJECT_DIR` and `APP_INSTALL_DIR`, defaulting to `.`. For a monorepo, the project directory might be `apps/mobile` while the lockfile/install directory remains `.`. Keep config paths relative to the app. `expo-explore setup --workflows` replaces `npm ci --ignore-scripts` with the frozen-lockfile install of the package manager whose lockfile it finds: pnpm, Yarn, or bun. For bun it also adds an `oven-sh/setup-bun` step, because the runner does not have bun.
|
||||
|
||||
|
||||
|
Before Width: | Height: | Size: 452 KiB After Width: | Height: | Size: 451 KiB |
|
Before Width: | Height: | Size: 452 KiB After Width: | Height: | Size: 452 KiB |
|
Before Width: | Height: | Size: 870 KiB After Width: | Height: | Size: 847 KiB |
|
Before Width: | Height: | Size: 832 KiB After Width: | Height: | Size: 830 KiB |
|
Before Width: | Height: | Size: 151 KiB After Width: | Height: | Size: 151 KiB |
|
Before Width: | Height: | Size: 147 KiB After Width: | Height: | Size: 147 KiB |
|
After Width: | Height: | Size: 169 KiB |
|
After Width: | Height: | Size: 179 KiB |
|
Before Width: | Height: | Size: 610 KiB After Width: | Height: | Size: 642 KiB |
|
Before Width: | Height: | Size: 606 KiB After Width: | Height: | Size: 643 KiB |
@@ -1,18 +1,17 @@
|
||||
{
|
||||
"name": "@expo/explore",
|
||||
"version": "0.18.1",
|
||||
"version": "0.19.5",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@expo/explore",
|
||||
"version": "0.18.1",
|
||||
"version": "0.19.5",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@expo/repack-app": "0.10.1",
|
||||
"@types/node": "^22.19.19",
|
||||
"@zip.js/zip.js": "2.16.0",
|
||||
"agent-device": "0.21.15",
|
||||
"ajv": "^8.17.1",
|
||||
"pngjs": "7.0.0",
|
||||
"typescript": "^5.9.3",
|
||||
@@ -30,6 +29,7 @@
|
||||
"@types/react-dom": "^19.2.4",
|
||||
"@vitejs/plugin-react": "^4.7.0",
|
||||
"@xyflow/react": "^12.11.3",
|
||||
"agent-device": "0.21.15",
|
||||
"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": "24.4.2"
|
||||
"eas-cli": "25.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@0no-co/graphql.web": {
|
||||
@@ -1600,15 +1600,15 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@expo/eas-build-job": {
|
||||
"version": "24.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@expo/eas-build-job/-/eas-build-job-24.3.0.tgz",
|
||||
"integrity": "sha512-CyDUm8B8pSH38XZg8QzdPaxukThspSWfJ4ccUBCzBLs/qL6SknaLVswD3OTxNQmirrZUyo72DfzupSxHDZOeyw==",
|
||||
"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": "24.0.0",
|
||||
"@expo/logger": "25.0.0",
|
||||
"@expo/results": "1.0.0",
|
||||
"@expo/turtle-spawn": "24.0.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": "24.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@expo/eas-json/-/eas-json-24.3.0.tgz",
|
||||
"integrity": "sha512-FIdvHmGeRFB0BoA4+aicn/tnpUUTSre4cCrN/hk6xkHOlpbjDVyl2tFaEe0RpiI1itrQ2ze/KTUYqdyecfHv0Q==",
|
||||
"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": "24.3.0",
|
||||
"@expo/eas-build-job": "25.0.0",
|
||||
"chalk": "4.1.2",
|
||||
"env-string": "1.0.1",
|
||||
"fs-extra": "11.2.0",
|
||||
@@ -1900,9 +1900,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@expo/logger": {
|
||||
"version": "24.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@expo/logger/-/logger-24.0.0.tgz",
|
||||
"integrity": "sha512-LezHQbZbqa7papq2ciCmwEjz4gUxe3b4oIdl3IU/wp3WGy+zQ4s+xKdDuUCbDLVkbqABBgVNqFav4ucXo1Gh/w==",
|
||||
"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": {
|
||||
@@ -2592,14 +2592,14 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@expo/steps": {
|
||||
"version": "24.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@expo/steps/-/steps-24.3.0.tgz",
|
||||
"integrity": "sha512-y0zuyUaivXiq1l7D0x9xosUbhtknDwQ4v669smGslshEYXZAuxYQJo0L6H0MRuRsaZn6N8zvfICBM+4n/n4Xeg==",
|
||||
"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": "24.3.0",
|
||||
"@expo/logger": "24.0.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",
|
||||
@@ -2637,13 +2637,13 @@
|
||||
"optional": true
|
||||
},
|
||||
"node_modules/@expo/turtle-spawn": {
|
||||
"version": "24.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@expo/turtle-spawn/-/turtle-spawn-24.0.0.tgz",
|
||||
"integrity": "sha512-HtumnPY7iVCc6vDmSmjsUEvhIPnmwVzpQ2aNPxAX+G0M2Zst88DAlItOd7mZUPSNNO8qp3izDPtqmI0fdLYPng==",
|
||||
"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": "24.0.0",
|
||||
"@expo/logger": "25.0.0",
|
||||
"@expo/spawn-async": "^1.7.2"
|
||||
}
|
||||
},
|
||||
@@ -4556,6 +4556,16 @@
|
||||
"node": ">=0.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/agent-base": {
|
||||
"version": "7.1.4",
|
||||
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz",
|
||||
"integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"engines": {
|
||||
"node": ">= 14"
|
||||
}
|
||||
},
|
||||
"node_modules/agent-cli-detector": {
|
||||
"version": "0.1.7",
|
||||
"resolved": "https://registry.npmjs.org/agent-cli-detector/-/agent-cli-detector-0.1.7.tgz",
|
||||
@@ -4573,6 +4583,7 @@
|
||||
"version": "0.21.15",
|
||||
"resolved": "https://registry.npmjs.org/agent-device/-/agent-device-0.21.15.tgz",
|
||||
"integrity": "sha512-Om1j6oNJkeKlkk8lBM+0V9bKwpxUXLMf/PDDSvAt3RFquBRqAiM58J81E0rvPQNxs6GCjhABYpwVvIAXptxjjA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"agent-device": "bin/agent-device.mjs"
|
||||
@@ -5711,9 +5722,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/eas-cli": {
|
||||
"version": "24.4.2",
|
||||
"resolved": "https://registry.npmjs.org/eas-cli/-/eas-cli-24.4.2.tgz",
|
||||
"integrity": "sha512-7tXqvzZ+4hRBS9p8Voo0PB2Ruapvqc9LLn99ZSw5m2VOQITAxdNhj8PcF+RAV3by7lMGT0oFotP7+/v3FDjpyg==",
|
||||
"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": {
|
||||
@@ -5721,11 +5732,11 @@
|
||||
"@expo/code-signing-certificates": "0.0.5",
|
||||
"@expo/config": "55.0.10",
|
||||
"@expo/config-plugins": "55.0.7",
|
||||
"@expo/eas-build-job": "24.3.0",
|
||||
"@expo/eas-json": "24.3.0",
|
||||
"@expo/eas-build-job": "25.0.0",
|
||||
"@expo/eas-json": "25.0.0",
|
||||
"@expo/env": "^1.0.0",
|
||||
"@expo/json-file": "8.3.3",
|
||||
"@expo/logger": "24.0.0",
|
||||
"@expo/logger": "25.0.0",
|
||||
"@expo/multipart-body-parser": "2.0.0",
|
||||
"@expo/osascript": "2.1.4",
|
||||
"@expo/package-manager": "1.9.10",
|
||||
@@ -5737,7 +5748,7 @@
|
||||
"@expo/results": "1.0.0",
|
||||
"@expo/rudder-sdk-node": "1.1.1",
|
||||
"@expo/spawn-async": "1.7.2",
|
||||
"@expo/steps": "24.3.0",
|
||||
"@expo/steps": "25.0.0",
|
||||
"@expo/timeago.js": "1.0.0",
|
||||
"@oclif/core": "^4.8.3",
|
||||
"@oclif/plugin-autocomplete": "^3.2.40",
|
||||
@@ -5768,7 +5779,7 @@
|
||||
"gradle-to-js": "2.0.1",
|
||||
"graphql": "16.8.1",
|
||||
"graphql-tag": "2.12.6",
|
||||
"https-proxy-agent": "5.0.1",
|
||||
"https-proxy-agent": "7.0.6",
|
||||
"ignore": "5.3.0",
|
||||
"indent-string": "4.0.0",
|
||||
"invariant": "^2.2.2",
|
||||
@@ -5817,19 +5828,6 @@
|
||||
"node": "^20.18.3 || >=22.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/eas-cli/node_modules/agent-base": {
|
||||
"version": "6.0.2",
|
||||
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
|
||||
"integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"debug": "4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/eas-cli/node_modules/ajv": {
|
||||
"version": "8.11.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.11.0.tgz",
|
||||
@@ -5847,20 +5845,6 @@
|
||||
"url": "https://github.com/sponsors/epoberezkin"
|
||||
}
|
||||
},
|
||||
"node_modules/eas-cli/node_modules/https-proxy-agent": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",
|
||||
"integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"agent-base": "6",
|
||||
"debug": "4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/eas-cli/node_modules/ignore": {
|
||||
"version": "5.3.0",
|
||||
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.0.tgz",
|
||||
@@ -7399,6 +7383,20 @@
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/https-proxy-agent": {
|
||||
"version": "7.0.6",
|
||||
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
|
||||
"integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"dependencies": {
|
||||
"agent-base": "^7.1.2",
|
||||
"debug": "4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 14"
|
||||
}
|
||||
},
|
||||
"node_modules/hyperlinker": {
|
||||
"version": "1.0.0",
|
||||
"resolved": "https://registry.npmjs.org/hyperlinker/-/hyperlinker-1.0.0.tgz",
|
||||
@@ -7808,13 +7806,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/jsep": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/jsep/-/jsep-1.4.0.tgz",
|
||||
"integrity": "sha512-B7qPcEVE3NVkmSJbaYxvv4cHkVW7DQsZz13pUMrfS8z8Q/BuShN+gcTXrUlPiGqM2/t/EEaI030bpxMqY8gMlw==",
|
||||
"version": "1.6.0",
|
||||
"resolved": "https://registry.npmjs.org/jsep/-/jsep-1.6.0.tgz",
|
||||
"integrity": "sha512-Y8Tr54CX7B5YGAwo7/n8eumidEX3Opx98RyyQVnlHqUaZcPA8uUzL2v1rshr9ypW9Q6hNjfJtg3sL+8kaNE7TA==",
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"engines": {
|
||||
"node": ">= 10.16.0"
|
||||
"node": ">= 20.16.0"
|
||||
}
|
||||
},
|
||||
"node_modules/jsesc": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@expo/explore",
|
||||
"version": "0.18.1",
|
||||
"version": "0.19.5",
|
||||
"description": "Source-driven mobile app maps, deterministic CI capture, and visual reviews",
|
||||
"license": "MIT",
|
||||
"type": "module",
|
||||
@@ -63,7 +63,6 @@
|
||||
"@expo/repack-app": "0.10.1",
|
||||
"@types/node": "^22.19.19",
|
||||
"@zip.js/zip.js": "2.16.0",
|
||||
"agent-device": "0.21.15",
|
||||
"ajv": "^8.17.1",
|
||||
"pngjs": "7.0.0",
|
||||
"typescript": "^5.9.3",
|
||||
@@ -73,7 +72,7 @@
|
||||
"optionalDependencies": {
|
||||
"@anthropic-ai/claude-agent-sdk": "0.3.285",
|
||||
"@openai/codex": "0.159.2",
|
||||
"eas-cli": "24.4.2"
|
||||
"eas-cli": "25.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@anthropic-ai/claude-code": "2.1.285",
|
||||
@@ -83,6 +82,7 @@
|
||||
"@types/react-dom": "^19.2.4",
|
||||
"@vitejs/plugin-react": "^4.7.0",
|
||||
"@xyflow/react": "^12.11.3",
|
||||
"agent-device": "0.21.15",
|
||||
"babel-plugin-react-compiler": "^1.0.0",
|
||||
"eslint": "^10.12.0",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
// Renders `expo-explore reports` over the saved runs in $EXPLORE_CACHE_DIR, as the CLI draws it, and writes the terminal
|
||||
// body as HTML for the README image's Paper artboards (skills/readme-refresh/SKILL.md says how it is used):
|
||||
//
|
||||
// EXPLORE_CACHE_DIR=<dir with saved runs> node scripts/readme-reports-rows.mjs > reports-rows.html
|
||||
//
|
||||
// Every coloured piece of a row is its own text box exactly as wide as its characters (7.8px cells of 13px JetBrains
|
||||
// Mono), so columns line up as they do in a terminal, and the wordmark is drawn as cell rectangles, since a design
|
||||
// tool's fonts do not render the block characters cell for cell.
|
||||
import { listSavedRuns } from "../dist/report/saved-runs.js";
|
||||
import { renderPicker } from "../dist/cli/reports-picker.js";
|
||||
import { WORDMARK } from "../dist/cli/title-intros.js";
|
||||
|
||||
const COLUMNS = 96, CELL = 7.8, ROW = 18;
|
||||
const runs = await listSavedRuns();
|
||||
if (!runs.length) { console.error("No saved runs in EXPLORE_CACHE_DIR; save the README's runs there first."); process.exit(1); }
|
||||
// Shown from a repository's checkout with every repository listed, so the keys include tab.
|
||||
const repository = runs.find(run => run.repository)?.repository;
|
||||
const lines = renderPicker({ runs, ...(repository ? { repository } : {}), scope: "all", filter: "", filtering: false, selected: 0, offset: 0 },
|
||||
{ width: COLUMNS, height: 20, color: true, totalBytes: runs.reduce((sum, run) => sum + run.bytes, 0) });
|
||||
// The picker pads to the terminal's height above its keys; the image keeps one blank row there.
|
||||
const keys = lines.slice(-2);
|
||||
let body = lines.slice(0, -2);
|
||||
while (body.length > 1 && body.at(-1).trim() === "" && body.at(-2).trim() === "") body = body.slice(0, -1);
|
||||
|
||||
const xterm = n => {
|
||||
if (n >= 232) { const v = 8 + (n - 232) * 10; return [v, v, v]; }
|
||||
const level = [0, 95, 135, 175, 215, 255]; n -= 16;
|
||||
return [level[Math.floor(n / 36)], level[Math.floor(n / 6) % 6], level[n % 6]];
|
||||
};
|
||||
const hex = rgb => `#${rgb.map(v => v.toString(16).padStart(2, "0")).join("").toUpperCase()}`;
|
||||
const escape = text => text.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||
const FONT = "font-family: 'JetBrains Mono'; font-size: 13px; line-height: 18px; white-space: pre; flex-shrink: 0; overflow: hidden;";
|
||||
|
||||
/** One terminal row as coloured pieces; a selected row (a background colour) gets it across the whole row. */
|
||||
function row(line) {
|
||||
if (/^\x1b\[38;5;238m─+/.test(line)) return `<div data-name="Rule" style="display: flex; align-items: center; height: ${ROW}px; flex-shrink: 0;"><div style="height: 1px; flex-grow: 1; background-color: #444444;"></div></div>`;
|
||||
let colour = "#D4D4D4", bold = false, background;
|
||||
const pieces = [];
|
||||
for (const part of line.split(/(\x1b\[[0-9;]*m)/)) {
|
||||
if (part.startsWith("\x1b[")) {
|
||||
const codes = part.slice(2, -1).split(";").map(Number);
|
||||
for (let i = 0; i < codes.length; i += 1) {
|
||||
const code = codes[i];
|
||||
if (code === 0) { colour = "#D4D4D4"; bold = false; }
|
||||
else if (code === 1) bold = true;
|
||||
else if (code === 2) colour = "#808080";
|
||||
else if (code === 97) colour = "#FFFFFF";
|
||||
else if (code === 38 && codes[i + 1] === 5) { colour = hex(xterm(codes[i + 2])); i += 2; }
|
||||
else if (code === 48 && codes[i + 1] === 5) { background = hex(xterm(codes[i + 2])); i += 2; }
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!part) continue;
|
||||
pieces.push(`<div style="${FONT} width: ${([...part].length * CELL).toFixed(1)}px; color: ${colour};${bold ? " font-weight: 700;" : ""}">${escape(part)}</div>`);
|
||||
}
|
||||
return `<div data-name="${background ? "Row — selected" : "Row"}" style="display: flex; height: ${ROW}px; flex-shrink: 0;${background ? ` background-color: ${background};` : ""}">${pieces.join("")}</div>`;
|
||||
}
|
||||
|
||||
/** The wordmark's two rows as rectangles: █ a whole cell, ▀ and ▄ its top or bottom half, overlapping a little so no seams show. */
|
||||
function wordmark() {
|
||||
const rects = [];
|
||||
WORDMARK.forEach((line, r) => [...line].forEach((ch, c) => {
|
||||
const x = c * CELL, y = r * ROW;
|
||||
if (ch === "█") rects.push([x, y, ROW]); else if (ch === "▀") rects.push([x, y, ROW / 2]); else if (ch === "▄") rects.push([x, y + ROW / 2, ROW / 2]);
|
||||
}));
|
||||
const svg = rects.map(([x, y, h]) => `<rect x="${(x - 0.25).toFixed(2)}" y="${(y - 0.25).toFixed(2)}" width="${(CELL + 0.5).toFixed(2)}" height="${(h + 0.5).toFixed(2)}"/>`).join("");
|
||||
const width = (WORDMARK[0].length * CELL).toFixed(1);
|
||||
return `<div data-name="Wordmark" style="display: flex; padding-left: ${(3 * CELL).toFixed(1)}px; height: ${2 * ROW}px; flex-shrink: 0;"><svg width="${width}" height="${2 * ROW}" viewBox="0 0 ${width} ${2 * ROW}" fill="#FFFFFF" xmlns="http://www.w3.org/2000/svg">${svg}</svg></div>`;
|
||||
}
|
||||
|
||||
const rows = [];
|
||||
for (let index = 0; index < body.length; index += 1) {
|
||||
// The picker draws the wordmark as two text rows; the image draws both as one picture.
|
||||
if (body[index].includes(WORDMARK[0])) { rows.push(wordmark()); index += 1; continue; }
|
||||
rows.push(body[index].trim() ? row(body[index]) : `<div data-name="Blank" style="height: ${ROW}px; flex-shrink: 0;"></div>`);
|
||||
}
|
||||
rows.push(...keys.map(row));
|
||||
console.log(`<div data-name="Terminal" style="display: flex; flex-direction: column; padding: 12px 18px 16px 18px;">\n${rows.join("\n")}\n</div>`);
|
||||
@@ -6,7 +6,8 @@
|
||||
// [--pr https://github.com/brentvatne/euxy/pull/148]
|
||||
//
|
||||
// --report a sealed review report (the hosted link's report.zip?platform=ios, or the PR's zip artifact)
|
||||
// --select the route selected on the hero Map (opens the Inspector); default /settings
|
||||
// --select the route selected on the hero Map (opens the Inspector); default /settings. The hero zooms in around it
|
||||
// (--zoom, default 73%) and is framed as a window on a soft stage, like the PR comment
|
||||
// --compare the Compare key of a modified screen: the slug in the Viewer's #/compare/<key> URL; default patterns
|
||||
// --pr a GitHub PR URL whose Explore comment becomes readme-pr-comment-light.png (public repository): the comment
|
||||
// at its own size on a soft stage, cut off with a fade after the list of changed screens
|
||||
@@ -22,6 +23,7 @@ const { values: args } = parseArgs({
|
||||
select: { type: "string", default: "/settings" },
|
||||
compare: { type: "string", default: "patterns" },
|
||||
pr: { type: "string" },
|
||||
zoom: { type: "string", default: "73" },
|
||||
},
|
||||
});
|
||||
if (!args.report) {
|
||||
@@ -31,7 +33,7 @@ if (!args.report) {
|
||||
|
||||
const out = fileURLToPath(new URL("../docs/screenshots/", import.meta.url));
|
||||
const SHOTS = [
|
||||
{ file: "readme-hero", hash: "#/map", viewport: { width: 2200, height: 1240 }, click: "Fit canvas", select: args.select },
|
||||
{ file: "readme-hero", hash: "#/map", viewport: { width: 1376, height: 774 }, click: "Fit canvas", select: args.select, zoom: Number(args.zoom), framed: true },
|
||||
{ file: "readme-compare", hash: `#/compare/${args.compare}`, viewport: { width: 1760, height: 1000 } },
|
||||
{ file: "readme-screens", hash: "#/screens", viewport: { width: 1760, height: 1000 } },
|
||||
];
|
||||
@@ -58,11 +60,28 @@ try {
|
||||
await page.mouse.move(400, shot.viewport.height - 30);
|
||||
await page.waitForTimeout(1500);
|
||||
}
|
||||
if (shot.zoom) {
|
||||
// Zoom around the selected screen with the wheel, which keeps it under the pointer, then pan it left and up, clear
|
||||
// of the minimap and the bottom bar. The camera stops at the first wheel step past the zoom asked for.
|
||||
const box = await page.locator(`.screen-screenshot-target[title="${shot.select}"]`).boundingBox();
|
||||
await page.mouse.move(box.x + box.width / 2, box.y + box.height / 2);
|
||||
for (let step = 0; step < 60; step++) {
|
||||
if (Number((await page.locator(".zoom-button span").first().textContent()).replace("%", "")) >= shot.zoom) break;
|
||||
await page.keyboard.down("Control");
|
||||
await page.mouse.wheel(0, -12);
|
||||
await page.keyboard.up("Control");
|
||||
await page.waitForTimeout(150);
|
||||
}
|
||||
await page.mouse.wheel(160, 90);
|
||||
await page.mouse.move(shot.viewport.width - 60, shot.viewport.height / 2);
|
||||
await page.waitForTimeout(1200);
|
||||
}
|
||||
if (shot.hash.startsWith("#/compare/") && !page.url().includes(shot.hash)) {
|
||||
throw new Error(`Compare key ${args.compare} is not a screen of this report (the Viewer went to ${page.url()}); pass --compare <key> from a #/compare/<key> URL.`);
|
||||
}
|
||||
const path = `${out}${shot.file}-${theme}.png`;
|
||||
await page.screenshot({ path });
|
||||
if (shot.framed) await writeFile(path, await stagedWindow(browser, await page.screenshot(), shot.viewport, theme));
|
||||
else await page.screenshot({ path });
|
||||
console.log(path);
|
||||
await context.close();
|
||||
}
|
||||
@@ -95,6 +114,26 @@ try {
|
||||
await server.close?.();
|
||||
}
|
||||
|
||||
/**
|
||||
* A Viewer screenshot as a window on a rounded 1600×900 stage (drawn at 2x), with a hairline border and a soft shadow,
|
||||
* as the post about Explore frames it. The corners outside the stage stay transparent, so it sits on either GitHub theme.
|
||||
*/
|
||||
async function stagedWindow(browser, shot, viewport, theme) {
|
||||
const dark = theme === "dark";
|
||||
const stage = dark ? "#151B23" : "#F6F8FA";
|
||||
const border = dark ? "#3D444D" : "#D1D9E0";
|
||||
const shadow = dark ? "0 2px 4px rgba(1,4,9,0.4), 0 30px 70px rgba(1,4,9,0.6)" : "0 2px 4px rgba(17,17,17,0.04), 0 30px 70px rgba(17,17,17,0.14)";
|
||||
const context = await browser.newContext({ viewport: { width: 1600, height: 900 }, deviceScaleFactor: 2 });
|
||||
const page = await context.newPage();
|
||||
await page.setContent(`<!doctype html><html><body style="margin:0;background:transparent">
|
||||
<div id="stage" style="position:relative;width:1600px;height:900px;background:${stage};border-radius:22px;overflow:hidden">
|
||||
<img src="data:image/png;base64,${shot.toString("base64")}" style="position:absolute;left:${(1600 - viewport.width) / 2}px;top:${(900 - viewport.height) / 2}px;width:${viewport.width}px;height:${viewport.height}px;box-sizing:border-box;border:1px solid ${border};border-radius:14px;box-shadow:${shadow}">
|
||||
</div></body></html>`);
|
||||
const png = await page.locator("#stage").screenshot({ omitBackground: true });
|
||||
await context.close();
|
||||
return png;
|
||||
}
|
||||
|
||||
/**
|
||||
* The comment on a rounded stage as wide as the README column (880 px, drawn at 2x), with a soft shadow and a fade at
|
||||
* the cut. The corners outside the stage stay transparent, so the image sits on either GitHub theme.
|
||||
|
||||
@@ -24,8 +24,8 @@ Platform, bundle id, app name and version are read from the archive; do not pass
|
||||
## What happens
|
||||
|
||||
1. Archive inspection and compatibility checks (size, simulator build, emulator ABI, sha256).
|
||||
2. `eas simulator:start` of an empty agent-device session, verified by exact session id before use.
|
||||
3. `agent-device install` of the archive straight into the session, 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`).
|
||||
@@ -65,14 +65,14 @@ The model only ever sees the reference; Explore types the value into the field.
|
||||
|
||||
## Already have a session? `explore:session`
|
||||
|
||||
When the app is already installed on an agent-device EAS Simulator session you started (for example after `eas simulator:start --type agent-device --out-config-type dotenv`, `agent-device install ...`, `agent-device open ...`), skip intake and install:
|
||||
When the app is already installed on an EAS Simulator session you started (for example after `eas simulator:start --type agent-device --out-config-type dotenv`, `agent-device install ...`, `agent-device open ...`; an `--type argent` session works the same way, with Argent's tools), skip intake and install:
|
||||
|
||||
```sh
|
||||
npx @expo/explore explore:session # session from ./.env.eas-simulator or EAS_SIMULATOR_SESSION_ID; explores the app in the foreground
|
||||
npx @expo/explore explore:session <session-id> --env-file path/.env.eas-simulator --bundle-id dev.brent.euxy --json
|
||||
```
|
||||
|
||||
The app is whatever is in the foreground, else the only user-installed app; pass `--bundle-id` when neither is clear (`BUNDLE_ID_REQUIRED` lists what is installed); `--app-name`/`--app-version` label the report. The session is checked with `eas simulator:get` (must be agent-device, in progress, and the same daemon as the connection you passed), your existing `agent-device` session on the device is reused, and the same model, budgets, hints and destructive-action flags apply. The map and `report/` are written under `--output` and opened in the local Viewer (`--port N`); `--no-open` skips that and `--upload` hosts the report instead. The session is never stopped: the output ends with the `eas simulator:stop --id ...` command for when you are done.
|
||||
The app is whatever is in the foreground, else the only user-installed app; pass `--bundle-id` when neither is clear (`BUNDLE_ID_REQUIRED` lists what is installed); `--app-name`/`--app-version` label the report. The session is checked with `eas simulator:get` (must be the controller type its connection names, agent-device or argent, in progress, and the same endpoint as the connection you passed; `--controller` must agree with it), your existing `agent-device` session on the device is reused, and the same model, budgets, hints and destructive-action flags apply. The map and `report/` are written under `--output` and opened in the local Viewer (`--port N`); `--no-open` skips that and `--upload` hosts the report instead. The session is never stopped: the output ends with the `eas simulator:stop --id ...` command for when you are done.
|
||||
|
||||
## An Expo project and no build: run it from source
|
||||
|
||||
|
||||
@@ -134,7 +134,7 @@ Adapt this to the app; do not copy sign-in guidance into an app without sign-in.
|
||||
|
||||
## Step 6: install the CI files
|
||||
|
||||
Run `expo-explore setup --workflows` from the app directory. It installs `explore-review.yml` and `explore-baseline.yml` at the repository root with the app and install directories and the package manager's install command, pins both to this CLI's `@expo/explore` version, and forwards every `{{secret:NAME}}` from the config and instructions to both capture steps. Existing workflows keep their edits; setup only updates the version and adds missing secret lines. Rerun it after adding a new secret reference. Replace a superseded Explore workflow only after identifying it, to avoid duplicate captures and comments.
|
||||
Run `expo-explore setup --workflows` from the app directory. It installs `explore-review.yml`, `explore-baseline.yml` and `explore-compare.yml` at the repository root with the app and install directories and the package manager's install command, pins them to this CLI's `@expo/explore` version, and forwards every `{{secret:NAME}}` from the config and instructions to each capture step. Existing workflows keep their edits; setup only updates the version and adds missing secret lines. Rerun it after adding a new secret reference. Replace a superseded Explore workflow only after identifying it, to avoid duplicate captures and comments.
|
||||
|
||||
The review workflow runs on `pull_request_target`, so GitHub runs the default branch's copy of the workflow and its `EXPLORE_VERSION`; a pull request cannot replace the tools that capture and publish its own review. This does not sandbox the app's build. If an app still has `.github/vendor/expo-explore` or an `EXPLORE_TOOLS_COMMIT` workflow from an older setup, `doctor` reports it: delete them and rerun `setup --workflows`.
|
||||
|
||||
@@ -150,6 +150,36 @@ Repeat `expo-explore doctor --json` and fix each `fail` until none remain, colle
|
||||
|
||||
`setup --check` validates only the config schema and instruction file; it is not runtime verification. When the static checks pass and the user approves the EAS usage (and model usage in agent mode), commit locally and run `expo-explore doctor --capture --yes`. It captures the committed HEAD like the baseline workflow with the local EAS login and reports each route. `CAPTURE_LANDING_UNVERIFIED` means the screen redirected: fix the state that setup or the instructions establish. Open the screenshots of guarded screens and confirm each shows the intended state, not just the right route. Do not start paid builds or simulators merely to validate YAML, and do not weaken capture checks to make a replay pass. A setup that was not run on a device is **authored but not runtime-verified**; say so.
|
||||
|
||||
## Review a change on this machine
|
||||
|
||||
The same review CI runs works locally, between any two commits. It reads `.expo-explore/config.yaml` from the head commit, else from the checkout when setup wrote it but it is not committed, else uses the defaults `setup --non-interactive` would write (with several simulator profiles, the one named `explore`), so it works before setup:
|
||||
|
||||
```sh
|
||||
npx @expo/explore capture # HEAD and the uncommitted changes, against where HEAD left the default branch
|
||||
npx @expo/explore capture --committed # HEAD alone
|
||||
npx @expo/explore capture --base v1.3.0 --head v1.4.0 --scope all
|
||||
```
|
||||
|
||||
- It prints which commits it compares. Each is checked out as a detached worktree in a temporary directory, its dependencies installed (frozen lockfile, no scripts, no Explore credentials in the environment), and removed afterwards; the user's checkout, index and branches are never touched.
|
||||
- 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 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 `<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
|
||||
|
||||
`explore-compare.yml` (installed by `setup --workflows` from 0.19.0; run `npx @expo/explore@latest setup --workflows` to add it to an existing setup) reviews a `head` against a `base`, each a branch, tag or commit SHA, with no pull request. It captures, compares and reports like a PR review and links the report from the run's summary. Its inputs are `base`, `head`, and the optional `scope` (`changes` or `all`) and `expires-in` (such as `30d`, or `never`).
|
||||
|
||||
- **Releases.** Unless the user asks otherwise, compare each release with the last stable release, with `scope: all` (every screen, so the report shows the whole release with what changed marked) and, when hosted previews are on, `expires-in: never` (the link outlives the 30-day artifact). For every tag as it is pushed, add the `release-review.yml` from the README's "Compare any two commits" section: it finds the newest earlier tag without a `-` (so a release candidate is compared with the last stable release) and calls `explore-compare.yml` with `secrets: inherit` and `permissions: { contents: read, actions: read }`. A nightly compares with yesterday's tag; a release branch with `main`.
|
||||
- **Once, on demand.** The workflow must be on the default branch to be dispatched: `gh workflow run explore-compare.yml -f base=<ref> -f head=<ref> -f scope=all -f expires-in=never`, or **Run workflow** under Actions → Expo Explore compare.
|
||||
- **Without CI.** `npx @expo/explore capture --base <ref> --head <ref> --scope all --upload` runs the same comparison on this machine (see the previous section).
|
||||
- Call the workflow once per workflow run (a second call in the same run reuses the first one's artifact names). A `base` the baseline workflow captured in the last 30 days is reused, so only `head` is captured.
|
||||
- To verify, run it once on the latest tag and open the run's summary: it lists each platform's result and links the report.
|
||||
|
||||
## Learn from observed failures
|
||||
|
||||
When revising an existing setup, read the previous run's diagnostics, navigation trace and screenshots together. Separate an app prerequisite or defect from a controller failure and a provider or configuration failure. A successful tool response alone does not prove recovery: check the field value, destination, or visible content. For agent mode, inspect `agent-usage.jsonl` before proposing another paid run; missing accounting is unknown, not zero, and dollar fields are estimates. Respect exhausted credit and requests to stop paid calls.
|
||||
|
||||
@@ -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, and gives a prompt to copy for trying it on your app 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
|
||||
@@ -38,18 +38,33 @@ node scripts/readme-screenshots.mjs --report ~/euxy-report/ios.zip --select /set
|
||||
|
||||
`docs/screenshots/readme-exploration-light.png` is the black-box map and comes from a euxy `explore:binary` run (`npx @expo/explore explore:binary <euxy simulator build> --no-upload`, then `expo-explore view --dir <output>` at 1760×1000, Map, Fit canvas). It has no dark variant and is a plain Markdown image. Regenerate it when the Map's rendering of edges or labels changed; otherwise keep it, and say so in the PR.
|
||||
|
||||
Look at every PNG you produced before committing, light and dark: the selected screen should be the one you asked for, the Compare view must show Before and After with outlines, the Screens grid must show the Added/Removed/Modified badges, the PR comment must show the heading links and result glyphs. Describe each in its Markdown alt text as what the picture shows, not what the feature is.
|
||||
`docs/screenshots/readme-reports-light.png` and `-dark.png` show `npx @expo/explore reports` in a terminal window on the same stage as the PR comment image. They are laid out in Paper (Brent's "Patient umbrella" file, page "README — reports picker image", one artboard per theme), from the real picker over real saved runs. Refresh them when the picker's layout or colours change:
|
||||
|
||||
```sh
|
||||
npx @expo/explore reports list # your saved runs: note a euxy local review's id
|
||||
export EXPLORE_CACHE_DIR=$(mktemp -d) # a scratch store for the image, not your own runs
|
||||
cd ~/code/euxy # inside euxy, so the commit messages are found
|
||||
npx @expo/explore reports add ~/.cache/expo-explore/reports/<that id>/ios.zip
|
||||
npx @expo/explore reports add ~/euxy-report/ios.zip # the PR report from step 1
|
||||
npx @expo/explore reports add <an explore:binary report directory> # an exploration, so all three kinds show
|
||||
cd - && npm run build:cli && node scripts/readme-reports-rows.mjs > /tmp/reports-rows.html
|
||||
```
|
||||
|
||||
- The script renders the picker as the CLI draws it (96 columns, the newest run selected) and writes the terminal body as HTML: each coloured piece is exactly its characters wide, so columns line up, and the wordmark is drawn as cell rectangles, since a design tool's font does not draw `█▀▄` cell for cell.
|
||||
- In Paper, replace the frame named "Terminal" inside each artboard's window with that HTML, check both artboards in a screenshot (crisp wordmark, aligned columns, the selected row highlighted to the end, coloured counts), and export both at 2x as `readme-reports-light.png` and `readme-reports-dark.png`. The window's title bar reads `npx @expo/explore reports`, as people run it.
|
||||
|
||||
Look at every PNG you produced before committing, light and dark: the selected screen should be the one you asked for, the Compare view must show Before and After with outlines, the Screens grid must show the added, removed and modified status dots, the PR comment must show the heading links and result glyphs. Describe each in its Markdown alt text as what the picture shows, not what the feature is.
|
||||
|
||||
## 3. Pass over the content as a first-time user
|
||||
|
||||
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`).
|
||||
2. **Try it on your 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.
|
||||
3. **Set up CI: reviews on every PR**: one sentence and the setup prompt.
|
||||
4. **What you get**: the PR comment, Compare, and Screens, each a heading, one line, and its picture, then a prompt for asking an agent about a report.
|
||||
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**: 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, several platforms, 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. Keep the collapsibles' `id` attributes that other docs link to (`#hosted-previews`, `#platforms`, `#agents`), and keep the Inspiration section (screenmap and Revyl's Atlas).
|
||||
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).
|
||||
|
||||
Check that each prompt still works as written:
|
||||
- the skill links it names (`https://unpkg.com/@expo/explore/skills/...`) are files the package ships (`files` in `package.json`), and they open from the published release;
|
||||
|
||||
@@ -233,7 +233,7 @@ async function hashDirectory(root: string, maxBytes: number): Promise<{ sha256:
|
||||
type TarVisitor = (entry: { name: string; type: string; size: number; mode: number }, contents: () => Promise<Buffer>, skip: () => Promise<void>) => Promise<boolean | void>;
|
||||
|
||||
/** Walk a gzip tarball once; `visit` returns true to stop. Long GNU names are honoured; nothing is written. */
|
||||
async function walkTar(path: string, visit: TarVisitor): Promise<void> {
|
||||
export async function walkTar(path: string, visit: TarVisitor): Promise<void> {
|
||||
const stream = createReadStream(path).pipe(createGunzip());
|
||||
const iterator = stream[Symbol.asyncIterator]();
|
||||
let buffer = Buffer.alloc(0);
|
||||
@@ -296,7 +296,7 @@ async function tarEntry(path: string, match: (name: string) => boolean): Promise
|
||||
return found;
|
||||
}
|
||||
|
||||
function safeRelativePath(name: string): string | undefined {
|
||||
export function safeRelativePath(name: string): string | undefined {
|
||||
const parts = name.replace(/^\.\//, "").split("/").filter(part => part.length);
|
||||
if (!parts.length || parts.some(part => part === "." || part === ".." || part.includes("\\") || part.includes("\0"))) return undefined;
|
||||
return parts.join("/");
|
||||
|
||||
@@ -7,7 +7,7 @@ import type { CaptureSetupAction } from "../config/explore-config.js";
|
||||
import { createExplorationInputs, explorationSecretNames } from "../config/exploration-inputs.js";
|
||||
import type { ExploreStore, PreparedArtifact } from "../map/store.js";
|
||||
import { CiError } from "../shared/ci-errors.js";
|
||||
import type { ActionKind, ActionRisk, Artifact, ElementRole, ExploreMap, ObservedElement, Observation, Screen } from "../types.js";
|
||||
import type { ActionKind, ActionRisk, Artifact, Controller, ElementRole, ExploreMap, ObservedElement, Observation, Screen } from "../types.js";
|
||||
|
||||
/** One look at the device: accessibility always, a PNG when the host could take a safe one. */
|
||||
export type BlackBoxFrame = {
|
||||
@@ -278,7 +278,7 @@ function markPressableGroups(nodes: readonly Record<string, unknown>[]): void {
|
||||
}
|
||||
}
|
||||
|
||||
export function elementsOf(nodes: readonly Record<string, unknown>[], allow: readonly string[]): Array<Omit<ObservedElement, "elementId">> {
|
||||
export function elementsOf(nodes: readonly Record<string, unknown>[], allow: readonly string[], controller: Controller = "agent-device"): Array<Omit<ObservedElement, "elementId">> {
|
||||
markPressableGroups(nodes);
|
||||
const occurrences = new Map<string, number>();
|
||||
const out: Array<Omit<ObservedElement, "elementId">> = [];
|
||||
@@ -306,7 +306,7 @@ export function elementsOf(nodes: readonly Record<string, unknown>[], allow: rea
|
||||
const occurrence = (occurrences.get(key) ?? 0) + 1;
|
||||
occurrences.set(key, occurrence);
|
||||
const rect = node.rect && typeof node.rect === "object" ? node.rect as Record<string, unknown> : undefined;
|
||||
out.push({ role, label, ...(identifier ? { identifier } : {}), occurrence, controller: "agent-device",
|
||||
out.push({ role, label, ...(identifier ? { identifier } : {}), occurrence, controller,
|
||||
actions: role === "field" ? ["fill"] : role === "toggle" ? ["press"] : ["press"],
|
||||
risk: riskOf(label, allow), actionable: true, enabled: node.enabled !== false, visible: true,
|
||||
...(rect && typeof rect.x === "number" && typeof rect.y === "number" && typeof rect.width === "number" && typeof rect.height === "number"
|
||||
@@ -497,7 +497,7 @@ export async function runBlackBoxExploration(options: BlackBoxExplorerOptions):
|
||||
for (const part of loose) seen.parts.add(part);
|
||||
seen.loadingOnly &&= loading;
|
||||
evidence.set(screen.id, seen);
|
||||
for (const element of elementsOf(frame.nodes, allow)) {
|
||||
for (const element of elementsOf(frame.nodes, allow, map.run.controller)) {
|
||||
const id = elementId(screen.id, element);
|
||||
if (!screen.elementIds.includes(id)) {
|
||||
screen.elementIds.push(id);
|
||||
@@ -538,7 +538,7 @@ export async function runBlackBoxExploration(options: BlackBoxExplorerOptions):
|
||||
}
|
||||
screenshotArtifactId = artifact.id;
|
||||
}
|
||||
const elements = elementsOf(frame.nodes, allow).map(element => ({ elementId: elementId(screen.id, element), ...element }));
|
||||
const elements = elementsOf(frame.nodes, allow, map.run.controller).map(element => ({ elementId: elementId(screen.id, element), ...element }));
|
||||
const observation: Observation = { id: observationId, screenId: screen.id, variantId: variant.id, capturedAt: frame.capturedAt, surfaceScope: "app",
|
||||
fingerprints: { combined: screenEvidenceKey(frame.nodes), accessibility: accessibilitySha, ...(screenshotArtifactId ? { visual: map.artifacts.find(item => item.id === screenshotArtifactId)!.sha256 } : {}) },
|
||||
elementIds: elements.map(element => element.elementId), elements, accessibilityArtifactId: accessibilityArtifact.id, ...(screenshotArtifactId ? { screenshotArtifactId } : {}) };
|
||||
|
||||
@@ -6,12 +6,14 @@ import { join } from "node:path";
|
||||
import { createCiAgentSession, type CiAgentSession, type CiAgentSessionConfig } from "../capture/agent/session.js";
|
||||
import { createLocalCiAgentSession } from "../capture/agent/session-local.js";
|
||||
import type { CiAgentProviderName } from "../capture/agent/provider.js";
|
||||
import { AGENT_DEVICE_VERSION, CONTROLLER_SESSION, baseEnvironment, isRecord } from "../capture/common.js";
|
||||
import { CONTROLLER_SESSION, baseEnvironment, isRecord } from "../capture/common.js";
|
||||
import { controllerData, defaultRunner, openedSimulatorDevice } from "../capture/controller.js";
|
||||
import type { CommandRequest, CommandResult } from "../capture/run.js";
|
||||
import { executeCaptureSetup } from "../capture/setup-actions.js";
|
||||
import { SIMULATOR_DOTENV_FILE_NAME, SIMULATOR_DOTENV_HEADER, assertSimulatorSessionIdentity, assertSimulatorStopped, readSimulatorDotenvHandoff,
|
||||
assertAttachedSimulatorSession, resolveAttachedSimulatorSession, simulatorOsVersion, simulatorStartFailure, type ActiveSimulatorRuntime, type SimulatorConnection } from "../capture/simulator.js";
|
||||
assertAttachedSimulatorSession, connectionController, controllerVersion, resolveAttachedSimulatorSession, simulatorOsVersion, simulatorStartFailure, type ActiveSimulatorRuntime, type SimulatorConnection } from "../capture/simulator.js";
|
||||
import { argentControllerInvocation } from "../capture/controller-invocation.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";
|
||||
@@ -46,6 +48,8 @@ export type BinaryExploreOptions = {
|
||||
owner?: string;
|
||||
/** EAS project slug the sessions run under; created on first use. */
|
||||
project?: string;
|
||||
/** The session's device controller; agent-device unless Argent is chosen. explore:session takes it from the session. */
|
||||
controller?: "agent-device" | "argent";
|
||||
environment?: NodeJS.ProcessEnv;
|
||||
runner?: typeof defaultRunner;
|
||||
createSession?: (config: CiAgentSessionConfig, options: { env: NodeJS.ProcessEnv; auth: ModelAuth }) => CiAgentSession;
|
||||
@@ -64,10 +68,19 @@ export type BinaryExploreResult = {
|
||||
durationMs: number;
|
||||
};
|
||||
|
||||
/** 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): 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. */
|
||||
function daemonSessions(runner: typeof defaultRunner, connection: SimulatorConnection, work: string, platform: Platform, environment: NodeJS.ProcessEnv): { name: string; device: string }[] {
|
||||
// Argent has no named sessions to share; its tool-server serves every caller.
|
||||
if (connectionController(connection) === "argent") return [];
|
||||
try {
|
||||
const result = runner({ command: packageBin("agent-device", "agent-device"), args: ["session", "list", "--json"], cwd: work, timeoutMs: 60_000,
|
||||
const result = runner({ command: agentDeviceLauncher(environment), args: ["session", "list", "--json"], cwd: work, timeoutMs: 60_000,
|
||||
environment: { ...baseEnvironment(environment), AGENT_DEVICE_DAEMON_BASE_URL: connection.daemonBaseUrl, AGENT_DEVICE_DAEMON_AUTH_TOKEN: connection.daemonAuthToken } });
|
||||
const data = controllerData(result.stdout, "session list");
|
||||
const sessions = Array.isArray(data.sessions) ? data.sessions : [];
|
||||
@@ -119,11 +132,11 @@ const named = (apps: { bundleId: string | undefined; name: string | undefined }[
|
||||
};
|
||||
|
||||
/** Finds the app to explore when the caller named none: the one the session has in the foreground, else the only user-installed app. */
|
||||
export function resolveSessionApp(runner: typeof defaultRunner, connection: SimulatorConnection, work: string, platform: Platform, device: string, controllerSession: string | undefined, environment: NodeJS.ProcessEnv): { bundleId: string; name?: string } {
|
||||
export function resolveSessionApp(runner: typeof defaultRunner, connection: SimulatorConnection, work: string, platform: Platform, device: string, controllerSession: string | undefined, environment: NodeJS.ProcessEnv, invocation?: ControllerInvocation): { bundleId: string; name?: string } {
|
||||
const run = (args: string[]): Record<string, unknown> | undefined => {
|
||||
try {
|
||||
const result = runner({ command: packageBin("agent-device", "agent-device"), args: [...args, ...(platform === "ios" ? ["--device", device] : []), "--platform", platform, "--json"], cwd: work, timeoutMs: 60_000,
|
||||
environment: { ...baseEnvironment(environment), AGENT_DEVICE_DAEMON_BASE_URL: connection.daemonBaseUrl, AGENT_DEVICE_DAEMON_AUTH_TOKEN: connection.daemonAuthToken } });
|
||||
const result = runner({ command: invocation?.command ?? agentDeviceLauncher(environment), args: [...args, ...(platform === "ios" ? ["--device", device] : []), "--platform", platform, "--json"], cwd: work, timeoutMs: 60_000,
|
||||
environment: invocation?.environment ?? { ...baseEnvironment(environment), AGENT_DEVICE_DAEMON_BASE_URL: connection.daemonBaseUrl, AGENT_DEVICE_DAEMON_AUTH_TOKEN: connection.daemonAuthToken } });
|
||||
return controllerData(result.stdout, args[0]!);
|
||||
} catch { return undefined; }
|
||||
};
|
||||
@@ -260,11 +273,20 @@ export type ConnectedSessionExploration = {
|
||||
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 } = ctx;
|
||||
const controllerSession = ctx.controllerSession ?? CONTROLLER_SESSION;
|
||||
const controllerConfig = join(work, "agent-device.json");
|
||||
await writeFile(controllerConfig, "{}\n", { flag: "wx", mode: 0o400 });
|
||||
const 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 };
|
||||
const agentDevice = packageBin("agent-device", "agent-device");
|
||||
const controllerKind = connectionController(connection);
|
||||
const controllerName = controllerKind === "argent" ? "Argent" : "agent-device";
|
||||
if (controllerKind === "argent") await ensureController("argent", { environment, progress: say });
|
||||
let agentDevice: string;
|
||||
let controllerEnvironment: NodeJS.ProcessEnv;
|
||||
if (controllerKind === "argent") {
|
||||
({ 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 });
|
||||
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);
|
||||
}
|
||||
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.
|
||||
@@ -275,22 +297,23 @@ export async function exploreConnectedSession(ctx: ConnectedSessionExploration):
|
||||
};
|
||||
const failureText = (error: unknown): string => lastLine(redactSecrets(error instanceof Error ? error.message : String(error), secrets)).slice(0, 400);
|
||||
const version = runner({ command: agentDevice, args: ["--version"], cwd: work, environment: controllerEnvironment, timeoutMs: 30_000 }).stdout.trim();
|
||||
if (version !== AGENT_DEVICE_VERSION) throw binaryError("EXPLORE_TOOLS_MISSING", `agent-device ${AGENT_DEVICE_VERSION} is required (found ${version || "none"}).`, "Reinstall @expo/explore.");
|
||||
if (version !== controllerVersion(controllerKind)) throw binaryError("EXPLORE_TOOLS_MISSING", `${controllerName} ${controllerVersion(controllerKind)} is required (found ${version || "none"}).`, "Reinstall @expo/explore.");
|
||||
|
||||
if (install) {
|
||||
say(`installing ${install.kind === "android-apk" ? "the APK" : "the app"} on session ${connection.sessionId}`);
|
||||
try { controller(["install", install.path, "--json"], 15 * 60_000); }
|
||||
catch (error) { throw binaryError("APP_INSTALL_FAILED", `agent-device 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 }); }
|
||||
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 }); }
|
||||
}
|
||||
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: "eas-simulator", controller: "agent-device", controllerPackageVersion: AGENT_DEVICE_VERSION, easCliVersion: "unknown", platform, controllerDeviceId: openedDevice.deviceId,
|
||||
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;
|
||||
try { runtime.osVersion = await simulatorOsVersion(sessionJson(), runtime.controllerDeviceId, fetch, platform); } catch { /* descriptive only */ }
|
||||
// Argent's `open` reports the OS version itself (list-devices); agent-device's comes from the session's preview.
|
||||
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";
|
||||
@@ -474,7 +497,13 @@ export async function runSessionExploration(options: SessionExploreOptions): Pro
|
||||
try { connection = await resolveAttachedSimulatorSession(environment, options.envFile, options.session); }
|
||||
catch (error) {
|
||||
throw binaryError("SESSION_NOT_PROVIDED", `No EAS Simulator session connection was found: ${error instanceof Error ? error.message : String(error)}`,
|
||||
"Start one with `eas simulator:start --type agent-device --out-config-type dotenv` and run explore:session in that directory (or pass --env-file / set EAS_SIMULATOR_SESSION_ID, AGENT_DEVICE_DAEMON_BASE_URL and AGENT_DEVICE_DAEMON_AUTH_TOKEN).");
|
||||
"Start one with `eas simulator:start --type agent-device --out-config-type dotenv` (or `--type argent`) and run explore:session in that directory (or pass --env-file / set EAS_SIMULATOR_SESSION_ID with AGENT_DEVICE_DAEMON_BASE_URL and AGENT_DEVICE_DAEMON_AUTH_TOKEN, or ARGENT_TOOLS_URL).");
|
||||
}
|
||||
const sessionController = connectionController(connection);
|
||||
if (!options.runner) await ensureController(sessionController, { environment, progress: say });
|
||||
if (options.controller && options.controller !== sessionController) {
|
||||
throw binaryError("CONTROLLER_MISMATCH", `--controller ${options.controller} was passed, but the session is driven by ${sessionController}.`,
|
||||
`Drop --controller, or start a session with \`eas simulator:start --type ${options.controller}\`.`, { sessionId: connection.sessionId });
|
||||
}
|
||||
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:session.");
|
||||
@@ -495,7 +524,7 @@ export async function runSessionExploration(options: SessionExploreOptions): Pro
|
||||
let device = options.device ?? "";
|
||||
const app = { name: options.appName ?? options.bundleId ?? "app", bundleId: options.bundleId ?? "app", ...(options.version ? { version: options.version } : {}) };
|
||||
const secrets = [environment.EXPO_TOKEN ?? "", connection.daemonAuthToken, ...inputs.values].filter(Boolean);
|
||||
const map: ExploreMap = { contract: CONTRACT, revision: 0, run: { id: randomUUID(), name: app.name, platform, controller: "agent-device", exploration: "black-box", bundleId: app.bundleId, status: "draft",
|
||||
const map: ExploreMap = { contract: CONTRACT, revision: 0, run: { id: randomUUID(), name: app.name, platform, controller: sessionController, exploration: "black-box", bundleId: app.bundleId, status: "draft",
|
||||
createdAt: new Date(now()).toISOString(), updatedAt: new Date(now()).toISOString(), build: { ...(app.version ? { version: app.version } : {}), source: "unknown" }, environment: {}, limits },
|
||||
artifacts: [], screens: [], variants: [], observations: [], elements: [], actionAttempts: [], transitions: [], journeys: [], frontier: [], gaps: [] };
|
||||
try {
|
||||
@@ -504,7 +533,7 @@ export async function runSessionExploration(options: SessionExploreOptions): Pro
|
||||
try { info = assertAttachedSimulatorSession(sessionJson(), connection, options.platform); }
|
||||
catch (error) {
|
||||
throw binaryError("SESSION_UNAVAILABLE", `EAS Simulator session ${connection.sessionId} cannot be explored: ${lastLine(redactSecrets(error instanceof Error ? error.message : String(error), secrets))}`,
|
||||
"Check `eas simulator:list`; the session must be in progress, of type agent-device, and match the connection you passed.", { sessionId: connection.sessionId });
|
||||
`Check \`eas simulator:list\`; the session must be in progress, of type ${sessionController}, and match the connection you passed.`, { sessionId: connection.sessionId });
|
||||
}
|
||||
platform = info.platform;
|
||||
const candidates = daemonSessions(runner, connection, work, platform, environment).filter(item => !device || item.device === device);
|
||||
@@ -514,7 +543,8 @@ export async function runSessionExploration(options: SessionExploreOptions): Pro
|
||||
if (existing) say(`reusing agent-device session "${existing.name}" on ${existing.device}`);
|
||||
device = device || existing?.device || (platform === "ios" ? DEFAULT_IOS_DEVICE : DEFAULT_ANDROID_DEVICE);
|
||||
if (!options.bundleId) {
|
||||
const resolved = resolveSessionApp(runner, connection, work, platform, device, existing?.name, environment);
|
||||
const resolved = resolveSessionApp(runner, connection, work, platform, device, existing?.name, environment,
|
||||
sessionController === "argent" ? await argentInvocation(connection, work, platform, environment) : undefined);
|
||||
app.bundleId = resolved.bundleId;
|
||||
if (!options.appName) app.name = resolved.name ?? app.bundleId;
|
||||
map.run.bundleId = app.bundleId;
|
||||
@@ -582,7 +612,10 @@ export async function runBinaryExploration(options: BinaryExploreOptions): Promi
|
||||
let exploration: BlackBoxExplorerResult | undefined;
|
||||
let owner = options.owner ?? "";
|
||||
const project = options.project ?? DEFAULT_BINARY_PROJECT;
|
||||
const map: ExploreMap = { contract: CONTRACT, revision: 0, run: { id: randomUUID(), name: archive.appName, platform, controller: "agent-device", exploration: "black-box", bundleId, status: "draft",
|
||||
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 });
|
||||
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" },
|
||||
environment: { deviceModel: device }, limits }, artifacts: [], screens: [], variants: [], observations: [], elements: [], actionAttempts: [], transitions: [], journeys: [], frontier: [], gaps: [] };
|
||||
@@ -610,7 +643,7 @@ export async function runBinaryExploration(options: BinaryExploreOptions): Promi
|
||||
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", "agent-device", "--package-version", AGENT_DEVICE_VERSION,
|
||||
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; }
|
||||
|
||||
@@ -18,6 +18,19 @@ export function resolveColorSchemes(appearance: AppearanceSetting, appConfig: Re
|
||||
return ["light"];
|
||||
}
|
||||
|
||||
/**
|
||||
* What an Argent capture renders: one pass, since Argent cannot switch the device's appearance yet
|
||||
* (software-mansion/argent#1509). An app that forces a style renders it on any device; any other app renders as the
|
||||
* fresh simulator starts, light. Requested schemes that pass cannot show are reported as skipped.
|
||||
*/
|
||||
export function argentColorSchemes(requested: readonly ColorScheme[], appConfig: Record<string, unknown> | undefined, platform: string): { schemes: ColorScheme[]; skipped: ColorScheme[] } {
|
||||
const platformConfig = appConfig?.[platform];
|
||||
const declared = (platformConfig && typeof platformConfig === "object" ? (platformConfig as Record<string, unknown>).userInterfaceStyle : undefined)
|
||||
?? appConfig?.userInterfaceStyle;
|
||||
const scheme: ColorScheme = declared === "dark" ? "dark" : "light";
|
||||
return { schemes: [scheme], skipped: requested.filter(item => item !== scheme) };
|
||||
}
|
||||
|
||||
export function parseAppearance(value: unknown, path: string): AppearanceSetting {
|
||||
if (value === undefined || value === "auto") return "auto";
|
||||
const list = Array.isArray(value) ? value : [value];
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* The Argent controller's command line: Explore runs it where it would run agent-device, with the same
|
||||
* arguments. Each command becomes `argent run <tool> --args <json>` calls, as EAS Simulator recommends
|
||||
* driving an `argent` session, with the session's ARGENT_TOOLS_URL and ARGENT_AUTH_TOKEN in the environment.
|
||||
*/
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { appendFile, copyFile, mkdir, readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { createRequire } from "node:module";
|
||||
import type { DecodedFrame } from "../shared/png-evidence.js";
|
||||
import { ArgentCallError, runBridgeCommand, type ArgentBridgeState, type ArgentPlatform, type ArgentTree } from "./argent-driver.js";
|
||||
import { ARGENT_VERSION } from "../shared/argent-version.js";
|
||||
import { ensureController } from "../shared/controller-cache.js";
|
||||
|
||||
const ARGENT_CALL_TIMEOUT_MS = 180_000;
|
||||
|
||||
async function readState(path: string): Promise<ArgentBridgeState> {
|
||||
try { return JSON.parse(await readFile(path, "utf8")) as ArgentBridgeState; }
|
||||
catch { return { generation: 0 }; }
|
||||
}
|
||||
|
||||
/** Written whole and renamed into place, so a command stopped mid-write never leaves a torn state. */
|
||||
async function writeState(path: string, state: ArgentBridgeState): Promise<void> {
|
||||
const temporary = `${path}.${process.pid}.tmp`;
|
||||
await writeFile(temporary, JSON.stringify(state), { mode: 0o600 });
|
||||
await rename(temporary, path);
|
||||
}
|
||||
|
||||
/** A call's arguments for the debug log: text that could be typed into a field is logged by length only. */
|
||||
function loggedArgs(args: Record<string, unknown>): Record<string, unknown> {
|
||||
return Object.fromEntries(Object.entries(args).map(([key, value]) => key === "text" && typeof value === "string" ? [key, `<${value.length} characters>`]
|
||||
: key === "steps" && Array.isArray(value) ? [key, `<${value.length} steps>`] : [key, value]));
|
||||
}
|
||||
|
||||
/** What a call answered, for the debug log: a tree's shape, not its contents. */
|
||||
function summarize(tool: string, value: unknown): unknown {
|
||||
if (!value || typeof value !== "object") return value;
|
||||
if (tool !== "ui-tree") return Object.keys(value);
|
||||
const tree = value as ArgentTree;
|
||||
let nodes = 0;
|
||||
const walk = (node: { children?: unknown[] }) => { nodes++; (node.children ?? []).forEach(child => walk(child as { children?: unknown[] })); };
|
||||
(tree.roots ?? []).forEach(walk);
|
||||
return { foregroundApp: tree.foregroundApp, alertVisible: tree.alertVisible, keyboardVisible: tree.keyboardVisible, truncated: tree.truncated,
|
||||
screen: tree.screen, nodes, roots: (tree.roots ?? []).map(root => [root.type ?? null, root.bundleId ?? null, (root.children ?? []).length]) };
|
||||
}
|
||||
|
||||
async function main(): Promise<number> {
|
||||
const environment = process.env;
|
||||
const statePath = environment.EXPLORE_ARGENT_STATE;
|
||||
const platform = environment.EXPLORE_ARGENT_PLATFORM as ArgentPlatform | undefined;
|
||||
const toolsUrl = environment.ARGENT_TOOLS_URL;
|
||||
if (!statePath || (platform !== "ios" && platform !== "android")) {
|
||||
process.stdout.write(JSON.stringify({ success: false, error: { code: "INVALID_ARGS", message: "The Argent controller needs EXPLORE_ARGENT_STATE and EXPLORE_ARGENT_PLATFORM." } }));
|
||||
return 1;
|
||||
}
|
||||
const argv = process.argv.slice(2);
|
||||
if (argv[0] !== "--version" && !toolsUrl) {
|
||||
// Without a URL the Argent client would start a local tool-server; Explore only drives the session's own.
|
||||
process.stdout.write(JSON.stringify({ success: false, error: { code: "INVALID_ARGS", message: "ARGENT_TOOLS_URL is not set for the Argent controller." } }));
|
||||
return 1;
|
||||
}
|
||||
// EXPLORE_ARGENT_LOG_DIR (opt-in): every Argent call this bridge makes, how long it took, and the shape of what it read.
|
||||
const logPath = environment.EXPLORE_ARGENT_LOG_DIR
|
||||
? join(environment.EXPLORE_ARGENT_LOG_DIR, `argent-${platform}-${environment.EXPLORE_ARGENT_LOG_NAME ?? "bridge"}.jsonl`) : undefined;
|
||||
const log = async (entry: Record<string, unknown>) => {
|
||||
if (!logPath) return;
|
||||
await appendFile(logPath, `${JSON.stringify({ at: new Date().toISOString(), command: argv[0], ...entry })}\n`, { mode: 0o600 }).catch(() => undefined);
|
||||
};
|
||||
const state = await readState(statePath);
|
||||
let cli: string;
|
||||
try { cli = argv[0] === "--version" ? "" : await ensureController("argent", { environment, progress: message => process.stderr.write(`[explore] ${message}\n`) }); }
|
||||
catch (error) {
|
||||
const failure = error as { code?: string; message?: string };
|
||||
process.stdout.write(JSON.stringify({ success: false, error: { code: failure.code ?? "CONTROLLER_DOWNLOAD_FAILED", message: failure.message ?? String(error) } }));
|
||||
return 1;
|
||||
}
|
||||
|
||||
const callArgent = async (tool: string, args: Record<string, unknown>, options?: { out?: string }): Promise<unknown> => {
|
||||
const run = spawnSync(process.execPath, [cli, "run", tool, "--args", JSON.stringify(args), ...(options?.out ? ["--out", options.out] : [])],
|
||||
{ env: environment, encoding: "utf8", maxBuffer: 64 * 1024 * 1024, timeout: ARGENT_CALL_TIMEOUT_MS });
|
||||
if (run.error) throw new ArgentCallError(`argent run ${tool}: ${run.error.message}`, true);
|
||||
if (run.status !== 0) {
|
||||
const detail = `${run.stderr ?? ""}\n${run.stdout ?? ""}`.trim().split("\n").filter(Boolean).slice(-4).join(" | ").slice(0, 800);
|
||||
throw new ArgentCallError(`argent run ${tool} failed: ${detail}`, true);
|
||||
}
|
||||
// With --out the client saves the tool's file and prints where ("Wrote: <path>"), not the tool's JSON.
|
||||
if (options?.out) {
|
||||
const written = await stat(options.out).catch(() => undefined);
|
||||
if (!written?.isFile() || written.size === 0) throw new ArgentCallError(`argent run ${tool} did not write ${options.out}`, true);
|
||||
return { path: options.out };
|
||||
}
|
||||
try { return JSON.parse(run.stdout); }
|
||||
catch { throw new ArgentCallError(`argent run ${tool} did not answer with JSON`, true); }
|
||||
};
|
||||
|
||||
const result = await runBridgeCommand(argv, {
|
||||
state, platform, version: ARGENT_VERSION,
|
||||
...(environment.EXPLORE_ARGENT_BUNDLE_ID ? { bundleId: environment.EXPLORE_ARGENT_BUNDLE_ID } : {}),
|
||||
call: async (tool, args, options) => {
|
||||
const started = Date.now();
|
||||
try {
|
||||
const value = await callArgent(tool, args, options);
|
||||
await log({ tool, args: loggedArgs(args), ms: Date.now() - started, summary: summarize(tool, value) });
|
||||
return value;
|
||||
} catch (error) {
|
||||
await log({ tool, args: loggedArgs(args), ms: Date.now() - started, error: (error instanceof Error ? error.message : String(error)).slice(0, 400) });
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
reachable: async () => {
|
||||
let ok = false;
|
||||
try {
|
||||
const token = environment.ARGENT_AUTH_TOKEN;
|
||||
// The same URL Argent's own client checks: ARGENT_TOOLS_URL may carry a path, which /tools is appended to.
|
||||
const response = await fetch(`${(toolsUrl ?? "").replace(/\/+$/, "")}/tools`, { headers: token ? { authorization: `Bearer ${token}` } : {}, signal: AbortSignal.timeout(5_000) });
|
||||
await response.body?.cancel();
|
||||
ok = response.status < 500;
|
||||
} catch { ok = false; }
|
||||
if (!ok) await log({ tool: "reachable", ok });
|
||||
return ok;
|
||||
},
|
||||
sleep: milliseconds => new Promise(resolve => setTimeout(resolve, milliseconds)),
|
||||
scratchImage: { path: join(dirname(statePath), "argent-scratch.png"), read: async path => {
|
||||
const { PNG } = createRequire(import.meta.url)("pngjs") as { PNG: { sync: { read(bytes: Buffer, options: { checkCRC: boolean }): DecodedFrame } } };
|
||||
return PNG.sync.read(await readFile(path), { checkCRC: false });
|
||||
} },
|
||||
moveFile: async (from, to) => {
|
||||
// Argent's client downloads a recording under its HOME or the working directory; nothing else is moved.
|
||||
const source = await realpath(from);
|
||||
const roots = await Promise.all([environment.HOME, process.cwd()].filter((root): root is string => !!root).map(root => realpath(root).catch(() => root)));
|
||||
if (!roots.some(root => source.startsWith(`${root}/`))) throw new Error(`Argent returned a recording outside its own directories: ${from}`);
|
||||
await mkdir(dirname(to), { recursive: true });
|
||||
try { await rename(from, to); }
|
||||
catch { await copyFile(from, to); await rm(from, { force: true }); }
|
||||
},
|
||||
});
|
||||
await writeState(statePath, state);
|
||||
await log({ result: result.exitCode === 0 ? "ok" : result.stdout.slice(0, 300) });
|
||||
process.stdout.write(result.stdout);
|
||||
return result.exitCode;
|
||||
}
|
||||
|
||||
process.exitCode = await main();
|
||||
@@ -0,0 +1,721 @@
|
||||
/**
|
||||
* Translates the agent-device commands Explore sends into Argent tool calls, and Argent's answers into
|
||||
* agent-device's JSON envelopes, so capture, setup, the agent tool host and black-box exploration drive
|
||||
* either controller without knowing which one runs. Pure: the Argent call, the clock and file moves are
|
||||
* injected, so the translation is tested against recorded Argent output.
|
||||
*/
|
||||
import { CONTROLLER_SESSION } from "./common.js";
|
||||
import type { DecodedFrame } from "../shared/png-evidence.js";
|
||||
|
||||
export type ArgentPlatform = "ios" | "android";
|
||||
|
||||
/** One `argent run <tool>` call. `sent: false` means the request provably never reached the tool-server. */
|
||||
export class ArgentCallError extends Error {
|
||||
constructor(message: string, readonly sent: boolean) { super(message); }
|
||||
}
|
||||
|
||||
export type ArgentCall = (tool: string, args: Record<string, unknown>, options?: { out?: string }) => Promise<unknown>;
|
||||
|
||||
type Rect = { x: number; y: number; width: number; height: number };
|
||||
|
||||
/** What the bridge keeps between commands, in the per-run state file. */
|
||||
export type ArgentBridgeState = {
|
||||
udid?: string;
|
||||
model?: string;
|
||||
osVersion?: string;
|
||||
/** The coordinate space of the last tree: points on iOS, pixels on Android, as agent-device reports them. */
|
||||
screen?: { width: number; height: number };
|
||||
generation: number;
|
||||
refs?: Record<string, { rect: Rect; type?: string; value?: string; secure?: boolean }>;
|
||||
/** iOS asks "Open in “<app>”?" for the first custom-scheme link of a session; later links open directly. */
|
||||
deepLinkPromptAccepted?: boolean;
|
||||
recording?: string;
|
||||
};
|
||||
|
||||
export type ArgentBridgeContext = {
|
||||
call: ArgentCall;
|
||||
state: ArgentBridgeState;
|
||||
platform: ArgentPlatform;
|
||||
/** The app under test when the caller names it outside the command (explore:binary's `install`). */
|
||||
bundleId?: string;
|
||||
version: string;
|
||||
sleep: (milliseconds: number) => Promise<void>;
|
||||
/** Moves a file the Argent client downloaded (a screen recording) to where Explore asked for it. */
|
||||
moveFile: (from: string, to: string) => Promise<void>;
|
||||
/** Whether the tool-server answers, checked before a UI action is sent (see `remoteUnavailable`). */
|
||||
reachable: () => Promise<boolean>;
|
||||
/** A file the bridge may overwrite with a screenshot, and a reader for it (the link-prompt fallback). */
|
||||
scratchImage?: { path: string; read: (path: string) => Promise<DecodedFrame> };
|
||||
};
|
||||
|
||||
export type BridgeResult = { exitCode: number; stdout: string };
|
||||
|
||||
const success = (data: Record<string, unknown>): BridgeResult => ({ exitCode: 0, stdout: JSON.stringify({ success: true, data }) });
|
||||
const failure = (code: string, message: string, details?: Record<string, unknown>): BridgeResult =>
|
||||
({ exitCode: 1, stdout: JSON.stringify({ success: false, error: { code, message, ...(details ? { details } : {}) } }) });
|
||||
|
||||
/**
|
||||
* agent-device's answer when its pre-flight health check fails, which Explore resends because the command was
|
||||
* provably never sent (controller.ts remoteDaemonUnavailable). The bridge gives it only on the same proof.
|
||||
*/
|
||||
const remoteUnavailable = () => failure("COMMAND_FAILED", "Remote daemon is unavailable");
|
||||
|
||||
/** Flags agent-device takes after a command; the bridge needs the platform only from its own context. */
|
||||
const VALUE_FLAGS = new Set(["--session", "--device", "--platform", "--level", "--udid", "--scope", "--bundle-id", "--serial", "--timeout"]);
|
||||
const BOOLEAN_FLAGS = new Set(["--json", "--relaunch", "--normalize-status-bar", "--force-full", "--in-app", "--system"]);
|
||||
|
||||
export function parseCommand(argv: readonly string[]): { positional: string[]; flags: Record<string, string | true> } {
|
||||
const positional: string[] = [];
|
||||
const flags: Record<string, string | true> = {};
|
||||
for (let index = 0; index < argv.length; index++) {
|
||||
const value = argv[index]!;
|
||||
if (value === "--") { positional.push(...argv.slice(index + 1)); break; }
|
||||
if (VALUE_FLAGS.has(value)) { flags[value.slice(2)] = argv[index + 1] ?? ""; index++; continue; }
|
||||
if (BOOLEAN_FLAGS.has(value)) { flags[value.slice(2)] = true; continue; }
|
||||
positional.push(value);
|
||||
}
|
||||
return { positional, flags };
|
||||
}
|
||||
|
||||
type ArgentNode = { role?: string; type?: string; label?: string; identifier?: string; value?: string; contentDescription?: string; disabled?: boolean;
|
||||
frame?: Rect; traits?: string[]; hidden?: boolean; selected?: boolean; password?: boolean; bundleId?: string; children?: ArgentNode[] };
|
||||
export type ArgentTree = { schemaVersion?: number; source?: string; screen?: { width: number; height: number }; roots?: ArgentNode[];
|
||||
truncated?: boolean; alertVisible?: boolean; keyboardVisible?: boolean; foregroundApp?: string };
|
||||
|
||||
const record = (value: unknown): Record<string, unknown> => (value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {});
|
||||
const finite = (value: unknown): value is number => typeof value === "number" && Number.isFinite(value);
|
||||
|
||||
/** Android widget classes as agent-device names their element types. */
|
||||
function agentDeviceType(node: ArgentNode, platform: ArgentPlatform): string {
|
||||
const type = node.type ?? node.role ?? "Other";
|
||||
if (node.password) return "SecureTextField";
|
||||
if (platform === "ios") return type;
|
||||
const simple = type.split(".").pop() ?? type;
|
||||
if (/EditText|TextInput/.test(simple)) return "TextField";
|
||||
if (/Button$|ImageButton|CheckBox|Switch|RadioButton/.test(simple)) return simple.endsWith("Button") ? "Button" : simple;
|
||||
if (/TextView/.test(simple)) return "StaticText";
|
||||
if (/ImageView/.test(simple)) return "Image";
|
||||
if (/ScrollView|RecyclerView|ListView/.test(simple)) return "ScrollView";
|
||||
return simple || "Other";
|
||||
}
|
||||
|
||||
/**
|
||||
* The tree as agent-device's snapshot: the app's root (an `Application` node sized to the screen) and every
|
||||
* element on or near the screen, in the units agent-device uses (points on iOS, pixels on Android), with
|
||||
* refs pinned to this snapshot's generation. Elements Argent lists twice (iOS AX does) appear once.
|
||||
*/
|
||||
export function snapshotFromTree(tree: ArgentTree, platform: ArgentPlatform, generation: number, bundleId?: string) {
|
||||
const screen = tree.screen;
|
||||
if (!screen || !finite(screen.width) || !finite(screen.height) || screen.width <= 0 || screen.height <= 0) {
|
||||
throw new Error("ui-tree did not report the screen size");
|
||||
}
|
||||
const app = bundleId ?? tree.foregroundApp;
|
||||
// Android's status bar and navigation (com.android.systemui) are not part of the app; a dialog another package draws
|
||||
// over it (a runtime permission prompt) is, because it covers the app and setup has to answer it.
|
||||
const roots = (tree.roots ?? []).filter(root => platform === "ios" || root.bundleId !== ANDROID_SYSTEM_UI);
|
||||
const nodes: Record<string, unknown>[] = [];
|
||||
const refs: NonNullable<ArgentBridgeState["refs"]> = {};
|
||||
const seen = new Set<string>();
|
||||
const toPoints = (frame: Rect): Rect => ({ x: frame.x * screen.width, y: frame.y * screen.height, width: frame.width * screen.width, height: frame.height * screen.height });
|
||||
/**
|
||||
* iOS visibility, as Argent computes it (a node is hidden when its frame misses every ancestor's frame), except that a
|
||||
* root clips to the whole screen. On iPhone Duo's inner display Argent 0.29 reports the app root as the top-left third
|
||||
* of the screen ([0, 0, 0.333, 0.333], its 3x scale applied twice), which hid everything outside that third: a sheet's
|
||||
* title and its Cancel button among them. Android's `hidden` is the system's own visible-to-user flag and is kept.
|
||||
*/
|
||||
const clipOf = (node: ArgentNode, clip: Rect | undefined, root: boolean): Rect | undefined => {
|
||||
if (root || !node.frame || ![node.frame.x, node.frame.y, node.frame.width, node.frame.height].every(finite)) return clip;
|
||||
return clip && intersect(node.frame, clip);
|
||||
};
|
||||
const visit = (node: ArgentNode, depth: number, parentIndex: number | undefined, appRoot: boolean, clip: Rect | undefined, root: boolean) => {
|
||||
const frame = node.frame;
|
||||
const inner = clipOf(node, clip, root);
|
||||
const rect = frame && [frame.x, frame.y, frame.width, frame.height].every(finite) ? toPoints(frame) : undefined;
|
||||
const onScreen = !!rect && rect.x < screen.width && rect.y < screen.height && rect.x + rect.width > 0 && rect.y + rect.height > 0;
|
||||
const type = appRoot ? "Application" : agentDeviceType(node, platform);
|
||||
const label = node.label ?? node.contentDescription;
|
||||
const key = JSON.stringify([type, label, node.identifier, node.value, rect && [Math.round(rect.x), Math.round(rect.y), Math.round(rect.width), Math.round(rect.height)]]);
|
||||
let index = parentIndex;
|
||||
// Off-screen content stays out, as agent-device leaves it out; its parents still come through for depth.
|
||||
if (rect && (onScreen || appRoot) && !seen.has(key)) {
|
||||
seen.add(key);
|
||||
index = nodes.length;
|
||||
const ref = `e${index + 1}`;
|
||||
const traits = node.traits ?? [];
|
||||
// iOS marks a disabled element with the notEnabled trait, Android with disabled.
|
||||
const enabled = !traits.includes("notEnabled") && node.disabled !== true;
|
||||
const visible = platform === "ios" ? !!inner : node.hidden !== true;
|
||||
nodes.push({ depth, index, ...(parentIndex === undefined ? {} : { parentIndex }), type, ref,
|
||||
rect: appRoot ? { x: 0, y: 0, width: screen.width, height: screen.height } : rect,
|
||||
...(label ? { label } : {}), ...(node.identifier ? { identifier: node.identifier } : {}),
|
||||
...(node.value !== undefined ? { value: node.value } : {}), enabled, hittable: enabled && visible && !appRoot,
|
||||
...(visible ? {} : { visible: false }), ...(node.selected || traits.includes("selected") ? { selected: true } : {}) });
|
||||
refs[ref] = { rect: appRoot ? { x: 0, y: 0, width: screen.width, height: screen.height } : rect, type,
|
||||
...(node.value !== undefined ? { value: node.value } : {}), ...(type === "SecureTextField" ? { secure: true } : {}) };
|
||||
}
|
||||
for (const child of node.children ?? []) visit(child, depth + 1, index, false, inner, false);
|
||||
};
|
||||
for (const root of roots) {
|
||||
const isAppRoot = platform === "ios" ? root.type === "Application" || nodes.length === 0 : root.bundleId === app;
|
||||
visit(root, 0, undefined, isAppRoot, { x: 0, y: 0, width: 1, height: 1 }, true);
|
||||
}
|
||||
return { nodes, refs, screen: { width: screen.width, height: screen.height } };
|
||||
}
|
||||
|
||||
function intersect(a: Rect, b: Rect): Rect | undefined {
|
||||
const x = Math.max(a.x, b.x), y = Math.max(a.y, b.y);
|
||||
const right = Math.min(a.x + a.width, b.x + b.width), bottom = Math.min(a.y + a.height, b.y + b.height);
|
||||
return right > x && bottom > y ? { x, y, width: right - x, height: bottom - y } : undefined;
|
||||
}
|
||||
|
||||
const centre = (rect: Rect, screen: { width: number; height: number }) =>
|
||||
({ x: (rect.x + rect.width / 2) / screen.width, y: (rect.y + rect.height / 2) / screen.height });
|
||||
|
||||
/**
|
||||
* Argent read nothing: exactly one bare root and no foreground app, which is what iOS 27.1 gives while the link prompt
|
||||
* is up. A read that returned no roots at all is a failed read, not this state.
|
||||
*/
|
||||
function blindTree(tree: ArgentTree): boolean {
|
||||
const roots = tree.roots ?? [];
|
||||
return !tree.foregroundApp && roots.length === 1 && (roots[0]!.children ?? []).length === 0 && !roots[0]!.label && !roots[0]!.type;
|
||||
}
|
||||
|
||||
/** A tree with the app's root and something in it: what a relaunch must reach before the app is usable. */
|
||||
function appReady(tree: ArgentTree, bundleId: string): boolean {
|
||||
if (tree.foregroundApp !== bundleId) return false;
|
||||
const count = (node: ArgentNode): number => 1 + (node.children ?? []).reduce((sum, child) => sum + count(child), 0);
|
||||
return (tree.roots ?? []).some(root => count(root) > 1);
|
||||
}
|
||||
|
||||
function flatten(tree: ArgentTree): ArgentNode[] {
|
||||
const nodes: ArgentNode[] = [];
|
||||
const walk = (node: ArgentNode) => { nodes.push(node); (node.children ?? []).forEach(walk); };
|
||||
(tree.roots ?? []).forEach(walk);
|
||||
return nodes;
|
||||
}
|
||||
|
||||
/** iOS: `com.apple.CoreSimulator.SimRuntime.iOS-26-5` → `26.5`. */
|
||||
export function iosRuntimeVersion(runtime: unknown): string | undefined {
|
||||
const match = typeof runtime === "string" ? /iOS-(\d+)-(\d+)(?:-(\d+))?$/.exec(runtime) : null;
|
||||
return match ? [match[1], match[2], match[3]].filter(Boolean).join(".") : undefined;
|
||||
}
|
||||
|
||||
const DEEP_LINK_PROMPT_CONFIRM = { dxPoints: 74, dyPoints: 37 };
|
||||
const KEYBOARD_DISMISS_LABELS = ["Hide keyboard", "Dismiss keyboard", "Done"];
|
||||
// A keyboard covers the lower part of the screen; its keys start below this share of the height.
|
||||
const KEYBOARD_TOP = 0.4;
|
||||
const ALERT_PREFERRED_BUTTONS = ["Open", "OK", "Allow", "Allow While Using App", "Continue"];
|
||||
const READ_TOOLS = new Set(["ui-tree", "list-devices", "screenshot", "foreground-app", "await-screen-idle", "describe"]);
|
||||
const SPRINGBOARD = "com.apple.springboard";
|
||||
const ANDROID_SYSTEM_UI = "com.android.systemui";
|
||||
const OPEN_IN_APP_PROMPT = /^Open in “.+”\?$/;
|
||||
|
||||
/**
|
||||
* iOS's "Open in “<app>”?" link prompt, recognized by its own text. Argent 0.29 does not always flag it as an alert
|
||||
* (on iOS 27.1, iPhone Duo, `alertVisible` stays false while SpringBoard shows it), and another alert must never be
|
||||
* taken for it: the bridge presses this prompt's Open on its own.
|
||||
*/
|
||||
export function openInAppPromptShowing(tree: ArgentTree): boolean {
|
||||
return flatten(tree).some(node => OPEN_IN_APP_PROMPT.test(node.label ?? ""));
|
||||
}
|
||||
|
||||
/** Any system alert in front of the app: one Argent flags, or the link prompt it does not. */
|
||||
function alertShowing(tree: ArgentTree): boolean {
|
||||
return tree.alertVisible === true || (tree.foregroundApp === SPRINGBOARD && openInAppPromptShowing(tree));
|
||||
}
|
||||
|
||||
/**
|
||||
* The link prompt's Open button found in a screenshot: the largest wide, filled system-blue shape in the middle of the
|
||||
* screen, as iOS 26 and 27 draw it. Used only when Argent cannot read the screen at all while the prompt is up.
|
||||
*/
|
||||
export function findOpenButton(frame: DecodedFrame): { x: number; y: number } | undefined {
|
||||
const step = Math.max(1, Math.round(frame.width / 200));
|
||||
const columns = Math.floor(frame.width / step), rows = Math.floor(frame.height / step);
|
||||
const top = Math.floor(rows * 0.2), bottom = Math.ceil(rows * 0.8);
|
||||
const blue = new Uint8Array(columns * rows);
|
||||
for (let row = top; row < bottom; row++) for (let column = 0; column < columns; column++) {
|
||||
const offset = (row * step * frame.width + column * step) * 4;
|
||||
const [red, green, blueValue] = [frame.data[offset]!, frame.data[offset + 1]!, frame.data[offset + 2]!];
|
||||
if (red < 70 && green > 90 && green < 170 && blueValue > 200) blue[row * columns + column] = 1;
|
||||
}
|
||||
let best: { cells: number; left: number; right: number; top: number; bottom: number } | undefined;
|
||||
const seen = new Uint8Array(columns * rows);
|
||||
for (let start = 0; start < blue.length; start++) {
|
||||
if (!blue[start] || seen[start]) continue;
|
||||
const shape = { cells: 0, left: columns, right: 0, top: rows, bottom: 0 };
|
||||
const queue = [start];
|
||||
seen[start] = 1;
|
||||
while (queue.length) {
|
||||
const cell = queue.pop()!;
|
||||
const row = Math.floor(cell / columns), column = cell % columns;
|
||||
shape.cells++;
|
||||
shape.left = Math.min(shape.left, column); shape.right = Math.max(shape.right, column);
|
||||
shape.top = Math.min(shape.top, row); shape.bottom = Math.max(shape.bottom, row);
|
||||
for (const next of [cell - 1, cell + 1, cell - columns, cell + columns]) {
|
||||
if (next < 0 || next >= blue.length || seen[next] || !blue[next]) continue;
|
||||
if (Math.abs((next % columns) - column) > 1) continue;
|
||||
seen[next] = 1;
|
||||
queue.push(next);
|
||||
}
|
||||
}
|
||||
const width = shape.right - shape.left + 1, height = shape.bottom - shape.top + 1;
|
||||
// A dialog button: wide, a few percent of the screen tall, and well under its full width.
|
||||
if (width < columns * 0.15 || width > columns * 0.6 || width < height * 1.5 || height < rows * 0.03 || height > rows * 0.12) continue;
|
||||
if (!best || shape.cells > best.cells) best = shape;
|
||||
}
|
||||
if (!best) return undefined;
|
||||
return { x: ((best.left + best.right + 1) / 2) / columns, y: ((best.top + best.bottom + 1) / 2) / rows };
|
||||
}
|
||||
|
||||
/**
|
||||
* The prompt's Open button from `describe`. On iOS 27.1 (iPhone Duo) `ui-tree` reports SpringBoard's frames with
|
||||
* x and y swapped, while `describe` reads them correctly, so the button is located there.
|
||||
*/
|
||||
export function describedButton(description: unknown, label: string): Rect | undefined {
|
||||
if (typeof description !== "string") return undefined;
|
||||
const escaped = label.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
// Only a whole line Argent printed counts, so an app label that spells out a button line cannot be picked.
|
||||
const match = new RegExp(`^\\s*AXButton "${escaped}"\\s+\\(([\\d.]+), ([\\d.]+), ([\\d.]+), ([\\d.]+)\\)\\s*$`, "m").exec(description);
|
||||
if (!match) return undefined;
|
||||
const [x, y, width, height] = match.slice(1).map(Number) as [number, number, number, number];
|
||||
return [x, y, width, height].every(finite) && width > 0 && height > 0 ? { x, y, width, height } : undefined;
|
||||
}
|
||||
|
||||
/** Runs one agent-device command against Argent and answers as agent-device would. */
|
||||
export async function runBridgeCommand(argv: readonly string[], context: ArgentBridgeContext): Promise<BridgeResult> {
|
||||
const { state, platform } = context;
|
||||
if (argv[0] === "--version") return { exitCode: 0, stdout: `${context.version}\n` };
|
||||
const [command, ...rest] = argv;
|
||||
const { positional, flags } = parseCommand(rest);
|
||||
const bundleFlag = typeof flags["bundle-id"] === "string" ? flags["bundle-id"] : context.bundleId;
|
||||
|
||||
/** 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>> => {
|
||||
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) {
|
||||
if (READ_TOOLS.has(tool) && attempt < 2) { await context.sleep(1_000 * (attempt + 1)); continue; }
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
};
|
||||
const tree = async (): Promise<ArgentTree> => (await call("ui-tree")) as ArgentTree;
|
||||
const ensureDevice = async () => {
|
||||
if (state.udid) return;
|
||||
let devices: Record<string, unknown>[] = [];
|
||||
// A tool-server that has just started can list no devices at all for its first call; that is not an answer.
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
const listed = await call("list-devices");
|
||||
const all = Array.isArray(listed.devices) ? listed.devices : [];
|
||||
devices = all.map(record).filter(device => device.platform === platform
|
||||
&& (platform === "ios" ? device.state === "Booted" && device.runtimeKind !== "tv" : device.state === "device" && device.runtimeKind !== "tv"));
|
||||
if (all.length) break;
|
||||
await context.sleep(2_000);
|
||||
}
|
||||
if (devices.length !== 1) throw new BridgeFailure("DEVICE_UNAVAILABLE", `Argent lists ${devices.length} booted ${platform} devices on this session; Explore drives exactly one.`);
|
||||
const device = devices[0]!;
|
||||
const udid = platform === "ios" ? device.udid : device.serial;
|
||||
if (typeof udid !== "string" || !udid) throw new BridgeFailure("DEVICE_UNAVAILABLE", "Argent did not name the booted device.");
|
||||
state.udid = udid;
|
||||
state.model = String(platform === "ios" ? device.name : device.model ?? device.avdName ?? udid);
|
||||
const version = platform === "ios" ? iosRuntimeVersion(device.runtime) : undefined;
|
||||
if (version) state.osVersion = version;
|
||||
};
|
||||
/** Relaunches until the app's tree is readable: an EAS simulator Argent did not boot needs a relaunch first. */
|
||||
const relaunch = async (bundleId: string) => {
|
||||
for (let restart = 0; restart < 2; restart++) {
|
||||
await call("restart-app", { bundleId });
|
||||
for (let poll = 0; poll < 12; poll++) {
|
||||
await context.sleep(1_000);
|
||||
if (appReady(await tree(), bundleId)) return;
|
||||
}
|
||||
}
|
||||
throw new BridgeFailure("APP_NOT_READY", `${bundleId} did not come up with a readable accessibility tree after relaunching.`);
|
||||
};
|
||||
const deviceEnvelope = (bundleId: string) => ({ session: CONTROLLER_SESSION, appBundleId: bundleId, platform, target: "mobile",
|
||||
device: { platform, target: "mobile", name: state.model, id: state.udid, ...(state.osVersion ? { osVersion: state.osVersion } : {}) },
|
||||
identifiers: { session: CONTROLLER_SESSION, appBundleId: bundleId, deviceName: state.model, deviceId: state.udid } });
|
||||
const screen = async () => {
|
||||
if (!state.screen) { const current = await tree(); if (current.screen) state.screen = { ...current.screen }; }
|
||||
if (!state.screen) throw new BridgeFailure("COMMAND_FAILED", "The screen size is not known yet.");
|
||||
return state.screen;
|
||||
};
|
||||
const tap = async (x: number, y: number) => { await call("gesture-tap", { x, y }); };
|
||||
const resolveRef = (value: string) => {
|
||||
const match = /^@?(e\d+)(?:~s(\d+))?$/.exec(value);
|
||||
if (!match) throw new BridgeFailure("INVALID_ARGS", `Not an element reference: ${value}`);
|
||||
if (match[2] && Number(match[2]) !== state.generation) throw new BridgeFailure("COMMAND_FAILED", `Element reference ${value} is stale; take a new snapshot.`);
|
||||
const target = state.refs?.[match[1]!];
|
||||
if (!target) throw new BridgeFailure("COMMAND_FAILED", `Element reference ${value} is not in the last snapshot.`);
|
||||
return target;
|
||||
};
|
||||
/**
|
||||
* A UI action is only sent when the tool-server answers first, so a failure after this point is never resent. A
|
||||
* session's tool-server can still be starting when EAS reports the session ready, so it is given about 25 s to answer.
|
||||
*/
|
||||
const beforeAction = async () => {
|
||||
for (const delay of [1_000, 2_000, 3_000, 4_000, 5_000, 5_000, 5_000]) {
|
||||
if (await context.reachable()) return;
|
||||
await context.sleep(delay);
|
||||
}
|
||||
if (!await context.reachable()) throw new UnsentFailure();
|
||||
};
|
||||
|
||||
try {
|
||||
switch (command) {
|
||||
case "open": {
|
||||
await ensureDevice();
|
||||
const target = positional.length === 2 ? { bundleId: positional[0]!, url: positional[1]! }
|
||||
: positional.length === 1 && /^[A-Za-z][A-Za-z0-9+.-]*:/.test(positional[0]!) ? { url: positional[0]! } : { bundleId: positional[0] };
|
||||
if (target.url) {
|
||||
await beforeAction();
|
||||
await call("open-url", { url: target.url });
|
||||
if (platform === "ios" && !state.deepLinkPromptAccepted) await acceptDeepLinkPrompt(target.bundleId ?? bundleFlag);
|
||||
return success({ ...(target.bundleId ? deviceEnvelope(target.bundleId) : { session: CONTROLLER_SESSION }), url: target.url });
|
||||
}
|
||||
const bundleId = target.bundleId ?? bundleFlag;
|
||||
if (!bundleId) throw new BridgeFailure("INVALID_ARGS", "open needs a bundle identifier or a URL.");
|
||||
// agent-device's plain open brings a running app forward and keeps its state; only --relaunch restarts it.
|
||||
if (flags.relaunch !== true && appReady(await tree(), bundleId)) return success({ ...deviceEnvelope(bundleId), appName: bundleId });
|
||||
await beforeAction();
|
||||
await relaunch(bundleId);
|
||||
return success({ ...deviceEnvelope(bundleId), appName: bundleId });
|
||||
}
|
||||
case "snapshot": {
|
||||
await ensureDevice();
|
||||
const current = await tree();
|
||||
state.generation += 1;
|
||||
const converted = snapshotFromTree(current, platform, state.generation, bundleFlag);
|
||||
state.refs = converted.refs;
|
||||
state.screen = converted.screen;
|
||||
const dialog = platform === "android" ? readAlert(current) : undefined;
|
||||
if (dialog && !converted.nodes.some(node => node.type === "Alert")) {
|
||||
// An Android dialog from another package covers the app: report it as agent-device does, as an Alert.
|
||||
converted.nodes.push({ depth: 1, index: converted.nodes.length, parentIndex: 0, type: "Alert", ref: `e${converted.nodes.length + 1}`,
|
||||
rect: { x: 0, y: 0, width: converted.screen.width, height: converted.screen.height }, label: dialog.message || "System dialog", enabled: true, hittable: false });
|
||||
} else if (platform === "ios" && alertShowing(current) && !converted.nodes.some(node => node.type === "Alert")
|
||||
&& !(bundleFlag && appReady(current, bundleFlag))) {
|
||||
// A system alert (SpringBoard's) hides the app's tree; report it the way agent-device does, as an Alert node.
|
||||
converted.nodes.push({ depth: 1, index: converted.nodes.length, parentIndex: 0, type: "Alert", ref: `e${converted.nodes.length + 1}`,
|
||||
rect: { x: 0, y: 0, width: converted.screen.width, height: converted.screen.height }, label: "System alert", enabled: true, hittable: false });
|
||||
}
|
||||
return success({ nodes: converted.nodes, truncated: current.truncated === true, refsGeneration: state.generation,
|
||||
...(current.foregroundApp ? { appBundleId: current.foregroundApp, appName: current.foregroundApp } : {}),
|
||||
snapshotQuality: { state: "healthy", backend: "argent" } });
|
||||
}
|
||||
case "appstate": {
|
||||
await ensureDevice();
|
||||
const current = await tree();
|
||||
const foreground = current.foregroundApp;
|
||||
return success({ ...(foreground ? { appBundleId: foreground, ...(platform === "android" ? { package: foreground } : {}) } : {}),
|
||||
session: CONTROLLER_SESSION, state: foreground ? "runningForeground" : "unknown", surface: foreground ? "app" : "home",
|
||||
device: { id: state.udid, name: state.model } });
|
||||
}
|
||||
case "alert": {
|
||||
await ensureDevice();
|
||||
const current = await tree();
|
||||
const alert = readAlert(current);
|
||||
if (positional[0] === "get") {
|
||||
if (!alert) return platform === "android" ? success({ platform: "android", alert: null }) : failure("COMMAND_FAILED", "alert not found");
|
||||
return platform === "android" ? success({ platform: "android", alert: { title: alert.message, buttons: alert.items } })
|
||||
: success({ message: alert.message, items: alert.items });
|
||||
}
|
||||
if (positional[0] === "accept" || positional[0] === "dismiss") {
|
||||
if (!alert) return failure("COMMAND_FAILED", "alert not found");
|
||||
const preferred = positional[0] === "dismiss"
|
||||
? alert.buttons.find(button => /^(Cancel|Not Now|Don.t Allow|Dismiss)$/.test(button.label)) ?? alert.buttons[0]
|
||||
: ALERT_PREFERRED_BUTTONS.map(label => alert.buttons.find(button => button.label === label)).find(Boolean) ?? alert.buttons.at(-1);
|
||||
if (!preferred) return failure("COMMAND_FAILED", "The alert has no button to press.");
|
||||
await beforeAction();
|
||||
const size = current.screen ?? await screen();
|
||||
// describe places SpringBoard's buttons correctly where ui-tree may not (iOS 27.1); the tree is the fallback.
|
||||
const described = describedButton(await call("describe").then(value => value.description, () => undefined), preferred.label);
|
||||
await tap(...Object.values(described ? centre(described, { width: 1, height: 1 }) : centre(preferred.rect, size)) as [number, number]);
|
||||
await context.sleep(800);
|
||||
if (readAlert(await tree())) return failure("COMMAND_FAILED", "The alert is still showing after its button was pressed.");
|
||||
return success({ action: positional[0], button: preferred.label });
|
||||
}
|
||||
return failure("INVALID_ARGS", `Unsupported alert command: ${positional[0] ?? ""}`);
|
||||
}
|
||||
case "press": {
|
||||
await ensureDevice();
|
||||
const size = await screen();
|
||||
let point: { x: number; y: number };
|
||||
if (positional[0]?.startsWith("@") || /^e\d+/.test(positional[0] ?? "")) point = centre(resolveRef(positional[0]!).rect, size);
|
||||
else {
|
||||
const x = Number(positional[0]), y = Number(positional[1]);
|
||||
if (!finite(x) || !finite(y)) throw new BridgeFailure("INVALID_ARGS", "press needs an element reference or x and y.");
|
||||
point = { x: x / size.width, y: y / size.height };
|
||||
}
|
||||
await beforeAction();
|
||||
await tap(point.x, point.y);
|
||||
return success({ action: "press", x: point.x, y: point.y });
|
||||
}
|
||||
case "fill": {
|
||||
await ensureDevice();
|
||||
const target = resolveRef(positional[0] ?? "");
|
||||
const text = positional.slice(1).join(" ");
|
||||
rejectSecretPlaceholder(text);
|
||||
const size = await screen();
|
||||
await beforeAction();
|
||||
await tap(...Object.values(centre(target.rect, size)) as [number, number]);
|
||||
await context.sleep(400);
|
||||
if (platform === "android") {
|
||||
const filled = await call("fill", { text });
|
||||
if (filled.verified !== true) return failure("COMMAND_FAILED", "Argent could not verify the field's new text.");
|
||||
return success({ action: "fill" });
|
||||
}
|
||||
// Argent's iOS `fill` cannot see React Native's focused field, so the old text is erased and the new one typed.
|
||||
const erase = target.secure ? 64 : (target.value ?? "").length;
|
||||
if (erase > 0) {
|
||||
const erased = await call("run-sequence", { steps: Array.from({ length: erase }, () => ({ tool: "keyboard", args: { udid: state.udid, key: "backspace" } })) });
|
||||
// run-sequence answers normally when it stops partway; typing over half-erased text would leave a wrong value.
|
||||
if (erased.completed !== erased.total) return failure("COMMAND_FAILED", `Erasing the field stopped after ${String(erased.completed)} of ${String(erased.total)} keys; nothing was typed.`);
|
||||
}
|
||||
if (text) await call("keyboard", { text });
|
||||
if (!target.secure) {
|
||||
const after = flatten(await tree()).find(node => node.frame && Math.abs(node.frame.x * size.width - target.rect.x) < 2
|
||||
&& Math.abs(node.frame.y * size.height - target.rect.y) < 2 && /TextField|EditText/.test(node.type ?? ""));
|
||||
if (after && (after.value ?? "") !== text) return failure("COMMAND_FAILED", "The field does not hold the requested text after typing it.");
|
||||
}
|
||||
return success({ action: "fill" });
|
||||
}
|
||||
case "type": {
|
||||
await ensureDevice();
|
||||
const text = positional.join(" ");
|
||||
rejectSecretPlaceholder(text);
|
||||
await beforeAction();
|
||||
await call("keyboard", { text });
|
||||
return success({ action: "type" });
|
||||
}
|
||||
case "keyboard": {
|
||||
if (positional[0] !== "dismiss") return failure("INVALID_ARGS", `Unsupported keyboard command: ${positional[0] ?? ""}`);
|
||||
await ensureDevice();
|
||||
const current = await tree();
|
||||
if (!current.keyboardVisible) return success({ platform, action: "dismiss", wasVisible: false, dismissed: false, visible: false });
|
||||
await beforeAction();
|
||||
if (platform === "android") await call("button", { button: "back" });
|
||||
else {
|
||||
// agent-device taps the keyboard's own dismiss control, and fails with this message when there is none, which
|
||||
// callers answer with the return key. Only a key in the keyboard's area counts: an app's "Done" above it is not one.
|
||||
const key = flatten(current).find(node => KEYBOARD_DISMISS_LABELS.includes(node.label ?? "") && node.frame && node.frame.y >= KEYBOARD_TOP);
|
||||
if (!key) return failure("COMMAND_FAILED", "Unable to dismiss the iOS keyboard: the keyboard exposes no dismiss control.");
|
||||
const size = current.screen ?? await screen();
|
||||
await tap(...Object.values(centre({ x: key.frame!.x * size.width, y: key.frame!.y * size.height,
|
||||
width: key.frame!.width * size.width, height: key.frame!.height * size.height }, size)) as [number, number]);
|
||||
}
|
||||
await context.sleep(500);
|
||||
const visible = (await tree()).keyboardVisible === true;
|
||||
if (visible && platform === "ios") return failure("COMMAND_FAILED", "Unable to dismiss the iOS keyboard: it is still showing after its dismiss key was pressed.");
|
||||
return success({ platform, action: "dismiss", wasVisible: true, dismissed: !visible, visible });
|
||||
}
|
||||
case "scroll": {
|
||||
await ensureDevice();
|
||||
const direction = positional[0] ?? "down";
|
||||
const vertical = direction === "down" || direction === "up";
|
||||
const [from, to] = direction === "down" || direction === "right" ? [0.7, 0.3] : [0.3, 0.7];
|
||||
await beforeAction();
|
||||
await call("gesture-swipe", vertical ? { fromX: 0.5, fromY: from, toX: 0.5, toY: to, momentum: false } : { fromX: from, fromY: 0.5, toX: to, toY: 0.5, momentum: false });
|
||||
return success({ action: "scroll", direction });
|
||||
}
|
||||
case "swipe": {
|
||||
await ensureDevice();
|
||||
const [x1, y1, x2, y2] = positional.slice(0, 4).map(Number);
|
||||
if (![x1, y1, x2, y2].every(finite)) throw new BridgeFailure("INVALID_ARGS", "swipe needs x1 y1 x2 y2.");
|
||||
const size = await screen();
|
||||
await beforeAction();
|
||||
await call("gesture-swipe", { fromX: x1! / size.width, fromY: y1! / size.height, toX: x2! / size.width, toY: y2! / size.height, momentum: false });
|
||||
return success({ action: "swipe" });
|
||||
}
|
||||
case "back": {
|
||||
await ensureDevice();
|
||||
await beforeAction();
|
||||
if (flags.system === true) {
|
||||
// agent-device's system back: the hardware button on Android, the edge swipe on iOS.
|
||||
if (platform === "android") await call("button", { button: "back" });
|
||||
else await call("gesture-swipe", { fromX: 0.05, fromY: 0.5, toX: 0.8, toY: 0.5, momentum: false });
|
||||
return success({ action: "back", mode: "system" });
|
||||
}
|
||||
const current = await tree();
|
||||
const nodes = flatten(current);
|
||||
const button = platform === "android"
|
||||
? nodes.find(node => /^(Navigate up|Back)$/i.test(node.contentDescription ?? node.label ?? "") && node.frame)
|
||||
: (() => {
|
||||
const bar = nodes.find(node => node.type === "NavigationBar" && node.frame);
|
||||
return bar && (bar.children ?? []).flatMap(function all(node: ArgentNode): ArgentNode[] { return [node, ...(node.children ?? []).flatMap(all)]; })
|
||||
.find(node => node.type === "Button" && node.frame && node.frame.x < 1 / 3);
|
||||
})();
|
||||
if (button?.frame) {
|
||||
await tap(button.frame.x + button.frame.width / 2, button.frame.y + button.frame.height / 2);
|
||||
return success({ action: "back", mode: "in-app" });
|
||||
}
|
||||
if (flags["in-app"] === true || platform === "ios") return failure("COMMAND_FAILED", "in-app back control is not available");
|
||||
await call("button", { button: "back" });
|
||||
return success({ action: "back", mode: "system" });
|
||||
}
|
||||
case "wait": {
|
||||
if (positional[0] === "stable") {
|
||||
await ensureDevice();
|
||||
const minStableMs = Number(positional[1] ?? 500), timeoutMs = Number(positional[2] ?? 8000);
|
||||
const idle = await call("await-screen-idle", { minStableMs: finite(minStableMs) ? minStableMs : 500, timeoutMs: finite(timeoutMs) ? timeoutMs : 8000 });
|
||||
return success({ stable: idle.settled === true });
|
||||
}
|
||||
const milliseconds = Number(positional[0]);
|
||||
if (!finite(milliseconds) || milliseconds < 0) throw new BridgeFailure("INVALID_ARGS", "wait needs a number of milliseconds or `stable`.");
|
||||
await context.sleep(milliseconds);
|
||||
return success({ waitedMs: milliseconds });
|
||||
}
|
||||
case "screenshot": {
|
||||
await ensureDevice();
|
||||
const path = positional[0];
|
||||
if (!path) throw new BridgeFailure("INVALID_ARGS", "screenshot needs a path.");
|
||||
await call("screenshot", { scale: 1 }, { out: path });
|
||||
return success({ path });
|
||||
}
|
||||
case "record": {
|
||||
await ensureDevice();
|
||||
if (positional[0] === "start") {
|
||||
if (!positional[1]) throw new BridgeFailure("INVALID_ARGS", "record start needs a path.");
|
||||
await call("screen-recording-start", { timeLimitSeconds: 300, trimStatic: false, showTouches: false });
|
||||
state.recording = positional[1];
|
||||
return success({ recording: true, outPath: positional[1] });
|
||||
}
|
||||
if (positional[0] === "stop") {
|
||||
const stopped = await call("screen-recording-stop");
|
||||
const target = state.recording;
|
||||
delete state.recording;
|
||||
if (typeof stopped.video !== "string") return failure("COMMAND_FAILED", "Argent did not return the recording.");
|
||||
if (target) await context.moveFile(stopped.video, target);
|
||||
return success({ outPath: target ?? stopped.video, ...(finite(stopped.durationMs) ? { durationMs: stopped.durationMs } : {}) });
|
||||
}
|
||||
return failure("INVALID_ARGS", `Unsupported record command: ${positional[0] ?? ""}`);
|
||||
}
|
||||
case "install": {
|
||||
await ensureDevice();
|
||||
const path = positional[0];
|
||||
if (!path || !bundleFlag) throw new BridgeFailure("INVALID_ARGS", "install needs an archive path and the app's bundle identifier.");
|
||||
await beforeAction();
|
||||
await call("reinstall-app", { bundleId: bundleFlag, appPath: path });
|
||||
return success({ installed: true, appBundleId: bundleFlag });
|
||||
}
|
||||
case "fold": {
|
||||
await ensureDevice();
|
||||
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();
|
||||
const folded = await call("fold", { posture });
|
||||
// The other panel lights at another size: every stored coordinate and element reference is stale.
|
||||
delete state.screen;
|
||||
delete state.refs;
|
||||
state.generation += 1;
|
||||
// Argent's accessibility reader can keep reading the panel that went dark (seen on iPhone Duo when it had read
|
||||
// the outer panel before the fold): its tree keeps the old panel's shape and comes back bare. Nothing is read
|
||||
// before the fold, and the tree must take the shape of the panel the fold lit before the bridge answers.
|
||||
const lit = record(folded.screen);
|
||||
if (finite(lit.width) && finite(lit.height) && lit.height > 0) {
|
||||
const litRatio = lit.width / lit.height;
|
||||
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 "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.
|
||||
case "settings": return failure("CONTROLLER_UNSUPPORTED", "Argent cannot change the device's appearance yet.");
|
||||
case "logs": return failure("CONTROLLER_UNSUPPORTED", "Argent does not provide device logs to Explore.");
|
||||
default: return failure("INVALID_ARGS", `Unsupported command for the Argent controller: ${command ?? ""}`);
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof UnsentFailure) return remoteUnavailable();
|
||||
if (error instanceof BridgeFailure) return failure(error.code, error.message);
|
||||
if (error instanceof ArgentCallError) {
|
||||
// Never "Remote daemon is unavailable" here: the request may have run, so Explore must not resend it.
|
||||
return failure(error.sent ? "ARGENT_TOOL_FAILED" : "COMMAND_FAILED", error.sent ? error.message : "Remote daemon is unavailable");
|
||||
}
|
||||
return failure("ARGENT_BRIDGE_FAILED", error instanceof Error ? error.message : String(error));
|
||||
}
|
||||
|
||||
/** Accepts iOS's "Open in “<app>”?" once per session; later links in the same session open without it. */
|
||||
async function acceptDeepLinkPrompt(bundleId: string | undefined) {
|
||||
for (let poll = 0; poll < 6; poll++) {
|
||||
await context.sleep(700);
|
||||
const current = await tree();
|
||||
// Argent can read nothing while iOS 27.1 shows the prompt; find Open in a screenshot instead.
|
||||
if (blindTree(current) && poll >= 1 && context.scratchImage) {
|
||||
if (await pressOpenFromScreenshot(context.scratchImage)) { state.deepLinkPromptAccepted = true; return; }
|
||||
continue;
|
||||
}
|
||||
if (!openInAppPromptShowing(current)) {
|
||||
if (bundleId && appReady(current, bundleId)) { state.deepLinkPromptAccepted = true; return; }
|
||||
// Another alert is the app's or the system's own business; capture answers it, the bridge does not.
|
||||
if (current.alertVisible) return;
|
||||
continue;
|
||||
}
|
||||
const size = current.screen;
|
||||
if (!size) break;
|
||||
const open = describedButton(await call("describe").then(described => described.description, () => undefined), "Open");
|
||||
// Without a described button, the prompt's Open button sits at a fixed offset from the centre on iPhone 17.
|
||||
await tap(...(open ? Object.values(centre(open, { width: 1, height: 1 })) as [number, number]
|
||||
: [0.5 + DEEP_LINK_PROMPT_CONFIRM.dxPoints / size.width, 0.5 + DEEP_LINK_PROMPT_CONFIRM.dyPoints / size.height] as [number, number]));
|
||||
if (await promptCleared()) { state.deepLinkPromptAccepted = true; return; }
|
||||
throw new BridgeFailure("CONTROLLER_DEEP_LINK_PROMPT", "iOS kept asking to open the link in the app after Open was pressed.");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* After Open is pressed, the prompt can stay in the tree for a second or two while the app comes forward (observed on
|
||||
* iPhone Duo's inner display), so the bridge reads again for a few seconds before it calls the press a failure.
|
||||
*/
|
||||
async function promptCleared(): Promise<boolean> {
|
||||
for (let poll = 0; poll < 6; poll++) {
|
||||
await context.sleep(1_000);
|
||||
if (!openInAppPromptShowing(await tree())) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Taps the Open button found in a screenshot, then confirms it is gone. */
|
||||
async function pressOpenFromScreenshot(scratch: NonNullable<ArgentBridgeContext["scratchImage"]>): Promise<boolean> {
|
||||
await call("screenshot", { scale: 1 }, { out: scratch.path });
|
||||
const open = findOpenButton(await scratch.read(scratch.path));
|
||||
if (!open) return false;
|
||||
await tap(open.x, open.y);
|
||||
await context.sleep(1_000);
|
||||
const after = await tree();
|
||||
if (!blindTree(after)) return !openInAppPromptShowing(after);
|
||||
await call("screenshot", { scale: 1 }, { out: scratch.path });
|
||||
return !findOpenButton(await scratch.read(scratch.path));
|
||||
}
|
||||
|
||||
function readAlert(current: ArgentTree) {
|
||||
const androidDialog = platform === "android"
|
||||
? (current.roots ?? []).find(root => root.bundleId && root.bundleId !== ANDROID_SYSTEM_UI && root.bundleId !== (bundleFlag ?? current.foregroundApp))
|
||||
: undefined;
|
||||
if (!androidDialog && !alertShowing(current)) return undefined;
|
||||
const size = current.screen ?? state.screen ?? { width: 1, height: 1 };
|
||||
const nodes = flatten(current);
|
||||
const container = nodes.find(node => node.type === "Alert")
|
||||
?? nodes.find(node => (node.children ?? []).length > 0 && OPEN_IN_APP_PROMPT.test(node.label ?? "")) ?? androidDialog;
|
||||
if (!container) return undefined;
|
||||
const inside = flatten({ roots: [container] });
|
||||
const buttons = inside.filter(node => /Button/.test(node.type ?? node.role ?? "") && node.label && node.frame)
|
||||
.map(node => ({ label: node.label!, rect: { x: node.frame!.x * size.width, y: node.frame!.y * size.height, width: node.frame!.width * size.width, height: node.frame!.height * size.height } }));
|
||||
const text = inside.filter(node => /StaticText|TextView/.test(node.type ?? node.role ?? "") && node.label).map(node => node.label!);
|
||||
return buttons.length ? { message: text.join(" ") || container.label || "", items: buttons.map(button => button.label), buttons } : undefined;
|
||||
}
|
||||
}
|
||||
|
||||
class BridgeFailure extends Error { constructor(readonly code: string, message: string) { super(message); } }
|
||||
class UnsentFailure extends Error {}
|
||||
|
||||
/** Argent's `fill` and `keyboard` would expand `{{secret:NAME}}` from Argent's own secret store; Explore resolves its own. */
|
||||
function rejectSecretPlaceholder(text: string) {
|
||||
if (/\{\{\s*secret\s*:/i.test(text)) throw new BridgeFailure("INVALID_ARGS", "Text for the device must not contain a {{secret:…}} placeholder.");
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { CiError } from "../shared/ci-errors.js";
|
||||
|
||||
export const EAS_CLI_VERSION = "24.4.2";
|
||||
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";
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type { SimulatorConnection } from "./simulator.js";
|
||||
import { controllerCacheRoot } from "../shared/controller-cache.js";
|
||||
|
||||
/** The Argent bridge's entry, run where agent-device's CLI would be. */
|
||||
export const ARGENT_CONTROLLER_WORKER = fileURLToPath(new URL("./argent-controller-worker.js", import.meta.url));
|
||||
|
||||
const shellQuote = (value: string) => `'${value.replace(/'/g, `'\\''`)}'`;
|
||||
|
||||
/**
|
||||
* The command and environment that drive an Argent session the way agent-device's are run: a small executable in
|
||||
* the run's private directory runs the bridge with this Node, so every caller keeps passing one command and its
|
||||
* arguments. The bridge gets only the session's tool-server variables, telemetry off, and a HOME of its own, so
|
||||
* Argent's state (links, downloaded recordings) is never shared between runs or sides of a review.
|
||||
*/
|
||||
export async function argentControllerInvocation(options: {
|
||||
directory: string; connection: SimulatorConnection; platform: "ios" | "android"; environment: NodeJS.ProcessEnv; bundleId?: string;
|
||||
/** The caller's full environment, which names the controller cache and npm registry the narrowed one drops. */
|
||||
sourceEnvironment?: NodeJS.ProcessEnv;
|
||||
}): Promise<{ command: string; environment: NodeJS.ProcessEnv }> {
|
||||
const source = options.sourceEnvironment ?? options.environment;
|
||||
const home = join(options.directory, "argent-home");
|
||||
await mkdir(home, { recursive: true, mode: 0o700 });
|
||||
const command = join(options.directory, "argent-controller");
|
||||
await writeFile(command, `#!/bin/sh\nexec ${shellQuote(process.execPath)} ${shellQuote(ARGENT_CONTROLLER_WORKER)} "$@"\n`, { mode: 0o700 });
|
||||
// agent-device's variables never reach Argent's bridge, and Argent's never reach agent-device.
|
||||
const environment = Object.fromEntries(Object.entries(options.environment).filter(([name]) => !/^(AGENT_DEVICE_|ARGENT_)/.test(name)));
|
||||
return {
|
||||
command,
|
||||
environment: { ...environment, HOME: home, DO_NOT_TRACK: "1",
|
||||
ARGENT_TOOLS_URL: options.connection.daemonBaseUrl,
|
||||
...(options.connection.daemonAuthToken ? { ARGENT_AUTH_TOKEN: options.connection.daemonAuthToken } : {}),
|
||||
EXPLORE_ARGENT_STATE: join(options.directory, "argent-state.json"), EXPLORE_ARGENT_PLATFORM: options.platform,
|
||||
// The bridge runs with a HOME of its own, so it is told where the fetched Argent release is cached.
|
||||
EXPLORE_CONTROLLER_CACHE: controllerCacheRoot(source),
|
||||
...(source.EXPLORE_NPM_REGISTRY ? { EXPLORE_NPM_REGISTRY: source.EXPLORE_NPM_REGISTRY } : {}),
|
||||
// Opt-in: each Argent call to a JSON-lines log, one file per session, for debugging a controller run.
|
||||
...(source.EXPLORE_ARGENT_LOG_DIR ? { EXPLORE_ARGENT_LOG_DIR: source.EXPLORE_ARGENT_LOG_DIR, EXPLORE_ARGENT_LOG_NAME: options.connection.sessionId } : {}),
|
||||
...(options.bundleId ? { EXPLORE_ARGENT_BUNDLE_ID: options.bundleId } : {}) },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* Runs a device controller Explore fetches on first use: `controller-launcher.js <controller> <args...>` makes sure
|
||||
* the pinned release is in the cache, then runs it with the arguments, passing its output and exit code through.
|
||||
* A failed fetch answers in agent-device's JSON envelope, so callers report it like any controller failure.
|
||||
*/
|
||||
import { spawn } from "node:child_process";
|
||||
import { ensureController, type ControllerName } from "../shared/controller-cache.js";
|
||||
|
||||
async function main(): Promise<number> {
|
||||
const [controller, ...args] = process.argv.slice(2);
|
||||
if (controller !== "agent-device") {
|
||||
process.stdout.write(JSON.stringify({ success: false, error: { code: "INVALID_ARGS", message: `Unknown controller: ${controller ?? ""}` } }));
|
||||
return 1;
|
||||
}
|
||||
let bin: string;
|
||||
try { bin = await ensureController(controller as ControllerName, { progress: message => process.stderr.write(`[explore] ${message}\n`) }); }
|
||||
catch (error) {
|
||||
const failure = error as { code?: string; message?: string; nextAction?: string };
|
||||
process.stdout.write(JSON.stringify({ success: false, error: { code: failure.code ?? "CONTROLLER_DOWNLOAD_FAILED",
|
||||
message: failure.message ?? String(error), ...(failure.nextAction ? { hint: failure.nextAction } : {}) } }));
|
||||
return 1;
|
||||
}
|
||||
return new Promise(resolve => {
|
||||
const child = spawn(process.execPath, [bin, ...args], { stdio: "inherit" });
|
||||
// A capture that stops the launcher stops the controller with it.
|
||||
for (const signal of ["SIGINT", "SIGTERM"] as const) process.on(signal, () => child.kill(signal));
|
||||
child.on("exit", (code, signal) => resolve(code ?? (signal ? 1 : 0)));
|
||||
child.on("error", () => resolve(1));
|
||||
});
|
||||
}
|
||||
|
||||
process.exitCode = await main();
|
||||
@@ -483,9 +483,11 @@ async function prepareHostedRepack(options: {
|
||||
}): Promise<string> {
|
||||
const staged = join(options.root, "project");
|
||||
await mkdir(staged, { mode: 0o700 });
|
||||
// Paths relative to the app directory, which is what is staged. With --full-name they were relative to the
|
||||
// repository root, so an app in a monorepo subdirectory (apps/mobile) copied apps/mobile/apps/mobile/... .
|
||||
const listed = options.runner({
|
||||
command: "git",
|
||||
args: ["ls-files", "-z", "--cached", "--full-name"],
|
||||
args: ["ls-files", "-z", "--cached"],
|
||||
cwd: options.project,
|
||||
environment: options.restrictedEnvironment,
|
||||
timeoutMs: 60_000,
|
||||
|
||||
@@ -1066,6 +1066,7 @@ export async function capturePlannedRoutes(options: {
|
||||
};
|
||||
if (rootLink) say(`reset: opening ${rootLink} before each route link (capture.reset: root-link)`);
|
||||
for (const route of options.routes) {
|
||||
capture.signal?.throwIfAborted();
|
||||
if (outcomes[route.id]?.status === "captured" && !setupFailure) continue;
|
||||
// The default app link would show this route without the prepared state. Keep the setup capture failure.
|
||||
if (prepared.has(route.id) && outcomes[route.id]?.status !== "captured") continue;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { appearanceArgs, bundleColorSchemes, mergeSchemeOutcomes, resolveColorSchemes, routeIdOfScreen, type AppearanceSetting, type ColorScheme } from "./appearance.js";
|
||||
import { appearanceArgs, argentColorSchemes, bundleColorSchemes, mergeSchemeOutcomes, resolveColorSchemes, routeIdOfScreen, type AppearanceSetting, type ColorScheme } from "./appearance.js";
|
||||
import { assertNoCaptureHealthIssues, captureHealthIssues, partitionCaptureHealthIssues } from "./health.js";
|
||||
import { type RouteResetSetting } from "./route-reset.js";
|
||||
import { defaultReadinessSeconds } from "./readiness.js";
|
||||
@@ -14,15 +14,16 @@ import type { SourceCapturePlan } from "../source/capture-plan.js";
|
||||
import { CONTRACT, type ExploreMap, type Platform, type RunStatus } from "../types.js";
|
||||
import { ExploreStore, validateMap } from "../map/store.js";
|
||||
import { CiError, serializeCiError, toCiError } from "../shared/ci-errors.js";
|
||||
import type { CaptureSetupAction } from "../config/explore-config.js";
|
||||
import type { CaptureSetupAction, DevicePose } from "../config/explore-config.js";
|
||||
import { type CiAgentRuntimeOptions } from "./agent/runtime.js";
|
||||
import { EAS_CLI_VERSION, AGENT_DEVICE_VERSION, CONTROLLER_SESSION, isRecord, parseJson, baseEnvironment, nonEmpty } from "./common.js";
|
||||
import { EAS_CLI_VERSION, CONTROLLER_SESSION, isRecord, parseJson, baseEnvironment, nonEmpty } from "./common.js";
|
||||
import { lstatIfExists, isWithin, temporaryCaptureDirectory, absoluteContractFile, readContractJson, assertNoSymlinkAncestors } from "./fs-safety.js";
|
||||
import { loadAppIcon, loadCachedAppIcon, storeAppIcon } from "./app-icon.js";
|
||||
import { defaultRunner } 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, simulatorSessionName, simulatorStartFailure, readSimulatorDotenvHandoff, assertSimulatorSessionIdentity, assertSimulatorStopped, collectRuntime, simulatorOsVersion, type ActiveSimulatorRuntime } from "./simulator.js";
|
||||
import { SIMULATOR_DOTENV_FILE_NAME, SIMULATOR_DOTENV_HEADER, simulatorSessionName, simulatorStartFailure, readSimulatorDotenvHandoff, assertSimulatorSessionIdentity, assertSimulatorStopped, collectRuntime, controllerVersion, simulatorOsVersion, type ActiveSimulatorRuntime } from "./simulator.js";
|
||||
import { argentControllerInvocation } from "./controller-invocation.js";
|
||||
import { type UnattributedSetting } from "./unattributed.js";
|
||||
import { appScheme, hasConcreteRoutePath, unavailableRoute, capturePlannedRoutes, deviceArgs } from "./route-capture.js";
|
||||
|
||||
@@ -51,6 +52,10 @@ export type CiMapOptions = {
|
||||
/** Host-side pause used while a controller read is resent; tests pair it with `now` so recovery waits are not real time. */
|
||||
sleep?: (milliseconds: number) => void;
|
||||
easCommand: string; repackCommand: string; agentDeviceCommand: string;
|
||||
/** The device controller EAS starts on the session; agent-device unless the config chose Argent. */
|
||||
controller?: "agent-device" | "argent";
|
||||
/** A foldable's pose (device.pose), set with the controller's `fold` before anything is captured. */
|
||||
devicePose?: DevicePose;
|
||||
/** Where the route observer is bundled into the app: a hosted EAS repack job (default) or repack-app on this machine. */
|
||||
repack?: RepackMode;
|
||||
/** Which appearances to capture; `auto` (default) follows the app's `userInterfaceStyle`. */
|
||||
@@ -65,9 +70,11 @@ export type CiMapOptions = {
|
||||
readinessSeconds?: number;
|
||||
/** Reports each step as it starts; capture output stays in the map and bundle. */
|
||||
progress?: Progress;
|
||||
/** Stops the capture between steps (before the build, the session and each route); a session it started is still stopped. */
|
||||
signal?: AbortSignal;
|
||||
};
|
||||
export type SimulatorRuntimeMetadata = {
|
||||
provider: "eas-simulator"; controller: "agent-device"; controllerPackageVersion: string;
|
||||
provider: "eas-simulator"; controller: "agent-device" | "argent"; controllerPackageVersion: string;
|
||||
easCliVersion: string; platform: Platform; deviceModel: string; osVersion: string; locale: string;
|
||||
orientation: "portrait" | "landscape"; colorScheme: "light" | "dark" | "system"; colorSchemes?: ColorScheme[];
|
||||
sessionLifecycle: "stopped";
|
||||
@@ -92,7 +99,7 @@ function newCaptureMap(options: CiMapOptions, runtime?: ActiveSimulatorRuntime,
|
||||
const timestamp = new Date((options.now ?? Date.now)()).toISOString();
|
||||
return {
|
||||
contract: CONTRACT, revision: 0,
|
||||
run: { id: options.buildId, name: options.name, platform: options.platform, controller: "agent-device", status: "draft",
|
||||
run: { id: options.buildId, name: options.name, platform: options.platform, controller: options.controller ?? "agent-device", status: "draft",
|
||||
bundleId: options.bundleId, ...(runtime ? { deviceId: runtime.controllerDeviceId } : {}),
|
||||
createdAt: timestamp, updatedAt: timestamp,
|
||||
build: { id: options.buildId, version: options.buildVersion, gitCommit: options.gitCommit, source: "eas", ...(fingerprint ? { hash: fingerprint } : {}) },
|
||||
@@ -161,6 +168,7 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
|
||||
const setup = revisionSetup(options.setup ?? [], plan, side);
|
||||
const runner = options.runner ?? defaultRunner;
|
||||
const sourceEnvironment = options.environment ?? process.env;
|
||||
const controller = options.controller ?? "agent-device";
|
||||
const restrictedEnvironment = baseEnvironment(sourceEnvironment);
|
||||
const easEnvironment = { ...restrictedEnvironment, ...(options.expoToken ? { EXPO_TOKEN: options.expoToken } : {}) };
|
||||
const assertCheckout = () => {
|
||||
@@ -277,7 +285,7 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
|
||||
app = { name: cachedBundle.appName ?? options.name };
|
||||
appIcon = await loadCachedAppIcon(cacheRoot, cachedBundle.appIcon);
|
||||
const cachedProfile = cachedBundle.runtimeProfile!;
|
||||
runtime = { provider: "eas-simulator", controller: "agent-device", controllerPackageVersion: AGENT_DEVICE_VERSION,
|
||||
runtime = { provider: "eas-simulator", controller, controllerPackageVersion: controllerVersion(controller),
|
||||
easCliVersion: EAS_CLI_VERSION, platform: options.platform, controllerDeviceId: cachedDeviceId ?? "cached",
|
||||
deviceModel: cachedProfile.deviceModel, osVersion: cachedProfile.osVersion, locale: cachedProfile.locale,
|
||||
orientation: cachedProfile.orientation === "landscape" ? "landscape" : "portrait",
|
||||
@@ -347,7 +355,7 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
|
||||
await rm(launchWorkDirectory, { recursive: true, force: true });
|
||||
const storedIcon = appIcon ? await storeAppIcon(outputDirectory, appIcon) : undefined;
|
||||
const bundle: CaptureBundle = { contract: "explore.bundle", side, gitCommit: options.gitCommit, easBuildId, completedAt: map.run.completedAt,
|
||||
easProjectId: projectId, platform: options.platform, profile: options.easProfile, appName: app.name, ...(storedIcon ? { appIcon: storedIcon } : {}),
|
||||
easProjectId: projectId, platform: options.platform, profile: options.easProfile, appName: app.name, ...(controller === "argent" ? { controller } : {}), ...(storedIcon ? { appIcon: storedIcon } : {}),
|
||||
selectedSurfaceIds: selectedIds,
|
||||
runtimeProfile: metadata ? { deviceModel: metadata.deviceModel, osVersion: metadata.osVersion, locale: metadata.locale,
|
||||
orientation: metadata.orientation, colorScheme: metadata.colorScheme, ...(metadata.colorSchemes ? { colorSchemes: metadata.colorSchemes.join(",") } : {}) } : null, images, outcomes, procedure: { reset: options.reset ?? "root-link", readinessSeconds: options.readinessSeconds ?? defaultReadinessSeconds(options.platform) },
|
||||
@@ -379,6 +387,11 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
|
||||
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);
|
||||
if (controller === "argent") {
|
||||
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;
|
||||
@@ -392,6 +405,7 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
|
||||
setStage("build");
|
||||
// Historical frames do not replace the fresh build needed for missing targets.
|
||||
easBuildId = null;
|
||||
options.signal?.throwIfAborted();
|
||||
say("computing the native fingerprint");
|
||||
const fingerprintResult = eas(["fingerprint:generate", "--platform", options.platform, "--build-profile", options.easProfile, "--json", "--non-interactive"]);
|
||||
fingerprint = fingerprintFrom(fingerprintResult.stdout);
|
||||
@@ -409,6 +423,7 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
|
||||
if (!app.version && reusable.appVersion) app.version = reusable.appVersion;
|
||||
if (!app.buildNumber && reusable.appBuildVersion) app.buildNumber = reusable.appBuildVersion;
|
||||
}
|
||||
options.signal?.throwIfAborted();
|
||||
if (!easBuildId) {
|
||||
say(options.forceFreshBuild ? "building on EAS (a fresh build was requested); waiting for it to finish"
|
||||
: `no finished simulator build has fingerprint ${fingerprint.slice(0, 12)}; building on EAS and waiting for it to finish`);
|
||||
@@ -424,6 +439,7 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
|
||||
if (!app.version && built.appVersion) app.version = built.appVersion;
|
||||
if (!app.buildNumber && built.appBuildVersion) app.buildNumber = built.appBuildVersion;
|
||||
}
|
||||
options.signal?.throwIfAborted();
|
||||
const simulatorProject = await realpath(await mkdtemp(join(tmpdir(), "expo-explore-session-")));
|
||||
const dotenvPath = join(simulatorProject, SIMULATOR_DOTENV_FILE_NAME);
|
||||
const statePath = options.sessionStatePath ? absoluteContractFile(options.sessionStatePath, "sessionStatePath") : undefined;
|
||||
@@ -441,7 +457,7 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
|
||||
await writeFile(dotenvPath, SIMULATOR_DOTENV_HEADER, { flag: "wx", mode: 0o600 });
|
||||
let startError: unknown;
|
||||
try { eas(["simulator:start", "--name", sessionName, "--platform", options.platform, "--device", options.device,
|
||||
"--type", "agent-device", "--package-version", AGENT_DEVICE_VERSION, "--build-id", easBuildId,
|
||||
"--type", controller, "--package-version", controllerVersion(controller), "--build-id", easBuildId, "--public-link",
|
||||
"--max-duration-minutes", String(options.maxDurationMinutes), "--out-config-type", "dotenv", "--non-interactive"], 20 * 60_000, simulatorProject); }
|
||||
catch (error) { startError = error; }
|
||||
const handoff = await readSimulatorDotenvHandoff(dotenvPath);
|
||||
@@ -475,15 +491,29 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
|
||||
await rm(dotenvPath, { force: true });
|
||||
const controllerConfig = join(simulatorProject, "agent-device.json");
|
||||
await writeFile(controllerConfig, "{}\n", { flag: "wx", mode: 0o400 });
|
||||
const controllerEnvironment = { ...restrictedEnvironment, AGENT_DEVICE_CONFIG: controllerConfig,
|
||||
const argent = controller === "argent"
|
||||
? await argentControllerInvocation({ directory: simulatorProject, connection: handoff.connection, platform: options.platform, environment: restrictedEnvironment, sourceEnvironment, bundleId: options.bundleId })
|
||||
: undefined;
|
||||
const controllerEnvironment = argent?.environment ?? { ...restrictedEnvironment, AGENT_DEVICE_CONFIG: controllerConfig,
|
||||
AGENT_DEVICE_DAEMON_BASE_URL: handoff.connection.daemonBaseUrl, AGENT_DEVICE_DAEMON_AUTH_TOKEN: handoff.connection.daemonAuthToken,
|
||||
AGENT_DEVICE_SESSION: CONTROLLER_SESSION, AGENT_DEVICE_SESSION_LOCK: "reject", AGENT_DEVICE_PLATFORM: options.platform };
|
||||
// Every controller call below goes to the session's controller; for Argent that is the bridge.
|
||||
const controllerCommand = argent?.command ?? options.agentDeviceCommand;
|
||||
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}`);
|
||||
runner({ command: controllerCommand, args: ["fold", options.devicePose, "--session", CONTROLLER_SESSION,
|
||||
...deviceArgs({ platform: options.platform, deviceModel: options.device }), "--platform", options.platform, "--json"],
|
||||
cwd: simulatorProject, environment: controllerEnvironment, timeoutMs: 2 * 60_000 });
|
||||
}
|
||||
runtimeStage = "runtime";
|
||||
setStage(runtimeStage);
|
||||
runtime = collectRuntime(options, controllerEnvironment);
|
||||
runtime = collectRuntime({ ...options, agentDeviceCommand: controllerCommand }, controllerEnvironment);
|
||||
runtime.colorScheme = colorSchemes[0]!;
|
||||
// The version is descriptive; a capture proceeds without it and records "unknown".
|
||||
try {
|
||||
// The version is descriptive; a capture proceeds without it and records "unknown". Argent names it with the device;
|
||||
// agent-device's is always taken from the session, as before.
|
||||
if (runtime.osVersion === "unknown" || controller !== "argent") try {
|
||||
runtime.osVersion = await simulatorOsVersion(eas(["simulator:get", "--id", sessionId, "--json", "--non-interactive"], 2 * 60_000).stdout,
|
||||
runtime.controllerDeviceId, options.fetch ?? fetch, options.platform);
|
||||
} catch (error) {
|
||||
@@ -499,7 +529,8 @@ 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()) {
|
||||
runner({ command: options.agentDeviceCommand, args: [...appearanceArgs(colorScheme), "--session", CONTROLLER_SESSION, ...deviceArgs(runtime), "--platform", options.platform],
|
||||
// Argent cannot switch the appearance yet (software-mansion/argent#1509); its single pass runs as the device starts.
|
||||
if (controller !== "argent") runner({ command: controllerCommand, args: [...appearanceArgs(colorScheme), "--session", CONTROLLER_SESSION, ...deviceArgs(runtime), "--platform", options.platform],
|
||||
cwd: simulatorProject, environment: controllerEnvironment, timeoutMs: 60_000 });
|
||||
// A scheme change recreates the Android activity in place, and the sheets it re-presents lose their inset; a
|
||||
// relaunch starts the app in the new scheme, the same way the first pass did.
|
||||
@@ -511,7 +542,7 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
|
||||
const record = await captureLaunch({ bundleId: options.bundleId, keepVideo: launchSetting === "video", platform: options.platform,
|
||||
directory: join(launchWorkDirectory, launchDirectory(colorScheme)), relativeDirectory: launchDirectory(colorScheme), ...(options.now ? { now: options.now } : {}),
|
||||
...(recordingTools ? { recordingTools } : {}),
|
||||
controller: (args, controllerOptions) => runner({ command: options.agentDeviceCommand, args: [...args, "--session", CONTROLLER_SESSION, ...deviceArgs(runtime!), "--platform", options.platform],
|
||||
controller: (args, controllerOptions) => runner({ command: controllerCommand, args: [...args, "--session", CONTROLLER_SESSION, ...deviceArgs(runtime!), "--platform", options.platform],
|
||||
cwd: simulatorProject, environment: controllerEnvironment, timeoutMs: controllerOptions?.timeoutMs ?? 60_000, ...(controllerOptions?.allowFailure ? { allowFailure: true } : {}) }) });
|
||||
launch[colorScheme] = { root: launchWorkDirectory, record };
|
||||
} catch (error) {
|
||||
@@ -519,11 +550,11 @@ async function executeCiMap(options: CiMapOptions, setStage: (stage: string) =>
|
||||
say(`the app launch could not be observed (${(error as Error).message}); the report has no launch evidence for ${colorScheme}`);
|
||||
await rm(join(launchWorkDirectory, launchDirectory(colorScheme)), { recursive: true, force: true });
|
||||
}
|
||||
} else if (index > 0) runner({ command: options.agentDeviceCommand, args: ["open", options.bundleId, "--relaunch", "--session", CONTROLLER_SESSION,
|
||||
} else if (index > 0) runner({ command: controllerCommand, args: ["open", options.bundleId, "--relaunch", "--session", CONTROLLER_SESSION,
|
||||
...deviceArgs(runtime), "--platform", options.platform, "--level", "full", "--json"], cwd: simulatorProject, environment: controllerEnvironment, timeoutMs: 60_000 });
|
||||
runtime.colorScheme = colorScheme;
|
||||
if (colorSchemes.length > 1) say(`appearance ${colorScheme} (${index + 1}/${colorSchemes.length})`);
|
||||
passes.push(await capturePlannedRoutes({ capture: { ...options, setup, progress: say }, routes: missingRoutes, inventory, scheme, appName: app.name, runtime,
|
||||
passes.push(await capturePlannedRoutes({ capture: { ...options, agentDeviceCommand: controllerCommand, setup, progress: say }, routes: missingRoutes, inventory, scheme, appName: app.name, runtime,
|
||||
connection: handoff.connection, environment: controllerEnvironment, store, map, acceptedFrames, outcomes: index === 0 ? outcomes : {},
|
||||
...(colorSchemes.length > 1 ? { appearance: { scheme: colorScheme, primary: index === 0 } } : {}) }));
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { toCiError, serializeCiError, CiError } from "../shared/ci-errors.js";
|
||||
import { isRecord, parseJson, baseEnvironment, AGENT_DEVICE_VERSION, CONTROLLER_SESSION, EAS_CLI_VERSION } from "./common.js";
|
||||
import { ARGENT_VERSION } from "../shared/argent-version.js";
|
||||
import { SIMULATOR_PREVIEW_HOST, framedSimulatorPreviewServer } from "../shared/simulator-preview.js";
|
||||
import { lstatIfExists } from "./fs-safety.js";
|
||||
import { defaultRunner, openedSimulatorDevice, controllerData } from "./controller.js";
|
||||
@@ -9,7 +10,21 @@ import type { RepackProfile } from "./eas-build.js";
|
||||
import type { SimulatorRuntimeMetadata, CiMapOptions } from "./run.js";
|
||||
import type { Platform } from "../types.js";
|
||||
|
||||
export type SimulatorConnection = { sessionId: string; daemonBaseUrl: string; daemonAuthToken: string };
|
||||
/**
|
||||
* How Explore reaches a session's device controller. For agent-device (no `controller`) these are the daemon's URL and
|
||||
* token; for Argent they are the tool-server's `ARGENT_TOOLS_URL` and `ARGENT_AUTH_TOKEN`, whose token may be empty.
|
||||
*/
|
||||
export type SimulatorConnection = { sessionId: string; daemonBaseUrl: string; daemonAuthToken: string; controller?: "argent" };
|
||||
|
||||
/** The controller a connection reaches: the session `--type` EAS started. */
|
||||
export function connectionController(connection: Pick<SimulatorConnection, "controller">): "agent-device" | "argent" {
|
||||
return connection.controller ?? "agent-device";
|
||||
}
|
||||
|
||||
/** The controller's pinned version: what EAS installs on the session (`--package-version`) and what runs here. */
|
||||
export function controllerVersion(controller: "agent-device" | "argent"): string {
|
||||
return controller === "argent" ? ARGENT_VERSION : AGENT_DEVICE_VERSION;
|
||||
}
|
||||
export type ActiveSimulatorRuntime = Omit<SimulatorRuntimeMetadata, "sessionLifecycle"> & { controllerDeviceId: string };
|
||||
const SIMULATOR_SESSION_NAME_MAX_CHARACTERS = 50;
|
||||
const SIMULATOR_SESSION_DIGEST_CHARACTERS = 20;
|
||||
@@ -64,24 +79,28 @@ function simulatorConnection(
|
||||
sessionId: string,
|
||||
daemonBaseUrl: unknown,
|
||||
daemonAuthToken: unknown,
|
||||
controller: "agent-device" | "argent" = "agent-device",
|
||||
): SimulatorConnection {
|
||||
// An Argent tool-server may run without a token (ARGENT_AUTH_TOKEN is only set when it needs one).
|
||||
if (controller === "argent" && daemonAuthToken === undefined) daemonAuthToken = "";
|
||||
if (
|
||||
typeof daemonBaseUrl !== "string"
|
||||
|| typeof daemonAuthToken !== "string"
|
||||
|| !daemonBaseUrl
|
||||
|| !daemonAuthToken
|
||||
|| (!daemonAuthToken && controller !== "argent")
|
||||
|| daemonBaseUrl.length > 2_048
|
||||
|| daemonAuthToken.length > 8_192
|
||||
|| /[\u0000-\u001f\u007f]/.test(daemonBaseUrl)
|
||||
|| /[\u0000-\u001f\u007f]/.test(daemonAuthToken)
|
||||
) {
|
||||
throw new Error("eas simulator:start returned an unsafe agent-device connection");
|
||||
throw new Error(`eas simulator:start returned an unsafe ${controller} connection`);
|
||||
}
|
||||
remoteDaemonDomain(daemonBaseUrl);
|
||||
remoteDaemonDomain(daemonBaseUrl, controller);
|
||||
return {
|
||||
sessionId,
|
||||
daemonBaseUrl,
|
||||
daemonAuthToken,
|
||||
...(controller === "argent" ? { controller } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -100,7 +119,7 @@ export function simulatorStartFailure(error: unknown, secrets: readonly string[]
|
||||
message: source.message.replace(/\\+(["'/])/g, "$1"),
|
||||
nextAction: "Inspect the EAS simulator start failure." }), { secrets });
|
||||
const message = failure.message
|
||||
.replace(/\b(?:AGENT_DEVICE_[A-Z_]+|EAS_SIMULATOR_[A-Z_]+|EXPO_TOKEN|agentDeviceRemoteSession(?:Token|Url)|webPreviewUrl)["']?\s*[:=][^\r\n]*/g, "[REDACTED_HANDOFF]")
|
||||
.replace(/\b(?:AGENT_DEVICE_[A-Z_]+|ARGENT_[A-Z_]+|EAS_SIMULATOR_[A-Z_]+|EXPO_TOKEN|agentDeviceRemoteSession(?:Token|Url)|toolsUrl|toolsAuthToken|webPreviewUrl|previewApiUrl)["']?\s*[:=][^\r\n]*/g, "[REDACTED_HANDOFF]")
|
||||
.replace(/\b[A-Za-z][A-Za-z0-9+.-]*:\/\/[^\s<>"']+/g, "[REDACTED_URL]")
|
||||
.slice(0, 1600);
|
||||
return { code: failure.code, stage: "session", message,
|
||||
@@ -149,6 +168,8 @@ export async function readSimulatorDotenvHandoff(path: string): Promise<Simulato
|
||||
"EAS_SIMULATOR_SESSION_ID",
|
||||
"AGENT_DEVICE_DAEMON_BASE_URL",
|
||||
"AGENT_DEVICE_DAEMON_AUTH_TOKEN",
|
||||
"ARGENT_TOOLS_URL",
|
||||
"ARGENT_AUTH_TOKEN",
|
||||
].includes(name)) {
|
||||
validationError ??= new Error("EAS Simulator dotenv handoff contains an unexpected assignment");
|
||||
continue;
|
||||
@@ -177,11 +198,14 @@ export async function readSimulatorDotenvHandoff(path: string): Promise<Simulato
|
||||
let connection: SimulatorConnection | undefined;
|
||||
if (sessionId) {
|
||||
try {
|
||||
connection = simulatorConnection(
|
||||
sessionId,
|
||||
assignments.AGENT_DEVICE_DAEMON_BASE_URL,
|
||||
assignments.AGENT_DEVICE_DAEMON_AUTH_TOKEN,
|
||||
);
|
||||
// An `argent` session writes the Argent tool-server's variables instead of agent-device's.
|
||||
connection = assignments.ARGENT_TOOLS_URL !== undefined
|
||||
? simulatorConnection(sessionId, assignments.ARGENT_TOOLS_URL, assignments.ARGENT_AUTH_TOKEN, "argent")
|
||||
: simulatorConnection(
|
||||
sessionId,
|
||||
assignments.AGENT_DEVICE_DAEMON_BASE_URL,
|
||||
assignments.AGENT_DEVICE_DAEMON_AUTH_TOKEN,
|
||||
);
|
||||
} catch (error) {
|
||||
validationError ??= error instanceof Error ? error : new Error(String(error));
|
||||
}
|
||||
@@ -207,7 +231,7 @@ export function assertSimulatorSessionIdentity(
|
||||
sessionId !== expectedSessionId
|
||||
|| !isRecord(value)
|
||||
|| value.name !== expectedSessionName
|
||||
|| value.type !== "agent-device"
|
||||
|| value.type !== (expectedConnection ? connectionController(expectedConnection) : "agent-device")
|
||||
|| value.platform !== expectedPlatform.toUpperCase()
|
||||
|| value.status !== "IN_PROGRESS"
|
||||
) {
|
||||
@@ -226,17 +250,19 @@ export function assertSimulatorSessionIdentity(
|
||||
if (!projectProven) {
|
||||
throw new Error("eas simulator:get did not prove the exact expected simulator session");
|
||||
}
|
||||
if (expectedConnection) {
|
||||
if (
|
||||
!isRecord(value.remoteConfig)
|
||||
|| value.remoteConfig.agentDeviceRemoteSessionUrl !== expectedConnection.daemonBaseUrl
|
||||
|| value.remoteConfig.agentDeviceRemoteSessionToken !== expectedConnection.daemonAuthToken
|
||||
) {
|
||||
throw new Error("eas simulator:get returned a different agent-device connection");
|
||||
}
|
||||
if (expectedConnection && !remoteConfigMatches(value.remoteConfig, expectedConnection)) {
|
||||
throw new Error(`eas simulator:get returned a different ${connectionController(expectedConnection)} connection`);
|
||||
}
|
||||
}
|
||||
|
||||
/** 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;
|
||||
return connectionController(connection) === "argent"
|
||||
? remoteConfig.toolsUrl === connection.daemonBaseUrl && (remoteConfig.toolsAuthToken ?? "") === connection.daemonAuthToken
|
||||
: remoteConfig.agentDeviceRemoteSessionUrl === connection.daemonBaseUrl && remoteConfig.agentDeviceRemoteSessionToken === connection.daemonAuthToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* A session Explore did not start: the connection comes from `eas simulator:start --out-config-type dotenv`
|
||||
* (`.env.eas-simulator`) or from the `EAS_SIMULATOR_SESSION_ID` / `AGENT_DEVICE_DAEMON_*` variables that
|
||||
@@ -263,7 +289,9 @@ export async function resolveAttachedSimulatorSession(
|
||||
if (requestedSessionId && environment.EAS_SIMULATOR_SESSION_ID && environment.EAS_SIMULATOR_SESSION_ID !== requestedSessionId) {
|
||||
throw new Error(`EAS_SIMULATOR_SESSION_ID is ${environment.EAS_SIMULATOR_SESSION_ID}, not ${requestedSessionId}`);
|
||||
}
|
||||
return simulatorConnection(sessionId, environment.AGENT_DEVICE_DAEMON_BASE_URL, environment.AGENT_DEVICE_DAEMON_AUTH_TOKEN);
|
||||
return environment.ARGENT_TOOLS_URL !== undefined && environment.AGENT_DEVICE_DAEMON_BASE_URL === undefined
|
||||
? simulatorConnection(sessionId, environment.ARGENT_TOOLS_URL, environment.ARGENT_AUTH_TOKEN, "argent")
|
||||
: simulatorConnection(sessionId, environment.AGENT_DEVICE_DAEMON_BASE_URL, environment.AGENT_DEVICE_DAEMON_AUTH_TOKEN);
|
||||
}
|
||||
|
||||
/** Proves an attached session is live, agent-device typed, and served by the connection we hold; returns its platform. */
|
||||
@@ -274,8 +302,8 @@ export function assertAttachedSimulatorSession(
|
||||
): { platform: Platform; name: string; deviceRunSessionUrl?: string } {
|
||||
const value = parseJson(stdout, "eas simulator:get");
|
||||
const sessionId = simulatorSessionId(value, "eas simulator:get");
|
||||
if (sessionId !== connection.sessionId || !isRecord(value) || value.type !== "agent-device") {
|
||||
throw new Error("eas simulator:get did not describe the attached agent-device session");
|
||||
if (sessionId !== connection.sessionId || !isRecord(value) || value.type !== connectionController(connection)) {
|
||||
throw new Error(`eas simulator:get did not describe the attached ${connectionController(connection)} session`);
|
||||
}
|
||||
if (value.status !== "IN_PROGRESS") {
|
||||
throw new Error(`EAS Simulator session ${sessionId} is ${String(value.status).toLowerCase()}, not in progress`);
|
||||
@@ -284,12 +312,8 @@ export function assertAttachedSimulatorSession(
|
||||
if (!platform || (expectedPlatform && platform !== expectedPlatform)) {
|
||||
throw new Error(`EAS Simulator session ${sessionId} is ${String(value.platform).toLowerCase()}${expectedPlatform ? `, not ${expectedPlatform}` : ""}`);
|
||||
}
|
||||
if (
|
||||
!isRecord(value.remoteConfig)
|
||||
|| value.remoteConfig.agentDeviceRemoteSessionUrl !== connection.daemonBaseUrl
|
||||
|| value.remoteConfig.agentDeviceRemoteSessionToken !== connection.daemonAuthToken
|
||||
) {
|
||||
throw new Error("eas simulator:get returned a different agent-device connection than the one provided");
|
||||
if (!remoteConfigMatches(value.remoteConfig, connection)) {
|
||||
throw new Error(`eas simulator:get returned a different ${connectionController(connection)} connection than the one provided`);
|
||||
}
|
||||
return {
|
||||
platform,
|
||||
@@ -309,12 +333,12 @@ export function assertSimulatorStopped(stdout: string, expectedSessionId: string
|
||||
}
|
||||
}
|
||||
|
||||
function remoteDaemonDomain(value: string): string {
|
||||
function remoteDaemonDomain(value: string, controller: "agent-device" | "argent" = "agent-device"): string {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(value);
|
||||
} catch {
|
||||
throw new Error("eas simulator returned an invalid agent-device URL");
|
||||
throw new Error(`eas simulator returned an invalid ${controller} URL`);
|
||||
}
|
||||
if (
|
||||
url.protocol !== "https:"
|
||||
@@ -322,19 +346,22 @@ function remoteDaemonDomain(value: string): string {
|
||||
|| url.password
|
||||
|| !url.hostname
|
||||
) {
|
||||
throw new Error("eas simulator returned an unsafe agent-device URL");
|
||||
throw new Error(`eas simulator returned an unsafe ${controller} URL`);
|
||||
}
|
||||
return url.hostname;
|
||||
}
|
||||
|
||||
export function collectRuntime(options: CiMapOptions & { platform: NonNullable<CiMapOptions["platform"]> }, environment: NodeJS.ProcessEnv): ActiveSimulatorRuntime {
|
||||
const runner = options.runner ?? defaultRunner;
|
||||
const controller = options.controller ?? "agent-device";
|
||||
const version = runner({ command: options.agentDeviceCommand, args: ["--version"], cwd: options.project,
|
||||
environment: baseEnvironment(options.environment ?? process.env), timeoutMs: 30_000 }).stdout.trim();
|
||||
if (version !== AGENT_DEVICE_VERSION) throw new Error(`agent-device version must be ${AGENT_DEVICE_VERSION}`);
|
||||
environment: controller === "argent" ? environment : baseEnvironment(options.environment ?? process.env), timeoutMs: 30_000 }).stdout.trim();
|
||||
if (version !== controllerVersion(controller)) throw new Error(`${controller} version must be ${controllerVersion(controller)}`);
|
||||
const opened = runner({ command: options.agentDeviceCommand,
|
||||
args: ["open", options.bundleId, "--session", CONTROLLER_SESSION, ...(options.platform === "ios" ? ["--device", options.device] : []),
|
||||
"--platform", options.platform, "--level", "full", "--json"], cwd: options.project, environment, timeoutMs: 60_000 });
|
||||
"--platform", options.platform, "--level", "full", "--json"], cwd: options.project, environment,
|
||||
// Argent's first call can wait for a tool-server that is still starting, then relaunch the app until it is readable.
|
||||
timeoutMs: controller === "argent" ? 180_000 : 60_000 });
|
||||
const device = openedSimulatorDevice(opened.stdout, options.bundleId, "initial app open", options.platform);
|
||||
if (options.platform === "ios" && device.deviceModel !== options.device) throw new CiError({ code: "DEVICE_MISMATCH", stage: "runtime",
|
||||
message: `EAS opened ${device.deviceModel} instead of the configured ${options.device}.`,
|
||||
@@ -345,7 +372,7 @@ export function collectRuntime(options: CiMapOptions & { platform: NonNullable<C
|
||||
const value = deviceData[key] ?? data[key];
|
||||
return typeof value === "string" && value.trim() ? value : "unknown";
|
||||
};
|
||||
return { provider: "eas-simulator", controller: "agent-device", controllerPackageVersion: AGENT_DEVICE_VERSION,
|
||||
return { provider: "eas-simulator", controller, controllerPackageVersion: controllerVersion(controller),
|
||||
easCliVersion: EAS_CLI_VERSION, platform: options.platform, controllerDeviceId: device.deviceId, deviceModel: device.deviceModel,
|
||||
osVersion: observed("osVersion"), locale: observed("locale"),
|
||||
orientation: observed("orientation") === "landscape" ? "landscape" : "portrait",
|
||||
@@ -361,11 +388,15 @@ export function collectRuntime(options: CiMapOptions & { platform: NonNullable<C
|
||||
export async function simulatorOsVersion(session: string, deviceId: string, transport: typeof fetch, platform: "ios" | "android" = "ios"): Promise<string> {
|
||||
const value = parseJson(session, "eas simulator:get");
|
||||
const remote = isRecord(value) && isRecord(value.remoteConfig) ? value.remoteConfig : {};
|
||||
if (typeof remote.webPreviewUrl !== "string") throw new Error("EAS did not publish the simulator preview URL");
|
||||
const preview = new URL(remote.webPreviewUrl);
|
||||
// eas-cli 25 publishes the preview server itself as previewApiUrl, with the token in its query, but only for a
|
||||
// session started with --public-link; its webPreviewUrl is then an expo.dev page with the token in the fragment.
|
||||
// Earlier versions folded the token into webPreviewUrl's query. A private session's output has no token at all.
|
||||
const published = typeof remote.previewApiUrl === "string" ? remote.previewApiUrl : remote.webPreviewUrl;
|
||||
if (typeof published !== "string") throw new Error("EAS did not publish the simulator preview URL");
|
||||
const preview = new URL(published);
|
||||
if (preview.protocol !== "https:" || preview.username || preview.password) throw new Error("The simulator preview URL is not HTTPS");
|
||||
// eas-cli --json folds the preview token into the URL; the catalog takes it as a bearer credential.
|
||||
const token = preview.searchParams.get("token");
|
||||
// The catalog takes the preview token as a bearer credential.
|
||||
const token = preview.searchParams.get("token") ?? new URLSearchParams(preview.hash.slice(1)).get("token");
|
||||
const catalog = new URL(framedSimulatorPreviewServer(preview) ?? preview.origin);
|
||||
if (!SIMULATOR_PREVIEW_HOST.test(catalog.hostname)) throw new Error(`The simulator preview URL names no preview server: ${preview.origin}${preview.pathname}`);
|
||||
// The iOS preview server lists simulators at /grid/api; the Android one has no grid and lists
|
||||
|
||||
@@ -11,6 +11,7 @@ import { canonicalJson } from "../shared/canonical-json.js";
|
||||
import type { ExploreConfig } from "../config/explore-config.js";
|
||||
import { hasVerifiedCapture } from "../capture/health.js";
|
||||
import { CAPTURE_OBSERVER_HASH } from "../capture/observer.js";
|
||||
import { ARGENT_VERSION } from "../shared/argent-version.js";
|
||||
|
||||
const METADATA = "cache-metadata.json";
|
||||
const CONTRACT = "explore.capture-cache";
|
||||
@@ -34,6 +35,8 @@ export function captureRecipeConfig(config: ExploreConfig, instructionsSha256?:
|
||||
app: { platform: config.app.platform, bundleId: config.app.bundleId, easProfile: config.app.easProfile,
|
||||
...(config.app.scheme === undefined ? {} : { scheme: config.app.scheme }) },
|
||||
device: config.device, parameters: config.parameters, setup: config.setup ?? [], capture: config.capture,
|
||||
// agent-device recipes stay as they were; an Argent capture is keyed to the Argent release that drove it.
|
||||
...(config.capture.controller === "argent" ? { controllerVersion: ARGENT_VERSION } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -4,14 +4,20 @@ import { CiError, serializeCiError, type CiErrorData } from "../shared/ci-errors
|
||||
import type { Progress } from "../shared/progress.js";
|
||||
|
||||
type WorkerMessage = { type: "progress"; message: string } | { type: "done"; result: CiMapResult } | { type: "error"; error: CiErrorData };
|
||||
/** From the parent: stop between steps, as `signal` does for a capture on the main thread. */
|
||||
type ParentMessage = { type: "abort"; reason: CiErrorData };
|
||||
|
||||
/** Options a worker can receive: the controller runs through synchronous subprocesses, so a side only overlaps another from its own thread. */
|
||||
export type CaptureWorkerOptions = Omit<CiMapOptions, "progress" | "runner" | "now" | "fetch" | "agent">;
|
||||
export type CaptureWorkerOptions = Omit<CiMapOptions, "progress" | "runner" | "now" | "fetch" | "agent" | "signal">;
|
||||
|
||||
/** Run one capture side on a worker thread so head and base can drive their simulator sessions at the same time. */
|
||||
export function runCiMapOnWorker(options: CaptureWorkerOptions, progress: Progress): Promise<CiMapResult> {
|
||||
export function runCiMapOnWorker(options: CaptureWorkerOptions, progress: Progress, signal?: AbortSignal): Promise<CiMapResult> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const worker = new Worker(new URL("./capture-worker.js", import.meta.url), { workerData: options });
|
||||
// An AbortSignal cannot cross threads; the worker aborts its own, and its capture stops its session as usual.
|
||||
const abort = () => worker.postMessage({ type: "abort", reason: serializeCiError(signal!.reason) } satisfies ParentMessage);
|
||||
if (signal?.aborted) abort(); else signal?.addEventListener("abort", abort, { once: true });
|
||||
worker.once("exit", () => signal?.removeEventListener("abort", abort));
|
||||
let settled = false;
|
||||
const finish = (callback: () => void) => { if (!settled) { settled = true; callback(); } };
|
||||
worker.on("message", (message: WorkerMessage) => {
|
||||
@@ -29,7 +35,11 @@ export function runCiMapOnWorker(options: CaptureWorkerOptions, progress: Progre
|
||||
if (!isMainThread && parentPort) {
|
||||
const port = parentPort;
|
||||
const options = workerData as CaptureWorkerOptions;
|
||||
runCiMap({ ...options, progress: message => port.postMessage({ type: "progress", message } satisfies WorkerMessage) })
|
||||
const controller = new AbortController();
|
||||
port.on("message", (message: ParentMessage) => { if (message.type === "abort") controller.abort(new CiError(message.reason)); });
|
||||
// Listening for an abort must not keep the worker alive once its capture is done.
|
||||
port.unref();
|
||||
runCiMap({ ...options, signal: controller.signal, progress: message => port.postMessage({ type: "progress", message } satisfies WorkerMessage) })
|
||||
.then(result => port.postMessage({ type: "done", result } satisfies WorkerMessage))
|
||||
.catch((error: unknown) => port.postMessage({ type: "error", error: serializeCiError(error, { secrets: [options.expoToken] }) } satisfies WorkerMessage));
|
||||
}
|
||||
@@ -8,14 +8,16 @@ import type { CaptureBundle } from "../contracts/capture.js";
|
||||
import type { SourceCapturePlan } from "../source/capture-plan.js";
|
||||
import type { CommandRunner } from "../capture/run.js";
|
||||
import { runBaselineCi } from "./pipeline.js";
|
||||
import { DEFAULT_EXPLORE_CONFIG_PATH, configPlatforms, readExploreConfig, readExploreInstructions, resolvePlatformConfig, type ExploreConfig, type ExplorePlatform } from "../config/explore-config.js";
|
||||
import { DEFAULT_EXPLORE_CONFIG_PATH, configPlatforms, readExploreConfig, readExploreInstructions, resolvePlatformConfig, withRunOverrides, type ExploreConfig, type ExplorePlatform } from "../config/explore-config.js";
|
||||
import { explorationSecretNames } from "../config/exploration-inputs.js";
|
||||
import { controllerCached } from "../shared/controller-cache.js";
|
||||
import { ARGENT_VERSION } from "../shared/argent-version.js";
|
||||
import { AGENT_PROVIDERS as PROVIDERS, DRAFT_INSTRUCTIONS_MARKER, EXPO_TOKENS_URL as TOKENS, appConfig, simulatorProfiles } from "../config/setup.js";
|
||||
import { captureCompatibility } from "../capture/observer.js";
|
||||
import { assertCaptureEasProfile, assertSimulatorAvailable, repackProfileFrom, unreproducibleEasVariables } from "../capture/eas-build.js";
|
||||
import { createCiAgentSession } from "../capture/agent/session.js";
|
||||
import { readRouteEntry, type RouteEntry, type RouteEntryReport } from "./route-entry.js";
|
||||
import { LEGACY_VENDOR_DIRECTORY, WORKFLOW_FILES, ciLayout, renderWorkflow, workflowIssues, workflowTemplateDrift, workflowVersion } from "./workflow-install.js";
|
||||
import { LEGACY_VENDOR_DIRECTORY, OPTIONAL_WORKFLOW_FILES, WORKFLOW_FILES, ciLayout, renderWorkflow, workflowIssues, workflowTemplateDrift, workflowVersion } from "./workflow-install.js";
|
||||
import { EXPLORE_VERSION, TOOL_ROOT, packageBin } from "../shared/package-paths.js";
|
||||
import type { Progress } from "../shared/progress.js";
|
||||
|
||||
@@ -46,6 +48,8 @@ export type DoctorOptions = {
|
||||
github?: boolean;
|
||||
/** One small model request with the local provider key. */
|
||||
checkModel?: boolean;
|
||||
/** `--controller`: the device controller to check, over the config's `capture.controller`. */
|
||||
controller?: string | undefined;
|
||||
run?: DoctorRun;
|
||||
environment?: NodeJS.ProcessEnv;
|
||||
nodeVersion?: string;
|
||||
@@ -240,8 +244,11 @@ async function ciFileChecks(project: string, secretNames: readonly string[], run
|
||||
const file = `.github/workflows/${name}`;
|
||||
const path = join(layout.root, file);
|
||||
if (!await exists(path)) {
|
||||
checks.push({ step: 6, id: `workflow-${name}`, status: "fail", code: "WORKFLOW_MISSING", message: `${file} is missing.`,
|
||||
nextAction: "Run expo-explore setup --workflows, then commit the workflows." });
|
||||
checks.push(OPTIONAL_WORKFLOW_FILES.has(name)
|
||||
? { step: 6, id: `workflow-${name}`, status: "warn", code: "WORKFLOW_MISSING", message: `${file} is missing, so reviews of two commits without a pull request (a tag against the last release, say) cannot run.`,
|
||||
nextAction: "Run expo-explore setup --workflows to add it, then commit it." }
|
||||
: { step: 6, id: `workflow-${name}`, status: "fail", code: "WORKFLOW_MISSING", message: `${file} is missing.`,
|
||||
nextAction: "Run expo-explore setup --workflows, then commit the workflows." });
|
||||
continue;
|
||||
}
|
||||
const text = await readFile(path, "utf8");
|
||||
@@ -301,6 +308,7 @@ function githubChecks(root: string, config: ExploreConfig, secretNames: readonly
|
||||
const published = remote(path, branch);
|
||||
let local: string | undefined;
|
||||
try { local = readFileSync(join(root, path), "utf8"); } catch { /* Reported by the CI file checks. */ }
|
||||
if (local === undefined && OPTIONAL_WORKFLOW_FILES.has(name)) return [];
|
||||
return published === undefined ? [`${name} (missing)`] : local !== undefined && published !== local ? [`${name} (different)`] : [];
|
||||
});
|
||||
checks.push(stale.length
|
||||
@@ -379,7 +387,7 @@ export async function runDoctor(options: DoctorOptions): Promise<DoctorReport> {
|
||||
return { ok: false, mode: null, checks, ...(routes ? { routes } : {}) };
|
||||
}
|
||||
let config: ExploreConfig;
|
||||
try { config = await readExploreConfig(project); }
|
||||
try { config = withRunOverrides(await readExploreConfig(project), { controller: options.controller }); }
|
||||
catch (error) {
|
||||
checks.push(fromError(4, "config", error, { code: "CONFIG_INVALID", nextAction: `Correct ${DEFAULT_EXPLORE_CONFIG_PATH} and rerun doctor.` }));
|
||||
return { ok: false, mode: null, checks };
|
||||
@@ -388,6 +396,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." });
|
||||
if (config.capture.controller === "argent") checks.push(argentCheck(environment));
|
||||
if (config.capture.launch !== "off") {
|
||||
const ffmpeg = run("ffmpeg", ["-version"], project);
|
||||
checks.push(ffmpeg.status === 0
|
||||
@@ -465,7 +474,7 @@ export async function runDoctor(options: DoctorOptions): Promise<DoctorReport> {
|
||||
checks.push(...files.checks);
|
||||
if (files.root) {
|
||||
const pending = run("git", ["status", "--porcelain", "--untracked-files=all", "--", DEFAULT_EXPLORE_CONFIG_PATH, ...(config.agent?.instructions ? [config.agent.instructions] : [])], project).stdout
|
||||
+ run("git", ["status", "--porcelain", "--untracked-files=normal", "--", ".github/workflows/explore-review.yml", ".github/workflows/explore-baseline.yml"], files.root).stdout;
|
||||
+ run("git", ["status", "--porcelain", "--untracked-files=normal", "--", ...WORKFLOW_FILES.map(name => `.github/workflows/${name}`)], files.root).stdout;
|
||||
const paths = [...new Set(pending.split("\n").map(line => line.slice(3).trim()).filter(Boolean))];
|
||||
if (paths.length) checks.push({ step: 6, id: "committed", status: "fail", code: "SETUP_FILES_UNCOMMITTED",
|
||||
message: `Setup files are not committed: ${list(paths)}. CI reads them from the pushed repository.`,
|
||||
@@ -543,7 +552,16 @@ 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.
|
||||
*/
|
||||
export async function runCaptureCheck(options: { project: string; output: string; platform?: ExplorePlatform; environment?: NodeJS.ProcessEnv; runner?: CommandRunner; progress?: Progress }): Promise<CaptureCheckResult> {
|
||||
/** 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);
|
||||
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; environment?: NodeJS.ProcessEnv; runner?: CommandRunner; progress?: Progress }): Promise<CaptureCheckResult> {
|
||||
const project = await realpath(options.project);
|
||||
const git = (...args: string[]) => spawnSync("git", ["-C", project, ...args], { encoding: "utf8", timeout: 10_000 });
|
||||
const head = git("rev-parse", "HEAD");
|
||||
@@ -555,7 +573,7 @@ export async function runCaptureCheck(options: { project: string; output: string
|
||||
nextAction: "Commit your changes, including .expo-explore (a local commit is enough; nothing is pushed), then rerun. "
|
||||
+ "To keep unrelated files, run it from a clean checkout instead: git worktree add --detach ../app-capture HEAD, install the app's dependencies there, and run doctor --capture in it." });
|
||||
const commit = head.stdout.trim();
|
||||
const config = resolvePlatformConfig(await readExploreConfig(project), options.platform);
|
||||
const config = withRunOverrides(resolvePlatformConfig(await readExploreConfig(project), options.platform), { controller: options.controller });
|
||||
// Capture keeps its working directories in the system temporary directory, outside the app.
|
||||
await mkdir(options.output, { recursive: true });
|
||||
const output = await realpath(options.output);
|
||||
@@ -565,7 +583,10 @@ export async function runCaptureCheck(options: { project: string; output: string
|
||||
nextAction: "Omit --output to use a new temporary directory, or pass a directory inside the system temporary directory." });
|
||||
let failure: CaptureCheckResult["failure"];
|
||||
try {
|
||||
// Agent mode with no API key set uses the local claude or codex login, as a local review does.
|
||||
const subscription = config.mode === "agent" && config.agent !== undefined && !(options.environment ?? process.env)[PROVIDERS[config.agent.provider].secret]?.trim();
|
||||
await runBaselineCi({ ...(options.platform ? { platform: options.platform } : {}), project, sha: commit, output, config, useLocalEasSession: true,
|
||||
...(subscription ? { subscription: true } : {}),
|
||||
...(options.environment ? { environment: options.environment } : {}), ...(options.runner ? { runner: options.runner } : {}),
|
||||
...(options.progress ? { progress: options.progress } : {}) });
|
||||
} catch (error) {
|
||||
|
||||
@@ -0,0 +1,486 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { copyFile, cp, lstat, mkdir, mkdtemp, readdir, readFile, realpath, rename, rm, stat, utimes, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, relative, resolve } from "node:path";
|
||||
import { runCiReview } from "./pipeline.js";
|
||||
import { resolveCommit } from "./workflow-steps.js";
|
||||
import { ciLayout, installCommand, type PackageManager } from "./workflow-install.js";
|
||||
import { configPlatforms, readExploreConfig, resolvePlatformConfig, withRunOverrides, DEFAULT_EXPLORE_CONFIG_PATH, type ExploreConfig, type ExplorePlatform } from "../config/explore-config.js";
|
||||
import { AGENT_PROVIDERS, defaultExploreConfig } from "../config/setup.js";
|
||||
import type { PrepareCiExplorationOptions } from "../capture/agent/exploration.js";
|
||||
import { createCiAgentSession } from "../capture/agent/session.js";
|
||||
import { createLocalCiAgentSession } from "../capture/agent/session-local.js";
|
||||
import type { CommandRunner } from "../capture/run.js";
|
||||
import { isSafeBranchRef, type LocalReviewPresentation, type PullRequestSidePresentation } from "../contracts/review.js";
|
||||
import { exportCiReport, readCiReportInput } from "../report/artifact.js";
|
||||
import { reviewChangeCount, reviewDevice, type PublicCommentState } from "../report/pr-comment-body.js";
|
||||
import { zipReportDirectory } from "../report/preview-deploy.js";
|
||||
import { CiError } from "../shared/ci-errors.js";
|
||||
import { exploreCacheRoot } from "../shared/cache-root.js";
|
||||
import { packageBin } from "../shared/package-paths.js";
|
||||
import { silentProgress, type Progress } from "../shared/progress.js";
|
||||
|
||||
/**
|
||||
* `capture:review --base REF [--head REF]` on a laptop: the same review CI runs (`runCiReview`), on two commits of the
|
||||
* current repository, with your own `eas login` and your local Claude or Codex login when no token or key is set.
|
||||
* Each commit is checked out as a detached worktree in a private temporary directory, its dependencies installed
|
||||
* without credentials in the environment, and both are removed afterwards. The report is packaged per platform.
|
||||
*/
|
||||
export type LocalReviewOptions = {
|
||||
project: string;
|
||||
base?: string | undefined;
|
||||
head?: string | undefined;
|
||||
/** Review HEAD alone, leaving out the working tree's changes. */
|
||||
committed?: boolean | undefined;
|
||||
/** Review the working tree even when eas.json sets cli.requireCommit. Without --head this is the default. */
|
||||
uncommitted?: boolean | undefined;
|
||||
platform?: ExplorePlatform | undefined;
|
||||
scope?: string | undefined;
|
||||
expiresIn?: string | undefined;
|
||||
/** `--controller`: the device controller for both sides, over the config's `capture.controller`. */
|
||||
controller?: string | undefined;
|
||||
/** Reuse and keep captures in the local capture cache (default true). */
|
||||
cache?: boolean | undefined;
|
||||
configPath?: string | undefined;
|
||||
environment?: NodeJS.ProcessEnv;
|
||||
progress?: Progress;
|
||||
/** Behaves like Ctrl+C when aborted: for callers (and tests) that stop a review without a signal. */
|
||||
interrupt?: AbortSignal | undefined;
|
||||
/** Tests: replace the dependency install (given the app directory in that side's checkout) and the capture process. */
|
||||
install?: (project: string, side: "base" | "head") => Promise<void>;
|
||||
runner?: CommandRunner; now?: () => number; sleep?: (milliseconds: number) => void;
|
||||
agentSessionFactory?: PrepareCiExplorationOptions["createSession"];
|
||||
};
|
||||
|
||||
export type LocalReviewReport = { platform: ExplorePlatform; directory: string; zip: string; changes?: number; device?: string };
|
||||
export type LocalReviewResult = {
|
||||
runId: string; base: PullRequestSidePresentation; head: PullRequestSidePresentation & { uncommitted?: string[] };
|
||||
work: string; reports: LocalReviewReport[]; config: ExploreConfig; repository: string;
|
||||
};
|
||||
|
||||
/** Git, without the user's hooks or fsmonitor, and never with a terminal prompt. */
|
||||
function git(cwd: string, args: string[], environment: NodeJS.ProcessEnv = process.env, input?: string) {
|
||||
const result = spawnSync("git", ["-c", "core.fsmonitor=false", "-c", "core.hooksPath=/dev/null", "-C", cwd, ...args],
|
||||
{ encoding: "utf8", env: { ...environment, GIT_TERMINAL_PROMPT: "0" }, maxBuffer: 64 * 1024 * 1024, ...(input === undefined ? {} : { input }) });
|
||||
return { ok: result.status === 0, stdout: result.stdout?.trim() ?? "", stderr: result.stderr?.trim() ?? "" };
|
||||
}
|
||||
|
||||
function must(result: ReturnType<typeof git>, message: string, nextAction: string): string {
|
||||
if (!result.ok) throw new CiError({ code: "LOCAL_REVIEW_GIT_FAILED", stage: "preflight", message: `${message}: ${result.stderr || "git failed"}`, nextAction });
|
||||
return result.stdout;
|
||||
}
|
||||
|
||||
const UNTRACKED_LIMIT_BYTES = 50 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* The working tree as a commit on top of HEAD, without touching the user's index, files or refs: a temporary
|
||||
* index seeded from the real one, `git add`, `write-tree`, `commit-tree`. Tracked changes only, unless `untracked`.
|
||||
* Undefined when nothing changed.
|
||||
*/
|
||||
export async function snapshotWorkingTree(root: string, options: { untracked?: boolean | undefined; work: string }):
|
||||
Promise<{ sha: string; changed: string[]; untracked: string[] } | undefined> {
|
||||
const index = join(options.work, "snapshot-index");
|
||||
const real = resolve(root, must(git(root, ["rev-parse", "--git-path", "index"]), "Cannot find the repository index", "Run this inside a git repository."));
|
||||
try { await copyFile(real, index); } catch { /* A repository without an index starts empty. */ }
|
||||
const environment = { ...process.env, GIT_INDEX_FILE: index, GIT_OPTIONAL_LOCKS: "0" };
|
||||
const untracked = options.untracked ? must(git(root, ["ls-files", "-z", "--others", "--exclude-standard"]), "Cannot list untracked files", "Check the repository.")
|
||||
.split("\0").filter(Boolean) : [];
|
||||
let bytes = 0;
|
||||
for (const file of untracked) bytes += (await stat(join(root, file)).catch(() => ({ size: 0 }))).size;
|
||||
if (bytes > UNTRACKED_LIMIT_BYTES) throw new CiError({ code: "LOCAL_REVIEW_UNTRACKED_TOO_LARGE", stage: "preflight",
|
||||
message: `The untracked files add up to ${Math.round(bytes / 1024 / 1024)} MB; they would be uploaded with the EAS build.`,
|
||||
nextAction: "Ignore or commit the large files, or pass --committed to review HEAD alone." });
|
||||
must(git(root, ["add", options.untracked ? "-A" : "-u", "--", "."], environment), "Cannot stage the working tree", "Check the repository's state.");
|
||||
const tree = must(git(root, ["write-tree"], environment), "Cannot write the working tree", "Check the repository's state.");
|
||||
await rm(index, { force: true });
|
||||
if (tree === must(git(root, ["rev-parse", "HEAD^{tree}"]), "The repository has no commit", "Commit once, then rerun.")) return undefined;
|
||||
const changed = must(git(root, ["diff", "--name-only", "-z", "HEAD", tree]), "Cannot list the changes", "Check the repository.").split("\0").filter(Boolean);
|
||||
const sha = must(git(root, ["commit-tree", tree, "-p", "HEAD", "-m", "Expo Explore: uncommitted changes"],
|
||||
{ ...process.env, GIT_AUTHOR_NAME: "Expo Explore", GIT_AUTHOR_EMAIL: "explore@localhost", GIT_COMMITTER_NAME: "Expo Explore", GIT_COMMITTER_EMAIL: "explore@localhost" }),
|
||||
"Cannot record the uncommitted changes", "Check the repository's state.");
|
||||
return { sha, changed, untracked: untracked.filter(file => changed.includes(file)) };
|
||||
}
|
||||
|
||||
/**
|
||||
* The base when none is given: where HEAD left the default branch (what it would merge), named after it. Both the
|
||||
* local branch and origin's are considered, by exact ref (a tag of the same name never counts), and the newer fork
|
||||
* point wins, so neither a stale local `main` nor an unfetched `origin/main` adds other people's changes. On the
|
||||
* default branch itself, its unpushed commits are reviewed against origin's.
|
||||
*/
|
||||
export function defaultBase(root: string, headSha: string): PullRequestSidePresentation {
|
||||
const remote = git(root, ["symbolic-ref", "--quiet", "--short", "refs/remotes/origin/HEAD"]);
|
||||
for (const branch of remote.ok ? [remote.stdout.replace(/^origin\//, "")] : ["main", "master"]) {
|
||||
const tips = [`refs/heads/${branch}`, `refs/remotes/origin/${branch}`]
|
||||
.map(ref => git(root, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`])).filter(result => result.ok).map(result => result.stdout);
|
||||
if (!tips.length) continue;
|
||||
const forks = tips.map(tip => git(root, ["merge-base", tip, headSha])).filter(result => result.ok).map(result => result.stdout);
|
||||
if (!forks.length) throw new CiError({ code: "LOCAL_REVIEW_BASE_REQUIRED", stage: "preflight", message: `${branch} and the head share no history.`,
|
||||
nextAction: "Pass --base with a commit the head descends from." });
|
||||
// Each fork point is an ancestor of the other; the newer one is where the head actually branched off. A fork point
|
||||
// that is the head itself is the branch you are on (main with unpushed commits): the other one is what you would push onto.
|
||||
const candidates = forks.filter(fork => fork !== headSha);
|
||||
const fork = (candidates.length ? candidates : forks).reduce((older, newer) => git(root, ["merge-base", "--is-ancestor", older, newer]).ok ? newer : older);
|
||||
return { ref: tips.includes(fork) ? branch : `${branch} (merge base)`, sha: fork };
|
||||
}
|
||||
throw new CiError({ code: "LOCAL_REVIEW_BASE_REQUIRED", stage: "preflight", message: "This repository has no default branch to compare with.",
|
||||
nextAction: "Pass --base with a branch, tag or commit SHA." });
|
||||
}
|
||||
|
||||
/**
|
||||
* The name a report gives a ref: as typed, unless the report's ref rules refuse it (`@{u}`, `@{-1}`, `HEAD@{1}`); then
|
||||
* the branch it names, or the commit's short SHA. Checked here, since the report itself is only written after capture.
|
||||
*/
|
||||
export function reportRef(root: string, ref: string, sha: string): string {
|
||||
if (isSafeBranchRef(ref)) return ref;
|
||||
const name = git(root, ["rev-parse", "--abbrev-ref", "--verify", "--quiet", ref]);
|
||||
return name.ok && name.stdout && name.stdout !== "HEAD" && isSafeBranchRef(name.stdout) ? name.stdout : sha.slice(0, 8);
|
||||
}
|
||||
|
||||
/** owner/name from a github.com `origin`, or a local name; the report shows it and the hosted project is named after it. */
|
||||
export function repositoryName(root: string, config: ExploreConfig): string {
|
||||
const remote = git(root, ["remote", "get-url", "origin"]).stdout;
|
||||
const match = /github\.com[:/]([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?$/.exec(remote);
|
||||
return match ? `${match[1]}/${match[2]}` : `local/${(config.app.name ?? "app").replace(/[^A-Za-z0-9_.-]+/g, "-").replace(/^[-.]+|[-.]+$/g, "") || "app"}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The environment of app installs: no variable named like a credential. A reviewed commit's .npmrc or .yarnrc.yml
|
||||
* could otherwise send `${NPM_TOKEN}` or `${CLAUDE_CODE_OAUTH_TOKEN}` to a registry it chooses, even with
|
||||
* --ignore-scripts. Proxy, certificate, cache and SSH-agent settings stay. This matches CI, whose install step
|
||||
* gets no secrets; registry auth in your own ~/.npmrc is scoped to its host and still applies. It is not a sandbox: a
|
||||
* commit's yarnPath, Yarn plugins or .pnpmfile.cjs still run as you, as its app config and bundling do later.
|
||||
*/
|
||||
export function appEnvironment(environment: NodeJS.ProcessEnv): NodeJS.ProcessEnv {
|
||||
return Object.fromEntries(Object.entries(environment).filter(([key]) =>
|
||||
key === "SSH_AUTH_SOCK" || !/(TOKEN|SECRET|PASSWORD|KEY|AUTH|CREDENTIAL|SESSION|COOKIE)/i.test(key)));
|
||||
}
|
||||
|
||||
/** The frozen-lockfile install setup derives for CI, without `corepack enable` (that changes your Node install). */
|
||||
export function localInstallCommand(manager: PackageManager, directory: string): string {
|
||||
return installCommand(manager, directory).replace(/^corepack enable && /, "");
|
||||
}
|
||||
|
||||
/** Install from the app directory: the lockfile is the nearest one at or above it, as `setup` finds it for CI. */
|
||||
export async function installDependencies(project: string, logFile: string, environment: NodeJS.ProcessEnv): Promise<void> {
|
||||
const layout = await ciLayout(project);
|
||||
if (!layout.manager) throw new CiError({ code: "LOCAL_REVIEW_LOCKFILE_MISSING", stage: "preflight", message: "The app has no lockfile at this commit.",
|
||||
nextAction: "Commit the app's lockfile, then rerun." });
|
||||
const command = localInstallCommand(layout.manager, layout.installDir);
|
||||
const result = spawnSync("sh", ["-c", command], { cwd: layout.root, env: appEnvironment(environment), encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
|
||||
await writeFile(logFile, `$ ${command}\n${result.stdout ?? ""}${result.stderr ?? ""}`);
|
||||
if (result.status !== 0) throw new CiError({ code: "LOCAL_REVIEW_INSTALL_FAILED", stage: "preflight", message: `Installing the app's dependencies failed: ${command}`,
|
||||
nextAction: `Read ${logFile}; ${layout.manager === "npm" ? "" : `make sure ${layout.manager.replace("-classic", "")} is installed, and `}check the lockfile at that commit. `
|
||||
+ "Installs run without credential environment variables: a registry that needs ${NPM_TOKEN} in the project's .npmrc must be authenticated in your own ~/.npmrc instead." });
|
||||
}
|
||||
|
||||
/** `~/.cache/expo-explore/captures/<platform>/<sha>`: one capture per commit and platform, reused while its recipe matches. */
|
||||
export function captureCacheDirectory(environment: NodeJS.ProcessEnv, platform: ExplorePlatform, sha: string): string {
|
||||
return join(exploreCacheRoot(environment), "captures", platform, sha);
|
||||
}
|
||||
|
||||
async function exists(path: string): Promise<boolean> { try { await lstat(path); return true; } catch { return false; } }
|
||||
|
||||
const CACHE_METADATA = "cache-metadata.json";
|
||||
|
||||
/**
|
||||
* Drops cached captures not used for 30 days, then the least recently used until the rest fit in 2 GB, as saved runs
|
||||
* are pruned. A capture counts as used when a review keeps or reuses it (its cache-metadata.json is touched then).
|
||||
*/
|
||||
export async function pruneCaptureCache(environment: NodeJS.ProcessEnv, now = Date.now(), limits = { maxAgeDays: 30, maxBytes: 2 * 1024 * 1024 * 1024 }): Promise<string[]> {
|
||||
const root = join(exploreCacheRoot(environment), "captures");
|
||||
const entries: Array<{ path: string; used: number; bytes: number }> = [];
|
||||
const size = async (path: string): Promise<number> => {
|
||||
const info = await lstat(path);
|
||||
if (!info.isDirectory()) return info.size;
|
||||
let total = 0;
|
||||
for (const name of await readdir(path)) total += await size(join(path, name));
|
||||
return total;
|
||||
};
|
||||
for (const platform of await readdir(root).catch(() => [] as string[])) {
|
||||
for (const sha of await readdir(join(root, platform)).catch(() => [] as string[])) {
|
||||
const path = join(root, platform, sha);
|
||||
if (!/^[0-9a-f]{40}$/.test(sha)) continue;
|
||||
const used = await stat(join(path, CACHE_METADATA)).then(info => info.mtimeMs, () => 0);
|
||||
entries.push({ path, used, bytes: await size(path).catch(() => 0) });
|
||||
}
|
||||
}
|
||||
entries.sort((a, b) => a.used - b.used);
|
||||
let total = entries.reduce((sum, entry) => sum + entry.bytes, 0);
|
||||
const removed: string[] = [];
|
||||
for (const entry of entries) {
|
||||
if (now - entry.used <= limits.maxAgeDays * 86_400_000 && total <= limits.maxBytes) continue;
|
||||
await rm(entry.path, { recursive: true, force: true });
|
||||
total -= entry.bytes;
|
||||
removed.push(entry.path);
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
async function cacheRecipe(directory: string): Promise<{ recipe: string; images: number } | undefined> {
|
||||
try {
|
||||
const metadata = JSON.parse(await readFile(join(directory, CACHE_METADATA), "utf8")) as { recipe?: unknown };
|
||||
const bundle = JSON.parse(await readFile(join(directory, "bundle.json"), "utf8")) as { images?: Record<string, unknown> };
|
||||
return typeof metadata.recipe === "string" ? { recipe: metadata.recipe, images: Object.keys(bundle.images ?? {}).length } : undefined;
|
||||
} catch { return undefined; }
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep an export as a commit's cached capture. Only exports whose evidence validated carry cache metadata. An entry
|
||||
* from another recipe (an Explore upgrade, a config change) is replaced; one with the same recipe only by an export
|
||||
* with at least as many screens, so a partial capture never shrinks a fuller one.
|
||||
*/
|
||||
export async function keepCapture(exported: string, target: string): Promise<boolean> {
|
||||
const next = await cacheRecipe(exported);
|
||||
if (!next) return false;
|
||||
const current = await cacheRecipe(target);
|
||||
if (current && current.recipe === next.recipe && current.images > next.images) return false;
|
||||
// Copied beside the entry and renamed into place, so a review reading the cache (or another one writing it) never
|
||||
// sees a half-copied capture; when two write at once, the first rename wins and the other copy is dropped.
|
||||
await mkdir(resolve(target, ".."), { recursive: true });
|
||||
const staged = `${target}.${randomBytes(4).toString("hex")}.tmp`;
|
||||
try {
|
||||
await cp(exported, staged, { recursive: true });
|
||||
await rm(target, { recursive: true, force: true });
|
||||
await rename(staged, target);
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (!["ENOTEMPTY", "EEXIST"].includes((error as NodeJS.ErrnoException).code ?? "")) throw error;
|
||||
return false;
|
||||
} finally {
|
||||
await rm(staged, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function recordedSessionIds(outputs: string[]): string[] {
|
||||
return outputs.flatMap(output => ["head-session", "base-session"].flatMap(name => {
|
||||
try { const id = readFileSync(join(output, name), "utf8").trim(); return /^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(id) ? [id] : []; } catch { return []; }
|
||||
}));
|
||||
}
|
||||
|
||||
/** Stop the EAS Simulator sessions a capture recorded and did not stop itself (an interrupted run), with the local login. */
|
||||
export async function stopRecordedSessions(outputs: string[], environment: NodeJS.ProcessEnv, runner: (args: string[]) => { status: number | null } =
|
||||
args => spawnSync(packageBin("eas-cli", "eas"), args, { env: environment, encoding: "utf8", timeout: 120_000 }), quiet = false): Promise<string[]> {
|
||||
const stopped: string[] = [];
|
||||
for (const output of outputs) for (const name of ["head-session", "base-session"]) {
|
||||
const file = join(output, name);
|
||||
const id = (await readFile(file, "utf8").catch(() => "")).trim();
|
||||
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(id)) continue;
|
||||
if (runner(["simulator:stop", "--id", id, "--json", "--non-interactive"]).status === 0) { stopped.push(id); await rm(file, { force: true }); }
|
||||
// During an interrupt the capture may stop the same session first; only the final pass reports a failure.
|
||||
else if (!quiet) process.stderr.write(`Could not stop EAS Simulator session ${id}; stop it with: eas simulator:stop --id ${id}\n`);
|
||||
}
|
||||
return stopped;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the head of a review without --head is: the working tree, as `eas build` uploads it (tracked and untracked
|
||||
* files, not ignored ones), unless the app's eas.json sets cli.requireCommit, which makes eas build refuse uncommitted
|
||||
* changes, or --committed asks for HEAD alone. --head names a commit, so the working tree is never part of it.
|
||||
*/
|
||||
export async function reviewHeadSource(options: Pick<LocalReviewOptions, "head" | "committed" | "uncommitted">, project: string):
|
||||
Promise<"working-tree" | "commit" | "require-commit"> {
|
||||
const namedHead = options.head !== undefined && options.head !== "HEAD";
|
||||
if (options.uncommitted && (namedHead || options.committed)) throw new CiError({ code: "LOCAL_REVIEW_UNCOMMITTED_HEAD", stage: "preflight",
|
||||
message: "--uncommitted reviews the working tree, which is on top of HEAD.", nextAction: `Leave out ${namedHead ? "--head" : "--committed"}, or leave out --uncommitted.` });
|
||||
if (namedHead || options.committed) return "commit";
|
||||
if (options.uncommitted) return "working-tree";
|
||||
let eas: unknown;
|
||||
try { eas = JSON.parse(await readFile(join(project, "eas.json"), "utf8")); } catch { return "working-tree"; }
|
||||
const cli = eas !== null && typeof eas === "object" ? (eas as { cli?: unknown }).cli : undefined;
|
||||
return cli !== null && typeof cli === "object" && (cli as { requireCommit?: unknown }).requireCommit === true ? "require-commit" : "working-tree";
|
||||
}
|
||||
|
||||
/**
|
||||
* The config a local review runs with: the head commit's; else the one in your checkout, when setup has written it but
|
||||
* it is not committed yet; else the defaults setup would write, so an app can be reviewed before it is set up. A
|
||||
* config path passed with --config must be in the head commit.
|
||||
*/
|
||||
export async function localReviewConfig(options: { project: string; head: string; configPath: string; explicit: boolean;
|
||||
platform?: ExplorePlatform | undefined; progress?: Progress }): Promise<ExploreConfig> {
|
||||
const progress = options.progress ?? silentProgress;
|
||||
if (options.explicit || await exists(join(options.head, options.configPath))) return readExploreConfig(options.head, options.configPath);
|
||||
if (await exists(join(options.project, options.configPath))) {
|
||||
progress(`config: ${options.configPath} from your checkout (it is not in the head commit)`);
|
||||
return readExploreConfig(options.project, options.configPath);
|
||||
}
|
||||
let config: ExploreConfig;
|
||||
try { config = await defaultExploreConfig(options.project, options.platform); }
|
||||
catch (error) {
|
||||
throw new CiError({ code: "LOCAL_REVIEW_CONFIG_DEFAULTS", stage: "preflight",
|
||||
message: `There is no ${options.configPath}, so this review uses setup's defaults, which need this: ${(error as Error).message}`,
|
||||
nextAction: "Fix that and rerun (with several simulator profiles, the one named explore is used), or run expo-explore setup to write a config." });
|
||||
}
|
||||
progress(`config: none yet, so setup's defaults (${config.app.bundleId}, EAS profile ${config.app.easProfile}, ${config.device.name}); `
|
||||
+ "expo-explore setup writes one you can change");
|
||||
return config;
|
||||
}
|
||||
|
||||
export async function runLocalReview(options: LocalReviewOptions): Promise<LocalReviewResult> {
|
||||
const environment = { ...(options.environment ?? process.env) };
|
||||
const progress = options.progress ?? silentProgress;
|
||||
const project = await realpath(options.project);
|
||||
const root = await realpath(must(git(project, ["rev-parse", "--show-toplevel"]), "Not a git repository", "Run this inside the app's git repository."));
|
||||
const appDirectory = relative(root, project) || ".";
|
||||
const runId = `local-${new Date((options.now ?? Date.now)()).toISOString().replace(/[^0-9]/g, "").slice(0, 14)}-${randomBytes(3).toString("hex")}`;
|
||||
const work = await realpath(await mkdtemp(join(tmpdir(), "expo-explore-review-")));
|
||||
const worktrees: string[] = [];
|
||||
const outputs: string[] = [];
|
||||
// The first Ctrl+C stops the captures between steps (deterministic or agent), aborts model requests and stops the
|
||||
// recorded simulator sessions, so the capture fails fast and unwinds through its own cleanup and the finally below. A second one quits now, naming any session left running.
|
||||
const abort = new AbortController();
|
||||
let interrupts = 0;
|
||||
const interrupt = () => {
|
||||
interrupts += 1;
|
||||
if (interrupts === 1) {
|
||||
process.stderr.write("\nStopping the review and its EAS Simulator sessions… (Ctrl+C again to quit now)\n");
|
||||
abort.abort(new CiError({ code: "LOCAL_REVIEW_INTERRUPTED", stage: "capture", message: "The review was interrupted.", nextAction: "Rerun it when you are ready." }));
|
||||
if (!options.runner) void stopRecordedSessions(outputs, environment, undefined, true);
|
||||
return;
|
||||
}
|
||||
for (const tree of worktrees) git(root, ["worktree", "remove", "--force", tree]);
|
||||
for (const id of recordedSessionIds(outputs)) process.stderr.write(`Still running: stop it with eas simulator:stop --id ${id}\n`);
|
||||
process.exit(130);
|
||||
};
|
||||
process.on("SIGINT", interrupt);
|
||||
process.on("SIGTERM", interrupt);
|
||||
options.interrupt?.addEventListener("abort", interrupt, { once: true });
|
||||
const factory = options.agentSessionFactory;
|
||||
let failed = false;
|
||||
try {
|
||||
// The commits.
|
||||
const headRef = options.head ?? "HEAD";
|
||||
let head: LocalReviewResult["head"];
|
||||
const source = await reviewHeadSource(options, project);
|
||||
if (source === "require-commit") progress("head: HEAD; eas.json sets cli.requireCommit, so uncommitted changes are left out as eas build leaves them out (--uncommitted includes them)");
|
||||
if (source === "working-tree") {
|
||||
const snapshot = await snapshotWorkingTree(root, { untracked: true, work });
|
||||
head = snapshot ? { ref: "uncommitted changes", sha: snapshot.sha, uncommitted: snapshot.changed } : { ref: "HEAD", sha: resolveCommit(root, "HEAD", "head") };
|
||||
if (snapshot) progress(`head: HEAD with your uncommitted changes to ${snapshot.changed.length} file${snapshot.changed.length === 1 ? "" : "s"}, as eas build would upload them`
|
||||
+ (snapshot.untracked.length ? ` (untracked, kept in .git/objects until git gc: ${snapshot.untracked.join(", ")})` : "") + "; --committed leaves them out");
|
||||
else progress("head: HEAD (no uncommitted changes)");
|
||||
} else {
|
||||
const sha = resolveCommit(root, headRef, "head");
|
||||
head = { ref: reportRef(root, headRef, sha), sha };
|
||||
}
|
||||
const baseSha = options.base ? resolveCommit(root, options.base, "base") : undefined;
|
||||
const base = options.base && baseSha ? { ref: reportRef(root, options.base, baseSha), sha: baseSha } : defaultBase(root, head.sha);
|
||||
if (base.sha === head.sha) throw new CiError({ code: "COMPARE_SAME_COMMIT", stage: "preflight", message: `${base.ref} and ${head.ref} are the same commit (${head.sha.slice(0, 8)}).`,
|
||||
nextAction: "Change something to review it, or pass --base with an earlier commit." });
|
||||
progress(`comparing ${head.ref} (${head.sha.slice(0, 8)}) with ${base.ref} (${base.sha.slice(0, 8)})`);
|
||||
|
||||
// The checkouts, and the config at head.
|
||||
const checkouts = { base: join(work, "base"), head: join(work, "head") };
|
||||
for (const side of ["base", "head"] as const) {
|
||||
must(git(root, ["worktree", "add", "--detach", "--quiet", checkouts[side], side === "base" ? base.sha : head.sha]),
|
||||
`Cannot check out the ${side} commit`, "Check the repository's state, then rerun.");
|
||||
worktrees.push(checkouts[side]);
|
||||
}
|
||||
const projects = { base: join(checkouts.base, appDirectory), head: join(checkouts.head, appDirectory) };
|
||||
const configPath = options.configPath ?? DEFAULT_EXPLORE_CONFIG_PATH;
|
||||
const rawConfig = await localReviewConfig({ project, head: projects.head, configPath, explicit: options.configPath !== undefined,
|
||||
platform: options.platform, progress });
|
||||
const platforms = options.platform ? [options.platform] : configPlatforms(rawConfig);
|
||||
const repository = repositoryName(root, rawConfig);
|
||||
|
||||
// Credentials: tokens and keys when set, otherwise your own logins.
|
||||
const useLocalEasSession = !environment.EXPO_TOKEN?.trim();
|
||||
if (useLocalEasSession && !options.runner) {
|
||||
const whoami = spawnSync(packageBin("eas-cli", "eas"), ["whoami"], { cwd: projects.head, env: environment, encoding: "utf8", timeout: 60_000 });
|
||||
if (whoami.status !== 0) throw new CiError({ code: "EXPO_LOGIN_REQUIRED", stage: "preflight", message: "You are not logged in to EAS.",
|
||||
nextAction: "Run eas login (or set EXPO_TOKEN), then rerun." });
|
||||
}
|
||||
const subscription = rawConfig.mode === "agent" && rawConfig.agent !== undefined && !environment[AGENT_PROVIDERS[rawConfig.agent.provider].secret]?.trim();
|
||||
if (subscription) progress(`model: your local ${rawConfig.agent!.provider === "anthropic" ? "claude" : "codex"} login (no ${AGENT_PROVIDERS[rawConfig.agent!.provider].secret} set)`);
|
||||
|
||||
let installed = false;
|
||||
const install = options.install ?? (async (project: string, side: "base" | "head") => {
|
||||
progress(`installing the ${side} commit's dependencies`);
|
||||
await installDependencies(project, join(work, `install-${side}.log`), environment);
|
||||
});
|
||||
const reports: LocalReviewReport[] = [];
|
||||
for (const platform of platforms) {
|
||||
const config = withRunOverrides(resolvePlatformConfig(rawConfig, platform), { scope: options.scope, expiresIn: options.expiresIn, controller: options.controller });
|
||||
const output = join(work, platform); await mkdir(output);
|
||||
outputs.push(output);
|
||||
const platformEnvironment = { ...environment };
|
||||
delete platformEnvironment.EXPLORE_CAPTURE_CACHE;
|
||||
const cachedBase = captureCacheDirectory(environment, platform, base.sha);
|
||||
if (options.cache !== false && await exists(join(cachedBase, CACHE_METADATA))) {
|
||||
platformEnvironment.EXPLORE_CAPTURE_CACHE = cachedBase;
|
||||
// Reusing a capture counts as using it, so pruning keeps the bases reviews come back to.
|
||||
await utimes(join(cachedBase, CACHE_METADATA), new Date(), new Date()).catch(() => undefined);
|
||||
}
|
||||
const presentation: LocalReviewPresentation = { origin: "local", repository, runId, title: `${head.ref} vs ${base.ref}`,
|
||||
base: { ref: base.ref, sha: base.sha }, head: { ref: head.ref, sha: head.sha } };
|
||||
const state: PublicCommentState = { phase: "pending", pullRequest: presentation, mode: config.exploration.scope, executionMode: config.mode,
|
||||
configPath: appDirectory === "." ? configPath : `${appDirectory}/${configPath}`,
|
||||
links: { viewer: null, download: null, run: "", config: "", artifacts: "" }, startedAt: Date.now(), updatedAt: Date.now(),
|
||||
build: { platform: config.app.platform, easProfile: config.app.easProfile }, artifactOnly: true };
|
||||
progress(`${platform}: reviewing`);
|
||||
const result = await runCiReview({ projects, output, config, presentation, runId, runAttempt: "1", state, environment: platformEnvironment,
|
||||
...(platforms.length > 1 ? { platforms } : {}), subscription, useLocalEasSession, progress: message => progress(`${platform}: ${message}`),
|
||||
...(options.runner ? { runner: options.runner } : {}), ...(options.now ? { now: options.now } : {}), ...(options.sleep ? { sleep: options.sleep } : {}),
|
||||
signal: abort.signal,
|
||||
// Model requests end on Ctrl+C: the session kills its own process group and restores any login it changed.
|
||||
agentSessionFactory: (configuration, sessionOptions) => {
|
||||
const session = (factory ?? (subscription ? createLocalCiAgentSession : createCiAgentSession))(configuration, sessionOptions);
|
||||
return { ...session,
|
||||
preflight: preflightOptions => session.preflight({ ...preflightOptions, signal: preflightOptions?.signal ? AbortSignal.any([preflightOptions.signal, abort.signal]) : abort.signal }),
|
||||
run: request => session.run({ ...request, signal: request.signal ? AbortSignal.any([request.signal, abort.signal]) : abort.signal }) };
|
||||
},
|
||||
prepareCapture: async () => {
|
||||
if (installed) return;
|
||||
for (const side of ["head", "base"] as const) await install(projects[side], side);
|
||||
installed = true;
|
||||
},
|
||||
assertCurrentHead: async () => {
|
||||
abort.signal.throwIfAborted();
|
||||
for (const side of ["base", "head"] as const) {
|
||||
if (git(projects[side], ["rev-parse", "HEAD"]).stdout !== (side === "base" ? base.sha : head.sha)
|
||||
|| git(checkouts[side], ["status", "--porcelain", "--untracked-files=normal"]).stdout) {
|
||||
throw new CiError({ code: "CHECKOUT_MODIFIED", stage: "capture", message: `The ${side} checkout changed during capture.`,
|
||||
nextAction: "Keep generated files outside the app's source, then rerun." });
|
||||
}
|
||||
}
|
||||
},
|
||||
postComment: async () => {} });
|
||||
const directory = join(output, "report");
|
||||
await exportCiReport({ inputPath: result.inputPath, outputPath: directory });
|
||||
const zip = join(output, "report.zip");
|
||||
await writeFile(zip, await zipReportDirectory(directory));
|
||||
const input = await readCiReportInput(result.inputPath);
|
||||
const changes = reviewChangeCount(input.commentState); const device = reviewDevice(input.commentState);
|
||||
reports.push({ platform, directory, zip, ...(changes === undefined ? {} : { changes }), ...(device ? { device } : {}) });
|
||||
// Keep both sides' captures for later reviews of these commits; a working-tree snapshot is never reviewed again.
|
||||
if (options.cache !== false) for (const side of ["base", "head"] as const) {
|
||||
if (side === "head" && head.uncommitted) continue;
|
||||
await keepCapture(join(output, `${side}-export`), captureCacheDirectory(environment, platform, side === "base" ? base.sha : head.sha));
|
||||
}
|
||||
if (options.cache !== false) await pruneCaptureCache(environment).catch(() => []);
|
||||
// The report is all that is kept; the captures, maps and checkouts are the bulk of the run.
|
||||
for (const entry of await readdir(output)) if (entry !== "report" && entry !== "report.zip") await rm(join(output, entry), { recursive: true, force: true });
|
||||
abort.signal.throwIfAborted();
|
||||
}
|
||||
// The install logs and snapshot index go too; the checkouts are removed with git below.
|
||||
for (const entry of await readdir(work)) if (![...platforms, "base", "head"].includes(entry)) await rm(join(work, entry), { recursive: true, force: true });
|
||||
return { runId, base, head, work, reports, config: rawConfig, repository };
|
||||
} catch (error) {
|
||||
failed = true;
|
||||
// A capture interrupted mid-session reports its cleanup; the interruption is what happened.
|
||||
throw abort.signal.aborted ? abort.signal.reason : error;
|
||||
} finally {
|
||||
process.off("SIGINT", interrupt);
|
||||
process.off("SIGTERM", interrupt);
|
||||
options.interrupt?.removeEventListener("abort", interrupt);
|
||||
// A capture stops its own sessions; this catches one that ended before it could. Tests inject their own runner.
|
||||
if (!options.runner) await stopRecordedSessions(outputs, environment).catch(() => []);
|
||||
// Only the run's own worktrees: a repository-wide prune would also drop the user's own worktrees on an unmounted disk.
|
||||
for (const tree of worktrees) git(root, ["worktree", "remove", "--force", tree]);
|
||||
// A failed run keeps what it produced for inspection; one that failed before producing anything leaves nothing.
|
||||
if (failed) {
|
||||
if ((await readdir(work).catch(() => [])).length) progress(`kept this review's files for inspection: ${work}`);
|
||||
else await rm(work, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -14,7 +14,7 @@ import { runCiMapOnWorker } from "./capture-worker.js";
|
||||
import { writeCiReportInput, readAppDirectory } from "../report/artifact.js";
|
||||
import { assessPublicEvidence, readExportedMap, type PublicEvidenceSide } from "../review/evidence-assessment.js";
|
||||
import { parseRuntimeExecutionContext } from "../review/runtime-adapter.js";
|
||||
import { projectPullRequestPresentation, type ReviewPresentation } from "../contracts/review.js";
|
||||
import { projectComparePresentation, projectPullRequestPresentation, type ReviewPresentation } from "../contracts/review.js";
|
||||
import { renderPublicComment, platformSectionMerge, type PublicCommentState } from "../report/pr-comment-body.js";
|
||||
import { upsertStickyComment } from "../report/pr-comment.js";
|
||||
import { viewerLinks } from "../report/viewer-links.js";
|
||||
@@ -26,6 +26,7 @@ import type { SourceCapturePlan } from "../source/capture-plan.js";
|
||||
import { createSourceChangeSummaries } from "../source/change-summary.js";
|
||||
import { assertNoCaptureHealthIssues, partitionCaptureHealthIssues, renderCaptureIssueAnnotation, renderComparisonDiagnosticAnnotation, renderNotesUnavailableAnnotation, renderReviewGapAnnotation, sortedCaptureHealthIssues } from "../capture/health.js";
|
||||
import { EXPLORE_PACKAGE, packageBin } from "../shared/package-paths.js";
|
||||
import { agentDeviceLauncher, ensureController } from "../shared/controller-cache.js";
|
||||
import { silentProgress, type Progress } from "../shared/progress.js";
|
||||
|
||||
|
||||
@@ -63,16 +64,22 @@ type CaptureClock = { now?: (() => number) | undefined; sleep?: ((milliseconds:
|
||||
|
||||
function captureOptions(config: ExploreConfig, environment: NodeJS.ProcessEnv, runner?: CommandRunner, clock: CaptureClock = {}) {
|
||||
return { ...(runner && clock.now ? { now: clock.now } : {}), ...(runner && clock.sleep ? { sleep: clock.sleep } : {}), platform: config.app.platform, bundleId: config.app.bundleId,
|
||||
...(config.app.scheme ? { scheme: config.app.scheme } : {}), device: config.device.name,
|
||||
...(config.app.scheme ? { scheme: config.app.scheme } : {}), device: config.device.name, ...(config.device.pose ? { devicePose: config.device.pose } : {}),
|
||||
easProfile: config.app.easProfile, expoToken: environment.EXPO_TOKEN ?? "",
|
||||
maxScreens: 5000, maxActions: config.capture.maxActions, maxDurationMinutes: config.capture.maxMinutes,
|
||||
setup: config.setup ?? [], forceFreshBuild: false, confirmExternalRun: true, confirmTrustedSource: true, repack: config.capture.repack, appearance: config.capture.appearance, launch: config.capture.launch, reset: config.capture.reset, unattributed: config.capture.unattributed, ...(config.capture.readinessSeconds !== undefined ? { readinessSeconds: config.capture.readinessSeconds } : {}),
|
||||
environment, ...(runner ? { runner } : {}), easCommand: packageBin("eas-cli", "eas"), agentDeviceCommand: packageBin("agent-device", "agent-device"), repackCommand: packageBin("@expo/repack-app", "repack-app") };
|
||||
setup: config.setup ?? [], forceFreshBuild: false, confirmExternalRun: true, confirmTrustedSource: true, repack: config.capture.repack, appearance: config.capture.appearance, launch: config.capture.launch, reset: config.capture.reset, unattributed: config.capture.unattributed, ...(config.capture.readinessSeconds !== undefined ? { readinessSeconds: config.capture.readinessSeconds } : {}), ...(config.capture.controller ? { controller: config.capture.controller } : {}),
|
||||
environment, ...(runner ? { runner } : {}), easCommand: packageBin("eas-cli", "eas"), agentDeviceCommand: agentDeviceLauncher(environment), repackCommand: packageBin("@expo/repack-app", "repack-app") };
|
||||
}
|
||||
/**
|
||||
* Head and base run in parallel worker threads when nothing ties them together: an agent session is
|
||||
* shared, an injected runner belongs to this thread, and a plausible baseline needs head's runtime profile.
|
||||
*/
|
||||
/** The controllers a capture of this config runs: agent-device always (it also compares screenshots), Argent when chosen. */
|
||||
async function prefetchControllers(config: ExploreConfig, environment: NodeJS.ProcessEnv, progress: Progress): Promise<void> {
|
||||
await ensureController("agent-device", { environment, progress });
|
||||
if (config.capture.controller === "argent") await ensureController("argent", { environment, progress });
|
||||
}
|
||||
|
||||
export function captureSidesConcurrently(input: { plan: SourceCapturePlan; agent: boolean; injectedRunner: boolean; baselineMayExist: boolean }): boolean {
|
||||
return !input.agent && !input.injectedRunner && !input.baselineMayExist
|
||||
&& input.plan.headCaptureSurfaceIds.length > 0 && input.plan.baseCaptureSurfaceIds.length > 0;
|
||||
@@ -105,35 +112,59 @@ export type PublicCiOptions = {
|
||||
progress?: Progress;
|
||||
};
|
||||
|
||||
export async function runPublicCi(options: PublicCiOptions) {
|
||||
const environment = options.environment ?? process.env;
|
||||
const transport = options.transport ?? fetch;
|
||||
const now = options.now ?? Date.now;
|
||||
const config = options.config;
|
||||
const githubToken = requireSecret(environment, "GITHUB_TOKEN");
|
||||
function assertRunIdentity(environment: NodeJS.ProcessEnv): void {
|
||||
if (!/^[1-9][0-9]*$/.test(environment.GITHUB_RUN_ID ?? "") || !/^[1-9][0-9]*$/.test(environment.GITHUB_RUN_ATTEMPT ?? "")) {
|
||||
throw new CiError({ code: "CI_RUN_IDENTITY_MISSING", stage: "preflight", message: "The GitHub run ID or attempt is missing.",
|
||||
nextAction: "Run capture:review inside the maintained Explore GitHub Actions workflow." });
|
||||
}
|
||||
const pr = projectPullRequestPresentation(JSON.parse(await readFile(options.pullRequestPath, "utf8")));
|
||||
}
|
||||
|
||||
/** What both CI adapters check before capture: exact checkouts of both sides and an output outside them. */
|
||||
async function prepareCiRun(options: Pick<PublicCiOptions, "baseProject" | "headProject" | "output" | "config" | "configPath" | "now">,
|
||||
environment: NodeJS.ProcessEnv, presentation: ReviewPresentation) {
|
||||
const now = options.now ?? Date.now;
|
||||
const config = options.config;
|
||||
const projects = { base: await realpath(options.baseProject), head: await realpath(options.headProject) };
|
||||
const output = resolve(options.output);
|
||||
const temporary = await realpath(environment.RUNNER_TEMP || tmpdir());
|
||||
const outputRelative = relative(temporary, output);
|
||||
if (!outputRelative || outputRelative.startsWith("..") || isAbsolute(outputRelative)) throw new Error("CI output must be inside RUNNER_TEMP, outside source checkouts");
|
||||
for (const side of ["base", "head"] as const) {
|
||||
assertCheckout(projects[side], pr[side].sha);
|
||||
assertCheckout(projects[side], presentation[side].sha);
|
||||
const rel = relative(projects[side], output);
|
||||
if (!rel.startsWith("..") && !isAbsolute(rel)) throw new Error("Capture output cannot be inside a source checkout");
|
||||
}
|
||||
const appDirectory = await readAppDirectory(projects.head);
|
||||
const configPath = options.configPath ?? DEFAULT_EXPLORE_CONFIG_PATH;
|
||||
const repositoryConfigPath = appDirectory === "." ? configPath : `${appDirectory}/${configPath}`;
|
||||
const state: PublicCommentState = { phase: "pending", pullRequest: pr, mode: config.exploration.scope,
|
||||
const state: PublicCommentState = { phase: "pending", pullRequest: presentation, mode: config.exploration.scope,
|
||||
executionMode: config.mode, configPath: repositoryConfigPath,
|
||||
links: viewerLinks({ repository: pr.repository, headSha: pr.head.sha, runId: environment.GITHUB_RUN_ID!,
|
||||
links: viewerLinks({ repository: presentation.repository, headSha: presentation.head.sha, runId: environment.GITHUB_RUN_ID!,
|
||||
runAttempt: environment.GITHUB_RUN_ATTEMPT!, configPath: repositoryConfigPath }),
|
||||
startedAt: now(), updatedAt: now(), build: { platform: config.app.platform, easProfile: config.app.easProfile }, artifactOnly: true };
|
||||
return { projects, output, state };
|
||||
}
|
||||
|
||||
/** A review of any two commits (`capture:review --compare FILE`): the same capture as a PR's, with no PR to verify or comment on. */
|
||||
export async function runCompareCi(options: Omit<PublicCiOptions, "pullRequestPath" | "transport" | "onComment"> & { comparePath: string }) {
|
||||
const environment = options.environment ?? process.env;
|
||||
assertRunIdentity(environment);
|
||||
const comparison = projectComparePresentation(JSON.parse(await readFile(options.comparePath, "utf8")));
|
||||
const { projects, output, state } = await prepareCiRun(options, environment, comparison);
|
||||
const assertCurrentHead = async () => { for (const side of ["base", "head"] as const) assertCheckout(projects[side], comparison[side].sha); };
|
||||
return runCiReview({ ...options, projects, output, state, presentation: comparison,
|
||||
environment, runId: environment.GITHUB_RUN_ID!, runAttempt: environment.GITHUB_RUN_ATTEMPT!,
|
||||
assertCurrentHead, postComment: async () => {} });
|
||||
}
|
||||
|
||||
export async function runPublicCi(options: PublicCiOptions) {
|
||||
const environment = options.environment ?? process.env;
|
||||
const transport = options.transport ?? fetch;
|
||||
const now = options.now ?? Date.now;
|
||||
const githubToken = requireSecret(environment, "GITHUB_TOKEN");
|
||||
assertRunIdentity(environment);
|
||||
const pr = projectPullRequestPresentation(JSON.parse(await readFile(options.pullRequestPath, "utf8")));
|
||||
const { projects, output, state } = await prepareCiRun(options, environment, pr);
|
||||
const postComment = async () => {
|
||||
await assertCurrentPr();
|
||||
state.updatedAt = now(); const body = renderPublicComment(state); options.onComment?.(state, body);
|
||||
@@ -217,9 +248,14 @@ export async function runCiReview(options: {
|
||||
agentSessionFactory?: PrepareCiExplorationOptions["createSession"];
|
||||
prepareCapture?: () => Promise<void>;
|
||||
progress?: Progress;
|
||||
/** Stops the captures between steps; model requests take it through agentSessionFactory. */
|
||||
signal?: AbortSignal;
|
||||
}) {
|
||||
const { projects, output, config, environment, state, assertCurrentHead, postComment } = options;
|
||||
const progress = options.progress ?? silentProgress;
|
||||
// The controllers are fetched before any EAS work, so a blocked download fails before a session is paid for. agent-device
|
||||
// also compares the screenshots. An injected runner (tests) runs no real controller.
|
||||
if (!options.runner) await prefetchControllers(config, environment, progress);
|
||||
const pr = options.presentation;
|
||||
const now = options.now ?? Date.now;
|
||||
const secretValues = Object.entries(environment).filter(([key]) => /(?:TOKEN|SECRET|PASSWORD|API_KEY)/i.test(key)).flatMap(([, value]) => value ? [value] : []);
|
||||
@@ -274,11 +310,11 @@ export async function runCiReview(options: {
|
||||
...(options.useLocalEasSession ? { useLocalEasSession: true } : {}),
|
||||
...(exploration.agent ? { agent: exploration.agent } : {}), project: projects[side],
|
||||
mapDirectory: join(output, `${side}-map`), outputDirectory: directory,
|
||||
name: config.app.name ?? pr.repository, buildId: pr.origin === "local" ? `local-${pr.runId}-${side}` : `pr-${pr.number}-${side}`, buildVersion: pr[side].sha.slice(0, 8), gitCommit: pr[side].sha,
|
||||
name: config.app.name ?? pr.repository, buildId: pr.origin === "local" ? `local-${pr.runId}-${side}` : pr.origin === "compare" ? `compare-${options.runId}-${side}` : `pr-${pr.number}-${side}`, buildVersion: pr[side].sha.slice(0, 8), gitCommit: pr[side].sha,
|
||||
planPath: join(output, "execution-plan.json"), side, sessionStatePath: join(output, `${side}-session`),
|
||||
...(reuseDirectory ? { reuseDirectory } : {}) };
|
||||
...(reuseDirectory ? { reuseDirectory } : {}), ...(options.signal ? { signal: options.signal } : {}) };
|
||||
const captured = concurrent
|
||||
? await runCiMapOnWorker((({ progress: _progress, runner: _runner, agent: _agent, ...rest }) => rest)(mapOptions), progress)
|
||||
? await runCiMapOnWorker((({ progress: _progress, runner: _runner, agent: _agent, signal: _signal, ...rest }) => rest)(mapOptions), progress, options.signal)
|
||||
: await runCiMap(mapOptions);
|
||||
const bundle = await readCaptureBundle(directory);
|
||||
bundle.profile = cacheRecipe.profile;
|
||||
@@ -318,7 +354,7 @@ export async function runCiReview(options: {
|
||||
stage = "compare";
|
||||
progress("comparing base and head captures");
|
||||
const sides = { base: await evidenceSide(join(output, "base-export")), head: await evidenceSide(join(output, "head-export")) };
|
||||
const evidence = await assessPublicEvidence({ platform: config.app.platform, plan, ...sides, ...(options.measure ? { measure: options.measure } : {}), profile: `${config.app.easProfile}:${config.app.bundleId}`, agentDeviceCommand: packageBin("agent-device", "agent-device") });
|
||||
const evidence = await assessPublicEvidence({ platform: config.app.platform, plan, ...sides, ...(options.measure ? { measure: options.measure } : {}), profile: `${config.app.easProfile}:${config.app.bundleId}`, agentDeviceCommand: agentDeviceLauncher(options.environment) });
|
||||
const result = await prepareCaptureReview({ plan, pullRequest: pr, baseDirectory: sides.base.directory, headDirectory: sides.head.directory,
|
||||
runId: options.runId, runAttempt: options.runAttempt, assertCurrentHead, assessments: evidence.surfaces,
|
||||
...(options.platforms ? { platforms: options.platforms } : {}),
|
||||
@@ -394,7 +430,7 @@ export async function runCiReview(options: {
|
||||
}
|
||||
}
|
||||
await preserveReport();
|
||||
progress("writing the report and updating the pull request comment");
|
||||
progress(pr.origin === "compare" || pr.origin === "local" ? "writing the report" : "writing the report and updating the pull request comment");
|
||||
await assertCurrentHead(); await postComment();
|
||||
return { ...result, evidence, inputPath };
|
||||
} catch (error) {
|
||||
@@ -413,9 +449,12 @@ export async function runBaselineCi(options: { platform?: ExplorePlatform; proje
|
||||
now?: () => number; sleep?: (milliseconds: number) => void;
|
||||
agentSessionFactory?: PrepareCiExplorationOptions["createSession"]; progress?: Progress;
|
||||
/** Use the local `eas login` session instead of EXPO_TOKEN (expo-explore doctor --capture). */
|
||||
useLocalEasSession?: boolean }) {
|
||||
useLocalEasSession?: boolean;
|
||||
/** Agent mode with the local claude or codex login instead of the provider's API key. */
|
||||
subscription?: boolean }) {
|
||||
const environment = options.environment ?? process.env;
|
||||
assertCheckout(options.project, options.sha);
|
||||
if (!options.runner) await prefetchControllers(options.config, environment, options.progress ?? silentProgress);
|
||||
const output = resolve(options.output);
|
||||
const relativeOutput = relative(await realpath(options.project), output);
|
||||
if (!relativeOutput.startsWith("..") || isAbsolute(relativeOutput)) throw new Error("Baseline output must be outside the source checkout");
|
||||
@@ -429,7 +468,7 @@ export async function runBaselineCi(options: { platform?: ExplorePlatform; proje
|
||||
let usagePhase: AgentUsagePhase = "preflight";
|
||||
const exploration = await prepareCiExploration(options.config, options.project, environment, active,
|
||||
{ ...(options.agentSessionFactory ? { createSession: options.agentSessionFactory } : {}),
|
||||
onUsage: recordAgentUsage(output, () => usagePhase) });
|
||||
onUsage: recordAgentUsage(output, () => usagePhase), ...(options.subscription ? { subscription: true } : {}) });
|
||||
const directory = join(output, "baseline-export");
|
||||
usagePhase = "capture-baseline";
|
||||
const result = await runCiMap({ ...captureOptions(options.config, environment, options.runner, { now: options.now, sleep: options.sleep }), progress,
|
||||
@@ -439,6 +478,7 @@ export async function runBaselineCi(options: { platform?: ExplorePlatform; proje
|
||||
buildId: `baseline-${options.sha.slice(0, 12)}`, buildVersion: options.sha.slice(0, 8), gitCommit: options.sha,
|
||||
side: "head", planPath: join(output, "execution-plan.json"), sessionStatePath: join(output, "baseline-session") });
|
||||
const cacheRecipe = await recipe(options.config, plan, "head", environment, exploration.instructionsSha256);
|
||||
if (options.subscription) cacheRecipe.toolsCommit += ":local-subscription";
|
||||
const bundle = await readCaptureBundle(directory); bundle.profile = cacheRecipe.profile;
|
||||
await writeFile(join(directory, "bundle.json"), JSON.stringify(bundle));
|
||||
const cached = await writeCaptureArtifactCache(directory, cacheRecipe);
|
||||
|
||||
@@ -4,7 +4,9 @@ import { lstat, mkdir, readFile, realpath, writeFile } from "node:fs/promises";
|
||||
import { dirname, join, relative } from "node:path";
|
||||
import { EXPLORE_VERSION, TOOL_ROOT } from "../shared/package-paths.js";
|
||||
|
||||
export const WORKFLOW_FILES = ["explore-review.yml", "explore-baseline.yml"] as const;
|
||||
export const WORKFLOW_FILES = ["explore-review.yml", "explore-baseline.yml", "explore-compare.yml"] as const;
|
||||
/** Installed by setup but not needed for pull request reviews: doctor reports one that is missing as a warning. */
|
||||
export const OPTIONAL_WORKFLOW_FILES: ReadonlySet<string> = new Set(["explore-compare.yml"]);
|
||||
/** Written by setup before npm distribution; CI now installs @expo/explore instead. */
|
||||
export const LEGACY_VENDOR_DIRECTORY = ".github/vendor/expo-explore";
|
||||
export const SECRET_ANCHOR = "# App-test secrets: one NAME: line per {{secret:NAME}} input in .expo-explore (expo-explore setup adds them).";
|
||||
@@ -116,8 +118,8 @@ export function forwardedSecretNames(workflow: string): string[] {
|
||||
|
||||
export function renderWorkflow(template: string, options: { projectDir: string; installDir: string; manager: PackageManager | undefined; secretNames: readonly string[] }): string {
|
||||
let text = pinWorkflowVersion(template)
|
||||
.replace(/^(\s+APP_PROJECT_DIR:) \.$/m, `$1 ${options.projectDir}`)
|
||||
.replace(/^(\s+APP_INSTALL_DIR:) \.$/m, `$1 ${options.installDir}`);
|
||||
.replace(/^(\s+APP_PROJECT_DIR:) \.$/gm, `$1 ${options.projectDir}`)
|
||||
.replace(/^(\s+APP_INSTALL_DIR:) \.$/gm, `$1 ${options.installDir}`);
|
||||
if (options.manager && options.manager !== "npm") {
|
||||
text = text.replace(TEMPLATE_INSTALL, (_match, directory: string) => installCommand(options.manager!, directory));
|
||||
}
|
||||
@@ -149,12 +151,14 @@ export function workflowIssues(file: string, text: string, expected: { projectDi
|
||||
if (!version || !EXACT_VERSION.test(version)) issues.push({ code: "EXPLORE_VERSION_INVALID", file,
|
||||
message: `${file} does not pin an exact @expo/explore version (EXPLORE_VERSION is ${version ?? "missing"}).`,
|
||||
nextAction: "Run expo-explore setup --workflows to set it." });
|
||||
const value = (name: string) => new RegExp(`^\\s+${name}: (.+)$`, "m").exec(text)?.[1]?.trim().replace(/^['"]|['"]$/g, "");
|
||||
// Workflows generated before 0.19 set these per job; every job must name the same directory.
|
||||
const values = (name: string) => [...text.matchAll(new RegExp(`^\\s+${name}: (.+)$`, "gm"))].map(match => match[1]!.trim().replace(/^['"]|['"]$/g, ""));
|
||||
for (const [name, wanted] of [["APP_PROJECT_DIR", expected.projectDir], ["APP_INSTALL_DIR", expected.installDir]] as const) {
|
||||
const actual = value(name);
|
||||
if (actual !== wanted) issues.push({ code: "WORKFLOW_APP_DIR_MISMATCH", file,
|
||||
message: `${name} is ${actual ?? "missing"}, but the app layout needs ${wanted}.`,
|
||||
nextAction: `Set ${name}: ${wanted} in ${file}.` });
|
||||
const actual = values(name);
|
||||
const wrong = actual.find(value => value !== wanted);
|
||||
if (!actual.length || wrong !== undefined) issues.push({ code: "WORKFLOW_APP_DIR_MISMATCH", file,
|
||||
message: `${name} is ${actual.length ? wrong : "missing"}${actual.length > 1 ? " in one of its jobs" : ""}, but the app layout needs ${wanted}.`,
|
||||
nextAction: `Set ${name}: ${wanted} everywhere in ${file}, or rerun expo-explore setup --workflows --force.` });
|
||||
}
|
||||
if (expected.manager && expected.manager !== "npm" && /npm ci --ignore-scripts --prefix/.test(text)) {
|
||||
const command = installCommand(expected.manager, "<dir>");
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { appendFile, lstat, mkdir, writeFile } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { parseTrustedAuthors, DEFAULT_EXPLORE_CONFIG_PATH } from "../config/explore-config.js";
|
||||
import { compareTitle, compareUrl, projectComparePresentation, projectPullRequestPresentation,
|
||||
type CompareReviewPresentation, type PullRequestPresentation } from "../contracts/review.js";
|
||||
import { CiError } from "../shared/ci-errors.js";
|
||||
import { readCiReportInput } from "../report/artifact.js";
|
||||
import { TOOL_ROOT, packageBin } from "../shared/package-paths.js";
|
||||
|
||||
/**
|
||||
* The work the GitHub workflows used to do in inline scripts: deciding which commits a run captures and whether it
|
||||
* may, finding a baseline to reuse, and cleaning up after capture. Each is one `expo-explore ci:*` command, so a
|
||||
* fix ships with the npm release instead of a regenerated workflow.
|
||||
*/
|
||||
|
||||
type Environment = NodeJS.ProcessEnv;
|
||||
const SHA = /^[0-9a-f]{40}$/;
|
||||
|
||||
/** `name=value` lines for later steps; a value never spans lines. */
|
||||
export async function writeStepOutputs(environment: Environment, values: Record<string, string>): Promise<void> {
|
||||
if (!environment.GITHUB_OUTPUT) return;
|
||||
await appendFile(environment.GITHUB_OUTPUT, Object.entries(values).map(([name, value]) => `${name}=${value.replace(/[\r\n]+/g, " ")}\n`).join(""));
|
||||
}
|
||||
|
||||
/** `capture:review`'s step output: `preview=eas` when the reviewed config hosts the report, which is what starts the deploy job. */
|
||||
export async function writeCaptureOutputs(inputPath: string, environment: Environment = process.env): Promise<void> {
|
||||
await writeStepOutputs(environment, { preview: (await readCiReportInput(inputPath)).preview?.hosting ?? "" });
|
||||
}
|
||||
|
||||
function githubContext(environment: Environment) {
|
||||
const repository = environment.GITHUB_REPOSITORY ?? "";
|
||||
const token = environment.GITHUB_TOKEN?.trim();
|
||||
if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository)) throw new CiError({ code: "CI_RUN_IDENTITY_MISSING", stage: "preflight",
|
||||
message: "GITHUB_REPOSITORY is missing.", nextAction: "Run this command inside a GitHub Actions workflow." });
|
||||
if (!token) throw new CiError({ code: "GITHUB_TOKEN_MISSING", stage: "preflight", message: "GITHUB_TOKEN is missing.",
|
||||
nextAction: "Pass GitHub's automatic github.token to this step as GITHUB_TOKEN." });
|
||||
return { repository, token };
|
||||
}
|
||||
|
||||
/** One GitHub REST read; 404 is an answer (undefined), every other failure stops the step with what to do. */
|
||||
async function githubGet<T>(path: string, context: { token: string }, transport: typeof fetch): Promise<T | undefined> {
|
||||
let response: Response;
|
||||
try {
|
||||
response = await transport(`https://api.github.com/${path}`, { redirect: "error", signal: AbortSignal.timeout(30_000),
|
||||
headers: { authorization: `Bearer ${context.token}`, accept: "application/vnd.github+json", "x-github-api-version": "2022-11-28" } });
|
||||
} catch (error) {
|
||||
throw new CiError({ code: "GITHUB_REQUEST_FAILED", stage: "preflight", message: `GitHub could not be reached (${path}).`,
|
||||
nextAction: "Check GitHub availability and rerun the workflow.", retryable: true, cause: error });
|
||||
}
|
||||
if (response.status === 404) { await response.body?.cancel().catch(() => {}); return undefined; }
|
||||
if (!response.ok) throw new CiError({ code: response.status === 401 ? "GITHUB_TOKEN_INVALID" : response.status === 403 ? "GITHUB_PERMISSION_DENIED" : "GITHUB_REQUEST_FAILED",
|
||||
stage: "preflight", message: `GitHub answered HTTP ${response.status} for ${path}.`, retryable: response.status >= 500,
|
||||
nextAction: response.status === 403 ? "Grant this job the permissions the workflow template gives it, then rerun." : "Rerun the workflow; check GitHub's status if it keeps failing." });
|
||||
return await response.json() as T;
|
||||
}
|
||||
|
||||
type GithubPull = {
|
||||
number: number; state: string; draft?: boolean; title: string; html_url: string; user?: { login?: string };
|
||||
base: { ref: string; sha: string; repo: { id: number; full_name: string; default_branch: string } };
|
||||
head: { ref: string; sha: string; repo?: { full_name?: string } | null };
|
||||
};
|
||||
|
||||
/**
|
||||
* `ci:pr`: the live pull request a review captures, refused unless it is open, not a draft, from this repository,
|
||||
* and written by someone with write access or listed in ci.trustedAuthors of the default branch's config.yaml.
|
||||
*/
|
||||
export async function resolvePullRequest(options: { number: number; appDirectory?: string; configPath?: string; environment?: Environment; transport?: typeof fetch }):
|
||||
Promise<{ presentation: PullRequestPresentation; author: string }> {
|
||||
const environment = options.environment ?? process.env; const transport = options.transport ?? fetch;
|
||||
const context = githubContext(environment);
|
||||
if (!Number.isSafeInteger(options.number) || options.number <= 0) throw new CiError({ code: "PR_NUMBER_INVALID", stage: "preflight",
|
||||
message: "The pull request number is invalid.", nextAction: "Provide an open pull request number." });
|
||||
const pr = await githubGet<GithubPull>(`repos/${context.repository}/pulls/${options.number}`, context, transport);
|
||||
if (!pr || pr.state !== "open" || pr.draft || pr.head.repo?.full_name !== context.repository) throw new CiError({ code: "SOURCE_NOT_TRUSTED", stage: "preflight",
|
||||
message: "Capture requires an open, non-draft same-repository pull request.", nextAction: "Run Explore for an open pull request from a branch of this repository." });
|
||||
const author = pr.user?.login ?? "";
|
||||
const permission = await githubGet<{ permission?: string }>(`repos/${context.repository}/collaborators/${encodeURIComponent(author)}/permission`, context, transport);
|
||||
if (!["admin", "maintain", "write"].includes(permission?.permission ?? "")) {
|
||||
const trusted = await trustedAuthors(context, transport, pr.base.repo.default_branch, options.appDirectory, options.configPath);
|
||||
if (!trusted.logins.includes(author.toLowerCase())) throw new CiError({ code: "SOURCE_NOT_TRUSTED", stage: "preflight",
|
||||
message: `${author || "The PR author"} has no write access to this repository and is not listed in ci.trustedAuthors.`
|
||||
+ (trusted.invalid ? ` The default branch's ci.trustedAuthors was ignored: ${trusted.invalid}` : ""),
|
||||
nextAction: trusted.invalid ? "Fix ci.trustedAuthors in .expo-explore/config.yaml on the default branch, then rerun Explore."
|
||||
: "The PR author must have current repository write access, or be listed in ci.trustedAuthors of .expo-explore/config.yaml on the default branch." });
|
||||
}
|
||||
for (const side of [pr.base, pr.head]) if (!SHA.test(side.sha)) throw new CiError({ code: "PR_COMMIT_INVALID", stage: "preflight",
|
||||
message: "GitHub returned an invalid commit for the pull request.", nextAction: "Refresh the PR and rerun Explore." });
|
||||
return { author, presentation: projectPullRequestPresentation({ repositoryId: String(pr.base.repo.id), repository: pr.base.repo.full_name,
|
||||
number: pr.number, title: pr.title, url: pr.html_url, base: { ref: pr.base.ref, sha: pr.base.sha }, head: { ref: pr.head.ref, sha: pr.head.sha } }) };
|
||||
}
|
||||
|
||||
/** ci.trustedAuthors from the default branch's config: a pull request cannot add its own author. An invalid list trusts no one, and says why. */
|
||||
async function trustedAuthors(context: { repository: string; token: string }, transport: typeof fetch, branch: string, appDirectory = ".", configPath = DEFAULT_EXPLORE_CONFIG_PATH): Promise<{ logins: string[]; invalid?: string }> {
|
||||
const directory = appDirectory.replace(/^\.(\/|$)/, "").replace(/\/$/, "");
|
||||
const path = `${directory ? `${directory}/` : ""}${configPath}`;
|
||||
const file = await githubGet<{ content?: string }>(`repos/${context.repository}/contents/${path.split("/").map(encodeURIComponent).join("/")}?ref=${encodeURIComponent(branch)}`, context, transport);
|
||||
if (!file?.content) return { logins: [] };
|
||||
try { return { logins: parseTrustedAuthors(Buffer.from(file.content, "base64").toString("utf8")).map(login => login.toLowerCase()) }; }
|
||||
catch (error) { return { logins: [], invalid: error instanceof Error ? error.message : String(error) }; }
|
||||
}
|
||||
|
||||
type GithubArtifact = { id: number; expired: boolean; workflow_run?: { id?: number } };
|
||||
type GithubRun = { conclusion: string | null; workflow_id: number; head_sha: string; head_branch: string; event: string; head_repository?: { full_name?: string } };
|
||||
|
||||
/**
|
||||
* `ci:find-baseline`: the newest successful baseline-workflow artifact of exactly this commit, uploaded from the
|
||||
* default branch of this repository. Its id and run go to the step outputs for actions/download-artifact.
|
||||
*/
|
||||
export async function findBaselineArtifact(options: { sha: string; platform?: string; environment?: Environment; transport?: typeof fetch }): Promise<{ id: number; run: number } | undefined> {
|
||||
const environment = options.environment ?? process.env; const transport = options.transport ?? fetch;
|
||||
const context = githubContext(environment);
|
||||
if (!SHA.test(options.sha)) throw new CiError({ code: "SHA_INVALID", stage: "preflight", message: "The base commit must be a full SHA.", nextAction: "Pass --sha with a 40-character commit SHA." });
|
||||
const repository = await githubGet<{ default_branch: string }>(`repos/${context.repository}`, context, transport);
|
||||
const workflow = await githubGet<{ id: number }>(`repos/${context.repository}/actions/workflows/explore-baseline.yml`, context, transport);
|
||||
if (!repository || !workflow) return undefined;
|
||||
// Baselines carry the platform suffix; iOS also accepts the unsuffixed name older baseline workflows uploaded.
|
||||
const names = [`explore-baseline-${options.sha}-${options.platform ?? "ios"}`, ...(options.platform === "android" ? [] : [`explore-baseline-${options.sha}`])];
|
||||
const artifacts: GithubArtifact[] = [];
|
||||
for (const name of names) for (let page = 1; page <= 10; page++) {
|
||||
const listed = await githubGet<{ artifacts: GithubArtifact[] }>(`repos/${context.repository}/actions/artifacts?name=${encodeURIComponent(name)}&per_page=100&page=${page}`, context, transport);
|
||||
artifacts.push(...listed?.artifacts ?? []);
|
||||
if ((listed?.artifacts.length ?? 0) < 100) break;
|
||||
}
|
||||
for (const artifact of artifacts.filter(candidate => !candidate.expired).sort((a, b) => b.id - a.id)) {
|
||||
if (!artifact.workflow_run?.id) continue;
|
||||
const run = await githubGet<GithubRun>(`repos/${context.repository}/actions/runs/${artifact.workflow_run.id}`, context, transport);
|
||||
if (!run || run.conclusion !== "success" || run.workflow_id !== workflow.id || run.head_sha !== options.sha
|
||||
|| run.head_branch !== repository.default_branch || !["push", "workflow_dispatch"].includes(run.event)
|
||||
|| run.head_repository?.full_name !== context.repository) continue;
|
||||
return { id: artifact.id, run: artifact.workflow_run.id };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* `ci:find-baseline` as the workflow runs it: a baseline is optional, so a lookup that fails (a GitHub 5xx, a rate
|
||||
* limit) is a warning and no baseline, never an error. A `ci:*` error would write explore-diagnostics/error.json,
|
||||
* which the failure comment would then report as the cause of an unrelated failure, possibly on another platform.
|
||||
*/
|
||||
export async function findOptionalBaseline(options: Parameters<typeof findBaselineArtifact>[0]):
|
||||
Promise<{ baseline?: { id: number; run: number }; warning?: { code: string; message: string } }> {
|
||||
try {
|
||||
const baseline = await findBaselineArtifact(options);
|
||||
return baseline ? { baseline } : {};
|
||||
} catch (error) {
|
||||
return { warning: { code: error instanceof CiError ? error.code : "BASELINE_LOOKUP_FAILED",
|
||||
message: `No baseline is reused, so capture captures the base too: ${error instanceof Error ? error.message : String(error)}` } };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The commit a ref names in a checkout. `HEAD` (and `HEAD~1`, `@`) is the checked-out commit, never `origin/HEAD`.
|
||||
* A name is tried as a tag, then a local branch, then a branch of `origin` (all CI has after a full checkout),
|
||||
* then as git spells it (a SHA, `origin/main`, `refs/heads/...`).
|
||||
*/
|
||||
export function resolveCommit(project: string, ref: string, side: "base" | "head"): string {
|
||||
if (!ref.trim() || ref.startsWith("-") || /[\s\u0000-\u001f]/.test(ref)) throw new CiError({ code: "COMPARE_REF_INVALID", stage: "preflight",
|
||||
message: `The ${side} '${ref}' is not a ref.`, nextAction: `Pass ${side} as a branch, tag or commit SHA.` });
|
||||
const relative = /^(?:HEAD|@)(?:[~^].*)?$/.test(ref);
|
||||
for (const candidate of relative ? [ref] : [`refs/tags/${ref}`, `refs/heads/${ref}`, `refs/remotes/origin/${ref}`, ref]) {
|
||||
const result = spawnSync("git", ["-C", project, "rev-parse", "--verify", "--quiet", `${candidate}^{commit}`], { encoding: "utf8" });
|
||||
if (result.status === 0 && SHA.test(result.stdout.trim())) return result.stdout.trim();
|
||||
}
|
||||
throw new CiError({ code: "COMPARE_REF_NOT_FOUND", stage: "preflight", message: `${ref} is not a branch, tag or commit of this repository.`,
|
||||
nextAction: "Check the ref's spelling, and that the checkout fetched every branch and tag (fetch-depth: 0)." });
|
||||
}
|
||||
|
||||
/**
|
||||
* `ci:compare-refs`: the commits two refs (branch, tag or SHA) name in a full clone, as the comparison a
|
||||
* `capture:review --compare` run captures. A tag wins over a branch of the same name.
|
||||
*/
|
||||
export function resolveCompareRefs(options: { project: string; base: string; head: string; title?: string; environment?: Environment }): CompareReviewPresentation {
|
||||
const environment = options.environment ?? process.env;
|
||||
const repository = environment.GITHUB_REPOSITORY ?? "", repositoryId = environment.GITHUB_REPOSITORY_ID ?? "";
|
||||
const commit = (ref: string, side: "base" | "head") => resolveCommit(options.project, ref, side);
|
||||
const base = { ref: options.base, sha: commit(options.base, "base") }, head = { ref: options.head, sha: commit(options.head, "head") };
|
||||
if (base.sha === head.sha) throw new CiError({ code: "COMPARE_SAME_COMMIT", stage: "preflight",
|
||||
message: `${options.base} and ${options.head} are the same commit (${head.sha}).`, nextAction: "Compare two different commits; the baseline workflow captures a single one." });
|
||||
return projectComparePresentation({ origin: "compare", repositoryId, repository, base, head,
|
||||
title: options.title ?? compareTitle(base, head), url: compareUrl(repository, base, head) });
|
||||
}
|
||||
|
||||
/**
|
||||
* `ci:after-capture`: after capture, success or not. Stops the EAS Simulator sessions the capture recorded in its output
|
||||
* directory, then checks that capture left each source checkout as it found it. Reports every problem, then fails.
|
||||
*/
|
||||
export async function cleanupAfterCapture(options: { output: string; checkouts: string[]; environment?: Environment }):
|
||||
Promise<{ stopped: string[]; failures: Array<{ code: string; message: string; nextAction: string }> }> {
|
||||
const environment = options.environment ?? process.env;
|
||||
const result: { stopped: string[]; failures: Array<{ code: string; message: string; nextAction: string }> } = { stopped: [], failures: [] };
|
||||
const sessionFiles: string[] = [];
|
||||
for (const name of ["head-session", "base-session", "baseline-session"]) {
|
||||
const path = resolve(options.output, name);
|
||||
try { await lstat(path); sessionFiles.push(path); } catch { /* That side never started a session. */ }
|
||||
}
|
||||
if (sessionFiles.length) {
|
||||
const script = await import(pathToFileURL(join(TOOL_ROOT, "scripts", "cleanup-ci-sessions.mjs")).href) as {
|
||||
cleanupCiSessions(input: { sessionFiles: string[]; easCommand: string; environment: Environment }): Promise<{ stopped: string[]; failures: Array<{ code: string; message: string; nextAction: string }> }> };
|
||||
const sessions = await script.cleanupCiSessions({ sessionFiles, easCommand: packageBin("eas-cli", "eas"), environment });
|
||||
result.stopped.push(...sessions.stopped); result.failures.push(...sessions.failures);
|
||||
}
|
||||
for (const directory of options.checkouts) {
|
||||
const checkout = resolve(directory);
|
||||
try { await lstat(join(checkout, ".git")); } catch { continue; }
|
||||
const status = spawnSync("git", ["-C", checkout, "status", "--porcelain", "--untracked-files=all"], { encoding: "utf8" });
|
||||
if (status.status !== 0 || status.stdout.trim()) result.failures.push({ code: "CHECKOUT_MODIFIED", message: `Capture modified ${directory}.`,
|
||||
nextAction: "Keep generated files outside source checkouts." });
|
||||
}
|
||||
if (result.failures.length) {
|
||||
const diagnostics = join(environment.RUNNER_TEMP || tmpdir(), "explore-diagnostics");
|
||||
await mkdir(diagnostics, { recursive: true });
|
||||
await writeFile(join(diagnostics, "cleanup.json"), `${JSON.stringify(result, null, 2)}\n`);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -9,8 +9,9 @@ import { command, resultContract, argumentError, validateCommandArguments, flag,
|
||||
import { help } from "./cli/help.js";
|
||||
import { listScreens, getScreen, listElements, listObservations, getObservation, nextFrontier, listAttempts, getAttempt, listTransitions, getTransition, neighbors, pathQuery, listJourneys, getJourney, listFrontier, listGaps, summary, search, status, validate, exportArtifacts } from "./cli/map-commands.js";
|
||||
import { compareCommand, exportWeb, view } from "./cli/catalog-commands.js";
|
||||
import { ciReport, ciPublish, ciFailure, ciDeploy, setup, doctor, sourceVerify, captureReview, captureBaseline, configPlatforms } from "./cli/ci-commands.js";
|
||||
import { ciReport, ciPublish, ciFailure, ciDeploy, ciPullRequest, ciFindBaseline, ciCompareRefs, ciAfterCapture, setup, doctor, sourceVerify, captureReview, captureBaseline, configPlatforms } from "./cli/ci-commands.js";
|
||||
import { exploreBinary, exploreSession } from "./cli/binary-commands.js";
|
||||
import { reports, reportUpload } from "./cli/report-commands.js";
|
||||
|
||||
const handlers: Record<string, () => Promise<void> | void> = {
|
||||
setup,
|
||||
@@ -38,10 +39,16 @@ const handlers: Record<string, () => Promise<void> | void> = {
|
||||
"export:web": exportWeb,
|
||||
"explore:binary": exploreBinary,
|
||||
"explore:session": exploreSession,
|
||||
"report:upload": reportUpload,
|
||||
reports,
|
||||
"ci:report": ciReport,
|
||||
"ci:publish": ciPublish,
|
||||
"ci:failure": ciFailure,
|
||||
"ci:deploy": ciDeploy,
|
||||
"ci:pr": ciPullRequest,
|
||||
"ci:find-baseline": ciFindBaseline,
|
||||
"ci:compare-refs": ciCompareRefs,
|
||||
"ci:after-capture": ciAfterCapture,
|
||||
"capture:review": captureReview,
|
||||
"capture:baseline": captureBaseline,
|
||||
"source:verify": sourceVerify,
|
||||
@@ -58,7 +65,7 @@ const handlers: Record<string, () => Promise<void> | void> = {
|
||||
};
|
||||
|
||||
/** Commands people type at a terminal; everything else answers agents and scripts in JSON. */
|
||||
const HUMAN_COMMANDS = new Set(["setup", "doctor", "view", "help", "explore:binary", "explore:session"]);
|
||||
const HUMAN_COMMANDS = new Set(["setup", "doctor", "view", "help", "explore:binary", "explore:session", "report:upload", "reports"]);
|
||||
|
||||
function version(): void {
|
||||
console.log(EXPLORE_VERSION);
|
||||
|
||||
@@ -26,15 +26,20 @@ const aliases: Record<string, string> = {
|
||||
"config platforms": "config:platforms",
|
||||
};
|
||||
|
||||
/** One-word names for commands people type: `capture` is the local review, `capture:review` without its CI flags. */
|
||||
const shortNames: Record<string, string> = { capture: "capture:review" };
|
||||
|
||||
const first = argv[0] ?? "help";
|
||||
const pair = `${first} ${argv[1] ?? ""}`.trim();
|
||||
export const command = aliases[pair] ?? first;
|
||||
export const resultContract = ["source:verify", "capture:review", "capture:baseline", "ci:report", "ci:publish", "ci:failure", "ci:deploy", "config:platforms", "explore:binary", "explore:session"].includes(command)
|
||||
export const command = aliases[pair] ?? shortNames[first] ?? first;
|
||||
export const resultContract = ["source:verify", "capture:review", "capture:baseline", "ci:report", "ci:publish", "ci:failure", "ci:deploy", "ci:pr", "ci:find-baseline", "ci:compare-refs", "ci:after-capture", "config:platforms", "explore:binary", "explore:session", "report:upload", "reports"].includes(command)
|
||||
? "explore.result" : QUERY_CONTRACT;
|
||||
const commandArgCount = aliases[pair] ? 2 : 1;
|
||||
const args = argv.slice(commandArgCount);
|
||||
/** Commands that take one bare argument before their flags, e.g. `explore:binary ./app.apk`. */
|
||||
const POSITIONAL_COMMANDS = new Set(["explore:binary", "explore:session"]);
|
||||
/** Commands that take any number of bare arguments among their flags, e.g. `report:upload ios/report.zip android/report.zip`. */
|
||||
const VARIADIC_COMMANDS = new Set(["report:upload", "reports"]);
|
||||
|
||||
const commonFlagKinds: Record<string, "value" | "boolean"> = {
|
||||
dir: "value",
|
||||
@@ -45,8 +50,8 @@ const flagKinds: Record<string, Record<string, "value" | "boolean">> = {
|
||||
setup: { project: "value", platform: "value", device: "value", scope: "value", profile: "value", "bundle-id": "value", scheme: "value", navigation: "value",
|
||||
mode: "value", provider: "value", model: "value", param: "value", "app-state": "value", workflows: "boolean", "no-workflows": "boolean",
|
||||
"non-interactive": "boolean", check: "boolean", force: "boolean", help: "boolean" },
|
||||
doctor: { project: "value", offline: "boolean", "no-github": "boolean", "check-model": "boolean", capture: "boolean", output: "value", platform: "value", yes: "boolean", help: "boolean" },
|
||||
"capture:baseline": { project:"value", sha:"value", output:"value", config:"value", platform:"value" },
|
||||
doctor: { project: "value", offline: "boolean", "no-github": "boolean", "check-model": "boolean", capture: "boolean", output: "value", platform: "value", controller: "value", yes: "boolean", help: "boolean" },
|
||||
"capture:baseline": { project:"value", sha:"value", output:"value", config:"value", platform:"value", controller:"value" },
|
||||
"source:verify": { "base-project":"value", "head-project":"value", "base-sha":"value", "head-sha":"value", output:"value", config:"value", scope:"value", platform:"value" },
|
||||
"config:platforms": { project:"value", config:"value" },
|
||||
"screen:list": { limit: "value", cursor: "value", unexplored: "boolean" },
|
||||
@@ -78,20 +83,25 @@ const flagKinds: Record<string, Record<string, "value" | "boolean">> = {
|
||||
validate: {},
|
||||
export: { output: "value" },
|
||||
"export:web": {catalog:"value",output:"value"},
|
||||
"capture:review": { "base-project":"value", "head-project":"value", "pull-request":"value", output:"value", config:"value", platform:"value" },
|
||||
"capture:review": { "base-project":"value", "head-project":"value", "pull-request":"value", compare:"value", output:"value", config:"value", platform:"value", controller:"value", scope:"value", "expires-in":"value",
|
||||
base:"value", head:"value", project:"value", committed:"boolean", uncommitted:"boolean", "include-untracked":"boolean", upload:"boolean", "no-open":"boolean", "no-cache":"boolean", port:"value" },
|
||||
|
||||
|
||||
|
||||
"explore:binary": { archive:"value", output:"value", platform:"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" },
|
||||
"explore:session": { session:"value", "env-file":"value", "bundle-id":"value", "app-name":"value", "app-version":"value", output:"value", platform:"value", device:"value", "launch-url":"value", hints:"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" },
|
||||
"ci:report": { input:"value", output:"value", platform:"value" },
|
||||
"ci:publish": { input:"value", "artifact-url":"value", platform:"value", inputs:"value" },
|
||||
"ci:failure": { pr:"value", head:"value", base:"value", diagnostics:"value", platform:"value" },
|
||||
"ci:deploy": { input:"value", report:"value", "artifact-url":"value", platform:"value", inputs:"value", reports:"value" },
|
||||
"ci:pr": { pr:"value", output:"value", "app-dir":"value", config:"value" },
|
||||
"ci:find-baseline": { sha:"value", platform:"value" },
|
||||
"ci:compare-refs": { project:"value", base:"value", head:"value", title:"value", output:"value" },
|
||||
"ci:after-capture": { output:"value", checkout:"value" },
|
||||
compare: {
|
||||
baseline: "value",
|
||||
current: "value",
|
||||
@@ -106,6 +116,8 @@ const flagKinds: Record<string, Record<string, "value" | "boolean">> = {
|
||||
|
||||
},
|
||||
view: { port: "value", catalog: "value", "no-open": "boolean" },
|
||||
"report:upload": { owner: "value", project: "value", "expires-in": "value", config: "value" },
|
||||
reports: { all: "boolean", owner: "value", project: "value", "expires-in": "value", config: "value", port: "value", "no-open": "boolean", "no-intro": "boolean" },
|
||||
help: { all: "boolean" },
|
||||
"--help": { all: "boolean" },
|
||||
"-h": { all: "boolean" },
|
||||
@@ -127,7 +139,7 @@ export function validateCommandArguments(): void {
|
||||
for (let index = 0; index < args.length; index += 1) {
|
||||
const token = args[index]!;
|
||||
if (!token.startsWith("--")) {
|
||||
if (index === 0 && POSITIONAL_COMMANDS.has(command)) continue;
|
||||
if ((index === 0 && POSITIONAL_COMMANDS.has(command)) || VARIADIC_COMMANDS.has(command)) continue;
|
||||
argumentError(`Unexpected argument: ${token}`);
|
||||
}
|
||||
const name = token.slice(2);
|
||||
@@ -150,6 +162,18 @@ export function positional(): string | undefined {
|
||||
return POSITIONAL_COMMANDS.has(command) && first !== undefined && !first.startsWith("--") ? first : undefined;
|
||||
}
|
||||
|
||||
/** The bare arguments of a variadic command, in order: every token that is neither a flag nor a flag's value. */
|
||||
export function positionals(): string[] {
|
||||
const allowed = { ...commonFlagKinds, ...flagKinds[command] };
|
||||
const values: string[] = [];
|
||||
for (let index = 0; index < args.length; index += 1) {
|
||||
const token = args[index]!;
|
||||
if (!token.startsWith("--")) values.push(token);
|
||||
else if (allowed[token.slice(2)] === "value") index += 1;
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
export function flag(name: string): string | undefined {
|
||||
const index = args.indexOf(`--${name}`);
|
||||
if (index < 0) return undefined;
|
||||
|
||||
@@ -3,7 +3,8 @@ import { basename, join, resolve } from "node:path";
|
||||
import { DEFAULT_BINARY_PROJECT, runBinaryExploration, runSessionExploration } from "../binary/run.js";
|
||||
import { openViewerInBrowser, startViewerServer, waitForViewerShutdown } from "../map/viewer-server.js";
|
||||
import { writeExplorationReport } from "../binary/report.js";
|
||||
import { assertHostingExport, deployExplorationReport } from "../report/preview-deploy.js";
|
||||
import { assertHostingExport, deployExplorationReport, zipReportDirectory } from "../report/preview-deploy.js";
|
||||
import { keepReports } from "./report-commands.js";
|
||||
import { argumentError, flag, flags, has, nonNegativeInteger, oneOf, output, positional, positiveInteger } from "./args.js";
|
||||
|
||||
const MAX_EXPIRY_DAYS = 90;
|
||||
@@ -37,13 +38,14 @@ export async function exploreBinary(): Promise<void> {
|
||||
const expiresAfterDays = expiresInDays(flag("expires-in") ?? "7d");
|
||||
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 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 (!has("no-upload")) await assertHostingExport();
|
||||
const result = await runBinaryExploration({
|
||||
archive: resolve(process.cwd(), archive), output: outputDirectory, progress: say,
|
||||
...(platform ? { platform } : {}), ...(provider ? { provider } : {}),
|
||||
...(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")! } : {}),
|
||||
...(allowDestructive.length ? { allowDestructive } : {}), ...(flag("model") ? { model: flag("model")! } : {}),
|
||||
@@ -54,10 +56,11 @@ export async function exploreBinary(): Promise<void> {
|
||||
});
|
||||
say(`exploration ${result.exploration.stopReason}: ${result.exploration.screens} screens, ${result.exploration.observations} captures, ${result.exploration.actions} actions`);
|
||||
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 (!has("no-upload")) {
|
||||
say("hosting the report on EAS Hosting");
|
||||
hosted = await deployExplorationReport({ reportPath: report.reportPath, project: flag("project") ?? DEFAULT_BINARY_PROJECT, owner: result.session.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,
|
||||
@@ -91,6 +94,7 @@ export async function exploreSession(): Promise<void> {
|
||||
const expiresAfterDays = expiresInDays(flag("expires-in") ?? "7d");
|
||||
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 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`); };
|
||||
@@ -101,7 +105,7 @@ export async function exploreSession(): Promise<void> {
|
||||
output: outputDirectory, progress: say,
|
||||
...(bundleId ? { bundleId } : {}), ...(session ? { session } : {}), ...(envFile ? { envFile } : {}),
|
||||
...(flag("app-name") ? { appName: flag("app-name")! } : {}), ...(flag("app-version") ? { version: flag("app-version")! } : {}),
|
||||
...(platform ? { platform } : {}), ...(provider ? { provider } : {}),
|
||||
...(platform ? { platform } : {}), ...(provider ? { provider } : {}), ...(controller ? { controller } : {}),
|
||||
...(flag("device") ? { device: flag("device")! } : {}),
|
||||
...(flag("launch-url") ? { launchUrl: flag("launch-url")! } : {}), ...(flag("hints") ? { hints: flag("hints")! } : {}),
|
||||
...(allowDestructive.length ? { allowDestructive } : {}), ...(flag("model") ? { model: flag("model")! } : {}),
|
||||
@@ -111,10 +115,11 @@ export async function exploreSession(): Promise<void> {
|
||||
});
|
||||
say(`exploration ${result.exploration.stopReason}: ${result.exploration.screens} screens, ${result.exploration.observations} captures, ${result.exploration.actions} actions`);
|
||||
const report = await writeExplorationReport(result, join(outputDirectory, "report"));
|
||||
await keepReports(async () => [{ platform: result.app.platform, zip: await zipReportDirectory(report.reportPath) }]);
|
||||
let hosted: Awaited<ReturnType<typeof deployExplorationReport>> | undefined;
|
||||
if (has("upload")) {
|
||||
say("hosting the report on EAS Hosting");
|
||||
hosted = await deployExplorationReport({ reportPath: report.reportPath, project: flag("project") ?? DEFAULT_BINARY_PROJECT, ...(flag("owner") ? { owner: flag("owner")! } : {}), expiresAfterDays, ...stableLinkOptions() });
|
||||
hosted = await deployExplorationReport({ reportPath: report.reportPath, platform: result.app.platform, project: flag("project") ?? DEFAULT_BINARY_PROJECT, ...(flag("owner") ? { owner: flag("owner")! } : {}), expiresAfterDays, ...stableLinkOptions() });
|
||||
say(`report: ${hosted.previewUrl}${hosted.expiresAt ? ` (expires ${hosted.expiresAt})` : ""}`);
|
||||
}
|
||||
const summary = { ok: true, app: result.app, device: { model: result.runtime.deviceModel, osVersion: result.runtime.osVersion },
|
||||
|
||||
@@ -1,27 +1,32 @@
|
||||
import { lstat, mkdtemp } from "node:fs/promises";
|
||||
import { cp, lstat, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
import { commitSubject, keepReports } from "./report-commands.js";
|
||||
import { createInterface } from "node:readline/promises";
|
||||
import { runPublicCi, runBaselineCi } from "../ci/pipeline.js";
|
||||
import { runPublicCi, runBaselineCi, runCompareCi } from "../ci/pipeline.js";
|
||||
import { exportCiReport, publishCiReportComment } from "../report/artifact.js";
|
||||
import { collectPlatformReports, deployPreview } from "../report/preview-deploy.js";
|
||||
import { collectPlatformReports, deployLocalReports, deployPreview, previewProjectSlug } from "../report/preview-deploy.js";
|
||||
import { startLocalReportServer } from "../report/local-report-server.js";
|
||||
import { openViewerInBrowser } from "../map/viewer-server.js";
|
||||
import { runLocalReview } from "../ci/local-review.js";
|
||||
import { publishFailureComment } from "../report/failure-comment.js";
|
||||
import { runExploreSetup } from "../config/setup.js";
|
||||
import { installCiFiles } from "../ci/workflow-install.js";
|
||||
import { readRouteEntry } from "../ci/route-entry.js";
|
||||
import { buildVerifiedPlan } from "../ci/verified-plan.js";
|
||||
import { formatCaptureCheck, formatDoctorReport, referencedSecretNames, runCaptureCheck, runDoctor } from "../ci/doctor.js";
|
||||
import { readExploreConfig, readExploreInstructions, resolvePlatformConfig, configPlatforms as listPlatforms, EXPLORE_PLATFORMS, DEFAULT_EXPLORE_CONFIG_PATH, type ExplorePlatform } from "../config/explore-config.js";
|
||||
import { argumentError, output, required, has, flag, flags, oneOf } from "./args.js";
|
||||
import { readExploreConfig, readExploreInstructions, resolvePlatformConfig, withRunOverrides, previewDays, configPlatforms as listPlatforms, EXPLORE_PLATFORMS, DEFAULT_EXPLORE_CONFIG_PATH, PREVIEW_DEFAULT_DAYS, type ExplorePlatform } from "../config/explore-config.js";
|
||||
import { argumentError, output, required, has, flag, flags, nonNegativeInteger, oneOf } from "./args.js";
|
||||
import { help } from "./help.js";
|
||||
import { CiError } from "../shared/ci-errors.js";
|
||||
import { cleanupAfterCapture, findOptionalBaseline, resolveCompareRefs, resolvePullRequest, writeCaptureOutputs, writeStepOutputs } from "../ci/workflow-steps.js";
|
||||
import { stderrProgress } from "../shared/progress.js";
|
||||
|
||||
export async function doctor(): Promise<void> {
|
||||
if (has("help")) return help();
|
||||
const project = flag("project") ?? process.cwd();
|
||||
const report = await runDoctor({ project, online: !has("offline"), github: !has("no-github") && !has("offline"),
|
||||
checkModel: has("check-model") });
|
||||
checkModel: has("check-model"), controller: flag("controller") });
|
||||
if (!has("capture")) {
|
||||
if (has("json")) output({ ...report });
|
||||
else console.log(formatDoctorReport(report));
|
||||
@@ -41,14 +46,14 @@ Fix the problems in steps 1–5 before a capture check.`);
|
||||
if (!has("yes")) {
|
||||
if (!process.stdin.isTTY || has("json")) argumentError("A capture check starts an EAS build and simulator session; pass --yes to confirm.", "yes");
|
||||
const terminal = createInterface({ input: process.stdin, output: process.stderr });
|
||||
const answer = await terminal.question(`This builds the app on EAS and runs an EAS Simulator session (EAS usage applies${report.mode === "agent" ? "; agent mode also uses your model API key" : ""}). Continue? (yes/no) `);
|
||||
const answer = await terminal.question(`This builds the app on EAS and runs an EAS Simulator session (EAS usage applies${report.mode === "agent" ? "; agent mode also uses your model API key or local claude/codex login" : ""}). Continue? (yes/no) `);
|
||||
terminal.close();
|
||||
if (!/^(y|yes)$/i.test(answer.trim())) return;
|
||||
}
|
||||
let result: Awaited<ReturnType<typeof runCaptureCheck>>;
|
||||
try {
|
||||
const platform = platformFlag();
|
||||
result = await runCaptureCheck({ project, ...(platform ? { platform } : {}), output: resolve(flag("output") ?? await mkdtemp(join(tmpdir(), "expo-explore-capture-"))), progress: stderrProgress() });
|
||||
result = await runCaptureCheck({ project, ...(platform ? { platform } : {}), controller: flag("controller"), output: resolve(flag("output") ?? await mkdtemp(join(tmpdir(), "expo-explore-capture-"))), progress: stderrProgress() });
|
||||
} catch (error) {
|
||||
// A refusal before any EAS work: show it with its next action next to the static report.
|
||||
if (!(error instanceof CiError)) throw error;
|
||||
@@ -73,7 +78,9 @@ export async function ciDeploy(): Promise<void> {
|
||||
const result = has("inputs") || has("reports")
|
||||
? await deployPreview({ reports: await collectPlatformReports({ inputsPath: required("inputs"), reportsPath: required("reports") }), onSecret })
|
||||
: await deployPreview({ inputPath: required("input"), reportPath: required("report"), artifactUrl: required("artifact-url"), onSecret });
|
||||
output({ ok: true, ...result });
|
||||
// A comparison's token is not masked (see deployPreview), so its link stays out of the log.
|
||||
const { previewUrl, ...unlinked } = result;
|
||||
output({ ok: true, ...(result.linkedFromRunSummary ? unlinked : { previewUrl, ...unlinked }) });
|
||||
}
|
||||
|
||||
export async function ciPublish(): Promise<void> {
|
||||
@@ -93,6 +100,41 @@ export async function ciFailure(): Promise<void> {
|
||||
...(has("diagnostics") ? { diagnosticsPath: required("diagnostics") } : {}), ...(platform ? { platform } : {}) }) });
|
||||
}
|
||||
|
||||
/** `ci:pr --pr N [--output FILE]`: the live, authorized pull request; its commits go to the step outputs. */
|
||||
export async function ciPullRequest(): Promise<void> {
|
||||
const { presentation, author } = await resolvePullRequest({ number: Number(required("pr")),
|
||||
...(has("app-dir") ? { appDirectory: required("app-dir") } : {}), ...(has("config") ? { configPath: required("config") } : {}) });
|
||||
if (has("output")) await writeFile(required("output"), JSON.stringify(presentation));
|
||||
await writeStepOutputs(process.env, { pr_number: String(presentation.number), base: presentation.base.sha, head: presentation.head.sha });
|
||||
output({ ok: true, pullRequest: presentation, author });
|
||||
}
|
||||
|
||||
/** `ci:find-baseline --sha SHA [--platform P]`: a reusable baseline artifact of the base commit, if one exists. */
|
||||
export async function ciFindBaseline(): Promise<void> {
|
||||
const platform = platformFlag();
|
||||
const { baseline, warning } = await findOptionalBaseline({ sha: required("sha"), ...(platform ? { platform } : {}) });
|
||||
if (baseline) await writeStepOutputs(process.env, { id: String(baseline.id), run: String(baseline.run) });
|
||||
if (warning && process.env.GITHUB_ACTIONS) console.log(`::warning title=${warning.code}::${warning.message.replace(/[\r\n]+/g, " ")}`);
|
||||
output({ ok: true, baseline: baseline ?? null, ...(warning ? { warning } : {}) });
|
||||
}
|
||||
|
||||
/** `ci:compare-refs --project DIR --base REF --head REF [--output FILE]`: the two commits a comparison captures. */
|
||||
export async function ciCompareRefs(): Promise<void> {
|
||||
const comparison = resolveCompareRefs({ project: required("project"), base: required("base"), head: required("head"),
|
||||
...(has("title") ? { title: required("title") } : {}) });
|
||||
if (has("output")) await writeFile(required("output"), JSON.stringify(comparison));
|
||||
await writeStepOutputs(process.env, { base: comparison.base.sha, head: comparison.head.sha, compare: JSON.stringify(comparison) });
|
||||
output({ ok: true, comparison });
|
||||
}
|
||||
|
||||
/** `ci:after-capture --output DIR --checkout DIR...`: stop recorded sessions and check the checkouts are untouched; fails after reporting every problem. */
|
||||
export async function ciAfterCapture(): Promise<void> {
|
||||
const result = await cleanupAfterCapture({ output: required("output"), checkouts: flags("checkout") });
|
||||
for (const failure of result.failures) console.error(`::error title=${failure.code}::${failure.message} ${failure.nextAction}`);
|
||||
output({ ok: result.failures.length === 0, ...result });
|
||||
if (result.failures.length) process.exitCode = 1;
|
||||
}
|
||||
|
||||
/** The `--platform` flag, when given; capture then reads that platform's fields from config.yaml. */
|
||||
export function platformFlag(): ExplorePlatform | undefined {
|
||||
return has("platform") ? oneOf("platform", EXPLORE_PLATFORMS) : undefined;
|
||||
@@ -155,19 +197,80 @@ export async function sourceVerify(): Promise<void> {
|
||||
}
|
||||
|
||||
export async function captureReview(): Promise<void> {
|
||||
// Refs without the CI flags: a review on this machine, with your own logins (see runLocalReview).
|
||||
if (!has("base-project") && !has("head-project") && !has("pull-request") && !has("compare")) return localReview();
|
||||
const headProject = required("head-project");
|
||||
const configPath = flag("config") ?? DEFAULT_EXPLORE_CONFIG_PATH;
|
||||
const platform = platformFlag();
|
||||
const rawConfig = await readExploreConfig(headProject, configPath);
|
||||
const config = resolvePlatformConfig(rawConfig, platform);
|
||||
const result = await runPublicCi({ ...(platform ? { platform } : {}), platforms: listPlatforms(rawConfig), baseProject: required("base-project"), headProject,
|
||||
pullRequestPath: required("pull-request"), output: required("output"), config, configPath, progress: stderrProgress() });
|
||||
const config = withRunOverrides(resolvePlatformConfig(rawConfig, platform), { scope: flag("scope"), expiresIn: flag("expires-in"), controller: flag("controller") });
|
||||
if (has("pull-request") === has("compare")) argumentError("Pass --pull-request FILE for a pull request, or --compare FILE for any two commits.", has("compare") ? "compare" : "pull-request");
|
||||
const common = { ...(platform ? { platform } : {}), platforms: listPlatforms(rawConfig), baseProject: required("base-project"), headProject,
|
||||
output: required("output"), config, configPath, progress: stderrProgress() };
|
||||
const result = has("compare") ? await runCompareCi({ ...common, comparePath: required("compare") })
|
||||
: await runPublicCi({ ...common, pullRequestPath: required("pull-request") });
|
||||
// The deploy job runs only when the reviewed config asks for a hosted report.
|
||||
await writeCaptureOutputs(result.inputPath);
|
||||
output({ ok: true, inputPath: result.inputPath });
|
||||
}
|
||||
|
||||
export async function captureBaseline(): Promise<void> {
|
||||
const project = required("project");
|
||||
const platform = platformFlag();
|
||||
const config = resolvePlatformConfig(await readExploreConfig(project, flag("config") ?? DEFAULT_EXPLORE_CONFIG_PATH), platform);
|
||||
const config = withRunOverrides(resolvePlatformConfig(await readExploreConfig(project, flag("config") ?? DEFAULT_EXPLORE_CONFIG_PATH), platform), { controller: flag("controller") });
|
||||
output({ ok: true, ...await runBaselineCi({ ...(platform ? { platform } : {}), project, sha: required("sha"), output: required("output"), config, progress: stderrProgress() }) });
|
||||
}
|
||||
|
||||
/** `capture` (or `capture:review`) `[--base REF] [--head REF | --committed]`: a local review, opened in the Viewer or hosted with --upload. */
|
||||
async function localReview(): Promise<void> {
|
||||
const platform = platformFlag();
|
||||
const result = await runLocalReview({ project: flag("project") ?? process.cwd(), base: flag("base"), head: flag("head"),
|
||||
// --include-untracked is accepted from before untracked files were included by default.
|
||||
committed: has("committed"), uncommitted: has("uncommitted"), ...(platform ? { platform } : {}),
|
||||
scope: flag("scope"), expiresIn: flag("expires-in"), controller: flag("controller"), cache: !has("no-cache"), configPath: flag("config"), progress: stderrProgress() });
|
||||
if (has("output")) {
|
||||
for (const report of result.reports) {
|
||||
const target = resolve(required("output"), report.platform);
|
||||
await cp(report.directory, join(target, "report"), { recursive: true });
|
||||
await cp(report.zip, join(target, "report.zip"));
|
||||
report.directory = join(target, "report"); report.zip = join(target, "report.zip");
|
||||
}
|
||||
// The reports now live under --output; the temporary copies are not needed.
|
||||
await rm(result.work, { recursive: true, force: true });
|
||||
}
|
||||
const summary = { ok: true, runId: result.runId, base: result.base, head: result.head,
|
||||
reports: result.reports.map(({ platform, directory, zip, changes, device }) => ({ platform, directory, zip, ...(changes === undefined ? {} : { changes }), ...(device ? { device } : {}) })) };
|
||||
const zips = await Promise.all(result.reports.map(async report => ({ platform: report.platform, zip: new Uint8Array(await readFile(report.zip)),
|
||||
...(report.changes === undefined ? {} : { changes: report.changes }), ...(report.device ? { device: report.device } : {}) })));
|
||||
// Kept among the saved runs, with the commits' subjects (an uncommitted head is named by the commit under it).
|
||||
const project = resolve(flag("project") ?? process.cwd());
|
||||
const headSubject = commitSubject(project, result.head.uncommitted ? `${result.head.sha}^` : result.head.sha), baseSubject = commitSubject(project, result.base.sha);
|
||||
const saved = await keepReports(zips.map(({ platform, zip }) => ({ platform, zip })), { subjects: { ...(headSubject ? { head: headSubject } : {}), ...(baseSubject ? { base: baseSubject } : {}) },
|
||||
...(result.head.uncommitted?.length ? { uncommittedFiles: result.head.uncommitted.length } : {}) });
|
||||
if (has("upload")) {
|
||||
const preview = result.config.report?.preview;
|
||||
const hosted = await deployLocalReports({ reports: zips, project: previewProjectSlug(result.repository, preview?.project), ...(preview?.owner ? { owner: preview.owner } : {}),
|
||||
// null is expiresAfter: never, which must not fall back to the default.
|
||||
expiresAfterDays: has("expires-in") ? previewDays(required("expires-in"), "--expires-in") : preview ? preview.expiresAfterDays : PREVIEW_DEFAULT_DAYS });
|
||||
// Hosted, the temporary copies are not needed (a failed upload keeps them for report:upload); --output keeps its own.
|
||||
const copied = has("output");
|
||||
if (!copied) await rm(result.work, { recursive: true, force: true });
|
||||
if (has("json")) output({ ...summary, ...(copied ? {} : { reports: summary.reports.map(({ directory: _directory, zip: _zip, ...report }) => report) }),
|
||||
url: hosted.previewUrl, expiresAt: hosted.expiresAt });
|
||||
else console.log(`Report: ${hosted.previewUrl}${hosted.expiresAt ? ` (until ${hosted.expiresAt.slice(0, 10)})` : ""}`);
|
||||
return;
|
||||
}
|
||||
if (has("json") || has("no-open")) {
|
||||
if (has("json")) output(summary);
|
||||
else for (const report of result.reports) console.log(`${report.platform}: ${report.zip}`);
|
||||
return;
|
||||
}
|
||||
const server = await startLocalReportServer({ reports: zips, ...(has("port") ? { port: nonNegativeInteger("port") } : {}) });
|
||||
console.log(`Viewer: ${server.url} (Ctrl+C to stop)`);
|
||||
if (saved) console.log(`Saved as ${saved.id}: expo-explore reports reopens it, and reports upload ${saved.id} hosts it.`);
|
||||
openViewerInBrowser(server.url);
|
||||
await new Promise<void>(done => { process.once("SIGINT", () => done()); process.once("SIGTERM", () => done()); });
|
||||
await server.close();
|
||||
// The Viewer served the reports from memory, and the saved run keeps them; the temporary copy is no longer needed.
|
||||
if (saved) await rm(result.work, { recursive: true, force: true });
|
||||
}
|
||||
@@ -15,16 +15,34 @@ const GET_STARTED = `Get started (run these in the Expo app's directory):
|
||||
doctor [--project DIRECTORY] [--offline] [--no-github] [--check-model] [--json]
|
||||
(checks every setup step and prints the next action for each problem; exits 1 until ready)
|
||||
(--offline skips EAS and GitHub; --check-model sends one small request with the local provider key)
|
||||
doctor --capture [--project DIRECTORY] [--output DIRECTORY] [--platform ios|android] [--yes]
|
||||
doctor --capture [--project DIRECTORY] [--output DIRECTORY] [--platform ios|android] [--controller agent-device|argent] [--yes]
|
||||
(captures the committed HEAD like the baseline workflow, with your eas login, and reports each route)
|
||||
capture [--base REF] [--head REF | --committed] [--platform ios|android] [--scope all|changes]
|
||||
[--controller agent-device|argent] [--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 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;
|
||||
it runs both commits' code as you, so review only commits you would run; capture:review is the same command;
|
||||
--controller argent drives the simulator with Argent instead of agent-device, the default (or set
|
||||
capture.controller in config.yaml); Argent cannot switch appearance yet, so it captures one appearance)
|
||||
view [--catalog FILE] [--port N] [--no-open]
|
||||
(opens a report in the Viewer)`;
|
||||
(opens a report in the Viewer)
|
||||
reports [list | open ID | add REPORT... | upload ID | rm ID | prune] [--all] [--json]
|
||||
(the runs kept on this machine: local reviews, explorations and uploaded reports, for 30 days or up to 2 GB;
|
||||
in a terminal, an arrow-key picker: Enter opens a run in the local Viewer, u hosts it, d deletes it;
|
||||
ID is a run's id from reports list, or latest; EXPLORE_INTRO=off skips the title animation)
|
||||
report:upload <report.zip | report directory>... [--owner ACCOUNT] [--project SLUG] [--expires-in 7d|30d|never] [--config FILE] [--json]
|
||||
(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 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)
|
||||
Flags, all optional: --device NAME --bundle-id ID --launch-url URL --hints "what to focus on"
|
||||
--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
|
||||
@@ -34,20 +52,22 @@ const BINARY = `Prebuilt apps (no source needed; runs on EAS Simulator with your
|
||||
(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" wrote .env.eas-simulator, or pass
|
||||
--env-file FILE, or export EAS_SIMULATOR_SESSION_ID, AGENT_DEVICE_DAEMON_BASE_URL and
|
||||
AGENT_DEVICE_DAEMON_AUTH_TOKEN; writes the map and report, then opens them in the local Viewer;
|
||||
"eas simulator:start --type agent-device --out-config-type dotenv" (or --type argent) wrote .env.eas-simulator,
|
||||
or pass --env-file FILE, or export EAS_SIMULATOR_SESSION_ID with AGENT_DEVICE_DAEMON_BASE_URL and
|
||||
AGENT_DEVICE_DAEMON_AUTH_TOKEN, or with ARGENT_TOOLS_URL and ARGENT_AUTH_TOKEN; writes the map and report, then opens them in the local Viewer;
|
||||
--upload hosts the report instead, --no-open skips the Viewer; the session is left running;
|
||||
the app is the one in the foreground, else the only installed one; --bundle-id picks it otherwise)
|
||||
the app is the one in the foreground, else the only installed one; --bundle-id picks it otherwise;
|
||||
the controller follows the session's type, and --controller must match it)
|
||||
Extra flags: --app-name NAME --app-version X.Y --port N, plus the explore:binary budget/model flags
|
||||
Afterwards: view --dir DIRECTORY, screen:list --dir DIRECTORY, gap:list --dir DIRECTORY`;
|
||||
|
||||
const CI = `CI (the installed workflows run these; they manage remote EAS Simulator sessions):
|
||||
config:platforms [--project DIRECTORY] [--config FILE]
|
||||
(lists the platforms config.yaml captures; the review workflow's matrix)
|
||||
capture:review --base-project DIRECTORY --head-project DIRECTORY --pull-request FILE
|
||||
--output TEMP_DIRECTORY [--config .expo-explore/config.yaml] [--platform ios|android]
|
||||
capture:baseline --project DIRECTORY --sha COMMIT --output TEMP_DIRECTORY [--config FILE] [--platform ios|android]
|
||||
capture:review --base-project DIRECTORY --head-project DIRECTORY (--pull-request FILE | --compare FILE)
|
||||
--output TEMP_DIRECTORY [--config .expo-explore/config.yaml] [--platform ios|android] [--controller agent-device|argent]
|
||||
(--compare reviews any two commits without a PR: {"origin":"compare","repositoryId","repository","base":{ref,sha},"head":{ref,sha}})
|
||||
capture:baseline --project DIRECTORY --sha COMMIT --output TEMP_DIRECTORY [--config FILE] [--platform ios|android] [--controller agent-device|argent]
|
||||
source:verify --base-project DIRECTORY --head-project DIRECTORY
|
||||
--base-sha COMMIT --head-sha COMMIT --output DIRECTORY [--config FILE] [--scope all|changes] [--platform ios|android]
|
||||
compare --baseline DIRECTORY --current DIRECTORY --output FILE
|
||||
@@ -58,7 +78,14 @@ const CI = `CI (the installed workflows run these; they manage remote EAS Simula
|
||||
ci:publish --input REPORT_INPUT --artifact-url GITHUB_ARTIFACT_URL [--platform ios|android]
|
||||
ci:publish --inputs DIRECTORY (one <platform>/ subdirectory per captured platform)
|
||||
ci:deploy --input REPORT_INPUT --report REPORT_DIR --artifact-url GITHUB_ARTIFACT_URL [--platform ios|android]
|
||||
ci:deploy --inputs DIRECTORY --reports DIRECTORY`;
|
||||
ci:deploy --inputs DIRECTORY --reports DIRECTORY
|
||||
ci:pr --pr N [--output FILE] [--app-dir DIRECTORY]
|
||||
(resolves the live PR and refuses it unless it is open, from this repository, and by a trusted author)
|
||||
ci:compare-refs --project DIRECTORY --base REF --head REF [--output FILE]
|
||||
ci:find-baseline --sha COMMIT [--platform ios|android]
|
||||
ci:after-capture --output TEMP_DIRECTORY --checkout DIRECTORY...
|
||||
(stops the capture's EAS Simulator sessions and checks capture left each checkout unchanged)
|
||||
(the ci:* commands write their results to $GITHUB_OUTPUT for the next steps)`;
|
||||
|
||||
const MAP_QUERIES = `Map queries (for coding agents reading a local exploration map; JSON output, never provision devices):
|
||||
summary
|
||||
|
||||
@@ -0,0 +1,239 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { readFile, stat } from "node:fs/promises";
|
||||
import { basename, dirname, join, relative, resolve, sep } from "node:path";
|
||||
import { DEFAULT_BINARY_PROJECT } from "../binary/run.js";
|
||||
import { pruneCaptureCache, repositoryName } from "../ci/local-review.js";
|
||||
import { readExploreConfig, previewDays, DEFAULT_EXPLORE_CONFIG_PATH, PREVIEW_DEFAULT_DAYS, type ExploreConfig, type ExplorePlatform } from "../config/explore-config.js";
|
||||
import { assertHostingExport, deployLocalReports, previewProjectSlug, readReportZip, zipReportDirectory, MAX_REPORT_BYTES, type ReportZipSummary } from "../report/preview-deploy.js";
|
||||
import { startLocalReportServer } from "../report/local-report-server.js";
|
||||
import { findSavedRun, listSavedRuns, pruneSavedRuns, readSavedReports, removeSavedRun, saveRun, savedRunsDirectory, SAVED_RUN_LIMITS, type SavedReport, type SavedRun } from "../report/saved-runs.js";
|
||||
import { openViewerInBrowser } from "../map/viewer-server.js";
|
||||
import { formatBytes, friendlyTime, kindLabel, runPicker, runTitle } from "./reports-picker.js";
|
||||
import { pickIntro } from "./title-intros.js";
|
||||
import { CiError, toCiError } from "../shared/ci-errors.js";
|
||||
import { argumentError, flag, has, nonNegativeInteger, output, positionals, required } from "./args.js";
|
||||
|
||||
/** explore:binary's default: an exploration link is for a quick look. */
|
||||
const EXPLORATION_DEFAULT_DAYS = 7;
|
||||
|
||||
/** A report directory (review.json or exploration.json and assets/), its parent holding report.zip, or a report ZIP. */
|
||||
async function readReport(path: string): Promise<{ path: string; zip: Uint8Array; summary: ReportZipSummary }> {
|
||||
const target = resolve(process.cwd(), path);
|
||||
const info = await stat(target).catch(() => undefined);
|
||||
if (!info) argumentError(`There is no report at ${path}`, undefined, "Pass a report.zip or report directory that exists.");
|
||||
try {
|
||||
// A ZIP is sized before it is read: nothing larger than a hosted report can be is loaded into memory.
|
||||
const readZip = async (file: string) => {
|
||||
if ((await stat(file)).size > MAX_REPORT_BYTES) throw new Error(`${path} is larger than the ${MAX_REPORT_BYTES / 1024 / 1024} MiB a hosted report can be`);
|
||||
return new Uint8Array(await readFile(file));
|
||||
};
|
||||
let zip: Uint8Array;
|
||||
if (!info.isDirectory()) zip = await readZip(target);
|
||||
else if (await stat(join(target, "report.zip")).then(file => file.isFile()).catch(() => false)) zip = await readZip(join(target, "report.zip"));
|
||||
else zip = await zipReportDirectory(target);
|
||||
return { path, zip, summary: await readReportZip(zip) };
|
||||
} catch (error) {
|
||||
throw toCiError(error, { code: "REPORT_ZIP_FAILED", stage: "export",
|
||||
nextAction: `${path} is not an Explore report. Pass a report.zip or report directory written by capture:review, explore:binary or ci:report, or a downloaded explore-review artifact.` });
|
||||
}
|
||||
}
|
||||
|
||||
type PreviewSettings = NonNullable<ExploreConfig["report"]>["preview"];
|
||||
|
||||
/** `<app>/.expo-explore/config.yaml` as the app directory and the path config readers take. */
|
||||
function configLocation(file: string): { app: string; path: string } {
|
||||
return basename(dirname(file)) === ".expo-explore" ? { app: dirname(dirname(file)), path: relative(dirname(dirname(file)), file) } : { app: dirname(file), path: basename(file) };
|
||||
}
|
||||
|
||||
/**
|
||||
* The report.preview a review's own uploads use: from --config, or else from this repository's committed config when the
|
||||
* reports are this repository's (the one in the current directory, or the only one, as in a monorepo). Says which.
|
||||
*/
|
||||
async function repositoryPreview(repository: string): Promise<{ preview: PreviewSettings; source: string } | undefined> {
|
||||
const explicit = flag("config");
|
||||
if (explicit) {
|
||||
const { app, path } = configLocation(resolve(process.cwd(), explicit));
|
||||
return { preview: (await readExploreConfig(app, path)).report?.preview, source: explicit };
|
||||
}
|
||||
const top = spawnSync("git", ["rev-parse", "--show-toplevel"], { cwd: process.cwd(), encoding: "utf8" });
|
||||
if (top.status !== 0) return undefined;
|
||||
const root = top.stdout.trim();
|
||||
const listed = spawnSync("git", ["ls-files", "--full-name", "--", ":(glob)**/.expo-explore/config.yaml"], { cwd: root, encoding: "utf8" });
|
||||
const committed = listed.status === 0 ? listed.stdout.split("\n").filter(Boolean) : [];
|
||||
const here = relative(root, join(process.cwd(), DEFAULT_EXPLORE_CONFIG_PATH)).split(sep).join("/");
|
||||
const file = committed.includes(here) ? here : committed.length === 1 ? committed[0]! : undefined;
|
||||
if (!file) return undefined;
|
||||
const { app, path } = configLocation(join(root, file));
|
||||
const config = await readExploreConfig(app, path);
|
||||
return repositoryName(root, config) === repository ? { preview: config.report?.preview, source: file } : undefined;
|
||||
}
|
||||
|
||||
type ReadReport = Awaited<ReturnType<typeof readReport>>;
|
||||
|
||||
/** Several reports share one link only as one review's platforms; an exploration goes up on its own. */
|
||||
function assertOneReview(reports: ReadReport[]): void {
|
||||
const [first, ...others] = reports as [ReadReport, ...ReadReport[]];
|
||||
const platforms = new Set<ExplorePlatform>([first.summary.platform]);
|
||||
for (const report of others) {
|
||||
if (platforms.has(report.summary.platform)) throw new CiError({ code: "PREVIEW_REPORTS_INVALID", stage: "preflight",
|
||||
message: `More than one ${report.summary.platform} report: one link holds one report per platform.`, nextAction: "Upload each platform's report once." });
|
||||
platforms.add(report.summary.platform);
|
||||
const a = first.summary, b = report.summary;
|
||||
if (a.kind !== "review" || b.kind !== "review" || a.repository !== b.repository || a.runId !== b.runId || a.base !== b.base || a.head !== b.head) {
|
||||
throw new CiError({ code: "PREVIEW_REPORTS_MISMATCH", stage: "preflight", message: `${first.path} and ${report.path} are not the same review's platforms.`,
|
||||
nextAction: "Upload the reports of one review together (one per platform), and anything else on its own." });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Hosts checked reports in the project `--upload` would have used (flags win), and prints the link. */
|
||||
async function hostReports(reports: ReadReport[]): Promise<void> {
|
||||
await assertHostingExport();
|
||||
const first = reports[0]!;
|
||||
const review = first.summary.kind === "review" ? first.summary : undefined;
|
||||
const found = review ? await repositoryPreview(review.repository) : undefined;
|
||||
const preview = found?.preview;
|
||||
if (review) process.stderr.write(found ? `report.preview from ${found.source}\n`
|
||||
: `no config of ${review.repository} here: hosting with the defaults (pass --config, or --owner, --project and --expires-in)\n`);
|
||||
const project = flag("project") ?? (review ? previewProjectSlug(review.repository, preview?.project) : DEFAULT_BINARY_PROJECT);
|
||||
const owner = flag("owner") ?? preview?.owner;
|
||||
const expiresAfterDays = has("expires-in") ? previewDays(required("expires-in"), "--expires-in")
|
||||
: preview ? preview.expiresAfterDays : review ? PREVIEW_DEFAULT_DAYS : EXPLORATION_DEFAULT_DAYS;
|
||||
const hosted = await deployLocalReports({ project, ...(owner ? { owner } : {}), expiresAfterDays,
|
||||
reports: reports.map(report => ({ platform: report.summary.platform, zip: report.zip,
|
||||
...(report.summary.changes === undefined ? {} : { changes: report.summary.changes }), ...(report.summary.device ? { device: report.summary.device } : {}) })),
|
||||
ownerHint: "Pass --owner with the Expo account that should host the report.",
|
||||
projectHint: "Give this EAS login permission to create projects under the owner, or pass --project with an existing project slug." });
|
||||
if (has("json")) {
|
||||
output({ ok: true, url: hosted.previewUrl, expiresAt: hosted.expiresAt, project: hosted.project, owner: hosted.owner,
|
||||
reports: reports.map(report => ({ path: report.path, platform: report.summary.platform, kind: report.summary.kind })) });
|
||||
return;
|
||||
}
|
||||
console.log(`Report: ${hosted.previewUrl}${hosted.expiresAt ? ` (until ${hosted.expiresAt.slice(0, 10)})` : ""}`);
|
||||
console.log(`Hosted on @${hosted.owner}/${hosted.project}. Anyone with the link can open it.`);
|
||||
}
|
||||
|
||||
/** Keeps reports among the saved runs; a failure to keep them never fails the command that made them. */
|
||||
export async function keepReports(reports: SavedReport[] | (() => Promise<SavedReport[]>), extra: Parameters<typeof saveRun>[1] = {}): Promise<SavedRun | undefined> {
|
||||
try { return await saveRun(typeof reports === "function" ? await reports() : reports, extra); }
|
||||
catch (error) { process.stderr.write(`Could not keep this run in expo-explore reports: ${error instanceof Error ? error.message : String(error)}\n`); return undefined; }
|
||||
}
|
||||
|
||||
/** The subject line of a commit, when this checkout has it. */
|
||||
export function commitSubject(cwd: string, sha: string): string | undefined {
|
||||
// --end-of-options: a commit named by a report is never read as one of git's options.
|
||||
const result = spawnSync("git", ["log", "-1", "--format=%s", "--end-of-options", sha], { cwd, encoding: "utf8" });
|
||||
return result.status === 0 && result.stdout.trim() ? result.stdout.trim() : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* `report:upload <report.zip | report directory>...`: hosts reports already on this machine behind one token-gated EAS
|
||||
* Hosting link, as `capture:review --upload` and `explore:binary` do for the report they just wrote. Several reports
|
||||
* must be one review's platforms; a review goes to the repository's preview project, an exploration to expo-explore.
|
||||
* The reports are also kept among the saved runs (`expo-explore reports`).
|
||||
*/
|
||||
export async function reportUpload(): Promise<void> {
|
||||
const paths = positionals();
|
||||
if (!paths.length) argumentError("Pass the report to host: expo-explore report:upload ios/report.zip", undefined,
|
||||
"Run expo-explore report:upload with a report.zip or report directory, one per platform of the same review.");
|
||||
const reports: ReadReport[] = [];
|
||||
for (const path of paths) reports.push(await readReport(path));
|
||||
assertOneReview(reports);
|
||||
const review = reports[0]!.summary.kind === "review" ? reports[0]!.summary : undefined;
|
||||
const head = review && commitSubject(process.cwd(), review.head), base = review && commitSubject(process.cwd(), review.base);
|
||||
await keepReports(reports.map(report => ({ platform: report.summary.platform, zip: report.zip })), { subjects: { ...(head ? { head } : {}), ...(base ? { base } : {}) } });
|
||||
await hostReports(reports);
|
||||
}
|
||||
|
||||
/** Serves reports in the local Viewer, opens it, and waits for Ctrl+C. */
|
||||
export async function openInViewer(reports: SavedReport[]): Promise<void> {
|
||||
const server = await startLocalReportServer({ reports, ...(has("port") ? { port: nonNegativeInteger("port") } : {}) });
|
||||
console.log(`Viewer: ${server.url} (Ctrl+C to stop)`);
|
||||
if (!has("no-open")) openViewerInBrowser(server.url);
|
||||
await new Promise<void>(done => { process.once("SIGINT", () => done()); process.once("SIGTERM", () => done()); });
|
||||
await server.close();
|
||||
}
|
||||
|
||||
/** This checkout's GitHub repository (owner/name), which saved reviews name; undefined outside one. */
|
||||
function currentRepository(): string | undefined {
|
||||
const remote = spawnSync("git", ["remote", "get-url", "origin"], { cwd: process.cwd(), encoding: "utf8" });
|
||||
const match = remote.status === 0 ? /github\.com[:/]([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?$/.exec(remote.stdout.trim()) : null;
|
||||
return match ? `${match[1]}/${match[2]}` : undefined;
|
||||
}
|
||||
|
||||
async function savedRun(id: string | undefined): Promise<SavedRun> {
|
||||
if (!id) argumentError("Name the run: an id from expo-explore reports list, or latest", undefined, "Run expo-explore reports list to see the saved runs.");
|
||||
const run = await findSavedRun(id);
|
||||
if (!run) throw new CiError({ code: "REPORT_RUN_NOT_FOUND", stage: "preflight", message: id === "latest" ? "There are no saved runs yet." : `There is no saved run ${id}.`,
|
||||
nextAction: "Run expo-explore reports list to see the saved runs." });
|
||||
return run;
|
||||
}
|
||||
|
||||
async function uploadSavedRun(run: SavedRun): Promise<void> {
|
||||
const reports: ReadReport[] = [];
|
||||
for (const report of await readSavedReports(run)) reports.push({ path: `${run.id}/${report.platform}.zip`, zip: report.zip, summary: await readReportZip(report.zip) });
|
||||
await hostReports(reports);
|
||||
}
|
||||
|
||||
function listLines(runs: SavedRun[], now = Date.now()): string[] {
|
||||
if (!runs.length) return ["No saved runs yet. expo-explore capture reviews your branch on this machine, and its report is kept here."];
|
||||
const idWidth = Math.max(...runs.map(run => run.id.length));
|
||||
return [...runs.map(run => `${run.id.padEnd(idWidth)} ${kindLabel(run).padEnd(9)}${runTitle(run)} (${run.platforms.join(", ")}, ${friendlyTime(run.createdAt, now)})`),
|
||||
"", "Open one with: expo-explore reports open <id>"];
|
||||
}
|
||||
|
||||
/**
|
||||
* `reports [list | open ID | add REPORT... | upload ID | rm ID | prune] [--all] [--json]`: the runs kept on this machine. In a terminal
|
||||
* with no subcommand it is an arrow-key picker (Enter opens the run in the local Viewer, u hosts it); elsewhere it lists.
|
||||
* ID is a run's id or `latest`.
|
||||
*/
|
||||
export async function reports(): Promise<void> {
|
||||
const [subcommand = "", id, ...rest] = positionals();
|
||||
const all = await listSavedRuns();
|
||||
const repository = currentRepository();
|
||||
const scoped = has("all") || !repository || !all.some(run => run.repository === repository) ? all : all.filter(run => run.repository === repository);
|
||||
const totalBytes = () => all.reduce((sum, run) => sum + run.bytes, 0);
|
||||
switch (subcommand) {
|
||||
case "open": return openInViewer(await readSavedReports(await savedRun(id)));
|
||||
case "add": {
|
||||
// A report already on disk (a downloaded explore-review artifact, say), kept like a run made here, without hosting it.
|
||||
const paths = [id, ...rest].filter((path): path is string => !!path);
|
||||
if (!paths.length) argumentError("Pass the report to keep: expo-explore reports add ios/report.zip", undefined, "Run expo-explore reports add with a report.zip or report directory, one per platform of the same review.");
|
||||
const read: ReadReport[] = [];
|
||||
for (const path of paths) read.push(await readReport(path));
|
||||
assertOneReview(read);
|
||||
const review = read[0]!.summary.kind === "review" ? read[0]!.summary : undefined;
|
||||
const head = review && commitSubject(process.cwd(), review.head), base = review && commitSubject(process.cwd(), review.base);
|
||||
const run = await saveRun(read.map(report => ({ platform: report.summary.platform, zip: report.zip })), { subjects: { ...(head ? { head } : {}), ...(base ? { base } : {}) } });
|
||||
if (has("json")) output({ ok: true, run }); else console.log(`Kept ${runTitle(run)} as ${run.id}.`);
|
||||
return;
|
||||
}
|
||||
case "upload": return uploadSavedRun(await savedRun(id));
|
||||
case "rm": {
|
||||
const run = await savedRun(id);
|
||||
await removeSavedRun(run.id);
|
||||
if (has("json")) output({ ok: true, removed: run.id }); else console.log(`Deleted ${runTitle(run)} (${run.id}).`);
|
||||
return;
|
||||
}
|
||||
case "prune": {
|
||||
const removed = await pruneSavedRuns();
|
||||
const captures = await pruneCaptureCache(process.env);
|
||||
if (has("json")) output({ ok: true, removed: removed.map(run => run.id), captures: captures.length });
|
||||
else console.log(removed.length || captures.length
|
||||
? `Removed ${removed.length} run${removed.length === 1 ? "" : "s"} and ${captures.length} cached capture${captures.length === 1 ? "" : "s"} kept longer than ${SAVED_RUN_LIMITS.maxAgeDays} days or past ${formatBytes(SAVED_RUN_LIMITS.maxBytes)}.`
|
||||
: "Nothing to prune.");
|
||||
return;
|
||||
}
|
||||
case "list": case "": break;
|
||||
default: argumentError(`Unknown reports subcommand: ${subcommand}`, undefined, "Use expo-explore reports, or reports list, open, add, upload, rm or prune.");
|
||||
}
|
||||
if (has("json")) { output({ ok: true, runs: scoped, bytes: totalBytes(), directory: savedRunsDirectory() }); return; }
|
||||
if (subcommand === "list" || !process.stdin.isTTY || !process.stdout.isTTY || process.env.CI) { for (const line of listLines(scoped)) console.log(line); return; }
|
||||
const color = !process.env.NO_COLOR && process.env.TERM !== "dumb";
|
||||
const action = await runPicker({ runs: all, ...(repository ? { repository } : {}),
|
||||
scope: scoped === all ? "all" : "repository", filter: "", filtering: false, selected: 0, offset: 0 },
|
||||
{ input: process.stdin, output: process.stdout, color, intro: color && !has("no-intro") ? pickIntro(process.env) : undefined,
|
||||
remove: async run => { await removeSavedRun(run.id); all.splice(all.findIndex(each => each.id === run.id), 1); }, totalBytes });
|
||||
if (action.type === "open") { console.log(`${runTitle(action.run)}`); await openInViewer(await readSavedReports(action.run)); }
|
||||
else if (action.type === "upload") { console.log(`Hosting ${runTitle(action.run)}…`); await uploadSavedRun(action.run); }
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
import { cleanRun, type SavedRun } from "../report/saved-runs.js";
|
||||
import { intros, WORDMARK, type IntroName, type Paint } from "./title-intros.js";
|
||||
|
||||
/**
|
||||
* The `expo-explore reports` picker: one aligned line per saved run, the selected run's details in a strip below,
|
||||
* arrow keys to move, Enter to open. Rendering and key handling are pure (state in, lines or state out); `runPicker`
|
||||
* owns the terminal: the alternate screen, raw input, resizes and the intro.
|
||||
*/
|
||||
export type PickerState = {
|
||||
runs: SavedRun[];
|
||||
/** This repository (owner/name), when run inside one with saved runs; `tab` switches to every repository. */
|
||||
repository?: string;
|
||||
scope: "repository" | "all";
|
||||
filter: string;
|
||||
filtering: boolean;
|
||||
selected: number;
|
||||
offset: number;
|
||||
/** The run awaiting `y` to delete. */
|
||||
confirming?: string | undefined;
|
||||
message?: string | undefined;
|
||||
};
|
||||
export type PickerAction = { type: "open" | "upload" | "delete"; run: SavedRun } | { type: "quit" };
|
||||
export type Key = "up" | "down" | "pageup" | "pagedown" | "home" | "end" | "enter" | "escape" | "tab" | "backspace" | "quit" | { text: string };
|
||||
|
||||
const PLAIN: Paint = { white: s => s, text: s => s, dim: s => s, faint: s => s, amber: s => s, green: s => s, yellow: s => s, blue: s => s, red: s => s };
|
||||
const sgr = (code: string) => (text: string) => `\x1b[${code}m${text}\x1b[0m`;
|
||||
export const COLOR: Paint = { white: sgr("1;97"), text: sgr("97"), dim: sgr("38;5;244"), faint: sgr("38;5;238"), amber: sgr("38;5;214"), green: sgr("38;5;114"),
|
||||
yellow: sgr("38;5;221"), blue: sgr("38;5;111"), red: sgr("38;5;203") };
|
||||
/** The selected row's background, kept across the row's own colour resets so it reaches the end of the line. */
|
||||
const SELECT = (text: string) => `\x1b[48;5;236m${text.replaceAll("\x1b[0m", "\x1b[0m\x1b[48;5;236m")}\x1b[0m`;
|
||||
|
||||
const visible = (text: string) => text.replace(/\x1b\[[0-9;]*m/g, "");
|
||||
const length = (text: string) => [...visible(text)].length;
|
||||
const pad = (text: string, width: number) => text + " ".repeat(Math.max(0, width - length(text)));
|
||||
/** A line cut to `width` visible columns, keeping its colour codes and closing them. */
|
||||
function fit(line: string, width: number): string {
|
||||
if (length(line) <= width) return line;
|
||||
let out = "", count = 0;
|
||||
for (const part of line.split(/(\x1b\[[0-9;]*m)/)) {
|
||||
if (part.startsWith("\x1b[")) { out += part; continue; }
|
||||
for (const ch of part) { if (count === width - 1) return `${out}…${out.includes("\x1b[") ? "\x1b[0m" : ""}`; out += ch; count += 1; }
|
||||
}
|
||||
return out;
|
||||
}
|
||||
const cut = (text: string, width: number) => [...text].length > width ? `${[...text].slice(0, Math.max(0, width - 1)).join("")}…` : text;
|
||||
|
||||
export function formatBytes(bytes: number): string {
|
||||
if (bytes < 1024 * 1024) return `${Math.max(1, Math.round(bytes / 1024))} KB`;
|
||||
if (bytes < 1024 ** 3) return `${Math.round(bytes / 1024 / 1024)} MB`;
|
||||
return `${(bytes / 1024 ** 3).toFixed(1)} GB`;
|
||||
}
|
||||
|
||||
/** "5 min ago", "this morning", "yesterday", "last Sunday", then "Oct 12" (with the year when it is not this year). */
|
||||
export function friendlyTime(iso: string, now = Date.now()): string {
|
||||
const then = new Date(iso), today = new Date(now);
|
||||
const minutes = Math.floor((now - then.getTime()) / 60_000);
|
||||
if (minutes < 1) return "just now";
|
||||
if (minutes < 60) return `${minutes} min ago`;
|
||||
const midnight = new Date(today.getFullYear(), today.getMonth(), today.getDate()).getTime();
|
||||
const days = Math.ceil((midnight - then.getTime()) / 86_400_000);
|
||||
if (then.getTime() >= midnight) return then.getHours() < 12 ? "this morning" : then.getHours() < 18 ? "this afternoon" : "this evening";
|
||||
if (days <= 1) return "yesterday";
|
||||
if (days < 7) return `last ${then.toLocaleDateString("en-US", { weekday: "long" })}`;
|
||||
return then.toLocaleDateString("en-US", { month: "short", day: "numeric", ...(then.getFullYear() === today.getFullYear() ? {} : { year: "numeric" }) });
|
||||
}
|
||||
|
||||
export function kindLabel(run: SavedRun): string {
|
||||
return run.kind === "local" ? "Local" : run.kind === "compare" ? "Compare" : run.kind === "exploration" ? "Explore" : `PR #${run.number ?? "?"}`;
|
||||
}
|
||||
|
||||
/** What the list calls a run: a local review of uncommitted changes says how many files; the rest use the report's title. */
|
||||
export function runTitle(run: SavedRun): string {
|
||||
if (run.kind === "local" && run.uncommittedFiles && run.base) return `HEAD + ${run.uncommittedFiles} uncommitted file${run.uncommittedFiles === 1 ? "" : "s"} vs ${run.base.ref}`;
|
||||
if (run.kind === "compare" && run.base && run.head) return `${run.base.ref} → ${run.head.ref}`;
|
||||
return run.title;
|
||||
}
|
||||
|
||||
const PLATFORM_NAMES: Record<string, string> = { ios: "iOS", android: "Android" };
|
||||
const platforms = (run: SavedRun) => run.platforms.map(platform => PLATFORM_NAMES[platform] ?? platform).join(" ");
|
||||
|
||||
/** The runs the list shows: this repository's (or all) that match the filter, across title, refs, subjects, SHAs and PR number. */
|
||||
export function visibleRuns(state: PickerState): SavedRun[] {
|
||||
const query = state.filter.trim().toLowerCase();
|
||||
return state.runs.filter(run => (state.scope === "all" || !state.repository || run.repository === state.repository)
|
||||
&& (!query || [runTitle(run), run.title, kindLabel(run), run.repository, run.head?.ref, run.head?.sha, run.head?.subject, run.base?.ref, run.base?.sha, run.base?.subject,
|
||||
run.explored?.app].some(field => field?.toLowerCase().includes(query))));
|
||||
}
|
||||
|
||||
function counts(run: SavedRun, paint: Paint): string {
|
||||
if (run.explored) return `${paint.text(String(run.explored.screens))} ${paint.dim("screens")} ${paint.dim(`${run.explored.unexplored} unexplored`)}`;
|
||||
const parts = ([["modified", paint.amber, "modified"], ["accessibility-only", paint.blue, "accessibility only"], ["added", paint.green, "added"], ["removed", paint.red, "removed"],
|
||||
["needs-review", paint.yellow, "need review"]] as const)
|
||||
.filter(([group]) => run.changes?.[group]).map(([group, colour, label]) => `${colour(String(run.changes![group]))} ${paint.dim(label)}`);
|
||||
return parts.length ? parts.join(" ") : paint.dim("no visible changes");
|
||||
}
|
||||
|
||||
const KIND_COLOUR = (run: SavedRun, paint: Paint) => ({ local: paint.blue, compare: paint.text, exploration: paint.green, "pull-request": paint.amber }[run.kind]);
|
||||
|
||||
/** The whole screen for a terminal `width` × `height`, top to bottom. */
|
||||
export function renderPicker(state: PickerState, options: { width: number; height: number; now?: number; color?: boolean; totalBytes: number; header?: string[] }): string[] {
|
||||
const paint = options.color === false ? PLAIN : COLOR;
|
||||
const select = options.color === false ? (text: string) => text : SELECT;
|
||||
const width = Math.max(40, options.width), now = options.now ?? Date.now();
|
||||
// Runs are made plain when saved and read; drawing them again plain keeps a hand-edited run.json from reaching the terminal.
|
||||
const runs = visibleRuns(state).map(cleanRun);
|
||||
const scope = state.scope === "all" || !state.repository ? "all repositories" : state.repository;
|
||||
const subtitle = paint.dim(`${state.runs.length} saved run${state.runs.length === 1 ? "" : "s"} · ${formatBytes(options.totalBytes)} on disk · ${scope}`);
|
||||
const tall = options.height >= 20 && width >= WORDMARK[0]!.length + 6;
|
||||
const header = options.header ?? (tall ? ["", ...WORDMARK.map(row => ` ${paint.white(row)}`), "", ` ${subtitle}`, ""] : [` ${paint.white("Expo Explore")} ${subtitle}`, ""]);
|
||||
const rule = paint.faint("─".repeat(width));
|
||||
// Columns: kind, title (what is left), head SHA, platforms, when; the SHA and platforms go first when narrow.
|
||||
const wide = width >= 72;
|
||||
const fixed = 2 + 9 + 2 + (wide ? 2 + 7 + 2 + 11 : 0) + 2 + 14;
|
||||
const titleWidth = Math.max(12, width - fixed);
|
||||
const row = (run: SavedRun) => [pad(KIND_COLOUR(run, paint)(kindLabel(run)), 9), " ", pad(cut(runTitle(run), titleWidth), titleWidth),
|
||||
...(wide ? [" ", paint.dim(pad(run.head?.sha.slice(0, 7) ?? "", 7)), " ", paint.dim(pad(cut(platforms(run), 11), 11))] : []), " ", paint.dim(cut(friendlyTime(run.createdAt, now), 14))].join("");
|
||||
|
||||
const footer: string[] = [rule];
|
||||
if (state.filtering) footer.push(` ${paint.amber("/")} ${state.filter}${paint.amber("▏")} ${paint.dim(`${runs.length} of ${state.runs.length} · Esc clears · ⏎ done`)}`);
|
||||
else if (state.confirming) {
|
||||
const run = state.runs.find(each => each.id === state.confirming);
|
||||
footer.push(` ${paint.red("Delete")} ${paint.white(run ? cut(runTitle(run), 50) : state.confirming)} ${paint.dim(`(${formatBytes(run?.bytes ?? 0)})`)}? ${paint.dim("y/N")}`);
|
||||
} else {
|
||||
const keys = width >= 80 ? `↑↓ move ⏎ open / filter u upload d delete${state.repository ? " tab all repos" : ""} q quit`
|
||||
: `↑↓ ⏎ open / filter u upload d delete${state.repository ? " tab" : ""} q`;
|
||||
footer.push(` ${state.message ? `${paint.text(state.message)} ` : ""}${paint.dim(keys)}`);
|
||||
}
|
||||
|
||||
if (!runs.length) {
|
||||
const empty = state.runs.length
|
||||
? [` ${paint.dim(state.filter ? `Nothing matches "${state.filter}".` : `No saved runs of ${state.repository}. Press tab for every repository.`)}`]
|
||||
: [` ${paint.text("No saved runs yet.")}`, ` ${paint.dim("expo-explore capture reviews your branch on this machine, and its report is kept here.")}`];
|
||||
return [...header, ...empty, "", ...footer].map(line => fit(line, width));
|
||||
}
|
||||
const selected = runs[Math.min(state.selected, runs.length - 1)]!;
|
||||
const detail = [rule, ` ${paint.white(runTitle(selected))}${selected.repository && state.scope === "all" ? paint.dim(` ${selected.repository}`) : ""}`];
|
||||
if (selected.explored) detail.push(` ${paint.dim("app ")} ${selected.explored.app}${selected.explored.version ? ` ${selected.explored.version}` : ""}${selected.explored.buildNumber ? ` (${selected.explored.buildNumber})` : ""}`, "");
|
||||
else {
|
||||
const commit = (label: string, side: SavedRun["head"], uncommitted?: number) => side
|
||||
? ` ${paint.dim(label)} ${(label === "head" ? paint.amber : paint.dim)(side.sha.slice(0, 7))} ${cut(side.subject ?? side.ref, width - 20)}${uncommitted ? paint.dim(` + ${uncommitted} uncommitted`) : ""}${side.subject && side.ref !== "HEAD" && !/^[0-9a-f]{7,40}$/.test(side.ref) && side.subject !== side.ref ? paint.dim(` ${side.ref}`) : ""}`
|
||||
: "";
|
||||
detail.push(commit("head", selected.head, selected.uncommittedFiles), commit("base", selected.base));
|
||||
}
|
||||
detail.push(` ${counts(selected, paint)}${selected.device ? paint.dim(` · ${selected.device}`) : ""}`);
|
||||
|
||||
// The list gets whatever the header, details and footer leave, and scrolls to keep the selection in view.
|
||||
const room = Math.max(3, options.height - header.length - detail.length - footer.length);
|
||||
const index = Math.min(state.selected, runs.length - 1);
|
||||
const offset = Math.min(Math.max(state.offset, index - room + 1, 0), index);
|
||||
const list = runs.slice(offset, offset + room).map((run, position) => offset + position === index
|
||||
? select(`${paint.amber("▌")} ${pad(row(run), width - 3)}`) : ` ${row(run)}`);
|
||||
// The details follow the list; what is left over sits above the keys, so a short list does not float away from them.
|
||||
return [...header, ...list, ...detail, ...Array.from({ length: room - list.length }, () => ""), ...footer].map(line => fit(line, width));
|
||||
}
|
||||
|
||||
/** One key against the state: the next state, and an action when the key asks for one. */
|
||||
export function reducePicker(state: PickerState, key: Key, pageSize = 10): { state: PickerState; action?: PickerAction } {
|
||||
const runs = visibleRuns(state);
|
||||
const at = Math.min(state.selected, Math.max(0, runs.length - 1));
|
||||
const move = (to: number): { state: PickerState } => ({ state: { ...state, selected: Math.max(0, Math.min(runs.length - 1, to)), message: undefined } });
|
||||
if (state.confirming) {
|
||||
const run = state.runs.find(each => each.id === state.confirming);
|
||||
const next: PickerState = { ...state, confirming: undefined };
|
||||
return typeof key === "object" && key.text.toLowerCase() === "y" && run ? { state: next, action: { type: "delete", run } } : { state: { ...next, message: "Kept it." } };
|
||||
}
|
||||
// Ctrl+C always quits, whatever the picker is in the middle of.
|
||||
if (key === "quit") return { state, action: { type: "quit" } };
|
||||
if (state.filtering) {
|
||||
if (key === "escape") return { state: { ...state, filtering: false, filter: "", selected: 0, offset: 0 } };
|
||||
if (key === "enter") return { state: { ...state, filtering: false } };
|
||||
if (key === "backspace") return { state: { ...state, filter: [...state.filter].slice(0, -1).join(""), selected: 0, offset: 0 } };
|
||||
if (key === "up" || key === "down") return reducePicker({ ...state, filtering: false }, key, pageSize);
|
||||
if (typeof key === "object") return { state: { ...state, filter: state.filter + key.text, selected: 0, offset: 0 } };
|
||||
return { state };
|
||||
}
|
||||
const run = runs[at];
|
||||
switch (key) {
|
||||
case "up": return move(at - 1);
|
||||
case "down": return move(at + 1);
|
||||
case "pageup": return move(at - pageSize);
|
||||
case "pagedown": return move(at + pageSize);
|
||||
case "home": return move(0);
|
||||
case "end": return move(runs.length - 1);
|
||||
case "enter": return run ? { state, action: { type: "open", run } } : { state };
|
||||
case "tab": return state.repository ? { state: { ...state, scope: state.scope === "all" ? "repository" : "all", selected: 0, offset: 0, message: undefined } } : { state };
|
||||
case "escape": return state.filter ? { state: { ...state, filter: "", selected: 0, offset: 0 } } : { state, action: { type: "quit" } };
|
||||
case "backspace": return { state };
|
||||
}
|
||||
switch (key.text) {
|
||||
case "j": return move(at + 1);
|
||||
case "k": return move(at - 1);
|
||||
case "g": return move(0);
|
||||
case "G": return move(runs.length - 1);
|
||||
case "/": return { state: { ...state, filtering: true, message: undefined } };
|
||||
case "u": return run ? { state, action: { type: "upload", run } } : { state };
|
||||
case "d": return run ? { state: { ...state, confirming: run.id, message: undefined } } : { state };
|
||||
case "q": return { state, action: { type: "quit" } };
|
||||
}
|
||||
return { state };
|
||||
}
|
||||
|
||||
/**
|
||||
* Raw terminal input to keys; a paste or several keys in one chunk become several keys. Escape sequences the picker has
|
||||
* no use for (Delete, F-keys, modified arrows, Alt+key) are consumed whole and ignored, so they never read as Esc.
|
||||
*/
|
||||
export function decodeKeys(data: string): Key[] {
|
||||
const keys: Key[] = [];
|
||||
const named: Record<string, Key> = { "[A": "up", OA: "up", "[B": "down", OB: "down", "[5~": "pageup", "[6~": "pagedown",
|
||||
"[H": "home", OH: "home", "[1~": "home", "[F": "end", OF: "end", "[4~": "end" };
|
||||
let rest = data;
|
||||
while (rest) {
|
||||
if (rest.startsWith("\x1b")) {
|
||||
// CSI: ESC [ parameters final byte; SS3: ESC O and one byte; Alt+key: ESC and the key; a lone ESC is Esc.
|
||||
const sequence = /^\x1b(\[[0-?]*[ -/]*[@-~]|O.|[^[O])/s.exec(rest);
|
||||
if (!sequence) { keys.push("escape"); rest = rest.slice(1); continue; }
|
||||
const key = named[sequence[1]!];
|
||||
if (key) keys.push(key);
|
||||
rest = rest.slice(sequence[0].length);
|
||||
continue;
|
||||
}
|
||||
const [first] = rest;
|
||||
rest = rest.slice(first!.length);
|
||||
if (first === "\r" || first === "\n") keys.push("enter");
|
||||
else if (first === "\t") keys.push("tab");
|
||||
else if (first === "\x7f" || first === "\b") keys.push("backspace");
|
||||
else if (first === "\x03" || first === "\x04") keys.push("quit");
|
||||
else if (first! >= " " && !/[\u007f-\u009f]/.test(first!)) keys.push({ text: first! });
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
export type PickerTerminal = {
|
||||
input: NodeJS.ReadStream; output: NodeJS.WriteStream;
|
||||
color: boolean; intro?: IntroName | undefined;
|
||||
/** Deletes a run; the picker drops it from the list. */
|
||||
remove: (run: SavedRun) => Promise<void>;
|
||||
totalBytes: () => number;
|
||||
};
|
||||
|
||||
/** Shows the picker until the person opens, uploads or quits; the terminal is restored before it returns. */
|
||||
export async function runPicker(initial: PickerState, terminal: PickerTerminal): Promise<PickerAction> {
|
||||
const { input, output } = terminal;
|
||||
let state = initial;
|
||||
const size = () => ({ width: output.columns || 80, height: output.rows || 24 });
|
||||
const paint = terminal.color ? COLOR : PLAIN;
|
||||
const draw = (header?: string[]) => {
|
||||
const lines = renderPicker(state, { ...size(), color: terminal.color, totalBytes: terminal.totalBytes(), ...(header ? { header } : {}) });
|
||||
output.write(`\x1b[H${lines.map(line => `${line}\x1b[K`).join("\n")}\x1b[J`);
|
||||
};
|
||||
output.write("\x1b[?1049h\x1b[?25l");
|
||||
input.setRawMode(true);
|
||||
input.setEncoding("utf8");
|
||||
input.resume();
|
||||
const pending: Key[] = [];
|
||||
let wake: (() => void) | undefined;
|
||||
const onData = (data: string) => { pending.push(...decodeKeys(data)); wake?.(); };
|
||||
const onResize = () => draw();
|
||||
input.on("data", onData);
|
||||
output.on("resize", onResize);
|
||||
try {
|
||||
// The intro plays where the wordmark will rest, with the list already drawn under it; any key skips it.
|
||||
const { height, width } = size();
|
||||
if (terminal.intro && height >= 20 && width >= WORDMARK[0]!.length + 6) {
|
||||
const intro = intros(Date.now())[terminal.intro];
|
||||
const start = Date.now();
|
||||
for (;;) {
|
||||
const t = Math.min(1, (Date.now() - start) / intro.duration);
|
||||
draw(["", ...intro.frame(t, paint).map(row => ` ${row}`), "", "", ""]);
|
||||
if (t === 1 || pending.length) break;
|
||||
await new Promise(done => setTimeout(done, 16));
|
||||
}
|
||||
// A key that skipped the intro only skips it; Ctrl+C still quits.
|
||||
const quit = pending.includes("quit");
|
||||
pending.length = 0;
|
||||
if (quit) pending.push("quit");
|
||||
}
|
||||
draw();
|
||||
for (;;) {
|
||||
if (!pending.length) await new Promise<void>(done => { wake = done; });
|
||||
wake = undefined;
|
||||
while (pending.length) {
|
||||
const result = reducePicker(state, pending.shift()!, Math.max(1, size().height - 16));
|
||||
state = result.state;
|
||||
const action = result.action;
|
||||
if (action?.type === "delete") {
|
||||
await terminal.remove(action.run);
|
||||
state = { ...state, runs: state.runs.filter(run => run.id !== action.run.id), message: `Deleted ${runTitle(action.run)}.` };
|
||||
} else if (action) return action;
|
||||
}
|
||||
draw();
|
||||
}
|
||||
} finally {
|
||||
input.off("data", onData);
|
||||
output.off("resize", onResize);
|
||||
input.setRawMode(false);
|
||||
input.pause();
|
||||
output.write("\x1b[?25h\x1b[?1049l");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* The "Expo Explore" wordmark `expo-explore reports` opens with, and the five ways it can arrive. One is picked at
|
||||
* random each launch (EXPLORE_INTRO names one, or `off`). Each intro is a function of progress t (0..1) to the
|
||||
* wordmark's two rows, so it can be drawn at any frame rate and tested without a terminal.
|
||||
*/
|
||||
export type Paint = Record<"white" | "text" | "dim" | "faint" | "amber" | "green" | "yellow" | "blue" | "red", (text: string) => string>;
|
||||
export type Intro = { duration: number; frame: (t: number, paint: Paint) => string[] };
|
||||
|
||||
// A two-row pixel font: one column between letters, three between words.
|
||||
const GLYPHS: Record<string, [string, string]> = { e: ["█▀▀", "██▄"], x: ["▀▄▀", "█ █"], p: ["█▀█", "█▀▀"], o: ["█▀█", "█▄█"], l: ["█ ", "█▄▄"], r: ["█▀█", "█▀▄"] };
|
||||
export const WORDMARK: string[] = [0, 1].map(row => "expo explore".split(" ").map(word => [...word].map(letter => GLYPHS[letter]![row]).join(" ")).join(" "));
|
||||
const WIDTH = WORDMARK[0]!.length;
|
||||
const NOISE = [..."░▒▓▚▞▖▗▘▝◆◇○●■□▪▫"];
|
||||
|
||||
const ease = (t: number) => 1 - (1 - t) ** 3;
|
||||
/** A small seeded random, so an intro plays the same way for the same seed (and in tests). */
|
||||
function seeded(seed: number): () => number {
|
||||
let state = seed % 2147483647 || 1;
|
||||
return () => { state = (state * 16807) % 2147483647; return state / 2147483647; };
|
||||
}
|
||||
const cells = (fn: (ch: string, row: number, column: number) => string) => WORDMARK.map((row, r) => [...row].map((ch, c) => fn(ch, r, c)).join(""));
|
||||
|
||||
export function intros(seed = 7): Record<"slider" | "decrypt" | "beams" | "snap" | "slide", Intro> {
|
||||
const random = seeded(seed);
|
||||
// decrypt: when each letter locks in.
|
||||
const lock = WORDMARK.map(row => [...row].map(() => 0.3 + random() * 0.6));
|
||||
// snap: letters start in each other's places and each snaps home at its own moment.
|
||||
const swaps = WORDMARK.map(row => {
|
||||
const map = [...row].map((_, c) => c);
|
||||
const letters = map.filter(c => row[c] !== " ");
|
||||
for (let i = 0; i < letters.length * 0.35; i += 1) {
|
||||
const a = letters[Math.floor(random() * letters.length)]!, b = letters[Math.floor(random() * letters.length)]!;
|
||||
[map[a], map[b]] = [map[b]!, map[a]!];
|
||||
}
|
||||
return map.map((from, c) => ({ from, at: from === c ? 0 : 0.3 + random() * 0.5 }));
|
||||
});
|
||||
const noise = () => NOISE[Math.floor(random() * NOISE.length)]!;
|
||||
return {
|
||||
// The Viewer's compare slider: the crisp "after" behind the handle, the faded "before" ahead of it.
|
||||
slider: { duration: 600, frame: (t, paint) => {
|
||||
const at = Math.round(ease(t) * WIDTH);
|
||||
return cells((ch, _r, c) => c === at && t < 1 ? paint.amber("┃") : c < at ? paint.white(ch) : paint.faint(ch === " " ? " " : "░"));
|
||||
} },
|
||||
// Every letter cycles through noise, then locks in with an amber flash.
|
||||
decrypt: { duration: 900, frame: (t, paint) => cells((ch, r, c) => {
|
||||
if (ch === " ") return " ";
|
||||
const at = lock[r]![c]!;
|
||||
if (t < at) return (t < 0.15 ? paint.faint : paint.blue)(noise());
|
||||
return t < at + 0.07 ? paint.amber(ch) : paint.white(ch);
|
||||
}) },
|
||||
// A diagonal beam of light draws the wordmark as it passes.
|
||||
beams: { duration: 700, frame: (t, paint) => {
|
||||
const beam = t * (WIDTH + 16) - 6;
|
||||
return cells((ch, r, c) => {
|
||||
const distance = c + r * 3 - beam;
|
||||
return distance > 0 ? " " : distance > -3 ? paint.amber(ch === " " ? "·" : ch) : distance > -6 ? paint.yellow(ch) : paint.white(ch);
|
||||
});
|
||||
} },
|
||||
// A visual diff resolving: misplaced letters (amber, modified) snap home (green), then settle.
|
||||
snap: { duration: 900, frame: (t, paint) => cells((ch, r, c) => {
|
||||
const { from, at } = swaps[r]![c]!;
|
||||
const original = WORDMARK[r]![from]!;
|
||||
if (t < 0.12) return paint.faint(original === " " ? " " : "░");
|
||||
if (at === 0) return paint.text(ch);
|
||||
if (t < at) return paint.amber(original);
|
||||
return t < at + 0.1 ? paint.green(ch) : paint.white(ch);
|
||||
}) },
|
||||
// Letters glide in from the right one after another, gray to white.
|
||||
slide: { duration: 800, frame: (t, paint) => WORDMARK.map(row => {
|
||||
const out = Array.from({ length: WIDTH + 24 }, () => " ");
|
||||
for (let c = 0; c < WIDTH; c += 1) {
|
||||
if (row[c] === " ") continue;
|
||||
const local = Math.min(1, Math.max(0, (t - (c / WIDTH) * 0.5) / 0.5));
|
||||
if (local === 0) continue;
|
||||
out[c + Math.round((1 - ease(local)) * 24)] = (local < 1 ? paint.dim : paint.white)(row[c]!);
|
||||
}
|
||||
return out.join("").trimEnd();
|
||||
}) },
|
||||
};
|
||||
}
|
||||
|
||||
export const INTRO_NAMES = ["slider", "decrypt", "beams", "snap", "slide"] as const;
|
||||
export type IntroName = (typeof INTRO_NAMES)[number];
|
||||
|
||||
/** EXPLORE_INTRO when it names one (or `off`), otherwise a random one. */
|
||||
export function pickIntro(environment: NodeJS.ProcessEnv, random = Math.random): IntroName | undefined {
|
||||
const chosen = environment.EXPLORE_INTRO?.trim().toLowerCase();
|
||||
if (chosen === "off" || chosen === "none") return undefined;
|
||||
if (chosen && (INTRO_NAMES as readonly string[]).includes(chosen)) return chosen as IntroName;
|
||||
return INTRO_NAMES[Math.floor(random() * INTRO_NAMES.length)];
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { CiError } from "../shared/ci-errors.js";
|
||||
import type { CaptureSetupAction } from "./explore-config.js";
|
||||
|
||||
const TOKEN = /\{\{secret:([A-Z][A-Z0-9_]{0,127})\}\}/g;
|
||||
const RESERVED = /^(?:GITHUB_|RUNNER_|ACTIONS_|AGENT_DEVICE_|OPENAI_|ANTHROPIC_|EXPO_TOKEN$)/;
|
||||
const RESERVED = /^(?:GITHUB_|RUNNER_|ACTIONS_|AGENT_DEVICE_|ARGENT_|OPENAI_|ANTHROPIC_|EXPO_TOKEN$)/;
|
||||
|
||||
/** References are data, never shell expressions or arbitrary environment access. */
|
||||
export function explorationSecretNames(text: string): string[] {
|
||||
|
||||
@@ -43,6 +43,10 @@ export const DEFAULT_ANDROID_DEVICE = "pixel_7";
|
||||
* One platform's capture target. `platforms.ios` fields default to the flat `app`/`device` fields;
|
||||
* `platforms.android` needs its own package and EAS profile (an `android.buildType: apk` profile).
|
||||
*/
|
||||
/** The poses a foldable device can be captured in (`fold` in agent-device and Argent). */
|
||||
export const DEVICE_POSES = ["closed", "half-open", "open"] as const;
|
||||
export type DevicePose = typeof DEVICE_POSES[number];
|
||||
|
||||
export type PlatformConfig = { device?: string; bundleId?: string; easProfile?: string };
|
||||
|
||||
/** Source discovery never consumes a user-authored screen inventory. */
|
||||
@@ -50,7 +54,11 @@ export type ExploreConfig = {
|
||||
mode: "deterministic" | "agent";
|
||||
app: { name?: string; platform: ExplorePlatform; bundleId: string; easProfile: string; scheme?: string };
|
||||
navigation: { provider: "auto" | "expo-router" | "react-navigation"; entry?: string };
|
||||
device: { name: string };
|
||||
/**
|
||||
* `pose` folds a foldable (iPhone Duo) before capture: closed lights the outer display, open the inner one.
|
||||
* Absent leaves the device as it starts (closed). It applies to the primary platform's device.
|
||||
*/
|
||||
device: { name: string; pose?: DevicePose };
|
||||
/**
|
||||
* Each platform Explore captures, in CI as one matrix job each. Absent: the single platform the
|
||||
* flat fields describe. Capture code never reads this map; resolvePlatformConfig flattens it.
|
||||
@@ -58,7 +66,9 @@ export type ExploreConfig = {
|
||||
platforms?: Partial<Record<ExplorePlatform, PlatformConfig>>;
|
||||
/** `exclude` names routes, as `requiresRoute` does, that stay in the map but are never captured. */
|
||||
exploration: { scope: "changes" | "all"; exclude?: string[] };
|
||||
capture: { maxMinutes: number; maxActions: number; repack: "eas" | "local"; appearance: AppearanceSetting; launch: LaunchSetting; reset: RouteResetSetting; unattributed: UnattributedSetting; readinessSeconds?: number };
|
||||
capture: { maxMinutes: number; maxActions: number; repack: "eas" | "local"; appearance: AppearanceSetting; launch: LaunchSetting; reset: RouteResetSetting; unattributed: UnattributedSetting; readinessSeconds?: number;
|
||||
/** The device controller; absent means agent-device, so configs that never chose one keep their cache recipes. */
|
||||
controller?: "argent" };
|
||||
parameters?: Record<string, Record<string, string>>;
|
||||
setup?: ExploreSetupAction[];
|
||||
agent?: { provider: "openai" | "anthropic"; model: string; instructions?: string };
|
||||
@@ -237,13 +247,15 @@ export function validateExploreConfig(value: unknown): ExploreConfig {
|
||||
const app = record(root.app, "app");
|
||||
exactKeys(app, ["name", "platform", "bundleId", "easProfile", "scheme"], "app");
|
||||
const device = record(root.device, "device");
|
||||
exactKeys(device, ["name"], "device");
|
||||
exactKeys(device, ["name", "pose"], "device");
|
||||
const pose = device.pose === undefined ? undefined : literal(device.pose, DEVICE_POSES, "device.pose", "closed");
|
||||
const navigation = optionalRecord(root.navigation, "navigation");
|
||||
exactKeys(navigation, ["provider", "entry"], "navigation");
|
||||
const exploration = optionalRecord(root.exploration, "exploration");
|
||||
exactKeys(exploration, ["scope", "exclude"], "exploration");
|
||||
const capture = optionalRecord(root.capture, "capture");
|
||||
exactKeys(capture, ["maxMinutes", "maxActions", "repack", "appearance", "launch", "reset", "unattributed", "readinessSeconds"], "capture");
|
||||
exactKeys(capture, ["maxMinutes", "maxActions", "repack", "appearance", "launch", "reset", "unattributed", "readinessSeconds", "controller"], "capture");
|
||||
const controller = literal(capture.controller, ["agent-device", "argent"] as const, "capture.controller", "agent-device");
|
||||
const mode = literal(root.mode, ["deterministic", "agent"] as const, "mode", "deterministic");
|
||||
const name = optionalText(app.name, "app.name", 128);
|
||||
const scheme = app.scheme === undefined ? undefined : customScheme(app.scheme, "app.scheme");
|
||||
@@ -276,7 +288,7 @@ export function validateExploreConfig(value: unknown): ExploreConfig {
|
||||
provider: literal(navigation.provider, ["auto", "expo-router", "react-navigation"] as const, "navigation.provider", "auto"),
|
||||
...(navigation.entry === undefined ? {} : { entry: repoPath(navigation.entry, "navigation.entry") }),
|
||||
},
|
||||
device: { name: text(device.name, "device.name", 128) },
|
||||
device: { name: text(device.name, "device.name", 128), ...(pose === undefined ? {} : { pose }) },
|
||||
...(platforms === undefined ? {} : { platforms }),
|
||||
exploration: {
|
||||
scope: literal(exploration.scope, ["changes", "all"] as const, "exploration.scope", "changes"),
|
||||
@@ -291,6 +303,7 @@ export function validateExploreConfig(value: unknown): ExploreConfig {
|
||||
reset: parseRouteResetSetting(capture.reset, "capture.reset"),
|
||||
unattributed: parseUnattributedSetting(capture.unattributed, "capture.unattributed"),
|
||||
...(capture.readinessSeconds !== undefined ? { readinessSeconds: positiveInteger(capture.readinessSeconds, "capture.readinessSeconds") } : {}),
|
||||
...(controller === "argent" ? { controller } : {}),
|
||||
},
|
||||
...(root.parameters === undefined ? {} : { parameters: parameters(root.parameters) }),
|
||||
...(root.setup === undefined ? {} : { setup: setupActions(root.setup, scheme) }),
|
||||
@@ -362,7 +375,33 @@ export function resolvePlatformConfig(config: ExploreConfig, platform: ExplorePl
|
||||
return { ...rest,
|
||||
app: { ...config.app, platform, bundleId: entry.bundleId ?? (primary ? config.app.bundleId : fail(`platforms.${platform}.bundleId is required`)),
|
||||
easProfile: entry.easProfile ?? (primary ? config.app.easProfile : fail(`platforms.${platform}.easProfile is required`)) },
|
||||
device: { name: entry.device ?? (primary ? config.device.name : platform === "android" ? DEFAULT_ANDROID_DEVICE : config.device.name) } };
|
||||
device: { name: entry.device ?? (primary ? config.device.name : platform === "android" ? DEFAULT_ANDROID_DEVICE : config.device.name),
|
||||
// A pose belongs to the primary platform's device; the other platform's device starts as it is.
|
||||
...(primary && config.device.pose ? { pose: config.device.pose } : {}) } };
|
||||
}
|
||||
|
||||
/**
|
||||
* One run's choices over the reviewed config, from the workflow that started it: a release comparison can capture
|
||||
* every screen (`scope: all`) and keep its hosted link (`expiresIn: never`). `expiresIn` changes nothing when the
|
||||
* config hosts no report.
|
||||
*/
|
||||
export function withRunOverrides(config: ExploreConfig, overrides: { scope?: string | undefined; expiresIn?: string | undefined; controller?: string | undefined }): ExploreConfig {
|
||||
let result = config;
|
||||
if (overrides.controller !== undefined) {
|
||||
if (overrides.controller !== "agent-device" && overrides.controller !== "argent") fail("--controller must be agent-device or argent", "--controller");
|
||||
const { controller: _previous, ...capture } = result.capture;
|
||||
result = { ...result, capture: { ...capture, ...(overrides.controller === "argent" ? { controller: "argent" as const } : {}) } };
|
||||
}
|
||||
if (overrides.scope !== undefined) {
|
||||
if (overrides.scope !== "changes" && overrides.scope !== "all") fail("--scope must be changes or all", "--scope");
|
||||
result = { ...result, exploration: { ...result.exploration, scope: overrides.scope } };
|
||||
}
|
||||
if (overrides.expiresIn !== undefined) {
|
||||
// Validated even without hosting, so a typo in a release workflow surfaces before hosting is turned on.
|
||||
const expiresAfterDays = previewDays(overrides.expiresIn, "--expires-in");
|
||||
if (result.report?.preview) result = { ...result, report: { ...result.report, preview: { ...result.report.preview, expiresAfterDays } } };
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** `expiresAfter` is a whole number of days (`30d`, `30 days`, or `30`), at most PREVIEW_MAX_DAYS, or `never` (null). */
|
||||
@@ -385,11 +424,15 @@ function ciConfig(value: unknown): ExploreConfig["ci"] {
|
||||
const ci = record(value, "ci");
|
||||
exactKeys(ci, ["trustedAuthors"], "ci");
|
||||
if (ci.trustedAuthors === undefined) return {};
|
||||
if (!Array.isArray(ci.trustedAuthors)) fail("ci.trustedAuthors must be a list of GitHub logins", "ci.trustedAuthors");
|
||||
if (ci.trustedAuthors.length > TRUSTED_AUTHORS_MAX) {
|
||||
return { trustedAuthors: trustedAuthorList(ci.trustedAuthors) };
|
||||
}
|
||||
|
||||
function trustedAuthorList(value: unknown): string[] {
|
||||
if (!Array.isArray(value)) fail("ci.trustedAuthors must be a list of GitHub logins", "ci.trustedAuthors");
|
||||
if (value.length > TRUSTED_AUTHORS_MAX) {
|
||||
fail(`ci.trustedAuthors lists at most ${TRUSTED_AUTHORS_MAX} logins`, "ci.trustedAuthors");
|
||||
}
|
||||
const trustedAuthors = ci.trustedAuthors.map((entry, index) => {
|
||||
const trustedAuthors = value.map((entry, index) => {
|
||||
const login = text(entry, `ci.trustedAuthors[${index}]`, 64);
|
||||
if (!GITHUB_LOGIN.test(login)) {
|
||||
fail(`ci.trustedAuthors[${index}] must be a GitHub login such as devin-ai-integration[bot]`, `ci.trustedAuthors[${index}]`);
|
||||
@@ -399,7 +442,7 @@ function ciConfig(value: unknown): ExploreConfig["ci"] {
|
||||
if (new Set(trustedAuthors.map(login => login.toLowerCase())).size !== trustedAuthors.length) {
|
||||
fail("ci.trustedAuthors lists a login twice", "ci.trustedAuthors");
|
||||
}
|
||||
return { trustedAuthors };
|
||||
return trustedAuthors;
|
||||
}
|
||||
|
||||
function reportConfig(value: unknown): ExploreConfig["report"] {
|
||||
@@ -425,8 +468,23 @@ function reportConfig(value: unknown): ExploreConfig["report"] {
|
||||
} };
|
||||
}
|
||||
|
||||
/**
|
||||
* ci.trustedAuthors alone, from a config the rest of which may be incomplete or from another release: the review
|
||||
* workflow's trust check reads only this list from the default branch, and other keys, under ci: too, are ignored.
|
||||
*/
|
||||
export function parseTrustedAuthors(source: string): string[] {
|
||||
const value = plainDocument(source);
|
||||
const ci = value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>).ci : undefined;
|
||||
const list = ci && typeof ci === "object" && !Array.isArray(ci) ? (ci as Record<string, unknown>).trustedAuthors : undefined;
|
||||
return list === undefined ? [] : trustedAuthorList(list);
|
||||
}
|
||||
|
||||
/** Parse YAML as plain data: no anchors, aliases, merge keys, or custom tags. */
|
||||
export function parseExploreConfig(source: string): ExploreConfig {
|
||||
return validateExploreConfig(plainDocument(source));
|
||||
}
|
||||
|
||||
function plainDocument(source: string): unknown {
|
||||
if (Buffer.byteLength(source) > MAX_CONFIG_BYTES) fail("file is too large");
|
||||
const document = parseDocument(source, { uniqueKeys: true, merge: false, schema: "core" });
|
||||
if (document.errors.length > 0) fail(document.errors[0]!.message.split("\n")[0]!);
|
||||
@@ -436,7 +494,7 @@ export function parseExploreConfig(source: string): ExploreConfig {
|
||||
fail("custom tags are not allowed");
|
||||
}
|
||||
});
|
||||
return validateExploreConfig(document.toJS());
|
||||
return document.toJS();
|
||||
}
|
||||
|
||||
/** Credential gate for active agent execution; never call during static planning. */
|
||||
|
||||
@@ -4,7 +4,7 @@ import { dirname, join, resolve } from "node:path";
|
||||
import { createInterface } from "node:readline/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { stringify } from "yaml";
|
||||
import { DEFAULT_EXPLORE_CONFIG_PATH, readExploreConfig, validateExploreConfig, type ExploreConfig } from "./explore-config.js";
|
||||
import { DEFAULT_EXPLORE_CONFIG_PATH, readExploreConfig, validateExploreConfig, type ExploreConfig, type ExplorePlatform } from "./explore-config.js";
|
||||
import { explorationSecretNames } from "./exploration-inputs.js";
|
||||
import type { RouteEntryReport } from "../ci/route-entry.js";
|
||||
import type { CiInstallResult } from "../ci/workflow-install.js";
|
||||
@@ -60,6 +60,8 @@ type SetupOptions = {
|
||||
appState?: string | undefined;
|
||||
workflows?: boolean | undefined;
|
||||
nonInteractive?: boolean;
|
||||
/** Return the config without writing anything. */
|
||||
dryRun?: boolean;
|
||||
check?: boolean;
|
||||
};
|
||||
type Interaction = {
|
||||
@@ -234,6 +236,14 @@ export type SetupResult = {
|
||||
nextSteps?: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* The config `setup --non-interactive` would write, without writing it: what a local review runs with in an app that
|
||||
* has no config yet. Throws setup's errors when the app cannot be built for capture.
|
||||
*/
|
||||
export async function defaultExploreConfig(project: string, platform?: ExplorePlatform): Promise<ExploreConfig> {
|
||||
return (await runExploreSetup({ project, platform, nonInteractive: true, dryRun: true })).config;
|
||||
}
|
||||
|
||||
/**
|
||||
* The guided setup. It writes what it can derive (app identity, mode, route parameters it was given,
|
||||
* an agent-instructions draft, CI files) and hands the app-specific flows to the user's coding agent.
|
||||
@@ -290,7 +300,9 @@ export async function runExploreSetup(options: SetupOptions = {}, interaction?:
|
||||
}
|
||||
const schemes = Array.isArray(app.scheme) ? app.scheme.filter((value): value is string => typeof value === "string") : undefined;
|
||||
const scheme = await choose("URL scheme (optional)", options.scheme, schemes?.[0] ?? string(app.scheme), schemes);
|
||||
const profile = await choose(platform === "android" ? "EAS emulator (APK) build profile" : "EAS simulator build profile", options.profile, profiles.length === 1 ? profiles[0]! : "", profiles);
|
||||
const profile = await choose(platform === "android" ? "EAS emulator (APK) build profile" : "EAS simulator build profile", options.profile,
|
||||
// With several, the one named explore, the name the README and the explore-setup skill give it.
|
||||
profiles.length === 1 ? profiles[0]! : profiles.includes("explore") ? "explore" : "", profiles);
|
||||
if (!profiles.includes(profile)) throw new Error(`Choose ${platform === "android" ? "an Android APK" : "a simulator"} profile from eas.json with --profile: ${profiles.join(", ")}.`);
|
||||
const inferredProvider = dependencies["expo-router"] ? "expo-router" : dependencies["@react-navigation/native"] ? "react-navigation" : "auto";
|
||||
const provider = await choose("Navigation provider", options.navigation, inferredProvider, ["auto", "expo-router", "react-navigation"]);
|
||||
@@ -390,6 +402,7 @@ export async function runExploreSetup(options: SetupOptions = {}, interaction?:
|
||||
const answer = await ui!.ask("Write this config? (yes/no)", "yes");
|
||||
if (!/^(y|yes)$/i.test(answer.trim())) throw new Error("Setup canceled; no config was written.");
|
||||
}
|
||||
if (options.dryRun) return { path, config, created: false };
|
||||
await mkdir(parent, { recursive: true });
|
||||
await writeFile(path, yaml, { flag: "wx" });
|
||||
if (instructions) await writeFile(instructionsPath, instructions, { flag: "wx" });
|
||||
|
||||
@@ -73,6 +73,8 @@ export type CaptureBundle = {
|
||||
/** Execution completion time, recorded even when no routes require screenshots. */
|
||||
completedAt?: string;
|
||||
appName?: string;
|
||||
/** The device controller that drove the capture; absent for agent-device, the default. */
|
||||
controller?: "argent";
|
||||
/** The icon the app config declares, shrunk to at most 128 pixels; absent when unavailable. */
|
||||
appIcon?: Omit<AppIconImage, "url"> & { path: string };
|
||||
profile: string; selectedSurfaceIds: string[];
|
||||
@@ -172,8 +174,18 @@ export type PublicVisualVerdict = {
|
||||
rect: { x: number; y: number; width: number; height: number };
|
||||
normalizedRect: { x: number; y: number; width: number; height: number };
|
||||
differentPixels: number; shareOfDiffPercentage: number; dominantChange: string; location: string;
|
||||
/**
|
||||
* Set when the region's content is the same in both screenshots, only moved: how far, in screenshot pixels
|
||||
* (right and down are positive). Absent when the content itself changed.
|
||||
*/
|
||||
shift?: { x: number; y: number };
|
||||
}>;
|
||||
tool: string;
|
||||
/**
|
||||
* Every region the comparison found (not only the published ones) only moved: nothing on the screen changed
|
||||
* content. Absent when any region changed, or moves were not measured.
|
||||
*/
|
||||
allRegionsMoved?: true;
|
||||
/** Diff regions inside the iOS status-bar band that were excluded from the verdict. */
|
||||
ignoredStatusBarRegions?: number;
|
||||
/** Diff regions that lay entirely inside the home-indicator band and were left out of the verdict. */
|
||||
@@ -228,6 +240,8 @@ export type PublicReview = {
|
||||
appIcon?: AppIconImage;
|
||||
/** Absent in reports published before Android support: iOS. */
|
||||
platform?: "ios" | "android";
|
||||
/** The device controller that drove the head capture; absent for agent-device, the default. */
|
||||
controller?: "argent";
|
||||
device?: { model: string; osVersion: string };
|
||||
/** The share of each screenshot's height the verdict ignored as the status bar. */
|
||||
statusBarBandPercent?: number;
|
||||
|
||||
@@ -8,12 +8,13 @@ const REVIEW_STATUSES = new Set(["added", "modified", "removed", "unchanged", "n
|
||||
const SOURCE_SCOPES = new Set(["screen", "app-wide", "none"]);
|
||||
/** Verdicts each source scope allows: only a source change makes a screen a review target. */
|
||||
const SCOPE_VERDICTS: Record<string, readonly string[]> = {
|
||||
screen: ["modified", "needs-review"],
|
||||
screen: ["modified", "needs-review", "unchanged"],
|
||||
"app-wide": ["modified", "needs-review", "unchanged"],
|
||||
none: ["unchanged", "variant"],
|
||||
};
|
||||
const VISUAL_VERDICTS = new Set(["unchanged", "modified", "needs-review"]);
|
||||
const MAX_REVIEW_DESCRIPTION = 160;
|
||||
const LEGACY_NO_VISIBLE_DIFFERENCE = "Source changed; no visible difference was captured.";
|
||||
|
||||
/** Source analysis belongs to capture planning; delivered reports contain runtime review evidence. */
|
||||
/** Capture shrinks the app icon to at most this many pixels on a side. */
|
||||
@@ -31,6 +32,14 @@ function hasVerifiedPair(surface: Surface): boolean {
|
||||
&& surface[`${side}Outcome`]?.landing === "verified");
|
||||
}
|
||||
|
||||
/**
|
||||
* A modified screen whose verified screenshots match: only what assistive technology reads (its accessibility tree)
|
||||
* changed. Screen readers and voice control see it, so it is a change to review, listed apart from the visual ones.
|
||||
*/
|
||||
export function isAccessibilityOnlyChange(surface: Surface): boolean {
|
||||
return surface.review?.status === "modified" && surface.visual?.verdict === "unchanged" && hasVerifiedPair(surface);
|
||||
}
|
||||
|
||||
function assertReviewFields(surface: Surface, enforceComparisonEvidence: boolean): void {
|
||||
const assertVerifiedPair = () => {
|
||||
if (enforceComparisonEvidence && !hasVerifiedPair(surface)) {
|
||||
@@ -66,13 +75,23 @@ function assertReviewFields(surface: Surface, enforceComparisonEvidence: boolean
|
||||
}
|
||||
}
|
||||
|
||||
/** A region's move between the screenshots: finite, and small enough to be layout drift rather than another screen. */
|
||||
function validShift(shift: unknown): boolean {
|
||||
if (!shift || typeof shift !== "object") return false;
|
||||
const { x, y } = shift as { x?: unknown; y?: unknown };
|
||||
return typeof x === "number" && typeof y === "number" && Number.isFinite(x) && Number.isFinite(y) && Math.abs(x) <= 64 && Math.abs(y) <= 64;
|
||||
}
|
||||
|
||||
function assertVisualVerdict(visual: PublicVisualVerdict, enforceComparisonEvidence: boolean, paired: boolean): void {
|
||||
if (!visual || typeof visual !== "object" || !VISUAL_VERDICTS.has(visual.verdict)
|
||||
|| typeof visual.reason !== "string" || (enforceComparisonEvidence && visual.reason === "diff-failed") || typeof visual.tool !== "string"
|
||||
|| typeof visual.threshold !== "number" || !Number.isFinite(visual.threshold)
|
||||
|| (visual.mismatchPercentage !== undefined
|
||||
&& (typeof visual.mismatchPercentage !== "number" || !Number.isFinite(visual.mismatchPercentage) || visual.mismatchPercentage < 0))
|
||||
|| (visual.regions !== undefined && (!Array.isArray(visual.regions) || visual.regions.length > 64))
|
||||
|| (visual.regions !== undefined && (!Array.isArray(visual.regions) || visual.regions.length > 64
|
||||
|| visual.regions.some(region => region?.shift !== undefined && !validShift(region.shift))))
|
||||
|| (visual.allRegionsMoved !== undefined && (visual.allRegionsMoved !== true || !visual.regions?.length
|
||||
|| visual.regions.some(region => region.shift === undefined)))
|
||||
|| !paired) {
|
||||
throw new Error("Public visual verdict is inconsistent");
|
||||
}
|
||||
@@ -207,6 +226,12 @@ export function normalizePublicReviewForReading(review: PublicReview, onGap?: (g
|
||||
surface = { ...surface, review: { ...surface.review, status: "variant",
|
||||
description: description.length > MAX_REVIEW_DESCRIPTION ? `${description.slice(0, MAX_REVIEW_DESCRIPTION - 1)}…` : description } };
|
||||
}
|
||||
// Reports before 0.19.1 called a screen whose source changed but whose captures matched "needs review". It has no
|
||||
// visible change, so it reads as unchanged and is not counted as a change.
|
||||
if (surface.review?.status === "needs-review" && surface.review.description === LEGACY_NO_VISIBLE_DIFFERENCE) {
|
||||
changed = true;
|
||||
surface = { ...surface, review: { ...surface.review, status: "unchanged", description: "No visible change" } };
|
||||
}
|
||||
const comparisonVerdict = surface.review && surface.review.status !== "added" && surface.review.status !== "removed";
|
||||
if (!((!hasVerifiedPair(surface) && (comparisonVerdict || surface.visual)) || surface.visual?.reason === "diff-failed")) return surface;
|
||||
changed = true;
|
||||
|
||||
@@ -32,10 +32,48 @@ export type LocalReviewPresentation = {
|
||||
number?: never;
|
||||
url?: never;
|
||||
};
|
||||
export type ReviewPresentation = PullRequestPresentation | LocalReviewPresentation;
|
||||
/** Any two commits of a GitHub repository, compared without a pull request: a tag against the last release, a nightly against yesterday. */
|
||||
export type CompareReviewPresentation = {
|
||||
origin: "compare";
|
||||
repositoryId: string;
|
||||
repository: string;
|
||||
title: string;
|
||||
/** github.com's compare page for the two commits. */
|
||||
url: string;
|
||||
base: PullRequestSidePresentation;
|
||||
head: PullRequestSidePresentation;
|
||||
number?: never;
|
||||
};
|
||||
export type ReviewPresentation = PullRequestPresentation | LocalReviewPresentation | CompareReviewPresentation;
|
||||
|
||||
/** "v1.4.0 vs v1.3.0": the title a comparison gets when its caller names none; a ref given as a SHA reads as its short form. */
|
||||
export function compareTitle(base: PullRequestSidePresentation, head: PullRequestSidePresentation): string {
|
||||
const name = (side: PullRequestSidePresentation) => /^[0-9a-f]{40}$/i.test(side.ref) ? side.sha.slice(0, 8) : side.ref;
|
||||
return `${name(head)} vs ${name(base)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The title for Markdown (job summaries): refs may contain ] ) < >, which would break a line's links, so each
|
||||
* ref, or a caller's own title, is a code span.
|
||||
*/
|
||||
export function compareTitleMarkdown(comparison: CompareReviewPresentation): string {
|
||||
const code = (value: string) => `\`${value.replace(/`/g, "'")}\``;
|
||||
if (comparison.title !== compareTitle(comparison.base, comparison.head)) return code(comparison.title);
|
||||
const name = (side: PullRequestSidePresentation) => /^[0-9a-f]{40}$/i.test(side.ref) ? side.sha.slice(0, 8) : side.ref;
|
||||
return `${code(name(comparison.head))} vs ${code(name(comparison.base))}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* github.com's two-dot comparison: the direct diff between the two commits, as capture compares them. The three-dot
|
||||
* form diffs from their merge base, which shows nothing for a rollback and drops base-only changes on diverged branches.
|
||||
*/
|
||||
export function compareUrl(repository: string, base: PullRequestSidePresentation, head: PullRequestSidePresentation): string {
|
||||
return `https://github.com/${repository}/compare/${base.sha}..${head.sha}`;
|
||||
}
|
||||
|
||||
export function projectReviewPresentation(value: unknown): ReviewPresentation {
|
||||
const candidate = record(value, "Review presentation");
|
||||
if (candidate.origin === "compare") return projectComparePresentation(value);
|
||||
if (candidate.origin !== "local") return projectPullRequestPresentation(value);
|
||||
exactKeys(candidate, ["origin", "repository", "runId", "title", "base", "head"], [], "Local review");
|
||||
const runId = text(candidate.runId, "Local run", 160);
|
||||
@@ -137,17 +175,14 @@ function fullSha(value: unknown, label: string): string {
|
||||
return candidate.toLowerCase();
|
||||
}
|
||||
|
||||
/** Whether a report may name a ref as given: no leading or trailing slash, `..`, backslash or reflog syntax (`@{`). */
|
||||
export function isSafeBranchRef(candidate: string): boolean {
|
||||
return !(candidate.startsWith("/") || candidate.endsWith("/") || candidate.includes("..") || candidate.includes("\\") || candidate.includes("@{"));
|
||||
}
|
||||
|
||||
function branchRef(value: unknown, label: string): string {
|
||||
const candidate = text(value, label, 255);
|
||||
if (
|
||||
candidate.startsWith("/")
|
||||
|| candidate.endsWith("/")
|
||||
|| candidate.includes("..")
|
||||
|| candidate.includes("\\")
|
||||
|| candidate.includes("@{")
|
||||
) {
|
||||
throw new Error(`${label} is not a safe branch ref`);
|
||||
}
|
||||
if (!isSafeBranchRef(candidate)) throw new Error(`${label} is not a safe branch ref`);
|
||||
return candidate;
|
||||
}
|
||||
|
||||
@@ -167,6 +202,20 @@ function pullRequestSide(value: unknown, label: string): PullRequestSidePresenta
|
||||
};
|
||||
}
|
||||
|
||||
/** Strictly project a two-commit comparison before it enters a published workspace; its URL is always github.com's compare page. */
|
||||
export function projectComparePresentation(value: unknown): CompareReviewPresentation {
|
||||
const candidate = record(value, "Comparison presentation");
|
||||
exactKeys(candidate, ["origin", "repositoryId", "repository", "base", "head"], ["title", "url"], "Comparison presentation");
|
||||
const repo = repository(candidate.repository);
|
||||
const base = pullRequestSide(candidate.base, "base");
|
||||
const head = pullRequestSide(candidate.head, "head");
|
||||
if (base.sha === head.sha) throw new Error("comparison base and head must be different commits");
|
||||
const url = compareUrl(repo, base, head);
|
||||
if (candidate.url !== undefined && candidate.url !== url) throw new Error("comparison URL must be the github.com compare URL of its two commits");
|
||||
return { origin: "compare", repositoryId: repositoryId(candidate.repositoryId), repository: repo,
|
||||
title: candidate.title === undefined ? compareTitle(base, head) : text(candidate.title, "comparison title", 512), url, base, head };
|
||||
}
|
||||
|
||||
/** Strictly project live GitHub PR metadata before it enters a published workspace. */
|
||||
export function projectPullRequestPresentation(value: unknown): PullRequestPresentation {
|
||||
const candidate = record(value, "Pull request presentation");
|
||||
|
||||
@@ -4,10 +4,11 @@
|
||||
* shell carries for fetchers that convert HTML to text. It reads the decrypted archive directly, so
|
||||
* it only picks the fields it publishes from the report JSON and treats everything else as untrusted.
|
||||
*/
|
||||
import { readZipDirectory, readZipEntry, type ZipEntry } from "./report-zip";
|
||||
import { readZipDirectory, readZipEntry, type ZipEntry } from "./zip-reader.js";
|
||||
|
||||
export const AGENT_API_VERSION = "v1";
|
||||
const MAX_METADATA_BYTES = 64 * 1024 * 1024;
|
||||
/** The largest review.json or exploration.json a hosted report reads. */
|
||||
export const MAX_METADATA_BYTES = 64 * 1024 * 1024;
|
||||
const MAX_ASSET_BYTES = 32 * 1024 * 1024;
|
||||
const MAX_RAW_BYTES = 8 * 1024 * 1024;
|
||||
const DEFAULT_LIMIT = 50;
|
||||
@@ -97,7 +98,8 @@ function reviewSurfaceItem(context: AgentContext, surface: Json): Json {
|
||||
const visual = rec(surface.visual), review = rec(surface.review);
|
||||
const id = str(surface.id) ?? "";
|
||||
return defined({
|
||||
id, route: str(route.route), kind: str(route.kind), routeFile: str(route.routeFile), status: str(surface.status), colorScheme: str(surface.colorScheme),
|
||||
id, route: str(route.route), kind: str(route.kind), routeFile: str(route.routeFile), status: verdictOf(surface),
|
||||
sourceStatus: verdictOf(surface) === str(surface.status) ? undefined : str(surface.status), colorScheme: str(surface.colorScheme),
|
||||
review: surface.review === undefined ? undefined : defined({ status: str(review.status), description: str(review.description), facts: arr(review.facts).map(fact => str(rec(fact).bullet)).filter(Boolean) }),
|
||||
visual: surface.visual === undefined ? undefined : defined({ verdict: str(visual.verdict), reason: str(visual.reason), mismatchPercentage: num(visual.mismatchPercentage), threshold: num(visual.threshold) }),
|
||||
note: str(rec(surface.note).text),
|
||||
@@ -119,19 +121,66 @@ function reviewSurfaceDetail(context: AgentContext, review: Json, surface: Json)
|
||||
}
|
||||
const edgeItem = (edge: Json): Json => defined({ from: str(edge.from), to: str(edge.to), kind: str(edge.kind), sourceFile: str(edge.sourceFile), provenance: str(edge.provenance) });
|
||||
|
||||
/**
|
||||
* A screen's status as the Viewer and the PR comment show it: the review's verdict where there is one, so `modified`
|
||||
* means a visible change. A screen whose source changed but whose captures match is unchanged, including in reports
|
||||
* from before 0.19.1, which called it "needs review". A modified screen whose screenshots match changed only in what
|
||||
* assistive technology reads: `accessibility-only`. A screen whose capture failed is `unavailable`, and one whose
|
||||
* source changed but that has no verdict was not compared: `not-compared`.
|
||||
*/
|
||||
/** Both sides captured at their verified destination route, as a verdict requires (isAccessibilityOnlyChange in the contract). */
|
||||
function verifiedPair(surface: Json): boolean {
|
||||
return (["base", "head"] as const).every(side => str(rec(surface[side]).kind) === "screen" && Boolean(surface[`${side}Image`])
|
||||
&& str(rec(surface[`${side}Outcome`]).status) === "captured" && str(rec(surface[`${side}Outcome`]).landing) === "verified");
|
||||
}
|
||||
|
||||
/** The side's planned capture ended without a screenshot, or captured another screen than the route (the Viewer's Unavailable). */
|
||||
function captureUnavailable(surface: Json, side: "base" | "head"): boolean {
|
||||
const outcome = surface[`${side}Outcome`];
|
||||
if (str(rec(surface[side]).kind) !== "screen" || outcome === undefined) return false;
|
||||
const image = Boolean(surface[`${side}Image`]);
|
||||
if (!image) return str(rec(outcome).status) !== "captured";
|
||||
return str(rec(outcome).status) === "captured" && str(rec(outcome).landing) !== "verified" && rec(outcome).observed !== undefined;
|
||||
}
|
||||
|
||||
function verdictOf(surface: Json): string | undefined {
|
||||
// A capture that failed is unavailable, as the Viewer says, whatever the source or an older verdict claims.
|
||||
if (str(surface.status) !== "removed" && captureUnavailable(surface, "head")) return "unavailable";
|
||||
if (["modified", "unchanged"].includes(str(surface.status) ?? "") && captureUnavailable(surface, "base")) return "unavailable";
|
||||
const review = rec(surface.review);
|
||||
const status = str(review.status);
|
||||
if (status === "needs-review" && str(review.description) === "Source changed; no visible difference was captured.") return "unchanged";
|
||||
if (status === "modified" && str(rec(surface.visual).verdict) === "unchanged" && verifiedPair(surface)) return "accessibility-only";
|
||||
// A source change nobody compared is not a change Explore saw.
|
||||
if (status === undefined && str(surface.status) === "modified") return "not-compared";
|
||||
return status ?? str(surface.status);
|
||||
}
|
||||
|
||||
const STATUS_ORDER = ["modified", "accessibility-only", "added", "removed", "needs-review", "unavailable", "not-compared", "unchanged", "variant"];
|
||||
const STATUS_WORDS: Record<string, string> = { "accessibility-only": "accessibility only (screenshots match, the accessibility tree does not)",
|
||||
"needs-review": "need review", "not-compared": "not compared", variant: "screen variants" };
|
||||
|
||||
/** "3 modified, 1 added, 1 removed, 30 unchanged": every status counted, so the parts add up to the total. */
|
||||
function screenCounts(screens: Json): string {
|
||||
const statuses = Object.keys(screens).filter(status => status !== "total")
|
||||
.sort((left, right) => (STATUS_ORDER.indexOf(left) + 1 || 99) - (STATUS_ORDER.indexOf(right) + 1 || 99));
|
||||
const parts = statuses.flatMap(status => (num(screens[status]) ? [`${num(screens[status])} ${STATUS_WORDS[status] ?? status}`] : []));
|
||||
return parts.length ? parts.join(", ") : "none";
|
||||
}
|
||||
|
||||
function reviewSummary(context: AgentContext, review: Json): Json {
|
||||
const surfaces = arr(review.surfaces).map(rec);
|
||||
const counts: Record<string, number> = {};
|
||||
for (const surface of surfaces) { const status = str(surface.status) ?? "unknown"; counts[status] = (counts[status] ?? 0) + 1; }
|
||||
for (const surface of surfaces) { const status = verdictOf(surface) ?? "unknown"; counts[status] = (counts[status] ?? 0) + 1; }
|
||||
const pr = rec(review.pullRequest), runtime = rec(review.runtime);
|
||||
return defined({
|
||||
kind: "pr-review", api: AGENT_API_VERSION, contract: str(review.contract),
|
||||
pullRequest: defined({ repository: str(pr.repository), number: num(pr.number), title: str(pr.title), url: str(pr.url), head: str(rec(pr.head).sha), base: str(rec(pr.base).sha) }),
|
||||
pullRequest: defined({ origin: str(pr.origin), repository: str(pr.repository), number: num(pr.number), title: str(pr.title), url: str(pr.url), head: str(rec(pr.head).sha), base: str(rec(pr.base).sha) }),
|
||||
app: defined({ name: str(runtime.appName), version: str(runtime.appVersion), build: str(runtime.appBuildNumber), platform: str(runtime.platform) ?? context.platform, device: rec(runtime.device).model === undefined ? undefined : `${str(rec(runtime.device).model)} ${str(rec(runtime.device).osVersion) ?? ""}`.trim() }),
|
||||
createdAt: str(review.createdAt), mode: str(review.mode), platforms: context.platforms, expiresAt: context.expiresAt,
|
||||
screens: { total: surfaces.length, ...counts },
|
||||
links: {
|
||||
screens: withPlatform(context, apiUrl(context, "/screens")), changed: withPlatform(context, apiUrl(context, "/screens?status=modified,added,removed")),
|
||||
screens: withPlatform(context, apiUrl(context, "/screens")), changed: withPlatform(context, apiUrl(context, "/screens?status=modified,accessibility-only,added,removed")),
|
||||
transitions: withPlatform(context, apiUrl(context, "/transitions")), raw: withPlatform(context, apiUrl(context, "/raw")),
|
||||
viewer: viewerUrl(context), viewerChanges: viewerUrl(context, { focus: "modified", inspect: "diff" }), markdown: `${context.pageUrl}/llms.txt`,
|
||||
},
|
||||
@@ -211,11 +260,14 @@ export function agentIndexMarkdown(context: AgentContext, loaded: LoadedReport):
|
||||
const lines: string[] = [];
|
||||
if (loaded.kind === "pr-review") {
|
||||
const pr = rec(summary.pullRequest);
|
||||
lines.push(`# Expo Explore report: ${escapeMd(app.name ?? pr.repository)} PR #${escapeMd(pr.number)}${app.platform ? ` (${escapeMd(app.platform)})` : ""}`, "",
|
||||
`> Visual review of pull request ${escapeMd(pr.repository)}#${escapeMd(pr.number)} by Expo Explore. ${screens.total} screens captured: ${screens.modified ?? 0} modified, ${screens.added ?? 0} added, ${screens.removed ?? 0} removed, ${screens.unchanged ?? 0} unchanged.${context.expiresAt ? ` This link stops serving the report after ${context.expiresAt}.` : ""}`, "",
|
||||
// A comparison of two commits has a title ("v1.4.0 vs v1.3.0") where a pull request has a number.
|
||||
// A comparison of two commits, or a local review on someone's machine, has no pull request: its title names both refs.
|
||||
const compared = pr.origin === "compare" || pr.origin === "local";
|
||||
lines.push(`# Expo Explore report: ${escapeMd(app.name ?? pr.repository)} ${compared ? escapeMd(pr.title) : `PR #${escapeMd(pr.number)}`}${app.platform ? ` (${escapeMd(app.platform)})` : ""}`, "",
|
||||
`> Visual review of ${compared ? `${escapeMd(pr.repository)} ${escapeMd(pr.title)}` : `pull request ${escapeMd(pr.repository)}#${escapeMd(pr.number)}`} by Expo Explore. ${screens.total} screens: ${screenCounts(screens)}.${context.expiresAt ? ` This link stops serving the report after ${context.expiresAt}.` : ""}`, "",
|
||||
"This URL is the human Viewer. The same report is available as read-only JSON (no credentials beyond this URL):", "",
|
||||
`- [Summary](${links.summary ?? withPlatform(context, apiUrl(context))}): kind, counts by status, app and PR identity, links`,
|
||||
`- [Changed screens](${links.changed}): the modified, added and removed screens with the review description, visual verdict and mismatch percentage; \`status=\` filters, \`limit=\`/\`cursor=\` page`,
|
||||
`- [Changed screens](${links.changed}): the modified, accessibility-only (screenshots match, the accessibility tree does not), added and removed screens with the review description, visual verdict and mismatch percentage; \`status=\` filters, \`limit=\`/\`cursor=\` page`,
|
||||
`- [All screens](${links.screens}): every captured screen; \`${links.screens}/{id}\` (the \`id\` field of a screen) adds source files and navigation in and out`,
|
||||
`- [Transitions](${links.transitions}): navigation edges between screens (\`?from=\`/\`?to=\` take a screen id or route)`,
|
||||
`- Screenshots: each screen's \`headImage\`/\`baseImage\` URL returns the PNG`,
|
||||
@@ -335,7 +387,7 @@ export async function agentApiReply(context: AgentContext, loaded: LoadedReport,
|
||||
const surfaces = arr(loaded.json.surfaces).map(rec);
|
||||
if (id !== undefined) { const surface = surfaces.find(s => s.id === id); return surface ? json(reviewSurfaceDetail(context, loaded.json, surface)) : notFound(); }
|
||||
const statuses = params.get("status")?.split(",").filter(Boolean);
|
||||
const items = surfaces.filter(s => !statuses || statuses.includes(str(s.status) ?? "")).map(s => reviewSurfaceItem(context, s));
|
||||
const items = surfaces.filter(s => !statuses || statuses.includes(verdictOf(s) ?? "")).map(s => reviewSurfaceItem(context, s));
|
||||
const paged = page(items, params);
|
||||
if (!paged) return json({ error: "bad_request", message: `limit must be 1-${MAX_LIMIT} and cursor a non-negative integer` }, 400);
|
||||
return wantsMarkdown ? markdown(screensMarkdown(loaded, paged.items, paged.total)) : json(paged);
|
||||
@@ -1,11 +1,11 @@
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { copyFile, mkdir, lstat, readFile, realpath, writeFile } from "node:fs/promises";
|
||||
import { appendFile, copyFile, mkdir, lstat, readFile, realpath, writeFile } from "node:fs/promises";
|
||||
import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
||||
import { assertPublicReview, projectPublicReviewForReport } from "../contracts/review-validation.js";
|
||||
import { createHash } from "node:crypto";
|
||||
import type { ArtifactReport } from "../contracts/artifact-report.js";
|
||||
import { projectReviewPresentation } from "../contracts/review.js";
|
||||
import { renderPublicComment, platformSectionMerge, type PublicCommentState } from "./pr-comment-body.js";
|
||||
import { compareTitleMarkdown, projectReviewPresentation, type CompareReviewPresentation } from "../contracts/review.js";
|
||||
import { renderPublicComment, platformSectionMerge, reviewChangeCount, type PublicCommentState } from "./pr-comment-body.js";
|
||||
import type { ExplorePlatform } from "../config/explore-config.js";
|
||||
import { upsertStickyComment } from "./pr-comment.js";
|
||||
import { previewLinks, viewerLinks } from "./viewer-links.js";
|
||||
@@ -123,10 +123,11 @@ export async function publishCiReportComment(options: {
|
||||
previewFailed?: boolean;
|
||||
}) {
|
||||
const environment = options.environment ?? process.env; const transport = options.transport ?? fetch;
|
||||
const input = await readInput(options.inputPath); const review = input.publicReview; const pr = review.pullRequest;
|
||||
if (pr.origin === "compare") return publishCompareSummary(input, options, environment);
|
||||
if (!environment.GITHUB_TOKEN?.trim()) throw new CiError({ code: "GITHUB_TOKEN_MISSING", stage: "preflight",
|
||||
message: "GITHUB_TOKEN is required to publish the PR report comment",
|
||||
nextAction: "Pass GITHUB_TOKEN to the publish job with Actions read and PR comment write permissions." });
|
||||
const input = await readInput(options.inputPath); const review = input.publicReview; const pr = review.pullRequest;
|
||||
if (review.runId !== environment.GITHUB_RUN_ID || review.runAttempt !== environment.GITHUB_RUN_ATTEMPT
|
||||
|| (environment.GITHUB_REPOSITORY && environment.GITHUB_REPOSITORY !== pr.repository)) {
|
||||
throw new CiError({ code: "REPORT_RUN_MISMATCH", stage: "publication",
|
||||
@@ -196,3 +197,27 @@ export async function publishCiReportComment(options: {
|
||||
return { artifactUrl: links.viewer!.open, headSha: pr.head.sha, ...(links.preview ? { previewUrl: links.preview.open } : {}),
|
||||
...(previousBody !== undefined ? { previousBody } : {}) };
|
||||
}
|
||||
|
||||
/**
|
||||
* A comparison has no pull request to comment on: `ci:publish` links its report from the run summary instead,
|
||||
* with the same Open (central Viewer) and zip links a PR comment carries for this platform.
|
||||
*/
|
||||
async function publishCompareSummary(input: CiReportInput, options: { artifactUrl: string; platform?: ExplorePlatform }, environment: NodeJS.ProcessEnv) {
|
||||
const review = input.publicReview; const comparison = review.pullRequest as CompareReviewPresentation;
|
||||
if (review.runId !== environment.GITHUB_RUN_ID || review.runAttempt !== environment.GITHUB_RUN_ATTEMPT
|
||||
|| (environment.GITHUB_REPOSITORY && environment.GITHUB_REPOSITORY !== comparison.repository)) {
|
||||
throw new CiError({ code: "REPORT_RUN_MISMATCH", stage: "publication",
|
||||
message: "Report input is not from the current repository run and attempt",
|
||||
nextAction: "Publish the report-input.json produced by this repository's current workflow run and attempt." });
|
||||
}
|
||||
const links = viewerLinks({ repository: comparison.repository, headSha: comparison.head.sha, runId: review.runId,
|
||||
runAttempt: review.runAttempt, configPath: input.commentState.configPath, artifactUrl: options.artifactUrl,
|
||||
...(options.platform ? { platform: options.platform } : {}) });
|
||||
const changes = input.commentState.review ?? review;
|
||||
const count = reviewChangeCount({ review: changes }) ?? 0;
|
||||
const platform = (options.platform ?? review.runtime.platform) === "android" ? "Android" : "iOS";
|
||||
if (environment.GITHUB_STEP_SUMMARY) {
|
||||
await appendFile(environment.GITHUB_STEP_SUMMARY, `- ${platform} report of ${compareTitleMarkdown(comparison)}: [Open](${links.viewer!.open}) · [zip](${links.download!}) · ${count} ${count === 1 ? "change" : "changes"}\n`);
|
||||
}
|
||||
return { artifactUrl: links.viewer!.open, headSha: comparison.head.sha };
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { readFile, stat } from "node:fs/promises";
|
||||
import { createServer, type Server } from "node:http";
|
||||
import { extname, resolve, sep } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import type { ExplorePlatform } from "../config/explore-config.js";
|
||||
import { AGENT_API_VERSION, agentApiReply, agentIndexMarkdown, loadReport, prefersHtml, type AgentContext, type LoadedReport } from "./agent-api.js";
|
||||
|
||||
/**
|
||||
* Serve review reports on this machine the way a hosted report serves them: the built Viewer at `/p/<token>`, each
|
||||
* platform's report at `/p/<token>/report.zip?platform=…`, and the platform list at `/p/<token>/reports.json`. The
|
||||
* Viewer already knows this layout, so nothing in it changes. An agent on this machine gets what it gets from a hosted
|
||||
* link: the Markdown index when it fetches `/p/<token>` without asking for HTML, `/p/<token>/llms.txt`, and the JSON
|
||||
* API at `/p/<token>/api/v1/...` (agent-api.ts, shared with the hosted Worker). Loopback only; anything else answers 404.
|
||||
*/
|
||||
export type LocalReport = { platform: ExplorePlatform; zip: Uint8Array; changes?: number; device?: string };
|
||||
export type LocalReportServer = { server: Server; url: string; close: () => Promise<void> };
|
||||
|
||||
const TYPES: Record<string, string> = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8",
|
||||
".svg": "image/svg+xml", ".png": "image/png", ".woff2": "font/woff2", ".woff": "font/woff", ".json": "application/json; charset=utf-8", ".cur": "image/x-icon" };
|
||||
const BASE32 = "abcdefghijklmnopqrstuvwxyz234567";
|
||||
const AGENT_ROUTE = /^(?:\/llms\.txt|\/api\/v1(?:\/[A-Za-z0-9._:@-]{1,200}){0,2}\/?)$/;
|
||||
|
||||
export async function startLocalReportServer(options: { reports: LocalReport[]; port?: number; viewerRoot?: string; token?: string }): Promise<LocalReportServer> {
|
||||
if (!options.reports.length) throw new Error("There is no report to serve");
|
||||
const viewerRoot = resolve(options.viewerRoot ?? fileURLToPath(new URL("../viewer/", import.meta.url)));
|
||||
await stat(resolve(viewerRoot, "index.html"));
|
||||
const token = options.token ?? [...randomBytes(32)].map(byte => BASE32[byte % 32]).join("");
|
||||
const page = `/p/${token}`;
|
||||
const listing = JSON.stringify(options.reports.map(report => ({ platform: report.platform,
|
||||
...(report.changes === undefined ? {} : { changes: report.changes }), ...(report.device ? { device: report.device } : {}) })));
|
||||
const loaded = new Map<LocalReport, Promise<LoadedReport | undefined>>();
|
||||
let pageUrl = "";
|
||||
const server = createServer((request, response) => {
|
||||
void (async () => {
|
||||
const url = new URL(request.url ?? "/", "http://localhost");
|
||||
const send = (status: number, body: Uint8Array | string, type = "text/plain; charset=utf-8", headers: Record<string, string> = {}) => {
|
||||
response.writeHead(status, { "content-type": type, "cache-control": "no-store", "x-content-type-options": "nosniff", ...headers });
|
||||
response.end(body);
|
||||
};
|
||||
if (request.method !== "GET" && request.method !== "HEAD") return send(405, "Method not allowed");
|
||||
// `?platform=` picks one of several reports, the first otherwise; an unknown platform matches nothing.
|
||||
const platforms = url.searchParams.getAll("platform");
|
||||
const report = platforms.length > 1 ? undefined : platforms.length ? options.reports.find(candidate => candidate.platform === platforms[0]) : options.reports[0];
|
||||
const accept = request.headers.accept ?? null;
|
||||
const isPage = url.pathname === page || url.pathname === `${page}/`;
|
||||
const agentPath = url.pathname.startsWith(`${page}/`) ? url.pathname.slice(page.length) : "";
|
||||
if ((isPage && !prefersHtml(accept)) || AGENT_ROUTE.test(agentPath)) {
|
||||
if (!report) return send(404, "Not found");
|
||||
if (!loaded.has(report)) loaded.set(report, loadReport(report.zip));
|
||||
const content = await loaded.get(report);
|
||||
if (!content) return send(404, "Not found");
|
||||
const context: AgentContext = { pageUrl, platform: report.platform, platforms: options.reports.map(entry => entry.platform), expiresAt: null };
|
||||
const link = { link: `<${pageUrl}/api/${AGENT_API_VERSION}>; rel="alternate"; type="application/json", <${pageUrl}/llms.txt>; rel="alternate"; type="text/markdown"`, vary: "Accept" };
|
||||
if (isPage || agentPath === "/llms.txt") return send(200, agentIndexMarkdown(context, content), "text/markdown; charset=utf-8", link);
|
||||
const reply = await agentApiReply(context, content, agentPath.slice("/api/v1".length).replace(/\/$/, ""), url.searchParams, accept);
|
||||
const body = typeof reply.body === "string" ? reply.body : new Uint8Array(await new Response(reply.body).arrayBuffer());
|
||||
return send(reply.status, body, reply.contentType, { vary: "Accept", ...reply.headers });
|
||||
}
|
||||
if (isPage) return send(200, await readFile(resolve(viewerRoot, "index.html")), TYPES[".html"]);
|
||||
if (url.pathname === `${page}/report.zip`) return report ? send(200, report.zip, "application/zip") : send(404, "Not found");
|
||||
if (url.pathname === `${page}/reports.json` && options.reports.length > 1) return send(200, listing, TYPES[".json"]);
|
||||
// The Viewer's own assets, at the absolute paths its index.html names; never anything outside the build.
|
||||
if (/^\/(assets|fonts|cursors)\/[A-Za-z0-9._/-]+$/.test(url.pathname) || url.pathname === "/favicon.svg") {
|
||||
const file = resolve(viewerRoot, `.${url.pathname}`);
|
||||
if (!file.startsWith(viewerRoot + sep)) return send(404, "Not found");
|
||||
try { return send(200, await readFile(file), TYPES[extname(file)] ?? "application/octet-stream"); }
|
||||
catch { return send(404, "Not found"); }
|
||||
}
|
||||
send(404, "Not found");
|
||||
})().catch(() => { if (!response.headersSent) response.writeHead(500); response.end(); });
|
||||
});
|
||||
await new Promise<void>((done, fail) => { server.once("error", fail); server.listen(options.port ?? 0, "127.0.0.1", done); });
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("The local report server has no port");
|
||||
pageUrl = `http://127.0.0.1:${address.port}${page}`;
|
||||
return { server, url: pageUrl,
|
||||
close: () => new Promise<void>(done => server.close(() => done())) };
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { PublicReview } from "../contracts/capture.js";
|
||||
import type { SimulatorRuntimeMetadata } from "../capture/run.js";
|
||||
import { CI_COMMENT_MARKER } from "./pr-comment.js";
|
||||
import { CHANGE_GROUPS, foldRecord, historyLine, readCommentRecords, recordLine, recordSummary, type ChangeGroup, type CommentPlatform, type CommentRecords, type HistoryEntry, type PlatformRecord } from "./pr-comment-record.js";
|
||||
import { sourceImpactSentences } from "../contracts/source-change.js";
|
||||
import { CHANGE_GROUPS, changeCountText, foldRecord, strongerGroup, historyLine, readCommentRecords, recordLine, recordSummary, type ChangeGroup, type CommentPlatform, type CommentRecords, type HistoryEntry, type PlatformRecord } from "./pr-comment-record.js";
|
||||
import { isAccessibilityOnlyChange } from "../contracts/review-validation.js";
|
||||
import type { PublicCaptureHealth, PublicEvidenceSummary } from "../review/evidence-assessment.js";
|
||||
import type { ReviewPresentation } from "../contracts/review.js";
|
||||
import type { ViewerLinks } from "./viewer-links.js";
|
||||
@@ -60,8 +60,8 @@ const GROUP_LABEL: Record<ReviewGroup, string> = {
|
||||
added: "🟩 Added",
|
||||
modified: "🟧 Modified",
|
||||
removed: "🟥 Removed",
|
||||
"accessibility-only": "🟦 Accessibility only",
|
||||
"needs-review": "🟨 Needs review",
|
||||
"source-affected": "🟨 Source-affected",
|
||||
};
|
||||
|
||||
/** The body is HTML, so no blank lines are needed and the block keeps its natural spacing. */
|
||||
@@ -121,16 +121,32 @@ function plural(count: number, noun: string): string {
|
||||
|
||||
type Surface = PublicReview["surfaces"][number];
|
||||
|
||||
/** Evidence-based group when the run produced verdicts; otherwise the source-based status. */
|
||||
function groupOf(surface: Surface, evidenceBased: boolean): ReviewGroup | "unchanged" | "variant" {
|
||||
/**
|
||||
* The group a surface is listed under, from the run's verdicts. A screen without one (its source changed but no
|
||||
* screenshots were compared) is not listed: Explore reports what the captures show. A capture that failed is counted as
|
||||
* unavailable in the result and named under Validation instead.
|
||||
*/
|
||||
function groupOf(surface: Surface, evidenceBased: boolean): ReviewGroup | "unlisted" {
|
||||
if (surface.status === "added" || surface.status === "removed") return surface.status;
|
||||
const verified = (["base", "head"] as const).every(side => surface[`${side}Image`]
|
||||
&& surface[`${side}Outcome`]?.status === "captured" && surface[`${side}Outcome`]?.landing === "verified");
|
||||
if (evidenceBased && verified && surface.review && surface.visual?.reason !== "diff-failed") return surface.review.status;
|
||||
switch (surface.status) {
|
||||
case "modified": return "source-affected";
|
||||
case "unchanged": return "unchanged";
|
||||
if (evidenceBased && verified && surface.review && surface.visual?.reason !== "diff-failed") {
|
||||
const status = surface.review.status;
|
||||
if (status === "unchanged" || status === "variant") return "unlisted";
|
||||
return isAccessibilityOnlyChange(surface) ? "accessibility-only" : status;
|
||||
}
|
||||
return "unlisted";
|
||||
}
|
||||
|
||||
/**
|
||||
* A screen whose source changed and whose captures were both verified, but that has no verdict: the comparison did
|
||||
* not run or failed. Not a change, but not a screen that looks the same either, so the result says how many.
|
||||
*/
|
||||
function notComparedChange(surface: Surface): boolean {
|
||||
if (surface.status !== "modified" || (surface.head ?? surface.base)?.kind === "redirect") return false;
|
||||
const verified = (["base", "head"] as const).every(side => surface[`${side}Image`]
|
||||
&& surface[`${side}Outcome`]?.status === "captured" && surface[`${side}Outcome`]?.landing === "verified");
|
||||
return verified && (!surface.review || surface.visual?.reason === "diff-failed");
|
||||
}
|
||||
|
||||
function routeOf(surface: Surface): string {
|
||||
@@ -143,9 +159,6 @@ function descriptionOf(surface: Surface, group: ReviewGroup): string {
|
||||
if (group === "added") return `Added ${route} screen`;
|
||||
if (group === "removed") return `Removed ${route} screen`;
|
||||
// A group's own label already says added or removed; the route makes the line readable alone.
|
||||
if (group === "source-affected") {
|
||||
return sourceImpactSentences(surface.sourceImpact) ?? "Source-affected; not compared";
|
||||
}
|
||||
if (surface.review) return plainText(surface.review.description, MAX_DESCRIPTION_LENGTH);
|
||||
return "No visible change";
|
||||
}
|
||||
@@ -270,10 +283,12 @@ export function platformRecordOf(state: PublicCommentState, platform?: CommentPl
|
||||
for (const surface of state.review.surfaces) {
|
||||
if ((surface.head ?? surface.base)?.kind === "redirect") continue;
|
||||
const group = groupOf(surface, evidenceBased);
|
||||
if (group === "unchanged" || group === "variant") continue;
|
||||
if (group === "unlisted") continue;
|
||||
const scheme = schemeOf(surface.id);
|
||||
record.changes.push({ id: surface.id, route: routeOf(surface), group, description: descriptionOf(surface, group), ...(scheme ? { scheme } : {}) });
|
||||
}
|
||||
const notCompared = state.review.surfaces.filter(notComparedChange).length;
|
||||
if (notCompared) record.notCompared = notCompared;
|
||||
record.context = contextLines(state.review).filter(line => line.length);
|
||||
const diagnostics = [...(state.evidence?.diagnostics ?? [])];
|
||||
for (const surface of state.review.surfaces) {
|
||||
@@ -318,12 +333,12 @@ function resultCell(record: PlatformRecord): string {
|
||||
}
|
||||
case "failed": return `🟥 failed · ${inlineText(record.failure?.step ?? "capture", 48)}`;
|
||||
case "ready": {
|
||||
const changes = record.changes?.length ?? 0;
|
||||
const unavailable = record.health ? record.health.base.unavailable + record.health.head.unavailable : 0;
|
||||
const unverified = record.health ? record.health.base.unverified + record.health.head.unverified : 0;
|
||||
const failed = (record.validation?.visual?.failed ?? 0) + (record.validation?.accessibility?.failed ?? 0);
|
||||
const icon = unavailable || unverified || failed ? "🟨" : "🟩";
|
||||
return [`${icon} ${plural(changes, "change")}`, unavailable ? `${unavailable} unavailable` : undefined, unverified ? `${unverified} unattributed` : undefined,
|
||||
const notCompared = record.notCompared ?? 0;
|
||||
const icon = unavailable || unverified || failed || notCompared ? "🟨" : "🟩";
|
||||
return [`${icon} ${changeCountText(record.changes?.map(change => change.group) ?? [])}`, notCompared ? `${notCompared} not compared` : undefined, unavailable ? `${unavailable} unavailable` : undefined, unverified ? `${unverified} unattributed` : undefined,
|
||||
failed ? `${failed} comparison${failed === 1 ? "" : "s"} failed` : undefined, duration(record.startedAt, record.updatedAt)].filter(Boolean).join(" · ");
|
||||
}
|
||||
}
|
||||
@@ -363,6 +378,8 @@ function changeRows(records: PlatformRecord[]): Map<ReviewGroup, ChangeRow[]> {
|
||||
for (const change of record.changes ?? []) {
|
||||
const href = record.links.report ? surfaceLink(record.links.report, change.id) : undefined;
|
||||
const row = rows.get(change.id) ?? { id: change.id, route: change.route, group: change.group, description: change.description, perPlatform: {}, ...(change.scheme ? { scheme: change.scheme } : {}) };
|
||||
// A screen accessibility-only on one platform and visibly changed on another is listed as the visible change.
|
||||
if (strongerGroup(row.group, change.group) !== row.group) Object.assign(row, { group: change.group, description: change.description });
|
||||
row.perPlatform[record.platform] = { group: change.group, ...(href ? { href } : {}) };
|
||||
rows.set(change.id, row);
|
||||
}
|
||||
@@ -390,12 +407,14 @@ function changesSection(records: PlatformRecord[], platforms: CommentPlatform[],
|
||||
const lines: string[] = [];
|
||||
const total = [...groups.values()].reduce((sum, rows) => sum + rows.length, 0);
|
||||
lines.push(`**Changes** · ${plural(total, "screen")}${platforms.length > 1 && ready.length > 1 ? " · a screen is listed once, with a link per platform" : ""}`, "");
|
||||
if (total === 0) lines.push("No screen changed on the reviewed platforms.", "");
|
||||
// With screens left uncompared, nothing changed only among the ones compared.
|
||||
if (total === 0) lines.push(ready.some(record => record.notCompared) ? "No compared screen changed on the reviewed platforms." : "No screen changed on the reviewed platforms.", "");
|
||||
for (const group of GROUP_ORDER) {
|
||||
const rows = groups.get(group) ?? [];
|
||||
if (!rows.length) continue;
|
||||
const shown = rows.slice(0, rowCap);
|
||||
const content = ["", ...shown.map(row => renderChangeRow(row, platforms))];
|
||||
const content = ["", ...(group === "accessibility-only" ? ["Before and After look the same. What screen readers and voice control read changed.", ""] : []),
|
||||
...shown.map(row => renderChangeRow(row, platforms))];
|
||||
if (rows.length > shown.length) {
|
||||
const report = ready.find(record => record.links.report)?.links.report;
|
||||
content.push(`- ${rows.length - shown.length} more${report ? ` — ${link("Explore report", report)}` : ""}`);
|
||||
@@ -593,20 +612,41 @@ export function platformSectionMerge(state: PublicCommentState, platform: Commen
|
||||
}
|
||||
|
||||
/** "iPhone 17 Pro 26.0 · light + dark": the device model and OS version the report's head capture ran on, and its appearances when it captured several. */
|
||||
export function reviewDevice(state: PublicCommentState): string {
|
||||
export function reviewDevice(state: { runtime?: Pick<SimulatorRuntimeMetadata, "deviceModel" | "osVersion" | "colorSchemes"> | undefined }): string {
|
||||
const device = [state.runtime?.deviceModel, state.runtime?.osVersion && state.runtime.osVersion !== "unknown" ? state.runtime.osVersion : undefined].filter(Boolean).join(" ");
|
||||
const schemes = state.runtime?.colorSchemes;
|
||||
return schemes && schemes.length > 1 ? [device, schemes.join(" + ")].filter(Boolean).join(" · ") : device;
|
||||
}
|
||||
|
||||
/** Surfaces the review calls changed (reviewer verdicts first, raw status otherwise); undefined before the review exists. */
|
||||
export function reviewChangeCount(state: PublicCommentState): number | undefined {
|
||||
return state.review?.surfaces.filter(surface => surface.review ? surface.review.status !== "unchanged" && surface.review.status !== "variant"
|
||||
: surface.status !== "unchanged").length;
|
||||
/** Each changed surface's group, as the comment lists it: what a summary of the review counts. */
|
||||
export function reviewChanges(review: PublicReview): Map<string, ChangeGroup> {
|
||||
const evidenceBased = review.surfaces.some(surface => surface.review);
|
||||
const changes = new Map<string, ChangeGroup>();
|
||||
for (const surface of review.surfaces) {
|
||||
if ((surface.head ?? surface.base)?.kind === "redirect") continue;
|
||||
const group = groupOf(surface, evidenceBased);
|
||||
if (group !== "unlisted") changes.set(surface.id, group);
|
||||
}
|
||||
return changes;
|
||||
}
|
||||
|
||||
/** How many screens the comment lists as changed; undefined before the review exists. */
|
||||
export function reviewChangeCount(state: Pick<PublicCommentState, "review">): number | undefined {
|
||||
return state.review ? reviewChanges(state.review).size : undefined;
|
||||
}
|
||||
|
||||
export { recordSummary, readCommentRecords };
|
||||
|
||||
/** A surface's status in the local text summary, named as the comment groups it. */
|
||||
function localStatus(surface: Surface): string {
|
||||
if (isAccessibilityOnlyChange(surface)) return "accessibility only";
|
||||
if (surface.review) return surface.review.status;
|
||||
if (surface.status === "added" || surface.status === "removed") return surface.status;
|
||||
const failed = (["base", "head"] as const).some(side => surface[side]?.kind === "screen" && !surface[`${side}Image`]
|
||||
&& surface[`${side}Outcome`] && surface[`${side}Outcome`]?.status !== "captured");
|
||||
return failed ? "unavailable" : "not compared";
|
||||
}
|
||||
|
||||
function renderLocalText(state: PublicCommentState): string {
|
||||
const pr = state.pullRequest as Extract<ReviewPresentation, { origin: "local" }>;
|
||||
const counts = state.capture;
|
||||
@@ -618,6 +658,6 @@ function renderLocalText(state: PublicCommentState): string {
|
||||
...(counts && counts.planned.base + counts.planned.head === 0 ? ["No captures selected; visual comparison was not required.", ""] : []),
|
||||
...(state.review?.surfaces.filter(s => (s.status === "added" || s.status === "removed"
|
||||
|| s.baseOutcome || s.headOutcome || s.review) && s.review?.status !== "unchanged" && s.review?.status !== "variant").map(s =>
|
||||
`- ${inlineText((s.head ?? s.base)?.route ?? s.id, 160)}: ${s.review?.status ?? (s.status === "added" || s.status === "removed" ? s.status : "not compared")}${s.note ? ` — ${inlineText(s.note.text, 500)}` : ""}`) ?? []),
|
||||
`- ${inlineText((s.head ?? s.base)?.route ?? s.id, 160)}: ${localStatus(s)}${s.note ? ` — ${inlineText(s.note.text, 500)}` : ""}`) ?? []),
|
||||
"", ...(state.review ? contextLines(state.review) : []), "Report: artifacts/report.zip", "Details: README.md, agent-mode-cost.md, issues.md", ""].join("\n");
|
||||
}
|
||||
@@ -13,8 +13,32 @@ import { deflateRawSync, inflateRawSync } from "node:zlib";
|
||||
*/
|
||||
export type CommentPlatform = "ios" | "android";
|
||||
export type RecordPhase = "pending" | "capturing" | "ready" | "failed";
|
||||
export type ChangeGroup = "added" | "modified" | "removed" | "needs-review" | "source-affected";
|
||||
export const CHANGE_GROUPS: ChangeGroup[] = ["added", "removed", "modified", "needs-review", "source-affected"];
|
||||
/**
|
||||
* `accessibility-only`: modified, but the screenshots match; only what assistive technology reads changed. A screen
|
||||
* whose source changed but that was not compared is no group: Explore reports what the captures show, not what the code
|
||||
* might do.
|
||||
*/
|
||||
export type ChangeGroup = "added" | "modified" | "removed" | "accessibility-only" | "needs-review";
|
||||
export const CHANGE_GROUPS: ChangeGroup[] = ["added", "removed", "modified", "accessibility-only", "needs-review"];
|
||||
|
||||
/**
|
||||
* "12 changes", or "3 visual changes · 12 accessibility only" when some changed only for assistive technology: those
|
||||
* are changes too (screen readers and voice control see them), but not ones a screenshot shows.
|
||||
*/
|
||||
/**
|
||||
* The group of a screen that changed on several platforms. Accessibility only says the screenshots match, so it
|
||||
* yields to any other group; otherwise the first platform's group stands, as it always has.
|
||||
*/
|
||||
export function strongerGroup(first: ChangeGroup, other: ChangeGroup): ChangeGroup {
|
||||
return first === "accessibility-only" ? other : first;
|
||||
}
|
||||
|
||||
export function changeCountText(groups: readonly ChangeGroup[]): string {
|
||||
const accessibility = groups.filter(group => group === "accessibility-only").length;
|
||||
const visual = groups.length - accessibility;
|
||||
if (!accessibility) return `${visual} change${visual === 1 ? "" : "s"}`;
|
||||
return [visual ? `${visual} visual change${visual === 1 ? "" : "s"}` : undefined, `${accessibility} accessibility only`].filter(Boolean).join(" · ");
|
||||
}
|
||||
|
||||
export type SideHealth = { planned: number; captured: number; verified: number; unverified: number; unavailable: number };
|
||||
|
||||
@@ -41,6 +65,8 @@ export type PlatformRecord = {
|
||||
};
|
||||
/** The review's changed surfaces, one per surface; `scheme` for a secondary appearance (`<route>@<scheme>`). */
|
||||
changes?: { id: string; route: string; group: ChangeGroup; description: string; scheme?: string }[];
|
||||
/** Screens whose source changed and whose captures were verified, but that got no verdict: the comparison did not run or failed. */
|
||||
notCompared?: number;
|
||||
/** Differences stated once rather than per screen (variants, app-wide source changes). */
|
||||
context?: string[];
|
||||
diagnostics?: { side?: "base" | "head"; route: string; code: string; message: string; nextAction: string }[];
|
||||
@@ -166,6 +192,7 @@ export function parsePlatformRecord(value: unknown): PlatformRecord | undefined
|
||||
&& isString(entry.message) && isString(entry.nextAction)
|
||||
? [{ ...(isSide(entry.side) ? { side: entry.side } : {}), route: entry.route, code: entry.code, message: entry.message, nextAction: entry.nextAction }] : []).slice(0, 20);
|
||||
}
|
||||
if (isCount(value.notCompared) && value.notCompared > 0) record.notCompared = value.notCompared;
|
||||
if (isCount(value.diagnosticCount)) record.diagnosticCount = value.diagnosticCount;
|
||||
if (isRecord(value.failure) && isString(value.failure.step, 200) && isString(value.failure.message)) record.failure = { step: value.failure.step, message: value.failure.message };
|
||||
if (value.superseded === true) record.superseded = true;
|
||||
@@ -207,13 +234,12 @@ export function readCommentRecords(body: string | undefined): CommentRecords {
|
||||
|
||||
/** A short result for a run that is no longer current: "🟩 34 changes", "🟨 12 changes · 4 unavailable", "🟥 failed · capture". */
|
||||
export function recordSummary(record: PlatformRecord): string {
|
||||
const changes = record.changes?.length;
|
||||
switch (record.phase) {
|
||||
case "failed": return `🟥 failed · ${record.failure?.step ?? "capture"}`;
|
||||
case "ready": {
|
||||
const unavailable = record.health ? record.health.base.unavailable + record.health.head.unavailable : 0;
|
||||
const icon = unavailable > 0 || (record.validation?.visual?.failed ?? 0) > 0 ? "🟨" : "🟩";
|
||||
return `${icon} ${changes ?? 0} change${changes === 1 ? "" : "s"}${unavailable > 0 ? ` · ${unavailable} unavailable` : ""}`;
|
||||
const icon = unavailable > 0 || (record.validation?.visual?.failed ?? 0) > 0 || record.notCompared ? "🟨" : "🟩";
|
||||
return `${icon} ${changeCountText(record.changes?.map(change => change.group) ?? [])}${unavailable > 0 ? ` · ${unavailable} unavailable` : ""}${record.notCompared ? ` · ${record.notCompared} not compared` : ""}`;
|
||||
}
|
||||
default: return "⏳ did not finish";
|
||||
}
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
import { createCipheriv, createHash, randomBytes } from "node:crypto";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { cp, lstat, mkdir, mkdtemp, readdir, readFile, realpath, rm, writeFile } from "node:fs/promises";
|
||||
import { appendFile, cp, lstat, mkdir, mkdtemp, readdir, readFile, realpath, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, relative, resolve, sep } from "node:path";
|
||||
import { Uint8ArrayReader, Uint8ArrayWriter, ZipWriter, configure } from "@zip.js/zip.js";
|
||||
import { MAX_METADATA_BYTES } from "./agent-api.js";
|
||||
import { publishCiReportComment, readCiReportInput, type CiReportInput } from "./artifact.js";
|
||||
import { readZipDirectory, readZipEntry } from "./zip-reader.js";
|
||||
import { reviewChangeCount, reviewDevice } from "./pr-comment-body.js";
|
||||
import type { ExplorePlatform } from "../config/explore-config.js";
|
||||
import type { ArtifactReport } from "../contracts/artifact-report.js";
|
||||
import { normalizePublicReviewForReading } from "../contracts/review-validation.js";
|
||||
import { EXPLORATION_REPORT_KIND, type ExplorationReport } from "../contracts/standalone-report.js";
|
||||
import { compareTitleMarkdown, type CompareReviewPresentation } from "../contracts/review.js";
|
||||
import { CiError, toCiError } from "../shared/ci-errors.js";
|
||||
import { TOOL_ROOT, packageBin } from "../shared/package-paths.js";
|
||||
|
||||
@@ -63,12 +69,15 @@ export type PreviewDeployResult = {
|
||||
reportBytes: number;
|
||||
reports: Array<{ platform?: ExplorePlatform; artifactUrl: string; reportSha256: string; reportBytes: number }>;
|
||||
headSha: string;
|
||||
/** A comparison's link is in the run summary only: callers must not print previewUrl, which is unmasked for it. */
|
||||
linkedFromRunSummary?: true;
|
||||
};
|
||||
|
||||
export const PREVIEW_EXPORT_PATH = join(TOOL_ROOT, "dist", "hosting-preview");
|
||||
const CIPHER_AAD = "expo-explore-preview/1";
|
||||
const BASE32 = "abcdefghijklmnopqrstuvwxyz234567";
|
||||
const MAX_REPORT_BYTES = 256 * 1024 * 1024;
|
||||
/** The largest report ZIP a hosted preview serves. */
|
||||
export const MAX_REPORT_BYTES = 256 * 1024 * 1024;
|
||||
const ZIP_DATE = new Date("2000-01-01T00:00:00Z");
|
||||
|
||||
function base32(bytes: Uint8Array): string {
|
||||
@@ -154,6 +163,54 @@ export async function zipReportDirectory(reportPath: string): Promise<Uint8Array
|
||||
return writer.close();
|
||||
}
|
||||
|
||||
/** What a report ZIP holds, from its review.json or exploration.json: where to host it and how the platform switch labels it. */
|
||||
export type ReportZipSummary = { platform: ExplorePlatform; changes?: number; device?: string }
|
||||
& ({ kind: "review"; repository: string; runId: string; base: string; head: string } | { kind: "exploration" });
|
||||
|
||||
/**
|
||||
* Reads a report ZIP as `zipReportDirectory` writes it (or GitHub's download of a report artifact): one report file and
|
||||
* its assets, nothing else. It uses the hosted reader (zip-reader.ts) with its limits, so a ZIP accepted here is one a
|
||||
* hosted or local Viewer link can serve, and a crafted one cannot inflate past them.
|
||||
*/
|
||||
export async function readReportZip(zip: Uint8Array): Promise<ReportZipSummary> {
|
||||
if (zip.byteLength > MAX_REPORT_BYTES) throw new Error("Report exceeds the 256 MiB hosted preview limit");
|
||||
const entries = readZipDirectory(zip);
|
||||
if (!entries) throw new Error("Not a ZIP archive a hosted report can read");
|
||||
const names = [...entries.keys()].filter(name => !name.endsWith("/"));
|
||||
const reportFile = REPORT_FILE_NAMES.find(name => names.includes(name));
|
||||
if (!reportFile || names.some(name => name !== reportFile && !/^assets\/[a-f0-9]{64}\.(png|mp4)$/.test(name))) {
|
||||
throw new Error("A report ZIP must contain review.json (or exploration.json) and assets/<sha256>.png or .mp4 only");
|
||||
}
|
||||
const bytes = await readZipEntry(zip, entries.get(reportFile)!, MAX_METADATA_BYTES);
|
||||
if (!bytes) throw new Error(`${reportFile} is unreadable or larger than ${MAX_METADATA_BYTES / 1024 / 1024} MiB`);
|
||||
const report = JSON.parse(new TextDecoder().decode(bytes));
|
||||
if (reportFile === "exploration.json") {
|
||||
const exploration = (report as Partial<ExplorationReport>).exploration;
|
||||
if (report?.kind !== EXPLORATION_REPORT_KIND || !exploration || (exploration.app?.platform !== "ios" && exploration.app?.platform !== "android")) {
|
||||
throw new Error("exploration.json is not an Explore exploration report");
|
||||
}
|
||||
return { kind: "exploration", platform: exploration.app.platform, device: `${exploration.device.model} ${exploration.device.osVersion}`.trim() };
|
||||
}
|
||||
const review = (report as Partial<ArtifactReport>).review;
|
||||
const pr = review?.pullRequest;
|
||||
// Reports from before Android support carry no platform; they are all iOS.
|
||||
const platform = review?.runtime?.platform ?? "ios";
|
||||
if (report?.kind !== "explore.report" || !review || !pr || (platform !== "ios" && platform !== "android")) {
|
||||
throw new Error("review.json is not an Explore review report");
|
||||
}
|
||||
// What the CLI later hands to git and shows in a terminal: full SHAs and plain text, or the ZIP is not a report.
|
||||
const sha = (value: unknown) => typeof value === "string" && /^[0-9a-f]{40}$/i.test(value);
|
||||
const text = (value: unknown) => typeof value === "string" && value.length > 0 && value.length <= 1000;
|
||||
if (!sha(pr.head?.sha) || !sha(pr.base?.sha) || !text(pr.head?.ref) || !text(pr.base?.ref) || !text(pr.repository) || !text(pr.title) || !text(review.runId)) {
|
||||
throw new Error("review.json does not name its repository, title and commits as a report does");
|
||||
}
|
||||
const changes = reviewChangeCount({ review: normalizePublicReviewForReading(review) });
|
||||
const device = reviewDevice({ runtime: { deviceModel: review.runtime?.device?.model ?? "", osVersion: review.runtime?.device?.osVersion ?? "",
|
||||
...(review.runtime?.colorSchemes ? { colorSchemes: review.runtime.colorSchemes } : {}) } });
|
||||
return { kind: "review", platform, repository: pr.repository, runId: review.runId, base: pr.base.sha, head: pr.head.sha,
|
||||
...(changes === undefined ? {} : { changes }), ...(device ? { device } : {}) };
|
||||
}
|
||||
|
||||
/** iv (12 bytes) || AES-256-GCM ciphertext || tag, authenticated with the preview AAD; what the Worker decrypts. */
|
||||
export function sealReport(plain: Uint8Array, key: Uint8Array, iv: Uint8Array): Uint8Array {
|
||||
const cipher = createCipheriv("aes-256-gcm", key, iv);
|
||||
@@ -179,11 +236,21 @@ type SealedReport = { entry: PreviewReportInput; input: CiReportInput; zip: Uint
|
||||
|
||||
function previewError(code: string, message: string, nextAction: string): CiError { return new CiError({ code, stage: "preflight", message, nextAction }); }
|
||||
|
||||
/** A device label for the platform switch, safe in the sealed .env: no `#` (a dotenv comment), markup or control characters, and short. */
|
||||
/**
|
||||
* A device label for the platform switch, safe in the sealed .env: letters, digits and a few separators only. `eas
|
||||
* deploy` reads that file with variable expansion, so a `$` (even single-quoted) would pull the deploying process's
|
||||
* environment into the label, and a `#` or a backslash would cut or corrupt the JSON around it.
|
||||
*/
|
||||
function listingDevice(device: string): string {
|
||||
return device.replace(/[^\p{L}\p{N} .,()+·_:/-]/gu, "").replace(/\s+/g, " ").trim().slice(0, 120);
|
||||
}
|
||||
|
||||
/** The worker's EXPLORE_PREVIEW_REPORTS entries, in the order the workflow lists platforms; also what reports.json must echo. */
|
||||
export function previewReportListing(reports: ReadonlyArray<Pick<SealedReport, "entry" | "input" | "file">>, reportDirectory: string) {
|
||||
return reports.map(report => {
|
||||
const changes = reviewChangeCount(report.input.commentState);
|
||||
const device = reviewDevice(report.input.commentState).replace(/[#<>\u0000-\u001f\u007f]/g, "").trim().slice(0, 120);
|
||||
const device = listingDevice(reviewDevice(report.input.commentState));
|
||||
return { platform: report.entry.platform!, path: `/_report/${reportDirectory}/${report.file}`,
|
||||
...(changes === undefined ? {} : { changes }), ...(device ? { device } : {}) };
|
||||
});
|
||||
@@ -212,8 +279,8 @@ export async function deployPreview(options: PreviewDeployOptions): Promise<Prev
|
||||
if (pr.origin === "local") throw new Error("Local reports cannot be deployed as hosted previews");
|
||||
for (const { input } of inputs.slice(1)) {
|
||||
const other = input.publicReview;
|
||||
if (!input.preview || other.pullRequest.origin === "local" || other.pullRequest.repository !== pr.repository || other.pullRequest.number !== pr.number
|
||||
|| other.pullRequest.head.sha !== pr.head.sha || other.runId !== review.runId || other.runAttempt !== review.runAttempt) {
|
||||
if (!input.preview || other.pullRequest.origin !== pr.origin || other.pullRequest.repository !== pr.repository || other.pullRequest.number !== pr.number
|
||||
|| other.pullRequest.head.sha !== pr.head.sha || other.pullRequest.base.sha !== pr.base.sha || other.runId !== review.runId || other.runAttempt !== review.runAttempt) {
|
||||
throw previewError("PREVIEW_REPORTS_MISMATCH", "The platform reports do not come from the same review run", "Deploy only the reports this workflow run produced for the same PR head.");
|
||||
}
|
||||
}
|
||||
@@ -240,11 +307,14 @@ export async function deployPreview(options: PreviewDeployOptions): Promise<Prev
|
||||
reportDirectory, ...(listing ? { listing } : {}), project, ...(first.preview.owner ? { owner: first.preview.owner } : {}),
|
||||
ownerHint: "Set report.preview.owner in .expo-explore/config.yaml to the account that should hold the preview project.",
|
||||
projectHint: "Give EXPO_TOKEN's account permission to create projects, or set report.preview.project to an existing project it can deploy to.",
|
||||
expiresAt, exportPath, environment, run, transport, now, random, ...(options.sleep ? { sleep: options.sleep } : {}), ...(options.onSecret ? { onSecret: options.onSecret } : {}),
|
||||
expiresAt, exportPath, environment, run, transport, now, random, ...(options.sleep ? { sleep: options.sleep } : {}),
|
||||
// The runner masks secrets in job summaries too, so a masked token would reach a comparison's summary as ***.
|
||||
// Its link appears nowhere else (not in the log), as a PR's appears only in its comment, for the same readers.
|
||||
...(options.onSecret && pr.origin !== "compare" ? { onSecret: options.onSecret } : {}),
|
||||
verifyTimeoutMs: options.verifyTimeoutMs ?? 180_000 });
|
||||
} catch (error) {
|
||||
// The report job's comment says the report is deploying; it must now offer the download-and-drop flow instead.
|
||||
for (const report of reports) {
|
||||
if (pr.origin !== "compare") for (const report of reports) {
|
||||
try {
|
||||
await publishCiReportComment({ inputPath: report.entry.inputPath, artifactUrl: report.entry.artifactUrl, environment, transport,
|
||||
...(report.entry.platform ? { platform: report.entry.platform } : {}), previewFailed: true });
|
||||
@@ -253,9 +323,11 @@ export async function deployPreview(options: PreviewDeployOptions): Promise<Prev
|
||||
throw error;
|
||||
}
|
||||
const previewUrl = hosted.previewUrl;
|
||||
// A comparison has no pull request: its link goes to the run's summary, which the same repository readers see.
|
||||
if (pr.origin === "compare") await writeCompareSummary(environment, pr, previewUrl, expiresAt, reports.map(report => report.input));
|
||||
{
|
||||
let headSha = pr.head.sha;
|
||||
for (const report of reports) {
|
||||
if (pr.origin !== "compare") for (const report of reports) {
|
||||
const published = await publishCiReportComment({ inputPath: report.entry.inputPath, artifactUrl: report.entry.artifactUrl, environment, transport,
|
||||
...(report.entry.platform ? { platform: report.entry.platform } : {}), preview: { url: previewUrl, expiresAt } });
|
||||
headSha = published.headSha;
|
||||
@@ -263,10 +335,30 @@ export async function deployPreview(options: PreviewDeployOptions): Promise<Prev
|
||||
return { previewUrl, expiresAt: expiresAt === null ? null : new Date(expiresAt).toISOString(), deploymentId: hosted.deploymentId, deploymentUrl: hosted.deploymentUrl,
|
||||
project, owner: hosted.owner, reportSha256: reports[0]!.sha256, reportBytes: reports[0]!.zip.byteLength,
|
||||
reports: reports.map(report => ({ ...(report.entry.platform ? { platform: report.entry.platform } : {}), artifactUrl: report.entry.artifactUrl,
|
||||
reportSha256: report.sha256, reportBytes: report.zip.byteLength })), headSha };
|
||||
reportSha256: report.sha256, reportBytes: report.zip.byteLength })), headSha,
|
||||
...(pr.origin === "compare" ? { linkedFromRunSummary: true as const } : {}) };
|
||||
}
|
||||
}
|
||||
|
||||
/** The comparison's job summary: what was compared, the hosted link, and each platform's change count. */
|
||||
export function renderCompareSummary(comparison: CompareReviewPresentation, previewUrl: string, expiresAt: number | null, inputs: CiReportInput[]): string {
|
||||
const platforms = inputs.map(input => {
|
||||
const changes = reviewChangeCount(input.commentState);
|
||||
const device = reviewDevice(input.commentState);
|
||||
return `- ${input.publicReview.runtime.platform === "android" ? "Android" : "iOS"}${device ? ` (${device})` : ""}: ${changes === undefined ? "no review" : `${changes} ${changes === 1 ? "change" : "changes"}`}`;
|
||||
});
|
||||
return [`### Explore: ${compareTitleMarkdown(comparison)}`, "",
|
||||
`[Open the report](${previewUrl}) · [${comparison.base.sha.slice(0, 8)}..${comparison.head.sha.slice(0, 8)}](${comparison.url})`
|
||||
+ (expiresAt === null ? "" : ` · link expires ${new Date(expiresAt).toISOString().slice(0, 10)}`), "",
|
||||
...platforms, ""].join("\n");
|
||||
}
|
||||
|
||||
async function writeCompareSummary(environment: NodeJS.ProcessEnv, comparison: CompareReviewPresentation, previewUrl: string, expiresAt: number | null, inputs: CiReportInput[]) {
|
||||
const path = environment.GITHUB_STEP_SUMMARY;
|
||||
if (!path) return;
|
||||
await appendFile(path, renderCompareSummary(comparison, previewUrl, expiresAt, inputs));
|
||||
}
|
||||
|
||||
type HostedReportInput = { zip: Uint8Array; sha256: string; file: string; query: string };
|
||||
export type HostedDeployment = { previewUrl: string; expiresAt: string | null; deploymentId: string; deploymentUrl: string; aliasUrl?: string; project: string; owner: string };
|
||||
|
||||
@@ -316,11 +408,13 @@ async function deploySealedReports(options: {
|
||||
|
||||
const who = run(process.execPath, [eas, "whoami"], { cwd: work, env: easEnvironment });
|
||||
const accounts = who.status === 0 ? whoamiAccounts(who.stdout) : [];
|
||||
if (!accounts.length) throw deployError("EAS_NOT_AUTHENTICATED", "The EAS CLI could not sign in with EXPO_TOKEN.",
|
||||
"Use a valid EXPO_TOKEN for a robot user of the app's Expo account.", { details: { stderr: lastLine(who.stderr) } });
|
||||
// On a laptop without EXPO_TOKEN the deploy uses your `eas login`, and the messages say so.
|
||||
const login = environment.EXPO_TOKEN?.trim() ? "EXPO_TOKEN" : "Your EAS login";
|
||||
if (!accounts.length) throw deployError("EAS_NOT_AUTHENTICATED", login === "EXPO_TOKEN" ? "The EAS CLI could not sign in with EXPO_TOKEN." : "You are not logged in to EAS.",
|
||||
login === "EXPO_TOKEN" ? "Use a valid EXPO_TOKEN for a robot user of the app's Expo account." : "Run eas login (or set EXPO_TOKEN), then rerun.", { details: { stderr: lastLine(who.stderr) } });
|
||||
const owner = options.owner ?? (accounts.length === 1 ? accounts[0]! : undefined);
|
||||
if (!owner || !accounts.includes(owner)) throw deployError("PREVIEW_OWNER_AMBIGUOUS",
|
||||
owner ? `EXPO_TOKEN has no access to the Expo account ${owner}.` : `EXPO_TOKEN can deploy to several Expo accounts: ${accounts.join(", ")}.`,
|
||||
owner ? `${login} has no access to the Expo account ${owner}.` : `${login} can deploy to several Expo accounts: ${accounts.join(", ")}.`,
|
||||
options.ownerHint, { details: { accounts } });
|
||||
await writeFile(join(work, "package.json"), JSON.stringify({ name: project, version: "0.0.0", private: true }));
|
||||
await writeFile(join(work, "app.json"), JSON.stringify({ expo: { name: `${project}`, slug: project, owner, web: { output: "server" } } }));
|
||||
@@ -396,6 +490,8 @@ async function deploySealedReports(options: {
|
||||
export type ExplorationDeployOptions = {
|
||||
/** The `explore:binary` report directory (exploration.json plus assets/). */
|
||||
reportPath: string;
|
||||
/** The explored app's platform, listed so the Worker does not take the report for iOS. */
|
||||
platform?: ExplorePlatform;
|
||||
project: string;
|
||||
owner?: string;
|
||||
/** Days until the hosted link stops serving the report; null never expires. */
|
||||
@@ -431,7 +527,10 @@ export async function deployExplorationReport(options: ExplorationDeployOptions)
|
||||
const random = options.random ?? (bytes => new Uint8Array(randomBytes(bytes)));
|
||||
const now = options.now ?? Date.now;
|
||||
const sha256 = createHash("sha256").update(zip).digest("hex");
|
||||
const hosted = await deploySealedReports({ reports: [{ zip, sha256, file: "report.zip.enc", query: "" }], reportDirectory: base32(random(10)), project: options.project,
|
||||
const reportDirectory = base32(random(10));
|
||||
const file = options.platform ? `${options.platform}.zip.enc` : "report.zip.enc";
|
||||
const hosted = await deploySealedReports({ reports: [{ zip, sha256, file, query: options.platform ? `?platform=${options.platform}` : "" }], reportDirectory,
|
||||
...(options.platform ? { listing: [{ platform: options.platform, path: `/_report/${reportDirectory}/${file}` }] } : {}), project: options.project,
|
||||
...(options.owner ? { owner: options.owner } : {}), ownerHint: "Pass --owner with the Expo account that should host the report.",
|
||||
projectHint: "Give this EAS login permission to create projects under the owner, or pass --project with an existing slug.",
|
||||
expiresAt: options.expiresAfterDays === null ? null : now() + options.expiresAfterDays * 86_400_000, exportPath, environment, run: options.run ?? defaultRun, ...(options.sleep ? { sleep: options.sleep } : {}),
|
||||
@@ -492,6 +591,43 @@ export async function deployFixturePreview(options: FixturePreviewOptions): Prom
|
||||
...(options.token ? { token: options.token } : {}) });
|
||||
}
|
||||
|
||||
/**
|
||||
* Report ZIPs on this machine behind one token (`capture:review --upload`, `report:upload`), one per platform: the same
|
||||
* sealed deployment as a PR preview, from ZIPs instead of GitHub artifacts, with the local EAS login or EXPO_TOKEN.
|
||||
*/
|
||||
export async function deployLocalReports(options: {
|
||||
reports: Array<{ platform: ExplorePlatform; zip: Uint8Array; changes?: number; device?: string }>;
|
||||
project: string; owner?: string; expiresAfterDays: number | null;
|
||||
/** What to change when the owner or project is not usable; defaults name report.preview in config.yaml. */
|
||||
ownerHint?: string; projectHint?: string;
|
||||
exportPath?: string; environment?: NodeJS.ProcessEnv; run?: CommandRunner; sleep?: (milliseconds: number) => Promise<void>;
|
||||
transport?: typeof fetch; now?: () => number; random?: (bytes: number) => Uint8Array; verifyTimeoutMs?: number;
|
||||
}): Promise<HostedDeployment> {
|
||||
const environment = options.environment ?? process.env;
|
||||
if (!options.reports.length || new Set(options.reports.map(report => report.platform)).size !== options.reports.length) {
|
||||
throw previewError("PREVIEW_REPORTS_INVALID", "A local upload needs one report per platform", "Capture each platform once, then upload.");
|
||||
}
|
||||
const exportPath = resolve(options.exportPath ?? PREVIEW_EXPORT_PATH);
|
||||
await assertExport(exportPath);
|
||||
const now = options.now ?? Date.now;
|
||||
const random = options.random ?? (bytes => new Uint8Array(randomBytes(bytes)));
|
||||
const reportDirectory = base32(random(10));
|
||||
// Always listed, even alone: the Worker takes an unlisted report for iOS, so an Android one would be mislabelled.
|
||||
const reports = options.reports.map(report => ({ ...report, sha256: createHash("sha256").update(report.zip).digest("hex"), file: `${report.platform}.zip.enc` }));
|
||||
const listing = reports.map(report => {
|
||||
const device = report.device ? listingDevice(report.device) : "";
|
||||
return { platform: report.platform, path: `/_report/${reportDirectory}/${report.file}`, ...(report.changes === undefined ? {} : { changes: report.changes }), ...(device ? { device } : {}) };
|
||||
});
|
||||
return deploySealedReports({
|
||||
reports: reports.map(report => ({ zip: report.zip, sha256: report.sha256, file: report.file, query: `?platform=${report.platform}` })),
|
||||
reportDirectory, listing, project: options.project, ...(options.owner ? { owner: options.owner } : {}),
|
||||
ownerHint: options.ownerHint ?? "Set report.preview.owner in .expo-explore/config.yaml to the account that should hold the hosted reports.",
|
||||
projectHint: options.projectHint ?? "Make sure your Expo account can create projects, or set report.preview.project to an existing project you can deploy to.",
|
||||
expiresAt: options.expiresAfterDays === null ? null : now() + options.expiresAfterDays * 86_400_000, exportPath, environment,
|
||||
run: options.run ?? defaultRun, ...(options.sleep ? { sleep: options.sleep } : {}), transport: options.transport ?? fetch, now, random,
|
||||
verifyTimeoutMs: options.verifyTimeoutMs ?? 180_000 });
|
||||
}
|
||||
|
||||
const ARTIFACT_DIRECTORY = /^explore-(capture|review)-\d+-\d+-(ios|android)$/;
|
||||
|
||||
/**
|
||||
@@ -591,10 +727,12 @@ async function verifyDeployment(check: { origin: string; token: string; reports:
|
||||
"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`;
|
||||
for (const path of ["/", `/p/${other}`, `/p/${other}/report.zip`, `/p/${check.token}/viewer/index.html`]) {
|
||||
// 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"],
|
||||
[`/p/${check.token}/viewer/index.html`, "/p/<token>/viewer/index.html"]] as const) {
|
||||
const response = await get(path);
|
||||
if (response.status !== 404) throw deployError("PREVIEW_VERIFY_FAILED", `The hosted preview answered HTTP ${response.status} without a valid token at ${path}.`,
|
||||
"Do not share this deployment; delete it in the EAS Hosting dashboard and report the issue to Explore.", { details: { path, status: response.status } });
|
||||
if (response.status !== 404) throw deployError("PREVIEW_VERIFY_FAILED", `The hosted preview answered HTTP ${response.status} without a valid token at ${shape}.`,
|
||||
"Do not share this deployment; delete it in the EAS Hosting dashboard and report the issue to Explore.", { details: { path: shape, status: response.status } });
|
||||
}
|
||||
return { liveAfterMs };
|
||||
}
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
import { createHash, randomBytes } from "node:crypto";
|
||||
import { lstat, mkdir, readdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import type { ExplorePlatform } from "../config/explore-config.js";
|
||||
import type { ArtifactReport } from "../contracts/artifact-report.js";
|
||||
import { EXPLORATION_REPORT_KIND, type ExplorationReport } from "../contracts/standalone-report.js";
|
||||
import { exploreCacheRoot } from "../shared/cache-root.js";
|
||||
import { MAX_METADATA_BYTES } from "./agent-api.js";
|
||||
import { normalizePublicReviewForReading } from "../contracts/review-validation.js";
|
||||
import { reviewChanges, reviewDevice } from "./pr-comment-body.js";
|
||||
import { strongerGroup, type ChangeGroup } from "./pr-comment-record.js";
|
||||
import { readZipDirectory, readZipEntry } from "./zip-reader.js";
|
||||
|
||||
/**
|
||||
* Every report a run produces on this machine is kept under `<cache>/reports/<id>/`: one `<platform>.zip` per platform
|
||||
* (the same ZIP a hosted or local Viewer serves) and `run.json`, what `expo-explore reports` lists. Local reviews,
|
||||
* explorations and uploaded reports land here, so a past run can be reopened or hosted without capturing it again.
|
||||
* Runs older than 30 days, and the oldest beyond 2 GB, are pruned whenever a run is saved.
|
||||
*/
|
||||
export type SavedCommit = { ref: string; sha: string; subject?: string };
|
||||
export type SavedRun = {
|
||||
version: 1;
|
||||
id: string;
|
||||
kind: "local" | "pull-request" | "compare" | "exploration";
|
||||
title: string;
|
||||
repository?: string;
|
||||
number?: number;
|
||||
head?: SavedCommit;
|
||||
base?: SavedCommit;
|
||||
/** A local review of uncommitted changes: how many files differed from HEAD. */
|
||||
uncommittedFiles?: number;
|
||||
platforms: ExplorePlatform[];
|
||||
device?: string;
|
||||
/** Changed surfaces by group across the platforms, as the PR comment counts them. */
|
||||
changes?: Partial<Record<ChangeGroup, number>>;
|
||||
explored?: { app: string; version?: string; buildNumber?: string; screens: number; unexplored: number };
|
||||
/** When the run happened, from its report. */
|
||||
createdAt: string;
|
||||
/** When it was kept here; pruning goes by this, so an old report saved today stays for the full period. */
|
||||
savedAt: string;
|
||||
bytes: number;
|
||||
};
|
||||
export type SavedReport = { platform: ExplorePlatform; zip: Uint8Array; changes?: number; device?: string };
|
||||
|
||||
export const SAVED_RUN_LIMITS = { maxAgeDays: 30, maxBytes: 2 * 1024 * 1024 * 1024 } as const;
|
||||
const ID = /^[a-z0-9][a-z0-9._-]{0,119}$/;
|
||||
|
||||
export function savedRunsDirectory(environment: NodeJS.ProcessEnv = process.env): string {
|
||||
return join(exploreCacheRoot(environment), "reports");
|
||||
}
|
||||
|
||||
const slug = (value: string, max: number) => value.toLowerCase().replace(/[^a-z0-9._-]+/g, "-").replace(/^[-.]+|[-.]+$/g, "").slice(0, max).replace(/[-.]+$/, "") || "run";
|
||||
|
||||
/** Text from a report or a commit, as a terminal may print it: no control characters (C0, DEL, C1), so no escape sequences. */
|
||||
export function plainText(value: string): string {
|
||||
return value.replace(/[\u0000-\u001f\u007f-\u009f]/g, "");
|
||||
}
|
||||
|
||||
/** A run with every string a report or a commit supplied made plain, including runs saved before this was enforced. */
|
||||
export function cleanRun(run: SavedRun): SavedRun {
|
||||
const commit = (side?: SavedCommit) => side && { ...side, ref: plainText(side.ref), ...(side.subject === undefined ? {} : { subject: plainText(side.subject) }) };
|
||||
return { ...run, title: plainText(run.title), ...(run.repository === undefined ? {} : { repository: plainText(run.repository) }),
|
||||
...(run.head ? { head: commit(run.head)! } : {}), ...(run.base ? { base: commit(run.base)! } : {}), ...(run.device === undefined ? {} : { device: plainText(run.device) }),
|
||||
...(run.explored ? { explored: { ...run.explored, app: plainText(run.explored.app), ...(run.explored.version ? { version: plainText(run.explored.version) } : {}),
|
||||
...(run.explored.buildNumber ? { buildNumber: plainText(run.explored.buildNumber) } : {}) } } : {}) };
|
||||
}
|
||||
|
||||
async function reportJson(zip: Uint8Array): Promise<{ file: "review.json" | "exploration.json"; json: unknown } | undefined> {
|
||||
const entries = readZipDirectory(zip);
|
||||
const file = entries?.has("review.json") ? "review.json" : entries?.has("exploration.json") ? "exploration.json" : undefined;
|
||||
if (!entries || !file) return undefined;
|
||||
const bytes = await readZipEntry(zip, entries.get(file)!, MAX_METADATA_BYTES);
|
||||
if (!bytes) return undefined;
|
||||
try { return { file, json: JSON.parse(new TextDecoder().decode(bytes)) }; } catch { return undefined; }
|
||||
}
|
||||
|
||||
/**
|
||||
* What a run's report ZIPs say about it: its kind, title, commits, platforms and changes. Commit subjects are not in
|
||||
* the reports; the caller adds them when it has the repository (`subjects`).
|
||||
*/
|
||||
export async function describeReports(reports: SavedReport[], extra: { subjects?: { head?: string; base?: string }; uncommittedFiles?: number; createdAt?: string } = {}):
|
||||
Promise<Omit<SavedRun, "version" | "bytes" | "savedAt">> {
|
||||
const parsed = await Promise.all(reports.map(async report => ({ report, content: await reportJson(report.zip) })));
|
||||
const first = parsed[0]?.content;
|
||||
if (!first) throw new Error("Not an Explore report ZIP");
|
||||
const createdAt = extra.createdAt ?? new Date().toISOString();
|
||||
const platforms = parsed.map(entry => entry.report.platform);
|
||||
if (first.file === "exploration.json") {
|
||||
const report = first.json as Partial<ExplorationReport>;
|
||||
if (report.kind !== EXPLORATION_REPORT_KIND || !report.exploration || !report.map) throw new Error("Not an Explore exploration report");
|
||||
const { app, device } = report.exploration;
|
||||
const zipHash = createHash("sha256").update(reports[0]!.zip).digest("hex").slice(0, 10);
|
||||
return { id: `explore-${slug(app.name, 40)}-${zipHash}`, kind: "exploration", title: `${app.name}${app.version ? ` ${app.version}` : ""}${app.buildNumber ? ` (${app.buildNumber})` : ""} on ${device.model}`,
|
||||
platforms, device: `${device.model} ${device.osVersion}`.trim(),
|
||||
explored: { app: app.name, ...(app.version ? { version: app.version } : {}), ...(app.buildNumber ? { buildNumber: app.buildNumber } : {}),
|
||||
screens: report.map.screens.length, unexplored: report.coverage?.frontier.pending ?? 0 },
|
||||
createdAt: report.exploration.completedAt ?? createdAt };
|
||||
}
|
||||
const reviews = parsed.map(entry => (entry.content?.json as Partial<ArtifactReport> | undefined)?.review);
|
||||
const review = reviews[0];
|
||||
const pr = review?.pullRequest;
|
||||
if (!review || !pr) throw new Error("Not an Explore review report");
|
||||
// One surface changed on two platforms is one change, under the group the PR comment lists it in (strongerGroup).
|
||||
const merged = new Map<string, ChangeGroup>();
|
||||
for (const each of reviews) if (each) for (const [id, group] of reviewChanges(normalizePublicReviewForReading(each))) {
|
||||
const first = merged.get(id);
|
||||
merged.set(id, first ? strongerGroup(first, group) : group);
|
||||
}
|
||||
const changes: Partial<Record<ChangeGroup, number>> = {};
|
||||
for (const group of merged.values()) changes[group] = (changes[group] ?? 0) + 1;
|
||||
const devices = [...new Set(reviews.map(each => each ? reviewDevice({ runtime: { deviceModel: each.runtime?.device?.model ?? "", osVersion: each.runtime?.device?.osVersion ?? "",
|
||||
...(each.runtime?.colorSchemes ? { colorSchemes: each.runtime.colorSchemes } : {}) } }) : "").filter(Boolean))];
|
||||
const kind = pr.origin === "local" ? "local" : pr.origin === "compare" ? "compare" : "pull-request";
|
||||
const number = "number" in pr && typeof pr.number === "number" ? pr.number : undefined;
|
||||
// The run's own id and attempt are never cut short: two runs of one repository must not share a folder.
|
||||
const id = kind === "local" ? slug(review.runId, 100)
|
||||
: `${kind === "compare" ? "compare" : `pr-${number}`}-${slug(pr.repository.split("/").at(-1) ?? "", 40)}-${slug(review.runId, 40)}-${slug(String(review.runAttempt), 8)}`;
|
||||
const commit = (side: "head" | "base"): SavedCommit => ({ ref: pr[side].ref, sha: pr[side].sha, ...(extra.subjects?.[side] ? { subject: extra.subjects[side] } : {}) });
|
||||
return { id, kind, title: pr.title, repository: pr.repository, ...(number === undefined ? {} : { number }), head: commit("head"), base: commit("base"),
|
||||
...(extra.uncommittedFiles ? { uncommittedFiles: extra.uncommittedFiles } : {}), platforms, ...(devices.length ? { device: devices.join(", ") } : {}),
|
||||
changes, createdAt: review.createdAt ?? createdAt };
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps a run's reports, then prunes. A review's platforms saved one at a time join the run already kept for the same
|
||||
* review (same repository, run, attempt and commits); anything else under that id is replaced. Written beside and
|
||||
* renamed into place.
|
||||
*/
|
||||
export async function saveRun(reports: SavedReport[], extra: Parameters<typeof describeReports>[1] = {}, environment: NodeJS.ProcessEnv = process.env, now = Date.now()): Promise<SavedRun> {
|
||||
let described = await describeReports(reports, extra);
|
||||
if (!ID.test(described.id)) throw new Error(`Cannot keep a run named ${described.id}`);
|
||||
const root = savedRunsDirectory(environment);
|
||||
await mkdir(root, { recursive: true });
|
||||
const target = join(root, described.id);
|
||||
const kept = await findSavedRun(described.id, environment);
|
||||
if (kept && described.kind !== "exploration" && kept.kind === described.kind && kept.repository === described.repository
|
||||
&& kept.head?.sha === described.head?.sha && kept.base?.sha === described.base?.sha) {
|
||||
const others = (await readSavedReports(kept, environment).catch(() => [] as SavedReport[])).filter(report => !reports.some(each => each.platform === report.platform));
|
||||
if (others.length) {
|
||||
const order: ExplorePlatform[] = ["ios", "android"];
|
||||
reports = [...reports, ...others].sort((a, b) => order.indexOf(a.platform) - order.indexOf(b.platform));
|
||||
const subjects = { ...(kept.head?.subject ? { head: kept.head.subject } : {}), ...(kept.base?.subject ? { base: kept.base.subject } : {}), ...extra.subjects };
|
||||
described = await describeReports(reports, { ...extra, subjects, ...(kept.uncommittedFiles && !extra.uncommittedFiles ? { uncommittedFiles: kept.uncommittedFiles } : {}) });
|
||||
}
|
||||
}
|
||||
const staged = join(root, `.${described.id}.${randomBytes(4).toString("hex")}.tmp`);
|
||||
const run = cleanRun({ version: 1, ...described, savedAt: new Date(now).toISOString(), bytes: reports.reduce((total, report) => total + report.zip.byteLength, 0) });
|
||||
try {
|
||||
await mkdir(staged);
|
||||
for (const report of reports) await writeFile(join(staged, `${report.platform}.zip`), report.zip);
|
||||
await writeFile(join(staged, "run.json"), `${JSON.stringify(run, null, 2)}\n`);
|
||||
await rm(target, { recursive: true, force: true });
|
||||
await rename(staged, target);
|
||||
} finally {
|
||||
await rm(staged, { recursive: true, force: true });
|
||||
}
|
||||
await pruneSavedRuns(environment, now, SAVED_RUN_LIMITS, run.id);
|
||||
return run;
|
||||
}
|
||||
|
||||
function validRun(value: unknown, id: string): SavedRun | undefined {
|
||||
const run = value as Partial<SavedRun> | undefined;
|
||||
if (!run || run.version !== 1 || run.id !== id || typeof run.title !== "string" || typeof run.bytes !== "number") return undefined;
|
||||
// Platforms name the ZIP files read back, so only the two there are.
|
||||
if (!Array.isArray(run.platforms) || !run.platforms.length || run.platforms.some(platform => platform !== "ios" && platform !== "android")) return undefined;
|
||||
if (!["local", "pull-request", "compare", "exploration"].includes(run.kind ?? "") || Number.isNaN(Date.parse(run.createdAt ?? "")) || Number.isNaN(Date.parse(run.savedAt ?? ""))) return undefined;
|
||||
return run as SavedRun;
|
||||
}
|
||||
|
||||
/** The saved runs, newest first; a folder without a readable run.json is skipped. */
|
||||
export async function listSavedRuns(environment: NodeJS.ProcessEnv = process.env): Promise<SavedRun[]> {
|
||||
const root = savedRunsDirectory(environment);
|
||||
const names = await readdir(root).catch(() => [] as string[]);
|
||||
const runs: SavedRun[] = [];
|
||||
for (const name of names) {
|
||||
if (!ID.test(name)) continue;
|
||||
try {
|
||||
const run = validRun(JSON.parse(await readFile(join(root, name, "run.json"), "utf8")), name);
|
||||
if (run) runs.push(cleanRun(run));
|
||||
} catch { /* a run being written, or not a run */ }
|
||||
}
|
||||
return runs.sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt));
|
||||
}
|
||||
|
||||
/** A saved run by id, or `latest`. */
|
||||
export async function findSavedRun(idOrLatest: string, environment: NodeJS.ProcessEnv = process.env): Promise<SavedRun | undefined> {
|
||||
const runs = await listSavedRuns(environment);
|
||||
return idOrLatest === "latest" ? runs[0] : runs.find(run => run.id === idOrLatest);
|
||||
}
|
||||
|
||||
/** A saved run's reports, in the order the run lists its platforms, labelled for a Viewer's platform switch. */
|
||||
export async function readSavedReports(run: SavedRun, environment: NodeJS.ProcessEnv = process.env): Promise<SavedReport[]> {
|
||||
const root = join(savedRunsDirectory(environment), run.id);
|
||||
return Promise.all(run.platforms.map(async platform => ({ platform, zip: new Uint8Array(await readFile(join(root, `${platform}.zip`))) })));
|
||||
}
|
||||
|
||||
export async function removeSavedRun(id: string, environment: NodeJS.ProcessEnv = process.env): Promise<boolean> {
|
||||
if (!ID.test(id)) return false;
|
||||
const target = join(savedRunsDirectory(environment), id);
|
||||
if (!await lstat(target).then(() => true, () => false)) return false;
|
||||
await rm(target, { recursive: true, force: true });
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Drops runs kept longer than the age limit, then the longest kept until the rest fit the size limit; never `keep`. Returns what it removed. */
|
||||
export async function pruneSavedRuns(environment: NodeJS.ProcessEnv = process.env, now = Date.now(), limits: { maxAgeDays: number; maxBytes: number } = SAVED_RUN_LIMITS,
|
||||
keep?: string): Promise<SavedRun[]> {
|
||||
const runs = (await listSavedRuns(environment)).sort((a, b) => Date.parse(a.savedAt) - Date.parse(b.savedAt));
|
||||
const removed: SavedRun[] = [];
|
||||
let total = runs.reduce((sum, run) => sum + run.bytes, 0);
|
||||
for (const run of runs) {
|
||||
if (run.id === keep) continue;
|
||||
const old = now - Date.parse(run.savedAt) > limits.maxAgeDays * 86_400_000;
|
||||
if (!old && total <= limits.maxBytes) continue;
|
||||
await removeSavedRun(run.id, environment);
|
||||
total -= run.bytes;
|
||||
removed.push(run);
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
@@ -59,8 +59,17 @@ export async function readZipEntry(bytes: Uint8Array, entry: ZipEntry, maxBytes:
|
||||
const compressed = bytes.subarray(start, start + entry.compressedSize);
|
||||
if (entry.method === 0) return compressed.byteLength === entry.size ? compressed : undefined;
|
||||
try {
|
||||
const stream = new Blob([compressed as BlobPart]).stream().pipeThrough(new DecompressionStream("deflate-raw"));
|
||||
const inflated = new Uint8Array(await new Response(stream).arrayBuffer());
|
||||
return inflated.byteLength === entry.size ? inflated : undefined;
|
||||
// Inflated in chunks and abandoned once past the declared size, so a header that lies cannot exhaust memory.
|
||||
const reader = new Blob([compressed as BlobPart]).stream().pipeThrough(new DecompressionStream("deflate-raw")).getReader();
|
||||
const inflated = new Uint8Array(entry.size);
|
||||
let length = 0;
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
if (length + value.byteLength > entry.size) { await reader.cancel(); return undefined; }
|
||||
inflated.set(value, length);
|
||||
length += value.byteLength;
|
||||
}
|
||||
return length === entry.size ? inflated : undefined;
|
||||
} catch { return undefined; }
|
||||
}
|
||||
@@ -268,6 +268,7 @@ async function constructCaptureReview(options: CaptureReviewOptions, store: Scre
|
||||
if (pr.head.sha !== plan.headSha || pr.base.sha !== plan.baseSha) throw new Error("PR identity differs from capture plan");
|
||||
const run = `${identifier(options.runId)}-${identifier(options.runAttempt)}`;
|
||||
const prefix = pr.origin === "local" ? `local/${identifier(pr.runId)}/${run}`
|
||||
: pr.origin === "compare" ? `reviews/${identifier(pr.repositoryId)}/compare/${pr.base.sha}-${pr.head.sha}/${run}`
|
||||
: `reviews/${identifier(pr.repositoryId)}/pr-${pr.number}/${pr.head.sha}/${run}`;
|
||||
await options.assertCurrentHead();
|
||||
const base = await uploadSide(store, options.baseDirectory, plan.baseSha, plan.baseCaptureSurfaceIds, `${prefix}/base`);
|
||||
@@ -283,6 +284,10 @@ async function constructCaptureReview(options: CaptureReviewOptions, store: Scre
|
||||
? sourceImpactKinds(surface.sourceChange.files.map((file) => file.relation))
|
||||
: []
|
||||
);
|
||||
// Each controller reads and drives the device its own way; a review compares captures made the same way.
|
||||
if ((head.bundle.controller ?? "agent-device") !== (base.bundle.controller ?? "agent-device")) {
|
||||
throw new Error(`The base was captured with ${base.bundle.controller ?? "agent-device"} and the head with ${head.bundle.controller ?? "agent-device"}; capture both sides with the same controller.`);
|
||||
}
|
||||
const colorSchemes = bundleColorSchemes(head.bundle);
|
||||
const baseColorSchemes = bundleColorSchemes(base.bundle);
|
||||
const review: PublicReview = {
|
||||
@@ -290,7 +295,7 @@ async function constructCaptureReview(options: CaptureReviewOptions, store: Scre
|
||||
runId: options.runId, runAttempt: options.runAttempt,
|
||||
...(plan.navigation ? { navigation: plan.navigation } : {}),
|
||||
runtime: { projectId: head.bundle.easProjectId ?? "", buildId: head.bundle.easBuildId ?? "", gitCommit: plan.headSha,
|
||||
platform: head.bundle.platform ?? "ios", statusBarBandPercent: statusBarBandPercent(head.bundle.platform),
|
||||
platform: head.bundle.platform ?? "ios", ...(head.bundle.controller === "argent" ? { controller: "argent" as const } : {}), statusBarBandPercent: statusBarBandPercent(head.bundle.platform),
|
||||
...(homeIndicatorBandPercent(head.bundle.platform) > 0 ? { homeIndicatorBandPercent: homeIndicatorBandPercent(head.bundle.platform) } : {}),
|
||||
...(options.platforms && options.platforms.length > 1 ? { platforms: [...options.platforms] } : {}),
|
||||
...(colorSchemes.length > 1 ? { colorSchemes: [...colorSchemes] } : {}),
|
||||
|
||||
@@ -27,6 +27,7 @@ import {
|
||||
} from "./visual-evidence.js";
|
||||
import { AGENT_DEVICE_VERSION } from "../shared/agent-device-version.js";
|
||||
import { STATUS_BAR_BAND_PERCENT } from "../shared/png-evidence.js";
|
||||
import { measureRegionShifts } from "./region-shift.js";
|
||||
|
||||
export const DEFAULT_VISUAL_THRESHOLD = 0.1;
|
||||
export const DEFAULT_EVIDENCE_TIME_BUDGET_MS = 10 * 60_000;
|
||||
@@ -141,6 +142,29 @@ function visualVerdict(assessment: VisualEvidenceAssessment, threshold: number):
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The published regions with how far their content moved, where a move explains it: a layout that shifted by a
|
||||
* device pixel reads as moved, not as changed. Every region the comparison found is measured, not only the ones
|
||||
* published, so `allRegionsMoved` can say nothing else on the screen changed. A measurement that fails leaves the
|
||||
* regions as they were.
|
||||
*/
|
||||
async function withRegionShifts(basePath: string, headPath: string, all: readonly VisualDiffRegion[], published: NonNullable<PublicVisualVerdict["regions"]>):
|
||||
Promise<Pick<PublicVisualVerdict, "regions" | "allRegionsMoved">> {
|
||||
try {
|
||||
const shifts = await measureRegionShifts(basePath, headPath, all.map(region => region.rect));
|
||||
const shiftOf = new Map(all.map((region, index) => [region.rect, shifts[index]] as const));
|
||||
return {
|
||||
regions: published.map(region => {
|
||||
const shift = shiftOf.get(region.rect);
|
||||
return shift ? { ...region, shift } : region;
|
||||
}),
|
||||
...(all.length > 0 && shifts.every(Boolean) ? { allRegionsMoved: true as const } : {}),
|
||||
};
|
||||
} catch {
|
||||
return { regions: published };
|
||||
}
|
||||
}
|
||||
|
||||
/** Remove status-bar-only diff regions from a measurement and recompute its verdict inputs. */
|
||||
export function ignoreStatusBar(measurement: ScreenshotDiffMeasurement, bandPercent: number = STATUS_BAR_BAND_PERCENT): { measurement: ScreenshotDiffMeasurement; ignored: number } {
|
||||
const bands = ignoreSystemBands(measurement, { top: bandPercent, bottom: 0 });
|
||||
@@ -277,11 +301,11 @@ function localEvidencePath(side: PublicEvidenceSide, relativePath: string): stri
|
||||
|
||||
/**
|
||||
* The verdict combines the source scope with the evidence. Only a source change makes a surface a
|
||||
* review target: a changed screen is Modified when evidence differs and Needs review when nothing
|
||||
* visible differs. A source-unchanged screen is never a review target: a difference there is the
|
||||
* same screen captured in another runtime state (a screen variant), not a change. When only
|
||||
* app-wide inputs changed, a screen without a visible difference stays Unchanged; the PR comment
|
||||
* names the app-wide change once.
|
||||
* review target: a changed screen is Modified when its evidence differs, Needs review when the
|
||||
* comparison could not tell, and Unchanged when both captures show the same thing. Explore reports
|
||||
* visual changes, so a source change nobody can see is not one. A source-unchanged screen is never a
|
||||
* review target: a difference there is the same screen captured in another runtime state (a screen
|
||||
* variant), not a change. The PR comment names an app-wide change once.
|
||||
*/
|
||||
export function decideReview(scope: SurfaceSourceScope, visual: PublicVisualVerdict, summary?: WhatChangedSummary): PublicSurfaceReview {
|
||||
const facts = summary?.facts.map((fact) => ({ category: fact.category, templateId: fact.templateId, bullet: truncate(fact.bullet) })) ?? [];
|
||||
@@ -303,8 +327,7 @@ export function decideReview(scope: SurfaceSourceScope, visual: PublicVisualVerd
|
||||
if (inconclusive) {
|
||||
return { status: "needs-review", description: truncate(visual.verdict === "needs-review" ? visualReasonText(visual) : issue ?? "Needs review") };
|
||||
}
|
||||
if (scope === "app-wide") return { status: "unchanged", description: "No visible change" };
|
||||
return { status: "needs-review", description: "Source changed; no visible difference was captured." };
|
||||
return { status: "unchanged", description: "No visible change" };
|
||||
}
|
||||
|
||||
function captureDiagnostic(surface: PlanSurface, side: "base" | "head", evidence: PublicEvidenceSide, surfaceId: string = surface.id): PublicEvidenceDiagnostic | undefined {
|
||||
@@ -464,6 +487,10 @@ export async function assessPublicEvidence(options: {
|
||||
representative: measurement,
|
||||
});
|
||||
visual = visualVerdict(assessment, threshold);
|
||||
// Measuring moves is extra: once the comparison budget is spent, regions go out unmeasured.
|
||||
if (visual.verdict === "modified" && visual.regions?.length && now() <= deadline) {
|
||||
Object.assign(visual, await withRegionShifts(basePath, headPath, measurement.regions, visual.regions));
|
||||
}
|
||||
if (ignoredTop > 0) visual.ignoredStatusBarRegions = ignoredTop;
|
||||
if (ignoredBottom > 0) visual.ignoredHomeIndicatorRegions = ignoredBottom;
|
||||
visualCounts.compared += 1;
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
import { createRequire } from "node:module";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import type { DecodedFrame } from "../shared/png-evidence.js";
|
||||
|
||||
/** How far a region's content moved from Before to After, in screenshot pixels (right and down are positive). */
|
||||
export type RegionShift = { x: number; y: number };
|
||||
type Rect = { x: number; y: number; width: number; height: number };
|
||||
|
||||
/**
|
||||
* The farthest a region is searched for, in screenshot pixels: layout drift, not a different screen. Drift adds up
|
||||
* down a long screen (a device pixel per text element above), so the vertical reach is the larger.
|
||||
*/
|
||||
const MAX_SHIFT_X = 4;
|
||||
const MAX_SHIFT_Y = 20;
|
||||
/** How close to the edge of the search a best fit may land and still count: the real one may lie beyond it. */
|
||||
const EDGE = 1.5;
|
||||
/**
|
||||
* The share of a region's difference one shift must explain for the region to have moved rather than changed.
|
||||
* A move of half a pixel or less re-rasterizes text rather than shifting it, so a pure shift explains only a
|
||||
* quarter to a half of it; content that changed (new text, a caret) explains under a quarter at that size, and
|
||||
* anything larger has to be explained mostly by the shift. Measured on euxy's SDK 58 upgrade (brentvatne/euxy#161).
|
||||
*/
|
||||
const MIN_EXPLAINED = 0.6;
|
||||
const MIN_EXPLAINED_SUBPIXEL = 0.25;
|
||||
const SUBPIXEL = 0.5;
|
||||
/** A smaller shift is rendering noise, not a move. */
|
||||
const MIN_SHIFT = 0.25;
|
||||
/** Sixths of a pixel in the refining search: a third of a 1x pixel is one device pixel on a 3x screen. */
|
||||
const STEPS_PER_PIXEL = 6;
|
||||
/** Fits this close to the best are ties, which go to the smallest move (content that is the same all along one axis). */
|
||||
const TIE = 1.005;
|
||||
/** Another fit this close at a vertical offset two or more pixels away makes the move ambiguous (repeating content). */
|
||||
const AMBIGUOUS = 1.05;
|
||||
/**
|
||||
* After aligning by the move, content is the same only where every channel is within this: re-rasterized text
|
||||
* differs by at most about 125 (brentvatne/euxy#161), new content by about 200. A few pixels over it are noise; more are a change.
|
||||
*/
|
||||
const CHANGED_CHANNEL = 140;
|
||||
const CHANGED_PIXELS = 3;
|
||||
|
||||
type Image = { width: number; height: number; frame: DecodedFrame; luminance: Float32Array };
|
||||
type Fit = { sx: number; sy: number; error: number };
|
||||
|
||||
function image(frame: DecodedFrame): Image {
|
||||
const luminance = new Float32Array(frame.width * frame.height);
|
||||
for (let index = 0; index < luminance.length; index += 1) {
|
||||
const offset = index * 4;
|
||||
luminance[index] = 0.299 * frame.data[offset]! + 0.587 * frame.data[offset + 1]! + 0.114 * frame.data[offset + 2]!;
|
||||
}
|
||||
return { width: frame.width, height: frame.height, frame, luminance };
|
||||
}
|
||||
|
||||
/** Bilinear sample of one plane: `channel` 0–2 of the frame, or luminance when undefined. */
|
||||
function at(source: Image, x: number, y: number, channel?: number): number {
|
||||
const cx = Math.min(source.width - 1, Math.max(0, x));
|
||||
const cy = Math.min(source.height - 1, Math.max(0, y));
|
||||
const x0 = Math.floor(cx), y0 = Math.floor(cy);
|
||||
const x1 = Math.min(source.width - 1, x0 + 1), y1 = Math.min(source.height - 1, y0 + 1);
|
||||
const fx = cx - x0, fy = cy - y0;
|
||||
const value = channel === undefined
|
||||
? (px: number, py: number) => source.luminance[py * source.width + px]!
|
||||
: (px: number, py: number) => source.frame.data[(py * source.width + px) * 4 + channel]!;
|
||||
return value(x0, y0) * (1 - fx) * (1 - fy) + value(x1, y0) * fx * (1 - fy) + value(x0, y1) * (1 - fx) * fy + value(x1, y1) * fx * fy;
|
||||
}
|
||||
|
||||
/** How badly After's region matches Before shifted by (sx, sy). */
|
||||
function mismatch(base: Image, head: Image, rect: Rect, sx: number, sy: number): number {
|
||||
let error = 0;
|
||||
for (let y = rect.y; y < rect.y + rect.height; y += 1) {
|
||||
for (let x = rect.x; x < rect.x + rect.width; x += 1) {
|
||||
error += Math.abs(at(base, x - sx, y - sy) - head.luminance[y * head.width + x]!);
|
||||
}
|
||||
}
|
||||
return error;
|
||||
}
|
||||
|
||||
/** The best of some fits, with near-ties going to the smallest move. */
|
||||
function bestOf(fits: readonly Fit[]): Fit {
|
||||
const least = Math.min(...fits.map(fit => fit.error));
|
||||
return fits.filter(fit => fit.error <= least * TIE + 1e-6)
|
||||
.sort((a, b) => Math.hypot(a.sx, a.sy) - Math.hypot(b.sx, b.sy))[0]!;
|
||||
}
|
||||
|
||||
/** Whether, aligned by the move, some of the region still differs strongly in any channel: content that changed. */
|
||||
function changedAfterMove(base: Image, head: Image, rect: Rect, sx: number, sy: number): boolean {
|
||||
let strong = 0;
|
||||
for (let y = rect.y; y < rect.y + rect.height; y += 1) {
|
||||
for (let x = rect.x; x < rect.x + rect.width; x += 1) {
|
||||
for (let channel = 0; channel < 3; channel += 1) {
|
||||
if (Math.abs(at(base, x - sx, y - sy, channel) - head.frame.data[(y * head.width + x) * 4 + channel]!) > CHANGED_CHANNEL) {
|
||||
strong += 1;
|
||||
if (strong >= CHANGED_PIXELS) return true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* The shift that explains one region's difference, if one does: the region's content is the same in both
|
||||
* screenshots, only moved. A region whose content changed (new text, another colour) has no shift, and neither has
|
||||
* one whose content repeats so that several shifts fit.
|
||||
*/
|
||||
function regionShift(base: Image, head: Image, region: Rect): RegionShift | undefined {
|
||||
const x = Math.max(0, Math.floor(region.x)), y = Math.max(0, Math.floor(region.y));
|
||||
const rect = { x, y, width: Math.min(head.width - x, Math.ceil(region.width)), height: Math.min(head.height - y, Math.ceil(region.height)) };
|
||||
if (rect.width <= 0 || rect.height <= 0) return undefined;
|
||||
const unshifted = mismatch(base, head, rect, 0, 0);
|
||||
if (unshifted === 0) return undefined;
|
||||
// Whole pixels first, every pixel counting: sampling every other row aliases on thin shapes (text, hairlines).
|
||||
const whole: Fit[] = [];
|
||||
for (let sy = -MAX_SHIFT_Y; sy <= MAX_SHIFT_Y; sy += 1) {
|
||||
for (let sx = -MAX_SHIFT_X; sx <= MAX_SHIFT_X; sx += 1) whole.push({ sx, sy, error: mismatch(base, head, rect, sx, sy) });
|
||||
}
|
||||
const coarse = bestOf(whole);
|
||||
if (whole.some(fit => Math.abs(fit.sy - coarse.sy) >= 2 && fit.error <= coarse.error * AMBIGUOUS + 1e-6)) return undefined;
|
||||
// Then sixths of a pixel around it, from whole-number steps so a move up and a move down round alike.
|
||||
const fine: Fit[] = [];
|
||||
for (let iy = -STEPS_PER_PIXEL; iy <= STEPS_PER_PIXEL; iy += 1) {
|
||||
for (let ix = -STEPS_PER_PIXEL; ix <= STEPS_PER_PIXEL; ix += 1) {
|
||||
const sx = coarse.sx + ix / STEPS_PER_PIXEL, sy = coarse.sy + iy / STEPS_PER_PIXEL;
|
||||
fine.push({ sx, sy, error: ix === 0 && iy === 0 ? coarse.error : mismatch(base, head, rect, sx, sy) });
|
||||
}
|
||||
}
|
||||
const best = bestOf(fine);
|
||||
if (Math.abs(best.sx) > MAX_SHIFT_X - EDGE || Math.abs(best.sy) > MAX_SHIFT_Y - EDGE) return undefined;
|
||||
const distance = Math.hypot(best.sx, best.sy);
|
||||
const needed = distance <= SUBPIXEL + 1e-6 ? MIN_EXPLAINED_SUBPIXEL : MIN_EXPLAINED;
|
||||
if (distance < MIN_SHIFT - 1e-6 || 1 - best.error / unshifted < needed) return undefined;
|
||||
if (changedAfterMove(base, head, rect, best.sx, best.sy)) return undefined;
|
||||
const round = (value: number) => Math.round(value * 100) / 100 || 0;
|
||||
return { x: round(best.sx), y: round(best.sy) };
|
||||
}
|
||||
|
||||
/** Each region's shift between two screenshots of the same size; undefined where a region's content changed. */
|
||||
export function regionShifts(baseFrame: DecodedFrame, headFrame: DecodedFrame, regions: readonly Rect[]): Array<RegionShift | undefined> {
|
||||
if (baseFrame.width !== headFrame.width || baseFrame.height !== headFrame.height) return regions.map(() => undefined);
|
||||
const base = image(baseFrame), head = image(headFrame);
|
||||
return regions.map(region => regionShift(base, head, region));
|
||||
}
|
||||
|
||||
/** Reads both PNG screenshots and measures each region's shift. */
|
||||
export async function measureRegionShifts(basePath: string, headPath: string, regions: readonly Rect[]): Promise<Array<RegionShift | undefined>> {
|
||||
const { PNG } = createRequire(import.meta.url.replace(/\?.*$/, ""))("pngjs") as
|
||||
{ PNG: { sync: { read(bytes: Buffer, options: { checkCRC: boolean }): DecodedFrame } } };
|
||||
const [base, head] = await Promise.all([readFile(basePath), readFile(headPath)]);
|
||||
return regionShifts(PNG.sync.read(base, { checkCRC: false }), PNG.sync.read(head, { checkCRC: false }), regions);
|
||||
}
|
||||
@@ -11,12 +11,14 @@ import type {
|
||||
} from "./runtime-evidence.js";
|
||||
import type { ExploreMap, Observation, Screen } from "../types.js";
|
||||
import { CAPTURE_OBSERVER_IDENTIFIER } from "../capture/observer.js";
|
||||
import { ARGENT_VERSION } from "../shared/argent-version.js";
|
||||
|
||||
/** Strict, non-secret subset written after a successful EAS Simulator cleanup. */
|
||||
export type RuntimeExecutionContext = {
|
||||
provider: "eas-simulator";
|
||||
controller: "agent-device";
|
||||
controllerPackageVersion: typeof AGENT_DEVICE_VERSION;
|
||||
controller: "agent-device" | "argent";
|
||||
/** The pinned package of the controller that drove the session. */
|
||||
controllerPackageVersion: typeof AGENT_DEVICE_VERSION | typeof ARGENT_VERSION;
|
||||
easCliVersion: typeof EAS_CLI_VERSION;
|
||||
platform: "ios" | "android";
|
||||
deviceModel: string;
|
||||
@@ -107,12 +109,13 @@ export function parseRuntimeExecutionContext(value: unknown): RuntimeExecutionCo
|
||||
}
|
||||
return context.colorSchemes.map((entry) => literal(entry, ["light", "dark"], "Runtime color schemes"));
|
||||
})();
|
||||
const controller = literal(context.controller, ["agent-device", "argent"], "Runtime controller");
|
||||
return {
|
||||
provider: literal(context.provider, ["eas-simulator"], "Runtime provider"),
|
||||
controller: literal(context.controller, ["agent-device"], "Runtime controller"),
|
||||
controller,
|
||||
controllerPackageVersion: literal(
|
||||
context.controllerPackageVersion,
|
||||
[AGENT_DEVICE_VERSION],
|
||||
[controller === "argent" ? ARGENT_VERSION : AGENT_DEVICE_VERSION],
|
||||
"Controller package version",
|
||||
),
|
||||
easCliVersion: literal(context.easCliVersion, [EAS_CLI_VERSION], "EAS CLI version"),
|
||||
|
||||
@@ -93,7 +93,7 @@ export type RawCaptureSample = {
|
||||
|
||||
export type RawSimulatorEnvironment = {
|
||||
provider: "eas-simulator";
|
||||
controller: "agent-device";
|
||||
controller: "agent-device" | "argent";
|
||||
platform: Platform;
|
||||
deviceModel: string;
|
||||
osVersion: string;
|
||||
@@ -247,7 +247,7 @@ export type RuntimeEnvironmentEvidence = {
|
||||
profile: EvidenceField<"capture-context", string>;
|
||||
fixturePersona?: EvidenceField<"capture-context", string>;
|
||||
provider: EvidenceField<"eas-agent-device", "eas-simulator">;
|
||||
controller: EvidenceField<"eas-agent-device", "agent-device">;
|
||||
controller: EvidenceField<"eas-agent-device", "agent-device" | "argent">;
|
||||
controllerPackageVersion?: EvidenceField<"capture-context", string>;
|
||||
easCliVersion?: EvidenceField<"capture-context", string>;
|
||||
platform: EvidenceField<"eas-agent-device", Platform>;
|
||||
@@ -785,7 +785,7 @@ function parseEnvironment(value: unknown): RawSimulatorEnvironment {
|
||||
);
|
||||
return {
|
||||
provider: literal(environment.provider, ["eas-simulator"], "Runtime provider"),
|
||||
controller: literal(environment.controller, ["agent-device"], "Runtime controller"),
|
||||
controller: literal(environment.controller, ["agent-device", "argent"], "Runtime controller"),
|
||||
platform: literal(environment.platform, PLATFORMS, "Runtime platform"),
|
||||
deviceModel: safeString(environment.deviceModel, "Device model", 256),
|
||||
osVersion: safeString(environment.osVersion, "OS version", 256),
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
/**
|
||||
* The one Argent version Explore runs. The local CLI (`package.json`) and the EAS Simulator controller
|
||||
* (`--package-version` for an `argent` session) must both be this version.
|
||||
*/
|
||||
export const ARGENT_VERSION = "0.29.0";
|
||||
@@ -0,0 +1,7 @@
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
/** Where Explore keeps what outlives a run on this machine: `$EXPLORE_CACHE_DIR`, else `$XDG_CACHE_HOME/expo-explore`, else `~/.cache/expo-explore`. */
|
||||
export function exploreCacheRoot(environment: NodeJS.ProcessEnv): string {
|
||||
return environment.EXPLORE_CACHE_DIR || join(environment.XDG_CACHE_HOME || join(environment.HOME || homedir(), ".cache"), "expo-explore");
|
||||
}
|
||||
@@ -159,7 +159,9 @@ export async function reportCiError(error: unknown, options: {
|
||||
const renderOptions = { secrets };
|
||||
const diagnostic = serializeCiError(error, renderOptions);
|
||||
const write = options.write ?? ((value: string) => process.stderr.write(`${value}\n`));
|
||||
write(renderCiErrorAnnotation(error, renderOptions));
|
||||
// An annotation in Actions; in a terminal (a local capture:review) the same redacted text, readable.
|
||||
write(env.GITHUB_ACTIONS === "true" || env.GITHUB_STEP_SUMMARY ? renderCiErrorAnnotation(error, renderOptions)
|
||||
: `Error [${diagnostic.code}]: ${diagnostic.message}\nNext action: ${diagnostic.nextAction}`);
|
||||
const outputs: Array<{ label: string; operation: Promise<unknown> }> = [];
|
||||
if (env.GITHUB_STEP_SUMMARY) outputs.push({ label: "job summary", operation: appendFile(env.GITHUB_STEP_SUMMARY, `${renderCiErrorSummary(error, renderOptions)}\n`) });
|
||||
if (options.diagnosticsPath) outputs.push({ label: "diagnostics file", operation: (async () => {
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
/**
|
||||
* The device controllers Explore drives, fetched on first use instead of installed with Explore. Each is pinned to
|
||||
* an exact npm release and its sha512 integrity; the tarball is checked before anything in it is written, nothing in
|
||||
* it runs at install time, and neither controller needs other packages at run time.
|
||||
*/
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
|
||||
import { chmod, mkdir, open, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join, resolve, sep } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { safeRelativePath, walkTar } from "../binary/archive.js";
|
||||
import { CiError } from "./ci-errors.js";
|
||||
import { AGENT_DEVICE_VERSION } from "./agent-device-version.js";
|
||||
import { ARGENT_VERSION } from "./argent-version.js";
|
||||
|
||||
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-Om1j6oNJkeKlkk8lBM+0V9bKwpxUXLMf/PDDSvAt3RFquBRqAiM58J81E0rvPQNxs6GCjhABYpwVvIAXptxjjA==" },
|
||||
argent: { name: "@swmansion/argent", version: ARGENT_VERSION, bin: "dist/cli.js",
|
||||
integrity: "sha512-XXWlWZJlHKqnAvNx3RDhuiVFQOPqh5EDB76+mFAyqC2mutC6irzw03+M/6S/WQ+Dzz2IYOkEfOzQnOOdhrGgJg==" },
|
||||
};
|
||||
|
||||
const COMPLETE = ".explore-controller.json";
|
||||
const MAX_CONTROLLER_BYTES = 256 * 1024 * 1024;
|
||||
const LAUNCHER = fileURLToPath(new URL("../capture/controller-launcher.js", import.meta.url));
|
||||
|
||||
/** Where fetched controllers live: EXPLORE_CONTROLLER_CACHE, else the user's cache directory. */
|
||||
export function controllerCacheRoot(environment: NodeJS.ProcessEnv = process.env): string {
|
||||
if (environment.EXPLORE_CONTROLLER_CACHE) return resolve(environment.EXPLORE_CONTROLLER_CACHE);
|
||||
const base = environment.XDG_CACHE_HOME || join(environment.HOME || homedir(), ".cache");
|
||||
return join(base, "expo-explore", "controllers");
|
||||
}
|
||||
|
||||
export function controllerDirectory(controller: ControllerName, environment: NodeJS.ProcessEnv = process.env): string {
|
||||
const { name, version } = CONTROLLER_PACKAGES[controller];
|
||||
return join(controllerCacheRoot(environment), `${name.replace("/", "+")}@${version}`);
|
||||
}
|
||||
|
||||
/** The controller's entry file in the cache; it exists once `ensureController` has run. */
|
||||
export function controllerBin(controller: ControllerName, environment: NodeJS.ProcessEnv = process.env): string {
|
||||
return join(controllerDirectory(controller, environment), CONTROLLER_PACKAGES[controller].bin);
|
||||
}
|
||||
|
||||
export function controllerCached(controller: ControllerName, environment: NodeJS.ProcessEnv = process.env): boolean {
|
||||
return existsSync(join(controllerDirectory(controller, environment), COMPLETE));
|
||||
}
|
||||
|
||||
/** The registry tarball for a release, from EXPLORE_NPM_REGISTRY (a mirror) or the public npm registry. */
|
||||
export function controllerTarballUrl(controller: ControllerName, environment: NodeJS.ProcessEnv = process.env): string {
|
||||
const { name, version } = CONTROLLER_PACKAGES[controller];
|
||||
const registry = (environment.EXPLORE_NPM_REGISTRY || "https://registry.npmjs.org").replace(/\/+$/, "");
|
||||
return `${registry}/${name}/-/${name.split("/").pop()}-${version}.tgz`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The command that runs agent-device: a small script in the cache that fetches the pinned release on first use and
|
||||
* then runs it with the same arguments. It names the cache, so a caller that narrows the environment (no HOME) still
|
||||
* finds it. Written synchronously, so capture options can name it before any controller call.
|
||||
*/
|
||||
export function agentDeviceLauncher(environment: NodeJS.ProcessEnv = process.env): string {
|
||||
const root = controllerCacheRoot(environment);
|
||||
const quote = (value: string) => `'${value.replace(/'/g, `'\\''`)}'`;
|
||||
// The registry is part of the command too: controller calls run with a narrowed environment that drops it.
|
||||
const registry = environment.EXPLORE_NPM_REGISTRY ? ` EXPLORE_NPM_REGISTRY=${quote(environment.EXPLORE_NPM_REGISTRY)}` : "";
|
||||
const script = `#!/bin/sh\nEXPLORE_CONTROLLER_CACHE=${quote(root)}${registry} exec ${quote(process.execPath)} ${quote(LAUNCHER)} agent-device "$@"\n`;
|
||||
// One command per pinned release and installation, so two Explore installs on a machine never swap each other's
|
||||
// controller in the middle of a capture.
|
||||
const digest = createHash("sha256").update(script).digest("hex").slice(0, 12);
|
||||
const command = join(root, "bin", `agent-device-${CONTROLLER_PACKAGES["agent-device"].version}-${digest}`);
|
||||
if (existsSync(command) && readFileSync(command, "utf8") === script) return command;
|
||||
mkdirSync(dirname(command), { recursive: true, mode: 0o700 });
|
||||
const temporary = `${command}.${process.pid}.${randomUUID()}`;
|
||||
writeFileSync(temporary, script, { mode: 0o755 });
|
||||
renameSync(temporary, command);
|
||||
return command;
|
||||
}
|
||||
|
||||
/** A fetch killed mid-download (a timed-out controller call) leaves its staging files; clear any over an hour old. */
|
||||
async function removeAbandonedStaging(root: string): Promise<void> {
|
||||
const cutoff = Date.now() - 60 * 60_000;
|
||||
for (const name of await readdir(root).catch(() => [] as string[])) {
|
||||
if (!name.startsWith(".staging-")) continue;
|
||||
const path = join(root, name);
|
||||
const info = await stat(path).catch(() => undefined);
|
||||
if (info && info.mtimeMs < cutoff) await rm(path, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function downloadFailed(controller: ControllerName, message: string): CiError {
|
||||
const { name, version } = CONTROLLER_PACKAGES[controller];
|
||||
return new CiError({ code: "CONTROLLER_DOWNLOAD_FAILED", stage: "preflight", message: `${name}@${version} could not be fetched: ${message}`,
|
||||
nextAction: "Check that this machine can reach the npm registry (or set EXPLORE_NPM_REGISTRY to a mirror that serves it), then rerun." });
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the pinned controller into the cache once and returns its entry file. The download is hashed while it
|
||||
* streams and must match the pinned integrity before it is unpacked; only regular files and directories inside the
|
||||
* package are written, and the finished directory is renamed into place, so concurrent runs never see half of it.
|
||||
*/
|
||||
export async function ensureController(controller: ControllerName, options: {
|
||||
environment?: NodeJS.ProcessEnv; fetch?: typeof fetch; progress?: (message: string) => void;
|
||||
/** Tests: releases built on the spot instead of the pinned npm ones. */
|
||||
packages?: typeof CONTROLLER_PACKAGES;
|
||||
} = {}): Promise<string> {
|
||||
const environment = options.environment ?? process.env;
|
||||
const pinned = (options.packages ?? CONTROLLER_PACKAGES)[controller];
|
||||
const directory = controllerDirectory(controller, environment);
|
||||
const bin = join(directory, pinned.bin);
|
||||
if (controllerCached(controller, environment)) return bin;
|
||||
const root = controllerCacheRoot(environment);
|
||||
await mkdir(root, { recursive: true, mode: 0o700 });
|
||||
await removeAbandonedStaging(root);
|
||||
const staging = join(root, `.staging-${process.pid}-${randomUUID()}`);
|
||||
const tarball = `${staging}.tgz`;
|
||||
try {
|
||||
options.progress?.(`fetching ${pinned.name}@${pinned.version}`);
|
||||
let response: Response;
|
||||
try { response = await (options.fetch ?? fetch)(controllerTarballUrl(controller, environment)); }
|
||||
catch (error) { throw downloadFailed(controller, error instanceof Error ? error.message : String(error)); }
|
||||
if (!response.ok || !response.body) throw downloadFailed(controller, `the registry answered ${response.status}`);
|
||||
const hash = createHash("sha512");
|
||||
const file = await open(tarball, "wx", 0o600);
|
||||
let bytes = 0;
|
||||
try {
|
||||
for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {
|
||||
bytes += chunk.length;
|
||||
if (bytes > MAX_CONTROLLER_BYTES) throw downloadFailed(controller, "the tarball is larger than expected");
|
||||
hash.update(chunk);
|
||||
await file.write(chunk);
|
||||
}
|
||||
} finally { await file.close(); }
|
||||
const integrity = `sha512-${hash.digest("base64")}`;
|
||||
if (integrity !== pinned.integrity) {
|
||||
throw new CiError({ code: "CONTROLLER_INTEGRITY_MISMATCH", stage: "preflight",
|
||||
message: `${pinned.name}@${pinned.version} from the registry does not match the release Explore pins (${integrity}).`,
|
||||
nextAction: "Do not use this registry for Explore's controllers; unset EXPLORE_NPM_REGISTRY or point it at a faithful mirror." });
|
||||
}
|
||||
await mkdir(staging, { mode: 0o700 });
|
||||
let written = 0;
|
||||
await walkTar(tarball, async (entry, contents) => {
|
||||
const relative = safeRelativePath(entry.name);
|
||||
if (relative === "package" && entry.type === "5") return;
|
||||
if (!relative || !relative.startsWith("package/")) throw downloadFailed(controller, `the tarball has an entry outside the package (${entry.name})`);
|
||||
const target = join(staging, relative.slice("package/".length));
|
||||
if (!target.startsWith(`${staging}${sep}`)) throw downloadFailed(controller, `the tarball has an unsafe entry (${entry.name})`);
|
||||
if (entry.type === "5") { await mkdir(target, { recursive: true }); return; }
|
||||
if (entry.type !== "0") throw downloadFailed(controller, `the tarball has a link or special file (${entry.name})`);
|
||||
written += entry.size;
|
||||
if (written > MAX_CONTROLLER_BYTES) throw downloadFailed(controller, "the package is larger than expected");
|
||||
await mkdir(dirname(target), { recursive: true });
|
||||
await writeFile(target, await contents(), { mode: entry.mode & 0o111 ? 0o755 : 0o644 });
|
||||
});
|
||||
if (!existsSync(join(staging, pinned.bin))) throw downloadFailed(controller, `the package has no ${pinned.bin}`);
|
||||
await chmod(join(staging, pinned.bin), 0o755);
|
||||
await writeFile(join(staging, COMPLETE), `${JSON.stringify({ name: pinned.name, version: pinned.version, integrity })}\n`);
|
||||
try { await rename(staging, directory); }
|
||||
catch (error) {
|
||||
// Another run finished first; its copy is the same verified release.
|
||||
if (!controllerCached(controller, environment)) throw error;
|
||||
}
|
||||
return bin;
|
||||
} finally {
|
||||
await rm(tarball, { force: true });
|
||||
await rm(staging, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
@@ -5,9 +5,13 @@ on:
|
||||
push:
|
||||
workflow_dispatch:
|
||||
permissions: {}
|
||||
# The exact @expo/explore release CI installs. expo-explore setup --workflows sets it.
|
||||
env:
|
||||
# The exact @expo/explore release CI installs. expo-explore setup --workflows sets it.
|
||||
EXPLORE_VERSION: set-by-expo-explore-setup
|
||||
APP_PROJECT_DIR: .
|
||||
APP_INSTALL_DIR: .
|
||||
TOOLS_PREFIX: explore-tools
|
||||
TOOLS: explore-tools/package
|
||||
concurrency:
|
||||
group: explore-baseline-${{ github.sha }}
|
||||
cancel-in-progress: false
|
||||
@@ -21,16 +25,15 @@ jobs:
|
||||
contents: read
|
||||
outputs:
|
||||
platforms: ${{ steps.platforms.outputs.platforms }}
|
||||
env:
|
||||
TOOLS_PREFIX: explore-tools
|
||||
TOOLS: explore-tools/package
|
||||
APP_PROJECT_DIR: .
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with: { ref: '${{ github.sha }}', path: app, persist-credentials: false }
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
- &setup-node
|
||||
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with: { node-version: 24, package-manager-cache: false }
|
||||
- name: Install Explore
|
||||
- &install-explore
|
||||
name: Install Explore
|
||||
id: explore
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -61,10 +64,6 @@ jobs:
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
TOOLS_PREFIX: explore-tools
|
||||
TOOLS: explore-tools/package
|
||||
APP_PROJECT_DIR: .
|
||||
APP_INSTALL_DIR: .
|
||||
PLATFORM: ${{ matrix.platform }}
|
||||
steps:
|
||||
- name: Validate baseline source
|
||||
@@ -78,21 +77,8 @@ jobs:
|
||||
fi
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with: { ref: '${{ github.sha }}', path: app, fetch-depth: 0, persist-credentials: false }
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with: { node-version: 24, package-manager-cache: false }
|
||||
- name: Install Explore
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ ! "$EXPLORE_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then
|
||||
echo '::error title=EXPLORE_VERSION_INVALID::Set EXPLORE_VERSION to an exact @expo/explore version. Run expo-explore setup --workflows.'; exit 1
|
||||
fi
|
||||
# npm ci against the release's npm-shrinkwrap.json installs the exact dependency tree it was tested with.
|
||||
mkdir -p "$TOOLS_PREFIX"
|
||||
npm pack "@expo/explore@$EXPLORE_VERSION" --pack-destination "$TOOLS_PREFIX" --silent > /dev/null
|
||||
tar -xzf "$TOOLS_PREFIX"/expo-explore-*.tgz -C "$TOOLS_PREFIX"
|
||||
cd "$TOOLS"
|
||||
npm ci --omit=dev --include=optional --ignore-scripts --no-audit --no-fund
|
||||
- *setup-node
|
||||
- *install-explore
|
||||
- name: Install the launch recording decoder
|
||||
shell: bash
|
||||
# Launch recordings (capture.launch) are decoded with ffmpeg; GitHub's Ubuntu runners do not ship it.
|
||||
@@ -123,27 +109,13 @@ jobs:
|
||||
set -euo pipefail
|
||||
node "$TOOLS/dist/cli.js" capture:baseline --project "$GITHUB_WORKSPACE/app/$APP_PROJECT_DIR" \
|
||||
--sha "$GITHUB_SHA" --config .expo-explore/config.yaml --output "$RUNNER_TEMP/explore-baseline" --platform "$PLATFORM"
|
||||
- name: Stop retained baseline session
|
||||
if: always()
|
||||
timeout-minutes: 3
|
||||
- name: Stop the capture session and check the checkout
|
||||
if: always() && steps.explore.outcome == 'success'
|
||||
timeout-minutes: 5
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ ! -e "$RUNNER_TEMP/explore-baseline/baseline-session" && ! -L "$RUNNER_TEMP/explore-baseline/baseline-session" ]]; then exit 0; fi
|
||||
node "$TOOLS/scripts/cleanup-ci-sessions.mjs" --eas "$GITHUB_WORKSPACE/$TOOLS/node_modules/.bin/eas" \
|
||||
--session-file "$RUNNER_TEMP/explore-baseline/baseline-session"
|
||||
- name: Verify application checkout remains clean
|
||||
if: always()
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ -d app/.git || -f app/.git ]]; then
|
||||
if [[ -n "$(git -C app status --porcelain --untracked-files=all)" ]]; then
|
||||
echo '::error title=CHECKOUT_MODIFIED::Capture modified the application checkout. Keep generated files outside source.'; exit 1
|
||||
fi
|
||||
fi
|
||||
run: node "$TOOLS/dist/cli.js" ci:after-capture --output "$RUNNER_TEMP/explore-baseline" --checkout app
|
||||
- name: Upload exact-commit baseline evidence
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
|
||||
@@ -0,0 +1,288 @@
|
||||
# Generated by expo-explore setup. Fingerprint: set-by-expo-explore-setup
|
||||
# Install on the default branch. Reviews any two commits of this repository, with no pull request:
|
||||
# run it from the Actions tab, or call it from any workflow with the base and head that event needs.
|
||||
#
|
||||
# on: { push: { tags: ['v*'] } }
|
||||
# jobs:
|
||||
# explore:
|
||||
# permissions: { contents: read, actions: read }
|
||||
# uses: ./.github/workflows/explore-compare.yml
|
||||
# with: { base: v1.3.0, head: '${{ github.ref_name }}' }
|
||||
# secrets: inherit
|
||||
#
|
||||
# Call it once per workflow run: a called workflow shares its caller's run, and its artifact names come from the run.
|
||||
# The report links are written to the run's summary. For a release, pass scope: all to capture every screen,
|
||||
# and expires-in: never to keep the hosted link (report.preview.hosting: eas) working.
|
||||
name: Expo Explore compare
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
base: { description: 'Base: a branch, tag or commit SHA', required: true }
|
||||
head: { description: 'Head: a branch, tag or commit SHA', required: true }
|
||||
scope: { description: 'changes (screens whose source changed) or all; default: exploration.scope in config.yaml', required: false, default: '' }
|
||||
expires-in: { description: 'Hosted link lifetime such as 30d, or never; default: report.preview.expiresAfter', required: false, default: '' }
|
||||
workflow_call:
|
||||
inputs:
|
||||
base: { description: 'Base: a branch, tag or commit SHA', required: true, type: string }
|
||||
head: { description: 'Head: a branch, tag or commit SHA', required: true, type: string }
|
||||
scope: { description: 'changes (screens whose source changed) or all; default: exploration.scope in config.yaml', required: false, type: string, default: '' }
|
||||
expires-in: { description: 'Hosted link lifetime such as 30d, or never; default: report.preview.expiresAfter', required: false, type: string, default: '' }
|
||||
permissions: {}
|
||||
env:
|
||||
# The exact @expo/explore release CI installs. expo-explore setup --workflows sets it.
|
||||
EXPLORE_VERSION: set-by-expo-explore-setup
|
||||
APP_PROJECT_DIR: .
|
||||
APP_INSTALL_DIR: .
|
||||
TOOLS_PREFIX: explore-tools
|
||||
TOOLS: explore-tools/package
|
||||
concurrency:
|
||||
# ".." cannot appear in a ref name, so no two different comparisons share a group.
|
||||
group: explore-compare-${{ inputs.base }}..${{ inputs.head }}
|
||||
cancel-in-progress: false
|
||||
jobs:
|
||||
# Resolves both refs to commits once, and lists the platforms .expo-explore/config.yaml captures at head.
|
||||
platforms:
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 10
|
||||
permissions:
|
||||
contents: read
|
||||
outputs:
|
||||
platforms: ${{ steps.platforms.outputs.platforms }}
|
||||
base: ${{ steps.refs.outputs.base }}
|
||||
head: ${{ steps.refs.outputs.head }}
|
||||
compare: ${{ steps.refs.outputs.compare }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with: { path: app-head, fetch-depth: 0, persist-credentials: false }
|
||||
- &setup-node
|
||||
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with: { node-version: 24, package-manager-cache: false }
|
||||
- &install-explore
|
||||
name: Install Explore
|
||||
id: explore
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ ! "$EXPLORE_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then
|
||||
echo '::error title=EXPLORE_VERSION_INVALID::Set EXPLORE_VERSION to an exact @expo/explore version. Run expo-explore setup --workflows.'; exit 1
|
||||
fi
|
||||
# npm ci against the release's npm-shrinkwrap.json installs the exact dependency tree it was tested with.
|
||||
mkdir -p "$TOOLS_PREFIX"
|
||||
npm pack "@expo/explore@$EXPLORE_VERSION" --pack-destination "$TOOLS_PREFIX" --silent > /dev/null
|
||||
tar -xzf "$TOOLS_PREFIX"/expo-explore-*.tgz -C "$TOOLS_PREFIX"
|
||||
cd "$TOOLS"
|
||||
npm ci --omit=dev --include=optional --ignore-scripts --no-audit --no-fund
|
||||
- name: Resolve base and head to commits
|
||||
id: refs
|
||||
env:
|
||||
BASE_REF: ${{ inputs.base }}
|
||||
HEAD_REF: ${{ inputs.head }}
|
||||
shell: bash
|
||||
run: node "$TOOLS/dist/cli.js" ci:compare-refs --project app-head --base "$BASE_REF" --head "$HEAD_REF"
|
||||
- name: Check out head
|
||||
env:
|
||||
HEAD_SHA: ${{ steps.refs.outputs.head }}
|
||||
shell: bash
|
||||
run: git -C app-head checkout --quiet --detach "$HEAD_SHA"
|
||||
- name: List the configured platforms
|
||||
id: platforms
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
platforms="$(node "$TOOLS/dist/cli.js" config:platforms --project "$GITHUB_WORKSPACE/app-head/$APP_PROJECT_DIR" --config .expo-explore/config.yaml | jq -c '.platforms')"
|
||||
echo "platforms=$platforms" >> "$GITHUB_OUTPUT"
|
||||
capture:
|
||||
needs: platforms
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
platform: ${{ fromJSON(needs.platforms.outputs.platforms) }}
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 120
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
outputs:
|
||||
# "eas" when .expo-explore/config.yaml sets report.preview.hosting; the deploy job runs only then.
|
||||
preview: ${{ steps.capture.outputs.preview }}
|
||||
env:
|
||||
PLATFORM: ${{ matrix.platform }}
|
||||
BASE_SHA: ${{ needs.platforms.outputs.base }}
|
||||
HEAD_SHA: ${{ needs.platforms.outputs.head }}
|
||||
steps:
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with: { ref: '${{ needs.platforms.outputs.base }}', path: app-base, fetch-depth: 0, persist-credentials: false }
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with: { ref: '${{ needs.platforms.outputs.head }}', path: app-head, fetch-depth: 0, persist-credentials: false }
|
||||
- *setup-node
|
||||
- *install-explore
|
||||
- name: Install the launch recording decoder
|
||||
shell: bash
|
||||
# Launch recordings (capture.launch) are decoded with ffmpeg; GitHub's Ubuntu runners do not ship it.
|
||||
run: |
|
||||
set -euo pipefail
|
||||
command -v ffmpeg > /dev/null || { sudo apt-get update -qq && sudo apt-get install -y -qq --no-install-recommends ffmpeg > /dev/null; }
|
||||
ffmpeg -version | head -1
|
||||
- name: Verify deterministic source planning
|
||||
env:
|
||||
SCOPE: ${{ inputs.scope }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
node "$TOOLS/dist/cli.js" source:verify \
|
||||
--base-project "$GITHUB_WORKSPACE/app-base/$APP_PROJECT_DIR" --head-project "$GITHUB_WORKSPACE/app-head/$APP_PROJECT_DIR" \
|
||||
--base-sha "$BASE_SHA" --head-sha "$HEAD_SHA" --config .expo-explore/config.yaml --output "$RUNNER_TEMP/explore-consistency" \
|
||||
--platform "$PLATFORM" ${SCOPE:+--scope "$SCOPE"}
|
||||
- name: Install app dependencies
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
npm ci --ignore-scripts --prefix "app-base/$APP_INSTALL_DIR"
|
||||
npm ci --ignore-scripts --prefix "app-head/$APP_INSTALL_DIR"
|
||||
- name: Find optional exact-base evidence
|
||||
id: cache
|
||||
continue-on-error: true
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
shell: bash
|
||||
run: node "$TOOLS/dist/cli.js" ci:find-baseline --sha "$BASE_SHA" --platform "$PLATFORM"
|
||||
- name: Download optional exact-base evidence
|
||||
if: steps.cache.outputs.id != ''
|
||||
continue-on-error: true
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
artifact-ids: ${{ steps.cache.outputs.id }}
|
||||
path: ${{ runner.temp }}/explore-cache
|
||||
merge-multiple: true
|
||||
run-id: ${{ steps.cache.outputs.run }}
|
||||
github-token: ${{ github.token }}
|
||||
- name: Capture review
|
||||
id: capture
|
||||
env:
|
||||
COMPARE: ${{ needs.platforms.outputs.compare }}
|
||||
SCOPE: ${{ inputs.scope }}
|
||||
EXPIRES_IN: ${{ inputs.expires-in }}
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
|
||||
ANTHROPIC_WORKSPACE_ID: ${{ vars.ANTHROPIC_WORKSPACE_ID }}
|
||||
# App-test secrets: one NAME: line per {{secret:NAME}} input in .expo-explore (expo-explore setup adds them).
|
||||
EXPLORE_CAPTURE_CACHE: ${{ runner.temp }}/explore-cache
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
printf '%s' "$COMPARE" > "$RUNNER_TEMP/explore-compare.json"
|
||||
node "$TOOLS/dist/cli.js" capture:review \
|
||||
--base-project "$GITHUB_WORKSPACE/app-base/$APP_PROJECT_DIR" --head-project "$GITHUB_WORKSPACE/app-head/$APP_PROJECT_DIR" \
|
||||
--compare "$RUNNER_TEMP/explore-compare.json" --output "$RUNNER_TEMP/explore-review" --config .expo-explore/config.yaml \
|
||||
--platform "$PLATFORM" ${SCOPE:+--scope "$SCOPE"} ${EXPIRES_IN:+--expires-in "$EXPIRES_IN"}
|
||||
- name: Stop capture sessions and check the checkouts
|
||||
if: always() && steps.explore.outcome == 'success'
|
||||
timeout-minutes: 5
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
shell: bash
|
||||
run: node "$TOOLS/dist/cli.js" ci:after-capture --output "$RUNNER_TEMP/explore-review" --checkout app-base --checkout app-head
|
||||
- name: Upload captured review for packaging
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: explore-capture-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.platform }}
|
||||
path: |
|
||||
${{ runner.temp }}/explore-review/report-input.json
|
||||
${{ runner.temp }}/explore-review/plan.json
|
||||
${{ runner.temp }}/explore-review/bundle.json
|
||||
${{ runner.temp }}/explore-review/review.json
|
||||
${{ runner.temp }}/explore-review/execution.json
|
||||
${{ runner.temp }}/explore-review/base-export
|
||||
${{ runner.temp }}/explore-review/head-export
|
||||
retention-days: 7
|
||||
if-no-files-found: error
|
||||
- name: Upload planning and failure diagnostics
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: explore-diagnostics-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.platform }}
|
||||
path: |
|
||||
${{ runner.temp }}/explore-consistency
|
||||
${{ runner.temp }}/explore-diagnostics
|
||||
${{ runner.temp }}/explore-review/execution.json
|
||||
${{ runner.temp }}/explore-review/diagnostics.json
|
||||
${{ runner.temp }}/explore-review/base-export
|
||||
${{ runner.temp }}/explore-review/head-export
|
||||
${{ runner.temp }}/explore-review/base-map/capture-diagnostics
|
||||
${{ runner.temp }}/explore-review/head-map/capture-diagnostics
|
||||
${{ runner.temp }}/explore-review/agent-notes-diagnostics.json
|
||||
${{ runner.temp }}/explore-review/agent-usage.jsonl
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
report:
|
||||
needs: [platforms, capture]
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
platform: ${{ fromJSON(needs.platforms.outputs.platforms) }}
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 20
|
||||
permissions:
|
||||
contents: read
|
||||
env:
|
||||
PLATFORM: ${{ matrix.platform }}
|
||||
steps:
|
||||
- *setup-node
|
||||
- *install-explore
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: explore-capture-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.platform }}
|
||||
path: ${{ runner.temp }}/explore-review
|
||||
- name: Package the report
|
||||
shell: bash
|
||||
run: node "$TOOLS/dist/cli.js" ci:report --input "$RUNNER_TEMP/explore-review/report-input.json" --output "$RUNNER_TEMP/explore-report" --platform "$PLATFORM"
|
||||
- name: Upload the report
|
||||
id: report
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: explore-review-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.platform }}
|
||||
path: ${{ runner.temp }}/explore-report
|
||||
retention-days: 30
|
||||
if-no-files-found: error
|
||||
- name: Link the report from the run summary
|
||||
env:
|
||||
ARTIFACT_URL: ${{ steps.report.outputs.artifact-url }}
|
||||
shell: bash
|
||||
run: node "$TOOLS/dist/cli.js" ci:publish --input "$RUNNER_TEMP/explore-review/report-input.json" --artifact-url "$ARTIFACT_URL" --platform "$PLATFORM"
|
||||
- name: Upload report failure diagnostics
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
name: explore-report-diagnostics-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.platform }}
|
||||
path: ${{ runner.temp }}/explore-diagnostics
|
||||
retention-days: 7
|
||||
if-no-files-found: ignore
|
||||
# Hosted report (opt-in, report.preview in config.yaml): one token-gated EAS Hosting deployment serving every platform's report.
|
||||
# This is the only job after capture that holds EXPO_TOKEN; it writes the link to the run summary.
|
||||
deploy:
|
||||
needs: [platforms, capture, report]
|
||||
if: needs.capture.outputs.preview == 'eas'
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 20
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
steps:
|
||||
- *setup-node
|
||||
- *install-explore
|
||||
# One directory per platform artifact (explore-capture-<run>-<attempt>-<platform>, explore-review-<run>-<attempt>-<platform>).
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
pattern: explore-capture-${{ github.run_id }}-${{ github.run_attempt }}-*
|
||||
path: ${{ runner.temp }}/explore-review
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
pattern: explore-review-${{ github.run_id }}-${{ github.run_attempt }}-*
|
||||
path: ${{ runner.temp }}/explore-report
|
||||
- name: Deploy the hosted report and link it from the run summary
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
shell: bash
|
||||
run: node "$TOOLS/dist/cli.js" ci:deploy --inputs "$RUNNER_TEMP/explore-review" --reports "$RUNNER_TEMP/explore-report"
|
||||
@@ -9,9 +9,14 @@ on:
|
||||
inputs:
|
||||
pr: { description: Open same-repository pull request number, required: true }
|
||||
permissions: {}
|
||||
# The exact @expo/explore release CI installs. expo-explore setup --workflows sets it.
|
||||
env:
|
||||
# The exact @expo/explore release CI installs. expo-explore setup --workflows sets it.
|
||||
EXPLORE_VERSION: set-by-expo-explore-setup
|
||||
APP_PROJECT_DIR: .
|
||||
APP_INSTALL_DIR: .
|
||||
TOOLS_PREFIX: explore-tools
|
||||
TOOLS: explore-tools/package
|
||||
PR_NUMBER: ${{ github.event.pull_request.number || inputs.pr }}
|
||||
concurrency:
|
||||
group: explore-review-${{ github.event.pull_request.number || inputs.pr }}
|
||||
cancel-in-progress: false
|
||||
@@ -28,31 +33,17 @@ jobs:
|
||||
pull-requests: read
|
||||
outputs:
|
||||
platforms: ${{ steps.platforms.outputs.platforms }}
|
||||
env:
|
||||
TOOLS_PREFIX: explore-tools
|
||||
TOOLS: explore-tools/package
|
||||
APP_PROJECT_DIR: .
|
||||
# The failure job comments with these when a capture job fails before it resolves the PR itself.
|
||||
pr_number: ${{ steps.pr.outputs.pr_number }}
|
||||
base: ${{ steps.pr.outputs.base }}
|
||||
head: ${{ steps.pr.outputs.head }}
|
||||
steps:
|
||||
- name: Resolve the live pull request head
|
||||
id: pr
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
env:
|
||||
PR_NUMBER: ${{ github.event.pull_request.number || inputs.pr }}
|
||||
with:
|
||||
script: |
|
||||
const number = Number(process.env.PR_NUMBER);
|
||||
if (!Number.isSafeInteger(number) || number <= 0) throw new Error('PR_NUMBER_INVALID: Provide an open pull request number.');
|
||||
const { data: pr } = await github.rest.pulls.get({ ...context.repo, pull_number: number });
|
||||
if (pr.state !== 'open' || pr.draft || pr.head.repo?.full_name !== `${context.repo.owner}/${context.repo.repo}`) {
|
||||
throw new Error('SOURCE_NOT_TRUSTED: Capture requires an open, non-draft same-repository pull request.');
|
||||
}
|
||||
if (!/^[0-9a-f]{40}$/.test(pr.head.sha)) throw new Error('PR_COMMIT_INVALID: Refresh the PR and rerun Explore.');
|
||||
core.setOutput('head', pr.head.sha);
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with: { ref: '${{ steps.pr.outputs.head }}', path: app-head, persist-credentials: false }
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
- &setup-node
|
||||
uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with: { node-version: 24, package-manager-cache: false }
|
||||
- name: Install Explore
|
||||
- &install-explore
|
||||
name: Install Explore
|
||||
id: explore
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
@@ -65,6 +56,14 @@ jobs:
|
||||
tar -xzf "$TOOLS_PREFIX"/expo-explore-*.tgz -C "$TOOLS_PREFIX"
|
||||
cd "$TOOLS"
|
||||
npm ci --omit=dev --include=optional --ignore-scripts --no-audit --no-fund
|
||||
- name: Resolve and authorize the live pull request
|
||||
id: pr
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
shell: bash
|
||||
run: node "$TOOLS/dist/cli.js" ci:pr --pr "$PR_NUMBER" --app-dir "$APP_PROJECT_DIR"
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with: { ref: '${{ steps.pr.outputs.head }}', path: app-head, persist-credentials: false }
|
||||
- name: List the configured platforms
|
||||
id: platforms
|
||||
shell: bash
|
||||
@@ -90,71 +89,22 @@ jobs:
|
||||
base: ${{ steps.pr.outputs.base }}
|
||||
head: ${{ steps.pr.outputs.head }}
|
||||
# "eas" when .expo-explore/config.yaml sets report.preview.hosting; the deploy job runs only then.
|
||||
preview: ${{ steps.preview.outputs.preview }}
|
||||
preview: ${{ steps.capture.outputs.preview }}
|
||||
env:
|
||||
TOOLS_PREFIX: explore-tools
|
||||
TOOLS: explore-tools/package
|
||||
APP_PROJECT_DIR: .
|
||||
APP_INSTALL_DIR: .
|
||||
PLATFORM: ${{ matrix.platform }}
|
||||
steps:
|
||||
- name: Resolve the live pull request and authorize its source
|
||||
- *setup-node
|
||||
- *install-explore
|
||||
- name: Resolve and authorize the live pull request
|
||||
id: pr
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
env:
|
||||
PR_NUMBER: ${{ github.event.pull_request.number || inputs.pr }}
|
||||
with:
|
||||
script: |
|
||||
const number = Number(process.env.PR_NUMBER);
|
||||
if (!Number.isSafeInteger(number) || number <= 0) throw new Error('PR_NUMBER_INVALID: Provide an open pull request number.');
|
||||
const { data: pr } = await github.rest.pulls.get({ ...context.repo, pull_number: number });
|
||||
if (pr.state !== 'open' || pr.draft || pr.head.repo?.full_name !== `${context.repo.owner}/${context.repo.repo}`) {
|
||||
throw new Error('SOURCE_NOT_TRUSTED: Capture requires an open, non-draft same-repository pull request.');
|
||||
}
|
||||
// ci.trustedAuthors in the default branch's config.yaml: logins (bots) reviewed without write access. A PR cannot add its own author.
|
||||
const trustedAuthors = async () => {
|
||||
const dir = (process.env.APP_PROJECT_DIR || '.').replace(/^\.(\/|$)/, '').replace(/\/$/, '');
|
||||
const path = `${dir ? `${dir}/` : ''}.expo-explore/config.yaml`;
|
||||
let yaml;
|
||||
try {
|
||||
const { data } = await github.rest.repos.getContent({ ...context.repo, path, ref: pr.base.repo.default_branch });
|
||||
yaml = Buffer.from(data.content, 'base64').toString('utf8');
|
||||
} catch (error) { if (error.status === 404) return []; throw error; }
|
||||
const block = yaml.match(/^ci:[ \t]*(?:#.*)?\n((?:[ \t]+\S.*\n?|[ \t]*\n)*)/m)?.[1] ?? '';
|
||||
const list = block.match(/^[ \t]+trustedAuthors:[ \t]*(?:\[(.*?)\][ \t]*(?:#.*)?$|(?:#.*)?\n((?:[ \t]+-[ \t]*\S.*\n?)+))/m);
|
||||
if (!list) return [];
|
||||
const entries = list[1] !== undefined ? list[1].split(',') : list[2].split('\n').map(line => line.replace(/^[ \t]+-[ \t]*/, ''));
|
||||
return entries.map(entry => entry.replace(/\s+#.*$/, '').trim().replace(/^(['"])(.*)\1$/, '$2').toLowerCase()).filter(Boolean);
|
||||
};
|
||||
const { data: permission } = await github.rest.repos.getCollaboratorPermissionLevel({ ...context.repo, username: pr.user.login });
|
||||
if (!['admin', 'maintain', 'write'].includes(permission.permission) && !(await trustedAuthors()).includes(pr.user.login.toLowerCase())) {
|
||||
throw new Error('SOURCE_NOT_TRUSTED: The PR author must have current repository write access (or be listed in ci.trustedAuthors of .expo-explore/config.yaml on the default branch).');
|
||||
}
|
||||
for (const side of [pr.base, pr.head]) if (!/^[0-9a-f]{40}$/.test(side.sha)) throw new Error('PR_COMMIT_INVALID: Refresh the PR and rerun Explore.');
|
||||
require('node:fs').writeFileSync(`${process.env.RUNNER_TEMP}/explore-pr.json`, JSON.stringify({
|
||||
repositoryId: String(pr.base.repo.id), repository: pr.base.repo.full_name, number: pr.number,
|
||||
title: pr.title, url: pr.html_url, base: { ref: pr.base.ref, sha: pr.base.sha }, head: { ref: pr.head.ref, sha: pr.head.sha }
|
||||
}));
|
||||
core.setOutput('pr_number', pr.number); core.setOutput('base', pr.base.sha); core.setOutput('head', pr.head.sha);
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
shell: bash
|
||||
run: node "$TOOLS/dist/cli.js" ci:pr --pr "$PR_NUMBER" --app-dir "$APP_PROJECT_DIR" --output "$RUNNER_TEMP/explore-pr.json"
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with: { ref: '${{ steps.pr.outputs.base }}', path: app-base, fetch-depth: 0, persist-credentials: false }
|
||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
||||
with: { ref: '${{ steps.pr.outputs.head }}', path: app-head, fetch-depth: 0, persist-credentials: false }
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with: { node-version: 24, package-manager-cache: false }
|
||||
- name: Install Explore
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ ! "$EXPLORE_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then
|
||||
echo '::error title=EXPLORE_VERSION_INVALID::Set EXPLORE_VERSION to an exact @expo/explore version. Run expo-explore setup --workflows.'; exit 1
|
||||
fi
|
||||
# npm ci against the release's npm-shrinkwrap.json installs the exact dependency tree it was tested with.
|
||||
mkdir -p "$TOOLS_PREFIX"
|
||||
npm pack "@expo/explore@$EXPLORE_VERSION" --pack-destination "$TOOLS_PREFIX" --silent > /dev/null
|
||||
tar -xzf "$TOOLS_PREFIX"/expo-explore-*.tgz -C "$TOOLS_PREFIX"
|
||||
cd "$TOOLS"
|
||||
npm ci --omit=dev --include=optional --ignore-scripts --no-audit --no-fund
|
||||
- name: Install the launch recording decoder
|
||||
shell: bash
|
||||
# Launch recordings (capture.launch) are decoded with ffmpeg; GitHub's Ubuntu runners do not ship it.
|
||||
@@ -182,24 +132,11 @@ jobs:
|
||||
- name: Find optional exact-base evidence
|
||||
id: cache
|
||||
continue-on-error: true
|
||||
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
BASE_SHA: ${{ steps.pr.outputs.base }}
|
||||
with:
|
||||
script: |
|
||||
const { data: repository } = await github.rest.repos.get(context.repo);
|
||||
const { data: baseline } = await github.rest.actions.getWorkflow({ ...context.repo, workflow_id: 'explore-baseline.yml' });
|
||||
// Baselines carry the platform suffix; iOS also accepts the unsuffixed name older baseline workflows uploaded.
|
||||
const names = [`explore-baseline-${process.env.BASE_SHA}-${process.env.PLATFORM}`, ...(process.env.PLATFORM === 'ios' ? [`explore-baseline-${process.env.BASE_SHA}`] : [])];
|
||||
const records = (await Promise.all(names.map(name => github.paginate(github.rest.actions.listArtifactsForRepo, { ...context.repo, name, per_page: 100 })))).flat();
|
||||
for (const artifact of records.filter(a => !a.expired).sort((a, b) => b.id - a.id)) {
|
||||
if (!artifact.workflow_run?.id) continue;
|
||||
const { data: run } = await github.rest.actions.getWorkflowRun({ ...context.repo, run_id: artifact.workflow_run.id });
|
||||
if (run.conclusion !== 'success' || run.workflow_id !== baseline.id || run.head_sha !== process.env.BASE_SHA
|
||||
|| run.head_branch !== repository.default_branch || !['push', 'workflow_dispatch'].includes(run.event)
|
||||
|| run.head_repository?.full_name !== `${context.repo.owner}/${context.repo.repo}`) continue;
|
||||
core.setOutput('id', artifact.id); core.setOutput('run', run.id); break;
|
||||
}
|
||||
shell: bash
|
||||
run: node "$TOOLS/dist/cli.js" ci:find-baseline --sha "$BASE_SHA" --platform "$PLATFORM"
|
||||
- name: Download optional exact-base evidence
|
||||
if: steps.cache.outputs.id != ''
|
||||
continue-on-error: true
|
||||
@@ -211,6 +148,7 @@ jobs:
|
||||
run-id: ${{ steps.cache.outputs.run }}
|
||||
github-token: ${{ github.token }}
|
||||
- name: Capture review
|
||||
id: capture
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
@@ -226,35 +164,13 @@ jobs:
|
||||
--base-project "$GITHUB_WORKSPACE/app-base/$APP_PROJECT_DIR" --head-project "$GITHUB_WORKSPACE/app-head/$APP_PROJECT_DIR" \
|
||||
--pull-request "$RUNNER_TEMP/explore-pr.json" --output "$RUNNER_TEMP/explore-review" --config .expo-explore/config.yaml \
|
||||
--platform "$PLATFORM"
|
||||
- name: Stop retained capture sessions
|
||||
if: always()
|
||||
- name: Stop capture sessions and check the checkouts
|
||||
if: always() && steps.pr.outcome == 'success'
|
||||
timeout-minutes: 5
|
||||
env:
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ ! -e "$RUNNER_TEMP/explore-review/head-session" && ! -L "$RUNNER_TEMP/explore-review/head-session" && ! -e "$RUNNER_TEMP/explore-review/base-session" && ! -L "$RUNNER_TEMP/explore-review/base-session" ]]; then exit 0; fi
|
||||
node "$TOOLS/scripts/cleanup-ci-sessions.mjs" --eas "$GITHUB_WORKSPACE/$TOOLS/node_modules/.bin/eas" \
|
||||
--session-file "$RUNNER_TEMP/explore-review/head-session" --session-file "$RUNNER_TEMP/explore-review/base-session"
|
||||
- name: Verify application checkouts remain clean
|
||||
if: always() && steps.pr.outcome == 'success'
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
for directory in app-base app-head; do
|
||||
if [[ -d "$directory/.git" || -f "$directory/.git" ]]; then
|
||||
if [[ -n "$(git -C "$directory" status --porcelain --untracked-files=all)" ]]; then
|
||||
echo "::error title=CHECKOUT_MODIFIED::Capture modified $directory. Keep generated files outside source checkouts."; exit 1
|
||||
fi
|
||||
fi
|
||||
done
|
||||
- name: Read the hosted preview request
|
||||
id: preview
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
echo "preview=$(jq -r '.preview.hosting // ""' "$RUNNER_TEMP/explore-review/report-input.json")" >> "$GITHUB_OUTPUT"
|
||||
run: node "$TOOLS/dist/cli.js" ci:after-capture --output "$RUNNER_TEMP/explore-review" --checkout app-base --checkout app-head
|
||||
- name: Upload captured review for packaging
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
with:
|
||||
@@ -300,34 +216,17 @@ jobs:
|
||||
actions: read
|
||||
pull-requests: write
|
||||
env:
|
||||
TOOLS_PREFIX: explore-tools
|
||||
TOOLS: explore-tools/package
|
||||
PLATFORM: ${{ matrix.platform }}
|
||||
steps:
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with: { node-version: 24, package-manager-cache: false }
|
||||
- name: Install Explore
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ ! "$EXPLORE_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then
|
||||
echo '::error title=EXPLORE_VERSION_INVALID::Set EXPLORE_VERSION to an exact @expo/explore version. Run expo-explore setup --workflows.'; exit 1
|
||||
fi
|
||||
# npm ci against the release's npm-shrinkwrap.json installs the exact dependency tree it was tested with.
|
||||
mkdir -p "$TOOLS_PREFIX"
|
||||
npm pack "@expo/explore@$EXPLORE_VERSION" --pack-destination "$TOOLS_PREFIX" --silent > /dev/null
|
||||
tar -xzf "$TOOLS_PREFIX"/expo-explore-*.tgz -C "$TOOLS_PREFIX"
|
||||
cd "$TOOLS"
|
||||
npm ci --omit=dev --include=optional --ignore-scripts --no-audit --no-fund
|
||||
- *setup-node
|
||||
- *install-explore
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: explore-capture-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.platform }}
|
||||
path: ${{ runner.temp }}/explore-review
|
||||
- name: Package hosted review bundle
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
node "$TOOLS/dist/cli.js" ci:report --input "$RUNNER_TEMP/explore-review/report-input.json" --output "$RUNNER_TEMP/explore-report" --platform "$PLATFORM"
|
||||
run: node "$TOOLS/dist/cli.js" ci:report --input "$RUNNER_TEMP/explore-review/report-input.json" --output "$RUNNER_TEMP/explore-report" --platform "$PLATFORM"
|
||||
- name: Upload hosted review bundle
|
||||
id: viewer
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
@@ -341,9 +240,7 @@ jobs:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
ARTIFACT_URL: ${{ steps.viewer.outputs.artifact-url }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
node "$TOOLS/dist/cli.js" ci:publish --input "$RUNNER_TEMP/explore-review/report-input.json" --artifact-url "$ARTIFACT_URL" --platform "$PLATFORM"
|
||||
run: node "$TOOLS/dist/cli.js" ci:publish --input "$RUNNER_TEMP/explore-review/report-input.json" --artifact-url "$ARTIFACT_URL" --platform "$PLATFORM"
|
||||
- name: Upload report failure diagnostics
|
||||
if: always()
|
||||
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
|
||||
@@ -364,31 +261,15 @@ jobs:
|
||||
contents: read
|
||||
actions: read
|
||||
pull-requests: write
|
||||
env:
|
||||
TOOLS_PREFIX: explore-tools
|
||||
TOOLS: explore-tools/package
|
||||
steps:
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with: { node-version: 24, package-manager-cache: false }
|
||||
- name: Install Explore
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ ! "$EXPLORE_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then
|
||||
echo '::error title=EXPLORE_VERSION_INVALID::Set EXPLORE_VERSION to an exact @expo/explore version. Run expo-explore setup --workflows.'; exit 1
|
||||
fi
|
||||
mkdir -p "$TOOLS_PREFIX"
|
||||
npm pack "@expo/explore@$EXPLORE_VERSION" --pack-destination "$TOOLS_PREFIX" --silent > /dev/null
|
||||
tar -xzf "$TOOLS_PREFIX"/expo-explore-*.tgz -C "$TOOLS_PREFIX"
|
||||
cd "$TOOLS"
|
||||
npm ci --omit=dev --include=optional --ignore-scripts --no-audit --no-fund
|
||||
- *setup-node
|
||||
- *install-explore
|
||||
# One directory per platform artifact (explore-capture-<run>-<attempt>-<platform>, explore-review-<run>-<attempt>-<platform>).
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
pattern: explore-capture-${{ github.run_id }}-${{ github.run_attempt }}-*
|
||||
path: ${{ runner.temp }}/explore-review
|
||||
- uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
id: report
|
||||
with:
|
||||
pattern: explore-review-${{ github.run_id }}-${{ github.run_attempt }}-*
|
||||
path: ${{ runner.temp }}/explore-report
|
||||
@@ -397,9 +278,7 @@ jobs:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
EXPO_TOKEN: ${{ secrets.EXPO_TOKEN }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
node "$TOOLS/dist/cli.js" ci:deploy --inputs "$RUNNER_TEMP/explore-review" --reports "$RUNNER_TEMP/explore-report"
|
||||
run: node "$TOOLS/dist/cli.js" ci:deploy --inputs "$RUNNER_TEMP/explore-review" --reports "$RUNNER_TEMP/explore-report"
|
||||
failure:
|
||||
needs: [platforms, capture, report, deploy]
|
||||
if: always() && (needs.platforms.result == 'failure' || needs.capture.result == 'failure' || needs.report.result == 'failure' || needs.deploy.result == 'failure')
|
||||
@@ -408,9 +287,6 @@ jobs:
|
||||
permissions:
|
||||
actions: read
|
||||
pull-requests: write
|
||||
env:
|
||||
TOOLS_PREFIX: explore-tools
|
||||
TOOLS: explore-tools/package
|
||||
steps:
|
||||
- name: Download capture failure diagnostic
|
||||
if: needs.capture.result == 'failure'
|
||||
@@ -426,26 +302,14 @@ jobs:
|
||||
with:
|
||||
pattern: explore-report-diagnostics-${{ github.run_id }}-${{ github.run_attempt }}-*
|
||||
path: ${{ runner.temp }}/explore-failure/report
|
||||
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
|
||||
with: { node-version: 24, package-manager-cache: false }
|
||||
- name: Install Explore
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
if [[ ! "$EXPLORE_VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?$ ]]; then
|
||||
echo '::error title=EXPLORE_VERSION_INVALID::Set EXPLORE_VERSION to an exact @expo/explore version. Run expo-explore setup --workflows.'; exit 1
|
||||
fi
|
||||
mkdir -p "$TOOLS_PREFIX"
|
||||
npm pack "@expo/explore@$EXPLORE_VERSION" --pack-destination "$TOOLS_PREFIX" --silent > /dev/null
|
||||
tar -xzf "$TOOLS_PREFIX"/expo-explore-*.tgz -C "$TOOLS_PREFIX"
|
||||
cd "$TOOLS"
|
||||
npm ci --omit=dev --include=optional --ignore-scripts --no-audit --no-fund
|
||||
- *setup-node
|
||||
- *install-explore
|
||||
- name: Report failure only on the current PR
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
PR_NUMBER: ${{ needs.capture.outputs.pr_number }}
|
||||
HEAD_SHA: ${{ needs.capture.outputs.head }}
|
||||
BASE_SHA: ${{ needs.capture.outputs.base }}
|
||||
PR_NUMBER: ${{ needs.capture.outputs.pr_number || needs.platforms.outputs.pr_number }}
|
||||
HEAD_SHA: ${{ needs.capture.outputs.head || needs.platforms.outputs.head }}
|
||||
BASE_SHA: ${{ needs.capture.outputs.base || needs.platforms.outputs.base }}
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
@@ -403,7 +403,7 @@ test("a hosted preview link downloads the report from its own token route, opens
|
||||
preview: { ...preview, token: "cdefghijklmnopqrstuvwxyz23456723", status: 410, body: JSON.stringify({ error: "expired", expiredAt: "2030-01-01T00:00:00.000Z" }) } });
|
||||
const goneShell = gone.page.locator(".report-loading-shell");
|
||||
await expect(goneShell).toHaveAttribute("data-loading-status", "failed");
|
||||
await expect(goneShell).toContainText("This preview link expired on Jan 1, 2030. Download the report from the pull request instead");
|
||||
await expect(goneShell).toContainText("This preview link expired on Jan 1, 2030. Download the report from the pull request or workflow run instead");
|
||||
await expect(gone.page.locator(".report-drop-input")).toHaveCount(0);
|
||||
assert.deepEqual(gone.errors, []);
|
||||
});
|
||||
@@ -1005,7 +1005,7 @@ test("a docs-only report with zero images and no EAS build opens Screens without
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test("unverified capture diagnostics stay separate from verified Needs review and source impact filters", async t => {
|
||||
test("unverified capture diagnostics stay separate from verified Needs review, and source changes nobody compared are not changes", async t => {
|
||||
const report = reportFixture();
|
||||
const home = report.review.surfaces[0];
|
||||
const uncertain = structuredClone(home);
|
||||
@@ -1029,12 +1029,13 @@ test("unverified capture diagnostics stay separate from verified Needs review an
|
||||
await expect(page.locator(".app-shell")).toBeVisible();
|
||||
await page.getByRole("button", { name: "Screens", exact: true }).click();
|
||||
await expect(page.locator(".screens-page .diff-frame.diff-needs-review")).toHaveCount(1);
|
||||
await expect(page.locator(".screens-page .diff-frame.diff-source-affected")).toHaveCount(2);
|
||||
await expect(page.locator(".screens-page .diff-frame.diff-not-compared")).toHaveCount(1);
|
||||
// The unverified /home and the never-captured /candidate changed in source only: not compared, like /untouched.
|
||||
await expect(page.locator(".screens-page .diff-frame.diff-source-affected")).toHaveCount(0);
|
||||
await expect(page.locator(".screens-page .diff-frame.diff-not-compared")).toHaveCount(3);
|
||||
await expect(page.locator(".screens-page .diff-frame.diff-modified")).toHaveCount(0);
|
||||
const menu = await openChangesMenu(page);
|
||||
const chips = menu.getByRole("group", { name: "Filter changes" }).getByRole("button");
|
||||
await expect(chips).toHaveText(["Modified 0", "No visible change 1", "Source-affected 2"]);
|
||||
await expect(chips).toHaveText(["Modified 0", "No visible change 1"]);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
@@ -1068,8 +1069,8 @@ test("an existing report with operational verdicts opens as diagnostics without
|
||||
const { page, errors } = await harness(t, await archive(report), { app: true });
|
||||
await expect(page.locator(".app-shell")).toBeVisible();
|
||||
await page.getByRole("button", { name: "Screens", exact: true }).click();
|
||||
await expect(page.locator(".screens-page .diff-frame.diff-source-affected")).toHaveCount(1);
|
||||
await expect(page.locator(".screens-page .diff-frame.diff-not-compared")).toHaveCount(1);
|
||||
await expect(page.locator(".screens-page .diff-frame.diff-source-affected")).toHaveCount(0);
|
||||
await expect(page.locator(".screens-page .diff-frame.diff-not-compared")).toHaveCount(2);
|
||||
await expect(page.locator(".screens-page .diff-frame.diff-unavailable")).toHaveCount(1, "an added route whose capture failed has nothing to show");
|
||||
await expect(page.locator(".screens-page .diff-frame.diff-removed")).toHaveCount(1);
|
||||
await expect(page.locator(".diff-frame.diff-needs-review, .diff-frame.diff-modified, .diff-frame.diff-unchanged, .diff-frame.diff-added")).toHaveCount(0);
|
||||
|
||||
@@ -406,10 +406,13 @@ test("the Screens tree folds by row, by keyboard, and all at once, and remembers
|
||||
await tree.getByRole("button", { name: "Expand all" }).click();
|
||||
await expect.poll(() => rows.count()).toBe(expandedRows);
|
||||
|
||||
// Section headings name the folder, with the path beneath.
|
||||
const onboarding = page.getByRole("region", { name: "Onboarding" });
|
||||
await expect(onboarding.getByRole("heading", { level: 2 })).toHaveText("Onboarding");
|
||||
await expect(onboarding.locator(".screens-section-head .path")).toHaveText("app/onboarding");
|
||||
// The tree names the folders, so the page beside it is one grid without section headings, in the tree's order.
|
||||
await expect(page.locator(".screens-page .screens-section-head")).toHaveCount(0);
|
||||
await expect(page.locator(".screens-page .screens-grid")).toHaveCount(1);
|
||||
const treeOrder = await tree.locator(".screens-tree-row[data-screen-id]").evaluateAll(rows => rows.map(row => row.dataset.screenId));
|
||||
const gridOrder = await page.locator(".screens-page .screens-cell").evaluateAll(cells => cells.map(cell => cell.dataset.screenId));
|
||||
assert.ok(gridOrder.length > 1);
|
||||
assert.deepEqual(gridOrder, treeOrder);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
|
||||
@@ -1309,7 +1309,100 @@ for (const canvas of ["map", "screens"] as const) {
|
||||
});
|
||||
}
|
||||
|
||||
test("reuses the Map screenshot card visual in Screens, with the route at the card's left edge", async ({ page }) => {
|
||||
test("← and → step through the Screens cards in page order, with focus, and leave the tree's arrows alone", async ({ page }) => {
|
||||
await serveWorkspace(page);
|
||||
await page.goto("/screens");
|
||||
const grid = page.getByRole("main", { name: "Screens" });
|
||||
await grid.getByRole("button", { name: /^All/ }).click();
|
||||
const cells = grid.locator(".screens-grid .screens-cell");
|
||||
const ids = await cells.evaluateAll(elements => elements.map(element => element.getAttribute("data-screen-id")!));
|
||||
expect(ids.length).toBeGreaterThan(2);
|
||||
const card = (id: string) => grid.locator(`.screens-cell[data-screen-id="${id}"] .screen-screenshot-card`);
|
||||
const target = (id: string) => grid.locator(`.screens-cell[data-screen-id="${id}"] .screen-screenshot-target`);
|
||||
|
||||
// With nothing selected, → starts at the first card.
|
||||
await expect(grid.locator(".screen-screenshot-card.selected")).toHaveCount(0);
|
||||
await page.keyboard.press("ArrowRight");
|
||||
await expect(card(ids[0]!)).toHaveClass(/selected/);
|
||||
await expect(target(ids[0]!)).toBeFocused();
|
||||
await page.keyboard.press("ArrowRight");
|
||||
await expect(card(ids[1]!)).toHaveClass(/selected/);
|
||||
await expect(target(ids[1]!)).toBeFocused();
|
||||
await page.keyboard.press("ArrowRight");
|
||||
await expect(card(ids[2]!)).toHaveClass(/selected/);
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
await expect(card(ids[1]!)).toHaveClass(/selected/);
|
||||
await expect(card(ids[2]!)).not.toHaveClass(/selected/);
|
||||
|
||||
// ↓ and ↑ move a row, to the card in the same column.
|
||||
const tops = await cells.evaluateAll(elements => elements.map(element => Math.round(element.getBoundingClientRect().top)));
|
||||
const columns = tops.filter(top => top === tops[0]).length;
|
||||
if (ids.length > 1 + columns) {
|
||||
await page.keyboard.press("ArrowDown");
|
||||
await expect(card(ids[1 + columns]!)).toHaveClass(/selected/);
|
||||
await expect(target(ids[1 + columns]!)).toBeFocused();
|
||||
await page.keyboard.press("ArrowUp");
|
||||
await expect(card(ids[1]!)).toHaveClass(/selected/);
|
||||
}
|
||||
|
||||
// Held, → keeps stepping, as in Compare, and stops on release.
|
||||
const selectedAt = async () => ids.indexOf((await grid.locator(".screens-cell:has(.screen-screenshot-card.selected)").getAttribute("data-screen-id"))!);
|
||||
const from = await selectedAt();
|
||||
await page.keyboard.down("ArrowRight");
|
||||
await expect.poll(selectedAt, { timeout: 4000 }).toBeGreaterThanOrEqual(Math.min(ids.length - 1, from + 3));
|
||||
await page.keyboard.up("ArrowRight");
|
||||
const released = await selectedAt();
|
||||
await page.waitForTimeout(500);
|
||||
expect(await selectedAt()).toBe(released);
|
||||
|
||||
// Return opens the pick in the Inspector, from the card or from anywhere on the page.
|
||||
const inspector = page.getByRole("complementary", { name: "Inspector panel" });
|
||||
await expect(inspector).toBeHidden();
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(inspector).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(inspector).toBeHidden();
|
||||
await page.evaluate(() => (document.activeElement as HTMLElement | null)?.blur());
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(inspector).toBeVisible();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(inspector).toBeHidden();
|
||||
|
||||
// In the tree, ← and → fold and unfold rows; they do not step the cards.
|
||||
const picked = await selectedAt();
|
||||
const row = grid.locator(".screens-tree-row").first();
|
||||
await row.focus();
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
await expect(card(ids[picked]!)).toHaveClass(/selected/);
|
||||
});
|
||||
|
||||
test("→ steps the Screens cards right after Screens is opened from the toolbar, and from a pick that Changed hides", async ({ page }) => {
|
||||
await serveWorkspace(page);
|
||||
await page.goto("/map");
|
||||
await page.getByRole("group", { name: "Canvas view" }).getByRole("button", { name: "Screens", exact: true }).click();
|
||||
const grid = page.getByRole("main", { name: "Screens" });
|
||||
const cells = grid.locator(".screens-grid .screens-cell");
|
||||
await expect(cells.first()).toBeVisible();
|
||||
// Focus is still on the toolbar's Screens button.
|
||||
await page.keyboard.press("ArrowRight");
|
||||
await expect(cells.first().locator(".screen-screenshot-card")).toHaveClass(/selected/);
|
||||
|
||||
// Pick a screen that Changed hides, then show Changed: → goes to the next changed card after it in the tree.
|
||||
await grid.getByRole("button", { name: /^All/ }).click();
|
||||
const all = await cells.evaluateAll(elements => elements.map(element => element.getAttribute("data-screen-id")!));
|
||||
await grid.getByRole("button", { name: /^Changed/ }).click();
|
||||
const changed = await cells.evaluateAll(elements => elements.map(element => element.getAttribute("data-screen-id")!));
|
||||
const hidden = all.find((id, position) => !changed.includes(id) && all.slice(position + 1).some(next => changed.includes(next)));
|
||||
test.skip(!hidden, "the fixture has no unchanged screen before a changed one");
|
||||
await grid.getByRole("button", { name: /^All/ }).click();
|
||||
await grid.locator(`.screens-cell[data-screen-id="${hidden}"] .screen-screenshot-target`).click();
|
||||
await grid.getByRole("button", { name: /^Changed/ }).click();
|
||||
const expected = all.slice(all.indexOf(hidden!) + 1).find(id => changed.includes(id))!;
|
||||
await page.keyboard.press("ArrowRight");
|
||||
await expect(grid.locator(`.screens-cell[data-screen-id="${expected}"] .screen-screenshot-card`)).toHaveClass(/selected/);
|
||||
});
|
||||
|
||||
test("reuses the Map screenshot card in Screens, with the route under the screenshot at the card's left edge", async ({ page }) => {
|
||||
await serveWorkspace(page);
|
||||
await page.goto("/screens");
|
||||
|
||||
@@ -1337,8 +1430,9 @@ test("reuses the Map screenshot card visual in Screens, with the route at the ca
|
||||
};
|
||||
});
|
||||
expect(layout.flexDirection).toBe("column");
|
||||
// The card is the Map's, so the heading still comes first in the markup; Screens shows it as the card's footer.
|
||||
expect(layout.headingBeforeImage).toBe(true);
|
||||
expect(layout.headingTop).toBeLessThan(layout.imageTop);
|
||||
expect(layout.headingTop).toBeGreaterThan(layout.imageTop);
|
||||
expect(layout.titleLeftDelta).toBeLessThan(1);
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"description": "Source: ax-service\nMode: flat\nCoordinates are normalized [0,1] fractions of the screen (x, y, width, height), not pixels.\nPass them straight to gesture-tap / gesture-swipe / gesture-pinch, which expect this same space.\nTo tap an element, use its centre: tap_x = frame.x + frame.width / 2, tap_y = frame.y + frame.height / 2.\n\nROOT AXGroup (0.000, 0.000, 1.000, 1.000)\n\n AXGroup \"Open in “euxy”?\" (0.067, 0.382, 0.687, 0.186)\n AXAdjustable \"Vertical scroll bar, 2 pages\" value=\"0%\" (0.682, 0.382, 0.064, 0.068)\n AXAdjustable \"Horizontal scroll bar, 1 page\" value=\"0%\" (0.067, 0.412, 0.687, 0.034)\n AXStaticText \"Open in “euxy”?\" (0.131, 0.414, 0.558, 0.030)\n AXAdjustable \"Vertical scroll bar, 1 page\" value=\"0%\" (0.682, 0.450, 0.064, 0.118)\n AXButton \"Cancel\" (0.101, 0.473, 0.300, 0.071)\n AXButton \"Open\" (0.418, 0.473, 0.300, 0.071)\n AXAdjustable \"Horizontal scroll bar, 1 page\" value=\"0%\" (0.067, 0.519, 0.687, 0.044)",
|
||||
"source": "ax-service",
|
||||
"hint": "This simulator was not booted through argent, so system dialogs and native modals may not appear in this tree; everything else reads normally. If something you expect is missing, boot-device with force=true reboots the simulator with the full accessibility settings"
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
{
|
||||
"devices": [
|
||||
{
|
||||
"platform": "ios",
|
||||
"udid": "404F2659-7202-4450-8465-912BD2AB744B",
|
||||
"name": "iPhone 17",
|
||||
"state": "Booted",
|
||||
"runtime": "com.apple.CoreSimulator.SimRuntime.iOS-26-5",
|
||||
"runtimeKind": "mobile"
|
||||
},
|
||||
{
|
||||
"platform": "ios",
|
||||
"udid": "13145DF8-2591-4879-8B4E-0EE52E38B9DC",
|
||||
"name": "Apple TV 4K (3rd generation)",
|
||||
"state": "Shutdown",
|
||||
"runtime": "com.apple.CoreSimulator.SimRuntime.tvOS-26-5",
|
||||
"runtimeKind": "tv"
|
||||
},
|
||||
{
|
||||
"platform": "ios",
|
||||
"udid": "9F874416-F37E-49D4-BE9F-D03A61447F37",
|
||||
"name": "Apple TV 4K (3rd generation) (at 1080p)",
|
||||
"state": "Shutdown",
|
||||
"runtime": "com.apple.CoreSimulator.SimRuntime.tvOS-26-5",
|
||||
"runtimeKind": "tv"
|
||||
},
|
||||
{
|
||||
"platform": "ios",
|
||||
"udid": "AA581E94-E134-4DEC-8D68-A80C02932E86",
|
||||
"name": "Apple TV",
|
||||
"state": "Shutdown",
|
||||
"runtime": "com.apple.CoreSimulator.SimRuntime.tvOS-26-5",
|
||||
"runtimeKind": "tv"
|
||||
},
|
||||
{
|
||||
"platform": "ios",
|
||||
"udid": "7166D6B3-15EA-485E-B233-D4CF5AA1A9E6",
|
||||
"name": "iPhone 17 Pro",
|
||||
"state": "Shutdown",
|
||||
"runtime": "com.apple.CoreSimulator.SimRuntime.iOS-26-5",
|
||||
"runtimeKind": "mobile"
|
||||
},
|
||||
{
|
||||
"platform": "ios",
|
||||
"udid": "65AF775B-D9DC-4293-88B6-7862868B66BC",
|
||||
"name": "iPhone 17 Pro Max",
|
||||
"state": "Shutdown",
|
||||
"runtime": "com.apple.CoreSimulator.SimRuntime.iOS-26-5",
|
||||
"runtimeKind": "mobile"
|
||||
},
|
||||
{
|
||||
"platform": "ios",
|
||||
"udid": "65D86638-6B23-47AB-A60B-B152A3E5FBEC",
|
||||
"name": "iPhone 17e",
|
||||
"state": "Shutdown",
|
||||
"runtime": "com.apple.CoreSimulator.SimRuntime.iOS-26-5",
|
||||
"runtimeKind": "mobile"
|
||||
},
|
||||
{
|
||||
"platform": "ios",
|
||||
"udid": "A690C59A-DE62-467C-9A93-6B9C81BE7859",
|
||||
"name": "iPhone Air",
|
||||
"state": "Shutdown",
|
||||
"runtime": "com.apple.CoreSimulator.SimRuntime.iOS-26-5",
|
||||
"runtimeKind": "mobile"
|
||||
},
|
||||
{
|
||||
"platform": "ios",
|
||||
"udid": "9D7FC73C-7A12-4BCF-83C2-9B52ACF9859D",
|
||||
"name": "iPad Pro 13-inch (M5)",
|
||||
"state": "Shutdown",
|
||||
"runtime": "com.apple.CoreSimulator.SimRuntime.iOS-26-5",
|
||||
"runtimeKind": "mobile"
|
||||
},
|
||||
{
|
||||
"platform": "ios",
|
||||
"udid": "E71C61D3-8D9F-4591-8511-8FE65229C790",
|
||||
"name": "iPad Pro 11-inch (M5)",
|
||||
"state": "Shutdown",
|
||||
"runtime": "com.apple.CoreSimulator.SimRuntime.iOS-26-5",
|
||||
"runtimeKind": "mobile"
|
||||
},
|
||||
{
|
||||
"platform": "ios",
|
||||
"udid": "ED9D983B-1AA4-4648-8EED-CDCD5327B8D6",
|
||||
"name": "iPad mini (A17 Pro)",
|
||||
"state": "Shutdown",
|
||||
"runtime": "com.apple.CoreSimulator.SimRuntime.iOS-26-5",
|
||||
"runtimeKind": "mobile"
|
||||
},
|
||||
{
|
||||
"platform": "ios",
|
||||
"udid": "9C0DF431-D699-4862-8CF3-264CA044F515",
|
||||
"name": "iPad Air 13-inch (M4)",
|
||||
"state": "Shutdown",
|
||||
"runtime": "com.apple.CoreSimulator.SimRuntime.iOS-26-5",
|
||||
"runtimeKind": "mobile"
|
||||
},
|
||||
{
|
||||
"platform": "ios",
|
||||
"udid": "B92DDF42-5EB6-47F1-A1E7-2B3F2CE2CA84",
|
||||
"name": "iPad Air 11-inch (M4)",
|
||||
"state": "Shutdown",
|
||||
"runtime": "com.apple.CoreSimulator.SimRuntime.iOS-26-5",
|
||||
"runtimeKind": "mobile"
|
||||
},
|
||||
{
|
||||
"platform": "ios",
|
||||
"udid": "44804797-154C-40DB-8559-342C3F95477A",
|
||||
"name": "iPad (A16)",
|
||||
"state": "Shutdown",
|
||||
"runtime": "com.apple.CoreSimulator.SimRuntime.iOS-26-5",
|
||||
"runtimeKind": "mobile"
|
||||
}
|
||||
],
|
||||
"avds": []
|
||||
}
|
||||
|
After Width: | Height: | Size: 215 KiB |
|
After Width: | Height: | Size: 167 KiB |
|
After Width: | Height: | Size: 131 KiB |
|
After Width: | Height: | Size: 619 KiB |
@@ -67,6 +67,7 @@ export async function fixture(t, provider, { docsOnly = false, unresolvedParamet
|
||||
await put('eas.json', JSON.stringify({ build: { capture: { ios: { simulator: true }, android: { buildType: 'apk', distribution: 'internal' } } } }));
|
||||
const registration = names => `import {createNativeStackNavigator} from '@react-navigation/native-stack';
|
||||
import {createStaticNavigation} from '@react-navigation/native';
|
||||
|
||||
${names.map(name => `import ${name} from './${name}';`).join('\n')}
|
||||
const Root=createNativeStackNavigator({screens:{${names.map(name => `${name}:{screen:${name},linking:'${name.toLowerCase()}'}`).join(',')}}});
|
||||
const Navigation=createStaticNavigation(Root); export default function App(){return <Navigation/>;}`;
|
||||
@@ -103,7 +104,7 @@ const Navigation=createStaticNavigation(Root); export default function App(){ret
|
||||
const pullRequestPath = join(root, 'pull-request.json'); await writeFile(pullRequestPath, JSON.stringify(pr));
|
||||
const environment = { PATH: process.env.PATH, HOME: root, RUNNER_TEMP: root, EXPO_TOKEN: 'test-expo-secret', GITHUB_TOKEN: 'test-github-secret',
|
||||
GITHUB_RUN_ID: '1234', GITHUB_RUN_ATTEMPT: '1', GITHUB_REPOSITORY: pr.repository, TOOLS_COMMIT: 'c'.repeat(40), EXPLORE_VIEWER_ORIGIN: 'https://viewer.example' };
|
||||
const requests = []; const comments = []; const sessions = new Map(); let currentSession; let currentPath = '/'; let sessionCounter = 0; let repackedSha; let openFailed = false; let currentScheme = 'light';
|
||||
const requests = []; const comments = []; const sessions = new Map(); let currentSession; const idleDevice = { path: '/', scheme: 'light' }; let sessionCounter = 0; let repackedSha; let openFailed = false;
|
||||
const identity = () => ({ session: 'expo-explore-runtime', appBundleId: config.app.bundleId,
|
||||
device: { id: 'device-1', name: config.device.name, platform, target: 'mobile', osVersion: '26.0', locale: 'en-US', orientation: 'portrait', colorScheme: 'light' },
|
||||
identifiers: { session: 'expo-explore-runtime', appBundleId: config.app.bundleId, deviceId: 'device-1', deviceName: config.device.name } });
|
||||
@@ -114,7 +115,7 @@ const Navigation=createStaticNavigation(Root); export default function App(){ret
|
||||
const sleep = milliseconds => { clockMs += milliseconds; };
|
||||
const runner = request => {
|
||||
requests.push(request);
|
||||
if (basename(request.command) === 'agent-device') clockMs += 600;
|
||||
if (/^agent-device(-|$)/.test(basename(request.command))) clockMs += 600;
|
||||
if (request.command === 'git') { const result = spawnSync('git', request.args, { cwd: request.cwd, encoding: 'utf8', env: request.environment }); assert.equal(result.status, 0); return { stdout: result.stdout, stderr: result.stderr }; }
|
||||
const command = request.args[0];
|
||||
if (basename(request.command) === 'eas') {
|
||||
@@ -140,8 +141,8 @@ const Navigation=createStaticNavigation(Root); export default function App(){ret
|
||||
return json({ jobs: [{ key: 'repack', status: 'SUCCESS', outputs: { build_id: `repacked-${repackedSha}`, platform } }] });
|
||||
}
|
||||
if (command === 'simulator:start') {
|
||||
const id = `session-${++sessionCounter}`; currentSession = id; currentPath = '/'; openFailed = false;
|
||||
const session = { id, name: value(request, '--name'), build: value(request, '--build-id') }; sessions.set(id, session);
|
||||
const id = `session-${++sessionCounter}`; currentSession = id; openFailed = false;
|
||||
const session = { id, name: value(request, '--name'), build: value(request, '--build-id'), path: '/', scheme: 'light' }; sessions.set(id, session);
|
||||
writeFileSync(join(request.cwd, '.env.eas-simulator'), `${HEADER}EAS_SIMULATOR_SESSION_ID='${id}'\nAGENT_DEVICE_DAEMON_BASE_URL='https://controller.example/${id}'\nAGENT_DEVICE_DAEMON_AUTH_TOKEN='controller-private-token'\n`);
|
||||
return { stdout: 'ready', stderr: '' };
|
||||
}
|
||||
@@ -154,7 +155,10 @@ const Navigation=createStaticNavigation(Root); export default function App(){ret
|
||||
mkdirSync(value(request, '--output'));
|
||||
return { stdout: '', stderr: '' };
|
||||
}
|
||||
if (basename(request.command) === 'agent-device') {
|
||||
if (/^agent-device(-|$)/.test(basename(request.command))) {
|
||||
// Base and head capture in parallel, each on its own simulator: a request names its session in the daemon URL,
|
||||
// so the route, appearance and build it sees are that session's, not whichever session started last.
|
||||
const device = sessions.get(/\/([^/]+)$/.exec(request.environment?.AGENT_DEVICE_DAEMON_BASE_URL ?? '')?.[1]) ?? sessions.get(currentSession) ?? idleDevice;
|
||||
if (command === '--version') return { stdout: AGENT_DEVICE_VERSION, stderr: '' };
|
||||
if (command === 'open') {
|
||||
if (request.args[2]?.startsWith('sample://')) {
|
||||
@@ -162,7 +166,7 @@ const Navigation=createStaticNavigation(Root); export default function App(){ret
|
||||
openFailed = true;
|
||||
return json({ success: false, error: { code: 'COMMAND_FAILED', message: 'The app is not ready for this link yet.' } });
|
||||
}
|
||||
currentPath = '/' + request.args[2].slice('sample://'.length);
|
||||
device.path = '/' + request.args[2].slice('sample://'.length);
|
||||
}
|
||||
return ok(identity());
|
||||
}
|
||||
@@ -170,17 +174,17 @@ const Navigation=createStaticNavigation(Root); export default function App(){ret
|
||||
if (command === 'wait') return ok({});
|
||||
if (command === 'alert' && request.args[1] === 'get') return json({ success: false, error: { code: 'COMMAND_FAILED', message: 'alert not found' } });
|
||||
if (command === 'snapshot') {
|
||||
const dynamic = currentPath.startsWith('/item/');
|
||||
const dynamic = device.path.startsWith('/item/');
|
||||
const destination = provider === 'expo-router'
|
||||
? { provider, pathname: currentPath, segments: dynamic ? ['item', '[id]'] : currentPath.split('/').filter(Boolean), parameters: dynamic ? { id: currentPath.slice('/item/'.length) } : {} }
|
||||
: { provider, segments: [currentPath.slice(1).replace(/^./, first => first.toUpperCase())], parameters: {} };
|
||||
? { provider, pathname: device.path, segments: dynamic ? ['item', '[id]'] : device.path.split('/').filter(Boolean), parameters: dynamic ? { id: device.path.slice('/item/'.length) } : {} }
|
||||
: { provider, segments: [device.path.slice(1).replace(/^./, first => first.toUpperCase())], parameters: {} };
|
||||
return ok({ truncated: false, nodes: [
|
||||
{ index: 0, type: 'StaticText', label: currentPath, identifier: 'screen-title', enabled: true, visible: true, rect: { x: 0, y: 0, width: 16, height: 24 } },
|
||||
...(currentPath === observerFailurePath ? [] : [{ index: 1, type: 'StaticText', label: JSON.stringify(destination), identifier: CAPTURE_OBSERVER_IDENTIFIER, enabled: true, visible: true }]),
|
||||
{ index: 0, type: 'StaticText', label: device.path, identifier: 'screen-title', enabled: true, visible: true, rect: { x: 0, y: 0, width: 16, height: 24 } },
|
||||
...(device.path === observerFailurePath ? [] : [{ index: 1, type: 'StaticText', label: JSON.stringify(destination), identifier: CAPTURE_OBSERVER_IDENTIFIER, enabled: true, visible: true }]),
|
||||
] });
|
||||
}
|
||||
if (command === 'settings') { if (request.args[1] === 'appearance') currentScheme = request.args[2]; return ok({ setting: request.args[1], value: request.args[2] }); }
|
||||
if (command === 'screenshot') { const color = createHash('sha256').update(`${currentPath}:${currentScheme}:${currentPath === '/home' ? sessions.get(currentSession).build : 'unchanged-source'}`).digest(); const data = Buffer.alloc(16 * 24 * 4); for (let i = 0; i < data.length; i += 4) { data[i] = color[0]; data[i + 1] = color[1]; data[i + 2] = color[2]; data[i + 3] = 255; } writeFileSync(request.args[1], PNG.sync.write({ width: 16, height: 24, data })); return ok({ path: request.args[1] }); }
|
||||
if (command === 'settings') { if (request.args[1] === 'appearance') device.scheme = request.args[2]; return ok({ setting: request.args[1], value: request.args[2] }); }
|
||||
if (command === 'screenshot') { const color = createHash('sha256').update(`${device.path}:${device.scheme}:${device.path === '/home' ? device.build : 'unchanged-source'}`).digest(); const data = Buffer.alloc(16 * 24 * 4); for (let i = 0; i < data.length; i += 4) { data[i] = color[0]; data[i + 1] = color[1]; data[i + 2] = color[2]; data[i + 3] = 255; } writeFileSync(request.args[1], PNG.sync.write({ width: 16, height: 24, data })); return ok({ path: request.args[1] }); }
|
||||
}
|
||||
throw new Error(`Unexpected mocked command: ${request.command} ${request.args.join(' ')}`);
|
||||
};
|
||||
|
||||
@@ -12,12 +12,14 @@ const reviewSource = await readFile(new URL("../../templates/explore-review.yml"
|
||||
const review = parse(reviewSource);
|
||||
const baselineSource = await readFile(new URL("../../templates/explore-baseline.yml", import.meta.url), "utf8");
|
||||
const baseline = parse(baselineSource);
|
||||
const workflows = [review, baseline];
|
||||
const compareSource = await readFile(new URL("../../templates/explore-compare.yml", import.meta.url), "utf8");
|
||||
const compare = parse(compareSource);
|
||||
const workflows = [review, baseline, compare];
|
||||
|
||||
test("one review and one baseline template replace all duplicate CI entrypoints", async () => {
|
||||
test("one review, one baseline and one compare template replace all duplicate CI entrypoints", async () => {
|
||||
const names = (await readdir(new URL("../../templates/", import.meta.url))).filter(name => name.endsWith(".yml"));
|
||||
assert.deepEqual(names.sort(), ["explore-baseline.yml", "explore-review.yml"]);
|
||||
for (const source of [actionSource, reviewSource, baselineSource]) {
|
||||
assert.deepEqual(names.sort(), ["explore-baseline.yml", "explore-compare.yml", "explore-review.yml"]);
|
||||
for (const source of [actionSource, reviewSource, baselineSource, compareSource]) {
|
||||
assert.doesNotMatch(source, /surface_manifest|surfaces\.json|runtime_probe|--keyless|KEYLESS|claude-code|agent_sandbox|report:export|report:comment/);
|
||||
}
|
||||
for (const removed of ["surface_manifest", "impact_plan", "runtime_probe_url", "keyless", "agent_sandbox", "bundle_id"]) {
|
||||
@@ -117,7 +119,7 @@ test("trusted tools retain native agent runtimes while omitting development depe
|
||||
const builds = [action.runs.steps.find(step => step.name === "Build the pinned Explore CLI"),
|
||||
...workflows.flatMap(workflow => Object.values(workflow.jobs)
|
||||
.flatMap(job => job.steps.filter(step => step.name === "Install Explore")))];
|
||||
assert.equal(builds.length, 8, "composite action, review platforms/capture/report/deploy/failure, and baseline platforms/baseline install the trusted tools");
|
||||
assert.equal(builds.length, 12, "composite action, review platforms/capture/report/deploy/failure, baseline platforms/baseline, and compare platforms/capture/report/deploy install the trusted tools");
|
||||
for (const step of builds) {
|
||||
const install = step.run.split("\n").find(line => /^\s*npm ci\b/.test(line));
|
||||
assert.ok(install, step.name);
|
||||
@@ -227,20 +229,18 @@ test("capture receives the automatic GitHub token for current PR verification",
|
||||
assert.equal(review.jobs.capture.permissions["pull-requests"], "write");
|
||||
});
|
||||
|
||||
test("always-run cleanup consumes only explicit retained handoffs before checkout verification", () => {
|
||||
for (const [job, name, sessionFiles] of [
|
||||
[review.jobs.capture, "Stop retained capture sessions", ["head-session", "base-session"]],
|
||||
[baseline.jobs.baseline, "Stop retained baseline session", ["baseline-session"]],
|
||||
test("after capture, success or not, ci:after-capture stops the recorded sessions and checks every checkout", () => {
|
||||
for (const [job, condition, output, checkouts] of [
|
||||
[review.jobs.capture, "always() && steps.pr.outcome == 'success'", "explore-review", ["app-base", "app-head"]],
|
||||
[compare.jobs.capture, "always() && steps.explore.outcome == 'success'", "explore-review", ["app-base", "app-head"]],
|
||||
[baseline.jobs.baseline, "always() && steps.explore.outcome == 'success'", "explore-baseline", ["app"]],
|
||||
]) {
|
||||
const index = job.steps.findIndex(step => step.name === name);
|
||||
const cleanup = job.steps[index];
|
||||
assert.equal(cleanup.if, "always()");
|
||||
const cleanup = job.steps.find(step => step.run?.includes("ci:after-capture"));
|
||||
assert.equal(cleanup.if, condition);
|
||||
assert.ok(cleanup["timeout-minutes"] <= 5);
|
||||
assert.equal(cleanup.env.EXPO_TOKEN, "${{ secrets.EXPO_TOKEN }}");
|
||||
assert.match(cleanup.run, /cleanup-ci-sessions\.mjs/);
|
||||
for (const path of sessionFiles) assert.ok(cleanup.run.includes(path));
|
||||
assert.ok(index < job.steps.findIndex(step => step.name?.startsWith("Verify application checkout")));
|
||||
assert.doesNotMatch(cleanup.run, /simulator:list|--all/);
|
||||
assert.equal(cleanup.run, `node "$TOOLS/dist/cli.js" ci:after-capture --output "$RUNNER_TEMP/${output}" ${checkouts.map(dir => `--checkout ${dir}`).join(" ")}`);
|
||||
assert.ok(job.steps.indexOf(cleanup) < job.steps.findIndex(step => step.uses?.startsWith("actions/upload-artifact@")), "before any upload");
|
||||
}
|
||||
assert.equal(action.runs.steps.at(-1).name, "Stop retained capture sessions");
|
||||
assert.equal(action.runs.steps.at(-1).if, "always() && steps.preflight.outcome == 'success'");
|
||||
@@ -305,10 +305,9 @@ test("the deploy job is the only post-capture job that holds EXPO_TOKEN, and it
|
||||
assert.ok(downloads.every(step => step.with.name === undefined && step.with["merge-multiple"] === undefined));
|
||||
assert.doesNotMatch(JSON.stringify(deploy), /OPENAI_API_KEY|ANTHROPIC_API_KEY/);
|
||||
assert.equal(review.jobs.report.outputs, undefined);
|
||||
assert.equal(review.jobs.capture.outputs.preview, "${{ steps.preview.outputs.preview }}");
|
||||
const previewStep = review.jobs.capture.steps.find(step => step.id === "preview");
|
||||
assert.match(previewStep.run, /jq -r '\.preview\.hosting \/\/ ""'/);
|
||||
assert.ok(review.jobs.capture.steps.indexOf(previewStep) < review.jobs.capture.steps.findIndex(step => step.name === "Upload captured review for packaging"));
|
||||
// capture:review writes preview=<hosting> to the step outputs from the reviewed config.
|
||||
assert.equal(review.jobs.capture.outputs.preview, "${{ steps.capture.outputs.preview }}");
|
||||
assert.match(review.jobs.capture.steps.find(step => step.id === "capture").run, /capture:review/);
|
||||
assert.deepEqual(review.jobs.failure.needs, ["platforms", "capture", "report", "deploy"]);
|
||||
assert.match(review.jobs.failure.if, /needs\.platforms\.result == 'failure'/);
|
||||
assert.match(review.jobs.failure.if, /needs\.deploy\.result == 'failure'/);
|
||||
@@ -339,12 +338,38 @@ test("review captures and reports each configured platform in its own matrix job
|
||||
assert.ok(uses.length > 0, command);
|
||||
for (const run of uses) assert.match(run, /--platform "\$PLATFORM"/, command);
|
||||
}
|
||||
const baselineLookup = review.jobs.capture.steps.find(step => step.name === "Find optional exact-base evidence").with.script;
|
||||
assert.match(baselineLookup, /explore-baseline-\$\{process\.env\.BASE_SHA\}-\$\{process\.env\.PLATFORM\}/);
|
||||
assert.match(baselineLookup, /process\.env\.PLATFORM === 'ios' \? \[`explore-baseline-\$\{process\.env\.BASE_SHA\}`\]/);
|
||||
for (const workflow of [review, compare]) {
|
||||
assert.equal(workflow.jobs.capture.steps.find(step => step.name === "Find optional exact-base evidence").run,
|
||||
'node "$TOOLS/dist/cli.js" ci:find-baseline --sha "$BASE_SHA" --platform "$PLATFORM"');
|
||||
}
|
||||
for (const [job, name] of [[review.jobs.capture, "Upload captured review for packaging"], [review.jobs.capture, "Upload planning and failure diagnostics"],
|
||||
[review.jobs.report, "Upload hosted review bundle"], [review.jobs.report, "Upload report failure diagnostics"],
|
||||
[baseline.jobs.baseline, "Upload exact-commit baseline evidence"], [baseline.jobs.baseline, "Upload planning and baseline diagnostics"]]) {
|
||||
assert.ok(job.steps.find(step => step.name === name).with.name.endsWith("-${{ matrix.platform }}"), name);
|
||||
}
|
||||
});
|
||||
|
||||
test("compare reviews any two refs from a manual run or another workflow, with no pull request access", () => {
|
||||
for (const trigger of ["workflow_dispatch", "workflow_call"]) {
|
||||
assert.deepEqual(Object.keys(compare.on[trigger].inputs).sort(), ["base", "expires-in", "head", "scope"]);
|
||||
for (const name of ["base", "head"]) assert.equal(compare.on[trigger].inputs[name].required, true);
|
||||
for (const name of ["scope", "expires-in"]) assert.deepEqual([compare.on[trigger].inputs[name].required, compare.on[trigger].inputs[name].default], [false, ""]);
|
||||
}
|
||||
assert.deepEqual(Object.keys(compare.on).sort(), ["workflow_call", "workflow_dispatch"]);
|
||||
for (const job of Object.values(compare.jobs)) assert.equal(job.permissions["pull-requests"], undefined, "a comparison never touches pull requests");
|
||||
const capture = compare.jobs.capture.steps.find(step => step.name === "Capture review");
|
||||
assert.match(capture.run, /capture:review[\s\S]*--compare "\$RUNNER_TEMP\/explore-compare\.json"/);
|
||||
assert.doesNotMatch(compareSource, /ci:failure|--pull-request/);
|
||||
// Each override reaches the CLI only when the caller set it; the CLI validates the value.
|
||||
assert.match(capture.run, /\$\{SCOPE:\+--scope "\$SCOPE"\} \$\{EXPIRES_IN:\+--expires-in "\$EXPIRES_IN"\}/);
|
||||
assert.match(compare.jobs.capture.steps.find(step => step.name === "Verify deterministic source planning").run, /\$\{SCOPE:\+--scope "\$SCOPE"\}/);
|
||||
assert.match(compare.jobs.report.steps.find(step => step.name === "Link the report from the run summary").run, /ci:publish --input .* --artifact-url "\$ARTIFACT_URL" --platform "\$PLATFORM"/);
|
||||
assert.equal(compare.jobs.capture.env.BASE_SHA, "${{ needs.platforms.outputs.base }}", "capture checks out the commits the refs resolved to once");
|
||||
assert.equal(compare.jobs.capture.env.HEAD_SHA, "${{ needs.platforms.outputs.head }}");
|
||||
assert.equal(compare.concurrency.group, "explore-compare-${{ inputs.base }}..${{ inputs.head }}", "\"..\" cannot appear in a ref, so groups never collide");
|
||||
const diagnostics = compare.jobs.report.steps.find(step => step.name === "Upload report failure diagnostics");
|
||||
assert.deepEqual([diagnostics.if, diagnostics.with.path], ["always()", "${{ runner.temp }}/explore-diagnostics"]);
|
||||
assert.match(compare.jobs.platforms.steps.find(step => step.id === "refs").run, /ci:compare-refs --project app-head --base "\$BASE_REF" --head "\$HEAD_REF"/);
|
||||
assert.match(compare.jobs.capture.steps.find(step => step.id === "capture").run, /printf '%s' "\$COMPARE" > "\$RUNNER_TEMP\/explore-compare\.json"/);
|
||||
assert.match(compare.jobs.deploy.steps.at(-1).run, /ci:deploy --inputs/);
|
||||
});
|
||||
@@ -0,0 +1,543 @@
|
||||
import assert from "node:assert/strict";
|
||||
import { readFileSync } from "node:fs";
|
||||
import test from "node:test";
|
||||
import { tsImport } from "tsx/esm/api";
|
||||
|
||||
const { PNG } = await import("pngjs");
|
||||
const { ArgentCallError, describedButton, findOpenButton, iosRuntimeVersion, openInAppPromptShowing, parseCommand, runBridgeCommand, snapshotFromTree } = await tsImport("../../src/capture/argent-driver.ts", import.meta.url);
|
||||
|
||||
const fixture = name => JSON.parse(readFileSync(new URL(`../fixtures/argent-0.29/${name}`, import.meta.url), "utf8"));
|
||||
const IOS_HOME = fixture("fixture-ios-ui-tree-home.json");
|
||||
const IOS_RENAME = fixture("fixture-ios-ui-tree-rename.json");
|
||||
const ANDROID_HOME = fixture("fixture-android-ui-tree-home.json");
|
||||
const ANDROID_RENAME = fixture("fixture-android-ui-tree-rename.json");
|
||||
const IOS_DEVICES = fixture("list-devices.out");
|
||||
// iOS 27.1 on iPhone Duo: the link prompt is up, SpringBoard is in front, and alertVisible is false.
|
||||
const DUO_PROMPT = fixture("fixture-ios27-duo-open-prompt-ui-tree.json");
|
||||
const DUO_PROMPT_DESCRIBE = fixture("fixture-ios27-duo-open-prompt-describe.json");
|
||||
const DUO_HOME = fixture("fixture-ios27-duo-home-ui-tree.json");
|
||||
// iPhone Duo opened (the inner display), Edit Lane sheet up: Argent reports the app root as the screen's top-left third.
|
||||
const DUO_OPEN_EDIT_LANE = fixture("fixture-ios27-duo-open-edit-lane-ui-tree.json");
|
||||
const DUO_DEVICES = { devices: [{ platform: "ios", udid: "74195B53-4DBC-4EAA-9991-F98E5BB86BA8", name: "iPhone Duo", state: "Booted", runtime: "com.apple.CoreSimulator.SimRuntime.iOS-27-1", runtimeKind: "mobile" }] };
|
||||
const ANDROID_DEVICES = { devices: [{ platform: "android", serial: "emulator-5554", state: "device", isEmulator: true, model: "sdk_gphone64_x86_64", avdName: "pixel_7", sdkLevel: 36, runtimeKind: "mobile" }], avds: [] };
|
||||
const BUNDLE = "dev.brent.euxy";
|
||||
const UDID = "404F2659-7202-4450-8465-912BD2AB744B";
|
||||
|
||||
/** A scripted tool-server: each tool answers from `answers` (a value, a function of the args, or a queue of either). */
|
||||
function harness(platform, answers, options = {}) {
|
||||
const calls = [];
|
||||
const moves = [];
|
||||
const queues = Object.fromEntries(Object.entries(answers).map(([tool, answer]) => [tool, Array.isArray(answer) ? [...answer] : answer]));
|
||||
const context = {
|
||||
platform, version: "0.29.0", state: options.state ?? { generation: 0 }, ...(options.bundleId ? { bundleId: options.bundleId } : {}),
|
||||
sleep: async () => {},
|
||||
reachable: async () => options.reachable ?? true,
|
||||
moveFile: async (from, to) => { moves.push([from, to]); },
|
||||
call: async (tool, args, callOptions) => {
|
||||
calls.push({ tool, args, ...(callOptions ? { options: callOptions } : {}) });
|
||||
let answer = queues[tool];
|
||||
if (Array.isArray(answer)) answer = answer.length > 1 ? answer.shift() : answer[0];
|
||||
if (answer === undefined) throw new Error(`unexpected tool ${tool}`);
|
||||
const value = typeof answer === "function" ? answer(args) : answer;
|
||||
if (value instanceof Error) throw value;
|
||||
return structuredClone(value);
|
||||
},
|
||||
};
|
||||
return { calls, moves, context, run: argv => runBridgeCommand(argv, context).then(result => ({ ...result, json: result.stdout.trim().startsWith("{") ? JSON.parse(result.stdout) : result.stdout })) };
|
||||
}
|
||||
|
||||
const flags = (platform, extra = []) => [...extra, "--session", "expo-explore-runtime", ...(platform === "ios" ? ["--device", "iPhone 17"] : []), "--platform", platform, "--json"];
|
||||
const flatten = tree => { const out = []; const walk = node => { out.push(node); (node.children ?? []).forEach(walk); }; (tree.roots ?? []).forEach(walk); return out; };
|
||||
|
||||
test("parseCommand separates agent-device's trailing flags from positionals and keeps text after --", () => {
|
||||
assert.deepEqual(parseCommand(["e3", "--session", "s", "--device", "iPhone 17", "--platform", "ios", "--json", "--", "-h", "--json"]),
|
||||
{ positional: ["e3", "-h", "--json"], flags: { session: "s", device: "iPhone 17", platform: "ios", json: true } });
|
||||
});
|
||||
|
||||
test("iosRuntimeVersion reads the OS version from a CoreSimulator runtime id", () => {
|
||||
assert.equal(iosRuntimeVersion("com.apple.CoreSimulator.SimRuntime.iOS-26-5"), "26.5");
|
||||
assert.equal(iosRuntimeVersion("com.apple.CoreSimulator.SimRuntime.iOS-18-0-1"), "18.0.1");
|
||||
assert.equal(iosRuntimeVersion("com.apple.CoreSimulator.SimRuntime.tvOS-26-5"), undefined);
|
||||
});
|
||||
|
||||
test("--version answers with the pinned Argent version without calling Argent", async () => {
|
||||
const { run, calls } = harness("ios", {});
|
||||
assert.equal((await run(["--version"])).stdout, "0.29.0\n");
|
||||
assert.equal(calls.length, 0);
|
||||
});
|
||||
|
||||
test("an iOS snapshot is agent-device's shape: points, the app root, the observer, and no duplicate nodes", () => {
|
||||
const { nodes, refs, screen } = snapshotFromTree(IOS_HOME, "ios", 1, BUNDLE);
|
||||
assert.deepEqual(screen, { width: 402, height: 874 });
|
||||
assert.equal(nodes[0].type, "Application");
|
||||
assert.deepEqual(nodes[0].rect, { x: 0, y: 0, width: 402, height: 874 });
|
||||
assert.equal(nodes[0].hittable, false);
|
||||
for (const [index, node] of nodes.entries()) {
|
||||
assert.equal(node.index, index);
|
||||
assert.equal(node.ref, `e${index + 1}`);
|
||||
assert.ok(refs[node.ref]);
|
||||
if (index > 0) assert.ok(node.parentIndex < index, "a parent comes before its children");
|
||||
assert.ok(node.rect.x < 402 && node.rect.y < 874 && node.rect.x + node.rect.width > 0 && node.rect.y + node.rect.height > 0, "only on-screen nodes");
|
||||
}
|
||||
const observer = nodes.find(node => node.identifier === "expo-explore-observer");
|
||||
assert.ok(observer, "the capture observer is in the tree");
|
||||
assert.equal(JSON.parse(observer.label).pathname, "/");
|
||||
const keys = nodes.map(node => JSON.stringify([node.type, node.label, node.identifier, node.value, Object.values(node.rect).map(Math.round)]));
|
||||
assert.equal(new Set(keys).size, keys.length, "iOS AX duplicates appear once");
|
||||
assert.ok(nodes.length < flatten(IOS_HOME).length);
|
||||
assert.ok(nodes.some(node => node.type === "Button" && node.identifier === "lane-row-title-0"));
|
||||
});
|
||||
|
||||
test("an Android snapshot keeps pixels, drops the system UI root, and names widgets as agent-device does", () => {
|
||||
const { nodes, screen } = snapshotFromTree(ANDROID_HOME, "android", 1, BUNDLE);
|
||||
assert.deepEqual(screen, { width: 720, height: 1600 });
|
||||
assert.equal(nodes[0].type, "Application");
|
||||
assert.deepEqual(nodes[0].rect, { x: 0, y: 0, width: 720, height: 1600 });
|
||||
assert.ok(!nodes.some(node => /^android\.widget\./.test(node.type)), "widget classes are simplified");
|
||||
assert.ok(nodes.some(node => node.identifier === "expo-explore-observer"));
|
||||
const systemUi = flatten({ roots: ANDROID_HOME.roots.filter(root => root.bundleId === "com.android.systemui") })
|
||||
.map(node => node.label ?? node.contentDescription).filter(Boolean);
|
||||
for (const label of systemUi) assert.ok(!nodes.some(node => node.label === label && node.depth === 0), `system UI root is left out (${label})`);
|
||||
assert.ok(nodes.filter(node => node.depth === 0).length === 1);
|
||||
});
|
||||
|
||||
test("snapshot pins refs to its generation and reports the foreground app; press resolves a ref to the element's centre", async () => {
|
||||
const { run, calls, context } = harness("ios", { "list-devices": IOS_DEVICES, "ui-tree": IOS_HOME, "gesture-tap": {} });
|
||||
const snapshot = await run(["snapshot", ...flags("ios", ["--force-full", "--level", "full"])]);
|
||||
assert.equal(snapshot.exitCode, 0);
|
||||
assert.equal(snapshot.json.data.refsGeneration, 1);
|
||||
assert.equal(snapshot.json.data.appBundleId, BUNDLE);
|
||||
assert.equal(snapshot.json.data.truncated, false);
|
||||
assert.equal(context.state.udid, UDID);
|
||||
assert.equal(context.state.model, "iPhone 17");
|
||||
assert.equal(context.state.osVersion, "26.5");
|
||||
const target = snapshot.json.data.nodes.find(node => node.identifier === "lane-row-title-0");
|
||||
const pressed = await run(["press", `@${target.ref}`, ...flags("ios")]);
|
||||
assert.equal(pressed.exitCode, 0);
|
||||
const tap = calls.at(-1);
|
||||
assert.equal(tap.tool, "gesture-tap");
|
||||
assert.equal(tap.args.udid, UDID);
|
||||
assert.ok(Math.abs(tap.args.x - (target.rect.x + target.rect.width / 2) / 402) < 1e-9);
|
||||
assert.ok(Math.abs(tap.args.y - (target.rect.y + target.rect.height / 2) / 874) < 1e-9);
|
||||
|
||||
const stale = await run(["press", `${target.ref}~s0`, ...flags("ios")]);
|
||||
assert.equal(stale.exitCode, 1);
|
||||
assert.match(stale.json.error.message, /stale/);
|
||||
});
|
||||
|
||||
test("press with coordinates normalizes Android pixels", async () => {
|
||||
const { run, calls } = harness("android", { "list-devices": ANDROID_DEVICES, "ui-tree": ANDROID_HOME, "gesture-tap": {} });
|
||||
assert.equal((await run(["press", "360", "400", ...flags("android")])).exitCode, 0);
|
||||
assert.deepEqual(calls.at(-1), { tool: "gesture-tap", args: { udid: "emulator-5554", x: 0.5, y: 0.25 } });
|
||||
});
|
||||
|
||||
test("open relaunches the app until its tree is readable and answers with agent-device's open envelope", async () => {
|
||||
const empty = { ...IOS_HOME, roots: [{ type: "Other", frame: { x: 0, y: 0, width: 1, height: 1 } }] };
|
||||
const { run, calls } = harness("ios", { "list-devices": IOS_DEVICES, "restart-app": {}, "ui-tree": [empty, empty, IOS_HOME] });
|
||||
const opened = await run(["open", BUNDLE, ...flags("ios", ["--level", "full"])]);
|
||||
assert.equal(opened.exitCode, 0);
|
||||
assert.deepEqual(opened.json.data.device, { platform: "ios", target: "mobile", name: "iPhone 17", id: UDID, osVersion: "26.5" });
|
||||
assert.equal(opened.json.data.appBundleId, BUNDLE);
|
||||
assert.equal(opened.json.data.session, "expo-explore-runtime");
|
||||
assert.deepEqual(opened.json.data.identifiers, { session: "expo-explore-runtime", appBundleId: BUNDLE, deviceName: "iPhone 17", deviceId: UDID });
|
||||
assert.deepEqual(calls.filter(call => call.tool === "restart-app").map(call => call.args), [{ udid: UDID, bundleId: BUNDLE }]);
|
||||
});
|
||||
|
||||
test("open fails clearly when the app never shows a tree", async () => {
|
||||
const empty = { ...IOS_HOME, roots: [] };
|
||||
const { run, calls } = harness("ios", { "list-devices": IOS_DEVICES, "restart-app": {}, "ui-tree": empty });
|
||||
const opened = await run(["open", BUNDLE, ...flags("ios")]);
|
||||
assert.equal(opened.exitCode, 1);
|
||||
assert.equal(opened.json.error.code, "APP_NOT_READY");
|
||||
assert.equal(calls.filter(call => call.tool === "restart-app").length, 2);
|
||||
});
|
||||
|
||||
test("a session with no single booted device is refused", async () => {
|
||||
const none = { devices: IOS_DEVICES.devices.map(device => ({ ...device, state: "Shutdown" })) };
|
||||
const { run } = harness("ios", { "list-devices": none });
|
||||
const result = await run(["snapshot", ...flags("ios")]);
|
||||
assert.equal(result.json.error.code, "DEVICE_UNAVAILABLE");
|
||||
});
|
||||
|
||||
test("the first iOS deep link accepts the Open prompt once; later links open directly", async () => {
|
||||
// iOS 26.5 flags the prompt as an alert; its text is what identifies it as the link prompt.
|
||||
const prompt = { ...IOS_HOME, alertVisible: true, foregroundApp: "com.apple.springboard",
|
||||
roots: [...IOS_HOME.roots, { type: "Alert", label: "Open in “euxy”?", frame: { x: 0.1, y: 0.4, width: 0.8, height: 0.2 }, children: [] }] };
|
||||
const { run, calls, context } = harness("ios", { "list-devices": IOS_DEVICES, "open-url": {}, "gesture-tap": {}, "ui-tree": [prompt, IOS_HOME] });
|
||||
const first = await run(["open", BUNDLE, "euxy://settings", ...flags("ios")]);
|
||||
assert.equal(first.exitCode, 0);
|
||||
const tap = calls.find(call => call.tool === "gesture-tap");
|
||||
assert.ok(Math.abs(tap.args.x - (0.5 + 74 / 402)) < 1e-9 && Math.abs(tap.args.y - (0.5 + 37 / 874)) < 1e-9);
|
||||
assert.equal(context.state.deepLinkPromptAccepted, true);
|
||||
const before = calls.length;
|
||||
assert.equal((await run(["open", "euxy://patterns", ...flags("ios")])).exitCode, 0);
|
||||
assert.deepEqual(calls.slice(before).map(call => call.tool), ["open-url"]);
|
||||
});
|
||||
|
||||
test("iOS fill taps the field, erases its text with backspaces, types, and checks the result", async () => {
|
||||
const field = flatten(IOS_RENAME).find(node => node.type === "TextField" && node.frame);
|
||||
assert.ok(field, "the rename fixture has a text field");
|
||||
const typed = structuredClone(IOS_RENAME);
|
||||
flatten(typed).find(node => node.type === "TextField" && node.frame).value = "Groove";
|
||||
const { run, calls } = harness("ios", { "list-devices": IOS_DEVICES, "ui-tree": [IOS_RENAME, typed], "gesture-tap": {}, "run-sequence": {}, keyboard: {} });
|
||||
const snapshot = await run(["snapshot", ...flags("ios")]);
|
||||
const node = snapshot.json.data.nodes.find(item => item.type === "TextField");
|
||||
const filled = await run(["fill", node.ref, ...flags("ios"), "--", "Groove"]);
|
||||
assert.equal(filled.exitCode, 0, filled.stdout);
|
||||
const tools = calls.slice(2).map(call => call.tool);
|
||||
assert.equal(tools[0], "gesture-tap");
|
||||
const erase = (field.value ?? "").length;
|
||||
if (erase) {
|
||||
const sequence = calls.find(call => call.tool === "run-sequence");
|
||||
assert.equal(sequence.args.steps.length, erase);
|
||||
assert.deepEqual(sequence.args.steps[0], { tool: "keyboard", args: { udid: UDID, key: "backspace" } });
|
||||
}
|
||||
assert.deepEqual(calls.find(call => call.tool === "keyboard").args, { udid: UDID, text: "Groove" });
|
||||
assert.ok(!calls.some(call => call.tool === "fill"), "Argent's iOS fill is not used");
|
||||
});
|
||||
|
||||
test("Android fill uses Argent's fill and requires it to verify the text", async () => {
|
||||
const { run, calls } = harness("android", { "list-devices": ANDROID_DEVICES, "ui-tree": ANDROID_RENAME, "gesture-tap": {}, fill: [{ verified: true }, { verified: false }] });
|
||||
const snapshot = await run(["snapshot", ...flags("android")]);
|
||||
const node = snapshot.json.data.nodes.find(item => item.type === "TextField");
|
||||
assert.ok(node, "the rename fixture has an EditText");
|
||||
assert.equal((await run(["fill", node.ref, ...flags("android"), "--", "Groove"])).exitCode, 0);
|
||||
assert.deepEqual(calls.find(call => call.tool === "fill").args, { udid: "emulator-5554", text: "Groove" });
|
||||
const unverified = await run(["fill", node.ref, ...flags("android"), "--", "Groove"]);
|
||||
assert.equal(unverified.exitCode, 1);
|
||||
});
|
||||
|
||||
test("text with a {{secret:…}} placeholder never reaches Argent", async () => {
|
||||
const { run, calls } = harness("ios", { "list-devices": IOS_DEVICES, keyboard: {} });
|
||||
const typed = await run(["type", ...flags("ios"), "--", "{{secret:PASSWORD}}"]);
|
||||
assert.equal(typed.json.error.code, "INVALID_ARGS");
|
||||
assert.ok(!calls.some(call => call.tool === "keyboard"));
|
||||
});
|
||||
|
||||
test("keyboard dismiss matches agent-device: Android presses back; iOS taps a dismiss key or reports it could not", async () => {
|
||||
const android = harness("android", { "list-devices": ANDROID_DEVICES, "ui-tree": [{ ...ANDROID_RENAME, keyboardVisible: true }, { ...ANDROID_RENAME, keyboardVisible: false }], button: {} });
|
||||
const dismissed = await android.run(["keyboard", "dismiss", ...flags("android")]);
|
||||
assert.deepEqual(dismissed.json.data, { platform: "android", action: "dismiss", wasVisible: true, dismissed: true, visible: false });
|
||||
assert.deepEqual(android.calls.find(call => call.tool === "button").args, { udid: "emulator-5554", button: "back" });
|
||||
|
||||
// agent-device fails with this message when the keyboard has no dismiss key, and callers fall back to the return key.
|
||||
const noKey = harness("ios", { "list-devices": IOS_DEVICES, "ui-tree": { ...IOS_HOME, keyboardVisible: true } });
|
||||
const failed = await noKey.run(["keyboard", "dismiss", ...flags("ios")]);
|
||||
assert.equal(failed.exitCode, 1);
|
||||
assert.match(failed.json.error.message, /^Unable to dismiss the iOS keyboard/);
|
||||
|
||||
const hidden = harness("ios", { "list-devices": IOS_DEVICES, "ui-tree": IOS_HOME });
|
||||
assert.equal((await hidden.run(["keyboard", "dismiss", ...flags("ios")])).json.data.wasVisible, false);
|
||||
});
|
||||
|
||||
test("iOS back with no navigation bar back control fails with agent-device's message", async () => {
|
||||
const { run } = harness("ios", { "list-devices": IOS_DEVICES, "ui-tree": IOS_HOME });
|
||||
const back = await run(["back", ...flags("ios")]);
|
||||
assert.equal(back.exitCode, 1);
|
||||
assert.equal(back.json.error.message, "in-app back control is not available");
|
||||
});
|
||||
|
||||
test("alerts read and answer in each platform's agent-device shape", async () => {
|
||||
const noAlert = harness("ios", { "list-devices": IOS_DEVICES, "ui-tree": IOS_HOME });
|
||||
assert.equal((await noAlert.run(["alert", "get", ...flags("ios")])).json.error.message, "alert not found");
|
||||
const androidNone = harness("android", { "list-devices": ANDROID_DEVICES, "ui-tree": ANDROID_HOME });
|
||||
assert.deepEqual((await androidNone.run(["alert", "get", ...flags("android")])).json.data, { platform: "android", alert: null });
|
||||
|
||||
const alertTree = { ...IOS_HOME, alertVisible: true, roots: [{ type: "Alert", label: "Allow?", frame: { x: 0.1, y: 0.4, width: 0.8, height: 0.2 }, children: [
|
||||
{ type: "StaticText", label: "Allow notifications?", frame: { x: 0.1, y: 0.4, width: 0.8, height: 0.05 } },
|
||||
{ type: "Button", label: "Don’t Allow", frame: { x: 0.1, y: 0.55, width: 0.4, height: 0.05 } },
|
||||
{ type: "Button", label: "Allow", frame: { x: 0.5, y: 0.55, width: 0.4, height: 0.05 } }] }] };
|
||||
const ios = harness("ios", { "list-devices": IOS_DEVICES, "ui-tree": [alertTree, alertTree, IOS_HOME], "gesture-tap": {} });
|
||||
assert.deepEqual((await ios.run(["alert", "get", ...flags("ios")])).json.data, { message: "Allow notifications?", items: ["Don’t Allow", "Allow"] });
|
||||
const accepted = await ios.run(["alert", "accept", ...flags("ios")]);
|
||||
assert.deepEqual(accepted.json.data, { action: "accept", button: "Allow" });
|
||||
const tap = ios.calls.find(call => call.tool === "gesture-tap");
|
||||
assert.ok(Math.abs(tap.args.x - 0.7) < 1e-9 && Math.abs(tap.args.y - 0.575) < 1e-9);
|
||||
});
|
||||
|
||||
test("screenshots download at full resolution to the requested path", async () => {
|
||||
const { run, calls } = harness("ios", { "list-devices": IOS_DEVICES, screenshot: {} });
|
||||
assert.deepEqual((await run(["screenshot", "/tmp/out.png", ...flags("ios")])).json.data, { path: "/tmp/out.png" });
|
||||
assert.deepEqual(calls.at(-1), { tool: "screenshot", args: { udid: UDID, scale: 1 }, options: { out: "/tmp/out.png" } });
|
||||
});
|
||||
|
||||
test("a recording is moved from where the Argent client downloaded it to the path Explore asked for", async () => {
|
||||
const { run, moves, context } = harness("android", { "list-devices": ANDROID_DEVICES, "screen-recording-start": {}, "screen-recording-stop": { video: "/home/.argent/recordings/r.mp4", durationMs: 4200 } });
|
||||
assert.equal((await run(["record", "start", "/work/launch.mp4", ...flags("android")])).exitCode, 0);
|
||||
assert.equal(context.state.recording, "/work/launch.mp4");
|
||||
const stopped = await run(["record", "stop", ...flags("android")]);
|
||||
assert.deepEqual(stopped.json.data, { outPath: "/work/launch.mp4", durationMs: 4200 });
|
||||
assert.deepEqual(moves, [["/home/.argent/recordings/r.mp4", "/work/launch.mp4"]]);
|
||||
assert.equal(context.state.recording, undefined);
|
||||
});
|
||||
|
||||
test("install reinstalls the archive under the bundle id the caller names", async () => {
|
||||
const { run, calls } = harness("ios", { "list-devices": IOS_DEVICES, "reinstall-app": {} }, { bundleId: BUNDLE });
|
||||
assert.deepEqual((await run(["install", "/work/bundle/euxy.app", ...flags("ios")])).json.data, { installed: true, appBundleId: BUNDLE });
|
||||
assert.deepEqual(calls.at(-1).args, { udid: UDID, bundleId: BUNDLE, appPath: "/work/bundle/euxy.app" });
|
||||
const missing = harness("ios", { "list-devices": IOS_DEVICES, "reinstall-app": {} });
|
||||
assert.equal((await missing.run(["install", "/work/a.app", ...flags("ios")])).json.error.code, "INVALID_ARGS");
|
||||
});
|
||||
|
||||
test("appearance and logs are reported as unsupported, not silently ignored", async () => {
|
||||
const { run } = harness("ios", {});
|
||||
assert.equal((await run(["settings", "appearance", "dark", ...flags("ios")])).json.error.code, "CONTROLLER_UNSUPPORTED");
|
||||
assert.equal((await run(["logs", "path", ...flags("ios")])).json.error.code, "CONTROLLER_UNSUPPORTED");
|
||||
});
|
||||
|
||||
test("a tool-server that is still starting is waited for before the action is sent", async () => {
|
||||
const { run, calls, context } = harness("ios", { "list-devices": IOS_DEVICES, "ui-tree": IOS_HOME, "gesture-tap": {} });
|
||||
const answers = [false, false, false, true];
|
||||
context.reachable = async () => answers.shift() ?? true;
|
||||
assert.equal((await run(["press", "10", "10", ...flags("ios")])).exitCode, 0);
|
||||
assert.equal(calls.filter(call => call.tool === "gesture-tap").length, 1);
|
||||
});
|
||||
|
||||
test("an unreachable tool-server before a UI action is the retryable 'Remote daemon is unavailable'", async () => {
|
||||
const { run, calls } = harness("ios", { "list-devices": IOS_DEVICES, "ui-tree": IOS_HOME, "gesture-tap": {} }, { reachable: false });
|
||||
const pressed = await run(["press", "10", "10", ...flags("ios")]);
|
||||
assert.deepEqual(pressed.json.error, { code: "COMMAND_FAILED", message: "Remote daemon is unavailable" });
|
||||
assert.ok(!calls.some(call => call.tool === "gesture-tap"));
|
||||
});
|
||||
|
||||
test("a UI action whose answer is lost is reported once and never retried", async () => {
|
||||
const { run, calls } = harness("ios", { "list-devices": IOS_DEVICES, "ui-tree": IOS_HOME, "gesture-tap": new ArgentCallError("argent run gesture-tap failed: socket hang up", true) });
|
||||
const pressed = await run(["press", "10", "10", ...flags("ios")]);
|
||||
assert.equal(pressed.json.error.code, "ARGENT_TOOL_FAILED");
|
||||
assert.notEqual(pressed.json.error.message, "Remote daemon is unavailable");
|
||||
assert.equal(calls.filter(call => call.tool === "gesture-tap").length, 1);
|
||||
});
|
||||
|
||||
test("reads are retried after a transport failure", async () => {
|
||||
const { run, calls } = harness("ios", { "list-devices": IOS_DEVICES, "ui-tree": [new ArgentCallError("timeout", true), IOS_HOME] });
|
||||
assert.equal((await run(["snapshot", ...flags("ios")])).exitCode, 0);
|
||||
assert.equal(calls.filter(call => call.tool === "ui-tree").length, 2);
|
||||
});
|
||||
|
||||
test("wait stable maps to await-screen-idle", async () => {
|
||||
const { run, calls } = harness("android", { "list-devices": ANDROID_DEVICES, "await-screen-idle": { settled: true } });
|
||||
assert.deepEqual((await run(["wait", "stable", "700", "5000", ...flags("android")])).json.data, { stable: true });
|
||||
assert.deepEqual(calls.at(-1).args, { udid: "emulator-5554", minStableMs: 700, timeoutMs: 5000 });
|
||||
});
|
||||
|
||||
test("iOS 27.1's link prompt is recognized by its text when Argent does not flag it as an alert", () => {
|
||||
assert.equal(DUO_PROMPT.alertVisible, false);
|
||||
assert.equal(openInAppPromptShowing(DUO_PROMPT), true);
|
||||
assert.equal(openInAppPromptShowing(DUO_HOME), false);
|
||||
assert.equal(openInAppPromptShowing(IOS_HOME), false);
|
||||
});
|
||||
|
||||
test("describe locates the prompt's Open button where it is on screen", () => {
|
||||
assert.deepEqual(describedButton(DUO_PROMPT_DESCRIBE.description, "Open"), { x: 0.418, y: 0.473, width: 0.3, height: 0.071 });
|
||||
assert.equal(describedButton(DUO_PROMPT_DESCRIBE.description, "Allow"), undefined);
|
||||
assert.equal(describedButton(undefined, "Open"), undefined);
|
||||
});
|
||||
|
||||
test("on iPhone Duo the first link taps Open where describe puts it, not at iPhone 17's offset", async () => {
|
||||
const { run, calls, context } = harness("ios", { "list-devices": DUO_DEVICES, "open-url": {}, "gesture-tap": {}, describe: DUO_PROMPT_DESCRIBE, "ui-tree": [DUO_PROMPT, DUO_HOME] });
|
||||
const opened = await run(["open", "dev.brent.euxy", "euxy://", ...flags("ios")]);
|
||||
assert.equal(opened.exitCode, 0, opened.stdout);
|
||||
const tap = calls.find(call => call.tool === "gesture-tap");
|
||||
assert.ok(Math.abs(tap.args.x - (0.418 + 0.15)) < 1e-9 && Math.abs(tap.args.y - (0.473 + 0.0355)) < 1e-9, JSON.stringify(tap.args));
|
||||
assert.equal(context.state.deepLinkPromptAccepted, true);
|
||||
});
|
||||
|
||||
test("a snapshot taken while iOS 27.1's link prompt is up reports it as an alert", async () => {
|
||||
const { run } = harness("ios", { "list-devices": DUO_DEVICES, "ui-tree": DUO_PROMPT });
|
||||
const snapshot = await run(["snapshot", ...flags("ios")]);
|
||||
assert.ok(snapshot.json.data.nodes.some(node => node.type === "Alert"));
|
||||
});
|
||||
|
||||
test("a tool-server that lists no devices on its first call is asked again", async () => {
|
||||
const { run, calls, context } = harness("ios", { "list-devices": [{ devices: [], avds: [] }, DUO_DEVICES], "ui-tree": DUO_HOME });
|
||||
assert.equal((await run(["snapshot", ...flags("ios")])).exitCode, 0);
|
||||
assert.equal(calls.filter(call => call.tool === "list-devices").length, 2);
|
||||
assert.equal(context.state.model, "iPhone Duo");
|
||||
assert.equal(context.state.osVersion, "27.1");
|
||||
});
|
||||
|
||||
test("alert get and accept read iOS 27.1's link prompt and press Open where describe puts it", async () => {
|
||||
const { run, calls } = harness("ios", { "list-devices": DUO_DEVICES, "gesture-tap": {}, describe: DUO_PROMPT_DESCRIBE, "ui-tree": [DUO_PROMPT, DUO_PROMPT, DUO_HOME] });
|
||||
const read = await run(["alert", "get", ...flags("ios")]);
|
||||
assert.deepEqual(read.json.data, { message: "Open in “euxy”?", items: ["Cancel", "Open"] });
|
||||
const accepted = await run(["alert", "accept", ...flags("ios")]);
|
||||
assert.deepEqual(accepted.json.data, { action: "accept", button: "Open" });
|
||||
const tap = calls.find(call => call.tool === "gesture-tap");
|
||||
assert.ok(Math.abs(tap.args.x - 0.568) < 1e-9 && Math.abs(tap.args.y - 0.5085) < 1e-9, JSON.stringify(tap.args));
|
||||
});
|
||||
|
||||
const image = name => PNG.sync.read(readFileSync(new URL(`../fixtures/argent-0.29/${name}`, import.meta.url)));
|
||||
const near = (actual, expected, tolerance = 0.02) => Math.abs(actual - expected) <= tolerance;
|
||||
|
||||
test("the link prompt's Open button is found in iOS 26 and iOS 27.1 screenshots", () => {
|
||||
// iPhone Duo: describe puts Open at (0.418, 0.473, 0.3 × 0.071).
|
||||
const duo = findOpenButton(image("screenshot-ios27-duo-open-prompt.png"));
|
||||
assert.ok(duo && near(duo.x, 0.568) && near(duo.y, 0.5085), JSON.stringify(duo));
|
||||
const iphone17 = findOpenButton(image("screenshot-ios26-iphone17-open-prompt.png"));
|
||||
assert.ok(iphone17 && iphone17.x > 0.5 && iphone17.x < 0.85 && iphone17.y > 0.48 && iphone17.y < 0.6, JSON.stringify(iphone17));
|
||||
});
|
||||
|
||||
test("no Open button is found without the prompt, even with a blue key on screen", () => {
|
||||
assert.equal(findOpenButton(image("screenshot-ios27-duo-no-prompt-small.png")), undefined);
|
||||
assert.equal(findOpenButton(image("screenshot-ios26-keyboard.png")), undefined);
|
||||
});
|
||||
|
||||
test("when Argent reads nothing while the prompt is up, Open is tapped from a screenshot", async () => {
|
||||
const blind = { schemaVersion: 1, source: "ax-service", screen: { width: 466, height: 678 }, roots: [{ role: "AXGroup", children: [] }], truncated: false, alertVisible: false };
|
||||
const frames = [image("screenshot-ios27-duo-open-prompt.png"), image("screenshot-ios27-duo-no-prompt-small.png")];
|
||||
const { run, calls, context } = harness("ios", { "list-devices": DUO_DEVICES, "open-url": {}, "gesture-tap": {}, screenshot: {}, "ui-tree": blind });
|
||||
context.scratchImage = { path: "/work/argent-scratch.png", read: async () => frames.shift() };
|
||||
const opened = await run(["open", "dev.brent.euxy", "euxy://", ...flags("ios")]);
|
||||
assert.equal(opened.exitCode, 0, opened.stdout);
|
||||
const tap = calls.find(call => call.tool === "gesture-tap");
|
||||
assert.ok(near(tap.args.x, 0.568) && near(tap.args.y, 0.5085), JSON.stringify(tap.args));
|
||||
assert.deepEqual(calls.filter(call => call.tool === "screenshot").map(call => call.options), [{ out: "/work/argent-scratch.png" }, { out: "/work/argent-scratch.png" }]);
|
||||
assert.equal(context.state.deepLinkPromptAccepted, true);
|
||||
});
|
||||
|
||||
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],
|
||||
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;
|
||||
const reads = calls.filter(call => call.tool === "ui-tree").length;
|
||||
const folded = await run(["fold", "open", ...flags("ios")]);
|
||||
assert.deepEqual(folded.json.data, { action: "fold", pose: "open" });
|
||||
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" });
|
||||
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("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: [
|
||||
{ type: "Button", label: "Delete", frame: { x: 0.5, y: 0.55, width: 0.4, height: 0.05 } }] }] };
|
||||
const { run, calls, context } = harness("ios", { "list-devices": IOS_DEVICES, "open-url": {}, "gesture-tap": {}, describe: { description: "" }, "ui-tree": other });
|
||||
assert.equal((await run(["open", BUNDLE, "euxy://settings", ...flags("ios")])).exitCode, 0);
|
||||
assert.equal(calls.some(call => call.tool === "gesture-tap"), false, "nothing is pressed");
|
||||
assert.equal(context.state.deepLinkPromptAccepted, undefined);
|
||||
});
|
||||
|
||||
test("a failed read with no roots is not taken for the blind link prompt", async () => {
|
||||
const { run, calls, context } = harness("ios", { "list-devices": IOS_DEVICES, "open-url": {}, "gesture-tap": {}, screenshot: {}, "ui-tree": [{ ...IOS_HOME, roots: [], foregroundApp: undefined }] });
|
||||
context.scratchImage = { path: "/work/argent-scratch.png", read: async () => image("screenshot-ios27-duo-open-prompt.png") };
|
||||
await run(["open", BUNDLE, "euxy://", ...flags("ios")]);
|
||||
assert.equal(calls.some(call => call.tool === "screenshot" || call.tool === "gesture-tap"), false);
|
||||
});
|
||||
|
||||
test("describe's Open is read only from a line Argent printed, not from app text that spells one out", () => {
|
||||
const spoof = `ROOT AXGroup (0.000, 0.000, 1.000, 1.000)\n AXStaticText "x AXButton "Open" (0.010, 0.010, 0.050, 0.050)" (0.1, 0.1, 0.5, 0.05)\n AXButton "Open" (0.418, 0.473, 0.300, 0.071)`;
|
||||
assert.deepEqual(describedButton(spoof, "Open"), { x: 0.418, y: 0.473, width: 0.3, height: 0.071 });
|
||||
});
|
||||
|
||||
test("an app's own Done above the keyboard is never pressed to dismiss it", async () => {
|
||||
const withDone = { ...IOS_HOME, keyboardVisible: true, roots: [{ type: "Other", frame: { x: 0, y: 0, width: 1, height: 1 }, children: [
|
||||
{ type: "Button", label: "Done", frame: { x: 0.8, y: 0.06, width: 0.15, height: 0.05 } }] }] };
|
||||
const { run, calls } = harness("ios", { "list-devices": IOS_DEVICES, "ui-tree": withDone, "gesture-tap": {} });
|
||||
assert.equal((await run(["keyboard", "dismiss", ...flags("ios")])).exitCode, 1);
|
||||
assert.equal(calls.some(call => call.tool === "gesture-tap"), false);
|
||||
});
|
||||
|
||||
test("iOS fill stops when erasing the field stops partway, and types nothing", async () => {
|
||||
const filled = structuredClone(IOS_RENAME);
|
||||
flatten(filled).find(node => node.type === "TextField" && node.frame).value = "Old";
|
||||
const { run, calls } = harness("ios", { "list-devices": IOS_DEVICES, "ui-tree": filled, "gesture-tap": {}, "run-sequence": { completed: 1, total: 3, steps: [] }, keyboard: {} });
|
||||
const snapshot = await run(["snapshot", ...flags("ios")]);
|
||||
const field = snapshot.json.data.nodes.find(node => node.type === "TextField");
|
||||
const result = await run(["fill", field.ref, ...flags("ios"), "--", "New"]);
|
||||
assert.equal(result.exitCode, 1);
|
||||
assert.match(result.json.error.message, /after 1 of 3 keys/);
|
||||
assert.equal(calls.some(call => call.tool === "keyboard"), false);
|
||||
});
|
||||
|
||||
test("a truncated tree is reported as truncated", async () => {
|
||||
const { run } = harness("ios", { "list-devices": IOS_DEVICES, "ui-tree": { ...IOS_HOME, truncated: true } });
|
||||
assert.equal((await run(["snapshot", ...flags("ios")])).json.data.truncated, true);
|
||||
});
|
||||
|
||||
test("Android disabled controls are reported disabled (the recorded rename screen has four)", () => {
|
||||
const { nodes } = snapshotFromTree(ANDROID_RENAME, "android", 1, BUNDLE);
|
||||
const rename = nodes.find(node => node.label === "Rename" && node.type === "Button");
|
||||
assert.ok(rename, "the rename fixture has its Rename button");
|
||||
assert.equal(rename.enabled, false);
|
||||
assert.equal(rename.hittable, false);
|
||||
});
|
||||
|
||||
test("an Android permission dialog from another package stays in the snapshot as an alert", async () => {
|
||||
const dialog = { ...ANDROID_HOME, roots: [...ANDROID_HOME.roots, { type: "android.widget.FrameLayout", bundleId: "com.google.android.permissioncontroller",
|
||||
frame: { x: 0.1, y: 0.35, width: 0.8, height: 0.3 }, children: [
|
||||
{ type: "android.widget.TextView", label: "Allow euxy to send you notifications?", frame: { x: 0.15, y: 0.4, width: 0.7, height: 0.05 } },
|
||||
{ type: "android.widget.Button", label: "Allow", frame: { x: 0.15, y: 0.55, width: 0.7, height: 0.05 } }] }] };
|
||||
const { run } = harness("android", { "list-devices": ANDROID_DEVICES, "ui-tree": dialog });
|
||||
const snapshot = (await run(["snapshot", ...flags("android")])).json.data;
|
||||
assert.ok(snapshot.nodes.some(node => node.type === "Button" && node.label === "Allow"), "the dialog's buttons can be found");
|
||||
assert.ok(snapshot.nodes.some(node => node.type === "Alert"), "capture sees an alert covering the app");
|
||||
assert.ok(!snapshot.nodes.some(node => /systemui/.test(JSON.stringify(node))), "the system UI is still left out");
|
||||
assert.deepEqual((await run(["alert", "get", ...flags("android")])).json.data.alert.buttons, ["Allow"]);
|
||||
});
|
||||
|
||||
test("system back swipes from the iOS edge; Android prefers an in-app back control", async () => {
|
||||
const ios = harness("ios", { "list-devices": IOS_DEVICES, "ui-tree": IOS_HOME, "gesture-swipe": {} });
|
||||
assert.equal((await ios.run(["back", "--system", ...flags("ios")])).exitCode, 0);
|
||||
assert.deepEqual(ios.calls.at(-1).args, { udid: UDID, fromX: 0.05, fromY: 0.5, toX: 0.8, toY: 0.5, momentum: false });
|
||||
|
||||
const up = { ...ANDROID_HOME, roots: [...ANDROID_HOME.roots.filter(root => root.bundleId !== BUNDLE), { type: "android.widget.FrameLayout", bundleId: BUNDLE,
|
||||
frame: { x: 0, y: 0, width: 1, height: 1 }, children: [{ type: "android.widget.ImageButton", contentDescription: "Navigate up", frame: { x: 0, y: 0.05, width: 0.1, height: 0.05 } }] }] };
|
||||
const android = harness("android", { "list-devices": ANDROID_DEVICES, "ui-tree": up, "gesture-tap": {}, button: {} });
|
||||
assert.deepEqual((await android.run(["back", "--in-app", ...flags("android")])).json.data, { action: "back", mode: "in-app" });
|
||||
assert.equal(android.calls.some(call => call.tool === "button"), false);
|
||||
const none = harness("android", { "list-devices": ANDROID_DEVICES, "ui-tree": ANDROID_HOME, button: {} });
|
||||
assert.equal((await none.run(["back", "--in-app", ...flags("android")])).json.error.message, "in-app back control is not available");
|
||||
assert.deepEqual((await none.run(["back", ...flags("android")])).json.data, { action: "back", mode: "system" });
|
||||
});
|
||||
|
||||
test("open without --relaunch keeps a running app as it is", async () => {
|
||||
const { run, calls } = harness("ios", { "list-devices": IOS_DEVICES, "ui-tree": IOS_HOME, "restart-app": {} });
|
||||
assert.equal((await run(["open", BUNDLE, ...flags("ios")])).exitCode, 0);
|
||||
assert.equal(calls.some(call => call.tool === "restart-app"), false);
|
||||
});
|
||||
|
||||
test("a link prompt that lingers a moment after Open is pressed is not a failure", async () => {
|
||||
const prompt = { ...IOS_HOME, alertVisible: true, foregroundApp: "com.apple.springboard",
|
||||
roots: [...IOS_HOME.roots, { type: "Alert", label: "Open in “euxy”?", frame: { x: 0.1, y: 0.4, width: 0.8, height: 0.2 }, children: [] }] };
|
||||
// Read once before the press, twice more while the app comes forward, then the app.
|
||||
const { run, context } = harness("ios", { "list-devices": IOS_DEVICES, "open-url": {}, "gesture-tap": {}, describe: { description: "" }, "ui-tree": [prompt, prompt, prompt, IOS_HOME] });
|
||||
assert.equal((await run(["open", BUNDLE, "euxy://", ...flags("ios")])).exitCode, 0);
|
||||
assert.equal(context.state.deepLinkPromptAccepted, true);
|
||||
});
|
||||
|
||||
test("on iPhone Duo's inner display, a sheet's title outside Argent's shrunken root frame is visible", () => {
|
||||
assert.deepEqual(DUO_OPEN_EDIT_LANE.roots[0].frame, { x: 0, y: 0, width: 0.3333333333333333, height: 0.3333333333333333 }, "the recorded Argent quirk");
|
||||
const { nodes } = snapshotFromTree(DUO_OPEN_EDIT_LANE, "ios", 1, BUNDLE);
|
||||
for (const label of ["Edit Lane", "Cancel", "Done"]) {
|
||||
const node = nodes.find(item => item.label === label);
|
||||
assert.ok(node, label);
|
||||
assert.notEqual(node.visible, false, `${label} is visible`);
|
||||
}
|
||||
});
|
||||
|
||||
test("a node its ancestor clips away is still reported hidden on iOS", () => {
|
||||
const clipped = { screen: { width: 400, height: 800 }, foregroundApp: BUNDLE, roots: [{ type: "Application", frame: { x: 0, y: 0, width: 1, height: 1 }, children: [
|
||||
{ type: "ScrollView", frame: { x: 0, y: 0, width: 1, height: 0.5 }, children: [
|
||||
{ type: "Button", label: "In view", frame: { x: 0.1, y: 0.1, width: 0.3, height: 0.05 } },
|
||||
{ type: "Button", label: "Scrolled away", frame: { x: 0.1, y: 0.7, width: 0.3, height: 0.05 } }] }] }] };
|
||||
const { nodes } = snapshotFromTree(clipped, "ios", 1, BUNDLE);
|
||||
assert.notEqual(nodes.find(node => node.label === "In view").visible, false);
|
||||
assert.equal(nodes.find(node => node.label === "Scrolled away").visible, false);
|
||||
});
|
||||
|
||||
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, "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, "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");
|
||||
});
|
||||
@@ -64,7 +64,11 @@ test("failure reporting downloads only this run attempt's failed-job diagnostics
|
||||
assert.equal(step.with["run-id"], undefined, "download-artifact defaults to this run");
|
||||
assert.equal(step.with.repository, undefined);
|
||||
}
|
||||
const resolve = workflow.jobs.capture.steps.findIndex(step => step.id === "pr");
|
||||
const install = workflow.jobs.capture.steps.findIndex(step => step.name === "Install Explore");
|
||||
assert.ok(resolve >= 0 && resolve < install, "authorized PR identity survives early tool settings failures");
|
||||
// A capture job that fails before it resolves the PR (its tool install, say) still gets its failure comment:
|
||||
// the platforms job already resolved and authorized the same PR.
|
||||
const report = job.steps.find(step => step.name === "Report failure only on the current PR");
|
||||
for (const [env, output] of [["PR_NUMBER", "pr_number"], ["HEAD_SHA", "head"], ["BASE_SHA", "base"]]) {
|
||||
assert.equal(report.env[env], `\${{ needs.capture.outputs.${output} || needs.platforms.outputs.${output} }}`);
|
||||
assert.equal(workflow.jobs.platforms.outputs[output], `\${{ steps.pr.outputs.${output} }}`);
|
||||
}
|
||||
});
|
||||
@@ -101,3 +101,27 @@ test("attached sessions are proven live, agent-device typed, and served by the g
|
||||
await assert.rejects(resolveAttachedSimulatorSession({}, undefined), /EAS_SIMULATOR_SESSION_ID did not return a session id/);
|
||||
await assert.rejects(resolveAttachedSimulatorSession({ ...env, AGENT_DEVICE_DAEMON_AUTH_TOKEN: "" }, undefined), /unsafe agent-device connection/);
|
||||
});
|
||||
|
||||
test("an attached argent session is found from ARGENT_* and proven against the session's tool-server", async () => {
|
||||
const { assertAttachedSimulatorSession, readSimulatorDotenvHandoff, resolveAttachedSimulatorSession } = await import(join(root, "dist", "capture", "simulator.js"));
|
||||
const connection = { sessionId: "01a1-mine", daemonBaseUrl: "https://tools.example.eas.dev", daemonAuthToken: "secret", controller: "argent" };
|
||||
const env = { EAS_SIMULATOR_SESSION_ID: "01a1-mine", ARGENT_TOOLS_URL: connection.daemonBaseUrl, ARGENT_AUTH_TOKEN: "secret" };
|
||||
assert.deepEqual(await resolveAttachedSimulatorSession(env, undefined), connection);
|
||||
// A tool-server that needs no token is still an argent session.
|
||||
assert.deepEqual(await resolveAttachedSimulatorSession({ ...env, ARGENT_AUTH_TOKEN: undefined }, undefined), { ...connection, daemonAuthToken: "" });
|
||||
await assert.rejects(resolveAttachedSimulatorSession({ ...env, ARGENT_TOOLS_URL: "http://tools.example.eas.dev" }, undefined), /unsafe argent/);
|
||||
const session = (overrides = {}) => JSON.stringify({ id: "01a1-mine", name: "mine", type: "argent", status: "IN_PROGRESS", platform: "ANDROID",
|
||||
remoteConfig: { toolsUrl: connection.daemonBaseUrl, toolsAuthToken: "secret" }, ...overrides });
|
||||
assert.equal(assertAttachedSimulatorSession(session(), connection).platform, "android");
|
||||
assert.throws(() => assertAttachedSimulatorSession(session({ type: "agent-device" }), connection), /attached argent session/);
|
||||
assert.throws(() => assertAttachedSimulatorSession(session({ remoteConfig: { toolsUrl: connection.daemonBaseUrl, toolsAuthToken: "other" } }), connection), /different argent connection/);
|
||||
const dir = await mkdtemp(join(tmpdir(), "explore-argent-dotenv-"));
|
||||
try {
|
||||
const path = join(dir, ".env.eas-simulator");
|
||||
await writeFile(path, "# Do not commit this file.\n# Do not modify these values manually. They are managed by eas-cli.\n# It holds configuration only for the current simulator session.\n\nEAS_SIMULATOR_SESSION_ID='01a1-mine'\nARGENT_TOOLS_URL='https://tools.example.eas.dev'\nARGENT_AUTH_TOKEN='secret'\n");
|
||||
const handoff = await readSimulatorDotenvHandoff(path);
|
||||
assert.equal(handoff.validationError, undefined);
|
||||
assert.deepEqual(handoff.connection, connection);
|
||||
assert.deepEqual(await resolveAttachedSimulatorSession({}, path), connection);
|
||||
} finally { await rm(dir, { recursive: true, force: true }); }
|
||||
});
|
||||
@@ -135,6 +135,11 @@ test("capture recipes exclude display settings but bind agent instructions and c
|
||||
assert.equal(JSON.parse(key).observer, CAPTURE_OBSERVER_HASH);
|
||||
assert.match(JSON.parse(key).observer, /^[a-f0-9]{64}$/);
|
||||
assert.equal(key,captureRecipeConfig({...config,app:{...config.app,name:"Renamed display"}}));
|
||||
// agent-device recipes are unchanged by Argent support; an Argent capture is keyed to Argent and its version.
|
||||
assert.equal(JSON.parse(key).controllerVersion, undefined);
|
||||
const argent = JSON.parse(captureRecipeConfig({...config,capture:{...config.capture,controller:"argent"}}));
|
||||
assert.equal(argent.capture.controller, "argent");
|
||||
assert.match(argent.controllerVersion, /^\d+\.\d+\.\d+$/);
|
||||
const agent = {...config,mode:"agent",agent:{provider:"openai",model:"another-model",instructions:".expo-explore/instructions.md"}};
|
||||
assert.notEqual(key,captureRecipeConfig(agent,"a".repeat(64)));
|
||||
assert.equal(JSON.parse(captureRecipeConfig(agent,"a".repeat(64))).agent.acceptancePolicy, AGENT_ACCEPTANCE_POLICY);
|
||||
|
||||
@@ -2,16 +2,44 @@ import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
|
||||
const { tsImport } = await import("tsx/esm/api");
|
||||
const { isVisibleChange } = await tsImport("../../viewer/src/utils/changed-screens.ts", import.meta.url);
|
||||
const { isCapturedChange } = await tsImport("../../viewer/src/utils/changed-screens.ts", import.meta.url);
|
||||
|
||||
test("only a change the captures show counts for Compare and Screens' Changed filter", () => {
|
||||
assert.equal(isVisibleChange({ status: "added" }), true);
|
||||
assert.equal(isVisibleChange({ status: "removed" }), true);
|
||||
assert.equal(isVisibleChange({ status: "modified" }), true);
|
||||
// The source changed but the captures look the same.
|
||||
assert.equal(isVisibleChange({ status: "modified", notVisible: true }), false);
|
||||
assert.equal(isVisibleChange({ status: "needs-review" }), false);
|
||||
assert.equal(isVisibleChange({ status: "source-affected" }), false);
|
||||
assert.equal(isVisibleChange({ status: "unchanged" }), false);
|
||||
assert.equal(isVisibleChange(undefined), false);
|
||||
assert.equal(isCapturedChange({ status: "added" }), true);
|
||||
assert.equal(isCapturedChange({ status: "removed" }), true);
|
||||
assert.equal(isCapturedChange({ status: "modified" }), true);
|
||||
// The screenshots match but the accessibility tree changed: screen readers see it, so it is reviewed.
|
||||
assert.equal(isCapturedChange({ status: "modified", accessibilityOnly: true }), true);
|
||||
// The source changed but the captures show nothing different.
|
||||
assert.equal(isCapturedChange({ status: "needs-review" }), false);
|
||||
assert.equal(isCapturedChange({ status: "source-affected" }), false);
|
||||
assert.equal(isCapturedChange({ status: "unchanged" }), false);
|
||||
assert.equal(isCapturedChange(undefined), false);
|
||||
});
|
||||
|
||||
const { splitForAssistiveTechnology } = await tsImport("../../viewer/src/utils/presented-changes.ts", import.meta.url);
|
||||
|
||||
test("What changed lists what assistive technology reads under its own heading", () => {
|
||||
const change = (id, category) => ({ id, copy: id, fact: { id, category, templateId: `${category}.x`, priority: 0, evidenceRefs: [] } });
|
||||
const changes = [change("Added button “Play”.", "element"), change("Changed accessibility label.", "accessibility")];
|
||||
const ids = ({ visible, assistive }) => [visible.map(entry => entry.id), assistive.map(entry => entry.id)];
|
||||
// Pixels differ: an added element may be visible, a label is not.
|
||||
assert.deepEqual(ids(splitForAssistiveTechnology(changes, { status: "modified" })), [["Added button “Play”."], ["Changed accessibility label."]]);
|
||||
// The screenshots match: nothing on the screen looks different, so every finding is for assistive technology.
|
||||
assert.deepEqual(ids(splitForAssistiveTechnology(changes, { status: "modified", accessibilityOnly: true })), [[], ["Added button “Play”.", "Changed accessibility label."]]);
|
||||
// A reviewer note is not a finding about the accessibility tree.
|
||||
assert.deepEqual(ids(splitForAssistiveTechnology([{ id: "review-note", copy: "Note" }], { status: "modified", accessibilityOnly: true })), [["review-note"], []]);
|
||||
});
|
||||
|
||||
const { focusCounts, focusStatusOf } = await tsImport("../../viewer/src/utils/changed-screens.ts", import.meta.url);
|
||||
|
||||
test("the Changes filter counts Accessibility only apart from Modified", () => {
|
||||
const screens = new Map([
|
||||
["a", { status: "modified" }], ["b", { status: "modified", accessibilityOnly: true }], ["c", { status: "modified", accessibilityOnly: true }],
|
||||
["d", { status: "added" }], ["e", { status: "not-compared" }], ["f", { status: "unchanged" }],
|
||||
]);
|
||||
assert.deepEqual(focusCounts({ screens }), { added: 1, modified: 1, "accessibility-only": 2, removed: 0, "needs-review": 0, "source-affected": 0 });
|
||||
assert.equal(focusStatusOf({ status: "modified", accessibilityOnly: true }), "accessibility-only");
|
||||
assert.equal(focusStatusOf({ status: "modified" }), "modified");
|
||||
assert.equal(focusStatusOf(undefined), undefined);
|
||||
});
|
||||
@@ -142,15 +142,19 @@ async function fixture(t, settings = {}) {
|
||||
}
|
||||
if (command === 'simulator:start') {
|
||||
sessionName = value(request, '--name');
|
||||
writeFileSync(join(request.cwd, '.env.eas-simulator'), HEADER + "EAS_SIMULATOR_SESSION_ID='session-1'\nAGENT_DEVICE_DAEMON_BASE_URL='https://controller.example/session'\nAGENT_DEVICE_DAEMON_AUTH_TOKEN='" + DAEMON_TOKEN + "'\n");
|
||||
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');
|
||||
return { stdout: 'ready', stderr: '' };
|
||||
}
|
||||
if (command === 'simulator:get') return json({ id: 'session-1', name: sessionName, type: 'agent-device', platform: settings.android ? 'ANDROID' : 'IOS', status: '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: { agentDeviceRemoteSessionUrl: 'https://controller.example/session', agentDeviceRemoteSessionToken: DAEMON_TOKEN,
|
||||
remoteConfig: { ...(settings.argent ? { toolsUrl: 'https://controller.example/session', toolsAuthToken: DAEMON_TOKEN }
|
||||
: { agentDeviceRemoteSessionUrl: 'https://controller.example/session', agentDeviceRemoteSessionToken: DAEMON_TOKEN }),
|
||||
// eas-cli --json folds the preview token into an expo.dev page that frames the preview server.
|
||||
webPreviewUrl: settings.webPreviewUrl ?? `https://expo.dev/simulator-preview/${PREVIEW_ID}?token=${PREVIEW_TOKEN}` } });
|
||||
webPreviewUrl: settings.webPreviewUrl ?? `https://expo.dev/simulator-preview/${PREVIEW_ID}?token=${PREVIEW_TOKEN}`,
|
||||
...(settings.previewApiUrl ? { previewApiUrl: settings.previewApiUrl } : {}) } });
|
||||
if (command === 'simulator:stop') {
|
||||
if (settings.stopFailure) throw new Error('stop unavailable');
|
||||
return json({ id: 'session-1', status: 'STOPPED' });
|
||||
@@ -164,8 +168,9 @@ async function fixture(t, settings = {}) {
|
||||
if (settings.android) writeFileSync(value(request, '--output'), 'apk'); else mkdirSync(value(request, '--output'));
|
||||
return { stdout: '', stderr: '' };
|
||||
}
|
||||
if (request.command === 'fake-controller') {
|
||||
if (command === '--version') return { stdout: AGENT_DEVICE_VERSION, stderr: '' };
|
||||
// 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 === 'open') {
|
||||
if (request.args.includes('--relaunch')) splashLeft = settings.splashFrames ?? 0;
|
||||
if (request.args[2]?.startsWith('sample://')) {
|
||||
@@ -184,6 +189,7 @@ async function fixture(t, settings = {}) {
|
||||
return ok(settings.wrongForeground ? { appBundleId: 'com.foreign.app' } : identity());
|
||||
}
|
||||
if (command === 'wait') return ok({});
|
||||
if (command === 'fold') return ok({ action: 'fold', pose: request.args[1] });
|
||||
if (command === 'record' && settings.recording) {
|
||||
if (request.args[1] === 'start') { recordingPath = request.args[2]; return ok({ path: recordingPath }); }
|
||||
writeFileSync(recordingPath, 'mp4-bytes'); return ok({ path: recordingPath });
|
||||
@@ -282,7 +288,7 @@ async function fixture(t, settings = {}) {
|
||||
buildId: 'source-capture', buildVersion: '1', gitCommit: SHA, bundleId: 'com.example.app',
|
||||
...(settings.noScheme ? {} : { scheme: 'sample' }), device: deviceName, easProfile: 'capture', expoToken: 'expo-private', ...(settings.android ? { platform: 'android' } : {}),
|
||||
planPath, maxScreens: 120, maxActions: 500, maxDurationMinutes: 30, forceFreshBuild: false,
|
||||
confirmExternalRun: true, confirmTrustedSource: true, easCommand: 'fake-eas', repackCommand: 'fake-repack', agentDeviceCommand: 'fake-controller', ...(settings.launch ? { launch: settings.launch, recordingTools: settings.recordingTools ?? null } : {}), ...(settings.repack ? { repack: settings.repack } : {}),
|
||||
confirmExternalRun: true, confirmTrustedSource: true, easCommand: 'fake-eas', repackCommand: 'fake-repack', agentDeviceCommand: 'fake-controller', ...(settings.argent ? { controller: 'argent' } : {}), ...(settings.devicePose ? { devicePose: settings.devicePose } : {}), ...(settings.launch ? { launch: settings.launch, recordingTools: settings.recordingTools ?? null } : {}), ...(settings.repack ? { repack: settings.repack } : {}),
|
||||
environment: { PATH: process.env.PATH, HOME: root, GITHUB_TOKEN: 'github-private', ANTHROPIC_API_KEY: 'must-not-be-used', AGENT_DEVICE_DAEMON_AUTH_TOKEN: 'wrong-token', ...settings.environment },
|
||||
// Every controller round trip advances the fixture clock by one poll interval, as a device snapshot would.
|
||||
runner: request => { clockMs += 600; return runner(request); }, now: () => clockMs, sleep: milliseconds => { clockMs += milliseconds; }, fetch: catalog };
|
||||
@@ -349,6 +355,74 @@ test('an app pinned to one appearance is captured once, in that appearance', asy
|
||||
assert.deepEqual(map.screens.map(screen => [screen.id, screen.colorScheme]), [[f.ids.home, undefined], [f.ids.settings, undefined]]);
|
||||
});
|
||||
|
||||
test('an Argent capture starts an argent session, drives it through the bridge, and records Argent as the controller', async t => {
|
||||
const f = await fixture(t, { argent: true, userInterfaceStyle: 'automatic', environment: { AGENT_DEVICE_DAEMON_BASE_URL: 'https://wrong.example', ARGENT_TOOLS_URL: 'https://wrong.example' } });
|
||||
const lines = [];
|
||||
const result = await runCiMap({ ...f.options, progress: line => lines.push(line) });
|
||||
assert.equal(result.runStatus, 'complete');
|
||||
const start = f.requests.find(request => request.args[0] === 'simulator:start');
|
||||
assert.equal(value(start, '--type'), 'argent');
|
||||
assert.equal(value(start, '--package-version'), '0.29.0');
|
||||
assert.ok(start.args.includes('--public-link'));
|
||||
const controller = f.requests.filter(request => request.command.endsWith('/argent-controller'));
|
||||
assert.ok(controller.length > 0);
|
||||
assert.ok(!f.requests.some(request => request.command === 'fake-controller'), 'every controller call goes through the bridge');
|
||||
for (const request of controller) {
|
||||
assert.equal(request.environment.ARGENT_TOOLS_URL, 'https://controller.example/session');
|
||||
assert.equal(request.environment.ARGENT_AUTH_TOKEN, DAEMON_TOKEN);
|
||||
assert.equal(request.environment.DO_NOT_TRACK, '1');
|
||||
assert.equal(request.environment.EXPLORE_ARGENT_PLATFORM, 'ios');
|
||||
assert.equal(request.environment.EXPLORE_ARGENT_BUNDLE_ID, 'com.example.app');
|
||||
assert.ok(request.environment.HOME.endsWith('/argent-home') && request.environment.HOME !== f.options.environment.HOME, 'Argent gets a HOME of its own');
|
||||
assert.deepEqual(Object.keys(request.environment).filter(name => name.startsWith('AGENT_DEVICE_')), []);
|
||||
}
|
||||
// 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 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);
|
||||
assert.deepEqual(map.screens.map(screen => screen.id), [f.ids.home, f.ids.settings]);
|
||||
const bundle = JSON.parse(await readFile(join(f.options.outputDirectory, 'bundle.json'), 'utf8'));
|
||||
assert.equal(bundle.controller, 'argent');
|
||||
const execution = parseRuntimeExecutionContext(JSON.parse(await readFile(join(f.options.outputDirectory, 'execution.json'), 'utf8')));
|
||||
assert.equal(execution.controller, 'argent');
|
||||
assert.equal(execution.controllerPackageVersion, '0.29.0');
|
||||
});
|
||||
|
||||
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 = [];
|
||||
await runCiMap({ ...f.options, progress: line => lines.push(line) });
|
||||
assert.equal(lines.some(line => /Argent cannot switch appearance/.test(line)), false);
|
||||
const execution = parseRuntimeExecutionContext(JSON.parse(await readFile(join(f.options.outputDirectory, 'execution.json'), 'utf8')));
|
||||
assert.equal(execution.colorScheme, 'dark');
|
||||
});
|
||||
|
||||
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 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'), []);
|
||||
}
|
||||
});
|
||||
|
||||
test('an agent-device capture writes no controller into its bundle', async t => {
|
||||
const f = await fixture(t);
|
||||
await runCiMap(f.options);
|
||||
const bundle = JSON.parse(await readFile(join(f.options.outputDirectory, 'bundle.json'), 'utf8'));
|
||||
assert.equal('controller' in bundle, false);
|
||||
const start = f.requests.find(request => request.args[0] === 'simulator:start');
|
||||
assert.equal(value(start, '--type'), 'agent-device');
|
||||
assert.equal(value(start, '--package-version'), AGENT_DEVICE_VERSION);
|
||||
});
|
||||
|
||||
test('a preview URL that names the preview server directly reads its catalog', async t => {
|
||||
const f = await fixture(t, { webPreviewUrl: `https://web-preview-${PREVIEW_ID}.eas-simulator.ngrok.dev/?token=${PREVIEW_TOKEN}` });
|
||||
const result = await runCiMap(f.options);
|
||||
@@ -356,6 +430,31 @@ test('a preview URL that names the preview server directly reads its catalog', a
|
||||
assert.deepEqual(f.catalogRequests.map(request => request.url), [`https://web-preview-${PREVIEW_ID}.eas-simulator.ngrok.dev/grid/api?limit=1000`]);
|
||||
});
|
||||
|
||||
test('sessions start with a public preview link, and eas-cli 25 publishes its token on previewApiUrl', async t => {
|
||||
// eas-cli 25 omits the preview token from a private session's --json output; a --public-link session carries it on
|
||||
// previewApiUrl (the preview server itself) and in the fragment of the expo.dev page.
|
||||
const f = await fixture(t, { webPreviewUrl: `https://expo.dev/simulator-preview/${PREVIEW_ID}#token=${PREVIEW_TOKEN}`,
|
||||
previewApiUrl: `https://web-preview-${PREVIEW_ID}.eas-simulator.ngrok.dev/?token=${PREVIEW_TOKEN}` });
|
||||
const result = await runCiMap(f.options);
|
||||
assert.ok(f.requests.find(request => request.args[0] === 'simulator:start').args.includes('--public-link'));
|
||||
assert.equal(result.simulatorRuntime.osVersion, '26.5');
|
||||
assert.deepEqual(f.catalogRequests.map(request => request.url), [`https://web-preview-${PREVIEW_ID}.eas-simulator.ngrok.dev/grid/api?limit=1000`]);
|
||||
});
|
||||
|
||||
test('a preview token in the expo.dev page fragment reaches the framed preview server', async t => {
|
||||
const f = await fixture(t, { webPreviewUrl: `https://expo.dev/simulator-preview/${PREVIEW_ID}#token=${PREVIEW_TOKEN}` });
|
||||
const result = await runCiMap(f.options);
|
||||
assert.equal(result.simulatorRuntime.osVersion, '26.5');
|
||||
assert.equal(f.catalogRequests.length, 1);
|
||||
});
|
||||
|
||||
test('a private session publishes no preview token, so the OS version is unknown and capture goes on', async t => {
|
||||
const f = await fixture(t, { webPreviewUrl: `https://expo.dev/simulator-preview/${PREVIEW_ID}` });
|
||||
const result = await runCiMap(f.options);
|
||||
assert.equal(result.outcomes[f.ids.home].status, 'captured');
|
||||
assert.ok(f.catalogRequests.every(request => request.authorization === null), 'no credential is invented');
|
||||
});
|
||||
|
||||
test('an unrecognized preview URL is not sent the preview token', async t => {
|
||||
const f = await fixture(t, { webPreviewUrl: `https://preview.example/session?token=${PREVIEW_TOKEN}` });
|
||||
const result = await runCiMap(f.options);
|
||||
@@ -2524,13 +2623,6 @@ test('a timed-out native alert query is unknown: the snapshot decides, and it is
|
||||
assert.equal(blocked.operations().includes('screenshot'), false);
|
||||
});
|
||||
|
||||
test('the installed agent-device dependency is the version every controller check uses', async () => {
|
||||
const manifest = JSON.parse(await readFile(new URL('../../package.json', import.meta.url), 'utf8'));
|
||||
const lock = JSON.parse(await readFile(new URL('../../package-lock.json', import.meta.url), 'utf8'));
|
||||
assert.equal(manifest.dependencies['agent-device'], AGENT_DEVICE_VERSION);
|
||||
assert.equal(lock.packages['node_modules/agent-device'].version, AGENT_DEVICE_VERSION);
|
||||
});
|
||||
|
||||
test('agent observation waits out a deferred system-surface snapshot instead of failing', async t => {
|
||||
const f = await fixture(t, { routes: [route('home')] });
|
||||
let refusals = 1, snapshots = 0;
|
||||
|
||||
@@ -122,6 +122,19 @@ test("version prints the package version", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("capture is the local review, capture:review by a shorter name", async (t) => {
|
||||
const outside = await mkdtemp(join(tmpdir(), "explore-capture-"));
|
||||
t.after(() => rm(outside, { recursive: true, force: true }));
|
||||
const failures = ["capture", "capture:review"].map(command => [
|
||||
runFailure(outside, [command, "--bogus", "--json"]),
|
||||
runFailure(outside, [command, "--committed", "--json"]),
|
||||
]);
|
||||
assert.deepEqual(failures[0], failures[1], "the same flags, errors and result contract");
|
||||
assert.equal(failures[0][0].command, "capture:review");
|
||||
assert.equal(failures[0][0].diagnostic.code, "CLI_ARGUMENT_INVALID");
|
||||
assert.equal(failures[0][1].diagnostic.code, "LOCAL_REVIEW_GIT_FAILED", "--committed is a known flag; outside a repository the review stops");
|
||||
});
|
||||
|
||||
test("removed map-writing commands fail as unknown commands", () => {
|
||||
for (const command of ["init", "screen:add", "attempt:commit", "frontier:claim", "gap:add", "finish"]) {
|
||||
const result = spawnSync(process.execPath, [cli, command], { cwd: root, encoding: "utf8" });
|
||||
|
||||