> ## 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.

# Browser and device automation

> Automate a browser, an iOS or Android app, or a Mac app from your own script with @e2e-dev/core, using the e2e engines, screen, and an optional AI agent, with no test runner.

`@e2e-dev/core` drives a browser, an iOS or Android app, or a Mac app from
plain code. It uses the e2e engines, `screen`, and the agent, without the
test runner: there is no config file, no report, and no `expect`.

## When to use it

| You want to | Use |
| --- | --- |
| Write tests and run them locally and in CI, with reports | `e2e`. See the [quickstart](https://e2e.com/docs/quickstart). |
| Give a coding agent a live session on your app | The [MCP server](https://e2e.com/docs/coding-agents#let-the-agent-use-the-app) |
| Drive an app from your own program: a script, a scraper, a bot, test data setup | `@e2e-dev/core` |
| Open a second browser or device inside a test | `@e2e-dev/core`. See [Open a host inside a test](#open-a-host-inside-a-test). |

## Install

<CodeGroup>

```bash npm
npm install @e2e-dev/core @e2e-dev/web
```

```bash pnpm
pnpm add @e2e-dev/core @e2e-dev/web
```

```bash bun
bun add @e2e-dev/core @e2e-dev/web
```

</CodeGroup>

Install `@e2e-dev/mobile` instead of (or alongside) `@e2e-dev/web` to drive
mobile devices, or `@e2e-dev/desktop` to drive Mac apps. `@e2e-dev/core`
doesn't need the `e2e` test runner installed, and runs on Node.js 22.22.3+
or 24.8+.

<Note>
Always import engines from their `/engine` subpath (like
`@e2e-dev/web/engine`). The root entry exports a `test` fixture that requires
the full `e2e` package.
</Note>

## Drive a browser

`launch` prepares an engine and returns a host. A session is one isolated
browser context on that host, and it holds the built-in fixtures `screen`,
`app`, and `platform`, and the one the engine contributes, here `browser`.

```ts title="prices.ts"

await using shop = await launch(web(), { app: { url: 'https://shop.example.com' } });

for (const sku of ['A-1001', 'B-2040']) {
  await using session = await shop.newSession();
  await session.app.open(`/products/${sku}`);
  const soldOut = session.screen.getByText('Sold out', { exact: false, visible: true });
  if (await soldOut.isVisible()) continue;
  const price = await session.screen.getByTestId('sale-price').textContent();
  console.log(sku, price);
}
```

Run it with `node prices.ts`. Node.js runs a `.ts` file without a build
step.

`screen` and `app` are the same API as in a test: see
[screen](https://e2e.com/docs/reference/screen) and [app](https://e2e.com/docs/reference/app). `await using` closes
each session at the end of its block, and the host, with its browser, at the
end of the file. It needs Node.js 24 or Bun. On Node.js 22, call `close()` in
a `finally`:

```ts
const shop = await launch(web(), { app: { url: 'https://shop.example.com' } });
try {
  const session = await shop.newSession();
  await session.app.open('/products/A-1001');
} finally {
  await shop.close(); // closes the open session too
}
```

| Rule | Behavior |
| --- | --- |
| Ownership | Pass a fresh engine instance to each `launch(web())` call; reusing one fails. |
| Sessions | One active session per host at a time. Close it before calling `newSession()`, or launch another host for parallel work. |
| Devices | Each `mobile()` host claims its own device session. See [Several hosts on devices](#several-hosts-on-devices). |
| Timeouts | Actions, waits, and reads default to 30s; `app.open()` and `app.restart()` default to 120s. Override with `launch({ timeout })` or `session.setDefaultTimeout(ms)`. |
| Cancellation | Pass an `AbortSignal` to `launch({ signal })` or `newSession({ signal })`. |
| Ctrl-C | Hosts close cleanly on SIGINT, SIGTERM, and SIGHUP so browsers and devices don't linger. Disable with `handleSignals: false`. |
| Files | Screenshots and downloads go to a temp folder that's deleted on `close()`. Pass `artifactsDir` to keep them. |

The [reference](https://e2e.com/docs/reference/core) lists every option.

### Several hosts on devices

Without a `session` option, each `mobile()` host drives its device under an
agent-device session of its own, named after its target and a random token
(`e2e-ios-<token>-0`). A host never takes over a device another session
holds, whether that is another host or a worker of `e2e run`.

- Boot one free device per host. Inside a test, the run's workers hold their
  devices first: by default a local run drives as many booted devices as it
  has workers and test files. Leave one free with `--workers`, or name the
  run's devices in the target's `device` option.
- Without a `device` option, two hosts that open at the same moment can read
  the same booted device as free. The one that loses moves to the next free
  device. When none is left, its launch fails. A target
  with `appPath` can still collide: see the next point.
- A host holds its device from the moment its app opens. A target that names
  only `appPath` opens no app at launch, so a second host launched before the
  first one opens its app can pick the same device. Call
  `device.installApp()` and then `app.open()` on each host's session before
  you launch the next one, or name each host's device in its `device` option.
- A program that ends without closing a host it opened an app on
  (`process.exit()`, a kill) leaves its device held, and so does a host
  whose session fails to close: its `close()` throws an error that names the
  session. Later hosts and `e2e run` skip that device until you close the
  session the error names.
  Replace `SESSION` with that name:

<CodeGroup>
```bash npm
npx agent-device close --session "SESSION"
```

```bash pnpm
pnpm dlx agent-device close --session "SESSION"
```

```bash bun
bunx agent-device close --session "SESSION"
```
</CodeGroup>

## Drive an app on a device

Pass `mobile()` and the app. The same `screen` code runs on a browser and
on a device.

```ts

await using shopApp = await launch(mobile({ platform: 'ios' }), {
  app: { bundleId: 'com.example.shop', linkBase: 'https://shop.example.com' },
});
await using session = await shopApp.newSession();
await session.app.open('/products/A-1001');
```

`app.linkBase` makes `app.open(path)` open a link in the app:
`https://shop.example.com/products/A-1001` as a universal link here, or
`shopapp://products/A-1001` with `linkBase: 'shopapp://'`. Without it,
`app.open()` launches the app and takes no path. `linkBase` also works in an
`e2e.config.ts` target; see [config](https://e2e.com/docs/reference/config#linkbase).

The iOS simulator can stop a custom-scheme link at an "Open in ...?" prompt.
Tap its `Open` button when it shows:
`session.screen.getByRole('button', 'Open')`.

## Drive a desktop app

Pass `desktop()` and a Mac app: `appPath` for a built `.app` bundle, or
`bundleId` for an installed app. The session holds a `desktop` fixture
beside `screen` and `app`.

```ts title="sign-in.ts"

await using myApp = await launch(desktop(), { app: { appPath: 'build/MyApp.app' } });
await using session = await myApp.newSession();
await session.app.open();
await session.screen.getByRole('textbox', 'Username').fill('ada');
await session.screen.getByRole('button', 'Sign in').tap();
const windows = await session.desktop.windows();
console.log(await Promise.all(windows.map((window) => window.title())));
```

<Note>
The desktop engine is [experimental](https://e2e.com/docs/desktop) and runs on macOS 13 or later
only. The program that starts your script needs the Accessibility and Screen
Recording permissions: see [Desktop](https://e2e.com/docs/desktop#set-up). Core doesn't need the `e2e`
package; only the `e2e doctor` check on that page uses it.
</Note>

`app.open()` launches the app in the background, unless you pass
`headed: true` to `launch`. An app that opens no window in the background,
like a document-based app, needs `headed: true` or
`desktop({ physicalInput: true })`.
[The desktop fixture](https://e2e.com/docs/desktop#the-desktop-fixture) covers windows and
keyboard input.

## Keep a signed-in state

`session.saveState()` captures a browser session's cookies and storage in
memory so you can pass it to `newSession({ state })` after closing the first
session. (Not supported on mobile devices.)

```ts
const state = await session.saveState();
await session.close();
await using next = await shop.newSession({ state });
```

To keep a state between program runs, encrypt it with a 32-byte key that you
keep, for example in a secret store. There is no plaintext export.

```ts

const key = randomBytes(32);
const bytes = await state.export({ key }); // write these to disk
const restored = await SessionState.import(bytes, { key });
```

Saved state only restores on a host using the same engine, platform, and
app (set matching `app.identity` values if addresses like `localhost` and
`127.0.0.1` differ). A mismatched host, wrong key, or tampered bytes will
fail to restore.

## Pass secrets

Give secret values to `launch`, then fill them by name.

```ts
await using shop = await launch(web(), {
  app: { url: 'https://shop.example.com' },
  secrets: { SHOP_PASSWORD: process.env.SHOP_PASSWORD! },
});
await session.screen.getByLabel('Password').fill(shop.secret('SHOP_PASSWORD'));
```

The values never appear in the errors a session throws, in `screen.tree()`,
or in what the agent reads. A read your code asks for, such as
`textContent()`, returns the page's text as it is. An exported state holds
the values the session knew, encrypted, so a host launched without them still
redacts them.

Every session in the program redacts the values of every host open in it.

An agent gets a secret through its params, by name only:
`agent.act('Sign in with {password}', { params: { password: shop.secret('SHOP_PASSWORD') } })`.

## Handle errors

Every failure is an error with a `code`. Check it with `isE2EError`, not
`instanceof`.

```ts

try {
  await session.screen.getByRole('button', 'Add to cart').tap();
} catch (error) {
  if (isE2EError(error) && error.code === 'LOCATOR_NOT_FOUND') console.log('not on sale');
  else throw error;
}
```

| Code | When |
| --- | --- |
| `LOCATOR_NOT_FOUND` | Nothing matched before the timeout. A wait that ran out has this code too. |
| `LOCATOR_AMBIGUOUS` | The locator matched more than one node. |
| `ACTION_FAILED` | The action did not finish. It may still have reached the app, so do not repeat a payment. |
| `APP_UNREACHABLE` | Nothing answered at the app's URL. |
| `CANCELLED` | A `signal` aborted the operation, or the session is closed. |
| `WORKER_PROTOCOL` | A second session on a host, a second host on one engine instance, or a closed host. |

[Errors](https://e2e.com/docs/reference/errors) lists every code.

## Let the agent act

`createAgent` from `@e2e-dev/core/agent` puts an agent over one session. Its
`act`, `assert`, `waitFor`, and `extract` work as they do in a
[test](https://e2e.com/docs/reference/agent). The agent needs the AI SDK, and the example reads a
typed result with `zod`: install `ai` and `zod` beside the engine.

```ts title="checkout.ts"

await using shop = await launch(web(), { app: { url: 'https://shop.example.com' } });
await using session = await shop.newSession();
await session.app.open('/products/A-1001');

const agent = createAgent(session, {
  model: gateway('anthropic/claude-sonnet-5-5'),
  cache: { dir: '.shop-bot/cache' },
});

await agent.act('Add the item to the cart and apply the coupon with the largest discount', {
  cacheKey: 'cart-best-coupon',
});
// A check after the step lets the cache keep its recording.
await session.screen.getByRole('button', /pay now/i).waitFor();

const order = await agent.extract('the order total', { schema: z.object({ total: z.number() }) });
if (order.total <= 39_000) {
  try {
    await session.screen.getByRole('button', /pay now/i).tap();
  } catch (error) {
    // A failed tap may still have reached the server:
    // check the order list, never retry the payment.
    console.error('check /my/orders');
    throw error;
  }
} else {
  console.log(`the total, ${order.total}, is over the limit: the order stays unpaid`);
}
```

`createAgent` accepts the same options as an [`agents` entry](https://e2e.com/docs/reference/config#agents)
(`model`, `judge`, `maxSteps`, `context`), plus `cache`. There's no default
model, so always pass one. `agent.act` defaults to a 120s timeout (override
per call with `timeout`).

### Replay recorded steps

Pass `cache` to record passing `agent.act` steps and replay them on future
runs with zero model calls. Every `act` call must then specify either a
`cacheKey` or `cache: false`. Entries are keyed by `cacheKey`, instruction,
params, app, and how many times the session made that call.

Recordings are saved when the session or host closes, as long as a check
like `locator.waitFor()`, `agent.assert()`, or `agent.waitFor()` passed
after the step. A failed agent step drops unconfirmed recordings, while a
failure in your own locator code (like a timed-out `waitFor`) drops nothing.
See [Caching](https://e2e.com/docs/cache) for how replay and self-healing work.

| Option | Default | Meaning |
| --- | --- | --- |
| `dir` | `.e2e/cache` | Cache directory (relative to `launch`'s `cwd`). |
| `mode` | `read-write` | Set `read-only` to replay without writing. |
| `strict` | `false` | Fail on stale recordings instead of falling back to the model. |
| `store` | - | Custom [`CacheStore`](https://e2e.com/docs/cache) instead of local files. |

## Open a host inside a test

A test can open a second session for another user or device. In this
browser example, a [setup test](https://e2e.com/docs/authentication) saves the sender's login
as `sender`. The recipient signs in on a separate host pointed at the same
app. Use test accounts and a conversation reserved for the test.

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

test('delivers a message to the recipient', { session: 'sender' }, async ({ app, screen }) => {
  const message = `Hello ${randomUUID()}`;
  await using host = await launch(web(), {
    app: { url: app.baseUrl },
    secrets: { RECIPIENT_PASSWORD: process.env.RECIPIENT_PASSWORD ?? '' },
  });
  const recipient = await host.newSession();
  await recipient.app.open('/login');
  await recipient.screen.getByLabel('Email').fill('recipient@example.test');
  await recipient.screen.getByLabel('Password').fill(host.secret('RECIPIENT_PASSWORD'));
  await recipient.screen.getByRole('button', 'Sign in').tap();
  await recipient.screen.getByRole('heading', 'Chat').waitFor();
  await app.open('/chat');

  await screen.getByLabel('Message').fill(message);
  await screen.getByRole('button', 'Send').tap();

  await expect(recipient.screen.getByText(message, { exact: true })).toBeVisible();
});
```

If you already captured the recipient's login with `saveState()` on a core
session, restore it with [`newSession({ state })`](https://e2e.com/docs/reference/core#newsession)
on a host for the same app, engine, and platform. Named runner sessions
from `session.save()` are restored through the runner's `session` option.

The test's report covers the session:

| In the report | Behavior |
| --- | --- |
| Steps | Each step of the session, under `launch-1`, `launch-2`, in the order the test opened the sessions. |
| Model usage | Counted with the test's. |
| Video | Kept beside the test's when the test records one, as `video/launch-1.webm`. The session must be opened inside the test, and `app.startRecording()` on it fails while it records. |
| Secrets | The host redacts the config's secrets, and the report redacts the host's until the test ends. |
| A host or session the test opened | Closed when the test ends, if still open. One a worker fixture or a `beforeAll` hook opened is left open, and records no video. |
| A call left running | A step, `launch`, or `newSession` still running when the test ends fails it with `STEP_NOT_AWAITED`: a step's session is closed, and an opening is cancelled. A call that failed and whose error the test caught does not fail the test. |

## Next

<CardGroup cols={2}>
  <Card title="@e2e-dev/core reference" href="/reference/core">
    Every option of `launch`, a session, a saved state, and `createAgent`.
  </Card>
  <Card title="screen" href="/reference/screen">
    Every query and action a session holds.
  </Card>
  <Card title="Agent" href="/reference/agent">
    What `act`, `assert`, `waitFor`, and `extract` take and return.
  </Card>
  <Card title="Models" href="/models">
    Choose and configure the model the agent calls.
  </Card>
</CardGroup>
