diff --git a/.changeset/trace-query-actions.md b/.changeset/trace-query-actions.md new file mode 100644 index 000000000..ba4cdc8d3 --- /dev/null +++ b/.changeset/trace-query-actions.md @@ -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. diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 3a6950ad6..924661d4e 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -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`, `WsMessageScope`, `WsPayloadFor`, `ClearExecutionDataWsPayload`, `ReplaceCommandWsPayload`. - Routing/scope constants: `WS_PATHS`, `WS_SCOPE`, `BASELINE_WS_SCOPE`, `TESTS_API`, `BASELINE_API`. - Process-control env vars: `REUSE_ENV`, `RUNNER_ENV`. @@ -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@`. 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). diff --git a/packages/app/CLAUDE.md b/packages/app/CLAUDE.md index 78b66ee81..ee14c0ccf 100644 --- a/packages/app/CLAUDE.md +++ b/packages/app/CLAUDE.md @@ -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 diff --git a/packages/app/src/components/trace-run-list.ts b/packages/app/src/components/trace-run-list.ts index 119526d9d..2493b1a34 100644 --- a/packages/app/src/components/trace-run-list.ts +++ b/packages/app/src/components/trace-run-list.ts @@ -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, diff --git a/packages/app/src/controller/trace-run.ts b/packages/app/src/controller/trace-run.ts index bfcfa3f38..f7acefd70 100644 --- a/packages/app/src/controller/trace-run.ts +++ b/packages/app/src/controller/trace-run.ts @@ -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. */ @@ -18,7 +18,7 @@ export type TraceRunEntry = { label: string } & ( | { status: 'pending' } - | { status: 'ready'; summary: TraceSummary } + | { status: 'ready'; summary: TraceRunSummary } | { status: 'error'; error: string } ) diff --git a/packages/app/src/utils/trace-summary.ts b/packages/app/src/utils/trace-summary.ts index cb52411e3..708d55118 100644 --- a/packages/app/src/utils/trace-summary.ts +++ b/packages/app/src/utils/trace-summary.ts @@ -1,20 +1,11 @@ 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[] @@ -22,26 +13,6 @@ export interface TraceSummary { 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[] @@ -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 ?? []), diff --git a/packages/app/tests/trace-run.test.ts b/packages/app/tests/trace-run.test.ts index 5377ca139..e4466d304 100644 --- a/packages/app/tests/trace-run.test.ts +++ b/packages/app/tests/trace-run.test.ts @@ -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 { @@ -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() {}, diff --git a/packages/app/tests/trace-summary.test.ts b/packages/app/tests/trace-summary.test.ts index 1259dc018..fd76141f3 100644 --- a/packages/app/tests/trace-summary.test.ts +++ b/packages/app/tests/trace-summary.test.ts @@ -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, @@ -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[] = [] @@ -66,28 +63,6 @@ async function perTestZip(commandsLog: CommandLog[]): Promise { 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'], @@ -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 }) diff --git a/packages/otel/src/emit-spans.ts b/packages/otel/src/emit-spans.ts index b3c585936..f656b1e33 100644 --- a/packages/otel/src/emit-spans.ts +++ b/packages/otel/src/emit-spans.ts @@ -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' @@ -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) - ) -} diff --git a/packages/shared/src/command-failure.ts b/packages/shared/src/command-failure.ts index f96446750..6fc8f04ed 100644 --- a/packages/shared/src/command-failure.ts +++ b/packages/shared/src/command-failure.ts @@ -55,7 +55,8 @@ function errorFailure(error: NonNullable): { 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) diff --git a/packages/shared/src/index.ts b/packages/shared/src/index.ts index ef9858778..a0caeab1f 100644 --- a/packages/shared/src/index.ts +++ b/packages/shared/src/index.ts @@ -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' @@ -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' diff --git a/packages/shared/src/request-failure.ts b/packages/shared/src/request-failure.ts new file mode 100644 index 000000000..0b2b19fa5 --- /dev/null +++ b/packages/shared/src/request-failure.ts @@ -0,0 +1,13 @@ +import type { NetworkRequest } from './types.js' + +const TRANSPORT_FAILURE_STATUS = 0 +const FIRST_ERROR_STATUS = 400 + +/** A transport failure, which the capture side records as status 0, or a response with an error status. A request with no status is unknown, not failed. */ +export function isFailedRequest(request: NetworkRequest): boolean { + return ( + request.status !== undefined && + (request.status === TRANSPORT_FAILURE_STATUS || + request.status >= FIRST_ERROR_STATUS) + ) +} diff --git a/packages/shared/src/trace-outcome.ts b/packages/shared/src/trace-outcome.ts new file mode 100644 index 000000000..ddddb0536 --- /dev/null +++ b/packages/shared/src/trace-outcome.ts @@ -0,0 +1,69 @@ +// A zip records no test state, so the player and the trace query library both read a test's outcome from its rows. + +import { effectiveFailure, retriedRows } from './command-failure.js' +import type { + TraceActionChild, + TraceActionGroupNode, + TracePlayerData +} from './trace-player.js' +import type { CommandLog } from './types.js' + +/** 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] + +function anyGroupFailed(children: readonly TraceActionChild[]): boolean { + return children.some( + (child) => + 'group' in child && + (child.group.failed || anyGroupFailed(child.group.children)) + ) +} + +function outcomeOf(failed: boolean, hasActions: boolean): TraceOutcome { + if (failed) { + return TRACE_OUTCOME.FAILED + } + return hasActions ? TRACE_OUTCOME.PASSED : TRACE_OUTCOME.UNKNOWN +} + +/** The `trace.commands` positions of every row in a tree, rows a wait issued included. */ +export function commandIndicesIn( + children: readonly TraceActionChild[] +): number[] { + return children.flatMap((child) => + 'group' in child + ? commandIndicesIn(child.group.children) + : [child.commandIndex, ...commandIndicesIn(child.children ?? [])] + ) +} + +export function traceOutcome(data: TracePlayerData): TraceOutcome { + const { commands } = data.trace + const retried = retriedRows(commands) + return outcomeOf( + commands.some((command) => effectiveFailure(command, retried)) || + anyGroupFailed(data.groups ?? []), + commands.length > 0 + ) +} + +/** One step of the action tree (a suite, a test) by the same rule; `retried` is `retriedRows` over every command. */ +export function stepOutcome( + step: TraceActionGroupNode, + commands: readonly CommandLog[], + retried: ReadonlySet +): TraceOutcome { + const indices = commandIndicesIn(step.children) + return outcomeOf( + Boolean(step.failed) || + anyGroupFailed(step.children) || + indices.some((index) => effectiveFailure(commands[index], retried)), + indices.length > 0 + ) +} diff --git a/packages/shared/src/trace-player.ts b/packages/shared/src/trace-player.ts index fa24de3c1..d309fb877 100644 --- a/packages/shared/src/trace-player.ts +++ b/packages/shared/src/trace-player.ts @@ -88,6 +88,8 @@ export interface TraceActionGroupNode { endTime: number /** Set when the step's own after errored or any descendant failed. */ failed?: boolean + /** The message the step's own after errored with, such as a failing hook's. */ + error?: string children: TraceActionChild[] } diff --git a/packages/shared/tests/command-failure.test.ts b/packages/shared/tests/command-failure.test.ts index dbf235ad1..31c7ef919 100644 --- a/packages/shared/tests/command-failure.test.ts +++ b/packages/shared/tests/command-failure.test.ts @@ -4,7 +4,8 @@ import { collapsedAssertResult, commandFailure, effectiveFailure, - retriedRows + retriedRows, + rowFailure } from '../src/command-failure.js' import { mapCommandToAction } from '../src/action-mapping.js' import type { CommandLog } from '../src/types.js' @@ -111,3 +112,24 @@ describe('retriedRows', () => { expect(retriedRows([unmapped, read(1)]).size).toBe(0) }) }) + +describe('rowFailure', () => { + it('reads a poll a passing wait retried past as failed on its own', () => { + const wait = row('waitUntil', { id: 1 }) + const poll = row('isDisplayed', { + parentId: 1, + error: { name: 'Error', message: 'stale element' } + }) + expect(effectiveFailure(poll, retriedRows([wait, poll]))).toBeUndefined() + expect(rowFailure(poll)).toEqual({ message: 'stale element' }) + }) + + it('reads an unmapped row by its error alone', () => { + expect(rowFailure(row('customCommand'))).toBeUndefined() + expect( + rowFailure( + row('customCommand', { error: { name: 'Error', message: 'boom' } }) + ) + ).toEqual({ message: 'boom' }) + }) +}) diff --git a/packages/shared/tests/request-failure.test.ts b/packages/shared/tests/request-failure.test.ts new file mode 100644 index 000000000..7b216d993 --- /dev/null +++ b/packages/shared/tests/request-failure.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from 'vitest' +import { isFailedRequest } from '../src/request-failure.js' +import type { NetworkRequest } from '../src/types.js' + +const request = (status?: number): NetworkRequest => ({ + id: '1', + url: 'http://127.0.0.1/a', + method: 'GET', + type: 'fetch', + timestamp: 0, + startTime: 0, + ...(status === undefined ? {} : { status }) +}) + +describe('isFailedRequest', () => { + it.each([0, 400, 404, 500])('reads status %s as failed', (status) => { + expect(isFailedRequest(request(status))).toBe(true) + }) + + it.each([200, 204, 304, 399])('reads status %s as not failed', (status) => { + expect(isFailedRequest(request(status))).toBe(false) + }) + + it('reads a request with no status as unknown rather than failed', () => { + expect(isFailedRequest(request())).toBe(false) + }) +}) diff --git a/packages/shared/tests/trace-outcome.test.ts b/packages/shared/tests/trace-outcome.test.ts new file mode 100644 index 000000000..64fbe83e2 --- /dev/null +++ b/packages/shared/tests/trace-outcome.test.ts @@ -0,0 +1,153 @@ +import { describe, expect, it } from 'vitest' +import { retriedRows } from '../src/command-failure.js' +import { + commandIndicesIn, + stepOutcome, + traceOutcome, + TRACE_OUTCOME +} from '../src/trace-outcome.js' +import type { + TraceActionChild, + TraceActionGroupNode, + TracePlayerData +} from '../src/trace-player.js' +import { TraceType, type CommandLog } from '../src/types.js' + +function playerData( + commands: CommandLog[], + groups?: TraceActionChild[] +): 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'], + timestamp, + ...extra +}) + +const failedClick = row('click', 3000, { + error: { name: 'Error', message: 'not found' } +}) + +// A passing wait (id 0, as the reader restores it) and the poll it retried past. +const waitWithRetriedPoll = [ + row('waitUntil', 3000, { id: 0, startTime: 2000 }), + row('isDisplayed', 2100, { + parentId: 0, + error: { name: 'Error', message: 'stale element' } + }) +] + +function step( + title: string, + children: TraceActionChild[], + failed?: boolean +): TraceActionGroupNode { + return { + callId: title, + title, + startTime: 0, + endTime: 1, + children, + ...(failed ? { failed } : {}) + } +} + +describe('traceOutcome', () => { + it('reads a trace whose actions all passed as passed', () => { + expect(traceOutcome(playerData([row('url', 2000)]))).toBe( + TRACE_OUTCOME.PASSED + ) + }) + + it('reads a trace with a failed action as failed', () => { + expect(traceOutcome(playerData([row('url', 2000), failedClick]))).toBe( + TRACE_OUTCOME.FAILED + ) + }) + + it('reads a failed assertion that carries no error as failed', () => { + const assertion = row('assert.equal', 2000, { + args: ['a', 'b'], + result: { passed: false, actual: 'a', expected: 'b' } + }) + expect(traceOutcome(playerData([assertion]))).toBe(TRACE_OUTCOME.FAILED) + }) + + it('does not count a poll a passing wait retried past', () => { + expect(traceOutcome(playerData(waitWithRetriedPoll))).toBe( + TRACE_OUTCOME.PASSED + ) + }) + + it('has no outcome for a trace with no actions', () => { + expect(traceOutcome(playerData([]))).toBe(TRACE_OUTCOME.UNKNOWN) + }) + + it('reads a step that failed on its own as failed', () => { + const groups = [ + { group: step('Login', [{ group: step('logs in', [], true) }]) } + ] + expect(traceOutcome(playerData([], groups))).toBe(TRACE_OUTCOME.FAILED) + }) +}) + +describe('stepOutcome', () => { + const commands = [row('url', 1000), failedClick, ...waitWithRetriedPoll] + const retried = retriedRows(commands) + + it('reads a step from the rows under it only', () => { + expect( + stepOutcome(step('a', [{ commandIndex: 0 }]), commands, retried) + ).toBe(TRACE_OUTCOME.PASSED) + expect( + stepOutcome( + step('suite', [{ group: step('b', [{ commandIndex: 1 }]) }]), + commands, + retried + ) + ).toBe(TRACE_OUTCOME.FAILED) + }) + + it('reads a wait that retried a poll as passed', () => { + const wait = { commandIndex: 2, children: [{ commandIndex: 3 }] } + expect(stepOutcome(step('c', [wait]), commands, retried)).toBe( + TRACE_OUTCOME.PASSED + ) + }) + + it('reads a step the reader marked failed, or one with no rows', () => { + expect(stepOutcome(step('d', [], true), commands, retried)).toBe( + TRACE_OUTCOME.FAILED + ) + expect(stepOutcome(step('e', []), commands, retried)).toBe( + TRACE_OUTCOME.UNKNOWN + ) + }) +}) + +describe('commandIndicesIn', () => { + it('lists the rows of nested steps and the rows a wait issued', () => { + const tree: TraceActionChild[] = [ + { group: step('s', [{ commandIndex: 0 }]) }, + { commandIndex: 2, children: [{ commandIndex: 3 }] } + ] + expect(commandIndicesIn(tree)).toEqual([0, 2, 3]) + }) +}) diff --git a/packages/trace-query/README.md b/packages/trace-query/README.md index e37c81872..287cff1f3 100644 --- a/packages/trace-query/README.md +++ b/packages/trace-query/README.md @@ -36,12 +36,45 @@ The trace is opened on demand: only the entries its payload is built from are re Only https URLs are fetched, on a connection of their own (no proxy, no pooled socket), within 5 minutes in all. A downloaded zip is held in memory, never written to disk. Messages name a URL without its query string, since a presigned URL carries its credentials there. +## Queries + +Each query takes the handle and returns plain JSON-safe data. Every time ends in `Ms` and counts milliseconds from the trace's start (`timeMs` for an instant, `startMs` and `durationMs` for a span). Fields with no value are left out, and long values (titles, selectors, arguments, results, messages) are cut, ending in `… (cut, N chars)` within the length they were cut to. + +```ts +import { + traceActionDetail, + traceErrors, + traceSummary +} from '@wdio/devtools-trace-query' + +const summary = traceSummary(handle) +const errors = traceErrors(handle) +const failed = + summary.firstError?.kind === 'action' ? summary.firstError.callId : undefined +const detail = failed ? traceActionDetail(handle, failed) : undefined +``` + +| Function | Returns | +|---|---| +| `traceSummary(handle, { maxChars? })` | `runner`, `browser` or `device`, `durationMs`, `outcome`, `counts` of what `traceErrors` and `traceActions` list (top-level actions, failed actions, steps that failed on their own, console errors, failed requests), the `firstError` and `tests`, the suites, tests and steps the zip records with each one's `outcome`. When the tree takes more than half the budget, only its failed branches stay, as many as fit, and `omittedTests` counts the suites, tests and steps left out. A summary still over `maxChars` cuts the first error's text, then leaves the tree out. | +| `traceErrors(handle, { maxChars?, cursor? })` | A page of failed top-level actions, steps that failed on their own (such as a failing hook), console errors and failed requests (status 0 or 400 and above), by `timeMs`: when the action or step started, the line was written or the request was issued. | +| `traceActions(handle, { status?, group?, fromMs?, toMs?, maxChars?, cursor? })` | A page of the top-level actions in the order they started, each with the first 20 rows it issued (a wait's polls) as `children` and `omittedChildren` counting the rest. `status: 'passed'` keeps a row that passed itself; `failed` and `retried` keep a row when it or one of its rows has that status. `group` takes the `callId` of a test from the summary, and `fromMs`/`toMs` keep the rows that ran at least partly inside the window. A row too large for a page sheds the rows it issued, then cuts its own title and error, so every page fits `maxChars`. | +| `traceActionDetail(handle, callId, { contextLines?, maxChars? })` | One action: its arguments and result as JSON, its error with a failed assertion's `expected` and `actual`, the test it ran in, the action that issued it and the first 20 it issued, its `callSite` and the `source` lines around it (3 on each side unless `contextLines`, up to 50, says otherwise), `>` marking the call. Source lines are dropped first (down to the call's own line, then that line too), and only then is each field cut, until the whole result fits `maxChars`. | +| `traceTranscript(handle, { maxChars?, cursor? })` | The zip's `transcript.md` a page of lines at a time, each line cut to fit a page, or `undefined` when the zip carries none. | + +An action's `status` is left out when it passed. It is `failed` by the same rule the trace player and `@wdio/opentelemetry` use, or `retried` for a failed poll that the wait which issued it went on to pass, which is not an error. A failed wait is one error; its failed polls are under it in `traceActions` and named in its detail. Actions are ordered by start time, which the trace writer sets in the order the test issued them, so a Nightwatch assertion reported at the end of its test still sits where it ran. A `callId` is the id the trace player's links name (`#action=call@12`). + +Each error names a `callId`: the failed action or step itself, or for a console line or request, the action last started at or before it; one before the first action names none. `firstError` is the first failed action, else the first step that failed on its own. In a trace that failed, nothing else is put in its place, so a console line or request is never offered as the cause; in one that did not, it is the first console error or failed request. + +A zip keeps an error's message but not its stack, so `callSite` and `source` say where the test was. Every query reads the whole zip: one that holds several tests is not narrowed to one of them. + ## Size budget -Every query is bounded by characters, as a stand-in for tokens, through one rule: +Every query is bounded by characters, as a stand-in for tokens, through one rule. A query refuses a `maxChars` below 1000 (`MIN_QUERY_CHARS`), the smallest budget every query's whole result is held within; from there up, a result never exceeds its `maxChars`. + -- `pageOf(items, { maxChars, cursor })` returns the items whose serialized length fits the budget (20000 characters unless `maxChars` says otherwise), and a `nextCursor` while items remain. A page always holds at least one item, so paging advances; an item larger than the budget comes back whole, which is why a query cuts its long fields first. -- A cursor is valid only for the query that returned it. One handed to a different listing is refused. +- `pageOf(items, { maxChars, cursor }, { scope, size })` returns the items that fit the budget (20000 characters unless `maxChars` says otherwise), the page's own `{ items, total, nextCursor }` wrapper and separators included, and a `nextCursor` while items remain. A page always holds at least one item, so paging advances; an item larger than the budget comes back whole, which is why a query cuts its long fields first. +- A cursor is valid only for the listing that returned it: it carries the list's length and a fingerprint of the listing's `scope` (each query's filters), and one handed to a different listing is refused. - `truncateText(text, maxChars)` cuts a single value to the budget in UTF-16 code units, never inside a surrogate pair, and says how long it was. ## Data handling diff --git a/packages/trace-query/src/action-detail.ts b/packages/trace-query/src/action-detail.ts new file mode 100644 index 000000000..3100b3b83 --- /dev/null +++ b/packages/trace-query/src/action-detail.ts @@ -0,0 +1,193 @@ +import { + collapsedAssertResult, + retriedRows, + type CollapsedAssertResult, + type CommandLog, + type TracePlayerData +} from '@wdio/devtools-shared' +import { + actionByCallId, + actionId, + actionStatus, + ownFailure +} from './actions.js' +import { clipText, clipValue, queryBudgetOf } from './budget.js' +import { + ACTION_STATUS, + DEFAULT_SOURCE_CONTEXT_LINES, + DETAIL_TEXT_STEPS, + MAX_LISTED_CHILDREN, + MAX_LIST_TEXT_CHARS, + MAX_SOURCE_CONTEXT_LINES, + MAX_SOURCE_LINE_CHARS, + MAX_TITLE_CHARS +} from './constants.js' +import { traceStateOf } from './open-trace.js' +import { sourceAround } from './source-lines.js' +import { stepPathOf } from './steps.js' +import type { + ActionDetail, + ActionDetailOptions, + ActionError, + DetailBasis, + DetailCut, + TraceHandle +} from './types.js' + +// The zip keeps an error's message alone, so a failed assertion's collapsed result is the only record of expected and actual. +function failedAssertion( + command: CommandLog +): CollapsedAssertResult | undefined { + const collapsed = collapsedAssertResult(command.result) + return collapsed?.passed === false ? collapsed : undefined +} + +function errorOf(command: CommandLog, text: number): ActionError | undefined { + const message = ownFailure(command) + if (message === undefined) { + return undefined + } + const values = failedAssertion(command) + const expected = clipValue(values?.expected, text) + const actual = clipValue(values?.actual, text) + return { + message: clipText(message, text), + ...(expected === undefined ? {} : { expected }), + ...(actual === undefined ? {} : { actual }) + } +} + +function relatives( + data: TracePlayerData, + command: CommandLog +): Pick { + const { commands } = data.trace + const parentAt = commands.findIndex( + (row) => row.id !== undefined && row.id === command.parentId + ) + const children = commands.flatMap((row, at) => + command.id !== undefined && row.parentId === command.id + ? [actionId(row, at)] + : [] + ) + const omitted = children.length - MAX_LISTED_CHILDREN + return { + ...(parentAt < 0 ? {} : { parent: actionId(commands[parentAt], parentAt) }), + ...(children.length + ? { children: children.slice(0, MAX_LISTED_CHILDREN) } + : {}), + ...(omitted > 0 ? { omittedChildren: omitted } : {}) + } +} + +function sourceOf( + data: TracePlayerData, + command: CommandLog, + cut: DetailCut +): Pick { + if (!command.callSource) { + return {} + } + const source = + cut.contextLines !== 'none' && + sourceAround( + data.trace.sources, + command.callSource, + cut.contextLines, + Math.min(cut.text, MAX_SOURCE_LINE_CHARS) + ) + return { + callSite: clipText( + command.callSource, + Math.min(cut.text, MAX_LIST_TEXT_CHARS) + ), + ...(source ? { source } : {}) + } +} + +function contextLinesOf(options: ActionDetailOptions): number { + const lines = options.contextLines ?? DEFAULT_SOURCE_CONTEXT_LINES + if ( + !Number.isInteger(lines) || + lines < 0 || + lines > MAX_SOURCE_CONTEXT_LINES + ) { + throw new Error( + `contextLines must be an integer from 0 to ${MAX_SOURCE_CONTEXT_LINES}, got ${lines}` + ) + } + return lines +} + +function detailOf( + data: TracePlayerData, + { action, status, test, relatives }: DetailBasis, + cut: DetailCut +): ActionDetail { + const { command } = action + const testPath = test.map((title) => + clipText(title, Math.min(cut.text, MAX_TITLE_CHARS)) + ) + const args = command.args.length + ? clipValue(command.args, cut.text) + : undefined + const result = failedAssertion(command) + ? undefined + : clipValue(command.result, cut.text) + const error = errorOf(command, cut.text) + const listChars = Math.min(cut.text, MAX_LIST_TEXT_CHARS) + return { + callId: action.callId, + title: clipText(command.title ?? command.command, cut.text), + command: clipText(command.command, cut.text), + startMs: action.startMs, + durationMs: action.endMs - action.startMs, + ...(status === ACTION_STATUS.PASSED ? {} : { status }), + ...(testPath.length ? { test: testPath } : {}), + ...relatives, + ...(command.selector + ? { selector: clipText(command.selector, listChars) } + : {}), + ...(args === undefined ? {} : { args }), + ...(result === undefined ? {} : { result }), + ...(error ? { error } : {}), + ...sourceOf(data, command, cut) + } +} + +// Source lines go first, the call's own line last, all at full text; only then does each field narrow, the order the README gives. The narrowest is returned even when it does not fit. +function cutsFor(contextLines: number): DetailCut[] { + const [widest, ...narrower] = DETAIL_TEXT_STEPS + const lines = [...new Set([contextLines, Math.min(contextLines, 1), 0])] + return [ + ...lines.map((count) => ({ text: widest, contextLines: count })), + { text: widest, contextLines: 'none' as const }, + ...narrower.map((text) => ({ text, contextLines: 'none' as const })) + ] +} + +/** One action in full: its arguments, result, error with expected and actual, and the test source around its call site, cut to fit `maxChars`. */ +export function traceActionDetail( + handle: TraceHandle, + callId: string, + options: ActionDetailOptions = {} +): ActionDetail { + const budget = queryBudgetOf(options.maxChars) + const contextLines = contextLinesOf(options) + const { data } = traceStateOf(handle) + const action = actionByCallId(data, callId) + const basis: DetailBasis = { + action, + status: actionStatus(action.command, retriedRows(data.trace.commands)), + test: stepPathOf(data, action.index), + relatives: relatives(data, action.command) + } + let detail: ActionDetail | undefined + for (const cut of cutsFor(contextLines)) { + detail = detailOf(data, basis, cut) + if (JSON.stringify(detail).length <= budget) { + break + } + } + return detail! +} diff --git a/packages/trace-query/src/action-list.ts b/packages/trace-query/src/action-list.ts new file mode 100644 index 000000000..60b6571ab --- /dev/null +++ b/packages/trace-query/src/action-list.ts @@ -0,0 +1,156 @@ +import { + nestCommands, + retriedRows, + type CommandNode, + type TracePlayerData +} from '@wdio/devtools-shared' +import { actionStatus, orderedActions, ownFailure } from './actions.js' +import { clipText, itemBudget, pageOf, queryBudgetOf } from './budget.js' +import { + ACTION_STATUS, + MAX_LIST_TEXT_CHARS, + MAX_LISTED_CHILDREN, + MAX_TITLE_CHARS, + MIN_TEXT_CHARS, + PAGE_SCOPE +} from './constants.js' +import { traceStateOf } from './open-trace.js' +import { commandsOfStep } from './steps.js' +import type { + ActionNode, + ActionQuery, + ActionRow, + ActionStatus, + Page, + TraceHandle +} from './types.js' + +/** The top-level rows in the trace's order, each with the rows it issued under it. */ +export function actionTree(data: TracePlayerData): ActionNode[] { + const ordered = orderedActions(data) + const byCommand = new Map(ordered.map((action) => [action.command, action])) + const retried = retriedRows(data.trace.commands) + const toNode = ({ command, children }: CommandNode): ActionNode => ({ + action: byCommand.get(command)!, + status: actionStatus(command, retried), + children: children.map(toNode) + }) + return nestCommands(ordered.map(({ command }) => command)).map(toNode) +} + +function toRow({ action, status, children }: ActionNode): ActionRow { + const error = ownFailure(action.command) + return { + callId: action.callId, + title: clipText( + action.command.title ?? action.command.command, + MAX_TITLE_CHARS + ), + startMs: action.startMs, + durationMs: action.endMs - action.startMs, + ...(status === ACTION_STATUS.PASSED ? {} : { status }), + ...(error ? { error: clipText(error, MAX_LIST_TEXT_CHARS) } : {}), + ...listedChildren(children) + } +} + +function listedChildren( + children: readonly ActionNode[] +): Pick { + const omitted = children.length - MAX_LISTED_CHILDREN + return { + ...(children.length + ? { children: children.slice(0, MAX_LISTED_CHILDREN).map(toRow) } + : {}), + ...(omitted > 0 ? { omittedChildren: omitted } : {}) + } +} + +// A failed wait is kept for a failed poll under it, but `passed` names the row itself, or a failed wait with a passing poll would match. +function hasStatus(node: ActionNode, status: ActionStatus): boolean { + if (status === ACTION_STATUS.PASSED) { + return node.status === status + } + return ( + node.status === status || + node.children.some((child) => hasStatus(child, status)) + ) +} + +function matcher( + data: TracePlayerData, + query: ActionQuery +): (node: ActionNode) => boolean { + const inStep = + query.group === undefined ? undefined : commandsOfStep(data, query.group) + const from = query.fromMs ?? -Infinity + const to = query.toMs ?? Infinity + return (node) => + (inStep === undefined || inStep.has(node.action.index)) && + (query.status === undefined || hasStatus(node, query.status)) && + node.action.endMs >= from && + node.action.startMs <= to +} + +function withChildren( + row: ActionRow, + children: ActionRow[], + omitted: number +): ActionRow { + const { children: _children, omittedChildren: _omitted, ...own } = row + return { + ...own, + ...(children.length ? { children } : {}), + ...(omitted > 0 ? { omittedChildren: omitted } : {}) + } +} + +// A page always holds one row, so a row larger than a page's budget sheds the rows it issued, then cuts its own text, rather than overrunning maxChars. +function rowWithin(row: ActionRow, budget: number): ActionRow { + const size = (candidate: ActionRow) => JSON.stringify(candidate).length + if (size(row) <= budget) { + return row + } + const children = row.children ?? [] + const omitted = row.omittedChildren ?? 0 + for (let keep = children.length - 1; keep >= 0; keep--) { + const shed = withChildren( + row, + children.slice(0, keep), + omitted + children.length - keep + ) + if (size(shed) <= budget) { + return shed + } + } + const bare = withChildren(row, [], omitted + children.length) + return { + ...bare, + title: clipText(bare.title, MIN_TEXT_CHARS), + ...(bare.error ? { error: clipText(bare.error, MIN_TEXT_CHARS) } : {}) + } +} + +/** The trace's actions in the order they ran, a page at a time, with a wait's rows nested under it. */ +export function traceActions( + handle: TraceHandle, + query: ActionQuery = {} +): Page { + queryBudgetOf(query.maxChars) + const { data } = traceStateOf(handle) + const { status, group, fromMs, toMs } = query + const scope = JSON.stringify([ + PAGE_SCOPE.ACTIONS, + status, + group, + fromMs, + toMs + ]) + const rows = actionTree(data).filter(matcher(data, query)).map(toRow) + const budget = itemBudget(rows.length, query.maxChars, scope) + return pageOf( + rows.map((row) => rowWithin(row, budget)), + query, + { scope } + ) +} diff --git a/packages/trace-query/src/actions.ts b/packages/trace-query/src/actions.ts new file mode 100644 index 000000000..d97b92fc1 --- /dev/null +++ b/packages/trace-query/src/actions.ts @@ -0,0 +1,78 @@ +import { + effectiveFailure, + rowFailure, + type CommandLog, + type TracePlayerData +} from '@wdio/devtools-shared' +import { ACTION_STATUS } from './constants.js' +import type { ActionStatus, OrderedAction } from './types.js' + +/** The id a row is addressed by. The reader gives every row of a zip a callId; a row without one is named by its position so it stays reachable. */ +export function actionId(command: CommandLog, index: number): string { + return command.callId ?? `row@${index}` +} + +/** Ms from the trace's start, rounded. */ +export function sinceStart(data: TracePlayerData, time: number): number { + return Math.round(time - data.startTime) +} + +const startOf = (command: CommandLog) => command.startTime ?? command.timestamp + +function orderedAction( + data: TracePlayerData, + command: CommandLog, + index: number +): OrderedAction { + return { + command, + index, + callId: actionId(command, index), + startMs: sinceStart(data, startOf(command)), + endMs: sinceStart(data, command.timestamp) + } +} + +/** Every row by start time, then position. The writer floors each start at the previous action's end and the reader keeps no `sequence`, so a zip's start order is already the order the test issued its rows in. */ +export function orderedActions(data: TracePlayerData): OrderedAction[] { + return data.trace.commands + .map((command, index) => orderedAction(data, command, index)) + .sort( + (a, b) => startOf(a.command) - startOf(b.command) || a.index - b.index + ) +} + +/** The row a callId names, with its position and clock; refuses one the trace does not hold. */ +export function actionByCallId( + data: TracePlayerData, + callId: string +): OrderedAction { + const { commands } = data.trace + const index = commands.findIndex( + (command, at) => actionId(command, at) === callId + ) + if (index < 0) { + throw new Error( + `The trace has no action ${JSON.stringify(callId)}: pass a callId from the action list` + ) + } + return orderedAction(data, commands[index], index) +} + +/** Why a row failed on its own, whether or not a passing wait retried it. */ +export function ownFailure(command: CommandLog): string | undefined { + return rowFailure(command)?.message +} + +/** `retried` is `retriedRows` over every row of the trace. */ +export function actionStatus( + command: CommandLog, + retried: ReadonlySet +): ActionStatus { + if (retried.has(command)) { + return ACTION_STATUS.RETRIED + } + return effectiveFailure(command, retried) + ? ACTION_STATUS.FAILED + : ACTION_STATUS.PASSED +} diff --git a/packages/trace-query/src/budget.ts b/packages/trace-query/src/budget.ts index 409e48b28..101e6104d 100644 --- a/packages/trace-query/src/budget.ts +++ b/packages/trace-query/src/budget.ts @@ -1,10 +1,30 @@ -import { DEFAULT_MAX_CHARS } from './constants.js' -import type { Page, PageRequest, TruncatedText } from './types.js' +import { DEFAULT_MAX_CHARS, MIN_QUERY_CHARS } from './constants.js' +import type { Page, PageOptions, PageRequest, TruncatedText } from './types.js' -// The list's length rides in the cursor, so a cursor handed back to a different listing is refused rather than read as an offset into it. -const CURSOR = /^(0|[1-9]\d*)\/(0|[1-9]\d*)$/ +// The cursor carries the list's length and its scope's fingerprint, so one handed to a different listing is refused rather than read as an offset into it. +const CURSOR = /^(0|[1-9]\d*)\/(0|[1-9]\d*)\/([0-9a-f]{8})$/ -function offsetOf(cursor: string | undefined, total: number): number { +const FNV_OFFSET = 0x811c9dc5 +const FNV_PRIME = 0x01000193 + +// The fingerprint only tells listings apart and guards nothing secret, so a 32-bit FNV-1a hash is enough. +function fingerprint(scope: string): string { + let hash = FNV_OFFSET + for (let at = 0; at < scope.length; at++) { + hash = Math.imul(hash ^ scope.charCodeAt(at), FNV_PRIME) >>> 0 + } + return hash.toString(16).padStart(8, '0') +} + +function cursorAt(offset: number, total: number, scope: string): string { + return `${offset}/${total}/${fingerprint(scope)}` +} + +function offsetOf( + cursor: string | undefined, + total: number, + scope: string +): number { if (cursor === undefined) { return 0 } @@ -15,7 +35,11 @@ function offsetOf(cursor: string | undefined, total: number): number { ) } const offset = Number(match[1]) - if (Number(match[2]) !== total || offset > total) { + if ( + Number(match[2]) !== total || + offset > total || + match[3] !== fingerprint(scope) + ) { throw new Error( `The cursor ${JSON.stringify(cursor)} belongs to a different listing: pass it back only to the query that returned it` ) @@ -23,7 +47,8 @@ function offsetOf(cursor: string | undefined, total: number): number { return offset } -function budgetOf(maxChars: number | undefined): number { +/** The character budget a request names, or the default; refuses one that is not a positive integer. */ +export function budgetOf(maxChars: number | undefined): number { const budget = maxChars ?? DEFAULT_MAX_CHARS if (!Number.isInteger(budget) || budget < 1) { throw new Error(`maxChars must be a positive integer, got ${budget}`) @@ -31,22 +56,51 @@ function budgetOf(maxChars: number | undefined): number { return budget } +/** A query's budget: refuses one below MIN_QUERY_CHARS, the smallest every query's result is held within. */ +export function queryBudgetOf(maxChars: number | undefined): number { + const budget = budgetOf(maxChars) + if (budget < MIN_QUERY_CHARS) { + throw new Error( + `maxChars must be at least ${MIN_QUERY_CHARS}, got ${budget}: a smaller result cannot hold what a query returns` + ) + } + return budget +} + function serializedLength(item: unknown): number { return JSON.stringify(item)?.length ?? 0 } -/** The items from the cursor on whose serialized length fits the budget. A page always holds one item, so paging advances; an item larger than the budget comes back whole, so a query cuts its long fields before paging. */ +// The wrapper and a cursor as long as any this listing can return, so a full page fits whatever cursor it ends with. +function wrapperLength(total: number, scope: string): number { + return serializedLength({ + items: [], + total, + nextCursor: cursorAt(total, total, scope) + }) +} + +/** What a page's items may take of a budget once the wrapper is paid for. */ +export function itemBudget( + total: number, + maxChars: number | undefined, + scope = '' +): number { + return budgetOf(maxChars) - wrapperLength(total, scope) +} + +/** The items from the cursor on that fit the budget, wrapper and separators included. A page always holds one item, so paging advances; an item larger than the budget comes back whole, so a query cuts its long fields before paging. */ export function pageOf( items: readonly T[], request: PageRequest = {}, - size: (item: T) => number = serializedLength + { scope = '', size = serializedLength }: PageOptions = {} ): Page { - const start = offsetOf(request.cursor, items.length) - const budget = budgetOf(request.maxChars) + const start = offsetOf(request.cursor, items.length, scope) + const budget = itemBudget(items.length, request.maxChars, scope) const page: T[] = [] let used = 0 for (let at = start; at < items.length; at++) { - const cost = size(items[at]!) + const cost = size(items[at]!) + (page.length > 0 ? 1 : 0) if (page.length > 0 && used + cost > budget) { break } @@ -57,7 +111,9 @@ export function pageOf( return { items: page, total: items.length, - ...(next < items.length ? { nextCursor: `${next}/${items.length}` } : {}) + ...(next < items.length + ? { nextCursor: cursorAt(next, items.length, scope) } + : {}) } } @@ -74,3 +130,21 @@ export function truncateText(text: string, maxChars?: number): TruncatedText { const end = isHighSurrogate(text.charCodeAt(budget - 1)) ? budget - 1 : budget return { text: text.slice(0, end), totalChars: text.length, truncated: true } } + +/** Text cut so that it and a note of its whole length fit `maxChars`; a budget shorter than the note still gets one character and the note. */ +export function clipText(text: string, maxChars: number): string { + if (text.length <= budgetOf(maxChars)) { + return text + } + const note = `… (cut, ${text.length} chars)` + return `${truncateText(text, Math.max(1, maxChars - note.length)).text}${note}` +} + +/** A value as JSON, so a string reads apart from a number, cut by `clipText`; undefined when it has no JSON form. */ +export function clipValue( + value: unknown, + maxChars: number +): string | undefined { + const json = JSON.stringify(value) as string | undefined + return json === undefined ? undefined : clipText(json, maxChars) +} diff --git a/packages/trace-query/src/constants.ts b/packages/trace-query/src/constants.ts index 93feae3c2..4e69a8eb6 100644 --- a/packages/trace-query/src/constants.ts +++ b/packages/trace-query/src/constants.ts @@ -1,6 +1,9 @@ /** Characters a result holds when its caller names no budget; a rough stand-in for tokens. */ export const DEFAULT_MAX_CHARS = 20_000 +/** The smallest budget a query accepts: below it a summary's own fields, or one error with its message, cannot fit, so the limit could not hold. */ +export const MIN_QUERY_CHARS = 1_000 + const MIB = 1024 * 1024 /** Largest zip opened, on disk or downloaded; a trace is usually a few megabytes. */ @@ -26,3 +29,49 @@ export const MAX_FOLDER_ENTRIES = 10_000 /** Zips a folder without a manifest is searched to, and how many an error lists. */ export const MAX_FOLDER_DEPTH = 4 export const MAX_LISTED = 20 + +/** Characters of an action title in a list; a Python row's title can carry a whole element reference. */ +export const MAX_TITLE_CHARS = 100 + +/** Characters of a message, URL or value in a list item, where many items share the budget. */ +export const MAX_LIST_TEXT_CHARS = 300 + +/** Characters a row's or a summary's own text is cut to once there is nothing else left to shed. */ +export const MIN_TEXT_CHARS = 60 + +/** Source lines shown on each side of an action's call site unless the caller names another count. */ +export const DEFAULT_SOURCE_CONTEXT_LINES = 3 + +/** The most source lines a caller may ask for on each side of a call site. */ +export const MAX_SOURCE_CONTEXT_LINES = 50 + +/** Characters of one source line, so a minified file cannot fill a result. */ +export const MAX_SOURCE_LINE_CHARS = 200 + +/** How an action ended. */ +export const ACTION_STATUS = { + PASSED: 'passed', + FAILED: 'failed', + RETRIED: 'retried' +} as const + +/** What a listed error is. */ +export const TRACE_ERROR_KIND = { + ACTION: 'action', + STEP: 'step', + CONSOLE: 'console', + REQUEST: 'request' +} as const + +/** Rows an action row or detail lists among those it issued, so one wait with many distinct calls stays within a page. */ +export const MAX_LISTED_CHILDREN = 20 + +/** What each paged listing is, as its cursor's scope. */ +export const PAGE_SCOPE = { + ACTIONS: 'actions', + ERRORS: 'errors', + TRANSCRIPT: 'transcript' +} as const + +/** Characters each field of an action's detail is cut to, tried in turn until the whole detail fits its budget. */ +export const DETAIL_TEXT_STEPS = [2_000, 1_000, 500, 250, 120, 60] as const diff --git a/packages/trace-query/src/errors.ts b/packages/trace-query/src/errors.ts new file mode 100644 index 000000000..879d9cd03 --- /dev/null +++ b/packages/trace-query/src/errors.ts @@ -0,0 +1,144 @@ +import { + isFailedRequest, + retriedRows, + stripAnsi, + type ConsoleLog, + type NetworkRequest, + type TracePlayerData +} from '@wdio/devtools-shared' +import { actionTree } from './action-list.js' +import { ownFailure, sinceStart } from './actions.js' +import { clipText, pageOf, queryBudgetOf } from './budget.js' +import { + ACTION_STATUS, + MAX_LIST_TEXT_CHARS, + MAX_TITLE_CHARS, + PAGE_SCOPE, + TRACE_ERROR_KIND +} from './constants.js' +import { traceStateOf } from './open-trace.js' +import { stepsFailedOnTheirOwn } from './steps.js' +import type { + ActionNode, + FailedStep, + OrderedAction, + Page, + PageRequest, + TraceError, + TraceHandle +} from './types.js' + +function consoleText(log: ConsoleLog): string { + const parts = log.args.map((arg) => + typeof arg === 'string' ? arg : JSON.stringify(arg) + ) + return stripAnsi(parts.join(' ')).trim() +} + +// A zip's HAR keeps a transport failure's text, when the capture side had one, as the status text of its status 0. +function requestMessage(request: NetworkRequest): string { + if (!request.status) { + return request.statusText || 'No response' + } + return `HTTP ${request.status} ${request.statusText ?? ''}`.trim() +} + +function actionError(action: OrderedAction): TraceError { + const { command } = action + return { + kind: TRACE_ERROR_KIND.ACTION, + timeMs: action.startMs, + callId: action.callId, + title: clipText(command.title ?? command.command, MAX_TITLE_CHARS), + message: clipText(ownFailure(command) ?? '', MAX_LIST_TEXT_CHARS) + } +} + +function stepError(data: TracePlayerData, step: FailedStep): TraceError { + return { + kind: TRACE_ERROR_KIND.STEP, + timeMs: sinceStart(data, step.startTime), + callId: step.callId, + title: clipText(step.title, MAX_TITLE_CHARS), + message: clipText(step.error, MAX_LIST_TEXT_CHARS) + } +} + +type LastStarted = (timeMs: number) => { callId?: string } + +/** The action last started at or before a moment; nothing before the first action. */ +function lastStartedBefore(tree: readonly ActionNode[]): LastStarted { + return (timeMs) => { + let last: string | undefined + for (const { action } of tree) { + if (action.startMs > timeMs) { + break + } + last = action.callId + } + return last === undefined ? {} : { callId: last } + } +} + +function consoleError( + data: TracePlayerData, + log: ConsoleLog, + near: LastStarted +): TraceError { + const timeMs = sinceStart(data, log.timestamp) + return { + kind: TRACE_ERROR_KIND.CONSOLE, + timeMs, + ...near(timeMs), + message: clipText(consoleText(log), MAX_LIST_TEXT_CHARS) + } +} + +function requestError( + data: TracePlayerData, + request: NetworkRequest, + near: LastStarted +): TraceError { + const timeMs = sinceStart(data, request.startTime) + return { + kind: TRACE_ERROR_KIND.REQUEST, + timeMs, + ...near(timeMs), + message: clipText(requestMessage(request), MAX_LIST_TEXT_CHARS), + ...(request.method ? { method: request.method } : {}), + url: clipText(request.url, MAX_LIST_TEXT_CHARS), + ...(request.status !== undefined ? { status: request.status } : {}) + } +} + +/** Failed top-level actions, steps that failed on their own, console errors and failed requests, by time. */ +export function collectErrors(data: TracePlayerData): TraceError[] { + const { consoleLogs, networkRequests, commands } = data.trace + const tree = actionTree(data) + const near = lastStartedBefore(tree) + return [ + ...tree + .filter((node) => node.status === ACTION_STATUS.FAILED) + .map((node) => actionError(node.action)), + ...stepsFailedOnTheirOwn(data, retriedRows(commands)).map((step) => + stepError(data, step) + ), + ...consoleLogs + .filter((log) => log.type === 'error') + .map((log) => consoleError(data, log, near)), + ...networkRequests + .filter(isFailedRequest) + .map((request) => requestError(data, request, near)) + ].sort((a, b) => a.timeMs - b.timeMs) +} + +/** Every error the trace records, in time order, a page at a time. A failed wait is listed once; its failed polls are in its detail and its action row. */ +export function traceErrors( + handle: TraceHandle, + request: PageRequest = {} +): Page { + queryBudgetOf(request.maxChars) + return pageOf(collectErrors(traceStateOf(handle).data), request, { + scope: PAGE_SCOPE.ERRORS + }) +} diff --git a/packages/trace-query/src/index.ts b/packages/trace-query/src/index.ts index 9fc558cc5..10ad481ec 100644 --- a/packages/trace-query/src/index.ts +++ b/packages/trace-query/src/index.ts @@ -2,20 +2,39 @@ export { bytesZipSource, type ZipSource } from '@wdio/devtools-trace/trace-reader' +export { traceActionDetail } from './action-detail.js' +export { traceActions } from './action-list.js' export { pageOf, truncateText } from './budget.js' export { + ACTION_STATUS, DEFAULT_MAX_CHARS, DEFAULT_MAX_INFLATED_BYTES, - DEFAULT_MAX_ZIP_BYTES + DEFAULT_MAX_ZIP_BYTES, + TRACE_ERROR_KIND } from './constants.js' +export { traceErrors } from './errors.js' export { openTrace, openTraceSource } from './open-trace.js' +export { traceSummary } from './summary.js' +export { traceTranscript } from './transcript.js' +export { TRACE_OUTCOME, type TraceOutcome } from '@wdio/devtools-shared' export type { + ActionDetail, + ActionDetailOptions, + ActionError, + ActionQuery, + ActionRow, + ActionStatus, OpenedTrace, OpenTraceOptions, Page, + PageOptions, PageRequest, + TestNode, + TraceError, + TraceErrorKind, TraceHandle, TraceSelection, + TraceSummary, TraceTarget, TruncatedText } from './types.js' diff --git a/packages/trace-query/src/source-lines.ts b/packages/trace-query/src/source-lines.ts new file mode 100644 index 000000000..da8ebb667 --- /dev/null +++ b/packages/trace-query/src/source-lines.ts @@ -0,0 +1,30 @@ +import { parseCallSource } from '@wdio/devtools-shared' +import { clipText } from './budget.js' +import { MAX_SOURCE_LINE_CHARS } from './constants.js' + +/** The numbered lines around a call site, `>` marking its own line; undefined when the trace holds no such file or line. */ +export function sourceAround( + sources: Readonly>, + callSource: string, + contextLines: number, + lineChars = MAX_SOURCE_LINE_CHARS +): string[] | undefined { + const site = parseCallSource(callSource) + const text = site ? sources[site.file] : undefined + if (!site || text === undefined) { + return undefined + } + const lines = text.split(/\r?\n/) + if (site.line < 1 || site.line > lines.length) { + return undefined + } + const first = Math.max(1, site.line - contextLines) + const last = Math.min(lines.length, site.line + contextLines) + const width = String(last).length + return lines.slice(first - 1, last).map((line, at) => { + const number = first + at + const marker = number === site.line ? '>' : ' ' + const code = clipText(line, lineChars) + return `${marker}${String(number).padStart(width)} | ${code}`.trimEnd() + }) +} diff --git a/packages/trace-query/src/steps.ts b/packages/trace-query/src/steps.ts new file mode 100644 index 000000000..61eba04d9 --- /dev/null +++ b/packages/trace-query/src/steps.ts @@ -0,0 +1,152 @@ +import { + commandIndicesIn, + effectiveFailure, + stepOutcome, + TRACE_OUTCOME, + type CommandLog, + type TraceActionChild, + type TraceActionGroupNode, + type TracePlayerData +} from '@wdio/devtools-shared' +import { clipText } from './budget.js' +import { MAX_TITLE_CHARS } from './constants.js' +import type { FailedStep, TestNode } from './types.js' + +function stepsIn( + children: readonly TraceActionChild[] +): TraceActionGroupNode[] { + return children.flatMap((child) => ('group' in child ? [child.group] : [])) +} + +function allSteps( + children: readonly TraceActionChild[] +): TraceActionGroupNode[] { + return stepsIn(children).flatMap((step) => [step, ...allSteps(step.children)]) +} + +/** The suites, tests and steps of the action tree, each with its outcome. */ +export function testTree( + data: TracePlayerData, + retried: ReadonlySet +): TestNode[] { + const build = (step: TraceActionGroupNode): TestNode => { + const children = stepsIn(step.children).map(build) + return { + callId: step.callId, + title: clipText(step.title, MAX_TITLE_CHARS), + outcome: stepOutcome(step, data.trace.commands, retried), + ...(children.length ? { children } : {}) + } + } + return stepsIn(data.groups ?? []).map(build) +} + +/** The innermost steps whose own end carried an error that no failed row under them explains, such as a failing hook. */ +export function stepsFailedOnTheirOwn( + data: TracePlayerData, + retried: ReadonlySet +): FailedStep[] { + const { commands } = data.trace + const unexplained = allSteps(data.groups ?? []).filter( + (step): step is FailedStep => + step.error !== undefined && + !commandIndicesIn(step.children).some((index) => + effectiveFailure(commands[index], retried) + ) + ) + const listed = new Set(unexplained) + // A wrapper step and the step inside it can both carry one error; the innermost names where it happened. + return unexplained.filter( + (step) => !allSteps(step.children).some((inner) => listed.has(inner)) + ) +} + +function countNodes(nodes: readonly TestNode[]): number { + return nodes.reduce( + (total, node) => total + 1 + countNodes(node.children ?? []), + 0 + ) +} + +/** The tree cut to its failed branches, and how many nodes that left out. */ +export function failedBranches(nodes: readonly TestNode[]): { + kept: TestNode[] + omitted: number +} { + let omitted = 0 + const prune = (level: readonly TestNode[]): TestNode[] => + level.flatMap((node) => { + const { children, ...own } = node + if (node.outcome !== TRACE_OUTCOME.FAILED) { + omitted += countNodes([node]) + return [] + } + const kept = prune(children ?? []) + return [kept.length ? { ...own, children: kept } : own] + }) + return { kept: prune(nodes), omitted } +} + +// Each kept node pays for its own fields, a separator and a `children` key, so the kept tree serializes within the budget. +const CHILDREN_KEY_CHARS = '"children":[],'.length + +/** The tree in order, as far as it fits the budget, and how many nodes that left out. */ +export function treeWithin( + nodes: readonly TestNode[], + budget: number +): { kept: TestNode[]; omitted: number } { + let used = 2 + let omitted = 0 + const take = (level: readonly TestNode[]): TestNode[] => + level.flatMap((node) => { + const { children, ...own } = node + const cost = JSON.stringify(own).length + 1 + CHILDREN_KEY_CHARS + if (used + cost > budget) { + omitted += countNodes([node]) + return [] + } + used += cost + const kept = take(children ?? []) + return [kept.length ? { ...own, children: kept } : own] + }) + return { kept: take(nodes), omitted } +} + +/** The `trace.commands` positions under the step a callId names; refuses one the tree does not hold. */ +export function commandsOfStep( + data: TracePlayerData, + callId: string +): Set { + const step = allSteps(data.groups ?? []).find( + (candidate) => candidate.callId === callId + ) + if (!step) { + throw new Error( + `The trace has no test or step ${JSON.stringify(callId)}: pass a callId from the summary's tests` + ) + } + return new Set(commandIndicesIn(step.children)) +} + +/** The titles of the steps a row ran in, outermost first. */ +export function stepPathOf(data: TracePlayerData, index: number): string[] { + const walk = ( + children: readonly TraceActionChild[], + path: string[] + ): string[] | undefined => { + for (const child of children) { + if (!('group' in child)) { + if (commandIndicesIn([child]).includes(index)) { + return path + } + continue + } + const found = walk(child.group.children, [...path, child.group.title]) + if (found) { + return found + } + } + return undefined + } + return walk(data.groups ?? [], []) ?? [] +} diff --git a/packages/trace-query/src/summary.ts b/packages/trace-query/src/summary.ts new file mode 100644 index 000000000..2d54c3541 --- /dev/null +++ b/packages/trace-query/src/summary.ts @@ -0,0 +1,145 @@ +import { + deviceLabel, + retriedRows, + traceOutcome, + TRACE_OUTCOME, + type Metadata, + type TraceOutcome +} from '@wdio/devtools-shared' +import { actionTree } from './action-list.js' +import { clipText, queryBudgetOf } from './budget.js' +import { + MAX_LIST_TEXT_CHARS, + MAX_TITLE_CHARS, + MIN_TEXT_CHARS, + TRACE_ERROR_KIND +} from './constants.js' +import { collectErrors } from './errors.js' +import { traceStateOf } from './open-trace.js' +import { failedBranches, testTree, treeWithin } from './steps.js' +import type { + PageRequest, + TestNode, + TraceError, + TraceHandle, + TraceSummary +} from './types.js' + +function browserOf(metadata: Metadata): string | undefined { + const capabilities = metadata.capabilities as + { browserName?: unknown; browserVersion?: unknown } | undefined + const name = capabilities?.browserName + if (typeof name !== 'string' || !name) { + return undefined + } + const version = capabilities?.browserVersion + const label = + typeof version === 'string' && version ? `${name} ${version}` : name + return clipText(label, MAX_TITLE_CHARS) +} + +// A failed trace is explained by an action or a step that failed; a console line or request there is a symptom, not the cause. +function firstError( + errors: readonly TraceError[], + outcome: TraceOutcome +): TraceError | undefined { + const of = (kind: TraceError['kind']) => + errors.find((error) => error.kind === kind) + const cause = of(TRACE_ERROR_KIND.ACTION) ?? of(TRACE_ERROR_KIND.STEP) + return cause ?? (outcome === TRACE_OUTCOME.FAILED ? undefined : errors[0]) +} + +// The tree is the one part of a summary that grows with the run, so past half the budget only its failed branches stay, as many as fit. +function boundedTests( + tests: TestNode[], + budget: number +): Pick { + const half = Math.floor(budget / 2) + if (JSON.stringify(tests).length <= half) { + return tests.length ? { tests } : {} + } + const failed = failedBranches(tests) + const { kept, omitted } = treeWithin(failed.kept, half) + return { + ...(kept.length ? { tests: kept } : {}), + omittedTests: failed.omitted + omitted + } +} + +function nodeCount(tests: readonly TestNode[]): number { + return tests.reduce( + (total, node) => total + 1 + nodeCount(node.children ?? []), + 0 + ) +} + +function errorCutTo(error: TraceError, chars: number): TraceError { + return { + ...error, + message: clipText(error.message, chars), + ...(error.title ? { title: clipText(error.title, chars) } : {}), + ...(error.url ? { url: clipText(error.url, chars) } : {}) + } +} + +// The tree only gets half the budget, so a summary still over it cuts the first error's text, then leaves the tree out, counting it. +function summaryWithin(summary: TraceSummary, budget: number): TraceSummary { + const fits = (candidate: TraceSummary) => + JSON.stringify(candidate).length <= budget + if (fits(summary)) { + return summary + } + const { firstError: error } = summary + for (const chars of [MAX_LIST_TEXT_CHARS, MIN_TEXT_CHARS]) { + const cut = error + ? { ...summary, firstError: errorCutTo(error, chars) } + : summary + if (fits(cut)) { + return cut + } + } + const { tests, omittedTests, ...rest } = summary + const omitted = (omittedTests ?? 0) + nodeCount(tests ?? []) + return { + ...rest, + ...(error ? { firstError: errorCutTo(error, MIN_TEXT_CHARS) } : {}), + ...(omitted > 0 ? { omittedTests: omitted } : {}) + } +} + +/** What the trace holds and how it went, small enough to read first. */ +export function traceSummary( + handle: TraceHandle, + request: Pick = {} +): TraceSummary { + const budget = queryBudgetOf(request.maxChars) + const { data } = traceStateOf(handle) + const { metadata, commands } = data.trace + const errors = collectErrors(data) + const count = (kind: TraceError['kind']) => + errors.filter((error) => error.kind === kind).length + const outcome = traceOutcome(data) + const browser = browserOf(metadata) + const error = firstError(errors, outcome) + return summaryWithin( + { + ...(metadata.runner ? { runner: metadata.runner } : {}), + ...(browser ? { browser } : {}), + ...(metadata.device + ? { device: clipText(deviceLabel(metadata.device), MAX_TITLE_CHARS) } + : {}), + durationMs: Math.round(data.duration), + outcome, + counts: { + actions: actionTree(data).length, + failedActions: count(TRACE_ERROR_KIND.ACTION), + failedSteps: count(TRACE_ERROR_KIND.STEP), + consoleErrors: count(TRACE_ERROR_KIND.CONSOLE), + failedRequests: count(TRACE_ERROR_KIND.REQUEST) + }, + ...(error ? { firstError: error } : {}), + ...boundedTests(testTree(data, retriedRows(commands)), budget) + }, + budget + ) +} diff --git a/packages/trace-query/src/transcript.ts b/packages/trace-query/src/transcript.ts new file mode 100644 index 000000000..b73658d19 --- /dev/null +++ b/packages/trace-query/src/transcript.ts @@ -0,0 +1,37 @@ +import { clipText, itemBudget, pageOf, queryBudgetOf } from './budget.js' +import { PAGE_SCOPE } from './constants.js' +import { traceStateOf } from './open-trace.js' +import type { Page, PageRequest, TraceHandle } from './types.js' + +// A page always holds one line, so a line is cut until its JSON form, quotes and escapes included, fits the page. +function lineWithin(line: string, budget: number): string { + let max = budget + let cut = line + while (JSON.stringify(cut).length > budget && max > 1) { + max = Math.max(1, max - (JSON.stringify(cut).length - budget)) + cut = clipText(line, max) + } + return cut +} + +/** The zip's `transcript.md` a page of lines at a time; undefined when the zip carries none. */ +export function traceTranscript( + handle: TraceHandle, + request: PageRequest = {} +): Page | undefined { + queryBudgetOf(request.maxChars) + const { transcript } = traceStateOf(handle).data + if (transcript === undefined) { + return undefined + } + const lines = transcript.split('\n') + const budget = Math.max( + 1, + itemBudget(lines.length, request.maxChars, PAGE_SCOPE.TRANSCRIPT) + ) + return pageOf( + lines.map((line) => lineWithin(line, budget)), + request, + { scope: PAGE_SCOPE.TRANSCRIPT } + ) +} diff --git a/packages/trace-query/src/types.ts b/packages/trace-query/src/types.ts index 4778a8a2c..b5291ff5b 100644 --- a/packages/trace-query/src/types.ts +++ b/packages/trace-query/src/types.ts @@ -1,3 +1,10 @@ +import type { + CommandLog, + TraceActionGroupNode, + TraceOutcome +} from '@wdio/devtools-shared' +import type { ACTION_STATUS, TRACE_ERROR_KIND } from './constants.js' + declare const traceHandleBrand: unique symbol /** An opened trace. Every query takes one; what it holds is not part of the API. */ @@ -11,6 +18,13 @@ export interface PageRequest { maxChars?: number } +export interface PageOptions { + /** What the listing is, such as its query's filters; a cursor from a listing with another scope is refused. */ + scope?: string + /** An item's cost against the budget; its serialized length unless named. */ + size?: (item: T) => number +} + export interface Page { items: T[] /** Items in the whole result, across every page. */ @@ -56,7 +70,7 @@ export interface TraceSelection { specFile: string attempt: number state?: string - /** The zip also holds other tests or earlier attempts, so a query narrows to this one. */ + /** The zip also holds other tests or earlier attempts, and the queries read all of it. */ sharedZip: boolean } @@ -77,3 +91,161 @@ export interface HttpResponse { /** One GET of a URL, without following redirects; injectable so tests need no server. */ export type HttpGet = (url: URL, signal: AbortSignal) => Promise + +/** How an action ended: `failed` by shared's rule, or `retried`, a failed poll that the wait which issued it went on to pass. */ +export type ActionStatus = (typeof ACTION_STATUS)[keyof typeof ACTION_STATUS] + +/** One action in the trace's order. */ +export interface ActionRow { + /** The action's id in the trace, which `traceActionDetail` takes and the player's links name. */ + callId: string + title: string + /** Ms from the trace's start. */ + startMs: number + durationMs: number + /** Absent when the action passed. */ + status?: Exclude + /** Why it failed, or what a retried poll raised; cut to a list's length. */ + error?: string + /** The rows it issued, such as a wait's polls, the first of them when it issued many. */ + children?: ActionRow[] + /** Rows it issued that `children` leaves out. */ + omittedChildren?: number +} + +export interface ActionQuery extends PageRequest { + /** `passed` keeps a row that passed itself; `failed` and `retried` keep a row when it or a row it issued has that status. */ + status?: ActionStatus + /** The `callId` of a suite, test or step from the summary's `tests`. */ + group?: string + /** Keeps rows that ran at least partly inside the window, in ms from the trace's start. */ + fromMs?: number + toMs?: number +} + +export type TraceErrorKind = + (typeof TRACE_ERROR_KIND)[keyof typeof TRACE_ERROR_KIND] + +/** A failed action, a step that failed on its own, a console error or a failed request. */ +export interface TraceError { + kind: TraceErrorKind + /** Ms from the trace's start at which the action or step started, the line was written or the request was issued. */ + timeMs: number + /** The failed action or step itself, or for a console line or request the action last started before it; absent before the first action. */ + callId?: string + /** The failed action's or step's title. */ + title?: string + message: string + method?: string + url?: string + status?: number +} + +/** A suite, test or step the trace records, with its outcome read from its rows. */ +export interface TestNode { + /** Passed to `traceActions` as `group` to list its actions. */ + callId: string + title: string + outcome: TraceOutcome + children?: TestNode[] +} + +export interface TraceSummary { + runner?: string + browser?: string + device?: string + /** Ms from the first event the trace recorded to the last. */ + durationMs: number + outcome: TraceOutcome + /** Each count is of the items `traceErrors` and `traceActions` list: top-level actions, not the rows they issued. */ + counts: { + actions: number + failedActions: number + failedSteps: number + consoleErrors: number + failedRequests: number + } + /** The first failed action, else the first step that failed on its own; in a trace that did not fail, the first console error or failed request. */ + firstError?: TraceError + tests?: TestNode[] + /** Suites, tests and steps left out of `tests` to keep the summary within its budget. */ + omittedTests?: number +} + +/** One action in full; long values are cut, saying so. */ +export interface ActionDetail { + callId: string + title: string + command: string + /** Ms from the trace's start. */ + startMs: number + durationMs: number + status?: Exclude + /** The suites and test it ran in, outermost first. */ + test?: string[] + /** The action that issued it, such as a wait. */ + parent?: string + /** The actions it issued, the first of them when it issued many. */ + children?: string[] + /** Actions it issued that `children` leaves out. */ + omittedChildren?: number + selector?: string + args?: string + result?: string + error?: ActionError + /** Where the test issued it, as `file:line`. */ + callSite?: string + /** The lines around the call site, numbered, with `>` on the call's own line. */ + source?: string[] +} + +/** The zip keeps an error's message, not its stack; `callSite` and `source` say where the test was. */ +export interface ActionError { + message: string + /** A failed assertion's expected and actual values, as JSON. */ + expected?: string + actual?: string +} + +export interface ActionDetailOptions { + /** Source lines on each side of the call site. */ + contextLines?: number + /** Characters the whole result may take; fields and source lines are cut until it fits. */ + maxChars?: number +} + +/** A row of `trace.commands` with its id and clock, in ms from the trace's start. */ +export interface OrderedAction { + command: CommandLog + /** Its position in `trace.commands`, which the action tree's `commandIndex` names. */ + index: number + callId: string + startMs: number + endMs: number +} + +/** A top-level row with the rows it issued, and how each ended. */ +export interface ActionNode { + action: OrderedAction + status: ActionStatus + children: ActionNode[] +} + +/** A step whose own end carried an error message. */ +export type FailedStep = TraceActionGroupNode & { error: string } + +/** How far one attempt at an action's detail cuts: each field's characters, and source lines on each side. */ +export interface DetailCut { + text: number + /** Source lines on each side of the call site, or none at all, the call's own line included. */ + contextLines: number | 'none' +} + +/** What an action's detail holds whatever it is cut to, read once per detail. */ +export interface DetailBasis { + action: OrderedAction + status: ActionStatus + /** Titles of the steps it ran in, outermost first, before cutting. */ + test: string[] + relatives: Pick +} diff --git a/packages/trace-query/tests/actions.test.ts b/packages/trace-query/tests/actions.test.ts new file mode 100644 index 000000000..b66b35458 --- /dev/null +++ b/packages/trace-query/tests/actions.test.ts @@ -0,0 +1,100 @@ +import { describe, expect, it } from 'vitest' +import { + TraceType, + type CommandLog, + type TracePlayerData +} from '@wdio/devtools-shared' +import { + actionByCallId, + actionId, + actionStatus, + orderedActions +} from '../src/actions.js' + +function playerData(commands: CommandLog[]): TracePlayerData { + return { + trace: { + mutations: [], + logs: [], + consoleLogs: [], + networkRequests: [], + commands, + sources: {}, + metadata: { type: TraceType.Standalone } + }, + frames: [], + startTime: 1_000, + duration: 0 + } +} + +const row = (callId: string, extra: Partial = {}): CommandLog => ({ + command: 'click', + args: [], + timestamp: 2_000, + callId, + ...extra +}) + +describe('orderedActions', () => { + it('orders by start time, then position', () => { + const data = playerData([ + row('late', { startTime: 1_500 }), + row('tie-a', { startTime: 1_300 }), + row('no-start', { timestamp: 1_100 }), + row('tie-b', { startTime: 1_300 }) + ]) + expect(orderedActions(data).map((action) => action.callId)).toEqual([ + 'no-start', + 'tie-a', + 'tie-b', + 'late' + ]) + }) + + it('times each action in ms from the trace start, keeping its position', () => { + const [action] = orderedActions( + playerData([row('a', { startTime: 1_200.4, timestamp: 1_450.6 })]) + ) + expect(action).toMatchObject({ index: 0, startMs: 200, endMs: 451 }) + }) +}) + +describe('actionByCallId', () => { + const data = playerData([row('call@3'), row('call@4')]) + + it('finds the row a callId names', () => { + expect(actionByCallId(data, 'call@4')).toMatchObject({ + command: data.trace.commands[1], + index: 1, + callId: 'call@4' + }) + }) + + it('refuses a callId the trace does not hold', () => { + expect(() => actionByCallId(data, 'call@9')).toThrow( + 'The trace has no action "call@9": pass a callId from the action list' + ) + }) + + it('names a row without a callId by its position', () => { + const anonymous = { command: 'click', args: [], timestamp: 2_000 } + const withGap = playerData([row('call@1'), anonymous]) + expect(actionId(anonymous, 1)).toBe('row@1') + expect(orderedActions(withGap).map((action) => action.callId)).toEqual([ + 'call@1', + 'row@1' + ]) + expect(actionByCallId(withGap, 'row@1').command).toBe(anonymous) + }) +}) + +describe('actionStatus', () => { + const failed = row('a', { error: { name: 'Error', message: 'boom' } }) + + it('reads a failed row, a retried row and a passing one', () => { + expect(actionStatus(failed, new Set())).toBe('failed') + expect(actionStatus(failed, new Set([failed]))).toBe('retried') + expect(actionStatus(row('b'), new Set())).toBe('passed') + }) +}) diff --git a/packages/trace-query/tests/budget.test.ts b/packages/trace-query/tests/budget.test.ts index d12d6316c..3e4d031cb 100644 --- a/packages/trace-query/tests/budget.test.ts +++ b/packages/trace-query/tests/budget.test.ts @@ -1,36 +1,46 @@ import { describe, expect, it } from 'vitest' -import { pageOf, truncateText } from '../src/budget.js' +import { clipText, clipValue, pageOf, truncateText } from '../src/budget.js' import { DEFAULT_MAX_CHARS } from '../src/constants.js' const ITEMS = ['aaaa', 'bbbb', 'cccc', 'dddd', 'eeee'] -const fourEach = () => 4 +const fourEach = { size: () => 4 } +// What the wrapper of a five-item listing with no scope costs, so item budgets below read as plain numbers. +const WRAPPER = JSON.stringify({ + items: [], + total: 5, + nextCursor: '5/5/811c9dc5' +}).length + +const budgetFor = (items: number) => WRAPPER + 4 * items + (items - 1) describe('pageOf', () => { it('returns every item and no cursor when they fit', () => { - expect(pageOf(ITEMS, { maxChars: 100 }, fourEach)).toEqual({ + expect(pageOf(ITEMS, { maxChars: 200 }, fourEach)).toEqual({ items: ITEMS, total: 5 }) }) - it('stops before the item that would exceed the budget', () => { - expect(pageOf(ITEMS, { maxChars: 9 }, fourEach)).toEqual({ - items: ['aaaa', 'bbbb'], - total: 5, - nextCursor: '2/5' - }) + it('stops before the item that would exceed the budget, separators and wrapper included', () => { + const page = pageOf(ITEMS, { maxChars: budgetFor(2) }, fourEach) + expect(page.items).toEqual(['aaaa', 'bbbb']) + expect(page.nextCursor).toMatch(/^2\/5\/[0-9a-f]{8}$/) + expect( + pageOf(ITEMS, { maxChars: budgetFor(2) - 1 }, fourEach).items + ).toEqual(['aaaa']) }) it('continues from the cursor it returned', () => { - const first = pageOf(ITEMS, { maxChars: 9 }, fourEach) + const request = { maxChars: budgetFor(2) } + const first = pageOf(ITEMS, request, fourEach) const second = pageOf( ITEMS, - { maxChars: 9, cursor: first.nextCursor }, + { ...request, cursor: first.nextCursor }, fourEach ) const third = pageOf( ITEMS, - { maxChars: 9, cursor: second.nextCursor }, + { ...request, cursor: second.nextCursor }, fourEach ) expect([second.items, third.items]).toEqual([['cccc', 'dddd'], ['eeee']]) @@ -38,49 +48,83 @@ describe('pageOf', () => { }) it('holds one item that alone exceeds the budget, so paging advances', () => { - expect(pageOf(['x'.repeat(50), 'y'], { maxChars: 10 })).toEqual({ - items: ['x'.repeat(50)], - total: 2, - nextCursor: '1/2' - }) - }) - - it('measures items as serialized JSON by default', () => { - const items = [{ a: 1 }, { a: 2 }] - expect(pageOf(items, { maxChars: 7 }).items).toEqual([{ a: 1 }]) - expect(pageOf(items, { maxChars: 14 }).items).toEqual(items) + const page = pageOf(['x'.repeat(50), 'y'], { maxChars: 10 }) + expect(page.items).toEqual(['x'.repeat(50)]) + expect(page.nextCursor).toMatch(/^1\/2\//) }) - it('uses the default budget when none is named', () => { - const half = DEFAULT_MAX_CHARS / 2 - const fit = Array.from({ length: 3 }, () => 'x'.repeat(half)) - const over = Array.from({ length: 3 }, () => 'x'.repeat(half + 1)) - const length = (item: string) => item.length - expect(pageOf(fit, {}, length).items).toHaveLength(2) - expect(pageOf(over, {}, length).items).toHaveLength(1) + it('serializes a full page within its budget', () => { + const items = Array.from({ length: 2_000 }, (_, i) => ({ + title: `row ${i} "quoted"`, + n: i + })) + let cursor: string | undefined + const seen: unknown[] = [] + do { + const page = pageOf(items, { maxChars: 1_000, cursor }, { scope: 's' }) + expect(JSON.stringify(page).length).toBeLessThanOrEqual(1_000) + expect(page.items.length).toBeGreaterThan(1) + seen.push(...page.items) + cursor = page.nextCursor + } while (cursor) + expect(seen).toEqual(items) + const full = pageOf(items) + expect(JSON.stringify(full).length).toBeLessThanOrEqual(DEFAULT_MAX_CHARS) + expect(JSON.stringify(full).length).toBeGreaterThan(DEFAULT_MAX_CHARS - 40) }) it('returns an empty last page at the end of the result', () => { - expect(pageOf(ITEMS, { cursor: '5/5' }, fourEach)).toEqual({ - items: [], - total: 5 - }) + const last = pageOf(ITEMS, { maxChars: budgetFor(5) - 1 }, fourEach) + const end = pageOf(ITEMS, { cursor: last.nextCursor }, fourEach) + expect(end.items).toEqual(['eeee']) + const after = pageOf( + ITEMS, + { cursor: last.nextCursor!.replace(/^4/, '5') }, + fourEach + ) + expect(after).toEqual({ items: [], total: 5 }) }) - it.each(['-1/5', '1.5/5', 'abc', '01/5', '2', '', '2/05'])( - 'refuses the malformed cursor %j', - (cursor) => { - expect(() => pageOf(ITEMS, { cursor })).toThrow(/Invalid cursor/) - } - ) + it.each([ + '-1/5/811c9dc5', + '1.5/5/811c9dc5', + 'abc', + '01/5/811c9dc5', + '2', + '', + '2/5', + '2/05/811c9dc5', + '2/5/811C9DC5' + ])('refuses the malformed cursor %j', (cursor) => { + expect(() => pageOf(ITEMS, { cursor })).toThrow(/Invalid cursor/) + }) - it.each(['2/9', '6/5', '0/4'])( + it.each(['2/9/811c9dc5', '6/5/811c9dc5', '0/4/811c9dc5', '2/5/00000000'])( 'refuses the cursor %j of a different listing', (cursor) => { expect(() => pageOf(ITEMS, { cursor })).toThrow(/different listing/) } ) + it('refuses the cursor of an equally long listing with another scope', () => { + const request = { maxChars: budgetFor(2) } + const { nextCursor } = pageOf(ITEMS, request, { ...fourEach, scope: 'a' }) + expect( + pageOf( + ITEMS, + { ...request, cursor: nextCursor }, + { ...fourEach, scope: 'a' } + ).items + ).toEqual(['cccc', 'dddd']) + expect(() => + pageOf( + ITEMS, + { ...request, cursor: nextCursor }, + { ...fourEach, scope: 'b' } + ) + ).toThrow(/different listing/) + }) + it.each([0, -3, 2.5, Number.NaN])('refuses maxChars %s', (maxChars) => { expect(() => pageOf(ITEMS, { maxChars })).toThrow(/maxChars/) }) @@ -120,3 +164,36 @@ describe('truncateText', () => { expect(truncateText(text).text).toHaveLength(DEFAULT_MAX_CHARS) }) }) + +describe('clipText', () => { + it('keeps text within the budget as it is', () => { + expect(clipText('hello', 5)).toBe('hello') + }) + + it('cuts text past the budget, the note of its length included', () => { + const text = 'x'.repeat(100) + expect(clipText(text, 40)).toBe(`${'x'.repeat(22)}… (cut, 100 chars)`) + expect(clipText(text, 40)).toHaveLength(40) + }) + + it('keeps one character and the note when the budget is shorter than the note', () => { + expect(clipText('hello world', 5)).toBe('h… (cut, 11 chars)') + }) +}) + +describe('clipValue', () => { + it('writes a value as JSON, so a string reads apart from a number', () => { + expect(clipValue('5', 10)).toBe('"5"') + expect(clipValue(5, 10)).toBe('5') + }) + + it('cuts a long value', () => { + expect(clipValue(['a'.repeat(40)], 30)).toBe( + '["aaaaaaaaaaa… (cut, 44 chars)' + ) + }) + + it('has nothing for a value with no JSON form', () => { + expect(clipValue(undefined, 10)).toBeUndefined() + }) +}) diff --git a/packages/trace-query/tests/edited-zips.test.ts b/packages/trace-query/tests/edited-zips.test.ts new file mode 100644 index 000000000..cd38bd0e5 --- /dev/null +++ b/packages/trace-query/tests/edited-zips.test.ts @@ -0,0 +1,73 @@ +// Fixture zips edited into shapes our writer never produces: a step that failed on its own, and no transcript. + +import { strFromU8, strToU8, unzipSync, zipSync } from 'fflate' +import { describe, expect, it } from 'vitest' +import { bytesZipSource } from '@wdio/devtools-trace/trace-reader' +import { traceActions } from '../src/action-list.js' +import { traceErrors } from '../src/errors.js' +import { openTraceSource } from '../src/open-trace.js' +import { traceSummary } from '../src/summary.js' +import { traceTranscript } from '../src/transcript.js' +import { fixtureBytes } from './traces.js' + +const PASSING = 'wdio-mocha-2026-10-28-14977b93.zip' +const SECOND_TEST = 'call@8' + +// A hook that throws ends its test's step with an error while every action in it passed. +function withFailedStep(callId: string, message: string): Uint8Array { + const entries = unzipSync(fixtureBytes(PASSING)) + const lines = strFromU8(entries['trace.trace']!) + .split('\n') + .map((line) => { + if (!line) { + return line + } + const event = JSON.parse(line) as Record + return event.type === 'after' && event.callId === callId + ? JSON.stringify({ ...event, error: { message } }) + : line + }) + entries['trace.trace'] = strToU8(lines.join('\n')) + return zipSync(entries) +} + +describe('a trace failed by a step alone', () => { + it('lists the step as the error and its first error', async () => { + const handle = await openTraceSource( + bytesZipSource(withFailedStep(SECOND_TEST, 'afterEach hook failed')) + ) + const summary = traceSummary(handle) + expect(summary).toMatchObject({ + outcome: 'failed', + counts: { failedActions: 0, failedSteps: 1 }, + firstError: { + kind: 'step', + callId: SECOND_TEST, + title: 'shows an error message for an invalid username', + message: 'afterEach hook failed' + } + }) + expect(traceErrors(handle).items).toEqual([summary.firstError]) + expect( + summary.tests?.find((test) => test.callId === SECOND_TEST)?.outcome + ).toBe('failed') + expect( + traceActions(handle, { group: SECOND_TEST }).items.length + ).toBeGreaterThan(0) + }) + + it('lists nothing for a passing trace', async () => { + const handle = await openTraceSource(bytesZipSource(fixtureBytes(PASSING))) + expect(traceSummary(handle).firstError).toBeUndefined() + expect(traceErrors(handle).items).toEqual([]) + }) +}) + +describe('traceTranscript', () => { + it('returns nothing for a zip that carries no transcript', async () => { + const entries = unzipSync(fixtureBytes(PASSING)) + delete entries['transcript.md'] + const handle = await openTraceSource(bytesZipSource(zipSync(entries))) + expect(traceTranscript(handle)).toBeUndefined() + }) +}) diff --git a/packages/trace-query/tests/fixture-queries.test.ts b/packages/trace-query/tests/fixture-queries.test.ts new file mode 100644 index 000000000..6d2449462 --- /dev/null +++ b/packages/trace-query/tests/fixture-queries.test.ts @@ -0,0 +1,107 @@ +// Every query over a real zip from each adapter's writer, older formats included. + +import { describe, expect, it } from 'vitest' +import { traceActionDetail } from '../src/action-detail.js' +import { traceActions } from '../src/action-list.js' +import { traceErrors } from '../src/errors.js' +import { traceStateOf } from '../src/open-trace.js' +import { DEFAULT_MAX_CHARS } from '../src/constants.js' +import { traceSummary } from '../src/summary.js' +import { traceTranscript } from '../src/transcript.js' +import type { ActionRow, TestNode } from '../src/types.js' +import { fixtures, openFixture } from './traces.js' + +function flatten(rows: readonly ActionRow[]): ActionRow[] { + return rows.flatMap((row) => [row, ...flatten(row.children ?? [])]) +} + +function leaves(nodes: readonly TestNode[]): TestNode[] { + return nodes.flatMap((node) => + node.children ? leaves(node.children) : [node] + ) +} + +describe.each(fixtures)('queries over $zipName', ({ zipName, manifest }) => { + it('summarizes the runner, browser and failures the zip records', async () => { + const summary = traceSummary(await openFixture(zipName)) + const failed = manifest.commands.failed + expect(summary).toMatchObject({ + runner: manifest.runner, + browser: manifest.browserName, + outcome: failed ? 'failed' : 'passed' + }) + expect(summary.counts.failedActions).toBe(failed) + expect(summary.firstError?.kind).toBe(failed ? 'action' : undefined) + expect(leaves(summary.tests ?? []).length).toBeGreaterThan(0) + }) + + it('lists the errors by time, each naming an action the trace holds', async () => { + const handle = await openFixture(zipName) + const { items, total } = traceErrors(handle) + expect(items).toHaveLength(total) + expect(items.map((error) => error.timeMs)).toEqual( + items.map((error) => error.timeMs).sort((a, b) => a - b) + ) + for (const error of items.filter((item) => item.callId)) { + expect(() => traceActionDetail(handle, error.callId!)).not.toThrow() + } + const failedRows = items.filter((error) => error.kind === 'action') + expect(failedRows).toHaveLength(manifest.commands.failed) + for (const error of failedRows) { + expect(traceActionDetail(handle, error.callId!).status).toBe('failed') + } + }) + + it('lists every action once, in the order they started', async () => { + const handle = await openFixture(zipName) + const { items, total, nextCursor } = traceActions(handle) + const rows = flatten(items) + expect(nextCursor).toBeUndefined() + expect(total).toBe(traceSummary(handle).counts.actions) + expect(rows).toHaveLength(manifest.commands.count) + expect(new Set(rows.map((row) => row.callId)).size).toBe(rows.length) + expect(items.map((row) => row.startMs)).toEqual( + items.map((row) => row.startMs).sort((a, b) => a - b) + ) + expect(rows.filter((row) => row.status === 'failed')).toHaveLength( + manifest.commands.failed + ) + }) + + it('details every action, with the source around its call site', async () => { + const handle = await openFixture(zipName) + const details = flatten(traceActions(handle).items).map((row) => { + const detail = traceActionDetail(handle, row.callId) + expect(detail).toMatchObject({ callId: row.callId, startMs: row.startMs }) + expect(JSON.stringify(detail).length).toBeLessThanOrEqual( + DEFAULT_MAX_CHARS + ) + return detail + }) + const withSource = details.filter((detail) => detail.source) + expect(withSource.length).toBeGreaterThan(0) + for (const { source } of withSource) { + expect(source!.filter((line) => line.startsWith('>'))).toHaveLength(1) + } + }) + + it('lists only the actions of the test it is asked for', async () => { + const handle = await openFixture(zipName) + for (const test of leaves(traceSummary(handle).tests ?? [])) { + for (const row of traceActions(handle, { group: test.callId }).items) { + expect(traceActionDetail(handle, row.callId).test?.slice(-1)).toEqual([ + test.title + ]) + } + } + }) + + it('returns the transcript the zip carries', async () => { + const handle = await openFixture(zipName) + const transcript = traceTranscript(handle) + expect(transcript?.items.join('\n')).toBe( + traceStateOf(handle).data.transcript + ) + expect(Boolean(transcript)).toBe(manifest.transcript) + }) +}) diff --git a/packages/trace-query/tests/open-trace.test.ts b/packages/trace-query/tests/open-trace.test.ts index 740d710c5..40224c418 100644 --- a/packages/trace-query/tests/open-trace.test.ts +++ b/packages/trace-query/tests/open-trace.test.ts @@ -1,32 +1,8 @@ -import { readdirSync, readFileSync } from 'node:fs' import { describe, expect, it } from 'vitest' import { bytesZipSource } from '@wdio/devtools-trace/trace-reader' -import type { TraceFormatManifest } from '../../trace/tests/fixtures/trace-formats/fixture-manifest.js' import { openTraceSource, traceStateOf } from '../src/open-trace.js' import type { TraceHandle } from '../src/types.js' - -const FIXTURE_DIR = new URL( - '../../trace/tests/fixtures/trace-formats/', - import.meta.url -) - -const fixtures = readdirSync(FIXTURE_DIR) - .filter((name) => name.endsWith('.zip')) - .map((zipName) => ({ - zipName, - manifest: JSON.parse( - readFileSync( - new URL(zipName.replace(/\.zip$/, '.json'), FIXTURE_DIR), - 'utf8' - ) - ) as TraceFormatManifest - })) - -function open(zipName: string) { - return openTraceSource( - bytesZipSource(new Uint8Array(readFileSync(new URL(zipName, FIXTURE_DIR)))) - ) -} +import { fixtures, openFixture as open } from './traces.js' describe('openTraceSource', () => { it('has a fixture to open', () => { diff --git a/packages/trace-query/tests/result-budgets.test.ts b/packages/trace-query/tests/result-budgets.test.ts new file mode 100644 index 000000000..c65fd936b --- /dev/null +++ b/packages/trace-query/tests/result-budgets.test.ts @@ -0,0 +1,199 @@ +import { describe, expect, it } from 'vitest' +import type { CommandLog } from '@wdio/devtools-shared' +import { traceActionDetail } from '../src/action-detail.js' +import { traceActions } from '../src/action-list.js' +import { traceSummary } from '../src/summary.js' +import { traceErrors } from '../src/errors.js' +import { traceTranscript } from '../src/transcript.js' +import { MIN_QUERY_CHARS } from '../src/constants.js' +import type { TraceHandle } from '../src/types.js' +import { fixtures, openFixture, openWritten } from './traces.js' + +const START = 1_700_000_000_000 +const SPEC = '/project/specs/budget.e2e.ts' +const SOURCE = Array.from({ length: 20 }, (_, i) => `line ${i + 1}`).join('\n') + +function row( + command: string, + startOffset: number, + endOffset: number, + extra: Partial = {} +): CommandLog { + return { + command, + args: [], + startTime: START + startOffset, + timestamp: START + endOffset, + ...extra + } +} + +const size = (value: unknown) => JSON.stringify(value).length + +describe('results within their budget', () => { + it('sheds a wait’s rows so every page of actions fits a small budget', async () => { + const polls = Array.from({ length: 25 }, (_, i) => + row('getText', 110 + i * 10, 115 + i * 10, { + parentId: 1, + args: [`#field-${i}`] + }) + ) + const handle = await openWritten({ + commands: [row('waitUntil', 100, 900, { id: 1 }), ...polls], + startTime: START + }) + for (const maxChars of [1_000, 1_200, 1_500]) { + const page = traceActions(handle, { maxChars }) + expect(size(page)).toBeLessThanOrEqual(maxChars) + expect(page.items[0]!.omittedChildren).toBeGreaterThan(5) + } + }) + + it('cuts the first error, then leaves the tree out, so a summary fits its budget', async () => { + const uids = Array.from({ length: 12 }, (_, i) => `t${i}`) + const handle = await openWritten({ + commands: uids.map((uid, i) => + row('click', 100 + i * 20, 110 + i * 20, { + testUid: uid, + ...(i === 0 + ? { error: { name: 'Error', message: `boom ${'x'.repeat(2_000)}` } } + : {}) + }) + ), + testMetadata: new Map( + uids.map((uid) => [ + uid, + { title: `${uid} ${'y'.repeat(80)}`, specFile: SPEC, ancestry: [] } + ]) + ), + startTime: START + }) + const whole = size(traceSummary(handle)) + expect(whole).toBeGreaterThan(1_500) + for (const maxChars of [1_000, 1_200, whole - 100]) { + const summary = traceSummary(handle, { maxChars }) + expect(size(summary)).toBeLessThanOrEqual(maxChars) + expect(summary.firstError?.message.startsWith('boom')).toBe(true) + } + }) + + it('drops the call’s own source line before cutting any value', async () => { + const handle = await openWritten({ + commands: [ + row('setValue', 100, 200, { + args: ['#field', 'v'.repeat(1_500)], + callSource: `${SPEC}:5` + }) + ], + sources: { [SPEC]: SOURCE }, + startTime: START + }) + const { callId } = traceActions(handle).items[0]! + const whole = traceActionDetail(handle, callId, { contextLines: 0 }) + expect(whole.source).toHaveLength(1) + const { source: _source, ...withoutSource } = whole + const detail = traceActionDetail(handle, callId, { + contextLines: 0, + maxChars: size(withoutSource) + }) + expect(detail.source).toBeUndefined() + expect(detail.args).toEqual(whole.args) + }) + + it(`refuses a budget below ${MIN_QUERY_CHARS} characters in every query`, async () => { + const handle = await openWritten({ + commands: [row('click', 100, 200)], + startTime: START + }) + const maxChars = MIN_QUERY_CHARS - 1 + const { callId } = traceActions(handle).items[0]! + for (const query of [ + () => traceSummary(handle, { maxChars }), + () => traceErrors(handle, { maxChars }), + () => traceActions(handle, { maxChars }), + () => traceActionDetail(handle, callId, { maxChars }), + () => traceTranscript(handle, { maxChars }) + ]) { + expect(query).toThrow(`maxChars must be at least ${MIN_QUERY_CHARS}`) + } + }) +}) + +async function hostileTrace(): Promise { + const long = (n: number) => 'x'.repeat(n) + return openWritten({ + commands: [ + row('waitUntil', 100, 900, { + id: 1, + args: [long(5_000)], + callSource: `${SPEC}:3`, + error: { name: 'Error', message: long(5_000) } + }), + ...Array.from({ length: 25 }, (_, i) => + row('getText', 110 + i * 10, 115 + i * 10, { + parentId: 1, + args: [`#${long(400)}`], + error: { name: 'Error', message: long(800) } + }) + ), + row('click', 1_000, 1_100, { + title: long(3_000), + args: [long(5_000)], + selector: long(5_000), + callSource: `${SPEC}:5`, + error: { name: 'Error', message: long(5_000) } + }) + ], + sources: { + [SPEC]: Array.from({ length: 200 }, () => long(500)).join('\n') + }, + startTime: START + }) +} + +describe('every query within every budget it accepts', () => { + it('holds on every adapter fixture and on a trace of oversized values', async () => { + const traces: [string, TraceHandle][] = [ + ['hostile', await hostileTrace()], + ...(await Promise.all( + fixtures.map( + async ({ zipName }) => + [zipName, await openFixture(zipName)] as [string, TraceHandle] + ) + )) + ] + const over: string[] = [] + for (const [name, handle] of traces) { + const callId = traceActions(handle).items[0]?.callId + for (const maxChars of [ + MIN_QUERY_CHARS, + 1_200, + 1_500, + 2_000, + 5_000, + 20_000 + ]) { + const results: [string, unknown][] = [ + ['summary', traceSummary(handle, { maxChars })], + ['errors', traceErrors(handle, { maxChars })], + ['actions', traceActions(handle, { maxChars })], + ['transcript', traceTranscript(handle, { maxChars })], + ...(callId + ? [ + ['detail', traceActionDetail(handle, callId, { maxChars })] as [ + string, + unknown + ] + ] + : []) + ] + for (const [query, result] of results) { + if (size(result ?? null) > maxChars) { + over.push(`${name} ${query} at ${maxChars}: ${size(result)}`) + } + } + } + } + expect(over).toEqual([]) + }) +}) diff --git a/packages/trace-query/tests/source-lines.test.ts b/packages/trace-query/tests/source-lines.test.ts new file mode 100644 index 000000000..eaa5add72 --- /dev/null +++ b/packages/trace-query/tests/source-lines.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from 'vitest' +import { sourceAround } from '../src/source-lines.js' + +const SOURCES = { '/spec.ts': ['a', 'b', 'c', 'd', 'e'].join('\n') } + +describe('sourceAround', () => { + it('numbers the lines around the call, marking its own', () => { + expect(sourceAround(SOURCES, '/spec.ts:2:7', 1)).toEqual([ + ' 1 | a', + '>2 | b', + ' 3 | c' + ]) + }) + + it('stops at the start and end of the file', () => { + expect(sourceAround(SOURCES, '/spec.ts:5', 3)).toEqual([ + ' 2 | b', + ' 3 | c', + ' 4 | d', + '>5 | e' + ]) + }) + + it('cuts a long line', () => { + const line = sourceAround({ '/min.js': 'x'.repeat(500) }, '/min.js:1', 0) + expect(line?.[0]).toMatch(/^>1 \| x+… \(cut, 500 chars\)$/) + }) + + it.each(['/other.ts:1', '/spec.ts', '/spec.ts:9', '/spec.ts:0'])( + 'has no lines for %s', + (callSource) => { + expect(sourceAround(SOURCES, callSource, 2)).toBeUndefined() + } + ) +}) diff --git a/packages/trace-query/tests/steps.test.ts b/packages/trace-query/tests/steps.test.ts new file mode 100644 index 000000000..e67ad032d --- /dev/null +++ b/packages/trace-query/tests/steps.test.ts @@ -0,0 +1,138 @@ +import { describe, expect, it } from 'vitest' +import { + TraceType, + type CommandLog, + type TraceActionChild, + type TraceActionGroupNode, + type TracePlayerData +} from '@wdio/devtools-shared' +import { collectErrors } from '../src/errors.js' +import { + failedBranches, + stepsFailedOnTheirOwn, + treeWithin +} from '../src/steps.js' +import type { TestNode } from '../src/types.js' + +const node = ( + title: string, + outcome: TestNode['outcome'], + children?: TestNode[] +): TestNode => ({ + callId: title, + title, + outcome, + ...(children ? { children } : {}) +}) + +const TREE: TestNode[] = [ + node('suite', 'failed', [ + node('passes', 'passed'), + node('fails', 'failed', [ + node('step ok', 'passed'), + node('step bad', 'failed') + ]), + node('empty', 'unknown') + ]), + node('other suite', 'passed', [node('a', 'passed'), node('b', 'passed')]) +] + +describe('failedBranches', () => { + it('keeps the failed branches and counts every node it leaves out', () => { + expect(failedBranches(TREE)).toEqual({ + kept: [ + node('suite', 'failed', [ + node('fails', 'failed', [node('step bad', 'failed')]) + ]) + ], + omitted: 6 + }) + }) +}) + +describe('treeWithin', () => { + it('keeps the whole tree when it fits', () => { + expect(treeWithin(TREE, 10_000)).toEqual({ kept: TREE, omitted: 0 }) + }) + + it('keeps nodes in order until the budget, serializing within it', () => { + for (const budget of [60, 150, 300]) { + const { kept, omitted } = treeWithin(TREE, budget) + expect(JSON.stringify(kept).length).toBeLessThanOrEqual(budget) + const count = (nodes: TestNode[]): number => + nodes.reduce((total, n) => total + 1 + count(n.children ?? []), 0) + expect(count(kept) + omitted).toBe(count(TREE)) + } + expect(treeWithin(TREE, 150).kept[0]?.title).toBe('suite') + }) +}) + +function step( + callId: string, + children: TraceActionChild[], + error?: string +): TraceActionGroupNode { + return { + callId, + title: callId, + startTime: 1_000, + endTime: 2_000, + children, + ...(error ? { failed: true, error } : {}) + } +} + +function playerData( + groups: TraceActionChild[], + commands: CommandLog[] = [{ command: 'click', args: [], timestamp: 1_500 }] +): TracePlayerData { + return { + trace: { + mutations: [], + logs: [], + consoleLogs: [], + networkRequests: [], + commands, + sources: {}, + metadata: { type: TraceType.Standalone } + }, + frames: [], + startTime: 1_000, + duration: 1_000, + groups + } +} + +describe('stepsFailedOnTheirOwn', () => { + it('lists only the innermost of nested steps carrying one error, once', () => { + const data = playerData([ + { + group: step( + 'wrapper', + [{ group: step('hook', [{ commandIndex: 0 }], 'hook failed') }], + 'hook failed' + ) + } + ]) + expect(stepsFailedOnTheirOwn(data, new Set()).map((s) => s.callId)).toEqual( + ['hook'] + ) + expect(collectErrors(data)).toEqual([ + expect.objectContaining({ kind: 'step', callId: 'hook' }) + ]) + }) + + it('leaves out a step whose failed row explains its error', () => { + const failed: CommandLog = { + command: 'click', + args: [], + timestamp: 1_500, + error: { name: 'Error', message: 'not found' } + } + const data = playerData( + [{ group: step('test', [{ commandIndex: 0 }], 'not found') }], + [failed] + ) + expect(stepsFailedOnTheirOwn(data, new Set())).toEqual([]) + }) +}) diff --git a/packages/trace-query/tests/traces.ts b/packages/trace-query/tests/traces.ts new file mode 100644 index 000000000..04adcb579 --- /dev/null +++ b/packages/trace-query/tests/traces.ts @@ -0,0 +1,75 @@ +// Opens the committed older-writer fixtures, and writes a trace with this checkout's writer for what no fixture holds. + +import { readdirSync, readFileSync } from 'node:fs' +import { + TraceType, + type CommandLog, + type ConsoleLog, + type NetworkRequest, + type TestMetadataMap +} from '@wdio/devtools-shared' +import { exportTraceZip } from '@wdio/devtools-trace/trace-exporter' +import { bytesZipSource } from '@wdio/devtools-trace/trace-reader' +import type { TraceFormatManifest } from '../../trace/tests/fixtures/trace-formats/fixture-manifest.js' +import { openTraceSource } from '../src/open-trace.js' +import type { TraceHandle } from '../src/types.js' + +const FIXTURE_DIR = new URL( + '../../trace/tests/fixtures/trace-formats/', + import.meta.url +) + +export const fixtures = readdirSync(FIXTURE_DIR) + .filter((name) => name.endsWith('.zip')) + .map((zipName) => ({ + zipName, + manifest: JSON.parse( + readFileSync( + new URL(zipName.replace(/\.zip$/, '.json'), FIXTURE_DIR), + 'utf8' + ) + ) as TraceFormatManifest + })) + +export function fixtureBytes(zipName: string): Uint8Array { + return new Uint8Array(readFileSync(new URL(zipName, FIXTURE_DIR))) +} + +export function openFixture(zipName: string): Promise { + return openTraceSource(bytesZipSource(fixtureBytes(zipName))) +} + +export interface WrittenRun { + commands: CommandLog[] + consoleLogs?: ConsoleLog[] + networkRequests?: NetworkRequest[] + sources?: Record + testMetadata?: TestMetadataMap + startTime: number +} + +/** A run written to a zip by this checkout's writer, then opened as a caller would. */ +export async function openWritten(run: WrittenRun): Promise { + const zip = await exportTraceZip( + { + mutations: [], + logs: [], + consoleLogs: run.consoleLogs ?? [], + networkRequests: run.networkRequests ?? [], + commands: run.commands, + sources: run.sources ?? {}, + metadata: { + type: TraceType.Testrunner, + sessionId: 'abc12345', + runner: 'mocha', + capabilities: { browserName: 'chrome' } + } + }, + { + sessionId: 'abc12345', + wallTimeOverride: run.startTime, + testMetadata: run.testMetadata + } + ) + return openTraceSource(bytesZipSource(new Uint8Array(zip))) +} diff --git a/packages/trace-query/tests/written-trace.test.ts b/packages/trace-query/tests/written-trace.test.ts new file mode 100644 index 000000000..922fedcb7 --- /dev/null +++ b/packages/trace-query/tests/written-trace.test.ts @@ -0,0 +1,513 @@ +// A run no fixture holds, written by this checkout's writer: retried and failed polls, a failed assertion, console and network failures. + +import { describe, expect, it } from 'vitest' +import type { CommandLog, NetworkRequest } from '@wdio/devtools-shared' +import { traceActionDetail } from '../src/action-detail.js' +import { traceActions } from '../src/action-list.js' +import { + DEFAULT_MAX_CHARS, + MAX_LISTED_CHILDREN, + MAX_TITLE_CHARS +} from '../src/constants.js' +import { traceErrors } from '../src/errors.js' +import { traceSummary } from '../src/summary.js' +import { traceTranscript } from '../src/transcript.js' +import type { ActionRow, TestNode, TraceHandle } from '../src/types.js' +import { openWritten } from './traces.js' + +const START = 1_700_000_000_000 +const SPEC = '/project/specs/login.e2e.ts' +const SPEC_SOURCE = Array.from({ length: 20 }, (_, i) => `line ${i + 1}`).join( + '\n' +) +const LONG_TEST = `asserts the heading ${'x'.repeat(200)}` +const LONG_SELECTOR = `#${'a'.repeat(500)}` + +const at = (offset: number) => START + offset + +function row( + command: string, + startOffset: number, + endOffset: number, + extra: Partial = {} +): CommandLog { + return { + command, + args: [], + startTime: at(startOffset), + timestamp: at(endOffset), + ...extra + } +} + +const COMMANDS: CommandLog[] = [ + row('url', 100, 400, { + args: ['http://127.0.0.1:4567/login'], + testUid: 'retries', + callSource: `${SPEC}:3` + }), + row('waitUntil', 500, 900, { id: 1, testUid: 'retries' }), + row('isDisplayed', 600, 650, { + parentId: 1, + testUid: 'retries', + error: { name: 'Error', message: 'stale element reference' } + }), + row('getText', 700, 750, { + parentId: 1, + testUid: 'retries', + result: 'x'.repeat(5_000) + }), + row('waitForDisplayed', 1_000, 2_000, { + id: 2, + args: ['#never'], + testUid: 'times-out', + error: { name: 'Error', message: 'element ("#never") still not displayed' } + }), + row('isDisplayed', 1_100, 1_150, { + parentId: 2, + testUid: 'times-out', + error: { name: 'Error', message: 'no such element' } + }), + row('isExisting', 1_200, 1_250, { + parentId: 2, + testUid: 'times-out', + result: true + }), + row('assert.equal', 2_100, 2_101, { + args: ['Login Page', 'Secure Area'], + testUid: 'asserts', + result: { passed: false, actual: 'Login Page', expected: 'Secure Area' }, + callSource: `${SPEC}:9` + }), + row('click', 2_200, 2_300, { + args: [LONG_SELECTOR], + selector: LONG_SELECTOR, + testUid: 'asserts' + }) +] + +function request( + id: string, + offset: number, + extra: Partial +): NetworkRequest { + return { + id, + url: `http://127.0.0.1:4567/${id}`, + method: 'GET', + type: 'fetch', + timestamp: at(offset), + startTime: at(offset), + endTime: at(offset + 10), + ...extra + } +} + +const TEST_METADATA = new Map( + [ + ['retries', 'retries a stale poll'], + ['times-out', 'times out'], + ['asserts', LONG_TEST] + ].map(([uid, title]) => [ + uid, + { + title, + specFile: SPEC, + ancestry: [{ uid: 'login', title: 'Login', kind: 'suite' as const }] + } + ]) +) + +function openRun(): Promise { + return openWritten({ + commands: COMMANDS, + consoleLogs: [ + { + type: 'error', + args: ['\u001b[31mUncaught TypeError\u001b[39m', { at: 'app.js' }], + timestamp: at(50), + source: 'browser' + }, + { type: 'log', args: ['ready'], timestamp: at(60), source: 'browser' } + ], + networkRequests: [ + request('ok', 150, { status: 200, statusText: 'OK' }), + // Nearer the timed-out wait's start, but issued while the passing wait was the last action started. + request('broken', 980, { status: 500, statusText: 'Server Error' }), + request('blocked', 2_150, { status: 0 }) + ], + sources: { [SPEC]: SPEC_SOURCE }, + testMetadata: TEST_METADATA, + startTime: START + }) +} + +function flattenRows(rows: readonly ActionRow[]): ActionRow[] { + return rows.flatMap((item) => [item, ...flattenRows(item.children ?? [])]) +} + +function byTitle(rows: readonly ActionRow[], prefix: string): ActionRow { + const found = flattenRows(rows).find((candidate) => + candidate.title.startsWith(prefix) + ) + expect(found, prefix).toBeDefined() + return found! +} + +const titles = (rows: readonly ActionRow[]) => + rows.map((item) => item.title.split('(')[0]) + +describe('a trace with waits and failures', () => { + it('nests a wait’s polls under it and does not fail a poll the wait retried past', async () => { + const { items } = traceActions(await openRun()) + expect(titles(items)).toEqual([ + 'Page.navigate', + 'Browser.waitForFunction', + 'Element.waitForDisplayed', + 'assert.equal', + 'Element.click' + ]) + const passingWait = byTitle(items, 'Browser.waitForFunction') + expect(passingWait.status).toBeUndefined() + expect(passingWait.children).toEqual([ + expect.objectContaining({ + status: 'retried', + error: 'stale element reference' + }), + expect.not.objectContaining({ status: expect.anything() }) + ]) + const failedWait = byTitle(items, 'Element.waitForDisplayed') + expect(failedWait.status).toBe('failed') + expect(failedWait.children).toEqual([ + expect.objectContaining({ status: 'failed', error: 'no such element' }), + expect.not.objectContaining({ status: expect.anything() }) + ]) + }) + + it('filters by status, test and time window', async () => { + const handle = await openRun() + expect(titles(traceActions(handle, { status: 'retried' }).items)).toEqual([ + 'Browser.waitForFunction' + ]) + expect(titles(traceActions(handle, { status: 'failed' }).items)).toEqual([ + 'Element.waitForDisplayed', + 'assert.equal' + ]) + expect(titles(traceActions(handle, { status: 'passed' }).items)).toEqual([ + 'Page.navigate', + 'Browser.waitForFunction', + 'Element.click' + ]) + const asserts = traceSummary(handle).tests?.[0]?.children?.[2] + expect( + titles(traceActions(handle, { group: asserts!.callId }).items) + ).toEqual(['assert.equal', 'Element.click']) + const wait = byTitle(traceActions(handle).items, 'Element.waitForDisplayed') + expect( + titles( + traceActions(handle, { + fromMs: wait.startMs + 1, + toMs: wait.startMs + 2 + }).items + ) + ).toEqual(['Element.waitForDisplayed']) + }) + + it('refuses a test it does not hold', async () => { + const handle = await openRun() + expect(() => traceActions(handle, { group: 'call@999' })).toThrow( + 'The trace has no test or step "call@999"' + ) + }) + + it('pages the action list, refusing a cursor from a differently filtered list', async () => { + const handle = await openRun() + const all = traceActions(handle).items + const first = traceActions(handle, { maxChars: 1_000 }) + expect(JSON.stringify(first).length).toBeLessThanOrEqual(1_000) + expect(first.nextCursor).toBeDefined() + const rest = traceActions(handle, { + maxChars: 100_000, + cursor: first.nextCursor + }) + const ids = (rows: ActionRow[]) => rows.map(({ callId }) => callId) + expect(ids([...first.items, ...rest.items])).toEqual(ids(all)) + expect(() => + traceActions(handle, { status: 'passed', cursor: first.nextCursor }) + ).toThrow('belongs to a different listing') + }) + + it('cuts a long title in a list, saying how long it was', async () => { + const click = byTitle(traceActions(await openRun()).items, 'Element.click') + expect(click.title).toMatch(/… \(cut, \d+ chars\)$/) + expect(click.title.length).toBeLessThanOrEqual(MAX_TITLE_CHARS) + }) + + it('lists each failure once, by start, each console line and request naming the action last started', async () => { + const handle = await openRun() + const callIdOf = (prefix: string) => + byTitle(traceActions(handle).items, prefix).callId + expect(traceErrors(handle).items).toEqual([ + { + kind: 'console', + timeMs: 50, + message: 'Uncaught TypeError {"at":"app.js"}' + }, + expect.objectContaining({ + kind: 'request', + timeMs: 980, + callId: callIdOf('Browser.waitForFunction'), + message: 'HTTP 500 Server Error', + method: 'GET', + status: 500 + }), + expect.objectContaining({ + kind: 'action', + timeMs: 1_000, + callId: callIdOf('Element.waitForDisplayed'), + message: 'element ("#never") still not displayed' + }), + expect.objectContaining({ + kind: 'action', + timeMs: 2_100, + message: 'Assertion failed' + }), + expect.objectContaining({ + kind: 'request', + callId: callIdOf('assert.equal'), + message: 'No response', + status: 0 + }) + ]) + }) + + it('summarizes the run, its first failed action and each test’s outcome', async () => { + const summary = traceSummary(await openRun()) + expect(summary).toMatchObject({ + runner: 'mocha', + browser: 'chrome', + outcome: 'failed', + counts: { + actions: 5, + failedActions: 2, + failedSteps: 0, + consoleErrors: 1, + failedRequests: 2 + }, + firstError: { + kind: 'action', + message: 'element ("#never") still not displayed' + } + }) + const [suite] = summary.tests! + expect(suite).toMatchObject({ title: 'Login', outcome: 'failed' }) + expect(suite!.children!.map(({ outcome }) => outcome)).toEqual([ + 'passed', + 'failed', + 'failed' + ]) + const longTitle = suite!.children![2]!.title + expect(longTitle).toMatch(/^asserts the heading x+… \(cut, 220 chars\)$/) + expect(longTitle.length).toBeLessThanOrEqual(MAX_TITLE_CHARS) + }) + + it('keeps only the failed tests, as many as fit, when the tree outgrows the budget', async () => { + const uids = Array.from({ length: 40 }, (_, i) => `t${i}`) + const handle = await openWritten({ + commands: uids.map((uid, i) => + row('click', 100 + i * 20, 110 + i * 20, { + testUid: uid, + ...(i % 4 === 0 + ? { error: { name: 'Error', message: 'no such element' } } + : {}) + }) + ), + testMetadata: new Map( + uids.map((uid) => [ + uid, + { + title: `${uid} ${'checks a long named behaviour '.repeat(3)}`, + specFile: SPEC, + ancestry: [{ uid: 'suite', title: 'Suite', kind: 'suite' as const }] + } + ]) + ), + startTime: START + }) + const outcomes = (tests: TestNode[] = []): string[] => + tests.flatMap((node) => [node.outcome, ...outcomes(node.children)]) + const full = JSON.stringify(traceSummary(handle).tests).length + const roomy = traceSummary(handle, { maxChars: 2 * full - 2 }) + expect(outcomes(roomy.tests).every((outcome) => outcome === 'failed')).toBe( + true + ) + expect(roomy.omittedTests).toBe(30) + const tight = traceSummary(handle, { maxChars: 1_000 }) + expect(JSON.stringify(tight).length).toBeLessThanOrEqual(1_000) + expect(JSON.stringify(tight.tests ?? []).length).toBeLessThanOrEqual(500) + expect(tight.omittedTests).toBeGreaterThan(30) + }) + + it('refuses a bad budget even with no tests to bound', async () => { + const handle = await openRun() + expect(() => traceSummary(handle, { maxChars: 0 })).toThrow('maxChars') + }) + + it('details a failed assertion with expected, actual and its source lines', async () => { + const handle = await openRun() + const { callId } = byTitle(traceActions(handle).items, 'assert.equal') + const detail = traceActionDetail(handle, callId, { contextLines: 1 }) + expect(detail).toMatchObject({ + callId, + title: 'assert.equal("Login Page", "Secure Area")', + command: 'assert.equal', + startMs: 2_100, + durationMs: 1, + status: 'failed', + args: '["Login Page","Secure Area"]', + error: { + message: 'Assertion failed', + expected: '"Secure Area"', + actual: '"Login Page"' + }, + callSite: `${SPEC}:9`, + source: [' 8 | line 8', '> 9 | line 9', ' 10 | line 10'] + }) + expect(detail.result).toBeUndefined() + expect(detail.test?.[0]).toBe('Login') + expect(detail.test?.[1]?.length).toBeLessThanOrEqual(MAX_TITLE_CHARS) + }) + + it('names a poll’s wait and a wait’s polls, cutting a long result and selector', async () => { + const handle = await openRun() + const { items } = traceActions(handle) + const wait = byTitle(items, 'Browser.waitForFunction') + const [poll, read] = wait.children! + expect(traceActionDetail(handle, wait.callId).children).toEqual([ + poll!.callId, + read!.callId + ]) + expect(traceActionDetail(handle, poll!.callId)).toMatchObject({ + status: 'retried', + parent: wait.callId, + error: { message: 'stale element reference' } + }) + expect(traceActionDetail(handle, read!.callId).result).toMatch( + /^"x+… \(cut, 5002 chars\)$/ + ) + const click = traceActionDetail( + handle, + byTitle(items, 'Element.click').callId + ) + expect(click.selector).toMatch(/^#a+… \(cut, 501 chars\)$/) + }) + + it('cuts a detail to the budget it is given', async () => { + const handle = await openRun() + const read = byTitle(traceActions(handle).items, 'Element.getText') + expect( + JSON.stringify(traceActionDetail(handle, read.callId)).length + ).toBeGreaterThan(1_000) + const small = traceActionDetail(handle, read.callId, { maxChars: 1_000 }) + expect(JSON.stringify(small).length).toBeLessThanOrEqual(1_000) + expect(small.result).toMatch(/… \(cut, 5002 chars\)$/) + }) + + it('drops source lines before it cuts any field', async () => { + const handle = await openWritten({ + commands: [ + row('assert.equal', 100, 200, { + args: ['a'.repeat(700), 'b'.repeat(700)], + callSource: `${SPEC}:9` + }) + ], + sources: { [SPEC]: SPEC_SOURCE }, + startTime: START + }) + const { callId } = traceActions(handle).items[0]! + const oneLine = traceActionDetail(handle, callId, { contextLines: 1 }) + const noLines = traceActionDetail(handle, callId, { contextLines: 0 }) + const fit = (maxChars: number) => + traceActionDetail(handle, callId, { contextLines: 3, maxChars }) + expect(fit(JSON.stringify(oneLine).length)).toEqual(oneLine) + expect(fit(JSON.stringify(noLines).length)).toEqual(noLines) + }) + + it('keeps the largest detail within the default budget', async () => { + const huge = 'y'.repeat(30_000) + const handle = await openWritten({ + commands: [ + row('assert.equal', 100, 200, { + title: huge, + args: [huge, huge], + selector: huge, + result: { passed: false, actual: huge, expected: huge }, + callSource: `${SPEC}:9` + }) + ], + sources: { [SPEC]: Array.from({ length: 20 }, () => huge).join('\n') }, + startTime: START + }) + const { callId } = traceActions(handle).items[0]! + const detail = traceActionDetail(handle, callId, { contextLines: 50 }) + expect(JSON.stringify(detail).length).toBeLessThanOrEqual(DEFAULT_MAX_CHARS) + expect(detail.source?.length).toBeGreaterThan(0) + }) + + it('lists the first of many rows a wait issued, counting the rest', async () => { + const polls = Array.from({ length: MAX_LISTED_CHILDREN + 5 }, (_, i) => + row('getText', 110 + i * 10, 115 + i * 10, { + parentId: 1, + args: [`#field-${i}`] + }) + ) + const handle = await openWritten({ + commands: [row('waitUntil', 100, 900, { id: 1 }), ...polls], + startTime: START + }) + const [wait] = traceActions(handle).items + expect(wait!.children).toHaveLength(MAX_LISTED_CHILDREN) + expect(wait!.omittedChildren).toBe(5) + expect(traceActionDetail(handle, wait!.callId)).toMatchObject({ + children: wait!.children!.map(({ callId }) => callId), + omittedChildren: 5 + }) + }) + + it('refuses an action, a context or a budget it cannot serve', async () => { + const handle = await openRun() + expect(() => traceActionDetail(handle, 'call@999')).toThrow( + 'The trace has no action "call@999"' + ) + const { callId } = traceActions(handle).items[0]! + expect(() => + traceActionDetail(handle, callId, { contextLines: -1 }) + ).toThrow('contextLines must be an integer') + expect(() => traceActionDetail(handle, callId, { maxChars: 0 })).toThrow( + 'maxChars' + ) + }) + + it('pages the transcript by line, each page within its budget', async () => { + const handle = await openWritten({ + commands: Array.from({ length: 30 }, (_, i) => + row('url', 100 + i * 20, 110 + i * 20, { + args: [`http://127.0.0.1:4567/${'p'.repeat(i === 3 ? 3_000 : 40)}`] + }) + ), + startTime: START + }) + const whole = traceTranscript(handle)!.items + expect(JSON.stringify(whole).length).toBeGreaterThan(2_000) + const lines: string[] = [] + let cursor: string | undefined + do { + const page = traceTranscript(handle, { maxChars: 1_000, cursor })! + expect(JSON.stringify(page).length).toBeLessThanOrEqual(1_000) + lines.push(...page.items) + cursor = page.nextCursor + } while (cursor) + expect(lines).toHaveLength(whole.length) + expect(lines.some((line) => /… \(cut, \d+ chars\)$/.test(line))).toBe(true) + }) +}) diff --git a/packages/trace/src/trace-reader-constants.ts b/packages/trace/src/trace-reader-constants.ts index a3c23b8f3..c9ce91523 100644 --- a/packages/trace/src/trace-reader-constants.ts +++ b/packages/trace/src/trace-reader-constants.ts @@ -43,3 +43,7 @@ export const REVERSE_ACTION_MAP: Record = { ]) ) } + +/** What a command's error reads as when the zip records an error without a string message. */ +export const UNREADABLE_ERROR_MESSAGE = + 'The trace records an error without a readable message' diff --git a/packages/trace/src/trace-reader-groups.ts b/packages/trace/src/trace-reader-groups.ts index efadf786b..4423c49c4 100644 --- a/packages/trace/src/trace-reader-groups.ts +++ b/packages/trace/src/trace-reader-groups.ts @@ -14,6 +14,7 @@ import type { import { REVERSE_ACTION_MAP } from './trace-reader-constants.js' import type { AfterEvent, BeforeEvent } from './trace-reader-types.js' +import { errorMessageOf } from './trace-reader-utils.js' /** An action in our vocabulary that other actions name as parentId issued them, so it stays a row; a foreign runner * step is never one. */ @@ -135,6 +136,10 @@ function buildGroupNodes( } if (after?.error) { node.failed = true + const message = errorMessageOf(after.error) + if (message !== undefined) { + node.error = message + } } nodes.set(before.callId, node) } diff --git a/packages/trace/src/trace-reader-utils.ts b/packages/trace/src/trace-reader-utils.ts index 476933d98..d8daa4c5c 100644 --- a/packages/trace/src/trace-reader-utils.ts +++ b/packages/trace/src/trace-reader-utils.ts @@ -368,3 +368,10 @@ export function buildMetadata(ctx: ContextOptionsEvent | undefined): Metadata { ...(device ? { device } : {}) } } + +/** An after event's error message when it is a string; a zip is untrusted input and may carry any value there. */ +export function errorMessageOf( + error: { message?: unknown } | undefined +): string | undefined { + return typeof error?.message === 'string' ? error.message : undefined +} diff --git a/packages/trace/src/trace-reader.ts b/packages/trace/src/trace-reader.ts index c04d5d0ba..fe20180fd 100644 --- a/packages/trace/src/trace-reader.ts +++ b/packages/trace/src/trace-reader.ts @@ -41,7 +41,8 @@ import { NETWORK_STREAM_SUFFIX, REVERSE_ACTION_MAP, STACKS_STREAM_SUFFIX, - TRACE_STREAM_SUFFIX + TRACE_STREAM_SUFFIX, + UNREADABLE_ERROR_MESSAGE } from './trace-reader-constants.js' import type { AfterEvent, @@ -68,6 +69,7 @@ import { buildConsoleLogs, buildMetadata, buildSources, + errorMessageOf, harToNetworkRequest, paramsToArgs, responseBodyEntry, @@ -232,7 +234,10 @@ function reconstructCommand( } const error = commandError(before, after, afters) if (error) { - command.error = { name: 'Error', message: error.message } + command.error = { + name: 'Error', + message: errorMessageOf(error) ?? UNREADABLE_ERROR_MESSAGE + } } if (after?.result !== undefined) { command.result = after.result diff --git a/packages/trace/tests/trace-reader.test.ts b/packages/trace/tests/trace-reader.test.ts index 6cf8ee3c0..06f95855a 100644 --- a/packages/trace/tests/trace-reader.test.ts +++ b/packages/trace/tests/trace-reader.test.ts @@ -871,9 +871,58 @@ describe('parseTraceZip with a foreign multi-stream zip', () => { expect(step.failed).toBe(true) expect(fixture.failed).toBe(true) expect(hook.failed).toBe(true) + expect(step.error).toBe('wrapped failure') + expect(fixture.error).toBeUndefined() }) }) +describe('a malformed error in a zip', () => { + const zipWithErrors = (error: unknown): Uint8Array => + zipSync({ + 'trace.trace': toNdjson([ + { + type: 'context-options', + wallTime: WALL_TIME, + browserName: 'chrome', + contextId: 'context@abcd1234' + }, + { + type: 'before', + callId: 'call@1', + startTime: 10, + class: 'Tracing', + method: 'tracingGroup', + title: 'logs in', + params: {} + }, + { + type: 'before', + callId: 'call@2', + parentId: 'call@1', + startTime: 20, + class: 'Element', + method: 'click', + params: {} + }, + { type: 'after', callId: 'call@2', endTime: 30, error }, + { type: 'after', callId: 'call@1', endTime: 40, error } + ]) + }) + + it.each([{}, { message: 42 }])( + 'keeps the failure of %j but no message that is not a string', + (error) => { + const { trace, groups } = parseTraceZip(zipWithErrors(error)) + expect(trace.commands[0]?.error?.message).toBe( + 'The trace records an error without a readable message' + ) + const [step] = allGroups(groups ?? []) + expect(step?.failed).toBe(true) + expect(step).not.toHaveProperty('error') + } + ) +}) + describe('glued callSource recovery from older zips', () => { it('recovers the line glued onto the file path', () => { expect(