Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/trace-query-actions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@wdio/devtools-trace-query': minor
---

Adds the queries an agent starts a failure with. `traceSummary` gives the runner, browser or device, duration, outcome, counts of actions, failed actions, failed steps, console errors and failed requests, the first error and the test tree with each test's outcome. `traceErrors` lists failed actions, steps that failed on their own (such as a failing hook), console errors and failed requests in time order, each naming the action it happened during. `traceActions` pages the actions in the order they ran, with a wait's polls nested under it, filterable by status, test and time window. `traceActionDetail` returns one action's arguments, result, error with a failed assertion's expected and actual, and the test source around its call site, cut to fit a character budget. `traceTranscript` pages the zip's `transcript.md`. A poll that a passing wait retried past reads as `retried`, not failed, by the same rule the trace player uses. Times are milliseconds from the trace's start, and long values are cut, saying how long they were. `pageOf` now counts a page's wrapper and separators against its budget and takes a `scope`, so a cursor is refused by any listing other than the one that returned it.
5 changes: 4 additions & 1 deletion ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ Contains the canonical definitions for:

- Domain types: `CommandLog`, `ConsoleLog`, `NetworkRequest`, `TraceMutation`, `Metadata`, `TraceLog`, `TraceType`, `TestStats`, `SuiteStats`, `TestStatus`, `TestError`, `ReporterError`, `PreservedAttempt`, `PreservedStep`, `PerformanceData`, `DocumentInfo`, `Viewport`, `ScreencastInfo`, `ScreencastFrame`, `ScreencastOptions`, `LogLevel`, `LogSource`.
- Row nesting: `CommandLog.parentId` names the row whose execution issued a row (a wait's condition reads and polls), and `nestCommands` (`command-tree.ts`) turns a flat row list into the tree the dashboard renders. Every adapter sends a wait as one running row and parents what it issued under it.
- Trace outcome: a zip records no test state, so `trace-outcome.ts` reads a trace's, and each step's, outcome from its rows through `effectiveFailure`, for the player's run list and for `trace-query` alike. `request-failure.ts` `isFailedRequest` is the one rule for a failed request (status 0 or an error status) that `otel` and `trace-query` count.
- WS wire format: `SocketMessage<T>`, `WsMessageScope`, `WsPayloadFor<T>`, `ClearExecutionDataWsPayload`, `ReplaceCommandWsPayload`.
- Routing/scope constants: `WS_PATHS`, `WS_SCOPE`, `BASELINE_WS_SCOPE`, `TESTS_API`, `BASELINE_API`.
- Process-control env vars: `REUSE_ENV`, `RUNNER_ENV`.
Expand Down Expand Up @@ -198,7 +199,9 @@ The DOM-walking scripts run in the page via `browser.execute`, so — like `scri

### `packages/trace-query`

The library under `@wdio/mcp`'s trace tools (`@wdio/devtools-trace-query`), published so a repo that cannot import the private `trace` package still reads traces through its one reader. `openTrace` resolves what an agent was given into one trace: a zip; a run's output folder, whose artifacts manifests (named by shared's `artifactsManifestFilename`, found by `isArtifactsManifestFilename`) map a target test (uid, spec file, session, attempt) to its zip through `trace`'s `traceArtifactFor` and `sharesTraceArtifact` (`output-folder.ts`); or an https URL. Local paths are checked against allowed roots by real path (`local-paths.ts`) and read a range at a time (`file-source.ts`): a path outside every root is refused before it is looked up, a zip is read only while it is still the regular file that was checked, and a folder's manifests are read only as regular files. URLs are fetched over `node:https` on a connection of their own (`agent: false`, so no proxy and no pooled socket) from allowed hosts only, every redirect re-checked, an IP literal checked directly and every name through a `lookup` that refuses private addresses, including an IPv4 one carried in IPv6 (`download.ts`, `network-guard.ts`). `openTraceSource` opens bytes on the lazy archive reader; both pass `maxInflatedBytes` to the reader's own eager-read check (`readTracePayload`) and return an opaque `TraceHandle` that every query takes; what it holds (the payload, the archive, the selected test) stays behind `traceStateOf`, so shared's row types never become the package's API. Every query is bounded by one rule in `budget.ts`: `pageOf` returns the items from a cursor whose serialized length fits a character budget, always at least one so paging advances, with a `nextCursor` that carries the list's length so a cursor handed to another listing is refused; an item larger than the budget comes back whole, so a query cuts its long fields with `truncateText` (UTF-16 code units, never inside a surrogate pair) before paging. It holds no MCP SDK or schema library; `@wdio/mcp` owns the tool schemas and descriptions.
The library under `@wdio/mcp`'s trace tools (`@wdio/devtools-trace-query`), published so a repo that cannot import the private `trace` package still reads traces through its one reader. `openTrace` resolves what an agent was given into one trace: a zip; a run's output folder, whose artifacts manifests (named by shared's `artifactsManifestFilename`, found by `isArtifactsManifestFilename`) map a target test (uid, spec file, session, attempt) to its zip through `trace`'s `traceArtifactFor` and `sharesTraceArtifact` (`output-folder.ts`); or an https URL. Local paths are checked against allowed roots by real path (`local-paths.ts`) and read a range at a time (`file-source.ts`): a path outside every root is refused before it is looked up, a zip is read only while it is still the regular file that was checked, and a folder's manifests are read only as regular files. URLs are fetched over `node:https` on a connection of their own (`agent: false`, so no proxy and no pooled socket) from allowed hosts only, every redirect re-checked, an IP literal checked directly and every name through a `lookup` that refuses private addresses, including an IPv4 one carried in IPv6 (`download.ts`, `network-guard.ts`). `openTraceSource` opens bytes on the lazy archive reader; both pass `maxInflatedBytes` to the reader's own eager-read check (`readTracePayload`) and return an opaque `TraceHandle` that every query takes; what it holds (the payload, the archive, the selected test) stays behind `traceStateOf`, so shared's row types never become the package's API. Every query is bounded by one rule in `budget.ts`, and refuses a `maxChars` below `MIN_QUERY_CHARS` (1000), the smallest budget every whole result is held within (a test checks every query on every fixture and a trace of oversized values): `pageOf` returns the items from a cursor that fit a character budget, the page's `{items, total, nextCursor}` wrapper and separators included, always at least one so paging advances, with a `nextCursor` that carries the list's length and an FNV-1a fingerprint of the listing's scope (its query's filters) so a cursor handed to another listing, even one of equal length, is refused; an item larger than the budget comes back whole, so a query cuts its long fields with `truncateText` (UTF-16 code units, never inside a surrogate pair) before paging. It holds no MCP SDK or schema library; `@wdio/mcp` owns the tool schemas and descriptions.

The queries take a handle and return the package's own result types, never shared's rows, named one to one after `@wdio/mcp`'s tools: `traceSummary` (runner, browser or device, duration, counts of what the other queries list, the first error and the test tree with each step's outcome from shared's `trace-outcome`; past half the budget the tree keeps its failed branches only, as many as fit, and a summary still over budget cuts its first error, then leaves the tree out), `traceErrors` (failed top-level actions, steps that failed on their own, console errors and failed requests in time order, each line or request naming the action last started before it), `traceActions` (top-level rows filterable by status, test and time window, the first 20 rows a wait issued nested under it through `nestCommands`, a row too large for a page shedding them before it cuts its own text), `traceActionDetail` (one row's arguments, result, error with a failed assertion's expected and actual, and the source lines around its call site; source lines go first, the call's own line last, before any value is cut) and `traceTranscript` (the zip's `transcript.md` by line). A row's failure is shared's `effectiveFailure`, so a poll a passing wait retried past reads as `retried`, not failed; `firstError` is a failed action or step, never a console line or request standing in for the cause of a failed trace. A step's own error message is kept by the reader on `TraceActionGroupNode.error` when it is a string, and only the innermost step whose error no failed row explains is listed. `actions.ts` owns the order (start time, then position; the writer floors each start at the previous end, so start order is issue order) and the `callId` lookup every query that takes an action uses; the reader gives every row of a zip a `callId`, and a row without one is named `row@<position>`. Every time ends in `Ms` and counts from the trace's start, every long value is cut with its length noted. A zip keeps an error's message but not its stack, so the call site and its source lines stand in for one. Every query reads the whole zip: one holding several tests is not narrowed to one of them.

Imports from: `shared`, and `trace` by subpath, inlined at build time like every published package. Its dist imports only `fflate` and Node built-ins. Does not import: the `trace` index, `core`, `backend`, `otel` or any adapter (ESLint enforces it).

Expand Down
2 changes: 1 addition & 1 deletion packages/app/CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ Owns the dashboard and trace-player UI, served by the backend and by the hosted

## Rules

- A zip records no test state; a row's outcome is derived from its rows (`utils/trace-summary.ts`).
- A zip records no test state; a row's outcome is derived from its rows by shared's `trace-outcome.ts`, which `@wdio/devtools-trace-query` reads too, so the player and the query library cannot disagree.
- Run start and one entry resetting inside a run share the `clearExecutionData` scope. `ClearExecutionDataWsPayload.runStart` disambiguates on the wire, since popouts see only WS. Don't infer it from uid vs `activeRerunSuiteUid`: that latch outlived its rerun and skipped the next run's wipe. A backend test asserts the flag ships.

## Known debt
Expand Down
2 changes: 1 addition & 1 deletion packages/app/src/components/trace-run-list.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { Element } from '@core/element'
import { html, css, nothing } from 'lit'
import { customElement, property } from 'lit/decorators.js'
import { TRACE_OUTCOME } from '@wdio/devtools-shared'

import { TRACE_RUN_SELECT_EVENT } from '../controller/constants.js'
import type { TraceRunEntry } from '../controller/trace-run.js'
import { TRACE_OUTCOME } from '../utils/trace-summary.js'
import {
stateIcon,
STATE_ICON_STYLES,
Expand Down
6 changes: 3 additions & 3 deletions packages/app/src/controller/trace-run.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import type { ReactiveControllerHost } from 'lit'
import { TRACE_OUTCOME } from '@wdio/devtools-shared'

import { readTraceArchive, type OpenedTrace } from './trace-archive.js'
import type { TraceSource } from '../utils/trace-sources.js'
import {
summarizeTrace,
traceLabelFromPath,
TRACE_OUTCOME,
type TraceSummary
type TraceRunSummary
} from '../utils/trace-summary.js'

/** One zip of an opened run: still to read, read, or refused by the reader. */
Expand All @@ -18,7 +18,7 @@ export type TraceRunEntry = {
label: string
} & (
| { status: 'pending' }
| { status: 'ready'; summary: TraceSummary }
| { status: 'ready'; summary: TraceRunSummary }
| { status: 'error'; error: string }
)

Expand Down
37 changes: 4 additions & 33 deletions packages/app/src/utils/trace-summary.ts
Original file line number Diff line number Diff line change
@@ -1,47 +1,18 @@
import {
effectiveFailure,
retriedRows,
traceOutcome,
type TraceActionChild,
type TraceOutcome,
type TracePlayerData
} from '@wdio/devtools-shared'

/** A zip records no test state, so this is read from its rows: a failed action or step, actions and none failed, or none at all. */
export const TRACE_OUTCOME = {
PASSED: 'passed',
FAILED: 'failed',
UNKNOWN: 'unknown'
} as const

export type TraceOutcome = (typeof TRACE_OUTCOME)[keyof typeof TRACE_OUTCOME]

export interface TraceSummary {
export interface TraceRunSummary {
outcome: TraceOutcome
/** The test the trace holds, outermost suite first; absent unless it holds exactly one. */
titlePath?: string[]
/** When the trace starts, which orders a run's traces as they ran. */
startTime: number
}

function anyGroupFailed(children: readonly TraceActionChild[]): boolean {
return children.some(
(child) =>
'group' in child &&
(child.group.failed || anyGroupFailed(child.group.children))
)
}

export function traceOutcome(data: TracePlayerData): TraceOutcome {
const { commands } = data.trace
const retried = retriedRows(commands)
if (
commands.some((command) => effectiveFailure(command, retried)) ||
anyGroupFailed(data.groups ?? [])
) {
return TRACE_OUTCOME.FAILED
}
return commands.length ? TRACE_OUTCOME.PASSED : TRACE_OUTCOME.UNKNOWN
}

// A per-test zip nests its test in one chain of groups, suites first, ending where a group holds actions or steps.
function singleTestPath(
children: readonly TraceActionChild[]
Expand All @@ -55,7 +26,7 @@ function singleTestPath(
return path.length ? path : undefined
}

export function summarizeTrace(data: TracePlayerData): TraceSummary {
export function summarizeTrace(data: TracePlayerData): TraceRunSummary {
return {
outcome: traceOutcome(data),
titlePath: singleTestPath(data.groups ?? []),
Expand Down
8 changes: 6 additions & 2 deletions packages/app/tests/trace-run.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
import { describe, expect, it, vi } from 'vitest'
import type { ReactiveControllerHost } from 'lit'
import type { CommandLog, TracePlayerData } from '@wdio/devtools-shared'
import {
TRACE_OUTCOME,
type CommandLog,
type TraceOutcome,
type TracePlayerData
} from '@wdio/devtools-shared'

import type { TraceArchiveClient } from '../src/controller/trace-archive.js'
import {
Expand All @@ -9,7 +14,6 @@ import {
type TraceRunEntry
} from '../src/controller/trace-run.js'
import type { TraceSource } from '../src/utils/trace-sources.js'
import { TRACE_OUTCOME, type TraceOutcome } from '../src/utils/trace-summary.js'

const host: ReactiveControllerHost = {
addController() {},
Expand Down
108 changes: 4 additions & 104 deletions packages/app/tests/trace-summary.test.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
// A zip records no test state, so the outcome the run list shows is read from
// the rows. These open zips from the real writer, so what the list derives is
// checked against what an adapter actually leaves on disk.
// What the run list shows for a zip, read from zips the real writer leaves on disk.

import fs from 'node:fs/promises'
import os from 'node:os'
import path from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import {
TRACE_OUTCOME,
TraceType,
type CommandLog,
type TestMetadataMap,
Expand All @@ -18,9 +17,7 @@ import { parseTraceZip } from '@wdio/devtools-trace/trace-reader'

import {
summarizeTrace,
traceLabelFromPath,
traceOutcome,
TRACE_OUTCOME
traceLabelFromPath
} from '../src/utils/trace-summary.js'

const dirs: string[] = []
Expand Down Expand Up @@ -66,28 +63,6 @@ async function perTestZip(commandsLog: CommandLog[]): Promise<TracePlayerData> {
return parseTraceZip(new Uint8Array(await fs.readFile(zip)))
}

/** A parsed trace holding `commands` and nothing else. */
function playerData(
commands: CommandLog[],
groups?: TracePlayerData['groups']
): TracePlayerData {
return {
trace: {
mutations: [],
logs: [],
consoleLogs: [],
networkRequests: [],
commands,
sources: {},
metadata: { type: TraceType.Testrunner }
},
frames: [],
startTime: 0,
duration: 0,
groups
}
}

const row = (command: string, timestamp: number, extra = {}): CommandLog => ({
command,
args: ['#login'],
Expand All @@ -96,87 +71,12 @@ const row = (command: string, timestamp: number, extra = {}): CommandLog => ({
...extra
})

describe('traceOutcome', () => {
it('reads a trace whose actions all passed as passed', async () => {
const data = await perTestZip([row('url', 2000), row('click', 3000)])

expect(traceOutcome(data)).toBe(TRACE_OUTCOME.PASSED)
})

it('reads a trace with a failed action as failed', async () => {
const data = await perTestZip([
row('url', 2000),
row('click', 3000, { error: { name: 'Error', message: 'not found' } })
])

expect(traceOutcome(data)).toBe(TRACE_OUTCOME.FAILED)
})

it('reads a failed assertion that carries no error as failed', async () => {
const data = await perTestZip([
row('assert.equal', 2000, {
args: ['a', 'b'],
result: { passed: false, actual: 'a', expected: 'b' }
})
])

expect(traceOutcome(data)).toBe(TRACE_OUTCOME.FAILED)
})

it('does not count a poll a passing wait retried past', async () => {
const data = await perTestZip([
row('waitUntil', 3000, { id: 7, startTime: 2000 }),
row('isDisplayed', 2100, {
parentId: 7,
error: { name: 'Error', message: 'stale element' }
})
])

expect(traceOutcome(data)).toBe(TRACE_OUTCOME.PASSED)
})

it('has no outcome for a trace with no actions', () => {
const data = playerData([])

expect(traceOutcome(data)).toBe(TRACE_OUTCOME.UNKNOWN)
})

it('reads a step that failed on its own as failed', () => {
const data = playerData(
[],
[
{
group: {
callId: 'g1',
title: 'Login',
startTime: 0,
endTime: 1,
children: [
{
group: {
callId: 'g2',
title: 'logs in',
startTime: 0,
endTime: 1,
failed: true,
children: []
}
}
]
}
}
]
)

expect(traceOutcome(data)).toBe(TRACE_OUTCOME.FAILED)
})
})

describe('summarizeTrace', () => {
it('names the one test a per-test zip holds, suites first', async () => {
const data = await perTestZip([row('url', 2000), row('click', 3000)])

expect(summarizeTrace(data)).toMatchObject({
outcome: TRACE_OUTCOME.PASSED,
titlePath: ['Login', 'logs in'],
startTime: data.startTime
})
Expand Down
15 changes: 4 additions & 11 deletions packages/otel/src/emit-spans.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ import {
type SpanOptions,
type Tracer
} from '@opentelemetry/api'
import type {
NetworkRequest,
TraceActionChild,
TracePlayerData
import {
isFailedRequest,
type TraceActionChild,
type TracePlayerData
} from '@wdio/devtools-shared'
import { normalizeSelector } from '@wdio/devtools-trace/action-key'
import type { ParsedManifestTest } from '@wdio/devtools-trace/artifacts-manifest-reader'
Expand Down Expand Up @@ -233,10 +233,3 @@ function urlPath(url: string): string {
return url.split(/[?#]/, 1)[0]
}
}

function isFailedRequest(request: NetworkRequest): boolean {
return (
request.status !== undefined &&
(request.status === 0 || request.status >= 400)
)
}
3 changes: 2 additions & 1 deletion packages/shared/src/command-failure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ function errorFailure(error: NonNullable<CommandLog['error']>): {
return { message: (error as { message?: string }).message ?? String(error) }
}

function rowFailure(cmd: CommandLog): { message: string } | undefined {
/** Why a row failed on its own, whatever the row that issued it did; `effectiveFailure` is the rule that counts. */
export function rowFailure(cmd: CommandLog): { message: string } | undefined {
const action = mapCommandToAction(cmd.command)
if (action) {
return commandFailure(cmd, action)
Expand Down
2 changes: 2 additions & 0 deletions packages/shared/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export * from './input-mask.js'
export * from './player-csp.js'
export * from './locator-dialect.js'
export * from './mode-traits.js'
export * from './request-failure.js'
export * from './request-type.js'
export * from './routes.js'
export * from './run-capabilities.js'
Expand All @@ -37,6 +38,7 @@ export * from './trace-actions.js'
export * from './trace-context.js'
export * from './trace-export.js'
export * from './trace-file.js'
export * from './trace-outcome.js'
export * from './trace-player.js'
export * from './types.js'
export * from './ws.js'
Loading