diff --git a/.changeset/manifest-option-warning.md b/.changeset/manifest-option-warning.md new file mode 100644 index 00000000..ef170390 --- /dev/null +++ b/.changeset/manifest-option-warning.md @@ -0,0 +1,7 @@ +--- +'@wdio/devtools-service': patch +'@wdio/selenium-devtools': patch +'@wdio/nightwatch-devtools': patch +--- + +The ignored-options warning now names `emitArtifactsManifest` when the active mode ignores it. diff --git a/.changeset/nightwatch-telemetry-mode.md b/.changeset/nightwatch-telemetry-mode.md new file mode 100644 index 00000000..0910ad8b --- /dev/null +++ b/.changeset/nightwatch-telemetry-mode.md @@ -0,0 +1,5 @@ +--- +'@wdio/nightwatch-devtools': minor +--- + +`mode: 'telemetry'` runs Nightwatch tests without any DevTools output: no backend, no UI window, no per-action capture, screencast or trace zips. The run writes only the artifacts manifest, which records the run id and each attempt's trace id. diff --git a/.changeset/selenium-telemetry-mode.md b/.changeset/selenium-telemetry-mode.md new file mode 100644 index 00000000..da7d8fa7 --- /dev/null +++ b/.changeset/selenium-telemetry-mode.md @@ -0,0 +1,5 @@ +--- +'@wdio/selenium-devtools': minor +--- + +Add `mode: 'telemetry'` to the Selenium adapter. It starts no backend and opens no dashboard, captures no per-action DOM, screenshots or screencast, and writes no trace zip. The test lifecycle still runs and the artifacts manifest is written at session end, so results can reach an external sink without a replayable trace. diff --git a/.changeset/selenium-telemetry-viewport.md b/.changeset/selenium-telemetry-viewport.md new file mode 100644 index 00000000..6651eeac --- /dev/null +++ b/.changeset/selenium-telemetry-viewport.md @@ -0,0 +1,5 @@ +--- +'@wdio/selenium-devtools': patch +--- + +In telemetry mode the Selenium adapter no longer reads the page viewport at session start. The manifest never used it, and the read cost a driver round-trip per session. diff --git a/.changeset/service-telemetry-mode.md b/.changeset/service-telemetry-mode.md new file mode 100644 index 00000000..a0e550b4 --- /dev/null +++ b/.changeset/service-telemetry-mode.md @@ -0,0 +1,5 @@ +--- +'@wdio/devtools-service': minor +--- + +Add `mode: 'telemetry'`. It skips the DevTools backend and UI window, takes no per-action capture, screencast or zip, and still runs the test lifecycle. At session end it writes the `devtools-artifacts-.json` manifest, which lists each test's state and the trace id of every attempt, so a run can be linked to its traces without recording them. Live and trace modes are unchanged. diff --git a/README.md b/README.md index b1a3104b..86b6554f 100644 --- a/README.md +++ b/README.md @@ -203,10 +203,11 @@ The Python adapter takes `enable(secrets=["...", {"env": "LOGIN_PASSWORD"}])`, ` ### 📦 Trace mode (trace.zip) -The dashboard runs in one of **two modes**, set per adapter via the shared `mode` option: +The dashboard runs in one of **three modes**, set per adapter via the shared `mode` option: - **`live`** (default) — the interactive DevTools UI window described above. - **`trace`** — a headless capture path that writes a portable trace archive, opened later in the **trace player**. +- **`telemetry`** — no backend, dashboard or per-action capture, and no trace zips: it writes only the `devtools-artifacts-.json` manifest, which carries each test's lifecycle, the run id and each attempt's trace and span ids. Zips stay opt-in through trace mode. All three JavaScript adapters (`@wdio/devtools-service`, `@wdio/selenium-devtools`, `@wdio/nightwatch-devtools`) emit the **same normalized trace** through the shared `@wdio/devtools-core` capture library, so one archive format and one player serve every framework. @@ -220,77 +221,80 @@ The Python adapter (`selenium-devtools-py`) writes the same archive through the | Feature | WebdriverIO | Selenium | Nightwatch | Python | |---|---|---|---|---| | Trace mode + `show-trace` player | ✓ | ✓ | ✓ | ✓ | -| DOM time-travel (mutation capture) | ✓ | ◐ ¹ | ◐ ¹ | ✓ | -| Network requests (browser sessions) | ✓ | ◐ ² | ◐ ³ | ✓ | +| Telemetry mode (artifacts manifest only, for OpenTelemetry export) | ✓ | ✓ | ✓ | ✕ ¹ | +| DOM time-travel (mutation capture) | ✓ | ◐ ² | ◐ ² | ✓ | +| Network requests (browser sessions) | ✓ | ◐ ³ | ◐ ⁴ | ✓ | | Stylesheets and fonts stored in the trace (`traceResources`, browser sessions) | ✓ | ✓ | ✓ | ✓ | -| Screencast (`filmstrip` / video) | ✓ ⁴ | ✓ ⁵ | ◐ ⁶ | ✓ ⁷ | -| Per-test granularity (`traceGranularity: 'test'`) | ✓ | ✓ | ◐ ⁸ | ✓ | -| Retry-aware retention (`tracePolicy`) | ✓ | ✓ | ◐ ⁹ | ◐ ¹⁰ | -| Per-test `screenshot` / `video`, attached to Allure | ✓ | ✓ | ◐ ¹¹ | ✕ ¹² | -| Cucumber Feature→Scenario→Step nesting | ◐ ¹³ | ✓ | ◐ ¹⁴ | ✕ ¹⁵ | -| Assertion capture (`captureAssertions`) | ✓ | ◐ ¹⁶ | ◐ ¹⁷ | ✓ | -| BiDi console / network capture | ✓ ¹⁸ | ✓ ¹⁸ | ◐ ¹⁹ | ✓ ¹⁸ | +| Screencast (`filmstrip` / video) | ✓ ⁵ | ✓ ⁶ | ◐ ⁷ | ✓ ⁸ | +| Per-test granularity (`traceGranularity: 'test'`) | ✓ | ✓ | ◐ ⁹ | ✓ | +| Retry-aware retention (`tracePolicy`) | ✓ | ✓ | ◐ ¹⁰ | ◐ ¹¹ | +| Per-test `screenshot` / `video`, attached to Allure | ✓ | ✓ | ◐ ¹² | ✕ ¹³ | +| Cucumber Feature→Scenario→Step nesting | ◐ ¹⁴ | ✓ | ◐ ¹⁵ | ✕ ¹⁶ | +| Assertion capture (`captureAssertions`) | ✓ | ◐ ¹⁷ | ◐ ¹⁸ | ✓ | +| BiDi console / network capture | ✓ ¹⁹ | ✓ ¹⁹ | ◐ ²⁰ | ✓ ¹⁹ | | A11y tab + pick-locator overlay (trace player) | ✓ | ✓ | ✓ | ✓ | | Transcript + Copy-for-LLM (trace player) | ✓ | ✓ | ✓ | ✓ | | Typed passwords and credential headers masked and redacted (`maskInputs`, `maskSelectors`, `secrets`) | ✓ | ✓ | ✓ | ✓ | -| Unpacked trace output (`traceFormat: 'ndjson-directory'`) | ✓ | ✓ | ✓ | ✕ ²⁰ | -| Artifacts manifest for CI and reporters (`emitArtifactsManifest`) | ✓ | ✓ | ◐ ²¹ | ✕ ²² | -| Prints where each kept trace was written | ✓ ²³ | ◐ ²⁴ | ◐ ²⁴ | ◐ ²⁵ | -| Network without BiDi (Safari, Appium mobile browsers) | ◐ ²⁶ | ◐ ²⁶ | ◐ ²⁶ | ◐ ²⁶ | +| Unpacked trace output (`traceFormat: 'ndjson-directory'`) | ✓ | ✓ | ✓ | ✕ ²¹ | +| Artifacts manifest for CI and reporters (`emitArtifactsManifest`) | ✓ | ✓ | ◐ ²² | ✕ ²³ | +| Prints where each kept trace was written | ✓ ²⁴ | ◐ ²⁵ | ◐ ²⁵ | ◐ ²⁶ | +| Network without BiDi (Safari, Appium mobile browsers) | ◐ ²⁷ | ◐ ²⁷ | ◐ ²⁷ | ◐ ²⁷ | ✓ supported. ◐ partial. ✕ not supported. A number points to its note below the table. Each supported cell is backed by the cross-adapter conformance suite, a named test or a manual check, listed in [the feature list](https://github.com/webdriverio/devtools/blob/main/packages/conformance/src/features.ts). -¹ Without BiDi (Safari, Appium) the page collector is injected after each navigation, so a page the test leaves within tens of milliseconds is never captured. +¹ The Python adapter writes no artifacts manifest, so it has no telemetry mode. -² Without BiDi a page the test leaves within tens of milliseconds is never drained, so its requests are not listed. +² Without BiDi (Safari, Appium) the page collector is injected after each navigation, so a page the test leaves within tens of milliseconds is never captured. -³ Without BiDi (`bidi: true`) or Chrome's performance log (`goog:loggingPrefs`), a page the test leaves within tens of milliseconds is never drained, so its requests are not listed. +³ Without BiDi a page the test leaves within tens of milliseconds is never drained, so its requests are not listed. -⁴ Chrome streams over CDP; other browsers poll. +⁴ Without BiDi (`bidi: true`) or Chrome's performance log (`goog:loggingPrefs`), a page the test leaves within tens of milliseconds is never drained, so its requests are not listed. -⁵ Chromium streams over CDP; other browsers poll. +⁵ Chrome streams over CDP; other browsers poll. -⁶ Nightwatch exposes no stable CDP handle, so frames come from a `takeScreenshot` poll every 200 ms. +⁶ Chromium streams over CDP; other browsers poll. -⁷ Chromium streams over CDP; other browsers take a frame per page-changing command, plus wait polls and reads at most every 200 ms. +⁷ Nightwatch exposes no stable CDP handle, so frames come from a `takeScreenshot` poll every 200 ms. -⁸ Nightwatch fires the global `beforeEach` / `afterEach` once per test module for `describe/it` and exports-object tests, so they collapse to one slice keyed to the first test; Cucumber scenarios get real per-test slices. +⁸ Chromium streams over CDP; other browsers take a frame per page-changing command, plus wait polls and reads at most every 200 ms. -⁹ For `describe/it` and exports-object tests, `--retries` reruns a testcase internally without firing the per-test hooks again, so the other policies behave like `retain-on-failure`; Cucumber scenarios record every attempt. +⁹ Nightwatch fires the global `beforeEach` / `afterEach` once per test module for `describe/it` and exports-object tests, so they collapse to one slice keyed to the first test; Cucumber scenarios get real per-test slices. -¹⁰ Nothing the Python adapter sends carries an attempt number, so the retry-aware policies behave like `retain-on-failure`. +¹⁰ For `describe/it` and exports-object tests, `--retries` reruns a testcase internally without firing the per-test hooks again, so the other policies behave like `retain-on-failure`; Cucumber scenarios record every attempt. -¹¹ Nightwatch has no live Allure attach API, so per-test screenshots and videos are written to disk and listed in the manifest but not attached. +¹¹ Nothing the Python adapter sends carries an attempt number, so the retry-aware policies behave like `retain-on-failure`. -¹² The Python adapter has no `screenshot` / `video` options and no Allure attachment yet. +¹² Nightwatch has no live Allure attach API, so per-test screenshots and videos are written to disk and listed in the manifest but not attached. -¹³ The service records no feature ancestry for a scenario, so the trace nests Scenario→Step. +¹³ The Python adapter has no `screenshot` / `video` options and no Allure attachment yet. -¹⁴ Nightwatch steps are not stamped as nested groups, so the trace nests Feature→Scenario. +¹⁴ The service records no feature ancestry for a scenario, so the trace nests Scenario→Step. -¹⁵ The Python adapter stamps no Feature or Step groups, so a pytest-bdd scenario is one flat test group with no Feature parent and no Step children. +¹⁵ Nightwatch steps are not stamped as nested groups, so the trace nests Feature→Scenario. -¹⁶ `node:assert` rows pass and fail; jest-style `expect()` and chai produce no rows at all, and a failing matcher only marks its test failed. +¹⁶ The Python adapter stamps no Feature or Step groups, so a pytest-bdd scenario is one flat test group with no Feature parent and no Step children. -¹⁷ `assert.*`, `verify.*` and `node:assert` rows pass and fail; Nightwatch's `expect` API produces no rows. +¹⁷ `node:assert` rows pass and fail; jest-style `expect()` and chai produce no rows at all, and a failing matcher only marks its test failed. -¹⁸ Attached by itself when the session supports BiDi. +¹⁸ `assert.*`, `verify.*` and `node:assert` rows pass and fail; Nightwatch's `expect` API produces no rows. -¹⁹ Nightwatch turns it on with `bidi: true` plus `webSocketUrl: true` in the capabilities. +¹⁹ Attached by itself when the session supports BiDi. -²⁰ The Python adapter has no option for it and sends no format in its export request, so the backend writes a zip. +²⁰ Nightwatch turns it on with `bidi: true` plus `webSocketUrl: true` in the capabilities. -²¹ Nightwatch has no live Allure signal to turn the manifest on by itself, so it stays opt-in. +²¹ The Python adapter has no option for it and sends no format in its export request, so the backend writes a zip. -²² The Python adapter writes no artifacts manifest. +²² Nightwatch has no live Allure signal to turn the manifest on by itself, so it stays opt-in. -²³ Printed to stdout whatever the `logLevel`. +²³ The Python adapter writes no artifacts manifest. -²⁴ Logs the path at info level through the adapter's logger rather than printing it, so a run that hides info messages does not show it. +²⁴ Printed to stdout whatever the `logLevel`. -²⁵ Logs the path (the folder, for per-test traces) at info level through Python's `logging`, which hides info messages unless the run enables them (`--log-cli-level=INFO` under pytest). +²⁵ Logs the path at info level through the adapter's logger rather than printing it, so a run that hides info messages does not show it. -²⁶ Fetch and XHR calls carry headers and bodies; every other load comes from the page's Resource Timing buffer, with timing and size but no headers or body, and no status on Safari. +²⁶ Logs the path (the folder, for per-test traces) at info level through Python's `logging`, which hides info messages unless the run enables them (`--log-cli-level=INFO` under pytest). + +²⁷ Fetch and XHR calls carry headers and bodies; every other load comes from the page's Resource Timing buffer, with timing and size but no headers or body, and no status on Safari. @@ -317,7 +321,7 @@ What counts as a user-facing action is filtered through the `ACTION_MAP` allow-l **Assertion targets.** An assertion row names the element it is about, so selecting it boxes that element in the snapshot. A `node:assert` call (or a Python `assert`) takes values rather than elements, so its element comes from where the asserted value was read: `assert.equal(await heading.getText(), 'Secure Area')` names `heading`'s selector, and so does a value from any other element read, WebdriverIO's `getHTML` and `getComputedRole` included. Only a read made earlier in the same test (or Cucumber scenario) counts, and a value read from the page itself, such as the title or the URL, names no element, even when some element's text reads the same. WebdriverIO's `browser.getTitle()` is a `Page.getTitle` row of its own, and `expect(browser).toHaveTitle(...)` folds into that read as one `expect.toHaveTitle` row. -Trace mode and live mode are **mutually exclusive** — `screencast` options are ignored in trace mode (live-mode feature). Live and trace serve different audiences (humans debugging vs. agents diffing), and stacking them only costs perf. +Trace mode and live mode are **mutually exclusive** — in trace mode `screencast.enabled` is ignored (a warning is logged): `filmstrip` and `video` decide what is recorded, and the screencast tuning fields (`quality`, `maxWidth`, `pollIntervalMs`, …) still apply to whichever recorder runs. Live and trace serve different audiences (humans debugging vs. agents diffing), and stacking them only costs perf. #### Viewing traces @@ -375,7 +379,7 @@ The hash names a position in the trace, for a `?trace=` URL, a picked file and ` | Option | Values | Default | Description | |--------|--------|---------|-------------| -| `mode` | `'live'` \| `'trace'` | `'live'` | `'live'` launches the DevTools UI; `'trace'` writes an offline artifact. | +| `mode` | `'live'` \| `'trace'` \| `'telemetry'` | `'live'` | `'live'` launches the DevTools UI; `'trace'` writes an offline artifact; `'telemetry'` writes only the artifacts manifest. | | `traceFormat` | `'zip'` \| `'ndjson-directory'` | `'zip'` | Output layout. `'zip'` writes a single archive; `'ndjson-directory'` unpacks into `trace-/`. | | `traceGranularity` | `'session'` \| `'spec'` \| `'test'` | `'session'` | `'session'` writes one trace per worker; `'spec'` one per spec file; `'test'` one per test into its own `--<browser>[-retryN]/trace.zip` folder — the smallest, most navigable artifacts, and the best pairing for a retention policy. | | `tracePolicy` | `'on'` \| `'retain-on-failure'` \| `'retain-on-first-failure'` \| `'on-first-retry'` \| `'on-all-retries'` \| `'retain-on-failure-and-retries'` | `'on'` | Which traces to keep. `'on'` keeps every trace; the rest keep only failing/retried tests — pairs well with `traceGranularity: 'test'`. | @@ -623,7 +627,7 @@ Common options (all optional): | Option | Values | Default | Notes | |---|---|---|---| -| `mode` | `'live'` \| `'trace'` | `'live'` | Dashboard vs. portable artifact | +| `mode` | `'live'` \| `'trace'` \| `'telemetry'` | `'live'` | Dashboard vs. portable artifact vs. manifest only | | `traceFormat` | `'zip'` \| `'ndjson-directory'` | `'zip'` | Trace mode only | | `traceGranularity` | `'session'` \| `'spec'` \| `'test'` | `'session'` | One trace per session / spec / test | | `tracePolicy` | `'on'` \| `'retain-on-failure'` \| … | `'on'` | Which traces to keep (trace mode) | diff --git a/packages/conformance/src/features.ts b/packages/conformance/src/features.ts index 0a6fe556..df1318e1 100644 --- a/packages/conformance/src/features.ts +++ b/packages/conformance/src/features.ts @@ -43,6 +43,19 @@ export const FEATURES = [ 'selenium-devtools-py': covered(`${PYTHON}test_trace_export.py`) } }, + { + id: 'telemetry-mode', + name: 'Telemetry mode (artifacts manifest only, for OpenTelemetry export)', + tables: ['readme-trace', 'cross-framework'], + cells: { + 'devtools-service': covered(`${WDIO}trace-granularity.test.ts`), + 'selenium-devtools': covered(`${SELENIUM}telemetry-mode.test.ts`), + 'nightwatch-devtools': covered(`${NIGHTWATCH}telemetryMode.test.ts`), + 'selenium-devtools-py': unsupported( + 'The Python adapter writes no artifacts manifest, so it has no telemetry mode.' + ) + } + }, { id: 'dom-time-travel', name: 'DOM time-travel (mutation capture)', diff --git a/packages/core/src/assert-patcher.ts b/packages/core/src/assert-patcher.ts index 64457c0d..2a281090 100644 --- a/packages/core/src/assert-patcher.ts +++ b/packages/core/src/assert-patcher.ts @@ -123,20 +123,25 @@ function describeAssertFailure(err: unknown): { } } +interface AssertEmitters { + passed: () => void + failed: (err: unknown) => void +} + function makeAssertEmitters( methodName: string, args: unknown[], onCommand: (cmd: CapturedAssert) => void, callerStack: string | undefined, resolveAssertTarget?: (args: unknown[]) => string | undefined -): { passed: () => void; failed: (err: unknown) => void } { +): AssertEmitters { const callInfo = getCallSourceFromStack(callerStack) // Drop asserts the user's test didn't fire directly: either no user-code frame // on the stack at all, or the assert's immediate caller is a dependency (a // framework/library assert firing during a user operation) — both are noise. // callerStack is captured in patchedAssert so the frame offsets line up. if (callInfo.filePath === undefined || !isAssertFromUserCode(callerStack)) { - return { passed: () => {}, failed: () => {} } + return NO_EMITTERS } const startedAt = Date.now() // Resolved from the RAW args: sanitizing loses the object identity an element @@ -167,24 +172,31 @@ function makeAssertEmitters( } } +const NO_EMITTERS: AssertEmitters = { passed: () => {}, failed: () => {} } + function makePatchedAssertMethod( methodName: string, assertObj: Record<string | symbol, unknown>, original: (...a: unknown[]) => unknown, onCommand: (cmd: CapturedAssert) => void, - resolveAssertTarget?: (args: unknown[]) => string | undefined + resolveAssertTarget?: (args: unknown[]) => string | undefined, + isActive?: () => boolean ): (...args: unknown[]) => unknown { return function patchedAssert(this: unknown, ...args: unknown[]) { // Captured HERE so frames[0] is this wrapper and frames[1] is the assert's // caller — a fixed offset isAssertFromUserCode reads (minification-robust). const callerStack = new Error().stack - const { passed, failed } = makeAssertEmitters( - methodName, - args, - onCommand, - callerStack, - resolveAssertTarget - ) + // Inactive, the call neither records a row nor rewrites the thrown error's message. + const { passed, failed } = + isActive?.() === false + ? NO_EMITTERS + : makeAssertEmitters( + methodName, + args, + onCommand, + callerStack, + resolveAssertTarget + ) let result: unknown // Node's internalMatch dispatches on `fn === assert.match` (Node ≤20), so // a wrapper installed on that property silently inverts `match` into @@ -305,7 +317,8 @@ export function matcherAssertionToCommandLog( function patchAssertNamespace( nsObj: Record<string | symbol, unknown>, onCommand: (cmd: CapturedAssert) => void, - resolveAssertTarget?: (args: unknown[]) => string | undefined + resolveAssertTarget?: (args: unknown[]) => string | undefined, + isActive?: () => boolean ): number { let count = 0 for (const methodName of TRACKED_ASSERT_METHODS) { @@ -318,7 +331,8 @@ function patchAssertNamespace( nsObj, original as (...a: unknown[]) => unknown, onCommand, - resolveAssertTarget + resolveAssertTarget, + isActive ) count++ } @@ -345,11 +359,13 @@ function patchAssertNamespace( * from its raw args. node:assert takes values, not elements, so * only the adapter that captured the reads can make the link; * the result rides along as `CapturedAssert.selector`. + * @param isActive Optional gate read on every call, for an adapter that patches before its mode is known; false makes the call a plain node:assert. */ export function patchNodeAssert( onCommand: (cmd: CapturedAssert) => void, onLog?: (level: 'info' | 'warn', message: string) => void, - resolveAssertTarget?: (args: unknown[]) => string | undefined + resolveAssertTarget?: (args: unknown[]) => string | undefined, + isActive?: () => boolean ): boolean { const log = (level: 'info' | 'warn', message: string) => onLog?.(level, message) @@ -370,7 +386,12 @@ export function patchNodeAssert( } assertObj[ASSERT_PATCHED_SYMBOL] = true - let patched = patchAssertNamespace(assertObj, onCommand, resolveAssertTarget) + let patched = patchAssertNamespace( + assertObj, + onCommand, + resolveAssertTarget, + isActive + ) // `import { strict as assert }` and `assert.strict.*` reference a separate // object with its own method identities; patch it too so strict-mode // assertions are captured the same as the default ones. `assert.strict` is a @@ -381,7 +402,8 @@ export function patchNodeAssert( patched += patchAssertNamespace( strict as Record<string | symbol, unknown>, onCommand, - resolveAssertTarget + resolveAssertTarget, + isActive ) } diff --git a/packages/core/src/session-capturer.ts b/packages/core/src/session-capturer.ts index 09e3ff5b..c2f47d33 100644 --- a/packages/core/src/session-capturer.ts +++ b/packages/core/src/session-capturer.ts @@ -67,6 +67,8 @@ export interface SessionCapturerOptions { * which covers the same-run case a process can't flag: the next spec's worker. */ reconnect?: boolean + /** False leaves console and stdout/stderr unpatched: a mode that reads no console rows must not buffer them unbounded. */ + captureOutput?: boolean } type ConsoleMethod = (typeof CONSOLE_METHODS)[number] @@ -174,8 +176,11 @@ export abstract class SessionCapturerBase { } // ── Construction ──────────────────────────────────────────────────────── + readonly #captureOutput: boolean + constructor(opts: SessionCapturerOptions = {}) { const { hostname, port, reconnect } = opts + this.#captureOutput = opts.captureOutput !== false if (hostname && port) { const query = new URLSearchParams({ [WORKER_WS_QUERY.runId]: resolveRunId(), @@ -697,6 +702,9 @@ export abstract class SessionCapturerBase { // ── Patching (call from subclass constructor) ─────────────────────────── /** Patch `console.log/info/warn/error` to forward through `onLine`. */ protected patchConsole(): void { + if (!this.#captureOutput) { + return + } CONSOLE_METHODS.forEach((method) => { const original = this.#originalConsoleMethods[method] console[method] = (...args: unknown[]) => { @@ -727,6 +735,9 @@ export abstract class SessionCapturerBase { * re-entrance when console patching itself writes to stdout. */ protected patchStreams(): void { + if (!this.#captureOutput) { + return + } const captureChunk = (raw: string | Uint8Array) => { if (this.#isCapturingStream) { return @@ -785,13 +796,20 @@ export abstract class SessionCapturerBase { wrap(process.stderr, this.#originalStderrWrite) } + // Unpatched, there is nothing to restore, and writing the construction-time references back would undo a later patch. protected restoreConsole(): void { + if (!this.#captureOutput) { + return + } CONSOLE_METHODS.forEach((method) => { console[method] = this.#originalConsoleMethods[method] }) } protected restoreStreams(): void { + if (!this.#captureOutput) { + return + } // Restoring the pre-patch references — the typed write signature differs // slightly from the runtime instance type after `.bind()`, hence the cast // through the stream's own `write` member type. diff --git a/packages/core/src/trace-finalizer.ts b/packages/core/src/trace-finalizer.ts index 4170977a..03c948b0 100644 --- a/packages/core/src/trace-finalizer.ts +++ b/packages/core/src/trace-finalizer.ts @@ -18,6 +18,7 @@ import type { TraceGranularity, TraceRetentionPolicy } from '@wdio/devtools-shared' +import { capturesTrace, forcesManifest } from '@wdio/devtools-shared' import { reportCaptureTiming } from './capture-timing.js' import { errorMessage } from './error.js' import { @@ -96,7 +97,8 @@ export interface TraceExportContext { onArtifact?: (a: TraceArtifact) => void /** When true, finalize writes a `devtools-artifacts-<sessionId>.json` manifest * enumerating every artifact (retained or not) plus per-test states, for - * ecosystem reporters (Allure, CI collectors) to consume. */ + * ecosystem reporters (Allure, CI collectors) to consume. Telemetry mode + * writes it regardless. */ emitManifest?: boolean /** Every artifact seen via `onArtifact` across the run (including eager * mid-run test-slice flushes, which the end-of-run fan-out dedupes away). @@ -277,7 +279,7 @@ export async function flushRangeTrace( ): Promise<TraceArtifact | undefined> { // Eager mid-run flushes reach here directly, bypassing finalizeTraceExport's // gate, so enforce trace-mode here too — a live run must not write slices. - if (ctx.mode !== 'trace') { + if (!capturesTrace(ctx.mode)) { return undefined } if (ctx.flushed.has(range.key)) { @@ -439,16 +441,20 @@ async function flushAllRanges( } /** - * Entry point for the after/end-of-run hook. No-op outside trace mode. Settles - * in-flight captures and eager flushes, then fans out to per-spec, per-test, or - * session writes and finally the artifacts manifest. `spec`/`test` granularity - * with no recorded boundaries warns and falls back to a single session-level - * trace. + * Entry point for the after/end-of-run hook. Live mode writes nothing. Telemetry + * writes only the manifest. Trace mode settles in-flight captures and eager + * flushes, then fans out to per-spec, per-test, or session writes and finally + * the artifacts manifest. `spec`/`test` granularity with no recorded boundaries + * warns and falls back to a single session-level trace. */ export async function finalizeTraceExport( ctx: TraceExportContext ): Promise<TraceArtifact[]> { - if (ctx.mode !== 'trace') { + if (forcesManifest(ctx.mode)) { + await maybeWriteManifest(ctx, [], true) + return [] + } + if (!capturesTrace(ctx.mode)) { return [] } // Settle in-flight snapshot captures AND the adapters' tracked fire-and-forget @@ -466,7 +472,7 @@ export async function finalizeTraceExport( `Could not redact a later password from ${artifactPath}: ${errorMessage(error)}` ) ) - await maybeWriteManifest(ctx, artifacts) + await maybeWriteManifest(ctx, artifacts, false) // After the writes, so the report's own output cannot land in the trace's console. await reportCaptureTiming(ctx.resolveOutputDir()) return artifacts @@ -507,14 +513,15 @@ function browserIdentity( } } -/** Write the artifacts manifest when enabled, preferring the adapter's full - * collected list (includes eager slices) over this pass's fan-out results. - * Never throws — a manifest failure must not abort the run. */ +/** Write the artifacts manifest when enabled (always, in telemetry), preferring + * the adapter's full collected list (includes eager slices) over this pass's + * fan-out results. Never throws — a manifest failure must not abort the run. */ async function maybeWriteManifest( ctx: TraceExportContext, - fanOutArtifacts: readonly TraceArtifact[] + fanOutArtifacts: readonly TraceArtifact[], + isTelemetry: boolean ): Promise<void> { - if (!ctx.emitManifest) { + if (!ctx.emitManifest && !isTelemetry) { return } const artifacts = ctx.collectedArtifacts ?? fanOutArtifacts diff --git a/packages/core/tests/assert-patcher.test.ts b/packages/core/tests/assert-patcher.test.ts index 6f544bdb..3252a741 100644 --- a/packages/core/tests/assert-patcher.test.ts +++ b/packages/core/tests/assert-patcher.test.ts @@ -114,6 +114,30 @@ describe('patchNodeAssert', () => { expect(message).not.toContain('ExampleThis') }) + it('leaves the call a plain node:assert while its gate is off, then captures once it is on', () => { + const captured: CapturedAssert[] = [] + let active = false + patchNodeAssert( + (c) => captured.push(c), + undefined, + undefined, + () => active + ) + const failure = (): string => { + try { + assert.strict.equal('Example Domain', 'This Is Not The Heading') + } catch (err) { + return (err as Error).message + } + return '' + } + expect(failure()).not.toContain("Expected: 'This Is Not The Heading'") + expect(captured).toHaveLength(0) + active = true + expect(failure()).toContain("Expected: 'This Is Not The Heading'") + expect(captured).toHaveLength(1) + }) + it('handles Promise-returning asserts (rejects/doesNotReject)', async () => { const captured: CapturedAssert[] = [] patchNodeAssert((c) => captured.push(c)) diff --git a/packages/core/tests/trace-finalizer.test.ts b/packages/core/tests/trace-finalizer.test.ts index f9527604..ce497fe1 100644 --- a/packages/core/tests/trace-finalizer.test.ts +++ b/packages/core/tests/trace-finalizer.test.ts @@ -395,6 +395,38 @@ describe('finalizeTraceExport', () => { ]) }) + it('writes the manifest in telemetry mode with no zips, even when emitManifest is unset', async () => { + const tracker = new TestAttemptTracker() + tracker.recordStart('u1', '/a.js') + tracker.recordOutcome('u1', 'passed') + const result = await finalizeTraceExport( + baseCtx({ + mode: 'telemetry', + outcomes: tracker, + testMetadata: meta([ + [ + 'u1', + { title: 'T1', specFile: '/a.js', state: 'passed', attempt: 0 } + ] + ]) + }) + ) + expect(result).toEqual([]) + expect(await fs.readdir(outputDir)).toEqual([ + 'devtools-artifacts-abcd1234.json' + ]) + const manifest = JSON.parse(await fs.readFile(manifestPath(), 'utf8')) + expect(manifest.runId).toEqual(expect.any(String)) + expect(manifest.tests[0].attempts).toEqual([ + expect.objectContaining({ + attempt: 0, + state: 'passed', + traceId: expect.stringMatching(/^[0-9a-f]{32}$/), + spanId: expect.stringMatching(/^[0-9a-f]{16}$/) + }) + ]) + }) + it('records browser identity', async () => { await finalizeTraceExport( baseCtx({ diff --git a/packages/nightwatch-devtools/README.md b/packages/nightwatch-devtools/README.md index 0698218d..7ecd2f45 100644 --- a/packages/nightwatch-devtools/README.md +++ b/packages/nightwatch-devtools/README.md @@ -172,6 +172,14 @@ The per-test options — `traceGranularity: 'test'`, and the `tracePolicy`, `scr --- +## Telemetry Mode + +Set `mode: 'telemetry'` when you want the run's test results without any DevTools output. No backend starts, no UI window opens, and nothing is captured per action: no screenshots, DOM, screencast, console or network capture, and no trace zips. The test lifecycle and retry tracking still run, and at run end the plugin writes only the artifacts manifest (`devtools-artifacts-<sessionId>.json`), which records the run id and each attempt's trace id. The manifest is written whether or not `emitArtifactsManifest` is set. + +```javascript +globals: nightwatchDevtools({ mode: 'telemetry' }) +``` + ## BiDi capture Enable WebDriver BiDi capture for browser console messages, JS exceptions, and network requests. Equivalent to the path selenium-devtools uses — both adapters call the same `attachBidiHandlers` in `@wdio/devtools-core`. @@ -248,7 +256,7 @@ The encoded video is sent to the DevTools dashboard via the `screencast` WS scop | `hostname` | `string` | `'localhost'` | Hostname the backend server binds to. | | `screencast` | `ScreencastOptions` | `{ enabled: false }` | Session video recording — live mode only (see [Screencast](#screencast)). | | `bidi` | `boolean` | `false` | Opt into WebDriver BiDi capture for browser console + JS exceptions + network. Requires `webSocketUrl: true` in your capabilities and a BiDi-capable chromedriver. When attached, the per-command Chrome perf-log network path is gated off so requests don't duplicate. | -| `mode` | `'live' \| 'trace'` | `'live'` | `'live'` opens the DevTools UI window; `'trace'` skips the UI and writes a `trace-<sessionId>.zip` (or directory) under a `test-results/` directory at run end (base dir resolved from the test file dir → config dir → cwd). See [Trace mode](#trace-mode). | +| `mode` | `'live' \| 'trace' \| 'telemetry'` | `'live'` | `'live'` opens the DevTools UI window; `'telemetry'` writes only the artifacts manifest (see [Telemetry Mode](#telemetry-mode)); `'trace'` skips the UI and writes a `trace-<sessionId>.zip` (or directory) under a `test-results/` directory at run end (base dir resolved from the test file dir → config dir → cwd). See [Trace mode](#trace-mode). | | `traceFormat` | `'zip' \| 'ndjson-directory'` | `'zip'` | Trace artifact layout — `zip` writes a single archive, `ndjson-directory` unpacks the same files into `trace-<sessionId>/`. Only applies when `mode: 'trace'`. | | `traceGranularity` | `'session' \| 'spec' \| 'test'` | `'session'` | One trace per session / spec file / test. `'test'` is what the per-test `screenshot` / `video` artifacts attach to. Only applies when `mode: 'trace'`. **Caveat:** the BDD `describe/it` interface collapses to a single session-scoped slice (see [Per-test slicing](#per-test-slicing--the-bdd-describeit-caveat)). For Cucumber, `'session'` spans every scenario in one zip; `'test'` gives one per scenario and is the recommendation. | | `tracePolicy` | `'on' \| 'retain-on-failure' \| 'retain-on-first-failure' \| 'on-first-retry' \| 'on-all-retries' \| 'retain-on-failure-and-retries'` | `'on'` | Which traces to keep. Pairs with `traceGranularity: 'test'`. Only applies when `mode: 'trace'`. | @@ -256,7 +264,7 @@ The encoded video is sent to the DevTools dashboard via the `screencast` WS scop | `traceResources` | `'styles'` \| `'none'` | `'styles'` | Trace mode only. `'styles'` stores the stylesheets and fonts each archive's pages used, once each by content hash, so the player replays them from the archive rather than the site; `'none'` stores nothing. Images always replay from the site. See the [root README](../../README.md#options) for caps and how the reads are kept out of the network rows. | | `screenshot` | `'off' \| 'on' \| 'only-on-failure'` | `'off'` | Per-test screenshot. Trace mode + `traceGranularity: 'test'` only. **Produce-only** — the PNG is written to the trace output dir (and listed in the artifacts manifest when `emitArtifactsManifest: true`); it is NOT attached inline to Allure (see note below). | | `video` | `'off' \| TraceRetentionPolicy` | `'off'` | Per-test video slice, retained per the given policy (e.g. `'retain-on-failure'`). Trace mode + `traceGranularity: 'test'` only. Setting a non-`off` policy starts the screencast recorder itself — you do **not** also need `filmstrip` or `screencast.enabled`; the recorder runs continuously for the session and each test's slice is cut from it by wall-clock window. **Produce-only** — the `.webm` is written to the trace output dir (and listed in the manifest when `emitArtifactsManifest: true`); NOT attached inline to Allure. | -| `emitArtifactsManifest` | `boolean` | `false` | Write the `devtools-artifacts-<sessionId>.json` manifest — the generic index reporters/CI consume to discover produced artifacts — next to the trace. **Opt-in for Nightwatch**: it has no live Allure signal to auto-detect against (`nightwatch-allure` is post-hoc), so unlike WDIO/Selenium it never auto-enables. Trace mode only. | +| `emitArtifactsManifest` | `boolean` | `false` | Write the `devtools-artifacts-<sessionId>.json` manifest — the generic index reporters/CI consume to discover produced artifacts — next to the trace. **Opt-in for Nightwatch**: it has no live Allure signal to auto-detect against (`nightwatch-allure` is post-hoc), so unlike WDIO/Selenium it never auto-enables. Ignored in live mode; telemetry mode always writes it. | | `captureAssertions` | `boolean` | `true` | Capture assertions as trace action rows — `node:assert` plus native `browser.assert.*` / `browser.verify.*`, including negated `.not.*` matchers. Passing assertions render green, failing ones red with the error. Set `false` to opt out. | | `maskInputs` | `boolean` | `true` | Replace the value of password fields with `••••` in the replayed page (DOM anchor, field state, value mutations), and redact what was typed into them, and the values of `Authorization`, `Proxy-Authorization`, `Cookie` and `Set-Cookie` headers, from command rows, network, console and the trace, live and trace mode alike. `false` turns both off. See [Password masking](../../README.md#-password-masking) and [Secret redaction](../../README.md#-secret-redaction). | | `maskSelectors` | `string[]` | `[]` | Also mask the text and value of every element these CSS selectors match, and everything inside it, in the replayed page. | diff --git a/packages/nightwatch-devtools/src/helpers/browserProxy.ts b/packages/nightwatch-devtools/src/helpers/browserProxy.ts index 6fbf3af7..ddfb4c8d 100644 --- a/packages/nightwatch-devtools/src/helpers/browserProxy.ts +++ b/packages/nightwatch-devtools/src/helpers/browserProxy.ts @@ -23,7 +23,7 @@ import { rememberReadValue, toError } from '@wdio/devtools-core' -import { isWaitCommand } from '@wdio/devtools-shared' +import { isWaitCommand, observesPage } from '@wdio/devtools-shared' import type { SessionCapturer } from '../session.js' import type { TestManager } from './testManager.js' import type { @@ -158,12 +158,11 @@ export class BrowserProxy { return this.currentTestFullPath } - setCurrentTestFullPath(path: string | null): void { - this.currentTestFullPath = path - } - /** Inject the DevTools script after every navigation; see {@link wrapNavigation}. */ wrapUrlMethod(browser: NightwatchBrowser): void { + if (!observesPage(this.sessionCapturer.traceMode)) { + return + } wrapNavigation(browser, this.sessionCapturer) } @@ -223,7 +222,10 @@ export class BrowserProxy { // captureAssertions:false → leave assert/verify original so no native // assertion rows are recorded (the finalize paths are gated to match). - if (this.captureAssertions) { + if ( + this.captureAssertions && + observesPage(this.sessionCapturer.traceMode) + ) { this.assertRecorder.wrapNamespaces(browser) } this.proxiedBrowsers.add(browser as object) @@ -528,9 +530,6 @@ export class BrowserProxy { args: unknown[] ): CommandInvocation { const callInfo = getCallSourceFromStack() - if (callInfo.filePath && !this.currentTestFullPath) { - this.currentTestFullPath = callInfo.filePath - } const lastArg = args[args.length - 1] // `waitUntil`'s first argument is its condition, never a result callback. const hasUserCallback = @@ -570,6 +569,11 @@ export class BrowserProxy { ) ) + // Before the mode gate: the spec path picks the output dir, so telemetry's manifest lands where trace mode's does. + this.currentTestFullPath ??= getCallSourceFromStack().filePath ?? null + if (!observesPage(this.sessionCapturer.traceMode)) { + return originalMethod(...args) + } const cmd = this.pendingCommand(methodName, args) const captureCallback = this.makeCaptureCallback(browser, cmd) // Opened at enqueue, Nightwatch's only hook; a command queued behind a long wait can outlive its bounded window. diff --git a/packages/nightwatch-devtools/src/index.ts b/packages/nightwatch-devtools/src/index.ts index a4146e90..555ed6a1 100644 --- a/packages/nightwatch-devtools/src/index.ts +++ b/packages/nightwatch-devtools/src/index.ts @@ -12,7 +12,6 @@ import { flushRangeLogged, resolveAdapterOutputDir, TestAttemptTracker, - tracePolicyModeWarning, configureInputMasking, configureSecretRedaction, type SpecRange, @@ -26,8 +25,13 @@ import { stop as stopBackend } from '@wdio/devtools-backend' import { DEFAULT_TRACE_RESOURCES, REUSE_ENV, + assertDevToolsMode, + capturesTrace, + ignoredOptionsWarning, + startsBackend, type CucumberPickle, - type CucumberPickleStep + type CucumberPickleStep, + observesPage } from '@wdio/devtools-shared' import logger from '@wdio/logger' import { @@ -140,6 +144,7 @@ class NightwatchDevToolsPlugin { #attemptTracker = new TestAttemptTracker() constructor(options: DevToolsOptions = {}) { + assertDevToolsMode(options.mode) const mode = options.mode ?? 'live' // Resolve the defaults ONCE and gate on the resolved values: reading the raw // `options.filmstrip === true` left the default-on filmstrip inert unless a @@ -153,9 +158,6 @@ class NightwatchDevToolsPlugin { video, screencast: options.screencast }) - if (screencast.warning) { - log.warn(screencast.warning) - } this.options = { port: options.port ?? 3000, hostname: options.hostname ?? 'localhost', @@ -181,7 +183,7 @@ class NightwatchDevToolsPlugin { for (const warning of configureSecretRedaction(this.options)) { log.warn(warning) } - const policyWarning = tracePolicyModeWarning(options.tracePolicy, mode) + const policyWarning = ignoredOptionsWarning(options, mode) if (policyWarning) { log.warn(policyWarning) } @@ -369,7 +371,7 @@ class NightwatchDevToolsPlugin { }, getRerunLabel: () => self.#getRerunLabel(), get traceMode() { - return self.options.mode === 'trace' + return capturesTrace(self.options.mode) }, get traceGranularity() { return self.options.traceGranularity @@ -408,7 +410,7 @@ class NightwatchDevToolsPlugin { internals.handleReuse = () => this.#handleReuseMode() internals.plugin = this await runPluginBefore(internals) - if (this.options.captureAssertions) { + if (this.options.captureAssertions && observesPage(this.options.mode)) { wireAssertCapture( () => this.sessionCapturer, // Rows are tagged per-`it` (BrowserProxy.rowTestUid); `#currentTestUid` @@ -539,7 +541,7 @@ class NightwatchDevToolsPlugin { suiteLine, testLines ) - if (fullPath && fullPath.includes('/')) { + if (fullPath && fullPath.includes('/') && observesPage(this.options.mode)) { this.sessionCapturer.captureSource(fullPath).catch(() => {}) } @@ -651,7 +653,7 @@ class NightwatchDevToolsPlugin { try { await this.#finalizeAllSuites(browser) this.#logRunSummary() - if (this.options.mode === 'trace') { + if (!startsBackend(this.options.mode)) { await this.#writeTraceIfNeeded() await this.sessionCapturer?.closeWebSocket() await stopBackend() @@ -726,7 +728,7 @@ class NightwatchDevToolsPlugin { async #writeTraceIfNeeded(): Promise<void> { const sessionId = this.sessionCapturer?.metadata?.sessionId - if (this.options.mode !== 'trace' || !this.sessionCapturer || !sessionId) { + if (!this.sessionCapturer || !sessionId) { return } await finalizeTraceExport(this.#traceContext(sessionId)) diff --git a/packages/nightwatch-devtools/src/plugin-screencast.ts b/packages/nightwatch-devtools/src/plugin-screencast.ts index 03726644..8edb648e 100644 --- a/packages/nightwatch-devtools/src/plugin-screencast.ts +++ b/packages/nightwatch-devtools/src/plugin-screencast.ts @@ -10,7 +10,11 @@ */ import { accumulatedScreencastFrames } from '@wdio/devtools-core' -import { SCREENCAST_DEFAULTS } from '@wdio/devtools-shared' +import { + SCREENCAST_DEFAULTS, + capturesTrace, + startsBackend +} from '@wdio/devtools-shared' import { finalizeCurrentScreencast } from './session-init.js' import type { SessionInitCtx } from './session-init.js' import type { ScreencastRecorder } from './screencast.js' @@ -35,30 +39,29 @@ export interface ScreencastResolutionInput { export interface ResolvedScreencast { /** What the plugin exposes as `options.screencast`. */ options: ScreencastOptions - /** Config warning to log, when the mode makes the option meaningless. */ - warning?: string } /** * Whether this run records a screencast, and under which options. Filmstrip OR a * produce-only per-test video drives the recorder in trace mode; bare screencast - * with neither is a live-mode feature and is dropped there. + * with neither is a live-mode feature and is dropped there. The caller's + * `ignoredOptionsWarning` names that drop. */ export function resolveScreencastOptions( input: ScreencastResolutionInput ): ResolvedScreencast { const screencast = input.screencast ?? {} - if (input.mode !== 'trace') { + if (startsBackend(input.mode)) { return { options: screencast } } + if (!capturesTrace(input.mode)) { + return { options: {} } + } if (input.filmstrip || input.video !== 'off') { return { options: { ...screencast, enabled: true } } } if (screencast.enabled === true) { - return { - options: {}, - warning: 'trace mode: ignoring screencast option (live-mode feature)' - } + return { options: {} } } return { options: screencast } } diff --git a/packages/nightwatch-devtools/src/run-lifecycle.ts b/packages/nightwatch-devtools/src/run-lifecycle.ts index 36fb823a..8dcf337b 100644 --- a/packages/nightwatch-devtools/src/run-lifecycle.ts +++ b/packages/nightwatch-devtools/src/run-lifecycle.ts @@ -12,7 +12,12 @@ import * as os from 'node:os' import logger from '@wdio/logger' import { remote } from 'webdriverio' import { errorMessage } from '@wdio/devtools-core' -import { REUSE_ENV, RUNNER_ENV, encodeInitialArgs } from '@wdio/devtools-shared' +import { + REUSE_ENV, + RUNNER_ENV, + encodeInitialArgs, + startsBackend +} from '@wdio/devtools-shared' import { start, stop } from '@wdio/devtools-backend' import type { SessionCapturer } from './session.js' @@ -96,11 +101,12 @@ export async function runPluginBefore(ctx: PluginBeforeCtx): Promise<void> { return } try { - // Trace mode: skip backend port-bind and UI entirely — matches the WDIO + // Modes without a backend skip port-bind and UI entirely — matches the WDIO // launcher gate. SessionCapturer construction in session-init also gates - // its WS init off in trace mode. - if (ctx.options.mode === 'trace') { - log.info('Trace mode — skipping backend port-bind and UI window') + // its WS init off in those modes. + const mode = ctx.options.mode ?? 'live' + if (!startsBackend(mode)) { + log.info(`${mode} mode — skipping backend port-bind and UI window`) } else { ctx.options.port = await findFreePort( ctx.options.port, @@ -199,7 +205,11 @@ export function logRunSummary(ctx: RunLifecycleCtx): void { .filter(Boolean) .join(' ') log.info(`${ctx.failCount > 0 ? '❌' : '✅'} Tests complete! ${summary}`) - log.info(` DevTools UI: http://${ctx.options.hostname}:${ctx.options.port}`) + if (startsBackend(ctx.options.mode)) { + log.info( + ` DevTools UI: http://${ctx.options.hostname}:${ctx.options.port}` + ) + } } export async function waitForDevtoolsBrowserClose( diff --git a/packages/nightwatch-devtools/src/session-init.ts b/packages/nightwatch-devtools/src/session-init.ts index f95da79b..647e6475 100644 --- a/packages/nightwatch-devtools/src/session-init.ts +++ b/packages/nightwatch-devtools/src/session-init.ts @@ -22,6 +22,7 @@ import { webdriverExecute, webdriverGet } from './helpers/webdriverHttp.js' +import { startsBackend, observesPage } from '@wdio/devtools-shared' import { errorMessage, finalizeScreencast, @@ -171,7 +172,9 @@ async function broadcastSessionMetadata( ctx.srcFolders = Array.isArray(sf) ? sf : sf ? [sf] : [] } - const viewport = await readViewport(browser) + const viewport = observesPage(ctx.mode) + ? await readViewport(browser) + : undefined const metadata = { type: TraceType.Testrunner, capabilities, @@ -199,7 +202,7 @@ async function broadcastSessionMetadata( ) // The dashboard window took the front; Safari clicks reach nothing there. if ( - ctx.mode === 'live' && + startsBackend(ctx.mode) && restoreBrowserFocus({ browserName: String(browserName), platformName: String( @@ -307,6 +310,9 @@ async function armCaptureForSession( browser: NightwatchBrowser ): Promise<void> { ctx.armedSessionId = browser.sessionId ?? undefined + if (!observesPage(ctx.mode)) { + return + } await tryRegisterPreload(ctx, browser) await tryAttachBidi(ctx, browser) await ctx.sessionCapturer.nativeNetwork.start({ @@ -420,7 +426,7 @@ export async function ensureSessionInitialized( setTimeout(resolve, TIMING.INITIAL_CONNECTION_WAIT) ) ctx.sessionCapturer = createRunCapturer(ctx, browser) - if (ctx.mode !== 'trace') { + if (startsBackend(ctx.mode)) { const connected = await ctx.sessionCapturer.waitForConnection(3000) if (!connected) { log.error('❌ Worker WebSocket failed to connect!') @@ -440,9 +446,14 @@ export function createRunCapturer( >, browser: NightwatchBrowser ): SessionCapturer { - // Trace mode: empty opts skip SessionCapturerBase's WS init; there is no backend to forward to. + // Empty opts skip SessionCapturerBase's WS init where no backend exists to forward events to. const capturer = new SessionCapturer( - ctx.mode === 'trace' ? {} : { port: ctx.port, hostname: ctx.hostname }, + { + ...(startsBackend(ctx.mode) + ? { port: ctx.port, hostname: ctx.hostname } + : {}), + captureOutput: observesPage(ctx.mode) + }, browser ) capturer.traceMode = ctx.mode @@ -457,7 +468,7 @@ export async function finalizeCurrentScreencast( if (!ctx.screencastRecorder || !ctx.screencastSessionId) { return } - if (ctx.mode === 'trace') { + if (!startsBackend(ctx.mode)) { // Trace mode: the per-test video is written by the produce path and the // filmstrip frames are embedded in the trace itself, so stop the recorder // without encoding a session .webm nothing references (orphan file). diff --git a/packages/nightwatch-devtools/src/session.ts b/packages/nightwatch-devtools/src/session.ts index a3a40891..bba95995 100644 --- a/packages/nightwatch-devtools/src/session.ts +++ b/packages/nightwatch-devtools/src/session.ts @@ -16,7 +16,9 @@ import { import { COLLECTOR_INJECT_SCRIPT, COLLECTOR_READY_SCRIPT, - skipsCapture + capturesTrace, + skipsCapture, + observesPage } from '@wdio/devtools-shared' import { captureActionSnapshot } from './action-snapshot.js' import { @@ -176,7 +178,7 @@ export class SessionCapturer extends SessionCapturerBase { timestamp: number, parentId: number | undefined ): void { - if (this.traceMode !== 'trace' || !this.#browser) { + if (!capturesTrace(this.traceMode) || !this.#browser) { return } // `url()` without a string argument is a getter; it does not navigate. @@ -444,7 +446,7 @@ export class SessionCapturer extends SessionCapturerBase { ): Promise<void> { // Polls the page for its own document identity, so there is nothing to // poll and nothing to anchor without one. - if (this.isNativeAppSession) { + if (!observesPage(this.traceMode) || this.isNativeAppSession) { return } const before = this.lastDocumentOrigin @@ -546,7 +548,7 @@ export class SessionCapturer extends SessionCapturerBase { * Inject the WDIO devtools script into the browser page */ async injectScript(browser: NightwatchBrowser) { - if (this.isNativeAppSession) { + if (!observesPage(this.traceMode) || this.isNativeAppSession) { return } try { @@ -596,7 +598,11 @@ export class SessionCapturer extends SessionCapturerBase { */ async captureNetworkFromPerformanceLogs(browser: NightwatchBrowser) { // BiDi network inspector is the source of truth when attached. - if (this.bidiActive || !this.perfLogsRequested) { + if ( + this.bidiActive || + !this.perfLogsRequested || + !observesPage(this.traceMode) + ) { return } // Off the queue: a queued `getLog` issued mid-command becomes that command's child and resolves its await early. @@ -649,6 +655,9 @@ export class SessionCapturer extends SessionCapturerBase { forceAnchor = false, anchorTimestamp?: number ) { + if (!observesPage(this.traceMode)) { + return + } // A native app has no document to drain, only the proxy's requests. Inside // the method, because the command hook and the navigation proxy both reach it. if (this.isNativeAppSession) { @@ -663,7 +672,7 @@ export class SessionCapturer extends SessionCapturerBase { /** Rows after the last capture saw a state nothing captured; one more capture, stamped at that capture, shows the test's end. */ async captureFinalFrame(): Promise<void> { - if (this.traceMode !== 'trace') { + if (!capturesTrace(this.traceMode)) { return } await this.testCapture.captureEndFrame( @@ -690,6 +699,9 @@ export class SessionCapturer extends SessionCapturerBase { /** At a test or scenario end, before its slice is written: the proxy drain there is never throttled. */ async captureTraceAtTestEnd(browser: NightwatchBrowser) { + if (!observesPage(this.traceMode)) { + return + } if (this.isNativeAppSession) { await this.nativeNetwork.forward() return diff --git a/packages/nightwatch-devtools/tests/browserProxy.test.ts b/packages/nightwatch-devtools/tests/browserProxy.test.ts index 0be0af13..6ae5d6b7 100644 --- a/packages/nightwatch-devtools/tests/browserProxy.test.ts +++ b/packages/nightwatch-devtools/tests/browserProxy.test.ts @@ -948,3 +948,31 @@ describe('BrowserProxy driver-activity window', () => { expect(isDriverBusy()).toBe(false) }) }) + +describe('BrowserProxy spec path', () => { + beforeEach(() => { + getCallSourceFromStack.mockReset() + getCallSourceFromStack.mockReturnValue({ + filePath: '/tests/spec.js', + callSource: '/tests/spec.js:9' + }) + }) + + // The path picks the manifest's output dir, so both modes must record the same one. + it.each(['trace', 'telemetry'] as const)( + 'records the spec file of the first command in %s mode', + (mode) => { + const { capturer } = makeCapturer() + ;(capturer as { traceMode?: string }).traceMode = mode + const proxy = new BrowserProxy(capturer, makeTestManager(), () => null) + const browser = makeBrowser() + proxy.wrapBrowserCommands(browser) + ;( + browser as unknown as { + titleContains: (a: string, cb: () => void) => void + } + ).titleContains('x', () => {}) + expect(proxy.getCurrentTestFullPath()).toBe('/tests/spec.js') + } + ) +}) diff --git a/packages/nightwatch-devtools/tests/modeValidation.test.ts b/packages/nightwatch-devtools/tests/modeValidation.test.ts new file mode 100644 index 00000000..449b0ae5 --- /dev/null +++ b/packages/nightwatch-devtools/tests/modeValidation.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it, vi } from 'vitest' +import { NightwatchDevToolsPlugin } from '../src/index.js' + +vi.mock('@wdio/devtools-backend', () => ({ start: vi.fn(), stop: vi.fn() })) + +describe('nightwatch mode validation', () => { + it('throws at plugin construction for an unknown mode', () => { + expect( + () => new NightwatchDevToolsPlugin({ mode: 'Trace' as never }) + ).toThrow( + 'Unknown DevTools mode "Trace"; expected one of: live, trace, telemetry' + ) + }) +}) diff --git a/packages/nightwatch-devtools/tests/pluginScreencast.test.ts b/packages/nightwatch-devtools/tests/pluginScreencast.test.ts index b11d2131..b2690903 100644 --- a/packages/nightwatch-devtools/tests/pluginScreencast.test.ts +++ b/packages/nightwatch-devtools/tests/pluginScreencast.test.ts @@ -44,10 +44,9 @@ describe('resolveScreencastOptions', () => { screencast: { pollIntervalMs: 500 } }) expect(resolved.options).toEqual({ pollIntervalMs: 500, enabled: true }) - expect(resolved.warning).toBeUndefined() }) - it('drops a bare trace-mode screencast and says why', () => { + it('drops a bare trace-mode screencast', () => { // Screencast with neither filmstrip nor video is a live-mode feature; left // enabled it would record a session .webm nothing in the trace references. const resolved = resolveScreencastOptions({ @@ -57,7 +56,17 @@ describe('resolveScreencastOptions', () => { screencast: { enabled: true } }) expect(resolved.options.enabled).toBeUndefined() - expect(resolved.warning).toContain('live-mode feature') + }) + + it('records nothing in telemetry mode, whatever the options say', () => { + expect( + resolveScreencastOptions({ + mode: 'telemetry', + filmstrip: true, + video: 'retain-on-failure', + screencast: { enabled: true } + }) + ).toEqual({ options: {} }) }) it('leaves live mode to the user options', () => { diff --git a/packages/nightwatch-devtools/tests/runLifecycle.test.ts b/packages/nightwatch-devtools/tests/runLifecycle.test.ts index d7825cbb..bb0dbd0f 100644 --- a/packages/nightwatch-devtools/tests/runLifecycle.test.ts +++ b/packages/nightwatch-devtools/tests/runLifecycle.test.ts @@ -134,6 +134,17 @@ describe('runPluginBefore', () => { delete process.env.DEVTOOLS_RUNNER_CWD }) + it('starts no backend in telemetry mode', async () => { + delete process.env.DEVTOOLS_APP_REUSE + vi.mocked(start).mockClear() + const telemetryCtx = { + ...ctx(), + options: { hostname: 'localhost', port: 39417, mode: 'telemetry' } + } as unknown as PluginBeforeCtx + await runPluginBefore(telemetryCtx) + expect(start).not.toHaveBeenCalled() + }) + it('leaves the selection to the run that started the backend when it is a rerun', async () => { process.env.DEVTOOLS_APP_REUSE = '1' process.env.DEVTOOLS_APP_HOST = 'localhost' diff --git a/packages/nightwatch-devtools/tests/telemetryCapture.test.ts b/packages/nightwatch-devtools/tests/telemetryCapture.test.ts new file mode 100644 index 00000000..11068c00 --- /dev/null +++ b/packages/nightwatch-devtools/tests/telemetryCapture.test.ts @@ -0,0 +1,150 @@ +import { describe, it, expect, vi, afterEach } from 'vitest' +import type * as DevToolsCore from '@wdio/devtools-core' +import { SessionCapturer } from '../src/session.js' +import { BrowserProxy } from '../src/helpers/browserProxy.js' +import { ensureSessionInitialized } from '../src/session-init.js' +import type { SessionInitCtx } from '../src/session-init.js' +import type { TestManager } from '../src/helpers/testManager.js' +import type { NightwatchBrowser } from '../src/types.js' + +const registerCollectorPreload = vi.hoisted(() => + vi.fn(async () => true as boolean) +) +vi.mock('@wdio/devtools-core', async (importOriginal) => ({ + ...(await importOriginal<typeof DevToolsCore>()), + registerCollectorPreload +})) + +const attachBidiHandlers = vi.hoisted(() => vi.fn(async () => true as boolean)) +vi.mock('../src/bidi.js', () => ({ + attachBidiHandlers, + buildBidiSinks: () => ({}) +})) + +vi.mock('../src/screencast-session.js', () => ({ + startScreencast: vi.fn(async () => {}), + rotateScreencastForSession: vi.fn() +})) + +/** Any touch of the browser fails the test: telemetry must not reach the page or the driver. */ +function untouchableBrowser(): NightwatchBrowser { + return new Proxy( + {}, + { + get(_target, prop) { + throw new Error(`browser touched: ${String(prop)}`) + } + } + ) as unknown as NightwatchBrowser +} + +function sessionBrowser(sessionId: string) { + return { + sessionId, + driver: { id: sessionId }, + capabilities: { browserName: 'chrome' }, + desiredCapabilities: {}, + options: {}, + execute: vi.fn(async () => null) + } +} + +afterEach(() => { + registerCollectorPreload.mockClear() + attachBidiHandlers.mockClear() +}) + +describe('telemetry mode reads nothing from the browser on the capture paths', () => { + it('injects no collector, drains no page and reads no perf log', async () => { + const capturer = new SessionCapturer({}, untouchableBrowser()) + capturer.traceMode = 'telemetry' + const browser = untouchableBrowser() + + await expect(capturer.injectScript(browser)).resolves.toBeUndefined() + await expect(capturer.captureTrace(browser, true)).resolves.toBeUndefined() + await expect( + capturer.captureTraceAtTestEnd(browser) + ).resolves.toBeUndefined() + await expect( + capturer.anchorAfterNavigation(browser, 1) + ).resolves.toBeUndefined() + await expect( + capturer.captureNetworkFromPerformanceLogs(browser) + ).resolves.toBeUndefined() + }) +}) + +describe('telemetry session bringup', () => { + it('registers no preload, attaches no BiDi, reads no viewport and patches no console or stdout', async () => { + const browser = sessionBrowser('session-1') + const ctx = { + hostname: 'localhost', + port: 3000, + screencastOptions: {}, + bidiEnabled: true, + mode: 'telemetry', + captureAssertions: false, + runner: 'nightwatch-bdd', + testReporter: { updateSuites: vi.fn(), updateUpstream: vi.fn() }, + browserProxy: {}, + isScriptInjected: true, + lastSessionId: undefined, + armedSessionId: undefined, + srcFolders: [], + screencastRecorder: undefined, + screencastSessionId: undefined, + screencastRotation: undefined, + configPath: undefined, + getCurrentTest: () => null, + getCurrentScenarioSuite: () => null, + buildMetadataOptions: () => ({}), + attemptFor: () => undefined, + recordOutcome: () => {}, + finalizeCurrentScreencast: vi.fn(async () => {}) + } as unknown as SessionInitCtx + + const write = process.stdout.write + const log = console.log + await ensureSessionInitialized(ctx, browser as unknown as NightwatchBrowser) + + expect([process.stdout.write, console.log]).toEqual([write, log]) + expect(registerCollectorPreload).not.toHaveBeenCalled() + expect(attachBidiHandlers).not.toHaveBeenCalled() + expect(browser.execute).not.toHaveBeenCalled() + expect(ctx.sessionCapturer?.metadata?.sessionId).toBe('session-1') + }) +}) + +describe('telemetry command wrapper', () => { + it('passes commands through without recording rows or navigation hooks', () => { + const click = vi.fn((_selector: string) => 'clicked') + const url = vi.fn((_href: string) => 'navigated') + const browser = { sessionId: 'session-1', click, url } + const capturer = { + traceMode: 'telemetry', + captureCommand: vi.fn(), + openCommand: vi.fn(), + commandsLog: [] + } + const testManager = { + detectTestBoundary: vi.fn(), + startTestIfPending: vi.fn() + } + const proxy = new BrowserProxy( + capturer as unknown as SessionCapturer, + testManager as unknown as TestManager, + () => null + ) + + proxy.wrapUrlMethod(browser as unknown as NightwatchBrowser) + proxy.wrapBrowserCommands(browser as unknown as NightwatchBrowser) + + expect(browser.click('#submit')).toBe('clicked') + expect(click).toHaveBeenCalledWith('#submit') + expect(browser.url('https://example.test/')).toBe('navigated') + expect(url).toHaveBeenCalledWith('https://example.test/') + expect(capturer.captureCommand).not.toHaveBeenCalled() + expect(capturer.openCommand).not.toHaveBeenCalled() + expect(testManager.startTestIfPending).toHaveBeenCalled() + }) +}) diff --git a/packages/nightwatch-devtools/tests/telemetryMode.test.ts b/packages/nightwatch-devtools/tests/telemetryMode.test.ts new file mode 100644 index 00000000..62798407 --- /dev/null +++ b/packages/nightwatch-devtools/tests/telemetryMode.test.ts @@ -0,0 +1,31 @@ +import { describe, it, expect, vi } from 'vitest' +import type * as DevToolsCore from '@wdio/devtools-core' +import { finalizeTraceExport } from '@wdio/devtools-core' +import { NightwatchDevToolsPlugin } from '../src/index.js' + +vi.mock('@wdio/devtools-core', async (importOriginal) => ({ + ...(await importOriginal<typeof DevToolsCore>()), + finalizeTraceExport: vi.fn(async () => []) +})) +vi.mock('@wdio/devtools-backend', () => ({ start: vi.fn(), stop: vi.fn() })) + +describe('telemetry mode finalize', () => { + // The finalizer forces the manifest on the mode it is handed (core forcesManifest), so the mode must arrive as telemetry. + it('hands the trace finalizer a telemetry context, which is what forces the manifest', async () => { + const plugin = new NightwatchDevToolsPlugin({ mode: 'telemetry' }) + Object.assign(plugin, { + suiteManager: { getAllSuites: () => new Map() }, + sessionCapturer: { + metadata: { sessionId: 'session-1' }, + snapshotCaptures: [], + nativeNetwork: { stop: vi.fn() }, + closeWebSocket: vi.fn(async () => {}) + } + }) + await plugin.after() + expect(finalizeTraceExport).toHaveBeenCalledTimes(1) + expect(finalizeTraceExport).toHaveBeenCalledWith( + expect.objectContaining({ mode: 'telemetry' }) + ) + }) +}) diff --git a/packages/selenium-devtools/README.md b/packages/selenium-devtools/README.md index 1ae20850..42c0730c 100644 --- a/packages/selenium-devtools/README.md +++ b/packages/selenium-devtools/README.md @@ -314,7 +314,9 @@ DevTools.configure({ rerunCommand: 'npm test -- --grep "{{testName}}"' }) ``` #### `mode` — live UI vs. headless trace.zip -**Default:** `'live'` (launches the dashboard window). Set to `'trace'` to skip the dashboard entirely and write a `trace-<sessionId>.zip` under a `test-results/` directory at session end (the base dir resolves from the test file's directory → the config directory → cwd) — meant for CI / offline replay / agentic diffing. For `traceGranularity: 'test'` the per-test artifact lands at `test-results/<spec>-<title>-<browser>[-retryN]/trace.zip`. `screencast` is ignored in trace mode (live-mode-only feature). +**Default:** `'live'` (launches the dashboard window). Set to `'trace'` to skip the dashboard entirely and write a `trace-<sessionId>.zip` under a `test-results/` directory at session end (the base dir resolves from the test file's directory → the config directory → cwd) — meant for CI / offline replay / agentic diffing. For `traceGranularity: 'test'` the per-test artifact lands at `test-results/<spec>-<title>-<browser>[-retryN]/trace.zip`. `screencast.enabled` is ignored in trace mode: `filmstrip` and `video` decide what is recorded, and the screencast tuning fields still apply. + +Set to `'telemetry'` for a run that only reports its results: no backend, no dashboard window, no trace zip, and no per-action DOM, screenshot or screencast capture. The test lifecycle still runs, and the artifacts manifest (`devtools-artifacts-<sessionId>.json`, carrying the run id and each attempt's trace id) is written at session end. Use it when the results go to an OpenTelemetry or other external sink and nothing needs a replayable trace. ```javascript DevTools.configure({ mode: 'trace' }) @@ -401,7 +403,7 @@ The trace uses a portable NDJSON schema, so the same `.zip` (or `ndjson-director | `headless` | `boolean` | `false` | Run the **test** browser headless (injects `--headless=old`). The DevTools UI window is unaffected. | | `screencast` | `ScreencastOptions` | `{ enabled: false }` | Per-session `.webm` video recording. See sub-options below. | | `rerunCommand` | `string` | auto | Command template for per-test rerun. `{{testName}}` is substituted. Auto-derived from runner argv if omitted. | -| `mode` | `'live' \| 'trace'` | `'live'` | `live` opens the DevTools UI; `trace` skips it and writes a portable trace artifact instead. Overrides `openUi`. | +| `mode` | `'live' \| 'trace' \| 'telemetry'` | `'live'` | `live` opens the DevTools UI; `trace` skips it and writes a portable trace artifact instead; `telemetry` skips the UI and writes no trace, only the artifacts manifest (see above). Overrides `openUi`. | | `traceFormat` | `'zip' \| 'ndjson-directory'` | `'zip'` | Trace artifact layout — a single `.zip` or an unpacked directory. Trace mode only. | | `traceGranularity` | `'session' \| 'spec' \| 'test'` | `'session'` | One trace per session / spec file / test. `'test'` writes each to `test-results/<spec>-<title>-<browser>[-retryN]/trace.zip`. Trace mode only. | | `tracePolicy` | `'on' \| 'retain-on-failure' \| 'retain-on-first-failure' \| 'on-first-retry' \| 'on-all-retries' \| 'retain-on-failure-and-retries'` | `'on'` | Which traces to keep. Pairs with `traceGranularity: 'test'`. Trace mode only. | @@ -409,7 +411,7 @@ The trace uses a portable NDJSON schema, so the same `.zip` (or `ndjson-director | `traceResources` | `'styles'` \| `'none'` | `'styles'` | Trace mode only. `'styles'` stores the stylesheets and fonts each archive's pages used, once each by content hash, so the player replays them from the archive rather than the site; `'none'` stores nothing. Images always replay from the site. See the [root README](../../README.md#options) for caps and how the reads are kept out of the network rows. | | `screenshot` | `'off' \| 'on' \| 'only-on-failure'` | `'off'` | Trace mode + `traceGranularity: 'test'`. Per-test screenshot, attached inline to Allure (`image/png`) via `allure-js-commons` when an Allure runner adapter is active. | | `video` | `'off' \| TraceRetentionPolicy` | `'off'` | Trace mode + `traceGranularity: 'test'`. Per-test screencast video, retained per the given policy, attached inline to Allure (`video/webm`) via `allure-js-commons` when an Allure runner adapter is active. | -| `emitArtifactsManifest` | `boolean` | auto | Write the `devtools-artifacts-<sessionId>.json` manifest — the generic index reporters/CI consume to discover produced artifacts — next to the trace. Off by default; **auto-enables** when an `allure-js-commons` runtime is active (the same signal the inline Allure attach uses). Set explicitly to force on/off. Trace mode only. | +| `emitArtifactsManifest` | `boolean` | auto | Write the `devtools-artifacts-<sessionId>.json` manifest — the generic index reporters/CI consume to discover produced artifacts — next to the trace. Off by default; **auto-enables** when an `allure-js-commons` runtime is active (the same signal the inline Allure attach uses). Set explicitly to force on/off. Ignored in live mode; telemetry mode always writes it. | | `captureAssertions` | `boolean` | `true` | Capture `node:assert` assertions (both passing and failing) as trace action rows. Set `false` to opt out. | | `maskInputs` | `boolean` | `true` | Replace the value of password fields with `••••` in the replayed page (DOM anchor, field state, value mutations), and redact what was typed into them, and the values of `Authorization`, `Proxy-Authorization`, `Cookie` and `Set-Cookie` headers, from command rows, network, console and the trace, live and trace mode alike. `false` turns both off. See [Password masking](../../README.md#-password-masking) and [Secret redaction](../../README.md#-secret-redaction). | | `maskSelectors` | `string[]` | `[]` | Also mask the text and value of every element these CSS selectors match, and everything inside it, in the replayed page. | diff --git a/packages/selenium-devtools/src/assertPatcher.ts b/packages/selenium-devtools/src/assertPatcher.ts index b3de39f5..0ad35b4d 100644 --- a/packages/selenium-devtools/src/assertPatcher.ts +++ b/packages/selenium-devtools/src/assertPatcher.ts @@ -26,7 +26,8 @@ export function resolveAssertTarget(args: unknown[]): string | undefined { * adapter's namespace. */ export function patchNodeAssert( - onCommand: (cmd: CapturedCommand) => void + onCommand: (cmd: CapturedCommand) => void, + isActive: () => boolean ): boolean { return patchNodeAssertCore( (cmd: CapturedAssert) => @@ -39,6 +40,7 @@ export function patchNodeAssert( fromElement: false }), (level, message) => log[level](message), - resolveAssertTarget + resolveAssertTarget, + isActive ) } diff --git a/packages/selenium-devtools/src/driverPatcher.ts b/packages/selenium-devtools/src/driverPatcher.ts index fdfd79f5..dc6034a8 100644 --- a/packages/selenium-devtools/src/driverPatcher.ts +++ b/packages/selenium-devtools/src/driverPatcher.ts @@ -198,7 +198,43 @@ function describeCall( } } -function makeWrappedMethod( +/** Telemetry reports the command without reading it: no stack walk, no serialization, no value registry. */ +function settleCall( + hooks: DriverPatcherHooks, + methodName: string, + args: unknown[], + fromElement: boolean, + target: unknown +): (result: unknown, error: Error | undefined) => void { + // Before the instrumentation below: serializing args and walking the stack + // both cost time that would otherwise land inside the row's own duration. + const startTime = Date.now() + // Holds the filmstrip poll off the driver until this command settles (see + // core driver-activity.ts); CDP push mode never polls. + const closeCommandWindow = beginDriverCommand(methodName) + if (hooks.observesPage?.() === false) { + return (_result, error) => { + closeCommandWindow() + emitCommand(hooks, { + command: methodName, + args: [], + callSource: undefined, + fromElement, + startTime, + result: undefined, + error, + timestamp: Date.now() + }) + } + } + return makeSettle( + hooks, + describeCall(methodName, args, fromElement, target, startTime), + closeCommandWindow + ) +} + +export function makeWrappedMethod( original: (...args: unknown[]) => unknown, methodName: string, fromElement: boolean, @@ -208,17 +244,7 @@ function makeWrappedMethod( !fromElement && (ELEMENT_LOCATOR_METHODS as readonly string[]).includes(methodName) return function (this: unknown, ...args: unknown[]): unknown { - // Before the instrumentation below: serializing args and walking the stack - // both cost time that would otherwise land inside the row's own duration. - const startTime = Date.now() - // Holds the filmstrip poll off the driver until this command settles (see - // core driver-activity.ts); CDP push mode never polls. - const closeCommandWindow = beginDriverCommand(methodName) - const settle = makeSettle( - hooks, - describeCall(methodName, args, fromElement, this, startTime), - closeCommandWindow - ) + const settle = settleCall(hooks, methodName, args, fromElement, this) let result: unknown try { @@ -524,7 +550,8 @@ export function patchSelenium(hooks: DriverPatcherHooks): boolean { WebDriver.prototype as Patchable, (cmd) => emitCommand(hooks, { ...cmd, result: safeSerialize(cmd.rawResult) }), - WebElementPromise + WebElementPromise, + () => hooks.observesPage?.() !== false ) const tracked = collectMethodNames(WebDriver.prototype).filter( diff --git a/packages/selenium-devtools/src/helpers/commandPostActions.ts b/packages/selenium-devtools/src/helpers/commandPostActions.ts index d0856d95..6375d361 100644 --- a/packages/selenium-devtools/src/helpers/commandPostActions.ts +++ b/packages/selenium-devtools/src/helpers/commandPostActions.ts @@ -9,7 +9,13 @@ import { type CapturedPerformancePayload, type RetryTracker } from '@wdio/devtools-core' -import { skipsCapture, type CaptureTrigger } from '@wdio/devtools-shared' +import { + capturesTrace, + skipsCapture, + startsBackend, + type CaptureTrigger, + observesPage +} from '@wdio/devtools-shared' import { ELEMENT_LOCATOR_METHODS } from '../constants.js' import { getDriverOriginals, getElementOriginals } from '../driverPatcher.js' import { captureOrReplaceCommand } from './captureOrReplaceCommand.js' @@ -174,7 +180,7 @@ export interface OnCommandCtx { readonly sessionCapturer: SessionCapturer | undefined readonly testManager: TestManager | undefined readonly retryTracker: RetryTracker - readonly options: { captureScreenshots: boolean; mode?: DevToolsMode } + readonly options: { captureScreenshots: boolean; mode: DevToolsMode } readonly finalized: boolean readonly driver: SeleniumDriverLike | undefined readonly actionSnapshots: ActionSnapshot[] @@ -222,7 +228,7 @@ function maybeDrainAfterDomCommand( cmd: CapturedCommand ): void { if ( - ctx.options.mode === 'trace' && + capturesTrace(ctx.options.mode) && cmd.fromElement && DOM_MUTATING_ELEMENT_COMMANDS.has(cmd.command) && !ctx.finalized @@ -279,7 +285,7 @@ function maybeDrainAfterLiveCommand( cmd: CapturedCommand ): void { if ( - ctx.options.mode === 'trace' || + !startsBackend(ctx.options.mode) || ctx.finalized || !warrantsLiveDrain(capturer, cmd) ) { @@ -306,7 +312,7 @@ export async function handleOnCommand( return } const test = testManager.getOrEnsureTest() - if (!test) { + if (!test || !observesPage(ctx.options.mode)) { return } const entry = await captureOrReplaceCommand({ @@ -385,7 +391,7 @@ function queueActionSnapshot( error: unknown, trigger: CaptureTrigger ): void { - if (ctx.options.mode !== 'trace' || error || !ctx.driver) { + if (!capturesTrace(ctx.options.mode) || error || !ctx.driver) { return } const driver = ctx.driver diff --git a/packages/selenium-devtools/src/helpers/driverMetadata.ts b/packages/selenium-devtools/src/helpers/driverMetadata.ts index b0969c26..018c8901 100644 --- a/packages/selenium-devtools/src/helpers/driverMetadata.ts +++ b/packages/selenium-devtools/src/helpers/driverMetadata.ts @@ -10,6 +10,8 @@ const log = logger('@wdio/selenium-devtools:driverMetadata') export interface DriverMetadataInput { driver: SeleniumDriverLike driverReadyTs: number + /** Telemetry mode reads no page; skipping the viewport saves a driver round-trip the manifest never uses. */ + observePage: boolean /** The JS test runner `detectRunner` found (mocha/jest/cucumber). Distinct * from `Metadata.runner`, which names this adapter for every one of them. */ detectedRunner: string | null @@ -140,7 +142,9 @@ export async function buildDriverMetadata( const capGet = makeCapGet(capabilities) logBrowserBoot(capGet, sessionId, driverReadyTs) const caps = serializeCapabilities(capabilities) - const viewport = await readViewport(driver, caps) + const viewport = input.observePage + ? await readViewport(driver, caps) + : undefined return { sessionId, metadata: { diff --git a/packages/selenium-devtools/src/helpers/finalFrame.ts b/packages/selenium-devtools/src/helpers/finalFrame.ts index f6a6a063..73151439 100644 --- a/packages/selenium-devtools/src/helpers/finalFrame.ts +++ b/packages/selenium-devtools/src/helpers/finalFrame.ts @@ -1,5 +1,6 @@ import logger from '@wdio/logger' import { errorMessage } from '@wdio/devtools-core' +import { capturesTrace } from '@wdio/devtools-shared' import { captureActionSnapshot } from '../action-snapshot.js' import type { SessionLifecycleCtx } from '../session-lifecycle.js' @@ -11,7 +12,7 @@ export async function captureFinalFrame( ): Promise<void> { const capturer = ctx.sessionCapturer if ( - ctx.options.mode !== 'trace' || + !capturesTrace(ctx.options.mode) || ctx.finalized || !ctx.driver || !capturer diff --git a/packages/selenium-devtools/src/helpers/screencast-options.ts b/packages/selenium-devtools/src/helpers/screencast-options.ts new file mode 100644 index 00000000..e4aa49a4 --- /dev/null +++ b/packages/selenium-devtools/src/helpers/screencast-options.ts @@ -0,0 +1,39 @@ +import { SCREENCAST_DEFAULTS, startsBackend } from '@wdio/devtools-shared' +import type { DevToolsOptions, ScreencastOptions } from '../types.js' + +/** Outside live mode `enabled` is the one field that does not apply (filmstrip and video decide recording); the tuning fields still do. */ +export function screencastFor( + options: ScreencastOptions, + mode: DevToolsOptions['mode'] +): ScreencastOptions { + return startsBackend(mode) + ? { ...options } + : { ...options, enabled: SCREENCAST_DEFAULTS.enabled } +} + +/** The user's options as given, kept apart from the mode, so a later mode change re-derives from them rather than from an already-forced value; a recorder copies them when its driver is created, so a change reaches the next driver, not a running recording. */ +export class ScreencastSettings { + #input: ScreencastOptions + #effective: Readonly<ScreencastOptions> + + constructor( + user: ScreencastOptions | undefined, + mode: DevToolsOptions['mode'] + ) { + this.#input = { ...SCREENCAST_DEFAULTS, ...user } + this.#effective = Object.freeze(screencastFor(this.#input, mode)) + } + + /** Frozen: a write would be lost at the next update(), so it throws instead; configure() is the way to change it. */ + get effective(): Readonly<ScreencastOptions> { + return this.#effective + } + + update( + user: ScreencastOptions | undefined, + mode: DevToolsOptions['mode'] + ): void { + this.#input = { ...this.#input, ...user } + this.#effective = Object.freeze(screencastFor(this.#input, mode)) + } +} diff --git a/packages/selenium-devtools/src/index.ts b/packages/selenium-devtools/src/index.ts index 30158eaf..d45c5ccb 100644 --- a/packages/selenium-devtools/src/index.ts +++ b/packages/selenium-devtools/src/index.ts @@ -11,6 +11,13 @@ import { handleOnCommand } from './helpers/commandPostActions.js' import { logConfigSummary } from './helpers/configSummary.js' +import { ScreencastSettings } from './helpers/screencast-options.js' +import { + assertDevToolsMode, + ignoredOptionsWarning, + startsBackend, + observesPage +} from '@wdio/devtools-shared' import { registerProcessHooks } from './helpers/processHooks.js' import { patchSelenium } from './driverPatcher.js' import { ensureBidiCapability, ensureHeadlessChrome } from './bidi.js' @@ -61,18 +68,12 @@ import { configureSecretRedaction, RetryTracker, errorMessage, - requestsInterceptedNetwork, - tracePolicyModeWarning + requestsInterceptedNetwork } from '@wdio/devtools-core' import { SeleniumTestArtifacts } from './test-artifacts.js' import { claimMochaRootHooks, tryRegisterRunnerHooks } from './runnerHooks.js' import { patchNodeAssert } from './assertPatcher.js' -import { - REUSE_ENV, - SCREENCAST_DEFAULTS, - TEST_STATE, - NAVIGATION_COMMANDS -} from './constants.js' +import { REUSE_ENV, TEST_STATE, NAVIGATION_COMMANDS } from './constants.js' import { type ActionSnapshot, type CapturedCommand, @@ -80,7 +81,6 @@ import { type MochaRootHooks, type RunnerHookCallbacks, type ScreencastFrame, - type ScreencastOptions, type SeleniumDriverLike, type TestStats } from './types.js' @@ -121,7 +121,7 @@ class SeleniumDevToolsPlugin { // Coalesce internal retries: same {command,args,src} replaces prior entry. #retryTracker = new RetryTracker() #screencast?: ScreencastRecorder - #screencastOptions: ScreencastOptions + #screencastSettings: ScreencastSettings #actionSnapshots: ActionSnapshot[] = [] #snapshotCaptures: Promise<void>[] = [] #sessionId?: string @@ -167,6 +167,7 @@ class SeleniumDevToolsPlugin { #testArtifacts = new SeleniumTestArtifacts() constructor(options: DevToolsOptions = {}) { + assertDevToolsMode(options.mode) this.#options = { port: options.port ?? 3000, hostname: options.hostname ?? 'localhost', @@ -189,10 +190,7 @@ class SeleniumDevToolsPlugin { secrets: options.secrets ?? [] } this.#applyCapturePolicy() - const policyWarning = tracePolicyModeWarning( - options.tracePolicy, - this.#options.mode - ) + const policyWarning = ignoredOptionsWarning(options, this.#options.mode) if (policyWarning) { log.warn(policyWarning) } @@ -200,21 +198,10 @@ class SeleniumDevToolsPlugin { if (options.rerunCommand) { this.#rerunManager.configure(options.rerunCommand) } - // Same gate as DevTools.configure() — direct construction with - // `{ mode: 'trace', screencast: { enabled: true } }` would otherwise - // bypass the runtime check. - if ( - this.#options.mode === 'trace' && - options.screencast?.enabled === true - ) { - log.warn('trace mode: ignoring screencast option (live-mode feature)') - this.#screencastOptions = { ...SCREENCAST_DEFAULTS } - } else { - this.#screencastOptions = { - ...SCREENCAST_DEFAULTS, - ...(options.screencast ?? {}) - } - } + this.#screencastSettings = new ScreencastSettings( + options.screencast, + this.#options.mode + ) // Reuse mode: rerun child inherits the parent's backend host/port. if ( process.env[REUSE_ENV.REUSE] === '1' && @@ -241,7 +228,7 @@ class SeleniumDevToolsPlugin { headless: this.#options.headless, captureScreenshots: this.#options.captureScreenshots, rerunCommand: this.#options.rerunCommand, - screencast: this.#screencastOptions, + screencast: this.#screencastSettings.effective, rerunManager: this.#rerunManager }) } @@ -256,11 +243,10 @@ class SeleniumDevToolsPlugin { this.#backendStartPromise = (async () => { try { this.#logConfigSummary() - // Trace mode parity with WDIO launcher gate: skip backend port-bind - // entirely — no UI to serve, SessionCapturer WS init is also gated - // off in session-lifecycle.ts. - if (this.#options.mode === 'trace') { - log.info('Trace mode — skipping backend port-bind and UI window') + if (!startsBackend(this.#options.mode)) { + log.info( + `${this.#options.mode} mode — skipping backend port-bind and UI window` + ) this.#backendStarted = true return } @@ -280,7 +266,7 @@ class SeleniumDevToolsPlugin { ) } this.#backendStarted = true - // mode==='trace' returned early above; only live mode reaches here. + // Non-live modes returned early above; only live mode reaches here. if (this.#options.openUi && !this.#isReuse) { this.#openUiWindow() } @@ -295,7 +281,7 @@ class SeleniumDevToolsPlugin { if (this.#uiReadyPromise) { return this.#uiReadyPromise } - if (!this.#options.openUi) { + if (!this.#options.openUi || !startsBackend(this.#options.mode)) { this.#uiReadyPromise = Promise.resolve() return this.#uiReadyPromise } @@ -327,6 +313,7 @@ class SeleniumDevToolsPlugin { } configure(opts: DevToolsOptions = {}) { + assertDevToolsMode(opts.mode) if ('rerunCommand' in opts) { this.#rerunManager.configure(opts.rerunCommand) this.#options.rerunCommand = opts.rerunCommand @@ -340,16 +327,11 @@ class SeleniumDevToolsPlugin { } // A preload already registered keeps the policy it was built with; only sessions started after this see a change. this.#applyCapturePolicy('secrets' in opts || 'maskInputs' in opts) - if (opts.screencast) { - if (this.#options.mode === 'trace' && opts.screencast.enabled) { - log.warn('trace mode: ignoring screencast option (live-mode feature)') - } else { - this.#screencastOptions = { - ...this.#screencastOptions, - ...opts.screencast - } - } + const ignored = ignoredOptionsWarning(opts, this.#options.mode) + if (ignored) { + log.warn(ignored) } + this.#screencastSettings.update(opts.screencast, this.#options.mode) } get options() { @@ -372,7 +354,7 @@ class SeleniumDevToolsPlugin { return self.#options }, get screencastOptions() { - return self.#screencastOptions + return self.#screencastSettings.effective }, get detectedRunner() { return DETECTED_RUNNER @@ -547,7 +529,7 @@ class SeleniumDevToolsPlugin { actionSnapshots: this.#actionSnapshots, frames: this.#screencast?.frames, outcomes: this.#testManager?.lastTestOutcomes() ?? [], - captureFormat: this.#screencastOptions.captureFormat, + captureFormat: this.#screencastSettings.effective.captureFormat, testFilePath: this.#testFilePath, onArtifact: (a) => this.#artifacts.push(a), onLog: (level, msg) => log[level](msg) @@ -585,7 +567,11 @@ class SeleniumDevToolsPlugin { /** Fallback path only: under the preload the destination instrumented itself. */ async instrumentNavigationTarget() { const capturer = this.#sessionCapturer - if (!capturer || capturer.preloadRegistered) { + if ( + !observesPage(this.#options.mode) || + !capturer || + capturer.preloadRegistered + ) { return } await capturer.injectScript() @@ -606,6 +592,9 @@ class SeleniumDevToolsPlugin { * front mid-test. Switching to the session's own window handle brings that * window forward, and only that one. */ async focusForInput() { + if (!observesPage(this.#options.mode)) { + return + } const internals = this.#getInternals() const driver = internals.driver as | (SeleniumDriverLike & { @@ -712,21 +701,26 @@ const plugin = new SeleniumDevToolsPlugin() const patched = patchSelenium({ onBeforeBuild: (builder) => { plugin.noteBuilder(builder) - ensureBidiCapability(builder) + if (observesPage(plugin.options.mode)) { + ensureBidiCapability(builder) + } if (plugin.options.headless) { ensureHeadlessChrome(builder) } }, onDriverCreated: (driver) => plugin.onDriverCreated(driver), onCommand: (cmd) => plugin.onCommand(cmd), + observesPage: () => observesPage(plugin.options.mode), afterNavigation: () => plugin.instrumentNavigationTarget(), beforeInput: () => plugin.focusForInput(), beforeTyping: (element, args) => - noteTypedIntoElement( - element, - args, - plugin.sessionCapturer?.isNativeAppSession === true - ), + observesPage(plugin.options.mode) + ? noteTypedIntoElement( + element, + args, + plugin.sessionCapturer?.isNativeAppSession === true + ) + : Promise.resolve(), afterActions: (driver) => plugin.onActionsPerformed(driver), // Per-scenario cleanup ONLY here (finalizes that driver's screencast, // clears per-driver state). The session-wide teardown — set-finalized, @@ -745,12 +739,15 @@ if (patched) { } // Patch eagerly (user specs must see the wrappers before they import assert); -// the gate runs at capture time because DevTools.configure() may arrive later. -patchNodeAssert((cmd) => { - if (plugin.options.captureAssertions) { - void plugin.onCommand(cmd) - } -}) +// the gate runs per call because DevTools.configure() may change the mode later. +patchNodeAssert( + (cmd) => { + if (plugin.options.captureAssertions) { + void plugin.onCommand(cmd) + } + }, + () => observesPage(plugin.options.mode) +) const runnerHookCallbacks: RunnerHookCallbacks = { onTestStart: (name, file, callSource, suiteName, suiteCallSource, attempt) => diff --git a/packages/selenium-devtools/src/session-lifecycle.ts b/packages/selenium-devtools/src/session-lifecycle.ts index a6e0db49..51251927 100644 --- a/packages/selenium-devtools/src/session-lifecycle.ts +++ b/packages/selenium-devtools/src/session-lifecycle.ts @@ -36,6 +36,11 @@ import { attachBidiHandlers, buildBidiSinks } from './bidi.js' import { getDriverOriginals } from './driverPatcher.js' import { gracefulShutdown } from './helpers/processHooks.js' import { isRunnerless } from './helpers/runtime.js' +import { + capturesTrace, + startsBackend, + observesPage +} from '@wdio/devtools-shared' import type { ActionSnapshot, DetectedRunner, @@ -60,7 +65,7 @@ export interface SessionLifecycleCtx { openUi: boolean captureScreenshots: boolean rerunCommand?: string - mode?: DevToolsMode + mode: DevToolsMode traceFormat?: TraceFormat traceGranularity?: TraceGranularity tracePolicy?: TraceRetentionPolicy @@ -69,7 +74,7 @@ export interface SessionLifecycleCtx { video?: TraceVideoPolicy emitArtifactsManifest?: boolean } - readonly screencastOptions: ScreencastOptions + readonly screencastOptions: Readonly<ScreencastOptions> /** The JS test runner `detectRunner` found (mocha/jest/cucumber). Distinct * from `Metadata.runner`, which names this adapter for every one of them. */ readonly detectedRunner: DetectedRunner @@ -89,7 +94,7 @@ export interface SessionLifecycleCtx { testFilePath: string | undefined keepAliveTimer: ReturnType<typeof setInterval> | undefined - // Populated by handleOnCommand when mode === 'trace'. + // Per-action snapshots, trace mode only; filled by queueActionSnapshot. readonly actionSnapshots: ActionSnapshot[] readonly snapshotCaptures: Promise<void>[] @@ -132,12 +137,15 @@ export async function onDriverCreated( } ctx.driver = driver - // In trace mode there's no backend to forward events to — pass an empty + // Without a backend there's nothing to forward events to — pass an empty // opts bag so SessionCapturerBase skips its WS init. ctx.sessionCapturer = new SessionCapturer( - ctx.options.mode === 'trace' - ? {} - : { hostname: ctx.options.hostname, port: ctx.options.port }, + { + ...(startsBackend(ctx.options.mode) + ? { hostname: ctx.options.hostname, port: ctx.options.port } + : {}), + captureOutput: observesPage(ctx.options.mode) + }, driver ) ctx.sessionCapturer.pageResourceStore.configure(ctx.options) @@ -177,13 +185,14 @@ function ctxPluginRef(ctx: SessionLifecycleCtx): unknown { * a non-`off` per-test `video` policy or `filmstrip` — both feed the recorder * even though live screencast is off in trace mode (parity with the service). */ function shouldRecordScreencast(ctx: SessionLifecycleCtx): boolean { - if (ctx.options.mode === 'trace') { + const mode = ctx.options.mode + if (capturesTrace(mode)) { return ( (!!ctx.options.video && ctx.options.video !== 'off') || !!ctx.options.filmstrip ) } - return !!ctx.screencastOptions.enabled + return startsBackend(mode) && !!ctx.screencastOptions.enabled } async function initPerDriverCapture( @@ -201,7 +210,8 @@ async function initPerDriverCapture( detectedRunner: ctx.detectedRunner, rerunCommand: ctx.options.rerunCommand, rerunTemplate: ctx.rerunTemplate, - launchCommand: ctx.launchCommand + launchCommand: ctx.launchCommand, + observePage: observesPage(ctx.options.mode) }) ctx.sessionId = sessionId if (metadata) { @@ -239,6 +249,9 @@ function startNativeNetwork( capturer: SessionCapturer, driver: SeleniumDriverLike ): Promise<void> { + if (!observesPage(ctx.options.mode)) { + return Promise.resolve() + } const exec = getDriverOriginals().executeScript return capturer.nativeNetwork.start({ requested: ctx.interceptRequestedFor(driver), @@ -254,6 +267,9 @@ async function attachBidi( ctx: SessionLifecycleCtx, driver: SeleniumDriverLike ): Promise<void> { + if (!observesPage(ctx.options.mode)) { + return + } try { const attached = await attachBidiHandlers( driver, @@ -285,6 +301,9 @@ function registerPreload( ctx: SessionLifecycleCtx, driver: SeleniumDriverLike ): Promise<void> { + if (!observesPage(ctx.options.mode)) { + return Promise.resolve() + } const capturer = ctx.sessionCapturer if (!capturer) { return Promise.resolve() @@ -311,13 +330,16 @@ export async function onDriverEnd(ctx: SessionLifecycleCtx): Promise<void> { // action) leaves the destination's async initial anchor unrun at teardown. // Live mode goes through the post-command queue instead, so the drains // still in flight land before the session goes away. - await (ctx.options.mode === 'trace' - ? ctx.sessionCapturer.captureTrace(true) - : ctx.sessionCapturer.drainAfterLiveCommand()) + const mode = ctx.options.mode + if (capturesTrace(mode)) { + await ctx.sessionCapturer.captureTrace(true) + } else if (startsBackend(mode)) { + await ctx.sessionCapturer.drainAfterLiveCommand() + } await settlePageResources(ctx) } if (ctx.screencast && ctx.sessionId) { - if (ctx.options.mode === 'trace') { + if (!startsBackend(ctx.options.mode)) { // Trace mode: the video is emitted per-test (sliced in #emitTestArtifacts) // and there's no dashboard to receive a session recording — just stop the // recorder to release resources; never encode an orphan session webm. @@ -369,15 +391,16 @@ export async function onSessionEnd(ctx: SessionLifecycleCtx): Promise<void> { logSessionSummary(ctx) ctx.sessionCapturer?.cleanup() - if (ctx.options.openUi && ctx.options.mode !== 'trace' && !ctx.isReuse) { + const mode = ctx.options.mode + if (ctx.options.openUi && startsBackend(mode) && !ctx.isReuse) { handleInteractivePath(ctx, shutdownStart) return } - // trace mode: no UI to wait for; close the WS so the backend can wind + // No UI to wait for (trace or telemetry): close the WS so the backend can wind // down naturally. process.exit is avoided — Jest/runners may treat // forced exits as failures. - if (ctx.options.mode === 'trace' && !ctx.isReuse) { + if (!startsBackend(mode) && !ctx.isReuse) { try { await ctx.sessionCapturer?.closeWebSocket() } catch { @@ -604,7 +627,7 @@ async function writeTraceIfNeeded( testFilePath: string | undefined ): Promise<void> { const sessionId = capturer?.metadata?.sessionId - if (ctx.options.mode !== 'trace' || !capturer || !sessionId) { + if (startsBackend(ctx.options.mode) || !capturer || !sessionId) { return } await finalizeTraceExport( diff --git a/packages/selenium-devtools/src/session.ts b/packages/selenium-devtools/src/session.ts index 42c3cc46..96c1d73c 100644 --- a/packages/selenium-devtools/src/session.ts +++ b/packages/selenium-devtools/src/session.ts @@ -15,7 +15,8 @@ import { PENDING_SETTLE_TIMEOUT_MS, serializeError, settlePending, - CAPTURE_CALL_TIMED_OUT + CAPTURE_CALL_TIMED_OUT, + type SessionCapturerOptions } from '@wdio/devtools-core' import { COLLECTOR_INJECT_SCRIPT, @@ -70,7 +71,7 @@ export class SessionCapturer extends SessionCapturerBase { #socket: IncomingMessage['socket'] | undefined constructor( - devtoolsOptions: { hostname?: string; port?: number } = {}, + devtoolsOptions: SessionCapturerOptions = {}, driver?: SeleniumDriverLike ) { super(devtoolsOptions) diff --git a/packages/selenium-devtools/src/types.ts b/packages/selenium-devtools/src/types.ts index c00fd3ea..c940b014 100644 --- a/packages/selenium-devtools/src/types.ts +++ b/packages/selenium-devtools/src/types.ts @@ -163,6 +163,8 @@ export interface DriverPatcherHooks { beforeTyping?: (element: unknown, args: unknown[]) => Promise<void> // Fired after perform() settles, failed too: a partly performed sequence may already have moved the page. afterActions?: (driver: SeleniumDriverLike) => void + // False in telemetry: onCommand still runs for its test lifecycle, but each command's args, result and stack are not read. + observesPage?: () => boolean } // Unwrapped WebDriver methods used by the plugin's own internal calls diff --git a/packages/selenium-devtools/src/wait-tracking.ts b/packages/selenium-devtools/src/wait-tracking.ts index 6bb7fc2c..31e0ee9d 100644 --- a/packages/selenium-devtools/src/wait-tracking.ts +++ b/packages/selenium-devtools/src/wait-tracking.ts @@ -94,7 +94,8 @@ type WaitOutcome = { value: unknown } | { error: unknown } export function trackWaits( proto: Patchable, emit: (cmd: CapturedCommand) => void, - WebElementPromise?: WebElementPromiseCtor + WebElementPromise?: WebElementPromiseCtor, + observesPage?: () => boolean ): void { const original = proto.wait if (typeof original !== 'function' || proto[WAIT_TRACKED_SYMBOL]) { @@ -106,6 +107,13 @@ export function trackWaits( condition: unknown, ...rest: unknown[] ) { + // Telemetry records no rows, so a wait there is selenium's own: no row, no poll scope, no serialized result. + if (observesPage?.() === false) { + return (original as (...a: unknown[]) => unknown).apply(this, [ + condition, + ...rest + ]) + } const outer = waitPoll.getStore() const scope = scopeFor(outer, condition) const settle = openWaitRow(emit, outer?.scope, scope, condition, rest[0]) diff --git a/packages/selenium-devtools/tests/assert-gate.test.ts b/packages/selenium-devtools/tests/assert-gate.test.ts new file mode 100644 index 00000000..b1576df2 --- /dev/null +++ b/packages/selenium-devtools/tests/assert-gate.test.ts @@ -0,0 +1,33 @@ +import assert from 'node:assert' +import { describe, expect, it, vi } from 'vitest' + +vi.mock('../src/helpers/detachedBackend.js', () => ({ + startDetachedBackend: vi.fn() +})) + +const { DevTools } = await import('../src/index.js') + +function failureMessage(): string { + try { + assert.strict.equal('Example Domain', 'This Is Not The Heading') + } catch (err) { + return (err as Error).message + } + return '' +} + +describe('node:assert patch per mode', () => { + it("leaves a telemetry run's assertion error as node wrote it, and rewrites it in trace mode", () => { + DevTools.configure({ mode: 'trace' }) + expect(failureMessage()).toContain("Expected: 'This Is Not The Heading'") + DevTools.configure({ mode: 'telemetry' }) + expect(failureMessage()).not.toContain( + "Expected: 'This Is Not The Heading'" + ) + }) + + it('rewrites the assertion error in trace mode even with captureAssertions off', () => { + DevTools.configure({ mode: 'trace', captureAssertions: false }) + expect(failureMessage()).toContain("Expected: 'This Is Not The Heading'") + }) +}) diff --git a/packages/selenium-devtools/tests/configure-warning.test.ts b/packages/selenium-devtools/tests/configure-warning.test.ts new file mode 100644 index 00000000..81db3eed --- /dev/null +++ b/packages/selenium-devtools/tests/configure-warning.test.ts @@ -0,0 +1,32 @@ +import { describe, expect, it, vi } from 'vitest' + +const warn = vi.hoisted(() => vi.fn()) +vi.mock('@wdio/logger', () => ({ + default: () => ({ info: vi.fn(), warn, error: vi.fn(), debug: vi.fn() }) +})) +vi.mock('../src/helpers/detachedBackend.js', () => ({ + startDetachedBackend: vi.fn() +})) + +const { DevTools } = await import('../src/index.js') + +describe('configure', () => { + it('names what a trace-mode configure ignores with the shared warning', () => { + warn.mockClear() + DevTools.configure({ mode: 'trace', screencast: { enabled: true } }) + expect(warn).toHaveBeenCalledWith( + expect.stringMatching(/^trace mode ignores `screencast\.enabled`/) + ) + expect(warn).not.toHaveBeenCalledWith( + expect.stringContaining('ignoring screencast option') + ) + }) + + it('names trace-only keys a telemetry configure ignores', () => { + warn.mockClear() + DevTools.configure({ mode: 'telemetry', video: 'on' }) + expect(warn).toHaveBeenCalledWith( + 'telemetry mode ignores `video` (trace mode only).' + ) + }) +}) diff --git a/packages/selenium-devtools/tests/driverMetadata.test.ts b/packages/selenium-devtools/tests/driverMetadata.test.ts index 3044ff21..a0c59a14 100644 --- a/packages/selenium-devtools/tests/driverMetadata.test.ts +++ b/packages/selenium-devtools/tests/driverMetadata.test.ts @@ -42,6 +42,7 @@ async function metadataFor(detectedRunner: string | null) { const { metadata } = await buildDriverMetadata({ driver: driverStub(), driverReadyTs: Date.now(), + observePage: true, detectedRunner }) return metadata as { @@ -89,6 +90,7 @@ describe('buildDriverMetadata', () => { getSession: () => Promise.reject(new Error('no such session')) } as unknown as SeleniumDriverLike, driverReadyTs: Date.now(), + observePage: true, detectedRunner: 'mocha' }) @@ -113,6 +115,7 @@ describe('buildDriverMetadata capability serialization', () => { const { metadata } = await buildDriverMetadata({ driver: driverStub('sess-1', NATIVE), driverReadyTs: Date.now(), + observePage: true, detectedRunner: 'mocha' }) @@ -123,6 +126,7 @@ describe('buildDriverMetadata capability serialization', () => { const { metadata } = await buildDriverMetadata({ driver: driverStub('sess-1', NATIVE), driverReadyTs: Date.now(), + observePage: true, detectedRunner: 'mocha' }) @@ -139,6 +143,7 @@ describe('buildDriverMetadata capability serialization', () => { getCapabilities: () => Promise.resolve({ browserName: 'firefox' }) } as unknown as SeleniumDriverLike, driverReadyTs: Date.now(), + observePage: true, detectedRunner: 'mocha' }) @@ -161,6 +166,7 @@ describe('buildDriverMetadata viewport', () => { const { metadata } = await buildDriverMetadata({ driver: driverStub(), driverReadyTs: Date.now(), + observePage: true, detectedRunner: 'mocha' }) expect((metadata as { viewport?: unknown }).viewport).toEqual({ @@ -184,6 +190,7 @@ describe('buildDriverMetadata viewport', () => { 'appium:automationName': 'UiAutomator2' }), driverReadyTs: Date.now(), + observePage: true, detectedRunner: 'mocha' }) expect((metadata as { viewport?: unknown }).viewport).toEqual({ @@ -203,9 +210,29 @@ describe('buildDriverMetadata viewport', () => { const { metadata } = await buildDriverMetadata({ driver: driverStub(), driverReadyTs: Date.now(), + observePage: true, detectedRunner: 'mocha' }) expect(metadata).toBeDefined() expect('viewport' in (metadata as object)).toBe(false) }) }) + +describe('buildDriverMetadata without a page to observe', () => { + it('reads no viewport and sends no page command', async () => { + const executeScript = vi.fn().mockResolvedValue({ width: 1, height: 1 }) + const getRect = vi.fn() + const manage = vi.fn().mockReturnValue({ window: () => ({ getRect }) }) + setDriverOriginalsForTest({ executeScript, manage }) + const { metadata } = await buildDriverMetadata({ + driver: driverStub(), + driverReadyTs: Date.now(), + observePage: false, + detectedRunner: 'mocha' + }) + expect('viewport' in (metadata as object)).toBe(false) + expect(executeScript).not.toHaveBeenCalled() + expect(manage).not.toHaveBeenCalled() + expect(getRect).not.toHaveBeenCalled() + }) +}) diff --git a/packages/selenium-devtools/tests/driverPatcher.test.ts b/packages/selenium-devtools/tests/driverPatcher.test.ts index 1f60a604..37456e58 100644 --- a/packages/selenium-devtools/tests/driverPatcher.test.ts +++ b/packages/selenium-devtools/tests/driverPatcher.test.ts @@ -1,14 +1,22 @@ -import { describe, it, expect, vi } from 'vitest' +import { describe, it, expect, vi, beforeEach } from 'vitest' import { isInputDispatchInFlight } from '@wdio/devtools-core' import { isWebElementLike, + makeWrappedMethod, safeSerialize, webElementSummary, getDriverOriginals, getElementOriginals } from '../src/driverPatcher.js' import { patchActions } from '../src/helpers/actions-patcher.js' -import type { DriverPatcherHooks } from '../src/types.js' +import { getCallSourceFromStack } from '../src/helpers/utils.js' +import type * as UtilsModule from '../src/helpers/utils.js' +import type { CapturedCommand, DriverPatcherHooks } from '../src/types.js' + +vi.mock('../src/helpers/utils.js', async (importOriginal) => ({ + ...(await importOriginal<typeof UtilsModule>()), + getCallSourceFromStack: vi.fn(() => ({ callSource: 'spec.ts:1' })) +})) describe('isWebElementLike', () => { it('detects an object with getId + click as a WebElement', () => { @@ -212,3 +220,56 @@ describe('patchActions', () => { expect(isInputDispatchInFlight()).toBe(false) }) }) + +describe('makeWrappedMethod', () => { + beforeEach(() => { + vi.mocked(getCallSourceFromStack).mockClear() + }) + + function wrapGet(observesPage: boolean) { + const original = vi.fn(() => 'page-title') + const onCommand = vi.fn<(cmd: CapturedCommand) => void>() + const hooks = { + onDriverCreated: () => {}, + onCommand, + observesPage: () => observesPage + } as unknown as DriverPatcherHooks + const wrapped = makeWrappedMethod(original, 'get', false, hooks) + return { original, onCommand, wrapped } + } + + it('in telemetry, skips the stack walk and serialization but still calls the original and reports the command', () => { + const { original, onCommand, wrapped } = wrapGet(false) + + const out = wrapped('https://example.test', { using: 'id', value: 'a' }) + + expect(out).toBe('page-title') + expect(original).toHaveBeenCalledWith('https://example.test', { + using: 'id', + value: 'a' + }) + expect(getCallSourceFromStack).not.toHaveBeenCalled() + expect(onCommand).toHaveBeenCalledTimes(1) + expect(onCommand.mock.calls[0]![0]).toMatchObject({ + command: 'get', + args: [], + result: undefined + }) + }) + + it('with the page observed, walks the stack and reports the serialized args and result', () => { + const { original, onCommand, wrapped } = wrapGet(true) + + const out = wrapped('https://example.test') + + expect(out).toBe('page-title') + expect(original).toHaveBeenCalledWith('https://example.test') + expect(getCallSourceFromStack).toHaveBeenCalled() + expect(onCommand.mock.calls[0]![0]).toMatchObject({ + command: 'get', + args: ['https://example.test'], + callSource: 'spec.ts:1', + result: 'page-title' + }) + }) +}) diff --git a/packages/selenium-devtools/tests/mode-validation.test.ts b/packages/selenium-devtools/tests/mode-validation.test.ts new file mode 100644 index 00000000..772ae9af --- /dev/null +++ b/packages/selenium-devtools/tests/mode-validation.test.ts @@ -0,0 +1,14 @@ +import { describe, expect, it, vi } from 'vitest' +import { DevTools } from '../src/index.js' + +vi.mock('../src/helpers/detachedBackend.js', () => ({ + startDetachedBackend: vi.fn() +})) + +describe('selenium mode validation', () => { + it('throws from configure for an unknown mode', () => { + expect(() => DevTools.configure({ mode: 'Trace' as never })).toThrow( + 'Unknown DevTools mode "Trace"; expected one of: live, trace, telemetry' + ) + }) +}) diff --git a/packages/selenium-devtools/tests/screencast-options.test.ts b/packages/selenium-devtools/tests/screencast-options.test.ts new file mode 100644 index 00000000..924a63e8 --- /dev/null +++ b/packages/selenium-devtools/tests/screencast-options.test.ts @@ -0,0 +1,66 @@ +import { describe, expect, it } from 'vitest' +import { SCREENCAST_DEFAULTS } from '@wdio/devtools-shared' +import { + ScreencastSettings, + screencastFor +} from '../src/helpers/screencast-options.js' + +describe('screencastFor', () => { + it('keeps the tuning fields outside live mode and drops only enabled', () => { + expect( + screencastFor( + { + ...SCREENCAST_DEFAULTS, + enabled: true, + quality: 40, + pollIntervalMs: 500 + }, + 'trace' + ) + ).toEqual({ + ...SCREENCAST_DEFAULTS, + quality: 40, + pollIntervalMs: 500, + enabled: false + }) + }) + + it('applies every field in live mode', () => { + expect( + screencastFor({ ...SCREENCAST_DEFAULTS, enabled: true }, 'live') + ).toEqual({ ...SCREENCAST_DEFAULTS, enabled: true }) + }) +}) + +describe('ScreencastSettings', () => { + it('records again after a live, trace, live toggle, keeping the tuning fields', () => { + const settings = new ScreencastSettings( + { enabled: true, quality: 40 }, + 'live' + ) + expect(settings.effective).toMatchObject({ enabled: true, quality: 40 }) + settings.update(undefined, 'trace') + expect(settings.effective).toMatchObject({ enabled: false, quality: 40 }) + settings.update(undefined, 'live') + expect(settings.effective).toMatchObject({ enabled: true, quality: 40 }) + }) + + it('rejects a write to the options it hands out, which the next update would lose', () => { + const settings = new ScreencastSettings({ enabled: true }, 'live') + expect(() => { + // @ts-expect-error the effective options are read-only + settings.effective.enabled = false + }).toThrow(TypeError) + expect(settings.effective.enabled).toBe(true) + }) + + it('merges each configure call over the earlier input', () => { + const settings = new ScreencastSettings({ quality: 40 }, 'live') + settings.update({ pollIntervalMs: 500 }, 'live') + expect(settings.effective).toMatchObject({ + quality: 40, + pollIntervalMs: 500, + enabled: SCREENCAST_DEFAULTS.enabled + }) + }) +}) diff --git a/packages/selenium-devtools/tests/session.test.ts b/packages/selenium-devtools/tests/session.test.ts index e98a5385..dc41a51c 100644 --- a/packages/selenium-devtools/tests/session.test.ts +++ b/packages/selenium-devtools/tests/session.test.ts @@ -457,6 +457,7 @@ describe('selenium SessionCapturer on a native session', () => { }) } as never, driverReadyTs: Date.now(), + observePage: true, detectedRunner: 'mocha' }) const cap = makeCapturer({}) diff --git a/packages/selenium-devtools/tests/telemetry-mode.test.ts b/packages/selenium-devtools/tests/telemetry-mode.test.ts new file mode 100644 index 00000000..aaad1bed --- /dev/null +++ b/packages/selenium-devtools/tests/telemetry-mode.test.ts @@ -0,0 +1,305 @@ +import { afterEach, describe, expect, it, vi } from 'vitest' +import type * as DevToolsCore from '@wdio/devtools-core' +import type * as BidiModule from '../src/bidi.js' +import { NativeNetworkCapture, RetryTracker } from '@wdio/devtools-core' +import type { ActionSnapshot } from '@wdio/devtools-shared' + +import { resetSignatureCounters } from '../src/helpers/utils.js' +import { TestManager } from '../src/helpers/testManager.js' +import { SuiteManager } from '../src/helpers/suiteManager.js' +import { TestReporter } from '../src/reporter.js' +import { SessionCapturer } from '../src/session.js' +import { + onDriverCreated, + onSessionEnd, + type SessionLifecycleCtx +} from '../src/session-lifecycle.js' +import { + handleOnCommand, + type OnCommandCtx +} from '../src/helpers/commandPostActions.js' +import { captureFinalFrame } from '../src/helpers/finalFrame.js' +import { getDriverOriginals } from '../src/driverPatcher.js' +import type { + CapturedCommand, + DevToolsMode, + SeleniumDriverLike +} from '../src/types.js' + +const finalizeTraceExport = vi.hoisted(() => vi.fn(async () => [])) +const registerCollectorPreload = vi.hoisted(() => + vi.fn(async () => true as boolean) +) +const attachBidiHandlers = vi.hoisted(() => vi.fn(async () => true)) + +vi.mock('@wdio/devtools-core', async (importOriginal) => ({ + ...(await importOriginal<typeof DevToolsCore>()), + finalizeTraceExport, + registerCollectorPreload +})) + +vi.mock('../src/bidi.js', async (importOriginal) => ({ + ...(await importOriginal<typeof BidiModule>()), + attachBidiHandlers +})) + +const SESSION_ID = 'sess-abcd1234ef' +const capturers: SessionCapturer[] = [] + +afterEach(() => { + while (capturers.length) { + capturers.pop()!.cleanup() + } + vi.clearAllMocks() +}) + +function makeCapturer() { + const capturer = new SessionCapturer() + capturer.metadata = { sessionId: SESSION_ID } as SessionCapturer['metadata'] + capturers.push(capturer) + const drains = { + liveDrain: vi.spyOn(capturer, 'drainAfterLiveCommand').mockResolvedValue(), + traceDrain: vi.spyOn(capturer, 'captureTrace').mockResolvedValue(), + reinject: vi.spyOn(capturer, 'reinjectIfNavigated').mockResolvedValue() + } + return { capturer, ...drains } +} + +function makeSessionEndCtx(mode: DevToolsMode, capturer: SessionCapturer) { + return { + options: { + hostname: 'localhost', + port: 3000, + openUi: true, + captureScreenshots: false, + mode, + traceFormat: 'zip', + traceGranularity: 'session', + tracePolicy: 'on', + filmstrip: false, + video: 'off', + emitArtifactsManifest: false + }, + screencastOptions: { enabled: false }, + driver: {}, + sessionCapturer: capturer, + finalized: false, + isReuse: false, + testFilePath: '/specs/login.spec.ts', + artifacts: [], + actionSnapshots: [] as ActionSnapshot[], + snapshotCaptures: [] as Promise<void>[], + traceFlushes: [] as Promise<unknown>[], + filmstripFrames: [], + specRanges: [], + flushedSpecs: new Set<string>(), + setFinalized: vi.fn(), + resetRetryTracker: vi.fn() + } as unknown as SessionLifecycleCtx +} + +function makeCommandCtx(mode: DevToolsMode, capturer: SessionCapturer) { + resetSignatureCounters() + const reporter = new TestReporter(vi.fn()) + const suiteManager = new SuiteManager(reporter) + const rootSuite = suiteManager.getOrCreateRootSuite('login.spec.ts', 'Suite') + const testManager = new TestManager(rootSuite, reporter, suiteManager) + const snapshotCaptures: Promise<void>[] = [] + const ctx = { + sessionCapturer: capturer, + testManager, + retryTracker: new RetryTracker(), + options: { captureScreenshots: false, mode }, + finalized: false, + driver: undefined, + actionSnapshots: [] as ActionSnapshot[], + snapshotCaptures + } as unknown as OnCommandCtx + return { ctx, snapshotCaptures } +} + +function cmd(overrides: Partial<CapturedCommand>): CapturedCommand { + return { + command: 'sendKeys', + args: [], + timestamp: 0, + startTime: 0, + fromElement: true, + result: undefined, + error: undefined, + callSource: undefined, + ...overrides + } +} + +describe('telemetry mode: session end', () => { + it('reaches the finalizer so the manifest is written, with no per-action capture', async () => { + const { capturer, liveDrain, traceDrain } = makeCapturer() + const ctx = makeSessionEndCtx('telemetry', capturer) + + await onSessionEnd(ctx) + + expect(finalizeTraceExport).toHaveBeenCalledTimes(1) + expect(finalizeTraceExport).toHaveBeenCalledWith( + expect.objectContaining({ mode: 'telemetry' }) + ) + expect(traceDrain).not.toHaveBeenCalled() + expect(liveDrain).not.toHaveBeenCalled() + }) + + it('still runs the trace-mode end-of-session capture', async () => { + const { capturer, traceDrain } = makeCapturer() + const ctx = makeSessionEndCtx('trace', capturer) + + await onSessionEnd(ctx) + + expect(traceDrain).toHaveBeenCalledWith(true) + expect(finalizeTraceExport).toHaveBeenCalledWith( + expect.objectContaining({ mode: 'trace' }) + ) + }) +}) + +describe('telemetry mode: command capture', () => { + it.each([['sendKeys'], ['click'], ['clear']])( + 'takes no DOM drain after %s', + async (command) => { + const { capturer, liveDrain, traceDrain, reinject } = makeCapturer() + const { ctx, snapshotCaptures } = makeCommandCtx('telemetry', capturer) + + await handleOnCommand(ctx, cmd({ command })) + await Promise.all(snapshotCaptures) + + expect(liveDrain).not.toHaveBeenCalled() + expect(traceDrain).not.toHaveBeenCalled() + expect(reinject).not.toHaveBeenCalled() + } + ) + + it('takes no end-of-test frame', async () => { + const captureEndFrame = vi.fn(async () => {}) + const ctx = { + options: { mode: 'telemetry' }, + finalized: false, + driver: {}, + sessionCapturer: { testCapture: { captureEndFrame } } + } as unknown as Parameters<typeof captureFinalFrame>[0] + + await captureFinalFrame(ctx) + + expect(captureEndFrame).not.toHaveBeenCalled() + }) +}) + +describe('telemetry mode: no page injection, preload or BiDi attach', () => { + function makeLifecycleCtx(mode: DevToolsMode): SessionLifecycleCtx { + return { + options: { hostname: 'localhost', port: 0, mode }, + screencastOptions: {}, + detectedRunner: 'mocha', + finalized: false, + interceptRequestedFor: () => true, + driver: undefined, + sessionCapturer: undefined, + actionSnapshots: [], + snapshotCaptures: [], + specRanges: [], + flushedSpecs: new Set<string>(), + traceFlushes: [], + artifacts: [], + filmstripFrames: [], + setFinalized: () => {}, + ensureBackendStarted: async () => {}, + flushPendingTestActions: () => {}, + resetRetryTracker: () => {}, + clearKeepAlive: () => {} + } as unknown as SessionLifecycleCtx + } + + it.each([ + ['telemetry', false], + ['trace', true] + ] as const)( + '%s: driver bringup patches stdout: %s', + async (mode, patched) => { + vi.spyOn(NativeNetworkCapture.prototype, 'start').mockResolvedValue() + const write = process.stdout.write + const ctx = makeLifecycleCtx(mode) + + await onDriverCreated(ctx, { id: 'd' } as unknown as SeleniumDriverLike) + + expect(process.stdout.write !== write).toBe(patched) + ctx.sessionCapturer?.cleanup() + } + ) + + it.each([ + ['telemetry', 0], + ['trace', 1] + ] as const)( + '%s: driver bringup registers the preload, attaches BiDi and starts native network %i time(s)', + async (mode, expected) => { + const start = vi + .spyOn(NativeNetworkCapture.prototype, 'start') + .mockResolvedValue() + const ctx = makeLifecycleCtx(mode) + + await onDriverCreated(ctx, { id: 'd' } as unknown as SeleniumDriverLike) + + expect(registerCollectorPreload).toHaveBeenCalledTimes(expected) + expect(attachBidiHandlers).toHaveBeenCalledTimes(expected) + expect(start).toHaveBeenCalledTimes(expected) + ctx.sessionCapturer?.cleanup() + } + ) + + it.each([ + ['telemetry', 0], + ['trace', 1] + ] as const)( + '%s: a navigation injects no collector and logs no command row (%i)', + async (mode, expected) => { + const { capturer } = makeCapturer() + const inject = vi.spyOn(capturer, 'injectScript').mockResolvedValue() + const { ctx, snapshotCaptures } = makeCommandCtx(mode, capturer) + + await handleOnCommand(ctx, cmd({ command: 'get', fromElement: false })) + await Promise.all(snapshotCaptures) + + expect(inject).toHaveBeenCalledTimes(expected) + expect(capturer.commandsLog.length).toBe(expected) + } + ) + + it.each([ + ['telemetry', false], + ['trace', true] + ] as const)( + '%s: the published metadata has a viewport only when observed (%s)', + async (mode, observed) => { + vi.spyOn(NativeNetworkCapture.prototype, 'start').mockResolvedValue() + const originals = getDriverOriginals() as Record<string, unknown> + const executeScript = vi.fn().mockResolvedValue({ width: 1, height: 1 }) + const manage = vi.fn() + Object.assign(originals, { executeScript, manage }) + const driver = { + getSession: () => Promise.resolve({ getId: () => 'sess-1' }), + getCapabilities: () => Promise.resolve({ browserName: 'chrome' }) + } as unknown as SeleniumDriverLike + const ctx = makeLifecycleCtx(mode) + + try { + await onDriverCreated(ctx, driver) + + const metadata = ctx.sessionCapturer?.metadata as object + expect('viewport' in metadata).toBe(observed) + expect(executeScript.mock.calls.length > 0).toBe(observed) + expect(manage.mock.calls.length > 0).toBe(false) + } finally { + delete originals.executeScript + delete originals.manage + ctx.sessionCapturer?.cleanup() + } + } + ) +}) diff --git a/packages/selenium-devtools/tests/wait-telemetry.test.ts b/packages/selenium-devtools/tests/wait-telemetry.test.ts new file mode 100644 index 00000000..07705f0d --- /dev/null +++ b/packages/selenium-devtools/tests/wait-telemetry.test.ts @@ -0,0 +1,33 @@ +import { describe, expect, it, vi } from 'vitest' +import { trackWaits, waitPollOf } from '../src/wait-tracking.js' +import type { Patchable } from '../src/types.js' + +type Wait = (condition: () => unknown) => unknown + +function trackedWait(observesPage: boolean) { + const emit = vi.fn() + const proto: Patchable = { + wait(condition: () => unknown) { + return condition() + } + } + trackWaits(proto, emit, undefined, () => observesPage) + const pollOfACall = () => waitPollOf('findElement', ['#x'], '#x') + return { wait: proto.wait as Wait, emit, pollOfACall } +} + +describe('trackWaits per mode', () => { + it('leaves a telemetry wait as selenium wrote it: no row and no poll scope', () => { + const { wait, emit, pollOfACall } = trackedWait(false) + expect(wait(pollOfACall)).toBeUndefined() + expect(emit).not.toHaveBeenCalled() + }) + + it('opens a row and a poll scope when the page is observed', async () => { + const { wait, emit, pollOfACall } = trackedWait(true) + expect(await wait(pollOfACall)).toMatchObject({ + pollKey: expect.any(String) + }) + expect(emit).toHaveBeenCalledTimes(2) + }) +}) diff --git a/packages/service/README.md b/packages/service/README.md index b469d160..87e08e1b 100644 --- a/packages/service/README.md +++ b/packages/service/README.md @@ -72,6 +72,8 @@ Set `mode: 'trace'` to skip the live UI window and write a portable `trace.zip` `test-results/` directory at session end — meant for CI, offline replay, and agentic diffing. See the [full trace mode docs](https://webdriver.io/docs/devtools/wdio/trace-mode). +Set `mode: 'telemetry'` to record nothing but the run's outcome: no backend, UI window, screencast, per-action capture or zip. It still runs the test lifecycle and writes a `devtools-artifacts-<sessionId>.json` manifest at session end, with each test's state and the trace id of every attempt, so reporters and CI can link a run to its traces without paying for them. + Open a trace in the first-party player: ```sh @@ -278,7 +280,7 @@ services: [['devtools', options]] | `hostname` | `string` | `'localhost'` | Hostname the DevTools UI server binds to | | `devtoolsCapabilities` | `Capabilities` | Chrome 1600×1200 | Capabilities used to open the DevTools UI window | | `screencast` | `ScreencastOptions` | — | Session video recording (live mode only — see below; for trace mode use `video`) | -| `mode` | `'live' \| 'trace'` | `'live'` | `'live'` opens the DevTools UI window; `'trace'` skips the UI and writes a `trace-<sessionId>.zip` under a `test-results/` directory (base dir resolved from the test file's dir → config dir → cwd) at session end. See [Trace mode](../../README.md#-trace-mode-tracezip) | +| `mode` | `'live' \| 'trace' \| 'telemetry'` | `'live'` | `'live'` opens the DevTools UI window; `'trace'` skips the UI and writes a `trace-<sessionId>.zip` under a `test-results/` directory (base dir resolved from the test file's dir → config dir → cwd) at session end. `'telemetry'` skips the UI and captures nothing per action, writing only the artifacts manifest (per-attempt trace ids, no zips). See [Trace mode](../../README.md#-trace-mode-tracezip) | | `traceFormat` | `'zip' \| 'ndjson-directory'` | `'zip'` | Trace mode only. Output layout — `'zip'` writes a single archive; `'ndjson-directory'` unpacks the same files into `trace-<id>/` (one less unzip step for scripted/agentic consumers). The `zip` opens in `show-trace`; a directory opens in other compatible viewers, or zip it first. | | `traceGranularity` | `'session' \| 'spec' \| 'test'` | `'session'` | Trace mode only. How traces are partitioned — one per worker session / spec file / test. `'test'` is required for per-test Allure attachments (trace, screenshot, video). | | `tracePolicy` | `TraceRetentionPolicy` | `'on'` | Trace mode only. Which traces to keep: `'on'` \| `'retain-on-failure'` \| `'retain-on-first-failure'` \| `'on-first-retry'` \| `'on-all-retries'` \| `'retain-on-failure-and-retries'`. The retry-aware policies pair best with `traceGranularity: 'test'`. | @@ -286,7 +288,7 @@ services: [['devtools', options]] | `video` | `'off' \| TraceRetentionPolicy` | `'off'` | Trace mode + `traceGranularity: 'test'`. Per-test screencast video, retained per the given policy, attached inline to Allure (`video/webm`). WDIO-service-specific. | | `filmstrip` | `boolean` | `true` | Trace mode only. Records a dense, continuous screencast filmstrip *into* the trace so the player scrubs smooth playback: dense frames are added alongside the per-action frames (not one frame per action). Frames are thinned (≥100 ms apart, ~600 max) and content-addressed (identical frames, such as a static wait, collapse to one resource); windowed per slice at any `traceGranularity`. Runs the screencast recorder (CDP push on Chrome, polling elsewhere). The polling recorder skips a tick while a command or a per-action capture holds the driver (once the newest frame is three intervals old it polls anyway, so the longest gap is about three intervals plus one screenshot; never during a click, typing or a capture), and keeps each per-action capture's screenshot as a frame, so its polls do not queue in front of the test. | | `traceResources` | `'styles'` \| `'none'` | `'styles'` | Trace mode only. `'styles'` stores the stylesheets and fonts each archive's pages used, once each by content hash, so the player replays them from the archive rather than the site; `'none'` stores nothing. Images always replay from the site. See the [root README](../../README.md#options) for caps and how the reads are kept out of the network rows. | -| `emitArtifactsManifest` | `boolean` | `false` | Trace mode only. Writes `devtools-artifacts-<sessionId>.json` next to the trace — a generic index of every produced artifact (trace/screenshot/video) plus each test's state, for reporters/CI to consume. Off by default; **auto-enabled when a reporter whose name contains `allure` (such as `@wdio/allure-reporter`) is in the config**, unless set to `false`. | +| `emitArtifactsManifest` | `boolean` | `false` | Ignored in live mode; trace mode honours it and `mode: 'telemetry'` always writes it. Writes `devtools-artifacts-<sessionId>.json` next to the trace — a generic index of every produced artifact (trace/screenshot/video) plus each test's state, for reporters/CI to consume. Off by default; **auto-enabled when a reporter whose name contains `allure` (such as `@wdio/allure-reporter`) is in the config**, unless set to `false`. | | `captureAssertions` | `boolean` | `true` | Capture assertions as command/action rows — `node:assert` plus passing *and* failing expect-webdriverio matchers, folded into single `expect.<matcher>` rows (e.g. `toHaveText`, `toExist`). Set `false` to opt out. | | `maskInputs` | `boolean` | `true` | Replace the value of password fields with `••••` in the replayed page (DOM anchor, field state, value mutations), and redact what was typed into them, and the values of `Authorization`, `Proxy-Authorization`, `Cookie` and `Set-Cookie` headers, from command rows, network, console and the trace, live and trace mode alike. `false` turns both off. See [Password masking](../../README.md#-password-masking) and [Secret redaction](../../README.md#-secret-redaction). | | `maskSelectors` | `string[]` | `[]` | Also mask the text and value of every element these CSS selectors match, and everything inside it, in the replayed page. | diff --git a/packages/service/src/assertion-tracker.ts b/packages/service/src/assertion-tracker.ts index d1a41960..8a07bd35 100644 --- a/packages/service/src/assertion-tracker.ts +++ b/packages/service/src/assertion-tracker.ts @@ -4,7 +4,11 @@ import logger from '@wdio/logger' import { errorMessage } from '@wdio/devtools-core' -import type { ActionSnapshot } from '@wdio/devtools-shared' +import { + capturesTrace, + observesPage, + type ActionSnapshot +} from '@wdio/devtools-shared' import { captureExpectFailure, expectAssertionToCommandLog, @@ -54,6 +58,14 @@ export class AssertionTracker { this.#ctx = ctx } + // Telemetry observes no page, so a matcher row (and its screenshot) would have no reader. + #capturing(): boolean { + return ( + this.#ctx.options.captureAssertions !== false && + observesPage(this.#ctx.options.mode) + ) + } + /** True while an expect-webdriverio matcher is polling, so a capture taken now is one of its polls. */ get matcherPolling(): boolean { return this.#assertionDepth > 0 @@ -77,7 +89,7 @@ export class AssertionTracker { matcherName: string expectedValue?: unknown }): void { - if (this.#ctx.options.captureAssertions === false) { + if (!this.#capturing()) { return } if (this.#assertionDepth === 0) { @@ -104,7 +116,7 @@ export class AssertionTracker { * this reliable hook: no `#assertionDepth`, no stack-frame detection. */ async afterAssertion(params: ExpectAssertion): Promise<void> { - if (this.#ctx.options.captureAssertions === false) { + if (!this.#capturing()) { return } this.#assertionDepth = Math.max(0, this.#assertionDepth - 1) @@ -136,7 +148,7 @@ export class AssertionTracker { log.debug(`assertion screenshot skipped: ${errorMessage(err)}`) } } - if (this.#ctx.options.mode === 'trace' && browser) { + if (capturesTrace(this.#ctx.options.mode) && browser) { await pushActionSnapshotAt( browser, entry.command, @@ -152,7 +164,7 @@ export class AssertionTracker { * afterAssertion never fired — synthesize its failing expect row. Any other * failure just marks the last action with the error. */ handleOutcome(error: unknown): void { - if (this.#ctx.options.captureAssertions === false) { + if (!this.#capturing()) { return } if (this.#pendingAssertion) { diff --git a/packages/service/src/index.ts b/packages/service/src/index.ts index e6836642..1cb2f167 100644 --- a/packages/service/src/index.ts +++ b/packages/service/src/index.ts @@ -15,7 +15,6 @@ import { resolveAdapterOutputDir, stepMetadataUid, TestAttemptTracker, - tracePolicyModeWarning, upsertRichestSnapshot, type TraceArtifact, type TraceExportContext, @@ -41,10 +40,15 @@ import { settleAfterLastAction } from './action-snapshot.js' import { + assertDevToolsMode, + capturesTrace, + ignoredOptionsWarning, isWaitCommand, skipsCapture, + startsBackend, type ActionSnapshot, - type TestMetadataMap + type TestMetadataMap, + observesPage } from '@wdio/devtools-shared' import { SevereServiceError } from 'webdriverio' import type { Services, Capabilities, Options, Reporters } from '@wdio/types' @@ -92,7 +96,7 @@ export { setupForDevtools } from './standalone.js' export default class DevToolsHookService implements Services.ServiceInstance { #testReporters: TestReporter[] = [] - #sessionCapturer = new SessionCapturer() + #sessionCapturer: SessionCapturer #browser?: WebdriverIO.Browser #options: ServiceOptions #actionSnapshots: ActionSnapshot[] = [] @@ -109,11 +113,15 @@ export default class DevToolsHookService implements Services.ServiceInstance { #slices: TraceSliceTracker constructor(serviceOptions: ServiceOptions = {}) { + assertDevToolsMode(serviceOptions.mode) this.#options = serviceOptions configureInputMasking(serviceOptions) for (const warning of configureSecretRedaction(serviceOptions)) { log.warn(warning) } + this.#sessionCapturer = new SessionCapturer({ + captureOutput: observesPage(serviceOptions.mode) + }) this.#assertionTracker = new AssertionTracker({ getCapturer: () => this.#sessionCapturer, getBrowser: () => this.#browser, @@ -122,8 +130,8 @@ export default class DevToolsHookService implements Services.ServiceInstance { options: this.#options, actionSnapshots: this.#actionSnapshots }) - const policyWarning = tracePolicyModeWarning( - serviceOptions.tracePolicy, + const policyWarning = ignoredOptionsWarning( + serviceOptions, serviceOptions.mode ) if (policyWarning) { @@ -254,13 +262,14 @@ export default class DevToolsHookService implements Services.ServiceInstance { const wdioCaps = caps as Capabilities.W3CCapabilities & { 'wdio:devtoolsOptions'?: ServiceOptions } - this.#sessionCapturer = new SessionCapturer( - wdioCaps['wdio:devtoolsOptions'] - ) + this.#sessionCapturer = new SessionCapturer({ + ...wdioCaps['wdio:devtoolsOptions'], + captureOutput: observesPage(this.#options.mode) + }) this.#sessionCapturer.traceMode = this.#options.mode ?? 'live' this.#sessionCapturer.pageResourceStore.configure(this.#options) // The dashboard window took the front; Safari clicks reach nothing there. - if ((this.#options.mode ?? 'live') === 'live') { + if (startsBackend(this.#options.mode)) { const caps = browser.capabilities as { browserName?: string; platformName?: string } | undefined restoreBrowserFocus({ @@ -273,7 +282,10 @@ export default class DevToolsHookService implements Services.ServiceInstance { stampRunnerMetadata(this.#sessionCapturer, browser, this.captureType) publishConfigFile(this.#sessionCapturer) - if (this.#options.captureAssertions !== false) { + if ( + this.#options.captureAssertions !== false && + observesPage(this.#options.mode) + ) { wireAssertCapture( () => this.#sessionCapturer, () => this.#currentTestUid @@ -285,7 +297,7 @@ export default class DevToolsHookService implements Services.ServiceInstance { * Skip on native mobile — Appium sessions don't support WebDriver BiDi * and the injection always fails with SevereServiceError. */ - if (!isAppiumSession(browser)) { + if (!isAppiumSession(browser) && observesPage(this.#options.mode)) { try { await this.#injectScriptSync(browser) } catch (err) { @@ -297,13 +309,15 @@ export default class DevToolsHookService implements Services.ServiceInstance { // WDIO has already subscribed the BiDi events by now, so attaching here // issues no mid-run protocol traffic and misses no early events. - if (browser.isBidi) { + if (browser.isBidi && observesPage(this.#options.mode)) { attachBidiListeners(browser, this.#sessionCapturer) } await this.#screencast.start(browser) - this.#nativeNetwork = new InterceptedNetwork(caps, this.#sessionCapturer) - await this.#nativeNetwork.start(browser) + if (observesPage(this.#options.mode)) { + this.#nativeNetwork = new InterceptedNetwork(caps, this.#sessionCapturer) + await this.#nativeNetwork.start(browser) + } /** * Propagate session metadata at the beginning of the session. Not awaited @@ -345,7 +359,11 @@ export default class DevToolsHookService implements Services.ServiceInstance { async #captureSessionMetadata(browser: WebdriverIO.Browser): Promise<void> { try { this.#sessionCapturer.mergeMetadata( - await resolveSessionMetadata(browser, this.captureType) + await resolveSessionMetadata( + browser, + this.captureType, + observesPage(this.#options.mode) + ) ) } catch (err) { log.warn(`Could not capture session metadata: ${errorMessage(err)}`) @@ -631,7 +649,7 @@ export default class DevToolsHookService implements Services.ServiceInstance { } async #finalizePerScenario() { - if (this.#options.mode !== 'trace' || !this.#browser) { + if (!capturesTrace(this.#options.mode) || !this.#browser) { return } // Drain the collector one final time while the session is still alive, so the @@ -820,6 +838,15 @@ export default class DevToolsHookService implements Services.ServiceInstance { if (!this.#browser || isServiceProbe(command)) { return } + // `url` is the one start-of-recording signal every runner reaches (Mocha, + // Jasmine, Cucumber, standalone), so the video's start marker hangs off it. + if (command === 'url') { + this.#screencast.markStart() + this.#sessionCapturer.sendUpstream('metadata', { url: args[0] }) + } + if (!observesPage(this.#options.mode)) { + return + } this.#typedInput.read(this.#browser, command, args) // Holds the filmstrip poll off the driver for the whole command (see // driver-activity.ts); opened before the pre-action probes so it spans them. @@ -829,12 +856,6 @@ export default class DevToolsHookService implements Services.ServiceInstance { this.#closeCommandWindow?.() this.#closeCommandWindow = beginDriverCommand(command) } - // `url` is the one start-of-recording signal every runner reaches (Mocha, - // Jasmine, Cucumber, standalone), so the video's start marker hangs off it. - if (command === 'url') { - this.#screencast.markStart() - this.#sessionCapturer.sendUpstream('metadata', { url: args[0] }) - } // Synchronous, and settled BEFORE any await below: afterCommand pops exactly // what this pushed, so a push stranded behind an await would let a same-tick // afterCommand miss the frame. @@ -866,7 +887,7 @@ export default class DevToolsHookService implements Services.ServiceInstance { // session is captured normally. if ( topLevelUserCommand && - this.#options.mode === 'trace' && + capturesTrace(this.#options.mode) && this.#browser && !inPageProbesDeadlock( this.#browser, @@ -928,6 +949,10 @@ export default class DevToolsHookService implements Services.ServiceInstance { error: Error | undefined, issuedByService: boolean ) { + // Pairs with #beforeCommand, which pushes no command frame without observesPage. + if (!observesPage(this.#options.mode)) { + return + } // Skip bookkeeping for internal injection calls and the snapshot's own probes if (this.#injecting || isServiceProbe(command)) { return @@ -969,7 +994,7 @@ export default class DevToolsHookService implements Services.ServiceInstance { ) // Trace mode captures nothing here: the state this action produced is // taken by the NEXT action's pre-capture, when the app has settled. - if (this.#options.mode !== 'trace') { + if (startsBackend(this.#options.mode)) { await this.#drainAfterLiveCommand(command) } await this.#nativeNetwork?.forward({ throttle: true }) @@ -1097,7 +1122,11 @@ export default class DevToolsHookService implements Services.ServiceInstance { async #ensureInjected(reason: string) { // Keep this for re-injection after context changes - if (!this.#browser || this.#injecting) { + if ( + !this.#browser || + this.#injecting || + !observesPage(this.#options.mode) + ) { return } try { diff --git a/packages/service/src/launcher.ts b/packages/service/src/launcher.ts index e98bc04c..ccb62be8 100644 --- a/packages/service/src/launcher.ts +++ b/packages/service/src/launcher.ts @@ -3,7 +3,12 @@ import http from 'node:http' import { remote } from 'webdriverio' import { start } from '@wdio/devtools-backend' import logger from '@wdio/logger' -import { REUSE_ENV, RUNNER_ENV } from '@wdio/devtools-shared' +import { + assertDevToolsMode, + REUSE_ENV, + RUNNER_ENV, + startsBackend +} from '@wdio/devtools-shared' import { resolveRunId } from '@wdio/devtools-core' import { DEFAULT_LAUNCH_CAPS } from './constants.js' import { configPathFromArgv, detectInvocationSpecs } from './invocation-args.js' @@ -43,6 +48,7 @@ export class DevToolsAppLauncher { #browser?: WebdriverIO.Browser constructor(options: ServiceOptions) { + assertDevToolsMode(options.mode) this.#options = options } @@ -70,8 +76,9 @@ export class DevToolsAppLauncher { // every worker this run forks then reports the same run id, which is what // stops the backend reading the next spec's worker as a new run. resolveRunId() - if (this.#options.mode === 'trace') { - log.info('Trace mode — skipping backend and Chrome window') + const mode = this.#options.mode ?? 'live' + if (!startsBackend(mode)) { + log.info(`${mode} mode — skipping backend and Chrome window`) return } try { diff --git a/packages/service/src/screencast-lifecycle.ts b/packages/service/src/screencast-lifecycle.ts index 4d8a2835..835c9e91 100644 --- a/packages/service/src/screencast-lifecycle.ts +++ b/packages/service/src/screencast-lifecycle.ts @@ -3,6 +3,7 @@ // slice. The plugin only forwards its hooks here — everything that reads or // writes recorder frames lives in this file. +import { capturesTrace, startsBackend } from '@wdio/devtools-shared' import { accumulatedScreencastFrames, captureAndAttachVideo, @@ -61,13 +62,6 @@ export class ScreencastLifecycle { constructor(ctx: ScreencastLifecycleContext) { this.#ctx = ctx - if (ctx.options.mode === 'trace' && ctx.options.screencast?.enabled) { - ctx.log( - 'warn', - 'trace mode: `screencast.enabled` is ignored — use `video` to record; ' + - 'the tuning fields (quality/interval) still apply' - ) - } } /** Filmstrip defaults ON in trace mode; explicit `filmstrip: false` opts out. */ @@ -79,13 +73,16 @@ export class ScreencastLifecycle { * mode: a non-`off` `video` policy (frames sliced per test at flush) or * `filmstrip` (dense frames written into the trace itself). */ #shouldRecord(): boolean { - if (this.#ctx.options.mode === 'trace') { + if (capturesTrace(this.#ctx.options.mode)) { return ( (!!this.#ctx.options.video && this.#ctx.options.video !== 'off') || this.#filmstripOn() ) } - return !!this.#ctx.options.screencast?.enabled + return ( + startsBackend(this.#ctx.options.mode) && + !!this.#ctx.options.screencast?.enabled + ) } /** Whole-run filmstrip frames for the export context: earlier sessions' @@ -133,7 +130,7 @@ export class ScreencastLifecycle { // cucumber `After(() => reloadSession())` is WDIO boilerplate), by which // point the recorder below has replaced these frames. Snapshot them now, // keyed to the ending test, so afterScenario can still slice its video. - if (this.#ctx.options.mode === 'trace' && this.#recorder) { + if (capturesTrace(this.#ctx.options.mode) && this.#recorder) { const frames = [...this.#recorder.frames] this.#pendingVideoFrames = { testUid: this.#ctx.getTestUid(), @@ -166,7 +163,7 @@ export class ScreencastLifecycle { // Trace mode: the video is emitted per-test (sliced in attachTestVideo), // and there's no dashboard to receive a session recording — so just stop the // recorder to release resources; never encode an orphan session-wide webm. - if (this.#ctx.options.mode === 'trace') { + if (!startsBackend(this.#ctx.options.mode)) { await this.#recorder.stop() return } diff --git a/packages/service/src/session-metadata.ts b/packages/service/src/session-metadata.ts index 79132cb3..518dfc8a 100644 --- a/packages/service/src/session-metadata.ts +++ b/packages/service/src/session-metadata.ts @@ -61,10 +61,11 @@ async function resolveViewport( */ export async function resolveSessionMetadata( browser: WebdriverIO.Browser, - type: TraceType + type: TraceType, + readsViewport = true ): Promise<Partial<Metadata>> { const capabilities = browser.capabilities as Capabilities.W3CCapabilities - const viewport = await resolveViewport(browser) + const viewport = readsViewport ? await resolveViewport(browser) : undefined const device = deviceFromCapabilities(capabilities) return { type, diff --git a/packages/service/src/session.ts b/packages/service/src/session.ts index 51968567..a34cda9b 100644 --- a/packages/service/src/session.ts +++ b/packages/service/src/session.ts @@ -14,7 +14,11 @@ import { rememberElementSelector, selectorForCommand } from './command-selectors.js' -import { isNativeAppSession, sessionHasDocument } from '@wdio/devtools-shared' +import { + isNativeAppSession, + sessionHasDocument, + observesPage +} from '@wdio/devtools-shared' import { isAppiumSession } from './mobile.js' import { applyPerformanceData, @@ -28,8 +32,10 @@ import { LOG_SOURCES, rememberReadValue, RetryTracker, - SessionCapturerBase + SessionCapturerBase, + type SessionCapturerOptions } from '@wdio/devtools-core' +import { startsBackend } from '@wdio/devtools-shared' import type { DevToolsMode, TraceMutation } from '@wdio/devtools-shared' import type { CommandLog } from './types.js' import { serializeCommandError } from './command-error.js' @@ -97,7 +103,7 @@ export class SessionCapturer extends SessionCapturerBase { } >() - constructor(devtoolsOptions: { hostname?: string; port?: number } = {}) { + constructor(devtoolsOptions: SessionCapturerOptions = {}) { super(devtoolsOptions) this.patchConsole() this.patchStreams() @@ -215,8 +221,11 @@ export class SessionCapturer extends SessionCapturerBase { // mobile BROWSER session keeps the old behaviour throughout: it replays // from its mutation stream. const nativeLiveCapture = - this.traceMode !== 'trace' && isNativeAppSession(browser.capabilities) - if (!isAppiumSession(browser) || nativeLiveCapture) { + startsBackend(this.traceMode) && isNativeAppSession(browser.capabilities) + if ( + observesPage(this.traceMode) && + (!isAppiumSession(browser) || nativeLiveCapture) + ) { try { commandLogEntry.screenshot = await screenshotWithin( browser, diff --git a/packages/service/src/trace-slices.ts b/packages/service/src/trace-slices.ts index 25b20534..00be1abb 100644 --- a/packages/service/src/trace-slices.ts +++ b/packages/service/src/trace-slices.ts @@ -11,6 +11,7 @@ import { type TraceArtifact, type TraceExportContext } from '@wdio/devtools-core' +import { capturesTrace } from '@wdio/devtools-shared' import type { SessionCapturer } from './session.js' import type { ServiceOptions } from './types.js' @@ -75,7 +76,7 @@ export class TraceSliceTracker { const browser = this.#ctx.getBrowser() if ( this.#ctx.options.traceGranularity !== 'test' || - this.#ctx.options.mode !== 'trace' || + !capturesTrace(this.#ctx.options.mode) || !browser ) { return undefined diff --git a/packages/service/tests/assertion-rows.test.ts b/packages/service/tests/assertion-rows.test.ts index d8e6735a..7569dd60 100644 --- a/packages/service/tests/assertion-rows.test.ts +++ b/packages/service/tests/assertion-rows.test.ts @@ -159,6 +159,27 @@ describe('DevtoolsService — expect.* assertion rows', () => { expect(pushActionSnapshotAt).not.toHaveBeenCalled() }) + it('telemetry takes no screenshot and logs no row for a matcher it cannot fold', async () => { + capturer.coalesceAssertionIntoLastRead.mockReturnValue(false) + const service = new DevToolsHookService({ mode: 'telemetry' }) + await service.before({} as never, [], mockBrowser) + + await service.beforeAssertion({ matcherName: 'toBe', expectedValue: 1 }) + await service.afterAssertion({ + matcherName: 'toBe', + expectedValue: 1, + result: { pass: true } + }) + await service.afterTest({ file: '/s.ts' } as never, undefined, { + passed: false, + error: new Error('boom') + } as never) + + expect(mockBrowser.takeScreenshot).not.toHaveBeenCalled() + expect(capturer.captureMatcherCommand).not.toHaveBeenCalled() + expect(capturer.failLastAction).not.toHaveBeenCalled() + }) + it('afterAssertion clears the armed matcher so test end does not re-synthesize', async () => { capturer.coalesceAssertionIntoLastRead.mockReturnValue(true) const service = new DevToolsHookService({ mode: 'live' }) diff --git a/packages/service/tests/index.test.ts b/packages/service/tests/index.test.ts index 9cb522d8..5e258f21 100644 --- a/packages/service/tests/index.test.ts +++ b/packages/service/tests/index.test.ts @@ -12,6 +12,9 @@ import { selectorForReadValue } from '@wdio/devtools-core' import DevToolsHookService from '../src/index.js' +import { attachBidiListeners } from '../src/bidi-listeners.js' +import { specFrameBelow } from '../src/call-source.js' +import type * as CallSource from '../src/call-source.js' // Controllable stack: `frames` defaults to a single user-spec frame (commands // read as top-level). A test can splice in `matcherFrame` to simulate a command @@ -62,6 +65,10 @@ const mockSessionCapturerInstance = { metadata: { url: 'http://test.com', viewport: {} } } +vi.mock('../src/bidi-listeners.js', () => ({ + attachBidiListeners: vi.fn() +})) + vi.mock('../src/session.js', () => ({ SessionCapturer: vi.fn(function (this: any) { return mockSessionCapturerInstance @@ -106,6 +113,10 @@ const mockNativeNetwork = { forward: vi.fn().mockResolvedValue(undefined) } +vi.mock('../src/call-source.js', async (importOriginal) => { + const actual = await importOriginal<typeof CallSource>() + return { ...actual, specFrameBelow: vi.fn(actual.specFrameBelow) } +}) vi.mock('../src/intercepted-network.js', () => ({ InterceptedNetwork: vi.fn(function () { return mockNativeNetwork @@ -507,6 +518,78 @@ describe('DevtoolsService - Internal Command Filtering', () => { ) expect(mockSessionCapturerInstance.captureTrace).not.toHaveBeenCalled() }) + + it('neither injects the collector nor attaches BiDi listeners in telemetry mode', async () => { + vi.clearAllMocks() + const telemetryBrowser = { + ...mockBrowser, + isBidi: true, + waitUntil: vi.fn().mockResolvedValue(true), + pause: vi.fn().mockResolvedValue(undefined), + getUrl: vi.fn().mockResolvedValue('http://test.com'), + getTitle: vi.fn().mockResolvedValue('title') + } as any + await new DevToolsHookService({ mode: 'telemetry' }).before( + {} as any, + [], + telemetryBrowser + ) + expect(mockSessionCapturerInstance.injectScript).not.toHaveBeenCalled() + expect(attachBidiListeners).not.toHaveBeenCalled() + + vi.clearAllMocks() + await new DevToolsHookService({ mode: 'live' }).before( + {} as any, + [], + telemetryBrowser + ) + expect(mockSessionCapturerInstance.injectScript).toHaveBeenCalled() + expect(attachBidiListeners).toHaveBeenCalled() + }) + + it('does not drain or flush in telemetry mode', async () => { + const telemetryBrowser = { + ...mockBrowser, + waitUntil: vi.fn().mockResolvedValue(true), + pause: vi.fn().mockResolvedValue(undefined), + getUrl: vi.fn().mockResolvedValue('http://test.com'), + getTitle: vi.fn().mockResolvedValue('title') + } as any + const telemetryService = new DevToolsHookService({ mode: 'telemetry' }) + await telemetryService.before({} as any, [], telemetryBrowser) + vi.clearAllMocks() + telemetryService.beforeCommand('click' as any, ['button']) + await telemetryService.afterCommand('click' as any, ['button'], {}) + telemetryService.beforeCommand('setValue' as any, ['#username', 'foobar']) + await telemetryService.afterCommand( + 'setValue' as any, + ['#username', 'foobar'], + {} + ) + expect(mockSessionCapturerInstance.captureTrace).not.toHaveBeenCalled() + }) + + it('walks no call stack per command in telemetry mode, and does in live', async () => { + const telemetryBrowser = { + ...mockBrowser, + waitUntil: vi.fn().mockResolvedValue(true), + pause: vi.fn().mockResolvedValue(undefined), + getUrl: vi.fn().mockResolvedValue('http://test.com'), + getTitle: vi.fn().mockResolvedValue('title') + } as any + const telemetryService = new DevToolsHookService({ mode: 'telemetry' }) + await telemetryService.before({} as any, [], telemetryBrowser) + vi.clearAllMocks() + await telemetryService.beforeCommand('click' as any, ['button']) + await telemetryService.afterCommand('click' as any, ['button'], {}) + expect(specFrameBelow).not.toHaveBeenCalled() + + const liveService = new DevToolsHookService({ mode: 'live' }) + await liveService.before({} as any, [], telemetryBrowser) + vi.clearAllMocks() + await liveService.beforeCommand('click' as any, ['button']) + expect(specFrameBelow).toHaveBeenCalled() + }) }) }) diff --git a/packages/service/tests/launcher.test.ts b/packages/service/tests/launcher.test.ts index c3a45e83..64c342ab 100644 --- a/packages/service/tests/launcher.test.ts +++ b/packages/service/tests/launcher.test.ts @@ -72,6 +72,16 @@ describe('DevToolsAppLauncher', () => { expect(mockBrowser.url).toHaveBeenCalledWith('http://localhost:3000') }) + it('skips the backend and the window in telemetry mode', async () => { + const launcher = new DevToolsAppLauncher({ mode: 'telemetry' }) + const caps = [{ browserName: 'chrome' }] as any + + await launcher.onPrepare(undefined as never, caps) + + expect(backend.start).not.toHaveBeenCalled() + expect(caps[0]['wdio:devtoolsOptions']).toBeUndefined() + }) + it('should use custom hostname', async () => { const customServer = { address: () => ({ port: 4000 }) } vi.mocked(backend.start).mockResolvedValue({ diff --git a/packages/service/tests/mode-validation.test.ts b/packages/service/tests/mode-validation.test.ts new file mode 100644 index 00000000..e45d741a --- /dev/null +++ b/packages/service/tests/mode-validation.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest' +import DevToolsHookService from '../src/index.js' +import { DevToolsAppLauncher } from '../src/launcher.js' + +const MESSAGE = + 'Unknown DevTools mode "Trace"; expected one of: live, trace, telemetry' + +describe('service mode validation', () => { + it('throws at launcher construction for an unknown mode', () => { + expect(() => new DevToolsAppLauncher({ mode: 'Trace' as never })).toThrow( + MESSAGE + ) + }) + + it('throws at worker service construction for an unknown mode', () => { + expect(() => new DevToolsHookService({ mode: 'Trace' as never })).toThrow( + MESSAGE + ) + }) +}) diff --git a/packages/service/tests/screencast-lifecycle.test.ts b/packages/service/tests/screencast-lifecycle.test.ts index 49f919d7..35026d5e 100644 --- a/packages/service/tests/screencast-lifecycle.test.ts +++ b/packages/service/tests/screencast-lifecycle.test.ts @@ -64,6 +64,11 @@ describe('ScreencastLifecycle.start', () => { it.each([ ['live, no options', {}, false], ['live, screencast enabled', { screencast: { enabled: true } }, true], + [ + 'telemetry, screencast enabled', + { mode: 'telemetry', screencast: { enabled: true } }, + false + ], ['trace, filmstrip default-on', { mode: 'trace' }, true], [ 'trace, filmstrip off + no video', @@ -276,22 +281,7 @@ describe('ScreencastLifecycle.finalize', () => { }) }) -describe('ScreencastLifecycle option warnings', () => { - it('warns that screencast.enabled is ignored in trace mode', () => { - const log = vi.fn() - makeLifecycle({ mode: 'trace', screencast: { enabled: true } }, { log }) - expect(log).toHaveBeenCalledWith( - 'warn', - expect.stringContaining('`screencast.enabled` is ignored') - ) - }) - - it('stays quiet in live mode', () => { - const log = vi.fn() - makeLifecycle({ screencast: { enabled: true } }, { log }) - expect(log).not.toHaveBeenCalled() - }) - +describe('ScreencastLifecycle markStart', () => { it('markStart forwards to the recorder only while one exists', async () => { const { lifecycle } = makeLifecycle({ screencast: { enabled: true } }) lifecycle.markStart() diff --git a/packages/service/tests/session-metadata.test.ts b/packages/service/tests/session-metadata.test.ts index 7436dfb1..eaf24eac 100644 --- a/packages/service/tests/session-metadata.test.ts +++ b/packages/service/tests/session-metadata.test.ts @@ -180,3 +180,24 @@ describe('resolveSessionMetadata', () => { expect(metadata.options).toEqual({ hostname: 'localhost' }) }) }) + +describe('resolveSessionMetadata without the viewport', () => { + it('makes no driver round trip when the mode reads no page', async () => { + const execute = vi.fn() + const getWindowSize = vi.fn() + const browser = { + capabilities: { browserName: 'chrome' }, + options: {}, + execute, + getWindowSize + } as unknown as WebdriverIO.Browser + const metadata = await resolveSessionMetadata( + browser, + TraceType.Testrunner, + false + ) + expect(execute).not.toHaveBeenCalled() + expect(getWindowSize).not.toHaveBeenCalled() + expect(metadata.viewport).toBeUndefined() + }) +}) diff --git a/packages/service/tests/telemetry-output.test.ts b/packages/service/tests/telemetry-output.test.ts new file mode 100644 index 00000000..419d411a --- /dev/null +++ b/packages/service/tests/telemetry-output.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from 'vitest' +import DevToolsHookService from '../src/index.js' + +describe('service console and stdout capture per mode', () => { + it('leaves console and stdout unpatched in telemetry mode', () => { + const write = process.stdout.write + const log = console.log + new DevToolsHookService({ mode: 'telemetry' }) + expect([process.stdout.write, console.log]).toEqual([write, log]) + }) + + it('patches them in trace mode, which reads them into the trace', () => { + const write = process.stdout.write + const log = console.log + new DevToolsHookService({ mode: 'trace' }) + const patched = process.stdout.write !== write && console.log !== log + process.stdout.write = write + console.log = log + expect(patched).toBe(true) + }) +}) diff --git a/packages/service/tests/trace-granularity.test.ts b/packages/service/tests/trace-granularity.test.ts index 7981377f..8edc6a96 100644 --- a/packages/service/tests/trace-granularity.test.ts +++ b/packages/service/tests/trace-granularity.test.ts @@ -219,6 +219,21 @@ describe('DevtoolsService - trace granularity slicing', () => { expect(flushRangeTrace).not.toHaveBeenCalled() }) + it('telemetry: after() reaches the trace finalizer, so the manifest is written', async () => { + const service = new DevToolsHookService({ mode: 'telemetry' }) + await service.before({} as never, [], mockBrowser) + service.beforeTest({ file, fullTitle: 'logs in' }) + await service.afterTest( + { file, fullTitle: 'logs in' }, + {}, + { passed: true } + ) + await service.after() + expect(finalizeTraceExport).toHaveBeenCalledWith( + expect.objectContaining({ mode: 'telemetry' }) + ) + }) + it('prints every written trace once capture is torn down, so a warn-level config still learns where its traces went', async () => { const service = await newService('test') finalizeTraceExport.mockImplementation( diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 6aae10a4..e9984474 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -23,6 +23,7 @@ export * from './image.js' export * from './input-mask.js' export * from './player-csp.js' export * from './locator-dialect.js' +export * from './mode-traits.js' export * from './request-type.js' export * from './routes.js' export * from './run-capabilities.js' diff --git a/packages/shared/src/mode-traits.ts b/packages/shared/src/mode-traits.ts new file mode 100644 index 00000000..20d71bfb --- /dev/null +++ b/packages/shared/src/mode-traits.ts @@ -0,0 +1,124 @@ +import type { DevToolsMode } from './types.js' + +const MODE_TRAITS: Record< + DevToolsMode, + { + startsBackend: boolean + capturesTrace: boolean + forcesManifest: boolean + } +> = { + live: { + startsBackend: true, + capturesTrace: false, + forcesManifest: false + }, + trace: { + startsBackend: false, + capturesTrace: true, + forcesManifest: false + }, + telemetry: { + startsBackend: false, + capturesTrace: false, + forcesManifest: true + } +} + +const KNOWN_MODES = Object.keys(MODE_TRAITS) as DevToolsMode[] + +function assertKnownMode(mode: unknown): asserts mode is DevToolsMode { + if (!KNOWN_MODES.some((known) => known === mode)) { + throw new Error( + `Unknown DevTools mode "${String(mode)}"; expected one of: ${KNOWN_MODES.join(', ')}` + ) + } +} + +/** Adapters call this where options arrive, so a typo fails at setup rather than on the first command. */ +export function assertDevToolsMode( + mode: unknown +): asserts mode is DevToolsMode | undefined { + if (mode !== undefined) { + assertKnownMode(mode) + } +} + +function traitsOf(mode: DevToolsMode): (typeof MODE_TRAITS)[DevToolsMode] { + assertKnownMode(mode) + return MODE_TRAITS[mode] +} + +export function startsBackend(mode: DevToolsMode = 'live'): boolean { + return traitsOf(mode).startsBackend +} + +export function capturesTrace(mode: DevToolsMode = 'live'): boolean { + return traitsOf(mode).capturesTrace +} + +/** Live feeds the dashboard and trace feeds the zip; telemetry feeds neither, so nothing observes the page. */ +export function observesPage(mode: DevToolsMode = 'live'): boolean { + return startsBackend(mode) || capturesTrace(mode) +} + +/** Telemetry writes its manifest even when the trace-mode switch that gates it is off. */ +export function forcesManifest(mode: DevToolsMode = 'live'): boolean { + return traitsOf(mode).forcesManifest +} + +export interface ModeScopedOptions { + traceFormat?: unknown + traceGranularity?: unknown + tracePolicy?: unknown + filmstrip?: unknown + screenshot?: unknown + video?: unknown + traceResources?: unknown + emitArtifactsManifest?: boolean + screencast?: { enabled?: boolean } +} + +const TRACE_ONLY_OPTIONS = [ + 'traceFormat', + 'traceGranularity', + 'tracePolicy', + 'filmstrip', + 'screenshot', + 'video', + 'traceResources' +] as const + +/** Names each option the user set that this mode drops, so a run that records nothing says why; undefined when every set option applies. */ +export function ignoredOptionsWarning( + options: ModeScopedOptions, + mode: DevToolsMode = 'live' +): string | undefined { + const ignored = capturesTrace(mode) + ? [] + : TRACE_ONLY_OPTIONS.filter((key) => options[key] !== undefined).map( + (key) => `\`${key}\` (trace mode only)` + ) + if ( + !capturesTrace(mode) && + !forcesManifest(mode) && + options.emitArtifactsManifest === true + ) { + ignored.push('`emitArtifactsManifest` (trace and telemetry modes only)') + } + if (forcesManifest(mode) && options.emitArtifactsManifest === false) { + ignored.push( + '`emitArtifactsManifest: false` (telemetry always writes the manifest)' + ) + } + if (!startsBackend(mode) && options.screencast?.enabled === true) { + ignored.push( + capturesTrace(mode) + ? '`screencast.enabled` (live mode only; `filmstrip` and `video` decide recording, the quality/interval fields still apply)' + : '`screencast.enabled` (live mode only)' + ) + } + return ignored.length + ? `${mode} mode ignores ${ignored.join(', ')}.` + : undefined +} diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts index 89f1179f..1d6f268d 100644 --- a/packages/shared/src/types.ts +++ b/packages/shared/src/types.ts @@ -31,8 +31,11 @@ export enum TraceType { export type TestStatus = 'passed' | 'failed' | 'skipped' | 'pending' | 'running' -/** `live` opens the DevTools UI window; `trace` skips it and lets a downstream exporter consume captured state. */ -export type DevToolsMode = 'live' | 'trace' +/** `live` starts the backend and opens the DevTools UI window. `trace` skips + * both and writes trace zips for a downstream exporter. `telemetry` skips both + * and captures no per-action state: it writes only the artifacts manifest, + * which carries per-test lifecycle, run id and attempt trace context. */ +export type DevToolsMode = 'live' | 'trace' | 'telemetry' /** `zip` (default) writes a single `trace-<id>.zip`; `ndjson-directory` writes * the same `trace.trace` + `trace.network` + `resources/` layout unpacked @@ -456,7 +459,8 @@ export interface BaseDevToolsOptions { /** Capture node:assert assertions (and framework `expect` matchers where * supported) as first-class commands. Default true. */ captureAssertions?: boolean - /** `live` (default) launches the DevTools UI; `trace` skips it. */ + /** `live` (default) launches the DevTools UI; `trace` writes zips; `telemetry` + * writes only the artifacts manifest. */ mode?: DevToolsMode /** Trace output layout — `zip` (default) writes a single archive, * `ndjson-directory` unpacks into `trace-<id>/`. Only applies in trace mode. */ @@ -479,7 +483,8 @@ export interface BaseDevToolsOptions { * Off by default; auto-enabled when an Allure reporter is detected (WDIO: * `@wdio/allure-reporter` in config; Selenium: an active `allure-js-commons` * runtime). Nightwatch has no live Allure signal, so it stays opt-in there. - * Only applies in trace mode. */ + * Telemetry mode always writes the manifest; otherwise this only applies in + * trace mode. */ emitArtifactsManifest?: boolean /** Mask password fields in the replayed page and redact typed passwords, credential headers and cookies from what is sent and written. Default true. */ maskInputs?: boolean diff --git a/packages/shared/tests/mode-traits.test.ts b/packages/shared/tests/mode-traits.test.ts new file mode 100644 index 00000000..68179712 --- /dev/null +++ b/packages/shared/tests/mode-traits.test.ts @@ -0,0 +1,154 @@ +import { describe, expect, it } from 'vitest' +import { + assertDevToolsMode, + capturesTrace, + forcesManifest, + ignoredOptionsWarning, + observesPage, + startsBackend +} from '../src/mode-traits.js' +import type { DevToolsMode } from '../src/types.js' + +describe('mode traits', () => { + it('answers forcesManifest from the table', () => { + expect(forcesManifest('live')).toBe(false) + expect(forcesManifest('trace')).toBe(false) + expect(forcesManifest('telemetry')).toBe(true) + expect(forcesManifest(undefined)).toBe(false) + }) + + it('answers startsBackend, capturesTrace and observesPage from the table', () => { + expect(startsBackend('live')).toBe(true) + expect(startsBackend('trace')).toBe(false) + expect(startsBackend('telemetry')).toBe(false) + expect(capturesTrace('live')).toBe(false) + expect(capturesTrace('trace')).toBe(true) + expect(capturesTrace('telemetry')).toBe(false) + expect(observesPage('live')).toBe(true) + expect(observesPage('trace')).toBe(true) + expect(observesPage('telemetry')).toBe(false) + }) + + it('treats an undefined mode as live', () => { + expect(startsBackend(undefined)).toBe(true) + expect(capturesTrace(undefined)).toBe(false) + expect(observesPage(undefined)).toBe(true) + }) +}) + +describe('mode traits with an unknown mode', () => { + const unknown = (mode: string): DevToolsMode => mode as DevToolsMode + const message = (mode: string) => + new Error( + `Unknown DevTools mode "${mode}"; expected one of: live, trace, telemetry` + ) + + it('throws naming the mode and the known ones instead of a raw TypeError', () => { + expect(() => startsBackend(unknown('Trace'))).toThrow(message('Trace')) + expect(() => capturesTrace(unknown('Trace'))).toThrow(message('Trace')) + expect(() => observesPage(unknown('Trace'))).toThrow(message('Trace')) + expect(() => forcesManifest(unknown('Trace'))).toThrow(message('Trace')) + }) + + it('does not answer for a property inherited from Object.prototype', () => { + expect(() => startsBackend(unknown('toString'))).toThrow( + message('toString') + ) + }) +}) + +describe('assertDevToolsMode', () => { + const message = (mode: string) => + `Unknown DevTools mode "${mode}"; expected one of: live, trace, telemetry` + + it('accepts an absent mode and each known mode', () => { + expect(() => assertDevToolsMode(undefined)).not.toThrow() + expect(() => assertDevToolsMode('live')).not.toThrow() + expect(() => assertDevToolsMode('trace')).not.toThrow() + expect(() => assertDevToolsMode('telemetry')).not.toThrow() + }) + + it('throws the traitsOf message for a typo, including a null or inherited value', () => { + expect(() => assertDevToolsMode('Trace')).toThrow(message('Trace')) + expect(() => assertDevToolsMode('toString')).toThrow(message('toString')) + expect(() => assertDevToolsMode(null)).toThrow(message('null')) + }) +}) + +describe('ignoredOptionsWarning', () => { + it('names every capture option telemetry drops in one warning', () => { + expect( + ignoredOptionsWarning( + { video: 'on', screencast: { enabled: true } }, + 'telemetry' + ) + ).toBe( + 'telemetry mode ignores `video` (trace mode only), `screencast.enabled` (live mode only).' + ) + }) + + it('names a trace option set in live mode, the default', () => { + expect(ignoredOptionsWarning({ tracePolicy: 'retain-on-failure' })).toBe( + 'live mode ignores `tracePolicy` (trace mode only).' + ) + }) + + it('names traceResources set outside trace mode', () => { + expect(ignoredOptionsWarning({ traceResources: 'none' }, 'telemetry')).toBe( + 'telemetry mode ignores `traceResources` (trace mode only).' + ) + }) + + it('points trace mode at filmstrip and video when screencast.enabled is set', () => { + expect( + ignoredOptionsWarning({ screencast: { enabled: true } }, 'trace') + ).toMatch( + /^trace mode ignores `screencast\.enabled` .*`filmstrip` and `video` decide recording/ + ) + }) + + it('stays silent when every set option applies to the mode', () => { + expect( + ignoredOptionsWarning( + { tracePolicy: 'on', video: 'on', filmstrip: false }, + 'trace' + ) + ).toBeUndefined() + expect( + ignoredOptionsWarning({ screencast: { enabled: true } }, 'live') + ).toBeUndefined() + expect(ignoredOptionsWarning({}, 'telemetry')).toBeUndefined() + }) + + it('names emitArtifactsManifest set to true in live mode', () => { + expect(ignoredOptionsWarning({ emitArtifactsManifest: true }, 'live')).toBe( + 'live mode ignores `emitArtifactsManifest` (trace and telemetry modes only).' + ) + }) + + it('names emitArtifactsManifest set to false in telemetry mode, which always writes the manifest', () => { + expect( + ignoredOptionsWarning({ emitArtifactsManifest: false }, 'telemetry') + ).toBe( + 'telemetry mode ignores `emitArtifactsManifest: false` (telemetry always writes the manifest).' + ) + }) + + it('stays silent for emitArtifactsManifest where the mode honours it', () => { + expect( + ignoredOptionsWarning({ emitArtifactsManifest: true }, 'telemetry') + ).toBeUndefined() + expect( + ignoredOptionsWarning({ emitArtifactsManifest: true }, 'trace') + ).toBeUndefined() + expect( + ignoredOptionsWarning({ emitArtifactsManifest: false }, 'trace') + ).toBeUndefined() + expect( + ignoredOptionsWarning({ emitArtifactsManifest: false }, 'live') + ).toBeUndefined() + expect( + ignoredOptionsWarning({ emitArtifactsManifest: undefined }, 'live') + ).toBeUndefined() + }) +}) diff --git a/packages/trace/src/trace-retention.ts b/packages/trace/src/trace-retention.ts index cdc35013..62e8bd8a 100644 --- a/packages/trace/src/trace-retention.ts +++ b/packages/trace/src/trace-retention.ts @@ -1,8 +1,4 @@ -import type { - DevToolsMode, - TestStatus, - TraceRetentionPolicy -} from '@wdio/devtools-shared' +import type { TestStatus, TraceRetentionPolicy } from '@wdio/devtools-shared' /** * Pure retention policy evaluation for trace mode. Adapters collect the @@ -121,18 +117,3 @@ function finalAttempt(group: TestOutcome[]): TestOutcome { function firstAttempt(group: TestOutcome[]): TestOutcome | undefined { return group.find((o) => attemptOf(o) === 0) } - -/** - * Warning text when a retention policy is configured outside trace mode, where - * it has no effect (the finalizer no-ops in live mode). Returns undefined when - * there is nothing to warn about, so each adapter can `if (msg) log.warn(msg)`. - */ -export function tracePolicyModeWarning( - policy: TraceRetentionPolicy | undefined, - mode: DevToolsMode | undefined -): string | undefined { - if (policy === undefined || mode === 'trace') { - return undefined - } - return 'tracePolicy only applies in trace mode; ignoring it because mode is not "trace".' -} diff --git a/packages/trace/tests/trace-retention.test.ts b/packages/trace/tests/trace-retention.test.ts index 00982ea2..244ad5de 100644 --- a/packages/trace/tests/trace-retention.test.ts +++ b/packages/trace/tests/trace-retention.test.ts @@ -1,8 +1,5 @@ import { describe, it, expect } from 'vitest' -import { - shouldRetainTrace, - tracePolicyModeWarning -} from '../src/trace-retention.js' +import { shouldRetainTrace } from '../src/trace-retention.js' import type { TestOutcome } from '../src/trace-retention.js' import type { TraceRetentionPolicy } from '@wdio/devtools-shared' @@ -259,19 +256,3 @@ describe('shouldRetainTrace groups a test’s attempts by uid', () => { expect(retain('on-all-retries', passThenFail)).toBe(true) }) }) - -describe('tracePolicyModeWarning', () => { - it('warns when a policy is set outside trace mode', () => { - expect(tracePolicyModeWarning('retain-on-failure', 'live')).toMatch( - /trace mode/ - ) - expect(tracePolicyModeWarning('retain-on-failure', undefined)).toMatch( - /trace mode/ - ) - }) - - it('stays silent in trace mode or when no policy is set', () => { - expect(tracePolicyModeWarning('retain-on-failure', 'trace')).toBeUndefined() - expect(tracePolicyModeWarning(undefined, 'live')).toBeUndefined() - }) -})