> ## Documentation Index
> Fetch the complete documentation index at: https://e2e.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# e2e/engine

> API reference for e2e/engine, the contract for building an engine, with defineEngine, observations, actions, lifecycle hooks, and fixtures.

`e2e/engine` is the contract an engine implements to drive a user interface,
such as a browser or simulator. [`defineEngine`](#defineengine) turns an
implementation into a handle for `targets` in the config. The runner drives it
over the
[engine protocol](https://e2e.com/docs/reference/engine-protocol), in its own process; see
[Engines](https://e2e.com/docs/engines). Use `test.extend` fixtures for resources outside the UI,
such as APIs or databases. `@e2e-dev/core/engine` is the same module: a
published engine imports it from there and peers on `@e2e-dev/core`, so it runs
under the runner and under [@e2e-dev/core](https://e2e.com/docs/core) alike.

This sketch assumes a `connect` adapter for the platform:

```ts title="src/index.ts"

export interface KioskEngine extends EngineHandle {}

export function kiosk(options: { host: string }): KioskEngine {
  const client = connect(options.host);
  return defineEngine({
    name: 'kiosk',
    version: '1.0.0',
    spiVersion: 1,
    platform: 'kiosk',
    async observe() {
      const screen = await client.snapshot();
      return {
        root: { ref: { id: 'root', revision: '' }, role: 'window', children: screen.nodes },
        viewport: screen.viewport,
      };
    },
    async locate(expression) {
      const screen = await client.snapshot();
      return resolveExpression(expression, screen.nodes);
    },
    actions: ['tap'],
    async perform(ref) {
      await client.tap(ref.id);
    },
  });
}
```

```ts title="e2e.config.ts"

export default {
  targets: [{ name: 'kiosk', engine: kiosk({ host: 'kiosk.local' }) }],
} satisfies E2EConfig;
```

## Reference

### defineEngine

Validates an engine spec, freezes it, computes its
[capabilities](#capabilities), and returns a branded handle.
`isEngineHandle` tells such a handle from any other value.

```ts

export function defineEngine<
  Fixtures extends object = {},
  Platform extends string = string,
  Isolation extends EngineIsolation = EngineIsolation,
>(spec: Engine & { readonly platform?: Platform; readonly isolation?: Isolation }): EngineHandle<Fixtures, Platform, Isolation>;
export function isEngineHandle(value: unknown): value is EngineHandle;

export interface EngineHandle<
  Fixtures extends object = {},
  Platform extends string = string,
  Isolation extends EngineIsolation = EngineIsolation,
> extends Engine {
  readonly capabilities: ReadonlySet<EngineCapability>;
  readonly platform?: Platform;
  readonly isolation?: Isolation;
}
```

Every function on the handle is bound to the spec it came from, so a class
instance is as valid a body as an object literal.

`Fixtures` types what the engine's [`fixtures`](#contributed-fixtures) contribute, such as
`{ browser: Browser }`. The compiler requires a factory in `fixtures` for each
fixture it names, returning that fixture; `screen`, `app`, and `platform` need
none, since every session holds them. Nothing checks it at runtime. With it, `launch` from [`@e2e-dev/core`](https://e2e.com/docs/core) types a session's fixtures
without a hand-written argument: return `defineEngine<{ device: Device }>(...)`
from the factory.

`Platform` and `Isolation` are literal types for the spec's `platform` and
`isolation`, such as `'ios'` and `'worker'`. They're needed to tell targets
apart when [a config's fixtures are typed](https://e2e.com/docs/reference/test#engine-fixtures-across-targets).
If you pass `Fixtures`, pass all three to keep the literals:
`defineEngine<{ device: Device }, 'ios', 'worker'>(...)`. Then set the same
`platform` in the spec, and `isolation: 'worker'` for `'worker'`.

Return your own interface from the factory, as `KioskEngine` does above. A
config that infers its type then names your package. A bare `EngineHandle` can
fail with TS2883 in a pnpm project that sets `declaration: true`.

To keep the literal types on your interface, give it `Platform` and
`Isolation` parameters with defaults of `string` and `EngineIsolation`, like
`WebEngine` and `MobileEngine`. Then put the literals in the factory's
return type: `web(): WebEngine<'web', 'attempt'>`.

`defineEngine` throws `INVALID_CONFIG` when the spec breaks one of these
rules:

| Member | Rejected when |
| --- | --- |
| the spec | It is not an object. |
| `name` | Missing or empty. |
| `version` | Missing or empty. |
| `spiVersion` | Anything but `1`. |
| `platform` | Empty. |
| `workers` | Not a positive safe integer. |
| `observe`, `readStyle`, `viewportIntersection`, `locate`, `perform`, `performAt`, `prepare`, `finish`, `doctor`, `init`, `startAttempt`, `settleAttempt`, `endAttempt`, `dispose`, `validateApp` | Not a function. |
| any other top-level key | On an object literal, `app` included: declare the app on the target and check it in `validateApp`. A class instance's own fields are not checked. |
| `readStyle`, `perform`, `locate`, `performAt`, `keyboard` | Declared without `observe`. |
| `viewportIntersection` | Declared without `locate`. |
| `perform`, `actions` | One without the other. An `actions` list that is empty, repeats a kind, or names one outside `KNOWN_LOCATOR_ACTION_KINDS`. |
| `performAt`, `pointerActions` | One without the other. A `pointerActions` list that is empty, repeats a kind, or names one outside `POINTER_ACTION_KINDS`. |
| `tapModifiers` | Not a boolean, or `true` without `perform`. |
| `selectsDevice` | Not a boolean, or `true` without `prepare`. |
| `grantsAllPermissions` | Not a boolean. |
| `launchArgumentValues` | Not a boolean. |
| `fileApps` | Not a boolean. |
| `isolation` | Anything but `'attempt'` or `'worker'`. |
| `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`, `request`, `services`, or `session`. |

<Note>
`artifacts.startTrace` and `artifacts.stopTrace` are not part of the contract.
An engine that declares them passes validation; the runner never calls them.
</Note>

### Engine

The body of one target. Every member but `name`, `version`, and
`spiVersion` is optional; the members an engine implements decide its
[capabilities](#capabilities).

| Member | Type |
| --- | --- |
| `name` | `string` |
| `version` | `string` |
| `spiVersion` | `1` |
| `platform` | `string` |
| `workers` | `number` |
| [`observe`](#observation) | method |
| [`readStyle`](#rendered-node-properties) | method |
| [`viewportIntersection`](#viewport-intersection) | method |
| [`perform`, `actions`](#actions) | method, kinds |
| [`locate`](#capabilities) | method |
| [`performAt`, `pointerActions`](#pointer-actions) | method, kinds |
| [`tapModifiers`](#capabilities) | `boolean` |
| [`selectsDevice`](#capabilities) | `boolean` |
| [`grantsAllPermissions`](#capabilities) | `boolean` |
| [`launchArgumentValues`](#engineappinfo) | `boolean` |
| [`fileApps`](#capabilities) | `boolean` |
| [`keyboard`](#keyboard) | `EngineKeyboard` |
| [`fixtures`](#contributed-fixtures) | factories |
| [`isolation`](#fixture-isolation) | `'attempt' \| 'worker'` |
| [`state`](#state) | `EngineStateCapability` |
| [`artifacts`](#artifacts) | `EngineArtifacts` |
| [`validateApp`](#app) | method |
| [`secrets`](#startattempt) | `Secret[]` |
| [`session`](#session) | `EngineSession` |
| [`prepare`, `finish`, `doctor`, `init`, `startAttempt`, `settleAttempt`, `endAttempt`, `dispose`](#lifecycle) | hooks |

```ts
export interface Engine {
  readonly name: string;
  readonly version: string;
  readonly spiVersion: EngineSpiVersion;
  readonly platform?: string;
  readonly workers?: number;
  observe?(context: OperationContext, options?: EngineObserveOptions): Promise<EngineSnapshot>;
  readStyle?(ref: NodeRef, properties: readonly ComputedStyleProperty[], context: OperationContext): Promise<ComputedStyleValues>;
  viewportIntersection?(ref: NodeRef, context: OperationContext): Promise<ViewportIntersection>;
  perform?(ref: NodeRef, action: LocatorAction, context: OperationContext): Promise<void>;
  readonly actions?: readonly LocatorActionKind[];
  locate?(
    expression: LocatorExpression,
    context: OperationContext,
  ): Promise<readonly SemanticNode[]>;
  performAt?(point: ViewportPoint, action: PointerAction, context: OperationContext): Promise<void>;
  readonly pointerActions?: readonly PointerActionKind[];
  readonly tapModifiers?: boolean;
  readonly selectsDevice?: boolean;
  readonly grantsAllPermissions?: boolean;
  readonly launchArgumentValues?: boolean;
  readonly fileApps?: boolean;
  readonly keyboard?: EngineKeyboard;
  readonly fixtures?: Readonly<Record<string, EngineFixtureFactory>>;
  readonly isolation?: EngineIsolation;
  readonly state?: EngineStateCapability;
  readonly artifacts?: EngineArtifacts;
  validateApp?(app: EngineAppDeclaration, info: EngineAppCheckInfo): void;
  readonly secrets?: readonly Secret[];
  readonly session?: EngineSession;
  prepare?(info: EnginePrepareInfo): Promise<void | EnginePrepareResult>;
  finish?(info: EngineFinishInfo): Promise<void>;
  doctor?(info: EngineDoctorInfo): Promise<readonly EngineDoctorCheck[]>;
  init?(info: EngineInitInfo): Promise<void>;
  startAttempt?(context: EngineAttemptContext): Promise<void>;
  settleAttempt?(context: EngineCleanupContext): Promise<void>;
  endAttempt?(context: EngineCleanupContext): Promise<void>;
  dispose?(context: EngineDisposeContext): Promise<void>;
}
```

The members with no section of their own:

| Member | Description |
| --- | --- |
| `name` | Shown in diagnostics. |
| `version` | Recorded in reports and sessions. A saved session never restores across engine versions; a cached trace replays across them and re-finds its nodes. |
| `spiVersion` | The contract version. Additive optional members never bump it; changed required semantics do. |
| `platform` | The platform label: `web`, `ios`, `android`, or one of the engine's own. Tests filter on it through `platforms`, and tool packs are scoped by it; the harness attaches no meaning to any value. A target inherits it, and a target that names a platform of its own must agree with it. |
| `workers` | The most workers the target gets, such as the number of devices in a pool. The cap applies even when `config.workers` is higher. Omit it when the engine has no concurrency limit. |
| `locate` | Resolves one expression to the nodes it matches right now, once. The harness owns polling, strictness, and staleness. |

#### `OperationContext`

What every engine call carries: its budget, the run and attempt ids, and who
is acting.

```ts
export interface OperationContext {
  readonly signal: AbortSignal;
  readonly timeoutMs: number;
  readonly runId: string;
  readonly attemptId: string;
  readonly origin: 'test' | 'agent';
}
```

| Field | Description |
| --- | --- |
| `signal` | Aborts when the attempt, or the hook running the call, ends. It does not abort at `timeoutMs`: bound each call by that budget yourself. |
| `timeoutMs` | The operation budget left when the call starts. A waiting call's last locate or read can get more than its deadline leaves: as long as the slowest one it has seen. |
| `origin` | `'test'` for a test's own deterministic step, `'agent'` for the agent acting on a screen it observed. A deterministic step verifies its outcome with `expect`, so an engine may act as soon as the target holds still. An agent reads the screen right after acting, so an engine may wait for the transition to end first. |

### Capabilities

The members an engine implements set its capabilities. A `screen`,
`Locator`, or `app` call that needs a missing one fails with
`UNSUPPORTED_CAPABILITY`. [Test APIs](#test-apis) lists what needs which
member. Two gaps end differently:

- A selected test that uses a `test.setup` session, on an engine without
  `state`, is a collection error before the setup runs.
- A `video` mode on an engine without video recording prints a notice and
  records no video.

| Member | Capability | Requires | Unlocks |
| --- | --- | --- | --- |
| `observe` | `observation` | - | The judgment tier, prompt snapshots, trace replay, the viewport swipe's root. |
| `readStyle` | `computed-style` | `observe` | Allow-listed rendered properties for read-only project tools. |
| `perform` + `actions` | `actions` | `observe` | Node actions of the declared kinds, with platform actionability checks. |
| `locate` | `location` | `observe` | `screen`, `Locator`, `expect(locator)`. |
| `viewportIntersection` | `viewport-intersection` | `locate` | `expect(locator).toBeInViewport()`. |
| `tapModifiers: true` | - | `perform` | `modifiers` on `tap`, `doubleTap`, `multiTap`, and `secondaryTap`. |
| `selectsDevice: true` | - | `prepare` | `e2e run --device`, the device `prepare` binds. Without it, the runner refuses the flag for the target before anything is prepared. |
| `grantsAllPermissions: true` | - | - | `app.permissions: 'all'`, which the engine receives as `EngineAppInfo.allPermissions`. Without it, config load refuses `'all'`. |
| `launchArgumentValues: true` | - | - | The object form of `app.launchArguments`, in `EngineAppInfo.launchArgumentValues`. |
| `fileApps: true` | - | - | A target whose `app.url` is a `file:` URL, read from the disk of the machine the harness runs on. `validateApp` is told with `fileApp: true`. Without it, config load refuses a file `app.url`. |
| `performAt` + `pointerActions` | `pointer` | `observe` | One pointer action at a viewport point, with no node behind it. |
| `keyboard.{type,press,dismiss?}` | `keyboard` | `observe` | Input to whatever holds focus. |
| `fixtures.<name>` | `<name>` | - | A contributed fixture. |
| `state` | `state` | - | `test.setup` sessions and the `session:` option. |
| `artifacts` | `artifacts` | - | Screenshots and videos. |
| `validateApp` | - | - | A config-load check of the target's `app`. |
| `session` | - | - | The `app` steering methods and the agent's `navigate`, `back`, `resize_viewport`, `switch_tab`, and `close_tab` verbs. |

#### Rendered node properties

`readStyle(ref, properties, context)` returns computed CSS strings for the requested
properties without changing app state. `ref` comes from the newest
observation. Return a string for
every requested property. Throw retryable `NODE_STALE` if the node no longer
binds. The harness redacts values before returning them to tools.

```ts
export type ComputedStyleProperty =
  | 'color' | 'background-color' | 'font-size' | 'font-weight' | 'font-style'
  | 'text-align' | 'text-decoration-line' | 'display' | 'visibility' | 'opacity';

export type ComputedStyleValues = Readonly<Partial<Record<ComputedStyleProperty, string>>>;
```

`COMPUTED_STYLE_PROPERTIES` exports the allow-list as a frozen array.
`validateComputedStyleProperties(properties)` returns a deduplicated copy and
throws `INVALID_ARGUMENT` for an empty list or a property outside the
allow-list. Call it before page access.
See [Project tools](https://e2e.com/docs/tools#read-a-nodes-computed-style) for `ToolContext.read`.

#### Viewport intersection

`viewportIntersection(ref, context)` measures how much of a located node is
inside the viewport for [`toBeInViewport`](https://e2e.com/docs/reference/expect#tobeinviewport),
without scrolling or changing app state. Clip the box by the viewport and every
clipping ancestor, such as a scroll container, `overflow: hidden`, or a frame.

```ts
export interface ViewportIntersection {
  readonly intersects: boolean;
  readonly ratio?: number;
}
```

`intersects` is whether a positive area of the box is inside: `false` for a
node with no box or an empty one. `ratio` is the inside area's share of the
whole box, from 0 to 1. Leave it out where the platform reports only the
visible part of a box.

Without `ratio`, `toBeInViewport` with `ratio > 0` fails with
`UNSUPPORTED_CAPABILITY`. Throw
retryable `NODE_STALE` if the node no longer binds, and
`UNSUPPORTED_CAPABILITY` if the platform cannot report the node's bounds or
screen position. A `ratio` is above `0` exactly when `intersects` is true. The
harness fails the step with `ENGINE_FAILURE` on an answer outside this shape.

#### Agent verbs

The agent offers the model only the verbs the engine's declarations unlock.
An undeclared verb is absent from the toolset.

| Verb | Needs |
| --- | --- |
| `tap` | the `tap` kind in `actions` |
| `double_tap` | `doubleTap` |
| `long_press` | `longPress` |
| `right_click` | `secondaryTap` |
| `hover` | `hover` |
| `type` | `fill`; without a target, `keyboard` |
| `type_secret` | `fill` |
| `press` | `press`; without a target, `keyboard` |
| `select` | `selectOption` |
| `check` | both `check` and `uncheck`, since it sets a state rather than flipping one |
| `scroll`, `scroll_to({ text })` | `swipe` |
| `scroll_to({ target })` | `scrollIntoView` |
| `drag` | `dragTo` |
| `upload` | `setInputFiles` |
| `navigate` | `session.open` |
| `back` | `session.back` |
| `resize_viewport` | `session.resize` |
| `switch_tab` | `session.switchTab` |
| `close_tab` | `session.closeTab` |
| `tap_at`, `hover_at` | the `tap` or `hover` kind, in `actions` or in `pointerActions` |
| `drag_at` | the `dragTo` kind, in `actions` or in `pointerActions` |
| `type_at` | `fill` or `keyboard` |
| `press_at` | `press` or `keyboard` |
| `select_at` | `selectOption` |
| `dismiss_keyboard` | `keyboard.dismiss` |

- `clear` and `focus` unlock no verb.
- `tap_at` and `hover_at` go through `performAt` (the `tap` and `hover`
  pointer kinds). Without that kind they go through `perform` when the point
  lands on a node the tree lists.
- `drag_at` goes through `performAt` with the `dragTo` pointer kind and the
  second point as its `target`. Without that kind it goes through `perform`
  when its two points land on two different listed nodes.
- `type_at`, `press_at`, and `select_at` go through `perform` when the point
  lands on a node the tree lists. Elsewhere `type_at` and `press_at` fall
  back to `keyboard`.

#### Test APIs

The test-facing APIs each engine member backs. A `screen` or `Locator`
method for an undeclared kind, or a call with `modifiers` and no
`tapModifiers`, fails with `UNSUPPORTED_CAPABILITY` before it reaches the
engine.

| API | Needs |
| --- | --- |
| `screen`, `Locator`, `expect(locator)` | `locate` |
| `screen` and `Locator` actions | `perform`, each only for a kind listed in `actions` |
| `screen.swipe()` | `perform` with `swipe` on the observation root |
| `modifiers` on a tap (`row.click({ modifiers: ['Shift'] })`) | `tapModifiers: true`; the keys are held for the click |
| `screen.tapAt`, `tap({ position })` | `performAt` with the `tap` pointer kind |
| `screen.doubleTapAt` | `performAt` with the `doubleTap` pointer kind |
| `screen.swipe({ from, to })` | `performAt` with the `swipeTo` pointer kind |
| `locator.pressSequentially` | the `focus` action and `keyboard`; the harness composes `focus` then `keyboard.type` |
| `test.setup` sessions, the `session:` option | `state` |
| `app.screenshot()`, assertion evidence, the failure screenshot | `artifacts` |
| `locator.screenshot()` | `artifacts`, with `observe` and `locate`; the `scrollIntoView` action when declared |
| every [`video` mode](https://e2e.com/docs/reference/config#recording) but `off`, from the config, a target, a test, or `--video` | `artifacts` |
| `app.open()` | `session.open`; on a target with no app URL, `session.restart`, or `session.openLink` for a path on a target with `app.linkBase` |
| `app.back()` | `session.back` |
| `app.restart()` | `session.restart` |
| `app.clearState()` | `session.reset` |

#### `engine.capabilities`

The computed `ReadonlySet` of capability names.

```ts
const engine = kiosk({ host: 'kiosk.local' });
engine.capabilities.has('location'); // true: the engine implements locate
```

```ts
export type EngineCapability =
  | 'observation'
  | 'computed-style'
  | 'viewport-intersection'
  | 'actions'
  | 'location'
  | 'pointer'
  | 'keyboard'
  | 'state'
  | 'artifacts'
  | (string & {});
```

#### Keyboard

```ts
export interface EngineKeyboard {
  type(text: string, options: { readonly replace: boolean }, context: OperationContext): Promise<void>;
  press(key: string, context: OperationContext): Promise<void>;
  dismiss?(context: OperationContext): Promise<void>;
}
```

Input to whatever holds focus, with no node behind it. Focus is the app's:
the harness tapped first, or the model said the field already has it.

| Member | Description |
| --- | --- |
| `type` | Types `text` into the focused field as a person typing would, through the platform's keyboard path. Where the platform has key events, the app must receive them: setting the value without keystrokes is not compliant, since `locator.pressSequentially` and the agent's `type` rely on the app reacting as it does to a user. With `replace`, clear the field first. |
| `press` | Sends one key of the [key grammar](#keys) to whatever holds focus. The harness has already validated the key's shape. |
| `dismiss` | Hides an on-screen keyboard. Leave it undefined on a platform without one. |

| Throws | When |
| --- | --- |
| `NOT_ACTIONABLE` | `type` when nothing that accepts text has focus. |
| `UNSUPPORTED_CAPABILITY` | `press` with a key the surface cannot deliver. |

### Lifecycle

The hooks the runner calls around workers and attempts. Every hook is
optional. Each hook's entry below states its contract.

`init` and `startAttempt` run within `launchTimeout`. `finish`,
`settleAttempt`, `endAttempt`, and `dispose` run within `cleanupTimeout`.
`prepare` has no timeout. Both budgets come from the
[config](https://e2e.com/docs/reference/config).

| Hook | Runs |
| --- | --- |
| [`prepare(info)`](#prepare) | Once per target, before any worker |
| [`finish(info)`](#finish) | After the target's last worker is gone |
| [`doctor(info)`](#doctor) | Once per target in `e2e doctor`, never in a run |
| [`init(info)`](#init) | Once per worker, before its first step |
| [`startAttempt(context)`](#startattempt) | Before each attempt |
| [`settleAttempt(context)`](#settleattempt) | After the body and after teardown |
| [`endAttempt(context)`](#endattempt) | After each attempt |
| [`dispose(context)`](#dispose) | Worker shutdown |

#### `prepare`

Runs once per target in the runner process, after collection and before
workers, app commands, and the run's clock start.

```ts
async prepare(info) {
  if (info.slots === 0) return; // nothing runs on this target
  info.log('booting devices');
  const devices = await pool.boot(info.slots, { signal: info.signal });
  return { workers: devices.length, env: { KIOSK_DEVICES: devices.join(',') } };
},
```

- Download dependencies or boot devices here, and report progress through
  `info.log`.
- 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`.

A failure ends the run before any test:

| Thrown | Becomes |
| --- | --- |
| A runner error class, such as a `ConfigurationError` for an option the engine cannot honour | The same code. |
| An `EngineError` with code `CANCELLED` | A cancellation. |
| Any other `EngineError`, or a plain `Error` | Infrastructure `ENGINE_FAILURE`. |

```ts
export interface EnginePrepareResult {
  readonly workers?: number;
  readonly env?: Readonly<Record<string, string>>;
}

export interface EngineHostIdentity {
  readonly hostId?: string | undefined;
}

export interface EnginePrepareInfo extends EngineHostIdentity {
  readonly runId: string;
  readonly targetName: string;
  readonly projectRoot: string;
  readonly app: EngineAppInfo;
  readonly slots: number;
  readonly env: Readonly<Record<string, string | undefined>>;
  readonly signal: AbortSignal;
  readonly headed: boolean;
  readonly device?: string;
  readonly log: (line: string) => void;
}
```

| Field | Description |
| --- | --- |
| `result.workers` | Lowers the target's worker cap for this run, from `1` to `info.slots`. |
| `result.env` | Variables every worker of this target is spawned with, on top of the run's environment: how `prepare` hands what it provisioned to each worker's `init`. The run's own variables win on a clash. |
| `info.hostId` | Set when a `launch()` host holds the target: a token no other host has. Hosts name their targets alike, so an engine that names what it holds after the target, such as a device session, adds this to keep hosts apart. `init` and `finish` receive it too. |
| `info.projectRoot` | The directory relative paths in the config resolve against, as in [`init`](#init). |
| `info.app` | The app the target declares, as `init` receives it: what a device installs or warms up here. |
| `info.slots` | The worker slots the run will start for this target, `0` to `slots - 1`: the smallest of the run's worker cap, the engine's declared `workers`, and the work units selected for the target. `0` when nothing runs on it while another target has work. Provision for exactly these slots; `init` then finds them ready. |
| `info.env` | 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 resolve and spawn against this, not `process.env`. |
| `info.signal` | Aborts on interrupt only. |
| `info.headed` | Whether the run asked for a visible surface (`--headed`). |
| `info.device` | The device `e2e run --device` names for this target, by name or id: the one to bind instead of the configured one. Only an engine that declares `selectsDevice` receives it. |
| `info.log` | Reports one line of progress. The runner streams it as a `notice` run event to the reporter and every host sink. |

#### `finish`

Runs once per run and target in the runner process, after every worker of
the target is gone. Release what `prepare` acquired for the run, such as a
leased cloud device. It runs on every exit path, whenever `prepare` was
called, and an interrupt never cancels it. A failure is a cleanup-phase run
error.

```ts
async finish(info) {
  await pool.release({ signal: info.signal });
},
```

The `finish` hooks of all prepared targets share one `cleanupTimeout`.

```ts
export interface EngineFinishInfo extends EngineCleanupContext, EngineHostIdentity {
  readonly runId: string;
  readonly targetName: string;
  readonly env: Readonly<Record<string, string | undefined>>;
  readonly log: (line: string) => void;
}
```

`info.env` is the run's environment, the same `prepare` saw. `info.log`
reports one line of progress, streamed as `prepare`'s is.

#### `doctor`

Runs once per target when [`e2e doctor`](https://e2e.com/docs/reference/cli#e2e-doctor) checks
the project, never during a run. Report what a run on this machine needs and
whether it's there. Each finding becomes a check under the target. Without the
hook, the target gets one `engine` check with status `skip`.

```ts
async doctor(info) {
  const sdk = await findToolchain(info.env);
  if (sdk === undefined) return [{ id: 'toolchain', status: 'fail', message: 'install the toolchain' }];
  return [{ id: 'toolchain', status: 'pass', message: `toolchain ${sdk.version}` }];
},
```

Keep it read-only and quick: never install, launch, lease, or start anything
a check could look up instead, and never call `prepare`. A check that cannot
tell reports nothing rather than guess.

`e2e doctor` gives the hook 30 seconds, starting a protocol engine's
server included. A throw, a timeout, a finding that isn't an
`EngineDoctorCheck`, or one with an id `e2e doctor` uses itself (`node`,
`config`, `engine`, `model`) becomes an `engine` check with status `fail`.
`info.signal` aborts at the 30 seconds, or when `e2e doctor` is interrupted.
Return within 5 seconds of it; the connection closes then.

```ts
export interface EngineDoctorInfo {
  readonly targetName: string;
  readonly projectRoot: string;
  readonly app: EngineAppInfo;
  readonly env: Readonly<Record<string, string | undefined>>;
  readonly headed: boolean;
  readonly signal: AbortSignal;
  readonly log: (line: string) => void;
}

export interface EngineDoctorCheck {
  readonly id: string;
  readonly status: 'pass' | 'warn' | 'fail' | 'skip';
  readonly message?: string;
}
```

| Field | Description |
| --- | --- |
| `info.projectRoot` | The directory relative paths in the config resolve against, as in [`init`](#init). |
| `info.app` | The app the target declares, as `prepare` receives it. |
| `info.env` | The environment a run would start with. |
| `info.headed` | Whether the run would show the surface (`--headed`). |
| `info.log` | Reports one line of progress; `e2e doctor` prints it to stderr. |
| `id` | What was checked, in kebab case: `browser`, `toolchain`. |
| `status` | `pass`; `warn` for something a run handles on its own, slower, such as a first-run download; `fail` for something that stops a run; `skip` for a check that does not apply to this target. |
| `message` | One line: what was found and, unless it passed, what to do. |

#### `init`

Runs once per worker, before the first step. Boot devices here, not in a step
budget.

```ts
async init(info) {
  const device = info.env.KIOSK_DEVICES?.split(',')[info.workerSlot];
  info.log(`slot ${info.workerSlot}: ${device}`);
},
```

`init` never learns the app URL; URLs arrive through `session.open` only. A
failure is an infrastructure error. The same handle can be booted again after
`dispose`, so `init` must work on a disposed engine as it does on a fresh one.

```ts
export interface EngineInitInfo extends EngineHostIdentity {
  readonly runId: string;
  readonly targetName: string;
  readonly projectRoot: string;
  readonly app: EngineAppInfo;
  readonly env: Readonly<Record<string, string | undefined>>;
  readonly headed: boolean;
  readonly workerSlot: number;
  readonly signal: AbortSignal;
  readonly log: (line: string) => void;
}
```

| Field | Description |
| --- | --- |
| `projectRoot` | The directory relative paths in the config resolve against: the config file's directory, or the run's `cwd` for a programmatic config. Resolve an engine option naming a file, such as a build to install, here and never against `process.cwd()`, which an in-process run does not change. |
| `app` | The app the target declares; see [`EngineAppInfo`](#engineappinfo). |
| `env` | This worker's environment: the run's, plus what this target's `prepare` returned in its result's `env`. Read what `prepare` provisioned from here, never from `process.env`: an in-process worker shares its process with the runner and every other target. |
| `headed` | Whether the run asked for a visible surface (`--headed`). |
| `workerSlot` | 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. |
| `signal` | Aborts on interrupt and when `init` exceeds the launch timeout; `init` must stop promptly. |
| `log` | Reports one line of progress. The runner streams it as a `notice` run event, prefixed with the target and worker slot, to the reporter and every host sink. Use it for a fact that only exists once the worker is up, such as the URL a hosted browser can be watched at. A line logged after `init` is delivered while the worker lives and dropped once it has exited. The line is shown as is, so keep tokens and other secrets out of it. |

#### `startAttempt`

Runs before each attempt, to set up the per-test isolation that
[`endAttempt`](#endattempt) tears down.

```ts
async startAttempt(context) {
  const password = await context.resolveSecret(options.password);
  await client.openContext({ password, signal: context.signal });
  context.environment({ device: 'Kiosk 2', os: 'KioskOS 4.1' });
},
```

On failure or timeout, `context.signal` aborts and `endAttempt` runs.

List the `secrets.get()` handles the engine's options hold, such as a
basic-auth password, in the spec's `secrets`. Config load checks that each
names a configured secret and fails with `INVALID_CONFIG` otherwise. Only
these resolve through `context.resolveSecret`.

<Warning>
A value from `resolveSecret` is protected as text only. Reports, logs, and
observations redact it and the attempt's text downloads are rewritten, but
a page that shows it outside a secure field is not masked in screenshots.
</Warning>

```ts
export interface EngineAttemptContext {
  readonly attemptId: string;
  readonly artifactsDir: string;
  readonly resolveSecret: (secret: Secret, options?: ResolveSecretOptions) => Promise<string>;
  readonly signal: AbortSignal;
  readonly appLog: (entry: AppLogEntry) => void;
  readonly navigation: (line: string) => void;
  readonly screen?: (snapshot: EngineSnapshot) => void;
  readonly environment: (facts: Readonly<Record<string, string>>) => void;
}

export interface AppLogEntry {
  readonly source: 'console' | 'error' | 'network' | 'system';
  readonly level: 'error' | 'warning' | 'info';
  readonly text: string;
}

export interface ResolveSecretOptions {
  readonly derived?: (plaintext: string) => readonly string[] | Promise<readonly string[]>;
}
```

| Field | Description |
| --- | --- |
| `artifactsDir` | The absolute directory every artifact of this attempt is written under. |
| `resolveSecret` | Resolves the plaintext of a secret the engine declared in `secrets`, for an option the engine hands the app itself. A provider runs again on every call. The value, and every value `options.derived` computes from it, join the attempt's redaction before the call resolves. |
| `options.derived` | Returns the forms of the value the app sees instead of the value itself, redacted under the secret's name: the base64 `user:password` of an `Authorization: Basic` header, which a page echoing its request headers would otherwise show. |
| `signal` | Aborts with the attempt, and the moment `startAttempt` fails or exceeds the launch timeout: a hook still running then must stop. |
| `appLog` | Reports something the app did on its own while the attempt ran: a console line, an uncaught exception, a failed request. The harness redacts the text and shows it on the trace page with the step that was running. Call it from the moment `startAttempt` begins until `endAttempt`. Entries past a per-attempt cap are dropped. |
| `entry.source` | The app's `console`, an `error` nothing caught, the `network`, or the `system` the app runs on, such as a crash or an OS log. |
| `entry.text` | One line, such as `GET /api/todos 500`; the harness clips it. |
| `navigation` | Reports where the app went on its own, as one line such as `navigated to /login`: a navigation the engine did not start, a tab, a frame. Shown under the step that was running. |
| `screen` | Hands the harness a screen for the trace: the capture a `locate` matched against, or one read right after an action. That read is on the action's path, so bound it and skip it where it is expensive; it never fails the action. Refs in it are not valid for `perform`. Absent when the attempt keeps no trace. |
| `environment` | Reports what the attempt runs on, such as `{ device: 'iPhone 16', os: 'iOS 26.0' }`, for the trace page. Later calls add to and overwrite earlier facts. |

| Throws | When |
| --- | --- |
| `SECRET_UNAVAILABLE` | `resolveSecret` gets a secret the engine did not declare. |

#### `settleAttempt`

Runs after the body has settled, and again after teardown, before the
verdict. It reports a failure on a path no step awaited, such as a request
interceptor or a native dialog handler. Wait for one still running, then
throw its error: the attempt fails with it the way a step would, and an error
already classified keeps its code. Report each failure once.

```ts
async settleAttempt() {
  const running = [...dialogHandlers];
  dialogHandlers.clear();
  await Promise.all(running); // rethrows a handler's failure
},
```

#### `endAttempt`

Runs after each attempt and tears down what `startAttempt` set up. A failure
marks cleanup failed; the test keeps its status. It must be idempotent, and
safe to call after a failed `startAttempt`.

```ts
async endAttempt(context) {
  await client.closeContext({ signal: context.signal });
},
```

#### `dispose`

Runs once per worker, once `init` was called. It runs even when `init`
failed, so it must tolerate a partly initialized engine. A worker that never
called `init` gets no `dispose`. A failure is a run error.

A live `context.reuseSignal` permits keeping run-owned resources, the
reusable ones `prepare` and `finish` own, for a replacement worker. A missing
or aborted one requires final cleanup. Final shutdown, a forced
interrupt, or parent disconnect revokes that permission; observe revocation
until disposal settles. `reuseSignal` does not cancel cleanup, which stays
bounded by `context.signal` and `context.timeoutMs`.

Cleanup is best effort within the cleanup budget. The runner does not
guarantee cleanup after a worker exits or after disposal settles with reuse
permission.

```ts
async dispose(context) {
  await client.shutdown({ signal: context.signal });
},
```

```ts
export interface EngineCleanupContext {
  readonly signal: AbortSignal;
  readonly timeoutMs: number;
}

export interface EngineDisposeContext extends EngineCleanupContext {
  readonly reuseSignal?: AbortSignal;
}
```

`EngineCleanupContext` is the budget of one cleanup hook (`settleAttempt`,
`endAttempt`, `dispose`): `signal` aborts when the cleanup budget is spent,
and `timeoutMs` is the budget left when the call starts.

### Observation

`observe` returns one fresh semantic snapshot of the surface under test.

| Field | Type |
| --- | --- |
| `location` | `string` |
| `root` | `SemanticNode` |
| `viewport` | `ViewportSize` |
| [`truncated`](#truncated-trees) | `boolean` |
| `keyboardVisible` | `boolean` |
| `tabs` | `{ count, active }` |
| [`treeUnavailable`](#pixel-fallback) | `true` |
| `pixels` | `ObservationPixels` |
| `maskedRegionCount` | `number` |

`tabs` reports the open tabs when there is more than one: `count`, and the
zero-based place of the tab `root` reads, in the order the tabs opened. Omit
it with one tab.

Return the surface as it is right now. The runner mints the revision and
stamps it onto every ref; it also owns secret redaction and the observation
byte budget. A valid empty tree may have a childless root and
include `pixels`.

`maskedRegionCount` is the number of regions masked in the screenshot; the
harness checks that it covers every secure node. An engine asked for pixels
that cannot mask every secure node on screen omits `pixels` and still reports
the regions it could mask. A count with no `pixels` always reads as withheld,
even when the tree holds no secure node, since a tree read only in part can
leave one out: `toHaveScreenshot` fails with `POLICY_DENIED` and the agent
reads `MASKING_UNPROVEN`, not a missing screenshot.

```ts
export interface EngineSnapshot {
  readonly location?: string;
  readonly root: SemanticNode;
  readonly viewport: ViewportSize;
  readonly truncated?: boolean;
  readonly keyboardVisible?: boolean;
  readonly tabs?: { readonly count: number; readonly active: number };
  readonly treeUnavailable?: true;
  readonly pixels?: ObservationPixels;
  readonly maskedRegionCount?: number;
}

export interface EngineObserveOptions {
  readonly pixels?: boolean;
  readonly pixelFallback?: boolean;
  readonly comparable?: boolean;
}
```

| Field | Description |
| --- | --- |
| `location` | Where the surface is, as an opaque address the platform understands: a URL on a document platform, the foreground screen or activity on a device, the front window on a desktop. The harness shows it to the model and the report, anchors trace replay on it, and applies the origin policy to it only when it parses as a URL. Omit it when the platform has no notion of a current location. |
| `root` | The tree under one root the engine minted. The root's id must be stable for the surface across observations: `perform(root, swipe)` is the viewport swipe, and the harness addresses it from an earlier observation, possibly one taken before a `restart` or `reset`. So the root swipe must not depend on a live handle from that observation. A platform with several top-level elements, such as a device's windows, wraps them in a root of its own. |
| `viewport` | The viewport `SemanticNode.rect` and `ViewportPoint` are measured in, in CSS pixels. |
| `keyboardVisible` | Whether an on-screen keyboard is showing, as the engine measured it apart from `root`. Set `false` when it measured none; omit it only when the engine did not measure it. |
| `pixels` | Masked pixels, when requested and producible; omitted otherwise. |
| `options.pixels` | Requests masked viewport pixels for the same revision as the tree. |
| `options.pixelFallback` | Permits the [pixel fallback](#pixel-fallback). |
| `options.comparable` | The pixels are compared against a stored screenshot: hold system chrome, such as a status bar's clock and battery, in a fixed state where the platform can. |

#### Truncated trees

Set `truncated` when `root` leaves out nodes that are on the surface: the
engine stopped reading at a node cap or a depth limit, or could not enter a
child document. The harness tells the model the listing is incomplete and
never calls such a screen unchanged. Omit it or set `false` for a tree read
whole.

#### Pixel fallback

When semantic capture times out, an engine may return masked pixels in place
of the tree, but only when `pixelFallback` is true and it can prove
screenshot masking without that capture.

```ts
return {
  treeUnavailable: true,
  root: { ref: rootRef },
  viewport,
  pixels,
};
```

- Return `treeUnavailable: true`, fresh `pixels`, and a `root` containing
  only its stable `ref`. That ref supports viewport actions; it supplies no
  semantic node evidence. Retire earlier node refs.
- The flag tells missing semantic evidence from a valid empty tree. Never
  infer absence from it.
- Without permission, pixels, or independent masking proof, propagate the
  capture failure. Cancellation, policy denial, and hard engine failures
  propagate too.
- The runner permits fallback for `act` and for judgments with
  `vision: true` or `'only'`. It includes the
  screenshot even if the initial observation requested only a tree.
- A step that loses semantic evidence cannot record or finish by replaying a
  trace.
- Engines whose masks depend on their semantic capture cannot provide this
  fallback.

The runner checks the shape at runtime:

| Throws | When |
| --- | --- |
| `UNSUPPORTED_CAPABILITY` | A fallback without permitted pixels. |
| `INVALID_STATE` | A fallback whose root carries semantic fields. |

### Actions

`perform` carries out one `LocatorAction` on a node; `performAt` carries out
one `PointerAction` at a viewport point. An engine declares the kinds it
honors in `actions` and `pointerActions`.

| Kind | Fields | `actions` | `pointerActions` |
| --- | --- | --- | --- |
| `tap` | `modifiers?` on a node | yes | yes |
| `doubleTap` | `modifiers?` on a node | yes | yes |
| `multiTap` | `count` (3 or more), `modifiers?`; `tap({ count })` | yes | - |
| `secondaryTap` | `modifiers?` on a node | yes | yes |
| `longPress` | `durationMs?` | yes | yes |
| `fill` | `value`, `sensitive` | yes | - |
| `clear` | - | yes | - |
| `press` | `key` | yes | - |
| `check` | - | yes | - |
| `uncheck` | - | yes | - |
| `focus` | - | yes | - |
| `blur` | - | yes | - |
| `hover` | - | yes | yes |
| `scrollIntoView` | - | yes | - |
| `selectOption` | `value` | yes | - |
| `setInputFiles` | `paths`; empty clears the input | yes | - |
| `setInputFilePayloads` | `files` with `name`, `mimeType`, and `Uint8Array` `buffer`. An empty `files` array clears the input. The runner uses it to clear when the engine declares this action without `setInputFiles`. | yes | - |
| `dragTo` | `target`: a `NodeRef` or a `ViewportPoint` | yes | yes |
| `swipe` | `direction`, `momentum?` | yes | yes |
| `scrollTo` | `edge`: `'top'`, `'bottom'`, `'left'`, or `'right'`. Not in SPI v1, so list it explicitly. | yes | - |
| `swipeTo` | `target`, `durationMs?` | - | yes |

The grammar is closed. Anything beyond it is an agent-side `defineTool`.

#### Locator actions

```ts
async perform(ref, action, context) {
  switch (action.kind) {
    case 'tap':
      return client.tap(ref.id, { signal: context.signal });
    case 'swipe':
      return client.scroll(ref.id === rootId ? undefined : ref.id, action.direction);
    default:
      throw new EngineError('UNSUPPORTED_CAPABILITY', `kiosk cannot ${action.kind}`, { retryable: false });
  }
},
```

```ts
export type LocatorAction =
  | {
      readonly kind: 'tap' | 'doubleTap' | 'secondaryTap';
      readonly modifiers?: readonly KeyModifier[];
    }
  | {
      readonly kind: 'multiTap';
      readonly count: number;
      readonly modifiers?: readonly KeyModifier[];
    }
  | {
      readonly kind:
        | 'check'
        | 'uncheck'
        | 'clear'
        | 'focus'
        | 'blur'
        | 'hover'
        | 'scrollIntoView';
    }
  | { readonly kind: 'longPress'; readonly durationMs?: number }
  | { readonly kind: 'fill'; readonly value: string; readonly sensitive: boolean }
  | { readonly kind: 'press'; readonly key: Key }
  | { readonly kind: 'selectOption'; readonly value: SelectOption }
  | { readonly kind: 'setInputFiles'; readonly paths: readonly string[] }
  | {
      readonly kind: 'setInputFilePayloads';
      readonly files: readonly { readonly name: string; readonly mimeType: string; readonly buffer: Uint8Array }[];
    }
  | { readonly kind: 'dragTo'; readonly target: NodeRef }
  | {
      readonly kind: 'swipe';
      readonly direction: ScrollDirection;
      readonly momentum?: Momentum;
    }
  | {
      readonly kind: 'scrollTo';
      readonly edge: ScrollEdge;
    };

export type LocatorActionKind = LocatorAction['kind'];

export const LOCATOR_ACTION_KINDS = [
  'tap',
  'doubleTap',
  'secondaryTap',
  'longPress',
  'fill',
  'clear',
  'press',
  'check',
  'uncheck',
  'focus',
  'hover',
  'scrollIntoView',
  'selectOption',
  'setInputFiles',
  'dragTo',
  'swipe',
] as const satisfies readonly LocatorActionKind[];

export const KNOWN_LOCATOR_ACTION_KINDS = [...LOCATOR_ACTION_KINDS, 'blur', 'setInputFilePayloads', 'multiTap', 'scrollTo'] as const satisfies readonly LocatorActionKind[];
```

- `perform` acts on a ref from the newest observation or `locate`, with the
  platform's actionability checks. Agent tools and locator actions both call
  it.
- A `swipe` on the observation root swipes the viewport. The agent's `scroll`
  verb and `screen.swipe()` both arrive as `perform(root, swipe)`.
- `multiTap` is `count` taps in a row: one multi-click in a browser, presses
  at the device's cadence on a device. Two taps are a `doubleTap`.
- `scrollTo` scrolls a container to one of its edges, as far as it goes. On a
  node, that is the node when it scrolls along the edge's axis, else its
  nearest ancestor that does; an engine that cannot tell which node scrolls
  drags inside the node's own box. On the observation root, it is the
  screen's main scrolling content, else what is under the viewport's center.
  Resolve once the container cannot scroll further toward `edge`, at once
  when it is there already or nothing scrolls along that axis, and stop when
  the operation's budget runs out.
- `LOCATOR_ACTION_KINDS` holds the kinds of SPI v1; list newer kinds
  explicitly. `KNOWN_LOCATOR_ACTION_KINDS` holds every kind this version of
  core understands: use it to check a kind.

| Throws | When |
| --- | --- |
| `NODE_STALE`, retryable | The ref no longer binds. |
| `ACTION_MAY_HAVE_COMMITTED` | Input may have reached the app. The runner never repeats such an action, which keeps trace replay safe. |
| `UNSUPPORTED_CAPABILITY` | A declared kind this particular node cannot take, such as a `check` on a toggle whose state is unknown. |

#### Pointer actions

Pointer actions use viewport coordinates when no semantic node is available.

- `dragTo` ends at another point.
- `swipe` starts a scroll gesture at the given point.
- `swipeTo` is the one kind with no node form: the finger's path from the
  point to `target`, a touch swipe on a device and a pointer drag on a
  document platform. It differs from `dragTo`, where a platform holds before
  it drags.
- The point is in the CSS pixels of `SemanticNode.rect`. Dispatch the pointer
  at the point as given: the harness has clamped an agent's point to the
  viewport and validated a test's.
- Throw `UNSUPPORTED_CAPABILITY` for a declared kind the surface cannot
  deliver at this particular point.
- `POINTER_ACTION_KINDS` is the closed list of pointer kinds.

```ts
export type PointerAction =
  | { readonly kind: 'tap' | 'doubleTap' | 'secondaryTap' | 'hover' }
  | { readonly kind: 'longPress'; readonly durationMs?: number }
  | { readonly kind: 'dragTo'; readonly target: ViewportPoint }
  | {
      readonly kind: 'swipe';
      readonly direction: ScrollDirection;
      readonly momentum?: Momentum;
    }
  | {
      readonly kind: 'swipeTo';
      readonly target: ViewportPoint;
      readonly durationMs?: number;
    };

export type PointerActionKind = PointerAction['kind'];

export const POINTER_ACTION_KINDS = [
  'tap',
  'doubleTap',
  'secondaryTap',
  'longPress',
  'hover',
  'dragTo',
  'swipe',
  'swipeTo',
] as const satisfies readonly PointerActionKind[];
```

#### Keys

The key grammar of `press`, shared by every engine, and its parser.

```ts
parseKey('Control+a'); // { modifiers: ['Control'], key: { kind: 'char', char: 'a' } }
parseKey('Shift+Tab'); // { modifiers: ['Shift'], key: { kind: 'named', name: 'Tab' } }
parseKey('Ctrl+a'); // undefined: Ctrl is not a modifier of the grammar
```

```ts
export type Key = string;

export const KEY_MODIFIERS = ['Shift', 'Control', 'Alt', 'Meta', 'ControlOrMeta'] as const;

export const KEY_NAMES = [
  'Enter',
  'Escape',
  'Tab',
  'Backspace',
  'Delete',
  'Insert',
  'Space',
  'ArrowUp',
  'ArrowDown',
  'ArrowLeft',
  'ArrowRight',
  'Home',
  'End',
  'PageUp',
  'PageDown',
  'F1',
  'F2',
  'F3',
  'F4',
  'F5',
  'F6',
  'F7',
  'F8',
  'F9',
  'F10',
  'F11',
  'F12',
] as const;

export interface ParsedKey {
  readonly modifiers: readonly KeyModifier[];
  readonly key: { readonly kind: 'named'; readonly name: KeyName } | { readonly kind: 'char'; readonly char: string };
}

export function parseKey(key: string): ParsedKey | undefined;
```

- A key is zero or more modifiers and one key, joined by `+`: `Control+a`,
  `Shift+Tab`, `Enter`, `$`.
- The modifiers are those in `KEY_MODIFIERS`. `ControlOrMeta` is Control on
  Windows and Linux, Meta on macOS.
- The key is a name in `KEY_NAMES` or any single printable character (`a`,
  `A`, `1`, `$`), typed as itself.
- A platform without a key maps it or throws `UNSUPPORTED_CAPABILITY`. It
  never reinterprets the spelling.
- `parseKey` is the one parser, so no engine carries its own.
  `ParsedKey.modifiers` keeps the order written.

### App

The app under test is declared on the target (`targets: [{ engine, app }]`,
see [the app under test](https://e2e.com/docs/reference/config#the-app-under-test)); an engine
only drives it. The harness checks the shape of every field. Then it hands
the declaration to [`validateApp`](#validateapp) at config load.

| Target field | Reaches the engine as |
| --- | --- |
| `url` | `validateApp` only. The harness opens it through `session.open`. |
| the origin of `url`, on the run's port | `info.app.origin` in `prepare` and `init` |
| the site of `url` | `info.app.site` in `prepare` and `init` |
| `bundleId`, `appPath`, `launchArguments`, `permissions` | `validateApp`, and `info.app` in `prepare` and `init`, as the target declared them; `launchArguments` declared as an object arrives as `launchArgumentValues` |
| `command`, `readyUrl` | Never. The runner starts the app. |

`CommandConfig` is exported from `e2e`, not `e2e/engine`.

#### `validateApp`

Checks the declared app at config load, synchronously.

```ts
validateApp(app, { targetName }) {
  if (app.url === undefined) {
    throw new ConfigurationError('INVALID_CONFIG', `target "${targetName}" needs app.url`);
  }
},
```

- It runs for every target the engine serves, with `{}` for a target that
  declares no `app`.
- `@e2e-dev/web` requires `url`; `@e2e-dev/mobile` requires `bundleId` or
  `appPath` and refuses `url`.
- `info.fileApp` is set when the app's `url` names a file on the runner's
  disk; only an engine that declares `fileApps` is handed one. The harness
  checks every file navigation against that disk, so refuse here a surface
  that cannot read it, such as a browser on another machine, or do not
  declare `fileApps`.

| Throws | When |
| --- | --- |
| `INVALID_CONFIG` | A field the platform needs is missing, or the engine cannot drive one. Name `info.targetName` in the message. |

```ts
export type EngineAppDeclaration = EngineAppInfo & {
  readonly url?: string;
};

export interface EngineAppCheckInfo {
  readonly targetName: string;
  readonly fileApp?: boolean;
}

export type AppPermissionState = 'grant' | 'deny' | 'reset';

export type LaunchArgumentValue = string | number | boolean | readonly string[];

export type LaunchArguments = readonly string[] | Readonly<Record<string, LaunchArgumentValue | undefined>>;

export type LaunchArgumentValues = Readonly<Record<string, LaunchArgumentValue>>;

export type ResolvedLaunchArguments = readonly string[] | LaunchArgumentValues;
```

#### `EngineAppInfo`

The resolved app, as `EnginePrepareInfo.app` and `EngineInitInfo.app`: the
origin and site of the URL, and the device fields as the target declared
them. Scope a credential the engine injects to the exact origin. Apply the
site to observed frames with [`sameSite`](#site-helpers).

```ts
if (new URL(request.url).origin === info.app.origin) request.headers.set('x-api-key', key);
```

```ts
export interface EngineAppInfo {
  readonly origin?: string;
  readonly site?: string;
  readonly bundleId?: string;
  readonly appPath?: string;
  readonly launchArguments?: readonly string[];
  readonly launchArgumentValues?: LaunchArgumentValues;
  readonly permissions?: Readonly<Record<string, AppPermissionState>>;
  readonly allPermissions?: true;
}
```

| Field | Description |
| --- | --- |
| `origin` | The app URL's origin on the run's port (`scheme://host:port`, as `URL.origin` serializes it). Absent when the app has no URL or its URL is a file, and for a free port the run has not assigned (`e2e doctor`). |
| `site` | The app URL's registrable domain, as `siteOf` reads it. Absent when the app has no URL or its URL is a file. |
| `bundleId` | The installed app to launch. |
| `appPath` | The build to install, relative to `projectRoot`. |
| `permissions` | The permissions the app holds, by name: `'grant'` for held, `'deny'` for refused, `'reset'` for not asked for yet, so the OS asks again. What each state means on the platform is the engine's; a device sets them before every fresh launch. |
| `allPermissions` | `app.permissions: 'all'`: grant every permission the engine can grant, in place of `permissions`. |

The harness sets one of `launchArguments` and `launchArgumentValues`, never
both. An object on an engine without `launchArgumentValues: true` fails at
config load with `INVALID_CONFIG`. An engine that takes both forms reads
whichever is present and spells an object for its platform's launch command.
An iOS or macOS engine spells it with
[`appleUserDefaults`](#appleuserdefaults):

```ts
const launchArguments = info.app.launchArgumentValues ?? info.app.launchArguments;
const args = launchArguments === undefined ? [] : appleUserDefaults(launchArguments);
```

An engine for another platform spells the object itself.

### Session

Steering hooks behind the universal `app` fixture and the agent's `navigate`,
`back`, `resize_viewport`, `switch_tab`, and `close_tab` verbs.

| Hook | Behind |
| --- | --- |
| `open(url)` | `app.open()`, the agent's `navigate` verb, the reopen after `restart` and `reset` |
| `openLink(url)` | `app.open(path)` on a target with `app.linkBase` |
| `back()` | `app.back()`, the agent's `back` verb |
| `resize(size)` | the agent's `resize_viewport` verb |
| `switchTab(index)` | the agent's `switch_tab` verb |
| `closeTab(index)` | the agent's `close_tab` verb |
| `restart()` | `app.restart()` |
| `reset()` | `app.clearState()` |

```ts
session: {
  async back(context) { await client.back({ signal: context.signal }); },
  async restart(context) { await client.relaunch(bundleId, { signal: context.signal }); },
},
```

```ts
export interface EngineSession {
  open?(url: string, context: OperationContext): Promise<void>;
  openLink?(url: string, context: OperationContext): Promise<void>;
  back?(context: OperationContext): Promise<void>;
  resize?(size: ViewportSize, context: OperationContext): Promise<void>;
  switchTab?(index: number, context: OperationContext): Promise<void>;
  closeTab?(index: number, context: OperationContext): Promise<void>;
  restart?(context: OperationContext): Promise<void>;
  reset?(context: OperationContext): Promise<void>;
}
```

| Hook | Description |
| --- | --- |
| `open` | Opens one URL the harness already resolved against the base URL and the origin policy. Leave it out on a surface without addressable locations. |
| `openLink` | Opens a link in the app under test, as a deep link or a universal link would. The link arrives joined, with its scheme checked. A device engine's hook: a target whose engine lacks it cannot declare `linkBase`. |
| `back` | Navigates back once in the surface's history. |
| `resize` | Sets the viewport to `size` in CSS pixels, for this page and every page the attempt opens after it. |
| `switchTab` | Shows the open tab at `index`, zero-based in the order the tabs opened, as `EngineSnapshot.tabs` counts them. Every observation and action after it reads and acts on that tab. Declare it with `tabs` in snapshots. |
| `closeTab` | Closes the open tab at `index`, counted as `switchTab` counts them. When it was the tab shown, the engine shows another, such as the tab that opened it. |
| `restart` | Recreates the execution context, keeping persisted state. |
| `reset` | Clears persisted client state and recreates the execution context. |

- `restart` and `reset` open nothing on an addressable surface. They end at a
  fresh surface with no location shown, and the harness reopens the app
  through `open` when the target has an address.
- A surface without `open`, such as a device with a pinned app, relaunches
  the app inside `restart` and `reset` itself.
- Node actions never live here; they are `perform`.

| Throws | When |
| --- | --- |
| `ACTION_FAILED`, which the model reads | `switchTab` or `closeTab` with an index that has no open tab, or `closeTab` on the last open tab. |

### Errors

An engine throws `EngineError` with one code of a closed set. The runner maps
each code to the error a test sees.

| Code | Runner mapping | Retryable |
| --- | --- | --- |
| `NODE_STALE` | re-resolve, then `LOCATOR_NOT_FOUND` | yes |
| `FRAME_NOT_FOUND` | re-resolve, then `LOCATOR_NOT_FOUND` | yes |
| `FRAME_AMBIGUOUS` | `LOCATOR_AMBIGUOUS` | no |
| `NOT_ACTIONABLE`, `ACTION_MAY_HAVE_COMMITTED`, `OPERATION_TIMEOUT` | `ACTION_FAILED` | no |
| `CANCELLED` | infrastructure `CANCELLED` | no |
| `UNSUPPORTED_CAPABILITY` | configuration `UNSUPPORTED_CAPABILITY` | no |
| `INVALID_STATE` | `APP_NOT_OPEN` | no |
| `ENGINE_FAILURE`, any non-`EngineError` | infrastructure `ENGINE_FAILURE` | no |

#### `EngineError`

```ts
throw new EngineError('NODE_STALE', `node ${ref.id} is gone`, { retryable: true });
```

```ts
export class EngineError extends Error {
  constructor(code: EngineErrorCode, message: string, options: { retryable: boolean; cause?: unknown });
  readonly code: EngineErrorCode;
  readonly retryable: boolean;
}

export const ENGINE_ERROR_CODES = [
  'NODE_STALE',
  'FRAME_NOT_FOUND',
  'FRAME_AMBIGUOUS',
  'NOT_ACTIONABLE',
  'ACTION_MAY_HAVE_COMMITTED',
  'OPERATION_TIMEOUT',
  'CANCELLED',
  'UNSUPPORTED_CAPABILITY',
  'INVALID_STATE',
  'ENGINE_FAILURE',
] as const;

export type EngineErrorCode = (typeof ENGINE_ERROR_CODES)[number];

export const RETRYABLE_ENGINE_ERROR_CODES: ReadonlySet<EngineErrorCode> = new Set([
  'NODE_STALE',
  'FRAME_NOT_FOUND',
]);
```

`retryable` says whether the runner may re-resolve and retry. Only the codes
in `RETRYABLE_ENGINE_ERROR_CODES` may be retryable, since both describe a
repeatable read. Any other retryable claim is coerced to a non-retryable
`ENGINE_FAILURE`.

#### Timeouts at a deadline

An `OPERATION_TIMEOUT` on a locate or read that started with under 100 ms, or
under its slowest completed locate or read, of a waiting call's deadline left,
after one that completed, ends the wait
instead:

| Waiting call | Fails with |
| --- | --- |
| an action, `waitFor` | `LOCATOR_NOT_FOUND`, with the timeout as its cause |
| an assertion | `ASSERTION_FAILED`, with the timeout as its cause |

[`pollCondition`](#pollcondition) polls by these rules.

#### Runner error classes

An `EngineError` a contributed fixture method throws is mapped by the table
above, so a fixture over a session that ended reports `APP_NOT_OPEN` the way
an observation would. A method can also fail a step with the runner's own
error classes, exported from the same entry.

```ts
throw new TestError('ASSERTION_FAILED', 'expected the receipt to print');
```

`E2EError` itself is not exported; construct one of the three. Its `category`
sets the exit code and its `code` names the cause.

| Class | For |
| --- | --- |
| `TestError` | A test failure: `ASSERTION_FAILED`, `INVALID_LOCATOR`, `ACTION_FAILED`, and the like. |
| `ConfigurationError` | `POLICY_DENIED`, `APP_URL_REQUIRED`, `UNSUPPORTED_CAPABILITY`, and the like. |
| `InfrastructureError` | The surface itself failed: `BROWSER_INSTALL_FAILED` and the like. |

```ts
declare class E2EError extends Error {
  readonly category: 'test' | 'configuration' | 'infrastructure' | 'internal' | 'interrupted';
  readonly code: string;
  readonly retryable: boolean;
}

export class TestError extends E2EError {
  constructor(code: string, message: string, options?: { retryable?: boolean; cause?: unknown });
}
export class ConfigurationError extends E2EError {
  constructor(code: string, message: string, options?: { cause?: unknown });
}
export class InfrastructureError extends E2EError {
  constructor(code: string, message: string, options?: { cause?: unknown });
}
```

To test a caught error, use `isE2EError` and read its `category` and `code`.
`instanceof` misses an error thrown by another copy of `@e2e-dev/core`, such
as the one a device provider package loads.

```ts

if (isE2EError(error) && error.category === 'configuration') throw error;
```

### Shared semantics

Helpers for semantics every engine reproduces. Import them instead of
carrying a copy.

| Export | Returns |
| --- | --- |
| [`matchesText`, `toTextPattern`, `describePattern`](#text-patterns) | `boolean`, `TextPattern`, `string` |
| [`resolveExpression`, `expressionSelectors`](#resolveexpression) | `SemanticNode[]`, `readonly string[]` |
| [`shownText`](#showntext) | `string \| undefined` |
| [`urlMatches`](#urlmatches) | `boolean` |
| [`siteOf`, `sameSite`](#site-helpers) | `string`, `boolean` |
| [`isRefusedLinkScheme`](#isrefusedlinkscheme) | `boolean` |
| [`pollCondition`, `Deadline`](#pollcondition) | `Promise<void>`, `Deadline` |
| [`validateJsonValue`](#validatejsonvalue) | `void` |
| [`rejectUnknownKeys`](#rejectunknownkeys) | `void` |
| [`checkLaunchArguments`](#checklauncharguments) | `ResolvedLaunchArguments \| undefined` |
| [`appleUserDefaults`](#appleuserdefaults) | `readonly string[]` |
| [`rejectUnknownOptions`](#rejectunknownoptions) | `void` |
| [`obj`](#obj) | `WithoutUndefined<T>` |
| [`raceAbort`, `withTimeout`, `sleep`, `withinCleanupBudget`](#timing-helpers) | `Promise<T>`, `Promise<T>`, `Promise<void>`, `Promise<void>` |
| [`readPngSize`](#readpngsize) | `{ width, height } \| undefined` |
| [`isSecret`](#issecret) | `boolean` |
| [`isProviderRecording`, `stopProviderRecording`](#provider-recordings) | `boolean`, `Promise<VideoSegment>` |

#### Text patterns

`TextPattern` matching for `locate` and text matchers.

```ts
export function toTextPattern(match: TextMatch, options?: { exact?: boolean }): TextPattern;
export function matchesText(actual: string, pattern: TextPattern): boolean;
export function describePattern(pattern: TextPattern): string;
```

```ts
const pattern = toTextPattern(/total/i);
matchesText('Order total', pattern); // true
describePattern(pattern); // '/total/i'
```

| Throws | When |
| --- | --- |
| `INVALID_ARGUMENT` | `toTextPattern` gets a `match` that is neither a string nor a `RegExp`. |

#### `resolveExpression`

The reference `locate`. Resolves one `LocatorExpression` over a semantic
tree, in document order.

```ts
export function resolveExpression(
  expression: LocatorExpression,
  nodes: readonly SemanticNode[],
  options?: ResolveExpressionOptions,
): SemanticNode[];

export function expressionSelectors(expression: LocatorExpression): readonly string[];
```

```ts
async locate(expression) {
  const screen = await client.snapshot();
  return resolveExpression(expression, screen.nodes);
},
```

- `text` matches a node's `text`, or its `name` when `text` is omitted or
  blank ([`shownText`](#showntext)); `label` matches the `name`.
- A `filter`'s `hasText` reads `name`, `text`, and `value`, so it keeps a
  node a `text` query skips.
- `text` and `label` answer with the innermost match when a container echoes
  a descendant's text.
- With `textQuery: 'text'` a `text` query matches the `text` alone, as a
  browser does, for a tree that carries every element's text. A scoped text
  query then also answers with the scope element when the text is its own.
- An engine whose tree is the whole truth (a device, a desktop app) calls
  it. A browser engine answers with its own query engine, where `text` reads
  text content and never an accessible name.
- A `selector` expression needs the `selector` option, which answers
  synchronously. An engine whose selector language is asynchronous (a
  DevTools query, a device daemon) queries every selector
  `expressionSelectors(expression)` returns first, then answers from those
  results.
- A `frame` expression is `FRAME_NOT_FOUND`.
- A `union` expression matches either branch in document order, without duplicate nodes.

#### `shownText`

The string a `text` query reads a node by: its `text`, or its `name` when
`text` is omitted or blank.

```ts
export function shownText(node: Pick<SemanticNode, 'name' | 'text'>): string | undefined;
```

```ts
shownText({ name: 'Words', text: '5' }); // '5'
shownText({ name: 'Close' }); // 'Close'
```

An engine that matches text itself calls it, so its `getByText` agrees with
`resolveExpression`.

#### `urlMatches`

`toHaveURL`-style comparison of a current URL against an expected one.

```ts
export function urlMatches(
  current: string,
  expected: string | RegExp,
  baseHref: string,
  ignoreCase?: boolean,
): boolean;
```

```ts
urlMatches('https://shop.test/cart', '/cart', 'https://shop.test/'); // true
```

`ignoreCase` works as on the locator matchers.

| Throws | When |
| --- | --- |
| `INVALID_ARGUMENT` | `expected` is neither a string nor a `RegExp`, as in `toTextPattern`. |

#### Site helpers

`siteOf` reads a hostname's registrable domain, the form
`EngineAppInfo.site` takes. `sameSite` tells whether a URL is on a site.

```ts
export function siteOf(hostname: string): string;
export function sameSite(url: string | URL, site: string): boolean;
```

#### `isRefusedLinkScheme`

Whether a link's scheme is one no app link may take: `file:`, `data:`,
`javascript:`, `view-source:`, `blob:`, or `filesystem:`. An engine that
opens app links (`session.openLink`) refuses these with `POLICY_DENIED`, as
`app.open` does with `app.linkBase`.

```ts
export function isRefusedLinkScheme(protocol: string): boolean;
```

```ts
if (isRefusedLinkScheme(new URL(link).protocol)) throw new ConfigurationError('POLICY_DENIED', 'refused link scheme');
```

#### `pollCondition`

Assertion polling: until a read sees the condition hold or, negated, not hold.

```ts
export function pollCondition(options: PollConditionOptions): Promise<void>;
```

```ts
const deadline = new Deadline(context.timeouts.assertion);
await pollCondition({
  deadline,
  signal: context.signal,
  negated: false,
  evaluate: async () => (await read(context.operation(deadline.remaining()))) === 'Paid',
  onTimeout: (cause) => new TestError('ASSERTION_FAILED', 'status never became Paid', { cause }),
});
```

- Bound each read `evaluate` makes by `deadline`
  (`context.operation(deadline.remaining())`). A read on the action timeout
  can outlast the assertion's own.
- It reads at 0, 20, and 50 ms, then at every multiple of 100 ms from its
  start. Actions and `waitFor` wait for their node the same way.
- An `OPERATION_TIMEOUT` from an `evaluate` ends the poll under the rules in
  [Timeouts at a deadline](#timeouts-at-a-deadline). `onTimeout(cause)`
  builds the failure with it.

#### `validateJsonValue`

Checks that a value is plain JSON.

```ts
export function validateJsonValue(value: unknown, label: string, rules?: JsonValueRules): void;
```

```ts
validateJsonValue(result, 'kiosk.evaluate result', { maxDepth: 32 });
```

- A top-level `undefined` passes.
- `rules.onSecret` replaces the `POLICY_DENIED` a `Secret` raises with an
  error of its own; `rules.maxDepth` caps the nesting.

| Throws | When |
| --- | --- |
| `INVALID_ARGUMENT` | A non-finite number, a cycle, an object that is not a plain object or array, or a function, symbol, bigint, or `undefined` inside. The message names `label`. |
| `POLICY_DENIED` | A `Secret`, unless `rules.onSecret` throws its own. |

#### `rejectUnknownKeys`

Throws for the first own key of `value` outside `keys`: the check the runner
runs on its own config objects, for an engine factory's options.

```ts
export function rejectUnknownKeys(
  label: string,
  value: object,
  keys: readonly string[],
  code?: 'INVALID_CONFIG' | 'INVALID_ARGUMENT', // default: 'INVALID_CONFIG'
): void;
```

```ts
rejectUnknownKeys('web()', options, ['browser', 'viewport']);
// web() has unknown key "viewprt"; did you mean "viewport"?
```

- The message names the nearest known key when one is a plausible typo, and
  the known keys otherwise.
- Pass `'INVALID_ARGUMENT'` as `code` for an object a test passes to a
  fixture method.

#### `checkLaunchArguments`

The shape check the runner runs on a target's `app.launchArguments`, for a
launch a test asks for by hand, such as `device.openApp(app, { launchArguments })`.
Returns the arguments with every `undefined` object property left out, or
throws; an `undefined` list item is refused like any other non-string.

```ts
export function checkLaunchArguments(
  label: string,
  declared: unknown,
  code?: 'INVALID_CONFIG' | 'INVALID_ARGUMENT', // default: 'INVALID_CONFIG'
): ResolvedLaunchArguments | undefined;
```

```ts
const launchArguments = checkLaunchArguments('device.openApp({ launchArguments })', options.launchArguments, 'INVALID_ARGUMENT');
// device.openApp({ launchArguments }).env must be a string, number, boolean, or array of strings, got null
```

- A list holds strings. An object maps a non-empty name to a string, a finite
  number below 2^53 in magnitude, a boolean, or a list of strings. A name has
  no control characters, and no whitespace but spaces inside it. Nothing holds a NUL character.
- An object's argument name does not start with a dash: write `AppleLocale`,
  not `-AppleLocale`. The engine adds the dash, so a dashed name fails.
- The engine adds its platform's rules after this check, with the same
  `code`.

#### `appleUserDefaults`

Spells launch arguments as the process arguments of an iOS or macOS app. A
list stays as it is. An object becomes `-name value` for each entry, in the
form `NSUserDefaults` reads. Pass the result to the launch command.

```ts
export function appleUserDefaults(launchArguments: ResolvedLaunchArguments): readonly string[];
```

```ts
appleUserDefaults({ AppleLanguages: ['fr', 'en-GB'], e2e: true, offset: -1, mode: '(draft)' });
// ['-AppleLanguages', '(fr, en-GB)', '-e2e', 'YES', '-offset', '"-1"', '-mode', '"(draft)"']
```

- A boolean is `YES` or `NO`. A list is an old-style plist array.
- A string or number is bare when it holds only letters, digits, and
  `_ $ / : . -` and does not start with `-` or `//`. Other values are quoted,
  with `\` and `"` escaped. The same rule applies to each item of a list, so
  `{ cdn: ['//cdn.example'] }` is `-cdn ("//cdn.example")`.

#### `rejectUnknownOptions`

Refuses an option key a fixture method or matcher does not take, so a
JavaScript caller's unsupported option fails instead of running on the
default.

```ts
export function rejectUnknownOptions(
  api: string,
  options: object | undefined,
  known: readonly string[],
  code?: 'INVALID_ARGUMENT' | 'INVALID_LOCATOR', // default: 'INVALID_ARGUMENT'
): void;
```

```ts
rejectUnknownOptions('kiosk.print', options, ['copies']);
```

- Pass `INVALID_LOCATOR` as `code` for a locator option.
- `options` must be a plain object or `undefined`; a class instance or an
  array is refused.
- Non-enumerable own keys count as keys.

#### `obj`

Drops `undefined`-valued keys, so a result built from optional inputs
satisfies exact optional property types.

```ts
obj({ a: 1, b: undefined, c: 3 }); // { a: 1, c: 3 }
```

#### Timing helpers

```ts
export function raceAbort<T>(work: Promise<T> | (() => Promise<T>), signal: AbortSignal, label: string): Promise<T>;
export function withTimeout<T>(promise: Promise<T>, timeoutMs: number, onTimeout: () => Error): Promise<T>;
export function sleep(ms: number, signal?: AbortSignal): Promise<void>;
export function stepTimeout(timeout: unknown, api: string): number | undefined;
export function withinCleanupBudget(
  promise: Promise<unknown>,
  budget: { readonly signal: AbortSignal; readonly timeoutMs: number },
): Promise<void>;
```

```ts
await raceAbort(() => client.tap(ref.id), context.signal, 'kiosk tap');
const operation = context.operation(stepTimeout(options?.timeout, 'kiosk.print'));
```

- `raceAbort` abandons the wait when `signal` aborts. Pass a thunk to check
  cancellation before dispatch.
- `withTimeout` races a promise against a timeout and throws what
  `onTimeout` builds.
- `sleep` waits `ms`, and rejects as soon as `signal` aborts, with the
  error the signal was aborted with when it is a runner error, else
  `CANCELLED`. A wait for a condition uses `pollCondition` instead.
- `stepTimeout` turns a call's own `timeout` option into a budget for
  `context.operation`: `0` waits until the test timeout, or `cleanupTimeout` in `afterEach`, and a negative,
  `NaN`, or infinite one is `INVALID_ARGUMENT`.
- `withinCleanupBudget` never rejects. It resolves when the promise settles,
  failures included, when `signal` aborts, or when `timeoutMs` passes.

#### `readPngSize`

```ts
export function readPngSize(data: Uint8Array): { readonly width: number; readonly height: number } | undefined;
```

Reads a PNG's pixel size from its header, for `ObservationPixels.width` and
`height`: the size must be that of the bytes, since the model's coordinates
are relative to them. Returns `undefined` for bytes that are not a PNG.

#### `isSecret`

Tells a `secrets.get()` handle from a string, for an option that takes
either.

```ts
const password = isSecret(options.password)
  ? await context.resolveSecret(options.password)
  : options.password;
```

### State

Platform-neutral state capture and restore, behind `test.setup` sessions and
the `session:` option.

| Member | Does |
| --- | --- |
| `capture(context)` | Captures the surface's persisted state as an `EngineState`. |
| `restore(state, context)` | Replaces the surface's whole persisted state with `state`. |

```ts
state: {
  async capture(context) {
    return { format: 'kiosk-storage', version: 1, data: await client.exportStorage(context) };
  },
  async restore(state, context) {
    await client.replaceStorage(state.data, context);
  },
},
```

<Warning>
Snapshots are credentials: cookies, tokens, and storage that authenticate
the app under test. An engine must not persist, cache, or log a snapshot on
its own, must not echo snapshot contents in an error message, and must treat
`restore` as a replacement, never a merge, so a restored session cannot leak
into the next attempt.
</Warning>

```ts
export interface EngineState {
  readonly format: string;
  readonly version: number;
  readonly data: unknown;
  readonly expiresAt?: string;
}

export interface EngineStateCapability {
  capture(context: OperationContext): Promise<EngineState>;
  restore(state: EngineState, context: OperationContext): Promise<void>;
}
```

A setup test captures a snapshot; an ordinary test restores it at launch. The
harness owns the snapshot from the moment `capture` returns. It encrypts it at
rest, binds it to the run, target, engine, and app identity, and deletes it
when the run ends. It never logs it, reports it, digests it, or sends it to a
model.

| Field | Description |
| --- | --- |
| `format` | An engine-defined format name. |
| `version` | The format version. With `format`, it lets an engine reject a snapshot it can no longer read. |
| `data` | Opaque JSON the harness never inspects. |
| `expiresAt` | The earliest moment the state is known to be invalid, if the engine knows one. |

### Artifacts

Evidence capture: screenshots under the attempt directory, and videos there
or at a provider.

| Member | Returns |
| --- | --- |
| `screenshot(label, context)` | `Promise<string>` |
| [`startVideo(context)`](#videos) | `Promise<void>` |
| [`stopVideo(context)`](#videos) | `Promise<readonly VideoSegment[]>` |

`screenshot` is required and returns the path of the file it wrote. The
screenshot is redacted: mask secure fields at the source. Every path is
relative to the attempt artifact directory the engine received in
`startAttempt`.

```ts
artifacts: {
  async screenshot(_label, context) {
    // The label comes from test code, so it never becomes part of the path.
    shots += 1;
    const path = `screenshots/${String(shots).padStart(3, '0')}.png`;
    await client.capture(join(artifactsDir, path), context);
    return path;
  },
},
```

```ts
export interface EngineArtifacts {
  screenshot(label: string | undefined, context: OperationContext): Promise<string>;
  startVideo?(context: OperationContext): Promise<void>;
  stopVideo?(context: OperationContext): Promise<readonly VideoSegment[]>;
}

export type VideoSegment = VideoFile | VideoLink;

export interface VideoFile {
  readonly path: string;
  readonly startedAt: string;
}

export interface VideoLink {
  readonly url: string;
  readonly mediaType: string;
  readonly startedAt: string;
}
```

#### Videos

The runner calls `startVideo` for an attempt whose
[video mode](https://e2e.com/docs/reference/config#video) records, and for each
[`app.startRecording()`](https://e2e.com/docs/reference/app#startrecording), so one attempt may
start and stop several times, never overlapping. It moves the files a stop
returns before the next start.

- `startVideo` runs after `startAttempt` and any session restore, within the
  launch budget.
- `stopVideo` runs before `endAttempt`, within the cleanup budget.
- When the video mode is set explicitly, a `startVideo` that fails fails the
  launch and a `stopVideo` that fails fails cleanup. With the default mode, a
  failure of either drops the video quietly.
- The runner decides which recordings are kept and deletes a file an attempt
  does not keep.
- A surface that has nothing to show yet, such as one with no page open, may
  defer the capture until it does. Each segment says when it began.
- `stopVideo` returns every segment written, in order. One segment is the
  common case. A surface whose recording is bound to a page returns one per
  page the attempt showed, since a restart or a state reset opens a new one.
  An attempt that never showed anything returns none.

| Segment field | Description |
| --- | --- |
| `path` | A `VideoFile`'s path, relative to the attempt artifact directory. |
| `url` | A `VideoLink`'s `http(s)` URL, for a recording a hosted service keeps. The report links to it and the runner never downloads it. |
| `mediaType` | The media type of what the URL serves: `video/mp4`, or `text/html` for a player page. |
| `startedAt` | When the segment started recording, as an ISO timestamp. Its first frame is at or just after it. |

#### Provider recordings

An engine that leases its browser or device from a hosted service can let the
service record the attempt in place of its own capture, as
[`BrowserProvider.record`](https://e2e.com/docs/reference/web#recording-on-the-provider) and
[`DeviceProvider.record`](https://e2e.com/docs/mobile#hosted-devices) do. `stopProviderRecording`
turns a provider's recording into a `VideoSegment`.

```ts
async stopVideo(context) {
  if (recording === undefined) return [];
  return [await stopProviderRecording(recording, { artifactsDir, provider: 'browser provider "kernel"', leaseId, signal: context.signal })];
},
```

- `isProviderRecording(value)` tells whether what a provider's `record`
  resolved to is a recording: a parseable `startedAt` and a `stop`. Check it
  before keeping one, so a malformed recording fails the start, named,
  instead of the stop.
- `stopProviderRecording` creates the attempt's `video` directory and calls
  `stop` with it. A file must be a plain name that exists in that directory;
  a link must be an `http(s)` URL with a media type.
- It returns `{ path: 'video/<file>', startedAt }` or
  `{ url, mediaType, startedAt }` for `stopVideo` to hand back.
- The target argument's type is exported as `ProviderRecordingTarget`.

| Throws | When |
| --- | --- |
| `ENGINE_FAILURE` | `stop` throws or returns anything else. The message names the provider and the lease. |

```ts
export interface ProviderRecordContext {
  readonly runId: string;
  readonly targetName: string;
  readonly attemptId: string;
  readonly env: Readonly<Record<string, string | undefined>>;
  readonly signal: AbortSignal;
}

export interface ProviderRecording {
  readonly startedAt: string;
  stop(context: ProviderRecordingStopContext): Promise<ProviderRecordingResult>;
}

export interface ProviderRecordingStopContext {
  readonly dir: string;
  readonly signal: AbortSignal;
}

export type ProviderRecordingResult =
  | { readonly file: string }
  | { readonly url: string; readonly mediaType: string };

export function isProviderRecording(value: unknown): value is ProviderRecording;

export function stopProviderRecording(
  recording: ProviderRecording,
  target: {
    readonly artifactsDir: string;
    readonly provider: string;
    readonly leaseId: string;
    readonly signal: AbortSignal;
  },
): Promise<VideoSegment>;
```

| Field | Description |
| --- | --- |
| `ProviderRecordContext` | Handed to a provider's `record`, once per attempt that records video. Its `env` is the run's environment, the same the provider's `acquire` saw. Its `signal` aborts when the attempt is cancelled or its launch budget is spent. |
| `ProviderRecording.startedAt` | When the recording started, as an ISO timestamp. Its first frame is at or just after it. |
| `ProviderRecordingStopContext` | Handed to `stop`, once per recording. `dir` is an absolute directory, already created, that a recording written as a file goes into. `signal` aborts when the cleanup budget is spent. |
| `target.artifactsDir` | The absolute attempt artifact directory. |
| `target.provider` | The provider as error messages name it: `browser provider "kernel"`. |

#### Redaction

- Videos are unmasked and carry `redaction: 'incomplete'`.
- A `download` an engine attaches is the app's bytes. When the session knows
  a secret value, the runner rewrites a text one (`.txt`, `.csv`, `.json`,
  `.html`) and labels it `complete`.
- Every other download keeps its bytes and carries
  `redaction: 'incomplete'`.

### Contributed fixtures

An engine contributes named surfaces to the test fixtures through
`fixtures`. Each key becomes a fixture and a capability name. To a test it is
a [built-in fixture](https://e2e.com/docs/reference/test#fixtures), beside `app` and `screen`.

```ts title="src/index.ts"
fixtures: {
  printer: (context) =>
    context.fixture(
      'printer',
      {
        async print(text: string): Promise<void> {
          await client.print(text, context.operation());
        },
      },
      { print: { kind: 'resource', label: (text) => text } },
    ),
},
```

```ts title="tests/receipt.e2e.ts"

const test = base.extend<{ printer: { print(text: string): Promise<void> } }>();

test('prints a receipt', { platforms: ['kiosk'] }, async ({ printer }) => {
  await printer.print('Order 42');
});
```

The factory runs once per attempt with an `EngineFixtureContext`:

| Member | Use |
| --- | --- |
| `targetName` | The target the fixture serves. |
| [`fixture(name, surface, operations)`](#declaring-operations) | Declares which methods are recorded steps. |
| `app` | The resolved app, plus `resolveUrl(url)`, which resolves a navigation target against the base URL. |
| `timeouts` | The `test`, `action`, and `assertion` budgets. |
| `signal` | The running phase's signal: the attempt's through `beforeEach` and the body, then a fresh one per `afterEach` hook, so teardown can still drive the app after a body timeout. Read it per call; a factory that captures it once keeps a signal that is dead by teardown. |
| `operation(timeoutMs?)` | A per-call `OperationContext`: the action timeout, or the one passed, plus the attempt signal. |
| `attachArtifact(kind, relativePath)` | Registers a file the current step produced under the attempt artifact directory. |
| `attachViewport(viewport)` | Records the viewport the current step established. |
| `locator(expression)` | Mints a public locator from a raw expression, such as a platform selector. |
| `screen(scope)` | Mints a screen scope whose every query is wrapped by `scope`, such as a nested document. |
| [`expectable(target, factory)`](#expectations) | Makes `expect(fixture)` return matchers. |

| Throws | When |
| --- | --- |
| `INVALID_CONFIG` | The factory returns a plain surface, not one declared through `context.fixture`, the first time a test reaches for it. |
| `APP_URL_REQUIRED` | `app.resolveUrl` on a target that declares no URL. |
| `POLICY_DENIED` | `app.resolveUrl` with any scheme but `http:` and `https:` (`about:blank` aside). |

```ts
export type EngineFixtureFactory = (context: EngineFixtureContext) => object;

export interface EngineFixtureContext {
  readonly targetName: string;
  fixture<T extends object>(name: string, surface: T, operations: FixtureOperations<T>): T;
  readonly app: EngineAppInfo & {
    resolveUrl(url: string): string;
  };
  readonly timeouts: {
    readonly test: number;
    readonly action: number;
    readonly assertion: number;
  };
  readonly signal: AbortSignal;
  operation(timeoutMs?: number): OperationContext;
  attachArtifact(
    kind: 'screenshot' | 'video' | 'download' | 'log',
    relativePath: string,
  ): void;
  attachViewport(viewport: { width: number; height: number; scale: number }): void;
  locator(expression: LocatorExpression): Locator;
  screen(scope: (expression: LocatorExpression) => LocatorExpression): Screen;
  expectable<T extends object, E extends object>(target: T, factory: () => E): T & Expectable<E>;
}
```

#### Fixture isolation

`isolation` declares whether what an attempt does stays for the next one. It
sets the scope of the built-in fixtures the engine backs: the ones it
contributes, `app`, and `screen`.

```ts
defineEngine({ name: 'device', /* ... */ isolation: 'worker' });
```

| Value | Means | Fixture scope |
| --- | --- | --- |
| `'attempt'` (default) | `startAttempt` gives each attempt a fresh surface, such as a browser context. | Test fixtures. `beforeAll` and `afterAll` cannot read them. |
| `'worker'` | What an attempt does stays. A device keeps permissions and installed apps. | [Worker fixtures](https://e2e.com/docs/reference/test#worker-fixtures). `beforeAll`, `afterAll`, and worker fixtures get them. |

`@e2e-dev/mobile` declares `'worker'`. On such an engine:

- Each pass of suite hooks runs in a short attempt of its own (`startAttempt`,
  then `endAttempt`). So do the teardowns of worker fixtures when the worker
  ends. Make `startAttempt` launch nothing.
- In a serial group, or a test an `e2e mcp` session runs, the hooks run on the
  attempt already open. An engine runs one attempt at a time.
- When the attempt cannot open, or the run was interrupted, the hooks run
  without those built-in fixtures. See [`beforeAll`](https://e2e.com/docs/reference/test#beforeall).

```ts
export type EngineIsolation = 'attempt' | 'worker';
```

#### Declaring operations

`context.fixture(name, surface, operations)` declares which methods are
recorded steps. Each operation takes:

| Field | Values | Default |
| --- | --- | --- |
| `kind` | `'resource'` or `'assertion'` | required |
| `label` | `(...args) => string` | none |
| `timeout` | milliseconds, a function of the arguments, or `false` when the method owns its deadline | `actionTimeout` |
| `verifies` | `boolean` | `true` for assertions |

- Only declared async methods are recorded. Sync accessors pass through
  unchanged and keep their identity.
- Arguments enter reports only through `label`.
- A wait may set `verifies` as well.
- Nested maps describe namespaces.
- Recording decorates the object in place, so create a fresh surface in each
  factory invocation.
- The runner opens the step before calling a declared method, so attachments
  and failures from synchronous and asynchronous work land on the same step.
  Work arriving after its step has closed cannot attach to a later one.
- Type the fixture with `test.extend<{ name: Type }>()`.

```ts
export interface FixtureOperation<Args extends unknown[] = unknown[]> {
  readonly kind: 'resource' | 'assertion';
  readonly label?: (...args: Args) => string;
  readonly timeout?: number | false | ((...args: Args) => number | undefined);
  readonly verifies?: boolean;
}

export type FixtureOperations<T extends object> = {
  readonly [Key in keyof T]?: T[Key] extends (...args: infer Args) => Promise<unknown>
    ? FixtureOperation<Args>
    : T[Key] extends object ? FixtureOperations<T[Key]> : never;
};
```

#### Expectations

`expectable` attaches an expectation surface so `expect(fixture)` returns it.
Declare matcher recording with `context.fixture('expect', matchers,
operations)`. The harness records every matcher call as an assertion step
named `expect.<matcher>`; the factory only decides what the matchers mean.

```ts
const printer = context.expectable(surface, () =>
  context.fixture('expect', matchers, { toHavePrinted: { kind: 'assertion' } }),
);
return context.fixture('printer', printer, { print: { kind: 'resource' } });
```

## Types

### Exported names

`EngineCleanupContext`, `EngineDisposeContext`, `OperationContext`,
`TextPattern`, `SemanticQuery`, `LocatorExpression`,
`NodeRef`, `SemanticNode`, `ViewportPoint`, `ViewportSize`,
`ObservationPixels`, `LocatorAction`, `LocatorActionKind`, `PointerAction`,
`PointerActionKind`, `ScrollDirection`, `ScrollEdge`, `Momentum`, `SelectOption`, `Key`,
`KeyModifier`, `KeyName`, `ParsedKey`, `ENGINE_SPI_VERSION`,
`LOCATOR_ACTION_KINDS`, `KNOWN_LOCATOR_ACTION_KINDS`, `POINTER_ACTION_KINDS`, `KEY_MODIFIERS`,
`KEY_NAMES`, `parseKey`, `ENGINE_ERROR_CODES`, `RETRYABLE_ENGINE_ERROR_CODES`,
`Secret`, `isSecret`, `TextMatch`, `JsonValue`, `JsonValueRules`,
`ResolveExpressionOptions`, `PollConditionOptions`, `WithoutUndefined`,
`FixtureOperation`, `EngineIsolation`, `OBSERVED_NAME_LIMIT`, and `OBSERVED_TEXT_LIMIT` are
exported from `e2e/engine`. So are the [engine protocol](https://e2e.com/docs/reference/engine-protocol)'s
`connectEngine`, `serveEngine`, `describeEngine`, `spawnTransport`,
`socketTransport`, `loopbackTransport`, `ENGINE_METHODS`,
`ENGINE_PROTOCOL_VERSION`, and their types.

### `SemanticNode`

```ts
export interface SemanticNode {
  readonly ref: NodeRef;
  readonly role?: string;
  readonly name?: string;
  readonly text?: string;
  readonly value?: string;
  readonly selection?: string;
  readonly testId?: string;
  readonly inputPurpose?: 'username' | 'password' | 'one-time-code' | 'generic-secret' | 'none';
  readonly states?: Readonly<
    Partial<
      Record<
        | 'checked'
        | 'disabled'
        | 'selected'
        | 'expanded'
        | 'pressed'
        | 'focused'
        | 'hidden'
        | 'secure'
        | 'readonly'
        | 'empty',
        boolean
      >
    >
  >;
  readonly level?: number;
  readonly attributes?: Readonly<Record<string, string>>;
  readonly rect?: {
    readonly x: number;
    readonly y: number;
    readonly width: number;
    readonly height: number;
  };
  readonly origin?: ViewportPoint;
  readonly selector?: string;
  readonly framePath?: readonly string[];
  readonly children?: readonly SemanticNode[];
}
```

| Field | Description |
| --- | --- |
| `ref` | Valid against the observation it came from. |
| `value` | The current input value. Never reported for a secure field. |
| `selection` | The text selected inside the node, for the focused field or editing host whose selection the platform reports. Absent when the selection is collapsed, and never reported for a secure field. |
| `testId` | The node's test id, when the platform gives it one: the value of the project's test-id attribute on a document platform, an accessibility identifier on iOS, a resource id on Android, an automation id on a desktop. The `testId` query resolves against this field. An engine may also match the id without its platform's namespacing. |
| `inputPurpose` | What a field takes, deciding which secrets may fill it. |
| `states.pressed` | A toggle button's pressed state. |
| `states.secure` | Marks a field whose value is never observed. |
| `states.readonly` | Present only on a node that has a read-only state, and only where the platform knows, as Android does: absent means there is no read-only state to read, not `false`. On the web it is what Playwright's `getReadonly` decides: an input, textarea, or select by its `readonly` attribute, an element whose ARIA role takes `aria-readonly` by that attribute, any other editing host `false`. |
| `states.empty` | Whether the node holds nothing. On the web it is what Playwright's `toBeEmpty` reads: an input or textarea by its raw value, any other element by its trimmed text content. On a device it is a text field by its value, any other node by the text and values in its subtree. Report it on the nodes `locate` returns, never in an observation, and never on a secure field: absent means the engine does not say. |
| `level` | A heading node's level, `1` through `6` on a document platform. Absent elsewhere. |
| `attributes` | Platform attributes: what `getAttribute` reads. |
| `rect` | The node's box in the top-level viewport's CSS pixels, the space of `ViewportPoint`, for every node. An engine that measures a child document against its own viewport shifts the boxes by the boundary element's before reporting them. |
| `origin` | The point an offset into the node is measured from, in `rect`'s space, when it is not `rect`'s top-left corner: a document element's padding box, inside its border, or the corner of a box a frame clipped `rect` from. `tap({ position })` adds the offset to it. |
| `selector` | A platform selector that addresses the node within its own document, when the platform has one. It is structural, not semantic: it survives the content changes that rename a node, and a runner may store it to re-find the node on a later run. It is never part of the node's identity, so what it resolves to is still checked before use. Anchor it on an attribute naming the node or one of its ancestors. Leave it out rather than make it positional all the way to the document root, since anything inserted above the node shifts such a path. |
| `framePath` | The enclosing nested-document chain, as the selector of each boundary node, outermost first. Absent for nodes in the main document. |

### Observed field limits

| Constant | Value | Cuts |
| --- | --- | --- |
| `OBSERVED_NAME_LIMIT` | 256 | `name` |
| `OBSERVED_TEXT_LIMIT` | 512 | `text`, and any `value` or `selection` the engine cuts |

- An engine that cuts an observed field cuts it at exactly its limit. A field
  exactly at its limit may have been cut; a shorter one, or a longer one the
  engine left whole, is complete.
- Keep the start and cut the end.
- Single-node reads are unbounded and always carry the full value.

### Queries

The `selector` expression kind carries a platform-native selector string;
`frame` scopes a query into a nested document.

```ts
export type QueryKind = 'role' | 'label' | 'placeholder' | 'text' | 'displayValue' | 'testId';
```

A `SemanticQuery` with `visible: true` must match only nodes whose
`states.hidden` is false. Use the same predicate the engine reports on
`SemanticNode`, so `getByText('x', { visible: true })` and `toBeVisible()`
never disagree. Apply it wherever the query sits in the expression, under a
scope, filter, or index too.

## Related

[Engines](https://e2e.com/docs/engines) compares the ways to build one.
[Writing an engine](https://e2e.com/docs/writing-an-engine) walks through `defineEngine`, and
an [engine server](https://e2e.com/docs/reference/engine-protocol#engine-servers) runs an engine
in another process, machine, or language.
`@e2e-dev/web` ([reference](https://e2e.com/docs/reference/web)) and `@e2e-dev/mobile`
([reference](https://e2e.com/docs/reference/mobile)) implement this contract with the same
public `defineEngine`.
