E2EConfig
Every configuration key, its default, its valid range, and the environment variables.
e2e.config.ts configures the runner: the targets tests run on, the app each
one tests, the agents, and the replay cache. Export an object with
satisfies E2EConfig, which checks its shape and keeps its inferred types.
The runner validates the config again at load, including ranges and rules
TypeScript cannot check.
For the options most projects change, see Configure the project.
import type { E2EConfig } from 'e2e';
import { web } from '@e2e-dev/web';
export default {
targets: [
{
name: 'web',
engine: web({ browser: 'chromium' }),
app: { url: process.env.APP_URL ?? 'http://localhost:3000' },
},
],
} satisfies E2EConfig;Reference
Top level
The full declaration is E2EConfig.
- An unknown key at any level is
INVALID_CONFIG. There is no top-levelappkey: each target declares the app it tests. - Every numeric value must be a safe integer.
- An optional key takes a value or is left out. Under
exactOptionalPropertyTypes,undefinedis a type error, sostore: process.env.CACHE_URL && createStore(...)fails to compile. At runtime,undefinedcounts as unset. - The target’s
appfields also acceptundefinedin their types, so they can readprocess.envdirectly. Spread any other key that depends on the environment in only when it has a value:
export default {
targets: [{ engine: web(), app: { url: 'http://localhost:3000' } }],
...(process.env.CACHE_URL === undefined ? {} : { cache: { store: createStore(process.env.CACHE_URL) } }),
} satisfies E2EConfig;projectId
A stable id for the project.
projectId: 'acme-web', // default: the root package.json name- 1 through 256 characters.
- Without a
namein the rootpackage.json, it falls back tounportable-<sha256 of the project root, 32 hex>.
tests
The test file globs, relative to the project root.
tests: ['tests/**/*.e2e.ts', '!tests/wip/**'], // default: 'tests/**/*.e2e.ts'- A glob takes
*,?, and a whole**segment.?matches one Unicode code point, including an emoji. - An entry that starts with
!excludes. The example selects every test file except those undertests/wip/. - A file is selected when an including glob matches it and no exclusion does, whatever the order of the list.
- Discovery visits only directories that could match. It never enters a
directory an exclusion takes whole, skips
node_modules, and ignores symlinks. - A dot directory is included only when a glob segment starts with a dot.
- The default selects TypeScript only. For JavaScript tests, set
'tests/**/*.e2e.js'(JavaScript).
timeout
The deadline of one test attempt, in milliseconds.
timeout: 180_000, // default: 120000launchTimeout
The budget for engine init and attempt start, in milliseconds.
launchTimeout: 90_000, // default: 60000actionTimeout
The budget of every engine operation, in milliseconds.
actionTimeout: 10_000, // default: 30000- A targeted agent action is bounded by the smaller of
actionTimeoutand 15 s. - A call’s own
timeoutoption wins over it.timeout: 0sets no deadline for that call; the test timeout, orcleanupTimeoutinafterEach, still bounds it. --action-timeout <ms>overrides it for one run.
assertionTimeout
The default expect deadline, in milliseconds.
assertionTimeout: 10_000, // default: 5000- A matcher’s own
timeoutoption wins over it.timeout: 0sets no deadline for that matcher; the test timeout, orcleanupTimeoutinafterEach, still bounds it. --assertion-timeout <ms>overrides it for one run.
cleanupTimeout
The budget of each afterEach hook, fixture teardown, and engine cleanup, in
milliseconds.
cleanupTimeout: 60_000, // default: 30000retries
Retries per test.
retries: 2, // default: 1 in CI, else 0- 0 through 10.
failOnSkippedFailure
Fails the run with exit code 1 when a test skips a retry after an earlier failed attempt.
failOnSkippedFailure: true, // default: false- The test keeps its
skippedstatus and reason. - Its failures remain in the report, and the CLI shows them under
Skipped After Failurewith either setting. - Clean skips, successful retries, and engine cleanup diagnostics do not trigger it.
A skip after a failed expect.soft needs no option: it
fails the attempt.
maxDuration
The wall-clock budget for running the tests, in milliseconds. It stops a run that takes too long.
export default { targets, maxDuration: 900_000 } satisfies E2EConfig; // default: none- At most 2147483647 (about 24 days).
- The clock starts when the tests start. The app command’s
startupTimeoutbounds app startup instead. - Once the time is spent, the runner dispatches nothing more. The running
tests end as
interrupted, and the tests not started are skipped with causetime-limit. The run records aRUN_TIMEOUTerror and exits 1. --last-failedruns the interrupted and skipped tests next.--max-duration <ms>overrides it for one run.e2e exploreignores it and keeps its own--timeout.
workers
Parallel workers.
workers: 4, // default: 1 in CI, else half the cores- 1 through 1024.
- Locally the default is
max(1, floor(availableParallelism() / 2)). - An engine may cap it lower:
workersnever exceeds what a target’s engine declares. - With more than one worker, each target’s files start longest first by the
timings history. A file with no time starts
before the timed ones. With
--changed-since, the likeliest files start before that, as Start the likeliest first says.
reporters
Output renderers and reporter objects.
reporters: ['list', 'junit'], // default: ['list']An unknown id is INVALID_CONFIG. See Reporters.
targets
A target is one named surface tests run on: the app under test and the
engine that drives it. targets is required and holds at least
one.
targets: [
{ name: 'chromium', engine: web(), app: { url: 'http://localhost:3000' } },
{ name: 'firefox', engine: web({ browser: 'firefox' }), app: { url: 'http://localhost:3000' } },
],{ engine: web(), app: { url } }is a complete target.- A test whose
requiresnames a capability the target lacks is skipped for it. Atest.setupthat a selected test depends on must be runnable there, or selection fails withCOLLECTION_ERROR.
The full declaration is Target.
name
The id --target, reports, sessions, and artifact paths use.
name: 'chromium', // default: the platform- ASCII letters, digits,
_,-, and., not only dots (.and..are path segments). - Unique across targets. Two targets on one platform need names.
platform
The platform label.
platform: 'web', // default: inherited from the engine- Required for a target without an engine.
- When the target and its engine both name one, they must agree.
engine
The engine driving the surface: web(...), mobile(...), or any
defineEngine handle.
engine: web({ browser: 'firefox' }),A target without an engine runs through agent tools only. A target with app
and no engine is INVALID_CONFIG.
The app under test
A target declares the app it tests in app; the engine only drives it. A
browser target names the URL it opens, a device target the installed app or
the build it launches. The runner resolves app at config load.
targets: [
{
name: 'web',
engine: web({ viewport: { width: 1440, height: 900 } }),
app: {
url: 'http://localhost:3000',
command: { executable: 'npm', args: ['run', 'dev'] },
readyUrl: 'http://localhost:3000/health',
},
},
{
name: 'ios',
engine: mobile({ platform: 'ios' }),
app: {
bundleId: 'com.example.app',
appPath: './build/App.app',
launchArguments: ['-e2e', 'YES'],
permissions: { camera: 'grant' },
},
},
],Each engine checks the keys at config load, with INVALID_CONFIG naming the
target. A target with app needs an engine.
- A
web()target needsapp.urland refusesbundleId,appPath, andlaunchArguments. - A
mobile()target needsapp.bundleIdorapp.appPath.app.urlon a mobile target is not supported yet. - An unknown key in
apporapp.commandfails with a did-you-mean.
The old spellings are unknown keys and fail at config load with
INVALID_CONFIG: web({ url }) and the other app options of web() and
mobile(), mobile({ app }) (now app.bundleId), an app key directly on the
target, a top-level app or url, and services anywhere.
url
The base URL: app.open() opens it and relative navigation resolves against
it.
url: 'http://localhost:3000',- WHATWG-normalized; no userinfo, query, or fragment.
- A missing scheme becomes
https://, orhttp://for a loopback host. - Plain HTTP is accepted for loopback hosts only.
- Port
0on127.0.0.1or[::1]asks for a free port. - Its origin scopes engine request credentials, and its site scopes observed frames: see the app’s site.
bundleId
The installed app a device launches: a bundle id, an Android package name, or
a display name the device resolves (Settings).
bundleId: 'com.example.app',A link is INVALID_CONFIG: a test opens one with device.openLink.
appPath
The build the suite runs against, an iOS .app bundle or an Android .apk,
resolved against the project root.
appPath: './build/App.app',Without bundleId, the app it installs is the one launched. See
the device engine for when it is installed.
identity
The stable identity keying replay cache and session entries.
identity: 'checkout-web', // default: the URL's origin and base path, else bundleId, else appPathSet a stable value to reuse entries across preview URLs or versioned build
paths. With a free port, the default derives from the declared
:0, so cache and session entries do not churn with the port.
Different apps must have different identities. A shared identity replays recordings across them.
environment
Labels the target in the report and joins the cache and session identity digest. It never gates a run.
environment: 'staging', // default: 'test' for a local host or no URL, else 'production''test','staging', or'production'.- A local host is a loopback,
.localhost, or.testhost.
launchArguments
Arguments every fresh launch passes the app: app.open(), app.restart(),
and app.clearState().
launchArguments: ['-e2e', 'YES'],Arguments that select a build mode change what the app is: give each mode its
own identity.
permissions
Permissions the app holds, by name.
permissions: { camera: 'grant' },Each is 'grant', 'deny', or 'reset'.
- A
mobile()target sets each one before every fresh launch. See permissions. - A
web()target takes'grant'only and grants it to every page of the attempt, on any origin. Headless Chromium refuses a permission left out. See Granting browser permissions.
A browser provider or connect takes the chromium names: the engine drives
it over CDP, Lightpanda included.
command
The process the runner starts before the first test and stops on every exit path: a dev server, or Metro for a debug build.
command: {
executable: 'pnpm',
args: ['dev', '--port', '{port}'],
inheritEnv: ['STRIPE_*'],
startupTimeout: 120_000, // default: 60000
},executableis resolved withPATHand never shell-interpreted.argspass verbatim.{port}inargsandenvvalues expands to the port ofurl.cwdresolves from the project root.- The child inherits only
PATH,HOME, the temp-directory variables, the variablesinheritEnvmatches, andcommand.env. Pass what the app needs explicitly. inheritEnvtakes exact names or prefixes ending in*('STRIPE_*'). It copies a variable only when it is set.envwins over an inherited value.- Every
argsentry andenvvalue is a string. Anundefinedenvvalue is dropped. startupTimeoutis the budget of thereadyUrlprobe.shutdownTimeoutis the grace period before force-kill.- In
e2e run, a command that exits after readiness fails the run withAPP_UNREACHABLEif a dependent target has unfinished work. This includes exit code 0 and termination by a signal. The runner interrupts active tests and skips queued tests only for those targets. Targets that have finished their work ignore the exit. logreceives the process’s stdout and stderr, appended, resolved from the project root. It must stay inside the project root.- With a
log, startup timeouts and command exits quote the lines appended since the command started. A log of up to 40 lines inside 8 KiB is quoted whole. Otherwise the quote keeps up to 20 lines from each end, with[startup output omitted]between them, and for a log past 8 KiB those lines come from its first and last 4 KiB. An empty or unreadable log producesno output in <log>. A shared log can include lines from other processes. The quote replacescommand.envandinheritEnvvalues of at least 4 characters with<secret:NAME>markers. Withoutlog, these errors ask you to set one. A command that fails to spawn reports the spawn error instead. reuseExisting: when the readiness URL already answers before the command starts, the runner uses that process. It starts nothing and stops nothing. CI ignores it, with a notice, and always starts the command.- Targets declaring the same command share one process, probed at the first
declaring target’s
readyUrl. - The runner never terminates a process it did not start.
log holds the raw, unredacted output. Keep it in an ignored directory.
The full declaration is CommandConfig.
readyUrl
The URL polled until command is ready, at a 200-499 status.
readyUrl: 'http://localhost:3000/health', // default: url- Required without a
url. {port}in it is the port ofurl.
The app’s site
A test or the agent may open any http(s) URL, and about:blank. Every other
scheme (file:, data:, javascript:, view-source:, blob:) is
POLICY_DENIED. The site of url is its registrable domain:
app.example.com and auth.example.com are one site. Child frames off the
site stay out of observations.
The browser engine’s headers and
basicAuth are scoped tighter, to the origin of
url (scheme, host, and port, the run’s free port included) plus the
origins you list. See
request credentials.
Free ports
A url on a literal loopback address with port 0 (http://127.0.0.1:0,
http://[::1]:0) asks the run for a free TCP port. The runner picks one when
the config loads. It substitutes the port wherever the declaration used it:
the base URL, the default readyUrl, and the report. The command must take
the port through {port} in args or env.
engine: web(),
app: {
url: 'http://127.0.0.1:0',
command: { executable: 'pnpm', args: ['dev', '--port', '{port}'], env: { PORT: '{port}' } },
},localhost:0isINVALID_APP_URL: it may resolve to an address other than the one the command binds. Write the address the command will bind.- Each target asking for port
0gets its own port and its own process. Two targets that declare the same command on a fixed port share one. - The default
identityderives from the declared:0. - Tests read the allocated URL from
app.baseUrl.
services
This version starts no dependency processes (a database, an API mock, a dev
server several targets share), and services is an unknown key wherever it
appears. Start them before the run, or have app.command start a script that
brings them up and serves the app. A services API returns in a later release.
output
The directory everything a run writes about itself goes under, resolved from the project root.
output: 'test-results/e2e', // default: '.e2e'--output <dir> on e2e run and e2e explore
overrides it for one run.
- A run that stops before its tests start writes nothing here. Such stops are
a selection that matches no test (
NO_TESTS, a mistyped--grep), a collection error, a target that cannot record what it asks for (UNSUPPORTED_ARTIFACT),NO_LAST_RUN, an app command that fails to start, or an interrupt. The previous run’sreport.json,ai-trace.json, andresults/stay as they were, so--last-failedstill reads the last run that executed. - An
e2e mcpsession writes its attempt’s artifacts underresults/mcp/and never clears it. - The replay cache stays in
cache.dirwhateveroutputsays, so moving the results never moves the recordings. e2e initwrites.gitignoreentries for the default.e2e/paths only. Withoutputset elsewhere, add that directory to.gitignoreyourself.
A run clears and owns part of the output directory. So the config load fails
with INVALID_CONFIG, naming the reason, when the directory:
- is the project root, or outside it;
- is a file, or a path under one (a missing directory is created);
- is the cache directory (
cache.dir,--cache-dir, orE2E_CACHE_DIR) or inside it, or would hold it underresults/,sessions/, orvideos/; - holds a directory a
testsglob scans (output: 'tests'with the defaulttests/**/*.e2e.ts).
Paths are compared with symlinks resolved. An absolute path spelled through a
symlink (/tmp for /private/tmp on macOS) names the same directory as its
target. A symlink whose target does not exist yet is followed too, so an
output through one that points outside the project root is refused.
The removed --artifacts <dir> flag fails with the --output it maps to. The
report used to go to the directory’s parent, so --artifacts out/artifacts is
--output out. A parent an output cannot be (the project root, or outside it)
maps to --output .e2e.
artifacts
artifacts says where artifacts go, not which are made. { store } hands
every artifact to a host store as it is produced; without one, files stay
local only.
artifacts: {
store: {
async put(artifact) {
const key = await bucket.upload(artifact.path, artifact.bytes);
return { ref: key };
},
},
},traceandvideochoose the recordings. The runner captures a failure’s screenshot and screen text whenever the engine can.- Each worker constructs its own store from the config module.
- A failed
putorputLinknever fails the run.
The removed forms fail with INVALID_CONFIG naming what replaced them:
The declarations are under ArtifactsConfig.
put
Receives every artifact once it is complete on disk and returns a reference
the report records as ref beside the local path.
async put(artifact) {
return { ref: await bucket.upload(artifact.path, artifact.bytes) };
},- Required on every store.
artifact.redactionis the report’s label. A store that exports only what the runner vouches for keeps back anincompleteartifact: a video or a download the runner did not rewrite.
putLink
Receives a video a hosted service keeps (a
provider’s own recording). Such a video is a link with
no bytes, so put never receives it.
async putLink(link) {
return { ref: await index.record(link.url, link.attemptId) };
},- Optional. Called for each link once the attempt stopped the recording.
- Its
reflands on the report’s artifact besideurl. - A passed attempt’s link under
retain-on-failureis never handed over, since the report leaves it out too.
Recording
trace and video choose what is recorded, with one set of modes.
trace: 'on',
video: 'retain-on-failure',
targets: [
{ name: 'chromium', engine: web(), app: { url } },
{ name: 'firefox', engine: web({ browser: 'firefox' }), app: { url }, video: 'on-first-retry' },
],/** Which tests keep a trace page, or which attempts record a video. */
export type RecordingMode = 'off' | 'on' | 'retain-on-failure' | 'on-first-retry' | 'on-all-retries';The names are Playwright’s use.trace and use.video modes. Under a retry
mode, a test with retries: 0 records nothing, and neither does a failure
the runner does not retry, such as LAUNCH_TIMEOUT. When such a test runs,
the run prints one notice per kind at plan time: no traces (or videos) will
be recorded for it.
Four places set a mode, lowest first. Each replaces the one before it, for
trace and video alike:
traceorvideoat the top of the config.- A target’s
traceorvideo. --trace [mode]or--video [mode]one2e run, over the config and every target. A bare flag ison.- A test’s or describe’s own
traceorvideooption, innermost wins:test('checkout', { video: 'on' }, ...).
- A serial group records as one unit, so its members cannot set
traceorvideo(aCOLLECTION_ERROR, likeretries). The value on the serialdescribe, or on a group around it, applies to every member. e2e exploreis one attempt and uses the target’s mode,--traceand--videoincluded, so a retry mode records nothing there.- An
e2e mcpsession writes no trace and never records video from the configured mode. Its recordings are the onesstart_recordingandstop_recordingmake. traceandvideo, at the top or on a target, enter neither the config digest nor a replay’s cache key. Turning one on or off never invalidates cached replays.
The old trace spellings fail with INVALID_CONFIG naming the mode they
meant, wherever a mode goes (the config, a target, a test, --trace):
'all' and { record: 'all' } are 'on', and 'retries' and { record: 'retries' } are 'on-all-retries'.
trace
Which tests keep a trace page.
trace: 'on', // default: 'retain-on-failure'- The default is the same locally and in CI.
- A trace page is markdown,
trace.mdin the test’s directory under<output>/results/, such as.e2e/results/checkout-applies-the-coupon-1a2b3c4d5e6f7a8b/trace.md: every step with what it did, the cache’s decisions, what the app logged, and the screen at failure. - It works on every engine. Debugging shows one.
video
Which attempts record a video.
video: 'retain-on-failure', // default: 'off'- Where the mode is set decides what an engine that cannot record does. See Engines that cannot record.
- A video costs CPU and holds what the screen showed, secrets included, so it is always asked for.
Engines that cannot record
Before any test starts, the run grades every target. Where a video mode
was set decides what an engine that cannot record video does:
- Set at the top of the config or with
--video: the mode applies to the targets whose engine can record it. The run prints one notice at plan time naming the targets that cannot, and runs them without video. - Set on a target, or on a test that will run on that target: the mode is
required. A target whose engine cannot record it fails the run with
UNSUPPORTED_ARTIFACT, naming the target and, for a test’s, the test.
Only a mode that records on some attempt counts: a run whose tests all
resolve to off, or to a retry mode with retries: 0, asks nothing of the
engine.
What a video writes
- Each segment carries
startedAt, sostep.startedAt - artifact.startedAtis a step’s offset into it. - A recording masks nothing and is recorded with
redaction: 'incomplete'.
Under retain-on-failure a link is left out of the report of a passed
attempt, but the service still holds the recording.
agents
Named agents, each one plain object: the built-in agent’s options, or
{ executor } for a custom brain.
import type { E2EConfig } from 'e2e';
import { web } from '@e2e-dev/web';
import { gateway } from 'ai';
import { houseBrain } from './house-brain.ts';
export default {
targets: [{ engine: web(), app: { url: 'http://localhost:3000' } }],
agents: {
default: { model: gateway('openai/gpt-6-luna-fast') },
ux: { model: gateway('openai/gpt-6-luna-fast'), system: 'Check labels, contrast, and keyboard access.' },
thorough: { model: gateway('anthropic/claude-opus-5'), context: 'Verify every claim on screen.' },
buyer: {
model: gateway('openai/gpt-6-luna-fast'),
system: 'You are a first-time buyer.',
context: 'Plans are called tiers. Billing lives under Settings.',
maxSteps: 40,
},
house: { executor: houseBrain, model: gateway('openai/gpt-6-luna-fast'), maxModelCalls: 10 },
},
} satisfies E2EConfig;- Tests use the
defaultagent unless you select another: withe2e run --agent <name>, a test or group option, or anagent.*call. A test with{ agent: ['buyer', 'admin'] }runs once for each agent. defaultexists even when the config declares no agents, but has no model.- Every entry starts from the built-in defaults. Agents do not inherit from
each other:
uxabove gets nocontextfromdefault. A key left out of an entry is the default value, never another entry’s. - Each worker constructs its own agents from this config module.
- Names may contain ASCII letters, numbers,
_,-, or., and are never only dots: a name is an artifact path segment.
See Agents and personas. The declarations are under
AgentConfig.
model
An AI SDK model instance. There is no implicit default.
model: gateway('openai/gpt-6-luna-fast'),Construct the model in your config with an AI SDK provider. Every provider
that supports tool calls works, see
AI SDK providers. For subscription sign-in, use
the e2e/oauth/* models.
- Reports record
providerandmodelIdper step. - Each worker constructs its own instance from the config module. A digest
that differs between the runner and a worker is
CONFIG_NOT_DETERMINISTIC. - A string is
INVALID_CONFIGnaming the constructor to write. - An agent never falls back to
default’s model. See Resolution order.
See Models and ModelInstance.
judge
The model for non-exploring assert, waitFor, and extract. Built-in
exploring assertions use agents.<name>.model, even when judge is set.
judge: gateway('anthropic/claude-opus-5'), // default: model- Judgments allow 8192 output tokens per call.
- A judgment sees the instruction, its params, the agent’s context, and the current screen with its location.
See A judge of its own.
context
What the app calls things, told to every model call this agent makes, act turns and judgments alike.
context: 'Plans are called tiers. Billing lives under Settings.',At most 16384 bytes.
system
How the acting agent should work, appended to the built-in rules. Only the act loop reads it.
system: 'You are a first-time buyer.',With executor it is INVALID_CONFIG: the executor brings its own prompt.
tools
Project tools from defineTool (e2e/agent), offered beside the built-in
toolset.
tools: { lookupOrder },With executor it is INVALID_CONFIG: the executor brings its own tools.
executor
A custom brain agent.act() dispatches to instead of the built-in agent.
house: { executor: houseBrain, model: gateway('openai/gpt-6-luna-fast'), maxModelCalls: 10 },model,judge,context, and the budgets still apply; judgments need a model.systemandtoolsbeside it areINVALID_CONFIG.maxModelCallsbounds the model turns of one step.- A
modelorjudgethat differs from the one the executor brought isINVALID_CONFIG.
See Custom executors.
maxSteps
Committed actions per agent call.
maxSteps: 40, // default: 251 through 100.
maxModelCalls
Model requests per agent call.
maxModelCalls: 10, // default: 251 through 100.
judgmentTimeout
The deadline of one assert, waitFor, or extract call, in milliseconds.
judgmentTimeout: 60_000, // default: 30000Raise it for a slow judge. Engine operations keep actionTimeout.
maxObservationBytes
The observation payload ceiling for act turns and judgments.
maxObservationBytes: 524_288, // default: 2621441024 through 16777216.
maxInputTokens
Input tokens per model request.
maxInputTokens: 128_000, // default: 64000- 1 through 1000000.
- A dense screen is cut to fit under it.
providerOptions
Provider options every model call carries, such as a reasoning effort.
providerOptions: { openai: { reasoningEffort: 'low' } },OpenAI and Azure OpenAI Responses calls also carry store: false and a prompt
cache key unless set here.
Removed options
An unknown key (the error names the nearest known one), a removed key, or a
value in an old shape fails the config load with INVALID_CONFIG:
filters
Test filters that leave out the tests a change can’t affect,
applied in order when the run passes --changed-since.
import type { E2EConfig } from 'e2e';
import { web } from '@e2e-dev/web';
import { gateway } from 'ai';
import { decisionFilter } from '@e2e-dev/decision';
export default {
targets: [{ engine: web(), app: { url: 'http://localhost:3000' } }],
filters: [decisionFilter({ model: gateway.decisionModel('typesafe-ai/jev') })],
} satisfies E2EConfig;Which tests always run is on
Test filters. A name follows the target name
rules, is at most 256 characters, and is unique among filters.
The declarations are under TestFilter, exported from e2e.
credentials
Named accounts. Each entry is a username and a password the model never sees.
credentials: {
admin: { username: 'admin@example.com', password: () => readFile('.secrets/admin', 'utf8') },
},- Credentials and secrets are separate namespaces.
secrets.get(name)returns asecretsentry only. A credential’s password is reachable only ascredentials.user(name).password. - The agent, the replay cache, and the reports know that password as a secret
named
<name>.password(<secret:admin.password>). Socredentials.adminandsecrets.admincan both exist.
See Authentication. The declarations are under
CredentialConfig.
username
The account’s plain username.
username: 'admin@example.com',E2E_USER_<NAME>_USERNAME wins over the config value. With neither, the
entry is INVALID_CONFIG.
password
The account’s password: a static value, or a SecretProvider function.
password: () => readFile('.secrets/admin', 'utf8'),- A static password is at least 6 characters (code points), like a
secret, or
INVALID_CONFIG. - A
SecretProviderruns on every authorized fill (a vault lookup, a freshly computed TOTP). The config digest records it by name only. A provider returning fewer than 6 characters fails the fill withAUTH_CREDENTIAL_UNAVAILABLE. E2E_USER_<NAME>_PASSWORDwins over both.
credentials.user()
Resolves a configured entry into a Credential in a test.
const admin = credentials.user('admin');- The username is a plain string. The password is an opaque
Secretthat test code cannot read, accepted only bylocator.fillandagent.actparams. - An unconfigured name throws
AUTH_CREDENTIAL_UNAVAILABLE.
secrets
Named values the model must never see: API keys, tokens, anything sourced from the environment.
secrets: {
apiKey: () => readFile('.secrets/api-key', 'utf8'),
},- A provider runs on every authorized fill (a vault lookup, a freshly computed TOTP). The config digest records it by name only.
- An
E2E_SECRET_<NAME>override wins over both. - Every entry must resolve to a string of at least 6 characters (code points)
or a function; anything else is
INVALID_CONFIG. A provider’s value is held to the same minimum at fill time, withSECRET_UNAVAILABLE. - The minimum exists for redaction. Every occurrence of a value becomes
<secret:name>, so a shorter value would take ordinary text in reports and output with it. - Two entries whose names map to one variable, like
api-keyandapi_key, areINVALID_CONFIG.
The declarations are under SecretConfig. See
Secrets that are not passwords.
secrets.get()
Returns the opaque Secret for a configured entry.
await screen.getByLabel('API key').fill(secrets.get('apiKey'));- It has no plaintext accessor and is accepted only by
locator.fillandagent.actparams. - The runner fills the field, masks the value in every observation, and redacts it from logs, traces, and the report.
- An unconfigured name throws
SECRET_UNAVAILABLE.
Secrets in engine options
While e2e.config.ts evaluates, before any run exists, secrets.get(name)
returns a reference by name that an engine option can hold.
engine: web({ basicAuth: { username, password: secrets.get('previewPassword') } }),- The engine declares it. When no
secretsentry has the name, the config load fails withINVALID_CONFIG. A credential’s password is not one: declare a value an engine option needs undersecrets. - The engine resolves the value when each attempt starts, so a provider runs again every time. The value then joins the attempt’s redaction. It goes to the engine, not onto the page, so it brings none of a fill’s screenshot restrictions.
- The digest records the name only.
- The reference is not the value. Turned into a string (a template literal,
String(),+,JSON.stringify), it throwsINVALID_CONFIG. So does a reference in anargsentry orenvvalue ofapp.command, which takes strings and placeholders only. Read a value a string needs, such as an app’s API key, fromprocess.envyourself.
cache
Replay cache mode or options. In read-write mode the replay cache records an
agent.act() only after a later verification passes, such as a locator
assertion or agent.assert().
cache: { mode: 'read-write', dir: '.e2e/cache', strict: true },A bare string is shorthand for { mode }: cache: 'read-only'. See
Caching. The declarations are under CacheConfig.
mode
What the replay cache reads and writes.
cache: 'read-write', // default: 'read-write' locally, 'read-only' in CI- An explicit mode overrides the default. Set
'read-write'explicitly when CI restores the cache from its own cache service. --no-cachewins over both and disables caching for the run.
store
A custom entry store that replaces the file store.
cache: { store: createStore(cacheUrl) },- Each worker constructs its own.
- Exempt from the CI demotion: it states its own trust through
writable. --cache-dirbeside it isINVALID_CONFIG, andE2E_CACHE_DIRis ignored.
CacheStore, CacheReadResult, TraceEntry, and ActionTrace are exported
from e2e.
dir
The file store directory, resolved against the project root.
cache: { dir: '.cache/e2e' }, // default: '.e2e/cache'- It stays where it is whatever
outputsays. --cache-dirandE2E_CACHE_DIRreplace it.
strict
Fails a step whose recording exists but no longer replays with
REPLAY_STALE, instead of handing it to the agent.
cache: { strict: true }, // default: false--strict-cacheturns it on for one run.- The run then never writes the cache.
See Fail on a stale recording.
Commit the replay cache
e2e init adds .e2e/cache/ to .gitignore, so committing entries is
opt-in. Remove that line to share replays with CI and teammates. CI stays
read-only unless cache: 'read-write' is set. See
Caching.
Run limits
The report’s run.limits block records the ceilings a run enforced. There is
no limits key: two fields come from the agents, and the runner fixes the
rest.
Per-call options may only lower an agent’s budgets.
Environment variables
The runner reads a closed set, listed on the
Environment variables page. E2E_USER_<NAME>_USERNAME
and E2E_USER_<NAME>_PASSWORD override a credential, E2E_SECRET_<NAME> a
secret, and CI switches the defaults below.
Resolution order
The built-in agent checks for a missing model once per run, when the agent
fixture is first acquired, and stops the run with exit 2. A custom
executor can implement act and assert without a model.
waitFor and extract still require one.
CI
CI mode is on unless CI is unset, blank, 0, or false.
Loading
How the runner finds the config and loads it and the files it imports.
Finding the config file
--config <path>selects an explicit file.- Otherwise the runner searches the working directory and each parent for
e2e.config.ts,e2e.config.mts,e2e.config.js, ore2e.config.mjs, stopping at the repository root. - A TypeScript config wins over a JavaScript one in the same directory, so
the
e2e.config.jsthattscemits besidee2e.config.tsis ignored. - Both TypeScript names, or both JavaScript names, in one directory is
CONFIG_AMBIGUOUS. - The selected file’s directory is the project root.
.env files
e2e loads no .env file itself. Load one at the top of e2e.config.ts with
Node’s process.loadEnvFile(). Every worker imports the config again, so the
variables reach the workers too:
process.loadEnvFile('.env');It throws when the file is missing; guard it with existsSync from
node:fs when only some machines have one. The path resolves against the
directory e2e runs from, but workers start in the config’s directory. To run
from a subdirectory, pass new URL('.env', import.meta.url) instead.
Module format
- Config and test files run as ESM whatever the nearest
package.jsontypesays. So does every.ts,.mts,.tsx, and.jsxfile they reach: a helper by path, a package that exports its.tssource by name, or a.tsfile a CommonJS file requires. - A
.ctsfile is CommonJS, written withrequire,import x = require(), andexport =; itsimportstatements are not turned intorequirecalls. - A
.tsfile written withrequireormodule.exportsfails to load: name it.cts. - JavaScript keeps the format its package declares.
JavaScript
A config and tests can be plain JavaScript, with no tsconfig.json:
import { web } from '@e2e-dev/web';
import { gateway } from 'ai';
/** @type {import('e2e').E2EConfig} */
export default {
tests: 'tests/**/*.e2e.js',
agents: { default: { model: gateway('openai/gpt-6-luna-fast') } },
targets: [{ engine: web(), app: { url: 'http://localhost:3000' } }],
};- Name the config
e2e.config.jsore2e.config.mjs(Finding the config file). - Write ES modules. Set
"type": "module"inpackage.json, or name the files.mjs. Without either, Node.js warns on every load that it reparsed the file as ESM. - Set
tests: the default selects only*.e2e.ts. Use'tests/**/*.e2e.mjs'for.mjstests. List'tests/**/*.e2e.ts'as well to run both kinds while you move a suite. - The
@typecomment does the job ofsatisfies E2EConfig: an editor completes keys and shows their documentation. Test fixtures get their types from thetestimport, with no annotation. - The runner never type-checks. For editor errors, add
// @ts-checkto a file, or"checkJs": trueto ajsconfig.json. - A JavaScript file imports a TypeScript helper by its
.tsname ('./helpers.ts'), not.js; see Import resolution. UndercheckJs, that import also needs"allowImportingTsExtensions": trueand"noEmit": true.
Import resolution
e2e compiles TypeScript and JSX itself. An import in such a file resolves the way TypeScript resolves it:
./helper.jsand./helperloadhelper.ts, and./view.jsxloadsview.tsx../libloads the filelib/package.jsonnames asmain, elselib/index.ts.- A bare import that
tsconfig.jsonmaps throughpathsorbaseUrlloads the mapped file. - A
#import or package export that names a missing./x.js,./x.jsx, or./xloads itsx.tsorx.tsxsource when imported. - A
#import or package export that names a directory, or a subpath of a package withoutexportsthat is a directory (@acme/db/enums), loads it the way./libloads. Under Yarn PnP that package subpath still fails. - A
require()of any of the last two fails as Node.js reports it. - An import written in a JavaScript file resolves as Node.js resolves it.
tsconfig.json
- The
tsconfig.jsonis the nearest one above the file. When that one hasreferencesand does not include the file itself (as Vite writes it), it is the transitively referenced one that does. - References are visited in declaration order, and cycles are skipped. If none owns the file, the nearest config remains the fallback.
- e2e reads its
paths,baseUrl,jsx,jsxFactory,jsxFragmentFactory,jsxImportSource,experimentalDecorators,emitDecoratorMetadata,useDefineForClassFields(andtarget, which sets its default), andverbatimModuleSyntax, once per process and again for each sessione2e mcpopens. - A
tsconfig.jsone2e cannot read, such as one thatextendsa package that is not installed, is skipped with a warning. - TypeScript inside an installed package compiles without the project’s
tsconfig.json.
What fails to compile
- e2e refuses, naming the file and line, two things it cannot compile:
auto-accessors (
accessor x = 1) and decorators withoutexperimentalDecorators. - Each file compiles on its own, without type information. So a type
imported without
import typefails to load when the import stays in the output (a decorated member’s type underemitDecoratorMetadata, a re-exported type). The error names the import to change. - A JSON file imported without
with { type: 'json' }loads with its parsed contents as the default export. - Stack traces and failure locations point at the TypeScript source, through
another loader’s source map too (
NODE_OPTIONS=--import tsx).
Types
E2EConfig
export interface E2EConfig {
/** Stable project id, 1 through 256 characters; defaults to the root `package.json` name. */
projectId?: string;
/** The surfaces tests run on; required, at least one, each naming its engine. */
targets: readonly Target[];
/** Test file globs relative to the project root (`*`, `?`, and a whole `**` segment; a leading `!` excludes); default every `*.e2e.ts` under `tests/`. */
tests?: string | readonly string[];
/** Test attempt deadline in milliseconds; default 120000. */
timeout?: number;
/** Engine init and attempt start budget in milliseconds; default 60000. */
launchTimeout?: number;
/** Budget of every engine operation in milliseconds; default 30000. */
actionTimeout?: number;
/** Default `expect` deadline in milliseconds; default 5000. */
assertionTimeout?: number;
/** Budget of each `afterEach` hook, fixture teardown, and engine cleanup in milliseconds; default 30000. */
cleanupTimeout?: number;
/** Retries per test, 0 through 10; default 1 in CI, else 0. */
retries?: number;
/** Fail the run when a test skips a retry after an earlier failed attempt; default false. */
failOnSkippedFailure?: boolean;
/** Wall-clock budget for running the tests, in milliseconds; default none. */
maxDuration?: number;
/** Parallel workers, 1 through 1024; default 1 in CI, else half the cores. An engine may cap it lower. */
workers?: number;
/** `{ store }` hands every artifact to a host store as it is produced. */
artifacts?: ArtifactsConfig;
/** Which tests keep a trace page; default `retain-on-failure`. */
trace?: RecordingMode;
/** Which attempts record a video; default `off`. */
video?: RecordingMode;
/** The results directory, relative to the project root; default `.e2e`. */
output?: string;
/** Output renderers and reporter objects; default `['list']`. */
reporters?: readonly (BuiltinReporter | Reporter)[];
/** Named agents: the built-in agent's options, or `{ executor }` for a custom brain. */
agents?: Readonly<Record<string, AgentConfig>>;
/** Test filters, in order, run with `--changed-since`: each judges the tests the one before it kept. */
filters?: readonly TestFilter[];
/** Replay cache mode or options; default `read-write`, `read-only` in CI. */
cache?: CacheMode | CacheConfig;
/** Named accounts: a username and a password the model never sees. */
credentials?: Readonly<Record<string, CredentialConfig>>;
/** Named values the model must never see: API keys, tokens, anything sourced from the environment. */
secrets?: Readonly<Record<string, SecretConfig>>;
}Target
/**
* One named test target: the app under test and the engine that drives it.
* Without an engine, the target supports agent tools only.
*/
export interface Target {
/** Label in reports and for `--target`; defaults to the platform. */
name?: string;
/** Platform label; inherited from the engine when omitted. */
platform?: string;
/** The engine driving the surface. */
engine?: EngineHandle;
/** The app under test: what it is, where it is served, and the command that starts it. */
app?: TargetApp;
/** Which tests on this target keep a trace page, in place of the config's `trace`. */
trace?: RecordingMode;
/** Which attempts on this target record a video, in place of the config's `video`. */
video?: RecordingMode;
}CommandConfig
export interface CommandConfig {
/** Resolved with `PATH`; never shell-interpreted. */
executable: string;
/** Passed verbatim; `{port}` expands to the app's port. */
args?: readonly string[];
/** Working directory, resolved from the project root. */
cwd?: string;
/** Added to the inherited set; `{port}` expands in values. */
env?: Readonly<Record<string, string>>;
/** Variables copied from the runner's environment when set: exact names, or prefixes ending in `*`. */
inheritEnv?: readonly string[];
/** Ready-probe budget in milliseconds; default 60000. */
startupTimeout?: number;
/** Grace period before force-kill in milliseconds; default 10000. */
shutdownTimeout?: number;
/** File that receives the process's stdout and stderr; omitted discards output. */
log?: string;
/** Use a process already answering the readiness URL instead of spawning; default `false`. */
reuseExisting?: boolean;
}ArtifactsConfig
export interface ArtifactsConfig {
/** Host store every produced artifact is handed to; omit it to keep files local only. */
store?: ArtifactStore;
}
export interface ArtifactStore {
put(artifact: StoredArtifact): Promise<{ readonly ref: string }>;
/** Receives a provider-hosted video as a link; optional. */
putLink?(link: StoredArtifactLink): Promise<{ readonly ref: string }>;
}
/** One produced artifact, handed to `store.put` once it is complete on disk. */
export interface StoredArtifact {
readonly kind: 'screenshot' | 'video' | 'download' | 'log';
readonly mediaType: string;
readonly bytes: Uint8Array;
readonly size: number;
readonly sha256: string;
/** Report-relative path with `/` separators, stable across runs of the same test. */
readonly path: string;
/** How much of the file the runner masked, as the report records it. */
readonly redaction: 'complete' | 'incomplete';
readonly runId: string;
readonly testId: string;
readonly attemptId: string;
/** The step that produced it, when one was running. */
readonly stepId?: string;
/** When a time-based artifact (a video segment) began recording. */
readonly startedAt?: string;
}
/** One provider-hosted recording, handed to `store.putLink` once the attempt stopped it. */
export interface StoredArtifactLink {
readonly kind: 'video';
/** The `http(s)` URL the service serves the recording from. */
readonly url: string;
readonly mediaType: string;
/** A recording masks nothing, so a link is always `incomplete`. */
readonly redaction: 'incomplete';
readonly runId: string;
readonly testId: string;
readonly attemptId: string;
/** When the recording started, as an ISO timestamp. */
readonly startedAt: string;
/** The step that was running when the recording was registered, if any. */
readonly stepId?: string;
}AgentConfig
/** A project tool as `defineTool` from `e2e/agent` returns it. */
export interface AgentTool {
readonly tool: object;
readonly annotations: { readonly mutates: boolean; readonly platforms?: readonly string[] };
}
/** The options every agent takes, whichever brain runs its `act` steps. */
export interface AgentOptions {
/** An AI SDK model instance; no implicit default. */
model?: ModelInstance;
/** Model for `assert`, `waitFor`, and `extract`; defaults to `model`. */
judge?: ModelInstance;
/** What the app calls things, told to every model call; at most 16384 bytes. */
context?: string;
/** Committed actions per agent call, 1 through 100; default 25. */
maxSteps?: number;
/** Model requests per agent call, 1 through 100; default 25. */
maxModelCalls?: number;
/** Deadline of one `assert`, `waitFor`, or `extract` call in milliseconds; default 30000. */
judgmentTimeout?: number;
/** Observation payload ceiling for act turns and judgments, 1024 through 16777216; default 262144. */
maxObservationBytes?: number;
/** Input tokens per model request, 1 through 1000000; default 64000. */
maxInputTokens?: number;
/** Provider options every model call carries, such as a reasoning effort. */
providerOptions?: ProviderOptions;
}
/** One entry of `agents`: the built-in agent with its options, or a custom brain under `executor`. */
export type AgentConfig = AgentOptions &
(
| {
/** How the acting agent should work, appended to the built-in rules. */
system?: string;
/** Project tools from `defineTool`, offered beside the built-in toolset. */
tools?: Readonly<Record<string, AgentTool>>;
}
| {
/** A custom brain `agent.act()` dispatches to instead of the built-in agent. */
executor: StepExecutor;
}
);ModelInstance
/**
* An AI SDK LanguageModelV2+ instance. Its provider handles transport
* and credentials.
*/
export interface ModelInstance {
/** The AI SDK specification the instance implements. */
readonly specificationVersion: string;
/** Provider id, recorded per step in the report. */
readonly provider: string;
/** Model id, recorded per step in the report. */
readonly modelId: string;
/** The generate call every AI SDK language model implements; what tells a live instance from its three id strings. */
readonly doGenerate: (...args: never[]) => unknown;
}TestFilter
interface TestFilter {
/** Names the filter in the report and in errors. */
readonly name: string;
readonly filter: (tests: readonly TestFilterCandidate[], context: TestFilterContext) => TestFilterResult | Promise<TestFilterResult>;
}
interface TestFilterCandidate {
/** The report's `testId`, and the key `exclude` and `relevance` take. */
readonly id: string;
/** Project-relative path of the test file. */
readonly file: string;
/** The describe titles, then the test title. */
readonly titlePath: readonly string[];
/** The describe chain's tags, then the test's own. */
readonly tags: readonly string[];
/** Project-relative path of the setup test file that saves the test's session; absent without one. */
readonly setupFile?: string;
}
interface TestFilterContext {
/** Absolute project root, spelled as on disk like `changes.root`. */
readonly projectRoot: string;
/** The change every filter of the run judges. */
readonly changes: TestFilterChanges;
/** The config file the run loaded, relative to `changes.root` like `changes.files`; `undefined` for a config object or one outside the repository. */
readonly configFile?: string | undefined;
/** Aborts when the run is interrupted, or with a `TimeoutError` after 5 minutes. */
readonly signal: AbortSignal;
/** Prints one progress line. */
log(line: string): void;
/** Replaces every fixed-value secret and credential password in `text`, and any run of 8 or more consecutive characters of one. */
redact(text: string): string;
}
interface TestFilterChanges {
/** The merge base of the `--changed-since` ref and `HEAD`. */
readonly base: string;
/** Absolute path of the repository root, spelled as on disk like `projectRoot`. */
readonly root: string;
/** Repository-relative POSIX paths of every changed file, uncommitted and untracked files included. Sorted, never empty. */
readonly files: readonly string[];
}
interface TestFilterResult {
/** The tests to leave out, by `id`, each with a non-empty reason the report shows. An `id` of a collected test this filter wasn't given is ignored; any other fails the filter. */
readonly exclude: Readonly<Record<string, string>>;
/** How likely each test is to fail on this change, by `id` as for `exclude`, from 0 to 1; any other score fails the filter. Each target starts the files of the likeliest first, in bands at 75%, 50%, and 25%, and targets go by the band of their best file, ties in config order. A test no filter scores counts as 0, and a test several filters score keeps its highest. */
readonly relevance?: Readonly<Record<string, number>>;
/** One line about the whole decision. */
readonly note?: string;
}TestFilter, TestFilterCandidate, TestFilterContext,
TestFilterChanges, and TestFilterResult are exported from e2e.
A filter that throws, returns an invalid result, or runs past 5 minutes
leaves nothing out, and a warning says so. An error it throws can carry
relevance, shaped as in TestFilterResult: the run still starts the
likeliest first. See Test filters.
CredentialConfig
/** One `config.credentials` entry: an account whose password is a secret named `<entry>.password`. */
export interface CredentialConfig {
username: string;
password: string | SecretProvider;
}
type SecretProvider = () => string | Promise<string>;
/** Named test identity. The password remains an opaque Secret. */
export interface Credential {
/** The entry's name in `credentials`. */
readonly name: string;
/** Plain username. */
readonly username: string;
/** Opaque; test code cannot read it. */
readonly password: Secret;
readonly [credentialBrand]: true;
}SecretConfig
/** One `config.secrets` entry: the value itself, or a provider computing it at fill time. */
export type SecretConfig = string | SecretProvider;
/**
* What a secret is for, which decides where it may be filled: a `password`
* goes only into a password field; a `generic-secret` (an API key, a token,
* any value from the environment) goes into any editable input.
*/
export type SecretPurpose = 'password' | 'generic-secret';
/** Opaque host-side value accepted only by sensitive input sinks. */
export interface Secret {
/** The entry's name in `secrets`, or `<credential>.password` for a credential's password. */
readonly name: string;
/** Where the value may be filled. */
readonly purpose: SecretPurpose;
readonly [secretBrand]: true;
}CacheConfig
/** Replay cache options. */
export interface CacheConfig {
/** Default `read-write`; `read-only` in CI when unset. */
mode?: CacheMode;
/** Custom entry store; omit it to use the file store at `dir`. */
store?: CacheStore;
/** File store directory, resolved against the project root; default `.e2e/cache`. */
dir?: string;
/** Fail a step whose recording no longer replays with `REPLAY_STALE`. Default `false`. */
strict?: boolean;
}
/** Where the replay cache keeps its entries: the file store by default, or a host's own through `cache.store`. */
export interface CacheStore {
readonly writable: boolean;
read(keyHash: string): Promise<CacheReadResult>;
/** Persists one trace, returning its size, or undefined when not written. */
write(keyHash: string, payload: ActionTrace): Promise<{ bytes: number } | undefined>;
/**
* Evicts one entry, best-effort. Called when a replayed or just-recorded
* flow is implicated in a failed attempt: the entry re-records on the next
* pass instead of replaying a poisoned flow forever. Optional: a store
* without eviction merely stays stale until the next confirmed write.
*/
delete?(keyHash: string): Promise<void>;
}
export type CacheReadResult =
| { readonly status: 'hit'; readonly entry: TraceEntry; readonly bytes: number }
| { readonly status: 'miss' }
| { readonly status: 'invalid'; readonly reason: string; readonly bytes?: number };