diff --git a/.changeset/peers-decision.md b/.changeset/peers-decision.md new file mode 100644 index 0000000000..ff9c149f7e --- /dev/null +++ b/.changeset/peers-decision.md @@ -0,0 +1,5 @@ +--- +"@e2e-dev/decision": patch +--- + +`decisionFilter()` counts a test as touched, and scores it so, when a setup file that saves one of its peers' sessions changed, as it does for the test's own session; a judged test's score is the highest of its own and its setups'. diff --git a/.changeset/peers-e2e.md b/.changeset/peers-e2e.md new file mode 100644 index 0000000000..9f5410c184 --- /dev/null +++ b/.changeset/peers-e2e.md @@ -0,0 +1,5 @@ +--- +"e2e": patch +--- + +Add `peers`: more users in one test, each on an app of its own. `test('pays Ava', { peers: { ava: { session: 'ava' } } }, async ({ app, peers }) => ...)` opens Ava's app before `beforeEach`, restores her saved session, and closes it with the test. A peer can run on another target (`target`), as another agent (`agent`, `agentContext`), and on a phone, where it takes a device of its own. Every step, file, app log line, and replay recording of a peer carries its name in the report, the terminal, Markdown, the trace page, `--step`, and `--ai-trace`; its files go in `peers//`. `EnginePrepareInfo.peerSlots` tells an engine how many of its `slots` are for peers. A suite's own fixture named `peers` keeps working; only a test that declares peers through it, or on a target whose engine contributes one, is refused. diff --git a/.changeset/peers-html-reporter.md b/.changeset/peers-html-reporter.md new file mode 100644 index 0000000000..f1c42ee480 --- /dev/null +++ b/.changeset/peers-html-reporter.md @@ -0,0 +1,5 @@ +--- +"@e2e-dev/html-reporter": patch +--- + +The HTML report names the peer on each of its steps and app log lines, plays each user's video on a timeline of its own with a switch between users, and shows each user's screen at the failure under their name, on the page and in the copied prompt. diff --git a/.changeset/peers-mobile.md b/.changeset/peers-mobile.md new file mode 100644 index 0000000000..b6376aff07 --- /dev/null +++ b/.changeset/peers-mobile.md @@ -0,0 +1,5 @@ +--- +"@e2e-dev/mobile": patch +--- + +A test's peer on a device target takes a simulator or emulator of its own from the pool: `prepare` binds one device per worker and one per peer. A run that puts a peer on a target with a device provider fails before any test with `UNSUPPORTED_CAPABILITY`, before anything is leased. `mobileTools` calls from a peer's agent act on the peer's own device. diff --git a/.changeset/peers-web.md b/.changeset/peers-web.md new file mode 100644 index 0000000000..8fe19d7f2b --- /dev/null +++ b/.changeset/peers-web.md @@ -0,0 +1,5 @@ +--- +"@e2e-dev/web": patch +--- + +A run that puts a test's peer on a target with a browser provider, or on a browser attached over CDP (`web({ connect })`), fails before any test with `UNSUPPORTED_CAPABILITY`, before anything is leased. A peer on a target that launches its own browser runs as usual. diff --git a/.github/workflows/mobile.yml b/.github/workflows/mobile.yml index ff6f773bc3..7142f9dfcb 100644 --- a/.github/workflows/mobile.yml +++ b/.github/workflows/mobile.yml @@ -220,7 +220,16 @@ jobs: GITHUB_TOKEN: ${{ inputs.agent-device-version == '' && github.token || '' }} E2E_MOBILE_BENCHMARK_IOS_APP: ${{ steps.app.outputs.app-path }} E2E_MOBILE_BENCHMARK_COMMENT: ios${{ matrix.suite == 'agentic' && ' agent' || '' }} - E2E_RUN: node node_modules/e2e/dist/cli/bin.js run --target ios-simulator ${{ matrix.suite == 'agentic' && '--config e2e.agent.config.ts --output .e2e/agent' || '' }} + E2E_RUN: node node_modules/e2e/dist/cli/bin.js run --target ios-simulator --exclude-tag peers ${{ matrix.suite == 'agentic' && '--config e2e.agent.config.ts --output .e2e/agent' || '' }} + run: $E2E_RUN || $E2E_RUN --last-failed + # The two-user test runs on its own: its peer takes the second + # simulator, so in the run above it would leave the whole suite one + # worker. It posts no comment; a failure fails the job. + - name: Run the two-user test + if: ${{ matrix.suite == 'deterministic' }} + env: + E2E_MOBILE_BENCHMARK_IOS_APP: ${{ steps.app.outputs.app-path }} + E2E_RUN: node node_modules/e2e/dist/cli/bin.js run --target ios-simulator --tag peers --output .e2e/peers run: $E2E_RUN || $E2E_RUN --last-failed # The artifact upload below fails whenever the repository's quota is # full, so the failure evidence goes into the log as well. @@ -245,6 +254,7 @@ jobs: path: &report-paths | apps/mobile-benchmark/.e2e/report.json apps/mobile-benchmark/.e2e/agent/report.json + apps/mobile-benchmark/.e2e/peers/report.json if-no-files-found: warn retention-days: 7 - name: Upload artifacts diff --git a/AGENTS.md b/AGENTS.md index beb3b392c9..f69c7803f1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -151,7 +151,8 @@ suites that consume the built packages the way a user would. can affect each test, packing test files into calls under the model's size limit, 8 calls at a time, and leaves out the unlikely ones. It runs every test on an `e2e.config` or lockfile change, and asks nothing about a - test whose test file, setup file, or stored screenshots changed. It scores + test whose test file, a setup file of its or a peer's session, or stored + screenshots changed. It scores each test it keeps through `relevance` (1 for a touched test, the model's probability for a judged one, 0.5 for one it did not judge), and the runner starts each target's likeliest files first. A failed diff --git a/SECURITY.md b/SECURITY.md index 912e28a0b1..79a22880ee 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -57,7 +57,10 @@ included, is in the pixels the model gets. A text download (`.txt`, `.csv`, `.json`, `.html`) is rewritten before it is registered or stored, every secret value becoming ``; any other download is kept as served and marked `incomplete`. Sessions are per-run, target-bound, encrypted -with a memory-only key, and deleted at cleanup. +with a memory-only key, and deleted at cleanup. A test with peers has one +set of secret values for all its users: a value any user typed or restored is +redacted from every user's model input and from every record of the attempt, +and a peer's session restores only on the peer's own target. ## Navigation and origins diff --git a/apps/mobile-benchmark/.gitignore b/apps/mobile-benchmark/.gitignore index 9d66de034f..d2e1df605e 100644 --- a/apps/mobile-benchmark/.gitignore +++ b/apps/mobile-benchmark/.gitignore @@ -43,6 +43,7 @@ yarn-error.* # e2e run output .e2e/results/ .e2e/agent/ +.e2e/peers/ # .e2e/cache/ is not ignored: recordings committed there replay in CI (AGENTS.md, "Committed recordings"). .e2e/sessions/ .e2e/report.json diff --git a/apps/mobile-benchmark/tests/fixtures.ts b/apps/mobile-benchmark/tests/fixtures.ts index aebafe2b34..d3a5e13ea5 100644 --- a/apps/mobile-benchmark/tests/fixtures.ts +++ b/apps/mobile-benchmark/tests/fixtures.ts @@ -33,21 +33,30 @@ function installs(): Installs { /** * `build`: installs the platform's build on this worker's device before its - * first test, and nothing when the run names none (the app is already on the - * device). The engine installs nothing on its own, so this is where the - * suite says it; the step shows in the first test's report. + * first test, and on the device of each peer a test declares, and nothing + * when the run names none (the app is already on the device). The engine + * installs nothing on its own, so this is where the suite says it; the step + * shows in the first test's report. */ export const test = base.extend<{ build: undefined }>({ - build: async ({ device, platform }, use) => { - const build = BUILDS[platform]; - if (build !== undefined) { - const pending = installs(); - let install = pending.get(platform); + build: async ({ device, platform, peers }, use) => { + const pending = installs(); + const installOnce = async (key: string, on: Device, build: string): Promise => { + let install = pending.get(key); if (install === undefined) { - install = device.installApp(build); - pending.set(platform, install); + install = on.installApp(build); + pending.set(key, install); } await install; + }; + const build = BUILDS[platform]; + if (build !== undefined) await installOnce(platform, device, build); + // A peer on a device of its own needs the build there too; a peer on a + // platform the run brings no build for (a browser) has no device to ask. + // In this suite a peer's name is one device for the worker's whole life. + for (const [name, peer] of Object.entries(peers)) { + const peerBuild = BUILDS[peer.platform]; + if (peerBuild !== undefined) await installOnce(`${peer.platform} peer ${name}`, peer.device as Device, peerBuild); } await use(undefined); }, diff --git a/apps/mobile-benchmark/tests/two-users.e2e.ts b/apps/mobile-benchmark/tests/two-users.e2e.ts new file mode 100644 index 0000000000..91ddc83923 --- /dev/null +++ b/apps/mobile-benchmark/tests/two-users.e2e.ts @@ -0,0 +1,55 @@ +/** + * Two users in one test, each on a simulator of its own: the test's own user + * and a peer on the same target. The app keeps no shared state, so what the + * test shows is that each user's steps, and each user's `device`, reach that + * user's device and no other. Locator steps only, so it runs without a model. + */ + +import type { Device } from '@e2e-dev/mobile'; +import { expect, openScenario, test } from './fixtures.ts'; + +/** The simulators the run names for the iOS target, as `e2e.config.ts` reads them. */ +const simulators = (process.env.E2E_MOBILE_BENCHMARK_IOS_DEVICE ?? '').split(',').filter((udid) => udid.trim() !== '').length; + +// A peer takes a device of its own beside the worker's, so the scenario runs +// only where the run names two simulators, as CI does; a run with one would +// stop before its first test. Its peer takes the second simulator, so a run +// that holds it runs every other test on one worker: CI runs the suite with +// `--exclude-tag peers`, then this test alone with `--tag peers`. iOS only: +// CI's Android job has one emulator. +test.describe('two users', { tags: ['peers'], platforms: ['ios'], skip: simulators < 2 ? 'needs two simulators in E2E_MOBILE_BENCHMARK_IOS_DEVICE' : false }, () => { + test('each user types on its own device, and each device fixture drives its own', { peers: { second: {} } }, async ({ app, device, screen, peers }) => { + const second = { app: peers.second.app, device: peers.second.device as Device, screen: peers.second.screen }; + // Two devices, under two agent-device sessions. + expect(second.device.unstable_raw.deviceId).not.toBe(device.unstable_raw.deviceId); + expect(second.device.unstable_raw.session).not.toBe(device.unstable_raw.session); + expect(peers.second.platform).toBe('ios'); + + await openScenario({ app, device, screen }, 'Control Inventory'); + await openScenario(second, 'Control Inventory'); + + // What one user types shows on its own screen only. + await screen.getByRole('textbox', 'Name field').fill('Grace Hopper'); + await expect(screen.getByTestId('name-echo')).toHaveText('name: Grace Hopper'); + await expect(second.screen.getByTestId('name-echo')).toHaveText('name: Ada Lovelace'); + await second.screen.getByRole('textbox', 'Name field').fill('Alan Turing'); + await expect(second.screen.getByTestId('name-echo')).toHaveText('name: Alan Turing'); + await expect(screen.getByTestId('name-echo')).toHaveText('name: Grace Hopper'); + + // Both act at once, each on its own device. + const mine = `first ${Date.now()}`; + const theirs = `second ${Date.now()}`; + await Promise.all([device.setClipboard(mine), second.device.setClipboard(theirs)]); + expect(await device.clipboard()).toBe(mine); + expect(await second.device.clipboard()).toBe(theirs); + + // A device setting of one leaves the other's alone. + try { + await second.device.setAppearance('dark'); + await expect(second.screen.getByTestId('color-scheme')).toHaveText('scheme: dark'); + await expect(screen.getByTestId('color-scheme')).toHaveText('scheme: light'); + } finally { + await second.device.setAppearance('light'); + } + }); +}); diff --git a/apps/testbed/README.md b/apps/testbed/README.md index 8a164e6565..6e9d55f265 100644 --- a/apps/testbed/README.md +++ b/apps/testbed/README.md @@ -11,7 +11,8 @@ here. - `app/server.mjs` — dependency-free playground app. The runner starts and stops it via the web engine's `command` option. The pages live under `app/pages/` by group, each module exporting its routes and its nav - entries: `basics` (home, todos, forms, login/session, dashboard, wizard), + entries: `basics` (home, todos, forms, login/session, dashboard, wizard, + a message board two users share), `interaction` (network, dialogs, board, pointer pad, iframes), `canvas` (four pixels-only surfaces), `downloads` (a file and a long page), and `controls` (control states, scrolling, the browser fixture's page, the @@ -29,7 +30,8 @@ here. credentials and secrets, plus one file per surface added since: control states and the failure codes (`controls`), pointer coordinates and path swipes (`pointer`), viewport and node scrolling (`scroll`), the `browser` - fixture's own verbs (`browser`), and the per-action speed floor (`speed`). + fixture's own verbs (`browser`), the per-action speed floor (`speed`), + and two users in one test (`peers`). The files tagged `playwright` are Playwright's own `tests/page` specs (and `tests/library/download.spec.ts`) at v1.64.1, ported to the public API: each header names its source and the tests left out. `fail: 'reason'` diff --git a/apps/testbed/app/pages/basics.mjs b/apps/testbed/app/pages/basics.mjs index 5a5b98aaf4..fcdf4e87a2 100644 --- a/apps/testbed/app/pages/basics.mjs +++ b/apps/testbed/app/pages/basics.mjs @@ -2,8 +2,9 @@ * The everyday pages: the landing page, a plans page of copy with inline * links and emphasis (unlisted in the nav), a todo list kept in localStorage, a * profile form, the cookie-session login and the dashboard behind it, a - * three-step wizard, and a checkout with one planted bug. What queries, - * fills, sessions, polling assertions, and judgments are dogfooded against. + * three-step wizard, a checkout with one planted bug, and a message board + * every visitor shares (two users in one test). What queries, fills, + * sessions, polling assertions, and judgments are dogfooded against. */ const nav = [ @@ -14,8 +15,13 @@ const nav = [ { path: '/dashboard', label: 'Dashboard' }, { path: '/wizard', label: 'Wizard' }, { path: '/checkout', label: 'Checkout' }, + { path: '/messages', label: 'Messages' }, ]; +function escapeHtml(text) { + return text.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`); +} + const pages = { '/': () => ({ title: 'Playground', @@ -194,6 +200,21 @@ const pages = { Sign out`, }), + // The board as `request.user` sees it: who they are, every message the + // server keeps (`request.messages`), and a form to post one. + '/messages': (request) => ({ + title: 'Messages', + body: `

Messages

+

Signed in as ${request.user}

+
    + ${(request.messages ?? []).map((message) => `
  • ${escapeHtml(message.author)}: ${escapeHtml(message.text)}
  • `).join('\n ')} +
+
+ + +
`, + }), + // Planted bug: the pay button keeps the total from page load, so after a // quantity change the summary and the button show different totals. '/checkout': () => ({ diff --git a/apps/testbed/app/server.mjs b/apps/testbed/app/server.mjs index 6edc97cad1..36a8119b21 100644 --- a/apps/testbed/app/server.mjs +++ b/apps/testbed/app/server.mjs @@ -12,6 +12,8 @@ import { playwrightRoutes } from './playwright/routes.mjs'; const PORT = Number(process.env.PORT ?? 4271); const playwright = playwrightRoutes(PORT); +/** The message board every visitor shares: one user posts, any other sees it (the peers test). */ +const messages = []; function parseCookies(request) { const header = request.headers.cookie ?? ''; @@ -64,6 +66,19 @@ const server = createServer(async (request, response) => { } return; } + if (url.pathname === '/messages') { + const author = parseCookies(request).session === 'admin' ? 'admin' : 'guest'; + if (request.method === 'POST') { + let body = ''; + for await (const chunk of request) body += chunk; + const text = new URLSearchParams(body).get('text')?.trim(); + if (text) messages.push({ author, text }); + send(303, { location: '/messages' }); + return; + } + html(render('/messages', { user: author, messages })); + return; + } if (url.pathname === '/logout') { send(303, { 'set-cookie': 'session=; Path=/; Max-Age=0', location: '/login' }); return; diff --git a/apps/testbed/e2e.lightpanda.config.ts b/apps/testbed/e2e.lightpanda.config.ts index 6a800927db..44560df170 100644 --- a/apps/testbed/e2e.lightpanda.config.ts +++ b/apps/testbed/e2e.lightpanda.config.ts @@ -11,5 +11,7 @@ import base from './e2e.config.ts'; */ export default { ...base, + // Lightpanda is a browser provider, where a peer cannot run: the peers test is left out. + tests: ['tests/**/*.e2e.ts', '!tests/peers.e2e.ts'], targets: base.targets.map((target) => ({ ...target, name: 'lightpanda', engine: web({ browser: lightpanda({ loadResources: ['iframe'] }) }) })), } satisfies E2EConfig; diff --git a/apps/testbed/tests/peers.e2e.ts b/apps/testbed/tests/peers.e2e.ts new file mode 100644 index 0000000000..a3430c62f4 --- /dev/null +++ b/apps/testbed/tests/peers.e2e.ts @@ -0,0 +1,15 @@ +import { test, expect } from 'e2e'; + +// Two users in one test: the signed-in admin posts, and a second user, in a +// browser of its own and signed out, sees the post on the shared board. +test('a message the admin posts reaches a signed-out user', { session: 'admin', peers: { guest: {} } }, async ({ app, screen, peers }) => { + await app.open('/messages'); + await expect(screen.getByRole('status', 'Signed in as')).toHaveText('admin'); + await screen.getByLabel('Message').fill('Standup moved to 10:30'); + await screen.getByRole('button', 'Post').tap(); + await expect(screen.getByRole('list', 'Messages')).toContainText('admin: Standup moved to 10:30'); + + await peers.guest.app.open('/messages'); + await expect(peers.guest.screen.getByRole('status', 'Signed in as')).toHaveText('guest'); + await expect(peers.guest.screen.getByRole('list', 'Messages')).toContainText('admin: Standup moved to 10:30'); +}); diff --git a/docs/authentication.mdx b/docs/authentication.mdx index 5032ab3cce..8d0e798c3d 100644 --- a/docs/authentication.mdx +++ b/docs/authentication.mdx @@ -287,6 +287,49 @@ Each name refers to an `agents` entry, a `credentials` entry, and a saved session. When the personas don't need separate sessions, [run one flow as several agents](/agents#one-flow-several-personas) instead. +## Two users in one test + +Declare more users with [`peers`](/reference/test#peers). Each peer gets an +app of its own, next to the test's, and the test drives both: + +```ts title="tests/payment.e2e.ts" +import { test } from '@e2e-dev/web'; +import { expect } from 'e2e'; + +test('Ava sees the payment', { session: 'member', peers: { ava: { session: 'ava' } } }, async ({ app, screen, peers }) => { + await app.open('/pay'); + await screen.getByRole('button', 'Pay Ava $3').tap(); + + await peers.ava.app.open('/activity'); + await expect(peers.ava.screen.getByText('$3.00 from Member')).toBeVisible(); +}); +``` + +`peers.ava` has its own `app`, `screen`, `agent`, and `platform`, and its +engine's fixtures, such as `browser` or `device`. Those are typed `unknown`, +since the peer's target decides them: cast one to use it, as in +`peers.ava.device as Device`. A peer opens before `beforeEach` and closes +with the test, also when it fails. + +- **Its own target.** Set `target: 'iphone'` to put the peer on another + target. The run must select it. The test still runs once on each selected + target, so pin the test's own side with `platforms: ['web']`. +- **Its own login.** A peer's `session` is saved by a setup test on the + peer's target. A phone restores no saved login, so a phone peer signs in + during the test. +- **Its own device.** A phone peer takes a simulator or emulator of its own: + see [Two users on two devices](/mobile#two-users-on-two-devices). +- **Its own records.** The report, the trace page, and the terminal name the + peer on each of its steps. Its files go in `peers//`, its replay + recordings are its own in each target and agent the test runs on, its + screenshot baselines in each target, and its agent sees only its own + earlier steps. +- **One set of secrets.** A secret either user types is redacted from what + every user's agent reads, and from every record of the attempt. + +Where a peer can't run, such as a serial group or a hosted browser, and the +error each case gives, is in the [`peers` reference](/reference/test#peers). + ## Next @@ -296,4 +339,7 @@ session. When the personas don't need separate sessions, The `credentials` and `secrets` blocks. + + Every option of a peer, and the errors. + diff --git a/docs/debugging.mdx b/docs/debugging.mdx index cb0389f4e1..819ff9c081 100644 --- a/docs/debugging.mdx +++ b/docs/debugging.mdx @@ -174,9 +174,10 @@ result holds: | --- | --- | | `error` | The code, message, source line, and assertion details | | `failure` | The screen and screenshot artifacts, and any locator candidates | -| `steps` | The calls that led to the failure. Each step's `events` hold what it did (`engine`), what it polled (`poll`), and where the app went (`navigation`). Agent steps add `cache` and recent model turns. `observationTruncated: true` means at least one semantic observation was incomplete. | -| `appLog` | What the app logged. Each line's `step` is the `index` of its step, absent before the first step. | -| `artifacts` | The captured files | +| `steps` | The calls that led to the failure. Each step's `events` hold what it did (`engine`), what it polled (`poll`), and where the app went (`navigation`). Agent steps add `cache` and recent model turns. `observationTruncated: true` means at least one semantic observation was incomplete. A [peer's](/authentication#two-users-in-one-test) step has `user`, the peer's name. | +| `appLog` | What the app logged. Each line's `step` is the `index` of its step, absent before the first step. A peer's line has `user`. | +| `artifacts` | The captured files. A peer's files have `user` and sit under `peers//`. | +| `peers` | Each peer's `target`, what it ran on (`environment`), and its own screen at the failure (`failure`). When a peer's step failed, its screen is here, not in `failure`. Holds the peers whose app opened, so it is absent when none did. | A serial group's tests have no `attempts` of their own. Their results are in `run.serialGroups`, one member for each test in each attempt. A retry the run diff --git a/docs/filters.mdx b/docs/filters.mdx index 94f20c4a35..0a25463b14 100644 --- a/docs/filters.mdx +++ b/docs/filters.mdx @@ -70,7 +70,7 @@ with `INVALID_CHANGED_SINCE`. The change is every file that differs from the merge base of the ref and `HEAD`, uncommitted and untracked files included. The model reads the diff of what the commits change, the test files, and the setup files that save -their sessions, with secrets redacted, except a value a secret provider +their sessions and their peers' sessions, with secrets redacted, except a value a secret provider returns. It gets a file only the working tree changes, uncommitted or untracked, by name alone, never its contents, so a file a CI step writes doesn't reach it. @@ -122,7 +122,8 @@ filter reads only what the commits change. The decision filter also runs: - The tests in a test file that changed or whose stored screenshots - changed, and the tests that use the sessions of such a setup file. + changed, and the tests that use the sessions of such a setup file, their + own or a [peer's](/reference/test#peers). - Every test, when the config the run loaded changes, whatever its name, or when a file named `e2e.config.ts` (`.mts`, `.js`, `.mjs`), Gradle's `libs.versions.toml`, or a lockfile changes in the project's @@ -152,8 +153,8 @@ the most with `--max-failures` and with one worker, the default in CI. | Test | Score | | --- | --- | -| Its test file, setup file, or stored screenshots changed | 100% | -| Every other test | The higher of its rating and its setup's, where a rating the model didn't give counts as 50% | +| Its test file, a setup file of its own or a peer's session, or its stored screenshots changed | 100% | +| Every other test | The highest of its rating and its setups' ratings, where a rating the model didn't give counts as 50% | - Files start in four bands: 75% and up, 50% up to 75%, 25% up to 50%, and under 25%. A file takes the band of its likeliest test. diff --git a/docs/mobile.mdx b/docs/mobile.mdx index a087f59dd6..f405ee8eaa 100644 --- a/docs/mobile.mdx +++ b/docs/mobile.mdx @@ -470,6 +470,30 @@ If none are booted, it boots a shut-down one: on iOS an iPhone before an iPad before an Apple TV, on Android a phone or tablet before a TV, then the newest OS, then name order. Two workers never drive the same device. +### Two users on two devices + +A test's [peers](/authentication#two-users-in-one-test) run beside its own +user. A peer on a device target takes a device of its own from the pool, so +a worker whose test has one peer there needs two devices: + +```ts +test('both see the order', { platforms: ['ios'], peers: { courier: {} } }, async ({ screen, peers }) => { + await screen.getByRole('button', 'Place order').tap(); + await expect(peers.courier.screen.getByText('New order')).toBeVisible(); +}); +``` + +The run sets those devices aside for every worker on the target, for the +whole run, so one test with a peer leaves the target fewer workers for every +test. With too few devices, it starts fewer workers and says so. When one +worker and its peers don't fit, it stops before any test. To keep the rest of +a suite on every device, tag the tests with peers and run them on their own, +as the mobile benchmark's CI does: `--exclude-tag peers` for the suite, then +`--tag peers`. + +A device restores no saved login, so a device peer signs in during the test. +A peer can't take a device from a [device provider](#hosted-devices). + ## Agent tools The agent already has basic actions such as `tap`, `type`, and `scroll`. @@ -495,7 +519,8 @@ export default { } satisfies E2EConfig; ``` -Calls go to the engine that runs the current attempt. `open_app`, `swipe`, +Calls go to the engine that runs the current attempt. A peer's agent calls +the tools on the peer's own device. `open_app`, `swipe`, and `alert` change device state, so the agent runs them live during a cache replay. The [mobile engine reference](/reference/mobile#agent-tools) describes each tool. To add your own beside them, see diff --git a/docs/reference/cli.mdx b/docs/reference/cli.mdx index 0c3ef28593..8ddbe150bb 100644 --- a/docs/reference/cli.mdx +++ b/docs/reference/cli.mdx @@ -964,7 +964,7 @@ bunx e2e list --changed-since origin/main | Reporter | Writes | | --- | --- | | `list` | One line per pair in selection order: `file › title [target]`, with the describe path joined by ` › ` (`tests/billing.e2e.ts › checkout › pays [web]`), then each declared tag as `#tag` (`tests/billing.e2e.ts › checkout › pays [web] #smoke #billing`). A skipped test keeps its line, with `(skipped: )` appended, and a test that a test filter left out ends with `(left out by : )`. Setup tests are listed like any other. | -| `json` | `{ "pairs": [...] }` to stdout. Each pair carries `id`, `file`, `title`, `titlePath`, `kind` (`test` or `setup`), `tags` (the tags the test declares, `[]` when none), `source` when the declaration is known, `session` when the test consumes one, `sessions`, `serialId` when the test is in a serial group, `target`, `agent`, `disposition` (`run`, `skip`, or `filtered` when a test filter left it out), `reason` when skipped or left out, and `filter`, the test filter's name, when one left it out. | +| `json` | `{ "pairs": [...] }` to stdout. Each pair carries `id`, `file`, `title`, `titlePath`, `kind` (`test` or `setup`), `tags` (the tags the test declares, `[]` when none), `source` when the declaration is known, `session` when the test consumes one, `peers` when the test declares [peers](/reference/test#peers) (each `{ name, target, session, agent }`, with the target and agent the pair fills in), `sessions`, `serialId` when the test is in a serial group, `target`, `agent`, `disposition` (`run`, `skip`, or `filtered` when a test filter left it out), `reason` when skipped or left out, and `filter`, the test filter's name, when one left it out. | Pairs a selection flag removed are not listed. [`list` from `e2e/runner`](/reference/runner) runs the same selection in process and also returns the removed pairs. diff --git a/docs/reference/config.mdx b/docs/reference/config.mdx index 141144797f..1d39a5425a 100644 --- a/docs/reference/config.mdx +++ b/docs/reference/config.mdx @@ -1776,6 +1776,8 @@ interface TestFilterCandidate { readonly tags: readonly string[]; /** Project-relative path of the setup test file that saves the test's session; absent without one. */ readonly setupFile?: string; + /** Project-relative paths of the setup test files that save its peers' sessions, each once; absent when no peer restores one. */ + readonly peerSetupFiles?: readonly string[]; } interface TestFilterContext { diff --git a/docs/reference/engine.mdx b/docs/reference/engine.mdx index a471d261f6..5526565984 100644 --- a/docs/reference/engine.mdx +++ b/docs/reference/engine.mdx @@ -97,7 +97,7 @@ rules: | `tapModifiers` | Not a boolean, or `true` without `perform`. | | `keyboard`, `state`, `artifacts`, `session` | An unknown key or a non-function member. `keyboard` without `type` and `press`; `state` without both `capture` and `restore`; `artifacts` without `screenshot`; `startVideo` without `stopVideo`, or the reverse. | | `secrets` | Not an array of `secrets.get()` handles. | -| `fixtures` | Not an object, a fixture that is not a factory function, or a fixture name that is not a lower-camel identifier or shadows `agent`, `app`, `screen`, `platform`, or `session`. | +| `fixtures` | Not an object, a fixture that is not a factory function, or a fixture name that is not a lower-camel identifier or shadows `agent`, `app`, `screen`, `platform`, or `session`. A fixture named `peers` works, but a test that declares [`peers`](/reference/test#peers) on its target fails selection with `COLLECTION_ERROR`. | `artifacts.startTrace` and `artifacts.stopTrace` were removed from the @@ -259,8 +259,8 @@ export interface Engine { * dependencies or boot devices here; report progress through `info.log`. * No launch timeout applies. A failure ends the run as an infrastructure * error. - * The result can lower the target's worker cap, for example after - * discovering how many devices are available. + * The result can say the engine serves fewer of the slots asked for, for + * example after discovering how many devices are available. */ prepare?(info: EnginePrepareInfo): Promise; /** @@ -548,6 +548,23 @@ async prepare(info) { }, ``` +A test's [peers](/reference/test#peers) run inside the worker that runs the +test, each on a slot of its own on the peer's target. `info.slots` counts the +target's own workers, and `info.peerSlots` more for peers. The run hands each +worker and each peer's engine one of those slots as its `workerSlot`, with the +`env` this hook returned. Treat the slots alike. + +An engine that serves fewer slots reports `workers`. The run then starts +fewer workers, the target's own first, and gives the peers the slots right +after them. When it can't serve one worker of each target and their peers, it +stops before any test. An engine that can't give a peer a surface of its own +throws here, before it acquires anything, as `@e2e-dev/web` does for a +browser provider. + +A peer's engine instance lives in the same worker process as the test's own, +each from its own `init`, so state an engine package keeps at module level is +shared between them. + A failure ends the run before any test: | Thrown | Becomes | @@ -559,12 +576,17 @@ A failure ends the run before any test: ```ts /** * What `prepare` learned that the run must honour. `workers` replaces the - * engine's declared cap for this target and run: the surfaces the engine - * actually provisioned, `1` to `info.slots`. Declared `workers` stays the - * static answer for engines that know it up front. + * engine's declared cap for this target and run: how many of `info.slots` + * the engine serves at once, the surfaces it actually provisioned, `1` to + * `info.slots`. Declared `workers` stays the static answer for engines that + * know it up front. */ export interface EnginePrepareResult { - /** Lowers the target's worker cap for this run, `1` to `info.slots`. */ + /** + * How many slots the engine serves at once for this run, `1` to + * `info.slots`: its own workers' and the peers' (`info.peerSlots`) together, + * not its own workers alone. The run fits its worker counts to it. + */ readonly workers?: number; /** * Variables every worker of this target is spawned with, on top of the @@ -589,14 +611,26 @@ export interface EnginePrepareInfo { /** The app the target declares, as `init` receives it: what a device installs or warms up here. */ readonly app: EngineAppInfo; /** - * The worker slots the run will start for this target, `0` to `slots - 1`: - * the run's worker cap, the engine's declared `workers`, and the work units - * selected for the target, whichever is smallest; `0` when nothing runs on - * it while another target has work. A run with nothing to run prepares no + * The slots the run may use on this target, `0` to `slots - 1`: one per + * worker it plans for the target (the run's worker cap, the engine's + * declared `workers`, and the work units selected for the target, whichever + * is smallest), and one per peer (`peerSlots`); `0` when nothing runs on it + * while another target has work. A run with nothing to run prepares no * target. Provision for exactly these slots (boot that many devices of a - * pool); `init` then finds them ready. + * pool); `init` then finds them ready. Treat the slots alike: which one a + * worker or a peer gets is settled after `prepare`, once the run fits its + * workers to what the engine serves. */ readonly slots: number; + /** + * How many of `slots` the run sets aside for peers: a test's other users + * (its `peers` option), each on an engine instance of its own inside the + * worker that runs the test, on a slot no worker of this target holds. A + * count, not a range: see `slots`. Absent in a run that puts no peer on + * the target. An engine that cannot serve a peer refuses here, before it + * acquires anything. + */ + readonly peerSlots?: number; /** * The run's environment: what every worker is started with. A host may hand * the run an environment other than the runner process's own, so anything @@ -747,7 +781,14 @@ export interface EngineInitInfo { * This worker's 0-based slot among the target's workers: the lowest slot * free when the worker was spawned, so a replacement worker takes over the * slot of the one that exited. An engine with several devices hands each - * slot its own; `config.workers` bounds the slots a target can reach. + * slot its own. A target's own workers take the lowest slots, as many as + * the run starts for it; an instance that runs a peer of a worker's test + * gets a slot after them that no worker and no other peer holds. When the + * run starts fewer workers than `prepare` was told, the peers' slots start + * lower too. So a slot can reach past `config.workers`, up to + * `EnginePrepareInfo.slots - 1`. A peer's instance lives in the same worker + * process as the test's own: state an engine package keeps at module level + * is shared between them. */ readonly workerSlot: number; /** Aborts on interrupt and when init exceeds the launch timeout; init must stop promptly. */ diff --git a/docs/reference/errors.mdx b/docs/reference/errors.mdx index 6406e597c7..c6b23cf691 100644 --- a/docs/reference/errors.mdx +++ b/docs/reference/errors.mdx @@ -130,7 +130,7 @@ These appear in terminal output and in the report as plain string codes. | `CONFIG_NOT_FOUND` | `--config ` names a file that does not exist, or no `e2e.config.ts`, `e2e.config.mts`, `e2e.config.js`, or `e2e.config.mjs` exists from the working directory up to the repository root | configuration | 2 | | `CONFIG_AMBIGUOUS` | Both `e2e.config.ts` and `e2e.config.mts` in one directory, or both `e2e.config.js` and `e2e.config.mjs` in one with no TypeScript config | configuration | 2 | | `CONFIG_LOAD_FAILED` | The config module failed to import: a package that is declared but not installed, an undeclared package, a wrong subpath, a removed export, or any other throw while it evaluates. The message names the fix. A config error raised while it evaluates keeps its own code: options a factory the config calls refuses, or a `secrets.get()` handle turned into a string, is `INVALID_CONFIG` | configuration | 2 | -| `INVALID_CONFIG` | A factory the config module calls (`web()`, `mobile()`, `defineEngine()`, `decisionExecutor()`, `decisionFilter()`) refused its options, with the factory's own message. Or: an unknown key, out-of-range value, invalid enum, or missing `targets`; a target key outside `{ name, platform, engine, app, trace, video }`; a target `app` key that is unknown or malformed; `app` on a target without an engine; a `web()` target without `app.url` or with a device field; a `mobile()` target without `app.bundleId` or `app.appPath`, with `app.url` (not supported yet), with a link in `bundleId`, or with an unknown permission name or state (the message names the nearest name); an unknown key in a `web()` or `mobile()` option, `web({ connect })` and `web({ basicAuth })` included (the message names the nearest one); a `trace` or `video` that is not a recording mode; the removed artifact kinds list (`artifacts: [...]` or `artifacts.kinds`) or `artifacts.trace` block (the message names the `trace` mode they meant); the removed `artifacts.video` block or `video` artifact kind (the message names the `video` option); the removed `specVersion` key; a `secrets.get()` in an engine option that names no `secrets` entry (a credential's password is not one); a `secrets.get()` reference turned into a string while the config evaluates (a template literal, `String()`), or given where a string is needed (an `app.command` `args` entry or `env` value; only an engine option that declares secrets takes one); an `app.command` `args` entry or `env` value that is not a string (an `undefined` `env` value is dropped instead); an unknown key in `app.command` (the message names the nearest one); an `engine` that is not a `defineEngine` handle; the `json` reporter combined with `list`, or in a run with `--step`; a duplicate or malformed target name; a secret or credential password shorter than 6 characters (code points); a credential that is not `{ username, password }`, whose `username` is not a string (only `password` may be a function), or that has no username in the config or `E2E_USER__USERNAME`; two credentials or two secrets whose names map to one `E2E_USER_*` or `E2E_SECRET_*` override variable (`api-key` and `api_key`); an oversized `agents..context`; an `expect.poll` `timeout` or `interval` that is not a finite number of milliseconds, or a `timeout` of 0 outside a test; a `tests` value that is not a glob or a list of globs, or a `tests` list of only `!` exclusions; the removed top-level `limits` key; an agents entry that is a bare `StepExecutor` (the message names `{ executor }`) or a model instance (the message names `{ model }`); an unknown agent key (the message names the nearest one); the removed agent keys `timeout` and `maxTurns` (the message names `judgmentTimeout` and `maxModelCalls`); `system` or `tools` beside `executor`; a `tools` entry that `defineTool` did not build, or that takes a built-in tool name (a grammar verb, `complete_step`, `locate`, `run_code`, `test_lines`, `start_recording`, `stop_recording`, or `report_finding`); `createToolLoopExecutor({ maxTurns })`; `reuseExisting` on an app whose `app.url` asks for a free port; a port-0 `app.url` with no `app.command` to serve it; a `filters` value that is not a list of `{ name, filter }` (for a bare function such as `decisionFilter`, the message says to call it); or a filter `name` that breaks the target name rules, is longer than 256 characters, or is used twice | configuration | 2 | +| `INVALID_CONFIG` | A factory the config module calls (`web()`, `mobile()`, `defineEngine()`, `decisionExecutor()`, `decisionFilter()`) refused its options, with the factory's own message. Or: an unknown key, out-of-range value, invalid enum, or missing `targets`; a target key outside `{ name, platform, engine, app, trace, video }`; a target `app` key that is unknown or malformed; `app` on a target without an engine; a `web()` target without `app.url` or with a device field; a `mobile()` target without `app.bundleId` or `app.appPath`, with `app.url` (not supported yet), with a link in `bundleId`, or with an unknown permission name or state (the message names the nearest name); an unknown key in a `web()` or `mobile()` option, `web({ connect })` and `web({ basicAuth })` included (the message names the nearest one); a `trace` or `video` that is not a recording mode; the removed artifact kinds list (`artifacts: [...]` or `artifacts.kinds`) or `artifacts.trace` block (the message names the `trace` mode they meant); the removed `artifacts.video` block or `video` artifact kind (the message names the `video` option); the removed `specVersion` key; a `secrets.get()` in an engine option that names no `secrets` entry (a credential's password is not one); a `secrets.get()` reference turned into a string while the config evaluates (a template literal, `String()`), or given where a string is needed (an `app.command` `args` entry or `env` value; only an engine option that declares secrets takes one); an `app.command` `args` entry or `env` value that is not a string (an `undefined` `env` value is dropped instead); an unknown key in `app.command` (the message names the nearest one); an `engine` that is not a `defineEngine` handle; the `json` reporter combined with `list`, or in a run with `--step`; a duplicate or malformed target name; a secret or credential password shorter than 6 characters (code points); a credential that is not `{ username, password }`, whose `username` is not a string (only `password` may be a function), or that has no username in the config or `E2E_USER__USERNAME`; two credentials or two secrets whose names map to one `E2E_USER_*` or `E2E_SECRET_*` override variable (`api-key` and `api_key`); an oversized `agents..context`; an `expect.poll` `timeout` or `interval` that is not a finite number of milliseconds, or a `timeout` of 0 outside a test; a `tests` value that is not a glob or a list of globs, or a `tests` list of only `!` exclusions; the removed top-level `limits` key; an agents entry that is a bare `StepExecutor` (the message names `{ executor }`) or a model instance (the message names `{ model }`); an unknown agent key (the message names the nearest one); the removed agent keys `timeout` and `maxTurns` (the message names `judgmentTimeout` and `maxModelCalls`); `system` or `tools` beside `executor`; a `tools` entry that `defineTool` did not build, or that takes a built-in tool name (a grammar verb, `complete_step`, `locate`, `run_code`, `test_lines`, `start_recording`, `stop_recording`, or `report_finding`); `createToolLoopExecutor({ maxTurns })`; `reuseExisting` on an app whose `app.url` asks for a free port; a port-0 `app.url` with no `app.command` to serve it; a `filters` value that is not a list of `{ name, filter }` (for a bare function such as `decisionFilter`, the message says to call it); or a filter `name` that breaks the target name rules, is longer than 256 characters, or is used twice. For [`peers`](/reference/test#peers): at launch, a peer whose engine is the same instance as another user's (an engine made inside a package); in the body, `peers.` for a peer the test does not declare | configuration | 2 | | `CONFIG_NOT_DETERMINISTIC` | A worker re-resolved the config module and got a different digest than the runner | configuration | 2 | | `APP_URL_REQUIRED` | A navigation or relative URL on a target that declares no `app.url`, or an `app.command` with no `app.url` or `app.readyUrl` to poll | configuration | 2 | | `INVALID_APP_URL` | A base URL that is unparseable or has userinfo, a query, a fragment, a non-HTTP scheme, or plain HTTP on a non-loopback host; port 0 on a host other than a literal loopback address (`127.0.0.1`, `[::1]`); or a loopback address the run could not bind a free port on | configuration | 2 | @@ -146,15 +146,15 @@ These appear in terminal output and in the report as plain string codes. | `UNKNOWN_TOPIC` | `e2e mcp`: an `e2e://guide/{topic}` resource named a topic the skill does not have. The message lists them | configuration | 2 | | `UNKNOWN_TOOL` | `e2e mcp`: `call` or `tools` named a tool the session's catalog does not have. The message lists the catalog. An action verb the engine does not declare is `UNSUPPORTED_CAPABILITY` instead | configuration | 2 | | `TEST_AMBIGUOUS` | `e2e mcp`: `open_session`'s `test` selected several tests on the session's target. The message lists them as `file:line` | configuration | 2 | -| `SESSION_TEST_UNSUPPORTED` | `e2e mcp`: `open_session`'s `test` selected a test a session cannot run alone: a serial group member, a test that starts from a setup test's `session`, or a test that runs as several agents. Run it with `e2e run` | configuration | 2 | +| `SESSION_TEST_UNSUPPORTED` | `e2e mcp`: `open_session`'s `test` selected a test a session cannot run alone: a serial group member, a test that starts from a setup test's `session`, a test that runs as several agents, or a test with [`peers`](/reference/test#peers). Run it with `e2e run` | configuration | 2 | | `UNSUPPORTED_ARTIFACT` | A [`video` mode](/reference/config#recording) set on a target, or on a test that will run there, records on some attempt, and the target's engine cannot record video. The message names the target, and the test for a test's mode. A mode from the config root or `--video` never raises it: it applies to the targets that can record, with a notice naming the rest | configuration | 2 | -| `UNSUPPORTED_CAPABILITY` | A fixture, action, or tier the target's engine does not declare: a contributed fixture it does not contribute, `screen` without `locate`, state restore without `state`, screenshots without `artifacts`, `app.clearState()` on a persistent browser context (the message names the mode), `agent.assert` `vision` with an executor that does not declare `vision: true`, or `app.startRecording()` while the test's video records | configuration | 2 | +| `UNSUPPORTED_CAPABILITY` | A fixture, action, or tier the target's engine does not declare: a contributed fixture it does not contribute, `screen` without `locate`, state restore without `state`, screenshots without `artifacts`, `app.clearState()` on a persistent browser context (the message names the mode), `agent.assert` `vision` with an executor that does not declare `vision: true`, or `app.startRecording()` while the test's video records. For [`peers`](/reference/test#peers): before any test, a peer on a target that leases browsers or devices from a provider or attaches to a browser over CDP; at launch, a run with no config file to load a peer's engine from (a config value, or tests registered in memory); or a peer the run reserved no slot for | configuration | 2 | | `NO_TESTS` | Zero runnable ordinary test-target pairs. The message names the cause: no file matched the `tests` globs (it lists look-alike files), a positional matched nothing (it names the `!` entry that excludes a file the positional names), a file registered no tests, or filters excluded everything. Suppress with `--pass-with-no-tests`. When [test filters](/filters) leave nothing to run, the run passes instead (exit 0). Also `e2e mcp`'s `open_session` when its `test` selects no runnable test. | configuration | 2 | | `RUNNER_BUSY` | A suite overlapped another suite, an opening or open host, or a live attempt; or a host opened during a suite; or an `e2e mcp` `run_tests` started while another was running. Await the suite and close existing hosts before you retry. | configuration | 2 | | `NO_LAST_RUN` | `--last-failed` found no `report.json` where the run writes it, or a file there that is not a `report-1` document. Run once without the flag first. | configuration | 2 | | `INVALID_CHANGED_SINCE` | `--changed-since` (`changedSince`) is not a string, is empty, or starts with `-`. Or, when the run calls test filters or `e2e explore` explores the change, it names no commit in the checkout or shares no history with HEAD (in a shallow clone the message says to fetch more history, otherwise that the histories are unrelated); or the project is not in a git repository, git is missing, or git did not answer within 30 seconds | configuration | 2 | | `ONLY_IN_CI` | A focused test reached a CI run | configuration | 2 | -| `COLLECTION_ERROR` | Registration outside collection; an invalid title; a non-function body; an async `describe` body; nested serial groups; an option forbidden inside a serial group; a setup test inside `describe`; an invalid session name; a malformed test option, such as `tags` that is not a list of distinct names; a test or `describe` option key the call does not take (the message names the nearest one); a test file that fails to import, in a run with no positionals or when the positionals selected it; a session that a selected test consumes, or `e2e explore --session` names, but no collected setup test produces (the message lists the declared sessions); a consumed session on a target whose engine has no `state` capability to save it; or a positional path outside the project root | configuration | 2 | +| `COLLECTION_ERROR` | Registration outside collection; an invalid title; a non-function body; an async `describe` body; nested serial groups; an option forbidden inside a serial group; a setup test inside `describe`; an invalid session name; a malformed test option, such as `tags` that is not a list of distinct names; a test or `describe` option key the call does not take (the message names the nearest one); a test file that fails to import, in a run with no positionals or when the positionals selected it; a session that a selected test consumes, or `e2e explore --session` names, but no collected setup test produces (the message lists the declared sessions); a consumed session on a target whose engine has no `state` capability to save it; a [`peers`](/reference/test#peers) option that breaks its rules (a name, a field, an unknown `target` or `agent`, a `target` the run does not select, a `session` no setup test saves or on a target that cannot restore one), peers on, inside, or around a serial group or on a setup test, a peer target served by an engine server, a test with peers on a target whose engine contributes its own `peers` fixture or through a `test.extend()` chain that defines one; or a positional path outside the project root | configuration | 2 | | `SESSION_MISMATCH` | A stored session does not match the current run, target, engine, platform, or app identity | configuration | 2 | | `SESSION_EXPIRED` | A stored session is past its expiry at restore time (configuration, exit 2), or a setup test saved state whose expiry is not after its creation (test, exit 1) | configuration or test | 2 or 1 | | `SESSION_INVALID` | A stored session failed authentication. Tampered or corrupt. | configuration | 2 | @@ -176,7 +176,7 @@ These appear in terminal output and in the report as plain string codes. | `NODE_UNSUPPORTED` | The runtime cannot run e2e: a Node.js outside `^22.22.3 \|\| >=24.8.0`, a Bun older than 1.4.3, or Deno. The CLI checks this before it starts and exits 2 with the same sentence. The loader checks again before it loads a config or test file, for a host that runs e2e's runner without the CLI. On Bun, `run`, `list`, `explore`, and `openHost` from `e2e/runner` throw it too: they need Node.js | infrastructure | 3 | | `TYPESCRIPT_COMPILER_UNAVAILABLE` | oxc, which compiles e2e's TypeScript, could not be loaded; the message gives the cause. Most often its native bindings for this platform (`@oxc-transform/binding--`, `@oxc-parser/binding--`) are not installed. npm leaves them out with `--omit=optional`, or when `package-lock.json` was written on another platform (npm/cli#4828). Install again without `--omit=optional`, or delete `package-lock.json` and `node_modules` and run `npm install` | infrastructure | 3 | | `IMAGE_CODEC_UNAVAILABLE` | `@napi-rs/image`, which reads and writes the PNGs of screenshots, could not be loaded; the message gives the cause. It is loaded when the first screenshot is read or written, so a run that takes none never needs it. Most often its native binding for this platform (`@napi-rs/image--*`) is not installed. npm leaves it out with `--omit=optional`, or when `package-lock.json` was written on another platform (npm/cli#4828). Install again without `--omit=optional`, or delete `package-lock.json` and `node_modules` and run `npm install`. The package publishes no binding for Linux on ppc64, s390x, or riscv64, where `toHaveScreenshot` cannot work, and neither can an agent screenshot the runner has to resize (one with a side over 768 px) | infrastructure | 3 | -| `ENGINE_FAILURE` | Any engine fault with no more specific mapping | infrastructure | 3 | +| `ENGINE_FAILURE` | Any engine fault with no more specific mapping; before any test, a target that cannot serve one worker and the [peers](/reference/test#peers) its tests bring to it | infrastructure | 3 | | `WORKER_PROTOCOL` | A worker reported the wrong unit, an attempt overlapped a live attempt, `openHost` tried to acquire an engine instance another host owns, or `host.openSession` tried to reuse a closed host or overlap an opening, live, or closing session | infrastructure | 3 | | `SESSION_KEY_INVALID` | A worker received a session key that is not 32 bytes. Packaging or IPC fault. | infrastructure | 3 | | `REPORT_WRITE_FAILED` | `report.json` or `ai-trace.json` could not be written. Recorded as a run error; the in-memory outcome is still complete. A `junit.xml` that could not be written is a line on the `junit` reporter's stderr instead | infrastructure | 3 | diff --git a/docs/reference/expect.mdx b/docs/reference/expect.mdx index b3578fcb19..08af965559 100644 --- a/docs/reference/expect.mdx +++ b/docs/reference/expect.mdx @@ -236,7 +236,7 @@ Both forms take the [Screenshot options](#screenshot-options). | Property | Value | | --- | --- | -| Stored at | `-snapshots/--.png`; `.png` is added to a name without it | +| Stored at | `-snapshots/--.png`; `.png` is added to a name without it. A [peer's](/reference/test#peers) is in `peers///` there, named after the peer's target | | Unnamed | The test's title path, lowercase, and a count: `checkout-pays-by-card-1` | | Missing | Taken from two screenshots in a row that are the same within the tolerance, then `ASSERTION_FAILED`. Written beside the test; in CI without `--update-snapshots` only attached to the results, at `snapshots/` | | Written earlier in the run | Without `--update-snapshots`, and always for `.not`, no comparison passes against a screenshot the same run wrote (a retry, a repeat, another test naming it): `ASSERTION_FAILED` until the next run. With `--update-snapshots` a positive matcher compares and may write it again | diff --git a/docs/reference/mcp.mdx b/docs/reference/mcp.mdx index 77fe2f30c6..8718f9cc09 100644 --- a/docs/reference/mcp.mdx +++ b/docs/reference/mcp.mdx @@ -715,7 +715,7 @@ open_session {test: "tests/checkout.e2e.ts:12"} | --- | --- | | `NO_TESTS` | `test` selects no runnable test. The message names the cause, as for `e2e run`. | | `TEST_AMBIGUOUS` | `test` selects several tests. The message lists them as `file:line`. | -| `SESSION_TEST_UNSUPPORTED` | The test is in a serial group, starts from a setup test's `session`, or runs as several agents. | +| `SESSION_TEST_UNSUPPORTED` | The test is in a serial group, starts from a setup test's `session`, runs as several agents, or has [`peers`](/reference/test#peers). | | `COLLECTION_ERROR` | A test file fails to collect, as for `e2e run`. | ## Several sessions diff --git a/docs/reference/reporters.mdx b/docs/reference/reporters.mdx index 8eb1ece6e4..479571d882 100644 --- a/docs/reference/reporters.mdx +++ b/docs/reference/reporters.mdx @@ -479,7 +479,7 @@ product failure. Every step phase the runner emits includes `progress.identity`: ```ts -{ attemptId: string; attemptIndex: number; stepId: string; stepIndex: number } +{ attemptId: string; attemptIndex: number; stepId: string; stepIndex: number; user?: string } ``` - The IDs match the final report. Both indexes start at zero. @@ -489,6 +489,9 @@ Every step phase the runner emits includes `progress.identity`: member's step IDs stay distinct. - Use `stepId` to match start, activity, event, replay, and end phases, including nested steps. +- `user` names the [peer](/reference/test#peers) whose app the step runs on. + It is absent for the test's own user. A peer's step can run while one of + the test's own does. - `identity` is optional in the type so a reporter can also accept older streams. diff --git a/docs/reference/runner.mdx b/docs/reference/runner.mdx index 367a43c591..cba001ca16 100644 --- a/docs/reference/runner.mdx +++ b/docs/reference/runner.mdx @@ -269,6 +269,7 @@ process sees an edit. | `file`, `title`, `titlePath`, `kind`, `tags` | The collected test. `kind` is `test` or `setup`. `tags` is `[]` when the test declares none. | | `source` | The declaration, project-relative: `{ file, line, column }`. `undefined` when the test recorded none. | | `session` | The session the test consumes, from the test or its describe chain. `undefined` when it consumes none. | +| `peers` | The test's [peers](/reference/test#peers), each `{ name, target, session, agent }`: `target` and `agent` are filled in from the pair when the peer sets none. Omitted when the test declares no peers. | | `sessions` | Session names a setup produces. `[]` on an ordinary test. | | `serialId` | Set when the test belongs to a serial group, otherwise `undefined`. | | `target`, `agent` | The target name and the configured agent this pair runs as. | diff --git a/docs/reference/security.mdx b/docs/reference/security.mdx index 1af4b4deb2..f60c0396cc 100644 --- a/docs/reference/security.mdx +++ b/docs/reference/security.mdx @@ -235,6 +235,7 @@ instruction, the strings in `agent.act` params, `agentContext`, and an | Minimum length | A static value shorter than 6 characters is `INVALID_CONFIG`. A provider that returns one fails the fill. | | Assertions | Unaffected. Redaction rewrites only what the runner reports. | | Cache entries | Secret values and their cut parts never enter them. | +| [Peers](/reference/test#peers) | The users of one test share one set of values: a secret any of them typed or restored is redacted from what every user's agent reads and from every record of the attempt. | ### Where redaction stops @@ -293,7 +294,8 @@ Every other download is kept as served and labeled A saved session holds authentication state. It also carries, in the same ciphertext, the secret values the setup test resolved from a provider. The test that restores it redacts those values. The envelope holds, unencrypted -but authenticated, the secret names. +but authenticated, the secret names. A [peer's](/reference/test#peers) session +is restored into the peer's app, bound to the peer's own target. | Property | Value | | --- | --- | diff --git a/docs/reference/test.mdx b/docs/reference/test.mdx index 4ed1d5ba8e..2dc2c71913 100644 --- a/docs/reference/test.mdx +++ b/docs/reference/test.mdx @@ -348,6 +348,7 @@ blocked event loop hangs it. | [`platforms`](#platforms) | `readonly string[]` | - | | [`requires`](#requires) | `readonly Capability[]` | - | | [`session`](#session) | `string` | - | +| [`peers`](#peers) | `Record` | - | | [`agentContext`](#agentcontext) | `string` | - | | [`agent`](#agent) | `string \| readonly string[]` | the run's agents | | [`trace`](#trace) | `RecordingMode` | the run's | @@ -357,7 +358,7 @@ blocked event loop hangs it. `test` takes every option but `serial` and `sessions`. `describe` takes every option but `only`, `fail`, and `sessions`. `test.setup` requires -`sessions` and takes no `session`, `only`, `skip`, or `fail`. +`sessions` and takes no `session`, `peers`, `only`, `skip`, or `fail`. Resolution order: test, nearest group, outer groups, config, built-in default. Inside a [serial group](#serial), the group's `retries`, `trace`, and @@ -464,6 +465,50 @@ test('sees the dashboard', { session: 'member' }, async ({ app }) => {}); See [`test.setup`](#test-setup). +#### `peers` + +More users in the test, by name. Each peer opens an app of its own before +`beforeEach` runs, on the test's target or another one, and closes with the +test. The test reaches it as `peers.`. + +```ts +test('Ava sees the payment', { session: 'member', peers: { ava: { session: 'ava' } } }, async ({ app, screen, peers }) => { + await app.open('/pay'); + await screen.getByRole('button', 'Pay Ava $3').tap(); + await peers.ava.app.open('/activity'); + await expect(peers.ava.screen.getByText('$3.00 from Member')).toBeVisible(); +}); +``` + +| Option | Type | Default | +| --- | --- | --- | +| `target` | `string` | the test's target | +| `session` | `string` | - | +| `agent` | `string` | the test's agent | +| `agentContext` | `string` | - | + +- `target` must be a target the run selects. The test still runs on each + selected target as its own; pin the test's side with + [`platforms`](#platforms). +- `session` is a session a setup test saved on the peer's target. The target + must save and restore state, so a phone peer signs in during the test. +- `agentContext` reaches the peer's agent steps only. The test's own + `agentContext` stays with the test's user. +- Names match `/^[A-Za-z0-9_.-]{1,128}$/`, are not `.` or `..`, and differ + in more than case, since each peer's files go in a folder named after it. +- Innermost wins, as a whole. + +See [Two users in one test](/authentication#two-users-in-one-test) for what +each peer gets. + +| Throws | When | +| --- | --- | +| `COLLECTION_ERROR` | A name or field that breaks the rules above, an unknown `target` or `agent`, a `target` the run does not select, a `session` no setup test saves, a `session` on a target that cannot restore one, `peers` on, inside, or around a serial group or on a setup test, a peer target whose engine runs in an engine server, or a target whose engine contributes its own `peers` fixture. | +| `SESSION_TEST_UNSUPPORTED` | `e2e mcp`'s `open_session` names the test: a session drives one app. | +| `UNSUPPORTED_CAPABILITY` | Before any test, the peer's target leases its browsers or devices from a provider, or attaches to a browser over CDP, or the run has no config file to load the peer's engine from: a config value or tests registered in memory. | +| `INVALID_CONFIG` | At launch, the peer's engine is the same object as another user's in the worker, as an engine made inside a package is. In the body, `peers.` names a peer the test does not declare. | +| `ENGINE_FAILURE` | Before any test, a target cannot serve one worker and the peers its tests bring to it. | + #### `agentContext` Extra context for agent steps. Layers are concatenated outermost first. @@ -551,7 +596,7 @@ describe('checkout', { serial: true }, () => { | Throws | When | | --- | --- | -| `COLLECTION_ERROR` | A member sets `retries`, `trace`, `video`, `session`, `platforms`, `requires`, `skip`, `only`, or a nested `serial`. | +| `COLLECTION_ERROR` | A member sets `retries`, `trace`, `video`, `session`, `peers`, `platforms`, `requires`, `skip`, `only`, or a nested `serial`. | #### `sessions` @@ -572,12 +617,18 @@ A static, non-empty array of unique names. Each name matches | [`app`](/reference/app) | `App` | | [`screen`](/reference/screen) | `Screen` | | `platform` | `string` | +| [`peers`](#peers) | `Record` | | [`session`](#test-setup) | `SetupSession` | -`agent`, `app`, and `screen` reach test bodies, `beforeEach`, and +`agent`, `app`, `screen`, and `peers` reach test bodies, `beforeEach`, and `afterEach`. `platform` reaches every hook too, and `session` only `test.setup` bodies. [`TestFixtures`](#testfixtures) describes each one. +`peers.` holds the peer's own `agent`, `app`, `screen`, and `platform`, +and the fixtures its target's engine contributes (`browser`, `device`). A +name the test does not declare throws `INVALID_CONFIG`, naming the peers it +declares. + Everything else is a fixture the target's engine contributes, or one of [your own](#your-own-fixtures). `@e2e-dev/web` contributes [`browser`](/reference/web); a device engine contributes `device`. @@ -643,6 +694,7 @@ Per attempt: | Mistake | Fails | | --- | --- | | A value that is not a plain object of functions, an empty name, a core name (`agent`, `app`, `screen`, `platform`, `session`), or a name an earlier `extend` in the chain defined | At import, `COLLECTION_ERROR` naming the fixture | +| A fixture named `peers` in the chain of a test that declares [`peers`](#peers), on the test or a `describe` around it | At import, `COLLECTION_ERROR` naming the test. Without `peers` on the test, your fixture works as before | | A name the target's engine contributes (`browser` on a Playwright target) | The attempt, in `beforeEach`, `TEST_SETUP_FAILED` | | A definition that returns without calling `use` | The attempt, in `beforeEach`, `TEST_SETUP_FAILED` | | A definition that calls `use` twice | The attempt, at teardown, `TEST_SETUP_FAILED` | @@ -666,8 +718,13 @@ hook finishes. export interface TestAPI { /** Registers one test synchronously during module evaluation. */ (title: string, fn: TestFn): TestCase; - /** Registers one configured test synchronously during module evaluation. */ - (title: string, options: TestOptions, fn: TestFn): TestCase; + /** + * Registers one configured test synchronously during module evaluation. + * The names the test's own `peers` option declares type its `peers` + * fixture, so a peer it never declared is a type error; peers set on a + * `describe` are typed by any name. + */ + > = never>(title: string, options: TestOptions & { peers?: Peers }, fn: TestFn): TestCase; /** Registers one skipped test. */ skip(title: string, fn: TestFn): TestCase; /** @@ -720,6 +777,9 @@ export interface TestAPI { * await workspace.cleanup(); * }, * }); + * + * A fixture named `peers` replaces the core one in its tests' types; those + * tests can't declare the `peers` option. */ extend(fixtures: FixtureDefinitions): TestAPI; /** Declares a group synchronously. */ @@ -774,6 +834,13 @@ export interface TestOptions { requires?: readonly Capability[]; /** Session a setup test saved, restored before the body runs. */ session?: string; + /** + * More users in the test, by name: each opens its own app before + * `beforeEach` runs, on the test's target or another one. Innermost wins, + * as a whole. Names are 1 through 128 ASCII letters, numbers, `_`, `-`, + * or `.`. Not allowed inside a serial group. + */ + peers?: Readonly>; /** Extra context for agent steps; layers are concatenated outermost first. */ agentContext?: string; /** @@ -805,7 +872,28 @@ export interface DescribeOptions extends Omit { serial?: boolean; } -export interface SetupOptions extends Omit { +/** + * One more user in a test: an app of its own, opened next to the test's, + * on the test's target or another one. The test reaches it as + * `peers.`. + */ +export interface PeerOptions { + /** The target the peer's app runs on; defaults to the test's own target. */ + target?: string; + /** + * A session a setup test saved on the peer's target, restored into the + * peer's app before the body runs. The peer's target must save and + * restore state, as for `session`; a device target cannot, so a device + * peer signs in during the test. + */ + session?: string; + /** The configured agent (`agents.`) the peer's `agent` runs with; defaults to the agent the test runs as. */ + agent?: string; + /** Extra context for the peer's agent steps. The test's own `agentContext` stays with the test's user. */ + agentContext?: string; +} + +export interface SetupOptions extends Omit { /** Session names this setup test MUST save. */ sessions: readonly string[]; /** A setup test runs once per target, so it pins at most one agent. */ @@ -825,6 +913,17 @@ export interface TestFixtures { readonly screen: Screen; /** The target's platform label: `web`, `ios`, `android`, or an engine's own string. */ readonly platform: string; + /** The test's peers by name (the `peers` option), each over an app of its own; empty when it declares none. */ + readonly peers: Readonly>; +} + +/** + * One peer's fixtures: what the test's own user has, over the peer's app, and + * the fixtures the peer target's engine contributes (`browser` on a web + * target, `device` on a phone). + */ +export interface PeerFixtures extends Omit { + readonly [fixture: string]: unknown; } export interface SetupFixtures extends TestFixtures { diff --git a/packages/decision/src/filter.ts b/packages/decision/src/filter.ts index 3da53307fd..7ec6b0c352 100644 --- a/packages/decision/src/filter.ts +++ b/packages/decision/src/filter.ts @@ -153,7 +153,7 @@ interface Answers { async function judge(given: readonly TestFilterCandidate[], context: TestFilterContext, options: DecisionFilterOptions): Promise { const { changes, signal, log, redact } = context; const touched = touchedBy(context); - const tests = given.filter((test) => !touched(test.file) && !touched(test.setupFile)); + const tests = given.filter((test) => !touched(test.file) && !setupFilesOf(test).some((file) => touched(file))); const relevance = unaskedRelevance(given, touched); const everything = runAllFile(context); if (everything !== undefined) return result({}, relevance, `${everything} changed, so the decision filter left nothing out`); @@ -173,9 +173,13 @@ async function judge(given: readonly TestFilterCandidate[], context: TestFilterC const unjudged = verdict.missed.length === 0 ? undefined : `${modelId} did not judge ${testsIn(verdict.missed)}: ${unjudgedBecause(failures, tooLarge)}`; return answered(verdict.exclude, { ...relevance, ...verdict.relevance }, [unasked, unjudged], spend); } -/** How likely each of `given` is to fail before the model says anything: `TOUCHED_RELEVANCE` for a test the change touches, `UNJUDGED_RELEVANCE` for the rest. */ +/** The setup files that save a test's session and its peers' sessions. */ +function setupFilesOf(test: TestFilterCandidate): readonly string[] { + return [...(test.setupFile === undefined ? [] : [test.setupFile]), ...(test.peerSetupFiles ?? [])]; +} +/** How likely each of `given` is to fail before the model says anything: `TOUCHED_RELEVANCE` for a test the change touches, itself or a setup of its session or its peers', `UNJUDGED_RELEVANCE` for the rest. */ function unaskedRelevance(given: readonly TestFilterCandidate[], touched: (file: string | undefined) => boolean): Record { - return Object.fromEntries(given.map((test) => [test.id, touched(test.file) || touched(test.setupFile) ? TOUCHED_RELEVANCE : UNJUDGED_RELEVANCE])); + return Object.fromEntries(given.map((test) => [test.id, touched(test.file) || setupFilesOf(test).some((file) => touched(file)) ? TOUCHED_RELEVANCE : UNJUDGED_RELEVANCE])); } /** * `error` with `relevance` on it, which the run reads off a filter that @@ -189,9 +193,9 @@ function withRelevance(error: unknown, relevance: Record): unkno } /** * The tests to leave out, each with its reason; how likely each test is to - * fail, the higher of the model's two answers, with a missing one counting as - * `UNJUDGED_RELEVANCE`; and the tests the model did not answer for, itself - * or its setup. + * fail, the highest of the model's answers for it and its setups, with a + * missing one counting as `UNJUDGED_RELEVANCE`; and the tests the model did + * not answer for, itself or one of its setups. */ function verdicts( tests: readonly TestFilterCandidate[], @@ -202,10 +206,12 @@ function verdicts( const missed: TestFilterCandidate[] = []; for (const test of tests) { const own = answers.tests.get(test.id); - const setup = test.setupFile === undefined ? 0 : answers.setups.get(test.setupFile); + const setupAnswers = setupFilesOf(test).map((file) => answers.setups.get(file)); + const setupsAnswered = setupAnswers.filter((answer) => answer !== undefined); + const setup = setupsAnswered.length === setupAnswers.length ? Math.max(0, ...setupsAnswered) : undefined; if (own === undefined || setup === undefined) missed.push(test); else if (Math.max(own, setup) < MIN_PROBABILITY) exclude[test.id] = `${Math.round(Math.max(own, setup) * 100)}% likely affected`; - relevance[test.id] = Math.max(own ?? UNJUDGED_RELEVANCE, setup ?? UNJUDGED_RELEVANCE); + relevance[test.id] = Math.max(own ?? UNJUDGED_RELEVANCE, ...setupAnswers.map((answer) => answer ?? UNJUDGED_RELEVANCE)); } return { exclude, relevance, missed }; } @@ -263,7 +269,7 @@ function touchedBy(context: TestFilterContext): (file: string | undefined) => bo */ async function subjects(tests: readonly TestFilterCandidate[], context: TestFilterContext): Promise { const { projectRoot, signal, redact } = context; - const setups = [...new Set(tests.flatMap((test) => (test.setupFile === undefined ? [] : [test.setupFile])))]; + const setups = [...new Set(tests.flatMap(setupFilesOf))]; const files = [...new Set([...tests.map((test) => test.file), ...setups])]; const read = await Promise.all(files.map((file) => readFile(path.join(projectRoot, file), { encoding: 'utf8', signal }))); const found = new Map(); diff --git a/packages/decision/tests/filter.test.ts b/packages/decision/tests/filter.test.ts index c25f6432ae..0e80b538f6 100644 --- a/packages/decision/tests/filter.test.ts +++ b/packages/decision/tests/filter.test.ts @@ -532,6 +532,58 @@ describe('decisionFilter', () => { expect(result.relevance).toEqual({ [ADDS.id]: 1, [SIGNS_IN.id]: 0.35, [scrolls.id]: 0.5 }); }); + it('treats the setup files that save a test peers sessions like its own setup file', async () => { + const PEERS = 'tests/peers.setup.e2e.ts'; + const base = { 'src/login.ts': 'export const ok = 1;\n', [CART]: "test('adds an item', async () => {});\n", [SEARCH]: "test('finds a product', async () => {});\n", [PEERS]: "setup('signs in ava', async () => {});\n" }; + const withPeers = { ...ADDS, peerSetupFiles: [PEERS] }; + + // A change to a peer setup keeps the test without asking. + const edited = changedRepo(base, { [PEERS]: "setup('signs in ava', async () => { /* edited */ });\n" }); + const untouched = scriptedJudge(() => 0); + expect(await decisionFilter({ model: untouched.model }).filter([withPeers, FINDS], filterContext(edited).context)).toEqual({ + exclude: { [FINDS.id]: '0% likely affected' }, + relevance: { [ADDS.id]: 1, [FINDS.id]: 0 }, + note: '1 test ran without asking: the test file, setup file, or stored screenshots changed; 1 call, 10 tokens', + }); + + // Otherwise the model is asked about the peer setup once, and the likelier answer decides. + const repo = changedRepo(base, { 'src/login.ts': 'export const ok = 2;\n' }); + const peersAsked = `Can the diff break the e2e setup in ${PEERS}, or the session it saves for the tests that use it? testFiles["${PEERS}"] is its file.`; + const likely = scriptedJudge((text) => (text === peersAsked ? 0.6 : 0.1)); + expect(await decisionFilter({ model: likely.model }).filter([withPeers, FINDS], filterContext(repo).context)).toEqual({ + exclude: { [FINDS.id]: '10% likely affected' }, + relevance: { [ADDS.id]: 0.6, [FINDS.id]: 0.1 }, + note: '1 call, 10 tokens', + }); + expect(Object.values(likely.requests[0]?.instructions ?? {}).filter((text) => text === peersAsked)).toHaveLength(1); + expect(Object.keys(sent(likely.requests[0]))).toEqual([CART, SEARCH, PEERS]); + const unlikely = scriptedJudge((text) => (text === peersAsked ? 0.1 : 0.05)); + expect(await decisionFilter({ model: unlikely.model }).filter([withPeers], filterContext(repo).context)).toMatchObject({ + exclude: { [ADDS.id]: '10% likely affected' }, + }); + + // With its own setup unlikely and a peer's likely, the peer's keeps the test. + const OWN = 'tests/auth.setup.e2e.ts'; + const both = changedRepo({ ...base, [OWN]: "setup('signs in', async () => {});\n" }, { 'src/login.ts': 'export const ok = 2;\n' }); + const ownAsked = `Can the diff break the e2e setup in ${OWN}, or the session it saves for the tests that use it? testFiles["${OWN}"] is its file.`; + const peerLikelier = scriptedJudge((text) => (text === peersAsked ? 0.6 : text === ownAsked ? 0.1 : 0.05)); + expect(await decisionFilter({ model: peerLikelier.model }).filter([{ ...withSetup(ADDS, OWN), peerSetupFiles: [PEERS] }], filterContext(both).context)).toEqual({ + exclude: {}, + relevance: { [ADDS.id]: 0.6 }, + note: '1 call, 10 tokens', + }); + + // When every call fails, the error still scores a test whose peer setup changed as one the change touches. + const failing = scriptedJudge( + () => 0, + () => { + throw new Error('Unauthorized: no AI Gateway key'); + }, + ); + const error = await rejection(decisionFilter({ model: failing.model }).filter([withPeers, FINDS], filterContext(changedRepo(base, { 'src/login.ts': 'export const ok = 2;\n', [PEERS]: "setup('signs in ava', async () => { /* edited */ });\n" })).context)); + expect(error).toMatchObject({ message: 'Unauthorized: no AI Gateway key', relevance: { [ADDS.id]: 1, [FINDS.id]: 0.5 } }); + }); + it('sends the provider options it is given with every call', async () => { const providerOptions = { gateway: { zeroDataRetention: true } }; const { model, requests } = scriptedJudge(() => 0.9); diff --git a/packages/e2e/schema/fixtures/report-v1.invalid.json b/packages/e2e/schema/fixtures/report-v1.invalid.json index c69d68b248..adb961348c 100644 --- a/packages/e2e/schema/fixtures/report-v1.invalid.json +++ b/packages/e2e/schema/fixtures/report-v1.invalid.json @@ -15,6 +15,7 @@ { "id": "no-file", "kind": "screenshot", + "user": "..", "mediaType": "image/png", "redaction": "complete", "producer": { diff --git a/packages/e2e/schema/fixtures/report-v1.valid.json b/packages/e2e/schema/fixtures/report-v1.valid.json index d697820ac0..532c9a67aa 100644 --- a/packages/e2e/schema/fixtures/report-v1.valid.json +++ b/packages/e2e/schema/fixtures/report-v1.valid.json @@ -284,6 +284,24 @@ "message": "semantic capture timed out", "retryable": false } + }, + { + "id": "018f0f5c-7b2a-7abc-8abc-0123456789ab:2", + "index": 2, + "kind": "locator", + "api": "locator.click", + "label": "getByRole('button', { name: 'Accept' })", + "user": "guest", + "source": { + "file": "tests/example.e2e.ts", + "line": 9, + "column": 3 + }, + "status": "passed", + "startedAt": "2026-07-24T12:00:01.000Z", + "durationMs": 300, + "events": [], + "artifacts": [] } ], "artifacts": [ @@ -310,6 +328,20 @@ "producer": { "kind": "attempt" } + }, + { + "id": "018f0f5c-7b2a-7abc-8abc-1123456789ab:artifact:2", + "kind": "video", + "mediaType": "video/webm", + "path": "web/tests_example.e2e.ts__opens_app/attempt-0/peers/guest/video/video.webm", + "size": 8, + "sha256": "2222222222222222222222222222222222222222222222222222222222222222", + "startedAt": "2026-07-24T12:00:00.000Z", + "redaction": "incomplete", + "user": "guest", + "producer": { + "kind": "attempt" + } } ], "secondaryErrors": [], @@ -317,6 +349,18 @@ "environment": { "browser": "chromium 141.0.7390.37" }, + "peers": { + "guest": { + "target": "web", + "environment": { + "browser": "chromium 141.0.7390.37" + }, + "failure": { + "url": "http://127.0.0.1:3000/invites", + "screen": "018f0f5c-7b2a-7abc-8abc-1123456789ab:artifact:2" + } + } + }, "failure": { "url": "http://127.0.0.1:3000/todos", "screen": "018f0f5c-7b2a-7abc-8abc-1123456789ab:artifact:0", @@ -349,6 +393,14 @@ "text": "POST /api/cart 500 Internal Server Error", "at": "2026-07-24T12:00:03.100Z", "step": 0 + }, + { + "source": "console", + "level": "warning", + "text": "invite link expires soon", + "at": "2026-07-24T12:00:01.200Z", + "step": 2, + "user": "guest" } ] } diff --git a/packages/e2e/schema/report-v1.schema.json b/packages/e2e/schema/report-v1.schema.json index c395a1fe41..b8eda3f542 100644 --- a/packages/e2e/schema/report-v1.schema.json +++ b/packages/e2e/schema/report-v1.schema.json @@ -28,6 +28,11 @@ "propertyNames": { "maxLength": 40 }, "additionalProperties": { "type": "string", "maxLength": 200 } }, + "user": { + "description": "A peer of the test, by the name its peers option gives it: the user whose app this came from. Absent for the test's own user.", + "type": "string", + "pattern": "^(?!\\.{1,2}$)[A-Za-z0-9_.-]{1,128}$" + }, "timestamp": { "type": "string", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}Z$", @@ -125,6 +130,7 @@ "ref": { "type": "string", "minLength": 1 }, "startedAt": { "$ref": "#/$defs/timestamp" }, "redaction": { "enum": ["complete", "incomplete"] }, + "user": { "$ref": "#/$defs/user" }, "producer": { "oneOf": [ { @@ -211,7 +217,8 @@ "level": { "enum": ["error", "warning", "info"] }, "text": { "type": "string", "maxLength": 300 }, "at": { "$ref": "#/$defs/timestamp" }, - "step": { "type": "integer", "minimum": 0 } + "step": { "type": "integer", "minimum": 0 }, + "user": { "$ref": "#/$defs/user" } } }, "stepMetrics": { @@ -345,6 +352,7 @@ "turns": { "type": "array", "maxItems": 32, "items": { "$ref": "#/$defs/turn" } }, "model": { "$ref": "#/$defs/model" }, "agent": { "type": "string", "minLength": 1 }, + "user": { "$ref": "#/$defs/user" }, "phase": { "enum": ["beforeEach", "afterEach"] }, "screen": { "$ref": "#/$defs/stepScreen" }, "error": { "$ref": "#/$defs/error" }, @@ -416,6 +424,21 @@ "secondaryErrors": { "type": "array", "items": { "$ref": "#/$defs/error" } }, "cleanup": { "enum": ["complete", "failed", "forced"] }, "environment": { "$ref": "#/$defs/environment" }, + "peers": { + "description": "The target each peer's app ran on, what the engine said it ran on, and what the runner saw on it when the failure landed, by peer name: the peers whose app opened, so absent when none did.", + "type": "object", + "propertyNames": { "$ref": "#/$defs/user" }, + "additionalProperties": { + "type": "object", + "additionalProperties": false, + "required": ["target"], + "properties": { + "target": { "type": "string", "minLength": 1 }, + "environment": { "$ref": "#/$defs/environment" }, + "failure": { "$ref": "#/$defs/failureEvidence" } + } + } + }, "extensions": { "$ref": "#/$defs/extensions" } }, "allOf": [ diff --git a/packages/e2e/src/agent/index.ts b/packages/e2e/src/agent/index.ts index edf95bbe83..b5138da93e 100644 --- a/packages/e2e/src/agent/index.ts +++ b/packages/e2e/src/agent/index.ts @@ -81,7 +81,8 @@ export function createAgentFixture(runtime: AgentContext): Agent { */ const visionHint = (): string | undefined => { if (!runtime.engineCapabilities.has('artifacts')) return undefined; - const steps = runtime.steps.completed(); + // The test's own user's recorder lists every user's steps; a peer's pixels prove nothing about this user's screen. + const steps = runtime.steps.completed().filter((step) => step.user === runtime.user); if (steps.some((step) => step.visionDegraded !== undefined)) return undefined; return steps.some((step) => step.visionInput === true) ? VISION_HINT : VISION_HINT_UNPROVEN; }; diff --git a/packages/e2e/src/agent/invocation.ts b/packages/e2e/src/agent/invocation.ts index c2e4a35bd3..2fd4434ccf 100644 --- a/packages/e2e/src/agent/invocation.ts +++ b/packages/e2e/src/agent/invocation.ts @@ -23,7 +23,7 @@ import type { StepMetrics, StepModelInfo, StepRecord, - StepRecorder, + StepSink, VisionDegradation, } from '../run/steps.ts'; import type { JsonValue, VisionMode } from '../types.ts'; @@ -86,7 +86,7 @@ export interface AgentContext { * engine says whether it produces pixels only once `observe` asks. */ readonly engineCapabilities: ReadonlySet; - readonly steps: StepRecorder; + readonly steps: StepSink; /** * The agent a call runs with: the one it names, else the test's pin, else * the run's. An unknown name is `INVALID_ARGUMENT`. @@ -108,6 +108,8 @@ export interface AgentContext { * its location, not the acting agent's account. */ readonly priorSteps: () => readonly StepRecord[]; + /** The peer whose agent this is; undefined for the test's own user. `steps` may hold every user's steps; this agent reads its own. */ + readonly user?: string | undefined; readonly secrets: SecretResolver; /** The attempt's live redactor (SecretLedger); sees values the moment they exist. */ readonly redact: (text: string) => string; diff --git a/packages/e2e/src/agent/phases.ts b/packages/e2e/src/agent/phases.ts index 7fb95fd8ec..7e94852e24 100644 --- a/packages/e2e/src/agent/phases.ts +++ b/packages/e2e/src/agent/phases.ts @@ -11,7 +11,7 @@ import { asEngineError, isE2EError } from '../internal/errors.ts'; import { timestamp } from '../internal/ids.ts'; import { POLL_INTERVAL_MS, sleep, type Deadline } from '../internal/time.ts'; import type { LocatorEngine } from '../locator/engine.ts'; -import type { StepActivity, StepEvent, StepRecorder } from '../run/steps.ts'; +import type { StepActivity, StepEvent, StepSink } from '../run/steps.ts'; import { AgentError, toAgentError } from './error.ts'; /** @@ -30,7 +30,7 @@ export function boundedOperation( /** Records one policy decision as a child event of the current step. */ export function recordPolicyEvent( - steps: StepRecorder, + steps: StepSink, name: string, decision: 'allowed' | 'denied', code?: string, @@ -48,7 +48,7 @@ export function recordPolicyEvent( /** The step recorder and optional debug trace a phase reports into. */ export interface PhaseHost { - readonly steps: StepRecorder; + readonly steps: StepSink; readonly debug?: DebugTrace | undefined; } diff --git a/packages/e2e/src/cache/context.ts b/packages/e2e/src/cache/context.ts index 3e626b6ff5..a2f9a8b227 100644 --- a/packages/e2e/src/cache/context.ts +++ b/packages/e2e/src/cache/context.ts @@ -22,6 +22,7 @@ import { traceCacheKeyHash, traceCallSignature, type CacheAgentIdentity, + type CachePeerIdentity, type CacheTargetIdentity, type TraceCacheKind, type TraceCallSignature, @@ -239,6 +240,8 @@ export function createAgentCacheContext(options: { readonly attemptIndex: number; /** The file store's listing under `cache.strict`, shared by the attempts of one worker and target (`storedRecordingsFor`). */ readonly recordings?: StoredRecordings | undefined; + /** The peer whose steps this context keys, with the target and agent of the test that brought it; absent for the test's own user, whose keys stay as they were. */ + readonly user?: CachePeerIdentity | undefined; }): AgentCacheContext | undefined { if (options.cache.mode === 'off') return undefined; const strict = options.cache.strict !== false; @@ -283,6 +286,7 @@ export function createAgentCacheContext(options: { callIndex, agent, policyVersion: REPLAY_POLICY_VERSION, + user: options.user, }); return { keyHash: traceCacheKeyHash(key), @@ -294,6 +298,7 @@ export function createAgentCacheContext(options: { paramsDigest: signature.paramsDigest, callIndex, agent: agent.name, + ...(options.user === undefined ? {} : { user: options.user.name, ownerTargetId: options.user.ownerTargetId, ownerAgent: options.user.ownerAgent }), }, }; }, diff --git a/packages/e2e/src/cache/identity.ts b/packages/e2e/src/cache/identity.ts index 9ac8c8df6e..f15fb44988 100644 --- a/packages/e2e/src/cache/identity.ts +++ b/packages/e2e/src/cache/identity.ts @@ -59,6 +59,19 @@ export interface TraceCacheKey { /** SHA-256 of the agent's redacted context (its `context` then the test's `agentContext`), or of the empty string. */ readonly agentContextDigest: string; readonly policyVersion: string; + /** The peer the step ran as, by name; absent for the test's own user, whose keys stay as they were. */ + readonly user?: string; + /** The target of the test that brought the peer, as `targetId` names one; set with `user`, so two pairs of one test key their peer's steps apart. */ + readonly ownerTargetId?: string; + /** The configured agent the test that brought the peer runs as; set with `user`. */ + readonly ownerAgent?: string; +} + +/** The peer a step runs on, as the key sees it: its name, and the target and agent of the test that brought it. */ +export interface CachePeerIdentity { + readonly name: string; + readonly ownerTargetId: string; + readonly ownerAgent: string; } /** The agent a step runs with, as the key sees it. */ @@ -170,6 +183,7 @@ export function buildTraceCacheKey(parts: { readonly callIndex: number; readonly agent: CacheAgentIdentity; readonly policyVersion: string; + readonly user?: CachePeerIdentity | undefined; }): TraceCacheKey { return { specVersion: '0.1', @@ -188,6 +202,7 @@ export function buildTraceCacheKey(parts: { agent: parts.agent.name, agentContextDigest: sha256Hex(parts.agent.context ?? ''), policyVersion: parts.policyVersion, + ...(parts.user === undefined ? {} : { user: parts.user.name, ownerTargetId: parts.user.ownerTargetId, ownerAgent: parts.user.ownerAgent }), }; } diff --git a/packages/e2e/src/cache/recorder.ts b/packages/e2e/src/cache/recorder.ts index 9246ce5f6f..c30551a8d5 100644 --- a/packages/e2e/src/cache/recorder.ts +++ b/packages/e2e/src/cache/recorder.ts @@ -349,5 +349,8 @@ export function recordedProvenance(provenance: TraceProvenance, redact: (text: s ...(provenance.paramsDigest === undefined ? {} : { paramsDigest: provenance.paramsDigest }), ...(provenance.callIndex === undefined ? {} : { callIndex: provenance.callIndex }), ...(provenance.agent === undefined ? {} : { agent: bound(redact(provenance.agent), MAX_TRACE_DESCRIPTOR_CHARS) }), + ...(provenance.user === undefined ? {} : { user: bound(redact(provenance.user), MAX_TRACE_DESCRIPTOR_CHARS) }), + ...(provenance.ownerTargetId === undefined ? {} : { ownerTargetId: bound(redact(provenance.ownerTargetId), MAX_TRACE_DESCRIPTOR_CHARS) }), + ...(provenance.ownerAgent === undefined ? {} : { ownerAgent: bound(redact(provenance.ownerAgent), MAX_TRACE_DESCRIPTOR_CHARS) }), }; } diff --git a/packages/e2e/src/cache/rekeyed.ts b/packages/e2e/src/cache/rekeyed.ts index 3b966e7d31..0ec069deaa 100644 --- a/packages/e2e/src/cache/rekeyed.ts +++ b/packages/e2e/src/cache/rekeyed.ts @@ -87,7 +87,13 @@ export function storedRecordingsFor(cache: ResolvedCacheConfig): StoredRecording /** The whole step as one map key, or undefined when the provenance does not record all of it. */ function stepKey(step: TraceProvenance): string | undefined { - const { testId, targetId, instructionDigest, paramsDigest, callIndex, agent } = step; + const { testId, targetId, instructionDigest, paramsDigest, callIndex, agent, user, ownerTargetId, ownerAgent } = step; if (paramsDigest === undefined || callIndex === undefined || agent === undefined) return undefined; - return JSON.stringify([testId, targetId, instructionDigest, paramsDigest, callIndex, agent]); + // A peer's step is its own, in its own pair of the test: neither the test's user's recording of the same step, + // nor the peer's in a pair on another target or as another agent, stands in for it. + return JSON.stringify( + user === undefined + ? [testId, targetId, instructionDigest, paramsDigest, callIndex, agent] + : [testId, targetId, instructionDigest, paramsDigest, callIndex, agent, user, ownerTargetId, ownerAgent], + ); } diff --git a/packages/e2e/src/cache/trace-read.ts b/packages/e2e/src/cache/trace-read.ts index 96986d2201..fd8fcea48b 100644 --- a/packages/e2e/src/cache/trace-read.ts +++ b/packages/e2e/src/cache/trace-read.ts @@ -426,6 +426,12 @@ function readProvenance(document: unknown): TraceProvenance | undefined { } const agent = raw['agent'] === undefined ? undefined : readBoundedText(raw['agent'], MAX_TRACE_DESCRIPTOR_CHARS); if (raw['agent'] !== undefined && agent === undefined) return undefined; + const user = raw['user'] === undefined ? undefined : readBoundedText(raw['user'], MAX_TRACE_DESCRIPTOR_CHARS); + if (raw['user'] !== undefined && user === undefined) return undefined; + const ownerTargetId = raw['ownerTargetId'] === undefined ? undefined : readBoundedText(raw['ownerTargetId'], MAX_TRACE_DESCRIPTOR_CHARS); + if (raw['ownerTargetId'] !== undefined && ownerTargetId === undefined) return undefined; + const ownerAgent = raw['ownerAgent'] === undefined ? undefined : readBoundedText(raw['ownerAgent'], MAX_TRACE_DESCRIPTOR_CHARS); + if (raw['ownerAgent'] !== undefined && ownerAgent === undefined) return undefined; return { testId, targetId, @@ -433,6 +439,9 @@ function readProvenance(document: unknown): TraceProvenance | undefined { ...(paramsDigest === undefined ? {} : { paramsDigest }), ...(callIndex === undefined ? {} : { callIndex }), ...(agent === undefined ? {} : { agent }), + ...(user === undefined ? {} : { user }), + ...(ownerTargetId === undefined ? {} : { ownerTargetId }), + ...(ownerAgent === undefined ? {} : { ownerAgent }), }; } diff --git a/packages/e2e/src/cache/trace.ts b/packages/e2e/src/cache/trace.ts index 4a142a52a0..2a7b2505e5 100644 --- a/packages/e2e/src/cache/trace.ts +++ b/packages/e2e/src/cache/trace.ts @@ -105,6 +105,12 @@ export interface TraceProvenance { readonly callIndex?: number; /** Name of the configured agent the step ran with. */ readonly agent?: string; + /** The peer the step ran as, by name; absent for the test's own user. */ + readonly user?: string; + /** The target of the test that brought the peer; set with `user`. */ + readonly ownerTargetId?: string; + /** The configured agent the test that brought the peer runs as; set with `user`. */ + readonly ownerAgent?: string; } /** diff --git a/packages/e2e/src/collect/registry.ts b/packages/e2e/src/collect/registry.ts index c6e8f44bc3..bf78ac47d4 100644 --- a/packages/e2e/src/collect/registry.ts +++ b/packages/e2e/src/collect/registry.ts @@ -17,6 +17,7 @@ import type { SourceLocation } from '../internal/source.ts'; import type { DescribeOptions, FixtureFn, + PeerOptions, SetupFn, SetupOptions, SuiteHookFn, @@ -171,6 +172,11 @@ class Collector { } } validateTestOptions(options, this.currentGroup, kind); + if (fixtures.some((fixture) => fixture.name === 'peers') && declaresPeers(options, this.currentGroup)) { + throw new CollectionError( + `test "${normalizedTitle}" declares peers, but its test.extend() chain defines a fixture named "peers"; rename that fixture to give the test its peers`, + ); + } const titlePath = [...groupTitles(this.currentGroup), normalizedTitle]; const registered: RegisteredTest = { kind, @@ -274,6 +280,7 @@ const TEST_OPTION_KEYS: readonly string[] = Object.keys({ platforms: true, requires: true, session: true, + peers: true, agentContext: true, agent: true, trace: true, @@ -302,6 +309,7 @@ const DESCRIBE_OPTION_KEYS: readonly string[] = Object.keys({ platforms: true, requires: true, session: true, + peers: true, agentContext: true, agent: true, trace: true, @@ -332,6 +340,7 @@ function validateCommonOptions(options: TestOptions | DescribeOptions, label: st } if (options.agent !== undefined) validateAgentOption(options.agent, label); if (options.tags !== undefined) validateTagsOption(options.tags, label); + if (options.peers !== undefined) validatePeersOption(options.peers, label); for (const kind of ['trace', 'video'] as const) { const mode = options[kind]; if (mode !== undefined && !isRecordingMode(mode)) { @@ -378,6 +387,63 @@ function isTagName(tag: unknown): tag is string { return typeof tag === 'string' && tag !== '' && tag.trim() === tag && !tag.includes(','); } +/** The keys one peer takes. */ +const PEER_OPTION_KEYS: readonly string[] = Object.keys({ + target: true, + session: true, + agent: true, + agentContext: true, +} satisfies Record); + +/** + * `peers` maps names to one peer each. Names follow the session-name rule, + * since they label a user in paths and reports; every field is a non-empty + * string, and a peer's `session` follows the session-name rule too. An + * empty map is allowed: an inner layer clears the peers of an outer one. + */ +function validatePeersOption(peers: unknown, label: string): void { + if (typeof peers !== 'object' || peers === null || Array.isArray(peers)) { + throw new CollectionError( + `${label}: peers must map peer names to their options, e.g. peers: { ava: { session: 'ava' } }, got ${describeValue(peers)}`, + ); + } + // A peer's files go in a folder named after it, so a name must be one folder of its own. + const folded = new Map(); + for (const [name, peer] of Object.entries(peers)) { + if (!SESSION_NAME_PATTERN.test(name) || name === '.' || name === '..') { + throw new CollectionError( + `${label}: invalid peer name ${JSON.stringify(name)}: names are 1 through 128 ASCII letters, numbers, "_", "-", or ".", and not "." or ".."`, + ); + } + const same = folded.get(name.toLowerCase()); + if (same !== undefined) { + throw new CollectionError( + `${label}: peer names ${JSON.stringify(same)} and ${JSON.stringify(name)} differ only in case; each peer's files go in a folder named after it, which a case-insensitive disk would share`, + ); + } + folded.set(name.toLowerCase(), name); + const where = `${label}: peer "${name}"`; + if (typeof peer !== 'object' || peer === null || Array.isArray(peer)) { + throw new CollectionError(`${where} must be an object of target, session, agent, and agentContext, got ${describeValue(peer)}`); + } + const unknown = unknownKeyMessage(where, peer, PEER_OPTION_KEYS); + if (unknown !== undefined) throw new CollectionError(unknown); + for (const key of PEER_OPTION_KEYS) { + const value: unknown = (peer as Record)[key]; + if (value === undefined) continue; + if (typeof value !== 'string' || value === '') { + throw new CollectionError(`${where}: ${key} must be a non-empty string, got ${describeValue(value)}`); + } + } + const { session } = peer as PeerOptions; + if (session !== undefined && !SESSION_NAME_PATTERN.test(session)) { + throw new CollectionError( + `${where}: invalid session name ${JSON.stringify(session)}: names are 1 through 128 ASCII letters, numbers, "_", "-", or "."`, + ); + } + } +} + /** `agent` names one configured agent, or lists several distinct ones to run the test once each. */ function validateAgentOption(agent: unknown, label: string): void { if (typeof agent === 'string') { @@ -403,6 +469,19 @@ function insideSerial(group: GroupNode | undefined): boolean { return outermostSerialGroup(group) !== undefined; } +/** Whether a test with `options` in `group` has peers: its own, else the ones a group around it sets. */ +function declaresPeers(options: TestOptions, group: GroupNode | undefined): boolean { + return options.peers === undefined ? groupWithPeers(group) !== undefined : Object.keys(options.peers).length > 0; +} + +/** The innermost group around `group` that sets peers its tests would take: none when the nearest one that sets them clears them. */ +function groupWithPeers(group: GroupNode | undefined): GroupNode | undefined { + for (let current = group; current !== undefined; current = current.parent) { + if (current.options.peers !== undefined) return Object.keys(current.options.peers).length > 0 ? current : undefined; + } + return undefined; +} + function validateTestOptions(options: TestOptions, group: GroupNode | undefined, kind: 'test' | 'setup'): void { if (kind === 'setup') validateCommonOptions(options, 'setup options', SETUP_OPTION_KEYS); else validateCommonOptions(options, 'test options', TEST_OPTION_KEYS); @@ -416,6 +495,7 @@ function validateTestOptions(options: TestOptions, group: GroupNode | undefined, 'trace', 'video', 'session', + 'peers', 'platforms', 'requires', 'skip', @@ -437,6 +517,14 @@ function validateDescribeOptions(options: DescribeOptions, parent: GroupNode | u if (options.serial === true && insideSerial(parent)) { throw new CollectionError('nested serial groups are collection errors'); } + // A serial group runs as one unit on one shared app; a second user's app is not part of it yet. + if (options.peers !== undefined && (options.serial === true || insideSerial(parent))) { + throw new CollectionError('describe option "peers" cannot be set on or inside a serial group; a serial group runs on one shared app'); + } + const peersAround = options.serial === true ? groupWithPeers(parent) : undefined; + if (peersAround !== undefined) { + throw new CollectionError(`describe option "serial" cannot be set inside a group with peers ("${peersAround.title}"); a serial group runs on one shared app`); + } // The serial group records as one unit, so a describe inside it cannot choose its own recordings. for (const kind of ['trace', 'video'] as const) { if (options[kind] !== undefined && insideSerial(parent)) { @@ -568,7 +656,11 @@ function normalizeArgs( return { options: optionsOrFn, fn: maybeFn }; } -/** Fixtures every attempt has without any engine or `test.extend()` defining them. */ +/** + * Fixtures every attempt has without any engine or `test.extend()` defining + * them. `peers` is one too, but a suite may still define its own, as it could + * before e2e had peers: only a test that declares peers through it is refused. + */ const CORE_FIXTURE_NAMES: ReadonlySet = new Set(['agent', 'app', 'screen', 'platform', 'session']); /** diff --git a/packages/e2e/src/collect/select.ts b/packages/e2e/src/collect/select.ts index 2113047834..ac67881857 100644 --- a/packages/e2e/src/collect/select.ts +++ b/packages/e2e/src/collect/select.ts @@ -10,6 +10,23 @@ import { attemptKeep, attemptVideo, type AttemptRecordings, type RecordingKind, import type { Capability, RecordingMode, TestOptions } from '../types.ts'; import { excludingEntry, type Collection, type CollectedTest, type UncollectedFile } from './collect.ts'; import { groupChain } from './registry.ts'; +import { isServedEngine } from '../engine/protocol/client.ts'; + +/** One more user a test declares, as written: its target defaults per pair (`peerTarget`). */ +export interface ResolvedPeer { + readonly name: string; + /** The target the peer's app runs on; undefined runs it on the pair's own target. */ + readonly target: string | undefined; + readonly session: string | undefined; + /** The configured agent the peer runs as; undefined runs it as the pair's agent. */ + readonly agent: string | undefined; + readonly agentContext: string | undefined; +} + +/** The name of the target a peer of `pair` runs on. */ +export function peerTarget(peer: ResolvedPeer, pair: Pick): string { + return peer.target ?? pair.target.name; +} export interface ResolvedTestOptions { readonly timeout: number; @@ -17,6 +34,8 @@ export interface ResolvedTestOptions { readonly platforms: readonly string[] | undefined; readonly requires: readonly Capability[]; readonly session: string | undefined; + /** The test's peers in declaration order, the innermost layer's map as a whole; empty when it has none. */ + readonly peers: readonly ResolvedPeer[]; readonly agentContext: string | undefined; /** * The configured agents the test runs as, one pair (and one result) each, @@ -166,6 +185,7 @@ export function resolveOptions(test: CollectedTest, config: ResolvedConfig): Res let platforms: readonly string[] | undefined; let requires: readonly Capability[] = []; let session: string | undefined; + let peers: TestOptions['peers']; let pin: readonly string[] | undefined; let skipReason: string | undefined; let trace: TestOptions['trace']; @@ -180,6 +200,7 @@ export function resolveOptions(test: CollectedTest, config: ResolvedConfig): Res if (layer.platforms !== undefined) platforms = layer.platforms; if (layer.requires !== undefined) requires = layer.requires; if (layer.session !== undefined) session = layer.session; + if (layer.peers !== undefined) peers = layer.peers; if (layer.agent !== undefined) pin = typeof layer.agent === 'string' ? [layer.agent] : layer.agent; if (layer.agentContext !== undefined) agentContextParts.push(layer.agentContext); if (layer.skip !== undefined && layer.skip !== false) { @@ -220,6 +241,7 @@ export function resolveOptions(test: CollectedTest, config: ResolvedConfig): Res platforms, requires, session, + peers: resolvePeers(test, peers, config), agents: effectiveAgents(test, pin, config.agentNames), agentContext: agentContextParts.length === 0 ? undefined : agentContextParts.join('\n'), skipReason: skipReason === undefined ? undefined : truncateUtf8(sanitizeText(staticSecretLedger(config.allSecrets).redact(skipReason)), 8192), @@ -230,6 +252,32 @@ export function resolveOptions(test: CollectedTest, config: ResolvedConfig): Res }; } +/** + * A test's peers with the facts the config settles checked here, before any + * process starts: the target and agent each names exist. Whether the target + * is selected and its login saved is decided per pair at selection. + */ +function resolvePeers(test: CollectedTest, peers: TestOptions['peers'], config: ResolvedConfig): readonly ResolvedPeer[] { + const targetNames = config.targets.map((target) => target.name); + const agentNames = [...config.agents.keys()]; + const named = `test "${test.titlePath.join(' > ')}" in ${test.file}`; + return Object.freeze( + Object.entries(peers ?? {}).map(([name, peer]) => { + if (peer.target !== undefined && !targetNames.includes(peer.target)) { + throw new CollectionError( + `${named} runs peer "${name}" on target "${peer.target}", which the config does not declare; targets: ${targetNames.map((each) => `"${each}"`).join(', ')}${didYouMean(peer.target, targetNames)}`, + ); + } + if (peer.agent !== undefined && !config.agents.has(peer.agent)) { + throw new CollectionError( + `${named} runs peer "${name}" as agent "${peer.agent}", which agents does not define; configured: ${agentNames.join(', ')}${didYouMean(peer.agent, agentNames)}`, + ); + } + return Object.freeze({ name, target: peer.target, session: peer.session, agent: peer.agent, agentContext: peer.agentContext }); + }), + ); +} + /** * Which attempts of a pair record `kind`, and where the mode came from: the * test's own, else its target's (which the flag and the config already @@ -353,7 +401,12 @@ export function select( collection: Collection, config: ResolvedConfig, filters: SelectionFilters = {}, - flags: { passWithNoTests?: boolean; noTestsHint?: string } = {}, + flags: { + passWithNoTests?: boolean; + noTestsHint?: string; + /** The caller refuses every test with peers itself (an MCP session drives one app), so selection leaves their targets and sessions unchecked. */ + peersRefused?: boolean; + } = {}, ): Selection { const tagMode = filters.tagMode ?? 'any'; const targets = selectTargets(config.targets, filters.targetIds); @@ -401,7 +454,7 @@ export function select( // shard machines agree on the cut whatever a filter answers. const withExclusions = filters.excluded === undefined ? withShard : applySerialClosure(applyExclusions(withShard, filters.excluded)); - const withSessions = applySessionSelection(withExclusions, sessionProducers, collection.uncollected); + const withSessions = applySessionSelection(withExclusions, sessionProducers, collection.uncollected, targets, flags.peersRefused === true); const runnableOrdinary = withSessions.filter( (pair) => pair.disposition === 'run' && pair.test.kind === 'test', @@ -637,9 +690,16 @@ function withSetupConsumers( for (const target of targets) { for (const test of tests) { const options = optionsByTest.get(test.id)!; - const producer = options.session === undefined ? undefined : sessionProducers.get(options.session); - if (producer === undefined) continue; - const rerun = optionsByTest.get(producer.id)!.agents.some((agent) => lastFailed.has(resultId(producer.id, target.name, agent))); + // Its own login on this target, then each peer's on the peer's target. + const logins = [ + { session: options.session, target: target.name }, + ...options.peers.map((peer) => ({ session: peer.session, target: peer.target ?? target.name })), + ]; + const rerun = logins.some(({ session, target: producedOn }) => { + const producer = session === undefined ? undefined : sessionProducers.get(session); + if (producer === undefined) return false; + return optionsByTest.get(producer.id)!.agents.some((agent) => lastFailed.has(resultId(producer.id, producedOn, agent))); + }); if (rerun) for (const agent of options.agents) widened.add(resultId(test.id, target.name, agent)); } } @@ -850,12 +910,13 @@ function applySessionSelection( pairs: readonly TestTargetPair[], sessionProducers: ReadonlyMap, uncollected: readonly UncollectedFile[], + targets: readonly ResolvedTarget[], + peersRefused: boolean, ): TestTargetPair[] { /** Each needed setup, by target and producer, with the sessions a selected test consumes from it. */ const neededSetups = new Map>(); - for (const pair of pairs) { - if (pair.disposition !== 'run' || pair.options.session === undefined) continue; - const producer = sessionProducers.get(pair.options.session); + const need = (pair: TestTargetPair, session: string, targetName: string, peer: string | undefined): void => { + const producer = sessionProducers.get(session); if (producer === undefined) { // The setup may be in a file a narrowed run could not collect; its error is then the cause. const cause = @@ -866,15 +927,57 @@ function applySessionSelection( const known = declared.length === 0 ? '; no collected setup test declares a session' - : `; setup tests declare ${declared.map((name) => `"${name}"`).join(', ')}${didYouMean(pair.options.session, declared)}`; + : `; setup tests declare ${declared.map((name) => `"${name}"`).join(', ')}${didYouMean(session, declared)}`; + const consumer = peer === undefined ? '' : ` for peer "${peer}"`; throw new CollectionError( - `test "${pair.test.titlePath.join(' > ')}" in ${pair.test.file} consumes session "${pair.options.session}" but no setup test produces it${known}${cause}`, + `test "${pair.test.titlePath.join(' > ')}" in ${pair.test.file} consumes session "${session}"${consumer} but no setup test produces it${known}${cause}`, ); } - const key = `${pair.target.name}::${producer.id}`; + const key = `${targetName}::${producer.id}`; const sessions = neededSetups.get(key) ?? new Set(); - sessions.add(pair.options.session); + sessions.add(session); neededSetups.set(key, sessions); + }; + const selected = new Map(targets.map((target) => [target.name, target])); + for (const pair of pairs) { + if (pair.disposition !== 'run') continue; + if (pair.options.session !== undefined) need(pair, pair.options.session, pair.target.name, undefined); + // A caller that refuses tests with peers says why itself: a target or setup they need is not its concern. + if (peersRefused) continue; + // An engine may contribute its own fixture named `peers`, as it could before e2e had them; it would hide the test's. + const engine = pair.target.engine; + if (pair.options.peers.length > 0 && engine?.capabilities.has('peers') === true) { + throw new CollectionError( + `test "${pair.test.titlePath.join(' > ')}" in ${pair.test.file} declares peers, but target "${pair.target.name}" runs on engine ${engine.name}, which contributes a fixture named "peers"; the peers option needs that name`, + ); + } + for (const peer of pair.options.peers) { + const targetName = peerTarget(peer, pair); + const named = `test "${pair.test.titlePath.join(' > ')}" in ${pair.test.file}`; + const target = selected.get(targetName); + // A peer's app runs on its target's engine, so the run must hold that + // target: a --target that leaves it out is an error, not a silent skip. + if (target === undefined) { + throw new CollectionError( + `${named} runs peer "${peer.name}" on target "${targetName}", which this run does not select; add --target ${targetName}`, + ); + } + // A peer's engine comes from a second load of the config in the + // worker; a target served by an engine server gets one more connection + // to the same server, which this version does not open for a peer. + if (target.engine !== undefined && isServedEngine(target.engine)) { + throw new CollectionError( + `${named} runs peer "${peer.name}" on target "${targetName}", whose engine runs in an engine server (connectEngine); a peer runs on an engine in the worker's own process only, so give the peer a target whose engine the config creates`, + ); + } + if (peer.session === undefined) continue; + if (target.engine !== undefined && !target.engine.capabilities.has('state')) { + throw new CollectionError( + `${named} restores session "${peer.session}" into peer "${peer.name}", but target "${targetName}" cannot save or restore a session: engine ${target.engine.name}, as configured, has no state capability; sign the peer in during the test instead`, + ); + } + need(pair, peer.session, targetName, peer.name); + } } return pairs.map((pair) => { if (pair.test.kind !== 'setup') return pair; diff --git a/packages/e2e/src/engine/index.ts b/packages/e2e/src/engine/index.ts index 2e9a94f5b2..a2e3690221 100644 --- a/packages/e2e/src/engine/index.ts +++ b/packages/e2e/src/engine/index.ts @@ -387,12 +387,17 @@ export interface EngineSession { /** * What `prepare` learned that the run must honour. `workers` replaces the - * engine's declared cap for this target and run: the surfaces the engine - * actually provisioned, `1` to `info.slots`. Declared `workers` stays the - * static answer for engines that know it up front. + * engine's declared cap for this target and run: how many of `info.slots` + * the engine serves at once, the surfaces it actually provisioned, `1` to + * `info.slots`. Declared `workers` stays the static answer for engines that + * know it up front. */ export interface EnginePrepareResult { - /** Lowers the target's worker cap for this run, `1` to `info.slots`. */ + /** + * How many slots the engine serves at once for this run, `1` to + * `info.slots`: its own workers' and the peers' (`info.peerSlots`) together, + * not its own workers alone. The run fits its worker counts to it. + */ readonly workers?: number; /** * Variables every worker of this target is spawned with, on top of the @@ -417,14 +422,26 @@ export interface EnginePrepareInfo { /** The app the target declares, as `init` receives it: what a device installs or warms up here. */ readonly app: EngineAppInfo; /** - * The worker slots the run will start for this target, `0` to `slots - 1`: - * the run's worker cap, the engine's declared `workers`, and the work units - * selected for the target, whichever is smallest; `0` when nothing runs on - * it while another target has work. A run with nothing to run prepares no + * The slots the run may use on this target, `0` to `slots - 1`: one per + * worker it plans for the target (the run's worker cap, the engine's + * declared `workers`, and the work units selected for the target, whichever + * is smallest), and one per peer (`peerSlots`); `0` when nothing runs on it + * while another target has work. A run with nothing to run prepares no * target. Provision for exactly these slots (boot that many devices of a - * pool); `init` then finds them ready. + * pool); `init` then finds them ready. Treat the slots alike: which one a + * worker or a peer gets is settled after `prepare`, once the run fits its + * workers to what the engine serves. */ readonly slots: number; + /** + * How many of `slots` the run sets aside for peers: a test's other users + * (its `peers` option), each on an engine instance of its own inside the + * worker that runs the test, on a slot no worker of this target holds. A + * count, not a range: see `slots`. Absent in a run that puts no peer on + * the target. An engine that cannot serve a peer refuses here, before it + * acquires anything. + */ + readonly peerSlots?: number; /** * The run's environment: what every worker is started with. A host may hand * the run an environment other than the runner process's own, so anything @@ -521,7 +538,14 @@ export interface EngineInitInfo { * This worker's 0-based slot among the target's workers: the lowest slot * free when the worker was spawned, so a replacement worker takes over the * slot of the one that exited. An engine with several devices hands each - * slot its own; `config.workers` bounds the slots a target can reach. + * slot its own. A target's own workers take the lowest slots, as many as + * the run starts for it; an instance that runs a peer of a worker's test + * gets a slot after them that no worker and no other peer holds. When the + * run starts fewer workers than `prepare` was told, the peers' slots start + * lower too. So a slot can reach past `config.workers`, up to + * `EnginePrepareInfo.slots - 1`. A peer's instance lives in the same worker + * process as the test's own: state an engine package keeps at module level + * is shared between them. */ readonly workerSlot: number; /** Aborts on interrupt and when init exceeds the launch timeout; init must stop promptly. */ @@ -874,9 +898,10 @@ export interface Engine { * of a run's duration. A run with nothing to run (the test filters left * nothing, or `--pass-with-no-tests` on an empty selection) prepares no * target, and so calls no `finish`. Failure is infrastructure and ends the - * run before any test executes. The result may lower the target's worker - * cap for this run, for an engine that only learns its capacity here (a - * device pool discovered from the booted devices). + * run before any test executes. The result may say the engine serves fewer + * of the slots asked for at once, for an engine that only learns its + * capacity here (a device pool discovered from the booted devices); the run + * then starts fewer workers. */ prepare?(info: EnginePrepareInfo): Promise; /** diff --git a/packages/e2e/src/engine/protocol/client.ts b/packages/e2e/src/engine/protocol/client.ts index 6ae9073f5e..def05bbe37 100644 --- a/packages/e2e/src/engine/protocol/client.ts +++ b/packages/e2e/src/engine/protocol/client.ts @@ -158,6 +158,13 @@ function isEngineClient(engine: EngineHandle): engine is EngineClientHandle { /** The client each in-process engine is served through, so every config load gets the same one. */ const loopbacks = new WeakMap(); +/** The clients in `loopbacks`: every other client speaks to an engine server. */ +const loopbackClients = new WeakSet(); + +/** Whether the harness reaches this engine in an engine server (`connectEngine`), not in this process. */ +export function isServedEngine(engine: EngineHandle): boolean { + return isEngineClient(engine) && !loopbackClients.has(engine); +} /** * The engine as the harness drives it: over the protocol. A `connectEngine` @@ -184,6 +191,7 @@ export function protocolEngine(engine: EngineHandle): EngineClientHandle { if (!isEngineClient(connected)) throw new Error('connectEngine returned a handle it did not make'); client = connected; loopbacks.set(engine, client); + loopbackClients.add(client); } return client; } diff --git a/packages/e2e/src/internal/ai-trace.ts b/packages/e2e/src/internal/ai-trace.ts index c6ab86d98e..7ff88d22cb 100644 --- a/packages/e2e/src/internal/ai-trace.ts +++ b/packages/e2e/src/internal/ai-trace.ts @@ -72,6 +72,19 @@ export interface AiTraceScope { readonly attempt: number; readonly api?: string; readonly label?: string; + /** The peer whose step made the call; absent for the test's own user. */ + readonly user?: string; + /** The configured agent that peer runs as, beside `agent`, which stays the attempt's; set with `user`. */ + readonly userAgent?: string; + /** The target that peer's app runs on, beside `target`, which stays the attempt's; set with `user`. */ + readonly userTarget?: string; +} + +/** The peer a step runs on, as its model calls are attributed: its name, the agent it runs as, and its app's target. */ +export interface AiTraceUser { + readonly name: string; + readonly agent: string; + readonly target: string; } const scopeStorage = new AsyncLocalStorage(); @@ -85,10 +98,10 @@ export function withAiTraceScope(scope: AiTraceScope, work: () => Promise) * Narrows the current attempt scope to one public API step. Outside an * attempt scope there is nothing to narrow, and the work runs as is. */ -export function withAiTraceStep(api: string, label: string, work: () => Promise): Promise { +export function withAiTraceStep(api: string, label: string, work: () => Promise, user?: AiTraceUser): Promise { const parent = scopeStorage.getStore(); if (parent === undefined) return work(); - return scopeStorage.run({ ...parent, api, label }, work); + return scopeStorage.run({ ...parent, api, label, ...(user === undefined ? {} : { user: user.name, userAgent: user.agent, userTarget: user.target }) }, work); } /** The scope of the calling async context, when inside an attempt. */ @@ -514,6 +527,9 @@ function redactScope(scope: AiTraceScope | undefined, redact: (text: string) => agent: redact(scope.agent), ...(scope.api === undefined ? {} : { api: redact(scope.api) }), ...(scope.label === undefined ? {} : { label: redact(scope.label) }), + ...(scope.user === undefined ? {} : { user: redact(scope.user) }), + ...(scope.userAgent === undefined ? {} : { userAgent: redact(scope.userAgent) }), + ...(scope.userTarget === undefined ? {} : { userTarget: redact(scope.userTarget) }), }; } @@ -523,6 +539,8 @@ function runName(scope: AiTraceScope | undefined, functionId: string | undefined // A test run as several agents is several runs; the name tells them apart. if (scope.agent !== 'default') parts.push(`as ${scope.agent}`); if (scope.attempt > 0) parts.push(`attempt ${scope.attempt + 1}`); + // Each user's model calls are their own runs: the name says whose step it was, and the agent that peer runs as when it is not the test's. + if (scope.user !== undefined) parts.push(scope.userAgent === scope.agent ? `peer ${scope.user}` : `peer ${scope.user} as ${scope.userAgent}`); if (scope.api !== undefined) { const label = scope.label === undefined || scope.label === '' ? '' : ` ${JSON.stringify(truncate(scope.label))}`; diff --git a/packages/e2e/src/locator/screen.ts b/packages/e2e/src/locator/screen.ts index e96581f278..6b335c0576 100644 --- a/packages/e2e/src/locator/screen.ts +++ b/packages/e2e/src/locator/screen.ts @@ -34,7 +34,7 @@ import type { TextMatch, TextMatchOptions, } from '../types.ts'; -import type { StepRecorder } from '../run/steps.ts'; +import type { StepSink } from '../run/steps.ts'; import { attributeOf, denySecureRead, isNodeVisible, locatorDetails, type LocatorEngine } from './engine.ts'; import { describeExpression, @@ -58,7 +58,7 @@ export interface SecretResolver { export interface ScreenContext { readonly engine: LocatorEngine; - readonly steps: StepRecorder; + readonly steps: StepSink; readonly secrets: SecretResolver; /** Base directory for resolving relative file paths, e.g. uploads. */ readonly projectRoot?: string; diff --git a/packages/e2e/src/report/build.ts b/packages/e2e/src/report/build.ts index 4a8ec66515..397b64f8da 100644 --- a/packages/e2e/src/report/build.ts +++ b/packages/e2e/src/report/build.ts @@ -20,6 +20,7 @@ import type { ArtifactRecord, AttemptRecord, FailureEvidence, + PeerAttemptFacts, ResultRecord, RunError, SerialAttemptRecord, @@ -246,6 +247,8 @@ export interface ReportStep { model?: StepModelInfo | undefined; /** The configured agent an agent step ran with, by name. */ agent?: string | undefined; + /** The peer whose app the step ran on, by name; absent for the test's own user. */ + user?: string | undefined; /** The hook the step ran in; absent for a step of the test body. */ phase?: StepRecord['phase']; /** How the last screen the step saw differs from the step before's; absent when it saw none. */ @@ -274,6 +277,8 @@ export interface ReportAttempt extends ReportAttemptBase { appLog?: readonly AppLogRecord[] | undefined; /** What the runner saw when the failure landed; absent on a pass or when nothing could be captured. */ failure?: FailureEvidence | undefined; + /** What each peer's app ran on and showed at the failure, by peer name: the peers whose app opened, so absent when none did. */ + peers?: Readonly> | undefined; /** Why the body skipped itself; present when `status` is `skipped`, and on an attempt that failed after skipping. */ skip?: SkipInfo | undefined; /** @@ -551,6 +556,7 @@ function serializeAttempt(attempt: AttemptRecord): ReportAttempt { return { ...serializeAttemptBase(attempt), ...(attempt.failure === undefined ? {} : { failure: attempt.failure }), + ...(attempt.peers === undefined ? {} : { peers: attempt.peers }), ...(attempt.skip === undefined ? {} : { skip: attempt.skip }), ...(attempt.expectedFailure === undefined ? {} diff --git a/packages/e2e/src/report/debug-steps.ts b/packages/e2e/src/report/debug-steps.ts index 79bd785049..11ead38514 100644 --- a/packages/e2e/src/report/debug-steps.ts +++ b/packages/e2e/src/report/debug-steps.ts @@ -26,7 +26,7 @@ export function agentStepTable( const mixedModels = models.size > 1; const rows = steps.map((step) => [ - truncate(step.label === '' ? step.api : `${step.api} ${JSON.stringify(step.label)}`, 64), + truncate(`${step.user === undefined ? '' : `${step.user} · `}${step.label === '' ? step.api : `${step.api} ${JSON.stringify(step.label)}`}`, 64), ...(mixedModels ? [viaLabel(step) ?? '-'] : []), formatMs(step.durationMs), formatMs(eventMs(step, 'model')), diff --git a/packages/e2e/src/report/failure-text.ts b/packages/e2e/src/report/failure-text.ts index a6d70da9e7..856be60157 100644 --- a/packages/e2e/src/report/failure-text.ts +++ b/packages/e2e/src/report/failure-text.ts @@ -12,9 +12,10 @@ import path from 'node:path'; import { modelLabel } from '../config/agent.ts'; import { isLoopbackHost } from '../internal/urls.ts'; import type { AppLogSource } from '../engine/index.ts'; +import type { FailureEvidence } from '../run/records.ts'; import type { AppLogRecord, StepCacheInfo, StepCacheRecord, StepEvent, StepTurn } from '../run/steps.ts'; import type { Report1Document, ReportError, ReportResult, ReportSource, ReportStep } from './build.ts'; -import { cell, code, formatDuration, link, MAX_CELL_CHARS, MAX_ID_CHARS, MAX_LABEL_CHARS, MAX_PATH_CHARS, MAX_TITLE_CHARS, plural } from './markdown-text.ts'; +import { cell, code, formatDuration, link, MAX_CELL_CHARS, MAX_ID_CHARS, MAX_LABEL_CHARS, MAX_PATH_CHARS, MAX_TITLE_CHARS, plural, userLead } from './markdown-text.ts'; import { repeatSuffix, STATUS_WORD } from './format.ts'; import type { AttemptView, Outcome } from './outcome.ts'; @@ -112,18 +113,24 @@ export function toldAttempt(result: ReportResult, final: Outcome): AttemptView { /** A step that did not pass. */ export type FailedStep = ReportStep & { readonly status: Exclude }; +/** What `failedStepOf` reads of a step: a report's, or a run record's, whose error keeps no source line. */ +type StepOutcome = Pick & { readonly error?: Pick | undefined }; + /** * The step whose error ended the attempt, with its position: the step in the * error's phase whose own error carries its code and line, else the last with * its code, since a caught failure comes earlier, else the step a timeout or * interrupt cut. */ -export function failedStepOf(attempt: { readonly steps: readonly ReportStep[]; readonly error?: ReportError | undefined }): { index: number; step: FailedStep } | undefined { +export function failedStepOf(attempt: { + readonly steps: readonly Step[]; + readonly error?: Pick | undefined; +}): { index: number; step: Step & Pick } | undefined { const error = attempt.error; if (error === undefined) return undefined; const phase = error.phase; const candidates = attempt.steps.flatMap((step, index) => - step.status !== 'passed' && (phase === undefined || (step.phase ?? 'body') === phase) ? [{ index, step: step as FailedStep }] : [], + step.status !== 'passed' && (phase === undefined || (step.phase ?? 'body') === phase) ? [{ index, step: step as Step & Pick }] : [], ); const alike = candidates.filter(({ step }) => step.error?.code === error.code); const line = error.source; @@ -204,9 +211,14 @@ export function lastTurnLines(step: ReportStep | undefined): string[] { return turns.slice(-MAX_SUMMARY_TURNS).map((turn) => turnLine(turn, 160)); } -/** `Screen: /path` and `Closest to the locator: ...`, for the run page. */ -export function screenLines(told: AttemptView): string[] { - const failure = told.failure; +/** What the runner saw on one user's screen when the failure landed: the test's own user's, or a peer's by name. */ +function failureOf(told: AttemptView, user: string | undefined): FailureEvidence | undefined { + return user === undefined ? told.failure : told.peers?.[user]?.failure; +} + +/** `Screen: /path` and `Closest to the locator: ...` on the screen of `user`, whose step failed, for the run page. */ +export function screenLines(told: AttemptView, user?: string): string[] { + const failure = failureOf(told, user); if (failure === undefined) return []; const lines: string[] = []; if (failure.url !== undefined) lines.push(`Screen: ${code(screenUrl(failure.url), MAX_PATH_CHARS)}`); @@ -250,22 +262,25 @@ export function appErrorLines(told: AttemptView): string[] { return [...shown.map(({ label, text }) => `App ${label}: ${code(text, MAX_DETAIL_CHARS)}`), ...(more === undefined ? [] : [more])]; } -/** The failure screenshot artifact of the told attempt, if one was recorded. */ +/** The failure screenshot of the told attempt, from the screen of the user whose step failed, if one was recorded. */ export function failureScreenshot(told: AttemptView): ReportArtifact | undefined { - const id = told.failure?.screenshot; + const id = failureOf(told, failedStepOf(told)?.step.user)?.screenshot; return id === undefined ? undefined : told.artifacts.find((artifact) => artifact.id === id); } -/** Artifacts of the told attempt by id, the failure's own first, one per kind. */ +/** Artifacts of the told attempt by id, the failure's own first (each user's), one per kind and user. */ export function evidenceOf(told: AttemptView): ReportArtifact[] { const byId = new Map(told.artifacts.map((artifact) => [artifact.id, artifact])); - const own = [told.failure?.screenshot, told.failure?.screen].flatMap((id) => (id === undefined ? [] : (byId.get(id) ?? []))); + const failures = [told.failure, ...Object.values(told.peers ?? {}).map((peer) => peer.failure)]; + const own = failures.flatMap((failure) => [failure?.screenshot, failure?.screen]).flatMap((id) => (id === undefined ? [] : (byId.get(id) ?? []))); const seen = new Set(own.map((artifact) => artifact.id)); const rest: ReportArtifact[] = []; const kinds = new Set(); for (const artifact of told.artifacts) { - if (seen.has(artifact.id) || kinds.has(artifact.kind) || artifact.kind === 'log') continue; - kinds.add(artifact.kind); + // Each user's app made its own video and screenshots: one of each per user. + const kind = `${artifact.user ?? ''}\u0000${artifact.kind}`; + if (seen.has(artifact.id) || kinds.has(kind) || artifact.kind === 'log') continue; + kinds.add(kind); rest.push(artifact); } return [...own, ...rest]; @@ -391,7 +406,7 @@ function appLogLines(steps: readonly ReportStep[], appLog: readonly AppLogRecord const numbers = new Map(steps.map((step, position) => [step.index, position + 1])); const items = appLog.map((entry) => { const number = entry.step === undefined ? undefined : numbers.get(entry.step); - return { at: entry.at, important: entry.level !== 'info', line: `${number === undefined ? 'before step 1' : `step ${number}`} · ${appLogLine(entry)}` }; + return { at: entry.at, important: entry.level !== 'info', line: `${number === undefined ? 'before step 1' : `step ${number}`} · ${userLead(entry.user)}${appLogLine(entry)}` }; }); const { shown, left } = importantThenLatest(items, MAX_APP_LOG_LINES); return [...(left === 0 ? [] : [`${left} ${left === 1 ? 'line' : 'lines'} left out`]), ...shown.map((item) => item.line)]; @@ -479,12 +494,14 @@ function timedVideos(told: AttemptView): TimedVideo[] { /** * `, video 0:12`: where the step starts in the recording that was running - * then, the last segment that began before it. An attempt cut into several + * on its user's app then, the last segment that began before it. Each user's + * app records its own video, so a step is timed only on its own user's. An attempt cut into several * segments (a restart opens a new page) names the segment too: * `, video-part2 0:03`. A step before the attempt's video began is at 0:00; * one outside every recording a step stopped gets nothing. */ -function videoOffset(step: ReportStep, videos: readonly TimedVideo[]): string { +function videoOffset(step: ReportStep, all: readonly TimedVideo[]): string { + const videos = all.filter((video) => video.artifact.user === step.user); const at = Date.parse(step.startedAt); const timed = videos.findLast((candidate) => candidate.startsAt <= at && at < candidate.endsAt) ?? @@ -496,13 +513,42 @@ function videoOffset(step: ReportStep, videos: readonly TimedVideo[]): string { return `, ${name} ${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}`; } +/** One user's screen when the failure landed, as a section of the page: where it was, its screenshot, the locator's closest candidates, and the screen text. */ +function screenAtFailureLines(told: AttemptView, failure: FailureEvidence, heading: string, options: TracePageOptions): string[] { + const lines = [heading, '']; + const screen = failure.screen === undefined ? undefined : told.artifacts.find((artifact) => artifact.id === failure.screen); + const listing = screen?.path === undefined ? undefined : options.readArtifact?.(screen.path); + const where = [ + ...(failure.url === undefined ? [] : [code(failure.url, MAX_PATH_CHARS)]), + ...(failure.viewport === undefined ? [] : [`viewport ${failure.viewport.width}x${failure.viewport.height}`]), + ...(failure.nodes === undefined ? [] : [plural(failure.nodes, 'node')]), + ]; + if (where.length > 0) lines.push(`${where.join(' · ')} `); + const shot = failure.screenshot === undefined ? undefined : told.artifacts.find((artifact) => artifact.id === failure.screenshot); + const shotHref = shot?.path === undefined ? undefined : pageHref(shot.path, options); + if (shotHref !== undefined) lines.push('', `!${link('screenshot at failure', shotHref)}`, ''); + if (failure.candidates !== undefined && failure.candidates.length > 0) { + lines.push('Closest to what the locator asked for: '); + for (const candidate of failure.candidates) lines.push(`- ${code(candidate, MAX_CELL_CHARS)}`); + } + if (listing !== undefined) { + const body = listing.length > MAX_SCREEN_CHARS ? `${listing.slice(0, MAX_SCREEN_CHARS)}\n…[cut at ${MAX_SCREEN_CHARS} characters; the file has the rest]` : listing; + if (lines.at(-1) !== '') lines.push(''); + lines.push('The screen as the agent reads it, one node per line: `#id role "name" text="…" [states]`.', '', '```text', body.replaceAll('```', "'''").trimEnd(), '```'); + } else if (screen !== undefined) { + lines.push(`${artifactPath(screen, options, 'screen')} `); + } + lines.push(''); + return lines; +} + // --- the page --- const STEP_GLYPH: Record = { passed: '✓', failed: '✗', blocked: '✗', 'timed-out': '✗', cancelled: '–' }; /** `[screenshot](run#artifacts) \`todos-adds-a-todo-1a2b…/attempt-1/screenshots/001-failure.png\``: the kind (or `label`), linked to the run's artifacts when there is a URL, and the file's path so the reader finds it. */ function artifactPath(artifact: ReportArtifact, options: TracePageOptions, label: string = artifact.kind): string { - const kind = cell(label, MAX_ID_CHARS); + const kind = `${userLead(artifact.user)}${cell(label, MAX_ID_CHARS)}`; // A video a hosted service keeps is its own link, wherever the run's files are. if (artifact.url !== undefined) return link(kind, artifact.url); const fromPage = artifact.path === undefined ? undefined : pageHref(artifact.path, options); @@ -543,8 +589,15 @@ export function renderTracePage(report: Report1Document, result: ReportResult, f formatDuration(final.durationMs), ]; lines.push(about.join(' · '), ''); - const ranOn = Object.entries(told.environment ?? {}); - if (ranOn.length > 0) lines.push(`Ran on: ${ranOn.map(([name, value]) => `${cell(name, MAX_ID_CHARS)} ${code(value, MAX_CELL_CHARS)}`).join(' · ')}`, ''); + const ranOn = (environment: Readonly> | undefined): string => + Object.entries(environment ?? {}).map(([name, value]) => `${cell(name, MAX_ID_CHARS)} ${code(value, MAX_CELL_CHARS)}`).join(' · '); + if (ranOn(told.environment) !== '') lines.push(`Ran on: ${ranOn(told.environment)}`, ''); + for (const [user, peer] of Object.entries(told.peers ?? {})) { + // A peer on another target says which; one on the test's own needs no telling. + const elsewhere = peer.target === result.targetId ? '' : ` target ${code(peer.target, MAX_ID_CHARS)}`; + const facts = ranOn(peer.environment); + if (elsewhere !== '' || facts !== '') lines.push(`${cell(user, MAX_ID_CHARS)} ran on${elsewhere}${facts === '' ? '' : `: ${facts}`}`, ''); + } // A test that failed as `test.fail` expected tells that failure, also below an earlier attempt's. const mark = result.attempts.at(-1)?.expectedFailure; @@ -572,7 +625,7 @@ export function renderTracePage(report: Report1Document, result: ReportResult, f const offset = videoOffset(step, videos); const hook = step.phase === undefined ? '' : ` in ${step.phase}`; const label = stepLabel(step, MAX_CELL_CHARS); - lines.push(`${index + 1}. ${STEP_GLYPH[step.status]} ${code(step.api, MAX_ID_CHARS)}${label === '' ? '' : ` ${label}`} (${formatDuration(step.durationMs)}${calls}${offset}${hook})${failed}${own}`); + lines.push(`${index + 1}. ${STEP_GLYPH[step.status]} ${userLead(step.user)}${code(step.api, MAX_ID_CHARS)}${label === '' ? '' : ` ${label}`} (${formatDuration(step.durationMs)}${calls}${offset}${hook})${failed}${own}`); if (step.status !== 'passed' && step.explanation !== undefined && step.explanation.trim() !== '') { lines.push(` > ${cell(step.explanation, MAX_DETAIL_CHARS)}`); } @@ -605,31 +658,10 @@ export function renderTracePage(report: Report1Document, result: ReportResult, f } const failure = told.failure; - if (failure !== undefined) { - lines.push('## Screen at failure', ''); - const screen = failure.screen === undefined ? undefined : told.artifacts.find((artifact) => artifact.id === failure.screen); - const listing = screen?.path === undefined ? undefined : options.readArtifact?.(screen.path); - const where = [ - ...(failure.url === undefined ? [] : [code(failure.url, MAX_PATH_CHARS)]), - ...(failure.viewport === undefined ? [] : [`viewport ${failure.viewport.width}x${failure.viewport.height}`]), - ...(failure.nodes === undefined ? [] : [plural(failure.nodes, 'node')]), - ]; - if (where.length > 0) lines.push(`${where.join(' · ')} `); - const shot = failureScreenshot(told); - const shotHref = shot?.path === undefined ? undefined : pageHref(shot.path, options); - if (shotHref !== undefined) lines.push('', `!${link('screenshot at failure', shotHref)}`, ''); - if (failure.candidates !== undefined && failure.candidates.length > 0) { - lines.push('Closest to what the locator asked for: '); - for (const candidate of failure.candidates) lines.push(`- ${code(candidate, MAX_CELL_CHARS)}`); - } - if (listing !== undefined) { - const body = listing.length > MAX_SCREEN_CHARS ? `${listing.slice(0, MAX_SCREEN_CHARS)}\n…[cut at ${MAX_SCREEN_CHARS} characters; the file has the rest]` : listing; - if (lines.at(-1) !== '') lines.push(''); - lines.push('The screen as the agent reads it, one node per line: `#id role "name" text="…" [states]`.', '', '```text', body.replaceAll('```', "'''").trimEnd(), '```'); - } else if (screen !== undefined) { - lines.push(`${artifactPath(screen, options, 'screen')} `); - } - lines.push(''); + if (failure !== undefined) lines.push(...screenAtFailureLines(told, failure, '## Screen at failure', options)); + // Each peer's screen when the failure landed, under its name. + for (const [user, peer] of Object.entries(told.peers ?? {})) { + if (peer.failure !== undefined) lines.push(...screenAtFailureLines(told, peer.failure, `## Screen at failure: ${cell(user, MAX_ID_CHARS)}`, options)); } if (told.secondaryErrors.length > 0) { @@ -644,7 +676,8 @@ export function renderTracePage(report: Report1Document, result: ReportResult, f const evidence = evidenceOf(told); if (evidence.length > 0) { lines.push('## Evidence', ''); - for (const artifact of evidence) lines.push(`- ${artifactPath(artifact, options, artifact.id === failure?.screen ? 'screen' : artifact.kind)}`); + const screens = new Set([failure?.screen, ...Object.values(told.peers ?? {}).map((peer) => peer.failure?.screen)]); + for (const artifact of evidence) lines.push(`- ${artifactPath(artifact, options, screens.has(artifact.id) ? 'screen' : artifact.kind)}`); lines.push(''); } diff --git a/packages/e2e/src/report/list-model.ts b/packages/e2e/src/report/list-model.ts index 09c26f8b48..93243e1989 100644 --- a/packages/e2e/src/report/list-model.ts +++ b/packages/e2e/src/report/list-model.ts @@ -48,7 +48,10 @@ export interface CurrentStep { export type FinishedStep = Pick< Extract, 'api' | 'label' | 'status' | 'durationMs' | 'modelCalls' ->; +> & { + /** The peer whose app the step ran on; absent for the test's own user. */ + readonly user?: string; +}; /** A pair that has started and whose result is still to come. */ export interface RunningTest { @@ -62,7 +65,10 @@ export interface RunningTest { * executing, but its result only arrives with the whole group. */ executing: boolean; + /** The test's own user's running step. */ current: CurrentStep | undefined; + /** Each peer's running step, by peer name: a peer's steps run beside the test's own. */ + readonly peerSteps: Map; /** * Finished agent steps across every attempt, oldest first. Shown under the * test in the live window while it runs, nested under its line in the file diff --git a/packages/e2e/src/report/list-steps.ts b/packages/e2e/src/report/list-steps.ts index a2a284adba..a39d0dae31 100644 --- a/packages/e2e/src/report/list-steps.ts +++ b/packages/e2e/src/report/list-steps.ts @@ -41,6 +41,16 @@ const REASONING_SEPARATOR_WIDTH = 3; /** A narrower clip than this hides more than it says; the excerpt is dropped instead. */ const MIN_REASONING_COLUMNS = 24; +/** `guest · `: the peer a step ran as, before its api; nothing for the test's own user. */ +export function userPrefix(user: string | undefined): string { + return user === undefined ? '' : `${bounded(user)} · `; +} + +/** `userPrefix` in cyan; nothing at all for the test's own user, so its lines carry no empty color codes. */ +function cyanUser(pc: Colors, user: string | undefined): string { + return user === undefined ? '' : pc.cyan(userPrefix(user)); +} + /** One-line, quoted step label; `maxColumns` clips it further to fit a row. */ export function quotedLabel(label: string, maxColumns = MAX_STEP_LABEL_COLUMNS): string { const max = Math.min(MAX_STEP_LABEL_COLUMNS, Math.max(MIN_STEP_LABEL_COLUMNS, maxColumns)); @@ -63,7 +73,7 @@ export function stepLine(pc: Colors, step: FinishedStep, options: StepLineOption const calls = step.modelCalls > 0 ? ` · ${step.modelCalls} model call${step.modelCalls === 1 ? '' : 's'}` : ''; const outcome = step.status === 'passed' ? '' : ` ${step.status}`; - const head = `${glyph} ${options.context ?? ''}${pc.dim(step.api)} `; + const head = `${glyph} ${options.context ?? ''}${cyanUser(pc, step.user)}${pc.dim(step.api)} `; const tail = pc.dim(`${formatTime(step.durationMs)}${calls}${outcome}`); const room = options.maxWidth === undefined @@ -98,7 +108,7 @@ function promptSource(step: HeldStep): string { */ export function stepPromptRows(pc: Colors, prompt: StepPrompt, options: { readonly maxWidth: number }): string[] { const rows = prompt.steps.map(({ step, number }) => { - const head = `${pc.bold(pc.cyan(`▶ step ${number}`))} ${pc.dim(step.api)} `; + const head = `${pc.bold(pc.cyan(`▶ step ${number}`))} ${cyanUser(pc, step.user)}${pc.dim(step.api)} `; const source = promptSource(step); const tail = source === '' ? '' : ` ${pc.dim(source)}`; const room = options.maxWidth - visibleWidth(head) - visibleWidth(tail) - LABEL_CHROME; @@ -118,7 +128,7 @@ export function stepPromptLine(prompt: StepPrompt): string { const numbers = prompt.steps.map(({ number }) => number).join(', '); const steps = prompt.steps.map(({ step }) => { const source = promptSource(step); - return `${step.api} ${quotedLabel(step.label)}${source === '' ? '' : ` (${source})`}`; + return `${userPrefix(step.user)}${step.api} ${quotedLabel(step.label)}${source === '' ? '' : ` (${source})`}`; }); const keys = [`enter to ${enterDoes(prompt)}`, ...STEP_KEYS.map(([key, does]) => `${key} to ${does}`)].join(', '); const at = prompt.steps.length === 1 ? 'step' : 'steps'; diff --git a/packages/e2e/src/report/list.ts b/packages/e2e/src/report/list.ts index 8e3944c2d7..cf2806877a 100644 --- a/packages/e2e/src/report/list.ts +++ b/packages/e2e/src/report/list.ts @@ -20,7 +20,7 @@ import { cleanupErrorsOf, expectedFailureOf, failureBeforeSkip, type ArtifactRec import type { Reporter, ReporterSummary } from '../types.ts'; import { projectSource } from './build.ts'; import { codeFrame, userFrame } from './code-frame.ts'; -import { appErrorsOf, type AppErrors } from './failure-text.ts'; +import { appErrorsOf, failedStepOf, type AppErrors } from './failure-text.ts'; import { addCacheTally, addModelTally, @@ -63,7 +63,7 @@ import { import { leftOutTests } from './left-out.ts'; import { ExploreView } from './list-explore.ts'; import { isShownEvent, type ConfiguredModel, type FileGroup, type PausedTest, type ReplayNotice, type RunningTest, type TestLine } from './list-model.ts'; -import { replayLine, replayNotices, stepLine, stepPromptLine } from './list-steps.ts'; +import { replayLine, replayNotices, stepLine, stepPromptLine, userPrefix } from './list-steps.ts'; import { LiveWindow } from './live-window.ts'; import { repeatGroups, repeatLine, repeatSummary, type RepeatRun } from './repeats.ts'; import { RunningTree } from './running-tree.ts'; @@ -127,6 +127,8 @@ interface ResultDetails { /** What the runner saw when the last failure landed, with the screen text's report path when it kept one. */ readonly failure: FailureEvidence | undefined; readonly screenPath: string | undefined; + /** The peer whose step failed, whose screen `failure` is; undefined for the test's own user. */ + readonly failureUser: string | undefined; /** What the app logged during the told attempt that went wrong; undefined for nothing. */ readonly appLog: AppLogSummary | undefined; /** Cleanup-phase secondary errors of attempts whose cleanup failed; shown under a passed or flaky test. */ @@ -186,13 +188,22 @@ function attemptDetails(attempts: readonly AttemptRecord[], passed: boolean, con }; } -/** The failure evidence of one attempt, and the path of the screen text it points at. */ -function failureOf( - attempt: { readonly failure?: FailureEvidence | undefined; readonly artifacts: readonly ArtifactRecord[] } | undefined, -): Pick { - const failure = attempt?.failure; +/** What `failureOf` reads of an attempt: its evidence and files, and the steps that say whose failure it was. */ +interface FailedAttemptView { + readonly failure?: FailureEvidence | undefined; + readonly artifacts: readonly ArtifactRecord[]; + readonly peers?: AttemptRecord['peers']; + readonly steps?: AttemptRecord['steps']; + readonly error?: AttemptRecord['error']; +} + +/** The failure evidence of one attempt on the screen of the user whose step failed, and the path of the screen text it points at. */ +function failureOf(attempt: FailedAttemptView | undefined): Pick { + // Without its steps, a failure is the test's own user's: a serial member runs no peers. + const failureUser = attempt?.steps === undefined ? undefined : failedStepOf({ steps: attempt.steps, error: attempt.error })?.step.user; + const failure = failureUser === undefined ? attempt?.failure : attempt?.peers?.[failureUser]?.failure; const screen = failure?.screen === undefined ? undefined : attempt?.artifacts.find((artifact) => artifact.id === failure.screen); - return { failure, screenPath: screen?.path }; + return { failure, screenPath: screen?.path, failureUser }; } /** Where each video these attempts kept is, in order: a report-relative path, or the URL of one a hosted service keeps. */ @@ -276,6 +287,8 @@ interface Failure { readonly videos: readonly string[]; readonly failure: FailureEvidence | undefined; readonly screenPath: string | undefined; + /** The peer whose step failed, whose screen `failure` is; undefined for the test's own user. */ + readonly failureUser: string | undefined; readonly appLog: AppLogSummary | undefined; /** Why a failed test skipped itself: the skip did not outrank the failure. */ readonly skipReason?: string | undefined; @@ -698,6 +711,7 @@ export class ListReporter implements Reporter { startedMs: Date.now(), executing: true, current: undefined, + peerSteps: new Map(), steps: this.pairs.get(key)?.steps ?? [], ran: this.stepping ? (this.pairs.get(key)?.ran ?? []) : undefined, }); @@ -716,15 +730,19 @@ export class ListReporter implements Reporter { const running = this.pairs.get(pairKey(event.testId, event.agent, event.target, event.repeat)); if (running === undefined) return; const { progress } = event; + // A peer's step runs beside the test's own: each user has its own current step. + const user = progress.identity?.user; + const current = user === undefined ? running.current : running.peerSteps.get(user); switch (progress.phase) { case 'start': { const { api, label, kind } = progress; - running.current = { api, label, kind, events: [], replaying: false, activity: undefined }; + const started = { api, label, kind, events: [], replaying: false, activity: undefined }; + if (user === undefined) running.current = started; + else running.peerSteps.set(user, started); this.window.redraw(); break; } case 'event': { - const { current } = running; this.explore?.action(progress.event); if (current === undefined) break; // The event ends whatever was announced; until the next announcement @@ -737,28 +755,27 @@ export class ListReporter implements Reporter { break; } case 'activity': { - const { current } = running; if (current === undefined) break; current.activity = progress.activity; this.window.redraw(); break; } case 'replay': { - const { current } = running; if (current === undefined) break; current.replaying = progress.active; this.window.redraw(); break; } case 'end': { - running.current = undefined; - running.ran?.push({ api: progress.api, label: progress.label, status: progress.status, durationMs: progress.durationMs, modelCalls: progress.modelCalls }); + if (user === undefined) running.current = undefined; + else running.peerSteps.delete(user); + const { api, label, status, durationMs, modelCalls } = progress; + const step = { api, label, status, durationMs, modelCalls, ...(user === undefined ? {} : { user }) }; + running.ran?.push(step); if (progress.kind !== 'agent') { this.window.redraw(); break; } - const { api, label, status, durationMs, modelCalls } = progress; - const step = { api, label, status, durationMs, modelCalls }; // An exploration's planner and charter steps show as the exploration's own rows. if (this.explore !== undefined) break; if (this.live) { @@ -807,7 +824,7 @@ export class ListReporter implements Reporter { // Read before `detailsOf` releases the result's serial group. const skippedAfter = failureBeforeSkip(result, (id) => this.pendingSerial.get(id)?.group); const id = resultId(result.test.id, result.target.name, result.agent, result.repeat); - const { durationMs, usage, models, cache, error, videos, screenshots, failure, screenPath, appLog, skipReason, replays, cleanupErrors } = + const { durationMs, usage, models, cache, error, videos, screenshots, failure, screenPath, failureUser, appLog, skipReason, replays, cleanupErrors } = this.detailsOf(result); this.screenshots.push(...screenshots); addUsage(this.runUsage, usage); @@ -823,7 +840,7 @@ export class ListReporter implements Reporter { // The exploration's verdict is its findings; any other error is a failure of its own, unless the run stopped it. this.explore.result(result.attempts.flatMap((attempt) => attempt.artifacts)); if (error !== undefined && result.status !== 'interrupted' && !this.explore.isVerdict(error)) { - this.failures.push({ id, group, title, declaredLine, status: result.status, error, videos, failure, screenPath, appLog }); + this.failures.push({ id, group, title, declaredLine, status: result.status, error, videos, failure, screenPath, failureUser, appLog }); } this.window.redraw(); return; @@ -850,7 +867,7 @@ export class ListReporter implements Reporter { run: { repeat: result.repeat, status: result.status, code: error?.code ?? result.attempts.findLast((attempt) => attempt.status !== 'passed')?.error?.code }, }); if (statusBucket(result.status) === 'failed') { - this.failures.push({ id, group, title, declaredLine, status: result.status, error, videos, failure, screenPath, appLog, skipReason }); + this.failures.push({ id, group, title, declaredLine, status: result.status, error, videos, failure, screenPath, failureUser, appLog, skipReason }); } if (skippedAfter !== undefined) { this.skippedFailures.push({ id, group, title, declaredLine, status: result.status, error: skippedAfter.error, videos, ...failureOf(skippedAfter), appLog: undefined }); @@ -1171,7 +1188,7 @@ export class ListReporter implements Reporter { this.print(''); this.print(this.errorBanner(`${heading} ${failures.length}`)); this.print(''); - failures.forEach(({ id, group, title, status, error, videos, failure, screenPath, appLog, skipReason }, index) => { + failures.forEach(({ id, group, title, status, error, videos, failure, screenPath, failureUser, appLog, skipReason }, index) => { this.print( `${pc.bold(pc.bgRed(status === 'skipped' ? ' SKIP ' : ' FAIL '))} ${this.badge(group.target)} ${bounded(group.file)}${this.separator}${title}`, ); @@ -1184,7 +1201,7 @@ export class ListReporter implements Reporter { this.printFailureLocation(error.stack); } if (skipReason !== undefined) this.print(pc.yellow(` ${pc.dim(F_POINTER)} ${pc.dim('skipped')} ${bounded(skipReason)}`)); - this.printEvidence(failure, screenPath, pages[id], appLog); + this.printEvidence(failure, failureUser, screenPath, pages[id], appLog); this.printVideos(videos); const marker = `[${index + 1}/${failures.length}]`; const { before, after } = rule(marker, 'right'); @@ -1208,12 +1225,12 @@ export class ListReporter implements Reporter { * error, and where the trace page is (else the screen text). The message * says what was asked; these lines say what was there. */ - private printEvidence(failure: FailureEvidence | undefined, screenPath: string | undefined, page: string | undefined, appLog: AppLogSummary | undefined): void { + private printEvidence(failure: FailureEvidence | undefined, user: string | undefined, screenPath: string | undefined, page: string | undefined, appLog: AppLogSummary | undefined): void { const { pc } = this; const row = (label: string, text: string): void => { this.print(pc.cyan(` ${pc.dim(F_POINTER)} ${pc.dim(label)} ${text}`)); }; - if (failure?.url !== undefined) row('at', bounded(failure.url)); + if (failure?.url !== undefined) row('at', `${userPrefix(user)}${bounded(failure.url)}`); for (const candidate of failure?.candidates ?? []) row('on screen', bounded(candidate)); if (appLog !== undefined) { row('app', `${appLog.tally} logged`); diff --git a/packages/e2e/src/report/markdown-text.ts b/packages/e2e/src/report/markdown-text.ts index f53489ce51..21f726e664 100644 --- a/packages/e2e/src/report/markdown-text.ts +++ b/packages/e2e/src/report/markdown-text.ts @@ -86,6 +86,11 @@ function href(url: string): string { return collapseText(url).replace(/[\s()<>]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, '0')}`); } +/** `guest · `: the peer a step, a log line, or a file belongs to, before it; nothing for the test's own user. */ +export function userLead(user: string | undefined): string { + return user === undefined ? '' : `${cell(user, MAX_ID_CHARS)} · `; +} + export function link(text: string, url: string): string { return `[${text}](${href(url)})`; } diff --git a/packages/e2e/src/report/markdown.ts b/packages/e2e/src/report/markdown.ts index 14d9528138..955f28223c 100644 --- a/packages/e2e/src/report/markdown.ts +++ b/packages/e2e/src/report/markdown.ts @@ -41,7 +41,7 @@ import { stepLabel, toldAttempt, } from './failure-text.ts'; -import { cell, code, formatDuration, link, MAX_ID_CHARS, MAX_PATH_CHARS, MAX_TITLE_CHARS, plural } from './markdown-text.ts'; +import { cell, code, formatDuration, link, MAX_ID_CHARS, MAX_PATH_CHARS, MAX_TITLE_CHARS, plural, userLead } from './markdown-text.ts'; import { outcome, type Outcome } from './outcome.ts'; import { isExploreVerdict } from './traces.ts'; import { posixRelative, writeTextReport } from './write.ts'; @@ -237,11 +237,16 @@ function spendLine(run: ReportRun, entries: readonly Entry[]): string | undefine /** `screenshot \`.e2e/results//attempt-1/screenshots/001-failure.png\``: each file as the reader finds it under `artifactsDir`, capped. */ function evidencePaths(sorted: readonly ReportArtifact[], dir: string): string[] { const files = sorted.flatMap((artifact) => (artifact.path === undefined ? [] : [{ artifact, file: path.posix.join(dir, artifact.path) }])); - const shown = files.slice(0, MAX_EVIDENCE_PATHS).map(({ artifact, file }) => `${artifact.kind} ${code(file)}`); + const shown = files.slice(0, MAX_EVIDENCE_PATHS).map(({ artifact, file }) => `${artifactLabel(artifact)} ${code(file)}`); if (files.length > shown.length) shown.push(`and ${files.length - shown.length} more`); return shown; } +/** `video`, or `guest · video` for a file a peer's app made. */ +function artifactLabel(artifact: ReportArtifact): string { + return `${userLead(artifact.user)}${artifact.kind}`; +} + /** * Where the evidence is: each kind linked to the run's artifacts when there * is a URL (the upload keeps one directory per test, named after it, so the @@ -255,7 +260,7 @@ function evidence(artifacts: readonly ReportArtifact[], options: MarkdownReportO const local = artifacts.filter((artifact) => artifact.url === undefined); if (local.length === 0) return hosted.join(', '); const sorted = local.toSorted((a, b) => KIND_RANK[a.kind] - KIND_RANK[b.kind]); - const kinds = [...new Set(sorted.map((artifact) => artifact.kind))]; + const kinds = [...new Set(sorted.map(artifactLabel))]; const url = options.artifactsUrl; const shown = url !== undefined ? kinds.map((kind) => link(kind, url)) @@ -277,7 +282,7 @@ function stepClause(steps: readonly ReportStep[], at: { index: number; step: Fai const calls = modelCalls(at.step); const spent = calls === 0 ? '' : ` and ${plural(calls, 'model call')}`; const call = at.step.kind === 'agent' ? `${code(at.step.api, MAX_ID_CHARS)} ${stepLabel(at.step, MAX_PATH_CHARS)}` : code(`${at.step.api} ${at.step.label}`, MAX_PATH_CHARS); - return `at step ${at.index + 1} of ${steps.length}: ${call}, after ${formatDuration(at.step.durationMs)}${spent}`; + return `at step ${at.index + 1} of ${steps.length}: ${userLead(at.step.user)}${call}, after ${formatDuration(at.step.durationMs)}${spent}`; } /** `**CODE** (phase)`: how the error names itself. */ @@ -333,7 +338,8 @@ function failureBlock({ result, final }: Entry, manyTargets: boolean, options: M const name = error === undefined ? `**${cell(result.status, MAX_ID_CHARS)}**` : errorName(error); const lead = at === undefined ? name : `${name} ${stepClause(told.steps, at)}`; const alike = attemptsLine(result, final); - const facts = [...detailLines(error), ...(alike === undefined ? [] : [alike]), ...lastTurnLines(at?.step), ...screenLines(told), ...appErrorLines(told)]; + // The screen the failure is told on is the one of the user whose step failed. + const facts = [...detailLines(error), ...(alike === undefined ? [] : [alike]), ...lastTurnLines(at?.step), ...screenLines(told, at?.step.user), ...appErrorLines(told)]; const where = evidence(evidenceOf(told), options); const page = options.traces?.get(result.id); const about = [sourceText(failureSource(result, told), options.sourceUrl), ...(manyTargets ? [cell(result.targetId, MAX_ID_CHARS)] : [])]; diff --git a/packages/e2e/src/report/outcome.ts b/packages/e2e/src/report/outcome.ts index c8166ee5e8..c3b62f1706 100644 --- a/packages/e2e/src/report/outcome.ts +++ b/packages/e2e/src/report/outcome.ts @@ -7,7 +7,7 @@ */ import type { SkipInfo } from '../collect/select.ts'; -import type { FailureEvidence } from '../run/records.ts'; +import type { FailureEvidence, PeerAttemptFacts } from '../run/records.ts'; import type { AppLogRecord } from '../run/steps.ts'; import { isCutSerialRetry } from '../run/retry.ts'; import type { ReportError, ReportResult, ReportSerialGroup, ReportStep } from './build.ts'; @@ -33,6 +33,8 @@ export interface AttemptView { readonly secondaryErrors: readonly ReportError[]; /** What the engine said the attempt ran on; for a serial member, the group attempt's. */ readonly environment?: Readonly> | undefined; + /** What each peer's app ran on and showed at the failure, by peer name: the peers whose app opened, so absent when none did. */ + readonly peers?: Readonly> | undefined; /** Why the body skipped itself; on a failed attempt, a skip the failure outranked. */ readonly skip: SkipInfo | undefined; } @@ -84,6 +86,7 @@ function attemptViews(result: ReportResult, groups: ReadonlyMap this.currentRows(current, user, maxEvents, now)); + return [...own, ...peers].slice(0, budget); + } + + /** One user's running step and, for an agent step, its calls and the work in flight. */ + private currentRows(current: CurrentStep, user: string | undefined, maxEvents: number, now: number): string[] { const { pc } = this; - const { current } = test; - if (current === undefined) return []; - const rows = [pc.dim(`${F_DOWN_RIGHT} ${current.api} ${quotedLabel(current.label)}`)]; - if (current.kind !== 'agent') return rows.slice(0, budget); + const rows = [pc.dim(`${F_DOWN_RIGHT} ${userPrefix(user)}${current.api} ${quotedLabel(current.label)}`)]; + if (current.kind !== 'agent') return rows; const overflow = current.events.length - maxEvents; if (overflow > 0) rows.push(` ${foldMarker(pc, overflow, 'call')}`); const maxWidth = terminalColumns() - WIDTH_MARGIN - DETAIL_INDENT.length - 2; @@ -203,7 +210,7 @@ export class RunningTree { rows.push(` ${eventLine(pc, event, { maxWidth })}`); } rows.push(` ${waitingRow(pc, now, waitingWord(current))}`); - return rows.slice(0, budget); + return rows; } } diff --git a/packages/e2e/src/run/artifacts.ts b/packages/e2e/src/run/artifacts.ts index 4dc6adeef0..932c8a893f 100644 --- a/packages/e2e/src/run/artifacts.ts +++ b/packages/e2e/src/run/artifacts.ts @@ -95,11 +95,13 @@ export function createAttemptArtifacts(options: { const absolute = path.join(dir, relativePath); const stepId = options.currentStepId?.(); const startedAt = registration?.startedAt; + const user = registration?.user; const record: ArtifactRecord = { id, kind, mediaType: mediaTypeFor(relativePath), ...(startedAt === undefined ? {} : { startedAt }), + ...(user === undefined ? {} : { user }), redaction: REDACTION_BY_KIND[kind], producer: stepId === undefined ? { kind: 'attempt' } : { kind: 'step', stepId }, }; @@ -163,6 +165,7 @@ export function createAttemptArtifacts(options: { mediaType: link.mediaType, url, startedAt: link.startedAt, + ...(link.user === undefined ? {} : { user: link.user }), redaction: REDACTION_BY_KIND.video, producer: stepId === undefined ? { kind: 'attempt' } : { kind: 'step', stepId }, }; diff --git a/packages/e2e/src/run/execute.ts b/packages/e2e/src/run/execute.ts index c5cd990994..8970ea16f0 100644 --- a/packages/e2e/src/run/execute.ts +++ b/packages/e2e/src/run/execute.ts @@ -1,8 +1,9 @@ /** Test-target execution engine. */ +import { mkdirSync } from 'node:fs'; import { rm } from 'node:fs/promises'; import path from 'node:path'; -import type { EngineDisposeContext, EngineSnapshot, ResolveSecretOptions } from '../engine/index.ts'; +import type { EngineDisposeContext, EngineHandle, EngineSnapshot, ResolveSecretOptions } from '../engine/index.ts'; import type { TargetSession, OperationContext, VideoSegment } from '../engine/surface.ts'; import type { ResolvedConfig, ResolvedTarget } from '../config/resolve.ts'; import { @@ -28,19 +29,21 @@ import { DebugTrace } from '../internal/debug.ts'; import { resultId, timestamp, uuidv7 } from '../internal/ids.ts'; import { engineAppInfo } from '../config/app.ts'; import { Deadline, NEVER_ABORTS, withAbort, withScopedBudget, withTimeout } from '../internal/time.ts'; -import { createAgentCacheContext, settleStagedTraces } from '../cache/context.ts'; +import { createAgentCacheContext, settleStagedTraces, type AgentCacheContext } from '../cache/context.ts'; +import type { CachePeerIdentity } from '../cache/identity.ts'; import { storedRecordingsFor, type StoredRecordings } from '../cache/rekeyed.ts'; import type { ModuleRegistration, RegisteredTest } from '../collect/registry.ts'; -import { pairRecordings, type TestTargetPair } from '../collect/select.ts'; +import { pairRecordings, peerTarget, type TestTargetPair } from '../collect/select.ts'; +import { reservedPeerSlot, type PeerSlots } from './peer-slots.ts'; import { keeps, type AttemptRecordings, type VideoRecording } from '../internal/recording-modes.ts'; -import type { ArtifactStore, Secret } from '../types.ts'; +import type { ArtifactStore, PeerFixtures, Secret } from '../types.ts'; import { attemptSegments, createAttemptArtifacts, resultSegment } from './artifacts.ts'; import { AttemptBudget } from './budget.ts'; import { createEngineSession } from '../engine/session.ts'; import { createExtendedFixtures } from './extended-fixtures.ts'; import { captureFailureEvidence } from './failure-evidence.ts'; -import { createFixtures, type ArtifactSink } from './fixtures.ts'; -import { WrittenScreenshots } from './screenshots.ts'; +import { createFixtures, type ArtifactSink, type AttemptEnvironment } from './fixtures.ts'; +import { WrittenScreenshots, type ScreenshotUser } from './screenshots.ts'; import { publishAttempt } from '../expect/attempt.ts'; import { PollScope, runInPollScope } from '../expect/poll-scope.ts'; import { SoftFailures } from '../expect/soft.ts'; @@ -58,7 +61,7 @@ import { traceScreen } from './step-screens.ts'; import { runWithRetries } from './retry.ts'; import { runSerialUnit, type SerialAttemptStart, type SerialHost, type SharedSerialSession } from './serial.ts'; import { interruptedInPhase, interruptedSkip, pairKey, pairResult, unstartedResult } from './units.ts'; -import { adoptSecrets, carriedSecrets, processSecrets, registerDerivedSecrets, redactForSession, resolveSecretValue, sessionLedger, staticSecretLedger } from './secrecy.ts'; +import { adoptSecrets, carriedSecrets, processSecrets, registerDerivedSecrets, redactForSession, resolveSecretValue, sessionLedger, shareSessionLedger, staticSecretLedger } from './secrecy.ts'; import { isSecret } from '../secrets.ts'; import { SessionStaging, SessionStore, targetIdentity, type SessionIdentity } from './sessions.ts'; import { StepRecorder, type StepHoldRequest, type StepProgress } from './steps.ts'; @@ -120,6 +123,8 @@ export interface TargetExecutorOptions { readonly headed: boolean; /** This worker's slot among the target's workers; see `EngineInitInfo.workerSlot`. */ readonly workerSlot: number; + /** The slots the run reserved for this worker's tests' peers, by peer target; see `WorkerBootstrap.peers`. */ + readonly peerSlots?: Readonly> | undefined; /** This worker's environment; see `EngineInitInfo.env`. */ readonly env: Readonly>; /** @@ -141,6 +146,43 @@ export interface TargetExecutorOptions { readonly events?: ExecutionEvents; /** The virtual file of tests registered in memory, and the agents they run as; see `InMemoryAttempts`. */ readonly inMemory?: InMemoryAttempts | undefined; + /** + * Loads the config afresh in this process, for the engines a test's peers + * run on: every load evaluates the config and the project files it imports + * again, so its engines are its own. Undefined where the run loaded no + * config file (a config value, tests registered in memory), which the + * runner refuses peers in before any engine prepares. + */ + readonly loadPeerConfig?: (() => Promise) | undefined; +} + +/** One peer's app in an attempt: the executor whose engine runs it, its session, and its own artifact folder. */ +interface OpenPeer { + readonly name: string; + readonly executor: TargetExecutor; + readonly session: TargetSession; + readonly sink: ArtifactSink; +} + +/** What a peer's fixtures are built from in the test's attempt; the peer's executor adds its own config, target, engine, and models. */ +export type PeerAttemptEnvironment = Omit & { + readonly test: { readonly file: string; readonly titlePath: readonly string[]; readonly user: ScreenshotUser }; +}; + +/** + * A peer's artifact folder, `peers//` inside the attempt's: what its + * engine writes there is registered on the attempt under that path, so two + * users never write the same file. + */ +function peerArtifactSink(sink: ArtifactSink, name: string): ArtifactSink { + const relative = path.posix.join('peers', name); + const dir = path.join(sink.dir, 'peers', name); + mkdirSync(dir, { recursive: true }); + return { + dir, + register: (kind, relativePath, registration) => sink.register(kind, path.posix.join(relative, relativePath), { ...registration, user: name }), + link: (url, registration) => sink.link(url, { ...registration, user: name }), + }; } /** @@ -174,6 +216,8 @@ export interface ClosingRecord { export interface SessionPlan { readonly session: string | undefined; readonly recordings: AttemptRecordings; + /** The session whose secret ledger this one shares: the test's own, for a peer's. */ + readonly ledgerOwner?: TargetSession | undefined; } /** What closing an attempt's session needs besides its verdict: the video it started. */ @@ -204,6 +248,10 @@ export class TargetExecutor implements SerialHost { readonly debug: DebugTrace; private readonly runErrors: RunError[] = []; + /** The executors of this worker's peer engines, by target and position among an attempt's peers on it. */ + private readonly peerExecutors = new Map>(); + /** The engine objects this worker's peers run on: one object is one engine client, which drives one attempt at a time. */ + private readonly peerEngines = new Set(); /** Fails the attempt in flight from outside it, while one is; see `strayRejection`. */ private strayFailure: ((cause: unknown) => void) | undefined; /** The last test whose attempt ended here: the likely source of a rejection that surfaces between attempts. */ @@ -373,6 +421,13 @@ export class TargetExecutor implements SerialHost { * connection, so the engine has nothing of it to release. */ async dispose(options: Pick = {}): Promise { + for (const pending of this.peerExecutors.values()) { + const peer = await pending.catch(() => undefined); + if (peer === undefined) continue; + await peer.dispose(options); + this.runErrors.push(...peer.collectedRunErrors()); + } + this.peerExecutors.clear(); const disposeEngine = this.target.engine?.dispose?.bind(this.target.engine); if (disposeEngine === undefined) return; try { @@ -388,6 +443,129 @@ export class TargetExecutor implements SerialHost { } } + /** + * The executor whose engine runs the `index`th peer on `targetName` in this + * worker's attempts: built from a fresh load of the config the first time + * and reused after, since a worker runs one attempt at a time. A load that + * failed fails every later attempt that needs it the same way, as an + * engine's failed boot does. + */ + private peerExecutor(pair: TestTargetPair, targetName: string, index: number): Promise { + const key = `${targetName}\u0000${String(index)}`; + const existing = this.peerExecutors.get(key); + if (existing !== undefined) return existing; + const pending = this.loadPeerExecutor(pair, targetName, index); + this.peerExecutors.set(key, pending); + // A load that failed is not kept: the next test's peer tries again, and its error names that test. + pending.catch(() => { + if (this.peerExecutors.get(key) === pending) this.peerExecutors.delete(key); + }); + return pending; + } + + private async loadPeerExecutor(pair: TestTargetPair, targetName: string, index: number): Promise { + const named = `test "${pair.test.titlePath.join(' > ')}" in ${pair.test.file}`; + // The peer runs on a slot of its target the run set aside for it: its own device, on a phone. + const reserved = reservedPeerSlot(this.options.peerSlots, targetName, index, named); + // The runner refuses peers in a run with no config file, so a worker that runs one has the file to load. + const config = await this.options.loadPeerConfig!(); + // The load matched the runner's config digest, so it declares every target selection checked. + const target = config.targets.find((candidate) => candidate.name === targetName)!; + // An engine made inside a package is one object every load of the config + // shares; it drives one attempt at a time, so it cannot serve two users, + // whichever targets they run on. + const engine = target.engine; + if (engine !== undefined && (engine === this.target.engine || this.peerEngines.has(engine))) { + throw new ConfigurationError( + 'INVALID_CONFIG', + `${named} runs a peer on target "${targetName}", whose engine is the same instance as another user's in every load of the config, so it cannot run next to them; create the engine in the config file or a project file it imports, not inside a package`, + ); + } + if (engine !== undefined) this.peerEngines.add(engine); + return new TargetExecutor({ + config, + target, + runId: this.options.runId, + artifactsRoot: this.artifactsRoot, + rerunDir: this.rerunDir, + sessionStore: this.options.sessionStore, + headed: this.options.headed, + workerSlot: reserved.slot, + // What the peer target's `prepare` handed its workers, such as which device each slot drives. + env: { ...this.options.env, ...reserved.env }, + isolated: this.options.isolated, + interruptSignal: this.interruptSignal, + debug: this.debug, + // A model failure the peer's agent meets stops the run, as one the test's own agent meets does. + events: { + onNotice: (message) => this.options.events?.onNotice?.(message), + onRunAbort: (error) => this.options.events?.onRunAbort?.(error), + }, + }); + } + + /** + * Opens each peer's app for one attempt, in declaration order, each on an + * engine of its own, sharing the test's secret ledger. Every peer that + * opened lands in `opened` before the next opens, so the caller closes it + * whatever fails after. + */ + private async launchPeers( + pair: TestTargetPair, + owner: TargetSession, + attempt: { readonly id: string; readonly sink: ArtifactSink; readonly recordings: AttemptRecordings; readonly signal: AbortSignal }, + opened: OpenPeer[], + steps: StepRecorder, + ): Promise { + const onTarget = new Map(); + for (const peer of pair.options.peers) { + const targetName = peerTarget(peer, pair); + const index = onTarget.get(targetName) ?? 0; + onTarget.set(targetName, index + 1); + const executor = await this.peerExecutor(pair, targetName, index); + const sink = peerArtifactSink(attempt.sink, peer.name); + const session = await executor.launchSession( + { session: peer.session, recordings: attempt.recordings, ledgerOwner: owner }, + attempt.id, + sink.dir, + attempt.signal, + ); + // What the peer's app logs, and the screens its steps saw, are the peer's. + session.appLog.route((event, at) => steps.recordAppEvent(event, at, peer.name)); + session.screens.route((observation) => + steps.recordScreen(() => + traceScreen(observation, { + ledger: sessionLedger(session, this.config.allSecrets), + maxBytes: this.config.limits.maxObservationBytes, + appOrigin: executor.target.app.base?.origin, + }), + ), + ); + opened.push({ name: peer.name, executor, session, sink }); + } + } + + /** + * One peer's fixtures in another executor's attempt: on that attempt's + * steps, budget, and secret ledger, over this executor's config, target, + * engine, and models, so the peer's agents and their tools see the peer's + * app and no other. + */ + peerFixtures(environment: PeerAttemptEnvironment): PeerFixtures { + const { fixtures } = createFixtures({ + ...environment, + config: this.config, + target: this.target, + models: this.models, + debug: this.debug, + saveSession: undefined, + test: { ...environment.test, writtenScreenshots: this.writtenScreenshots }, + }); + // The graph is a peer's whole: its engine's own fixtures are reached by name. + const peer: Omit = fixtures; + return peer; + } + /** * Runs one file-target unit: runnable pairs of a single file, in declaration * order, sharing a realm between passing non-serial tests. Dispatch-time gating (selection dispositions and @@ -626,6 +804,7 @@ export class TargetExecutor implements SerialHost { } const { video } = plan.recordings; const session = createEngineSession({ engine, targetName: this.target.name, traced: plan.recordings.trace !== undefined }); + if (plan.ledgerOwner !== undefined) shareSessionLedger(session, plan.ledgerOwner, this.config.allSecrets); const launch = (label: string, run: (launchSignal: AbortSignal) => Promise) => this.lifecycle(label, this.config.launchTimeout, 'LAUNCH_TIMEOUT', signal, run); const launchOp = (launchSignal: AbortSignal) => @@ -726,6 +905,30 @@ export class TargetExecutor implements SerialHost { ); } + /** Closes one peer's app on its own executor. */ + private async closePeer(open: OpenPeer, close: SessionClose, record: ClosingRecord, secondaryErrors: SerializedError[]): Promise { + await open.executor.closeSession(open.session, close, record, open.sink, secondaryErrors); + } + + /** + * A peer's replay cache in another executor's attempt: keyed on this + * executor's target, the peer's name, and the target and agent of the test + * that brought it, so no user replays another's recording, nor one peer + * its own from another pair of the test. + */ + peerCache(testId: string, attemptIndex: number, user: CachePeerIdentity): AgentCacheContext | undefined { + return createAgentCacheContext({ + cache: this.config.cache, + projectRoot: this.config.projectRoot, + projectId: this.config.projectId, + testId, + target: this.sessionIdentity, + attemptIndex, + recordings: this.storedRecordings, + user, + }); + } + /** * Finalizes the video, then ends the attempt with a fresh cleanup * budget. The caller has classified the attempt by now: `record.status` @@ -864,6 +1067,8 @@ export class TargetExecutor implements SerialHost { const shared = context.kind === 'serial' ? context.shared : undefined; const onProgress = this.options.events?.onProgress; let openSession: TargetSession | null = null; + // Each peer's app, as it opens; closed before the test's own, on every path. + const openPeers: OpenPeer[] = []; // Secret values the session has seen never enter an error record or a // step label; the ledger is live, so a value resolved mid-attempt is // covered too. Before a session opens, the static values still are. @@ -883,9 +1088,10 @@ export class TargetExecutor implements SerialHost { }); // Agent prompts quote completed steps as prior context. Serial-group // members prepend the steps earlier members already contributed. + // A peer's steps are its own history: the test's user's prompt never quotes them. const priorSteps = shared === undefined - ? () => steps.completed() + ? () => steps.completed().filter((step) => step.user === undefined) : () => [...shared.priorSteps, ...steps.completed()]; const secondaryErrors: SerializedError[] = []; const attemptAbort = new AbortController(); @@ -959,7 +1165,7 @@ export class TargetExecutor implements SerialHost { // Captured the moment the primary failure lands: steps that pass later — // afterEach cleanup, teardown — must not confirm traces the failure // implicated (a cleanup assertion says nothing about the failed flow). - let lastVerifiedAtFailure = -1; + let lastVerifiedAtFailure = new Map(); // Whether any failure, primary or later, says something about the app: // one where no model answered does not, but an afterEach assertion // failing after it still implicates the flows nothing confirmed. @@ -975,7 +1181,7 @@ export class TargetExecutor implements SerialHost { ); return; } - lastVerifiedAtFailure = steps.lastVerifiedStepIndex; + lastVerifiedAtFailure = new Map([undefined, ...openPeers.map((open) => open.name)].map((user) => [user, steps.lastVerifiedStepIndexOf(user)])); failure = classified; failurePhase = atPhase; }; @@ -999,8 +1205,25 @@ export class TargetExecutor implements SerialHost { interrupt: this.interruptSignal, }).catch(() => undefined); if (evidence !== undefined) record.failure = evidence; + // The failure may be on any user's app, so each peer's screen is kept + // too, in its own folder; the attempt's failure record stays the test's. + for (const open of openPeers) { + const peerEvidence = await captureFailureEvidence({ + session: open.session, + error: failure, + ledger: sessionLedger(open.session, this.config.allSecrets), + config: this.config, + appOrigin: open.executor.target.app.base?.origin, + artifacts: open.sink, + operation: (signal, timeoutMs) => this.op(attemptId, timeoutMs, signal), + interrupt: this.interruptSignal, + }).catch(() => undefined); + if (peerEvidence !== undefined) record.peers = { ...record.peers, [open.name]: { target: open.executor.target.name, ...record.peers?.[open.name], failure: peerEvidence } }; + } }; const inMemory = this.options.inMemory?.file === pair.test.file ? this.options.inMemory : undefined; + /** Each peer's replay cache, by name, settled with the test's own at the end. */ + const peerCaches = new Map(); const cache = inMemory === undefined ? createAgentCacheContext({ @@ -1045,6 +1268,20 @@ export class TargetExecutor implements SerialHost { }), ), ); + // Each peer opens its own app before the deadline starts, as the test's + // own app does, on an engine of its own. + await this.launchPeers(pair, session, { id: attemptId, sink: artifacts.sink, recordings, signal: attemptAbort.signal }, openPeers, steps); + // Every user's app is settled, each failure recorded: one user's failure never keeps another's from the verdict. + const settleUsers = async (onFailure: (cause: unknown) => void | Promise): Promise => { + const settles = [() => this.settleAttempt(session, attemptId), ...openPeers.map((open) => () => open.executor.settleAttempt(open.session, attemptId))]; + for (const settle of settles) { + try { + await settle(); + } catch (cause) { + await onFailure(cause); + } + } + }; const testDeadline = new Deadline(pair.options.timeout); this.options.events?.onAttemptDeadline?.(pair, { index: attemptIndex, id: attemptId, startedAt }); @@ -1056,7 +1293,17 @@ export class TargetExecutor implements SerialHost { signal: attemptAbort.signal, ask: (step, signal) => holdStep( - { target: this.target.name, testId: pair.test.id, agent: pair.agent, repeat: pair.repeat, title, api: step.api, label: step.label, ...(step.source === undefined ? {} : { source: step.source }) }, + { + target: this.target.name, + testId: pair.test.id, + agent: pair.agent, + repeat: pair.repeat, + title, + api: step.api, + label: step.label, + ...(step.source === undefined ? {} : { source: step.source }), + ...(step.user === undefined ? {} : { user: step.user }), + }, signal, ), // The runner's watchdog keeps the test deadline too; it gets what is left. @@ -1083,6 +1330,32 @@ export class TargetExecutor implements SerialHost { carriedSecrets(sessionLedger(session, this.config.allSecrets), this.config.allSecrets), ); }; + // A peer runs as its own agent, with its own context and executor memory. + const peerFixtures = Object.fromEntries( + openPeers.map((open) => { + const declared = pair.options.peers.find((peer) => peer.name === open.name)!; + const peerAgent = declared.agent ?? pair.agent; + // The peer's recordings are its own in this pair: keyed by the test's own target and agent too. + const owner = { name: open.name, ownerTargetId: this.sessionIdentity.targetId, ownerAgent: pair.agent }; + const peerCache = open.executor.peerCache(pair.test.id, attemptIndex, owner); + if (peerCache !== undefined) peerCaches.set(open.name, peerCache); + const fixturesOfPeer = open.executor.peerFixtures({ + session: open.session, + steps: steps.forUser(open.name, { agent: peerAgent, target: open.executor.target.name }), + budget, + runId: this.options.runId, + attemptId, + attempt: { ...attempt, memory: new Map() }, + artifacts: open.sink, + priorSteps: () => steps.completed().filter((step) => step.user === open.name), + agentContext: declared.agentContext, + agent: peerAgent, + test: { file: pair.test.file, titlePath: pair.test.titlePath, user: { name: open.name, ownerTarget: this.target.name } }, + ...(peerCache === undefined ? {} : { cache: peerCache }), + }); + return [open.name, fixturesOfPeer]; + }), + ); const { fixtures } = createFixtures({ config: inMemory?.agents === undefined ? this.config : { ...this.config, agents: inMemory.agents }, target: this.target, @@ -1101,6 +1374,7 @@ export class TargetExecutor implements SerialHost { debug: this.debug, models: this.models, test: { file: pair.test.file, titlePath: pair.test.titlePath, writtenScreenshots: this.writtenScreenshots }, + peers: peerFixtures, }); // `expect.poll` and `expect.soft` take no fixture, so the attempt they // run on is published here and cleared when `attemptEnd` fires in `finally`. @@ -1258,12 +1532,10 @@ export class TargetExecutor implements SerialHost { // the last step is collected here, so it is the verdict instead of the // next attempt's surprise. Evidence is taken now, before a teardown // navigates away from the page the callback saw. - try { - await this.settleAttempt(session, attemptId); - } catch (cause) { + await settleUsers(async (cause) => { recordFailure(cause, 'body'); await captureEvidence(); - } + }); enter('afterEach'); // Each teardown gets its own cleanup budget: a body that timed out or @@ -1288,7 +1560,7 @@ export class TargetExecutor implements SerialHost { recordFailure(cause, 'afterEach'); } } - await this.settleAttempt(session, attemptId).catch((cause: unknown) => recordFailure(cause, 'afterEach')); + await settleUsers((cause) => recordFailure(cause, 'afterEach')); } catch (cause) { recordFailure(cause, phase); } finally { @@ -1318,6 +1590,16 @@ export class TargetExecutor implements SerialHost { serialize: (error) => serializeError(error, { phase: 'body', projectRoot: this.config.projectRoot, redact }), redact, }); + // Peers close first, each with the verdict the test reached. + for (const open of openPeers) { + await this.closePeer(open, { attemptId, video }, record, secondaryErrors); + // Every peer that opened is told under its name, with the target it ran on. + const environment = open.session.environment.read(redact); + record.peers = { + ...record.peers, + [open.name]: { target: open.executor.target.name, ...record.peers?.[open.name], ...(environment === undefined ? {} : { environment }) }, + }; + } // A serial member's recording ends with the member, not the group. if (openSession !== null && shared !== undefined) { await this.stopRunningRecording(openSession, attemptId, record, artifacts.sink, secondaryErrors); @@ -1354,7 +1636,23 @@ export class TargetExecutor implements SerialHost { record.status === 'interrupted' ? undefined : { - lastVerifiedStepIndex: failure === undefined ? steps.lastVerifiedStepIndex : lastVerifiedAtFailure, + lastVerifiedStepIndex: failure === undefined ? steps.lastVerifiedStepIndex : (lastVerifiedAtFailure.get(undefined) ?? -1), + implicatesUnconfirmed: failure === undefined || implicatesUnconfirmed, + }, + ); + for (const step of record.steps) { + const write = writes.get(step.index); + if (step.cache !== undefined && write !== undefined) step.cache.write = write; + } + } + // Each peer's recordings stand or fall on that peer's own checks. + for (const [user, peerCache] of peerCaches) { + const writes = await settleStagedTraces( + peerCache, + record.status === 'interrupted' + ? undefined + : { + lastVerifiedStepIndex: failure === undefined ? steps.lastVerifiedStepIndexOf(user) : (lastVerifiedAtFailure.get(user) ?? -1), implicatesUnconfirmed: failure === undefined || implicatesUnconfirmed, }, ); diff --git a/packages/e2e/src/run/fixtures.ts b/packages/e2e/src/run/fixtures.ts index b290f80c2f..5a119cf740 100644 --- a/packages/e2e/src/run/fixtures.ts +++ b/packages/e2e/src/run/fixtures.ts @@ -15,7 +15,7 @@ import type { DebugTrace } from '../internal/debug.ts'; import { ConfigurationError, errorMessage, InfrastructureError, TestError } from '../internal/errors.ts'; import { Deadline } from '../internal/time.ts'; import { didYouMean } from '../internal/suggest.ts'; -import { createScreenshotContext, type ScreenshotContext, type WrittenScreenshots } from './screenshots.ts'; +import { createScreenshotContext, type ScreenshotContext, type ScreenshotUser, type WrittenScreenshots } from './screenshots.ts'; import { sessionRecordings } from './recordings.ts'; import { resolveSecretValue, sessionLedger } from './secrecy.ts'; import { baseUrlOf, resolveNavigationUrl } from '../internal/urls.ts'; @@ -31,8 +31,8 @@ import { } from '../locator/screen.ts'; import { engineAppInfo } from '../config/app.ts'; import type { ResolvedAgentConfig, ResolvedConfig, ResolvedTarget } from '../config/resolve.ts'; -import type { Agent, App, CommandConfig, Expectable, RecordingOptions, SetupSession, TestFixtures } from '../types.ts'; -import type { StepRecord, StepRecorder } from './steps.ts'; +import type { Agent, App, CommandConfig, Expectable, PeerFixtures, RecordingOptions, SetupSession, TestFixtures } from '../types.ts'; +import type { StepRecord, StepSink } from './steps.ts'; export interface ArtifactSink { /** Absolute attempt artifact directory, for runner-written artifacts. */ @@ -44,20 +44,22 @@ export interface ArtifactSink { options?: ArtifactRegistration, ): string; /** Registers a video a hosted service keeps, by URL, and returns its report artifact ID; nothing is read or stored. */ - link(url: string, options: { readonly mediaType: string; readonly startedAt: string }): string; + link(url: string, options: { readonly mediaType: string; readonly startedAt: string; readonly user?: string }): string; } /** Facts about a produced artifact its file does not carry. */ export interface ArtifactRegistration { /** When a time-based artifact (a video segment) began recording. */ readonly startedAt?: string; + /** The peer whose app produced it, by name; absent for the test's own user. */ + readonly user?: string; } export interface AttemptEnvironment { readonly config: ResolvedConfig; readonly target: ResolvedTarget; readonly session: TargetSession; - readonly steps: StepRecorder; + readonly steps: StepSink; /** The running phase's signal and deadline; read at call time, never captured. */ readonly budget: AttemptBudget; readonly runId: string; @@ -82,9 +84,17 @@ export interface AttemptEnvironment { /** * The test the attempt runs, which `toHaveScreenshot` keeps its screenshots * beside, and the screenshots the run wrote; absent for a session with no - * test (`e2e mcp`). + * test (`e2e mcp`). `user` names the peer a peer's graph is for, whose + * screenshots keep a folder of their own. */ - readonly test?: { readonly file: string; readonly titlePath: readonly string[]; readonly writtenScreenshots: WrittenScreenshots }; + readonly test?: { + readonly file: string; + readonly titlePath: readonly string[]; + readonly writtenScreenshots: WrittenScreenshots; + readonly user?: ScreenshotUser; + }; + /** The fixtures of each peer the test declares, by name, already over their own apps; absent for a peer's own graph. */ + readonly peers?: Readonly>; } /** Builds the lazy fixture graph for one attempt. */ @@ -102,7 +112,7 @@ interface ScreenWiring { readonly runId: string; readonly attemptId: string; readonly config: ResolvedConfig; - readonly steps: StepRecorder; + readonly steps: StepSink; readonly secrets: SecretResolver; /** The session's secret ledger, which `screen.tree()` passes its text through. */ readonly redaction: NodeRedaction; @@ -174,6 +184,7 @@ export function createFixtures(environment: AttemptEnvironment): AttemptFixtures titlePath: environment.test.titlePath, written: environment.test.writtenScreenshots, artifacts: environment.artifacts, + user: environment.test.user, }), }), }); @@ -242,6 +253,7 @@ export function createFixtures(environment: AttemptEnvironment): AttemptFixtures app: environment.target.app, attempt: environment.attempt, priorSteps: environment.priorSteps, + ...(environment.test?.user === undefined ? {} : { user: environment.test.user.name }), secrets, redact: ledger.redact, redactCut: ledger.redactCut, @@ -261,6 +273,7 @@ export function createFixtures(environment: AttemptEnvironment): AttemptFixtures app, screen, platform: environment.target.platform, + peers: peersFixture(environment.peers ?? {}), session: { save: async (name: string) => { const saveSession = environment.saveSession; @@ -284,6 +297,27 @@ export function createFixtures(environment: AttemptEnvironment): AttemptFixtures return { fixtures: gateUnknownFixtures(fixtures, environment), agentRuntime }; } +/** + * The test's peers by name. Reaching for a name the test does not declare + * fails at that touch, naming the ones it does, instead of a TypeError on + * `undefined` a line later. + */ +function peersFixture(declared: Readonly>): Readonly> { + const peers = Object.freeze({ ...declared }); + return new Proxy(peers, { + get(target, property, receiver) { + if (typeof property !== 'string' || property in target || PROBED_KEYS.has(property)) { + return Reflect.get(target, property, receiver) as unknown; + } + const names = Object.keys(target); + throw new ConfigurationError( + 'INVALID_CONFIG', + `the test declares no peer "${property}"; ${names.length === 0 ? 'it declares no peers, which the peers option adds' : `it declares ${names.map((name) => `"${name}"`).join(', ')}`}${didYouMean(property, names)}`, + ); + }, + }); +} + /** Keys a test body may probe without meaning a fixture. */ const PROBED_KEYS = new Set(['then', 'constructor', 'toJSON', 'toString', 'valueOf', 'inspect']); diff --git a/packages/e2e/src/run/peer-slots.ts b/packages/e2e/src/run/peer-slots.ts new file mode 100644 index 0000000000..3bd0c14f5d --- /dev/null +++ b/packages/e2e/src/run/peer-slots.ts @@ -0,0 +1,153 @@ +/** + * Slots for peers. A peer of a test (the `peers` option) runs on an engine of + * its own inside the worker that runs the test, so on the peer's target it + * takes a slot no worker of that target holds: a device of its own, on a + * phone target. The runner asks each target's `prepare` for its own workers' + * slots plus the ones peers need, lowers worker counts where an engine serves + * fewer, and tells each worker which slots its tests' peers take. + */ + +import { peerTarget, type Selection } from '../collect/select.ts'; +import { ConfigurationError, InfrastructureError } from '../internal/errors.ts'; + +/** + * The most peers one test of a target puts on each peer target, by the + * test's target, then the peer's: what one worker of the first can need of + * the second at once, since a worker runs one test at a time. + */ +export type PeersBrought = ReadonlyMap>; + +/** Counts the peers each runnable test brings to each target, and keeps the most per test target. */ +export function peersBrought(selection: Pick): PeersBrought { + const brought = new Map>(); + for (const pair of selection.pairs) { + if (pair.disposition !== 'run') continue; + const perTest = new Map(); + for (const peer of pair.options.peers) { + const target = peerTarget(peer, pair); + perTest.set(target, (perTest.get(target) ?? 0) + 1); + } + for (const [target, count] of perTest) { + const own = brought.get(pair.target.name) ?? new Map(); + own.set(target, Math.max(own.get(target) ?? 0, count)); + brought.set(pair.target.name, own); + } + } + return brought; +} + +/** The slots `target` must serve at once with these worker counts: one per worker of its own, and one per peer any worker brings to it. */ +export function slotsNeeded(target: string, workers: ReadonlyMap, brought: PeersBrought): { readonly slots: number; readonly peerSlots: number } { + let peerSlots = 0; + for (const [from, onTargets] of brought) peerSlots += (workers.get(from) ?? 0) * (onTargets.get(target) ?? 0); + return { slots: (workers.get(target) ?? 0) + peerSlots, peerSlots }; +} + +/** One target as the fit reads it: the workers its own units can use, and the slots its engine serves at once, when it said. */ +export interface TargetSlots { + readonly name: string; + readonly workers: number; + readonly served: number | undefined; +} + +/** The worker counts that fit every engine, and a line for each target that runs fewer workers than planned. */ +export interface FittedWorkers { + readonly workers: ReadonlyMap; + readonly notices: readonly string[]; +} + +/** + * Lowers worker counts until every target serves its own workers and the + * peers brought to it. A target short of slots gives up its own workers + * first, down to one; then the targets whose tests bring it the most peers + * do. A target that cannot serve one worker of each is an error, raised + * before any test starts. + */ +export function fitWorkers(targets: readonly TargetSlots[], brought: PeersBrought): FittedWorkers { + const workers = new Map(targets.map((target) => [target.name, target.workers])); + const short = (): TargetSlots | undefined => + targets.find((target) => target.served !== undefined && slotsNeeded(target.name, workers, brought).slots > target.served); + for (let target = short(); target !== undefined; target = short()) { + const own = workers.get(target.name) ?? 0; + if (own > 1) { + workers.set(target.name, own - 1); + continue; + } + // The slots a target's workers beyond its first take here: what lowering it can give back. + const gives = (other: TargetSlots): number => { + const count = workers.get(other.name) ?? 0; + return count > 1 ? count * (brought.get(other.name)?.get(target.name) ?? 0) : 0; + }; + const most = targets.reduce((best, other) => (gives(other) > gives(best) ? other : best), target); + if (gives(most) === 0) { + const parts = [ + ...(own === 0 ? [] : ['1 for its own worker']), + ...targets.flatMap((other) => { + const count = brought.get(other.name)?.get(target.name) ?? 0; + return count === 0 ? [] : [`${count} for the ${count === 1 ? 'peer' : 'peers'} of one ${other.name === target.name ? 'of its own tests' : `"${other.name}" test`}`]; + }), + ]; + throw new InfrastructureError( + 'ENGINE_FAILURE', + `target "${target.name}" serves ${target.served} at once, and this run needs ${slotsNeeded(target.name, workers, brought).slots} of it at once with one worker per target: ${parts.join(', ')}; a peer takes a slot of its own, a device on a phone target, so give the target more, or keep the tests that put a peer on it out of this run`, + ); + } + workers.set(most.name, (workers.get(most.name) ?? 0) - 1); + } + const notices = targets.flatMap((target) => { + const fitted = workers.get(target.name) ?? 0; + // An engine that serves fewer workers than planned lowers its own count as it always has, silently; a line tells only what peers took. + if (fitted === Math.min(target.workers, target.served ?? target.workers)) return []; + return [`target "${target.name}" runs ${fitted} ${fitted === 1 ? 'worker' : 'workers'} at a time, not ${target.workers}: the peers of tests take slots of their own on their targets, and an engine serves only so many at once`]; + }); + return { workers, notices }; +} + +/** The slots on one peer target that one worker's tests' peers take: `count` of them from `firstSlot`. */ +export interface PeerSlots { + readonly firstSlot: number; + readonly count: number; + /** What the peer target's `prepare` handed its workers, which the peer's engine reads the same way. */ + readonly env?: Readonly>; +} + +/** + * The slots worker `workerSlot` of `target` has on each target its tests put + * a peer on. A target's slots are laid out as its own workers first, then one + * block per target in `order` for the peers that target's workers bring, a + * worker's peers side by side: no two users of a run share a slot. + */ +export function peerSlotsOf( + target: string, + workerSlot: number, + order: readonly string[], + workers: ReadonlyMap, + brought: PeersBrought, +): Record { + const slots: Record = {}; + for (const [peerTargetName, count] of brought.get(target) ?? []) { + let firstSlot = workers.get(peerTargetName) ?? 0; + for (const before of order) { + if (before === target) break; + firstSlot += (workers.get(before) ?? 0) * (brought.get(before)?.get(peerTargetName) ?? 0); + } + slots[peerTargetName] = { firstSlot: firstSlot + workerSlot * count, count }; + } + return slots; +} + +/** + * The slot the `index`th peer on `targetName` takes in a worker, from what + * the run reserved for the worker. A peer the run reserved nothing for is an + * error: it never takes a slot, or a device, the run did not set aside. + */ +export function reservedPeerSlot(reserved: Readonly> | undefined, targetName: string, index: number, named: string): PeerSlots & { readonly slot: number } { + const slots = reserved?.[targetName]; + if (slots === undefined || index >= slots.count) { + throw new ConfigurationError( + 'UNSUPPORTED_CAPABILITY', + `${named} runs a peer on target "${targetName}", and the run reserved no slot there for it; a peer never takes a slot, or a device, the run did not set aside`, + ); + } + return { ...slots, slot: slots.firstSlot + index }; +} diff --git a/packages/e2e/src/run/provision.ts b/packages/e2e/src/run/provision.ts index 485484fd40..367e0e5af8 100644 --- a/packages/e2e/src/run/provision.ts +++ b/packages/e2e/src/run/provision.ts @@ -154,13 +154,13 @@ export class PreparedEngines { private readonly targets: ResolvedTarget[] = []; /** - * Runs one target's `prepare` hook for `slots` worker slots, streaming its + * Runs one target's `prepare` hook for `slots` slots, `peerSlots` of them for peers, streaming its * progress lines as notices. Resolves to nothing when the engine declares * no hook. Callers run targets in turn: two engines provisioning the same * toolchain would race, and the notices of one download read better than * two interleaved. */ - async prepare(target: ResolvedTarget, slots: number, scope: PrepareScope): Promise { + async prepare(target: ResolvedTarget, slots: number, scope: PrepareScope, peerSlots = 0): Promise { const engine = target.engine; if (engine?.prepare === undefined) return; // Registered before the hook runs: a `prepare` that throws part-way still gets its `finish`. @@ -173,6 +173,7 @@ export class PreparedEngines { headed: scope.headed, app: engineAppInfo(target.app), slots, + ...(peerSlots === 0 ? {} : { peerSlots }), env: scope.env, signal: scope.signal, log: (line) => scope.notice(target.name, line), diff --git a/packages/e2e/src/run/records.ts b/packages/e2e/src/run/records.ts index d710fa035b..c4415d18d5 100644 --- a/packages/e2e/src/run/records.ts +++ b/packages/e2e/src/run/records.ts @@ -28,6 +28,8 @@ export interface ArtifactRecord { * is the step's offset into it. */ startedAt?: string; + /** The peer whose app produced it, by name; absent for the test's own user. */ + user?: string; /** * Mirrors report-1: how much of the file the runner masked. A screenshot is * `complete`; a video is `incomplete`, since a recording masks nothing @@ -65,6 +67,14 @@ export interface FailureEvidence { candidates?: string[]; } +/** What an attempt kept of one peer beside its steps: the peer's engine's environment facts and its failure evidence. */ +export interface PeerAttemptFacts { + /** The target the peer's app ran on. */ + target: string; + environment?: Record; + failure?: FailureEvidence; +} + export interface AttemptRecord { id: string; index: number; @@ -88,6 +98,8 @@ export interface AttemptRecord { secondaryErrors: SerializedError[]; /** What the engine said the attempt ran on (`EngineAttemptContext.environment`), redacted. */ environment?: Record; + /** Each peer's own facts, by name: what its engine said it ran on, and the evidence its screen held when the attempt failed. */ + peers?: Record; /** Which of the attempt's outcomes keep a trace (`keeps`), when it keeps one at all; the runner's, never in the report. */ trace?: Keep | undefined; cleanup: 'complete' | 'failed' | 'forced'; diff --git a/packages/e2e/src/run/runner.ts b/packages/e2e/src/run/runner.ts index a8f966cf0f..a895e16ddd 100644 --- a/packages/e2e/src/run/runner.ts +++ b/packages/e2e/src/run/runner.ts @@ -13,6 +13,7 @@ import { import { collect, collectInMemory, collectSetups, type Collection } from '../collect/collect.ts'; import type { ModuleRegistration } from '../collect/registry.ts'; import { + peerTarget, repeatEach, select, selectTargets, @@ -55,6 +56,7 @@ import { runUnits, type TargetFailure } from './scheduler.ts'; import type { BeforeStep, HeldStep, StepPrompt } from './step-hold.ts'; import { stepPromptLine } from '../report/list-steps.ts'; import { buildWorkPlans, nonRunResult, orderWorkPlans, plannedSlots, type TargetWorkPlan, type TimeLimit } from './units.ts'; +import { fitWorkers, peerSlotsOf, peersBrought, slotsNeeded, type PeerSlots, type PeersBrought } from './peer-slots.ts'; import { SessionStore } from './sessions.ts'; import { outputLayout } from './output.ts'; import type { RunnerOutput } from './process-output.ts'; @@ -322,6 +324,14 @@ export interface ListOptions targets?: readonly string[] | undefined; } +/** One peer of a listed pair, with its defaults filled in from the pair. */ +export interface ListedPeer { + readonly name: string; + readonly target: string; + readonly session: string | undefined; + readonly agent: string; +} + /** * One test, target, and agent the selection produced, filtered pairs * included. `id` is the result id `report.json` stores for repeat 0. @@ -340,6 +350,8 @@ export interface ListedPair { readonly source: { readonly file: string; readonly line: number; readonly column: number } | undefined; /** The session the test consumes, from the test or its describe chain. */ readonly session: string | undefined; + /** The users the test adds, each with the target it runs on and the agent it runs as; omitted when it adds none. */ + readonly peers?: readonly ListedPeer[]; /** Session names a setup produces; `[]` on an ordinary test. */ readonly sessions: readonly string[]; /** Set when the test belongs to a serial group. */ @@ -964,6 +976,10 @@ export async function run(options: RunOptions = {}): Promise { // The work units, built once: the same plans tell each engine's `prepare` // how many worker slots to provision and the scheduler what to dispatch. let plans = buildWorkPlans(selection, collection, config.projectRoot); + // A test's peers run in its worker on slots of their own on their targets, + // which each target's `prepare` provisions beside its own workers'. + const brought = peersBrought(selection); + let fitted: ReadonlyMap = new Map(); // A run with nothing to run (the filters left nothing, or // --pass-with-no-tests on an empty selection) still reports, but // prepares no engine and starts no app. @@ -977,6 +993,20 @@ export async function run(options: RunOptions = {}): Promise { const workerConfigPath = options.tests === undefined ? config.configPath : undefined; const inProcess = workerConfigPath === undefined; const runWorkers = inProcess ? 1 : config.workers; + // A peer's engine comes from a second load of the config file in the + // worker, so a run with no file to load refuses peers here, before any + // engine sets a slot aside, or boots a device, for one. + const peered = inProcess ? selection.pairs.find((pair) => pair.disposition === 'run' && pair.options.peers.length > 0) : undefined; + if (peered !== undefined) { + recordFailure( + new ConfigurationError( + 'UNSUPPORTED_CAPABILITY', + `test "${peered.test.titlePath.join(' > ')}" in ${peered.test.file} declares peers, which need a run from a config file: a run given a config value, or of tests registered in memory, has no file to load a second engine from`, + ), + 'collection', + ); + return; + } // Starting long files early only pays when other workers take the rest, so only such a run reads the timings history. const previous = runWorkers > 1 ? await loadTimings(timingsPath(config), outputLayout(config.output).report) : undefined; plans = orderWorkPlans(plans, { @@ -998,9 +1028,12 @@ export async function run(options: RunOptions = {}): Promise { // of a worker's stderr fighting the live status block. if (hasWork) { try { - plans = await debug.time('engine.prepare', () => - prepareEngines(plans, runWorkers, engines, { runId, projectRoot: config.projectRoot, env, signal: interrupted, headed: options.headed ?? false, notice }, emit), + const prepared = await debug.time('engine.prepare', () => + prepareEngines(plans, runWorkers, brought, engines, { runId, projectRoot: config.projectRoot, env, signal: interrupted, headed: options.headed ?? false, notice }, emit), ); + plans = prepared.plans; + fitted = prepared.workers; + for (const line of prepared.notices) notice('run', line); } catch (cause) { if (!interrupted.aborted) recordFailure(cause, 'launch'); return; @@ -1117,6 +1150,7 @@ export async function run(options: RunOptions = {}): Promise { aiTrace: aiTrace !== undefined, step: options.beforeStep !== undefined, envFor: workerEnvFor(plans, env), + peersFor: peerSlotsFor(plans, fitted, brought, env), }); // The list reporter shows the prompt under its test; without it, the @@ -1245,53 +1279,90 @@ export async function run(options: RunOptions = {}): Promise { async function prepareEngines( plans: readonly TargetWorkPlan[], runWorkers: number, + brought: PeersBrought, engines: PreparedEngines, scope: PrepareScope, emit: (fact: RunEventFact) => void, -): Promise { - const prepared: TargetWorkPlan[] = []; +): Promise<{ plans: TargetWorkPlan[]; workers: ReadonlyMap; notices: readonly string[] }> { + // Each target is asked for its own workers' slots and one per peer the + // other workers' tests put on it, as planned: an engine that serves fewer + // says so, and the worker counts are fitted to every answer below. + const planned = new Map(plans.map((plan) => [plan.target.name, plannedSlots(plan, runWorkers)])); + const results = new Map(); for (const plan of plans) { const { target } = plan; const engine = target.engine; - if (engine?.prepare === undefined || scope.signal.aborted) { - prepared.push(plan); - continue; - } + if (engine?.prepare === undefined || scope.signal.aborted) continue; const step: SetupStep = { kind: 'prepare', target: target.name, engine: engine.name }; emit({ type: 'setup', step, state: 'started' }); const startedMs = Date.now(); - const slots = plannedSlots(plan, runWorkers); - const result = await engines.prepare(target, slots, scope); - prepared.push(withPreparedWorkers(plan, engine.name, slots, result)); + const { slots, peerSlots } = slotsNeeded(target.name, planned, brought); + const result = await engines.prepare(target, slots, scope, peerSlots); + results.set(target.name, checkedPrepareResult(target.name, engine.name, slots, result)); if (!scope.signal.aborted) { emit({ type: 'setup', step, state: 'finished', durationMs: Date.now() - startedMs }); } } - return prepared; + const served = (plan: TargetWorkPlan): number | undefined => results.get(plan.target.name)?.workers ?? plan.target.engine?.workers; + const { workers, notices } = fitWorkers( + plans.map((plan) => ({ name: plan.target.name, workers: planned.get(plan.target.name) ?? 0, served: served(plan) })), + brought, + ); + return { + plans: plans.map((plan) => { + const result = results.get(plan.target.name); + const own = planned.get(plan.target.name) ?? 0; + const fittedWorkers = workers.get(plan.target.name) ?? 0; + // A target that gave workers up to peers runs what the fit left it, and so does one that hosts peers: what its + // engine serves counts the peers' slots too, and a worker beyond the fit would start on a slot a peer holds. + // Any other keeps the cap its engine reported. + const hostsPeers = slotsNeeded(plan.target.name, workers, brought).peerSlots > 0; + const cap = fittedWorkers < Math.min(own, served(plan) ?? own) || hostsPeers ? fittedWorkers : result?.workers; + return { + ...plan, + ...(cap === undefined ? {} : { workers: cap }), + ...(result?.env === undefined ? {} : { env: result.env }), + }; + }), + workers, + notices, + }; } /** - * Applies the worker cap `prepare` reported to the plan. The engine may only - * narrow what the run planned: a cap outside `1..slots` is an engine defect. + * The result of `prepare`, checked: the engine may only narrow what the run + * asked for, so a count outside `1..slots` is an engine defect. */ -function withPreparedWorkers( - plan: TargetWorkPlan, - engineName: string, - slots: number, - result: void | EnginePrepareResult, -): TargetWorkPlan { +function checkedPrepareResult(targetName: string, engineName: string, slots: number, result: void | EnginePrepareResult): void | EnginePrepareResult { const workers = result?.workers; if (workers !== undefined && (!Number.isSafeInteger(workers) || workers < 1 || workers > Math.max(1, slots))) { throw new InfrastructureError( 'ENGINE_FAILURE', - `engine ${engineName} reported ${String(workers)} workers from prepare for target "${plan.target.name}"; it was asked to provision ${slots}`, + `engine ${engineName} reported ${String(workers)} workers from prepare for target "${targetName}"; it was asked to provision ${slots}`, ); } - return { - ...plan, - ...(workers === undefined ? {} : { workers }), - ...(result?.env === undefined ? {} : { env: result.env }), - }; + return result; +} + +/** + * The slots each worker's tests' peers take, with what each peer target's + * `prepare` handed its own workers: the peer's engine reads its device from + * the same variables, under the run's own, which win on a clash. + */ +function peerSlotsFor( + plans: readonly TargetWorkPlan[], + workers: ReadonlyMap, + brought: PeersBrought, + env: NodeJS.ProcessEnv, +): (targetName: string, workerSlot: number) => Record { + const order = plans.map((plan) => plan.target.name); + const additions = new Map( + plans.map((plan) => [plan.target.name, Object.fromEntries(Object.entries(plan.env ?? {}).filter(([name]) => env[name] === undefined))]), + ); + return (targetName, workerSlot) => + Object.fromEntries( + Object.entries(peerSlotsOf(targetName, workerSlot, order, workers, brought)).map(([peer, slots]) => [peer, { ...slots, env: additions.get(peer) ?? {} }]), + ); } /** @@ -1362,6 +1433,9 @@ function toListedPair(projectRoot: string, pair: TestTargetPair): ListedPair { tags: pair.test.tags, source: projectSource(projectRoot, pair.test.source, pair.test.file), session: pair.options.session, + ...(pair.options.peers.length === 0 + ? {} + : { peers: pair.options.peers.map((peer) => ({ name: peer.name, target: peerTarget(peer, pair), session: peer.session, agent: peer.agent ?? pair.agent })) }), sessions: pair.test.sessions, serialId: pair.test.serialId, target: pair.target.name, diff --git a/packages/e2e/src/run/scheduler.ts b/packages/e2e/src/run/scheduler.ts index 7d7c9067d8..8829a8c2b5 100644 --- a/packages/e2e/src/run/scheduler.ts +++ b/packages/e2e/src/run/scheduler.ts @@ -8,7 +8,7 @@ * execution. */ -import type { SkipInfo, TestTargetPair } from '../collect/select.ts'; +import { peerTarget, type SkipInfo, type TestTargetPair } from '../collect/select.ts'; import type { ResolvedTarget } from '../config/resolve.ts'; import type { AiTraceSnapshot } from '../internal/ai-trace.ts'; import type { DebugSnapshot } from '../internal/debug.ts'; @@ -504,7 +504,7 @@ class Scheduler { const affected: TargetState[] = []; for (const name of failure.targetNames) { const state = this.targets.get(name); - if (state !== undefined && this.hasPendingWork(state)) affected.push(state); + if (state !== undefined && (this.hasPendingWork(state) || this.hostsPendingPeers(state))) affected.push(state); } if (affected.length === 0) return; this.options.events.onRunError({ error: failure.error }); @@ -522,6 +522,25 @@ class Scheduler { ); } + /** + * Whether another target's work still to run puts a peer on this target: + * a queued unit, one a worker holds next, or a pair a worker runs that has + * not reported. Such a test cannot run once this target's app is gone. + */ + private hostsPendingPeers(state: TargetState): boolean { + const name = state.target.name; + const bringsPeer = (pair: TestTargetPair): boolean => pair.options.peers.some((peer) => peerTarget(peer, pair) === name); + for (const other of this.targets.values()) { + if (other !== state && [...other.setupQueue, ...other.fileQueue].some((unit) => unit.pairs.some(bringsPeer))) return true; + } + return this.workers.some( + (worker) => + worker.targetName !== name && + (worker.queued?.pairs.some(bringsPeer) === true || + worker.unit?.pairs.some((pair) => bringsPeer(pair) && !worker.reported.has(pairKey(pair.test.id, pair.agent, pair.repeat))) === true), + ); + } + /** Stops the run once the time limit is due, checking again at the new due time after a hold pushed it back. */ private checkTimeLimit(limit: TimeLimit): void { clearTimeout(this.timeLimitTimer); @@ -684,9 +703,26 @@ class Scheduler { private peekUnit(state: TargetState): WorkUnit | undefined { if (state.unavailable !== undefined) return undefined; if (state.setupQueue.length > 0) return state.setupQueue[0]; - // Ordinary units wait until every setup for this target has finished. + // Ordinary units wait until every setup for this target has finished, + // and for the targets their peers restore a session from. if (this.hasPendingSetup(state)) return undefined; - return state.fileQueue[0]; + const next = state.fileQueue[0]; + if (next !== undefined && this.peerSetupTargets(next).some((target) => this.hasPendingSetup(target))) return undefined; + return next; + } + + /** The targets whose setups save a session one of `unit`'s peers restores. */ + private peerSetupTargets(unit: WorkUnit): TargetState[] { + const names = new Set(); + for (const pair of unit.pairs) { + for (const peer of pair.options.peers) { + if (peer.session !== undefined) names.add(peerTarget(peer, pair)); + } + } + return [...names].flatMap((name) => { + const state = this.targets.get(name); + return state === undefined ? [] : [state]; + }); } /** @@ -735,16 +771,21 @@ class Scheduler { else state.fileQueue.unshift(unit); } - /** Skip info when a pair's session was not produced by a passing setup. */ - private dependencySkip( - state: TargetState, - pair: TestTargetPair, - ): ReturnType | undefined { - const session = pair.options.session; - if (session === undefined) return undefined; - const failedSetup = state.failedSessions.get(session); - if (failedSetup === undefined) return undefined; - return setupFailedSkip(session, failedSetup); + /** Skip info when a pair's session was not produced by a passing setup, or a peer's target is unavailable. */ + private dependencySkip(state: TargetState, pair: TestTargetPair): SkipInfo | undefined { + const own = pair.options.session; + const failedOwn = own === undefined ? undefined : state.failedSessions.get(own); + if (own !== undefined && failedOwn !== undefined) return setupFailedSkip(own, failedOwn); + for (const peer of pair.options.peers) { + const peerState = this.targets.get(peerTarget(peer, pair)); + // A peer's app runs on its own target, whose app or workers may be gone. + if (peerState?.unavailable !== undefined) return peerState.unavailable.skip; + // A peer's session comes from its own target's setup, which may have failed there. + if (peer.session === undefined) continue; + const failedPeer = peerState?.failedSessions.get(peer.session); + if (failedPeer !== undefined) return setupFailedSkip(peer.session, failedPeer); + } + return undefined; } // --- workers --- diff --git a/packages/e2e/src/run/screenshots.ts b/packages/e2e/src/run/screenshots.ts index 0d236c4933..9ff59cb99b 100644 --- a/packages/e2e/src/run/screenshots.ts +++ b/packages/e2e/src/run/screenshots.ts @@ -39,6 +39,14 @@ export interface ScreenshotContextOptions { readonly titlePath: readonly string[]; readonly written: WrittenScreenshots; readonly artifacts: ArtifactSink; + /** The peer the screenshots are of; absent for the test's own user. */ + readonly user?: ScreenshotUser | undefined; +} + +/** A peer whose screenshots these are: its name, and the target of the test that brought it. */ +export interface ScreenshotUser { + readonly name: string; + readonly ownerTarget: string; } /** @@ -71,11 +79,17 @@ export class WrittenScreenshots { } } -/** The screenshot context of one attempt: beside the test file, one file per target and operating system. */ +/** + * The screenshot context of one attempt: beside the test file, one file per + * target and operating system. A peer's are in `peers//` + * there, so two users' screenshots of one name never share a file, nor do one + * peer's in two pairs of the test on two targets. + */ export function createScreenshotContext(options: ScreenshotContextOptions): ScreenshotContext { + const directory = path.join(options.projectRoot, `${options.file}-snapshots`); return { projectRoot: options.projectRoot, - directory: path.join(options.projectRoot, `${options.file}-snapshots`), + directory: options.user === undefined ? directory : path.join(directory, 'peers', options.user.ownerTarget, options.user.name), suffix: `-${options.targetName}-${process.platform}`, titlePath: options.titlePath, update: options.update, diff --git a/packages/e2e/src/run/secrecy.ts b/packages/e2e/src/run/secrecy.ts index d01d04afad..7af41a547c 100644 --- a/packages/e2e/src/run/secrecy.ts +++ b/packages/e2e/src/run/secrecy.ts @@ -130,6 +130,16 @@ export function sessionLedger( return ledger; } +/** + * Makes `session` redact with `owner`'s ledger from now on, so every user + * of one attempt redacts every value any of them has seen: a secret typed on + * one user's screen and shown on another's never reaches the second user's + * model input. Called before `session` resolves or restores anything. + */ +export function shareSessionLedger(session: TargetSession, owner: TargetSession, secrets: ResolvedConfig['allSecrets']): void { + ledgerBySession.set(session, sessionLedger(owner, secrets)); +} + /** * Redacts `text` with every value `session` has seen, or with the static * values while no session is open yet, so text an attempt produces before diff --git a/packages/e2e/src/run/standalone-test.ts b/packages/e2e/src/run/standalone-test.ts index 9dcd75bb54..c1db83edc6 100644 --- a/packages/e2e/src/run/standalone-test.ts +++ b/packages/e2e/src/run/standalone-test.ts @@ -83,7 +83,8 @@ export async function selectStandaloneTest( graph: string | undefined, ): Promise { const collection = await collectAlone(() => collect(config, [positional], graph)); - const { pairs } = select(collection, config, { targetIds: [target.name] }, { noTestsHint: 'name a test file the config finds, alone when it holds one test, or with :line on the line its test( call is on, not a line inside the test' }); + // A session refuses a test with peers below, so selection leaves their targets to that refusal. + const { pairs } = select(collection, config, { targetIds: [target.name] }, { noTestsHint: 'name a test file the config finds, alone when it holds one test, or with :line on the line its test( call is on, not a line inside the test', peersRefused: true }); // A serial group's other members run beside a selected one; only what the positional named counts. const runnable = pairs.filter((pair) => pair.disposition === 'run' && pair.test.kind === 'test' && pair.test.selected); const tests = [...new Map(runnable.map((pair) => [pair.test.id, pair.test])).values()]; @@ -104,6 +105,10 @@ export async function selectStandaloneTest( if (pair.options.session !== undefined) { throw unsupported(`${named} starts from session "${pair.options.session}", which a setup test saves first; a session does not run setup tests yet, so run it with npx e2e run`); } + if (pair.options.peers.length > 0) { + const peers = pair.options.peers.map((peer) => `"${peer.name}"`).join(', '); + throw unsupported(`${named} runs peers ${peers}, each on an app of its own; a session drives one app, so run it with npx e2e run`); + } if (otherAgents.length > 0) { const agents = [pair, ...otherAgents].map((each) => `"${each.agent}"`).join(', '); throw unsupported(`${named} runs as agents ${agents}; a session runs one, so run it with npx e2e run`); diff --git a/packages/e2e/src/run/step-hold.ts b/packages/e2e/src/run/step-hold.ts index 57c64baf5f..e1bd0c423d 100644 --- a/packages/e2e/src/run/step-hold.ts +++ b/packages/e2e/src/run/step-hold.ts @@ -23,6 +23,8 @@ export interface HeldStep { /** Already redacted. */ readonly label: string; readonly source?: SourceLocation; + /** The peer whose app the step runs on; absent for the test's own user. */ + readonly user?: string; } /** A held step with its place among its test's held steps, from 1. */ diff --git a/packages/e2e/src/run/steps.ts b/packages/e2e/src/run/steps.ts index 1b26c436d7..ba2e9f6537 100644 --- a/packages/e2e/src/run/steps.ts +++ b/packages/e2e/src/run/steps.ts @@ -215,6 +215,8 @@ export interface StepRecord { model?: StepModelInfo; /** The configured agent an agent step ran with, by name. */ agent?: string; + /** The peer whose app the step ran on, by name (the `peers` option); absent for the test's own user. */ + user?: string; /** The hook the step ran in; absent for a step of the test body. */ phase?: StepPhase; /** How the last screen the step saw differs from the step before's; absent when it saw none. */ @@ -240,6 +242,8 @@ interface StepProgressIdentity { readonly attemptIndex: number; readonly stepId: string; readonly stepIndex: number; + /** The peer whose app the step runs on; absent for the test's own user. */ + readonly user?: string; } /** One progress payload before the recorder attaches its identity. */ @@ -292,6 +296,38 @@ export interface StepRunOptions { readonly verifies?: boolean; /** The configured agent an agent step runs with, recorded on the step. */ readonly agent?: string | undefined; + /** The peer whose app the step runs on; a step inside another runs on that one's. Set by `StepRecorder.forUser`. */ + readonly user?: string | undefined; +} + +/** + * What fixtures record steps through: the attempt's recorder itself for the + * test's own user, or `forUser`'s view of it for a peer, which marks every + * step it opens as the peer's. + */ +export type StepSink = Pick< + StepRecorder, + | 'run' + | 'recordEvent' + | 'activity' + | 'attachAgentDetails' + | 'attachArtifact' + | 'attachViewport' + | 'redactText' + | 'replaying' + | 'completed' + | 'currentStepId' + | 'currentStepIndex' +>; + +/** + * The agent a peer runs as and its app's target, as `forUser` takes them. + * Declared here, not imported from the AI trace module, whose declarations + * import the optional `ai` package: this one is on the public types. + */ +interface PeerTraceIdentity { + readonly agent: string; + readonly target: string; } export interface StepRecorderOptions { @@ -322,6 +358,8 @@ export interface StepHoldRequest { /** Already redacted. */ readonly label: string; readonly source?: SourceLocation; + /** The peer whose app the step runs on; absent for the test's own user. */ + readonly user?: string; } /** A step call waiting at its hold, kept so a body that returns without awaiting it still fails as `STEP_NOT_AWAITED`. */ @@ -366,6 +404,8 @@ export interface AppLogRecord { readonly level: AppLogEntry['level']; readonly text: string; readonly at: string; + /** The peer whose app logged it, by name; absent for the test's own user's app. */ + readonly user?: string; readonly step?: number; } /** Characters of an event's detail the report admits. */ @@ -399,17 +439,19 @@ export class StepRecorder { /** The promises of abandoned steps, for the wait before teardown. */ private readonly abandonedPromises: Promise[] = []; /** The index every step before which a passed verification proves, or -1 when none has passed. */ - private lastVerified = -1; + private readonly lastVerifiedBy = new Map(); /** What the app logged this attempt, within `APP_LOG_LIMITS`. */ private readonly logged: AppLogRecord[] = []; - /** App log entries of each kind `APP_LOG_LIMITS` counts, kept so far. */ - private readonly loggedCounts = { errorsAndWarnings: 0, info: 0 }; + /** App log entries of each kind `APP_LOG_LIMITS` counts, kept so far, by user: each user's app has its own limit. */ + private readonly loggedCounts = new Map(); /** The last screen each running step saw, read only when the step ends. */ private readonly seenScreens = new Map ScreenText | undefined>(); - /** The last screen a finished step saw, the one the next step's is compared with. */ - private lastScreen: { readonly step: number; readonly screen: ScreenText } | undefined; - /** Where the app went before the attempt's first step, told under it once it starts. */ - private readonly earlyNavigations: { line: string; at: string }[] = []; + /** The last screen each user's finished step saw, the one that user's next step's is compared with; the test's own user is `undefined`. */ + private readonly lastScreens = new Map(); + /** Where each user's app went before that user's first step, told under it once it starts. */ + private readonly earlyNavigations = new Map(); + /** Each peer's agent and target, by name, which its steps' model calls are attributed to. */ + private readonly users = new Map(); private readonly maxEventsPerStep: number; private readonly onProgress: ((progress: StepProgress) => void) | undefined; private readonly projectRoot: string | undefined; @@ -447,7 +489,16 @@ export class StepRecorder { /** The index every step before which a passed verification proves, or -1 when none has passed. */ get lastVerifiedStepIndex(): number { - return this.lastVerified; + return this.lastVerifiedStepIndexOf(undefined); + } + + /** + * The same for one user's steps: a peer's passing check proves only what + * the peer's own steps before it left, never another user's, so each + * user's staged recordings are confirmed by that user's checks alone. + */ + lastVerifiedStepIndexOf(user: string | undefined): number { + return this.lastVerifiedBy.get(user) ?? -1; } /** Runs one public API call as a recorded top-level step. */ @@ -481,7 +532,8 @@ export class StepRecorder { this.held.add(call); const promise = (async () => { try { - await hold({ api: call.api, label: call.label, ...(source === undefined ? {} : { source }) }, call.cancel.signal); + const user = call.options.user; + await hold({ api: call.api, label: call.label, ...(source === undefined ? {} : { source }), ...(user === undefined ? {} : { user }) }, call.cancel.signal); // Released in the same turn the body abandoned it: it must not run. call.cancel.signal.throwIfAborted(); } catch (cause) { @@ -511,14 +563,15 @@ export class StepRecorder { // A verification run inside another step (an `onAction` hook's) proves // only what the steps before that one left, never the step still running. const verifiesBefore = parent?.index ?? this.steps.length; - const record = this.open(kind, api, label, stack, options); + // Each user's steps name it: a peer's come through its own sink, so one the test's own code runs inside a peer's step stays the test's. + const record = this.open(kind, api, label, stack, options, options.user); const promise = this.execute(record, body, options, verifiesBefore); this.pending.set(record.id, promise); return promise; } /** Records a step as started now and tells reporters. */ - private open(kind: StepKind, api: string, label: string, stack: string | undefined, options: StepRunOptions): StepRecord { + private open(kind: StepKind, api: string, label: string, stack: string | undefined, options: StepRunOptions, user: string | undefined): StepRecord { const index = this.steps.length; const startedAt = timestamp(); const source = sourceLocation(stack, this.projectRoot); @@ -534,12 +587,13 @@ export class StepRecorder { durationMs: 0, events: [], ...(options.agent === undefined ? {} : { agent: options.agent }), + ...(user === undefined ? {} : { user }), ...(this.phase === undefined ? {} : { phase: this.phase }), artifacts: [], }; this.steps.push(record); this.running.add(record.id); - for (const { line, at } of this.earlyNavigations.splice(0)) this.fileNavigation(record, line, at); + for (const { line, at } of this.earlyNavigations.get(user)?.splice(0) ?? []) this.fileNavigation(record, line, at); if (stack !== undefined) this.stacks.set(record.id, stack); this.publish(record, { phase: 'start', kind, api, label }); return record; @@ -549,11 +603,12 @@ export class StepRecorder { const startedMs = Date.now(); try { // Model calls made inside the body are attributed to this step. - const work = this.scope.run(record, () => withAiTraceStep(record.api, record.label, body)); + const user = record.user === undefined ? undefined : { name: record.user, ...this.users.get(record.user)! }; + const work = this.scope.run(record, () => withAiTraceStep(record.api, record.label, body, user)); const result = await (this.signal === undefined ? work : withAbort(work, this.signal, () => new TestError('CANCELLED', `${record.api} cancelled`))); if (this.abandoned.has(record.id)) return result; record.durationMs = Date.now() - startedMs; - if (options.verifies === true) this.lastVerified = Math.max(this.lastVerified, verifiesBefore); + if (options.verifies === true) this.lastVerifiedBy.set(record.user, Math.max(this.lastVerifiedStepIndexOf(record.user), verifiesBefore)); return result; } catch (cause) { if (this.abandoned.has(record.id)) { @@ -600,7 +655,7 @@ export class StepRecorder { const held = [...this.held].map((call) => { this.held.delete(call); call.cancel.abort(); - const record = this.open(call.kind, call.api, call.label, call.stack, call.options); + const record = this.open(call.kind, call.api, call.label, call.stack, call.options, call.options.user); this.pending.set(record.id, call.promise); return record; }); @@ -659,11 +714,11 @@ export class StepRecorder { * when none is running. The running step wins so a step that ran a nested * step (a fixture call that clicked a link, say) still owns what it produced. */ - attachArtifact(artifactId: string): void { - // Cleanup outside a scope may attach to the last step. Work inherited - // from a closed scope must never attach to a newer step. + attachArtifact(artifactId: string, user?: string): void { + // Cleanup outside a scope may attach to the last step, of the user whose + // app made it. Work inherited from a closed scope must never attach to a newer step. const target = this.scope.getStore() === undefined - ? this.steps[this.steps.length - 1] + ? this.steps.findLast((step) => step.user === user) : this.current(); if (target !== undefined) target.artifacts.push(artifactId); } @@ -683,23 +738,29 @@ export class StepRecorder { * attempt's app log (`appLog`), within `APP_LOG_LIMITS`; where the app went * is an event of the step, and one before the first step waits for it. */ - recordAppEvent(event: AppEvent, at: string = timestamp()): void { - const target = this.current() ?? this.steps.at(-1); + recordAppEvent(event: AppEvent, at: string = timestamp(), user?: string): void { + // Each user's app reports on its own: what it did lands with that user's steps. + const running = this.current(); + const target = running !== undefined && running.user === user ? running : this.steps.findLast((step) => step.user === user); if (event.kind === 'navigation') { if (target === undefined) { + const waiting = this.earlyNavigations.get(user) ?? []; // A step takes no more events than this, so no more wait for one. - if (this.earlyNavigations.length < this.maxEventsPerStep) this.earlyNavigations.push({ line: event.line, at }); + if (waiting.length < this.maxEventsPerStep) waiting.push({ line: event.line, at }); + this.earlyNavigations.set(user, waiting); } else this.fileNavigation(target, event.line, at); return; } const { entry } = event; const counted = entry.level === 'info' ? 'info' : 'errorsAndWarnings'; - if (this.loggedCounts[counted] >= APP_LOG_LIMITS[counted]) return; - this.loggedCounts[counted] += 1; + const counts = this.loggedCounts.get(user) ?? { errorsAndWarnings: 0, info: 0 }; + if (counts[counted] >= APP_LOG_LIMITS[counted]) return; + counts[counted] += 1; + this.loggedCounts.set(user, counts); // Redacted before it is cut, so no cut leaves the head of a secret behind. const text = bound(this.redactText(entry.text.replace(/\s+/g, ' ').trim()), MAX_EVENT_DETAIL_CHARS); - this.logged.push({ source: entry.source, level: entry.level, text, at, ...(target === undefined ? {} : { step: target.index }) }); + this.logged.push({ source: entry.source, level: entry.level, text, at, ...(target === undefined ? {} : { step: target.index }), ...(user === undefined ? {} : { user }) }); } /** What the app logged this attempt, oldest first. */ @@ -730,8 +791,8 @@ export class StepRecorder { return; } if (screen === undefined) return; - record.screen = compareScreens(this.lastScreen, screen); - this.lastScreen = { step: record.index, screen }; + record.screen = compareScreens(this.lastScreens.get(record.user), screen); + this.lastScreens.set(record.user, { step: record.index, screen }); } private fileNavigation(target: StepRecord, line: string, at: string): void { @@ -808,6 +869,36 @@ export class StepRecorder { return this.steps.filter((step) => !this.running.has(step.id)); } + /** + * The recorder as one peer's fixtures see it: every step they open is the + * peer's, on the attempt's one timeline, and the steps it reads back as + * completed are the peer's alone. `as` is the agent the peer runs as and + * its app's target, which its steps' model calls are attributed to. + */ + forUser(user: string, as: PeerTraceIdentity): StepSink { + this.users.set(user, as); + // The view's getters have the view as `this`; these read the recorder's running step. + const runningId = (): string | undefined => this.currentStepId; + const runningIndex = (): number | undefined => this.currentStepIndex; + return { + run: (kind, api, label, body, options = {}) => this.run(kind, api, label, body, { ...options, user }), + recordEvent: (event) => this.recordEvent(event), + activity: (activity) => this.activity(activity), + attachAgentDetails: (details) => this.attachAgentDetails(details), + attachArtifact: (artifactId) => this.attachArtifact(artifactId, user), + attachViewport: (viewport) => this.attachViewport(viewport), + redactText: (text) => this.redactText(text), + replaying: (active) => this.replaying(active), + completed: () => this.completed().filter((step) => step.user === user), + get currentStepId() { + return runningId(); + }, + get currentStepIndex() { + return runningIndex(); + }, + }; + } + private current(): StepRecord | undefined { const record = this.scope.getStore(); return record !== undefined && this.running.has(record.id) && !this.abandoned.has(record.id) ? record : undefined; @@ -822,6 +913,7 @@ export class StepRecorder { attemptIndex: this.attempt.index, stepId: record.id, stepIndex: record.index, + ...(record.user === undefined ? {} : { user: record.user }), }, }); } diff --git a/packages/e2e/src/run/test-filters.ts b/packages/e2e/src/run/test-filters.ts index 65ba6ff791..e180d14390 100644 --- a/packages/e2e/src/run/test-filters.ts +++ b/packages/e2e/src/run/test-filters.ts @@ -213,21 +213,26 @@ export function filterCandidates(selection: Selection): readonly TestFilterCandi for (const { test } of selection.pairs) { if (test.kind === 'setup') for (const session of test.sessions) producers.set(session, test.file); } - const tests = new Map(); + const tests = new Map(); for (const { test, options, disposition } of selection.pairs) { if (test.kind !== 'test' || disposition !== 'run' || tests.has(test.id)) continue; - tests.set(test.id, { test, setupFile: options.session === undefined ? undefined : producers.get(options.session) }); + const peerSetupFiles = [...new Set(options.peers.flatMap((peer) => { + const file = peer.session === undefined ? undefined : producers.get(peer.session); + return file === undefined ? [] : [file]; + }))]; + tests.set(test.id, { test, setupFile: options.session === undefined ? undefined : producers.get(options.session), peerSetupFiles }); } return Object.freeze( [...tests.values()] .toSorted((a, b) => compareTests(a.test, b.test)) - .map(({ test, setupFile }) => + .map(({ test, setupFile, peerSetupFiles }) => Object.freeze({ id: test.id, file: test.file, titlePath: Object.freeze([...test.titlePath]), tags: Object.freeze([...test.tags]), ...(setupFile === undefined ? {} : { setupFile }), + ...(peerSetupFiles.length === 0 ? {} : { peerSetupFiles: Object.freeze(peerSetupFiles) }), }), ), ); diff --git a/packages/e2e/src/run/worker/entry.ts b/packages/e2e/src/run/worker/entry.ts index 43589def81..466b812a67 100644 --- a/packages/e2e/src/run/worker/entry.ts +++ b/packages/e2e/src/run/worker/entry.ts @@ -9,7 +9,7 @@ import { collectFromRegistration } from '../../collect/collect.ts'; import { collectModule } from '../../collect/registry.ts'; import type { TestTargetPair } from '../../collect/select.ts'; import { importModule, loadConfigModule } from '../../config/load.ts'; -import { assignPorts, resolveConfig } from '../../config/resolve.ts'; +import { assignPorts, resolveConfig, type ResolvedConfig } from '../../config/resolve.ts'; import { setSecretRegistry } from '../../secrets.ts'; import { loadAiSdk } from '../../agent/ai-sdk.ts'; import { AiTraceRecorder, registerAiTraceRecorder } from '../../internal/ai-trace.ts'; @@ -153,19 +153,28 @@ async function bootstrap( if (aiTrace !== undefined) await registerAiTraceRecorder(aiTrace, loadAiSdk); // What the config's top-level code prints is held until its secrets are // registered, so it is redacted like a test's output. + /** + * One load of the config as the runner resolved it: its ports, and a digest + * that must match. `graph` loads the project files it imports afresh too, + * which a peer's engine needs to be an instance of its own. + */ + const loadResolved = async (options: { readonly graph: boolean }): Promise => { + const raw = await loadConfigModule(message.configPath, options.graph ? { graph: true } : {}); + const resolved = assignPorts( + resolveConfig(raw, { projectRoot: message.projectRoot, configPath: message.configPath, env: process.env, cli: message.cli }), + message.ports, + ); + if (resolved.configDigest !== message.configDigest) { + throw new ConfigurationError( + 'CONFIG_NOT_DETERMINISTIC', + 'worker resolved a different config digest than the runner; config must be deterministic', + ); + } + return resolved; + }; const { config, target } = await configLoad.during( async () => { - const raw = await loadConfigModule(message.configPath); - const resolved = assignPorts( - resolveConfig(raw, { projectRoot: message.projectRoot, configPath: message.configPath, env: process.env, cli: message.cli }), - message.ports, - ); - if (resolved.configDigest !== message.configDigest) { - throw new ConfigurationError( - 'CONFIG_NOT_DETERMINISTIC', - 'worker resolved a different config digest than the runner; config must be deterministic', - ); - } + const resolved = await loadResolved({ graph: false }); const named = resolved.targets.find((candidate) => candidate.name === message.targetName); if (named === undefined) { throw new ConfigurationError('UNKNOWN_TARGET', `unknown target "${message.targetName}"`); @@ -214,11 +223,13 @@ async function bootstrap( rerunDir: message.rerunDir, headed: message.headed, workerSlot: message.workerSlot, + peerSlots: message.peers, env: process.env, isolated: true, resolvePairs, debug, step: message.step, + loadPeerConfig: () => loadResolved({ graph: true }), }; } diff --git a/packages/e2e/src/run/worker/handle.ts b/packages/e2e/src/run/worker/handle.ts index f6f3e82992..15b48d695c 100644 --- a/packages/e2e/src/run/worker/handle.ts +++ b/packages/e2e/src/run/worker/handle.ts @@ -30,17 +30,19 @@ function resolveEntry(): { path: string; execArgv: string[] } { } /** Run-wide settings every child-process worker boots with. */ -export type ChildProcessSpawnOptions = Omit & { +export type ChildProcessSpawnOptions = Omit & { /** The environment each target's workers are spawned with. */ readonly envFor: (targetName: string) => NodeJS.ProcessEnv; + /** The slots a worker's tests' peers take on each peer target; see `WorkerBootstrap.peers`. */ + readonly peersFor: (targetName: string, workerSlot: number) => WorkerBootstrap['peers']; }; /** Creates the spawn factory the scheduler uses for child-process execution. */ export function childProcessSpawner(options: ChildProcessSpawnOptions): SpawnUnitRunner { - const { envFor, ...bootstrap } = options; + const { envFor, peersFor, ...bootstrap } = options; return (targetName, workerSlot, events) => new ChildProcessRunner( - { ...bootstrap, targetName, workerSlot }, + { ...bootstrap, targetName, workerSlot, peers: peersFor(targetName, workerSlot) }, { projectRoot: bootstrap.projectRoot, env: envFor(targetName) }, events, ); diff --git a/packages/e2e/src/run/worker/protocol.ts b/packages/e2e/src/run/worker/protocol.ts index 1fda59c95e..f59fa4060c 100644 --- a/packages/e2e/src/run/worker/protocol.ts +++ b/packages/e2e/src/run/worker/protocol.ts @@ -15,6 +15,7 @@ import type { DebugSnapshot } from '../../internal/debug.ts'; import type { SerializedError } from '../../internal/errors.ts'; import type { AttemptRecord, ResultRecord, RunError, SerialAttemptRecord, SerialGroupRecord, SerialMemberRecord, WireResultRecord } from '../records.ts'; import type { SerialAttemptStart } from '../serial.ts'; +import type { PeerSlots } from '../peer-slots.ts'; import type { HeldStep } from '../step-hold.ts'; import type { StepProgress } from '../steps.ts'; @@ -61,6 +62,12 @@ export interface WorkerBootstrap { readonly targetName: string; /** This worker's slot among the target's workers; see `EngineInitInfo.workerSlot`. */ readonly workerSlot: number; + /** + * The slots this worker's tests' peers take, by the peer's target: reserved + * for this worker alone when the targets were prepared, with what that + * target's `prepare` handed its own workers. Empty when its tests have no peers. + */ + readonly peers: Readonly>; readonly runId: string; readonly artifactsRoot: string; /** See `TargetExecutorOptions.rerunDir`. */ diff --git a/packages/e2e/src/run/worker/session.ts b/packages/e2e/src/run/worker/session.ts index b023c7250f..3857279709 100644 --- a/packages/e2e/src/run/worker/session.ts +++ b/packages/e2e/src/run/worker/session.ts @@ -13,6 +13,7 @@ import { DebugTrace } from '../../internal/debug.ts'; import { uuidv7 } from '../../internal/ids.ts'; import { abortError, cancelledError } from '../../internal/time.ts'; import { TargetExecutor, type InMemoryAttempts } from '../execute.ts'; +import type { PeerSlots } from '../peer-slots.ts'; import { encodeResult, type RunError } from '../records.ts'; import type { SessionStore } from '../sessions.ts'; import type { HeldStep } from '../step-hold.ts'; @@ -50,6 +51,8 @@ export interface TargetWorkerDeps { readonly headed: boolean; /** See `TargetExecutorOptions.workerSlot`. */ readonly workerSlot: number; + /** See `TargetExecutorOptions.peerSlots`. */ + readonly peerSlots?: Readonly> | undefined; /** See `TargetExecutorOptions.env`. */ readonly env: Readonly>; /** Whether the worker has a process of its own; see `TargetExecutorOptions.isolated`. */ @@ -60,6 +63,8 @@ export interface TargetWorkerDeps { readonly inMemory?: InMemoryAttempts | undefined; /** Whether steps wait for the runner's `step-release` (`e2e run --step`). */ readonly step?: boolean | undefined; + /** See `TargetExecutorOptions.loadPeerConfig`; only a child-process worker, which loaded a config file, has it. */ + readonly loadPeerConfig?: (() => Promise) | undefined; } /** Transport callbacks a target worker needs. */ @@ -117,12 +122,14 @@ export class TargetWorker { sessionStore: deps.sessionStore, headed: deps.headed, workerSlot: deps.workerSlot, + peerSlots: deps.peerSlots, env: deps.env, isolated: deps.isolated, interruptSignal: this.interruptController.signal, ...(deps.step === true ? { holdStep: (step: HeldStep, signal: AbortSignal) => this.holdStep(step, signal) } : {}), ...(deps.debug !== undefined ? { debug: deps.debug } : {}), inMemory: deps.inMemory, + loadPeerConfig: deps.loadPeerConfig, events: { onResult: (result) => { // Teardown after the result (an afterAll) belongs to no pair. diff --git a/packages/e2e/src/types.ts b/packages/e2e/src/types.ts index cdd84a6340..b89fa33176 100644 --- a/packages/e2e/src/types.ts +++ b/packages/e2e/src/types.ts @@ -715,6 +715,22 @@ export interface TestFixtures { readonly screen: Screen; /** The target's platform label: `web`, `ios`, `android`, or an engine's own string. */ readonly platform: string; + /** The test's peers by name (the `peers` option), each over an app of its own; empty when it declares none. */ + readonly peers: Readonly>; +} + +/** `Fixtures` with `peers` narrowed to the names a test declares; unchanged when it declares none. */ +type WithPeers = [Peers] extends [never] + ? Fixtures + : Omit & { readonly peers: { readonly [Name in keyof Peers]: PeerFixtures } }; + +/** + * One peer's fixtures: what the test's own user has, over the peer's app, and + * the fixtures the peer target's engine contributes (`browser` on a web + * target, `device` on a phone). + */ +export interface PeerFixtures extends Omit { + readonly [fixture: string]: unknown; } export interface SetupFixtures extends TestFixtures { @@ -727,6 +743,27 @@ export interface SuiteFixtures { readonly platform: string; } +/** + * One more user in a test: an app of its own, opened next to the test's, + * on the test's target or another one. The test reaches it as + * `peers.`. + */ +export interface PeerOptions { + /** The target the peer's app runs on; defaults to the test's own target. */ + target?: string; + /** + * A session a setup test saved on the peer's target, restored into the + * peer's app before the body runs. The peer's target must save and + * restore state, as for `session`; a device target cannot, so a device + * peer signs in during the test. + */ + session?: string; + /** The configured agent (`agents.`) the peer's `agent` runs with; defaults to the agent the test runs as. */ + agent?: string; + /** Extra context for the peer's agent steps. The test's own `agentContext` stays with the test's user. */ + agentContext?: string; +} + export interface TestOptions { /** Attempt deadline in milliseconds; defaults to `config.timeout`. Innermost wins. */ timeout?: number; @@ -750,6 +787,13 @@ export interface TestOptions { requires?: readonly Capability[]; /** Session a setup test saved, restored before the body runs. */ session?: string; + /** + * More users in the test, by name: each opens its own app before + * `beforeEach` runs, on the test's target or another one. Innermost wins, + * as a whole. Names are 1 through 128 ASCII letters, numbers, `_`, `-`, + * or `.`. Not allowed inside a serial group. + */ + peers?: Readonly>; /** Extra context for agent steps; layers are concatenated outermost first. */ agentContext?: string; /** @@ -781,7 +825,7 @@ export interface DescribeOptions extends Omit { serial?: boolean; } -export interface SetupOptions extends Omit { +export interface SetupOptions extends Omit { /** Session names this setup test MUST save. */ sessions: readonly string[]; /** A setup test runs once per target, so it pins at most one agent. */ @@ -815,8 +859,11 @@ export type FixtureFn = ( * type error (and a `COLLECTION_ERROR` at runtime). */ export type FixtureDefinitions = { - readonly [K in keyof Extra]: K extends keyof Base ? never : FixtureFn; + // `peers` stays open to a suite's own fixture, as it was before e2e had peers. + readonly [K in keyof Extra]: K extends Exclude ? never : FixtureFn; }; +/** `Fixtures` and `Extra` together; a suite's own `peers` replaces the core one for its tests, which then declare no peers. */ +type Extended = ('peers' extends keyof Extra ? Omit : Fixtures) & Extra; /** A `describe` body. An async body is a type error. */ export type SynchronousBody = Extract> extends never ? () => Result @@ -830,8 +877,17 @@ export interface TestCase { export interface TestAPI { /** Registers one test synchronously during module evaluation. */ (title: string, fn: TestFn): TestCase; - /** Registers one configured test synchronously during module evaluation. */ - (title: string, options: TestOptions, fn: TestFn): TestCase; + /** + * Registers one configured test synchronously during module evaluation. + * The names the test's own `peers` option declares type its `peers` + * fixture, so a peer it never declared is a type error; peers set on a + * `describe` are typed by any name. + */ + > = never>( + title: string, + options: TestOptions & { peers?: Peers }, + fn: TestFn>, + ): TestCase; /** Registers one skipped test. */ skip(title: string, fn: TestFn): TestCase; /** @@ -870,7 +926,7 @@ export interface TestAPI { * * export const test = base.extend<{ device: Device }>(); */ - extend(): TestAPI; + extend(): TestAPI>; /** * Returns a new `test` whose registrations carry these fixture * definitions on top of the ones it already had. Each attempt sets them up @@ -885,7 +941,7 @@ export interface TestAPI { * }, * }); */ - extend(fixtures: FixtureDefinitions): TestAPI; + extend(fixtures: FixtureDefinitions): TestAPI>; /** Declares a group synchronously. */ describe(title: string, body: SynchronousBody): void; /** Declares a configured group synchronously. */ @@ -1654,6 +1710,8 @@ export interface TestFilterCandidate { readonly tags: readonly string[]; /** Project-relative POSIX path of the setup test file that saves the test's session; absent when the test uses none. */ readonly setupFile?: string; + /** Project-relative POSIX paths of the setup test files that save its peers' sessions, each once, in peer order; absent when no peer restores one. */ + readonly peerSetupFiles?: readonly string[]; } /** What a run's test filters judge: every file that differs from the base commit. */ diff --git a/packages/e2e/tests/helpers/fake-engine.ts b/packages/e2e/tests/helpers/fake-engine.ts index 4b3783802a..316e7ef361 100644 --- a/packages/e2e/tests/helpers/fake-engine.ts +++ b/packages/e2e/tests/helpers/fake-engine.ts @@ -15,6 +15,8 @@ import type { EngineHandle, EngineInitInfo, EngineObserveOptions, + EnginePrepareInfo, + EnginePrepareResult, EngineState, LocatorAction, LocatorActionKind, @@ -81,6 +83,10 @@ export interface RecordedSessionCall { export type RecordedCall = RecordedPerform | RecordedPointerAction | RecordedKey | RecordedSessionCall; export interface FakeEngineBehavior { + /** Declares `prepare`: what it returns is the engine's answer, a count of slots it serves and variables for its workers. */ + prepare?(info: EnginePrepareInfo): EnginePrepareResult | void | Promise; + /** Declares `workers`: the most the engine serves at once, known before `prepare`. */ + workers?: number; /** Throw to fail worker boot. Called before any attempt. */ onInit?(info: EngineInitInfo): void | Promise; /** Throw or hang to fail attempt launches. */ @@ -248,6 +254,8 @@ export function createFakeEngine(behavior: FakeEngineBehavior = {}): FakeEngineH name: 'fake', version: '1.0.0', spiVersion: ENGINE_SPI_VERSION, + ...(behavior.workers === undefined ? {} : { workers: behavior.workers }), + ...(behavior.prepare === undefined ? {} : { prepare: async (info: EnginePrepareInfo) => behavior.prepare!(info) }), async init(info) { events.push('init'); inits.push(info); diff --git a/packages/e2e/tests/integration/app-command-exit.test.ts b/packages/e2e/tests/integration/app-command-exit.test.ts index ab9af9c285..0a274221b4 100644 --- a/packages/e2e/tests/integration/app-command-exit.test.ts +++ b/packages/e2e/tests/integration/app-command-exit.test.ts @@ -350,6 +350,74 @@ test('queued test', async ({ app }) => { } }); + it("reports an exit of a target that only hosts peers, and skips the queued tests that put a peer there", async () => { + const portA = await freePort(); + const portB = await freePort(); + const target = (name: string, platform: string, port: number) => `{ + name: '${name}', platform: '${platform}', engine: createFakeEngine().engine, + app: { url: 'http://127.0.0.1:${port}', command: { + executable: ${JSON.stringify(process.execPath)}, + args: ['server.cjs', '${port}', '1', '${name}-'], + log: '.e2e/logs/${name}-app.log', + shutdownTimeout: 1000, + } }, + }`; + const project = createProject({ + 'server.cjs': SERVER, + // Target b runs no test of its own: a test on a puts its peer there. + 'e2e.config.ts': `import type { E2EConfig } from 'e2e'; +import { createFakeEngine } from '../../helpers/fake-engine.ts'; +export default { + workers: 1, + timeout: 10000, + cleanupTimeout: 2000, + targets: [${target('a', 'fake', portA)}, ${target('b', 'other', portB)}], +} satisfies E2EConfig; +`, + 'tests/1-first.e2e.ts': `import { existsSync, writeFileSync } from 'node:fs'; +import { test } from 'e2e'; +${WAIT_FOR_FILE} +test('first', { platforms: ['fake'], peers: { ava: { target: 'b' } } }, async () => { + writeFileSync('b-exit-now', 'requested'); + await waitForFile('app-exit-observed'); +});`, + 'tests/2-second.e2e.ts': `import { writeFileSync } from 'node:fs'; +import { test } from 'e2e'; +test('second', { platforms: ['fake'], peers: { ava: { target: 'b' } } }, async () => { + writeFileSync('second-ran', 'ran'); +});`, + 'tests/3-own.e2e.ts': `import { writeFileSync } from 'node:fs'; +import { test } from 'e2e'; +test('own', { platforms: ['fake'] }, async () => { + writeFileSync('own-ran', 'ran'); +});`, + }); + try { + const outcome = await runExistingWithConfigFile(project, { + runOptions: { + onEvent(event) { + if (event.type === 'run-error' && event.error.code === 'APP_UNREACHABLE') { + writeFileSync(path.join(project.dir, 'app-exit-observed'), 'observed'); + } + }, + }, + }); + expect.soft(outcome.report.run.errors).toEqual([ + expect.objectContaining({ code: 'APP_UNREACHABLE', message: expect.stringContaining('target "b" command exited with code 1') }), + ]); + const status = (title: string) => outcome.results.find((result) => result.test.title === title && result.target.name === 'a'); + expect.soft(status('first')?.status).toBe('passed'); + expect.soft(status('second')?.status).toBe('skipped'); + expect.soft(status('second')?.skip).toMatchObject({ cause: 'infrastructure-unavailable', reason: expect.stringContaining('target "b" command exited with code 1') }); + expect.soft(existsSync(path.join(project.dir, 'second-ran'))).toBe(false); + expect.soft(status('own')?.status).toBe('passed'); + expect.soft(outcome.exitCode).toBe(3); + assertValidReport(outcome.report); + } finally { + project.cleanup(); + } + }); + it('stops every target sharing the exited command and starts that command only once', async () => { const port = await freePort(); const project = createProject({ diff --git a/packages/e2e/tests/integration/mcp-test-run.test.ts b/packages/e2e/tests/integration/mcp-test-run.test.ts index b6f3bccebd..266312321d 100644 --- a/packages/e2e/tests/integration/mcp-test-run.test.ts +++ b/packages/e2e/tests/integration/mcp-test-run.test.ts @@ -217,6 +217,7 @@ describe('open_session {test}', { timeout: 120_000 }, () => { 'tests/visual.e2e.ts': VISUAL, 'tests/expected.e2e.ts': EXPECTED, 'tests/marked-hooks.e2e.ts': MARKED_HOOKS, + 'tests/pair.e2e.ts': `import { test } from 'e2e';\ntest('with a peer', { peers: { ava: {}, bob: {} } }, async () => {});\n`, }); const transport = new StdioClientTransport({ command: process.execPath, @@ -378,16 +379,20 @@ describe('open_session {test}', { timeout: 120_000 }, () => { ); expect(await refused('tests/others.e2e.ts:12')).toMatch(/^SESSION_TEST_UNSUPPORTED: test "flow › step one" \(tests\/others\.e2e\.ts:12\) is in a serial group/); expect(await refused('tests/others.e2e.ts:17')).toMatch(/^SESSION_TEST_UNSUPPORTED: test "signed in" \(tests\/others\.e2e\.ts:17\) starts from session "member"/); + expect(await refused('tests/pair.e2e.ts')).toBe( + 'SESSION_TEST_UNSUPPORTED: test "with a peer" (tests/pair.e2e.ts:2) runs peers "ava", "bob", each on an app of its own; a session drives one app, so run it with npx e2e run', + ); expect((await invoke('close_session')).text).toBe('No session is open.'); }); }); /** An in-process host whose sessions load `config` on the fixture app, as the project's config file would. */ - const inProcessHost = (project: FixtureProject, config: Omit = {}) => + // `targets` is called on every load, so each session gets engines of its own, as a config file's load does. + const inProcessHost = (project: FixtureProject, config: Omit = {}, targets = () => [webTarget('web', app.url)]) => new SessionHost({ locateConfig: () => path.join(project.dir, 'e2e.config.ts'), loadConfig: async (configPath) => ({ - ...resolveConfig({ ...config, targets: [webTarget('web', app.url)] } as E2EConfig as never, { projectRoot: project.dir, env: {}, configPath }), + ...resolveConfig({ ...config, targets: targets() } as E2EConfig as never, { projectRoot: project.dir, env: {}, configPath }), configPath, }), loadEngineConfig: () => Promise.reject(new Error('these sessions open on the config')), @@ -396,6 +401,25 @@ describe('open_session {test}', { timeout: 120_000 }, () => { log: () => undefined, }); + describe('a test with a peer on another target', () => { + let project: FixtureProject; + + beforeAll(() => { + project = createProject({ + 'tests/pair.e2e.ts': `import { test } from 'e2e';\ntest('with a peer elsewhere', { peers: { ava: { target: 'admin' } } }, async () => {});\n`, + }); + }); + afterAll(() => project.cleanup()); + + it('is refused as a test a session cannot run, not as a run that left its target out', async () => { + const sessions = inProcessHost(project, {}, () => [webTarget('web', app.url), webTarget('admin', app.url)]); + await expect(sessions.open({ test: 'tests/pair.e2e.ts', target: 'web' })).rejects.toMatchObject({ + code: 'SESSION_TEST_UNSUPPORTED', + message: 'test "with a peer elsewhere" (tests/pair.e2e.ts:2) runs peers "ava", each on an app of its own; a session drives one app, so run it with npx e2e run', + }); + }); + }); + describe('the replay cache', () => { const counter = FLOWS.find((flow) => flow.title === 'increments the counter')!; let project: FixtureProject; diff --git a/packages/e2e/tests/integration/peers.test.ts b/packages/e2e/tests/integration/peers.test.ts new file mode 100644 index 0000000000..8aa08a11e6 --- /dev/null +++ b/packages/e2e/tests/integration/peers.test.ts @@ -0,0 +1,1963 @@ +/** + * Peers: more users in one test, each with an app of its own. These run the + * built runner end to end on fixture projects: the web cases on a real + * Chromium through child workers, which load the config a second time for + * a peer's engine, and the lifecycle cases on the fake engine. + */ + +import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'; +import path from 'node:path'; +import { fileURLToPath, pathToFileURL } from 'node:url'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { createFakeEngine, FAKE_APP } from '../helpers/fake-engine.ts'; +import { startFixtureApp, type FixtureApp } from '../helpers/fixture-app.ts'; +import type { HeldStep } from '../../src/run/step-hold.ts'; +import { assertValidReport } from '../helpers/report-schema.ts'; +import { REFUSAL_EXPLANATION } from '../helpers/unserved-copilot-model.ts'; +import { + listProject, + resultByTitle, + runExistingWithConfigFile, + runProject, + runProjectWithConfigFile, + workerConfigSource, + type RunOutcome, +} from '../helpers/run-project.ts'; + +/** A web-like target and a second one a peer can run on, each with a fake engine that saves state. */ +const TARGETS = [ + { name: 'fake', platform: 'fake', engine: createFakeEngine({ state: true }).engine, app: FAKE_APP }, + { name: 'phone', platform: 'phone', engine: createFakeEngine({ state: true }).engine, app: FAKE_APP }, +]; +const AGENTS = { default: {}, buyer: {}, ava: { context: 'You are Ava.' } }; +/** The built engine API by file URL, which a package in a fixture project can import without resolving `e2e`. */ +const BUILT_ENGINE_API = pathToFileURL(path.resolve(fileURLToPath(import.meta.url), '..', '..', '..', 'dist', 'engine', 'index.js')).href; + +/** The only result's first attempt, with the run errors for a readable failure. */ +function onlyAttempt(outcome: RunOutcome, title: string) { + const result = resultByTitle(outcome, title); + return { result, attempt: result.attempts[0]!, why: JSON.stringify({ errors: result.attempts.map((attempt) => attempt.error), run: outcome.report.run.errors }) }; +} + +describe('peers: declared and listed', () => { + it('lists each pair peers with the target each runs on and the agent each runs as', async () => { + const files = { + 'tests/auth.setup.e2e.ts': `import { test } from 'e2e'; +test.setup('sign in', { sessions: ['member', 'ava'] }, async () => {}); +`, + 'tests/pay.e2e.ts': `import { test } from 'e2e'; +test('pays', { platforms: ['fake'], session: 'member', peers: { ava: { target: 'phone', session: 'ava', agent: 'ava' }, bob: {} }, agent: ['buyer', 'ava'] }, async () => {}); +test('alone', { platforms: ['fake'] }, async () => {}); +`, + }; + const { pairs, project } = await listProject(files, { config: { targets: TARGETS, agents: AGENTS } }); + try { + const pays = pairs.filter((pair) => pair.title === 'pays' && pair.target === 'fake'); + expect(pays.map((pair) => [pair.agent, pair.peers])).toEqual([ + ['buyer', [{ name: 'ava', target: 'phone', session: 'ava', agent: 'ava' }, { name: 'bob', target: 'fake', session: undefined, agent: 'buyer' }]], + ['ava', [{ name: 'ava', target: 'phone', session: 'ava', agent: 'ava' }, { name: 'bob', target: 'fake', session: undefined, agent: 'ava' }]], + ]); + expect(pairs.find((pair) => pair.title === 'alone')).not.toHaveProperty('peers'); + // The setup that saves Ava's session runs on her target as well as the test's own. + expect(pairs.filter((pair) => pair.kind === 'setup' && pair.disposition === 'run').map((pair) => pair.target).toSorted()).toEqual(['fake', 'phone']); + } finally { + project.cleanup(); + } + }); +}); + +describe('peers on one web target', () => { + let app: FixtureApp; + beforeAll(async () => { + app = await startFixtureApp(); + }); + afterAll(async () => { + await app.close(); + }); + const run = (files: Readonly>, extra = '') => + runProjectWithConfigFile(files, { appUrl: app.url, configSource: workerConfigSource(1, extra) }); + + it('gives each user an app of its own: what one adds on the server the other sees, and their browser state stays apart', async () => { + const { outcome, project } = await run({ + 'tests/pair.e2e.ts': `import { test, expect } from 'e2e'; +test('pair', { peers: { ava: {} } }, async ({ app, screen, peers }) => { + await app.open('/todos'); + await screen.getByLabel('New todo').fill('Oat milk'); + await screen.getByRole('button', 'Add').tap(); + await expect(screen.getByRole('status', 'Result')).toHaveText('added'); + await peers.ava.app.open('/todos'); + await expect(peers.ava.screen.getByText('Oat milk')).toBeVisible(); + + await peers.ava.app.open('/storage'); + await peers.ava.screen.getByRole('button', 'Save marker').tap(); + await expect(peers.ava.screen.getByRole('status', 'Marker')).toHaveText('saved'); + await app.open('/storage'); + await expect(screen.getByRole('status', 'Marker')).toHaveText('empty'); + + // Each user has its engine's own fixtures, on its own page. + await expect(peers.ava.browser).toHaveURL('/storage'); + expect(peers.ava.platform).toBe('web'); + expect(Object.keys(peers)).toEqual(['ava']); + let refused = ''; + try { + void peers.bob; + } catch (error) { + refused = (error as Error).message; + } + if (!refused.startsWith('the test declares no peer "bob"; it declares "ava"')) throw new Error('an undeclared peer gave: ' + refused); + // Probing the map as a promise does, or as an inspector does, is not asking for a peer. + if ((await Promise.resolve(peers)) !== peers) throw new Error('awaiting the peers changed them'); +}); +`, + }); + try { + const { result, why } = onlyAttempt(outcome, 'pair'); + expect(result.status, why).toBe('passed'); + } finally { + project.cleanup(); + } + }); + + it('restores each user its own saved session', async () => { + const { outcome, project } = await run({ + 'tests/auth.setup.e2e.ts': `import { test, expect } from 'e2e'; +test.setup('sign in both', { sessions: ['member', 'ava'] }, async ({ app, screen, session }) => { + await app.open('/storage'); + await session.save('ava'); + await screen.getByRole('button', 'Save marker').tap(); + await expect(screen.getByRole('status', 'Marker')).toHaveText('saved'); + await session.save('member'); +}); +`, + 'tests/pair.e2e.ts': `import { test, expect } from 'e2e'; +test('signed in', { session: 'member', peers: { ava: { session: 'ava' }, guest: {} } }, async ({ app, screen, peers }) => { + await app.open('/storage'); + await expect(screen.getByRole('status', 'Marker')).toHaveText('saved'); + await peers.ava.app.open('/storage'); + await expect(peers.ava.screen.getByRole('status', 'Marker')).toHaveText('empty'); + await peers.guest.app.open('/storage'); + await expect(peers.guest.screen.getByRole('status', 'Marker')).toHaveText('empty'); +}); +`, + }); + try { + const { result, why } = onlyAttempt(outcome, 'signed in'); + expect(result.status, why).toBe('passed'); + } finally { + project.cleanup(); + } + }); + + it('hands peers to beforeEach, afterEach, and test.extend fixtures, and runs both users at once', async () => { + const { outcome, project } = await run({ + 'tests/pair.e2e.ts': `import { test as base, expect } from 'e2e'; +const test = base.extend<{ avaOnTodos: string }>({ + avaOnTodos: async ({ peers }, use) => { + await peers.ava.app.open('/todos'); + await use('ready'); + await peers.ava.app.open('/storage'); + }, +}); +test.beforeEach(async ({ peers }) => { + await expect(peers.ava.screen.getByRole('heading', 'Todos')).toBeVisible(); +}); +test.afterEach(async ({ peers }) => { + await expect(peers.ava.screen.getByRole('heading', 'About')).toBeVisible(); +}); +test('together', { peers: { ava: {} } }, async ({ app, screen, peers, avaOnTodos }) => { + expect(avaOnTodos).toBe('ready'); + await Promise.all([app.open('/storage'), peers.ava.app.open('/about')]); + await Promise.all([ + expect(screen.getByRole('heading', 'Storage')).toBeVisible(), + expect(peers.ava.screen.getByRole('heading', 'About')).toBeVisible(), + ]); +}); +`, + }); + try { + const { result, why } = onlyAttempt(outcome, 'together'); + expect(result.status, why).toBe('passed'); + } finally { + project.cleanup(); + } + }); + + it('fails the test on a failing peer check, and keeps each user evidence in its own folder', async () => { + const { outcome, project } = await run({ + 'tests/pair.e2e.ts': `import { test, expect } from 'e2e'; +test('peer fails', { peers: { ava: {} } }, async ({ app, peers }) => { + await app.open('/storage'); + await peers.ava.app.open('/about'); + await expect(peers.ava.screen.getByRole('heading', 'Nowhere')).toBeVisible({ timeout: 500 }); +}); +`, + }); + try { + const { result, attempt, why } = onlyAttempt(outcome, 'peer fails'); + expect(result.status, why).toBe('failed'); + expect(attempt.error?.code).toBe('ASSERTION_FAILED'); + const paths = attempt.artifacts.map((artifact) => artifact.path ?? ''); + expect(paths.some((file) => file.endsWith('/screen-at-failure.txt') && !file.includes('/peers/'))).toBe(true); + const peerScreen = paths.find((file) => file.endsWith('/peers/ava/screen-at-failure.txt')); + expect(peerScreen, JSON.stringify(paths)).toBeDefined(); + expect(readFileSync(path.join(project.dir, '.e2e', 'results', ...peerScreen!.split('/')), 'utf8')).toContain('About'); + } finally { + project.cleanup(); + } + }); + + it('records a video for each user, in each user folder', async () => { + const { outcome, project } = await run({ + 'tests/pair.e2e.ts': `import { test } from 'e2e'; +test('filmed', { peers: { ava: {} }, video: 'on' }, async ({ app, peers }) => { + await app.open('/storage'); + await peers.ava.app.open('/about'); +}); +`, + }); + try { + const { result, attempt, why } = onlyAttempt(outcome, 'filmed'); + expect(result.status, why).toBe('passed'); + const videos = attempt.artifacts.filter((artifact) => artifact.kind === 'video').map((artifact) => artifact.path ?? ''); + expect(videos.filter((file) => !file.includes('/peers/')), JSON.stringify(videos)).toHaveLength(1); + expect(videos.filter((file) => file.includes('/peers/ava/video/')), JSON.stringify(videos)).toHaveLength(1); + for (const file of videos) expect(existsSync(path.join(project.dir, '.e2e', 'results', ...file.split('/')))).toBe(true); + } finally { + project.cleanup(); + } + }); + + it('runs each user agent steps as its own agent, with its own context and memory, on its own screen', async () => { + const { outcome, project } = await runProjectWithConfigFile( + { + 'tests/pair.e2e.ts': `import { test } from 'e2e'; +import { writeFileSync } from 'node:fs'; +test('agents', { agentContext: 'Test user context.', peers: { ava: { agent: 'ava', agentContext: 'Peer context.' }, bob: {} } }, async ({ app, agent, peers }) => { + await app.open('/storage'); + await peers.ava.app.open('/about'); + await peers.bob.app.open('/todos'); + const read = async (who: typeof agent) => JSON.parse((await who.act('report')).summary); + const seen = { mine: await read(agent), hers: await read(peers.ava.agent), hersAgain: await read(peers.ava.agent), bobs: await read(peers.bob.agent) }; + writeFileSync(new URL('../agents.json', import.meta.url), JSON.stringify(seen)); +}); +`, + }, + { + appUrl: app.url, + configSource: `import type { E2EConfig, StepExecutor } from 'e2e'; +import { web } from '@e2e-dev/web'; + +// Reports what the step met: the agent's context, a count kept in its memory, and the pages its screen shows. +const report: StepExecutor = { + name: 'report', + version: '1', + cache: 'off', + async runStep(ctx) { + const count = ((ctx.attempt.memory.get('count') as number | undefined) ?? 0) + 1; + ctx.attempt.memory.set('count', count); + const screen = await ctx.observe(); + const sees = ['Storage', 'About', 'Todos'].filter((page) => screen.text.includes(page)); + return { status: 'passed', summary: JSON.stringify({ context: ctx.agentContext, count, sees }) }; + }, +}; + +export default { + targets: [{ name: 'web', engine: web(), app: { url: process.env.APP_URL! } }], + workers: 1, + agents: { default: { executor: report, context: 'Default agent.' }, ava: { executor: report, context: 'Ava agent.' } }, +} satisfies E2EConfig; +`, + }, + ); + try { + const { result, why } = onlyAttempt(outcome, 'agents'); + expect(result.status, why).toBe('passed'); + const seen = JSON.parse(readFileSync(path.join(project.dir, 'agents.json'), 'utf8')); + expect(seen.mine).toEqual({ context: 'Default agent.\nTest user context.', count: 1, sees: ['Storage'] }); + expect(seen.hers).toEqual({ context: 'Ava agent.\nPeer context.', count: 1, sees: ['About'] }); + expect(seen.hersAgain.count).toBe(2); + expect(seen.bobs).toEqual({ context: 'Default agent.', count: 1, sees: ['Todos'] }); + } finally { + project.cleanup(); + } + }); + + it('redacts a secret one user typed from what the other user reads of the screen', async () => { + const TOKEN = 'synthetic-peer-token-2718'; + const { outcome, project } = await run( + { + 'tests/pair.e2e.ts': `import { test, expect, secrets } from 'e2e'; +test('shares a token', { peers: { ava: {} } }, async ({ app, screen, peers }) => { + await app.open('/todos'); + await screen.getByLabel('New todo').fill(secrets.get('token')); + await screen.getByRole('button', 'Add').tap(); + await expect(screen.getByRole('status', 'Result')).toHaveText('added'); + await peers.ava.app.open('/todos'); + // Ava's page shows the token, but what her agent reads of it never does. + await expect(peers.ava.screen.getByRole('list', 'Todos')).toContainText('2718'); + const tree = await peers.ava.screen.tree(); + // The marker stands where the token was: nothing dropped the todo instead. + if (!tree.includes('')) throw new Error('the peer screen read has no redaction marker: ' + tree); + if (tree.includes('${TOKEN}')) throw new Error('the token reached the peer screen read'); +}); +`, + }, + `\n secrets: { token: () => '${TOKEN}' },`, + ); + try { + const { result, why } = onlyAttempt(outcome, 'shares a token'); + expect(result.status, why).toBe('passed'); + const report = readFileSync(path.join(project.dir, '.e2e', 'report.json'), 'utf8'); + expect(report).toContain(''); + expect(report).not.toContain(TOKEN); + } finally { + project.cleanup(); + } + }); + + it("labels each peer's steps, files, and app log lines in the report, keeps each user's environment apart, and adds no field for a test with no peers", async () => { + const { outcome, project } = await run({ + 'tests/solo.e2e.ts': `import { test, expect } from 'e2e'; +test('solo', { video: 'on' }, async ({ app, screen }) => { + await app.open('/nowhere-for-me'); + await app.open('/about'); + await expect(screen.getByRole('heading', 'Nowhere')).toBeVisible({ timeout: 500 }); +}); +`, + 'tests/pair.e2e.ts': `import { test, expect } from 'e2e'; +test('labelled', { peers: { ava: {} } }, async ({ app, screen, peers }) => { + await app.open('/storage'); + await expect(screen.getByRole('heading', 'Storage')).toBeVisible(); + await peers.ava.app.open('/about'); + await expect(peers.ava.screen.getByRole('heading', 'About')).toBeVisible(); + await peers.ava.app.open('/nowhere-for-ava'); + await expect(screen.getByRole('heading', 'Storage')).toBeVisible(); + await peers.ava.app.screenshot('board'); + await app.screenshot('board'); +}); +`, + }); + try { + const { result, attempt, why } = onlyAttempt(outcome, 'labelled'); + expect(result.status, why).toBe('passed'); + const document = JSON.parse(readFileSync(path.join(project.dir, '.e2e', 'report.json'), 'utf8')) as unknown; + assertValidReport(document); + // The written report carries what the records do. + const results = (document as { run: { results: { titlePath: string[]; attempts: Record[] }[] } }).run.results; + const pairAttempt = results.find((each) => each.titlePath.includes('labelled'))!.attempts[0]! as { + steps: { user?: string }[]; + peers?: Record }>; + }; + expect(pairAttempt.steps.map((step) => step.user ?? null)).toEqual([null, null, 'ava', 'ava', 'ava', null, 'ava', null]); + expect(pairAttempt.peers?.['ava']?.environment?.['browser']).toMatch(/chromium/u); + const steps = attempt.steps.map((step) => [step.api, step.user ?? null]); + expect(steps).toEqual([ + ['app.open', null], + ['expect.toBeVisible', null], + ['app.open', 'ava'], + ['expect.toBeVisible', 'ava'], + ['app.open', 'ava'], + ['expect.toBeVisible', null], + ['app.screenshot', 'ava'], + ['app.screenshot', null], + ]); + const logged = (attempt.appLog ?? []).filter((line) => line.text.includes('/nowhere-for-ava')); + expect(logged.length, JSON.stringify(attempt.appLog)).toBeGreaterThan(0); + for (const line of logged) expect(line).toMatchObject({ user: 'ava', step: 4 }); + const shots = attempt.artifacts.filter((artifact) => artifact.kind === 'screenshot').map((artifact) => [artifact.path, artifact.user ?? null]); + expect(shots).toHaveLength(2); + expect(shots.find(([, user]) => user === 'ava')?.[0]).toMatch(/\/peers\/ava\/screenshots\/[^/]*board[^/]*\.png$/u); + expect(shots.find(([, user]) => user === null)?.[0]).not.toContain('/peers/'); + expect(attempt.peers?.['ava']?.environment?.['browser']).toBe(attempt.environment?.['browser']); + expect(attempt.peers?.['ava']?.environment?.['browser']).toMatch(/chromium/u); + + // A test with no peers has everything a peer would label, and no field names a user. + const solo = onlyAttempt(outcome, 'solo'); + expect(solo.result.status, solo.why).toBe('failed'); + expect(solo.attempt.appLog?.length).toBeGreaterThan(0); + expect(solo.attempt.failure).toBeDefined(); + expect(solo.attempt.artifacts.some((artifact) => artifact.kind === 'video')).toBe(true); + const keys: string[] = []; + const walk = (value: unknown): void => { + if (Array.isArray(value)) value.forEach(walk); + else if (typeof value === 'object' && value !== null) { + for (const [key, inner] of Object.entries(value)) { + keys.push(key); + walk(inner); + } + } + }; + const written = (document as { run: { results: { titlePath: string[] }[] } }).run.results.find((each) => each.titlePath.includes('solo')); + expect(written).toBeDefined(); + walk(written); + expect(keys).not.toContain('user'); + expect(keys).not.toContain('peers'); + } finally { + project.cleanup(); + } + }); + + it("keeps the failing peer's own screen as its failure evidence, under its name", async () => { + const { outcome, project } = await run({ + 'tests/pair.e2e.ts': `import { test, expect } from 'e2e'; +test('peer fails', { peers: { ava: {} } }, async ({ app, peers }) => { + await app.open('/storage'); + await peers.ava.app.open('/about'); + await expect(peers.ava.screen.getByRole('heading', 'Nowhere')).toBeVisible({ timeout: 500 }); +}); +`, + }); + try { + const { result, attempt, why } = onlyAttempt(outcome, 'peer fails'); + expect(result.status, why).toBe('failed'); + expect(attempt.steps.at(-1)).toMatchObject({ api: 'expect.toBeVisible', user: 'ava', status: 'failed' }); + const hers = attempt.peers?.['ava']?.failure; + expect(hers?.url, JSON.stringify(attempt.peers)).toMatch(/\/about$/u); + expect(attempt.failure?.url).toMatch(/\/storage$/u); + const screen = attempt.artifacts.find((artifact) => artifact.id === hers?.screen); + expect(screen).toMatchObject({ user: 'ava' }); + expect(screen?.path).toMatch(/\/peers\/ava\/screen-at-failure\.txt$/u); + } finally { + project.cleanup(); + } + }); + + it("keeps each user's toHaveScreenshot baseline of one name in a file of its own", async () => { + const { outcome, project } = await run({ + 'tests/pair.e2e.ts': `import { test, expect } from 'e2e'; +test('baselines', { peers: { ava: {} } }, async ({ app, screen, peers }) => { + await app.open('/storage'); + await peers.ava.app.open('/about'); + await expect.soft(screen).toHaveScreenshot('page'); + await expect.soft(peers.ava.screen).toHaveScreenshot('page'); +}); +`, + }); + try { + // The first run has no stored screenshots: each user's is written to its own file. + const first = onlyAttempt(outcome, 'baselines'); + expect(first.result.status, first.why).toBe('failed'); + const snapshots = path.join(project.dir, 'tests', 'pair.e2e.ts-snapshots'); + const suffix = `-web-${process.platform}.png`; + const mine = path.join(snapshots, `page${suffix}`); + // Hers sits under the test's own target, then her name. + const hers = path.join(snapshots, 'peers', 'web', 'ava', `page${suffix}`); + expect(existsSync(mine)).toBe(true); + expect(existsSync(hers)).toBe(true); + expect(readFileSync(hers).equals(readFileSync(mine))).toBe(false); + // Each user's screen then matches its own. + const second = onlyAttempt(await runExistingWithConfigFile(project, { appUrl: app.url }), 'baselines'); + expect(second.result.status, second.why).toBe('passed'); + } finally { + project.cleanup(); + } + }, 120_000); + + it('holds each user step under e2e run --step, the peer named, including two called together', async () => { + const held: HeldStep[] = []; + const { outcome, project } = await runProjectWithConfigFile( + { + 'tests/pair.e2e.ts': `import { test } from 'e2e'; +test('stepped', { peers: { ava: {} } }, async ({ app, peers }) => { + await app.open('/storage'); + await peers.ava.app.open('/about'); + await Promise.all([app.open('/todos'), peers.ava.app.open('/storage')]); +}); +`, + }, + { + appUrl: app.url, + configSource: workerConfigSource(1), + runOptions: { + beforeStep: async (step) => { + held.push(step); + }, + }, + }, + ); + try { + const { result, why } = onlyAttempt(outcome, 'stepped'); + expect(result.status, why).toBe('passed'); + expect(held.map((step) => [step.label, step.user ?? null]).toSorted()).toEqual( + [ + ['/storage', null], + ['/about', 'ava'], + ['/todos', null], + ['/storage', 'ava'], + ].toSorted(), + ); + expect(held.slice(0, 2).map((step) => step.user ?? null)).toEqual([null, 'ava']); + } finally { + project.cleanup(); + } + }); + + /** A config whose one agent reads the screen, then reports, as its step summary, the earlier steps its prompt was given. */ + const ledgerConfig = `import type { E2EConfig, StepExecutor } from 'e2e'; +import { web } from '@e2e-dev/web'; + +const ledger: StepExecutor = { + name: 'ledger', + version: '1', + cache: 'off', + async runStep(ctx) { + const seen = await ctx.observe({ pixels: true }); + if (seen.pixels !== undefined) await ctx.attachScreenshot(seen.pixels, 'look'); + return { status: 'passed', summary: ctx.ledger }; + }, +}; + +export default { + targets: [{ name: 'web', engine: web(), app: { url: process.env.APP_URL! } }], + workers: 1, + agents: { default: { executor: ledger } }, +} satisfies E2EConfig; +`; + + it("tells each user's agent only that user's earlier steps, and compares each user's screens with that user's own", async () => { + const { outcome, project } = await runProjectWithConfigFile( + { + 'tests/pair.e2e.ts': `import { test } from 'e2e'; +import { writeFileSync } from 'node:fs'; +test('histories', { peers: { ava: {} } }, async ({ app, agent, peers }) => { + await app.open('/storage'); + await peers.ava.app.open('/about'); + await agent.act('note the storage page'); + await peers.ava.agent.act('note the about page'); + const mine = (await agent.act('tell what came before')).summary; + const hers = (await peers.ava.agent.act('tell what came before')).summary; + writeFileSync(new URL('../ledgers.json', import.meta.url), JSON.stringify({ mine, hers })); +}); +`, + }, + { appUrl: app.url, configSource: ledgerConfig }, + ); + try { + const { result, attempt, why } = onlyAttempt(outcome, 'histories'); + expect(result.status, why).toBe('passed'); + // Each agent step saw its own user's screen; a later one compares with that user's earlier one, not the other user's. + const acts = attempt.steps.filter((step) => step.api === 'agent.act'); + expect(acts.map((step) => [step.user ?? null, step.screen?.location])).toEqual([ + [null, `${app.url}/storage`], + ['ava', `${app.url}/about`], + [null, `${app.url}/storage`], + ['ava', `${app.url}/about`], + ]); + const opens = attempt.steps.filter((step) => step.api === 'app.open'); + expect(acts.map((step) => step.screen?.since)).toEqual([opens[0]!.index, opens[1]!.index, acts[0]!.index, acts[1]!.index]); + for (const step of acts) expect(step.screen?.changes).toEqual([]); + // A tool's screenshot of one label is a file in each user's own folder. + const looks = attempt.artifacts.filter((artifact) => artifact.kind === 'screenshot' && (artifact.path ?? '').endsWith('/look.png')); + expect(looks.map((artifact) => artifact.user ?? null).toSorted(), JSON.stringify(attempt.artifacts)).toEqual(['ava', 'ava', null, null].toSorted()); + expect(new Set(looks.filter((artifact) => artifact.user === 'ava').map((artifact) => artifact.path)).size).toBe(1); + expect(looks.filter((artifact) => artifact.user === 'ava').every((artifact) => artifact.path?.includes('/peers/ava/'))).toBe(true); + expect(looks.filter((artifact) => artifact.user === undefined).every((artifact) => !artifact.path?.includes('/peers/'))).toBe(true); + const { mine, hers } = JSON.parse(readFileSync(path.join(project.dir, 'ledgers.json'), 'utf8')) as { mine: string; hers: string }; + expect(mine).toContain('note the storage page'); + expect(mine).toContain('/storage'); + expect(mine).not.toContain('note the about page'); + expect(mine).not.toContain('/about'); + expect(hers).toContain('note the about page'); + expect(hers).toContain('/about'); + expect(hers).not.toContain('note the storage page'); + expect(hers).not.toContain('/storage'); + } finally { + project.cleanup(); + } + }); +}); + +describe('peers on another web target', () => { + let app: FixtureApp; + let other: FixtureApp; + beforeAll(async () => { + app = await startFixtureApp(); + other = await startFixtureApp(); + process.env['OTHER_URL'] = other.url; + }); + afterAll(async () => { + delete process.env['OTHER_URL']; + await app.close(); + await other.close(); + }); + + /** The test's own Chromium target, and another on its own app, in French. */ + const twoTargets = (otherApp: string) => `import type { E2EConfig } from 'e2e'; +import { web } from '@e2e-dev/web'; + +export default { + targets: [ + { name: 'web', engine: web(), app: { url: process.env.APP_URL! } }, + { name: 'french', engine: web({ locale: 'fr-FR' }), app: ${otherApp} }, + ], + workers: 1, +} satisfies E2EConfig; +`; + + it("runs a peer on another web target, on that target's own engine, app, and saved login", async () => { + const { outcome, project } = await runProjectWithConfigFile( + { + 'tests/auth.setup.e2e.ts': `import { test, expect } from 'e2e'; +test.setup('sign in ava', { sessions: ['ava'] }, async ({ app, screen, session }) => { + await app.open('/storage'); + await screen.getByRole('button', 'Save marker').tap(); + await expect(screen.getByRole('status', 'Marker')).toHaveText('saved'); + await session.save('ava'); +}); +`, + 'tests/pair.e2e.ts': `import { test, expect } from 'e2e'; +test('across', { peers: { ava: { target: 'french', session: 'ava' } } }, async ({ app, peers }) => { + await app.open('/storage'); + await peers.ava.app.open('/storage'); + await expect(peers.ava.screen.getByRole('status', 'Marker')).toHaveText('saved'); + const where = await peers.ava.browser.url(); + if (!where.startsWith(process.env.OTHER_URL!)) throw new Error('Ava opened ' + where); + const language = await peers.ava.browser.evaluate('navigator.language'); + if (language !== 'fr-FR') throw new Error('Ava runs in ' + language); +}); +`, + }, + { appUrl: app.url, configSource: twoTargets('{ url: process.env.OTHER_URL! }') }, + ); + try { + // The test runs on each target as its own, as every test does; its peer is on "french" both times. + const results = outcome.results.filter((result) => result.test.title === 'across'); + expect(results.map((result) => [result.target.name, result.status]).toSorted()).toEqual([ + ['french', 'passed'], + ['web', 'passed'], + ]); + const document = JSON.parse(readFileSync(path.join(project.dir, '.e2e', 'report.json'), 'utf8')) as unknown; + assertValidReport(document); + const onWeb = results.find((result) => result.target.name === 'web')!.attempts[0]!; + expect(onWeb.peers?.['ava']?.target).toBe('french'); + expect(onWeb.peers?.['ava']?.environment?.['browser']).toMatch(/chromium/u); + expect(onWeb.steps.filter((step) => step.user === 'ava').map((step) => step.api)).toEqual(['app.open', 'expect.toHaveText', 'browser.url', 'browser.evaluate']); + // The test's own user stays on its own app: its main page was the first app's. + expect(app.url).not.toBe(other.url); + } finally { + project.cleanup(); + } + }); + + it("starts the app command of a peer's target once for the run, on the free port the run chose for it", async () => { + const { outcome, project } = await runProjectWithConfigFile( + { + 'other-app.mjs': `import { appendFileSync } from 'node:fs'; +import { createServer } from 'node:http'; +appendFileSync(new URL('./started.log', import.meta.url), 'started\\n'); +createServer((_request, response) => { + response.writeHead(200, { 'content-type': 'text/html' }); + response.end('Other

Other app

'); +}).listen(Number(process.env.PORT), '127.0.0.1'); +`, + 'tests/pair.e2e.ts': `import { test, expect } from 'e2e'; +test('across', { peers: { ava: { target: 'french' } } }, async ({ app, peers }) => { + await app.open('/'); + await peers.ava.app.open('/'); + await expect(peers.ava.screen.getByRole('heading', 'Other app')).toBeVisible(); +}); +`, + }, + { + appUrl: app.url, + configSource: twoTargets(`{ url: 'http://127.0.0.1:0', command: { executable: process.execPath, args: ['other-app.mjs'], env: { PORT: '{port}' } } }`), + }, + ); + try { + const results = outcome.results.filter((result) => result.test.title === 'across'); + expect(results.map((result) => [result.target.name, result.status, JSON.stringify(result.attempts[0]?.error ?? null)]).toSorted()).toEqual([ + ['french', 'passed', 'null'], + ['web', 'passed', 'null'], + ]); + expect(readFileSync(path.join(project.dir, 'started.log'), 'utf8')).toBe('started\n'); + } finally { + project.cleanup(); + } + }, 120_000); +}); + +/** + * A config with a phone target on the fake engine whose `prepare` serves + * `devices` slots, a device each, and hands its workers which device every + * slot drives. Each `prepare` and each engine start is a line of `pool.log`. + */ +function poolConfig(devices: number, workers: number, phones = ''): string { + return `import type { E2EConfig } from 'e2e'; +import { appendFileSync } from 'node:fs'; +import { createFakeEngine, FAKE_APP } from '../../helpers/fake-engine.ts'; + +const log = (line: string) => appendFileSync(new URL('./pool.log', import.meta.url), line + '\\n'); +const phones = createFakeEngine({ + prepare: (info) => { + if (info.slots === 0) return {}; + log('prepare ' + JSON.stringify({ slots: info.slots, peerSlots: info.peerSlots ?? null })); + const bound = Math.min(info.slots, ${devices}); + return { workers: bound, env: { FAKE_POOL: Array.from({ length: bound }, (_, slot) => 'device-' + slot).join(',') } }; + }, + onInit: (info) => log('init ' + JSON.stringify({ slot: info.workerSlot, device: (info.env.FAKE_POOL ?? '').split(',')[info.workerSlot] ?? null })), + ${phones} +}).engine; + +export default { + targets: [ + { name: 'fake', platform: 'fake', engine: createFakeEngine({ state: true }).engine, app: FAKE_APP }, + { name: 'phones', platform: 'ios', engine: phones, app: FAKE_APP }, + ], + workers: ${workers}, +} satisfies E2EConfig; +`; +} + +/** The lines of `pool.log` that start with `kind`, parsed. */ +function poolLines(projectDir: string, kind: 'prepare' | 'init'): Record[] { + const file = path.join(projectDir, 'pool.log'); + if (!existsSync(file)) return []; + return readFileSync(file, 'utf8') + .trim() + .split('\n') + .filter((line) => line.startsWith(`${kind} `)) + .map((line) => JSON.parse(line.slice(kind.length + 1)) as Record); +} + +describe('peers: a slot of its own on the peer target', () => { + /** Two files whose test holds its worker a moment, so the run's two workers are live together. */ + const twoFiles = (options: string) => + Object.fromEntries( + ['a', 'b'].map((name) => [ + `tests/${name}.e2e.ts`, + `import { test } from 'e2e'; +test('${name}', ${options}, async () => { + await new Promise((resolve) => setTimeout(resolve, 400)); +}); +`, + ]), + ); + const runPool = async (files: Readonly>, devices: number, workers: number) => { + const notices: string[] = []; + const { outcome, project } = await runProjectWithConfigFile(files, { + configSource: poolConfig(devices, workers), + runOptions: { + onEvent: (event) => { + if (event.type === 'notice' && event.target === 'run') notices.push(event.message); + }, + }, + }); + return { outcome, project, notices }; + }; + const statuses = (outcome: RunOutcome, target: string) => + outcome.results + .filter((result) => result.target.name === target) + .map((result) => [result.test.title, result.status, result.attempts[0]?.error?.message ?? null]) + .toSorted(); + + it("asks a phone target for a slot per peer and starts each worker's peer on its own, with the device that slot was bound", async () => { + const { outcome, project, notices } = await runPool(twoFiles(`{ platforms: ['fake'], peers: { ava: { target: 'phones' } } }`), 2, 2); + try { + expect(statuses(outcome, 'fake')).toEqual([ + ['a', 'passed', null], + ['b', 'passed', null], + ]); + // The target runs no test of its own: both slots are for the two workers' peers. + expect(poolLines(project.dir, 'prepare')).toEqual([{ slots: 2, peerSlots: 2 }]); + expect(poolLines(project.dir, 'init').toSorted((a, b) => Number(a['slot']) - Number(b['slot']))).toEqual([ + { slot: 0, device: 'device-0' }, + { slot: 1, device: 'device-1' }, + ]); + expect(notices.filter((line) => line.includes('at a time'))).toEqual([]); + } finally { + project.cleanup(); + } + // A run with no peer names no peer slot to the engine. + const alone = await runPool(twoFiles(`{ platforms: ['ios'] }`), 2, 2); + try { + expect(statuses(alone.outcome, 'phones')).toEqual([ + ['a', 'passed', null], + ['b', 'passed', null], + ]); + expect(poolLines(alone.project.dir, 'prepare')).toEqual([{ slots: 2, peerSlots: null }]); + } finally { + alone.project.cleanup(); + } + }, 120_000); + + it("lets the run's own variable win over what the peer target's prepare handed, as for that target's own workers", async () => { + process.env['FAKE_POOL'] = 'from-the-run-0,from-the-run-1'; + try { + const { outcome, project } = await runPool(twoFiles(`{ platforms: ['fake'], peers: { ava: { target: 'phones' } } }`), 2, 2); + try { + expect(statuses(outcome, 'fake')).toEqual([ + ['a', 'passed', null], + ['b', 'passed', null], + ]); + expect(poolLines(project.dir, 'init').map((line) => line['device']).toSorted()).toEqual(['from-the-run-0', 'from-the-run-1']); + } finally { + project.cleanup(); + } + } finally { + delete process.env['FAKE_POOL']; + } + }); + + it('runs fewer workers, and says so, when the phone target serves fewer slots than the workers peers need', async () => { + const { outcome, project, notices } = await runPool(twoFiles(`{ platforms: ['fake'], peers: { ava: { target: 'phones' } } }`), 1, 2); + try { + expect(statuses(outcome, 'fake')).toEqual([ + ['a', 'passed', null], + ['b', 'passed', null], + ]); + expect(notices.filter((line) => line.includes('at a time'))).toEqual([ + 'target "fake" runs 1 worker at a time, not 2: the peers of tests take slots of their own on their targets, and an engine serves only so many at once', + ]); + // One worker ran both files, so one peer engine started, on the one device. + expect(poolLines(project.dir, 'init')).toEqual([{ slot: 0, device: 'device-0' }]); + } finally { + project.cleanup(); + } + }); + + it("keeps a test's own user and its peer on two slots of one phone target, a worker fewer for each peer", async () => { + const { outcome, project, notices } = await runPool(twoFiles(`{ platforms: ['ios'], peers: { ava: {} } }`), 2, 2); + try { + expect(statuses(outcome, 'phones')).toEqual([ + ['a', 'passed', null], + ['b', 'passed', null], + ]); + // Two workers with a peer each would need four devices; the two serve one worker and its peer. + expect(poolLines(project.dir, 'prepare')).toEqual([{ slots: 4, peerSlots: 2 }]); + expect(notices.filter((line) => line.includes('at a time'))).toEqual([ + 'target "phones" runs 1 worker at a time, not 2: the peers of tests take slots of their own on their targets, and an engine serves only so many at once', + ]); + const starts = poolLines(project.dir, 'init'); + expect(starts.toSorted((a, b) => Number(a['slot']) - Number(b['slot']))).toEqual([ + { slot: 0, device: 'device-0' }, + { slot: 1, device: 'device-1' }, + ]); + } finally { + project.cleanup(); + } + }); + + it("runs no more of a phone target's own workers than the fit left room for beside the peers it hosts, when its prepare serves more", async () => { + // The engine serves one worker of its own; prepare, asked for that worker's slot and the web test's peer's, serves both. + const files = { + 'tests/web.e2e.ts': `import { test } from 'e2e'; +test('web', { platforms: ['fake'], peers: { ava: { target: 'phones' } } }, async () => { + await new Promise((resolve) => setTimeout(resolve, 400)); +}); +`, + ...Object.fromEntries( + ['p1', 'p2'].map((name) => [ + `tests/${name}.e2e.ts`, + `import { test } from 'e2e'; +test('${name}', { platforms: ['ios'] }, async () => { + await new Promise((resolve) => setTimeout(resolve, 400)); +}); +`, + ]), + ), + }; + const { outcome, project } = await runProjectWithConfigFile(files, { configSource: poolConfig(4, 8, 'workers: 1,') }); + try { + expect(outcome.results.filter((result) => result.status !== 'skipped').map((result) => [result.test.title, result.target.name, result.status]).toSorted()).toEqual([ + ['p1', 'phones', 'passed'], + ['p2', 'phones', 'passed'], + ['web', 'fake', 'passed'], + ]); + expect(poolLines(project.dir, 'prepare')).toEqual([{ slots: 2, peerSlots: 1 }]); + // One phone worker ran both phone files on slot 0; the web test's peer had slot 1 to itself. + expect(poolLines(project.dir, 'init').toSorted((a, b) => Number(a['slot']) - Number(b['slot']))).toEqual([ + { slot: 0, device: 'device-0' }, + { slot: 1, device: 'device-1' }, + ]); + } finally { + project.cleanup(); + } + }); + + it("runs no more of a phone target's workers than the fit when its prepare serves its own tests' peers too, past the engine's own bound", async () => { + // The engine serves two workers; prepare, asked for theirs and their peers' four slots, serves all four. + const files = Object.fromEntries( + ['p1', 'p2', 'p3', 'p4'].map((name) => [ + `tests/${name}.e2e.ts`, + `import { test } from 'e2e'; +test('${name}', { platforms: ['ios'], peers: { ava: {} } }, async () => { + await new Promise((resolve) => setTimeout(resolve, 400)); +}); +`, + ]), + ); + const { outcome, project } = await runProjectWithConfigFile(files, { configSource: poolConfig(4, 8, 'workers: 2,') }); + try { + expect(outcome.results.filter((result) => result.status !== 'skipped').map((result) => [result.test.title, result.target.name, result.status]).toSorted()).toEqual([ + ['p1', 'phones', 'passed'], + ['p2', 'phones', 'passed'], + ['p3', 'phones', 'passed'], + ['p4', 'phones', 'passed'], + ]); + expect(poolLines(project.dir, 'prepare')).toEqual([{ slots: 4, peerSlots: 2 }]); + // Two workers on slots 0 and 1, their peers on 2 and 3: each slot started once, on its own device. + expect(poolLines(project.dir, 'init').toSorted((a, b) => Number(a['slot']) - Number(b['slot']))).toEqual([ + { slot: 0, device: 'device-0' }, + { slot: 1, device: 'device-1' }, + { slot: 2, device: 'device-2' }, + { slot: 3, device: 'device-3' }, + ]); + } finally { + project.cleanup(); + } + }); + + it('fails the run before any test when a phone target cannot serve one worker and its peer', async () => { + const { outcome, project } = await runPool(twoFiles(`{ platforms: ['ios'], peers: { ava: {} } }`), 1, 2); + try { + expect(outcome.results.filter((result) => result.attempts.length > 0)).toEqual([]); + expect(outcome.exitCode).not.toBe(0); + expect(outcome.report.run.errors.map((error) => [error.code, error.phase, error.message])).toEqual([ + [ + 'ENGINE_FAILURE', + 'launch', + 'target "phones" serves 1 at once, and this run needs 2 of it at once with one worker per target: 1 for its own worker, 1 for the peer of one of its own tests; a peer takes a slot of its own, a device on a phone target, so give the target more, or keep the tests that put a peer on it out of this run', + ], + ]); + expect(poolLines(project.dir, 'init')).toEqual([]); + } finally { + project.cleanup(); + } + }); +}); + +describe('peers: targets a peer cannot run on', () => { + it("fails the run before any test, with the engine's own code, when a peer's target leases its browsers from a provider", async () => { + const { outcome, project } = await runProjectWithConfigFile( + { + 'tests/pair.e2e.ts': `import { test } from 'e2e'; +test('pair', { platforms: ['fake'], peers: { ava: { target: 'cloud' } } }, async () => {}); +`, + }, + { + configSource: `import type { E2EConfig } from 'e2e'; +import { appendFileSync } from 'node:fs'; +import { web } from '@e2e-dev/web'; +import { createFakeEngine, FAKE_APP } from '../../helpers/fake-engine.ts'; + +const cloud = { + name: 'toy-cloud', + async acquire() { + appendFileSync(new URL('./leases.log', import.meta.url), 'acquired\\n'); + return { id: 'lease', cdpEndpoint: 'ws://127.0.0.1:9' }; + }, + async release() {}, +}; + +export default { + targets: [ + { name: 'fake', platform: 'fake', engine: createFakeEngine({ state: true }).engine, app: FAKE_APP }, + { name: 'cloud', engine: web({ browser: cloud }), app: { url: 'http://127.0.0.1:4599' } }, + ], + workers: 1, +} satisfies E2EConfig; +`, + }, + ); + try { + expect(outcome.results.filter((result) => result.attempts.length > 0)).toEqual([]); + expect(outcome.report.run.errors.map((error) => [error.code, error.phase, error.message])).toEqual([ + [ + 'UNSUPPORTED_CAPABILITY', + 'launch', + 'target "cloud" leases its browsers from toy-cloud, and a test\'s peer on it would need a lease of its own, which this version does not take for a peer; run the peer on a target that launches its browser on this machine', + ], + ]); + expect(existsSync(path.join(project.dir, 'leases.log'))).toBe(false); + } finally { + project.cleanup(); + } + }); +}); + +describe('peers: the replay cache', () => { + let app: FixtureApp; + beforeAll(async () => { + app = await startFixtureApp(); + }); + afterAll(async () => { + await app.close(); + }); + + /** A config whose one agent taps Increment twice, through actions the replay cache records, and logs each time it runs. */ + const counterConfig = `import type { E2EConfig, StepExecutor } from 'e2e'; +import { appendFileSync } from 'node:fs'; +import { web } from '@e2e-dev/web'; + +const twice: StepExecutor = { + name: 'twice', + version: '1', + async runStep(ctx) { + appendFileSync(new URL('./calls.log', import.meta.url), ctx.step.instruction + '\\n'); + const screen = await ctx.observe(); + const line = screen.text.split('\\n').find((row) => row.includes('button "Increment"')); + const id = /#(\\S+)/u.exec(line ?? '')?.[1]; + if (id === undefined) return { status: 'failed', summary: 'There is no Increment button.' }; + await ctx.actions.tap({ id }); + await ctx.actions.tap({ id }); + return { status: 'passed', summary: 'Incremented the counter twice.' }; + }, +}; + +export default { + targets: [{ name: 'web', engine: web(), app: { url: process.env.APP_URL! } }], + workers: 1, + cache: { mode: 'read-write' }, + agents: { default: { executor: twice } }, +} satisfies E2EConfig; +`; + + const calls = (project: { dir: string }): string[] => + existsSync(path.join(project.dir, 'calls.log')) ? readFileSync(path.join(project.dir, 'calls.log'), 'utf8').trim().split('\n') : []; + + it('keeps a recording for each user of one step, and each replays its own when the two run in the other order', async () => { + const { outcome, project } = await runProjectWithConfigFile( + { + 'tests/pair.e2e.ts': `import { test, expect } from 'e2e'; +import { existsSync } from 'node:fs'; +const reversed = existsSync(new URL('../reversed', import.meta.url)); +test('both count', { peers: { ava: {} } }, async ({ app, agent, screen, peers }) => { + await app.open('/'); + await peers.ava.app.open('/'); + const mine = async () => { + await agent.act('increment the counter twice'); + await expect(screen.getByRole('status', 'Counter')).toHaveText('2'); + }; + const hers = async () => { + await peers.ava.agent.act('increment the counter twice'); + await expect(peers.ava.screen.getByRole('status', 'Counter')).toHaveText('2'); + }; + if (reversed) { + await hers(); + await mine(); + } else { + await mine(); + await hers(); + } +}); +`, + }, + { appUrl: app.url, configSource: counterConfig }, + ); + try { + const first = onlyAttempt(outcome, 'both count'); + expect(first.result.status, first.why).toBe('passed'); + const acts = first.attempt.steps.filter((step) => step.api === 'agent.act'); + expect(acts.map((step) => [step.user ?? null, step.cache?.write])).toEqual([ + [null, 'saved'], + ['ava', 'saved'], + ]); + expect(acts[0]!.cache?.entry).not.toBe(acts[1]!.cache?.entry); + expect(calls(project)).toHaveLength(2); + const entries = readdirSync(path.join(project.dir, '.e2e', 'cache'), { recursive: true }).filter((file) => String(file).endsWith('.json')); + expect(entries).toHaveLength(2); + + writeFileSync(path.join(project.dir, 'reversed'), ''); + const second = await runExistingWithConfigFile(project, { appUrl: app.url }); + const again = onlyAttempt(second, 'both count'); + expect(again.result.status, again.why).toBe('passed'); + const replayed = again.attempt.steps.filter((step) => step.api === 'agent.act'); + expect(replayed.map((step) => [step.user ?? null, step.cache?.mode, step.cache?.entry])).toEqual([ + ['ava', 'self-finalized', acts[1]!.cache?.entry], + [null, 'self-finalized', acts[0]!.cache?.entry], + ]); + // Nothing called the agent: both steps replayed. + expect(calls(project)).toHaveLength(2); + } finally { + project.cleanup(); + } + }, 120_000); + + it("keeps a recording of a peer's step for each agent a test runs as, though the peer runs as one agent in both", async () => { + const files = { + 'tests/pair.e2e.ts': `import { test, expect } from 'e2e'; +test('sweep', { agent: ['admin', 'member'], peers: { ava: { agent: 'guest' } } }, async ({ app, peers }) => { + await app.open('/'); + await peers.ava.app.open('/'); + await peers.ava.agent.act('increment the counter twice'); + await expect(peers.ava.screen.getByRole('status', 'Counter')).toHaveText('2'); +}); +`, + }; + const configSource = counterConfig.replace('agents: { default: { executor: twice } },', 'agents: { default: { executor: twice }, admin: { executor: twice }, member: { executor: twice }, guest: { executor: twice } },'); + const { outcome, project } = await runProjectWithConfigFile(files, { appUrl: app.url, configSource }); + try { + const acts = outcome.results.map((result) => [result.agent, result.status, result.attempts[0]?.steps.find((step) => step.api === 'agent.act')?.cache?.write ?? null]); + // Each pair's peer recorded its own step: the admin pair's recording never stands in for the member pair's. + expect(acts.toSorted()).toEqual([ + ['admin', 'passed', 'saved'], + ['member', 'passed', 'saved'], + ]); + expect(calls(project)).toHaveLength(2); + const entries = readdirSync(path.join(project.dir, '.e2e', 'cache'), { recursive: true }).filter((file) => String(file).endsWith('.json')); + expect(entries).toHaveLength(2); + } finally { + project.cleanup(); + } + }); + + it("keeps a peer's recordings and screenshot baselines for each target the test runs on, though the peer runs on one", async () => { + const files = { + 'tests/pair.e2e.ts': `import { test, expect } from 'e2e'; +test('two targets', { peers: { ava: { target: 'web' } } }, async ({ app, peers }) => { + await app.open('/'); + await peers.ava.app.open('/'); + await peers.ava.agent.act('increment the counter twice'); + await expect(peers.ava.screen.getByRole('status', 'Counter')).toHaveText('2'); + await expect(peers.ava.screen).toHaveScreenshot('counter'); +}); +`, + }; + const configSource = counterConfig.replace( + "targets: [{ name: 'web', engine: web(), app: { url: process.env.APP_URL! } }],", + "targets: [{ name: 'web', engine: web(), app: { url: process.env.APP_URL! } }, { name: 'web-b', engine: web(), app: { url: process.env.APP_URL! } }],", + ); + const { outcome, project } = await runProjectWithConfigFile(files, { appUrl: app.url, configSource }); + try { + const acts = (run: RunOutcome) => + run.results.map((result) => [result.target.name, result.attempts[0]?.steps.find((step) => step.api === 'agent.act')?.cache?.write ?? null]).toSorted(); + // Each pair's peer recorded its own step, and wrote its own missing baseline. + expect(acts(outcome)).toEqual([ + ['web', 'saved'], + ['web-b', 'saved'], + ]); + expect(calls(project)).toHaveLength(2); + const snapshots = path.join(project.dir, 'tests', 'pair.e2e.ts-snapshots'); + for (const pairTarget of ['web', 'web-b']) { + expect(existsSync(path.join(snapshots, 'peers', pairTarget, 'ava', `counter-web-${process.platform}.png`)), pairTarget).toBe(true); + } + // The next run replays each pair's own recording and matches each pair's own baseline. + const second = await runExistingWithConfigFile(project, { appUrl: app.url }); + expect(second.results.map((result) => [result.target.name, result.status]).toSorted()).toEqual([ + ['web', 'passed'], + ['web-b', 'passed'], + ]); + expect(calls(project)).toHaveLength(2); + } finally { + project.cleanup(); + } + }, 120_000); + + it("runs a peer's step live under --strict-cache when only the test's own user has a recording of it", async () => { + const { outcome, project } = await runProjectWithConfigFile( + { + 'tests/pair.e2e.ts': `import { test, expect } from 'e2e'; +import { existsSync } from 'node:fs'; +const withAva = existsSync(new URL('../with-ava', import.meta.url)); +test('strict', { peers: { ava: {} } }, async ({ app, agent, screen, peers }) => { + await app.open('/'); + await peers.ava.app.open('/'); + await agent.act('increment the counter twice'); + await expect(screen.getByRole('status', 'Counter')).toHaveText('2'); + if (!withAva) return; + await peers.ava.agent.act('increment the counter twice'); + await expect(peers.ava.screen.getByRole('status', 'Counter')).toHaveText('2'); +}); +`, + }, + { appUrl: app.url, configSource: counterConfig }, + ); + try { + const first = onlyAttempt(outcome, 'strict'); + expect(first.result.status, first.why).toBe('passed'); + writeFileSync(path.join(project.dir, 'with-ava'), ''); + const second = await runExistingWithConfigFile(project, { appUrl: app.url, runOptions: { strictCache: true } }); + const again = onlyAttempt(second, 'strict'); + expect(again.result.status, again.why).toBe('passed'); + const acts = again.attempt.steps.filter((step) => step.api === 'agent.act'); + expect(acts.map((step) => [step.user ?? null, step.cache?.mode, step.cache?.reason ?? null])).toEqual([ + [null, 'self-finalized', null], + ['ava', 'missed', 'no-entry'], + ]); + expect(calls(project)).toHaveLength(2); + } finally { + project.cleanup(); + } + }, 120_000); + + it("keys a peer's recording on the peer's own target", async () => { + const twoTargets = counterConfig.replace( + "targets: [{ name: 'web', engine: web(), app: { url: process.env.APP_URL! } }],", + "targets: [{ name: 'web', engine: web(), app: { url: process.env.APP_URL! } }, { name: 'web-b', engine: web(), app: { url: process.env.APP_URL! } }],", + ); + expect(twoTargets).not.toBe(counterConfig); + const { outcome, project } = await runProjectWithConfigFile( + { + 'tests/pair.e2e.ts': `import { test, expect } from 'e2e'; +test('elsewhere', { platforms: ['web'], peers: { ava: { target: 'web-b' } } }, async ({ app, peers }) => { + await app.open('/'); + await peers.ava.app.open('/'); + await peers.ava.agent.act('increment the counter twice'); + await expect(peers.ava.screen.getByRole('status', 'Counter')).toHaveText('2'); +}); +`, + }, + { appUrl: app.url, configSource: twoTargets }, + ); + try { + const results = outcome.results.filter((result) => result.test.title === 'elsewhere'); + expect(results.map((result) => result.status)).toEqual(['passed', 'passed']); + const files = readdirSync(path.join(project.dir, '.e2e', 'cache'), { recursive: true }).filter((file) => String(file).endsWith('.json')); + const recordedFor = files.map( + (file) => + (JSON.parse(readFileSync(path.join(project.dir, '.e2e', 'cache', String(file)), 'utf8')) as { payload: { recordedFor?: { targetId: string; user?: string; ownerTargetId?: string } } }).payload + .recordedFor, + ); + // Both runs of the test have Ava on "web-b": each run's recording is on her target, one for each target the test ran on. + expect(recordedFor.map((step) => [step?.targetId, step?.user, step?.ownerTargetId]).toSorted()).toEqual([ + ['web-b', 'ava', 'web'], + ['web-b', 'ava', 'web-b'], + ]); + } finally { + project.cleanup(); + } + }); + + it("confirms, on an attempt that fails, only what each user's own checks verified before the failure", async () => { + const { outcome, project } = await runProjectWithConfigFile( + { + 'tests/pair.e2e.ts': `import { test, expect } from 'e2e'; +test('fails after my check', { peers: { ava: {}, bob: {} } }, async ({ app, agent, screen, peers }) => { + await app.open('/'); + await peers.ava.app.open('/'); + await peers.bob.app.open('/'); + await peers.ava.agent.act('increment the counter twice'); + await peers.bob.agent.act('increment the counter twice'); + await expect(peers.bob.screen.getByRole('status', 'Counter')).toHaveText('2'); + await agent.act('increment the counter twice'); + await expect(screen.getByRole('status', 'Counter')).toHaveText('2'); + await expect(screen.getByRole('status', 'Counter')).toHaveText('3', { timeout: 300 }); +}); +`, + }, + { appUrl: app.url, configSource: counterConfig }, + ); + try { + const { result, attempt, why } = onlyAttempt(outcome, 'fails after my check'); + expect(result.status, why).toBe('failed'); + const acts = attempt.steps.filter((step) => step.api === 'agent.act'); + expect(acts.map((step) => [step.user ?? null, step.cache?.write])).toEqual([ + ['ava', 'unconfirmed'], + ['bob', 'saved'], + [null, 'saved'], + ]); + } finally { + project.cleanup(); + } + }); + + it("confirms a user's recording only by that user's own later check", async () => { + const { outcome, project } = await runProjectWithConfigFile( + { + 'tests/pair.e2e.ts': `import { test, expect } from 'e2e'; +test('only mine checked', { peers: { ava: {} } }, async ({ app, agent, screen, peers }) => { + await app.open('/'); + await peers.ava.app.open('/'); + await peers.ava.agent.act('increment the counter twice'); + await agent.act('increment the counter twice'); + await expect(screen.getByRole('status', 'Counter')).toHaveText('2'); +}); +`, + }, + { appUrl: app.url, configSource: counterConfig }, + ); + try { + const { result, attempt, why } = onlyAttempt(outcome, 'only mine checked'); + expect(result.status, why).toBe('passed'); + const acts = attempt.steps.filter((step) => step.api === 'agent.act'); + expect(acts.map((step) => [step.user ?? null, step.cache?.write])).toEqual([ + ['ava', 'unconfirmed'], + [null, 'saved'], + ]); + } finally { + project.cleanup(); + } + }); +}); + +/** + * A worker-path config on the fake engine whose every load numbers itself: + * the runner's and the worker's own loads come first, so a peer's engine is + * a later number. Each engine logs its lifecycle to `events.log`. + */ +function lifecycleConfig(behavior: string): string { + return `import type { E2EConfig } from 'e2e'; +import { appendFileSync } from 'node:fs'; +import { createFakeEngine, FAKE_APP } from '../../helpers/fake-engine.ts'; + +const g = globalThis as { __peerLoads?: number }; +const id = (g.__peerLoads = (g.__peerLoads ?? 0) + 1); +const log = (event: string) => appendFileSync(new URL('./events.log', import.meta.url), process.pid + ':' + id + ' ' + event + '\\n'); +const engine = createFakeEngine({ + onInit: () => { log('init'); ${behavior.includes('boot') ? "if (id > 1) throw new Error('the peer engine would not boot');" : ''} }, + onStartAttempt: () => { log('start'); ${behavior.includes('start') ? "if (id > 1) throw new Error('the peer app would not open');" : ''} }, + onEndAttempt: () => { log('end'); ${behavior.includes('end') ? "if (id > 1) throw new Error('the peer app would not close');" : ''} }, + ${behavior.includes('settle-every') ? "onSettleAttempt: () => { throw new Error('the ' + (id > 1 ? 'peer' : 'test') + ' app failed after its last step'); }," : behavior.includes('settle') ? "onSettleAttempt: () => { if (id > 1) throw new Error('the peer app failed after its last step'); }," : ''} + onDispose: () => { log('dispose'); ${behavior.includes('dispose') ? "if (id > 1) throw new Error('the peer engine would not shut down');" : ''} }, +}).engine; + +export default { + targets: [{ name: 'fake', platform: 'fake', engine, app: FAKE_APP }], + workers: 1, +} satisfies E2EConfig; +`; +} + +/** The lifecycle lines of the worker that ran the tests, with its first engine as `test` and later ones as `peer`. */ +function workerEvents(projectDir: string): string[] { + const lines = readFileSync(path.join(projectDir, 'events.log'), 'utf8').trim().split('\n'); + const worker = lines.find((line) => line.endsWith(' start'))?.split(':')[0]; + const own = lines.filter((line) => line.startsWith(`${worker}:`)).map((line) => line.slice(line.indexOf(':') + 1)); + const first = Math.min(...own.map((line) => Number(line.split(' ')[0]))); + return own.map((line) => { + const [id, event] = line.split(' '); + return `${Number(id) === first ? 'test' : 'peer'} ${event}`; + }); +} + +describe('peers: engines and lifecycle', () => { + it("stops the run once when a peer's agent meets a model its provider does not serve, as the test's own agent does", async () => { + // The same run twice: the test's own agent meets the model, then a peer's agent does. + const ends = async (options: string, fixture: string, agent: string) => { + const { outcome, project } = await runProjectWithConfigFile( + { + 'tests/pair.e2e.ts': `import { test } from 'e2e'; +test('first', ${options}, async ({ ${fixture} }) => { + await ${agent}.act('do the thing'); +}); +test('second', async () => {}); +`, + }, + { + configSource: `import type { E2EConfig } from 'e2e'; +import { createFakeEngine, FAKE_APP } from '../../helpers/fake-engine.ts'; +import { refusedCopilotModel } from '../../helpers/unserved-copilot-model.ts'; + +export default { + targets: [{ name: 'fake', platform: 'fake', engine: createFakeEngine({ state: true }).engine, app: FAKE_APP }], + workers: 1, + cache: 'off', + agents: { default: {}, guest: { model: refusedCopilotModel() } }, +} satisfies E2EConfig; +`, + }, + ); + try { + return { + exitCode: outcome.exitCode, + errors: outcome.report.run.errors.map((error) => [error.code, error.message.includes(REFUSAL_EXPLANATION)]), + results: outcome.report.run.results.map((result) => [result.titlePath.at(-1), result.status, result.attempts.length, result.attempts[0]?.error?.code]), + }; + } finally { + project.cleanup(); + } + }; + const own = await ends("{ agent: 'guest' }", 'agent', 'agent'); + // The run's stop cuts the test short in the worker, so its attempt reads interrupted or the model's code, as other runs of it do. + expect(own).toEqual({ + exitCode: 2, + errors: [['MODEL_UNAVAILABLE', true]], + results: [ + ['first', 'interrupted', 1, expect.stringMatching(/^(INTERRUPTED|MODEL_UNAVAILABLE)$/)], + ['second', 'skipped', 0, undefined], + ], + }); + expect(await ends("{ peers: { ava: { agent: 'guest' } } }", 'peers', 'peers.ava.agent')).toEqual(own); + }); + + it('runs a peer on an engine of its own, opened before the body and closed with the test, then disposed with the worker', async () => { + const { outcome, project } = await runProjectWithConfigFile( + { + 'tests/pair.e2e.ts': `import { test } from 'e2e'; +test('unused peer', { peers: { ava: {} } }, async () => {}); +test('second', { peers: { ava: {} } }, async () => {}); +`, + }, + { configSource: lifecycleConfig('') }, + ); + try { + expect(onlyAttempt(outcome, 'unused peer').result.status).toBe('passed'); + expect(workerEvents(project.dir)).toEqual([ + 'test init', 'test start', 'peer init', 'peer start', 'peer end', 'test end', + 'test start', 'peer start', 'peer end', 'test end', + 'peer dispose', 'test dispose', + ]); + } finally { + project.cleanup(); + } + }); + + it("closes every user's app when the test times out in a peer's step, when the run is interrupted mid-test, and at the run's time limit", async () => { + // A peer step that never finishes on its own: the fake engine's tap waits on its signal. + const files = { + 'tests/pair.e2e.ts': `import { test } from 'e2e'; +test('slow peer', { peers: { ava: {} }, timeout: 800 }, async ({ peers }) => { + await peers.ava.screen.getByRole('button', 'Submit').tap(); +}); +`, + }; + const hanging = lifecycleConfig('').replace( + "const engine = createFakeEngine({", + "const engine = createFakeEngine({\n perform: (_ref, _action, operation) => new Promise((_resolve, reject) => operation.signal.addEventListener('abort', () => reject(operation.signal.reason), { once: true })),", + ); + expect(hanging).not.toBe(lifecycleConfig('')); + const timedOut = await runProjectWithConfigFile(files, { configSource: hanging }); + try { + const { result, attempt, why } = onlyAttempt(timedOut.outcome, 'slow peer'); + expect(result.status, why).toBe('timed-out'); + expect(attempt.steps.find((step) => step.api === 'locator.tap')).toMatchObject({ user: 'ava' }); + expect(attempt.steps.find((step) => step.api === 'locator.tap')?.status).not.toBe('passed'); + expect(workerEvents(timedOut.project.dir)).toEqual(['test init', 'test start', 'peer init', 'peer start', 'peer end', 'test end', 'peer dispose', 'test dispose']); + } finally { + timedOut.project.cleanup(); + } + + // The same test with a long timeout, interrupted once the peer's step is running. + const interrupt = new AbortController(); + const interrupted = await runProjectWithConfigFile( + { 'tests/pair.e2e.ts': files['tests/pair.e2e.ts'].replace('timeout: 800', 'timeout: 60_000') }, + { + configSource: hanging, + runOptions: { + interruptSignal: interrupt.signal, + onEvent: (event) => { + if (event.type === 'step' && event.progress.phase === 'start' && event.progress.identity?.user === 'ava') setTimeout(() => interrupt.abort(), 200); + }, + }, + }, + ); + try { + const { result, why } = onlyAttempt(interrupted.outcome, 'slow peer'); + expect(result.status, why).toBe('interrupted'); + expect(interrupted.outcome.report.run.status).toBe('interrupted'); + expect(workerEvents(interrupted.project.dir)).toEqual(['test init', 'test start', 'peer init', 'peer start', 'peer end', 'test end', 'peer dispose', 'test dispose']); + } finally { + interrupted.project.cleanup(); + } + + // And when the run's time limit lands mid-test. + const limited = await runProjectWithConfigFile( + { 'tests/pair.e2e.ts': files['tests/pair.e2e.ts'].replace('timeout: 800', 'timeout: 60_000') }, + { configSource: hanging, runOptions: { maxDuration: 2_000 } }, + ); + try { + const { result, why } = onlyAttempt(limited.outcome, 'slow peer'); + expect(result.status, why).toBe('interrupted'); + expect(workerEvents(limited.project.dir)).toEqual(['test init', 'test start', 'peer init', 'peer start', 'peer end', 'test end', 'peer dispose', 'test dispose']); + } finally { + limited.project.cleanup(); + } + }, 180_000); + + it('fails the launch when a peer app cannot open, and closes the test app too', async () => { + const { outcome, project } = await runProjectWithConfigFile( + { 'tests/pair.e2e.ts': `import { test } from 'e2e';\ntest('pair', { peers: { ava: {} } }, async () => {});\n` }, + { configSource: lifecycleConfig('start') }, + ); + try { + const { result, attempt, why } = onlyAttempt(outcome, 'pair'); + expect(result.status, why).toBe('failed'); + expect(attempt.error).toMatchObject({ code: 'ENGINE_FAILURE', phase: 'launch' }); + expect(attempt.error?.message).toContain('the peer app would not open'); + expect(workerEvents(project.dir)).toEqual(['test init', 'test start', 'peer init', 'peer start', 'peer end', 'test end', 'peer dispose', 'test dispose']); + } finally { + project.cleanup(); + } + }); + + it('keeps a peer engine boot failure for every later test on the worker, as for the test own engine', async () => { + const { outcome, project } = await runProjectWithConfigFile( + { + 'tests/pair.e2e.ts': `import { test } from 'e2e'; +test('first', { peers: { ava: {} } }, async () => {}); +test('second', { peers: { ava: {} } }, async () => {}); +`, + }, + { configSource: lifecycleConfig('boot') }, + ); + try { + for (const title of ['first', 'second']) { + const { result, attempt, why } = onlyAttempt(outcome, title); + expect(result.status, why).toBe('failed'); + expect(attempt.error?.message).toContain('the peer engine would not boot'); + } + expect(workerEvents(project.dir).filter((event) => event === 'peer init')).toHaveLength(1); + } finally { + project.cleanup(); + } + }); + + it('fails the test with a failure a peer app reports after its last step', async () => { + const { outcome, project } = await runProjectWithConfigFile( + { 'tests/pair.e2e.ts': `import { test } from 'e2e';\ntest('pair', { peers: { ava: {} } }, async () => {});\n` }, + { configSource: lifecycleConfig('settle') }, + ); + try { + const { result, attempt, why } = onlyAttempt(outcome, 'pair'); + expect(result.status, why).toBe('failed'); + expect(attempt.error?.message).toContain('the peer app failed after its last step'); + } finally { + project.cleanup(); + } + }); + + it("records every user's failure after the last step, the peer's beside the test's own app's", async () => { + const { outcome, project } = await runProjectWithConfigFile( + { 'tests/pair.e2e.ts': `import { test } from 'e2e';\ntest('pair', { peers: { ava: {} } }, async () => {});\n` }, + { configSource: lifecycleConfig('settle-every') }, + ); + try { + const { result, attempt, why } = onlyAttempt(outcome, 'pair'); + expect(result.status, why).toBe('failed'); + // Settled after the body and again after teardown: each time every user is, whichever fails first. + expect([attempt.error!, ...attempt.secondaryErrors].map((error) => [error.phase, error.message])).toEqual([ + ['body', 'attempt settle failed: the test app failed after its last step'], + ['body', 'attempt settle failed: the peer app failed after its last step'], + ['afterEach', 'attempt settle failed: the test app failed after its last step'], + ['afterEach', 'attempt settle failed: the peer app failed after its last step'], + ]); + } finally { + project.cleanup(); + } + }); + + it("names the peer on a video its engine's host keeps by URL, as on a video file it writes", async () => { + const { outcome, project } = await runProjectWithConfigFile( + { 'tests/pair.e2e.ts': `import { test } from 'e2e';\ntest('filmed', { peers: { ava: {} }, video: 'on' }, async () => {});\n` }, + { + configSource: `import type { E2EConfig } from 'e2e'; +import { createFakeEngine, FAKE_APP } from '../../helpers/fake-engine.ts'; + +export default { + targets: [{ name: 'fake', platform: 'fake', engine: createFakeEngine({ video: true, videoLinks: ['https://recordings.example/r.mp4'] }).engine, app: FAKE_APP }], + workers: 1, +} satisfies E2EConfig; +`, + }, + ); + try { + const { result, attempt, why } = onlyAttempt(outcome, 'filmed'); + expect(result.status, why).toBe('passed'); + const videos = attempt.artifacts.filter((artifact) => artifact.kind === 'video'); + // Each user's engine hands back a link and a file: the peer's two carry its name, the test's own user's neither. + expect(videos.map((video) => [video.url === undefined ? 'file' : 'link', video.user ?? null]).toSorted()).toEqual([ + ['file', null], + ['file', 'ava'], + ['link', null], + ['link', 'ava'], + ]); + assertValidReport(outcome.report); + } finally { + project.cleanup(); + } + }); + + it('gives a peer its own instance of an engine made in a project file the config imports', async () => { + const { outcome, project } = await runProjectWithConfigFile( + { + 'engines.ts': `import { createFakeEngine } from '../../helpers/fake-engine.ts';\nexport const engine = createFakeEngine().engine;\n`, + 'tests/pair.e2e.ts': `import { test } from 'e2e';\ntest('pair', { peers: { ava: {} } }, async () => {});\n`, + }, + { + configSource: `import type { E2EConfig } from 'e2e'; +import { FAKE_APP } from '../../helpers/fake-engine.ts'; +import { engine } from './engines.ts'; +export default { targets: [{ name: 'fake', platform: 'fake', engine, app: FAKE_APP }], workers: 1 } satisfies E2EConfig; +`, + }, + ); + try { + const { result, why } = onlyAttempt(outcome, 'pair'); + expect(result.status, why).toBe('passed'); + } finally { + project.cleanup(); + } + }); + + it('marks the attempt cleanup failed when a peer app cannot close', async () => { + const { outcome, project } = await runProjectWithConfigFile( + { 'tests/pair.e2e.ts': `import { test } from 'e2e';\ntest('pair', { peers: { ava: {} } }, async () => {});\n` }, + { configSource: lifecycleConfig('end') }, + ); + try { + const { attempt, why } = onlyAttempt(outcome, 'pair'); + expect(attempt.cleanup, why).toBe('failed'); + expect(attempt.secondaryErrors.map((error) => error.message).join('\n')).toContain('the peer app would not close'); + } finally { + project.cleanup(); + } + }); + + it('reports a peer engine that cannot shut down as a run error', async () => { + const { outcome, project } = await runProjectWithConfigFile( + { 'tests/pair.e2e.ts': `import { test } from 'e2e';\ntest('pair', { peers: { ava: {} } }, async () => {});\n` }, + { configSource: lifecycleConfig('dispose') }, + ); + try { + expect(onlyAttempt(outcome, 'pair').result.status).toBe('passed'); + expect(outcome.report.run.errors.map((error) => error.message).join('\n')).toContain('the peer engine would not shut down'); + } finally { + project.cleanup(); + } + }); + + it('opens fresh apps for both users on every retry', async () => { + const { outcome, project } = await runProjectWithConfigFile( + { + 'tests/pair.e2e.ts': `import { test } from 'e2e'; +import { existsSync, writeFileSync } from 'node:fs'; +const flag = new URL('../first-try', import.meta.url); +test('flaky', { peers: { ava: {} }, retries: 1 }, async () => { + if (!existsSync(flag)) { + writeFileSync(flag, ''); + throw new Error('first try fails'); + } +}); +`, + }, + { configSource: lifecycleConfig('') }, + ); + try { + const result = resultByTitle(outcome, 'flaky'); + expect(result.status).toBe('flaky'); + expect(workerEvents(project.dir).filter((event) => event.endsWith(' start'))).toEqual(['test start', 'peer start', 'test start', 'peer start']); + } finally { + project.cleanup(); + } + }); + + it('refuses a peer whose target engine comes from a package, the one instance every load shares', async () => { + const { outcome, project } = await runProjectWithConfigFile( + { + 'node_modules/shared-engine/package.json': JSON.stringify({ name: 'shared-engine', type: 'module', exports: './index.js' }), + 'node_modules/shared-engine/index.js': `import { defineEngine } from '${BUILT_ENGINE_API}'; +export const engine = defineEngine({ name: 'shared', version: '1.0.0', spiVersion: 1 }); +`, + 'tests/pair.e2e.ts': `import { test } from 'e2e';\ntest('pair', { peers: { ava: {} } }, async () => {});\ntest('second pair', { peers: { ava: {} } }, async () => {});\n`, + }, + { + configSource: `import type { E2EConfig } from 'e2e'; +import { engine } from 'shared-engine'; +export default { targets: [{ name: 'shared', platform: 'shared', engine, app: { url: 'http://127.0.0.1:4599' } }], workers: 1 } satisfies E2EConfig; +`, + }, + ); + try { + const { result, attempt, why } = onlyAttempt(outcome, 'pair'); + expect(result.status, why).toBe('failed'); + expect(attempt.error).toMatchObject({ code: 'INVALID_CONFIG', phase: 'launch' }); + expect(attempt.error?.message).toContain("whose engine is the same instance as another user's in every load of the config"); + // The second test on the worker meets the same refusal, under its own name. + const second = onlyAttempt(outcome, 'second pair'); + expect(second.attempt.error?.message, second.why).toContain('test "second pair" in tests/pair.e2e.ts runs a peer'); + } finally { + project.cleanup(); + } + }); + + it("starts the app of a peer's target that runs no test of its own, on the port the run chose", async () => { + const { outcome, project } = await runProjectWithConfigFile( + { + 'other-app.mjs': `import { appendFileSync } from 'node:fs'; +import { createServer } from 'node:http'; +appendFileSync(new URL('./started.log', import.meta.url), process.env.PORT + '\\n'); +createServer((_request, response) => response.end('other')).listen(Number(process.env.PORT), '127.0.0.1'); +`, + 'tests/pair.e2e.ts': `import { test } from 'e2e'; +import { readFileSync } from 'node:fs'; +test('pair', { requires: ['state'], peers: { ava: { target: 'other' } } }, async ({ peers }) => { + // The run started the other target's app on a free port, and the peer's engine reads the same port. + const started = readFileSync(new URL('../started.log', import.meta.url), 'utf8').trim(); + if (!peers.ava.app.baseUrl.endsWith(':' + started)) throw new Error('the peer app is at ' + peers.ava.app.baseUrl + ', its command on ' + started); +}); +`, + }, + { + configSource: `import type { E2EConfig } from 'e2e'; +import { createFakeEngine, FAKE_APP } from '../../helpers/fake-engine.ts'; + +export default { + targets: [ + { name: 'fake', platform: 'fake', engine: createFakeEngine({ state: true }).engine, app: FAKE_APP }, + // No saved state: the test requires it, so this target runs none of its own. + { + name: 'other', + platform: 'other', + engine: createFakeEngine().engine, + app: { url: 'http://127.0.0.1:0', command: { executable: process.execPath, args: ['other-app.mjs'], env: { PORT: '{port}' } } }, + }, + ], + workers: 1, +} satisfies E2EConfig; +`, + }, + ); + try { + const results = outcome.results.filter((result) => result.test.title === 'pair'); + expect(results.map((result) => [result.target.name, result.status]).toSorted()).toEqual([ + ['fake', 'passed'], + ['other', 'skipped'], + ]); + const onFake = results.find((result) => result.target.name === 'fake')!; + expect(onFake.attempts[0]?.error, JSON.stringify(onFake.attempts[0]?.error)).toBeUndefined(); + } finally { + project.cleanup(); + } + }); + + it("hands each user's agent the tools of that user's own config load, so a tool reaches its own user's engine", async () => { + const { outcome, project } = await runProjectWithConfigFile( + { + 'tests/pair.e2e.ts': `import { test } from 'e2e'; +test('pair', { peers: { ava: {}, bob: {} } }, async ({ agent, peers }) => { + await peers.ava.agent.act('say who you are'); + await agent.act('say who you are'); + await peers.bob.agent.act('say who you are'); +}); +`, + }, + { + configSource: `import type { E2EConfig } from 'e2e'; +import { defineTool } from 'e2e/agent'; +import { appendFileSync } from 'node:fs'; +import { z } from 'zod'; +import { createFakeEngine, FAKE_APP } from '../../helpers/fake-engine.ts'; +import { installFakeLoopModel } from '../../helpers/fake-loop-model.ts'; + +// Every load of the config numbers itself, and builds an engine and a tool that knows which engine is its own. +const g = globalThis as { __toolLoads?: number }; +const load = (g.__toolLoads = (g.__toolLoads ?? 0) + 1); +let running = false; +const engine = createFakeEngine({ + onStartAttempt: () => { running = true; }, + onEndAttempt: () => { running = false; }, +}).engine; +const whoami = defineTool( + { + description: 'Says which load of the config built this tool, and whether its engine has an attempt running', + inputSchema: z.object({}), + execute: async () => { + appendFileSync(new URL('./tools.log', import.meta.url), process.pid + ' load ' + load + ' running ' + running + '\\n'); + return 'load ' + load; + }, + }, + { mutates: false }, +); +const model = installFakeLoopModel((call) => + call.lastToolResult.startsWith('load ') + ? [{ toolName: 'complete_step', input: { status: 'passed', summary: call.lastToolResult } }] + : [{ toolName: 'whoami', input: {} }], +); + +export default { + targets: [{ name: 'fake', platform: 'fake', engine, app: FAKE_APP }], + workers: 1, + cache: 'off', + agents: { default: { model, tools: { whoami } } }, +} satisfies E2EConfig; +`, + }, + ); + try { + const { result, attempt, why } = onlyAttempt(outcome, 'pair'); + expect(result.status, why).toBe('passed'); + const calls = readFileSync(path.join(project.dir, 'tools.log'), 'utf8').trim().split('\n').map((line) => line.split(' ')); + // One worker made every call; each came from a different load, whose own engine was running. + expect(new Set(calls.map(([pid]) => pid)).size).toBe(1); + expect(calls.map((call) => call.slice(3).join(' '))).toEqual(['running true', 'running true', 'running true']); + const loads = calls.map((call) => call[2]); + expect(new Set(loads).size).toBe(3); + // The step's own summary is what its own tool answered. + const acts = attempt.steps.filter((step) => step.api === 'agent.act'); + expect(acts.map((step) => step.user ?? null)).toEqual(['ava', null, 'bob']); + expect(acts.map((step) => step.explanation)).toEqual(loads.map((load) => `load ${load}`)); + } finally { + project.cleanup(); + } + }); + + it("gives the test's own inconclusive judgment the vision hint of its own steps, not a peer's", async () => { + const { outcome, project } = await runProjectWithConfigFile( + { + 'tests/pair.e2e.ts': `import { test } from 'e2e'; +test('pair', { peers: { ava: {} } }, async ({ agent, peers }) => { + await peers.ava.agent.assert('the invite is on screen', { vision: true }); + await agent.assert('the order total is shown'); +}); +test('peer', { peers: { ava: {} } }, async ({ peers }) => { + await peers.ava.agent.assert('the invite is on screen', { vision: true }); + await peers.ava.agent.assert('the order total is shown'); +}); +`, + }, + { + configSource: `import type { E2EConfig } from 'e2e'; +import { createFakeEngine, FAKE_APP } from '../../helpers/fake-engine.ts'; +import { installFakeModel, judgment } from '../../helpers/fake-model.ts'; + +const engine = createFakeEngine({ + artifacts: true, + pixels: (options) => (options.pixels === true ? { pixels: { data: new Uint8Array([1, 2, 3]), mediaType: 'image/png', width: 2, height: 2, scale: 1 } } : undefined), +}).engine; +const model = installFakeModel((call) => (call.instruction === 'the invite is on screen' ? judgment(true, 'the invite is shown') : judgment('inconclusive', 'no order total is on this screen'))); + +export default { + targets: [{ name: 'fake', platform: 'fake', engine, app: FAKE_APP }], + workers: 1, + cache: 'off', + agents: { default: { model } }, +} satisfies E2EConfig; +`, + }, + ); + try { + const { result, attempt, why } = onlyAttempt(outcome, 'pair'); + expect(result.status, why).toBe('failed'); + // Ava's judgment saw pixels; the test's own user's steps never did. + expect(attempt.steps.find((step) => step.user === 'ava')?.visionInput).toBe(true); + expect(attempt.error?.code).toBe('ASSERTION_INCONCLUSIVE'); + expect(attempt.error?.message).toContain('the judge saw the semantic tree only; if the engine captures pixels, pass vision: true when the answer is in pixels'); + // Ava's own judgment after her own pixels names vision outright. + const peer = onlyAttempt(outcome, 'peer'); + expect(peer.attempt.error?.code, peer.why).toBe('ASSERTION_INCONCLUSIVE'); + expect(peer.attempt.error?.message).toContain('no order total is on this screen; the judge saw the semantic tree only; pass vision: true when the answer is in pixels'); + } finally { + project.cleanup(); + } + }); + + it("names each peer's model calls in the AI trace with the agent the peer runs as and its app's target", async () => { + const { outcome, project } = await runProjectWithConfigFile( + { + 'tests/pair.e2e.ts': `import { test } from 'e2e'; +test('pair', { platforms: ['fake'], agent: 'admin', peers: { ava: { agent: 'guest', target: 'phone' } } }, async ({ agent, peers }) => { + await agent.act('send the invite'); + await peers.ava.agent.act('accept the invite'); +}); +`, + }, + { + configSource: `import type { E2EConfig } from 'e2e'; +import { createFakeEngine, FAKE_APP } from '../../helpers/fake-engine.ts'; +import { installFakeLoopModel } from '../../helpers/fake-loop-model.ts'; + +const model = installFakeLoopModel(() => [{ toolName: 'complete_step', input: { status: 'passed', summary: 'done' } }]); + +export default { + targets: [ + { name: 'fake', platform: 'fake', engine: createFakeEngine().engine, app: FAKE_APP }, + { name: 'phone', platform: 'phone', engine: createFakeEngine().engine, app: FAKE_APP }, + ], + workers: 1, + cache: 'off', + agents: { default: { model }, admin: { model }, guest: { model } }, +} satisfies E2EConfig; +`, + runOptions: { aiTrace: true }, + }, + ); + try { + const result = outcome.results.find((entry) => entry.test.title === 'pair' && entry.target.name === 'fake')!; + expect(result.status, JSON.stringify(result.attempts.map((attempt) => attempt.error))).toBe('passed'); + const trace = JSON.parse(readFileSync(path.join(project.dir, '.e2e', 'ai-trace.json'), 'utf8')) as { + runs: { function_id: string; e2e?: Record }[]; + }; + expect(trace.runs.map((run) => [run.function_id, run.e2e?.['agent'], run.e2e?.['target'], run.e2e?.['userAgent'] ?? null, run.e2e?.['userTarget'] ?? null])).toEqual([ + ['pair · as admin · agent.act "send the invite"', 'admin', 'fake', null, null], + ['pair · as admin · peer ava as guest · agent.act "accept the invite"', 'admin', 'fake', 'guest', 'phone'], + ]); + } finally { + project.cleanup(); + } + }); + + it('refuses a second user on an engine object another user in the worker already runs on, whichever target names it', async () => { + const { outcome, project } = await runProjectWithConfigFile( + { + 'tests/pair.e2e.ts': `import { test } from 'e2e'; +test('two targets', { platforms: ['fake'], peers: { ava: { target: 'left' }, bob: { target: 'right' } } }, async () => {}); +test('one target', { platforms: ['fake'], peers: { ava: { target: 'left' }, bob: { target: 'left' } } }, async () => {}); +test('apart', { platforms: ['fake'], peers: { ava: { target: 'left' } } }, async () => {}); +`, + }, + { + configSource: `import type { E2EConfig } from 'e2e'; +import { createFakeEngine, FAKE_APP } from '../../helpers/fake-engine.ts'; + +// One engine object every load of the config shares, as one made inside a package is. +const g = globalThis as { __shared?: ReturnType['engine'] }; +const shared = (g.__shared ??= createFakeEngine({ state: true }).engine); + +export default { + targets: [ + { name: 'fake', platform: 'fake', engine: createFakeEngine({ state: true }).engine, app: FAKE_APP }, + { name: 'left', platform: 'shared', engine: shared, app: FAKE_APP }, + { name: 'right', platform: 'shared', engine: shared, app: FAKE_APP }, + ], + workers: 1, +} satisfies E2EConfig; +`, + }, + ); + try { + const onFake = (title: string) => { + const result = outcome.results.find((candidate) => candidate.test.title === title && candidate.target.name === 'fake')!; + return { result, attempt: result.attempts[0]!, why: JSON.stringify(result.attempts.map((each) => each.error)) }; + }; + for (const [title, target] of [['two targets', 'right'], ['one target', 'left']] as const) { + const { result, attempt, why } = onFake(title); + expect(result.status, why).toBe('failed'); + expect(attempt.error).toMatchObject({ code: 'INVALID_CONFIG', phase: 'launch' }); + expect(attempt.error?.message).toContain(`runs a peer on target "${target}", whose engine is the same instance as another user's`); + } + // A worker runs one test at a time: the next test's peer takes the engine again. + const apart = onFake('apart'); + expect(apart.result.status, apart.why).toBe('passed'); + } finally { + project.cleanup(); + } + }); + + it('refuses peers in a run that loaded no config file before any engine prepares, which has nowhere to load a second engine from', async () => { + const prepared: (number | null)[] = []; + const engine = createFakeEngine({ state: true, prepare: (info) => void prepared.push(info.peerSlots ?? null) }).engine; + const { outcome, project } = await runProject( + { 'tests/pair.e2e.ts': `import { test } from 'e2e';\ntest('pair', { peers: { ava: {} } }, async () => {});\n` }, + { config: { targets: [{ name: 'fake', platform: 'fake', engine, app: FAKE_APP }] } }, + ); + try { + expect(outcome.exitCode).toBe(2); + expect(outcome.results.filter((result) => result.attempts.length > 0)).toEqual([]); + expect(outcome.report.run.errors.map((error) => [error.code, error.phase, error.message])).toEqual([ + [ + 'UNSUPPORTED_CAPABILITY', + 'collection', + 'test "pair" in tests/pair.e2e.ts declares peers, which need a run from a config file: a run given a config value, or of tests registered in memory, has no file to load a second engine from', + ], + ]); + // No engine set a slot aside, or booted a device, for a peer that never runs. + expect(prepared).toEqual([]); + } finally { + project.cleanup(); + } + // A test with peers that does not run leaves the run alone. + const skipped = await runProject( + { 'tests/pair.e2e.ts': `import { test } from 'e2e';\ntest('pair', { peers: { ava: {} }, skip: true }, async () => {});\ntest('alone', async () => {});\n` }, + { config: { targets: [{ name: 'fake', platform: 'fake', engine, app: FAKE_APP }] } }, + ); + try { + expect(skipped.outcome.report.run.errors).toEqual([]); + expect(skipped.outcome.results.map((result) => [result.test.title, result.status]).toSorted()).toEqual([ + ['alone', 'passed'], + ['pair', 'skipped'], + ]); + } finally { + skipped.project.cleanup(); + } + }); +}); diff --git a/packages/e2e/tests/types/sdk-types.ts b/packages/e2e/tests/types/sdk-types.ts index 6a5a7e1d91..b4d3a61478 100644 --- a/packages/e2e/tests/types/sdk-types.ts +++ b/packages/e2e/tests/types/sdk-types.ts @@ -24,6 +24,7 @@ import { type KeyModifier, type Locator, type ModelInstance, + type PeerOptions, type PointDragResult, type PointHit, type PointTapResult, @@ -660,6 +661,38 @@ test.describe('as each persona', { agent: ['buyer', 'admin'] }, () => {}); test('as each persona', { agent: ['buyer', 'admin'] }, async () => {}); // @ts-expect-error a setup test runs once per target, so it pins at most one agent test.setup('sign in', { sessions: ['buyer'], agent: ['buyer', 'admin'] }, async () => {}); +// Peers: more users in one test, by name, each with its own target, saved session, agent, and context. +const peer: PeerOptions = { target: 'iphone', session: 'ava', agent: 'ava', agentContext: 'You are Ava.' }; +test('pays a friend', { session: 'member', peers: { ava: peer, bob: {} } }, async () => {}); +test.describe('with a friend', { peers: { ava: { session: 'ava' } } }, () => {}); +// @ts-expect-error a peer takes only target, session, agent, and agentContext +test('misspelled', { peers: { ava: { sesion: 'ava' } } }, async () => {}); +// @ts-expect-error a peer runs as one agent, not a list +test('as each', { peers: { ava: { agent: ['ava', 'bob'] } } }, async () => {}); +// @ts-expect-error a setup test saves sessions and declares no peers +test.setup('sign in', { sessions: ['ava'], peers: { ava: {} } }, async () => {}); +// Each peer has the test user's fixtures over its own app, and its engine's own. +// A suite's own fixture named peers, as before e2e had peers, keeps its own type. +const withOwnPeers = test.extend<{ peers: number }>({ peers: async (_fixtures, use) => use(7) }); +withOwnPeers('counts its own peers', async ({ peers }) => { + const count: number = peers; + // @ts-expect-error the suite's own peers is a number, not the core peers fixture + const core: Readonly> = peers; + void count; + void core; +}); +test('sees the payment', { peers: { ava: {} } }, async ({ peers }) => { + const ava = peers.ava; + // @ts-expect-error the test declares no peer bob + void peers.bob; + await ava.app.open('/'); + await ava.screen.getByText('$13.00').tap(); + const platform: string = ava.platform; + const contributed: unknown = ava['browser']; + void [platform, contributed]; + // @ts-expect-error a peer has no peers of its own + void ava.peers.bob; +}); declare const condition: boolean; // @ts-expect-error a conditionally async describe is still asynchronous test.describe('conditionally asynchronous', () => condition ? undefined : Promise.resolve()); diff --git a/packages/e2e/tests/unit/ai-trace.test.ts b/packages/e2e/tests/unit/ai-trace.test.ts index 1ff3fc1e63..2fb2150cdd 100644 --- a/packages/e2e/tests/unit/ai-trace.test.ts +++ b/packages/e2e/tests/unit/ai-trace.test.ts @@ -8,6 +8,7 @@ import { withAiTraceScope, withAiTraceStep, } from '../../src/internal/ai-trace.ts'; +import { StepRecorder } from '../../src/run/steps.ts'; import { gate } from '../helpers/gate.ts'; const SCOPE = { test: 'todos › adds one', testId: 't1', target: 'web', agent: 'default', attempt: 0 }; @@ -139,6 +140,53 @@ describe('AiTraceRecorder', () => { expect(names[1]).toMatch(/^todos › adds one · attempt 2 · agent\.assert "a{80}…"$/); }); + it("names a peer's step run after the peer, and records the peer in its scope", async () => { + const recorder = new AiTraceRecorder(); + await withAiTraceScope(SCOPE, async () => { + await withAiTraceStep('agent.act', 'send the invite', () => generation(recorder, 'mine')); + await withAiTraceStep('agent.act', 'accept the invite', () => generation(recorder, 'hers'), { name: 'ava', agent: 'default', target: 'web' }); + }); + const runs = recorder.drain().runs; + expect(runs.map((run) => run.function_id)).toEqual([ + 'todos › adds one · agent.act "send the invite"', + 'todos › adds one · peer ava · agent.act "accept the invite"', + ]); + expect(runs[0]!.e2e).toEqual({ ...SCOPE, api: 'agent.act', label: 'send the invite' }); + expect(runs[1]!.e2e).toEqual({ ...SCOPE, api: 'agent.act', label: 'accept the invite', user: 'ava', userAgent: 'default', userTarget: 'web' }); + }); + + it("names the agent a peer runs as, beside the test's own, and records the peer's agent and target in its scope", async () => { + const recorder = new AiTraceRecorder(); + const steps = new StepRecorder('attempt'); + await withAiTraceScope({ ...SCOPE, agent: 'admin' }, async () => { + await steps.run('agent', 'agent.act', 'send the invite', () => generation(recorder, 'mine')); + await steps.forUser('ava', { agent: 'guest', target: 'phone' }).run('agent', 'agent.act', 'accept the invite', () => generation(recorder, 'hers')); + await steps.forUser('bob', { agent: 'admin', target: 'web' }).run('agent', 'agent.act', 'decline the invite', () => generation(recorder, 'his')); + }); + const runs = recorder.drain().runs; + // The test's own agent still names the pair, so two pairs of a persona sweep stay apart. + expect(runs.map((run) => run.function_id)).toEqual([ + 'todos › adds one · as admin · agent.act "send the invite"', + 'todos › adds one · as admin · peer ava as guest · agent.act "accept the invite"', + 'todos › adds one · as admin · peer bob · agent.act "decline the invite"', + ]); + expect(runs.map((run) => [run.e2e?.agent, run.e2e?.target, run.e2e?.user ?? null, run.e2e?.userAgent ?? null, run.e2e?.userTarget ?? null])).toEqual([ + ['admin', 'web', null, null, null], + ['admin', 'web', 'ava', 'guest', 'phone'], + ['admin', 'web', 'bob', 'admin', 'web'], + ]); + }); + + it("attributes a peer's recorded step to the peer", async () => { + const recorder = new AiTraceRecorder(); + const steps = new StepRecorder('attempt'); + await withAiTraceScope(SCOPE, async () => { + await steps.run('agent', 'agent.act', 'send the invite', () => generation(recorder, 'mine')); + await steps.forUser('ava', { agent: 'default', target: 'web' }).run('agent', 'agent.act', 'accept the invite', () => generation(recorder, 'hers')); + }); + expect(recorder.drain().runs.map((run) => run.e2e?.user)).toEqual([undefined, 'ava']); + }); + it('continues one run across the generations of a single step, and starts a new run per step', async () => { const recorder = new AiTraceRecorder(); await withAiTraceScope(SCOPE, async () => { @@ -371,3 +419,18 @@ it('redacts run names and scope metadata before label truncation', async () => { expect(runs[0]?.function_id).not.toContain(token.slice(0, 5)); expect(runs[1]?.function_id).toBe('function '); }); + +it("redacts a peer's name, agent, and target in the scope and the run name", async () => { + const token = 'synthetic-peer-secret-271828'; + const redact = (text: string): string => text.replaceAll(token, ''); + const recorder = new AiTraceRecorder(redact); + const scope = { ...SCOPE, api: 'agent.act', label: 'accept', user: `ava-${token}`, userAgent: `agent-${token}`, userTarget: `target-${token}` }; + await withAiTraceScope(scope, async () => { + await recorder.telemetry.onStart?.({ callId: 'peer', operationId: 'ai.generateText' } as never); + await recorder.telemetry.onEnd?.({ callId: 'peer' } as never); + }); + const { runs } = recorder.drain(); + expect(runs[0]?.e2e).toEqual({ ...scope, user: 'ava-', userAgent: 'agent-', userTarget: 'target-' }); + expect(runs[0]?.function_id).toContain('ava-'); + expect(JSON.stringify(runs)).not.toContain(token); +}); diff --git a/packages/e2e/tests/unit/debug-steps.test.ts b/packages/e2e/tests/unit/debug-steps.test.ts index b932f3f8ed..007a851045 100644 --- a/packages/e2e/tests/unit/debug-steps.test.ts +++ b/packages/e2e/tests/unit/debug-steps.test.ts @@ -114,6 +114,12 @@ describe('agentStepTable', () => { expect(stepModelLabel(acted)).toBe('typesafe-ai/jev'); }); + it("names the peer before a peer's step", () => { + const table = agentStepTable([result('invites', [step('s1', 'send the invite'), step('s2', 'accept the invite', { user: 'ava' })])], []); + const [, ...rows] = cells(table); + expect(rows.map((row) => row[0])).toEqual(['agent.act "send the invite"', 'ava · agent.act "accept the invite"']); + }); + it('shows `-` for a step whose model record lacks provenance and never prints undefined', () => { const table = agentStepTable( [result('pays', [ diff --git a/packages/e2e/tests/unit/explore-body.test.ts b/packages/e2e/tests/unit/explore-body.test.ts index 38bde34d49..1154a1d2b7 100644 --- a/packages/e2e/tests/unit/explore-body.test.ts +++ b/packages/e2e/tests/unit/explore-body.test.ts @@ -48,7 +48,7 @@ function fixtures(script: Script, state: ExploreState, change?: { readonly skipp const app = { open: async (target?: string) => void opened.push(target ?? '/') } as unknown as App; const body = createExploreBody({ state, stepTimeoutMs: 240_000, openApp: true, ...(change === undefined ? {} : { change }) }); return { - run: () => body({ agent, app, screen: {} as never, platform: 'web' } as TestFixtures), + run: () => body({ agent, app, screen: {} as never, platform: 'web', peers: {} } as TestFixtures), planInstructions, skipOffered, actCalls, @@ -194,7 +194,7 @@ describe('the exploration body', () => { } as unknown as Agent; const app = { open: async () => undefined } as unknown as App; const body = createExploreBody({ state, stepTimeoutMs: 240_000, openApp: true, now: () => clock }); - await body({ agent, app, screen: {} as never, platform: 'web' } as TestFixtures); + await body({ agent, app, screen: {} as never, platform: 'web', peers: {} } as TestFixtures); // 300 s left minus the 60 s finish reserve. expect(timeouts).toEqual([240_000]); expect(planInstructions).toHaveLength(2); @@ -222,7 +222,7 @@ describe('the exploration body', () => { const app = { open: async () => void opened.push('/') } as unknown as App; // Nothing ran and nothing was found, so the body concludes blocked; the clock is what this test is about. await expect( - Promise.resolve().then(() => createExploreBody({ state, stepTimeoutMs: 240_000, openApp: false, now: () => clock })({ agent, app, screen: {} as never, platform: 'ios' } as TestFixtures)), + Promise.resolve().then(() => createExploreBody({ state, stepTimeoutMs: 240_000, openApp: false, now: () => clock })({ agent, app, screen: {} as never, platform: 'ios', peers: {} } as TestFixtures)), ).rejects.toMatchObject({ code: 'AUTOMATION_UNSUPPORTED' }); expect(opened).toEqual([]); expect(acts).toEqual([]); @@ -253,7 +253,7 @@ describe('the exploration body', () => { }, } as unknown as Agent; const app = { open: async () => undefined } as unknown as App; - await createExploreBody({ state, stepTimeoutMs: 240_000, openApp: true, accounts: [{ name: 'ada', username: 'ada@example.test' }] })({ agent, app, screen: {} as never, platform: 'web' } as TestFixtures); + await createExploreBody({ state, stepTimeoutMs: 240_000, openApp: true, accounts: [{ name: 'ada', username: 'ada@example.test' }] })({ agent, app, screen: {} as never, platform: 'web', peers: {} } as TestFixtures); expect(planInstructions[0]).toContain('- ada (username: ada@example.test)'); expect(planInstructions[0]).not.toContain('bookworm'); const params = actParams[0] as { credentials: { ada: { username: string; password: unknown } } }; @@ -401,7 +401,7 @@ describe('the exploration body', () => { const invalid = () => new AgentError('MODEL_OUTPUT_INVALID', 'extracted data failed schema validation'); const app = { open: async () => undefined } as unknown as App; const run = (state: ExploreState, agent: Agent) => - createExploreBody({ state, stepTimeoutMs: 240_000, openApp: true })({ agent, app, screen: {} as never, platform: 'web' } as TestFixtures); + createExploreBody({ state, stepTimeoutMs: 240_000, openApp: true })({ agent, app, screen: {} as never, platform: 'web', peers: {} } as TestFixtures); const first = new ExploreState('goal', budgets); let plans = 0; @@ -476,7 +476,7 @@ describe('the exploration body', () => { }, act: async () => ({ summary: 'toured', modelCalls: 1, actions: 3 }), } as unknown as Agent, - app, screen: {} as never, platform: 'web', + app, screen: {} as never, platform: 'web', peers: {}, } as TestFixtures); expect(state.steps.map((step) => step.title)).toEqual(['Survey the app']); expect(state.ended).toBe('finished'); diff --git a/packages/e2e/tests/unit/peer-slots.test.ts b/packages/e2e/tests/unit/peer-slots.test.ts new file mode 100644 index 0000000000..296bff77e9 --- /dev/null +++ b/packages/e2e/tests/unit/peer-slots.test.ts @@ -0,0 +1,170 @@ +/** + * Slots for peers: how many each target must serve beside its own workers, + * how worker counts are lowered where an engine serves fewer, and which + * slots each worker's peers take, so no two users of a run share one. + */ + +import { describe, expect, it } from 'vitest'; +import type { TestTargetPair } from '../../src/collect/select.ts'; +import { fitWorkers, peerSlotsOf, peersBrought, reservedPeerSlot, slotsNeeded, type PeersBrought } from '../../src/run/peer-slots.ts'; + +/** A pair on `target` whose test declares one peer per entry of `peers`, each on the named target or the test's own. */ +function pair(target: string, peers: readonly (string | undefined)[], disposition: TestTargetPair['disposition'] = 'run'): TestTargetPair { + return { + target: { name: target }, + disposition, + options: { peers: peers.map((peer, index) => ({ name: `peer${index}`, ...(peer === undefined ? {} : { target: peer }) })) }, + } as unknown as TestTargetPair; +} + +const brought = (entries: Record>): PeersBrought => + new Map(Object.entries(entries).map(([from, on]) => [from, new Map(Object.entries(on))])); + +describe('peersBrought', () => { + it('keeps, per test target, the most peers one runnable test puts on each target', () => { + const counted = peersBrought({ + pairs: [ + pair('web', ['iphone', 'iphone', undefined]), + // A later test with fewer peers leaves the most standing. + pair('web', ['iphone']), + pair('web', []), + pair('iphone', [undefined]), + // A test that does not run opens no peer. + pair('web', ['iphone', 'iphone', 'iphone'], 'skip'), + ], + }); + expect([...counted].map(([from, on]) => [from, [...on]])).toEqual([ + ['web', [['iphone', 2], ['web', 1]]], + ['iphone', [['iphone', 1]]], + ]); + expect(peersBrought({ pairs: [pair('web', [])] }).size).toBe(0); + }); +}); + +describe('slotsNeeded', () => { + it("adds, to a target's own workers, a slot per peer every worker brings to it", () => { + const peers = brought({ web: { iphone: 2 }, iphone: { iphone: 1 } }); + const workers = new Map([['web', 3], ['iphone', 2]]); + // 2 own workers, each with 1 peer of its own, and 3 web workers with 2 peers each. + expect(slotsNeeded('iphone', workers, peers)).toEqual({ slots: 10, peerSlots: 8 }); + expect(slotsNeeded('web', workers, peers)).toEqual({ slots: 3, peerSlots: 0 }); + expect(slotsNeeded('tablet', workers, peers)).toEqual({ slots: 0, peerSlots: 0 }); + }); +}); + +describe('fitWorkers', () => { + it('leaves every count as planned when each engine serves enough, or names no bound', () => { + const fitted = fitWorkers( + [{ name: 'web', workers: 2, served: undefined }, { name: 'iphone', workers: 1, served: 3 }], + brought({ web: { iphone: 1 } }), + ); + expect([...fitted.workers]).toEqual([['web', 2], ['iphone', 1]]); + expect(fitted.notices).toEqual([]); + }); + + it("lowers a short target's own workers first, down to one, then the workers of the targets that bring it peers, and says so", () => { + // 3 own workers and 2 web workers with a peer each need 5; the engine serves 3. + const first = fitWorkers( + [{ name: 'web', workers: 2, served: undefined }, { name: 'iphone', workers: 3, served: 3 }], + brought({ web: { iphone: 1 } }), + ); + expect([...first.workers]).toEqual([['web', 2], ['iphone', 1]]); + expect(first.notices).toEqual([ + 'target "iphone" runs 1 worker at a time, not 3: the peers of tests take slots of their own on their targets, and an engine serves only so many at once', + ]); + // With 2 served, its own worker stays and the web workers give way. + const second = fitWorkers( + [{ name: 'web', workers: 3, served: undefined }, { name: 'iphone', workers: 2, served: 2 }], + brought({ web: { iphone: 1 } }), + ); + expect([...second.workers]).toEqual([['web', 1], ['iphone', 1]]); + // A count left above one reads in the plural. + expect(fitWorkers([{ name: 'web', workers: 2, served: undefined }, { name: 'iphone', workers: 3, served: 4 }], brought({ web: { iphone: 1 } })).notices).toEqual([ + 'target "iphone" runs 2 workers at a time, not 3: the peers of tests take slots of their own on their targets, and an engine serves only so many at once', + ]); + expect(second.notices).toEqual([ + 'target "web" runs 1 worker at a time, not 3: the peers of tests take slots of their own on their targets, and an engine serves only so many at once', + 'target "iphone" runs 1 worker at a time, not 2: the peers of tests take slots of their own on their targets, and an engine serves only so many at once', + ]); + }); + + it('lowers first the target whose workers bring the most peers', () => { + const fitted = fitWorkers( + [{ name: 'web', workers: 2, served: undefined }, { name: 'tablet', workers: 2, served: undefined }, { name: 'iphone', workers: 0, served: 5 }], + brought({ web: { iphone: 1 }, tablet: { iphone: 2 } }), + ); + // 2 + 4 needed of 5: one tablet worker fewer leaves 2 + 2. + expect([...fitted.workers]).toEqual([['web', 2], ['tablet', 1], ['iphone', 0]]); + }); + + it("counts a target's own tests' peers with each of its own workers", () => { + // Two devices: one worker, with its test's own user on one and the peer on the other. + const fitted = fitWorkers([{ name: 'iphone', workers: 2, served: 2 }], brought({ iphone: { iphone: 1 } })); + expect([...fitted.workers]).toEqual([['iphone', 1]]); + }); + + it('says nothing of an engine that serves fewer workers than planned when no peer took a slot', () => { + const fitted = fitWorkers([{ name: 'iphone', workers: 3, served: 2 }, { name: 'web', workers: 2, served: undefined }], brought({ web: { web: 1 } })); + expect([...fitted.workers]).toEqual([['iphone', 2], ['web', 2]]); + expect(fitted.notices).toEqual([]); + expect(fitWorkers([{ name: 'iphone', workers: 3, served: 2 }], new Map()).notices).toEqual([]); + }); + + it('fails, naming the target and the count, when it cannot serve one worker of each target at once', () => { + expect(() => + fitWorkers([{ name: 'web', workers: 2, served: undefined }, { name: 'iphone', workers: 2, served: 1 }], brought({ web: { iphone: 1 } })), + ).toThrow( + 'target "iphone" serves 1 at once, and this run needs 2 of it at once with one worker per target: 1 for its own worker, 1 for the peer of one "web" test; a peer takes a slot of its own, a device on a phone target, so give the target more, or keep the tests that put a peer on it out of this run', + ); + // Its own tests' peers, and a target with no worker of its own. + expect(() => fitWorkers([{ name: 'iphone', workers: 1, served: 2 }], brought({ iphone: { iphone: 2 } }))).toThrow( + 'serves 2 at once, and this run needs 3 of it at once with one worker per target: 1 for its own worker, 2 for the peers of one of its own tests;', + ); + expect(() => + fitWorkers([{ name: 'web', workers: 1, served: undefined }, { name: 'iphone', workers: 0, served: 1 }], brought({ web: { iphone: 2 } })), + ).toThrow('target "iphone" serves 1 at once, and this run needs 2 of it at once with one worker per target: 2 for the peers of one "web" test;'); + try { + fitWorkers([{ name: 'iphone', workers: 1, served: 1 }], brought({ iphone: { iphone: 1 } })); + expect.unreachable(); + } catch (error) { + expect(error).toMatchObject({ code: 'ENGINE_FAILURE', category: 'infrastructure' }); + } + }); +}); + +describe('peerSlotsOf', () => { + it("gives every worker's peers slots no worker and no other peer holds: the target's own workers first, then a block per target in order", () => { + const peers = brought({ web: { iphone: 2 }, iphone: { iphone: 1 }, tablet: { iphone: 1, web: 1 } }); + const workers = new Map([['web', 2], ['iphone', 2], ['tablet', 1]]); + const order = ['web', 'iphone', 'tablet']; + const taken: number[] = [0, 1]; + for (const [target, count] of workers) { + for (let slot = 0; slot < count; slot += 1) { + const reserved = peerSlotsOf(target, slot, order, workers, peers)['iphone']; + if (reserved !== undefined) for (let index = 0; index < reserved.count; index += 1) taken.push(reserved.firstSlot + index); + } + } + // 2 own workers, 4 for the web workers' peers, 2 for its own workers' peers, 1 for the tablet worker's: every slot once. + expect(taken.toSorted((a, b) => a - b)).toEqual([0, 1, 2, 3, 4, 5, 6, 7, 8]); + expect(slotsNeeded('iphone', workers, peers).slots).toBe(9); + expect(peerSlotsOf('web', 1, order, workers, peers)).toEqual({ iphone: { firstSlot: 4, count: 2 } }); + expect(peerSlotsOf('iphone', 1, order, workers, peers)).toEqual({ iphone: { firstSlot: 7, count: 1 } }); + expect(peerSlotsOf('tablet', 0, order, workers, peers)).toEqual({ iphone: { firstSlot: 8, count: 1 }, web: { firstSlot: 2, count: 1 } }); + expect(peerSlotsOf('web', 0, order, workers, brought({}))).toEqual({}); + }); +}); + +describe('reservedPeerSlot', () => { + it('gives each peer on a target the next reserved slot, with what the target handed its workers', () => { + const reserved = { iphone: { firstSlot: 3, count: 2, env: { POOL: 'x' } } }; + expect(reservedPeerSlot(reserved, 'iphone', 0, 'test "pays"')).toEqual({ firstSlot: 3, count: 2, env: { POOL: 'x' }, slot: 3 }); + expect(reservedPeerSlot(reserved, 'iphone', 1, 'test "pays"').slot).toBe(4); + }); + + it('refuses a peer the run reserved nothing for, so it never takes a slot or a device another user holds', () => { + const refusal = 'test "pays" runs a peer on target "iphone", and the run reserved no slot there for it; a peer never takes a slot, or a device, the run did not set aside'; + expect(() => reservedPeerSlot({ iphone: { firstSlot: 3, count: 2 } }, 'iphone', 2, 'test "pays"')).toThrow(refusal); + expect(() => reservedPeerSlot({}, 'iphone', 0, 'test "pays"')).toThrow(refusal); + expect(() => reservedPeerSlot(undefined, 'iphone', 0, 'test "pays"')).toThrow(refusal); + }); +}); diff --git a/packages/e2e/tests/unit/registry.test.ts b/packages/e2e/tests/unit/registry.test.ts index 2c97e65e2b..3f41fe7852 100644 --- a/packages/e2e/tests/unit/registry.test.ts +++ b/packages/e2e/tests/unit/registry.test.ts @@ -81,7 +81,7 @@ describe('registration', () => { 'test options has unknown key "timout"; did you mean "timeout"?', ); await expect(register(() => test('x', { retry: 2 } as never, noop))).rejects.toThrow( - 'test options has unknown key "retry"; expected one of timeout, retries, tags, skip, fail, only, platforms, requires, session, agentContext, agent, trace, video', + 'test options has unknown key "retry"; expected one of timeout, retries, tags, skip, fail, only, platforms, requires, session, peers, agentContext, agent, trace, video', ); await expect(register(() => test.describe('group', { searial: true } as never, () => {}))).rejects.toThrow( 'describe options has unknown key "searial"; did you mean "serial"?', @@ -328,6 +328,109 @@ describe('serial groups', () => { }); }); +describe('peers', () => { + const register = (declare: () => void) => collectModule(async () => declare()); + + it('registers a map of named peers on a test and a describe, as declared', async () => { + const registration = await register(() => { + test.describe('group', { peers: { ava: { session: 'ava' } } }, () => { + test('pays', { peers: { ava: { target: 'iphone', agent: 'ava', agentContext: 'You are Ava.' }, 'bob.2': {} } }, noop); + }); + test('clears', { peers: {} }, noop); + }); + expect(registration.tests.map((item) => item.options.peers)).toEqual([ + { ava: { target: 'iphone', agent: 'ava', agentContext: 'You are Ava.' }, 'bob.2': {} }, + {}, + ]); + // A setup test saves sessions and declares no peers. + await expect(register(() => test.setup('login', { sessions: ['admin'], peers: {} } as never, noop))).rejects.toThrow( + /^setup options has unknown key "peers"/, + ); + }); + + it('rejects peers that are not a map of names to objects', async () => { + await expect(register(() => test('x', { peers: ['ava'] } as never, noop))).rejects.toThrow( + 'test options: peers must map peer names to their options, e.g. peers: { ava: { session: \'ava\' } }, got', + ); + await expect(register(() => test('x', { peers: null } as never, noop))).rejects.toThrow(/peers must map peer names/); + await expect(register(() => test('x', { peers: { ava: 'ava' } } as never, noop))).rejects.toThrow( + /test options: peer "ava" must be an object of target, session, agent, and agentContext, got/, + ); + await expect(register(() => test('x', { peers: { ava: null } } as never, noop))).rejects.toThrow(/peer "ava" must be an object/); + }); + + it('rejects a peer name a session name could not be', async () => { + for (const name of ['', 'two words', 'x'.repeat(129), 'a/b']) { + await expect(register(() => test('x', { peers: { [name]: {} } }, noop))).rejects.toThrow( + `test options: invalid peer name ${JSON.stringify(name)}: names are 1 through 128 ASCII letters`, + ); + } + await expect(register(() => test('x', { peers: { ['x'.repeat(128)]: {} } }, noop))).resolves.toBeDefined(); + }); + + it("rejects a peer name that could not be a folder of the peer's own: a dot, two dots, or another peer's name in other case", async () => { + for (const name of ['.', '..']) { + await expect(register(() => test('x', { peers: { [name]: {} } }, noop))).rejects.toThrow( + `test options: invalid peer name ${JSON.stringify(name)}: names are 1 through 128 ASCII letters, numbers, "_", "-", or ".", and not "." or ".."`, + ); + } + await expect(register(() => test('x', { peers: { Ava: {}, ava: {} } }, noop))).rejects.toThrow( + 'test options: peer names "Ava" and "ava" differ only in case; each peer\'s files go in a folder named after it, which a case-insensitive disk would share', + ); + await expect(register(() => test('x', { peers: { '.ava': {}, 'ava.': {}, '...': {}, ava: {}, bob: {} } }, noop))).resolves.toBeDefined(); + }); + + it('rejects an unknown peer key, naming the nearest, and fields that are not non-empty strings', async () => { + await expect(register(() => test('x', { peers: { ava: { sesion: 'ava' } } } as never, noop))).rejects.toThrow( + 'test options: peer "ava" has unknown key "sesion"; did you mean "session"?', + ); + for (const key of ['target', 'session', 'agent', 'agentContext']) { + await expect(register(() => test('x', { peers: { ava: { [key]: '' } } } as never, noop))).rejects.toThrow( + `test options: peer "ava": ${key} must be a non-empty string, got`, + ); + await expect(register(() => test('x', { peers: { ava: { [key]: 7 } } } as never, noop))).rejects.toThrow( + `test options: peer "ava": ${key} must be a non-empty string, got`, + ); + } + await expect(register(() => test('x', { peers: { ava: { session: 'two words' } } }, noop))).rejects.toThrow( + 'test options: peer "ava": invalid session name "two words"', + ); + }); + + it('checks peers on a describe the same way', async () => { + await expect(register(() => test.describe('group', { peers: { 'a b': {} } }, () => {}))).rejects.toThrow( + 'describe options: invalid peer name "a b"', + ); + }); + + it('is refused on, inside, and under a serial group, which runs on one shared app', async () => { + await expect(register(() => test.describe('group', { serial: true }, () => { + test('member', { peers: { ava: {} } }, noop); + }))).rejects.toThrow('test option "peers" cannot be overridden inside a serial group; it belongs to the unit'); + await expect(register(() => test.describe('group', { serial: true, peers: { ava: {} } }, () => {}))).rejects.toThrow( + 'describe option "peers" cannot be set on or inside a serial group; a serial group runs on one shared app', + ); + await expect(register(() => test.describe('group', { serial: true }, () => { + test.describe('inner', { peers: { ava: {} } }, () => {}); + }))).rejects.toThrow('describe option "peers" cannot be set on or inside a serial group'); + }); + + it('refuses a serial group inside a group whose peers its tests would take, and allows one under a group that clears them', async () => { + await expect(register(() => test.describe('outer', { peers: { ava: {} } }, () => { + test.describe('group', { serial: true }, () => { + test('member', noop); + }); + }))).rejects.toThrow('describe option "serial" cannot be set inside a group with peers ("outer"); a serial group runs on one shared app'); + await expect(register(() => test.describe('outer', { peers: { ava: {} } }, () => { + test.describe('alone', { peers: {} }, () => { + test.describe('group', { serial: true }, () => { + test('member', noop); + }); + }); + }))).resolves.toBeDefined(); + }); +}); + describe('test.extend', () => { const fixture = async (_fixtures: unknown, use: (value: string) => Promise) => { await use('value'); @@ -388,6 +491,22 @@ describe('test.extend', () => { }); }); +describe("a suite's own fixture named peers", () => { + const register = (declare: () => void) => collectModule(async () => declare()); + const own = test.extend<{ peers: string }>({ peers: async (_fixtures, use) => use('mine') }); + + it('keeps working for its tests that declare no peers, as before e2e had peers', async () => { + await expect(register(() => own('no peers', noop))).resolves.toBeDefined(); + await expect(register(() => test.describe('group', { peers: { ava: {} } }, () => own('cleared', { peers: {} }, noop)))).resolves.toBeDefined(); + }); + + it('refuses a test that declares peers through it, on the test or a describe around it', async () => { + const refusal = 'declares peers, but its test.extend() chain defines a fixture named "peers"; rename that fixture to give the test its peers'; + await expect(register(() => own('with peers', { peers: { ava: {} } }, noop))).rejects.toThrow(`test "with peers" ${refusal}`); + await expect(register(() => test.describe('group', { peers: { ava: {} } }, () => own('inside', noop)))).rejects.toThrow(`test "inside" ${refusal}`); + }); +}); + describe('collectFromRegistration', () => { it("derives each test's tags from its describe layers and its own, outermost first, each once", async () => { const registration = await collectModule(async () => { diff --git a/packages/e2e/tests/unit/report-failure-text.test.ts b/packages/e2e/tests/unit/report-failure-text.test.ts index a9ab9458fd..dbaba288bb 100644 --- a/packages/e2e/tests/unit/report-failure-text.test.ts +++ b/packages/e2e/tests/unit/report-failure-text.test.ts @@ -167,6 +167,79 @@ describe('renderTracePage', () => { return renderTracePage(document, failing, outcome(failing, NO_GROUPS), { artifactsDir: '.e2e/artifacts', readArtifact }); }; + it("tells a peer's steps, log lines, environment, screen at failure, video, and files under the peer's name", () => { + const at = (seconds: number) => new Date(Date.UTC(2026, 9, 27, 10, 0, seconds)).toISOString(); + const file = (id: string, kind: 'video' | 'screenshot' | 'log', path: string, user?: string) => ({ + id, + kind, + mediaType: kind === 'video' ? 'video/webm' : kind === 'log' ? 'text/plain' : 'image/png', + path, + redaction: 'incomplete' as const, + startedAt: at(kind === 'video' && user !== undefined ? 3 : 0), + producer: { kind: 'attempt' as const }, + ...(user === undefined ? {} : { user }), + }); + const error = reportError(); + const screens: Record = { 't/peers/ava/screen-at-failure.txt': '#n1 heading "Invites"', 't/screen-at-failure.txt': '#n1 heading "Cart"' }; + const body = page( + [ + failed({ + error, + steps: [ + step({ index: 0, api: 'app.open', label: '/cart', startedAt: at(0) }), + step({ index: 1, api: 'app.open', label: '/invites', user: 'ava', startedAt: at(4) }), + step({ index: 2, api: 'app.reload', label: '/cart', startedAt: at(5) }), + step({ index: 3, api: 'locator.tap', label: 'Accept', user: 'ava', status: 'failed', error, startedAt: at(6) }), + ], + appLog: [ + { source: 'console', level: 'warning', text: 'invite expires soon', at: at(5), step: 1, user: 'ava' }, + { source: 'console', level: 'warning', text: 'cart is empty', at: at(1), step: 0 }, + ], + environment: { browser: 'chromium 141' }, + peers: { + ava: { target: 'web-b', environment: { browser: 'webkit 26' }, failure: { url: '/invites', screen: 'a:3' } }, + bob: { target: 'web-b' }, + carol: { target: 'web' }, + }, + failure: { url: '/cart', screen: 'a:2' }, + artifacts: [ + file('a:0', 'video', 't/video/video.webm'), + file('a:1', 'video', 't/peers/ava/video/video.webm', 'ava'), + file('a:2', 'log', 't/screen-at-failure.txt'), + file('a:3', 'log', 't/peers/ava/screen-at-failure.txt', 'ava'), + ], + }), + ], + (reportPath) => screens[reportPath], + ); + const lines = body.split('\n'); + expect(lines).toContain('Ran on: browser `chromium 141`'); + expect(lines).toContain('ava ran on target `web-b`: browser `webkit 26`'); + // A peer on another target says which even with nothing else to tell; one on the test's own says nothing. + expect(lines).toContain('bob ran on target `web-b`'); + expect(lines.some((line) => line.startsWith('carol'))).toBe(false); + const steps = lines.filter((line) => /^\d\. /.test(line)); + // Each step is placed on its own user's video: Ava's began at 0:03, and the test's own runs on under it. + expect(steps[0]).toMatch(/^1\. ✓ `app\.open` `\/cart` \(100ms, video 0:00\)/u); + expect(steps[1]).toMatch(/^2\. ✓ ava · `app\.open` `\/invites` \(100ms, video 0:01\)/u); + expect(steps[2]).toMatch(/^3\. ✓ `app\.reload` `\/cart` \(100ms, video 0:05\)/u); + expect(steps[3]).toMatch(/^4\. ✗ ava · `locator\.tap` `Accept` \(100ms, video 0:03\)/u); + expect(lines).toContain('- step 1 · ⚠ console warning: `cart is empty`'); + expect(lines).toContain('- step 2 · ava · ⚠ console warning: `invite expires soon`'); + const mine = lines.indexOf('## Screen at failure'); + const hers = lines.indexOf('## Screen at failure: ava'); + expect(mine).toBeGreaterThan(-1); + expect(hers).toBeGreaterThan(mine); + expect(lines.slice(mine, hers).join('\n')).toContain('#n1 heading "Cart"'); + expect(lines.slice(hers).join('\n')).toContain('#n1 heading "Invites"'); + const evidence = lines.slice(lines.indexOf('## Evidence')); + expect(evidence).toContain('- screen `.e2e/artifacts/t/screen-at-failure.txt`'); + expect(evidence).toContain('- ava · screen `.e2e/artifacts/t/peers/ava/screen-at-failure.txt`'); + expect(evidence).toContain('- video `.e2e/artifacts/t/video/video.webm`'); + expect(evidence).toContain('- ava · video `.e2e/artifacts/t/peers/ava/video/video.webm`'); + expect(screenLines(toldAttempt(reportResult({ status: 'failed', attempts: [failed({ peers: { ava: { target: 'web', failure: { url: '/invites' } } }, failure: { url: '/cart' } })] }), outcome(reportResult({ status: 'failed', attempts: [failed({ peers: { ava: { target: 'web', failure: { url: '/invites' } } }, failure: { url: '/cart' } })] }), NO_GROUPS)), 'ava')).toEqual(['Screen: `/invites`']); + }); + it('lists the screenshots a step attached under that step, and no other artifact', () => { const image = (id: string, file: string) => ({ id, kind: 'screenshot' as const, mediaType: 'image/png', path: `t/screenshots/${file}`, redaction: 'complete' as const, producer: { kind: 'step' as const, stepId: 's1' } }); const log = { id: 'a:3', kind: 'log' as const, mediaType: 'text/plain', path: 't/console.txt', redaction: 'complete' as const, producer: { kind: 'step' as const, stepId: 's1' } }; diff --git a/packages/e2e/tests/unit/report-junit.test.ts b/packages/e2e/tests/unit/report-junit.test.ts index be48f03965..2f2eeb8a8c 100644 --- a/packages/e2e/tests/unit/report-junit.test.ts +++ b/packages/e2e/tests/unit/report-junit.test.ts @@ -5,7 +5,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import type { FinishedRun } from '../../src/types.ts'; import type { Report1Document, ReportSerialGroup } from '../../src/report/build.ts'; import { junitReporter, renderJunitReport, type JunitReportOptions } from '../../src/report/junit.ts'; -import { REPORT_AT as AT, reportAttempt, reportDocument, reportError, reportResult } from '../helpers/report.ts'; +import { REPORT_AT as AT, reportAttempt, reportDocument, reportError, reportResult, reportStep } from '../helpers/report.ts'; /** XML 1.0 `Char`, over code points: a lone surrogate is a code point of its own and falls outside every range. */ // oxlint-disable-next-line no-control-regex -- the allowed range is the point @@ -530,6 +530,16 @@ describe('renderJunitReport', () => { expect(xml).toContain('[[ATTACHMENT|shots/target.png]]'); }); + it("attaches the screenshot of the peer whose step failed, not the test user's", () => { + const failed = reportStep({ status: 'failed', user: 'ava', error: reportError({ message: 'heading not visible' }) }); + const document = failedWithShot({ + steps: [reportStep({ index: 0 }), { ...failed, index: 1 }], + peers: { ava: { target: 'chromium', failure: { screenshot: 'shot-ava' } } }, + artifacts: [shotArtifact('shot-1', 'checkout/001-failure.png'), { ...shotArtifact('shot-ava', 'checkout/peers/ava/001-failure.png'), user: 'ava' }], + }); + expect(render(document, { artifactsDir: '.' })).toContain('[[ATTACHMENT|checkout/peers/ava/001-failure.png]]'); + }); + it('takes the screenshot of the told attempt when the last retry was interrupted', () => { const interrupted = reportAttempt({ id: 'attempt-2', diff --git a/packages/e2e/tests/unit/report-list.test.ts b/packages/e2e/tests/unit/report-list.test.ts index 1a11b4d98e..9e26bc8d6c 100644 --- a/packages/e2e/tests/unit/report-list.test.ts +++ b/packages/e2e/tests/unit/report-list.test.ts @@ -6,6 +6,8 @@ import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vites import { resultId } from '../../src/internal/ids.ts'; import { visibleWidth } from '../../src/report/format.ts'; import { ListReporter } from '../../src/report/list.ts'; +import { stepLine, stepPromptLine, stepPromptRows } from '../../src/report/list-steps.ts'; +import picocolors from 'picocolors'; import { userFrame } from '../../src/report/code-frame.ts'; import type { CacheWrite } from '../../src/cache/context.ts'; import type { RunEventFact, RunEventOf, RunEventResult } from '../../src/run/events.ts'; @@ -455,6 +457,46 @@ describe('ListReporter', () => { expect(lines).toContain(' ❯ screen .e2e/artifacts/chromium/a/attempt-0/screen.txt'); }); + it("shows the screen of the peer whose step failed, named, and not the test user's", () => { + const { lines, output } = capture(); + const reporter = plainReporter(output); + reporter.handle(runStarted()); + reporter.handle(plan([{ file: 'tests/a.e2e.ts', tests: 1 }])); + const step = (user: string | undefined, status: string) => + ({ + id: `${user ?? 'own'}-step`, + index: 0, + kind: 'locator', + api: 'locator.tap', + label: 'Accept', + status, + startedAt: new Date(0).toISOString(), + durationMs: 10, + events: [], + artifacts: [], + ...(user === undefined ? {} : { user }), + ...(status === 'failed' ? { error: { category: 'test', code: 'ASSERTION_FAILED', message: 'no Accept button', retryable: false } } : {}), + }) as unknown as AttemptRecord['steps'][number]; + const failed = failedAttempt('no Accept button'); + failed.steps = [step(undefined, 'passed'), step('ava', 'failed')]; + const screenText = (id: string, user: string | undefined, file: string) => ({ + id, kind: 'log' as const, mediaType: 'text/plain', path: file, redaction: 'complete' as const, producer: { kind: 'attempt' as const }, ...(user === undefined ? {} : { user }), + }); + failed.failure = { url: 'https://app.test/cart', candidates: ['button "Checkout"'], screen: 'attempt-1:artifact:0' }; + failed.peers = { ava: { target: 'chromium', failure: { url: 'https://app.test/invites', candidates: ['button "Accept invite"'], screen: 'attempt-1:artifact:1' } } }; + failed.artifacts = [ + screenText('attempt-1:artifact:0', undefined, 'chromium/a/attempt-0/screen.txt'), + screenText('attempt-1:artifact:1', 'ava', 'chromium/a/attempt-0/peers/ava/screen.txt'), + ]; + reporter.handle(finished(result({ status: 'failed', id: 'a', file: 'tests/a.e2e.ts', title: ['invites'], attempts: [failed] }))); + reporter.handle(runFinished({ status: 'failed', exitCode: 1, reportPath: '/project/.e2e/report.json' })); + expect(lines).toContain(' ❯ at ava · https://app.test/invites'); + expect(lines).toContain(' ❯ on screen button "Accept invite"'); + expect(lines).toContain(' ❯ screen .e2e/artifacts/chromium/a/attempt-0/peers/ava/screen.txt'); + expect(lines.join('\n')).not.toContain('https://app.test/cart'); + expect(lines.join('\n')).not.toContain('Checkout'); + }); + it('quotes the first app errors under the tally, loopback origins dropped, and counts the rest', () => { const { lines, output } = capture(); const reporter = plainReporter(output); @@ -1286,6 +1328,59 @@ describe('ListReporter', () => { expect(chunks.at(-1)).not.toContain('└──'); }); + it("shows each user's running step under its test, and names the peer on its finished steps and at the --step prompt", () => { + const restore = withTerminalSize({ columns: 120, rows: 40 }); + try { + const { chunks, output } = liveCapture(); + const reporter = new ListReporter(output, { live: true, colors: false, stepping: true }); + reporter.handle(runStarted()); + reporter.handle(plan([{ file: 'tests/invite.e2e.ts', tests: 1 }])); + reporter.handle(testStarted('t1', 'invites a friend', 'chromium', 'tests/invite.e2e.ts')); + const step = (progress: object, user?: string) => + reporter.handle({ + type: 'step', + testId: 't1', + agent: 'default', + repeat: 0, + target: 'chromium', + progress: { ...progress, identity: { attemptId: 'a', attemptIndex: 0, stepId: user ?? 'own', stepIndex: 0, ...(user === undefined ? {} : { user }) } }, + } as never); + const shown = () => { + const window = chunks.at(-1)!.replace(ANSI_PATTERN, '').split('\n').filter((line) => line.trim() !== ''); + const row = window.findIndex((line) => line.includes('invites a friend')); + return window.slice(row + 1, window.findIndex((line) => line.includes('Test Files'))).map((line) => line.trim()); + }; + step({ phase: 'start', kind: 'agent', api: 'agent.act', label: 'pay' }); + step({ phase: 'start', kind: 'agent', api: 'agent.act', label: 'accept' }, 'ava'); + // What each user's step waits on shows under that step only. + step({ phase: 'activity', api: 'agent.act', activity: 'action' }, 'ava'); + expect(shown().map((line) => line.replace(/^\S+ (Acting|Thinking)$/u, '$1'))).toEqual(['↳ agent.act "pay"', 'Thinking', '↳ ava · agent.act "accept"', 'Acting']); + step({ phase: 'replay', api: 'agent.act', active: true }); + expect(shown().map((line) => line.replace(/^\S+ (Acting|Thinking|Replaying)$/u, '$1'))).toEqual(['↳ agent.act "pay"', 'Replaying', '↳ ava · agent.act "accept"', 'Acting']); + step({ phase: 'end', kind: 'agent', api: 'agent.act', label: 'pay', status: 'passed', durationMs: 40, modelCalls: 0 }); + step({ phase: 'end', kind: 'agent', api: 'agent.act', label: 'accept', status: 'passed', durationMs: 50, modelCalls: 0 }, 'ava'); + step({ phase: 'start', kind: 'locator', api: 'locator.click', label: 'Send invite' }); + step({ phase: 'start', kind: 'locator', api: 'locator.click', label: 'Accept' }, 'ava'); + expect(shown().slice(-2)).toEqual(['↳ locator.click "Send invite"', '↳ ava · locator.click "Accept"']); + step({ phase: 'end', kind: 'locator', api: 'locator.click', label: 'Accept', status: 'passed', durationMs: 85, modelCalls: 0 }, 'ava'); + expect(shown().slice(-2)).toEqual(['✓ ava · locator.click "Accept" 85ms', '↳ locator.click "Send invite"']); + step({ phase: 'end', kind: 'locator', api: 'locator.click', label: 'Send invite', status: 'passed', durationMs: 90, modelCalls: 0 }); + const held = { target: 'chromium', testId: 't1', agent: 'default', repeat: 0, title: 'invites a friend', api: 'locator.click', label: 'Join', user: 'ava' }; + reporter.showStepPrompt({ steps: [{ step: held, number: 3 }], help: false }); + expect(shown()).toEqual([ + '✓ agent.act "pay" 40ms', + '✓ ava · agent.act "accept" 50ms', + '✓ ava · locator.click "Accept" 85ms', + '✓ locator.click "Send invite" 90ms', + '▶ step 3 ava · locator.click "Join"', + 'press enter to run this step, press h to show help, press q to quit', + ]); + expect(stepPromptLine({ steps: [{ step: held, number: 3 }], help: false })).toContain(': ava · locator.click "Join" · press enter'); + } finally { + restore(); + } + }); + it('shows the --step prompt under its paused test, after every step that ran, and takes it down', () => { const restore = withTerminalSize({ columns: 120, rows: 40 }); try { @@ -2280,3 +2375,18 @@ describe('screenshots row', () => { ]); }); }); + +describe('step lines in color', () => { + it("color a peer's name, and add no empty color codes for the test's own user", () => { + const pc = picocolors.createColors(true); + const step = { status: 'passed', api: 'locator.tap', label: 'Pay', durationMs: 5, modelCalls: 0 } as Parameters[1]; + const emptyCyan = '\u001b[36m\u001b[39m'; + expect(stepLine(pc, step)).not.toContain(emptyCyan); + expect(stepLine(pc, { ...step, user: 'ava' })).toContain(pc.cyan('ava · ')); + const held = { target: 'web', testId: 't1', agent: 'default', repeat: 0, title: 'pays', api: 'locator.tap', label: 'Pay' }; + const [own] = stepPromptRows(pc, { steps: [{ step: held, number: 1 }], help: false }, { maxWidth: 120 }); + expect(own).not.toContain(emptyCyan); + const [peer] = stepPromptRows(pc, { steps: [{ step: { ...held, user: 'ava' }, number: 1 }], help: false }, { maxWidth: 120 }); + expect(peer).toContain(pc.cyan('ava · ')); + }); +}); diff --git a/packages/e2e/tests/unit/report-markdown.test.ts b/packages/e2e/tests/unit/report-markdown.test.ts index 604054d7f3..96d370379a 100644 --- a/packages/e2e/tests/unit/report-markdown.test.ts +++ b/packages/e2e/tests/unit/report-markdown.test.ts @@ -331,6 +331,30 @@ describe('renderMarkdownReport', () => { expect(worded).toContain(', after 15.1s\n\n> the Save button stayed\n\n- Expected:'); }); + it("names the peer whose step failed, tells the failure on that peer's screen, and names each user's evidence", () => { + const error = { code: 'ASSERTION_FAILED', message: 'heading "Welcome" never showed' }; + const failedAttempt = attempt({ + status: 'failed', + error, + artifacts: ['video', 'video'], + steps: [ + step({ index: 0, kind: 'app', api: 'app.open', label: '/' }), + step({ index: 1, kind: 'agent', api: 'agent.act', label: 'Accept the invite', user: 'ava', status: 'failed', durationMs: 2_000, error: reportError({ message: error.message }) }), + ], + }); + failedAttempt.artifacts = failedAttempt.artifacts.map((artifact, index) => (index === 1 ? { ...artifact, user: 'ava', path: 't/attempt-0/peers/ava/video-1.bin' } : artifact)); + failedAttempt.failure = { url: '/cart', candidates: ['#n2 button "Pay"'] }; + failedAttempt.peers = { ava: { target: 'web', failure: { url: '/invites', candidates: ['#n7 button "Accept"'] } } }; + const body = renderMarkdownReport(page({ status: 'failed', results: [named({ title: 'invites', status: 'failed', attempts: [failedAttempt] })] }), { artifactsDir: '.e2e/artifacts' }); + expect(body).toContain('**ASSERTION_FAILED** at step 2 of 2: ava · `agent.act` "Accept the invite", after 2.0s'); + expect(body).toContain('- Screen: `/invites`\n- Closest to the locator: `#n7 button "Accept"`'); + expect(body).not.toContain('`/cart`'); + expect(body).toContain('Evidence: video `.e2e/artifacts/t/attempt-0/video-0.bin`, ava · video `.e2e/artifacts/t/attempt-0/peers/ava/video-1.bin`'); + // With a link to the run's files, each user's video is its own link. + const linked = renderMarkdownReport(page({ status: 'failed', results: [named({ title: 'invites', status: 'failed', attempts: [failedAttempt] })] }), { artifactsUrl: 'https://ci.example/run/1#artifacts' }); + expect(linked).toContain('Evidence: [video](https://ci.example/run/1#artifacts), [ava · video](https://ci.example/run/1#artifacts)'); + }); + it('puts run-level errors before the failures and says no tests ran', () => { const body = renderMarkdownReport( page({ diff --git a/packages/e2e/tests/unit/scheduler.test.ts b/packages/e2e/tests/unit/scheduler.test.ts index 21e46426f4..2d54e3cc5d 100644 --- a/packages/e2e/tests/unit/scheduler.test.ts +++ b/packages/e2e/tests/unit/scheduler.test.ts @@ -29,6 +29,7 @@ const defaultOptions: ResolvedTestOptions = { platforms: undefined, requires: [], session: undefined, + peers: [], agents: ['default'], agentContext: undefined, skipReason: undefined, @@ -483,6 +484,90 @@ async function run( return collected; } +describe('an app exit on a target that only hosts peers', () => { + afterEach(() => vi.useRealTimers()); + + const failure: TargetFailure = { + targetNames: ['host'], + error: { category: 'infrastructure', code: 'APP_UNREACHABLE', message: 'target "host" command exited with code 1 after becoming ready', retryable: false }, + }; + const web = makeTarget('web', 0); + const host = makeTarget('host', 1); + const withPeer = (title: string) => + makePair(makeTest(`tests/${title}.e2e.ts`, title), web, { options: { ...defaultOptions, peers: [{ name: 'ava', target: 'host', session: undefined, agent: undefined, agentContext: undefined }] } }); + // The host runs no test of its own: a skipped pair gives it a plan, as a selected target has. + const hostSkipped = makePair(makeTest('tests/host.e2e.ts', 'host'), host, { disposition: 'skip', skip: { cause: 'platform-unavailable', reason: 'test declares platforms [web]' } }); + + it('reports the exit and skips a queued test that puts a peer there', async () => { + const pays = withPeer('pays'); + const fleet = new FakeFleet(); + const collected = await run(makeSelection([{ target: web, pairs: [pays] }, { target: host, pairs: [hostSkipped] }]), makeCollection([pays.test.file, hostSkipped.test.file], [pays, hostSkipped]), fleet, { + subscribeTargetFailures(receive) { + receive(failure); + return () => undefined; + }, + }); + expect(collected.runErrors).toEqual([{ error: failure.error }]); + expect(collected.results.find((result) => result.test.id === pays.test.id)).toMatchObject({ status: 'skipped', skip: { cause: 'infrastructure-unavailable', reason: failure.error.message } }); + expect(fleet.unitsByWorker.flat()).toEqual([]); + }); + + it('reports the exit while a test that puts a peer there is running', async () => { + const pays = withPeer('pays'); + const fleet = new FakeFleet({ overrun: { [pays.test.id]: 'slow-teardown' } }); + vi.useFakeTimers(); + const running = run(makeSelection([{ target: web, pairs: [pays] }, { target: host, pairs: [hostSkipped] }]), makeCollection([pays.test.file, hostSkipped.test.file], [pays, hostSkipped]), fleet, { + workers: 1, + subscribeTargetFailures(receive) { + setTimeout(() => receive(failure), 10); + return () => undefined; + }, + }); + await vi.runAllTimersAsync(); + const collected = await running; + expect(collected.runErrors).toEqual([{ error: failure.error }]); + expect(fleet.unitsByWorker.flat().map((unit) => unit.unitId)).toEqual(['file::web::tests/pays.e2e.ts']); + }); + + it('ignores the exit once every test that put a peer there has reported', async () => { + const pays = withPeer('pays'); + const after = makePair(makeTest('tests/pays.e2e.ts', 'after', { declarationIndex: 1 }), web); + const fleet = new FakeFleet({ overrun: { [after.test.id]: 'slow-teardown' } }); + vi.useFakeTimers(); + const running = run(makeSelection([{ target: web, pairs: [pays, after] }, { target: host, pairs: [hostSkipped] }]), makeCollection([pays.test.file, hostSkipped.test.file], [pays, after, hostSkipped]), fleet, { + workers: 1, + subscribeTargetFailures(receive) { + setTimeout(() => receive(failure), 10); + return () => undefined; + }, + }); + await vi.runAllTimersAsync(); + const collected = await running; + expect(collected.results.find((result) => result.test.id === pays.test.id)?.status).toBe('passed'); + expect(collected.runErrors).toEqual([]); + }); + + it('reports the exit while a starting worker holds a test that puts a peer there', async () => { + const pays = withPeer('pays'); + const fleet = new FakeFleet({ neverReady: ['web'] }); + const interrupt = new AbortController(); + // The worker never becomes ready, so the run ends only when it is interrupted, after the exit. + const timer = setTimeout(() => interrupt.abort(), 40); + const collected = await run(makeSelection([{ target: web, pairs: [pays] }, { target: host, pairs: [hostSkipped] }]), makeCollection([pays.test.file, hostSkipped.test.file], [pays, hostSkipped]), fleet, { + workers: 1, + interruptSignal: interrupt.signal, + subscribeTargetFailures(receive) { + setTimeout(() => receive(failure), 10); + return () => undefined; + }, + }); + clearTimeout(timer); + expect(fleet.spawned.map((worker) => worker.targetName)).toEqual(['web']); + expect(fleet.unitsByWorker.flat()).toEqual([]); + expect(collected.runErrors).toEqual([{ error: failure.error }]); + }); +}); + describe('app command failures', () => { afterEach(() => vi.useRealTimers()); @@ -1808,3 +1893,96 @@ describe('scheduler fault handling', () => { expect(collected.results.find((result) => result.test.id === 'filter-me')!.selected).toBe(false); }); }); + +describe('peers and setup gating', () => { + const peerOf = (session: string, target: string | undefined) => ({ name: 'ava', target, session, agent: undefined, agentContext: undefined }); + const setupFor = (target: ResolvedTarget, session: string) => + makePair(makeTest(`tests/${session}.setup.e2e.ts`, `save ${session}`, { kind: 'setup', sessions: [session], id: `setup::${session}` }), target); + + it('starts a test only after the setup that saves its peer session on the peer target has finished, and no other', async () => { + const web = makeTarget('web', 0); + const admin = makeTarget('admin', 1); + const pays = makePair(makeTest('tests/pays.e2e.ts', 'pays'), web, { options: { ...defaultOptions, peers: [peerOf('ava', 'admin')] } }); + const setup = setupFor(admin, 'ava'); + const fleet = new FakeFleet(); + const collected = await run( + makeSelection([{ target: web, pairs: [pays] }, { target: admin, pairs: [setup] }]), + makeCollection([pays.test.file, setup.test.file], [pays, setup]), + fleet, + { workers: 2 }, + ); + // The web worker is ready first and its own target has no setup, yet it waits for the admin one. + expect(collected.results.map((result) => result.test.id)).toEqual(['setup::ava', pays.test.id]); + expect(collected.results[1]!.status).toBe('passed'); + + // A peer that restores no session holds nothing back. + const chats = makePair(makeTest('tests/chats.e2e.ts', 'chats'), web, { + options: { ...defaultOptions, peers: [{ name: 'ava', target: 'admin', session: undefined, agent: undefined, agentContext: undefined }] }, + }); + const other = setupFor(admin, 'other'); + const unheld = await run( + makeSelection([{ target: web, pairs: [chats] }, { target: admin, pairs: [other] }]), + makeCollection([chats.test.file, other.test.file], [chats, other]), + new FakeFleet(), + { workers: 2 }, + ); + expect(unheld.results.map((result) => result.test.id)).toEqual([chats.test.id, 'setup::other']); + }); + + it('skips a test whose peer session setup failed, on the peer target or its own', async () => { + const web = makeTarget('web', 0); + const admin = makeTarget('admin', 1); + const across = makePair(makeTest('tests/across.e2e.ts', 'across'), web, { options: { ...defaultOptions, peers: [peerOf('ava', 'admin')] } }); + const local = makePair(makeTest('tests/local.e2e.ts', 'local'), web, { options: { ...defaultOptions, peers: [peerOf('bob', undefined)] } }); + const avaSetup = setupFor(admin, 'ava'); + const bobSetup = setupFor(web, 'bob'); + const fleet = new FakeFleet({ status: { 'setup::ava': 'failed', 'setup::bob': 'failed' } }); + const collected = await run( + makeSelection([{ target: web, pairs: [bobSetup, across, local] }, { target: admin, pairs: [avaSetup] }]), + makeCollection([across.test.file, local.test.file, avaSetup.test.file, bobSetup.test.file], [bobSetup, across, local, avaSetup]), + fleet, + { workers: 2 }, + ); + const byId = new Map(collected.results.map((result) => [result.test.id, result])); + expect(byId.get(across.test.id)).toMatchObject({ status: 'skipped', skip: { cause: 'setup-failed', relatedId: 'setup::ava' } }); + expect(byId.get(local.test.id)).toMatchObject({ status: 'skipped', skip: { cause: 'setup-failed', relatedId: 'setup::bob' } }); + }); + + it('skips a test whose peer target could not start a worker, instead of running it without the session', async () => { + const web = makeTarget('web', 0); + const admin = makeTarget('admin', 1); + const pays = makePair(makeTest('tests/pays.e2e.ts', 'pays'), web, { options: { ...defaultOptions, peers: [peerOf('ava', 'admin')] } }); + const setup = setupFor(admin, 'ava'); + const fleet = new FakeFleet({ failInit: ['admin'] }); + const collected = await run( + makeSelection([{ target: web, pairs: [pays] }, { target: admin, pairs: [setup] }]), + makeCollection([pays.test.file, setup.test.file], [pays, setup]), + fleet, + { workers: 2 }, + ); + // The setup never ran: the target's own reason says why, not a setup failure. + expect(collected.results.find((result) => result.test.id === pays.test.id)).toMatchObject({ + status: 'skipped', + skip: { cause: 'infrastructure-unavailable', reason: 'worker process failed to start' }, + }); + }); + + it('skips a test whose peer restores no session, when the peer target could not start a worker', async () => { + const web = makeTarget('web', 0); + const admin = makeTarget('admin', 1); + const pays = makePair(makeTest('tests/pays.e2e.ts', 'pays'), web, { options: { ...defaultOptions, peers: [{ name: 'ava', target: 'admin', session: undefined, agent: undefined, agentContext: undefined }] } }); + const own = makePair(makeTest('tests/admin.e2e.ts', 'admin'), admin); + const fleet = new FakeFleet({ failInit: ['admin'] }); + const collected = await run( + // The admin target comes first, so its workers fail before the web test is taken. + makeSelection([{ target: admin, pairs: [own] }, { target: web, pairs: [pays] }]), + makeCollection([own.test.file, pays.test.file], [own, pays]), + fleet, + { workers: 1 }, + ); + expect(collected.results.find((result) => result.test.id === pays.test.id)).toMatchObject({ + status: 'skipped', + skip: { cause: 'infrastructure-unavailable', reason: 'worker process failed to start' }, + }); + }); +}); diff --git a/packages/e2e/tests/unit/schema-fixtures.test.ts b/packages/e2e/tests/unit/schema-fixtures.test.ts index 07b0df8199..12f167c98c 100644 --- a/packages/e2e/tests/unit/schema-fixtures.test.ts +++ b/packages/e2e/tests/unit/schema-fixtures.test.ts @@ -109,6 +109,37 @@ describe.each(schemas)('%s schema', (name) => { } }); + it("names the peer a step, a file, and a log line came from, and keeps each peer's facts apart", () => { + const report = readJson('fixtures', 'report-v1.valid.json') as { + run: { results: { attempts: (Record & { steps: Record[]; artifacts: Record[] })[] }[] }; + }; + const attempt = report.run.results[0]!.attempts[0]!; + const step = attempt.steps.find((candidate) => candidate['user'] !== undefined)!; + const video = attempt.artifacts.find((artifact) => artifact['user'] !== undefined)!; + const line = (attempt['appLog'] as Record[]).find((entry) => entry['user'] !== undefined)!; + const peers = attempt['peers'] as Record>; + expect(validate(report)).toBe(true); + const cases: [() => void, () => void][] = [ + [() => (step['user'] = '..'), () => (step['user'] = 'guest')], + [() => (step['user'] = '.'), () => (step['user'] = 'guest.2')], + [() => (step['user'] = 'a guest'), () => (step['user'] = 'guest')], + [() => (video['user'] = ''), () => (video['user'] = 'guest')], + [() => (line['user'] = 'x'.repeat(129)), () => (line['user'] = 'x'.repeat(128))], + [() => (peers['..'] = {}), () => delete peers['..']], + [() => (peers['guest']!['region'] = 'eu'), () => delete peers['guest']!['region']], + [() => delete peers['guest']!['target'], () => (peers['guest']!['target'] = 'web')], + [() => (peers['guest']!['target'] = ''), () => (peers['guest']!['target'] = 'web')], + [() => (peers['guest']!['environment'] = { cores: 8 }), () => (peers['guest']!['environment'] = { cores: '8' })], + [() => (peers['guest']!['failure'] = { screen: 1 }), () => (peers['guest']!['failure'] = {})], + ]; + for (const [breakIt, fixIt] of cases) { + breakIt(); + expect(validate(report)).toBe(false); + fixIt(); + expect(validate(report)).toBe(true); + } + }); + it('constrains result tags to distinct names --tag can spell back', () => { const report = readJson('fixtures', 'report-v1.valid.json') as { run: { results: { tags?: string[] }[] } }; const result = report.run.results[0]!; diff --git a/packages/e2e/tests/unit/select.test.ts b/packages/e2e/tests/unit/select.test.ts index b592e20d1d..2d6bb1e1a7 100644 --- a/packages/e2e/tests/unit/select.test.ts +++ b/packages/e2e/tests/unit/select.test.ts @@ -6,7 +6,7 @@ import { collectFromRegistration, type Collection } from '../../src/collect/coll import { collectModule, test } from '../../src/collect/registry.ts'; import { pairRecording, pairRecordings, repeatEach, resolveOptions, select, type SelectionFilters } from '../../src/collect/select.ts'; import { resolveConfig } from '../../src/config/resolve.ts'; -import { defineEngine } from '../../src/engine/index.ts'; +import { connectEngine, defineEngine, describeEngine, loopbackTransport } from '../../src/engine/index.ts'; import { resultId } from '../../src/internal/ids.ts'; import type { E2EConfig } from '../../src/types.ts'; @@ -967,3 +967,161 @@ describe('positional file selection', () => { expect(() => select(col, config())).toThrow(/none is runnable: 1 file not selected by a positional argument, 1 skipped with test.skip/); }); }); + +describe('peers', () => { + /** A web target and an admin console, each on its own platform, so `platforms` can pin a test's own side. */ + const twoTargets = (raw: Partial = {}) => + config({ targets: [{ name: 'web', platform: 'web' }, { name: 'admin', platform: 'admin' }], ...raw }); + const setupOn = (selection: ReturnType, target: string) => + selection.pairs.find((pair) => pair.test.kind === 'setup' && pair.target.name === target)!; + + it('resolves peers innermost-first as a whole, leaving each one target and agent to the pair', async () => { + const col = await collection(() => { + test.describe('outer', { peers: { ava: { session: 'ava' }, bob: {} } }, () => { + test('inherits', noop); + test('replaces', { peers: { cat: { target: 'admin', agent: 'buyer', agentContext: 'You are Cat.' } } }, noop); + test('clears', { peers: {} }, noop); + }); + test('none', noop); + }); + const cfg = twoTargets({ agents: { default: {}, buyer: {} } }); + expect(col.tests.map((entry) => resolveOptions(entry, cfg).peers)).toEqual([ + [ + { name: 'ava', target: undefined, session: 'ava', agent: undefined, agentContext: undefined }, + { name: 'bob', target: undefined, session: undefined, agent: undefined, agentContext: undefined }, + ], + [{ name: 'cat', target: 'admin', session: undefined, agent: 'buyer', agentContext: 'You are Cat.' }], + [], + [], + ]); + }); + + it('rejects a peer target or agent the config does not declare, naming the nearest', async () => { + const col = await collection(() => { + test('pays', { peers: { ava: { target: 'admn' } } }, noop); + test('asks', { peers: { ava: { agent: 'buyr' } } }, noop); + }); + const cfg = twoTargets({ agents: { default: {}, buyer: {} } }); + expect(() => resolveOptions(col.tests[0]!, cfg)).toThrow( + 'test "pays" in tests/a.e2e.ts runs peer "ava" on target "admn", which the config does not declare; targets: "web", "admin"; did you mean "admin"?', + ); + expect(() => resolveOptions(col.tests[1]!, cfg)).toThrow( + 'test "asks" in tests/a.e2e.ts runs peer "ava" as agent "buyr", which agents does not define; configured: default, buyer; did you mean "buyer"?', + ); + }); + + it('runs a test with a peer once per selected target, and platforms pins the test own side', async () => { + const col = await collection(() => { + test('everywhere', { peers: { ava: { target: 'admin' } } }, noop); + test('from the web', { platforms: ['web'], peers: { ava: { target: 'admin' } } }, noop); + }); + const runs = select(col, twoTargets()).pairs.filter((pair) => pair.disposition === 'run'); + expect(runs.map((pair) => [pair.test.title, pair.target.name])).toEqual([ + ['everywhere', 'web'], + ['from the web', 'web'], + ['everywhere', 'admin'], + ]); + }); + + it('refuses a run whose --target leaves out the target a selected peer runs on', async () => { + const col = await collection(() => { + test('from the web', { platforms: ['web'], peers: { ava: { target: 'admin' } } }, noop); + }); + expect(() => select(col, twoTargets(), { targetIds: ['web'] })).toThrow( + 'test "from the web" in tests/a.e2e.ts runs peer "ava" on target "admin", which this run does not select; add --target admin', + ); + expect(running(select(col, twoTargets(), { targetIds: ['web', 'admin'] }))).toEqual(['from the web']); + }); + + it('refuses a peer on a target whose engine runs in an engine server, and takes one on an engine the config creates', async () => { + const local = defineEngine({ name: 'local', version: '1.0.0', spiVersion: 1, platform: 'admin' }); + const served = connectEngine({ manifest: describeEngine(local), transport: loopbackTransport(local) }); + const col = await collection(() => { + test('from the web', { platforms: ['web'], peers: { ava: { target: 'admin' } } }, noop); + }); + const withEngine = (engine: typeof local) => config({ targets: [{ name: 'web', platform: 'web' }, { name: 'admin', engine, app: { url: 'http://localhost:3001' } }] }); + expect(() => select(col, withEngine(served))).toThrow( + 'test "from the web" in tests/a.e2e.ts runs peer "ava" on target "admin", whose engine runs in an engine server (connectEngine); a peer runs on an engine in the worker\'s own process only, so give the peer a target whose engine the config creates', + ); + expect(running(select(col, withEngine(local)))).toEqual(['from the web']); + }); + + it('fails when no setup test produces a peer session, naming the peer', async () => { + const col = await collection(() => { + test('pays', { peers: { ava: { session: 'ava' } } }, noop); + }); + expect(() => select(col, config())).toThrow( + /^test "pays" in tests\/a\.e2e\.ts consumes session "ava" for peer "ava" but no setup test produces it; no collected setup test declares a session$/, + ); + }); + + it('runs the setup test that saves a peer session on the peer target, and only there', async () => { + const col = await collection(() => { + test.setup('sign in', { sessions: ['ava'] }, noop); + test('pays', { platforms: ['web'], peers: { ava: { target: 'admin', session: 'ava' } } }, noop); + }); + const selection = select(col, twoTargets()); + expect(setupOn(selection, 'admin').disposition).toBe('run'); + expect(setupOn(selection, 'web').disposition).not.toBe('run'); + + // The same peer on the test own target needs the setup there instead. + const sameTarget = await collection(() => { + test.setup('sign in', { sessions: ['ava'] }, noop); + test('pays', { platforms: ['web'], peers: { ava: { session: 'ava' } } }, noop); + }); + const local = select(sameTarget, twoTargets()); + expect(setupOn(local, 'web').disposition).toBe('run'); + expect(setupOn(local, 'admin').disposition).not.toBe('run'); + }); + + it("keeps an engine's own fixture named peers for tests without peers, and refuses a test with peers on its target", async () => { + const own = defineEngine({ name: 'toy', version: '1.0.0', spiVersion: 1, fixtures: { peers: () => ({ mine: true }) } }); + const cfg = config({ targets: [{ name: 'web', platform: 'web', engine: own }] }); + const alone = await collection(() => test('alone', noop)); + expect(select(alone, cfg).pairs.map((pair) => pair.disposition)).toEqual(['run']); + const pair = await collection(() => test('pays', { peers: { ava: {} } }, noop)); + expect(() => select(pair, cfg)).toThrow( + 'test "pays" in tests/a.e2e.ts declares peers, but target "web" runs on engine toy, which contributes a fixture named "peers"; the peers option needs that name', + ); + }); + + it('refuses a peer session on a target whose engine cannot restore one, before any test runs', async () => { + const col = await collection(() => { + test.setup('sign in', { sessions: ['ava'] }, noop); + test('pays', { platforms: ['web'], peers: { ava: { target: 'admin', session: 'ava' } } }, noop); + }); + const stateless = defineEngine({ name: 'toy', version: '1.0.0', spiVersion: 1 }); + const cfg = config({ targets: [{ name: 'web', platform: 'web' }, { name: 'admin', platform: 'admin', engine: stateless }] }); + expect(() => select(col, cfg)).toThrow( + 'test "pays" in tests/a.e2e.ts restores session "ava" into peer "ava", but target "admin" cannot save or restore a session: engine toy, as configured, has no state capability; sign the peer in during the test instead', + ); + }); + + it('brings a peer setup test into the shard that runs the test, and not into the others', async () => { + const col = await collection(() => { + test.setup('sign in', { sessions: ['ava'] }, noop); + test('a', { platforms: ['web'] }, noop); + test('b', { platforms: ['web'], peers: { ava: { target: 'admin', session: 'ava' } } }, noop); + }); + const second = select(col, twoTargets(), { shard: { index: 2, total: 2 } }); + expect(running(second)).toContain('b'); + expect(setupOn(second, 'admin').disposition).toBe('run'); + const first = select(col, twoTargets(), { shard: { index: 1, total: 2 } }); + expect(running(first)).not.toContain('b'); + expect(setupOn(first, 'admin').disposition).not.toBe('run'); + }); + + it('reruns, under --last-failed, a test whose peer setup failed on the peer target last time', async () => { + const col = await collection(() => { + test.setup('sign in', { sessions: ['ava'] }, noop); + test('pays', { platforms: ['web'], peers: { ava: { target: 'admin', session: 'ava' } } }, noop); + test('other', { platforms: ['web'] }, noop); + }); + const setup = col.tests.find((entry) => entry.kind === 'setup')!; + const onPeerTarget = select(col, twoTargets(), { lastFailed: new Set([resultId(setup.id, 'admin', 'default')]) }); + expect(running(onPeerTarget)).toContain('pays'); + expect(running(onPeerTarget)).not.toContain('other'); + // A failure of the same setup on the test own target is not the peer one. + expect(() => select(col, twoTargets(), { lastFailed: new Set([resultId(setup.id, 'web', 'default')]) })).toThrow(/NO_TESTS|none is runnable|no test/i); + }); +}); diff --git a/packages/e2e/tests/unit/serial-record.test.ts b/packages/e2e/tests/unit/serial-record.test.ts index c24b4df1c0..98baad6b37 100644 --- a/packages/e2e/tests/unit/serial-record.test.ts +++ b/packages/e2e/tests/unit/serial-record.test.ts @@ -24,6 +24,7 @@ const OPTIONS: ResolvedTestOptions = { platforms: undefined, requires: [], session: undefined, + peers: [], agents: ['default'], agentContext: undefined, skipReason: undefined, diff --git a/packages/e2e/tests/unit/step-cache.test.ts b/packages/e2e/tests/unit/step-cache.test.ts index d440e8b23d..2d01994fab 100644 --- a/packages/e2e/tests/unit/step-cache.test.ts +++ b/packages/e2e/tests/unit/step-cache.test.ts @@ -1394,6 +1394,32 @@ describe('cache.strict and a step whose key changed under its recording', () => } }); + it("runs live a peer's step when the only recording is another user's of the same step", async () => { + const peerStep = { ...exampleStep, user: 'ava' }; + const peerClaim = (context: AgentCacheContext): AgentCacheContext => ({ ...context, claimKey: () => ({ keyHash: OWN_KEY, context: exampleContext, step: peerStep }) }); + // The test's own user's recording never stands in for Ava's step, nor Bob's for hers. + for (const recordedFor of [exampleStep, { ...exampleStep, user: 'bob' }]) { + const session = makeSession(peerClaim(await rekeyedContext(recordedPayload(recordedFor))), makeHost(['/'])); + await expect(session.begin(), JSON.stringify(recordedFor)).resolves.toBeUndefined(); + } + // Nor hers for the test's own step. + await expect(makeSession(await rekeyedContext(recordedPayload(peerStep)), makeHost(['/'])).begin()).resolves.toBeUndefined(); + // Her own recording under another key is stale, as the test's own is. + const session = makeSession(peerClaim(await rekeyedContext(recordedPayload(peerStep))), makeHost(['/'])); + await expect(session.begin()).rejects.toMatchObject({ code: 'REPLAY_STALE' }); + }); + + it("runs live a peer's step when the only recording is the same peer's in another pair of the test, on another target or as another agent", async () => { + const peerStep = { ...exampleStep, user: 'ava', ownerTargetId: 'web', ownerAgent: 'admin' }; + const peerClaim = (context: AgentCacheContext): AgentCacheContext => ({ ...context, claimKey: () => ({ keyHash: OWN_KEY, context: exampleContext, step: peerStep }) }); + for (const recordedFor of [{ ...peerStep, ownerTargetId: 'ios' }, { ...peerStep, ownerAgent: 'member' }]) { + const session = makeSession(peerClaim(await rekeyedContext(recordedPayload(recordedFor))), makeHost(['/'])); + await expect(session.begin(), JSON.stringify(recordedFor)).resolves.toBeUndefined(); + } + // Her recording in this pair, under another key, is stale. + await expect(makeSession(peerClaim(await rekeyedContext(recordedPayload(peerStep))), makeHost(['/'])).begin()).rejects.toMatchObject({ code: 'REPLAY_STALE' }); + }); + it('runs live when the only recording is truncated or records no step', async () => { const tapUpgrade = { name: 'tap', summary: 'tap button "Upgrade"', target: { role: 'button', name: 'Upgrade' } } as const; const truncated = recordedPayload(exampleStep, { actions: Array.from({ length: 50 }, () => tapUpgrade), truncated: true }); diff --git a/packages/e2e/tests/unit/step-users.test.ts b/packages/e2e/tests/unit/step-users.test.ts new file mode 100644 index 0000000000..96767000bb --- /dev/null +++ b/packages/e2e/tests/unit/step-users.test.ts @@ -0,0 +1,174 @@ +/** + * Steps of more than one user in one attempt: `StepRecorder.forUser` is a + * peer's view of the attempt's one recorder. Every step it opens is the + * peer's, and what the peer's app reports, the screens it shows, and the + * checks that pass on it stay with that peer's steps. + */ + +import { describe, expect, it } from 'vitest'; +import type { AppEvent } from '../../src/engine/surface.ts'; +import { APP_LOG_LIMITS } from '../../src/engine/session.ts'; +import { StepRecorder, type StepHoldRequest, type StepProgress } from '../../src/run/steps.ts'; + +/** The agent and target peer ava's steps are attributed to. */ +const AVA = { agent: 'default', target: 'web' }; + +const pass = async (): Promise => undefined; +const log = (text: string): AppEvent => ({ kind: 'log', entry: { source: 'console', level: 'warning', text } }); +/** A screen of one line, as `recordScreen` reads it. */ +const screen = (text: string) => () => ({ location: 'http://app.test/', lines: [{ id: 'root', text }] }); + +describe('StepRecorder.forUser', () => { + it("marks each step a peer opens, and the steps inside it, as the peer's, and the test's own as no one's", async () => { + const heard: StepProgress[] = []; + const steps = new StepRecorder('attempt', { onProgress: (progress) => heard.push(progress) }); + const ava = steps.forUser('ava', AVA); + await steps.run('app', 'app.open', '/', pass); + await ava.run('agent', 'agent.act', 'accept the invite', async () => { + await ava.run('locator', 'locator.tap', 'button "Accept"', async () => { + steps.activity('action'); + steps.recordEvent({ kind: 'engine', startedAt: '2026-01-01T00:00:00.000Z', durationMs: 1, status: 'passed', detail: 'tapped' }); + }); + }); + expect(steps.all().map((step) => [step.api, step.user])).toEqual([ + ['app.open', undefined], + ['agent.act', 'ava'], + ['locator.tap', 'ava'], + ]); + expect(Object.hasOwn(steps.all()[0]!, 'user')).toBe(false); + // Every phase a reporter hears names the peer whose step it is. + expect(heard.map((progress) => [progress.phase, progress.identity?.user])).toEqual([ + ['start', undefined], + ['end', undefined], + ['start', 'ava'], + ['start', 'ava'], + ['activity', 'ava'], + ['event', 'ava'], + ['end', 'ava'], + ['end', 'ava'], + ]); + expect(Object.hasOwn(heard[0]!.identity!, 'user')).toBe(false); + }); + + it("lists only the peer's own finished steps", async () => { + const steps = new StepRecorder('attempt'); + const ava = steps.forUser('ava', AVA); + await steps.run('app', 'app.open', '/', pass); + await ava.run('app', 'app.open', '/invites', pass); + expect(ava.completed().map((step) => step.label)).toEqual(['/invites']); + expect(steps.completed()).toHaveLength(2); + }); + + it("records the test's own step inside a peer's step as the test's own: every step of a peer names it", async () => { + const steps = new StepRecorder('attempt'); + const ava = steps.forUser('ava', AVA); + // The test's own check in an `onAction` hook of Ava's agent step, beside one of Ava's own. + await ava.run('agent', 'agent.act', 'accept the invite', async () => { + await steps.run('assertion', 'expect.toBeVisible', 'getByText("Cart")', pass); + await ava.run('locator', 'locator.tap', 'button "Accept"', pass); + }); + expect(steps.all().map((step) => [step.api, step.user])).toEqual([ + ['agent.act', 'ava'], + ['expect.toBeVisible', undefined], + ['locator.tap', 'ava'], + ]); + expect(ava.completed().map((step) => step.api)).toEqual(['agent.act', 'locator.tap']); + }); + + it("files what a peer's app reports between steps with that peer's last step, and its first navigation with its first step", async () => { + const steps = new StepRecorder('attempt'); + const ava = steps.forUser('ava', AVA); + steps.recordAppEvent({ kind: 'navigation', line: 'ava went to /invites' }, '2026-01-01T00:00:00.000Z', 'ava'); + await ava.run('app', 'app.open', '/invites', pass); + await steps.run('app', 'app.open', '/', pass); + // Both arrive after the test's own step, the newest; each lands with its own user's last step. + steps.recordAppEvent(log('invite link expires soon'), '2026-01-01T00:00:01.000Z', 'ava'); + steps.recordAppEvent(log('cart is empty'), '2026-01-01T00:00:02.000Z'); + expect(steps.all()[0]!.events.map((event) => event.detail)).toEqual(['ava went to /invites']); + expect(steps.all()[1]!.events).toEqual([]); + expect(steps.appLog().map((line) => [line.text, line.step, line.user])).toEqual([ + ['invite link expires soon', 0, 'ava'], + ['cart is empty', 1, undefined], + ]); + expect(Object.hasOwn(steps.appLog()[1]!, 'user')).toBe(false); + }); + + it("keeps each user's app log within its own limit, so a noisy peer leaves the test's own errors in", async () => { + const steps = new StepRecorder('attempt'); + const ava = steps.forUser('ava', AVA); + await ava.run('app', 'app.open', '/invites', pass); + await steps.run('app', 'app.open', '/', pass); + for (let index = 0; index <= APP_LOG_LIMITS.errorsAndWarnings; index += 1) steps.recordAppEvent(log(`ava noise ${index}`), '2026-01-01T00:00:01.000Z', 'ava'); + steps.recordAppEvent(log('checkout failed'), '2026-01-01T00:00:02.000Z'); + const lines = steps.appLog(); + expect(lines.filter((line) => line.user === 'ava')).toHaveLength(APP_LOG_LIMITS.errorsAndWarnings); + expect(lines.filter((line) => line.user === undefined).map((line) => line.text)).toEqual(['checkout failed']); + }); + + it("files what a peer's app reports while the test's own step runs with the peer's last step, not the running one", async () => { + const steps = new StepRecorder('attempt'); + await steps.forUser('ava', AVA).run('app', 'app.open', '/invites', pass); + await steps.run('app', 'app.open', '/', async () => { + steps.recordAppEvent(log('invite link expires soon'), '2026-01-01T00:00:01.000Z', 'ava'); + steps.recordAppEvent({ kind: 'navigation', line: 'ava went to /invites/1' }, '2026-01-01T00:00:01.000Z', 'ava'); + steps.recordAppEvent(log('cart is empty'), '2026-01-01T00:00:02.000Z'); + }); + expect(steps.appLog().map((line) => [line.text, line.step])).toEqual([ + ['invite link expires soon', 0], + ['cart is empty', 1], + ]); + expect(steps.all().map((step) => step.events.map((event) => event.detail))).toEqual([['ava went to /invites/1'], []]); + }); + + it("compares each step's screen with the last one its own user saw", async () => { + const steps = new StepRecorder('attempt'); + const ava = steps.forUser('ava', AVA); + await steps.run('app', 'app.open', '/', async () => steps.recordScreen(screen('document "Cart"'))); + await ava.run('app', 'app.open', '/invites', async () => steps.recordScreen(screen('document "Invites"'))); + await steps.run('app', 'app.reload', '/', async () => steps.recordScreen(screen('document "Cart"'))); + await ava.run('app', 'app.reload', '/invites', async () => steps.recordScreen(screen('document "Invites"'))); + expect(steps.all().map((step) => [step.screen?.since, step.screen?.changes])).toEqual([ + [undefined, []], + [undefined, []], + [0, []], + [1, []], + ]); + }); + + it("confirms by a passed check only that check's own user's steps", async () => { + const steps = new StepRecorder('attempt'); + const ava = steps.forUser('ava', AVA); + await ava.run('agent', 'agent.act', 'accept the invite', pass); + await steps.run('agent', 'agent.act', 'send the invite', pass); + await steps.run('assertion', 'expect.toBeVisible', 'sent', pass, { verifies: true }); + expect(steps.lastVerifiedStepIndex).toBe(2); + expect(steps.lastVerifiedStepIndexOf(undefined)).toBe(2); + expect(steps.lastVerifiedStepIndexOf('ava')).toBe(-1); + await ava.run('assertion', 'expect.toBeVisible', 'joined', pass, { verifies: true }); + expect(steps.lastVerifiedStepIndexOf('ava')).toBe(3); + expect(steps.lastVerifiedStepIndex).toBe(2); + }); + + it("attaches a file made outside any step to the last step of the user whose app made it", async () => { + const steps = new StepRecorder('attempt'); + const ava = steps.forUser('ava', AVA); + await ava.run('app', 'app.open', '/invites', pass); + await steps.run('app', 'app.open', '/', pass); + ava.attachArtifact('her-video'); + steps.attachArtifact('my-video'); + expect(steps.all().map((step) => step.artifacts)).toEqual([['her-video'], ['my-video']]); + }); + + it('names the peer whose step waits at an e2e run --step hold', async () => { + const held: StepHoldRequest[] = []; + const steps = new StepRecorder('attempt', { hold: async (step) => void held.push(step) }); + steps.holdable = true; + await steps.run('app', 'app.open', '/', pass); + await steps.forUser('ava', AVA).run('app', 'app.open', '/invites', pass); + expect(held.map((step) => [step.label, step.user])).toEqual([ + ['/', undefined], + ['/invites', 'ava'], + ]); + expect(Object.hasOwn(held[0]!, 'user')).toBe(false); + }); +}); diff --git a/packages/e2e/tests/unit/test-filters.test.ts b/packages/e2e/tests/unit/test-filters.test.ts index 626a3c76ca..cd9f51ce02 100644 --- a/packages/e2e/tests/unit/test-filters.test.ts +++ b/packages/e2e/tests/unit/test-filters.test.ts @@ -260,6 +260,33 @@ describe('filterCandidates', () => { ['guest page', undefined], ]); }); + + it('names the files of the setup tests that save its peers sessions, each once, and none without', async () => { + const memberSetup = await collection(() => { + test.setup('sign in member', { sessions: ['member'] }, noop); + }, 'tests/member.setup.e2e.ts'); + const peerSetups = await collection(() => { + test.setup('sign in ava', { sessions: ['ava', 'cat'] }, noop); + test.setup('sign in bob', { sessions: ['bob'] }, noop); + }, 'tests/peers.setup.e2e.ts'); + const otherSetup = await collection(() => { + test.setup('sign in dan', { sessions: ['dan'] }, noop); + }, 'tests/dan.setup.e2e.ts'); + const pages = await collection(() => { + test('pays', { session: 'member', peers: { ava: { session: 'ava' }, bob: { session: 'bob' }, cat: { session: 'cat' }, eve: {} } }, noop); + test('chats', { peers: { dan: { session: 'dan' }, eve: {} } }, noop); + test('alone', { peers: { eve: {} } }, noop); + }, 'tests/pages.e2e.ts'); + const parts = [memberSetup, peerSetups, otherSetup, pages]; + const col: Collection = { ...pages, files: parts.flatMap((part) => part.files), tests: parts.flatMap((part) => part.tests) }; + const selection = select(col, config({ targets: [{ name: 'web', platform: 'web', engine: ENGINE }] })); + expect(filterCandidates(selection).map(({ titlePath, setupFile, peerSetupFiles }) => [titlePath.at(-1), setupFile, peerSetupFiles])).toEqual([ + ['pays', 'tests/member.setup.e2e.ts', ['tests/peers.setup.e2e.ts']], + ['chats', undefined, ['tests/dan.setup.e2e.ts']], + ['alone', undefined, undefined], + ]); + expect(filterCandidates(selection).find((candidate) => candidate.titlePath.at(-1) === 'alone')).not.toHaveProperty('peerSetupFiles'); + }); }); describe('applyTestFilters', () => { diff --git a/packages/e2e/tests/unit/trace-identity.test.ts b/packages/e2e/tests/unit/trace-identity.test.ts index ae95bc2508..e3cff8432f 100644 --- a/packages/e2e/tests/unit/trace-identity.test.ts +++ b/packages/e2e/tests/unit/trace-identity.test.ts @@ -97,6 +97,21 @@ describe('traceCacheKeyHash', () => { expect(traceCacheKeyHash(buildTraceCacheKey(withParams))).toBe('400b6e2625b0feb2483a87adcd90ab7ddb03a83ef47ed5409e57680cbb1d0caf'); }); + it("keys a peer's step on the peer's name, and the test's own target and agent, and leaves the test's own user's key as it was", () => { + const mine = buildTraceCacheKey(parts); + for (const field of ['user', 'ownerTargetId', 'ownerAgent']) expect(Object.hasOwn(mine, field)).toBe(false); + expect(traceCacheKeyHash(buildTraceCacheKey({ ...parts, user: undefined }))).toBe(traceCacheKeyHash(mine)); + const peer = { name: 'ava', ownerTargetId: 'web', ownerAgent: 'admin' }; + expect(buildTraceCacheKey({ ...parts, user: peer })).toMatchObject({ user: 'ava', ownerTargetId: 'web', ownerAgent: 'admin' }); + const ava = traceCacheKeyHash(buildTraceCacheKey({ ...parts, user: peer })); + expect(ava).not.toBe(traceCacheKeyHash(mine)); + expect(traceCacheKeyHash(buildTraceCacheKey({ ...parts, user: { ...peer, name: 'bob' } }))).not.toBe(ava); + // Two pairs of one test, on two targets or as two agents, each key their peer's steps apart. + expect(traceCacheKeyHash(buildTraceCacheKey({ ...parts, user: { ...peer, ownerTargetId: 'ios' } }))).not.toBe(ava); + expect(traceCacheKeyHash(buildTraceCacheKey({ ...parts, user: { ...peer, ownerAgent: 'member' } }))).not.toBe(ava); + expect(traceCacheKeyHash(buildTraceCacheKey({ ...parts, user: { ...peer } }))).toBe(ava); + }); + it('keys the agent context by digest, never by its text', () => { const key = buildTraceCacheKey({ ...parts, agent: { name: 'buyer', context: 'Pay with .' } }); expect(key.agent).toBe('buyer'); diff --git a/packages/e2e/tests/unit/trace-recorder.test.ts b/packages/e2e/tests/unit/trace-recorder.test.ts index 9133e7f7c2..38d83a1461 100644 --- a/packages/e2e/tests/unit/trace-recorder.test.ts +++ b/packages/e2e/tests/unit/trace-recorder.test.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest'; import { describeTarget } from '../../src/agent/actions.ts'; import { TraceRecorder } from '../../src/cache/recorder.ts'; -import { buildTraceEntry, MAX_TRACE_INPUT_CHARS } from '../../src/cache/trace.ts'; +import { buildTraceEntry, MAX_TRACE_INPUT_CHARS, type ActionTrace, type TraceProvenance } from '../../src/cache/trace.ts'; import { readTraceEntry } from '../../src/cache/trace-read.ts'; import { createRedactor, SecretLedger } from '../../src/internal/redact.ts'; import { redacted } from '../helpers/redacted.ts'; @@ -25,6 +25,13 @@ const passwordField = redacted({ states: { secure: true }, }); +/** A finished trace whose provenance is written as given, past what the recorder itself would bound. */ +function makeRecorderTrace(recordedFor: TraceProvenance): ActionTrace { + const recorder = makeRecorder(); + recorder.record({ name: 'tap', node: upgradeButton }); + return { ...recorder.finalize(conclusion)!, recordedFor }; +} + function makeRecorder(options: { maxActions?: number; secrets?: ReadonlyMap } = {}) { const redact = createRedactor(options.secrets ?? new Map()); return new TraceRecorder({ @@ -41,6 +48,21 @@ const conclusion = { }; describe('TraceRecorder', () => { + it("records the peer a recording is for, with the test's own target and agent, and reads them back from the stored entry; the test's own user's names none", () => { + for (const recordedFor of [{ ...conclusion.recordedFor, user: 'ava', ownerTargetId: 'ios', ownerAgent: 'admin' }, conclusion.recordedFor]) { + const recorder = makeRecorder(); + recorder.record({ name: 'tap', node: upgradeButton }); + const trace = recorder.finalize({ ...conclusion, recordedFor }); + expect(trace?.recordedFor).toEqual(recordedFor); + const stored = readTraceEntry(JSON.parse(JSON.stringify(buildTraceEntry(trace!)))); + expect(stored?.payload.recordedFor).toEqual(recordedFor); + } + for (const oversized of [{ user: 'x'.repeat(301) }, { user: 'ava', ownerTargetId: 'x'.repeat(301), ownerAgent: 'admin' }, { user: 'ava', ownerTargetId: 'ios', ownerAgent: 'x'.repeat(301) }]) { + const unreadable = buildTraceEntry(makeRecorderTrace({ ...conclusion.recordedFor, ...oversized })); + expect(readTraceEntry(JSON.parse(JSON.stringify(unreadable))), JSON.stringify(Object.keys(oversized))).toBeUndefined(); + } + }); + it.each(['provider', 'model'] as const)('omits an oversized recorded %s', (field) => { const recorder = makeRecorder(); recorder.record({ name: 'tap', node: upgradeButton }); diff --git a/packages/e2e/tests/unit/units.test.ts b/packages/e2e/tests/unit/units.test.ts index 489a771173..fedc87c17b 100644 --- a/packages/e2e/tests/unit/units.test.ts +++ b/packages/e2e/tests/unit/units.test.ts @@ -88,6 +88,7 @@ const defaultOptions: ResolvedTestOptions = { platforms: undefined, requires: [], session: undefined, + peers: [], agents: ['default'], agentContext: undefined, skipReason: undefined, diff --git a/packages/e2e/tests/unit/worker-handle.test.ts b/packages/e2e/tests/unit/worker-handle.test.ts index 00c174ffa4..5e445997b5 100644 --- a/packages/e2e/tests/unit/worker-handle.test.ts +++ b/packages/e2e/tests/unit/worker-handle.test.ts @@ -83,6 +83,7 @@ describe('ChildProcessRunner', () => { aiTrace: false, step: false, envFor: () => ({ ...process.env, NODE_OPTIONS: `--import ${pathToFileURL(preload).href}` }), + peersFor: () => ({}), }); let exit: string | undefined; const runner = spawn('web', 0, { diff --git a/packages/html-reporter/app/data.ts b/packages/html-reporter/app/data.ts index 43c7ce4e49..c3e2ae708a 100644 --- a/packages/html-reporter/app/data.ts +++ b/packages/html-reporter/app/data.ts @@ -29,6 +29,20 @@ export interface AttemptView { readonly failure: Attempt['failure']; readonly artifacts: readonly Artifact[]; readonly environment: Attempt['environment']; + /** What each peer's app ran on and showed at the failure, by peer name: the peers whose app opened, so absent when none did. */ + readonly peers?: Attempt['peers']; +} + +/** One user's evidence at the failure: the test's own (`user` undefined), or a peer's. */ +export interface UserFailure { + readonly user: string | undefined; + readonly failure: NonNullable; +} + +/** What each user's screen showed at the failure: the test's own first, then each peer's under its name; a user with none is left out. */ +export function failuresByUser(attempt: Pick): UserFailure[] { + const users = [{ user: undefined, failure: attempt.failure }, ...Object.entries(attempt.peers ?? {}).map(([user, peer]) => ({ user, failure: peer.failure }))]; + return users.flatMap(({ user, failure }) => (failure === undefined ? [] : [{ user, failure }])); } /** The page's whole model, built once from the payload. */ @@ -86,6 +100,7 @@ function attemptViews(result: Result, groups: ReadonlyMap): failure: attempt.failure, artifacts: attempt.artifacts, environment: attempt.environment, + ...(attempt.peers === undefined ? {} : { peers: attempt.peers }), })); } return (groups.get(result.serialGroupId)?.attempts ?? []).map((attempt) => { @@ -197,16 +212,31 @@ export interface TimedVideo { readonly endsAt: number; } -/** The attempt's playable videos in recording order, each ending where the next begins. */ -export function timedVideos(artifacts: readonly Artifact[], media: ReportMedia): TimedVideo[] { +/** + * One user's playable videos of the attempt, the test's own user's when + * `user` is absent, in recording order, each ending where the next begins. + * Each user's app records its own, so each user's videos are a timeline of their own. + */ +export function timedVideos(artifacts: readonly Artifact[], media: ReportMedia, user?: string): TimedVideo[] { const videos = artifacts.flatMap((artifact) => { - const url = artifact.kind === 'video' ? artifactUrl(artifact, media) : undefined; + const url = artifact.kind === 'video' && artifact.user === user ? artifactUrl(artifact, media) : undefined; return url === undefined || artifact.startedAt === undefined ? [] : [{ artifact, url, startsAt: Date.parse(artifact.startedAt) }]; }); const sorted = videos.toSorted((a, b) => a.startsAt - b.startsAt); return sorted.map((video, index) => ({ ...video, endsAt: sorted[index + 1]?.startsAt ?? Infinity })); } +/** The users whose app left a playable video: the test's own user first, then each peer in the order its first video was registered. */ +export function videoUsers(artifacts: readonly Artifact[], media: ReportMedia): (string | undefined)[] { + const users = new Set(); + for (const artifact of artifacts) { + if (artifact.kind === 'video' && artifact.startedAt !== undefined && artifactUrl(artifact, media) !== undefined) users.add(artifact.user); + } + // Sorting would put `undefined` last whatever the comparator says, so the test's own user is placed first by hand. + const peers = [...users].filter((user) => user !== undefined); + return users.has(undefined) ? [undefined, ...peers] : peers; +} + /** * Where a step starts in the recording that was running then: the segment * and the second into it. A step before the first segment began is at its diff --git a/packages/html-reporter/app/player.tsx b/packages/html-reporter/app/player.tsx index 65e7bfb614..579976f55b 100644 --- a/packages/html-reporter/app/player.tsx +++ b/packages/html-reporter/app/player.tsx @@ -35,6 +35,9 @@ export function VideoPlayer({ onIndexChange, videoRef, steps, + users, + user, + onUserChange, playingStep, onPlayhead, shape, @@ -44,7 +47,12 @@ export function VideoPlayer({ index: number; onIndexChange: (index: number) => void; videoRef: RefObject; + /** The steps of the user whose videos these are. */ steps: readonly Step[]; + /** Every user whose app recorded a video, the test's own user as `undefined`; a choice shows only with more than one. */ + users: readonly (string | undefined)[]; + user: string | undefined; + onUserChange: (user: string | undefined) => void; playingStep: Step | undefined; onPlayhead: (at: number) => void; /** @@ -150,6 +158,22 @@ export function VideoPlayer({ {formatClock(time)} / {formatClock(duration)} + {users.length > 1 ? ( +
+ {users.map((candidate) => ( + + ))} +
+ ) : null} {videos.length > 1 ? (
{videos.map((candidate, partIndex) => ( diff --git a/packages/html-reporter/app/prompt.ts b/packages/html-reporter/app/prompt.ts index 3a0f6ae54b..02d2e510c7 100644 --- a/packages/html-reporter/app/prompt.ts +++ b/packages/html-reporter/app/prompt.ts @@ -1,4 +1,4 @@ -import { formatDuration, testTitle, type Artifact, type AttemptView, type ReportError, type ReportModel, type Result, type Step } from './data.ts'; +import { failuresByUser, formatDuration, testTitle, type Artifact, type AttemptView, type ReportError, type ReportModel, type Result, type Step } from './data.ts'; /** Agent turns quoted per failed step; the trace page has every one. */ const MAX_TURNS = 3; @@ -61,7 +61,8 @@ function errorLines(error: ReportError): string[] { function stepLines(step: Step, index: number, attempt: AttemptView): string[] { const label = step.label === '' ? '' : `: ${step.label.replaceAll('\n', ' ')}`; const notes = [formatDuration(step.durationMs), step.phase, step.cache === undefined ? undefined : `cache ${step.cache.mode}`].filter((note) => note !== undefined); - const head = `${index + 1}. ${step.status} ${step.api}${label} (${notes.join(', ')})`; + const user = step.user === undefined ? '' : `${step.user} · `; + const head = `${index + 1}. ${step.status} ${user}${step.api}${label} (${notes.join(', ')})`; if (step.status === 'passed') return [head]; const actions = step.events.flatMap((event) => (event.kind === 'engine' && event.detail !== undefined ? [`${event.detail}${event.status === 'passed' ? '' : ` (${event.status})`}`] : [])); const turns = (step.turns ?? []).slice(-MAX_TURNS).map((turn) => `turn ${turn.index}: ${turn.calls.join(', ')} -> ${turn.outcome}`); @@ -80,26 +81,30 @@ function stepLines(step: Step, index: number, attempt: AttemptView): string[] { ]; } +/** What the runner saw on each user's screen at the failure: the test's own, then each peer's under its name. */ function failureLines(attempt: AttemptView): string[] { - const { failure } = attempt; - if (failure === undefined) return []; - return [ - ...(failure.url === undefined ? [] : [`- Screen: ${failure.url}`]), - ...(failure.candidates === undefined || failure.candidates.length === 0 ? [] : ['- Closest on screen:', ...failure.candidates.map((line) => ` - ${line}`)]), - ]; + return failuresByUser(attempt).flatMap(({ user, failure }) => { + const whose = user === undefined ? '' : ` of ${user}`; + return [ + ...(failure.url === undefined ? [] : [`- Screen${whose}: ${failure.url}`]), + ...(failure.candidates === undefined || failure.candidates.length === 0 ? [] : [`- Closest on screen${whose}:`, ...failure.candidates.map((line) => ` - ${line}`)]), + ]; + }); } /** The trace page, the failure evidence, the videos, and the files the test left; the step screenshots are in the trace. */ function fileLines(model: ReportModel, result: Result, attempt: AttemptView): string[] { const trace = Object.hasOwn(model.traces, result.id) ? model.traces[result.id] : undefined; const describe = (artifact: Artifact): string | undefined => { - if (artifact.id === attempt.failure?.screen) return 'the screen tree at the failure'; - if (artifact.id === attempt.failure?.screenshot) return 'a screenshot at the failure'; + const failure = artifact.user === undefined ? attempt.failure : attempt.peers?.[artifact.user]?.failure; + if (artifact.id === failure?.screen) return 'the screen tree at the failure'; + if (artifact.id === failure?.screenshot) return 'a screenshot at the failure'; if (artifact.kind === 'video') return 'the recording'; return artifact.kind === 'screenshot' ? undefined : artifact.kind; }; const files = attempt.artifacts.flatMap((artifact) => { - const about = describe(artifact); + const described = describe(artifact); + const about = described === undefined || artifact.user === undefined ? described : `${described}, of ${artifact.user}`; return about === undefined || artifact.path === undefined ? [] : [`- ${model.resultsDir}/${artifact.path}: ${about}`]; }); return [...(trace === undefined ? [] : [`- ${trace}: the runner's trace of this test`]), ...files]; diff --git a/packages/html-reporter/app/test.tsx b/packages/html-reporter/app/test.tsx index dfcbf85396..f5bf5a38f7 100644 --- a/packages/html-reporter/app/test.tsx +++ b/packages/html-reporter/app/test.tsx @@ -2,18 +2,21 @@ import { useMemo, useRef, useState, type ReactNode } from 'react'; import { artifactUrl, formatClock, + failuresByUser, formatCost, formatDuration, formatTokens, testTitle, timedVideos, videoPosition, + videoUsers, type Artifact, type AttemptView, type ReportModel, type Result, type Step, type TimedVideo, + type UserFailure, } from './data.ts'; import { CodeFrame, ErrorBlock, hasFrame } from './failure.tsx'; import { failurePrompt } from './prompt.ts'; @@ -80,7 +83,14 @@ const WEB_SHAPE: VideoShape = { width: 1280, height: 720 }; const PHONE_SHAPE: VideoShape = { width: 402, height: 874 }; function AttemptPanel({ attempt, model, prompt, platform }: { attempt: AttemptView; model: ReportModel; prompt: () => string; platform: string }) { - const videos = useMemo(() => timedVideos(attempt.artifacts, model.media), [attempt, model.media]); + // Each user's app recorded its own videos; the player shows one user's at a time. + const users = useMemo(() => videoUsers(attempt.artifacts, model.media), [attempt, model.media]); + const videosOf = useMemo( + () => new Map(users.map((user) => [user, timedVideos(attempt.artifacts, model.media, user)])), + [users, attempt, model.media], + ); + const [videoUser, setVideoUser] = useState(users[0]); + const videos = videosOf.get(videoUser) ?? []; const videoRef = useRef(null); const [videoIndex, setVideoIndex] = useState(0); const [playhead, setPlayhead] = useState(undefined); @@ -91,12 +101,14 @@ function AttemptPanel({ attempt, model, prompt, platform }: { attempt: AttemptVi ); const portrait = isPortrait(shape); - // The step the video is showing: the last one that started at or before the playhead. - const playingStep = playhead === undefined ? undefined : attempt.steps.findLast((step) => Date.parse(step.startedAt) <= playhead); + // The step the video is showing: the last of its user's that started at or before the playhead. + const shownSteps = attempt.steps.filter((step) => step.user === videoUser); + const playingStep = playhead === undefined ? undefined : shownSteps.findLast((step) => Date.parse(step.startedAt) <= playhead); const seek = (step: Step) => { - const position = videoPosition(step, videos); + const position = videoPosition(step, videosOf.get(step.user) ?? []); if (position === undefined) return; + setVideoUser(step.user); setVideoIndex(position.video); // A new segment loads its source first; seek once its metadata is in. requestAnimationFrame(() => { @@ -121,7 +133,8 @@ function AttemptPanel({ attempt, model, prompt, platform }: { attempt: AttemptVi : thrownAt; // The failure evidence has its own section; the gallery and the file list leave it out. - const evidence = new Set([attempt.failure?.screenshot, attempt.failure?.screen]); + const atFailure = failuresByUser(attempt); + const evidence = new Set(atFailure.flatMap(({ failure }) => [failure.screenshot, failure.screen])); // A page without media (`media: 'none'`), or a file the reporter could not embed, has no URL to show. const shown = attempt.artifacts.filter((artifact) => !evidence.has(artifact.id) && artifactUrl(artifact, model.media) !== undefined); const screenshots = shown.filter((artifact) => artifact.kind === 'screenshot'); @@ -140,7 +153,13 @@ function AttemptPanel({ attempt, model, prompt, platform }: { attempt: AttemptVi index={videoIndex} onIndexChange={setVideoIndex} videoRef={videoRef} - steps={attempt.steps} + steps={shownSteps} + users={users} + user={videoUser} + onUserChange={(user) => { + setVideoUser(user); + setVideoIndex(0); + }} playingStep={playingStep} onPlayhead={setPlayhead} shape={shape} @@ -159,7 +178,7 @@ function AttemptPanel({ attempt, model, prompt, platform }: { attempt: AttemptVi step={step} attempt={attempt} model={model} - videos={videos} + videos={videosOf.get(step.user) ?? []} playing={step === playingStep} onSeek={seek} /> @@ -172,12 +191,14 @@ function AttemptPanel({ attempt, model, prompt, platform }: { attempt: AttemptVi

app log

-            {attempt.appLog.map((line) => `${line.level.padEnd(5)} ${line.text}`).join('\n')}
+            {attempt.appLog.map((line) => `${line.level.padEnd(5)} ${line.user === undefined ? '' : `${line.user} · `}${line.text}`).join('\n')}
           
)}
- + {atFailure.map(({ user, failure }) => ( + + ))} {screenshots.length === 0 ? null : (

screenshots

@@ -272,6 +293,11 @@ function StepRow({ + {step.user === undefined ? null : ( + + {step.user} + + )} {step.api} {step.label} @@ -385,15 +411,15 @@ function Detail({ label, children }: { label: string; children: ReactNode }) { ); } -function FailureEvidence({ attempt, model }: { attempt: AttemptView; model: ReportModel }) { - const { failure } = attempt; - if (failure === undefined) return null; - const find = (id: string | undefined) => (id === undefined ? undefined : attempt.artifacts.find((artifact) => artifact.id === id)); +/** What one user's screen showed at the failure; a peer's names it. */ +function FailureEvidence({ user, failure, artifacts, model }: UserFailure & { artifacts: readonly Artifact[]; model: ReportModel }) { + const find = (id: string | undefined) => (id === undefined ? undefined : artifacts.find((artifact) => artifact.id === id)); const screenshot = find(failure.screenshot); const screen = find(failure.screen); + const whose = user === undefined ? '' : ` · ${user}`; return ( -
-

at failure

+
+

at failure{whose}

{failure.url === undefined ? null : {failure.url}} {screenshot === undefined ? null : } {screen === undefined ? null : } diff --git a/packages/html-reporter/tests/unit/data.test.ts b/packages/html-reporter/tests/unit/data.test.ts index 5453be66a7..526dbad37c 100644 --- a/packages/html-reporter/tests/unit/data.test.ts +++ b/packages/html-reporter/tests/unit/data.test.ts @@ -1,11 +1,73 @@ import type { Report } from 'e2e'; import { describe, expect, it } from 'vitest'; -import { buildModel } from '../../app/data.ts'; +import { buildModel, failuresByUser, timedVideos, videoPosition, videoUsers, type Artifact, type Step } from '../../app/data.ts'; +import { failurePrompt } from '../../app/prompt.ts'; import fixture from '../../../e2e/schema/fixtures/report-v1.valid.json' with { type: 'json' }; // The page's own tsconfig checks this file: the model it tests reads the DOM. const REPORT = fixture as unknown as Report; +describe('videos of more than one user', () => { + const at = (seconds: number) => new Date(Date.UTC(2026, 0, 1, 0, 0, seconds)).toISOString(); + const video = (id: string, startedAt: string, user?: string): Artifact => ({ + id, + kind: 'video', + mediaType: 'video/webm', + path: `t/${user === undefined ? '' : `peers/${user}/`}${id}.webm`, + redaction: 'incomplete', + startedAt, + producer: { kind: 'attempt' }, + ...(user === undefined ? {} : { user }), + }); + const media = { mode: 'link', base: 'results' } as const; + const artifacts = [video('mine', at(0)), video('hers', at(3), 'ava'), video('mine-2', at(6))]; + + it("keeps each user's videos on a timeline of its own, so a peer's never cuts the test's own short", () => { + expect(videoUsers(artifacts, media)).toEqual([undefined, 'ava']); + expect(videoUsers([video('hers', at(3), 'ava'), video('mine', at(5))], media)).toEqual([undefined, 'ava']); + const mine = timedVideos(artifacts, media); + expect(mine.map((each) => [each.artifact.id, each.endsAt])).toEqual([ + ['mine', Date.parse(at(6))], + ['mine-2', Infinity], + ]); + const hers = timedVideos(artifacts, media, 'ava'); + expect(hers.map((each) => [each.artifact.id, each.endsAt])).toEqual([['hers', Infinity]]); + const step = (startedAt: string) => ({ startedAt }) as Step; + expect(videoPosition(step(at(4)), mine)).toEqual({ video: 0, seconds: 4 }); + expect(videoPosition(step(at(4)), hers)).toEqual({ video: 0, seconds: 1 }); + }); + + it('lists no user whose videos the page cannot show', () => { + expect(videoUsers(artifacts, { mode: 'none' })).toEqual([]); + }); +}); + +describe('each user at the failure', () => { + it("lists the test's own screen first, then each peer's under its name, and leaves out a user with none", () => { + const model = buildModel({ report: REPORT, media: { mode: 'none' }, resultsDir: '.e2e/results', traces: {}, sources: {} }); + const attempt = model.attempts(model.results[0]!)[0]!; + expect(failuresByUser(attempt).map(({ user, failure }) => [user, failure.url])).toEqual([ + [undefined, 'http://127.0.0.1:3000/todos'], + ['guest', 'http://127.0.0.1:3000/invites'], + ]); + expect(failuresByUser({ ...attempt, failure: undefined, peers: { ...attempt.peers, bob: { target: 'web' } } }).map(({ user }) => user)).toEqual(['guest']); + }); +}); + +describe('the copied prompt', () => { + it("names the peer of a step, the peer's screen at the failure, and the peer's files", () => { + const model = buildModel({ report: REPORT, media: { mode: 'none' }, resultsDir: '.e2e/results', traces: {}, sources: {} }); + const result = model.results[0]!; + const attempt = model.attempts(result)[0]!; + const prompt = failurePrompt(model, result, attempt, { number: 1, count: 1 }); + expect(prompt).toContain(`3. passed guest · locator.click: getByRole('button', { name: 'Accept' }) (300ms)`); + expect(prompt).toContain('- Screen: http://127.0.0.1:3000/todos\n- Closest on screen:'); + expect(prompt).toContain('- Screen of guest: http://127.0.0.1:3000/invites'); + expect(prompt).toContain('- .e2e/results/web/tests_example.e2e.ts__opens_app/attempt-0/peers/guest/video/video.webm: the screen tree at the failure, of guest'); + expect(prompt).toContain('- .e2e/results/web/tests_example.e2e.ts__opens_app/attempt-0/video/video.webm: the screen tree at the failure\n'); + }); +}); + describe('serial members', () => { it('show their own error, never the group\'s once they passed, and the group\'s when they have none', () => { const [group] = REPORT.run.serialGroups; diff --git a/packages/mobile/src/pool.ts b/packages/mobile/src/pool.ts index 55c31a936e..44adc8df8e 100644 --- a/packages/mobile/src/pool.ts +++ b/packages/mobile/src/pool.ts @@ -251,6 +251,13 @@ export class DevicePool { */ async prepare(info: EnginePrepareInfo): Promise { if (info.slots === 0) return {}; + // Refused before anything is leased: a hosted device is billed from the start. + if (this.source instanceof LeasedDevices && (info.peerSlots ?? 0) > 0) { + throw new ConfigurationError( + 'UNSUPPORTED_CAPABILITY', + `target "${info.targetName}" leases its devices from a device provider, and a test's peer on it would need a lease of its own, which this version does not take for a peer; run the peer on a simulator or emulator on this machine`, + ); + } const bindings = await this.source.bind(info); await this.warm(bindings, info); this.bound.set(info.targetName, bindings); diff --git a/packages/mobile/tests/unit/provider.test.ts b/packages/mobile/tests/unit/provider.test.ts index 3c8ec2bedd..00db03bf7e 100644 --- a/packages/mobile/tests/unit/provider.test.ts +++ b/packages/mobile/tests/unit/provider.test.ts @@ -67,6 +67,20 @@ const finishInfo = (log: (line: string) => void = () => undefined) => ({ }); describe('device provider', () => { + it("refuses, before it leases anything, a run that puts a test's peer on the target", async () => { + const cloud = provider(); + const h = harness({ device: cloud.impl }); + await expect(h.prepare({ ...prepareInfo({}, 2), peerSlots: 1 })).rejects.toMatchObject({ + code: 'UNSUPPORTED_CAPABILITY', + message: + 'target "ios" leases its devices from a device provider, and a test\'s peer on it would need a lease of its own, which this version does not take for a peer; run the peer on a simulator or emulator on this machine', + }); + expect(cloud.acquired).toEqual([]); + // A simulator pool on this machine serves a peer: each slot is a device of its own. + const local = harness({ device: ['iPhone 17 Pro peers-1', 'iPhone 17 Pro peers-2'] }); + expect((await local.prepare({ ...prepareInfo({}, 2), peerSlots: 1 }))?.workers).toBe(2); + }); + it('rejects a provider without a name or the two methods', () => { expect(() => harness({ device: { name: '' } as unknown as DeviceProvider })).toThrow(/non-empty `name`/); expect(() => harness({ device: null as unknown as DeviceProvider })).toThrow(/non-empty `name`/); diff --git a/packages/web/src/provider.ts b/packages/web/src/provider.ts index 7a124a5d5f..42a86d078d 100644 --- a/packages/web/src/provider.ts +++ b/packages/web/src/provider.ts @@ -363,6 +363,13 @@ export class LeasedBrowsers { */ async prepare(info: EnginePrepareInfo): Promise { if (info.slots === 0) return {}; + // Refused before anything is leased: a lease is billed from the start. + if ((info.peerSlots ?? 0) > 0) { + throw new ConfigurationError( + 'UNSUPPORTED_CAPABILITY', + `target "${info.targetName}" leases its browsers from ${this.provider.name}, and a test's peer on it would need a lease of its own, which this version does not take for a peer; run the peer on a target that launches its browser on this machine`, + ); + } const variable = handoffVariable(info.targetName); const held: BrowserLease[] = []; this.held.set(info.targetName, held); diff --git a/packages/web/src/surface.ts b/packages/web/src/surface.ts index 2bde0c5b4f..db47a50969 100644 --- a/packages/web/src/surface.ts +++ b/packages/web/src/surface.ts @@ -364,7 +364,17 @@ export class PlaywrightSurface { async prepare(info: EnginePrepareInfo): Promise { await this.configuredInitScripts.load(info.projectRoot); if (this.leases !== undefined) return this.leases.prepare(info); - if (this.connect !== undefined) return; + if (this.connect !== undefined) { + // An attached browser is one the target does not launch, and a + // reconnecting attach shares one context: a peer would not have a browser of its own. + if ((info.peerSlots ?? 0) > 0) { + throw new ConfigurationError( + 'UNSUPPORTED_CAPABILITY', + `target "${info.targetName}" attaches to a browser over CDP (web({ connect })), and a test's peer on it would not get a browser of its own; run the peer on a target that launches its browser on this machine`, + ); + } + return; + } await ensureBrowsersInstalled([this.browserName], { env: info.env, signal: info.signal, log: info.log, headed: info.headed }); } diff --git a/packages/web/tests/unit/browser-provider.test.ts b/packages/web/tests/unit/browser-provider.test.ts index 03f8ff9776..e491f42e2a 100644 --- a/packages/web/tests/unit/browser-provider.test.ts +++ b/packages/web/tests/unit/browser-provider.test.ts @@ -269,6 +269,23 @@ describe('worker scope', () => { expect(cloud.released).toHaveLength(2); }); + it("refuses, before it leases anything, a run that puts a test's peer on the target", async () => { + for (const scope of ['worker', 'attempt'] as const) { + const cloud = provider(); + const runner = new PlaywrightSurface({ browser: { ...cloud.impl, scope } }); + await expect(runner.prepare({ ...prepareInfo(3), peerSlots: 1 })).rejects.toMatchObject({ + code: 'UNSUPPORTED_CAPABILITY', + message: + 'target "web" leases its browsers from toy-cloud, and a test\'s peer on it would need a lease of its own, which this version does not take for a peer; run the peer on a target that launches its browser on this machine', + }); + expect(cloud.acquired).toEqual([]); + } + // A run with no peer there leases as it always has. + const cloud = provider(); + await new PlaywrightSurface({ browser: cloud.impl }).prepare({ ...prepareInfo(1), peerSlots: 0 }); + expect(cloud.acquired).toHaveLength(1); + }); + it('leases nothing for a target with no slots', async () => { const cloud = provider(); const runner = new PlaywrightSurface({ browser: cloud.impl }); diff --git a/packages/web/tests/unit/cdp-connect.test.ts b/packages/web/tests/unit/cdp-connect.test.ts index 73ad1f1375..a020b07206 100644 --- a/packages/web/tests/unit/cdp-connect.test.ts +++ b/packages/web/tests/unit/cdp-connect.test.ts @@ -71,6 +71,18 @@ describe('web({ connect })', () => { }); describe('PlaywrightSurface CDP attach', () => { + it("refuses a run that puts a test's peer on an attached browser, and prepares any other run as before", async () => { + const attached = new PlaywrightSurface({ connect: { cdpEndpoint: () => 'ws://localhost:0' } }); + const info = { runId: 'r', targetName: 'cdp', projectRoot: '/project', app: {}, slots: 2, env: {}, signal: new AbortController().signal, headed: false, log: () => undefined }; + await expect(attached.prepare({ ...info, peerSlots: 1 })).rejects.toMatchObject({ + code: 'UNSUPPORTED_CAPABILITY', + message: 'target "cdp" attaches to a browser over CDP (web({ connect })), and a test\'s peer on it would not get a browser of its own; run the peer on a target that launches its browser on this machine', + }); + await expect(attached.prepare(info)).resolves.toBeUndefined(); + await expect(attached.prepare({ ...info, peerSlots: 0 })).resolves.toBeUndefined(); + }); + + it('fails init with ENGINE_FAILURE when the endpoint resolves empty or the resolver throws, without touching a browser', async () => { const empty = new PlaywrightSurface({ connect: { cdpEndpoint: () => ' ' } }); await expect(empty.init(initInfo())).rejects.toMatchObject({ diff --git a/plugins/e2e/skills/e2e/references/debugging.md b/plugins/e2e/skills/e2e/references/debugging.md index 6cab63cc2e..13f8797312 100644 --- a/plugins/e2e/skills/e2e/references/debugging.md +++ b/plugins/e2e/skills/e2e/references/debugging.md @@ -80,7 +80,8 @@ jq '.run.results[] | select(.selected and .status != "passed") | .attempts[-1] `error.details` holds the facts, `error.source` the line, `failure` the `url`, `screen` and `screenshot` artifact ids, and `candidates`; a - failed agent step has `turns`; any agent step has + peer's step has `user`, and when it failed, the peer's screen is in + `peers..failure`, not `failure`; a failed agent step has `turns`; any agent step has `observationTruncated: true` when a semantic observation was incomplete; `selected` drops filtered-out tests (recorded as `skipped`). diff --git a/plugins/e2e/skills/e2e/references/mcp.md b/plugins/e2e/skills/e2e/references/mcp.md index 4e450a8049..da62cc4d37 100644 --- a/plugins/e2e/skills/e2e/references/mcp.md +++ b/plugins/e2e/skills/e2e/references/mcp.md @@ -270,8 +270,8 @@ session runs the test and stops where it failed: the session's target. Several fail with `TEST_AMBIGUOUS`, which lists them as `file:line`; none fails with `NO_TESTS`. - `SESSION_TEST_UNSUPPORTED`: a test in a serial group, a test that starts - from a setup test's `session`, and a test that runs as several agents - can't run alone in a session. Fix those with `run_tests`. + from a setup test's `session`, a test that runs as several agents, and a + test with peers can't run alone in a session. Fix those with `run_tests`. ## Rules diff --git a/plugins/e2e/skills/e2e/references/running.md b/plugins/e2e/skills/e2e/references/running.md index d44fe1c59b..0377844f7e 100644 --- a/plugins/e2e/skills/e2e/references/running.md +++ b/plugins/e2e/skills/e2e/references/running.md @@ -294,7 +294,8 @@ jobs: passes on `pull_request` alone; never pass it on `pull_request_target`. Every test runs without it and on a `--last-failed` rerun. The decision filter also runs every test on a lockfile or `e2e.config` change, and the - tests whose test file, setup file, or stored screenshots changed. It scores + tests whose test file, a setup file of its or a peer's session, or stored + screenshots changed. It scores each test, and each target starts the likeliest files first. With one worker (the CI default) only the relevance bands order files and collection order breaks ties, since the timings history matters only above one worker. On GitLab, pass `--changed-since ${CI_MERGE_REQUEST_TARGET_BRANCH_SHA:-$CI_MERGE_REQUEST_DIFF_BASE_SHA}` diff --git a/plugins/e2e/skills/e2e/references/setup.md b/plugins/e2e/skills/e2e/references/setup.md index 0afc20fb9a..37ef973a64 100644 --- a/plugins/e2e/skills/e2e/references/setup.md +++ b/plugins/e2e/skills/e2e/references/setup.md @@ -165,7 +165,7 @@ or `E2E_USER_ADMIN_PASSWORD` first, or defer to fill time with | `reporters` | `['list']` | `list`, `json`, `junit`, `markdown`, or `{ name, onEvent?, onRunFinished? }` objects; `json` excludes `list`, `--reporter` keeps the objects. | | `cache` | `'read-write'` | `'read-write'`, `'read-only'`, `'off'`, or `{ mode, store, dir, strict }`; CI demotes only a defaulted mode to `'read-only'`. `strict` (`--strict-cache`) fails a step whose recording no longer replays (`REPLAY_STALE`) instead of handing it to the agent; retries replay too, and the run never writes the cache. | | `agents` | `{ default: built-in }` | Tests run with `default`, `e2e run --agent ` picks another, entries never inherit from `default`. Options: topic `agent`. | -| `filters` | `[]` | Test filters `{ name, filter(tests, context) }`, unique names, applied in order with `--changed-since `. Use `filters: [decisionFilter({ model: gateway.decisionModel('typesafe-ai/jev') })]`, with `decisionFilter` from `@e2e-dev/decision` and `gateway` from `ai` (install `@e2e-dev/decision ai`), to run only the tests a pull request can affect. `filter` gets candidates `{ id, file, titlePath, tags, setupFile? }` and a context `{ projectRoot, changes: { base, root, files }, configFile, signal, log, redact }` with repository-relative `files`, and returns `{ exclude: { [id]: reason }, relevance?: { [id]: 0 to 1 }, note? }`; every test it does not name runs, and `relevance` (how likely each test is to fail) makes each target start the likeliest files first. Read files, the environment, or the network inside `filter`, never at config load: workers load the config too. When filters run: topic `running`. | +| `filters` | `[]` | Test filters `{ name, filter(tests, context) }`, unique names, applied in order with `--changed-since `. Use `filters: [decisionFilter({ model: gateway.decisionModel('typesafe-ai/jev') })]`, with `decisionFilter` from `@e2e-dev/decision` and `gateway` from `ai` (install `@e2e-dev/decision ai`), to run only the tests a pull request can affect. `filter` gets candidates `{ id, file, titlePath, tags, setupFile?, peerSetupFiles? }` and a context `{ projectRoot, changes: { base, root, files }, configFile, signal, log, redact }` with repository-relative `files`, and returns `{ exclude: { [id]: reason }, relevance?: { [id]: 0 to 1 }, note? }`; every test it does not name runs, and `relevance` (how likely each test is to fail) makes each target start the likeliest files first. Read files, the environment, or the network inside `filter`, never at config load: workers load the config too. When filters run: topic `running`. | | `credentials` | `{}` | Named `{ username, password }`; `password` is a 6+ code point string or a function returning it. | | `secrets` | `{}` | Named values the model never sees (API keys, tokens), same value rule. A separate namespace: a credential's password is `credentials.user(name).password` (named `.password`), never `secrets.get()`, so a name may be both. | | `output` | `'.e2e'` | Results directory; `--output ` for one run. Inside the project root, not the root, not a tests glob's directory, never the cache dir (`cache.dir` stays `.e2e/cache`). | diff --git a/plugins/e2e/skills/e2e/references/writing-tests.md b/plugins/e2e/skills/e2e/references/writing-tests.md index 2d4e4f5a97..9c7a516450 100644 --- a/plugins/e2e/skills/e2e/references/writing-tests.md +++ b/plugins/e2e/skills/e2e/references/writing-tests.md @@ -9,6 +9,7 @@ - Locators - expect - Sign-in sessions +- Two users in one test - Start near the screen under test - The browser fixture (browser only) - Habits @@ -149,12 +150,13 @@ or a blocked agent verdict still fails the test. | `platforms` | unset | Only targets with these platforms, e.g. `['ios']`. | | `requires` | `[]` | Engine capabilities, e.g. `['browser']`; missing ones skip the test at selection rather than failing it with `UNSUPPORTED_CAPABILITY`. | | `session` | unset | Restore state saved by a setup test. | +| `peers` | unset | More users by name, each on an app of its own: `{ ava: { target?, session?, agent?, agentContext? } }`. See Two users in one test. | | `agentContext` | unset | Extra context for `agent.*` calls in this test or group. | | `agent` | the run's agent | A configured name (`agents.`) or a list run once per agent; `--agent` narrows the list, a setup test takes one name. Innermost wins; `agent.act(..., { agent })` names another for one call. | | `trace`, `video` | the target's | `'off'`, `'on'`, `'retain-on-failure'`, `'on-first-retry'`, `'on-all-retries'`: whether the test keeps a trace page, which attempts record video. Innermost wins over `--trace` / `--video`, the target, and the config; video where the engine cannot record is `UNSUPPORTED_ARTIFACT` for the run. | | `serial` | `false` | Groups only. Members share app state, run in order on one worker, retry as a whole, and take the group's `trace` and `video`. | -Serial members cannot set `retries`, `trace`, `video`, `session`, +Serial members cannot set `retries`, `trace`, `video`, `session`, `peers`, `platforms`, `requires`, `skip`, `fail`, or `only`, nor can a nested `describe` set `trace` or `video`; nesting serial groups is a `COLLECTION_ERROR`. @@ -174,7 +176,9 @@ configured model, else `MODEL_UNAVAILABLE` (topic `agent`). `platform` (`string`): always, hooks included; `web`, `ios`, `android`, or an engine's label. `browser` (`Browser`): browser targets, import `test` from `@e2e-dev/web`. `device` (`Device`): device targets, import `test` from `@e2e-dev/mobile`. -`session` (`SetupSession`): only in `test.setup`. +`session` (`SetupSession`): only in `test.setup`. `peers` (by name): each +declared peer's own `app`, `screen`, `agent`, `platform`, and its engine's +fixtures; empty without the option. ### app @@ -464,6 +468,38 @@ credentials: { `` (and so does the test id, for a value in a title), so the agent cannot type it. Pass the handle. +## Two users in one test + +`peers` adds users to one test, each on an app of its own, opened before +`beforeEach` and closed with the test: + +```ts +test('Ava sees the payment', { session: 'member', peers: { ava: { session: 'ava' } } }, async ({ app, screen, peers }) => { + await app.open('/pay'); + await screen.getByRole('button', 'Pay Ava $3').tap(); + await peers.ava.app.open('/activity'); + await expect(peers.ava.screen.getByText('$3.00 from Member')).toBeVisible(); +}); +``` + +- `target` defaults to the test's own; the run must select a peer's target + (`--target`), and the test still runs once per selected target, so pin the + test's side with `platforms`. +- A peer's `session` is saved by a setup test on the peer's target. A device + restores none: a device peer signs in during the test. +- A device peer takes a device of its own; with too few, the run starts + fewer workers, and with none to spare for a peer it stops before any test. +- Each peer's steps carry `user` in the report, its files go in + `peers//`, its replay recordings are its own in each target and + agent the test runs on, its screenshot baselines in each target, and its + agent sees only its own earlier steps. One secret ledger covers every user. +- A peer's engine fixtures (`browser`, `device`) are typed `unknown`: cast + one to use it, as in `peers.ava.device as Device`. +- Not in a serial group, a setup test, `open_session`, on an engine-server + target, a hosted browser or device provider, or a CDP attach. The peer's + engine must be created in the config or a file it imports, in a run from a + config file. + ## Start near the screen under test A test pays for every step before the screen it checks, on every run and on diff --git a/skills/e2e/references/debugging.md b/skills/e2e/references/debugging.md index 6cab63cc2e..13f8797312 100644 --- a/skills/e2e/references/debugging.md +++ b/skills/e2e/references/debugging.md @@ -80,7 +80,8 @@ jq '.run.results[] | select(.selected and .status != "passed") | .attempts[-1] `error.details` holds the facts, `error.source` the line, `failure` the `url`, `screen` and `screenshot` artifact ids, and `candidates`; a - failed agent step has `turns`; any agent step has + peer's step has `user`, and when it failed, the peer's screen is in + `peers..failure`, not `failure`; a failed agent step has `turns`; any agent step has `observationTruncated: true` when a semantic observation was incomplete; `selected` drops filtered-out tests (recorded as `skipped`). diff --git a/skills/e2e/references/mcp.md b/skills/e2e/references/mcp.md index 4e450a8049..da62cc4d37 100644 --- a/skills/e2e/references/mcp.md +++ b/skills/e2e/references/mcp.md @@ -270,8 +270,8 @@ session runs the test and stops where it failed: the session's target. Several fail with `TEST_AMBIGUOUS`, which lists them as `file:line`; none fails with `NO_TESTS`. - `SESSION_TEST_UNSUPPORTED`: a test in a serial group, a test that starts - from a setup test's `session`, and a test that runs as several agents - can't run alone in a session. Fix those with `run_tests`. + from a setup test's `session`, a test that runs as several agents, and a + test with peers can't run alone in a session. Fix those with `run_tests`. ## Rules diff --git a/skills/e2e/references/running.md b/skills/e2e/references/running.md index d44fe1c59b..0377844f7e 100644 --- a/skills/e2e/references/running.md +++ b/skills/e2e/references/running.md @@ -294,7 +294,8 @@ jobs: passes on `pull_request` alone; never pass it on `pull_request_target`. Every test runs without it and on a `--last-failed` rerun. The decision filter also runs every test on a lockfile or `e2e.config` change, and the - tests whose test file, setup file, or stored screenshots changed. It scores + tests whose test file, a setup file of its or a peer's session, or stored + screenshots changed. It scores each test, and each target starts the likeliest files first. With one worker (the CI default) only the relevance bands order files and collection order breaks ties, since the timings history matters only above one worker. On GitLab, pass `--changed-since ${CI_MERGE_REQUEST_TARGET_BRANCH_SHA:-$CI_MERGE_REQUEST_DIFF_BASE_SHA}` diff --git a/skills/e2e/references/setup.md b/skills/e2e/references/setup.md index 0afc20fb9a..37ef973a64 100644 --- a/skills/e2e/references/setup.md +++ b/skills/e2e/references/setup.md @@ -165,7 +165,7 @@ or `E2E_USER_ADMIN_PASSWORD` first, or defer to fill time with | `reporters` | `['list']` | `list`, `json`, `junit`, `markdown`, or `{ name, onEvent?, onRunFinished? }` objects; `json` excludes `list`, `--reporter` keeps the objects. | | `cache` | `'read-write'` | `'read-write'`, `'read-only'`, `'off'`, or `{ mode, store, dir, strict }`; CI demotes only a defaulted mode to `'read-only'`. `strict` (`--strict-cache`) fails a step whose recording no longer replays (`REPLAY_STALE`) instead of handing it to the agent; retries replay too, and the run never writes the cache. | | `agents` | `{ default: built-in }` | Tests run with `default`, `e2e run --agent ` picks another, entries never inherit from `default`. Options: topic `agent`. | -| `filters` | `[]` | Test filters `{ name, filter(tests, context) }`, unique names, applied in order with `--changed-since `. Use `filters: [decisionFilter({ model: gateway.decisionModel('typesafe-ai/jev') })]`, with `decisionFilter` from `@e2e-dev/decision` and `gateway` from `ai` (install `@e2e-dev/decision ai`), to run only the tests a pull request can affect. `filter` gets candidates `{ id, file, titlePath, tags, setupFile? }` and a context `{ projectRoot, changes: { base, root, files }, configFile, signal, log, redact }` with repository-relative `files`, and returns `{ exclude: { [id]: reason }, relevance?: { [id]: 0 to 1 }, note? }`; every test it does not name runs, and `relevance` (how likely each test is to fail) makes each target start the likeliest files first. Read files, the environment, or the network inside `filter`, never at config load: workers load the config too. When filters run: topic `running`. | +| `filters` | `[]` | Test filters `{ name, filter(tests, context) }`, unique names, applied in order with `--changed-since `. Use `filters: [decisionFilter({ model: gateway.decisionModel('typesafe-ai/jev') })]`, with `decisionFilter` from `@e2e-dev/decision` and `gateway` from `ai` (install `@e2e-dev/decision ai`), to run only the tests a pull request can affect. `filter` gets candidates `{ id, file, titlePath, tags, setupFile?, peerSetupFiles? }` and a context `{ projectRoot, changes: { base, root, files }, configFile, signal, log, redact }` with repository-relative `files`, and returns `{ exclude: { [id]: reason }, relevance?: { [id]: 0 to 1 }, note? }`; every test it does not name runs, and `relevance` (how likely each test is to fail) makes each target start the likeliest files first. Read files, the environment, or the network inside `filter`, never at config load: workers load the config too. When filters run: topic `running`. | | `credentials` | `{}` | Named `{ username, password }`; `password` is a 6+ code point string or a function returning it. | | `secrets` | `{}` | Named values the model never sees (API keys, tokens), same value rule. A separate namespace: a credential's password is `credentials.user(name).password` (named `.password`), never `secrets.get()`, so a name may be both. | | `output` | `'.e2e'` | Results directory; `--output ` for one run. Inside the project root, not the root, not a tests glob's directory, never the cache dir (`cache.dir` stays `.e2e/cache`). | diff --git a/skills/e2e/references/writing-tests.md b/skills/e2e/references/writing-tests.md index 2d4e4f5a97..9c7a516450 100644 --- a/skills/e2e/references/writing-tests.md +++ b/skills/e2e/references/writing-tests.md @@ -9,6 +9,7 @@ - Locators - expect - Sign-in sessions +- Two users in one test - Start near the screen under test - The browser fixture (browser only) - Habits @@ -149,12 +150,13 @@ or a blocked agent verdict still fails the test. | `platforms` | unset | Only targets with these platforms, e.g. `['ios']`. | | `requires` | `[]` | Engine capabilities, e.g. `['browser']`; missing ones skip the test at selection rather than failing it with `UNSUPPORTED_CAPABILITY`. | | `session` | unset | Restore state saved by a setup test. | +| `peers` | unset | More users by name, each on an app of its own: `{ ava: { target?, session?, agent?, agentContext? } }`. See Two users in one test. | | `agentContext` | unset | Extra context for `agent.*` calls in this test or group. | | `agent` | the run's agent | A configured name (`agents.`) or a list run once per agent; `--agent` narrows the list, a setup test takes one name. Innermost wins; `agent.act(..., { agent })` names another for one call. | | `trace`, `video` | the target's | `'off'`, `'on'`, `'retain-on-failure'`, `'on-first-retry'`, `'on-all-retries'`: whether the test keeps a trace page, which attempts record video. Innermost wins over `--trace` / `--video`, the target, and the config; video where the engine cannot record is `UNSUPPORTED_ARTIFACT` for the run. | | `serial` | `false` | Groups only. Members share app state, run in order on one worker, retry as a whole, and take the group's `trace` and `video`. | -Serial members cannot set `retries`, `trace`, `video`, `session`, +Serial members cannot set `retries`, `trace`, `video`, `session`, `peers`, `platforms`, `requires`, `skip`, `fail`, or `only`, nor can a nested `describe` set `trace` or `video`; nesting serial groups is a `COLLECTION_ERROR`. @@ -174,7 +176,9 @@ configured model, else `MODEL_UNAVAILABLE` (topic `agent`). `platform` (`string`): always, hooks included; `web`, `ios`, `android`, or an engine's label. `browser` (`Browser`): browser targets, import `test` from `@e2e-dev/web`. `device` (`Device`): device targets, import `test` from `@e2e-dev/mobile`. -`session` (`SetupSession`): only in `test.setup`. +`session` (`SetupSession`): only in `test.setup`. `peers` (by name): each +declared peer's own `app`, `screen`, `agent`, `platform`, and its engine's +fixtures; empty without the option. ### app @@ -464,6 +468,38 @@ credentials: { `` (and so does the test id, for a value in a title), so the agent cannot type it. Pass the handle. +## Two users in one test + +`peers` adds users to one test, each on an app of its own, opened before +`beforeEach` and closed with the test: + +```ts +test('Ava sees the payment', { session: 'member', peers: { ava: { session: 'ava' } } }, async ({ app, screen, peers }) => { + await app.open('/pay'); + await screen.getByRole('button', 'Pay Ava $3').tap(); + await peers.ava.app.open('/activity'); + await expect(peers.ava.screen.getByText('$3.00 from Member')).toBeVisible(); +}); +``` + +- `target` defaults to the test's own; the run must select a peer's target + (`--target`), and the test still runs once per selected target, so pin the + test's side with `platforms`. +- A peer's `session` is saved by a setup test on the peer's target. A device + restores none: a device peer signs in during the test. +- A device peer takes a device of its own; with too few, the run starts + fewer workers, and with none to spare for a peer it stops before any test. +- Each peer's steps carry `user` in the report, its files go in + `peers//`, its replay recordings are its own in each target and + agent the test runs on, its screenshot baselines in each target, and its + agent sees only its own earlier steps. One secret ledger covers every user. +- A peer's engine fixtures (`browser`, `device`) are typed `unknown`: cast + one to use it, as in `peers.ava.device as Device`. +- Not in a serial group, a setup test, `open_session`, on an engine-server + target, a hosted browser or device provider, or a CDP attach. The peer's + engine must be created in the config or a file it imports, in a run from a + config file. + ## Start near the screen under test A test pays for every step before the screen it checks, on every run and on