From 4d0feb9391c790d16e16643b84c39a0be4a13ab5 Mon Sep 17 00:00:00 2001 From: Vince Graics Date: Mon, 9 Nov 2026 21:31:18 +0100 Subject: [PATCH 01/15] feat(core): stamp a trace and span id on each test attempt in the artifacts manifest A manifest that lists only test states cannot link a run to the traces it produced or to a CI parent span. Each attempt now mints its trace and span id when it starts, and the manifest records the run id and any TRACEPARENT parent, so an external consumer can address every attempt. Co-Authored-By: Claude Haiku 5.5 --- .changeset/manifest-cucumber-steps.md | 7 + .changeset/manifest-test-timing.md | 5 + .changeset/otel-attempt-trace-ids.md | 7 + packages/core/src/allure-artifacts.ts | 2 +- packages/core/src/artifacts-manifest.ts | 71 ++-- packages/core/src/attempt-tracker.ts | 67 +++- packages/core/src/index.ts | 5 + packages/core/src/screenshot-artifact.ts | 2 +- packages/core/src/spec-trace-helpers.ts | 25 +- packages/core/src/suite-helpers.ts | 12 + packages/core/src/trace-context.ts | 44 +++ packages/core/src/trace-finalizer.ts | 22 +- packages/core/src/uid.ts | 10 + packages/core/src/video-slice.ts | 2 +- .../core/tests/artifacts-manifest.test.ts | 248 ++++++++++++- packages/core/tests/attempt-tracker.test.ts | 114 +++++- packages/core/tests/trace-context.test.ts | 85 +++++ packages/core/tests/trace-finalizer.test.ts | 12 +- packages/core/tests/uid.test.ts | 19 +- .../src/helpers/testManager.ts | 5 +- .../nightwatch-devtools/src/session-init.ts | 8 +- .../tests/attemptTracking.test.ts | 75 ++++ .../src/helpers/testManager.ts | 6 +- packages/service/README.md | 10 +- packages/service/src/index.ts | 39 ++- packages/service/src/session.ts | 4 +- packages/service/src/test-metadata.ts | 97 +++++- packages/service/src/wait-rows.ts | 4 +- packages/service/tests/trace-metadata.test.ts | 328 +++++++++++++++++- packages/service/tests/wait-rows.test.ts | 19 + packages/shared/src/artifacts-manifest.ts | 59 ++++ packages/shared/src/index.ts | 2 + packages/shared/src/trace-context.ts | 86 +++++ packages/shared/src/types.ts | 7 + packages/shared/tests/trace-context.test.ts | 91 +++++ 35 files changed, 1485 insertions(+), 114 deletions(-) create mode 100644 .changeset/manifest-cucumber-steps.md create mode 100644 .changeset/manifest-test-timing.md create mode 100644 .changeset/otel-attempt-trace-ids.md create mode 100644 packages/core/src/trace-context.ts create mode 100644 packages/core/tests/trace-context.test.ts create mode 100644 packages/shared/src/artifacts-manifest.ts create mode 100644 packages/shared/src/trace-context.ts create mode 100644 packages/shared/tests/trace-context.test.ts diff --git a/.changeset/manifest-cucumber-steps.md b/.changeset/manifest-cucumber-steps.md new file mode 100644 index 000000000..f87ab5a39 --- /dev/null +++ b/.changeset/manifest-cucumber-steps.md @@ -0,0 +1,7 @@ +--- +'@wdio/devtools-service': patch +'@wdio/selenium-devtools': patch +'@wdio/nightwatch-devtools': patch +--- + +The artifacts manifest lists each Cucumber scenario once and no longer lists its steps as tests, and a scenario's entry now carries its attempt. diff --git a/.changeset/manifest-test-timing.md b/.changeset/manifest-test-timing.md new file mode 100644 index 000000000..bc47ca506 --- /dev/null +++ b/.changeset/manifest-test-timing.md @@ -0,0 +1,5 @@ +--- +"@wdio/devtools-service": minor +--- + +The WebdriverIO service's artifacts manifest (`devtools-artifacts-.json`) now carries each test's start and end time, framework-reported duration (Cucumber scenarios fall back to wall-clock time, since WDIO's Cucumber duration is only the nanoseconds field of the worst step), and the failure message of its final attempt, so reporters can build a per-test record without opening the trace zip. The Selenium and Nightwatch adapters do not write these fields yet. diff --git a/.changeset/otel-attempt-trace-ids.md b/.changeset/otel-attempt-trace-ids.md new file mode 100644 index 000000000..fd19d290f --- /dev/null +++ b/.changeset/otel-attempt-trace-ids.md @@ -0,0 +1,7 @@ +--- +'@wdio/devtools-service': minor +'@wdio/selenium-devtools': minor +'@wdio/nightwatch-devtools': minor +--- + +The artifacts manifest now carries the run's `runId`, the parent trace context from `TRACEPARENT` when set, and an `attempts[]` list per test whose entries hold a trace and span id minted when the attempt starts. diff --git a/packages/core/src/allure-artifacts.ts b/packages/core/src/allure-artifacts.ts index a47797532..54a8c9a71 100644 --- a/packages/core/src/allure-artifacts.ts +++ b/packages/core/src/allure-artifacts.ts @@ -27,7 +27,7 @@ import { shouldRetainTrace, type TestOutcome } from '@wdio/devtools-trace/trace-retention' -import type { TraceArtifact } from './trace-finalizer.js' +import type { TraceArtifact } from '@wdio/devtools-shared' /** Adapter-supplied binding to the active Allure reporter. Attaches one file to * the currently-executing test. Undefined = attach unsupported (produce-only). */ diff --git a/packages/core/src/artifacts-manifest.ts b/packages/core/src/artifacts-manifest.ts index 0853e4012..be8b2f570 100644 --- a/packages/core/src/artifacts-manifest.ts +++ b/packages/core/src/artifacts-manifest.ts @@ -13,31 +13,45 @@ import fs from 'node:fs/promises' import path from 'node:path' import type { + ArtifactManifestTest, + ArtifactsManifest, + TestAttemptRecord, TestMetadataEntry, TestMetadataMap, + TraceArtifact, TraceFormat } from '@wdio/devtools-shared' -import type { TraceArtifact } from './trace-finalizer.js' +import { stepOwnerUid } from './uid.js' -/** One test's outcome as recorded at export time. Field types track - * TestMetadataEntry in shared; adds the keying uid, drops trace-only ancestry. */ -export interface ArtifactManifestTest extends Pick< - TestMetadataEntry, - 'title' | 'specFile' | 'state' | 'attempt' -> { - uid: string +/** Deterministic manifest filename for a session (used by writers and readers). */ +export function artifactsManifestFilename(sessionId: string): string { + return `devtools-artifacts-${sessionId}.json` } -export interface ArtifactsManifest { - sessionId: string - format: TraceFormat - artifacts: TraceArtifact[] - tests: ArtifactManifestTest[] +// Steps stay in testMetadata for the trace's step groups but are not test units; WDIO keys one off its scenario's uid, Selenium and Nightwatch nest it as a test under a scenario suite. +function isStepEntry( + uid: string, + meta: TestMetadataEntry, + metadata: TestMetadataMap +): boolean { + const owner = stepOwnerUid(uid) + return ( + (owner !== undefined && metadata.has(owner)) || + meta.ancestry?.at(-1)?.kind === 'scenario' + ) } -/** Deterministic manifest filename for a session (used by writers and readers). */ -export function artifactsManifestFilename(sessionId: string): string { - return `devtools-artifacts-${sessionId}.json` +/** Stamps `final` on the attempt the test ended on, else on the last one recorded: the manifest reader rejects a list with no final record. */ +function markFinalAttempt( + attempts: TestAttemptRecord[], + finalAttempt: number | undefined +): TestAttemptRecord[] { + const final = + attempts.find((record) => record.attempt === finalAttempt) ?? + attempts[attempts.length - 1] + return attempts.map((record) => + record === final ? { ...record, final: true } : record + ) } /** Assemble the manifest from the artifacts collected across the run and the @@ -47,22 +61,39 @@ export function buildArtifactsManifest(input: { format: TraceFormat artifacts: readonly TraceArtifact[] testMetadata: TestMetadataMap + runId?: string + parent?: ArtifactsManifest['parent'] + attemptsFor?: (uid: string) => TestAttemptRecord[] }): ArtifactsManifest { const tests: ArtifactManifestTest[] = [] for (const [uid, meta] of input.testMetadata) { - tests.push({ + if (isStepEntry(uid, meta, input.testMetadata)) { + continue + } + const test: ArtifactManifestTest = { uid, title: meta.title, specFile: meta.specFile, state: meta.state, - attempt: meta.attempt - }) + attempt: meta.attempt, + startTime: meta.startTime, + endTime: meta.endTime, + durationMs: meta.durationMs, + error: meta.error + } + const attempts = input.attemptsFor?.(uid) + if (attempts && attempts.length > 0) { + test.attempts = markFinalAttempt(attempts, meta.attempt) + } + tests.push(test) } return { sessionId: input.sessionId, format: input.format, artifacts: [...input.artifacts], - tests + tests, + runId: input.runId, + parent: input.parent } } diff --git a/packages/core/src/attempt-tracker.ts b/packages/core/src/attempt-tracker.ts index ba7c3e2fc..a33143a50 100644 --- a/packages/core/src/attempt-tracker.ts +++ b/packages/core/src/attempt-tracker.ts @@ -1,5 +1,17 @@ -import type { TestStatus } from '@wdio/devtools-shared' +import type { TestAttemptRecord, TestStatus } from '@wdio/devtools-shared' import type { TestOutcome } from '@wdio/devtools-trace/trace-retention' +import { + mintTraceContext, + resolveParentTraceContext, + type AttemptIds +} from './trace-context.js' + +interface AttemptSlot { + outcome: TestOutcome + startTime: number + endTime?: number + trace: AttemptIds +} /** * Framework-agnostic per-test attempt ledger. Every supported runner re-enters @@ -17,10 +29,12 @@ export interface RetryOutcomeView { forSpec(specFile: string): TestOutcome[] /** A single test's attempts; pass `attempt` to scope to one attempt's slice. */ forTest(uid: string, attempt?: number): TestOutcome[] + /** Every attempt of `uid` with its timing and trace context, for the manifest. */ + attemptsFor(uid: string): TestAttemptRecord[] } export class TestAttemptTracker implements RetryOutcomeView { - #ledger = new Map() + #ledger = new Map() #sawRetry = false /** Record a starting test; returns its attempt number (0 first, +1 per rerun). @@ -33,10 +47,16 @@ export class TestAttemptTracker implements RetryOutcomeView { // --require plugin) can't observe the failed attempt's state from their // outcome hook and report it as passed — the retry starting IS the // reliable failure signal, so stamp the prior attempt failed here. - entry.attempts[entry.attempts.length - 1].state = 'failed' + const prior = entry.attempts[entry.attempts.length - 1]! + prior.outcome.state = 'failed' + prior.endTime ??= Date.now() } const attempt = entry ? entry.attempts.length : 0 - const slot: TestOutcome = { uid, attempt } + const slot: AttemptSlot = { + outcome: { uid, attempt }, + startTime: Date.now(), + trace: mintTraceContext(resolveParentTraceContext()) + } if (entry) { entry.attempts.push(slot) if (specFile !== undefined) { @@ -48,22 +68,22 @@ export class TestAttemptTracker implements RetryOutcomeView { return attempt } - /** Stamp the resolved state onto uid's most recent attempt slot once the - * outcome is known. `attempt` overrides the slot's number when the adapter - * resolved a more authoritative value (e.g. WDIO's result.retries). */ + /** Stamp the resolved state onto uid's most recent attempt slot once the outcome is known. A runner attempt + * past the ledger's count (in-worker repeat) renumbers the slot to it, so the record matches the test's attempt. */ recordOutcome( uid: string, state: TestStatus | undefined, attempt?: number ): void { - const attempts = this.#ledger.get(uid)?.attempts - const slot = attempts?.[attempts.length - 1] + const attempts = this.#ledger.get(uid)?.attempts ?? [] + const slot = attempts[attempts.length - 1] if (!slot) { return } - slot.state = state - if (attempt !== undefined) { - slot.attempt = attempt + slot.outcome.state = state + slot.endTime = Date.now() + if (attempt !== undefined && attempt >= attempts.length) { + slot.outcome.attempt = attempt } } @@ -81,7 +101,7 @@ export class TestAttemptTracker implements RetryOutcomeView { all(): TestOutcome[] { const out: TestOutcome[] = [] for (const entry of this.#ledger.values()) { - out.push(...entry.attempts) + out.push(...entry.attempts.map((slot) => slot.outcome)) } return out } @@ -90,17 +110,30 @@ export class TestAttemptTracker implements RetryOutcomeView { const out: TestOutcome[] = [] for (const entry of this.#ledger.values()) { if (entry.specFile === specFile) { - out.push(...entry.attempts) + out.push(...entry.attempts.map((slot) => slot.outcome)) } } return out } forTest(uid: string, attempt?: number): TestOutcome[] { - const attempts = this.#ledger.get(uid)?.attempts ?? [] + const outcomes = (this.#ledger.get(uid)?.attempts ?? []).map( + (slot) => slot.outcome + ) return attempt === undefined - ? attempts - : attempts.filter((a) => a.attempt === attempt) + ? outcomes + : outcomes.filter((o) => o.attempt === attempt) + } + + attemptsFor(uid: string): TestAttemptRecord[] { + return (this.#ledger.get(uid)?.attempts ?? []).map((slot) => ({ + attempt: slot.outcome.attempt ?? 0, + state: slot.outcome.state, + startTime: slot.startTime, + endTime: slot.endTime, + traceId: slot.trace.traceId, + spanId: slot.trace.spanId + })) } /** Clear all state — used at session boundaries and reuse-mode reconnects. */ diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index e710bfc3d..3775c19cf 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -16,6 +16,11 @@ export * from './action-snapshot.js' export * from './artifact-naming.js' export * from './capture-timing.js' export * from './artifacts-manifest.js' +export type { + ArtifactManifestTest, + ArtifactsManifest, + TraceArtifact +} from '@wdio/devtools-shared' export * from './allure-artifacts.js' export * from './attempt-tracker.js' export * from './screenshot-artifact.js' diff --git a/packages/core/src/screenshot-artifact.ts b/packages/core/src/screenshot-artifact.ts index 881ff6e3c..e7bbfd3c9 100644 --- a/packages/core/src/screenshot-artifact.ts +++ b/packages/core/src/screenshot-artifact.ts @@ -11,7 +11,7 @@ import fs from 'node:fs/promises' import path from 'node:path' import type { TraceScreenshotPolicy } from '@wdio/devtools-shared' import { fileSlug } from './artifact-naming.js' -import type { TraceArtifact } from './trace-finalizer.js' +import type { TraceArtifact } from '@wdio/devtools-shared' /** Whether a per-test screenshot should be captured for this outcome. */ export function shouldCaptureScreenshot( diff --git a/packages/core/src/spec-trace-helpers.ts b/packages/core/src/spec-trace-helpers.ts index c410d2ede..e6a9b2188 100644 --- a/packages/core/src/spec-trace-helpers.ts +++ b/packages/core/src/spec-trace-helpers.ts @@ -7,13 +7,14 @@ */ import path from 'node:path' -import type { - ActionSnapshot, - CommandLog, - ScreencastFrame, - TestMetadataMap, - TraceFormat, - TraceGranularity +import { + retryKeyOf, + type ActionSnapshot, + type CommandLog, + type ScreencastFrame, + type TestMetadataMap, + type TraceFormat, + type TraceGranularity } from '@wdio/devtools-shared' import type { TraceCapturer } from '@wdio/devtools-trace/trace-exporter' import { writeTraceZip } from '@wdio/devtools-trace/trace-exporter' @@ -333,9 +334,13 @@ export function recordSliceBoundary( const priorAttempts = ctx.specRanges.filter( (r) => r.testUid === testUid ).length - const key = - priorAttempts === 0 ? testUid : `${testUid}-retry${priorAttempts}` - return pushSliceRange(ctx, specFile, key, testUid, false) + return pushSliceRange( + ctx, + specFile, + retryKeyOf(testUid, priorAttempts), + testUid, + false + ) } return null } diff --git a/packages/core/src/suite-helpers.ts b/packages/core/src/suite-helpers.ts index 67512f79a..e12e880d6 100644 --- a/packages/core/src/suite-helpers.ts +++ b/packages/core/src/suite-helpers.ts @@ -184,6 +184,17 @@ function deriveAncestorKind( return 'suite' } +// SuiteStats carries no retry count; a scenario's steps are stamped with the scenario's attempt. +function scenarioAttempt(suite: SuiteStats): number { + let attempt = 0 + for (const entry of suite.tests ?? []) { + if (typeof entry === 'object' && entry !== null) { + attempt = Math.max(attempt, entry.retries ?? 0) + } + } + return attempt +} + /** * Recursive walk over suite trees collecting every test's metadata entry — * uid → title/specFile/state/attempt plus the ancestor chain (outermost @@ -214,6 +225,7 @@ export function collectSuiteTestMetadata( title: suite.title, specFile: suite.file, state: suite.state, + attempt: scenarioAttempt(suite), ancestry: ancestors }) } diff --git a/packages/core/src/trace-context.ts b/packages/core/src/trace-context.ts new file mode 100644 index 000000000..1aee5a2c8 --- /dev/null +++ b/packages/core/src/trace-context.ts @@ -0,0 +1,44 @@ +import { + randomSpanId, + randomTraceId, + parseTraceparent, + TRACE_CONTEXT_ENV, + type ParentTraceContext, + type TestTraceContext +} from '@wdio/devtools-shared' + +// Sampling is the parent's to decide, and the manifest records it once on `parent`, so an attempt carries ids alone. +export type AttemptIds = Pick + +let parentCache: { value: ParentTraceContext | undefined } | undefined + +/** A new context for one test attempt; a parent contributes the trace it joins. */ +export function mintTraceContext(parent?: TestTraceContext): AttemptIds { + return { + traceId: parent?.traceId ?? randomTraceId(), + spanId: randomSpanId() + } +} + +/** The `TRACEPARENT` this process was launched under, read once per process. */ +export function resolveParentTraceContext(): ParentTraceContext | undefined { + parentCache ??= { value: readParentFromEnv() } + return parentCache.value +} + +function readParentFromEnv(): ParentTraceContext | undefined { + const header = process.env[TRACE_CONTEXT_ENV.TRACEPARENT] + if (!header) { + return undefined + } + const parent = parseTraceparent(header) + if (parent === undefined) { + process.emitWarning( + `Ignoring invalid ${TRACE_CONTEXT_ENV.TRACEPARENT}; expected a W3C traceparent.`, + 'DevToolsTraceContext' + ) + return undefined + } + const traceState = process.env[TRACE_CONTEXT_ENV.TRACESTATE] + return traceState ? { ...parent, traceState } : parent +} diff --git a/packages/core/src/trace-finalizer.ts b/packages/core/src/trace-finalizer.ts index ec8bb3410..9f04fffa7 100644 --- a/packages/core/src/trace-finalizer.ts +++ b/packages/core/src/trace-finalizer.ts @@ -11,6 +11,7 @@ import type { DevToolsMode, ScreencastFrame, TestMetadataMap, + TraceArtifact, TraceFormat, TraceGranularity, TraceRetentionPolicy @@ -21,6 +22,8 @@ import { buildArtifactsManifest, writeArtifactsManifest } from './artifacts-manifest.js' +import { resolveParentTraceContext } from './trace-context.js' +import { resolveRunId } from './run-id.js' import { filterTestMetadataBySpec, filterTestMetadataByUid, @@ -38,20 +41,6 @@ import { type TraceCapturer } from '@wdio/devtools-trace/trace-exporter' -/** One artifact produced (or, when `retained` is false, decided-against) by a - * trace-mode run — a trace slice, a screencast video, or a per-test - * screenshot. */ -export interface TraceArtifact { - kind: 'trace' | 'video' | 'screenshot' - path: string - scope: 'session' | 'spec' | 'test' - /** specFile for spec scope, testUid for test scope. */ - key?: string - testUids: string[] - /** false = decided-not-to-write (reported, not written). Always true today. */ - retained: boolean -} - export interface TraceExportContext { mode?: DevToolsMode /** undefined → treated as `on` (always retain) by the retention evaluator. */ @@ -505,7 +494,10 @@ async function maybeWriteManifest( sessionId: ctx.sessionId, format: ctx.format ?? 'zip', artifacts, - testMetadata: ctx.testMetadata + testMetadata: ctx.testMetadata, + runId: resolveRunId(), + parent: resolveParentTraceContext(), + attemptsFor: ctx.outcomes?.attemptsFor.bind(ctx.outcomes) }) ) ctx.log?.('info', `Artifacts manifest written to ${path}`) diff --git a/packages/core/src/uid.ts b/packages/core/src/uid.ts index d0e81d722..c7d64c013 100644 --- a/packages/core/src/uid.ts +++ b/packages/core/src/uid.ts @@ -35,6 +35,16 @@ export function isStepUidOf(uid: string, testUid: string): boolean { return uid.startsWith(`${testUid}${STEP_UID_SEPARATOR}`) } +// Splits on the last separator, so a nested key resolves one level up. +export function stepOwnerUid(uid: string): string | undefined { + const at = uid.lastIndexOf(STEP_UID_SEPARATOR) + if (at < 0) { + return undefined + } + const index = uid.slice(at + STEP_UID_SEPARATOR.length) + return /^\d+$/.test(index) ? uid.slice(0, at) : undefined +} + // Counter for disambiguating repeated (file, name) signatures within a single // test run. Cleared by resetSignatureCounters() between runs. const signatureCounters = new Map() diff --git a/packages/core/src/video-slice.ts b/packages/core/src/video-slice.ts index d20e71bba..1c713eeea 100644 --- a/packages/core/src/video-slice.ts +++ b/packages/core/src/video-slice.ts @@ -13,7 +13,7 @@ import type { ScreencastFrame } from '@wdio/devtools-shared' import { fileSlug } from './artifact-naming.js' import { encodeToVideo } from './video-encoder.js' import { errorMessage } from './error.js' -import type { TraceArtifact } from './trace-finalizer.js' +import type { TraceArtifact } from '@wdio/devtools-shared' /** Frames captured at or after `startWallTime` (ms) — one test's window, since * the buffer runs continuously and the next test's frames arrive later. */ diff --git a/packages/core/tests/artifacts-manifest.test.ts b/packages/core/tests/artifacts-manifest.test.ts index 0c7e969b2..4e7b30bbf 100644 --- a/packages/core/tests/artifacts-manifest.test.ts +++ b/packages/core/tests/artifacts-manifest.test.ts @@ -5,11 +5,14 @@ import { join } from 'node:path' import { buildArtifactsManifest, writeArtifactsManifest, - artifactsManifestFilename, - type ArtifactsManifest + artifactsManifestFilename } from '../src/artifacts-manifest.js' -import type { TraceArtifact } from '../src/trace-finalizer.js' -import type { TestMetadataMap } from '@wdio/devtools-shared' +import type { + ArtifactsManifest, + TestMetadataMap, + TraceArtifact +} from '@wdio/devtools-shared' +import { stepMetadataUid } from '../src/uid.js' function metadata(): TestMetadataMap { return new Map([ @@ -80,6 +83,243 @@ describe('artifacts manifest', () => { ]) }) + it('copies per-test timing and failure when the metadata carries them', () => { + const testMetadata: TestMetadataMap = new Map([ + [ + 'u2', + { + title: 'fails', + specFile: '/a.spec.ts', + state: 'failed', + attempt: 1, + startTime: 1000, + endTime: 1500, + durationMs: 480, + error: 'boom' + } + ] + ]) + const m = buildArtifactsManifest({ + sessionId: 'sess-t', + format: 'zip', + artifacts: [], + testMetadata + }) + expect(m.tests).toEqual([ + { + uid: 'u2', + title: 'fails', + specFile: '/a.spec.ts', + state: 'failed', + attempt: 1, + startTime: 1000, + endTime: 1500, + durationMs: 480, + error: 'boom' + } + ]) + }) + + it('leaves timing and error keys out of the file when the metadata lacks them', async () => { + const dir = await mkdtemp(join(tmpdir(), 'manifest-')) + dirs.push(dir) + const m = buildArtifactsManifest({ + sessionId: 'sess-u', + format: 'zip', + artifacts: [], + testMetadata: metadata() + }) + const filePath = await writeArtifactsManifest(dir, m) + const parsed = JSON.parse(await readFile(filePath, 'utf8')) as { + tests: Record[] + } + expect(Object.keys(parsed.tests[0]).sort()).toEqual( + ['attempt', 'specFile', 'state', 'title', 'uid'].sort() + ) + }) + + it('leaves out a step nested as a test under a scenario suite', () => { + const feature = { uid: 'f1', title: 'Cart', kind: 'feature' as const } + const scenario = { + uid: 's1', + title: 'checkout', + kind: 'scenario' as const + } + const testMetadata: TestMetadataMap = new Map([ + [ + 's1', + { + title: 'checkout', + specFile: '/a.feature', + state: 'passed', + ancestry: [feature] + } + ], + [ + 'step-1', + { + title: 'Given a cart', + specFile: '/a.feature', + state: 'passed', + attempt: 0, + ancestry: [feature, scenario] + } + ], + [ + 'mocha-test', + { + title: 'plain test', + specFile: '/a.spec.ts', + state: 'passed', + attempt: 0, + ancestry: [{ uid: 'd1', title: 'describe', kind: 'suite' as const }] + } + ] + ]) + const manifest = buildArtifactsManifest({ + sessionId: 's', + format: 'zip', + artifacts: [], + testMetadata + }) + expect(manifest.tests.map((t) => t.uid)).toEqual(['s1', 'mocha-test']) + }) + + it("leaves a scenario's steps out of tests[]", () => { + const testMetadata: TestMetadataMap = new Map([ + [ + 'stable-abc', + { + title: 'checkout', + specFile: '/a.feature', + state: 'passed', + attempt: 0 + } + ], + [ + stepMetadataUid('stable-abc', 1), + { title: 'Given a cart', specFile: '/a.feature' } + ], + [ + stepMetadataUid('stable-abc', 2), + { title: 'When I pay', specFile: '/a.feature' } + ] + ]) + const m = buildArtifactsManifest({ + sessionId: 'sess-s', + format: 'zip', + artifacts: [], + testMetadata + }) + expect(m.tests.map((t) => t.uid)).toEqual(['stable-abc']) + }) + + it('keeps a step-looking uid whose owner is not in the map', () => { + const testMetadata: TestMetadataMap = new Map([ + ['orphan:step:1', { title: 'stray', specFile: '/a.feature' }] + ]) + const m = buildArtifactsManifest({ + sessionId: 'sess-o', + format: 'zip', + artifacts: [], + testMetadata + }) + expect(m.tests.map((t) => t.uid)).toEqual(['orphan:step:1']) + }) + + it('carries the run id, parent context and per-attempt records when given', () => { + const attempts = [ + { + attempt: 1, + state: 'failed' as const, + startTime: 1, + endTime: 2, + traceId: '0af7651916cd43dd8448eb211c80319c', + spanId: 'b7ad6b7169203331' + } + ] + const m = buildArtifactsManifest({ + sessionId: 'sess-r', + format: 'zip', + artifacts: [], + testMetadata: metadata(), + runId: 'run-1', + parent: { + traceId: '0af7651916cd43dd8448eb211c80319c', + spanId: 'b7ad6b7169203331', + traceFlags: 1, + traceState: 'vendor=1' + }, + attemptsFor: (uid) => (uid === 'u2' ? attempts : []) + }) + expect(m.runId).toBe('run-1') + expect(m.parent?.traceState).toBe('vendor=1') + expect(m.tests[0]).not.toHaveProperty('attempts') + expect(m.tests[1]!.attempts).toEqual([{ ...attempts[0], final: true }]) + }) + + it('leaves run id, parent and attempts out when not given', async () => { + const dir = await mkdtemp(join(tmpdir(), 'manifest-')) + dirs.push(dir) + const m = buildArtifactsManifest({ + sessionId: 'sess-n', + format: 'zip', + artifacts: [], + testMetadata: metadata() + }) + const parsed = JSON.parse( + await readFile(await writeArtifactsManifest(dir, m), 'utf8') + ) as Record + expect(parsed).not.toHaveProperty('runId') + expect(parsed).not.toHaveProperty('parent') + expect(m.tests.every((t) => !('attempts' in t))).toBe(true) + }) + + it('stamps final on the last recorded attempt when none matches the test attempt', () => { + const record = (attempt: number) => ({ + attempt, + startTime: attempt, + traceId: '0af7651916cd43dd8448eb211c80319c', + spanId: 'b7ad6b7169203331' + }) + const testMetadata: TestMetadataMap = new Map([ + ['u1', { title: 'a', specFile: '/a.js', state: 'passed', attempt: 1 }], + ['u2', { title: 'b', specFile: '/a.js', state: 'passed', attempt: 5 }] + ]) + const m = buildArtifactsManifest({ + sessionId: 'sess-f', + format: 'zip', + artifacts: [], + testMetadata, + attemptsFor: () => [record(0), record(1)] + }) + expect(m.tests[0]!.attempts).toEqual([ + record(0), + { ...record(1), final: true } + ]) + expect(m.tests[1]!.attempts!.map((a) => a.final)).toEqual([undefined, true]) + }) + + it('stamps final on the last recorded attempt when the test has no attempt number', () => { + const record = (attempt: number) => ({ + attempt, + startTime: attempt, + traceId: '0af7651916cd43dd8448eb211c80319c', + spanId: 'b7ad6b7169203331' + }) + const testMetadata: TestMetadataMap = new Map([ + ['u1', { title: 'a', specFile: '/a.js', state: 'passed' }] + ]) + const m = buildArtifactsManifest({ + sessionId: 'sess-l', + format: 'zip', + artifacts: [], + testMetadata, + attemptsFor: () => [record(0), record(1)] + }) + expect(m.tests[0]!.attempts!.map((a) => a.final)).toEqual([undefined, true]) + }) + it('filename is deterministic per session', () => { expect(artifactsManifestFilename('abc')).toBe('devtools-artifacts-abc.json') }) diff --git a/packages/core/tests/attempt-tracker.test.ts b/packages/core/tests/attempt-tracker.test.ts index 845e6f8ba..69722f313 100644 --- a/packages/core/tests/attempt-tracker.test.ts +++ b/packages/core/tests/attempt-tracker.test.ts @@ -1,6 +1,11 @@ -import { describe, it, expect } from 'vitest' +import { afterEach, describe, it, expect, vi } from 'vitest' import { TestAttemptTracker } from '../src/attempt-tracker.js' +const HEX_32 = /^[0-9a-f]{32}$/ +const HEX_16 = /^[0-9a-f]{16}$/ +const PARENT_TRACE_ID = '0af7651916cd43dd8448eb211c80319c' +const PARENT_SPAN_ID = 'b7ad6b7169203331' + describe('TestAttemptTracker', () => { it('numbers the first start 0 and each rerun +1', () => { const t = new TestAttemptTracker() @@ -66,6 +71,21 @@ describe('TestAttemptTracker', () => { ]) }) + it('recordOutcome renumbers the slot to a runner attempt past the ledger count', () => { + const t = new TestAttemptTracker() + t.recordStart('a') + t.recordOutcome('a', 'passed', 3) + expect(t.attemptsFor('a').map((r) => r.attempt)).toEqual([3]) + }) + + it('recordOutcome keeps the ledger number when the runner attempt is not ahead', () => { + const t = new TestAttemptTracker() + t.recordStart('a') + t.recordStart('a') + t.recordOutcome('a', 'passed', 0) + expect(t.attemptsFor('a').map((r) => r.attempt)).toEqual([0, 1]) + }) + it('a retry stamps the prior attempt failed (swallowed-failure runners)', () => { // Mocha via a --require plugin reports the retried attempt as passed; the // retry starting is the reliable failure signal, so attempt 0 is corrected. @@ -80,12 +100,14 @@ describe('TestAttemptTracker', () => { ]) }) - it('recordOutcome can override the slot attempt (authoritative retry #)', () => { + it('numbers attempts 0, 1, 2 in start order, the numbers their slices are keyed by', () => { const t = new TestAttemptTracker() - t.recordStart('a') - t.recordOutcome('a', 'failed', 3) - expect(t.forTest('a')).toEqual([ - { uid: 'a', attempt: 3, state: 'failed' } + for (const state of ['failed', 'failed', 'passed'] as const) { + t.recordStart('a') + t.recordOutcome('a', state) + } + expect(t.attemptsFor('a').map((record) => record.attempt)).toEqual([ + 0, 1, 2 ]) }) @@ -132,4 +154,84 @@ describe('TestAttemptTracker', () => { expect(t.all()).toEqual([]) }) }) + describe('attempt records', () => { + afterEach(() => { + vi.useRealTimers() + vi.unstubAllEnvs() + vi.resetModules() + }) + + it('stamps start and end times and mints hex trace context per attempt', () => { + vi.useFakeTimers() + vi.setSystemTime(1000) + const t = new TestAttemptTracker() + t.recordStart('a') + vi.setSystemTime(1500) + t.recordOutcome('a', 'failed') + vi.setSystemTime(2000) + t.recordStart('a') + t.recordOutcome('a', 'passed') + const [first, second] = t.attemptsFor('a') + expect(first).toMatchObject({ + attempt: 0, + state: 'failed', + startTime: 1000, + endTime: 1500 + }) + expect(second).toMatchObject({ + attempt: 1, + state: 'passed', + startTime: 2000, + endTime: 2000 + }) + expect(first!.traceId).toMatch(HEX_32) + expect(first!.spanId).toMatch(HEX_16) + }) + + it('gives each attempt its own span, and its own trace when no parent is set', async () => { + vi.stubEnv('TRACEPARENT', '') + vi.resetModules() + const { TestAttemptTracker: Tracker } = + await import('../src/attempt-tracker.js') + const t = new Tracker() + t.recordStart('a') + t.recordStart('a') + const [first, second] = t.attemptsFor('a') + expect(first!.spanId).not.toBe(second!.spanId) + expect(first!.traceId).not.toBe(second!.traceId) + }) + + it('joins the parent trace when TRACEPARENT is set', async () => { + vi.stubEnv('TRACEPARENT', `00-${PARENT_TRACE_ID}-${PARENT_SPAN_ID}-01`) + vi.resetModules() + const { TestAttemptTracker: Tracker } = + await import('../src/attempt-tracker.js') + const t = new Tracker() + t.recordStart('a') + t.recordStart('a') + t.recordStart('b') + const traceIds = t.attemptsFor('a').map((r) => r.traceId) + expect(traceIds).toEqual([PARENT_TRACE_ID, PARENT_TRACE_ID]) + expect(t.attemptsFor('b')[0]!.traceId).toBe(PARENT_TRACE_ID) + expect(t.attemptsFor('a')[0]!.spanId).not.toBe(PARENT_SPAN_ID) + }) + + it('attemptsFor is empty for an unseen uid', () => { + expect(new TestAttemptTracker().attemptsFor('ghost')).toEqual([]) + }) + + it('keeps the outcome views shaped as before', () => { + const t = new TestAttemptTracker() + t.recordStart('a') + t.recordOutcome('a', 'passed') + expect(t.forTest('a')).toEqual([ + { uid: 'a', attempt: 0, state: 'passed' } + ]) + expect(Object.keys(t.forTest('a')[0]!).sort()).toEqual([ + 'attempt', + 'state', + 'uid' + ]) + }) + }) }) diff --git a/packages/core/tests/trace-context.test.ts b/packages/core/tests/trace-context.test.ts new file mode 100644 index 000000000..cdce354f2 --- /dev/null +++ b/packages/core/tests/trace-context.test.ts @@ -0,0 +1,85 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const HEX_32 = /^[0-9a-f]{32}$/ +const HEX_16 = /^[0-9a-f]{16}$/ +const TRACE_ID = '0af7651916cd43dd8448eb211c80319c' +const SPAN_ID = 'b7ad6b7169203331' + +describe('mintTraceContext', () => { + it('mints lowercase hex ids of the W3C lengths', async () => { + const { mintTraceContext } = await import('../src/trace-context.js') + const ctx = mintTraceContext() + expect(ctx.traceId).toMatch(HEX_32) + expect(ctx.spanId).toMatch(HEX_16) + }) + + it('gives every mint its own ids', async () => { + const { mintTraceContext } = await import('../src/trace-context.js') + const a = mintTraceContext() + const b = mintTraceContext() + expect(a.traceId).not.toBe(b.traceId) + expect(a.spanId).not.toBe(b.spanId) + }) + + it('joins a parent trace with a fresh span', async () => { + const { mintTraceContext } = await import('../src/trace-context.js') + const ctx = mintTraceContext({ + traceId: TRACE_ID, + spanId: SPAN_ID, + traceFlags: 0 + }) + expect(ctx.traceId).toBe(TRACE_ID) + expect(ctx.spanId).not.toBe(SPAN_ID) + expect(ctx.spanId).toMatch(HEX_16) + }) +}) + +describe('resolveParentTraceContext', () => { + beforeEach(() => { + delete process.env.TRACEPARENT + delete process.env.TRACESTATE + vi.resetModules() + }) + afterEach(() => { + vi.unstubAllEnvs() + vi.restoreAllMocks() + }) + + it('is undefined when no TRACEPARENT is set', async () => { + const { resolveParentTraceContext } = + await import('../src/trace-context.js') + expect(resolveParentTraceContext()).toBeUndefined() + }) + + it('reads TRACEPARENT and TRACESTATE', async () => { + vi.stubEnv('TRACEPARENT', `00-${TRACE_ID}-${SPAN_ID}-01`) + vi.stubEnv('TRACESTATE', 'vendor=1') + const { resolveParentTraceContext } = + await import('../src/trace-context.js') + expect(resolveParentTraceContext()).toEqual({ + traceId: TRACE_ID, + spanId: SPAN_ID, + traceFlags: 1, + traceState: 'vendor=1' + }) + }) + + it('warns once and ignores an invalid TRACEPARENT', async () => { + const warn = vi.spyOn(process, 'emitWarning').mockImplementation(() => {}) + vi.stubEnv('TRACEPARENT', 'garbage') + const { resolveParentTraceContext } = + await import('../src/trace-context.js') + expect(resolveParentTraceContext()).toBeUndefined() + expect(resolveParentTraceContext()).toBeUndefined() + expect(warn).toHaveBeenCalledTimes(1) + }) + + it('reads the environment once per process', async () => { + vi.stubEnv('TRACEPARENT', `00-${TRACE_ID}-${SPAN_ID}-01`) + const { resolveParentTraceContext } = + await import('../src/trace-context.js') + const first = resolveParentTraceContext() + vi.stubEnv('TRACEPARENT', `00-${'1'.repeat(32)}-${SPAN_ID}-01`) + expect(resolveParentTraceContext()).toBe(first) + }) +}) diff --git a/packages/core/tests/trace-finalizer.test.ts b/packages/core/tests/trace-finalizer.test.ts index 756a80934..feddaad30 100644 --- a/packages/core/tests/trace-finalizer.test.ts +++ b/packages/core/tests/trace-finalizer.test.ts @@ -395,6 +395,11 @@ describe('finalizeTraceExport', () => { ]) }) + it('writes nothing in live mode, even when emitManifest is set', async () => { + await finalizeTraceExport(baseCtx({ mode: 'live', emitManifest: true })) + expect(await fs.readdir(outputDir)).toEqual([]) + }) + it('includes eager-flushed slices the fan-out deduped away', async () => { const ctx = baseCtx({ granularity: 'test', @@ -522,7 +527,12 @@ describe('finalizeTraceExport', () => { // outcomes present but this scope's view is empty (e.g. an adapter that // didn't feed this scope): must use metadata, not fail-open into retaining // a passing test. - const emptyView = { all: () => [], forSpec: () => [], forTest: () => [] } + const emptyView = { + all: () => [], + forSpec: () => [], + forTest: () => [], + attemptsFor: () => [] + } const result = await finalizeTraceExport( baseCtx({ policy: 'retain-on-failure', diff --git a/packages/core/tests/uid.test.ts b/packages/core/tests/uid.test.ts index 06d46e8e4..2e4920853 100644 --- a/packages/core/tests/uid.test.ts +++ b/packages/core/tests/uid.test.ts @@ -4,7 +4,8 @@ import { generateStableUid, isStepUidOf, resetSignatureCounters, - stepMetadataUid + stepMetadataUid, + stepOwnerUid } from '@wdio/devtools-core' describe('deterministicUid', () => { @@ -56,3 +57,19 @@ describe('stepMetadataUid / isStepUidOf', () => { expect(isStepUidOf('stable-abc', 'stable-abc')).toBe(false) }) }) + +describe('stepOwnerUid', () => { + it('returns the owning test uid for a step key', () => { + expect(stepOwnerUid(stepMetadataUid('stable-abc', 2))).toBe('stable-abc') + }) + + it('returns undefined for a uid that is not a step key', () => { + expect(stepOwnerUid('abc')).toBeUndefined() + expect(stepOwnerUid('abc:step:')).toBeUndefined() + expect(stepOwnerUid('abc:step:x')).toBeUndefined() + }) + + it('resolves one level of a nested key', () => { + expect(stepOwnerUid('a:step:1:step:2')).toBe('a:step:1') + }) +}) diff --git a/packages/nightwatch-devtools/src/helpers/testManager.ts b/packages/nightwatch-devtools/src/helpers/testManager.ts index c7a3b60a8..860b453cd 100644 --- a/packages/nightwatch-devtools/src/helpers/testManager.ts +++ b/packages/nightwatch-devtools/src/helpers/testManager.ts @@ -17,7 +17,9 @@ export class TestManager { constructor( private testReporter: TestReporter, /** Stamps a test's resolved terminal state onto the retry ledger. */ - private recordOutcome?: (uid: string, state: TestStats['state']) => void + private recordOutcome?: (uid: string, state: TestStats['state']) => void, + /** Opens an attempt for a test starting on its first command; `specFile` enables spec-scoped retention. */ + private recordAttempt?: (uid: string, specFile?: string) => number ) {} /** @@ -163,6 +165,7 @@ export class TestManager { const test = this.findTestInSuite(currentSuite, currentTestName) if (test && test.state === TEST_STATE.PENDING) { + test.retries = this.recordAttempt?.(test.uid, currentSuite.file) ?? 0 test.start = new Date() test.end = null this.updateTestState(test, TEST_STATE.RUNNING as TestStats['state']) diff --git a/packages/nightwatch-devtools/src/session-init.ts b/packages/nightwatch-devtools/src/session-init.ts index 9898aec6b..d08478c09 100644 --- a/packages/nightwatch-devtools/src/session-init.ts +++ b/packages/nightwatch-devtools/src/session-init.ts @@ -88,6 +88,8 @@ export interface SessionInitCtx { buildMetadataOptions(): unknown /** Latest attempt recorded for `uid`, or undefined if it never started. */ attemptFor(uid: string): number | undefined + /** Opens an attempt for uid; `specFile` enables spec-scoped retention. */ + recordAttempt(uid: string, specFile?: string): number /** Stamps the terminal state onto uid's latest attempt, for the retry-aware retention policies. */ recordOutcome(uid: string, state: TestStats['state']): void /** Drains the live recorder's frames into the run's filmstrip buffer, then @@ -108,8 +110,10 @@ function initReporterChain(ctx: SessionInitCtx): void { }, (uid) => ctx.attemptFor(uid) ) - ctx.testManager = new TestManager(ctx.testReporter, (uid, state) => - ctx.recordOutcome(uid, state) + ctx.testManager = new TestManager( + ctx.testReporter, + (uid, state) => ctx.recordOutcome(uid, state), + (uid, specFile) => ctx.recordAttempt(uid, specFile) ) ctx.suiteManager = new SuiteManager(ctx.testReporter) ctx.browserProxy = new BrowserProxy( diff --git a/packages/nightwatch-devtools/tests/attemptTracking.test.ts b/packages/nightwatch-devtools/tests/attemptTracking.test.ts index 5a3f03570..1e3b35196 100644 --- a/packages/nightwatch-devtools/tests/attemptTracking.test.ts +++ b/packages/nightwatch-devtools/tests/attemptTracking.test.ts @@ -6,6 +6,8 @@ import { import { buildCucumberScenarioSuite } from '../src/helpers/cucumberScenarioBuilder.js' import { buildTraceContext } from '../src/trace-context.js' import { startNextTest, type TestLifecycleCtx } from '../src/test-lifecycle.js' +import { TestManager } from '../src/helpers/testManager.js' +import type { TestReporter } from '../src/reporter.js' import { TEST_STATE } from '../src/constants.js' import type { SessionCapturer } from '../src/session.js' import type { SuiteStats, TestStats } from '../src/types.js' @@ -118,6 +120,79 @@ describe('regular test retry attempt via startNextTest', () => { }) }) +describe('BDD module tests past the first `it` record their attempt', () => { + function moduleFixture() { + const tests = [ + makeTest('uid-1', 'first'), + makeTest('uid-2', 'second'), + makeTest('uid-3', 'third') + ] + const suite = { + uid: 'suite-uid', + file: '/spec.ts', + tests + } as unknown as SuiteStats + const reporter = { + getCurrentSuite: () => suite, + onTestStart: vi.fn(), + onTestEnd: vi.fn() + } as unknown as TestReporter + const tracker = new TestAttemptTracker() + const manager = new TestManager( + reporter, + (uid, state) => tracker.recordOutcome(uid, state), + (uid, specFile) => tracker.recordStart(uid, specFile) + ) + const ctx = { + suiteManager: { markSuiteAsRunning: vi.fn() }, + testManager: manager, + testReporter: reporter, + setCurrentTest: vi.fn(), + recordAttempt: (uid: string) => tracker.recordStart(uid) + } as unknown as TestLifecycleCtx + return { tests, suite, tracker, manager, ctx } + } + + it('gives every `it` of a module exactly one attempt slot and keeps a failed state', async () => { + const { tests, suite, tracker, manager, ctx } = moduleFixture() + const [first, second, third] = tests + + await startNextTest(ctx, suite, 'first', new Set(), null) + manager.detectTestBoundary({ name: 'second', module: 'spec.js' } as never) + manager.startTestIfPending('second') + manager.updateTestState( + second, + TEST_STATE.FAILED as TestStats['state'], + new Date(), + 0 + ) + manager.detectTestBoundary({ name: 'third', module: 'spec.js' } as never) + manager.startTestIfPending('third') + + expect(tests.map((t) => tracker.forTest(t.uid).length)).toEqual([1, 1, 1]) + expect(tracker.forTest(second.uid)).toEqual([ + { uid: second.uid, attempt: 0, state: 'failed' } + ]) + expect(second.state).toBe(TEST_STATE.FAILED) + expect(third.state).toBe(TEST_STATE.RUNNING) + expect(tests.map((t) => t.retries)).toEqual([0, 0, 0]) + expect(first.state).toBe(TEST_STATE.RUNNING) + }) + + it('does not record a second attempt for the first `it` when its command runs', async () => { + const { tests, suite, tracker, manager, ctx } = moduleFixture() + const [first] = tests + + await startNextTest(ctx, suite, 'first', new Set(), null) + manager.detectTestBoundary({ name: 'first', module: 'spec.js' } as never) + manager.startTestIfPending('first') + + expect(tracker.forTest(first.uid)).toEqual([ + { uid: first.uid, attempt: 0, state: undefined } + ]) + }) +}) + describe('buildTraceContext', () => { it('sets attemptInfoAvailable and carries retries through to attempt', () => { const capturer = { diff --git a/packages/selenium-devtools/src/helpers/testManager.ts b/packages/selenium-devtools/src/helpers/testManager.ts index 95de92c76..8ce2ac795 100644 --- a/packages/selenium-devtools/src/helpers/testManager.ts +++ b/packages/selenium-devtools/src/helpers/testManager.ts @@ -180,11 +180,7 @@ export class TestManager { // (passed) attempt and stops over-retaining, retain-on-first-failure on // attempt 0. Skipped for the synthetic session test (no recordStart). if (this.#currentRetryStableUid !== undefined) { - this.#attemptTracker.recordOutcome( - this.#currentRetryStableUid, - state, - test.retries - ) + this.#attemptTracker.recordOutcome(this.#currentRetryStableUid, state) this.#currentRetryStableUid = undefined } this.testReporter.onTestEnd(test) diff --git a/packages/service/README.md b/packages/service/README.md index acd6e333e..47e664ad4 100644 --- a/packages/service/README.md +++ b/packages/service/README.md @@ -112,8 +112,9 @@ These apply in live mode and in the trace player alike. ## Allure integration When `@wdio/allure-reporter` is installed, trace-mode artifacts are attached to -the Allure report automatically (and `emitArtifactsManifest` is auto-enabled, so -the run also writes the `devtools-artifacts-.json` index): +the Allure report automatically (and `emitArtifactsManifest` is auto-enabled for +any reporter whose name contains `allure`, so the run also writes the +`devtools-artifacts-.json` index): - **`traceGranularity: 'test'`** — each test's trace (`application/zip`, a download that opens in `pnpm show-trace`), screenshot (`image/png`, inline) @@ -123,7 +124,8 @@ the run also writes the `devtools-artifacts-.json` index): `trace.zip` is written to disk and enumerated in `devtools-artifacts-.json` (the artifacts manifest, listing every artifact + each test's state), but it is **not** attached to individual test - cards. + cards. Each test entry also carries `startTime`/`endTime` (epoch ms), + `durationMs` and the final attempt's `error` message when available. ### Why session/spec traces aren't attached per test @@ -275,7 +277,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-.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 `@wdio/allure-reporter` is in the config**. | +| `emitArtifactsManifest` | `boolean` | `false` | Trace mode only. Writes `devtools-artifacts-.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.` 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), live and trace mode alike. `false` records them as typed. Command rows always keep the typed text. See [Password masking](../../README.md#-password-masking) for what is and is not covered. | | `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/index.ts b/packages/service/src/index.ts index 6aa4650d2..a792e36f7 100644 --- a/packages/service/src/index.ts +++ b/packages/service/src/index.ts @@ -159,7 +159,7 @@ export default class DevToolsHookService implements Services.ServiceInstance { #currentStepUid?: string /** Per-scenario step counter for stable, collision-free step uids. */ #currentStepIndex = 0 - /** True when @wdio/allure-reporter is in the WDIO config (detected in + /** True when a reporter whose name contains "allure" is in the WDIO config (detected in * beforeSession) — auto-enables the artifacts manifest even if the option * isn't set, since session/spec-scoped Allure attach reads it. */ #allureReporterConfigured = false @@ -421,7 +421,8 @@ export default class DevToolsHookService implements Services.ServiceInstance { this.#attemptTracker.recordStart(uid, featureFile) this.#testMetadata.set(uid, { title: scenarioName, - specFile: featureFile + specFile: featureFile, + startTime: Date.now() }) } } @@ -448,7 +449,8 @@ export default class DevToolsHookService implements Services.ServiceInstance { this.#attemptTracker.recordStart(uid, test?.file) this.#testMetadata.set(uid, { title: testTitle, - specFile: test?.file ?? '' + specFile: test?.file ?? '', + startTime: Date.now() }) } } @@ -479,17 +481,21 @@ export default class DevToolsHookService implements Services.ServiceInstance { _scenario?: unknown, result?: { error?: unknown } ) { - await this.#closeOpenWaits(result?.error) + await this.#closeOpenWaits(result?.error, Date.now()) this.#currentStepUid = undefined this.#assertionTracker.handleOutcome(result?.error) } /** Stamp final state + the resolved 0-based attempt onto the test's metadata * entry, taking the max of the tracker count and WDIO's retry field. */ - #stampOutcome(uid: string, result?: TestOutcomeResult): void { + #stampOutcome( + uid: string, + result: TestOutcomeResult | undefined, + endTime: number + ): void { const fallback = this.#attemptTracker.attemptFor(uid) ?? 0 const attempt = resolveTestAttempt(result, fallback) - stampTestState(this.#testMetadata, uid, result, attempt) + stampTestState(this.#testMetadata, uid, result, attempt, endTime) // Feed the per-attempt ledger so session/spec retention sees this attempt's // real outcome, not just the final state that overwrites #testMetadata. this.#attemptTracker.recordOutcome( @@ -505,12 +511,20 @@ export default class DevToolsHookService implements Services.ServiceInstance { }, result?: TestOutcomeResult ) { - await this.#closeOpenWaits(result?.error) + // Read before the hook settle below, which is the service's teardown, not the scenario's. + const endTime = Date.now() + await this.#closeOpenWaits(result?.error, endTime) const { uri, name, astNodeIds } = world?.pickle ?? {} const uid = uri && name ? cucumberScenarioUid(uri, name, astNodeIds) : undefined if (uid) { - this.#stampOutcome(uid, result) + // WDIO's cucumber result.duration is only the nanos field of the worst step's + // Duration (seconds dropped), not the scenario's span, so wall time stands in. + this.#stampOutcome( + uid, + result && { ...result, duration: undefined }, + endTime + ) } await this.#finalizePerScenario() await this.#emitTestArtifacts(uid, isFailedResult(result)) @@ -521,12 +535,13 @@ export default class DevToolsHookService implements Services.ServiceInstance { _context?: unknown, result?: TestOutcomeResult ) { - await this.#closeOpenWaits(result?.error) + const endTime = Date.now() + await this.#closeOpenWaits(result?.error, endTime) this.#assertionTracker.handleOutcome(result?.error) const testTitle = test?.fullTitle || test?.title const uid = testTitle ? testMetadataUid(test?.file, testTitle) : undefined if (uid) { - this.#stampOutcome(uid, result) + this.#stampOutcome(uid, result, endTime) } await this.#finalizePerScenario() await this.#emitTestArtifacts(uid, isFailedResult(result)) @@ -698,14 +713,14 @@ export default class DevToolsHookService implements Services.ServiceInstance { } /** Before the outcome marks a row and the slice is flushed, so the wait carries the failure rather than its last poll. */ - async #closeOpenWaits(error: unknown) { + async #closeOpenWaits(error: unknown, endedAt: number) { if (!(await this.#hooksInFlight.settled(HOOKS_SETTLE_TIMEOUT_MS))) { log.warn( `a command hook was still running ${HOOKS_SETTLE_TIMEOUT_MS} ms after its test ended` ) } for (const id of this.#commandStack.takeOpenWaits()) { - this.#sessionCapturer.closeOpenWait(id, error) + this.#sessionCapturer.closeOpenWait(id, error, endedAt) } } diff --git a/packages/service/src/session.ts b/packages/service/src/session.ts index 556da1545..f2200d85c 100644 --- a/packages/service/src/session.ts +++ b/packages/service/src/session.ts @@ -294,9 +294,9 @@ export class SessionCapturer extends SessionCapturerBase { } /** Closes a wait left open when its test or step ended, with that test's failure or as passed; an assertion failure stays on its own row. */ - closeOpenWait(id: number, testError: unknown): void { + closeOpenWait(id: number, testError: unknown, endedAt: number): void { this.#restoreWaitSelector(id) - this.#waitRows.closeOpen(id, toCommandError(testError)) + this.#waitRows.closeOpen(id, toCommandError(testError), endedAt) this.#retryTracker.reset() } diff --git a/packages/service/src/test-metadata.ts b/packages/service/src/test-metadata.ts index 5e37ba204..1d3fdbeb1 100644 --- a/packages/service/src/test-metadata.ts +++ b/packages/service/src/test-metadata.ts @@ -1,7 +1,7 @@ // Per-test metadata helpers shared between the before* and after* hooks so the // state stamp in afterTest/afterScenario lands on the entry beforeTest created. -import { deterministicUid } from '@wdio/devtools-core' +import { deterministicUid, errorMessage } from '@wdio/devtools-core' import type { TestMetadataMap, TestStatus } from '@wdio/devtools-shared' /** The subset of a WDIO afterTest/afterScenario hook result this adapter reads: @@ -10,6 +10,7 @@ export interface TestOutcomeResult { error?: unknown passed?: boolean skipped?: boolean + duration?: number retries?: { attempts?: number } } @@ -35,6 +36,75 @@ export function cucumberScenarioUid( : deterministicUid(uri, name) } +// WDIO's cucumber result.error is Cucumber's formatted stackTrace string, not a message. +const FRAME_START = /^\s+at / +const FRAME_LOCATION = /:\d+(?::\d+)?\)?$/ +const CAUSED_BY = /^\s*Caused by:/ + +const isBlank = (line: string) => line.trim() === '' +const isLocatedFrame = (line: string) => + FRAME_START.test(line) && FRAME_LOCATION.test(line.trimEnd()) + +/** For each line, whether it sits in a run of contiguous "at" lines that holds a located frame. */ +function inLocatedRun(lines: readonly string[]): boolean[] { + const result = new Array(lines.length).fill(false) + let runStart = -1 + let located = false + for (let i = 0; i <= lines.length; i++) { + if (i < lines.length && FRAME_START.test(lines[i]!)) { + runStart = runStart < 0 ? i : runStart + located ||= isLocatedFrame(lines[i]!) + } else if (runStart >= 0) { + result.fill(located, runStart, i) + runStart = -1 + located = false + } + } + return result +} + +// A stack is a contiguous tail of "at" lines (up to a "Caused by:") holding at least one located frame, so an "at" +// line inside the message, or a run with no location at all, is never mistaken for one. A blank line is skipped at the +// very end, as a serialized stack's trailing newline leaves one, or when the run of "at" lines above it holds a located +// frame; otherwise it ends the stack. +function stackStart(lines: readonly string[]): number { + const locatedRun = inLocatedRun(lines) + let start = lines.length + let tailIsFrames = true + let located = false + let trailing = true + let blankBelow = false + for (let i = lines.length - 1; i >= 0; i--) { + const line = lines[i]! + if (isBlank(line)) { + blankBelow = !trailing + continue + } + if (blankBelow && !locatedRun[i]) { + tailIsFrames = false + } + trailing = false + blankBelow = false + if (CAUSED_BY.test(line)) { + tailIsFrames = true + located = false + } else if (!FRAME_START.test(line)) { + tailIsFrames = false + } else if (tailIsFrames) { + located ||= FRAME_LOCATION.test(line.trimEnd()) + if (located) { + start = i + } + } + } + return start +} + +function failureMessage(error: unknown): string | undefined { + const lines = errorMessage(error).split('\n') + return lines.slice(0, stackStart(lines)).join('\n') || undefined +} + /** Canonical test state from a WDIO afterTest/afterScenario result. */ export function resultToState(result: { passed?: boolean @@ -54,18 +124,29 @@ export function isFailedResult( return result ? resultToState(result) === 'failed' : false } -/** Stamp the final state (and, when known, the 0-based attempt) onto the - * metadata entry beforeTest/beforeScenario created, so retention can gate its - * trace per attempt. No-op when there's no entry. */ +/** Stamp the final state, end time, framework duration and failure message + * (and, when known, the 0-based attempt) onto the metadata entry + * beforeTest/beforeScenario created. The error is reassigned on every stamp, + * so a passing retry clears the failed attempt's message. No-op when there's + * no entry. */ export function stampTestState( metadata: TestMetadataMap, uid: string, - result?: Pick, - attempt?: number + result: TestOutcomeResult | undefined, + attempt: number | undefined, + endTime: number ): void { - const entry = result && metadata.get(uid) - if (entry) { + const entry = metadata.get(uid) + if (result && entry) { entry.state = resultToState(result) + entry.endTime = endTime + entry.durationMs = + result.duration ?? + (entry.startTime === undefined ? undefined : endTime - entry.startTime) + entry.error = + isFailedResult(result) && result.error + ? failureMessage(result.error) + : undefined if (attempt !== undefined) { entry.attempt = attempt } diff --git a/packages/service/src/wait-rows.ts b/packages/service/src/wait-rows.ts index b165a8d22..be1c52bb2 100644 --- a/packages/service/src/wait-rows.ts +++ b/packages/service/src/wait-rows.ts @@ -77,10 +77,10 @@ export class WaitRows { } /** Closes a wait from its running row when its own hook never ran, so it keeps its call site, selector and start. */ - closeOpen(id: number, error: CommandLog['error']): void { + closeOpen(id: number, error: CommandLog['error'], endedAt: number): void { const running = this.#rows.get(id) if (running) { - this.close({ ...running, error, timestamp: Date.now() }, id) + this.close({ ...running, error, timestamp: endedAt }, id) } } diff --git a/packages/service/tests/trace-metadata.test.ts b/packages/service/tests/trace-metadata.test.ts index 2deeee70e..dc3e2fbcd 100644 --- a/packages/service/tests/trace-metadata.test.ts +++ b/packages/service/tests/trace-metadata.test.ts @@ -1,9 +1,12 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' import type * as DevtoolsCore from '@wdio/devtools-core' import { deterministicUid } from '@wdio/devtools-core' +import { HooksInFlight } from '../src/command-stack.js' +import type { TestMetadataEntry, TestMetadataMap } from '@wdio/devtools-shared' import { cucumberScenarioUid, resultToState, + stampTestState, testMetadataUid } from '../src/test-metadata.js' @@ -93,6 +96,50 @@ describe('test-metadata helpers', () => { }) }) +describe('stampTestState', () => { + it('reassigns the error on every stamp so a passing retry leaves none', () => { + const metadata: TestMetadataMap = new Map([ + ['u', { title: 't', specFile: 's' }] + ]) + stampTestState( + metadata, + 'u', + { passed: false, error: new Error('first') }, + 0, + 10 + ) + stampTestState(metadata, 'u', { passed: true, duration: 5 }, 1, 20) + const entry = metadata.get('u') + expect(entry?.state).toBe('passed') + expect(entry?.error).toBeUndefined() + expect(entry?.durationMs).toBe(5) + expect(entry?.endTime).toBe(20) + expect(entry?.attempt).toBe(1) + }) + + it('records the message of a failed result and no-ops without an entry', () => { + const metadata: TestMetadataMap = new Map([ + ['u', { title: 't', specFile: 's' }] + ]) + stampTestState( + metadata, + 'u', + { passed: false, error: new Error('boom') }, + 0, + 10 + ) + expect(metadata.get('u')?.error).toBe('boom') + stampTestState( + metadata, + 'missing', + { passed: false, error: new Error('x') }, + 0, + 10 + ) + expect(metadata.has('missing')).toBe(false) + }) +}) + describe('DevtoolsService - afterTest state stamping', () => { const file = '/proj/specs/login.spec.ts' const mockBrowser = { @@ -215,8 +262,232 @@ describe('DevtoolsService - afterTest state stamping', () => { await service.after() const ctx = finalizeTraceExport.mock.calls.at(-1)?.[0] as { testMetadata: Map + outcomes: { attemptsFor(uid: string): Array<{ attempt: number }> } + } + const uid = deterministicUid(file, title) + expect(ctx.testMetadata.get(uid)?.attempt).toBe(3) + expect(ctx.outcomes.attemptsFor(uid).map((r) => r.attempt)).toEqual([3]) + }) + + it('takes a Cucumber scenario duration from its own start and end', async () => { + const service = new DevToolsHookService({ + mode: 'trace', + tracePolicy: 'retain-on-failure' + }) + await service.before({} as never, [], mockBrowser) + const uri = '/proj/features/cart.feature' + service.beforeScenario({ pickle: { uri, name: 'timed scenario' } }) + await service.afterScenario( + { pickle: { uri, name: 'timed scenario' } }, + { passed: true, duration: 0.975347 } + ) + await service.after() + const ctx = finalizeTraceExport.mock.calls.at(-1)?.[0] as { + testMetadata: TestMetadataMap + } + const entry = ctx.testMetadata.get(deterministicUid(uri, 'timed scenario')) + expect(entry?.durationMs).toBe( + (entry?.endTime ?? NaN) - (entry?.startTime ?? NaN) + ) + }) + + it('ends a test before the service waits for its own command hooks', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + const settle = vi + .spyOn(HooksInFlight.prototype, 'settled') + .mockImplementation(async () => { + vi.setSystemTime(13_000) + return true + }) + try { + const service = new DevToolsHookService({ + mode: 'trace', + tracePolicy: 'retain-on-failure' + }) + await service.before({} as never, [], mockBrowser) + const uri = '/proj/features/cart.feature' + const file = '/proj/specs/cart.spec.ts' + vi.setSystemTime(1_000) + service.beforeScenario({ pickle: { uri, name: 'settling scenario' } }) + service.beforeTest({ file, title: 'settling test' } as never) + vi.setSystemTime(3_000) + await service.afterScenario( + { pickle: { uri, name: 'settling scenario' } }, + { passed: true } + ) + vi.setSystemTime(3_000) + await service.afterTest({ file, title: 'settling test' }, undefined, { + passed: true, + duration: 2_000 + }) + await service.after() + const ctx = finalizeTraceExport.mock.calls.at(-1)?.[0] as { + testMetadata: TestMetadataMap + } + const scenario = ctx.testMetadata.get( + deterministicUid(uri, 'settling scenario') + ) + const test = ctx.testMetadata.get(deterministicUid(file, 'settling test')) + expect(scenario).toMatchObject({ endTime: 3_000, durationMs: 2_000 }) + expect(test?.endTime).toBe(3_000) + } finally { + settle.mockRestore() + vi.useRealTimers() + } + }) + + it('leaves no failure message on a failed scenario that reported no error', async () => { + const service = new DevToolsHookService({ + mode: 'trace', + tracePolicy: 'retain-on-failure' + }) + await service.before({} as never, [], mockBrowser) + const uri = '/proj/features/cart.feature' + service.beforeScenario({ pickle: { uri, name: 'pending scenario' } }) + await service.afterScenario( + { pickle: { uri, name: 'pending scenario' } }, + { passed: false } + ) + await service.after() + const ctx = finalizeTraceExport.mock.calls.at(-1)?.[0] as { + testMetadata: TestMetadataMap + } + const entry = ctx.testMetadata.get( + deterministicUid(uri, 'pending scenario') + ) + expect(entry?.state).toBe('failed') + expect(entry?.error).toBeUndefined() + }) + + async function stampedError(error: string): Promise { + const service = new DevToolsHookService({ + mode: 'trace', + tracePolicy: 'retain-on-failure' + }) + await service.before({} as never, [], mockBrowser) + const file = '/proj/specs/stack.spec.ts' + service.beforeTest({ file, title: 'fails' } as never) + await service.afterTest({ file, title: 'fails' }, undefined, { + passed: false, + error + }) + await service.after() + const ctx = finalizeTraceExport.mock.calls.at(-1)?.[0] as { + testMetadata: TestMetadataMap + } + return ctx.testMetadata.get(deterministicUid(file, 'fails'))?.error + } + + it('leaves no failure message when the error is only stack lines', async () => { + expect( + await stampedError(' at foo (a.js:1:2)\n at bar (b.js:3:4)') + ).toBeUndefined() + }) + + it('cuts at a stack whose first frame has no file location', async () => { + expect( + await stampedError( + 'Error: x\n at new Promise ()\n at foo (a.js:1:2)' + ) + ).toBe('Error: x') + }) + + it('cuts a stack that ends in a newline or holds a blank line', async () => { + expect( + await stampedError( + 'Error: x\n at foo (a.js:1:2)\n\n at bar (b.js:3:4)\n' + ) + ).toBe('Error: x') + }) + + it('keeps an "at" message line that a blank line separates from the stack', async () => { + expect( + await stampedError('Expected:\n at least 2\n\n at foo (a.js:1:2)') + ).toBe('Expected:\n at least 2\n') + }) + + it('cuts an unlocated frame above a blank line when its run holds a located frame', async () => { + expect( + await stampedError( + 'Error: x\n at a (x.js:1:2)\n at native\n\n at b (y.js:3:4)' + ) + ).toBe('Error: x') + }) + + // A scan that revisits the blanks above each blank takes ~3 s here; one pass takes a few ms. + it( + 'cuts a stack padded with many blank lines', + { timeout: 1000 }, + async () => { + const blanks = '\n'.repeat(20_000) + expect( + await stampedError( + `Error: x\n at a (x.js:1:2)${blanks} at b (y.js:3:4)${blanks}` + ) + ).toBe('Error: x') + } + ) + + it('keeps a located-looking "at" line in the middle of the message', async () => { + expect( + await stampedError( + 'Expected:\n at index 5:10\nReceived: 1\n at foo (a.js:1:2)' + ) + ).toBe('Expected:\n at index 5:10\nReceived: 1') + }) + + it('keeps a trailing "at" line when no located frame follows', async () => { + expect(await stampedError('Expected:\n at least 2')).toBe( + 'Expected:\n at least 2' + ) + }) + + it('keeps a message line that starts with "at" but is not a stack frame', async () => { + const service = new DevToolsHookService({ + mode: 'trace', + tracePolicy: 'retain-on-failure' + }) + await service.before({} as never, [], mockBrowser) + const file = '/proj/specs/cart.spec.ts' + service.beforeTest({ file, title: 'counts items' } as never) + await service.afterTest({ file, title: 'counts items' }, undefined, { + passed: false, + error: + 'Expected:\n at least 2\nReceived: 1\n at async Context. (cart.spec.ts:4:9)' + }) + await service.after() + const ctx = finalizeTraceExport.mock.calls.at(-1)?.[0] as { + testMetadata: TestMetadataMap } - expect(ctx.testMetadata.get(deterministicUid(file, title))?.attempt).toBe(3) + expect( + ctx.testMetadata.get(deterministicUid(file, 'counts items'))?.error + ).toBe('Expected:\n at least 2\nReceived: 1') + }) + + it("keeps a Cucumber failure's message and drops its stack trace", async () => { + const service = new DevToolsHookService({ + mode: 'trace', + tracePolicy: 'retain-on-failure' + }) + await service.before({} as never, [], mockBrowser) + const uri = '/proj/features/cart.feature' + service.beforeScenario({ pickle: { uri, name: 'failing scenario' } }) + await service.afterScenario( + { pickle: { uri, name: 'failing scenario' } }, + { + passed: false, + error: + 'AssertionError: expected 2\n+ actual 1\n at World. (steps.ts:4:9)\n at run (cucumber.js:1:1)\nCaused by: Error: inner\n at x (y.ts:1:1)' + } + ) + await service.after() + const ctx = finalizeTraceExport.mock.calls.at(-1)?.[0] as { + testMetadata: TestMetadataMap + } + const entry = ctx.testMetadata.get( + deterministicUid(uri, 'failing scenario') + ) + expect(entry?.error).toBe('AssertionError: expected 2\n+ actual 1') }) it('stamps a Cucumber scenario state in afterScenario', async () => { @@ -239,6 +510,61 @@ describe('DevtoolsService - afterTest state stamping', () => { ctx.testMetadata.get(deterministicUid(uri, 'add to cart'))?.state ).toBe('failed') }) + + it('records start, end, framework duration and the failure message', async () => { + const before = Date.now() + const service = new DevToolsHookService({ + mode: 'trace', + tracePolicy: 'retain-on-failure' + }) + await service.before({} as never, [], mockBrowser) + service.beforeTest({ file, fullTitle: 'timed fails' }) + await service.afterTest( + { file, fullTitle: 'timed fails' }, + {}, + { passed: false, error: new Error('boom'), duration: 42 } + ) + await service.after() + const after = Date.now() + const entry = finalizedEntry('timed fails') + expect(entry?.durationMs).toBe(42) + expect(entry?.error).toBe('boom') + expect(entry?.startTime).toBeGreaterThanOrEqual(before) + expect(entry?.endTime).toBeLessThanOrEqual(after) + expect(entry?.startTime).toBeLessThanOrEqual(entry?.endTime ?? NaN) + }) + + it('clears the failed attempt error when a retry passes', async () => { + const service = new DevToolsHookService({ + mode: 'trace', + tracePolicy: 'retain-on-failure' + }) + await service.before({} as never, [], mockBrowser) + service.beforeTest({ file, fullTitle: 'flaky' }) + await service.afterTest( + { file, fullTitle: 'flaky' }, + {}, + { passed: false, error: new Error('first try') } + ) + service.beforeTest({ file, fullTitle: 'flaky' }) + await service.afterTest( + { file, fullTitle: 'flaky' }, + {}, + { passed: true, duration: 7 } + ) + await service.after() + const entry = finalizedEntry('flaky') + expect(entry?.state).toBe('passed') + expect(entry?.error).toBeUndefined() + expect(entry?.durationMs).toBe(7) + }) + + function finalizedEntry(title: string): TestMetadataEntry | undefined { + const ctx = finalizeTraceExport.mock.calls.at(-1)?.[0] as { + testMetadata: TestMetadataMap + } + return ctx.testMetadata.get(deterministicUid(file, title)) + } }) /** diff --git a/packages/service/tests/wait-rows.test.ts b/packages/service/tests/wait-rows.test.ts index b6abe7181..89fa5d190 100644 --- a/packages/service/tests/wait-rows.test.ts +++ b/packages/service/tests/wait-rows.test.ts @@ -634,6 +634,25 @@ describe('a wait whose afterCommand WDIO skipped is closed when its test ends (# expect(wait.error?.message).toBe(TIMEOUT.message) }) + it('stamps a wait it closes at the step end, not after the hook settle', async () => { + const gated = wdioHookGate() + const release = heldScreenshot() + const { poll } = await elementWaitHeldInPoll(gated) + await elementWaitSettles(gated, TIMEOUT) + const stepEnded = Date.now() + const ended = service.afterStep(undefined, undefined, { + error: TIMEOUT.message + }) + await new Promise((resolve) => setTimeout(resolve, 30)) + const settled = Date.now() + release() + await Promise.all([ended, poll]) + + const wait = rows().find((r) => r.command === 'waitForExist')! + expect(wait.timestamp).toBeGreaterThanOrEqual(stepEnded) + expect(wait.timestamp).toBeLessThan(settled) + }) + it("closes it with a step's string error as the runner reported it, ANSI stripped and with no stack of the service's", async () => { const gated = wdioHookGate() const release = heldScreenshot() diff --git a/packages/shared/src/artifacts-manifest.ts b/packages/shared/src/artifacts-manifest.ts new file mode 100644 index 000000000..9b5a5c979 --- /dev/null +++ b/packages/shared/src/artifacts-manifest.ts @@ -0,0 +1,59 @@ +import type { ParentTraceContext } from './trace-context.js' +import type { TestMetadataEntry, TestStatus, TraceFormat } from './types.js' + +/** The retry key of attempt `attempt` of `uid`; attempt 0 keeps the bare uid. */ +export function retryKeyOf(uid: string, attempt: number): string { + return attempt > 0 ? `${uid}-retry${attempt}` : uid +} + +/** One artifact produced (or, when `retained` is false, decided-against) by a + * trace-mode run — a trace slice, a screencast video, or a per-test screenshot. */ +export interface TraceArtifact { + kind: 'trace' | 'video' | 'screenshot' + path: string + scope: 'session' | 'spec' | 'test' + /** specFile for spec scope; testUid for test scope, `${testUid}-retry${n}` for retry n. */ + key?: string + testUids: string[] + /** false = decided-not-to-write (reported, not written). Always true today. */ + retained: boolean +} + +/** One attempt of a test, with the trace context minted when it started. */ +export interface TestAttemptRecord { + attempt: number + state?: TestStatus + startTime: number + endTime?: number + traceId: string + spanId: string + /** Set on the attempt that decided the test's outcome; absent in manifests that predate it. */ + final?: boolean +} + +/** One test's outcome as recorded at export time. Field types track + * TestMetadataEntry; adds the keying uid, drops trace-only ancestry. */ +export interface ArtifactManifestTest extends Pick< + TestMetadataEntry, + | 'title' + | 'specFile' + | 'state' + | 'attempt' + | 'startTime' + | 'endTime' + | 'durationMs' + | 'error' +> { + uid: string + attempts?: TestAttemptRecord[] +} + +export interface ArtifactsManifest { + sessionId: string + format: TraceFormat + artifacts: TraceArtifact[] + tests: ArtifactManifestTest[] + runId?: string + /** Trace context inherited from a `TRACEPARENT` set by the CI job that launched the run. */ + parent?: ParentTraceContext +} diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index 45140e1e9..403695953 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -2,6 +2,7 @@ // across @wdio/devtools-* packages. See ARCHITECTURE.md §2 and CLAUDE.md §2.1. export * from './action-mapping.js' +export * from './artifacts-manifest.js' export * from './baseline.js' export * from './browser-schemes.js' export * from './call-source.js' @@ -29,6 +30,7 @@ export * from './runner.js' export * from './snapshot-format.js' export * from './timing.js' export * from './trace-actions.js' +export * from './trace-context.js' export * from './trace-export.js' export * from './trace-file.js' export * from './trace-player.js' diff --git a/packages/shared/src/trace-context.ts b/packages/shared/src/trace-context.ts new file mode 100644 index 000000000..81cbef2c1 --- /dev/null +++ b/packages/shared/src/trace-context.ts @@ -0,0 +1,86 @@ +/** W3C Trace Context (`traceparent`) for one test attempt. */ +export interface TestTraceContext { + /** 32 lowercase hex chars. */ + traceId: string + /** 16 lowercase hex chars. */ + spanId: string + traceFlags: number +} + +/** A parent context read from `TRACEPARENT`, with the optional `TRACESTATE` it arrived with. */ +export type ParentTraceContext = TestTraceContext & { traceState?: string } + +export const TRACE_ID_BYTES = 16 +export const SPAN_ID_BYTES = 8 + +export const TRACE_CONTEXT_ENV = { + TRACEPARENT: 'TRACEPARENT', + TRACESTATE: 'TRACESTATE' +} as const + +const VERSION_RE = /^[0-9a-f]{2}$/ +const TRACE_ID_RE = new RegExp(`^[0-9a-f]{${TRACE_ID_BYTES * 2}}$`) +const SPAN_ID_RE = new RegExp(`^[0-9a-f]{${SPAN_ID_BYTES * 2}}$`) +const FLAGS_RE = /^[0-9a-f]{2}$/ +const ALL_ZERO_RE = /^0+$/ +const INVALID_VERSION = 'ff' +const VERSION_00 = '00' + +export function isTraceId(value: unknown): value is string { + return ( + typeof value === 'string' && + TRACE_ID_RE.test(value) && + !ALL_ZERO_RE.test(value) + ) +} + +export function isSpanId(value: unknown): value is string { + return ( + typeof value === 'string' && + SPAN_ID_RE.test(value) && + !ALL_ZERO_RE.test(value) + ) +} + +/** Versions above `00` may append fields; `00` admits exactly four. */ +export function parseTraceparent( + header: string | undefined +): TestTraceContext | undefined { + if (header === undefined) { + return undefined + } + const [version, traceId, spanId, flags, ...extra] = header.split('-') + if ( + version === undefined || + !VERSION_RE.test(version) || + version === INVALID_VERSION || + (version === VERSION_00 && extra.length > 0) || + !isTraceId(traceId) || + !isSpanId(spanId) || + !FLAGS_RE.test(flags ?? '') + ) { + return undefined + } + return { + traceId: traceId!, + spanId: spanId!, + traceFlags: parseInt(flags!, 16) + } +} + +// Web Crypto, so this module stays usable in the browser. An all-zero id, the one invalid draw, has odds of 2^-64 or less. +function randomHex(bytes: number): string { + const buffer = new Uint8Array(bytes) + globalThis.crypto.getRandomValues(buffer) + return Array.from(buffer, (byte) => byte.toString(16).padStart(2, '0')).join( + '' + ) +} + +export function randomTraceId(): string { + return randomHex(TRACE_ID_BYTES) +} + +export function randomSpanId(): string { + return randomHex(SPAN_ID_BYTES) +} diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts index 9ea039199..d91e3ee30 100644 --- a/packages/shared/src/types.ts +++ b/packages/shared/src/types.ts @@ -81,6 +81,13 @@ export interface TestMetadataEntry { state?: TestStatus attempt?: number ancestry?: TestAncestor[] + /** Wall-clock epoch ms of the attempt this entry describes. */ + startTime?: number + endTime?: number + /** Framework-reported duration, when the runner provides one. */ + durationMs?: number + /** Failure message of the final attempt; absent unless it failed. */ + error?: string } /** Test metadata keyed by testUid — maps stable test IDs to human-readable diff --git a/packages/shared/tests/trace-context.test.ts b/packages/shared/tests/trace-context.test.ts new file mode 100644 index 000000000..acc9a2e70 --- /dev/null +++ b/packages/shared/tests/trace-context.test.ts @@ -0,0 +1,91 @@ +import { describe, expect, it } from 'vitest' +import { + isSpanId, + isTraceId, + parseTraceparent, + randomSpanId, + randomTraceId, + TRACE_CONTEXT_ENV +} from '../src/trace-context.js' + +const TRACE_ID = '0af7651916cd43dd8448eb211c80319c' +const SPAN_ID = 'b7ad6b7169203331' +const VALID = `00-${TRACE_ID}-${SPAN_ID}-01` + +describe('traceparent', () => { + it('reads the flags of an unsampled header as 0', () => { + expect(parseTraceparent(`00-${TRACE_ID}-${SPAN_ID}-00`)?.traceFlags).toBe(0) + }) + + it('parses a valid version-00 header', () => { + expect(parseTraceparent(VALID)).toEqual({ + traceId: TRACE_ID, + spanId: SPAN_ID, + traceFlags: 1 + }) + }) + + it('accepts a higher version that appends fields', () => { + expect(parseTraceparent(`01-${TRACE_ID}-${SPAN_ID}-01-extra`)).toEqual({ + traceId: TRACE_ID, + spanId: SPAN_ID, + traceFlags: 1 + }) + }) + + it('rejects version 00 with trailing fields', () => { + expect(parseTraceparent(`${VALID}-extra`)).toBeUndefined() + }) + + it('rejects wrong lengths', () => { + expect( + parseTraceparent(`00-${TRACE_ID.slice(1)}-${SPAN_ID}-01`) + ).toBeUndefined() + expect(parseTraceparent(`00-${TRACE_ID}-${SPAN_ID}0-01`)).toBeUndefined() + expect(parseTraceparent(`00-${TRACE_ID}-${SPAN_ID}-1`)).toBeUndefined() + }) + + it('rejects uppercase hex', () => { + expect( + parseTraceparent(`00-${TRACE_ID.toUpperCase()}-${SPAN_ID}-01`) + ).toBeUndefined() + }) + + it('rejects all-zero trace and span ids', () => { + expect( + parseTraceparent(`00-${'0'.repeat(32)}-${SPAN_ID}-01`) + ).toBeUndefined() + expect( + parseTraceparent(`00-${TRACE_ID}-${'0'.repeat(16)}-01`) + ).toBeUndefined() + }) + + it('rejects version ff and non-hex versions', () => { + expect(parseTraceparent(`ff-${TRACE_ID}-${SPAN_ID}-01`)).toBeUndefined() + expect(parseTraceparent(`zz-${TRACE_ID}-${SPAN_ID}-01`)).toBeUndefined() + }) + + it('treats undefined and garbage as no context', () => { + expect(parseTraceparent(undefined)).toBeUndefined() + expect(parseTraceparent('')).toBeUndefined() + expect(parseTraceparent('not-a-header')).toBeUndefined() + }) + + it('names the env vars the context travels in', () => { + expect(TRACE_CONTEXT_ENV).toEqual({ + TRACEPARENT: 'TRACEPARENT', + TRACESTATE: 'TRACESTATE' + }) + }) +}) + +describe('random ids', () => { + it('draws valid, distinct trace and span ids', () => { + const traceIds = new Set(Array.from({ length: 50 }, randomTraceId)) + const spanIds = new Set(Array.from({ length: 50 }, randomSpanId)) + expect(traceIds.size).toBe(50) + expect(spanIds.size).toBe(50) + expect([...traceIds].every(isTraceId)).toBe(true) + expect([...spanIds].every(isSpanId)).toBe(true) + }) +}) From f43d6de136fa14d8c22190779a56d1ca62fdb1d2 Mon Sep 17 00:00:00 2001 From: Vince Graics Date: Wed, 11 Nov 2026 09:03:59 +0100 Subject: [PATCH 02/15] fix: keep one manifest entry per retried test and number attempts from the real attempt A retried Selenium test was listed twice with final on its failed attempt, because the test uid carried a per-process counter the attempt ledger did not. A specFileRetries rerun recorded attempt 0, the tracker could renumber an attempt into a repeat, and only the final attempt kept its error. Artifact paths are now written relative to the manifest directory so a moved or downloaded results folder still resolves, and the manifest records cwd and browser identity for the exporter to slice by. Co-Authored-By: Claude Fable 5.2 --- .../manifest-relative-artifact-paths.md | 7 ++ .changeset/manifest-test-timing.md | 6 +- .changeset/otel-attempt-trace-ids.md | 2 +- .changeset/selenium-retry-manifest.md | 5 + .changeset/service-spec-file-retry-attempt.md | 5 + packages/core/src/artifacts-manifest.ts | 42 ++++++++- packages/core/src/attempt-tracker.ts | 36 ++++--- packages/core/src/spec-trace-helpers.ts | 4 +- packages/core/src/suite-helpers.ts | 22 ++++- packages/core/src/trace-finalizer.ts | 24 ++++- .../core/tests/artifacts-manifest.test.ts | 55 ++++++++++- packages/core/tests/attempt-tracker.test.ts | 27 ++++-- .../core/tests/spec-trace-helpers.test.ts | 7 ++ packages/core/tests/suite-helpers.test.ts | 23 +++++ packages/core/tests/trace-finalizer.test.ts | 20 ++++ .../src/helpers/testManager.ts | 93 ++++++++++++------- packages/selenium-devtools/src/index.ts | 15 +-- .../src/runnerHooks/cucumber.ts | 4 +- .../src/runnerHooks/mocha.ts | 10 +- .../src/session-lifecycle.ts | 11 ++- .../selenium-devtools/src/test-management.ts | 16 ++-- packages/selenium-devtools/src/types.ts | 11 ++- .../tests/attempt-capture.test.ts | 76 ++++++++++++++- .../tests/mocha-root-hooks.test.ts | 49 ++++++++++ .../tests/trace-granularity.test.ts | 9 +- packages/service/src/index.ts | 25 +++-- packages/service/src/reporter.ts | 13 ++- packages/service/src/test-metadata.ts | 37 ++++---- packages/service/src/trace-slices.ts | 4 +- packages/service/tests/reporter.test.ts | 16 +++- packages/service/tests/trace-metadata.test.ts | 55 ++++++++++- .../service/tests/trace-slice-tracker.test.ts | 10 ++ packages/shared/src/artifacts-manifest.ts | 6 ++ 33 files changed, 613 insertions(+), 132 deletions(-) create mode 100644 .changeset/manifest-relative-artifact-paths.md create mode 100644 .changeset/selenium-retry-manifest.md create mode 100644 .changeset/service-spec-file-retry-attempt.md diff --git a/.changeset/manifest-relative-artifact-paths.md b/.changeset/manifest-relative-artifact-paths.md new file mode 100644 index 000000000..dbb8c5187 --- /dev/null +++ b/.changeset/manifest-relative-artifact-paths.md @@ -0,0 +1,7 @@ +--- +'@wdio/devtools-service': minor +'@wdio/selenium-devtools': minor +'@wdio/nightwatch-devtools': minor +--- + +`artifacts[].path` in the artifacts manifest is now relative to the manifest's directory, so a results folder can be moved or downloaded and still be read. A script that read the absolute path must resolve it against the manifest's directory. diff --git a/.changeset/manifest-test-timing.md b/.changeset/manifest-test-timing.md index bc47ca506..c4262a74c 100644 --- a/.changeset/manifest-test-timing.md +++ b/.changeset/manifest-test-timing.md @@ -1,5 +1,7 @@ --- -"@wdio/devtools-service": minor +'@wdio/devtools-service': minor +'@wdio/selenium-devtools': minor +'@wdio/nightwatch-devtools': minor --- -The WebdriverIO service's artifacts manifest (`devtools-artifacts-.json`) now carries each test's start and end time, framework-reported duration (Cucumber scenarios fall back to wall-clock time, since WDIO's Cucumber duration is only the nanoseconds field of the worst step), and the failure message of its final attempt, so reporters can build a per-test record without opening the trace zip. The Selenium and Nightwatch adapters do not write these fields yet. +The artifacts manifest (`devtools-artifacts-.json`) now carries each test's start and end time and framework-reported duration, and the failure message of its final attempt, so reporters can build a per-test record without opening the trace zip. The WebdriverIO service writes Cucumber scenario durations from wall-clock time, since WDIO's Cucumber duration is only the nanoseconds field of the worst step. diff --git a/.changeset/otel-attempt-trace-ids.md b/.changeset/otel-attempt-trace-ids.md index fd19d290f..e2105c0af 100644 --- a/.changeset/otel-attempt-trace-ids.md +++ b/.changeset/otel-attempt-trace-ids.md @@ -4,4 +4,4 @@ '@wdio/nightwatch-devtools': minor --- -The artifacts manifest now carries the run's `runId`, the parent trace context from `TRACEPARENT` when set, and an `attempts[]` list per test whose entries hold a trace and span id minted when the attempt starts. +The artifacts manifest now carries the run's `runId`, the parent trace context from `TRACEPARENT` when set, the `cwd` and browser name, version and platform, and an `attempts[]` list per test. Each attempt entry holds a trace and span id minted when the attempt starts, and its own `error`. Attempt numbers no longer repeat within a worker, and a `specFileRetries` rerun starts at its real attempt, so `on-first-retry` now retains a rerun's trace and `retain-on-first-failure` does not. diff --git a/.changeset/selenium-retry-manifest.md b/.changeset/selenium-retry-manifest.md new file mode 100644 index 000000000..12fee8c59 --- /dev/null +++ b/.changeset/selenium-retry-manifest.md @@ -0,0 +1,5 @@ +--- +'@wdio/selenium-devtools': patch +--- + +A retried Mocha test is listed once in the artifacts manifest, with its last attempt marked final. An attempt Mocha will retry is reported failed rather than passed, and a repeated Cucumber step text is no longer read as a retry. diff --git a/.changeset/service-spec-file-retry-attempt.md b/.changeset/service-spec-file-retry-attempt.md new file mode 100644 index 000000000..88fe95e32 --- /dev/null +++ b/.changeset/service-spec-file-retry-attempt.md @@ -0,0 +1,5 @@ +--- +'@wdio/devtools-service': patch +--- + +A test run by a `specFileRetries` rerun records its real attempt number instead of 0. diff --git a/packages/core/src/artifacts-manifest.ts b/packages/core/src/artifacts-manifest.ts index be8b2f570..39d4906fd 100644 --- a/packages/core/src/artifacts-manifest.ts +++ b/packages/core/src/artifacts-manifest.ts @@ -54,6 +54,13 @@ function markFinalAttempt( ) } +/** Drops undefined values so an unset key is absent from the manifest, not present as undefined. */ +function presentKeys>(values: T): Partial { + return Object.fromEntries( + Object.entries(values).filter(([, value]) => value !== undefined) + ) as Partial +} + /** Assemble the manifest from the artifacts collected across the run and the * test-metadata map. Pure — the write is separate so it stays unit-testable. */ export function buildArtifactsManifest(input: { @@ -64,6 +71,10 @@ export function buildArtifactsManifest(input: { runId?: string parent?: ArtifactsManifest['parent'] attemptsFor?: (uid: string) => TestAttemptRecord[] + cwd?: string + browserName?: string + browserVersion?: string + platformName?: string }): ArtifactsManifest { const tests: ArtifactManifestTest[] = [] for (const [uid, meta] of input.testMetadata) { @@ -93,10 +104,33 @@ export function buildArtifactsManifest(input: { artifacts: [...input.artifacts], tests, runId: input.runId, - parent: input.parent + parent: input.parent, + ...presentKeys({ + cwd: input.cwd, + browserName: input.browserName, + browserVersion: input.browserVersion, + platformName: input.platformName + }) } } +/** Artifact paths are stored relative to the manifest so the directory can move; a path on another Windows drive stays absolute. */ +function relativizeArtifacts( + outputDir: string, + artifacts: readonly TraceArtifact[] +): TraceArtifact[] { + return artifacts.map((artifact) => { + if (artifact.path === '') { + return artifact + } + const relative = path.relative(outputDir, artifact.path) + if (path.isAbsolute(relative)) { + return artifact + } + return { ...artifact, path: relative.split(path.sep).join('/') } + }) +} + /** Write the manifest to `outputDir`, returning its absolute path. */ export async function writeArtifactsManifest( outputDir: string, @@ -107,6 +141,10 @@ export async function writeArtifactsManifest( outputDir, artifactsManifestFilename(manifest.sessionId) ) - await fs.writeFile(filePath, JSON.stringify(manifest, null, 2), 'utf8') + const portable = { + ...manifest, + artifacts: relativizeArtifacts(outputDir, manifest.artifacts) + } + await fs.writeFile(filePath, JSON.stringify(portable, null, 2), 'utf8') return filePath } diff --git a/packages/core/src/attempt-tracker.ts b/packages/core/src/attempt-tracker.ts index a33143a50..0443a1473 100644 --- a/packages/core/src/attempt-tracker.ts +++ b/packages/core/src/attempt-tracker.ts @@ -10,6 +10,7 @@ interface AttemptSlot { outcome: TestOutcome startTime: number endTime?: number + error?: string trace: AttemptIds } @@ -36,8 +37,18 @@ export interface RetryOutcomeView { export class TestAttemptTracker implements RetryOutcomeView { #ledger = new Map() #sawRetry = false + #base = 0 - /** Record a starting test; returns its attempt number (0 first, +1 per rerun). + /** Number the attempts of tests started from here on from `base`. */ + startNumberingAt(base: number): void { + this.#base = base + } + + get base(): number { + return this.#base + } + + /** Record a starting test; returns its attempt number (base first, +1 per rerun). * `specFile` (optional) enables spec-scoped retention lookups. */ recordStart(uid: string, specFile?: string): number { const entry = this.#ledger.get(uid) @@ -51,7 +62,7 @@ export class TestAttemptTracker implements RetryOutcomeView { prior.outcome.state = 'failed' prior.endTime ??= Date.now() } - const attempt = entry ? entry.attempts.length : 0 + const attempt = this.#base + (entry ? entry.attempts.length : 0) const slot: AttemptSlot = { outcome: { uid, attempt }, startTime: Date.now(), @@ -68,29 +79,27 @@ export class TestAttemptTracker implements RetryOutcomeView { return attempt } - /** Stamp the resolved state onto uid's most recent attempt slot once the outcome is known. A runner attempt - * past the ledger's count (in-worker repeat) renumbers the slot to it, so the record matches the test's attempt. */ + /** Stamp the resolved state, and the failure message when there is one, onto uid's most recent attempt slot once the outcome is known. */ recordOutcome( uid: string, state: TestStatus | undefined, - attempt?: number + error?: string ): void { - const attempts = this.#ledger.get(uid)?.attempts ?? [] - const slot = attempts[attempts.length - 1] + const slot = this.#ledger.get(uid)?.attempts.at(-1) if (!slot) { return } slot.outcome.state = state slot.endTime = Date.now() - if (attempt !== undefined && attempt >= attempts.length) { - slot.outcome.attempt = attempt + if (error !== undefined) { + slot.error = error } } - /** Latest attempt recorded for `uid`, or undefined if it never started. */ + /** Latest attempt number recorded for `uid`, or undefined if it never started. */ attemptFor(uid: string): number | undefined { const entry = this.#ledger.get(uid) - return entry ? entry.attempts.length - 1 : undefined + return entry ? this.#base + entry.attempts.length - 1 : undefined } /** True once any test has started more than once (a retry occurred). */ @@ -132,11 +141,12 @@ export class TestAttemptTracker implements RetryOutcomeView { startTime: slot.startTime, endTime: slot.endTime, traceId: slot.trace.traceId, - spanId: slot.trace.spanId + spanId: slot.trace.spanId, + ...(slot.error === undefined ? {} : { error: slot.error }) })) } - /** Clear all state — used at session boundaries and reuse-mode reconnects. */ + /** Clear all state — used at session boundaries and reuse-mode reconnects. The attempt base survives. */ reset(): void { this.#ledger.clear() this.#sawRetry = false diff --git a/packages/core/src/spec-trace-helpers.ts b/packages/core/src/spec-trace-helpers.ts index e6a9b2188..e7deade24 100644 --- a/packages/core/src/spec-trace-helpers.ts +++ b/packages/core/src/spec-trace-helpers.ts @@ -277,6 +277,8 @@ export interface SpecBoundaryContext { /** The adapter's live in-flight capture list, stamped onto each range as * `captureStartIdx`. Live by reference: it grows as the run does. */ pendingCaptures?: ArrayLike + /** Attempt number the first recorded attempt of a test is keyed by; see `TestAttemptTracker.startNumberingAt`. */ + attemptBase?: number } /** Push a new slice range and return the previous (unflushed) range to flush. @@ -337,7 +339,7 @@ export function recordSliceBoundary( return pushSliceRange( ctx, specFile, - retryKeyOf(testUid, priorAttempts), + retryKeyOf(testUid, (ctx.attemptBase ?? 0) + priorAttempts), testUid, false ) diff --git a/packages/core/src/suite-helpers.ts b/packages/core/src/suite-helpers.ts index e12e880d6..1fa3821c4 100644 --- a/packages/core/src/suite-helpers.ts +++ b/packages/core/src/suite-helpers.ts @@ -1,6 +1,8 @@ import type { + ReporterError, SuiteStats, TestAncestor, + TestMetadataEntry, TestMetadataMap, TestStats, TestStatus @@ -195,6 +197,20 @@ function scenarioAttempt(suite: SuiteStats): number { return attempt } +function timingOf(stats: { + start: Date + end?: Date | null + _duration: number + error?: ReporterError +}): Pick { + const endTime = stats.end ? new Date(stats.end).getTime() : undefined + return { + startTime: new Date(stats.start).getTime(), + ...(endTime === undefined ? {} : { endTime, durationMs: stats._duration }), + ...(stats.error === undefined ? {} : { error: stats.error.message }) + } +} + /** * Recursive walk over suite trees collecting every test's metadata entry — * uid → title/specFile/state/attempt plus the ancestor chain (outermost @@ -226,7 +242,8 @@ export function collectSuiteTestMetadata( specFile: suite.file, state: suite.state, attempt: scenarioAttempt(suite), - ancestry: ancestors + ancestry: ancestors, + ...timingOf(suite) }) } for (const entry of suite.tests ?? []) { @@ -239,7 +256,8 @@ export function collectSuiteTestMetadata( specFile: entry.file ?? suite.file, state: entry.state, attempt: entry.retries ?? 0, - ancestry: chain + ancestry: chain, + ...timingOf(entry) }) } for (const child of suite.suites ?? []) { diff --git a/packages/core/src/trace-finalizer.ts b/packages/core/src/trace-finalizer.ts index 9f04fffa7..28564ba05 100644 --- a/packages/core/src/trace-finalizer.ts +++ b/packages/core/src/trace-finalizer.ts @@ -6,8 +6,10 @@ * finalizeTraceExport — all sequencing lives here. */ +import { deepCapString } from '@wdio/devtools-shared' import type { ActionSnapshot, + ArtifactsManifest, DevToolsMode, ScreencastFrame, TestMetadataMap, @@ -476,6 +478,21 @@ async function fanOutTraceWrites( return artifact ? [artifact] : [] } +/** Browser identity from the session's matched capabilities; unread keys stay undefined. */ +function browserIdentity( + capabilities: unknown +): Pick { + if (typeof capabilities !== 'object' || capabilities === null) { + return {} + } + const caps = capabilities as Record + return { + browserName: deepCapString(caps, 'browserName'), + browserVersion: deepCapString(caps, 'browserVersion'), + platformName: deepCapString(caps, 'platformName') + } +} + /** 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. */ @@ -487,6 +504,9 @@ async function maybeWriteManifest( return } const artifacts = ctx.collectedArtifacts ?? fanOutArtifacts + const browser = browserIdentity( + ctx.capabilities ?? ctx.capturer.metadata?.capabilities + ) try { const path = await writeArtifactsManifest( ctx.resolveOutputDir(), @@ -497,7 +517,9 @@ async function maybeWriteManifest( testMetadata: ctx.testMetadata, runId: resolveRunId(), parent: resolveParentTraceContext(), - attemptsFor: ctx.outcomes?.attemptsFor.bind(ctx.outcomes) + attemptsFor: ctx.outcomes?.attemptsFor.bind(ctx.outcomes), + cwd: process.cwd(), + ...browser }) ) ctx.log?.('info', `Artifacts manifest written to ${path}`) diff --git a/packages/core/tests/artifacts-manifest.test.ts b/packages/core/tests/artifacts-manifest.test.ts index 4e7b30bbf..e0402f0c2 100644 --- a/packages/core/tests/artifacts-manifest.test.ts +++ b/packages/core/tests/artifacts-manifest.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect, afterEach } from 'vitest' import { rm, readFile, mkdtemp } from 'node:fs/promises' import { tmpdir } from 'node:os' -import { join } from 'node:path' +import { join, relative } from 'node:path' import { buildArtifactsManifest, writeArtifactsManifest, @@ -338,6 +338,57 @@ describe('artifacts manifest', () => { const parsed = JSON.parse( await readFile(filePath, 'utf8') ) as ArtifactsManifest - expect(parsed).toEqual(manifest) + expect(parsed).toEqual({ + ...manifest, + artifacts: artifacts.map((a) => ({ ...a, path: relative(dir, a.path) })) + }) + }) + + it('writes artifact paths relative to the manifest directory', async () => { + const dir = await mkdtemp(join(tmpdir(), 'manifest-')) + dirs.push(dir) + const inside = join(dir, 'traces', 'u1.zip') + const manifest = buildArtifactsManifest({ + sessionId: 'sess-rel', + format: 'zip', + artifacts: [ + { ...artifacts[0]!, path: inside }, + { ...artifacts[1]!, path: '' } + ], + testMetadata: metadata() + }) + const filePath = await writeArtifactsManifest(dir, manifest) + const parsed = JSON.parse( + await readFile(filePath, 'utf8') + ) as ArtifactsManifest + expect(parsed.artifacts.map((a) => a.path)).toEqual(['traces/u1.zip', '']) + expect(manifest.artifacts[0]!.path).toBe(inside) + }) + + it('passes cwd and browser identity through, leaving unset keys out', () => { + const m = buildArtifactsManifest({ + sessionId: 'sess-id', + format: 'zip', + artifacts: [], + testMetadata: metadata(), + cwd: '/work', + browserName: 'chrome', + browserVersion: '150.0', + platformName: 'linux' + }) + expect(m).toMatchObject({ + cwd: '/work', + browserName: 'chrome', + browserVersion: '150.0', + platformName: 'linux' + }) + const bare = buildArtifactsManifest({ + sessionId: 'sess-bare', + format: 'zip', + artifacts: [], + testMetadata: metadata() + }) + expect(bare).not.toHaveProperty('cwd') + expect(bare).not.toHaveProperty('browserName') }) }) diff --git a/packages/core/tests/attempt-tracker.test.ts b/packages/core/tests/attempt-tracker.test.ts index 69722f313..0bf9798f5 100644 --- a/packages/core/tests/attempt-tracker.test.ts +++ b/packages/core/tests/attempt-tracker.test.ts @@ -71,19 +71,34 @@ describe('TestAttemptTracker', () => { ]) }) - it('recordOutcome renumbers the slot to a runner attempt past the ledger count', () => { + it('never repeats or reorders attempt numbers', () => { const t = new TestAttemptTracker() t.recordStart('a') - t.recordOutcome('a', 'passed', 3) - expect(t.attemptsFor('a').map((r) => r.attempt)).toEqual([3]) + t.recordOutcome('a', 'failed') + expect(t.recordStart('a')).toBe(1) + t.recordOutcome('a', 'passed') + expect(t.attemptsFor('a').map((r) => r.attempt)).toEqual([0, 1]) }) - it('recordOutcome keeps the ledger number when the runner attempt is not ahead', () => { + it('numbers from the base', () => { + const t = new TestAttemptTracker() + t.startNumberingAt(2) + expect(t.base).toBe(2) + expect(t.recordStart('a')).toBe(2) + expect(t.recordStart('a')).toBe(3) + expect(t.attemptFor('a')).toBe(3) + expect(t.attemptsFor('a').map((r) => r.attempt)).toEqual([2, 3]) + }) + + it('keeps the error of each attempt', () => { const t = new TestAttemptTracker() t.recordStart('a') + t.recordOutcome('a', 'failed', 'boom') t.recordStart('a') - t.recordOutcome('a', 'passed', 0) - expect(t.attemptsFor('a').map((r) => r.attempt)).toEqual([0, 1]) + t.recordOutcome('a', 'passed') + const [first, second] = t.attemptsFor('a') + expect(first).toMatchObject({ attempt: 0, error: 'boom' }) + expect(second).not.toHaveProperty('error') }) it('a retry stamps the prior attempt failed (swallowed-failure runners)', () => { diff --git a/packages/core/tests/spec-trace-helpers.test.ts b/packages/core/tests/spec-trace-helpers.test.ts index f88917084..307144579 100644 --- a/packages/core/tests/spec-trace-helpers.test.ts +++ b/packages/core/tests/spec-trace-helpers.test.ts @@ -272,6 +272,13 @@ describe('recordSliceBoundary (test granularity)', () => { expect(ctx.specRanges.every((r) => r.testUid === 'u1')).toBe(true) }) + it('numbers retry keys from attemptBase when the run resumes an earlier numbering', () => { + const ctx = boundaryCtx({ attemptBase: 2 }) + recordSliceBoundary(ctx, 'test', '/a.js', 'u1') + recordSliceBoundary(ctx, 'test', '/a.js', 'u1') + expect(ctx.specRanges.map((r) => r.key)).toEqual(['u1-retry2', 'u1-retry3']) + }) + it('returns null when no testUid is provided', () => { const ctx = boundaryCtx() expect(recordSliceBoundary(ctx, 'test', '/a.js')).toBeNull() diff --git a/packages/core/tests/suite-helpers.test.ts b/packages/core/tests/suite-helpers.test.ts index af49d5eb8..c27f8687f 100644 --- a/packages/core/tests/suite-helpers.test.ts +++ b/packages/core/tests/suite-helpers.test.ts @@ -245,6 +245,29 @@ describe('collectSuiteTestMetadata', () => { expect(map.size).toBe(2) }) + it('carries timing from the suite tree', () => { + const root = createSuiteStats({ uid: 'root', title: 'Root', file: '/a.ts' }) + root.tests = [ + namedTest('t1', 'root', { + start: new Date(1000), + end: new Date(1500), + _duration: 480, + error: new Error('boom') + }), + namedTest('t2', 'root', { start: new Date(2000), end: null }) + ] + const map = collectSuiteTestMetadata([root]) + expect(map.get('t1')).toMatchObject({ + startTime: 1000, + endTime: 1500, + durationMs: 480, + error: 'boom' + }) + expect(map.get('t2')?.startTime).toBe(2000) + expect(map.get('t2')).not.toHaveProperty('endTime') + expect(map.get('t2')).not.toHaveProperty('error') + }) + it('carries state and attempt (from retries), defaulting attempt to 0', () => { const root = createSuiteStats({ uid: 'r', title: 'R', file: '/a.ts' }) root.tests = [ diff --git a/packages/core/tests/trace-finalizer.test.ts b/packages/core/tests/trace-finalizer.test.ts index feddaad30..389da118e 100644 --- a/packages/core/tests/trace-finalizer.test.ts +++ b/packages/core/tests/trace-finalizer.test.ts @@ -395,6 +395,26 @@ describe('finalizeTraceExport', () => { ]) }) + it('records cwd and browser identity', async () => { + await finalizeTraceExport( + baseCtx({ + emitManifest: true, + capabilities: { + browserName: 'chrome', + browserVersion: '150.0.1', + platformName: 'linux' + } + }) + ) + const manifest = JSON.parse(await fs.readFile(manifestPath(), 'utf8')) + expect(manifest).toMatchObject({ + cwd: process.cwd(), + browserName: 'chrome', + browserVersion: '150.0.1', + platformName: 'linux' + }) + }) + it('writes nothing in live mode, even when emitManifest is set', async () => { await finalizeTraceExport(baseCtx({ mode: 'live', emitManifest: true })) expect(await fs.readdir(outputDir)).toEqual([]) diff --git a/packages/selenium-devtools/src/helpers/testManager.ts b/packages/selenium-devtools/src/helpers/testManager.ts index 8ce2ac795..018f75aef 100644 --- a/packages/selenium-devtools/src/helpers/testManager.ts +++ b/packages/selenium-devtools/src/helpers/testManager.ts @@ -30,13 +30,6 @@ export class TestManager { // Retry-stable-keyed so a test's attempts group under one entry; the trace // finalizer reads it (attemptOutcomes) for retry-aware retention. #attemptTracker = new TestAttemptTracker() - // Retry-stable uid of the in-progress marked test, so endCurrent can stamp - // this attempt's outcome onto the same ledger entry recordStart opened. - #currentRetryStableUid: string | undefined - // Retry-stable uid of the most-recently-started marked test, retained past - // endCurrent so the per-test artifact path (which runs after the test ends) - // can read this test's attempts from the ledger for video retention. - #lastRetryStableUid: string | undefined /** Set true the first time the user calls startMarkedTest. Once true we * never auto-create the synthetic session test — orphan commands attach * to the most-recently-marked test instead. */ @@ -139,49 +132,83 @@ export class TestManager { // Scope by parent so two suites with the same test/step name don't // collide on signatureCounter disambiguation across rerun processes. const signature = `${this.suite.uid}::${name}` + const retriedUid = this.#retriedUid(name, file, signature, opts.attempt) + const uid = retriedUid ?? generateStableUid(file, signature) + const ledgerAttempt = this.#attemptTracker.recordStart(uid, file) const test = createTestStats({ - uid: generateStableUid(file, signature), + uid, cid: DEFAULTS.CID, title: name, file, parent: this.suite.uid, callSource: opts.callSource }) - // deterministicUid is retry-stable (no counter), so re-entering with the - // same logical test increments the heuristic. Mocha supplies an - // authoritative per-test retry index via opts.attempt; prefer it. - const retryStableUid = deterministicUid(file, signature) - const heuristicAttempt = this.#attemptTracker.recordStart( - retryStableUid, - file - ) - this.#currentRetryStableUid = retryStableUid - this.#lastRetryStableUid = retryStableUid - test.retries = opts.attempt ?? heuristicAttempt + test.retries = opts.attempt ?? ledgerAttempt log.info( `Started marked test "${name}" (callSource: ${opts.callSource || 'n/a'})` ) - this.suite.tests.push(test) + const replaced = + retriedUid === undefined + ? -1 + : this.suite.tests.findIndex( + (t) => typeof t !== 'string' && t.uid === retriedUid + ) + if (replaced === -1) { + this.suite.tests.push(test) + } else { + this.suite.tests[replaced] = test + } this.#currentTest = test this.#lastMarkedTest = test this.testReporter.onTestStart(test) return test } - endCurrent(state: TestStats['state']): void { + /** The uid of the attempt a re-entry retries, so one tests[] entry carries every attempt. A cucumber step is never a retry. */ + #retriedUid( + name: string, + file: string, + signature: string, + attempt: number | undefined + ): string | undefined { + const prior = this.#lastMarkedTest + if (attempt !== undefined) { + return attempt > 0 && + prior?.title === name && + prior.parent === this.suite.uid + ? prior.uid + : undefined + } + const stableUid = deterministicUid(file, signature) + const isStep = this.suite !== this.rootSuite + if (isStep) { + return undefined + } + const earlier = this.suite.tests.find( + (t) => typeof t !== 'string' && t.uid === stableUid + ) + // A retry only follows a failure, so a passed namesake is another test. + return typeof earlier === 'object' && earlier.state !== 'passed' + ? stableUid + : undefined + } + + endCurrent(state: TestStats['state'], error?: string): void { const test = this.#currentTest if (!test) { return } test.state = state stampTestEnd(test) - // Stamp this attempt's real outcome onto its retry-stable ledger slot so a - // fail-then-pass groups under one test: retain-on-failure keys on the final - // (passed) attempt and stops over-retaining, retain-on-first-failure on - // attempt 0. Skipped for the synthetic session test (no recordStart). - if (this.#currentRetryStableUid !== undefined) { - this.#attemptTracker.recordOutcome(this.#currentRetryStableUid, state) - this.#currentRetryStableUid = undefined + if (error !== undefined) { + test.error = { name: 'Error', message: error } + } + // Stamp this attempt's real outcome onto its ledger slot so a fail-then-pass + // groups under one test: retain-on-failure keys on the final (passed) + // attempt and stops over-retaining, retain-on-first-failure on attempt 0. + // Skipped for the synthetic session test, which never recordStart'd. + if (this.#lastMarkedTest === test) { + this.#attemptTracker.recordOutcome(test.uid, state, error) } this.testReporter.onTestEnd(test) this.#currentTest = null @@ -197,15 +224,13 @@ export class TestManager { return this.#attemptTracker } - /** The just-ended marked test's attempts, keyed by its retry-stable uid (the - * ledger key), for the per-test video retention decision. The artifact - * filename uses the marked uid, but retention groups a test's attempts under - * the retry-stable key — this bridges the two. Empty when no marked test ran. */ + /** The just-ended marked test's attempts, for the per-test video retention + * decision. Empty when no marked test ran. */ lastTestOutcomes(): TestOutcome[] { - if (this.#lastRetryStableUid === undefined) { + if (this.#lastMarkedTest === null) { return [] } - return this.#attemptTracker.forTest(this.#lastRetryStableUid) + return this.#attemptTracker.forTest(this.#lastMarkedTest.uid) } /** A plain script's end: closes only the synthetic test; one the script started is the script's to end. */ diff --git a/packages/selenium-devtools/src/index.ts b/packages/selenium-devtools/src/index.ts index a44e27d2f..47547c856 100644 --- a/packages/selenium-devtools/src/index.ts +++ b/packages/selenium-devtools/src/index.ts @@ -490,9 +490,9 @@ class SeleniumDevToolsPlugin { // Async + awaited by the runner's afterEach so the per-test artifact emit // (trace slice + screenshot + video attach) completes while the test is still // open; otherwise allure closes the test before attachment() runs. - async endTest(state: TestStats['state'] = 'passed') { + async endTest(state: TestStats['state'] = 'passed', error?: string) { const ended = this.#testManager?.getCurrentTest() ?? null - tmEndTest(this.#getInternals(), state) + tmEndTest(this.#getInternals(), state, error) await settlePageResources(this.#getInternals()) await captureFinalFrame(this.#getInternals()) const flushed = flushCurrentTestTrace(this.#getInternals()) @@ -505,9 +505,9 @@ class SeleniumDevToolsPlugin { recordTraceBoundary(this.#getInternals(), meta.file) } - async endScenario(state: TestStats['state'] = 'passed') { + async endScenario(state: TestStats['state'] = 'passed', error?: string) { const ended = this.#testManager?.getCurrentTest() ?? null - tmEndScenario(this.#getInternals(), state) + tmEndScenario(this.#getInternals(), state, error) await settlePageResources(this.#getInternals()) await captureFinalFrame(this.#getInternals()) const flushed = flushCurrentTestTrace(this.#getInternals()) @@ -740,7 +740,8 @@ const runnerHookCallbacks: RunnerHookCallbacks = { buildStartTestMeta(file, callSource, suiteName, suiteCallSource, attempt) ), // Return the promise so the runner hook awaits the full attach chain. - onTestEnd: (state) => plugin.endTest(state === 'pending' ? 'skipped' : state), + onTestEnd: (state, error) => + plugin.endTest(state === 'pending' ? 'skipped' : state, error), onScenarioStart: (name, file, callSource, featureName, featureCallSource) => { plugin.startScenario(name, { file, @@ -749,8 +750,8 @@ const runnerHookCallbacks: RunnerHookCallbacks = { featureCallSource }) }, - onScenarioEnd: (state) => - plugin.endScenario(state === 'pending' ? 'skipped' : state), + onScenarioEnd: (state, error) => + plugin.endScenario(state === 'pending' ? 'skipped' : state, error), onTestRunComplete: () => { void plugin.finalizeTestRun() } diff --git a/packages/selenium-devtools/src/runnerHooks/cucumber.ts b/packages/selenium-devtools/src/runnerHooks/cucumber.ts index b6a33800b..bc09733a2 100644 --- a/packages/selenium-devtools/src/runnerHooks/cucumber.ts +++ b/packages/selenium-devtools/src/runnerHooks/cucumber.ts @@ -179,7 +179,7 @@ interface GherkinFeature { interface CucumberTestCase { gherkinDocument?: { feature?: GherkinFeature } pickle?: CucumberPickle - result?: { status?: string } + result?: { status?: string; message?: string } } interface CucumberStepArg { pickleStep?: CucumberPickleStep @@ -305,7 +305,7 @@ async function handleScenarioEnd( } else { counters.pending++ } - await callbacks.onScenarioEnd?.(scenarioState) + await callbacks.onScenarioEnd?.(scenarioState, testCase?.result?.message) } function registerScenarioHooks( diff --git a/packages/selenium-devtools/src/runnerHooks/mocha.ts b/packages/selenium-devtools/src/runnerHooks/mocha.ts index 974711acd..aa01da812 100644 --- a/packages/selenium-devtools/src/runnerHooks/mocha.ts +++ b/packages/selenium-devtools/src/runnerHooks/mocha.ts @@ -100,6 +100,14 @@ function resolveMochaState( if (test?.state === 'pending') { return 'pending' } + // Mocha leaves state unset on an attempt it is about to retry. + if ( + test && + test.state === undefined && + (test._retries ?? -1) > (test._currentRetry ?? 0) + ) { + return 'failed' + } return 'passed' } @@ -123,7 +131,7 @@ function makeMochaAfterEach( } else { counters.pending++ } - await callbacks.onTestEnd(state) + await callbacks.onTestEnd(state, test?.err?.message) } } diff --git a/packages/selenium-devtools/src/session-lifecycle.ts b/packages/selenium-devtools/src/session-lifecycle.ts index 95e6a57e3..3fa9f2619 100644 --- a/packages/selenium-devtools/src/session-lifecycle.ts +++ b/packages/selenium-devtools/src/session-lifecycle.ts @@ -530,20 +530,21 @@ function recordSpecBoundary(ctx: SessionLifecycleCtx, specFile: string): void { /** * Record a per-test boundary keyed by the currently-active marked test's uid. * The first test's startTest fires before the driver exists (no capturer yet), - * so flushPendingTestActions re-invokes this once capture is live; the - * same-uid guard keeps that replay from minting a spurious retry slice. + * so flushPendingTestActions re-invokes this once capture is live; a replay + * finds its attempt already recorded and is skipped, while a retry is a new slice. */ function recordTestBoundary( ctx: SessionLifecycleCtx, specFile: string | undefined ): void { - const testUid = ctx.testManager?.getCurrentTest()?.uid + const test = ctx.testManager?.getCurrentTest() + const testUid = test?.uid const file = specFile ?? ctx.testFilePath if (!ctx.sessionCapturer || !testUid || !file) { return } - const lastRange = ctx.specRanges[ctx.specRanges.length - 1] - if (lastRange?.testUid === testUid) { + const recorded = ctx.specRanges.filter((r) => r.testUid === testUid).length + if (recorded > (test?.retries ?? 0)) { return } coreRecordSliceBoundary( diff --git a/packages/selenium-devtools/src/test-management.ts b/packages/selenium-devtools/src/test-management.ts index b4df38756..b503bcd20 100644 --- a/packages/selenium-devtools/src/test-management.ts +++ b/packages/selenium-devtools/src/test-management.ts @@ -29,7 +29,7 @@ export type PendingTestAction = suiteName?: string suiteCallSource?: string } - | { kind: 'end'; state: TestStats['state'] } + | { kind: 'end'; state: TestStats['state']; error?: string } export interface PendingScenario { name: string @@ -158,13 +158,14 @@ export function startTest( export function endTest( ctx: TestManagementCtx, - state: TestStats['state'] = 'passed' + state: TestStats['state'] = 'passed', + error?: string ): void { if (!ctx.testManager) { - ctx.pendingTestActions.push({ kind: 'end', state }) + ctx.pendingTestActions.push({ kind: 'end', state, error }) return } - ctx.testManager.endCurrent(state) + ctx.testManager.endCurrent(state, error) } /** Cucumber scenario boundary — opens a sub-suite under the feature root. */ @@ -211,12 +212,13 @@ export function startScenario( export function endScenario( ctx: TestManagementCtx, - state: TestStats['state'] = 'passed' + state: TestStats['state'] = 'passed', + error?: string ): void { if (!ctx.suiteManager) { return } - ctx.testManager?.endCurrent(state) + ctx.testManager?.endCurrent(state, error) ctx.suiteManager.endScenarioSuite(state) ctx.retryTracker.reset() } @@ -297,7 +299,7 @@ export function flushPendingTestActions(ctx: TestManagementCtx): void { ctx.sessionCapturer?.captureSource(action.meta.file).catch(() => {}) } } else { - ctx.testManager?.endCurrent(action.state) + ctx.testManager?.endCurrent(action.state, action.error) } } ctx.pendingTestActions = [] diff --git a/packages/selenium-devtools/src/types.ts b/packages/selenium-devtools/src/types.ts index 3192033e0..7d68101f8 100644 --- a/packages/selenium-devtools/src/types.ts +++ b/packages/selenium-devtools/src/types.ts @@ -196,6 +196,9 @@ export interface MochaTestCtx { parent?: { title?: string } /** Mocha's authoritative retry index — 0 on the first run, +1 per retry. */ _currentRetry?: number + /** Configured retry count — -1 when unset. */ + _retries?: number + err?: { message?: string } } /** The four root hooks, in the shape of a mocha root hook plugin's `mochaHooks`. */ @@ -219,7 +222,10 @@ export interface RunnerHookCallbacks { ) => void // Async so the runner's afterEach/After awaits the full per-test artifact // emit (trace slice + screenshot + video attach) before Allure closes the test. - onTestEnd: (state: Exclude) => void | Promise + onTestEnd: ( + state: Exclude, + error?: string + ) => void | Promise // Cucumber-only: scenario boundary creates a sub-suite under the feature // rootSuite; subsequent onTestStart/onTestEnd attach as Gherkin steps inside. onScenarioStart?: ( @@ -230,7 +236,8 @@ export interface RunnerHookCallbacks { featureCallSource?: string ) => void onScenarioEnd?: ( - state: Exclude + state: Exclude, + error?: string ) => void | Promise // Fires from the runner's after-all hook so the dashboard suite header // updates without waiting for process exit. diff --git a/packages/selenium-devtools/tests/attempt-capture.test.ts b/packages/selenium-devtools/tests/attempt-capture.test.ts index 8f4484bd1..ecc70657b 100644 --- a/packages/selenium-devtools/tests/attempt-capture.test.ts +++ b/packages/selenium-devtools/tests/attempt-capture.test.ts @@ -1,5 +1,6 @@ import { describe, it, expect, vi } from 'vitest' import { + buildArtifactsManifest, collectSuiteTestMetadata, shouldRetainTrace } from '@wdio/devtools-core' @@ -165,10 +166,10 @@ describe('retry outcome ledger feeds retry-aware retention', () => { const retry = mgr.startMarkedTest('flaky') mgr.endCurrent('passed') - // Selenium gives each attempt its own suite-node uid… - expect(first.uid).not.toBe(retry.uid) + // Each attempt is the same suite-node tests[] entry… + expect(first.uid).toBe(retry.uid) - // …but the ledger records both attempts under ONE retry-stable uid. + // …and the ledger records both attempts under that one uid. const ledger = mgr.attemptOutcomes.all() expect(ledger).toHaveLength(2) expect(ledger[0]).toMatchObject({ attempt: 0, state: 'failed' }) @@ -231,3 +232,72 @@ describe('retry outcome ledger feeds retry-aware retention', () => { } }) }) + +describe('one tests[] entry per test across retries', () => { + it('a Mocha retry keeps one tests[] entry whose last attempt is final', () => { + const { mgr, rootSuite } = makeManager() + + mgr.startMarkedTest('login', { attempt: 0 }) + mgr.endCurrent('failed') + mgr.startMarkedTest('login', { attempt: 1 }) + mgr.endCurrent('passed') + + const manifest = buildArtifactsManifest({ + sessionId: 'sess-1', + format: 'zip', + artifacts: [], + testMetadata: collectSuiteTestMetadata([rootSuite]), + attemptsFor: (uid) => mgr.attemptOutcomes.attemptsFor(uid) + }) + + expect(manifest.tests).toHaveLength(1) + expect(manifest.tests[0]).toMatchObject({ attempt: 1 }) + expect(manifest.tests[0].attempts).toHaveLength(2) + expect(manifest.tests[0].attempts?.[0].final).toBeFalsy() + expect(manifest.tests[0].attempts?.[1].final).toBe(true) + }) + + it('a repeated step text is not a retry', () => { + const { mgr, suiteManager, rootSuite } = makeManager() + suiteManager.startScenarioSuite('scenario', '/spec.feature') + + const first = mgr.startMarkedTest('I open the page') + mgr.endCurrent('passed') + const second = mgr.startMarkedTest('I open the page') + mgr.endCurrent('passed') + + expect(second.uid).not.toBe(first.uid) + expect(second.retries).toBe(0) + expect(mgr.attemptOutcomes.forTest(second.uid)).toHaveLength(1) + expect(rootSuite.suites).toHaveLength(1) + }) +}) + +describe('failure message reaches the manifest', () => { + it('a failed test carries its error, timing and failed attempt error', () => { + const { mgr, rootSuite } = makeManager() + + mgr.startMarkedTest('boom') + mgr.endCurrent('failed', 'expected 1 to equal 2') + + const manifest = buildArtifactsManifest({ + sessionId: 'sess-1', + format: 'zip', + artifacts: [], + testMetadata: collectSuiteTestMetadata([rootSuite]), + attemptsFor: (uid) => mgr.attemptOutcomes.attemptsFor(uid) + }) + + expect(manifest.tests[0]).toMatchObject({ + state: 'failed', + error: 'expected 1 to equal 2' + }) + expect(manifest.tests[0].startTime).toEqual(expect.any(Number)) + expect(manifest.tests[0].endTime).toEqual(expect.any(Number)) + expect(manifest.tests[0].durationMs).toEqual(expect.any(Number)) + expect(manifest.tests[0].attempts?.[0]).toMatchObject({ + state: 'failed', + error: 'expected 1 to equal 2' + }) + }) +}) diff --git a/packages/selenium-devtools/tests/mocha-root-hooks.test.ts b/packages/selenium-devtools/tests/mocha-root-hooks.test.ts index 118f2012a..41e5aa3d8 100644 --- a/packages/selenium-devtools/tests/mocha-root-hooks.test.ts +++ b/packages/selenium-devtools/tests/mocha-root-hooks.test.ts @@ -90,3 +90,52 @@ describe('mocha root hooks', () => { expect(g.afterEach).toHaveBeenCalledTimes(1) }) }) + +describe('mocha attempt state', () => { + async function mochaAfterEach(test: Record) { + const { claimMochaRootHooks } = await import('../src/runnerHooks.js') + const cb = callbacks() + const hooks = claimMochaRootHooks(cb) + await hooks.afterEach.call({ currentTest: test }) + return cb + } + + it('reports an attempt mocha will retry as failed', async () => { + const cb = await mochaAfterEach({ + title: 'flaky', + state: undefined, + _retries: 2, + _currentRetry: 0 + }) + expect(cb.onTestEnd.mock.calls[0][0]).toBe('failed') + }) + + it('does not force the final allowed attempt to failed', async () => { + const cb = await mochaAfterEach({ + title: 'flaky', + state: undefined, + _retries: 2, + _currentRetry: 2 + }) + expect(cb.onTestEnd.mock.calls[0][0]).toBe('passed') + }) + + it('keeps a first-attempt pass passed when retries are configured', async () => { + const cb = await mochaAfterEach({ + title: 'stable', + state: 'passed', + _retries: 2, + _currentRetry: 0 + }) + expect(cb.onTestEnd.mock.calls[0][0]).toBe('passed') + }) + + it('passes the failure message to onTestEnd', async () => { + const cb = await mochaAfterEach({ + title: 'boom', + state: 'failed', + err: { message: 'expected 1 to equal 2' } + }) + expect(cb.onTestEnd).toHaveBeenCalledWith('failed', 'expected 1 to equal 2') + }) +}) diff --git a/packages/selenium-devtools/tests/trace-granularity.test.ts b/packages/selenium-devtools/tests/trace-granularity.test.ts index 8f133a242..95212412f 100644 --- a/packages/selenium-devtools/tests/trace-granularity.test.ts +++ b/packages/selenium-devtools/tests/trace-granularity.test.ts @@ -104,7 +104,7 @@ describe('trace granularity: test', () => { expect(ctx.specRanges).toHaveLength(1) }) - it('a retry gets its own distinct slice (selenium gives each attempt a uid)', () => { + it('a retry gets its own distinct slice keyed by its attempt', () => { const spec = makeTmpSpec() const { ctx, testManager } = makeCtx('test', spec) @@ -116,9 +116,12 @@ describe('trace granularity: test', () => { recordTraceBoundary(ctx, spec) testManager.endCurrent('passed') - expect(first.uid).not.toBe(retry.uid) + expect(first.uid).toBe(retry.uid) expect(ctx.specRanges).toHaveLength(2) - expect(ctx.specRanges.map((r) => r.key)).toEqual([first.uid, retry.uid]) + expect(ctx.specRanges.map((r) => r.key)).toEqual([ + first.uid, + `${first.uid}-retry1` + ]) }) it('eager-flushes each test to its own artifact at test end', async () => { diff --git a/packages/service/src/index.ts b/packages/service/src/index.ts index a792e36f7..78ec6775f 100644 --- a/packages/service/src/index.ts +++ b/packages/service/src/index.ts @@ -26,7 +26,6 @@ import { AssertionTracker } from './assertion-tracker.js' import { cucumberScenarioUid, isFailedResult, - resolveTestAttempt, stampTestState, testMetadataUid, type TestOutcomeResult @@ -138,6 +137,7 @@ export default class DevToolsHookService implements Services.ServiceInstance { options: this.#options, getBrowser: () => this.#browser, getCapturer: () => this.#sessionCapturer, + getAttemptBase: () => this.#attemptTracker.base, buildExportContext: (browser) => this.#traceContext(browser) }) } @@ -173,9 +173,8 @@ export default class DevToolsHookService implements Services.ServiceInstance { /** Map of testUid → metadata for trace group events and per-spec partitioning. */ #testMetadata: TestMetadataMap = new Map() - /** Per-test attempt counter. specFileRetries spawns a fresh worker (hence a - * fresh instance) per retry, so this only reflects same-process retries - * (Mocha this.retries(n)); cross-worker attempts rely on the WDIO result. */ + /** Per-test attempt ledger. A specFileRetries rerun is a fresh worker, so its + * numbering starts at the attempt its runner reports (see TestReporter). */ #attemptTracker = new TestAttemptTracker() /** Every trace/video artifact seen this run (retained or not), for the @@ -380,7 +379,9 @@ export default class DevToolsHookService implements Services.ServiceInstance { self.#sessionCapturer.sendUpstream('suites', upstreamData), (location: string) => { self.#sessionCapturer.ensureSourceLoaded(location) - } + }, + (attempt: number) => + self.#attemptTracker.startNumberingAt(attempt) ) self.#testReporters.push(this) } @@ -486,23 +487,19 @@ export default class DevToolsHookService implements Services.ServiceInstance { this.#assertionTracker.handleOutcome(result?.error) } - /** Stamp final state + the resolved 0-based attempt onto the test's metadata - * entry, taking the max of the tracker count and WDIO's retry field. */ + /** Stamp final state + the tracker's 0-based attempt onto the test's metadata + * entry, so the entry and the manifest's attempt record name the same attempt. */ #stampOutcome( uid: string, result: TestOutcomeResult | undefined, endTime: number ): void { - const fallback = this.#attemptTracker.attemptFor(uid) ?? 0 - const attempt = resolveTestAttempt(result, fallback) + const attempt = this.#attemptTracker.attemptFor(uid) stampTestState(this.#testMetadata, uid, result, attempt, endTime) // Feed the per-attempt ledger so session/spec retention sees this attempt's // real outcome, not just the final state that overwrites #testMetadata. - this.#attemptTracker.recordOutcome( - uid, - this.#testMetadata.get(uid)?.state, - attempt - ) + const metadata = this.#testMetadata.get(uid) + this.#attemptTracker.recordOutcome(uid, metadata?.state, metadata?.error) } async afterScenario( diff --git a/packages/service/src/reporter.ts b/packages/service/src/reporter.ts index 8a56b3c53..81a9527f6 100644 --- a/packages/service/src/reporter.ts +++ b/packages/service/src/reporter.ts @@ -1,4 +1,5 @@ import WebdriverIOReporter, { + type RunnerStats, type SuiteStats, type TestStats } from '@wdio/reporter' @@ -13,6 +14,7 @@ import { setCurrentSpecFile, mapSuiteToSource } from './utils.js' +import { specFileAttemptOf } from './test-metadata.js' import { readFileSync, existsSync } from 'node:fs' // True when the stats object is a Cucumber scenario. The `type` field on @@ -177,18 +179,27 @@ export class TestReporter extends WebdriverIOReporter { * step uids. Undefined outside a scenario (Mocha/Jasmine). */ #currentScenarioUid?: string + #onSpecFileAttempt: (attempt: number) => void + constructor( options: Reporters.Options, report: (data: Record[]) => void, - loadSource: (location: string) => void = () => {} + loadSource: (location: string) => void = () => {}, + onSpecFileAttempt: (attempt: number) => void = () => {} ) { super(options) this.#report = report this.#loadSource = loadSource + this.#onSpecFileAttempt = onSpecFileAttempt // Reset signature counters for each new reporter instance (new test run) resetSignatureCounters() } + onRunnerStart(runnerStats: RunnerStats): void { + super.onRunnerStart(runnerStats) + this.#onSpecFileAttempt(specFileAttemptOf(runnerStats)) + } + onSuiteStart(suiteStats: SuiteStats): void { super.onSuiteStart(suiteStats) diff --git a/packages/service/src/test-metadata.ts b/packages/service/src/test-metadata.ts index 1d3fdbeb1..f47392792 100644 --- a/packages/service/src/test-metadata.ts +++ b/packages/service/src/test-metadata.ts @@ -5,13 +5,29 @@ import { deterministicUid, errorMessage } from '@wdio/devtools-core' import type { TestMetadataMap, TestStatus } from '@wdio/devtools-shared' /** The subset of a WDIO afterTest/afterScenario hook result this adapter reads: - * pass/skip state, the error, and WDIO's authoritative 0-based retry count. */ + * pass/skip state, the error and the framework duration. */ export interface TestOutcomeResult { error?: unknown passed?: boolean skipped?: boolean duration?: number - retries?: { attempts?: number } +} + +/** The fields of @wdio/reporter's RunnerStats that carry a spec file's attempt. */ +export interface SpecFileAttemptSource { + specFileAttempt?: number + retry?: number + config?: { specFileRetries?: number } +} + +/** 0-based attempt of a spec file run under `specFileRetries`: each rerun is a fresh worker. */ +export function specFileAttemptOf(runner: SpecFileAttemptSource): number { + if (typeof runner.specFileAttempt === 'number') { + return runner.specFileAttempt + } + const specFileRetries = runner.config?.specFileRetries ?? 0 + const retry = runner.retry ?? 0 + return specFileRetries && retry <= specFileRetries ? retry : 0 } /** Stable per-test key. beforeTest and afterTest derive it identically so keys @@ -63,10 +79,7 @@ function inLocatedRun(lines: readonly string[]): boolean[] { return result } -// A stack is a contiguous tail of "at" lines (up to a "Caused by:") holding at least one located frame, so an "at" -// line inside the message, or a run with no location at all, is never mistaken for one. A blank line is skipped at the -// very end, as a serialized stack's trailing newline leaves one, or when the run of "at" lines above it holds a located -// frame; otherwise it ends the stack. +// The stack is the trailing run of "at" lines holding a located frame; a blank line ends it unless the run above holds one. function stackStart(lines: readonly string[]): number { const locatedRun = inLocatedRun(lines) let start = lines.length @@ -152,15 +165,3 @@ export function stampTestState( } } } - -/** Resolve the 0-based attempt for a test. WDIO's mocha framework reports - * `retries.attempts` as 0 even on a retry, so it can't override the in-process - * tracker — take the max so a present-but-zero runner field never clobbers a - * real retry count, while a genuine runner value still wins when it's higher. */ -export function resolveTestAttempt( - result: Pick | undefined, - fallback: number -): number { - const attempts = result?.retries?.attempts - return Math.max(typeof attempts === 'number' ? attempts : 0, fallback) -} diff --git a/packages/service/src/trace-slices.ts b/packages/service/src/trace-slices.ts index 2a7e3b502..25b205340 100644 --- a/packages/service/src/trace-slices.ts +++ b/packages/service/src/trace-slices.ts @@ -21,6 +21,7 @@ export interface TraceSliceContext { options: ServiceOptions getCapturer: () => SessionCapturer getBrowser: () => WebdriverIO.Browser | undefined + getAttemptBase: () => number buildExportContext: (browser: WebdriverIO.Browser) => TraceExportContext } @@ -50,7 +51,8 @@ export class TraceSliceTracker { { specRanges: this.ranges, flushedSpecs: this.flushed, - capturer: this.#ctx.getCapturer() + capturer: this.#ctx.getCapturer(), + attemptBase: this.#ctx.getAttemptBase() }, this.#ctx.options.traceGranularity, specFile, diff --git a/packages/service/tests/reporter.test.ts b/packages/service/tests/reporter.test.ts index 5d5721081..5835d462c 100644 --- a/packages/service/tests/reporter.test.ts +++ b/packages/service/tests/reporter.test.ts @@ -3,7 +3,7 @@ import fs from 'node:fs' import os from 'node:os' import path from 'node:path' import { TestReporter } from '../src/reporter.js' -import type { TestStats, SuiteStats } from '@wdio/reporter' +import type { TestStats, SuiteStats, RunnerStats } from '@wdio/reporter' describe('TestReporter - Rerun & Stable UID', () => { let reporter: TestReporter @@ -403,3 +403,17 @@ describe('TestReporter - Rerun & Stable UID', () => { }) }) }) + +describe('TestReporter - spec file attempt', () => { + it('reports the spec file attempt from runner start', () => { + const onSpecFileAttempt = vi.fn() + const r = new TestReporter( + { logFile: '/tmp/test.log' }, + vi.fn(), + () => {}, + onSpecFileAttempt + ) + r.onRunnerStart({ specFileAttempt: 1 } as RunnerStats) + expect(onSpecFileAttempt).toHaveBeenCalledWith(1) + }) +}) diff --git a/packages/service/tests/trace-metadata.test.ts b/packages/service/tests/trace-metadata.test.ts index dc3e2fbcd..a723624b1 100644 --- a/packages/service/tests/trace-metadata.test.ts +++ b/packages/service/tests/trace-metadata.test.ts @@ -2,10 +2,13 @@ import { describe, it, expect, vi, beforeEach } from 'vitest' import type * as DevtoolsCore from '@wdio/devtools-core' import { deterministicUid } from '@wdio/devtools-core' import { HooksInFlight } from '../src/command-stack.js' +import type { TestReporter } from '../src/reporter.js' +import type { RunnerStats } from '@wdio/reporter' import type { TestMetadataEntry, TestMetadataMap } from '@wdio/devtools-shared' import { cucumberScenarioUid, resultToState, + specFileAttemptOf, stampTestState, testMetadataUid } from '../src/test-metadata.js' @@ -96,6 +99,23 @@ describe('test-metadata helpers', () => { }) }) +describe('specFileAttemptOf', () => { + it('reads the attempt of a first run as 0', () => { + expect(specFileAttemptOf({ specFileAttempt: 0 })).toBe(0) + }) + + it('reads the attempt of a first rerun as 1', () => { + expect(specFileAttemptOf({ specFileAttempt: 1 })).toBe(1) + }) + + it('derives the attempt from retry when specFileAttempt is absent', () => { + expect( + specFileAttemptOf({ retry: 1, config: { specFileRetries: 2 } }) + ).toBe(1) + expect(specFileAttemptOf({})).toBe(0) + }) +}) + describe('stampTestState', () => { it('reassigns the error on every stamp so a passing retry leaves none', () => { const metadata: TestMetadataMap = new Map([ @@ -246,7 +266,7 @@ describe('DevtoolsService - afterTest state stamping', () => { expect(ctx.testMetadata.get(deterministicUid(file, title))?.attempt).toBe(1) }) - it('uses the runner attempts count when it exceeds the tracker', async () => { + it('keeps the metadata attempt on the attempt the manifest records, even when the runner reports more', async () => { const service = new DevToolsHookService({ mode: 'trace', tracePolicy: 'retain-on-failure-and-retries' @@ -265,8 +285,37 @@ describe('DevtoolsService - afterTest state stamping', () => { outcomes: { attemptsFor(uid: string): Array<{ attempt: number }> } } const uid = deterministicUid(file, title) - expect(ctx.testMetadata.get(uid)?.attempt).toBe(3) - expect(ctx.outcomes.attemptsFor(uid).map((r) => r.attempt)).toEqual([3]) + expect(ctx.testMetadata.get(uid)?.attempt).toBe(0) + expect(ctx.outcomes.attemptsFor(uid).map((r) => r.attempt)).toEqual([0]) + }) + + it('numbers a specFileRetries rerun worker from the attempt its runner reports', async () => { + const service = new DevToolsHookService({ + mode: 'trace', + tracePolicy: 'retain-on-failure' + }) + const config = { reporters: [] as unknown[] } + service.beforeSession(config as never, { browserName: 'chrome' } as never) + const DevToolsReporter = config.reporters[0] as new (options: { + logFile: string + }) => TestReporter + new DevToolsReporter({ logFile: '/tmp/rerun.log' }).onRunnerStart({ + specFileAttempt: 1 + } as RunnerStats) + await service.before({} as never, [], mockBrowser) + const title = 'rerun worker' + service.beforeTest({ file, fullTitle: title }) + await service.afterTest({ file, fullTitle: title }, {}, { passed: true }) + await service.after() + const ctx = finalizeTraceExport.mock.calls.at(-1)?.[0] as { + testMetadata: Map + outcomes: { + attemptsFor(uid: string): Array<{ attempt: number; final?: boolean }> + } + } + const uid = deterministicUid(file, title) + expect(ctx.testMetadata.get(uid)?.attempt).toBe(1) + expect(ctx.outcomes.attemptsFor(uid).map((r) => r.attempt)).toEqual([1]) }) it('takes a Cucumber scenario duration from its own start and end', async () => { diff --git a/packages/service/tests/trace-slice-tracker.test.ts b/packages/service/tests/trace-slice-tracker.test.ts index edfbe69d7..f6f0ea03d 100644 --- a/packages/service/tests/trace-slice-tracker.test.ts +++ b/packages/service/tests/trace-slice-tracker.test.ts @@ -37,6 +37,7 @@ function makeTracker( options, getCapturer: () => capturer as never, getBrowser: () => browser, + getAttemptBase: () => 0, buildExportContext: () => exportContext, ...overrides } @@ -67,6 +68,15 @@ describe('TraceSliceTracker.recordBoundary', () => { expect(tracker.ranges.map((r) => r.key)).toEqual(['uid-1', 'uid-1-retry1']) }) + it('keys a rerun worker slice from the attempt its runner reports', () => { + const tracker = makeTracker( + { mode: 'trace', traceGranularity: 'test' }, + { getAttemptBase: () => 1 } + ) + tracker.recordBoundary('a.spec.ts', 'uid-1') + expect(tracker.ranges.map((r) => r.key)).toEqual(['uid-1-retry1']) + }) + it('spec granularity flushes the previous, unflushed slice when the file changes', async () => { const tracker = makeTracker({ mode: 'trace', traceGranularity: 'spec' }) tracker.recordBoundary('a.spec.ts') diff --git a/packages/shared/src/artifacts-manifest.ts b/packages/shared/src/artifacts-manifest.ts index 9b5a5c979..c9e6ca636 100644 --- a/packages/shared/src/artifacts-manifest.ts +++ b/packages/shared/src/artifacts-manifest.ts @@ -10,6 +10,7 @@ export function retryKeyOf(uid: string, attempt: number): string { * trace-mode run — a trace slice, a screencast video, or a per-test screenshot. */ export interface TraceArtifact { kind: 'trace' | 'video' | 'screenshot' + /** Relative to the manifest's directory, `/`-separated. */ path: string scope: 'session' | 'spec' | 'test' /** specFile for spec scope; testUid for test scope, `${testUid}-retry${n}` for retry n. */ @@ -29,6 +30,7 @@ export interface TestAttemptRecord { spanId: string /** Set on the attempt that decided the test's outcome; absent in manifests that predate it. */ final?: boolean + error?: string } /** One test's outcome as recorded at export time. Field types track @@ -56,4 +58,8 @@ export interface ArtifactsManifest { runId?: string /** Trace context inherited from a `TRACEPARENT` set by the CI job that launched the run. */ parent?: ParentTraceContext + cwd?: string + browserName?: string + browserVersion?: string + platformName?: string } From 7104114dbf76cf3ed3bafb4eb032528534624afb Mon Sep 17 00:00:00 2001 From: Vince Graics Date: Wed, 11 Nov 2026 14:27:05 +0100 Subject: [PATCH 03/15] fix: keep one tracing group per attempt of a retried Selenium test A retried Mocha test now reuses its first attempt's uid so the artifacts manifest lists it once. The trace writer keyed a test's group on that uid, so in a zip holding more than one test both attempts merged into a single group and the examples smoke check counted one attempt where two ran. Selenium stamps the attempt on each row of a retried attempt and the group is keyed on the uid plus that attempt. A first attempt, and every adapter that sets no attempt, exports exactly as before. Also fixes the two test files that failed typecheck: a mock read through a plainly typed hook, and a WebdriverIO-shaped result passed as a literal to a parameter that deliberately omits the field the service ignores. Co-Authored-By: Claude Fable 5.2 --- .changeset/selenium-retry-manifest.md | 2 +- .../src/helpers/captureOrReplaceCommand.ts | 13 +++++-- .../tests/captureOrReplaceCommand.test.ts | 34 +++++++++++++++++++ .../tests/mocha-root-hooks.test.ts | 6 ++-- packages/service/tests/trace-metadata.test.ts | 14 +++----- packages/shared/src/types.ts | 2 ++ packages/shared/wire-schema.json | 3 ++ packages/trace/src/trace-hierarchy.ts | 3 +- packages/trace/tests/trace-exporter.test.ts | 29 ++++++++++++++++ packages/trace/tests/trace-hierarchy.test.ts | 12 +++++++ 10 files changed, 100 insertions(+), 18 deletions(-) diff --git a/.changeset/selenium-retry-manifest.md b/.changeset/selenium-retry-manifest.md index 12fee8c59..9b52d55e1 100644 --- a/.changeset/selenium-retry-manifest.md +++ b/.changeset/selenium-retry-manifest.md @@ -2,4 +2,4 @@ '@wdio/selenium-devtools': patch --- -A retried Mocha test is listed once in the artifacts manifest, with its last attempt marked final. An attempt Mocha will retry is reported failed rather than passed, and a repeated Cucumber step text is no longer read as a retry. +A retried Mocha test is listed once in the artifacts manifest, with its last attempt marked final. An attempt Mocha will retry is reported failed rather than passed, and a repeated Cucumber step text is no longer read as a retry. Each attempt of a retried test keeps its own group in a trace that holds more than one test. diff --git a/packages/selenium-devtools/src/helpers/captureOrReplaceCommand.ts b/packages/selenium-devtools/src/helpers/captureOrReplaceCommand.ts index 03ffbabb0..b35fe60ff 100644 --- a/packages/selenium-devtools/src/helpers/captureOrReplaceCommand.ts +++ b/packages/selenium-devtools/src/helpers/captureOrReplaceCommand.ts @@ -5,11 +5,18 @@ import type { CapturedCommand, CommandLog, TestStats } from '../types.js' /** Fields the capturer's positional API doesn't carry. An absent `selector` * leaves the previous one standing: `replaceCommand` mutates the row in place, * so a retry must not blank the locator its first attempt resolved. */ -function applyCapturedFields(entry: CommandLog, cmd: CapturedCommand): void { +function applyCapturedFields( + entry: CommandLog, + cmd: CapturedCommand, + attempt: number | undefined +): void { entry.startTime = cmd.startTime if (cmd.selector) { entry.selector = cmd.selector } + if (attempt) { + entry.attempt = attempt + } // Captures run in issue order, so the wait's own row already has its id when a row its condition issued arrives. const parentId = cmd.waitScope?.rowId if (parentId !== undefined) { @@ -89,7 +96,7 @@ async function captureOrReplaceSerially(opts: { cmd.callSource, cmd.timestamp )) as CommandLog & { _id?: number } - applyCapturedFields(entry, cmd) + applyCapturedFields(entry, cmd, test.retries) capturer.sendCommand(entry) if (!ofWait) { retryTracker.recordCapture(cmdSig, entry._id ?? null) @@ -118,7 +125,7 @@ function replaceRow( cmd.timestamp ) const entry = replaced.entry as CommandLog & { _id?: number } - applyCapturedFields(entry, cmd) + applyCapturedFields(entry, cmd, test.retries) capturer.sendReplaceCommand(replaced.oldTimestamp, entry) return entry } diff --git a/packages/selenium-devtools/tests/captureOrReplaceCommand.test.ts b/packages/selenium-devtools/tests/captureOrReplaceCommand.test.ts index 956958518..74ed96438 100644 --- a/packages/selenium-devtools/tests/captureOrReplaceCommand.test.ts +++ b/packages/selenium-devtools/tests/captureOrReplaceCommand.test.ts @@ -85,6 +85,40 @@ describe('captureOrReplaceCommand', () => { } }) + it('stamps the retry attempt on rows captured during a retried attempt only', async () => { + const capturer = new SessionCapturer({}) + const retryTracker = new RetryTracker() + const retried = { uid: 'test-1', retries: 1 } as TestStats + try { + const first = await captureOrReplaceCommand({ + capturer, + retryTracker, + test, + cmd: command({ command: 'click', selector: '#go' }) + }) + const retry = await captureOrReplaceCommand({ + capturer, + retryTracker, + test: retried, + cmd: command({ command: 'getText', timestamp: 2_000, startTime: 1_900 }) + }) + expect(first.attempt).toBeUndefined() + expect(retry.attempt).toBe(1) + expect(capturer.commandsLog[0].attempt).toBeUndefined() + expect(capturer.commandsLog[1].attempt).toBe(1) + const folded = await captureOrReplaceCommand({ + capturer, + retryTracker, + test: retried, + cmd: command({ command: 'getText', timestamp: 2_100, startTime: 2_050 }) + }) + expect(capturer.commandsLog).toHaveLength(2) + expect(folded.attempt).toBe(1) + } finally { + capturer.cleanup() + } + }) + it('folds polls that overlap in flight into one row', async () => { // selenium's `wait()` polls `getCurrentUrl` every 200 ms and the patcher // does not await `onCommand`, so the second poll used to be captured diff --git a/packages/selenium-devtools/tests/mocha-root-hooks.test.ts b/packages/selenium-devtools/tests/mocha-root-hooks.test.ts index 41e5aa3d8..cc588f798 100644 --- a/packages/selenium-devtools/tests/mocha-root-hooks.test.ts +++ b/packages/selenium-devtools/tests/mocha-root-hooks.test.ts @@ -107,7 +107,7 @@ describe('mocha attempt state', () => { _retries: 2, _currentRetry: 0 }) - expect(cb.onTestEnd.mock.calls[0][0]).toBe('failed') + expect(vi.mocked(cb.onTestEnd).mock.calls[0]?.[0]).toBe('failed') }) it('does not force the final allowed attempt to failed', async () => { @@ -117,7 +117,7 @@ describe('mocha attempt state', () => { _retries: 2, _currentRetry: 2 }) - expect(cb.onTestEnd.mock.calls[0][0]).toBe('passed') + expect(vi.mocked(cb.onTestEnd).mock.calls[0]?.[0]).toBe('passed') }) it('keeps a first-attempt pass passed when retries are configured', async () => { @@ -127,7 +127,7 @@ describe('mocha attempt state', () => { _retries: 2, _currentRetry: 0 }) - expect(cb.onTestEnd.mock.calls[0][0]).toBe('passed') + expect(vi.mocked(cb.onTestEnd).mock.calls[0]?.[0]).toBe('passed') }) it('passes the failure message to onTestEnd', async () => { diff --git a/packages/service/tests/trace-metadata.test.ts b/packages/service/tests/trace-metadata.test.ts index a723624b1..b044f2dd0 100644 --- a/packages/service/tests/trace-metadata.test.ts +++ b/packages/service/tests/trace-metadata.test.ts @@ -252,13 +252,10 @@ describe('DevtoolsService - afterTest state stamping', () => { // Two starts before a single end simulate a same-process (Mocha) retry. // WDIO's mocha framework reports retries.attempts:0 even on the retry, so // the runner field must NOT clobber the tracker's real count of 1. + const wdioResult = { passed: true, retries: { attempts: 0 } } service.beforeTest({ file, fullTitle: title }) service.beforeTest({ file, fullTitle: title }) - await service.afterTest( - { file, fullTitle: title }, - {}, - { passed: true, retries: { attempts: 0 } } - ) + await service.afterTest({ file, fullTitle: title }, {}, wdioResult) await service.after() const ctx = finalizeTraceExport.mock.calls.at(-1)?.[0] as { testMetadata: Map @@ -273,12 +270,9 @@ describe('DevtoolsService - afterTest state stamping', () => { }) await service.before({} as never, [], mockBrowser) const title = 'checkout retries' + const wdioResult = { passed: true, retries: { attempts: 3 } } service.beforeTest({ file, fullTitle: title }) - await service.afterTest( - { file, fullTitle: title }, - {}, - { passed: true, retries: { attempts: 3 } } - ) + await service.afterTest({ file, fullTitle: title }, {}, wdioResult) await service.after() const ctx = finalizeTraceExport.mock.calls.at(-1)?.[0] as { testMetadata: Map diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts index d91e3ee30..2167b0175 100644 --- a/packages/shared/src/types.ts +++ b/packages/shared/src/types.ts @@ -203,6 +203,8 @@ export interface CommandLog { callSource?: string screenshot?: string testUid?: string + /** 0-based retry attempt of `testUid` this row ran in; unset for a first attempt. */ + attempt?: number performance?: PerformanceData cookies?: string documentInfo?: DocumentInfo diff --git a/packages/shared/wire-schema.json b/packages/shared/wire-schema.json index af27d18a2..3cff701e0 100644 --- a/packages/shared/wire-schema.json +++ b/packages/shared/wire-schema.json @@ -300,6 +300,9 @@ "testUid": { "type": "string" }, + "attempt": { + "type": "number" + }, "performance": { "$ref": "#/$defs/PerformanceData" }, diff --git a/packages/trace/src/trace-hierarchy.ts b/packages/trace/src/trace-hierarchy.ts index ba102d7ea..ac8c8b07f 100644 --- a/packages/trace/src/trace-hierarchy.ts +++ b/packages/trace/src/trace-hierarchy.ts @@ -3,6 +3,7 @@ // markers. The path is the test's ancestry (feature/scenario/suite, from the // suite-metadata walk) + the test itself + its step, when a stepUid is set. +import { retryKeyOf } from '@wdio/devtools-shared' import type { CommandLog, TestMetadataMap } from '@wdio/devtools-shared' export interface GroupNode { @@ -37,7 +38,7 @@ export function buildGroupPath( }) } path.push({ - uid: cmd.testUid, + uid: retryKeyOf(cmd.testUid, cmd.attempt ?? 0), title: ownTitle(entry?.title ?? cmd.testUid, path[path.length - 1]) }) } diff --git a/packages/trace/tests/trace-exporter.test.ts b/packages/trace/tests/trace-exporter.test.ts index 7eecb6fc9..850e232d3 100644 --- a/packages/trace/tests/trace-exporter.test.ts +++ b/packages/trace/tests/trace-exporter.test.ts @@ -221,6 +221,35 @@ describe('buildActionEvents — tracingGroup (testUid boundaries)', () => { expect(groupAfters).toHaveLength(2) }) + it('keeps one tracingGroup for a test whose commands share a testUid', () => { + const commands = [ + cmd('url', { testUid: 'uid-1', timestamp: 1200, startTime: 1150 }), + cmd('click', { testUid: 'uid-1', timestamp: 1500, startTime: 1450 }) + ] + const groups = buildActionEvents(commands, pageId, wallTime, testMeta) + .filter(isBefore) + .filter(isTracingGroup) + expect(groups).toHaveLength(1) + }) + + it('opens a new tracingGroup for a retried attempt of the same testUid', () => { + const commands = [ + cmd('url', { testUid: 'uid-1', timestamp: 1200, startTime: 1150 }), + cmd('click', { + testUid: 'uid-1', + attempt: 1, + timestamp: 1500, + startTime: 1450 + }) + ] + const groups = buildActionEvents(commands, pageId, wallTime, testMeta) + .filter(isBefore) + .filter(isTracingGroup) + expect(groups).toHaveLength(2) + expect(groups[0]!.params).toEqual({ name: 'test A' }) + expect(groups[1]!.params).toEqual({ name: 'test A' }) + }) + it('uses raw testUid as fallback name when testMetadata is missing', () => { const commands = [cmd('url', { testUid: 'unknown-uid' })] const events = buildActionEvents(commands, pageId, wallTime) diff --git a/packages/trace/tests/trace-hierarchy.test.ts b/packages/trace/tests/trace-hierarchy.test.ts index 2afa6d2f7..b96a55f66 100644 --- a/packages/trace/tests/trace-hierarchy.test.ts +++ b/packages/trace/tests/trace-hierarchy.test.ts @@ -61,6 +61,18 @@ describe('buildGroupPath', () => { ]) }) + it('keys a retried attempt of the test on its own group uid', () => { + const meta: TestMetadataMap = new Map([ + ['t1', { title: 'logs in', specFile: 'a.js' }] + ]) + expect(buildGroupPath(cmd({ testUid: 't1', attempt: 1 }), meta)).toEqual([ + { uid: 't1-retry1', title: 'logs in' } + ]) + expect(buildGroupPath(cmd({ testUid: 't1', attempt: 0 }), meta)).toEqual([ + { uid: 't1', title: 'logs in' } + ]) + }) + // The composition of this with core's per-test metadata filter is asserted in // core's spec-trace-helpers.test.ts — it spans both packages, so it can only // live in the one that sees both. From a046d35c2b442d59caa82a12a3b7972eb692e0c7 Mon Sep 17 00:00:00 2001 From: Vince Graics Date: Fri, 13 Nov 2026 09:15:24 +0100 Subject: [PATCH 04/15] feat(core): version the artifacts manifest and give a test one trace The manifest carries manifestVersion 2, since artifact paths, attempts[] and specFile changed shape and a reader could not tell the formats apart. Without a TRACEPARENT every attempt of a test now joins one trace derived from the run id and the test's uid, so a retried test is not three unrelated traces, while a large run is not one oversized trace. The absolute cwd is gone: specFile is written relative to it instead. A final attempt that matches no recorded attempt is reported, not silently replaced by the last one. Co-Authored-By: Claude Haiku 5.5 --- .../manifest-relative-artifact-paths.md | 2 +- packages/core/src/artifacts-manifest.ts | 105 ++++++++++++----- packages/core/src/attempt-tracker.ts | 2 +- packages/core/src/trace-context.ts | 20 +++- packages/core/src/trace-finalizer.ts | 3 +- .../core/tests/artifacts-manifest.test.ts | 111 +++++++++++++++++- packages/core/tests/attempt-tracker.test.ts | 17 ++- packages/core/tests/trace-context.test.ts | 77 ++++++++++-- packages/core/tests/trace-finalizer.test.ts | 4 +- packages/shared/src/artifacts-manifest.ts | 4 +- 10 files changed, 290 insertions(+), 55 deletions(-) diff --git a/.changeset/manifest-relative-artifact-paths.md b/.changeset/manifest-relative-artifact-paths.md index dbb8c5187..4cb3f5209 100644 --- a/.changeset/manifest-relative-artifact-paths.md +++ b/.changeset/manifest-relative-artifact-paths.md @@ -4,4 +4,4 @@ '@wdio/nightwatch-devtools': minor --- -`artifacts[].path` in the artifacts manifest is now relative to the manifest's directory, so a results folder can be moved or downloaded and still be read. A script that read the absolute path must resolve it against the manifest's directory. +The artifacts manifest format changed incompatibly. Artifact paths are relative to the manifest's directory, `tests[].attempts[]` carries a `final` flag on the attempt that decided the test, `tests[].specFile` is relative to the working directory when it lies under it, and the absolute `cwd` is gone. The manifest now carries `manifestVersion: 2`, so a reader can tell it from the older format. A script that read the absolute artifact path must resolve it against the manifest's directory, and one that read `cwd` must stop doing so. Without a `TRACEPARENT`, every attempt of one test now carries the same trace id, derived from the run id (`DEVTOOLS_RUN_ID`) and the test's uid, where each attempt had its own before; a run id reused across runs therefore puts the same test's attempts from those runs in one trace. diff --git a/packages/core/src/artifacts-manifest.ts b/packages/core/src/artifacts-manifest.ts index 39d4906fd..56741c899 100644 --- a/packages/core/src/artifacts-manifest.ts +++ b/packages/core/src/artifacts-manifest.ts @@ -12,6 +12,7 @@ import fs from 'node:fs/promises' import path from 'node:path' +import { ARTIFACTS_MANIFEST_VERSION } from '@wdio/devtools-shared' import type { ArtifactManifestTest, ArtifactsManifest, @@ -41,14 +42,21 @@ function isStepEntry( ) } -/** Stamps `final` on the attempt the test ended on, else on the last one recorded: the manifest reader rejects a list with no final record. */ +/** Stamps `final` on the attempt the test ended on; the reader rejects a list with none. */ function markFinalAttempt( + uid: string, attempts: TestAttemptRecord[], - finalAttempt: number | undefined + finalAttempt: number | undefined, + warn: ((message: string) => void) | undefined ): TestAttemptRecord[] { - const final = - attempts.find((record) => record.attempt === finalAttempt) ?? - attempts[attempts.length - 1] + const matching = attempts.find((record) => record.attempt === finalAttempt) + if (matching === undefined && finalAttempt !== undefined) { + const recorded = attempts.map((record) => record.attempt).join(', ') + warn?.( + `Test ${uid} ended on attempt ${finalAttempt}, which matches no recorded attempt (${recorded}); marking attempt ${attempts[attempts.length - 1]!.attempt} final.` + ) + } + const final = matching ?? attempts[attempts.length - 1] return attempts.map((record) => record === final ? { ...record, final: true } : record ) @@ -61,6 +69,61 @@ function presentKeys>(values: T): Partial { ) as Partial } +/** A path relative to `base`, `/`-separated, or undefined when none exists (another Windows drive). */ +function portableRelative(base: string, target: string): string | undefined { + const relative = path.relative(base, target) + return path.isAbsolute(relative) + ? undefined + : relative.split(path.sep).join('/') +} + +/** A spec file under `specRoot` is written relative to it, anything else as is. */ +function specFileFor(specFile: string, specRoot: string | undefined): string { + // Metadata from adapters is not validated, so a spec file can still arrive unset. + if ( + specRoot === undefined || + typeof specFile !== 'string' || + !path.isAbsolute(specFile) + ) { + return specFile + } + const relative = portableRelative(specRoot, specFile) + if (relative === undefined || relative.split('/')[0] === '..') { + return specFile + } + return relative +} + +/** One test's manifest entry, with its attempts when any were recorded. */ +function manifestTestOf( + uid: string, + meta: TestMetadataEntry, + input: Pick< + Parameters[0], + 'attemptsFor' | 'specRoot' | 'warn' + > +): ArtifactManifestTest { + const test: ArtifactManifestTest = { + uid, + title: meta.title, + specFile: specFileFor(meta.specFile, input.specRoot), + state: meta.state, + attempt: meta.attempt, + startTime: meta.startTime, + endTime: meta.endTime, + durationMs: meta.durationMs, + error: meta.error + } + const attempts = input.attemptsFor?.(uid) ?? [] + if (attempts.length === 0) { + return test + } + return { + ...test, + attempts: markFinalAttempt(uid, attempts, meta.attempt, input.warn) + } +} + /** Assemble the manifest from the artifacts collected across the run and the * test-metadata map. Pure — the write is separate so it stays unit-testable. */ export function buildArtifactsManifest(input: { @@ -71,34 +134,20 @@ export function buildArtifactsManifest(input: { runId?: string parent?: ArtifactsManifest['parent'] attemptsFor?: (uid: string) => TestAttemptRecord[] - cwd?: string + specRoot?: string + warn?: (message: string) => void browserName?: string browserVersion?: string platformName?: string }): ArtifactsManifest { const tests: ArtifactManifestTest[] = [] for (const [uid, meta] of input.testMetadata) { - if (isStepEntry(uid, meta, input.testMetadata)) { - continue - } - const test: ArtifactManifestTest = { - uid, - title: meta.title, - specFile: meta.specFile, - state: meta.state, - attempt: meta.attempt, - startTime: meta.startTime, - endTime: meta.endTime, - durationMs: meta.durationMs, - error: meta.error - } - const attempts = input.attemptsFor?.(uid) - if (attempts && attempts.length > 0) { - test.attempts = markFinalAttempt(attempts, meta.attempt) + if (!isStepEntry(uid, meta, input.testMetadata)) { + tests.push(manifestTestOf(uid, meta, input)) } - tests.push(test) } return { + manifestVersion: ARTIFACTS_MANIFEST_VERSION, sessionId: input.sessionId, format: input.format, artifacts: [...input.artifacts], @@ -106,7 +155,6 @@ export function buildArtifactsManifest(input: { runId: input.runId, parent: input.parent, ...presentKeys({ - cwd: input.cwd, browserName: input.browserName, browserVersion: input.browserVersion, platformName: input.platformName @@ -123,11 +171,8 @@ function relativizeArtifacts( if (artifact.path === '') { return artifact } - const relative = path.relative(outputDir, artifact.path) - if (path.isAbsolute(relative)) { - return artifact - } - return { ...artifact, path: relative.split(path.sep).join('/') } + const relative = portableRelative(outputDir, artifact.path) + return relative === undefined ? artifact : { ...artifact, path: relative } }) } diff --git a/packages/core/src/attempt-tracker.ts b/packages/core/src/attempt-tracker.ts index 0443a1473..92961a3be 100644 --- a/packages/core/src/attempt-tracker.ts +++ b/packages/core/src/attempt-tracker.ts @@ -66,7 +66,7 @@ export class TestAttemptTracker implements RetryOutcomeView { const slot: AttemptSlot = { outcome: { uid, attempt }, startTime: Date.now(), - trace: mintTraceContext(resolveParentTraceContext()) + trace: mintTraceContext(uid, resolveParentTraceContext()) } if (entry) { entry.attempts.push(slot) diff --git a/packages/core/src/trace-context.ts b/packages/core/src/trace-context.ts index 1aee5a2c8..bdc595c64 100644 --- a/packages/core/src/trace-context.ts +++ b/packages/core/src/trace-context.ts @@ -1,21 +1,33 @@ +import { createHash } from 'node:crypto' import { randomSpanId, - randomTraceId, parseTraceparent, TRACE_CONTEXT_ENV, type ParentTraceContext, type TestTraceContext } from '@wdio/devtools-shared' +import { resolveRunId } from './run-id.js' // Sampling is the parent's to decide, and the manifest records it once on `parent`, so an attempt carries ids alone. export type AttemptIds = Pick let parentCache: { value: ParentTraceContext | undefined } | undefined -/** A new context for one test attempt; a parent contributes the trace it joins. */ -export function mintTraceContext(parent?: TestTraceContext): AttemptIds { +/** The trace one test's attempts share, derived from the run id and the test's uid. */ +export function testTraceId(runId: string, uid: string): string { + return createHash('sha256') + .update(`${runId}\n${uid}`) + .digest('hex') + .slice(0, 32) +} + +/** An attempt joins the parent's trace, else its test's, so a test's retries share a trace. */ +export function mintTraceContext( + uid: string, + parent?: TestTraceContext +): AttemptIds { return { - traceId: parent?.traceId ?? randomTraceId(), + traceId: parent?.traceId ?? testTraceId(resolveRunId(), uid), spanId: randomSpanId() } } diff --git a/packages/core/src/trace-finalizer.ts b/packages/core/src/trace-finalizer.ts index 28564ba05..cc48635b3 100644 --- a/packages/core/src/trace-finalizer.ts +++ b/packages/core/src/trace-finalizer.ts @@ -518,7 +518,8 @@ async function maybeWriteManifest( runId: resolveRunId(), parent: resolveParentTraceContext(), attemptsFor: ctx.outcomes?.attemptsFor.bind(ctx.outcomes), - cwd: process.cwd(), + specRoot: process.cwd(), + warn: (message) => ctx.log?.('warn', message), ...browser }) ) diff --git a/packages/core/tests/artifacts-manifest.test.ts b/packages/core/tests/artifacts-manifest.test.ts index e0402f0c2..738fa35d8 100644 --- a/packages/core/tests/artifacts-manifest.test.ts +++ b/packages/core/tests/artifacts-manifest.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect, afterEach } from 'vitest' +import { describe, it, expect, afterEach, vi } from 'vitest' import { rm, readFile, mkdtemp } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join, relative } from 'node:path' @@ -365,19 +365,17 @@ describe('artifacts manifest', () => { expect(manifest.artifacts[0]!.path).toBe(inside) }) - it('passes cwd and browser identity through, leaving unset keys out', () => { + it('passes browser identity through, leaving unset keys out', () => { const m = buildArtifactsManifest({ sessionId: 'sess-id', format: 'zip', artifacts: [], testMetadata: metadata(), - cwd: '/work', browserName: 'chrome', browserVersion: '150.0', platformName: 'linux' }) expect(m).toMatchObject({ - cwd: '/work', browserName: 'chrome', browserVersion: '150.0', platformName: 'linux' @@ -388,7 +386,110 @@ describe('artifacts manifest', () => { artifacts: [], testMetadata: metadata() }) - expect(bare).not.toHaveProperty('cwd') expect(bare).not.toHaveProperty('browserName') }) + + it('versions the format and never carries an absolute cwd', () => { + const m = buildArtifactsManifest({ + sessionId: 'sess-v', + format: 'zip', + artifacts: [], + testMetadata: metadata() + }) + expect(m.manifestVersion).toBe(2) + expect(Object.keys(m)[0]).toBe('manifestVersion') + expect(m).not.toHaveProperty('cwd') + }) + + it('writes a spec file under specRoot relative to it, and keeps one outside it', () => { + const m = buildArtifactsManifest({ + sessionId: 'sess-s', + format: 'zip', + artifacts: [], + testMetadata: new Map([ + [ + 'inside', + { + title: 'in', + specFile: '/work/proj/tests/a.spec.ts', + state: 'passed', + attempt: 0 + } + ], + [ + 'outside', + { + title: 'out', + specFile: '/elsewhere/b.spec.ts', + state: 'passed', + attempt: 0 + } + ], + [ + 'relative', + { title: 'rel', specFile: 'c.spec.ts', state: 'passed', attempt: 0 } + ] + ]), + specRoot: '/work/proj' + }) + expect(m.tests.map((t) => t.specFile)).toEqual([ + 'tests/a.spec.ts', + '/elsewhere/b.spec.ts', + 'c.spec.ts' + ]) + }) + + it('warns once when the final attempt matches no recorded attempt', () => { + const warn = vi.fn() + const attempt = (n: number) => ({ + attempt: n, + state: 'failed' as const, + startTime: n, + endTime: n + 1, + traceId: '0af7651916cd43dd8448eb211c80319c', + spanId: 'b7ad6b7169203331' + }) + buildArtifactsManifest({ + sessionId: 'sess-w', + format: 'zip', + artifacts: [], + testMetadata: new Map([ + ['u9', { title: 't', specFile: '/a.js', state: 'passed', attempt: 5 }] + ]), + attemptsFor: () => [attempt(0), attempt(1)], + warn + }) + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0]![0]).toContain('u9') + expect(warn.mock.calls[0]![0]).toContain('attempt 5') + expect(warn.mock.calls[0]![0]).toContain('0, 1') + }) + + it('does not warn when the final attempt matches a recorded attempt', () => { + const warn = vi.fn() + buildArtifactsManifest({ + sessionId: 'sess-m', + format: 'zip', + artifacts: [], + testMetadata: new Map([ + ['u9', { title: 't', specFile: '/a.js', state: 'passed', attempt: 1 }] + ]), + attemptsFor: () => [ + { + attempt: 0, + startTime: 0, + traceId: '0af7651916cd43dd8448eb211c80319c', + spanId: 'b7ad6b7169203331' + }, + { + attempt: 1, + startTime: 1, + traceId: '0af7651916cd43dd8448eb211c80319c', + spanId: 'b7ad6b7169203331' + } + ], + warn + }) + expect(warn).not.toHaveBeenCalled() + }) }) diff --git a/packages/core/tests/attempt-tracker.test.ts b/packages/core/tests/attempt-tracker.test.ts index 0bf9798f5..e900785d5 100644 --- a/packages/core/tests/attempt-tracker.test.ts +++ b/packages/core/tests/attempt-tracker.test.ts @@ -203,7 +203,7 @@ describe('TestAttemptTracker', () => { expect(first!.spanId).toMatch(HEX_16) }) - it('gives each attempt its own span, and its own trace when no parent is set', async () => { + it('gives each attempt its own span, and the test trace when no parent is set', async () => { vi.stubEnv('TRACEPARENT', '') vi.resetModules() const { TestAttemptTracker: Tracker } = @@ -213,7 +213,20 @@ describe('TestAttemptTracker', () => { t.recordStart('a') const [first, second] = t.attemptsFor('a') expect(first!.spanId).not.toBe(second!.spanId) - expect(first!.traceId).not.toBe(second!.traceId) + expect(first!.traceId).toBe(second!.traceId) + }) + + it('gives two different tests different traces when no parent is set', async () => { + vi.stubEnv('TRACEPARENT', '') + vi.resetModules() + const { TestAttemptTracker: Tracker } = + await import('../src/attempt-tracker.js') + const t = new Tracker() + t.recordStart('a') + t.recordStart('b') + expect(t.attemptsFor('a')[0]!.traceId).not.toBe( + t.attemptsFor('b')[0]!.traceId + ) }) it('joins the parent trace when TRACEPARENT is set', async () => { diff --git a/packages/core/tests/trace-context.test.ts b/packages/core/tests/trace-context.test.ts index cdce354f2..303007a6e 100644 --- a/packages/core/tests/trace-context.test.ts +++ b/packages/core/tests/trace-context.test.ts @@ -1,29 +1,68 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { RUNNER_ENV } from '@wdio/devtools-shared' const HEX_32 = /^[0-9a-f]{32}$/ const HEX_16 = /^[0-9a-f]{16}$/ const TRACE_ID = '0af7651916cd43dd8448eb211c80319c' const SPAN_ID = 'b7ad6b7169203331' +const RUN_ID = '0AF76519-16CD-43DD-8448-EB211C80319C' +const OTHER_RUN_ID = '5f3e1c2a-9b8d-4e7f-a1b2-c3d4e5f60718' +const UID = 'suite > test' +const OTHER_UID = 'suite > other test' describe('mintTraceContext', () => { it('mints lowercase hex ids of the W3C lengths', async () => { const { mintTraceContext } = await import('../src/trace-context.js') - const ctx = mintTraceContext() + const ctx = mintTraceContext(UID) expect(ctx.traceId).toMatch(HEX_32) expect(ctx.spanId).toMatch(HEX_16) }) - it('gives every mint its own ids', async () => { - const { mintTraceContext } = await import('../src/trace-context.js') - const a = mintTraceContext() - const b = mintTraceContext() - expect(a.traceId).not.toBe(b.traceId) - expect(a.spanId).not.toBe(b.spanId) + describe('with a run id', () => { + beforeEach(() => { + vi.stubEnv(RUNNER_ENV.RUN_ID, RUN_ID) + }) + afterEach(() => { + vi.unstubAllEnvs() + }) + + it('gives every attempt of one test the same trace, with its own span', async () => { + const { mintTraceContext } = await import('../src/trace-context.js') + const a = mintTraceContext(UID) + const b = mintTraceContext(UID) + expect(b.traceId).toBe(a.traceId) + expect(a.spanId).not.toBe(b.spanId) + }) + + it('gives two different tests their own traces', async () => { + const { mintTraceContext } = await import('../src/trace-context.js') + const a = mintTraceContext(UID) + const b = mintTraceContext(OTHER_UID) + expect(b.traceId).not.toBe(a.traceId) + }) + + it('gives a different run its own trace', async () => { + const { mintTraceContext } = await import('../src/trace-context.js') + const first = mintTraceContext(UID) + vi.stubEnv(RUNNER_ENV.RUN_ID, OTHER_RUN_ID) + const second = mintTraceContext(UID) + expect(second.traceId).not.toBe(first.traceId) + }) + + it('still joins a parent trace over the test trace', async () => { + const { mintTraceContext } = await import('../src/trace-context.js') + const ctx = mintTraceContext(UID, { + traceId: TRACE_ID, + spanId: SPAN_ID, + traceFlags: 0 + }) + expect(ctx.traceId).toBe(TRACE_ID) + }) }) it('joins a parent trace with a fresh span', async () => { const { mintTraceContext } = await import('../src/trace-context.js') - const ctx = mintTraceContext({ + const ctx = mintTraceContext(UID, { traceId: TRACE_ID, spanId: SPAN_ID, traceFlags: 0 @@ -34,6 +73,28 @@ describe('mintTraceContext', () => { }) }) +describe('testTraceId', () => { + it('is 32 lower-case hex digits', async () => { + const { testTraceId } = await import('../src/trace-context.js') + expect(testTraceId(RUN_ID, UID)).toMatch(HEX_32) + }) + + it('is stable for the same run id and uid', async () => { + const { testTraceId } = await import('../src/trace-context.js') + expect(testTraceId('run-a', UID)).toBe(testTraceId('run-a', UID)) + }) + + it('differs when the run id differs', async () => { + const { testTraceId } = await import('../src/trace-context.js') + expect(testTraceId('run-a', UID)).not.toBe(testTraceId('run-b', UID)) + }) + + it('differs when the uid differs', async () => { + const { testTraceId } = await import('../src/trace-context.js') + expect(testTraceId('run-a', UID)).not.toBe(testTraceId('run-a', OTHER_UID)) + }) +}) + describe('resolveParentTraceContext', () => { beforeEach(() => { delete process.env.TRACEPARENT diff --git a/packages/core/tests/trace-finalizer.test.ts b/packages/core/tests/trace-finalizer.test.ts index 389da118e..f9527604e 100644 --- a/packages/core/tests/trace-finalizer.test.ts +++ b/packages/core/tests/trace-finalizer.test.ts @@ -395,7 +395,7 @@ describe('finalizeTraceExport', () => { ]) }) - it('records cwd and browser identity', async () => { + it('records browser identity', async () => { await finalizeTraceExport( baseCtx({ emitManifest: true, @@ -408,7 +408,7 @@ describe('finalizeTraceExport', () => { ) const manifest = JSON.parse(await fs.readFile(manifestPath(), 'utf8')) expect(manifest).toMatchObject({ - cwd: process.cwd(), + manifestVersion: 2, browserName: 'chrome', browserVersion: '150.0.1', platformName: 'linux' diff --git a/packages/shared/src/artifacts-manifest.ts b/packages/shared/src/artifacts-manifest.ts index c9e6ca636..8d65de582 100644 --- a/packages/shared/src/artifacts-manifest.ts +++ b/packages/shared/src/artifacts-manifest.ts @@ -50,7 +50,10 @@ export interface ArtifactManifestTest extends Pick< attempts?: TestAttemptRecord[] } +export const ARTIFACTS_MANIFEST_VERSION = 2 + export interface ArtifactsManifest { + manifestVersion: typeof ARTIFACTS_MANIFEST_VERSION sessionId: string format: TraceFormat artifacts: TraceArtifact[] @@ -58,7 +61,6 @@ export interface ArtifactsManifest { runId?: string /** Trace context inherited from a `TRACEPARENT` set by the CI job that launched the run. */ parent?: ParentTraceContext - cwd?: string browserName?: string browserVersion?: string platformName?: string From b70735f6bf34e7e77d4614680c9bd9075d0d5e3c Mon Sep 17 00:00:00 2001 From: Vince Graics Date: Fri, 13 Nov 2026 09:15:54 +0100 Subject: [PATCH 05/15] fix(python): regenerate the wire types for the command row's attempt field The shared wire schema gained CommandLog.attempt, and the Python CI job fails when the generated types are out of date with it. Co-Authored-By: Claude Fable 5.2 --- .../selenium-devtools-py/changes/command-row-attempt-type.md | 5 +++++ .../src/selenium_devtools/_wire_types.py | 1 + 2 files changed, 6 insertions(+) create mode 100644 packages/selenium-devtools-py/changes/command-row-attempt-type.md diff --git a/packages/selenium-devtools-py/changes/command-row-attempt-type.md b/packages/selenium-devtools-py/changes/command-row-attempt-type.md new file mode 100644 index 000000000..9235b7dd4 --- /dev/null +++ b/packages/selenium-devtools-py/changes/command-row-attempt-type.md @@ -0,0 +1,5 @@ +--- +patch +--- + +The generated wire types include the optional `attempt` field the shared contract now carries on a command row, naming the attempt of a retried test the row belongs to. The Python adapter does not set it. diff --git a/packages/selenium-devtools-py/src/selenium_devtools/_wire_types.py b/packages/selenium-devtools-py/src/selenium_devtools/_wire_types.py index a5c80a1d6..471a0bbd2 100644 --- a/packages/selenium-devtools-py/src/selenium_devtools/_wire_types.py +++ b/packages/selenium-devtools-py/src/selenium_devtools/_wire_types.py @@ -71,6 +71,7 @@ class CommandLog(_CommandLogRequired, total=False): callSource: str screenshot: str testUid: str + attempt: float performance: PerformanceData cookies: str documentInfo: DocumentInfo From 761c59c2ab96beb97d08e9a44b500e1d9ef97066 Mon Sep 17 00:00:00 2001 From: Vince Graics Date: Fri, 13 Nov 2026 21:11:29 +0100 Subject: [PATCH 06/15] fix(core): keep each attempt's per-test screenshot A retried test's attempts share one uid, and the screenshot was named from the uid and the session alone, so a retry overwrote the earlier attempt's file and the manifest listed one path twice. The file and its artifact key now carry the attempt, the same way the per-test trace slice does. Co-Authored-By: Claude Haiku 5.5 --- .changeset/per-attempt-screenshot.md | 7 +++++ packages/core/src/allure-artifacts.ts | 3 ++ packages/core/src/screenshot-artifact.ts | 9 ++++-- packages/core/tests/allure-artifacts.test.ts | 9 ++++++ .../core/tests/screenshot-artifact.test.ts | 29 ++++++++++++++++++- .../nightwatch-devtools/src/test-artifacts.ts | 1 + .../tests/testArtifacts.test.ts | 3 +- .../selenium-devtools/src/test-artifacts.ts | 1 + packages/service/src/index.ts | 9 +++--- 9 files changed, 62 insertions(+), 9 deletions(-) create mode 100644 .changeset/per-attempt-screenshot.md diff --git a/.changeset/per-attempt-screenshot.md b/.changeset/per-attempt-screenshot.md new file mode 100644 index 000000000..bbabc5998 --- /dev/null +++ b/.changeset/per-attempt-screenshot.md @@ -0,0 +1,7 @@ +--- +'@wdio/devtools-service': patch +'@wdio/selenium-devtools': patch +'@wdio/nightwatch-devtools': patch +--- + +A retried test's per-test screenshot is kept per attempt. Each attempt's file and manifest entry carry the attempt, so a retry no longer overwrites the earlier attempt's screenshot. diff --git a/packages/core/src/allure-artifacts.ts b/packages/core/src/allure-artifacts.ts index 54a8c9a71..ee8fddf0c 100644 --- a/packages/core/src/allure-artifacts.ts +++ b/packages/core/src/allure-artifacts.ts @@ -130,6 +130,8 @@ export async function captureAndAttachScreenshot(input: { sessionId: string | undefined outputDir: string testUid: string | undefined + /** 0-based attempt of `testUid`; undefined reads as the first attempt. */ + attempt: number | undefined attach: AllureAttachSink | undefined onArtifact: (artifact: TraceArtifact) => void onLog?: LogFn @@ -149,6 +151,7 @@ export async function captureAndAttachScreenshot(input: { const artifact = await writeScreenshotArtifact({ outputDir: input.outputDir, testUid: input.testUid, + attempt: input.attempt ?? 0, sessionId, base64: screenshotBase64 }) diff --git a/packages/core/src/screenshot-artifact.ts b/packages/core/src/screenshot-artifact.ts index e7bbfd3c9..f8f85242a 100644 --- a/packages/core/src/screenshot-artifact.ts +++ b/packages/core/src/screenshot-artifact.ts @@ -9,7 +9,7 @@ import fs from 'node:fs/promises' import path from 'node:path' -import type { TraceScreenshotPolicy } from '@wdio/devtools-shared' +import { retryKeyOf, type TraceScreenshotPolicy } from '@wdio/devtools-shared' import { fileSlug } from './artifact-naming.js' import type { TraceArtifact } from '@wdio/devtools-shared' @@ -35,18 +35,21 @@ export function shouldCaptureScreenshot( export async function writeScreenshotArtifact(input: { outputDir: string testUid: string + /** 0-based; a retried test's attempts share one uid, so the key carries it. */ + attempt: number sessionId: string base64: string }): Promise { await fs.mkdir(input.outputDir, { recursive: true }) - const filename = `screenshot-${fileSlug(input.testUid)}-${input.sessionId.slice(0, 8)}.png` + const key = retryKeyOf(input.testUid, input.attempt) + const filename = `screenshot-${fileSlug(key)}-${input.sessionId.slice(0, 8)}.png` const filePath = path.join(input.outputDir, filename) await fs.writeFile(filePath, Buffer.from(input.base64, 'base64')) return { kind: 'screenshot', path: filePath, scope: 'test', - key: input.testUid, + key, testUids: [input.testUid], retained: true } diff --git a/packages/core/tests/allure-artifacts.test.ts b/packages/core/tests/allure-artifacts.test.ts index 39bffc9f7..85e65a07e 100644 --- a/packages/core/tests/allure-artifacts.test.ts +++ b/packages/core/tests/allure-artifacts.test.ts @@ -148,6 +148,7 @@ describe('captureAndAttachScreenshot', () => { sessionId: 'sess1234', outputDir: dir, testUid: 'u1', + attempt: 0, attach: sink as unknown as AllureAttachSink, onArtifact: (a) => collected.push(a), ...over @@ -163,6 +164,14 @@ describe('captureAndAttachScreenshot', () => { expect(await readdir(dir)).toHaveLength(1) }) + it('gives each attempt of a retried test its own file and manifest entry', async () => { + const dir = await run({ failed: true, attempt: 0 }) + await run({ failed: true, attempt: 1, outputDir: dir }) + expect(collected.map((a) => a.key)).toEqual(['u1', 'u1-retry1']) + expect(new Set(collected.map((a) => a.path)).size).toBe(2) + expect(await readdir(dir)).toHaveLength(2) + }) + it('produces without attaching when the sink is absent', async () => { await run({ attach: undefined }) expect(collected).toHaveLength(1) diff --git a/packages/core/tests/screenshot-artifact.test.ts b/packages/core/tests/screenshot-artifact.test.ts index a24a1efe4..21624a051 100644 --- a/packages/core/tests/screenshot-artifact.test.ts +++ b/packages/core/tests/screenshot-artifact.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, afterEach } from 'vitest' -import { mkdtemp, readFile, rm } from 'node:fs/promises' +import { mkdtemp, readdir, readFile, rm } from 'node:fs/promises' import { tmpdir } from 'node:os' import { join } from 'node:path' import { @@ -39,15 +39,42 @@ describe('writeScreenshotArtifact', () => { const artifact = await writeScreenshotArtifact({ outputDir: dir, testUid: 'suite > a test/name', + attempt: 0, sessionId: 'abcd1234ef', base64 }) expect(artifact.kind).toBe('screenshot') expect(artifact.scope).toBe('test') expect(artifact.key).toBe('suite > a test/name') + expect(artifact.testUids).toEqual(['suite > a test/name']) expect(artifact.retained).toBe(true) // Filename is slugged (no spaces/slashes) and session-scoped. expect(artifact.path).toMatch(/screenshot-suite-a-test-name-abcd1234\.png$/) expect(await readFile(artifact.path, 'utf8')).toBe('png-bytes') }) + + it('keys and names a retry attempt distinctly from attempt 0', async () => { + const dir = await mkdtemp(join(tmpdir(), 'shot-')) + dirs.push(dir) + const base64 = Buffer.from('png-bytes').toString('base64') + const first = await writeScreenshotArtifact({ + outputDir: dir, + testUid: 'u1', + attempt: 0, + sessionId: 'abcd1234ef', + base64 + }) + const retry = await writeScreenshotArtifact({ + outputDir: dir, + testUid: 'u1', + attempt: 1, + sessionId: 'abcd1234ef', + base64 + }) + expect(retry.key).toBe('u1-retry1') + expect(retry.testUids).toEqual(['u1']) + expect(retry.path).toMatch(/screenshot-u1-retry1-abcd1234\.png$/) + expect(retry.path).not.toBe(first.path) + expect(await readdir(dir)).toHaveLength(2) + }) }) diff --git a/packages/nightwatch-devtools/src/test-artifacts.ts b/packages/nightwatch-devtools/src/test-artifacts.ts index b81af5e85..6e9b9c126 100644 --- a/packages/nightwatch-devtools/src/test-artifacts.ts +++ b/packages/nightwatch-devtools/src/test-artifacts.ts @@ -69,6 +69,7 @@ export async function emitTestArtifacts( sessionId: input.sessionId, outputDir: input.outputDir, testUid: input.uid, + attempt: input.attempt, attach: undefined, onArtifact: input.onArtifact, onLog: input.onLog diff --git a/packages/nightwatch-devtools/tests/testArtifacts.test.ts b/packages/nightwatch-devtools/tests/testArtifacts.test.ts index 327033925..6010d7dc1 100644 --- a/packages/nightwatch-devtools/tests/testArtifacts.test.ts +++ b/packages/nightwatch-devtools/tests/testArtifacts.test.ts @@ -118,7 +118,8 @@ describe('emitTestArtifacts — produce-only per-test artifacts', () => { screenshotBase64: 'SCREENSHOT_B64', sessionId: 'session-abcdef', outputDir: '/out', - testUid: 'uid-1' + testUid: 'uid-1', + attempt: 1 }) ) expect(captureAndAttachVideo).toHaveBeenCalledWith( diff --git a/packages/selenium-devtools/src/test-artifacts.ts b/packages/selenium-devtools/src/test-artifacts.ts index e4be621c6..471fe4858 100644 --- a/packages/selenium-devtools/src/test-artifacts.ts +++ b/packages/selenium-devtools/src/test-artifacts.ts @@ -93,6 +93,7 @@ export class SeleniumTestArtifacts { sessionId: input.sessionId, outputDir, testUid, + attempt: input.endedTest?.retries, attach, onArtifact, onLog diff --git a/packages/service/src/index.ts b/packages/service/src/index.ts index 78ec6775f..4838d2acc 100644 --- a/packages/service/src/index.ts +++ b/packages/service/src/index.ts @@ -562,6 +562,10 @@ export default class DevToolsHookService implements Services.ServiceInstance { await attachTraceArtifact(artifact, attach, onLog) } } + // Authoritative attempt for this test (stamped into metadata by + // #stampOutcome, which ran just before this). Scopes retention + the video + // filename to this attempt so retries don't overwrite each other. + const attempt = uid ? this.#testMetadata.get(uid)?.attempt : undefined await captureAndAttachScreenshot({ mode: this.#options.mode, granularity: this.#options.traceGranularity, @@ -574,13 +578,10 @@ export default class DevToolsHookService implements Services.ServiceInstance { sessionId: this.#browser?.sessionId, outputDir: this.#outputDir, testUid: uid, + attempt, attach, onArtifact: (a) => this.#artifacts.push(a) }) - // Authoritative attempt for this test (stamped into metadata by - // #stampOutcome, which ran just before this). Scopes retention + the video - // filename to this attempt so retries don't overwrite each other. - const attempt = uid ? this.#testMetadata.get(uid)?.attempt : undefined await this.#screencast.attachTestVideo({ testUid: uid, attempt, From 3b016071c39172933fb353bc08450e3ddc696a01 Mon Sep 17 00:00:00 2001 From: Vince Graics Date: Fri, 13 Nov 2026 23:01:44 +0100 Subject: [PATCH 07/15] fix(selenium): list a Cucumber scenario, not its steps, in the artifacts manifest The Selenium root suite keeps the working directory as its file, so the scenario under it was read as the feature and no scenario was ever recorded: the manifest listed each step as a test. A suite whose feature file is a .feature now counts as the feature, and the scenario feeds the attempt ledger, so it gets its own attempts and trace ids. Co-Authored-By: Claude Haiku 5.5 --- .../selenium-cucumber-scenario-manifest.md | 5 ++ packages/core/src/suite-helpers.ts | 5 +- .../core/tests/artifacts-manifest.test.ts | 39 ++++++++++++ packages/core/tests/suite-helpers.test.ts | 38 +++++++++++ .../src/helpers/testManager.ts | 13 ++++ .../selenium-devtools/src/test-management.ts | 23 ++++++- .../tests/attempt-capture.test.ts | 63 +++++++++++++++++++ 7 files changed, 183 insertions(+), 3 deletions(-) create mode 100644 .changeset/selenium-cucumber-scenario-manifest.md diff --git a/.changeset/selenium-cucumber-scenario-manifest.md b/.changeset/selenium-cucumber-scenario-manifest.md new file mode 100644 index 000000000..e35a43a7b --- /dev/null +++ b/.changeset/selenium-cucumber-scenario-manifest.md @@ -0,0 +1,5 @@ +--- +'@wdio/selenium-devtools': patch +--- + +The artifacts manifest lists a Selenium Cucumber scenario as the test, not each of its Gherkin steps. A scenario gets its own attempt record and trace ids. Per-test trace zips, screenshots and videos are still written per step, so their `testUids` name step uids that the manifest no longer lists. diff --git a/packages/core/src/suite-helpers.ts b/packages/core/src/suite-helpers.ts index 1fa3821c4..795502660 100644 --- a/packages/core/src/suite-helpers.ts +++ b/packages/core/src/suite-helpers.ts @@ -180,7 +180,10 @@ function deriveAncestorKind( } // Cucumber scenario suites carry the same .feature file as their parent — // only a suite not already under a feature/scenario counts as the feature. - if (suite.file?.endsWith('.feature') && parentKind !== 'scenario') { + // Selenium's root keeps `file` at cwd and names the .feature as `featureFile`. + const isFeatureFile = + suite.file?.endsWith('.feature') || suite.featureFile?.endsWith('.feature') + if (isFeatureFile && parentKind !== 'scenario') { return 'feature' } return 'suite' diff --git a/packages/core/tests/artifacts-manifest.test.ts b/packages/core/tests/artifacts-manifest.test.ts index 738fa35d8..b0f16bcaa 100644 --- a/packages/core/tests/artifacts-manifest.test.ts +++ b/packages/core/tests/artifacts-manifest.test.ts @@ -13,6 +13,11 @@ import type { TraceArtifact } from '@wdio/devtools-shared' import { stepMetadataUid } from '../src/uid.js' +import { + collectSuiteTestMetadata, + createSuiteStats, + createTestStats +} from '../src/suite-helpers.js' function metadata(): TestMetadataMap { return new Map([ @@ -214,6 +219,40 @@ describe('artifacts manifest', () => { expect(m.tests.map((t) => t.uid)).toEqual(['stable-abc']) }) + it('lists a Selenium Cucumber scenario in tests[] and none of its steps', () => { + const root = createSuiteStats({ + uid: 'root', + title: 'Cart', + file: '/work', + featureFile: '/work/cart.feature' + }) + const scenario = createSuiteStats({ + uid: 'sc', + title: 'checkout', + file: '/work/cart.feature', + featureFile: '/work/cart.feature', + parent: 'root' + }) + scenario.state = 'passed' + scenario.tests = ['Given a cart', 'When I pay'].map((title, i) => + createTestStats({ + uid: `step-${i}`, + title, + file: '/work/cart.feature', + parent: 'sc' + }) + ) + root.suites = [scenario] + + const m = buildArtifactsManifest({ + sessionId: 's', + format: 'zip', + artifacts: [], + testMetadata: collectSuiteTestMetadata([root]) + }) + expect(m.tests.map((t) => t.uid)).toEqual(['sc']) + }) + it('keeps a step-looking uid whose owner is not in the map', () => { const testMetadata: TestMetadataMap = new Map([ ['orphan:step:1', { title: 'stray', specFile: '/a.feature' }] diff --git a/packages/core/tests/suite-helpers.test.ts b/packages/core/tests/suite-helpers.test.ts index c27f8687f..c9acea7d2 100644 --- a/packages/core/tests/suite-helpers.test.ts +++ b/packages/core/tests/suite-helpers.test.ts @@ -236,6 +236,44 @@ describe('collectSuiteTestMetadata', () => { expect(map.get('t2')?.specFile).toBe('/spec/t2.ts') }) + it('reads a suite as a feature when its featureFile is a .feature, and its scenario as a scenario', () => { + const root = createSuiteStats({ + uid: 'root', + title: 'Cart', + file: '/work', + featureFile: '/work/cart.feature' + }) + const scenario = createSuiteStats({ + uid: 'sc', + title: 'checkout', + file: '/work/cart.feature', + featureFile: '/work/cart.feature', + parent: 'root' + }) + scenario.tests = [namedTest('step', 'sc', { file: '/work/cart.feature' })] + root.suites = [scenario] + + const map = collectSuiteTestMetadata([root]) + expect(map.get('sc')?.title).toBe('checkout') + expect(map.get('step')?.ancestry?.map((a) => a.kind)).toEqual([ + 'feature', + 'scenario' + ]) + }) + + it('keeps a mocha-style suite tree unchanged when no suite names a feature file', () => { + const root = createSuiteStats({ + uid: 'root', + title: 'Login', + file: '/spec/login.ts' + }) + root.tests = [namedTest('t1', 'root')] + + const map = collectSuiteTestMetadata([root]) + expect(map.has('root')).toBe(false) + expect(map.get('t1')?.ancestry?.map((a) => a.kind)).toEqual(['suite']) + }) + it('walks multiple root suites from any iterable', () => { const a = createSuiteStats({ uid: 'a', title: 'A', file: '/a.ts' }) const b = createSuiteStats({ uid: 'b', title: 'B', file: '/b.ts' }) diff --git a/packages/selenium-devtools/src/helpers/testManager.ts b/packages/selenium-devtools/src/helpers/testManager.ts index 018f75aef..e0b432b28 100644 --- a/packages/selenium-devtools/src/helpers/testManager.ts +++ b/packages/selenium-devtools/src/helpers/testManager.ts @@ -224,6 +224,19 @@ export class TestManager { return this.#attemptTracker } + /** A Cucumber scenario is the test unit, so its attempt opens and closes here, not per step. */ + recordScenarioStart(uid: string, specFile: string): void { + this.#attemptTracker.recordStart(uid, specFile) + } + + recordScenarioOutcome( + uid: string, + state: TestStats['state'], + error?: string + ): void { + this.#attemptTracker.recordOutcome(uid, state, error) + } + /** The just-ended marked test's attempts, for the per-test video retention * decision. Empty when no marked test ran. */ lastTestOutcomes(): TestOutcome[] { diff --git a/packages/selenium-devtools/src/test-management.ts b/packages/selenium-devtools/src/test-management.ts index b503bcd20..f273d3da1 100644 --- a/packages/selenium-devtools/src/test-management.ts +++ b/packages/selenium-devtools/src/test-management.ts @@ -202,7 +202,15 @@ export function startScenario( ctx.testReporter.updateSuites() } const file = meta.file ?? root?.file ?? process.cwd() - ctx.suiteManager.startScenarioSuite(name, file, meta.callSource, meta.file) + const scenario = ctx.suiteManager.startScenarioSuite( + name, + file, + meta.callSource, + meta.file + ) + if (scenario) { + ctx.testManager?.recordScenarioStart(scenario.uid, file) + } ctx.retryTracker.reset() ctx.sessionCapturer?.resetTestCapture() if (meta.file) { @@ -218,8 +226,12 @@ export function endScenario( if (!ctx.suiteManager) { return } + const scenario = ctx.suiteManager.getCurrentParent() ctx.testManager?.endCurrent(state, error) ctx.suiteManager.endScenarioSuite(state) + if (scenario && scenario !== ctx.suiteManager.getRootSuite()) { + ctx.testManager?.recordScenarioOutcome(scenario.uid, state, error) + } ctx.retryTracker.reset() } @@ -256,7 +268,14 @@ export function ensureSuiteAndTestManager( const p = ctx.pendingScenario ctx.pendingScenario = null const file = p.file ?? rootSuite.file - ctx.suiteManager.startScenarioSuite(p.name, file, p.callSource) + const scenario = ctx.suiteManager.startScenarioSuite( + p.name, + file, + p.callSource + ) + if (scenario) { + ctx.testManager?.recordScenarioStart(scenario.uid, file) + } if (p.file) { ctx.sessionCapturer?.captureSource(p.file).catch(() => {}) } diff --git a/packages/selenium-devtools/tests/attempt-capture.test.ts b/packages/selenium-devtools/tests/attempt-capture.test.ts index ecc70657b..04bb90279 100644 --- a/packages/selenium-devtools/tests/attempt-capture.test.ts +++ b/packages/selenium-devtools/tests/attempt-capture.test.ts @@ -2,10 +2,17 @@ import { describe, it, expect, vi } from 'vitest' import { buildArtifactsManifest, collectSuiteTestMetadata, + RetryTracker, shouldRetainTrace } from '@wdio/devtools-core' import { resetSignatureCounters } from '../src/helpers/utils.js' +import { + endScenario, + ensureSuiteAndTestManager, + startScenario, + type TestManagementCtx +} from '../src/test-management.js' import { TestManager } from '../src/helpers/testManager.js' import { SuiteManager } from '../src/helpers/suiteManager.js' import { TestReporter } from '../src/reporter.js' @@ -157,6 +164,62 @@ describe('artifacts manifest gating', () => { }) }) +describe('a Cucumber scenario is the attempt-ledger unit', () => { + it('records one attempt for the scenario, not one per step', () => { + const testReporter = new TestReporter(vi.fn()) + const suiteManager = new SuiteManager(testReporter) + const rootSuite = suiteManager.getOrCreateRootSuite('/work', 'Cart') + const testManager = new TestManager(rootSuite, testReporter, suiteManager) + const ctx: TestManagementCtx = { + retryTracker: new RetryTracker(), + testReporter, + sessionCapturer: undefined, + suiteManager, + testManager, + testFilePath: undefined, + pendingTestActions: [], + pendingScenario: null + } + + startScenario(ctx, 'checkout', { file: '/work/cart.feature' }) + testManager.startMarkedTest('Given a cart') + testManager.endCurrent('passed') + testManager.startMarkedTest('When I pay') + testManager.endCurrent('passed') + endScenario(ctx, 'passed') + + const scenarioUid = rootSuite.suites[0]!.uid + expect(testManager.attemptOutcomes.forTest(scenarioUid)).toMatchObject([ + { uid: scenarioUid, attempt: 0, state: 'passed' } + ]) + }) + + it('records a scenario queued before the session existed', () => { + const testReporter = new TestReporter(vi.fn()) + const suiteManager = new SuiteManager(testReporter) + const ctx: TestManagementCtx = { + retryTracker: new RetryTracker(), + testReporter, + sessionCapturer: undefined, + suiteManager: undefined, + testManager: undefined, + testFilePath: undefined, + pendingTestActions: [], + pendingScenario: null + } + + startScenario(ctx, 'checkout', { file: '/work/cart.feature' }) + ctx.suiteManager = suiteManager + ensureSuiteAndTestManager(ctx, 'Cart') + endScenario(ctx, 'failed', 'boom') + + const scenarioUid = suiteManager.getRootSuite()!.suites[0]!.uid + expect(ctx.testManager!.attemptOutcomes.forTest(scenarioUid)).toMatchObject( + [{ uid: scenarioUid, attempt: 0, state: 'failed' }] + ) + }) +}) + describe('retry outcome ledger feeds retry-aware retention', () => { it('groups a fail-then-pass retry under one retry-stable uid', () => { const { mgr } = makeManager() From 2e57161a8a64f3e6bb1ae67fa0c0738ea731b84e Mon Sep 17 00:00:00 2001 From: Vince Graics Date: Mon, 9 Nov 2026 21:33:47 +0100 Subject: [PATCH 08/15] feat: add a telemetry mode that writes only the artifacts manifest Co-Authored-By: Claude Haiku 5.5 --- .changeset/manifest-option-warning.md | 7 + .changeset/nightwatch-telemetry-mode.md | 5 + .changeset/selenium-telemetry-mode.md | 5 + .changeset/service-telemetry-mode.md | 5 + README.md | 90 +++--- packages/conformance/src/features.ts | 13 + packages/core/src/assert-patcher.ts | 52 +++- packages/core/src/session-capturer.ts | 18 ++ packages/core/src/trace-finalizer.ts | 35 ++- packages/core/tests/assert-patcher.test.ts | 24 ++ packages/core/tests/trace-finalizer.test.ts | 32 +++ packages/nightwatch-devtools/README.md | 12 +- .../src/helpers/browserProxy.ts | 22 +- packages/nightwatch-devtools/src/index.ts | 24 +- .../src/plugin-screencast.ts | 21 +- .../nightwatch-devtools/src/run-lifecycle.ts | 22 +- .../nightwatch-devtools/src/session-init.ts | 23 +- packages/nightwatch-devtools/src/session.ts | 24 +- .../tests/browserProxy.test.ts | 28 ++ .../tests/modeValidation.test.ts | 14 + .../tests/pluginScreencast.test.ts | 15 +- .../tests/runLifecycle.test.ts | 11 + .../tests/telemetryCapture.test.ts | 150 ++++++++++ .../tests/telemetryMode.test.ts | 31 ++ packages/selenium-devtools/README.md | 8 +- .../selenium-devtools/src/assertPatcher.ts | 6 +- .../selenium-devtools/src/driverPatcher.ts | 53 +++- .../src/helpers/commandPostActions.ts | 18 +- .../src/helpers/finalFrame.ts | 3 +- .../src/helpers/screencast-options.ts | 39 +++ packages/selenium-devtools/src/index.ts | 107 ++++--- .../src/session-lifecycle.ts | 56 ++-- packages/selenium-devtools/src/session.ts | 5 +- packages/selenium-devtools/src/types.ts | 2 + .../selenium-devtools/src/wait-tracking.ts | 10 +- .../tests/assert-gate.test.ts | 33 +++ .../tests/configure-warning.test.ts | 32 +++ .../tests/driverPatcher.test.ts | 65 ++++- .../tests/mode-validation.test.ts | 14 + .../tests/screencast-options.test.ts | 66 +++++ .../tests/telemetry-mode.test.ts | 272 ++++++++++++++++++ .../tests/wait-telemetry.test.ts | 33 +++ packages/service/README.md | 6 +- packages/service/src/assertion-tracker.ts | 22 +- packages/service/src/index.ts | 79 +++-- packages/service/src/launcher.ts | 13 +- packages/service/src/screencast-lifecycle.ts | 19 +- packages/service/src/session-metadata.ts | 5 +- packages/service/src/session.ts | 19 +- packages/service/src/trace-slices.ts | 3 +- packages/service/tests/assertion-rows.test.ts | 21 ++ packages/service/tests/index.test.ts | 83 ++++++ packages/service/tests/launcher.test.ts | 10 + .../service/tests/mode-validation.test.ts | 20 ++ .../tests/screencast-lifecycle.test.ts | 22 +- .../service/tests/session-metadata.test.ts | 21 ++ .../service/tests/telemetry-output.test.ts | 21 ++ .../service/tests/trace-granularity.test.ts | 15 + packages/shared/src/index.ts | 1 + packages/shared/src/mode-traits.ts | 124 ++++++++ packages/shared/src/types.ts | 13 +- packages/shared/tests/mode-traits.test.ts | 154 ++++++++++ packages/trace/src/trace-retention.ts | 21 +- packages/trace/tests/trace-retention.test.ts | 21 +- 64 files changed, 1877 insertions(+), 341 deletions(-) create mode 100644 .changeset/manifest-option-warning.md create mode 100644 .changeset/nightwatch-telemetry-mode.md create mode 100644 .changeset/selenium-telemetry-mode.md create mode 100644 .changeset/service-telemetry-mode.md create mode 100644 packages/nightwatch-devtools/tests/modeValidation.test.ts create mode 100644 packages/nightwatch-devtools/tests/telemetryCapture.test.ts create mode 100644 packages/nightwatch-devtools/tests/telemetryMode.test.ts create mode 100644 packages/selenium-devtools/src/helpers/screencast-options.ts create mode 100644 packages/selenium-devtools/tests/assert-gate.test.ts create mode 100644 packages/selenium-devtools/tests/configure-warning.test.ts create mode 100644 packages/selenium-devtools/tests/mode-validation.test.ts create mode 100644 packages/selenium-devtools/tests/screencast-options.test.ts create mode 100644 packages/selenium-devtools/tests/telemetry-mode.test.ts create mode 100644 packages/selenium-devtools/tests/wait-telemetry.test.ts create mode 100644 packages/service/tests/mode-validation.test.ts create mode 100644 packages/service/tests/telemetry-output.test.ts create mode 100644 packages/shared/src/mode-traits.ts create mode 100644 packages/shared/tests/mode-traits.test.ts diff --git a/.changeset/manifest-option-warning.md b/.changeset/manifest-option-warning.md new file mode 100644 index 000000000..ef1703901 --- /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 000000000..0910ad8b3 --- /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 000000000..da7d8fa74 --- /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/service-telemetry-mode.md b/.changeset/service-telemetry-mode.md new file mode 100644 index 000000000..a0e550b43 --- /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 6bb766144..e1a9fe993 100644 --- a/README.md +++ b/README.md @@ -173,10 +173,11 @@ The Python adapter takes the same options as `enable(mask_inputs=..., mask_selec ### 📦 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. @@ -190,77 +191,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) | ✓ | ✓ | ✓ | ✓ | | Password fields masked in the replayed page (`maskInputs`, `maskSelectors`) | ✓ | ✓ | ✓ | ✓ | -| 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. @@ -287,7 +291,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 @@ -345,7 +349,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'`. | @@ -592,7 +596,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 f2ecb1f81..5654e60d2 100644 --- a/packages/conformance/src/features.ts +++ b/packages/conformance/src/features.ts @@ -42,6 +42,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 64457c0d8..2a281090f 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 43e51e6bf..7fd240b62 100644 --- a/packages/core/src/session-capturer.ts +++ b/packages/core/src/session-capturer.ts @@ -62,6 +62,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] @@ -169,8 +171,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(), @@ -665,6 +670,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[]) => { @@ -695,6 +703,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 @@ -753,13 +764,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 cc48635b3..18acd6ad1 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 { @@ -91,7 +92,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). @@ -272,7 +274,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)) { @@ -432,16 +434,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 @@ -452,7 +458,7 @@ export async function finalizeTraceExport( // can miss the manifest. A no-op for WDIO (awaits eager flushes inline). await awaitPendingCaptures(ctx) const artifacts = await fanOutTraceWrites(ctx) - 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 @@ -493,14 +499,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 6f544bdb1..3252a741c 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 f9527604e..ce497fe11 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 ac0a7b2fc..392c5c647 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), live and trace mode alike. `false` records them as typed. Command rows always keep the typed text. See [Password masking](../../README.md#-password-masking) for what is and is not covered. | | `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 e3d811d41..f94f9ee9a 100644 --- a/packages/nightwatch-devtools/src/helpers/browserProxy.ts +++ b/packages/nightwatch-devtools/src/helpers/browserProxy.ts @@ -22,7 +22,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 { @@ -157,12 +157,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) } @@ -222,7 +221,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) @@ -527,9 +529,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 = @@ -569,6 +568,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 01a83044a..c105384bd 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, type SpecRange, type TraceArtifact, @@ -25,8 +24,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 { @@ -139,6 +143,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 @@ -152,9 +157,6 @@ class NightwatchDevToolsPlugin { video, screencast: options.screencast }) - if (screencast.warning) { - log.warn(screencast.warning) - } this.options = { port: options.port ?? 3000, hostname: options.hostname ?? 'localhost', @@ -176,7 +178,7 @@ class NightwatchDevToolsPlugin { maskSelectors: options.maskSelectors ?? [] } configureInputMasking(this.options) - const policyWarning = tracePolicyModeWarning(options.tracePolicy, mode) + const policyWarning = ignoredOptionsWarning(options, mode) if (policyWarning) { log.warn(policyWarning) } @@ -364,7 +366,7 @@ class NightwatchDevToolsPlugin { }, getRerunLabel: () => self.#getRerunLabel(), get traceMode() { - return self.options.mode === 'trace' + return capturesTrace(self.options.mode) }, get traceGranularity() { return self.options.traceGranularity @@ -403,7 +405,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` @@ -534,7 +536,7 @@ class NightwatchDevToolsPlugin { suiteLine, testLines ) - if (fullPath && fullPath.includes('/')) { + if (fullPath && fullPath.includes('/') && observesPage(this.options.mode)) { this.sessionCapturer.captureSource(fullPath).catch(() => {}) } @@ -646,7 +648,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() @@ -721,7 +723,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 037266443..8edb648ef 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 36fb823ab..8dcf337b8 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 d08478c09..bddd3a660 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, @@ -170,7 +171,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, @@ -198,7 +201,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( @@ -304,6 +307,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({ @@ -417,7 +423,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!') @@ -437,9 +443,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 @@ -454,7 +465,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 a8085d977..6ca1646af 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 { @@ -175,7 +177,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. @@ -443,7 +445,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 @@ -545,7 +547,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 { @@ -595,7 +597,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. @@ -648,6 +654,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) { @@ -662,7 +671,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( @@ -689,6 +698,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 0be0af13a..6ae5d6b75 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 000000000..449b0ae53 --- /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 b11d21311..b2690903e 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 d7825cbbb..bb0dbd0f3 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 000000000..11068c00d --- /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 000000000..627984070 --- /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 f011e60a1..370dab52b 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), live and trace mode alike. `false` records them as typed. Command rows always keep the typed text. See [Password masking](../../README.md#-password-masking) for what is and is not covered. | | `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 b3de39f59..0ad35b4db 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 53afc1c24..7cfc049d9 100644 --- a/packages/selenium-devtools/src/driverPatcher.ts +++ b/packages/selenium-devtools/src/driverPatcher.ts @@ -184,7 +184,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, @@ -194,17 +230,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 { @@ -513,7 +539,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 4db5619ff..f0a36ce0e 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/finalFrame.ts b/packages/selenium-devtools/src/helpers/finalFrame.ts index 5e5d94069..41033adb6 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 000000000..e4aa49a41 --- /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 47547c856..3fef66cb6 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' @@ -59,18 +66,12 @@ import { configureInputMasking, 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, @@ -78,7 +79,6 @@ import { type MochaRootHooks, type RunnerHookCallbacks, type ScreencastFrame, - type ScreencastOptions, type SeleniumDriverLike, type TestStats } from './types.js' @@ -119,7 +119,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 @@ -165,6 +165,7 @@ class SeleniumDevToolsPlugin { #testArtifacts = new SeleniumTestArtifacts() constructor(options: DevToolsOptions = {}) { + assertDevToolsMode(options.mode) this.#options = { port: options.port ?? 3000, hostname: options.hostname ?? 'localhost', @@ -186,10 +187,7 @@ class SeleniumDevToolsPlugin { maskSelectors: options.maskSelectors ?? [] } configureInputMasking(this.#options) - const policyWarning = tracePolicyModeWarning( - options.tracePolicy, - this.#options.mode - ) + const policyWarning = ignoredOptionsWarning(options, this.#options.mode) if (policyWarning) { log.warn(policyWarning) } @@ -197,21 +195,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' && @@ -238,7 +225,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 }) } @@ -253,11 +240,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 } @@ -277,7 +263,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() } @@ -292,7 +278,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 } @@ -314,6 +300,7 @@ class SeleniumDevToolsPlugin { } configure(opts: DevToolsOptions = {}) { + assertDevToolsMode(opts.mode) if ('rerunCommand' in opts) { this.#rerunManager.configure(opts.rerunCommand) this.#options.rerunCommand = opts.rerunCommand @@ -327,16 +314,11 @@ class SeleniumDevToolsPlugin { } // A preload already registered keeps the policy it was built with; only sessions started after this see a change. configureInputMasking(this.#options) - 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() { @@ -359,7 +341,7 @@ class SeleniumDevToolsPlugin { return self.#options }, get screencastOptions() { - return self.#screencastOptions + return self.#screencastSettings.effective }, get detectedRunner() { return DETECTED_RUNNER @@ -534,7 +516,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) @@ -572,7 +554,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() @@ -593,6 +579,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 & { @@ -699,13 +688,16 @@ 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(), afterActions: (driver) => plugin.onActionsPerformed(driver), @@ -726,12 +718,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 3fa9f2619..9c3074eca 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( @@ -239,6 +248,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 +266,9 @@ async function attachBidi( ctx: SessionLifecycleCtx, driver: SeleniumDriverLike ): Promise<void> { + if (!observesPage(ctx.options.mode)) { + return + } try { const attached = await attachBidiHandlers( driver, @@ -284,6 +299,9 @@ function registerPreload( ctx: SessionLifecycleCtx, driver: SeleniumDriverLike ): Promise<void> { + if (!observesPage(ctx.options.mode)) { + return Promise.resolve() + } return registerCollectorPreload(driver, (level, message) => log[level](message) ).then((registered) => { @@ -306,13 +324,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. @@ -364,15 +385,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 { @@ -599,7 +621,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 05d527263..05aefd7a1 100644 --- a/packages/selenium-devtools/src/session.ts +++ b/packages/selenium-devtools/src/session.ts @@ -13,7 +13,8 @@ import { pollUntilReady, PENDING_SETTLE_TIMEOUT_MS, serializeError, - settlePending + settlePending, + type SessionCapturerOptions } from '@wdio/devtools-core' import { COLLECTOR_INJECT_SCRIPT, @@ -61,7 +62,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 7d68101f8..76c8fdf7e 100644 --- a/packages/selenium-devtools/src/types.ts +++ b/packages/selenium-devtools/src/types.ts @@ -161,6 +161,8 @@ export interface DriverPatcherHooks { beforeInput?: () => 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 6bb7fc2c4..31e0ee9d7 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 000000000..b1576df2d --- /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 000000000..81db3eedc --- /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/driverPatcher.test.ts b/packages/selenium-devtools/tests/driverPatcher.test.ts index 1f60a6046..37456e589 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 000000000..772ae9af5 --- /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 000000000..924a63e87 --- /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/telemetry-mode.test.ts b/packages/selenium-devtools/tests/telemetry-mode.test.ts new file mode 100644 index 000000000..a18f4875d --- /dev/null +++ b/packages/selenium-devtools/tests/telemetry-mode.test.ts @@ -0,0 +1,272 @@ +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 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) + } + ) +}) 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 000000000..07705f0de --- /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 47e664ad4..7cda83005 100644 --- a/packages/service/README.md +++ b/packages/service/README.md @@ -65,6 +65,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 @@ -269,7 +271,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'`. | @@ -277,7 +279,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), live and trace mode alike. `false` records them as typed. Command rows always keep the typed text. See [Password masking](../../README.md#-password-masking) for what is and is not covered. | | `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 aa37cc855..2926d18e9 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, @@ -53,6 +57,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 @@ -76,7 +88,7 @@ export class AssertionTracker { matcherName: string expectedValue?: unknown }): void { - if (this.#ctx.options.captureAssertions === false) { + if (!this.#capturing()) { return } if (this.#assertionDepth === 0) { @@ -103,7 +115,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) @@ -132,7 +144,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, @@ -148,7 +160,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 4838d2acc..fc382948f 100644 --- a/packages/service/src/index.ts +++ b/packages/service/src/index.ts @@ -14,7 +14,6 @@ import { resolveAdapterOutputDir, stepMetadataUid, TestAttemptTracker, - tracePolicyModeWarning, upsertRichestSnapshot, type TraceArtifact, type TraceExportContext, @@ -38,10 +37,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' @@ -89,7 +93,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[] = [] @@ -106,8 +110,12 @@ export default class DevToolsHookService implements Services.ServiceInstance { #slices: TraceSliceTracker constructor(serviceOptions: ServiceOptions = {}) { + assertDevToolsMode(serviceOptions.mode) this.#options = serviceOptions configureInputMasking(serviceOptions) + this.#sessionCapturer = new SessionCapturer({ + captureOutput: observesPage(serviceOptions.mode) + }) this.#assertionTracker = new AssertionTracker({ getCapturer: () => this.#sessionCapturer, getBrowser: () => this.#browser, @@ -116,8 +124,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) { @@ -247,13 +255,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({ @@ -266,7 +275,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 @@ -278,7 +290,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) { @@ -290,13 +302,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 @@ -338,7 +352,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)}`) @@ -614,7 +632,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 @@ -803,6 +821,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 + } // 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. // Not for an injection call: #afterCommand skips those before closing, so @@ -811,12 +838,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. @@ -848,7 +869,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, @@ -910,6 +931,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 @@ -947,7 +972,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 }) @@ -1075,7 +1100,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 e98bc04cf..ccb62be8f 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 4d8a28350..835c9e91c 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 79132cb3a..518dfc8a9 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 f2200d85c..6303aaaea 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, @@ -30,8 +34,10 @@ import { rememberReadValue, RetryTracker, SessionCapturerBase, - type CapturedPerformancePayload + type CapturedPerformancePayload, + 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' @@ -91,7 +97,7 @@ export class SessionCapturer extends SessionCapturerBase { } >() - constructor(devtoolsOptions: { hostname?: string; port?: number } = {}) { + constructor(devtoolsOptions: SessionCapturerOptions = {}) { super(devtoolsOptions) this.patchConsole() this.patchStreams() @@ -209,8 +215,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 browser.takeScreenshot() } catch (screenshotError) { diff --git a/packages/service/src/trace-slices.ts b/packages/service/src/trace-slices.ts index 25b205340..00be1abb9 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 d8e6735ab..7569dd605 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 396924acf..a7288be97 100644 --- a/packages/service/tests/index.test.ts +++ b/packages/service/tests/index.test.ts @@ -10,6 +10,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 @@ -60,6 +63,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 @@ -104,6 +111,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 @@ -505,6 +516,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 c3a45e83a..64c342ab5 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 000000000..e45d741a6 --- /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 49f919d70..35026d5ee 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 7436dfb1b..eaf24eac5 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 000000000..419d411ac --- /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 7981377fc..8edc6a96c 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 403695953..ad117f301 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 000000000..20d71bfba --- /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 2167b0175..faf851feb 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 @@ -448,7 +451,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. */ @@ -471,7 +475,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 the value of password fields in the replayed page (DOM snapshot, * field state, value mutations). Default true. Command rows always keep diff --git a/packages/shared/tests/mode-traits.test.ts b/packages/shared/tests/mode-traits.test.ts new file mode 100644 index 000000000..68179712a --- /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 cdc35013b..62e8bd8ae 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 00982ea23..244ad5dec 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() - }) -}) From 36b14edda5de9ff7a350428e46a23852dc7f42a5 Mon Sep 17 00:00:00 2001 From: Vince Graics <wince17@gmail.com> Date: Tue, 24 Nov 2026 16:52:52 +0100 Subject: [PATCH 09/15] fix(selenium): stamp the .feature file on a Cucumber scenario queued before the driver A scenario started before the driver existed is replayed from pendingScenario. The replay skipped the root featureFile stamp and the featureFile argument to startScenarioSuite that startScenario applies, so the scenario sub-suite inherited the .feature file as its own file and the collector classed it as a 'feature' instead of a 'scenario'. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../selenium-devtools/src/test-management.ts | 22 ++++++++++---- .../tests/attempt-capture.test.ts | 30 +++++++++++++++++++ 2 files changed, 46 insertions(+), 6 deletions(-) diff --git a/packages/selenium-devtools/src/test-management.ts b/packages/selenium-devtools/src/test-management.ts index f273d3da1..2ee8f1a8f 100644 --- a/packages/selenium-devtools/src/test-management.ts +++ b/packages/selenium-devtools/src/test-management.ts @@ -16,7 +16,7 @@ import { DEFAULTS } from './constants.js' import type { SessionCapturer } from './session.js' import type { TestReporter } from './reporter.js' import type { SuiteManager } from './helpers/suiteManager.js' -import type { DetectedRunner, TestStats } from './types.js' +import type { DetectedRunner, SuiteStats, TestStats } from './types.js' import { clearReadValues, type RetryTracker } from '@wdio/devtools-core' const log = logger('@wdio/selenium-devtools:test-management') @@ -197,10 +197,7 @@ export function startScenario( // backend, which strips `--name` and uses it as a positional arg for // feature-level reruns. const root = ctx.suiteManager.getRootSuite() - if (root && meta.file && root.featureFile !== meta.file) { - root.featureFile = meta.file - ctx.testReporter.updateSuites() - } + stampFeatureFile(ctx.testReporter, root, meta.file) const file = meta.file ?? root?.file ?? process.cwd() const scenario = ctx.suiteManager.startScenarioSuite( name, @@ -235,6 +232,17 @@ export function endScenario( ctx.retryTracker.reset() } +function stampFeatureFile( + reporter: TestReporter, + root: SuiteStats | null, + featureFile: string | undefined +): void { + if (root && featureFile && root.featureFile !== featureFile) { + root.featureFile = featureFile + reporter.updateSuites() + } +} + /** Lazy-create rootSuite + testManager so they take the real describe title. */ export function ensureSuiteAndTestManager( ctx: TestManagementCtx, @@ -268,10 +276,12 @@ export function ensureSuiteAndTestManager( const p = ctx.pendingScenario ctx.pendingScenario = null const file = p.file ?? rootSuite.file + stampFeatureFile(ctx.testReporter, rootSuite, p.file) const scenario = ctx.suiteManager.startScenarioSuite( p.name, file, - p.callSource + p.callSource, + p.file ) if (scenario) { ctx.testManager?.recordScenarioStart(scenario.uid, file) diff --git a/packages/selenium-devtools/tests/attempt-capture.test.ts b/packages/selenium-devtools/tests/attempt-capture.test.ts index 04bb90279..a16c5dc08 100644 --- a/packages/selenium-devtools/tests/attempt-capture.test.ts +++ b/packages/selenium-devtools/tests/attempt-capture.test.ts @@ -218,6 +218,36 @@ describe('a Cucumber scenario is the attempt-ledger unit', () => { [{ uid: scenarioUid, attempt: 0, state: 'failed' }] ) }) + + it('stamps the .feature file on a scenario queued before the session existed', () => { + const testReporter = new TestReporter(vi.fn()) + const suiteManager = new SuiteManager(testReporter) + const ctx: TestManagementCtx = { + retryTracker: new RetryTracker(), + testReporter, + sessionCapturer: undefined, + suiteManager: undefined, + testManager: undefined, + testFilePath: undefined, + pendingTestActions: [], + pendingScenario: null + } + + startScenario(ctx, 'checkout', { file: '/work/cart.feature' }) + ctx.suiteManager = suiteManager + ensureSuiteAndTestManager(ctx, 'Cart') + endScenario(ctx, 'passed') + + const root = suiteManager.getRootSuite()! + const scenarioUid = root.suites[0]!.uid + const metadata = collectSuiteTestMetadata([root]) + expect(root.featureFile).toBe('/work/cart.feature') + expect(metadata.get(scenarioUid)).toMatchObject({ + title: 'checkout', + specFile: '/work/cart.feature' + }) + expect(metadata.size).toBe(1) + }) }) describe('retry outcome ledger feeds retry-aware retention', () => { From 7fe9ccbb7e06dd7c6ec2cfc0b9486d8765ad87d5 Mon Sep 17 00:00:00 2001 From: Vince Graics <wince17@gmail.com> Date: Tue, 24 Nov 2026 16:55:53 +0100 Subject: [PATCH 10/15] perf(selenium): skip the viewport read in telemetry mode Telemetry mode writes only the artifacts manifest, which never uses the viewport, yet every Selenium session paid a driver round-trip for it. Gate the read on observesPage(mode), as the Nightwatch adapter already does. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .changeset/selenium-telemetry-viewport.md | 5 ++++ .../src/helpers/driverMetadata.ts | 6 +++- .../src/session-lifecycle.ts | 3 +- .../tests/driverMetadata.test.ts | 28 +++++++++++++++++++ .../selenium-devtools/tests/session.test.ts | 1 + 5 files changed, 41 insertions(+), 2 deletions(-) create mode 100644 .changeset/selenium-telemetry-viewport.md diff --git a/.changeset/selenium-telemetry-viewport.md b/.changeset/selenium-telemetry-viewport.md new file mode 100644 index 000000000..6651eeac3 --- /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/packages/selenium-devtools/src/helpers/driverMetadata.ts b/packages/selenium-devtools/src/helpers/driverMetadata.ts index b0969c265..36063e5f5 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, so the viewport probe is skipped there. */ + 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/session-lifecycle.ts b/packages/selenium-devtools/src/session-lifecycle.ts index 9c3074eca..b5f92048d 100644 --- a/packages/selenium-devtools/src/session-lifecycle.ts +++ b/packages/selenium-devtools/src/session-lifecycle.ts @@ -210,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) { diff --git a/packages/selenium-devtools/tests/driverMetadata.test.ts b/packages/selenium-devtools/tests/driverMetadata.test.ts index 3044ff219..034d47d23 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,30 @@ 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) }) }) + +// Telemetry mode reads no page, and each read is a driver round-trip the manifest never uses. +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/session.test.ts b/packages/selenium-devtools/tests/session.test.ts index e98a5385d..dc41a51cc 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({}) From 8ca71f443da05a69a4d284317899f86ccf5d821a Mon Sep 17 00:00:00 2001 From: Vince Graics <wince17@gmail.com> Date: Tue, 24 Nov 2026 16:56:15 +0100 Subject: [PATCH 11/15] fix(service): end an attempt when its test ends, not after the hook settle afterTest captures endTime before it waits for the command hooks to settle, but the attempt ledger stamped Date.now() after that wait. attempts[].endTime in the artifacts manifest therefore ran past the test's own end by the settle time. recordOutcome now takes the captured endTime, and the service passes it through. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- ...pt-end-time-and-queued-scenario-feature.md | 7 ++++ packages/core/src/attempt-tracker.ts | 5 +-- packages/core/tests/attempt-tracker.test.ts | 7 ++++ packages/service/src/index.ts | 7 +++- packages/service/tests/trace-metadata.test.ts | 32 +++++++++++++++++++ 5 files changed, 55 insertions(+), 3 deletions(-) create mode 100644 .changeset/attempt-end-time-and-queued-scenario-feature.md diff --git a/.changeset/attempt-end-time-and-queued-scenario-feature.md b/.changeset/attempt-end-time-and-queued-scenario-feature.md new file mode 100644 index 000000000..218505b54 --- /dev/null +++ b/.changeset/attempt-end-time-and-queued-scenario-feature.md @@ -0,0 +1,7 @@ +--- +'@wdio/selenium-devtools': patch +'@wdio/devtools-core': patch +'@wdio/devtools-service': patch +--- + +A Cucumber scenario that was queued before the Selenium driver existed is now stamped with its `.feature` file, so the artifacts manifest lists it as a scenario rather than a feature. `attempts[].endTime` in the manifest now ends when the test ends, not after the service has waited for its command hooks to settle. diff --git a/packages/core/src/attempt-tracker.ts b/packages/core/src/attempt-tracker.ts index 92961a3be..3df3f42e9 100644 --- a/packages/core/src/attempt-tracker.ts +++ b/packages/core/src/attempt-tracker.ts @@ -83,14 +83,15 @@ export class TestAttemptTracker implements RetryOutcomeView { recordOutcome( uid: string, state: TestStatus | undefined, - error?: string + error?: string, + endTime: number = Date.now() ): void { const slot = this.#ledger.get(uid)?.attempts.at(-1) if (!slot) { return } slot.outcome.state = state - slot.endTime = Date.now() + slot.endTime = endTime if (error !== undefined) { slot.error = error } diff --git a/packages/core/tests/attempt-tracker.test.ts b/packages/core/tests/attempt-tracker.test.ts index e900785d5..e5861d43e 100644 --- a/packages/core/tests/attempt-tracker.test.ts +++ b/packages/core/tests/attempt-tracker.test.ts @@ -170,6 +170,13 @@ describe('TestAttemptTracker', () => { }) }) describe('attempt records', () => { + it('stores an explicit end time instead of the clock', () => { + const t = new TestAttemptTracker() + t.recordStart('a') + t.recordOutcome('a', 'passed', undefined, 42) + expect(t.attemptsFor('a')[0]?.endTime).toBe(42) + }) + afterEach(() => { vi.useRealTimers() vi.unstubAllEnvs() diff --git a/packages/service/src/index.ts b/packages/service/src/index.ts index 4838d2acc..03492858c 100644 --- a/packages/service/src/index.ts +++ b/packages/service/src/index.ts @@ -499,7 +499,12 @@ export default class DevToolsHookService implements Services.ServiceInstance { // Feed the per-attempt ledger so session/spec retention sees this attempt's // real outcome, not just the final state that overwrites #testMetadata. const metadata = this.#testMetadata.get(uid) - this.#attemptTracker.recordOutcome(uid, metadata?.state, metadata?.error) + this.#attemptTracker.recordOutcome( + uid, + metadata?.state, + metadata?.error, + endTime + ) } async afterScenario( diff --git a/packages/service/tests/trace-metadata.test.ts b/packages/service/tests/trace-metadata.test.ts index b044f2dd0..f0429d0f3 100644 --- a/packages/service/tests/trace-metadata.test.ts +++ b/packages/service/tests/trace-metadata.test.ts @@ -379,6 +379,38 @@ describe('DevtoolsService - afterTest state stamping', () => { } }) + it('ends an attempt before the service waits for its command hooks', async () => { + vi.useFakeTimers({ toFake: ['Date'] }) + const settle = vi + .spyOn(HooksInFlight.prototype, 'settled') + .mockImplementation(async () => { + vi.setSystemTime(13_000) + return true + }) + try { + const service = new DevToolsHookService({ + mode: 'trace', + tracePolicy: 'retain-on-failure' + }) + await service.before({} as never, [], mockBrowser) + const title = 'settling attempt' + vi.setSystemTime(1_000) + service.beforeTest({ file, fullTitle: title }) + vi.setSystemTime(3_000) + await service.afterTest({ file, fullTitle: title }, {}, { passed: true }) + await service.after() + const ctx = finalizeTraceExport.mock.calls.at(-1)?.[0] as { + outcomes: { attemptsFor(uid: string): Array<{ endTime?: number }> } + } + expect( + ctx.outcomes.attemptsFor(deterministicUid(file, title)) + ).toMatchObject([{ endTime: 3_000 }]) + } finally { + settle.mockRestore() + vi.useRealTimers() + } + }) + it('leaves no failure message on a failed scenario that reported no error', async () => { const service = new DevToolsHookService({ mode: 'trace', From 11067a17cf90dcd5a8b9d0b14c114876f2cea736 Mon Sep 17 00:00:00 2001 From: Vince Graics <wince17@gmail.com> Date: Tue, 24 Nov 2026 17:00:59 +0100 Subject: [PATCH 12/15] test(selenium): cover the telemetry viewport skip at the session call site Unit tests exercised buildDriverMetadata with observePage passed directly, so a call site that dropped the observesPage(mode) gate would pass them. The new test drives onDriverCreated in both modes and checks the published metadata. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../src/helpers/driverMetadata.ts | 2 +- .../tests/driverMetadata.test.ts | 1 - .../tests/telemetry-mode.test.ts | 33 +++++++++++++++++++ 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/packages/selenium-devtools/src/helpers/driverMetadata.ts b/packages/selenium-devtools/src/helpers/driverMetadata.ts index 36063e5f5..018c8901b 100644 --- a/packages/selenium-devtools/src/helpers/driverMetadata.ts +++ b/packages/selenium-devtools/src/helpers/driverMetadata.ts @@ -10,7 +10,7 @@ const log = logger('@wdio/selenium-devtools:driverMetadata') export interface DriverMetadataInput { driver: SeleniumDriverLike driverReadyTs: number - /** Telemetry mode reads no page, so the viewport probe is skipped there. */ + /** 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. */ diff --git a/packages/selenium-devtools/tests/driverMetadata.test.ts b/packages/selenium-devtools/tests/driverMetadata.test.ts index 034d47d23..a0c59a14f 100644 --- a/packages/selenium-devtools/tests/driverMetadata.test.ts +++ b/packages/selenium-devtools/tests/driverMetadata.test.ts @@ -218,7 +218,6 @@ describe('buildDriverMetadata viewport', () => { }) }) -// Telemetry mode reads no page, and each read is a driver round-trip the manifest never uses. 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 }) diff --git a/packages/selenium-devtools/tests/telemetry-mode.test.ts b/packages/selenium-devtools/tests/telemetry-mode.test.ts index a18f4875d..aaad1bedd 100644 --- a/packages/selenium-devtools/tests/telemetry-mode.test.ts +++ b/packages/selenium-devtools/tests/telemetry-mode.test.ts @@ -19,6 +19,7 @@ import { type OnCommandCtx } from '../src/helpers/commandPostActions.js' import { captureFinalFrame } from '../src/helpers/finalFrame.js' +import { getDriverOriginals } from '../src/driverPatcher.js' import type { CapturedCommand, DevToolsMode, @@ -269,4 +270,36 @@ describe('telemetry mode: no page injection, preload or BiDi attach', () => { 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() + } + } + ) }) From a1aa3c53ba5ed4c079499af3cec1a59f17b98be6 Mon Sep 17 00:00:00 2001 From: Vince Graics <wince17@gmail.com> Date: Thu, 26 Nov 2026 09:04:52 +0100 Subject: [PATCH 13/15] fix: redact secrets from manifest error messages The manifest copies test and attempt errors verbatim, so a configured secret or a learned password in a failure message leaked into the JSON while the trace zips stayed redacted. Run them through the same redactor as the zips. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- packages/core/src/artifacts-manifest.ts | 12 ++++- .../core/tests/artifacts-manifest.test.ts | 51 +++++++++++++++++++ 2 files changed, 61 insertions(+), 2 deletions(-) diff --git a/packages/core/src/artifacts-manifest.ts b/packages/core/src/artifacts-manifest.ts index 56741c899..dfb1e9f7a 100644 --- a/packages/core/src/artifacts-manifest.ts +++ b/packages/core/src/artifacts-manifest.ts @@ -22,6 +22,7 @@ import type { TraceArtifact, TraceFormat } from '@wdio/devtools-shared' +import { redactSecrets } from './secret-redaction.js' import { stepOwnerUid } from './uid.js' /** Deterministic manifest filename for a session (used by writers and readers). */ @@ -94,6 +95,13 @@ function specFileFor(specFile: string, specRoot: string | undefined): string { return relative } +/** Attempt errors reach the manifest as well as the test's, so both go through the run's redactor. */ +function redactAttemptError(record: TestAttemptRecord): TestAttemptRecord { + return record.error === undefined + ? record + : { ...record, error: redactSecrets(record.error) } +} + /** One test's manifest entry, with its attempts when any were recorded. */ function manifestTestOf( uid: string, @@ -112,9 +120,9 @@ function manifestTestOf( startTime: meta.startTime, endTime: meta.endTime, durationMs: meta.durationMs, - error: meta.error + error: meta.error === undefined ? undefined : redactSecrets(meta.error) } - const attempts = input.attemptsFor?.(uid) ?? [] + const attempts = (input.attemptsFor?.(uid) ?? []).map(redactAttemptError) if (attempts.length === 0) { return test } diff --git a/packages/core/tests/artifacts-manifest.test.ts b/packages/core/tests/artifacts-manifest.test.ts index b0f16bcaa..a0a1bee2e 100644 --- a/packages/core/tests/artifacts-manifest.test.ts +++ b/packages/core/tests/artifacts-manifest.test.ts @@ -7,12 +7,14 @@ import { writeArtifactsManifest, artifactsManifestFilename } from '../src/artifacts-manifest.js' +import { MASKED_VALUE } from '@wdio/devtools-shared' import type { ArtifactsManifest, TestMetadataMap, TraceArtifact } from '@wdio/devtools-shared' import { stepMetadataUid } from '../src/uid.js' +import { configureSecretRedaction } from '../src/secret-redaction.js' import { collectSuiteTestMetadata, createSuiteStats, @@ -532,3 +534,52 @@ describe('artifacts manifest', () => { expect(warn).not.toHaveBeenCalled() }) }) + +describe('artifacts manifest secret redaction', () => { + const SECRET = 'SuperSecretPassword!' + afterEach(() => configureSecretRedaction()) + + it('redacts a configured secret from the test error and every attempt error', () => { + configureSecretRedaction({ secrets: [SECRET] }) + const m = buildArtifactsManifest({ + sessionId: 'sess-r', + format: 'zip', + artifacts: [], + testMetadata: new Map([ + [ + 'u1', + { + title: 'login', + specFile: '/a.spec.ts', + state: 'failed', + attempt: 1, + error: `bad password ${SECRET}` + } + ] + ]), + attemptsFor: () => [ + { + attempt: 0, + startTime: 1, + traceId: 't0', + spanId: 's0', + error: `first try ${SECRET}` + }, + { + attempt: 1, + startTime: 2, + traceId: 't1', + spanId: 's1', + error: `retry ${SECRET}` + } + ] + }) + const json = JSON.stringify(m) + expect(json).not.toContain(SECRET) + expect(m.tests[0].error).toBe(`bad password ${MASKED_VALUE}`) + expect(m.tests[0].attempts?.map((a) => a.error)).toEqual([ + `first try ${MASKED_VALUE}`, + `retry ${MASKED_VALUE}` + ]) + }) +}) From d5c83fd5f3b71552bea45055ad32651792aff290 Mon Sep 17 00:00:00 2001 From: Vince Graics <wince17@gmail.com> Date: Thu, 26 Nov 2026 09:04:52 +0100 Subject: [PATCH 14/15] fix: merge a same-named selenium test only on a real retry signal Without a runner attempt, a same-named test after a failure was taken for a retry and replaced the earlier entry, so a Jest test.each failure followed by a same-named pass reported one passing test. Merge only when the runner passes attempt > 0 (Mocha); Jest exposes no hook-visible retry count, so it never merges. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- .../src/helpers/testManager.ts | 34 +++++------------- .../tests/attempt-capture.test.ts | 36 +++++++++++++------ .../tests/trace-granularity.test.ts | 4 +-- 3 files changed, 36 insertions(+), 38 deletions(-) diff --git a/packages/selenium-devtools/src/helpers/testManager.ts b/packages/selenium-devtools/src/helpers/testManager.ts index e0b432b28..612de14b5 100644 --- a/packages/selenium-devtools/src/helpers/testManager.ts +++ b/packages/selenium-devtools/src/helpers/testManager.ts @@ -132,7 +132,7 @@ export class TestManager { // Scope by parent so two suites with the same test/step name don't // collide on signatureCounter disambiguation across rerun processes. const signature = `${this.suite.uid}::${name}` - const retriedUid = this.#retriedUid(name, file, signature, opts.attempt) + const retriedUid = this.#retriedUid(name, opts.attempt) const uid = retriedUid ?? generateStableUid(file, signature) const ledgerAttempt = this.#attemptTracker.recordStart(uid, file) const test = createTestStats({ @@ -164,32 +164,14 @@ export class TestManager { return test } - /** The uid of the attempt a re-entry retries, so one tests[] entry carries every attempt. A cucumber step is never a retry. */ - #retriedUid( - name: string, - file: string, - signature: string, - attempt: number | undefined - ): string | undefined { + /** The uid of the attempt a runner's retry index re-enters, so one tests[] entry carries every attempt. Without that index a same-named test is another test (Jest test.each, duplicate names). */ + #retriedUid(name: string, attempt: number | undefined): string | undefined { const prior = this.#lastMarkedTest - if (attempt !== undefined) { - return attempt > 0 && - prior?.title === name && - prior.parent === this.suite.uid - ? prior.uid - : undefined - } - const stableUid = deterministicUid(file, signature) - const isStep = this.suite !== this.rootSuite - if (isStep) { - return undefined - } - const earlier = this.suite.tests.find( - (t) => typeof t !== 'string' && t.uid === stableUid - ) - // A retry only follows a failure, so a passed namesake is another test. - return typeof earlier === 'object' && earlier.state !== 'passed' - ? stableUid + return attempt !== undefined && + attempt > 0 && + prior?.title === name && + prior.parent === this.suite.uid + ? prior.uid : undefined } diff --git a/packages/selenium-devtools/tests/attempt-capture.test.ts b/packages/selenium-devtools/tests/attempt-capture.test.ts index a16c5dc08..fdff0f749 100644 --- a/packages/selenium-devtools/tests/attempt-capture.test.ts +++ b/packages/selenium-devtools/tests/attempt-capture.test.ts @@ -32,18 +32,18 @@ function makeManager() { } describe('retry/attempt capture', () => { - it('re-entering the start hook for the same test increments retries (heuristic)', () => { + it('a re-entry carrying the runner attempt index increments retries', () => { const { mgr } = makeManager() - const first = mgr.startMarkedTest('flaky') + const first = mgr.startMarkedTest('flaky', { attempt: 0 }) expect(first.retries).toBe(0) mgr.endCurrent('failed') - const retry = mgr.startMarkedTest('flaky') + const retry = mgr.startMarkedTest('flaky', { attempt: 1 }) expect(retry.retries).toBe(1) mgr.endCurrent('failed') - const retry2 = mgr.startMarkedTest('flaky') + const retry2 = mgr.startMarkedTest('flaky', { attempt: 2 }) expect(retry2.retries).toBe(2) }) @@ -63,9 +63,9 @@ describe('retry/attempt capture', () => { it('flows retries into metadata attempt and the trace ctx flags attempt info', () => { const { mgr, suiteManager, rootSuite } = makeManager() - mgr.startMarkedTest('flaky') + mgr.startMarkedTest('flaky', { attempt: 0 }) mgr.endCurrent('failed') - const retry = mgr.startMarkedTest('flaky') + const retry = mgr.startMarkedTest('flaky', { attempt: 1 }) mgr.endCurrent('passed') expect(retry.retries).toBe(1) @@ -254,9 +254,9 @@ describe('retry outcome ledger feeds retry-aware retention', () => { it('groups a fail-then-pass retry under one retry-stable uid', () => { const { mgr } = makeManager() - const first = mgr.startMarkedTest('flaky') + const first = mgr.startMarkedTest('flaky', { attempt: 0 }) mgr.endCurrent('failed') - const retry = mgr.startMarkedTest('flaky') + const retry = mgr.startMarkedTest('flaky', { attempt: 1 }) mgr.endCurrent('passed') // Each attempt is the same suite-node tests[] entry… @@ -273,9 +273,9 @@ describe('retry outcome ledger feeds retry-aware retention', () => { it('exposes outcomes on the ctx so retain-on-failure drops a fail-then-pass but retain-on-first-failure keeps it', () => { const { mgr, suiteManager } = makeManager() - mgr.startMarkedTest('flaky') + mgr.startMarkedTest('flaky', { attempt: 0 }) mgr.endCurrent('failed') - mgr.startMarkedTest('flaky') + mgr.startMarkedTest('flaky', { attempt: 1 }) mgr.endCurrent('passed') const capturer = new SessionCapturer() @@ -366,6 +366,22 @@ describe('one tests[] entry per test across retries', () => { }) }) +describe('same-named tests without a runner attempt are distinct', () => { + it('keeps a failed test and a same-named passing test as two entries', () => { + const { mgr, rootSuite } = makeManager() + + mgr.startMarkedTest('case') + mgr.endCurrent('failed', 'expected 1 to equal 2') + mgr.startMarkedTest('case') + mgr.endCurrent('passed') + + expect(rootSuite.tests).toMatchObject([ + { title: 'case', state: 'failed' }, + { title: 'case', state: 'passed' } + ]) + }) +}) + describe('failure message reaches the manifest', () => { it('a failed test carries its error, timing and failed attempt error', () => { const { mgr, rootSuite } = makeManager() diff --git a/packages/selenium-devtools/tests/trace-granularity.test.ts b/packages/selenium-devtools/tests/trace-granularity.test.ts index 95212412f..aeb491e61 100644 --- a/packages/selenium-devtools/tests/trace-granularity.test.ts +++ b/packages/selenium-devtools/tests/trace-granularity.test.ts @@ -108,11 +108,11 @@ describe('trace granularity: test', () => { const spec = makeTmpSpec() const { ctx, testManager } = makeCtx('test', spec) - const first = testManager.startMarkedTest('flaky') + const first = testManager.startMarkedTest('flaky', { attempt: 0 }) recordTraceBoundary(ctx, spec) testManager.endCurrent('failed') - const retry = testManager.startMarkedTest('flaky') + const retry = testManager.startMarkedTest('flaky', { attempt: 1 }) recordTraceBoundary(ctx, spec) testManager.endCurrent('passed') From c1434c45e7bc6159cb853907d82071e645d680c1 Mon Sep 17 00:00:00 2001 From: Vince Graics <wince17@gmail.com> Date: Thu, 26 Nov 2026 09:28:56 +0100 Subject: [PATCH 15/15] test: pin that Jest re-runs stay separate attempt-0 entries Jest exposes no retry index to hooks, so after dropping the name heuristic a retryTimes re-run is its own test. Pin that, and fix the attempt option comment that still described the removed heuristic. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --- packages/selenium-devtools/src/types.ts | 2 +- packages/selenium-devtools/tests/attempt-capture.test.ts | 7 ++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/packages/selenium-devtools/src/types.ts b/packages/selenium-devtools/src/types.ts index 7c0615c9c..c00fd3ea0 100644 --- a/packages/selenium-devtools/src/types.ts +++ b/packages/selenium-devtools/src/types.ts @@ -219,7 +219,7 @@ export interface RunnerHookCallbacks { suiteName?: string, suiteCallSource?: string, // Authoritative per-test retry index when the runner exposes one (Mocha's - // `_currentRetry`); undefined leaves the heuristic tracker to decide. + // `_currentRetry`); undefined makes a same-named test a separate test. attempt?: number ) => void // Async so the runner's afterEach/After awaits the full per-test artifact diff --git a/packages/selenium-devtools/tests/attempt-capture.test.ts b/packages/selenium-devtools/tests/attempt-capture.test.ts index fdff0f749..44f68d8a2 100644 --- a/packages/selenium-devtools/tests/attempt-capture.test.ts +++ b/packages/selenium-devtools/tests/attempt-capture.test.ts @@ -367,7 +367,8 @@ describe('one tests[] entry per test across retries', () => { }) describe('same-named tests without a runner attempt are distinct', () => { - it('keeps a failed test and a same-named passing test as two entries', () => { + // Jest exposes no retry index to hooks, so a retryTimes re-run is also recorded as its own attempt-0 test. + it('keeps a failed test and a same-named passing test as two attempt-0 entries', () => { const { mgr, rootSuite } = makeManager() mgr.startMarkedTest('case') @@ -376,8 +377,8 @@ describe('same-named tests without a runner attempt are distinct', () => { mgr.endCurrent('passed') expect(rootSuite.tests).toMatchObject([ - { title: 'case', state: 'failed' }, - { title: 'case', state: 'passed' } + { title: 'case', state: 'failed', retries: 0 }, + { title: 'case', state: 'passed', retries: 0 } ]) }) })