mirror of
https://github.com/tester-army/e2e.git
synced 2026-11-22 18:19:48 +08:00
* feat(test): set fixtures up once per worker and pass them to beforeAll
test.extend() takes [fn, { scope: 'worker' }]: one instance per worker and
target, torn down when the worker ends. Suite hooks receive worker fixtures.
Engines can declare isolation: 'worker'; @e2e-dev/mobile does, so its device,
app, and screen reach beforeAll, afterAll, and worker fixtures.
Refs ENG-1297
* feat(e2e)!: set up fixtures on demand
A test now sets up only the test.extend() fixtures its body and its
beforeEach and afterEach hooks name in their first parameter, the fixtures
those name, and the auto ones. A suite hook sets up the worker fixtures it
names and the auto worker fixtures. Names are read from the function's
source, as Playwright and Vitest read them.
- [fn, { auto: true }] and [fn, { scope: 'worker', auto: true }] run a
fixture nothing names.
- A fixture can name the fixtures declared beside it in the same extend()
call. Fixtures run in declaration order, each after the ones it names.
- The attempt is resolved as one unit before the session launches: a
fixture only an afterEach names is set up before the first beforeEach.
An afterEach that names a fixture whose setup failed is skipped.
- Fixture rules fail as COLLECTION_ERROR with the file and line of the
code: a parameter that is not destructured or takes a rest property, and
a cycle, when the file is collected; a name the target lacks, a test
fixture named by a suite hook or a worker fixture, and a fixture named
like an engine's, at selection, for the pairs that run on that target.
- On an engine with isolation: 'worker', a suite hook or a worker fixture
teardown that names no engine-backed fixture opens no engine attempt.
BREAKING CHANGE: a fixture nothing names no longer runs unless it is
declared with auto: true, and a test body, hook, or fixture function that
takes the whole fixture object (async (fixtures) => {}) no longer loads.
Refs ENG-1297
* refactor(core): declare core fixtures in one table
The five core fixtures (agent, app, screen, platform, session) are one
table in @e2e-dev/core: name, scope, and factory. createFixtures builds
the built-ins object through one loop over that table and the engine's
factories, every fixture a lazy accessor behind the same gate as before.
The runner's fixture pool, test.extend() validation, and launch read the
names and scopes from the table, so the name lists and the per-name scope
checks are gone. A launch session exposes the core fixtures that do not
belong to a test: app, screen, platform.
No behaviour change. app and screen were built with the attempt and are
now built on first read, like agent and the engine's fixtures.
Refs ENG-1297
* feat(e2e): extend a built-in fixture through test.extend
A test.extend() fixture named like one the test already has extends it,
by Playwright's rule: inside its function its own name is the fixture it
extends (the built-in, or an earlier fixture of that name), and tests,
hooks, and other fixtures that name it receive what it hands to use().
base.extend({ device: async ({ device }, use) => {
await device.setPermission('camera', 'deny');
await use(device);
} })
- A plain function takes the scope the extended fixture has on the
target: device is a worker fixture on mobile, so its override runs once
per worker and reaches beforeAll; app is a test fixture on web and a
worker fixture on mobile. A declared scope that differs is a
COLLECTION_ERROR naming both.
- A worker-scoped override receives what a worker fixture receives for
that built-in, the forwarder to the attempt that is running.
- On a target without the built-in nothing fails until code that runs
there names it; then the target has no such fixture.
- Only user code sees the override: the attempt's own built-ins, which the
runner and the worker fixtures' forwarders read, are untouched.
- Types: the override keeps the extended fixture's type and scope, through
an extend() overload that takes overrides without type arguments.
A fixture named like a core fixture, an engine's, or an earlier one of the
chain was refused before.
Refs ENG-1297
* docs(fixtures): name built-in fixtures and give their scope per engine
The docs now use one term, built-in fixtures, for agent, app, screen,
platform, session, and the ones an engine contributes (browser, device),
where pages said core fixtures, contributed fixtures, or engine fixtures.
The test reference gets one table with each built-in fixture's scope on
web and on mobile, and says what the scope decides: a test fixture reaches
test bodies, beforeEach, and afterEach; a worker fixture also reaches
beforeAll, afterAll, and worker fixtures. The hooks, worker fixtures, and
override sections link to it, as do the fixtures guide and the engine
pages. The Japanese and Chinese pages carry the table and the same terms.
Refs ENG-1297
* docs(ja): translate the fixture scope and on-demand changes
* docs(zh): translate the fixture scope and on-demand changes
* fix(e2e): let a worker fixture name an extended app or screen
A fixture that extends `app` or `screen` was taken for a test fixture when
its test.extend() call was checked, before any target is known. A worker
fixture declared after it that names `app` then failed at import on every
target, though the same fixture is accepted without the override and the
plan resolves both to worker scope on an engine whose state outlives a
test.
The scope of a plain function is now unresolved until a target is known,
whatever it extends, as it already was for an engine's own fixtures.
Refs ENG-1297
* fix(e2e): fail a suite hook that left an engine step running
On an engine whose state outlives a test, a beforeAll or afterAll hook, or
a worker fixture's teardown, can start a device step and not await it. The
hook's attempt then closed under the step, and its failure arrived later
as a stray rejection charged to whichever test ran then.
The suite attempt now does what a test attempt does once its body settled:
the step is failed at its call and cancelled, its outcome is awaited within
the cleanup budget, and the hook fails with STEP_NOT_AWAITED (HOOK_FAILED
for a suite hook).
The suite attempt keeps no step records, and StepRecorder dropped the
record of the step it had just opened before marking it running, so there
was nothing to abandon: a step now counts as running before the retained
window is trimmed.
Refs ENG-1297
* refactor(e2e): keep the fixtures a function names beside it
Registration parsed each test body, hook, and fixture function for the
fixtures it names, dropped the result, and left it in a WeakMap that the
planner and the pool read back with placeholder subjects. A cache miss
there would have named the wrong code and no line.
The parse result is now data: `names` on the registered test, the hook,
and the fixture definition. The planner and the pool read it, the WeakMap
and the per-function wrappers are gone, and one describeUser() gives an
error its subject. The explore test, registered by hand, parses its body
where it builds the record.
Unit tests state the names instead of generating source text for them.
Refs ENG-1297
* refactor(core): resolve built-in fixtures in one place
The core table declared the core fixtures, but what a target's built-in
fixtures are was still assembled around it: core names plus engine names in
three files, the 'engine' scope resolved in e2e through a cast into the
table, `platform` hard-coded as the one fixture that needs no attempt, and
two structural copies of the target.
core now exports builtInFixtures(target): names, scope(name),
needsAttempt(name), attemptless(name), and the unknown-fixture message,
over one BuiltInTarget. `platform` declares in the table that the target
alone decides it. launch, the planner, and the pool read from it.
DECLARED_BUILT_INS is the same view before a target is known: a scope the
engine decides is 'unresolved'. The planner takes either one, so its
no-target mode and the `target === undefined` branches through scopeOf and
read are gone. The scope of a fixture that extends `app` before a target
is known is 'unresolved' by construction.
Refs ENG-1297
* refactor(e2e): hand each function the fixtures it names
Every test body, hook, and fixture function must destructure its first
parameter, so what it reads is known before it runs. bindFixtures still
built a Proxy-gated bag for arbitrary property reads: one value in three
stores, the gate run twice (once over a faked plan), a third derivation of
scope, and an own-name shadow that re-derived what the planner had resolved.
No test code could reach the gate's throwing branches; only unit tests did,
by reading the bag directly.
The plan now records, per function, what each name it reads resolved to: a
chain fixture or a built-in. The pool hands each function a plain object
with exactly those names, the value a chain fixture handed over, or a
built-in read off the attempt when the function destructures it, so
built-ins stay lazy. An override that names itself receives the fixture it
extends because that is what its own name resolved to.
- bound.call(user) replaces user.fn(bound.fixtures); ready(user) asks
whether every chain fixture it names was provided.
- attemptlessBuiltIns is a function from a name to a value that throws the
reason for a built-in that needs an attempt.
- The planner runs once: it records what each fixture names, and the order
is one declaration-order walk over that record. A second validating pass
only reordered.
Behaviour: a bound or native function, whose parameters cannot be read, is
a COLLECTION_ERROR; it used to parse as naming nothing and still got lazy
built-ins. The docs no longer promise hooks and the body one shared object.
Refs ENG-1297
* refactor(e2e): move the suite attempt out of TargetExecutor
dispose, openSuiteHooks, and openSuiteAttempt were 177 lines of a second
attempt lifecycle inside TargetExecutor, written as closures in one method.
run/suite-attempt.ts now owns it: a SuiteAttempt class with open, acquire,
within, and close, over a SuiteAttemptHost interface the executor satisfies
(the way serial.ts borrows it through SerialHost), plus the worker
fixtures' teardown pass. It is the realm's SuiteHookSession itself, so the
executor keeps a context object and two call sites.
The three branches that built an attemptless reader with a "not available
to the <label>" error are one NoAttempt value ('isolated', 'unnamed',
'interrupted', or the launch failure) and one mapper to the message.
execute.ts: 1244 lines to 1052.
Refs ENG-1297
* refactor(e2e): share the attempt's fixture sequence
A run's attempt and an `e2e mcp` session's test each planned the test's
fixtures, bound them, entered the worker pool, set them up, ran the
beforeEach hooks and the body, filtered the afterEach hooks that can still
run, and labelled the teardowns. This PR widened that copy, and
standalone-test.ts asked the realm for the same hooks four times.
planAttemptFixtures(target, test, hooks) plans before any session exists
and returns open(), which binds the plan to the attempt: enter(), run()
for setup, hooks, and body, and cleanup() for the labelled afterEach hooks
and teardowns. Both call sites keep their own phases, budgets, and error
handling around it.
execute.ts: 1052 lines to 1031, its size on main.
Refs ENG-1297
* refactor(e2e): open the suite-hook pass without a lazy thunk
withSuiteHooks handed its work a thunk that opened the pass on first use.
Opening one does no I/O: the suite attempt launches nothing until a hook
that names an engine fixture runs. The pass is now opened up front and
closed in finally, and the `opened` slot and the `hooks()` call form go.
Refs ENG-1297
* refactor(e2e): ask the registry which hooks apply to a test
The selection-time fixture check rebuilt the scope chain of a test and
filtered the file's hooks by it, which the realm already did its own way.
registry.ts now exports scopeChain(test) and hooksFor(registration, test),
and both use them.
Refs ENG-1297
* refactor(core): move the fixture types into types/fixtures.ts
types.ts grew from 1679 to 1798 lines in this PR. The fixture scope, the
worker fixtures, and what test.extend() takes (definitions and overrides)
are one coherent group that nothing else in the file defines against, so
they move to types/fixtures.ts and types.ts re-exports them. The public
surface is the same.
types.ts: 1798 lines to 1715.
Refs ENG-1297
* refactor(core): drop the redundant override branch in FixtureDefinitions
A fixture that extends one the base already has was typed three ways: a
conditional branch inside the `Extra` map of FixtureDefinitions, the
`& FixtureOverrides` intersection, and the extend(overrides) overload.
Compiling the type tests without each in turn: the intersection types an
override written beside new fixtures with type arguments, and the overload
types an override-only call without them; both fail the tests when
removed. The conditional branch does not: with it gone the tests pass, and
a base name in `Extra` is `never` again, as it was before overrides. It is
removed, and the reference's copy of the declaration follows.
Refs ENG-1297
* refactor(e2e): split fixture errors from the parser, share hookLog
fixture-names.ts parses a parameter list, and also held FixtureUseError and
declarationSite, which format an error. They move to fixture-errors.ts.
Its identifier pattern held two raw zero-width characters; they are
written as escapes now.
hookLog and LOG_MODULE were pasted into three integration tests; they are
one helper in tests/helpers/hook-log.ts.
Refs ENG-1297
* docs(e2e): name the scope rule in the selection check's summary
The summary of assertFixtureUse still listed a chain fixture named like an
engine's as an error. Such a fixture extends the built-in now; the rule
left is a declared scope that differs from the extended fixture's.
Refs ENG-1297
* refactor(e2e): take execute.ts under 1000 lines
Two more pieces that are not the attempt's own sequence leave the file.
- Holding steps for `e2e run --step`: reading the screen a hold starts on
and wiring AttemptHolds to the runner's hook move to step-hold.ts, beside
the holds they configure (holdAttemptSteps, readHeldScreen).
- The result of a finished test or setup unit is a pure function of the
pair, the verdict, the attempts, and a beforeAll failure: unitResult in
units.ts, beside pairResult.
execute.ts: 1031 lines to 956. It was 1031 on main and 1226 at the review.
Refs ENG-1297
* test(e2e): match the not-awaited message without a step label
Main's #1880 names an unlabeled step by its api alone ("gadget.hang
finished"), where the message used to quote an empty label. The suite-hook
test's pattern required a label between the two, so it failed on the merge
with main.
* feat(e2e): an override inherits auto from the fixture it extends
A fixture that extends another and does not state `auto` now has the
extended fixture's, the way it has its scope: an override of an auto
fixture is set up for every test, and one of a built-in fixture on demand.
An `auto` that differs from the extended fixture's is a COLLECTION_ERROR
naming both, worded like the scope mismatch. This matches Playwright.
It also fixes which fixtures the plan starts from. An auto fixture was a
root by its own flag, so with an auto base and its override in one chain
the base was set up and the override skipped, while the name resolved to
the override; an override that replaced the base without naming it still
left the base running. An auto fixture is now a root only where its name
stands for it: the base runs once through the override's own name, or not
at all when the override replaces it.
Refs ENG-1297
* fix(core): name the hook or fixture that left a step running
STEP_NOT_AWAITED said "the test body returned before ..." for a step a
beforeAll, afterAll or beforeEach hook, a fixture's setup or a worker
fixture's teardown left running. The recorder now keeps the owner each
step was started under, and the runner says which code runs: the pool
for fixtures, hooks and the body, the suite attempt for suite hooks, and
a hosted session for itself.
---------
Co-authored-by: Oskar Kwaśniewski <oskar@okwasniewski.com>
273 lines
17 KiB
Plaintext
273 lines
17 KiB
Plaintext
---
|
||
title: エンジンプロトコル
|
||
description: エンジンを別のプロセスやマシンで動かしたり、別の言語で実装したりできます。
|
||
---
|
||
|
||
エンジンプロトコルは、[エンジン契約](/reference/engine)を JSON-RPC メッセージで表したものです。ランナーは、すべてのエンジンをこのプロトコルで操作します。別のプロセス、マシン、言語で動かすには、[エンジンサーバー](/engine-servers)を参照してください。
|
||
|
||
```ts title="e2e.config.ts"
|
||
import type { E2EConfig } from 'e2e';
|
||
import { connectEngine, spawnTransport } from 'e2e/engine';
|
||
|
||
export default {
|
||
targets: [
|
||
{
|
||
name: 'kiosk',
|
||
engine: connectEngine({
|
||
manifest: { name: 'kiosk', version: '1.0.0', spiVersion: 1, platform: 'kiosk', methods: ['engine/observe'] },
|
||
transport: spawnTransport({ command: './kiosk-engine' }),
|
||
resolveLocators: true,
|
||
}),
|
||
},
|
||
],
|
||
} satisfies E2EConfig;
|
||
```
|
||
|
||
## リファレンス
|
||
|
||
| 関数 | 戻り値 |
|
||
| --- | --- |
|
||
| [`connectEngine`](#connectengine) | `EngineHandle` |
|
||
| [`serveEngine`](#serveengine) | `Promise<void>` |
|
||
| [`describeEngine`](#describeengine) | `EngineManifest` |
|
||
| [`spawnTransport`](#spawntransport) | `EngineTransport` |
|
||
| [`socketTransport`](#sockettransport) | `EngineTransport` |
|
||
| [`loopbackTransport`](#loopbacktransport) | `EngineTransport` |
|
||
|
||
### `connectEngine`
|
||
|
||
エンジンサーバーを、ターゲットの `engine` に指定できるエンジンハンドルに変換します。
|
||
|
||
```ts
|
||
export function connectEngine(options: ConnectEngineOptions): EngineHandle;
|
||
|
||
export interface ConnectEngineOptions {
|
||
/** What the server is; the server's manifest from `initialize` must match it. */
|
||
readonly manifest: EngineManifest;
|
||
/** How to reach the server. */
|
||
readonly transport: EngineTransport;
|
||
/** Engine options the server receives in `initialize`, as JSON. */
|
||
readonly initializationOptions?: JsonValue;
|
||
/** The `secrets.get()` handles the server may resolve. */
|
||
readonly secrets?: readonly Secret[];
|
||
/** Fixtures that run on the client, beside the test. */
|
||
readonly fixtures?: Engine['fixtures'];
|
||
/** Checks the target's app at config load, on the client. */
|
||
readonly validateApp?: Engine['validateApp'];
|
||
/** Answers locators on the client from observations, for a server without `engine/locate`. */
|
||
readonly resolveLocators?: boolean;
|
||
/** Session hooks the client answers instead of the server. */
|
||
readonly session?: EngineSession;
|
||
}
|
||
```
|
||
|
||
ランナーは、サーバーが動く前の設定読み込み時にマニフェストを読みます。サーバーのマニフェストが異なる場合、最初の接続が失敗します。
|
||
|
||
ハンドルは、ハーネスがエンジンを呼び出す場所で接続を開きます。ランナーでは、ターゲットごとに 1 接続が `prepare` から `finish` まで存続します。ただし、サーバーが `lifecycle/prepare` または `lifecycle/finish` に対応する場合だけ開きます。各ワーカーでは、1 接続が `init` から `dispose` まで存続します。`e2e doctor` はターゲットごとに `doctor` 接続を開き、`lifecycle/doctor` だけを呼び出して閉じます。`spawnTransport` のように、そのためにトランスポートがサーバーを起動してもかまいませんが、マシンのプロビジョニング、デバイスのリース、アプリのインストールは行ってはいけません。doctor のシグナルが発火すると、サーバーには応答まで 5 秒の猶予が与えられ、その後接続が閉じます。`init`..`dispose` の外で操作を呼び出すと、`INVALID_STATE` で失敗します。`init` を実行しなかったワーカーには接続がないため、サーバーに `lifecycle/dispose` は届きません。2 つの接続で状態を共有するかどうかは、サーバーが決めます。spawn したサーバーは接続ごとにプロセスを持ち、loopback や socket のサーバーはひとつのエンジンで全接続を処理できます。
|
||
|
||
`resolveLocators` を指定すると、各 `locate` が観測を行い、[`resolveExpression`](/reference/engine#resolveexpression) で式を解決します。`fixtures`、`validateApp`、`secrets`、`session` フックはクライアント側で実行します。`session` フックは、サーバーの同名メソッドを置き換えます。[ホスト側の処理をクライアントに置く](/engine-servers#keep-host-work-on-the-client)を参照してください。
|
||
|
||
<Warning>
|
||
`lifecycle/prepare`、`lifecycle/init`、`lifecycle/finish`、`lifecycle/doctor` には、モデルのキーや `E2E_SECRET_*` の値を含む実行環境の変数が渡されます。`attempt/resolveSecret` は平文で応答します。信頼できるサーバーにだけ接続してください。`socketTransport` は暗号化しません。
|
||
</Warning>
|
||
|
||
| 発生するエラー | 条件 |
|
||
| --- | --- |
|
||
| `INVALID_CONFIG` | マニフェストが不正。未知または重複したメソッド、あるいは `defineEngine` が拒否する組み合わせ。例: `keyboard/press` のない `keyboard/type`、`actions` のない `engine/perform`、`engine/observe` のない `engine/perform`。 |
|
||
| `ENGINE_FAILURE` | サーバーのマニフェストが異なる、または呼び出し中に接続が閉じた。メッセージには、サーバーの標準エラー出力の末尾など、トランスポートの診断情報が含まれます。 |
|
||
|
||
### `serveEngine`
|
||
|
||
`defineEngine` で作ったエンジンをひとつの接続で提供します。クライアントが `exit` を送るか、ストリームが閉じるまで続けます。
|
||
|
||
```ts
|
||
export function serveEngine(
|
||
engine: EngineHandle | ((initializationOptions: unknown) => EngineHandle | Promise<EngineHandle>),
|
||
streams?: MessageStreams, // default: process.stdin and process.stdout
|
||
): Promise<void>;
|
||
```
|
||
|
||
標準出力はプロトコルに使うため、サーバー自身のログは標準エラー出力に書いてください。[TypeScript エンジンをサーバーとして提供する](/engine-servers#serve-a-typescript-engine)を参照してください。
|
||
|
||
### `describeEngine`
|
||
|
||
エンジンハンドルに対して `serveEngine` が公開するマニフェストを返します。静的メンバー、宣言済みメンバーが対応するメソッド、`serveEngine` が常に対応する `lifecycle/startAttempt` と `lifecycle/endAttempt` が含まれます。別の場所で提供する TypeScript エンジンのマニフェストを宣言するために使います。
|
||
|
||
```ts
|
||
export function describeEngine(engine: EngineHandle): EngineManifest;
|
||
```
|
||
|
||
### `spawnTransport`
|
||
|
||
エディターが言語サーバーを起動するのと同じように、接続ごとにサーバーを子プロセスとして起動し、標準入力と標準出力で通信します。
|
||
|
||
```ts
|
||
export function spawnTransport(options: {
|
||
readonly command: string;
|
||
readonly args?: readonly string[];
|
||
/** Added to the worker's environment. */
|
||
readonly env?: Readonly<Record<string, string>>;
|
||
readonly cwd?: string; // default: the project root
|
||
}): EngineTransport;
|
||
```
|
||
|
||
接続を閉じると、標準入力を終了し、`SIGTERM` を送ります。クリーンアップの制限時間を使い切ると `SIGKILL` を送ります。
|
||
|
||
### `socketTransport`
|
||
|
||
同じマシンまたは別のマシンの TCP ポートで、すでに待ち受けているサーバーに接続します。接続を閉じるとソケットを終了しますが、サーバーは動き続けます。
|
||
|
||
```ts
|
||
export function socketTransport(options: { readonly host: string; readonly port: number }): EngineTransport;
|
||
```
|
||
|
||
### `loopbackTransport`
|
||
|
||
メモリー内のストリームを通して、同じプロセス内でエンジンを提供します。すべての呼び出しは、他のトランスポートと同じようにシリアライズされ、プロトコルを通ります。
|
||
|
||
```ts
|
||
export function loopbackTransport(engine: EngineHandle): EngineTransport;
|
||
```
|
||
|
||
## メッセージ
|
||
|
||
基礎となるのは [Language Server Protocol の基本プロトコル](https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#baseProtocol)です。各メッセージは、`Content-Length` ヘッダーと空行に続く UTF-8 の JSON-RPC 2.0 です。どちら側からもリクエストと通知を送れます。
|
||
|
||
### ライフサイクル
|
||
|
||
接続は LSP と同じ方法で開始・終了します。
|
||
|
||
| メッセージ | 方向 | パラメーター | 結果 |
|
||
| --- | --- | --- | --- |
|
||
| `initialize` | リクエスト、クライアントからサーバー | `{ protocolVersion: 1, clientInfo, role, initializationOptions? }` | `{ protocolVersion: 1, manifest }` |
|
||
| `initialized` | 通知、クライアントからサーバー | `{}` | - |
|
||
| `shutdown` | リクエスト、クライアントからサーバー | - | `null` |
|
||
| `exit` | 通知、クライアントからサーバー | - | - |
|
||
|
||
両側とも、`1` 以外の `protocolVersion` は拒否します。`shutdown` の後は、保持するシグナルをそのままにします。`shutdown` なしで接続が閉じた場合は、保持するすべてのシグナルを中断します。
|
||
|
||
### マニフェスト
|
||
|
||
JSON Schema は、`e2e` パッケージの `schema/engine-manifest-v1.schema.json` に含まれます。
|
||
|
||
```ts
|
||
export interface EngineManifest {
|
||
readonly name: string;
|
||
readonly version: string;
|
||
readonly spiVersion: 1;
|
||
readonly platform?: string;
|
||
readonly workers?: number;
|
||
/** The engine methods the server answers; one left out is a capability the engine lacks. */
|
||
readonly methods: readonly EngineMethod[];
|
||
/** Required with `engine/perform`. */
|
||
readonly actions?: readonly LocatorActionKind[];
|
||
/** Required with `engine/performAt`. */
|
||
readonly pointerActions?: readonly PointerActionKind[];
|
||
readonly tapModifiers?: boolean;
|
||
/** See `Engine.isolation`; left out for `attempt`. */
|
||
readonly isolation?: 'worker';
|
||
}
|
||
```
|
||
|
||
### エンジンメソッド
|
||
|
||
各メソッドはひとつのエンジンメンバーに対応し、クライアントからサーバーへのリクエストです。パラメーターはメンバーの引数を名前付きで渡し、すべての `OperationContext` は `operation` とします。全メソッドは `ENGINE_METHODS` に列挙されています。
|
||
|
||
| メソッド | パラメーター | 結果 |
|
||
| --- | --- | --- |
|
||
| `engine/observe` | `{ operation, options? }` | `EngineSnapshot` |
|
||
| `engine/readStyle` | `{ ref, properties, operation }` | `ComputedStyleValues` |
|
||
| `engine/locate` | `{ expression, operation }` | `SemanticNode[]` |
|
||
| `engine/perform` | `{ ref, action, operation }` | `null` |
|
||
| `engine/performAt` | `{ point, action, operation }` | `null` |
|
||
| `keyboard/type` | `{ text, options: { replace }, operation }` | `null` |
|
||
| `keyboard/press` | `{ key, operation }` | `null` |
|
||
| `keyboard/dismiss` | `{ operation }` | `null` |
|
||
| `state/capture` | `{ operation }` | `EngineState` |
|
||
| `state/restore` | `{ state, operation }` | `null` |
|
||
| `artifacts/screenshot` | `{ label?, operation }` | `{ path }` または `{ data, mediaType }` |
|
||
| `artifacts/startVideo` | `{ operation }` | `null` |
|
||
| `artifacts/stopVideo` | `{ operation }` | `VideoSegment[]` |
|
||
| `session/open` | `{ url, operation }` | `null` |
|
||
| `session/openLink` | `{ url, operation }` | `null` |
|
||
| `session/back`, `session/restart`, `session/reset` | `{ operation }` | `null` |
|
||
| `session/resize` | `{ size: { width, height }, operation }` | `null` |
|
||
| `session/switchTab` | `{ index, operation }` | `null` |
|
||
| `session/closeTab` | `{ index, operation }` | `null` |
|
||
| `lifecycle/prepare` | `log` を除く `EnginePrepareInfo` | `EnginePrepareResult` または `null` |
|
||
| `lifecycle/finish` | `log` を除く `EngineFinishInfo` | `null` |
|
||
| `lifecycle/doctor` | `log` を除く `EngineDoctorInfo` | `EngineDoctorCheck[]` |
|
||
| `lifecycle/init` | `log` を除く `EngineInitInfo` | `null` |
|
||
| `lifecycle/startAttempt` | `{ attemptId, artifactsDir, signal, screens }` | `null` |
|
||
| `lifecycle/settleAttempt`, `lifecycle/endAttempt` | `{ signal, timeoutMs }` | `null` |
|
||
| `lifecycle/dispose` | `{ signal, timeoutMs, reuseSignal? }` | `null` |
|
||
|
||
デバイス上のサーバーなど、試行のアーティファクトディレクトリに書き込めない場合、`artifacts/screenshot` は画像を base64 にして `{ data, mediaType: 'image/png' }` を返します。クライアントが `screenshots/` 配下に書き込みます。観測画像も同様で、`pixels.data` は base64 です。
|
||
|
||
`lifecycle/startAttempt` の `screens` は、試行がトレースを保持するかを示します。保持する場合にサーバーは `attempt/screen` を送れます。
|
||
|
||
### サーバーからクライアントへ
|
||
|
||
エンジンからハーネスへのコールバックは、サーバーからクライアントへのメッセージになります。各 `attempt/*` メッセージには、属する試行の `attemptId` が付きます。終了済み試行のメッセージはクライアントが破棄します。
|
||
|
||
| メッセージ | 種類 | パラメーター |
|
||
| --- | --- | --- |
|
||
| `engine/log` | 通知 | `prepare`、`init`、`finish` からの `{ line }` |
|
||
| `attempt/appLog` | 通知 | `{ attemptId, entry }` |
|
||
| `attempt/navigation` | 通知 | `{ attemptId, line }` |
|
||
| `attempt/environment` | 通知 | `{ attemptId, facts }` |
|
||
| `attempt/screen` | 通知 | `{ attemptId, snapshot }` |
|
||
| `attempt/resolveSecret` | リクエスト | `{ attemptId, name, derivation? }`、結果は `{ value }` |
|
||
|
||
`derivation` がある場合、クライアントは回答前に `attempt/deriveSecret` で `{ derivation, plaintext }` を問い合わせます。サーバーは、Basic 認証ヘッダーなど、エンジンが値から導いた形式を `{ values }` として返し、クライアントはそれらをシークレット名でマスキングします。
|
||
|
||
### シグナル
|
||
|
||
`AbortSignal` は `{ id, aborted?, reason? }` として渡します。クライアントはシグナルごとに ID を作り、中断時に `$/abort` を `{ id, reason? }` とともに送ります。送信時にすでに中断済みなら `aborted: true` が付きます。テストのタイムアウトなど、ハーネス自身のエラーで中断した場合、`reason` は失敗したメソッドの[エラー](#errors)と同じ形式の JSON-RPC エラーオブジェクトです。サーバーはそのエラーでシグナルを中断するため、エンジンが `signal.reason` を投げ直すと、同一プロセス内の場合と同じエラーになります。`reason` がなければ、プラットフォームの `AbortError` で中断します。サーバーはシグナルの中断時に ID を破棄し、`lifecycle/endAttempt` の完了時には、その試行中に初めて見た全 ID を破棄します。その後に同じ ID が送られても、新しいシグナルとして扱います。
|
||
|
||
### エラー
|
||
|
||
エンジンメソッドが失敗した場合、JSON-RPC エラーコード `-32000` と、`data` 内の e2e エラーで応答します。これにより、ハーネスはリモートの失敗をローカルと同じように分類します。
|
||
|
||
| `data` | エンジンが投げたもの |
|
||
| --- | --- |
|
||
| `{ type: 'engine', code, retryable }` | [`EngineError`](/reference/engine#engineerror)。リトライ可能にできるのは `NODE_STALE` と `FRAME_NOT_FOUND` だけです。 |
|
||
| `{ type: 'e2e', category, code, retryable, details? }` | `TestError` や `ConfigurationError` などのランナーエラー。 |
|
||
|
||
他のエラーコードでは、メッセージだけを渡します。ハーネスは、ローカルエンジンの通常の `Error` と同じように、インフラ障害として扱います。どのエラーの `data` にも、`stack`、`errno`(`ECONNREFUSED` などの Node エラーコード)、同じ形式のエラーオブジェクトである `cause` を追加できます。これにより、レポートでエンジンの失敗箇所がわかります。
|
||
|
||
## 型
|
||
|
||
トランスポートは、ひとつの接続のバイトストリームを開きます。[トランスポートを実装する](/engine-servers#write-a-transport)を参照してください。
|
||
|
||
```ts
|
||
export interface EngineTransport {
|
||
/** For error messages: the command, or the address. */
|
||
readonly label: string;
|
||
open(context: TransportContext): Promise<TransportConnection>;
|
||
}
|
||
|
||
export interface TransportContext {
|
||
readonly role: 'run' | 'worker' | 'doctor';
|
||
readonly env: Readonly<Record<string, string | undefined>>;
|
||
/** The project root. */
|
||
readonly cwd: string;
|
||
readonly signal: AbortSignal;
|
||
/** The target's app, from `prepare`, `init`, or `doctor`: what a transport installs, since a server elsewhere cannot read the project's files. */
|
||
readonly app?: EngineAppInfo;
|
||
}
|
||
|
||
export interface TransportConnection {
|
||
readonly input: Readable;
|
||
readonly output: Writable;
|
||
/** Releases the process or socket, within `timeoutMs`. */
|
||
close(timeoutMs: number): Promise<void>;
|
||
/** What went wrong, for an error message. */
|
||
diagnostics?(): string;
|
||
}
|
||
```
|
||
|
||
## 関連ページ
|
||
|
||
[エンジン](/engines)では実装方法を比較しています。[`e2e/engine`](/reference/engine) は各メッセージが表す契約です。[エンジンサーバー](/engine-servers)と[エンジンを作る](/writing-an-engine)では、実装の手順を説明しています。
|