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

# Caching

> Replay verified agent actions from the replay cache with zero model calls, and let the agent take over when the UI changes.

The replay cache saves the actions from a passing `agent.act()` step once a
later check confirms the outcome. On future runs, e2e replays those actions
with zero model calls. If the UI changed and an element or expected end
state no longer matches, the agent takes over from the current screen. See
[Self-healing tests](https://e2e.com/docs/self-healing).

<VideoCard
  id="FHTMtH0v4SI"
  title="How Does Agentic Caching Work in e2e?"
  subtitle="In this video, Kacper shows how e2e replays an agent's actions without a model call, and what happens when the app changes."
/>

`agent.assert`, `agent.waitFor`, and `agent.extract` always run live.
The run summary breaks down what happened to your `agent.act` steps:

```text
           AI  4.1k tokens · 2 model calls · openai/gpt-6-luna-fast
        Cache  4 replayed · 1 handed off · 1 missed · 1 not saved
```

`not saved` counts steps that passed without writing a recording, usually
because no assertion followed the step or the step caused no visible UI
change.

## When a recording is written

Always end a test with an assertion. In `read-write` mode, e2e only saves
`agent.act` recordings at the end of a test if a later verification check
passed. One check at the end confirms every `agent.act` before it.

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

test('adds an item', async ({ app, agent, screen }) => {
  await app.open('/cart');

  await agent.act('add one item to the cart');

  await expect(screen.getByRole('status')).toHaveText('1 item');
});
```

| Counts as verification | Does not count |
| --- | --- |
| `expect(locator).toHaveText(...)` and other locator matchers | `expect(value).toBe(...)` on a plain value |
| `expect(browser).toHaveURL(...)` and other engine assertions | `expect.poll(...)` |
| `locator.waitFor()`, `browser.waitForURL()` | `locator.textContent()` and other reads |
| `agent.assert(...)`, `agent.waitFor(...)` | `agent.extract(...)`, another `act`, or just passing |

In the JSON report, `step.cache.write` records what happened to the entry:

| `step.cache.write` | Meaning |
| --- | --- |
| `saved` | Recorded for future runs. |
| `kept` | Existing entry left as is. |
| `unconfirmed` | Not saved because no verification check passed after the step. |
| `evicted` | Deleted because the replay failed, needed repair, or wasn't confirmed before a failure. |
| `no-change` | Not saved because no visible control or route changed (including steps that only touch a [cross-origin iframe](https://e2e.com/docs/reference/web#framelocator)). Such a step runs live on every run. |
| `not-written` | Not saved because the cache store rejected it. The file store does when the test's file would go over the 1 MiB limit, or when it holds a recording the store can't read, which `npx e2e cache ls` names. |

If a test fails partway through, e2e still saves any earlier steps that were
already confirmed, and evicts the broken replay. To preserve setup steps
while you debug a failing assertion, put a quick `locator.waitFor()` after
setup. Cancelling a run leaves the cache untouched.

<Accordion title="Failures where the model couldn't answer">
If a test fails only because the model couldn't be reached (no model
configured, rejected API key, rate limit, or provider outage), e2e doesn't
evict your recordings. Those failures say nothing about your app, so a
`read-write` run without model access won't wipe working cache entries.

Flow failures still evict as usual: invalid model output
(`MODEL_OUTPUT_INVALID`), context overflow (`CONTEXT_OVERFLOW`), refusals
(`MODEL_REFUSED`), `STEP_TIMEOUT`, or any other failure in the same attempt
(such as an `afterEach` assertion).
</Accordion>

## What must match

Each cache entry belongs to one test, target, instruction, set of params,
and agent. A cache miss happens if you:

- rename the test, its `describe` block, or the target, or move the test file,
- change the instruction text or a normal param,
- switch to a different agent or change its `context` / `agentContext`,
- switch engines, or change `projectId` or `app.identity`.

Switching models or upgrading the engine does **not** invalidate your cache.
Use `--no-cache` when you want to test how a new model performs.

Dynamic values like timestamps or generated emails would miss on every run.
Wrap them in `unique()` so e2e substitutes the new value during replay:

```ts

const name = `E2E ${Date.now()} Company`;
await agent.act('create a company named {name}', { params: { name: unique(name) } });
await expect(screen.getByRole('heading', { name })).toBeVisible();
```

Use `unique()` for data the flow enters or displays, and plain params for
values that change the branch of the flow (like a plan name). Don't reuse a
`unique()` value inside another param's value, or e2e will skip recording
that step.

For preview URLs that change on every deploy, set
[`app.identity`](https://e2e.com/docs/reference/config#the-app-under-test) so recordings stay
valid across previews. On mobile devices, replay identifies screens by
their [screen title](https://e2e.com/docs/reference/mobile#replay-cache-on-a-device).

## Rerun a test while you fix it

Keep the cache in `read-write` mode (the local default) while iterating on a
failing test. Earlier setup goals that were already confirmed replay with no
model calls:

1. Run only the test you're fixing by line number:
   `npx e2e run tests/cart.e2e.ts:3`.
2. Don't rename the test or reword passing goals, since that
   [causes a miss](#what-must-match).
3. Pass `--retries 0` if retries are enabled (retries skip replay and run
   every goal live).
4. Once it passes, run it once with `--no-cache` to confirm the live agent
   can still reach the goal without a recording.

## How a replay works

1. **Check the starting screen** to make sure the app is on the same route.
2. **Replay each recorded action**, matching controls by role, name, test
   ID, and surrounding context. e2e waits for controls to appear and stops
   if a match is ambiguous.
3. **Check the end state** (final route plus the controls that appeared,
   disappeared, or changed state).
4. **Finish with zero model calls**, or hand off to the live agent with a
   summary of what already ran.

Typed text replays verbatim; secret fills resolve the current secret by name
and re-run authorization.

Replay finishes as soon as the recorded UI changes appear, which can happen
before content further down the page finishes loading. If the next step
checks async content, use `agent.waitFor` instead of `agent.assert`.

<Accordion title="What counts as the same route">
A route includes the origin, path, and query parameters, ignoring dynamic
IDs, tokens, timestamps, and fragments. For example,
`/orders/42?t=1727780000` and `/orders/7?t=1727780999` match as the same
route, while `?tab=notes` vs `?tab=billing` or `/products/a` vs
`/products/b` are treated as different routes.

Pages on your app's own origin are compared by path only, so recordings work
across preview URLs that share an `app.identity`.
</Accordion>

<Accordion title="How the end check verifies the screen">
- At least one recorded change must happen during replay (or the last action
  must navigate to another route). State that was already on screen before
  the step doesn't count.
- An unexpected alert that didn't happen during recording stops the replay.
- Volatile values like dates, durations, or generated UUIDs are tolerated as
  long as a stable UI change also happened. A labeled count that appeared on
  the same screen (like `3 records imported`) must still match on replay.
- Unnamed controls are matched by their position inside their named row,
  list item, or group. If a test ID changes, e2e falls back to role and name
  when that match is unambiguous.
</Accordion>

## Why a step was not replayed

Each `act` step includes cache details in the
[trace page](https://e2e.com/docs/debugging#traces) and on `result.cache`.

| Run summary | `step.cache.mode` | Meaning |
| --- | --- | --- |
| `replayed` | `self-finalized` | Replayed completely with no model call. |
| `handed off` | `agent-concluded` | Started replaying, then handed off to the agent. |
| `missed` | `missed` | Ran live from the start. |

When a step misses or hands off, the trace shows the reason and which action
stopped. `step.cache.entry` is the entry's key, and the trace page names the
test's recording file. A `truncated` recording never replays, so the default
reporter also says so on the step's line, on every run until the step changes:

```text
   ✓ adds a note > agent.act "Add a note to the first row" 9.41s · 3 model calls · not replayed: truncated
```

| Reason | What happened | What to do |
| --- | --- | --- |
| `no-entry` | No recording matches this step and params. | The next verified pass will record it. |
| `retry` | Retries run live (unless `--strict-cache` is on). | Nothing. |
| `invalid-entry` | The test's recording file is unreadable (a merge conflict in its lock, say), over 1 MiB, or edited. The test records nothing until it reads again. | Undo the edit, or delete the test's `.yml` and `.lock.json`. `npx e2e cache ls` names the file and what's wrong. |
| `truncated` | Recording hit a size or action limit ([see below](#limits-and-gaps)). | Split the step into smaller goals, or pass secrets as `Secret` handles. |
| `wrong-context` | App started on a different route than recorded. | Open the same screen before the step. |
| `target-not-found` | A recorded control didn't appear within 15 seconds. | If the UI changed, the next passing run updates the cache. Give unnamed controls labels or put them in named containers. |
| `target-ambiguous` | Multiple controls matched where the recording expected one (or the count of matching controls changed). | Give repeated controls distinct names or use unique test data. |
| `gap` | An action can't be replayed safely ([see below](#limits-and-gaps)). | Let the agent handle it live, or pass stable values via `params`. |
| `action-failed` | The app rejected a replayed action. | Check the app. |
| `action-uncertain` | A replayed action failed and may have taken effect; the agent checks the screen before acting. | Check the app. |
| `viewport-changed` | A coordinate tap/hover/drag was recorded at a different viewport size. | Keep the viewport size consistent. |
| `end-mismatch` | Every action ran, but the expected UI changes didn't match. | Check for leftover data, flaky banners, or a real regression. |

To rule out the cache when debugging a failure, run once with `--no-cache`:

<CodeGroup>
```bash npm
npx e2e run --no-cache
```

```bash pnpm
pnpm exec e2e run --no-cache
```

```bash bun
bunx e2e run --no-cache
```
</CodeGroup>

### Limits and gaps

A recording is marked `truncated` if a step took more than 50 actions, typed
a string longer than 4,096 characters (or a registered secret directly), or
interacted with a control that had no usable description.

Some actions can't be replayed safely and are marked as a `gap`, so the live
agent handles them instead:

- calling a mutating [project tool](https://e2e.com/docs/tools),
- typing a value the agent read off the screen (like a freshly generated
  one-time code or token), worked out from the current date, or read from a
  screenshot.

Values passed in the instruction or `params` (as well as values composed by
the agent) replay normally. In a one-time-code field, or the focused field
in a step that showed one, only a whole value of two or more characters
spelled out in the instruction or `params` replays; codes typed across
separate digit boxes are a gap from the first character.

## What a recording holds

Each test's recordings are one YAML file under `.e2e/cache/`, named for the
test (`tests/admin/login.e2e.ts`'s `signs in` is `admin-login-signs-in.yml`),
beside a generated `<test>.lock.json` that holds the cache keys and digests.
Don't edit the lock. Review it only when it changes with no YAML change
beside it: such a change can point a key at another step's recording. Each
step sits under its instruction, then under each target it was recorded on:

```yaml title=".e2e/cache/login-form-signs-in.yml"
test: signs in
file: tests/login-form.e2e.ts

steps:
  - act: log in with the given credentials
    params:
      email: tester@example.com
      password: { kind: secret, name: account.password, purpose: password }
    targets:
      web:
        at: /login
        do:
          - type: tester@example.com
            into: { role: textbox, name: Email }
          - secret: account.password
            into: { role: textbox, name: Password, inputPurpose: password }
          - tap: { role: button, name: Log in }
        expect:
          shows:
            - { role: status, text: Logged in }
          gone:
            - { role: button, name: Log in }
```

- `do` is what a replay does, and `expect` is the end check: up to eight
  controls that appeared and eight that went away. `at` is the route, or
  `from` and `to` when the step moved.
- A step keeps one recording per target; a recording under a new key
  replaces it. Steps are in the order the test runs them, and a repeated
  `act` shows `call: 2`, `call: 3`, and so on.
- Review the YAML, but don't edit it. An edited recording reads as
  `invalid-entry`, and the test records nothing until the edit is undone.
  Meanwhile a run that evicts another of the test's recordings drops it
  from the lock only, so it stops replaying. Its block stays in the YAML,
  and `npx e2e cache ls` names it: delete it too, and the test records
  again once the edit is undone.
  A run rewrites the file when it records, so comments are lost. Moving
  steps around is fine. A run killed while it writes leaves the pair for the
  next `read-write` run, which finishes or drops that write before it reads.
  Until then, `--strict-cache` and `npx e2e cache ls` read a step it was
  recording again as `invalid-entry`, and a step it was adding as not
  recorded, unless the test had no recordings yet: then its YAML has no
  lock, and the test's steps read as `invalid-entry`.
- To record a step again, or drop one whose instruction or params changed,
  delete it from the YAML; the next run that records drops its lock entry.
  To drop a test's recordings, delete both files: a YAML without its lock
  doesn't read.
- Two branches that each recorded into one test conflict in both files.
  Keep both sides in each, then run `npx e2e cache ls` to check the file
  reads. Where both sides recorded the same step under the same key, keep
  one side's step in the YAML and its entry in the lock: a lock that lists
  a key twice doesn't read.
- A name is the test file's folders below the top one, the file's name
  without `.e2e.ts`, and the test's titles. Two tests whose names come out
  the same (`tests/login.e2e.ts` and `e2e/login.e2e.ts`, say) get one name
  each: the second to record adds `--` and a hash of its test id. A name that leaves part of
  the test out (a title in Japanese, say, since names use ASCII letters
  and digits only, or a name cut at 80 characters) always ends in that
  hash, so it doesn't depend on which test records first.
- Recordings hold no prompts, conversations, screenshots, observed trees,
  or secret values. A secret fill stores only the secret's name. A title
  that spells a secret the run learns only mid-test is filed redacted, so
  that test records again on every run, and an agent or target name that
  spells one reads as `invalid-entry`. So does an agent context that spells
  one: a step repeated on both sides of the fill that resolves it keeps one
  recording of the two. Keep secret values out of titles, names, and
  agent context.

<Warning>
Non-secret typed values are stored verbatim. Review cache diffs before
committing or sharing them. See [cache trust](https://e2e.com/docs/reference/security#cache-trust).
</Warning>

## Modes

| Mode | Replays | Records | Default |
| --- | --- | --- | --- |
| `'read-write'` | yes | yes | locally |
| `'read-only'` | yes | no | in CI when `cache` is unset |
| `'off'` | no | no | `--no-cache` for one run |

```ts title="e2e.config.ts fragment"
cache: 'off',
// or
cache: { mode: 'read-write', dir: '.e2e/cache' },
```

`--no-cache` overrides the config for one run. In `read-only` mode, stale
entries stay untouched until a `read-write` run replaces them. A custom
`cache.store` replaces the file store and doesn't default to `read-only` in
CI. Interactive `e2e explore` and `e2e mcp` sessions don't use the cache
(except when MCP runs a test via
[`open_session {test}`](https://e2e.com/docs/reference/mcp#running-a-test)).

## Share the cache across checkouts

Point multiple checkouts or worktrees at one shared folder with
`E2E_CACHE_DIR` or `--cache-dir`. Give each checkout the same `projectId`
(or `package.json` `name`) so entries match across paths.

- A write locks the test's files and replaces them atomically, so parallel
  runs can share the directory. Checkouts share entries, so a failing run in
  any checkout evicts the shared entry and different branches with the same
  app identity overwrite each other.
- A step keeps one recording per target, so runs of one target against two
  environments (another `app.url` origin or `app.environment`) replace each
  other's recordings, and fail as `REPLAY_STALE` under `--strict-cache`.
  Give each environment its own target name.
- While the override is set, a cache committed in `cache.dir` isn't read.
- Keep one directory per project so `--strict-cache` doesn't confuse entries
  from another repo.

```bash
E2E_CACHE_DIR=~/.cache/my-app/e2e npx e2e run
```

## Commit the replay cache

<span id="commit-your-traces" />

`e2e init` adds `.e2e/cache/` to `.gitignore`. To share recordings across
your team and CI, replace that line with these two, which keep out the files
a writer works with (a lock, a record of a write in progress, a temporary
file a crash left), and commit `.e2e/cache/`:

```text title=".gitignore"
.e2e/cache/.*
.e2e/cache/*.tmp
```

CI defaults to `read-only`, so it replays committed entries without
modifying them. Review
the `.yml` files in the pull request that records them. To fold the
generated lock files in GitHub diffs, add this line to `.gitattributes`:

```text title=".gitattributes"
**/.e2e/cache/*.lock.json linguist-generated=true
```

The reader refuses YAML tags, anchors, and unknown keys. It also refuses a
lock entry edited to point a key at another step's recording, unless the
entry says its step's act or params are redacted or cut, which it cannot
check against the YAML.

Local runs keep your git diff clean: e2e only rewrites a cache file when a
step is recorded for the first time, heals after a UI change, gets evicted,
or an `e2e` upgrade changes the cache key format.

## Fail on a stale recording

By default, if a committed recording stops matching the app, the live agent
takes over and CI pays for model calls on every run until someone updates
the cache. Pass `--strict-cache` (or set `cache: { strict: true }`) to fail
immediately instead of calling a model:

<CodeGroup>
```bash npm
CI=1 npx e2e run --strict-cache
```

```bash pnpm
CI=1 pnpm exec e2e run --strict-cache
```

```bash bun
CI=1 bunx e2e run --strict-cache
```
</CodeGroup>

Strict mode fails any recording whose UI or cache key changed with
`REPLAY_STALE` (exit 2, no retry), and never writes or deletes cache files.
Alternate-key detection only applies to the built-in file store (not a
custom `cache.store`), and steps that were never recorded yet, hit a store
read failure, or have a `gap` or `truncated` recording still run live.

A step recorded by an earlier release also runs live, with the reason
`no-entry`, when the path to one of its `unique()` values contains `|` or
`}}`, or ends in `}`: strict mode can't tell that its cache key changed.
Refresh it with the steps below.

To refresh a stale recording:

1. Run the test locally in `read-write` mode without `--strict-cache` (turn
   `cache.strict` off if your config sets it).
2. Commit the updated `.yml` and `.lock.json`.

## Inspect the cache

<CodeGroup>
```bash npm
npx e2e cache ls      # one row per recording: file, target, instruction, age, actions
npx e2e cache stats   # entry count and size
npx e2e cache clear   # delete every entry
```

```bash pnpm
pnpm exec e2e cache ls      # one row per recording: file, target, instruction, age, actions
pnpm exec e2e cache stats   # entry count and size
pnpm exec e2e cache clear   # delete every entry
```

```bash bun
bunx e2e cache ls      # one row per recording: file, target, instruction, age, actions
bunx e2e cache stats   # entry count and size
bunx e2e cache clear   # delete every entry
```
</CodeGroup>

Entries an older `e2e` wrote, one `<key>.json` file each, are no longer
read, so the steps they recorded run live. A run on the built-in file
store says how many it found, `ls` counts them, and `clear` deletes them.
Run `clear` first, then record those steps again with a `read-write` run
and strict mode off (a strict run never writes): `clear` deletes the new
recordings too. If you recorded first, delete only the `<key>.json` files.

<Note>
The `cached` percentage in AI usage is the provider's prompt cache. It
lowers the cost of a model call. The replay cache skips the call.
</Note>

## Next

<CardGroup cols={2}>
  <Card title="Config reference" icon="sliders" href="/reference/config#cache">
    `mode`, `store`, `dir`.
  </Card>
  <Card title="CLI reference" icon="terminal" href="/reference/cli#e2e-cache">
    `e2e cache ls`, `stats`, `clear`.
  </Card>
</CardGroup>
