> ## 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 (for example, exceeding the size limit). |

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. 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` | Recording is unreadable, too large, or from an incompatible schema. | Run `npx e2e cache clear`. |
| `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 entry is a JSON file under `.e2e/cache/` containing the recorded
actions, target descriptions, typed text, a short summary, and the expected
end-state checks. Recordings never store prompts, transcripts, screenshots,
DOM trees, or secret values (secret fills store only the secret's name).

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

- Writes are atomic 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.
- 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, remove that line and commit `.e2e/cache/`. CI defaults to
`read-only`, so it replays committed entries without modifying them.

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.

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 cache file.

## Inspect the cache

<CodeGroup>
```bash npm
npx e2e cache ls      # one row per entry: test, target, instruction digest, 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 entry: test, target, instruction digest, 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 entry: test, target, instruction digest, age, actions
bunx e2e cache stats   # entry count and size
bunx e2e cache clear   # delete every entry
```
</CodeGroup>

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