Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
chore(trace): remove context attribution from the trace model (#42208)
Pavel Feldmana2b1ade0dc6b
diff --git a/packages/isomorphic/trace/entries.ts b/packages/isomorphic/trace/entries.tsindex 91fb093258..71e2f2bfd4 100644--- a/packages/isomorphic/trace/entries.ts+++ b/packages/isomorphic/trace/entries.ts@@ -29,6 +29,7 @@ export type ContextEntry = {platform?: string;playwrightVersion?: string;wallTime: number;+ monotonicTime: number;sdkLanguage?: Language;testIdAttributeName?: string;title?: string;@@ -40,7 +41,6 @@ export type ContextEntry = {stdio: trace.StdioTraceEvent[];errors: trace.ErrorTraceEvent[];hasSource: boolean;- contextId: string;testTimeout?: number;annotations?: trace.TraceEventAnnotation[];};diff --git a/packages/isomorphic/trace/snapshotStorage.ts b/packages/isomorphic/trace/snapshotStorage.tsindex 28eb3eedae..d71407146b 100644--- a/packages/isomorphic/trace/snapshotStorage.ts+++ b/packages/isomorphic/trace/snapshotStorage.ts@@ -27,15 +27,15 @@ export class SnapshotStorage {renderers: SnapshotRenderer[],}>();private _cache = new LRUCache<SnapshotRenderer, string>(100_000_000); // 100MB per each trace- private _contextToResources = new Map<string, ResourceSnapshot[]>();+ private _resources: ResourceSnapshot[] = [];private _resourceUrlsWithOverrides = new Set<string>();- addResource(contextId: string, resource: ResourceSnapshot): void {+ addResource(resource: ResourceSnapshot): void {resource.request.url = rewriteURLForCustomProtocol(resource.request.url);- this._ensureResourcesForContext(contextId).push(resource);+ this._resources.push(resource);}- addFrameSnapshot(contextId: string, snapshot: FrameSnapshot, screencastFrames: PageEntry['screencastFrames']) {+ addFrameSnapshot(snapshot: FrameSnapshot, screencastFrames: PageEntry['screencastFrames']) {for (const override of snapshot.resourceOverrides)override.url = rewriteURLForCustomProtocol(override.url);let frameSnapshots = this._frameSnapshots.get(snapshot.frameId);@@ -49,8 +49,7 @@ export class SnapshotStorage {this._frameSnapshots.set(snapshot.pageId, frameSnapshots);}frameSnapshots.raw.push(snapshot);- const resources = this._ensureResourcesForContext(contextId);- const renderer = new SnapshotRenderer(this._cache, resources, frameSnapshots.raw, screencastFrames, frameSnapshots.raw.length - 1);+ const renderer = new SnapshotRenderer(this._cache, this._resources, frameSnapshots.raw, screencastFrames, frameSnapshots.raw.length - 1);frameSnapshots.renderers.push(renderer);return renderer;}@@ -66,8 +65,7 @@ export class SnapshotStorage {finalize() {// Resources are not necessarily sorted in the trace file, so sort them now.- for (const resources of this._contextToResources.values())- resources.sort((a, b) => (a._monotonicTime || 0) - (b._monotonicTime || 0));+ this._resources.sort((a, b) => (a._monotonicTime || 0) - (b._monotonicTime || 0));// Resources that have overrides should not be cached, otherwise we might get stale content// while serving snapshots with different override values.for (const frameSnapshots of this._frameSnapshots.values()) {@@ -81,13 +79,4 @@ export class SnapshotStorage {hasResourceOverride(url: string) {return this._resourceUrlsWithOverrides.has(url);}-- private _ensureResourcesForContext(contextId: string): ResourceSnapshot[] {- let resources = this._contextToResources.get(contextId);- if (!resources) {- resources = [];- this._contextToResources.set(contextId, resources);- }- return resources;- }}diff --git a/packages/isomorphic/trace/traceLoader.ts b/packages/isomorphic/trace/traceLoader.tsindex a8a3a1b088..777bfbcc5f 100644--- a/packages/isomorphic/trace/traceLoader.ts+++ b/packages/isomorphic/trace/traceLoader.ts@@ -139,6 +139,7 @@ function createEmptyContext(): ContextEntry {origin: 'testRunner',startTime: Number.MAX_SAFE_INTEGER,wallTime: Number.MAX_SAFE_INTEGER,+ monotonicTime: 0,endTime: 0,browserName: '',options: {@@ -153,6 +154,5 @@ function createEmptyContext(): ContextEntry {errors: [],stdio: [],hasSource: false,- contextId: '',};}diff --git a/packages/isomorphic/trace/traceModel.ts b/packages/isomorphic/trace/traceModel.tsindex eaa75073bf..e1a37b04ed 100644--- a/packages/isomorphic/trace/traceModel.ts+++ b/packages/isomorphic/trace/traceModel.ts@@ -23,11 +23,8 @@ import type { ActionTraceEvent } from '@trace/trace';import type { ActionEntry, ContextEntry, PageEntry } from './entries';import type { ActionGroup } from '../protocolFormatter';-const contextSymbol = Symbol('context');-const nextInContextSymbol = Symbol('nextInContext');const prevByEndTimeSymbol = Symbol('prevByEndTime');const nextByStartTimeSymbol = Symbol('nextByStartTime');-const eventsSymbol = Symbol('events');export type SourceLocation = {file: string;@@ -41,21 +38,17 @@ export type SourceModel = {content: string | undefined;};-export type ResourceEntry = ResourceSnapshot & { id: string };--export type ActionTraceEventInContext = ActionEntry & {- context: ContextEntry;-};+export type ResourceEntry = ResourceSnapshot & { id: string, contextTitle: string };export type ActionTreeItem = {id: string;children: ActionTreeItem[];parent: ActionTreeItem | undefined;- action: ActionTraceEventInContext;+ action: ActionEntry;};export type ErrorDescription = {- action?: ActionTraceEventInContext;+ action?: ActionEntry;stack?: trace.StackFrame[];message: string;};@@ -73,7 +66,7 @@ export class TraceModel {readonly title?: string;readonly options: trace.BrowserContextEventOptions;readonly pages: PageEntry[];- readonly actions: ActionTraceEventInContext[];+ readonly actions: ActionEntry[];readonly attachments: Attachment[];readonly visibleAttachments: Attachment[];readonly events: (trace.EventTraceEvent | trace.ConsoleMessageTraceEvent)[];@@ -91,10 +84,9 @@ export class TraceModel {readonly testTimeout?: number;readonly annotations?: trace.TraceEventAnnotation[];readonly pagerefToTitle = new Map<string, string>();- readonly contextToTitle = new Map<ContextEntry, string>();+ private _eventsForAction = new Map<ActionEntry, (trace.EventTraceEvent | trace.ConsoleMessageTraceEvent)[]>();constructor(traceUri: string, contexts: ContextEntry[]) {- contexts.forEach(contextEntry => indexModel(contextEntry));const libraryContext = contexts.find(context => context.origin === 'library');this.traceUri = traceUri;@@ -119,19 +111,18 @@ export class TraceModel {this.errors = ([] as trace.ErrorTraceEvent[]).concat(...contexts.map(c => c.errors));this.hasSource = contexts.some(c => c.hasSource);this.hasStepData = contexts.some(context => context.origin === 'testRunner');- this.resources = [...contexts.map(c => c.resources)].flat().map(entry => ({ ...entry, id: `${entry.pageref}-${entry.startedDateTime}-${entry.request.url}` }));- this.attachments = this.actions.flatMap(action => action.attachments?.map(attachment => ({ ...attachment, callId: action.callId, traceUri })) ?? []);- this.visibleAttachments = this.attachments.filter(attachment => !attachment.name.startsWith('_'));-- this.pages.forEach((page, index) => this.pagerefToTitle.set(page.pageId, 'page#' + (index + 1)));+ this.resources = [];let lastApiContextId = 0;let lastBrowserContextId = 0;for (const context of contexts) {- if (context.resources.some(resource => resource._apiRequest))- this.contextToTitle.set(context, 'api#' + (++lastApiContextId));- else- this.contextToTitle.set(context, 'browser#' + (++lastBrowserContextId));+ const contextTitle = context.resources.some(resource => resource._apiRequest) ? 'api#' + (++lastApiContextId) : 'browser#' + (++lastBrowserContextId);+ for (const entry of context.resources)+ this.resources.push({ ...entry, id: `${entry.pageref ?? lastApiContextId}-${entry.startedDateTime}-${entry.request.url}`, contextTitle });}+ this.attachments = this.actions.flatMap(action => action.attachments?.map(attachment => ({ ...attachment, callId: action.callId, traceUri })) ?? []);+ this.visibleAttachments = this.attachments.filter(attachment => !attachment.name.startsWith('_'));++ this.pages.forEach((page, index) => this.pagerefToTitle.set(page.pageId, 'page#' + (index + 1)));this.events.sort((a1, a2) => a1.time - a2.time);this.resources.sort((a1, a2) => a1._monotonicTime! - a2._monotonicTime!);@@ -157,6 +148,38 @@ export class TraceModel {return this.actions.findLast(a => a.error);}+ eventsForAction(action: ActionEntry): (trace.EventTraceEvent | trace.ConsoleMessageTraceEvent)[] {+ let result = this._eventsForAction.get(action);+ if (result)+ return result;++ let nextAction = nextActionByStartTime(action);+ while (nextAction && nextAction.class === 'Route')+ nextAction = nextActionByStartTime(nextAction);+ result = this.events.filter(event => {+ return event.time >= action.startTime && (!nextAction || event.time < nextAction.startTime);+ });+ this._eventsForAction.set(action, result);+ return result;+ }++ stats(action: ActionEntry): { errors: number, warnings: number } {+ let errors = 0;+ let warnings = 0;+ for (const event of this.eventsForAction(action)) {+ if (event.type === 'console') {+ const type = event.messageType;+ if (type === 'warning')+ ++warnings;+ else if (type === 'error')+ ++errors;+ }+ if (event.type === 'event' && event.method === 'pageError')+ ++errors;+ }+ return { errors, warnings };+ }+filteredActions(actionsFilter: ActionGroup[]) {const filter = new Set<string>(actionsFilter);return this.actions.filter(action => !action.group || filter.has(action.group));@@ -198,30 +221,8 @@ export class TraceModel {}}-function indexModel(context: ContextEntry) {- for (const page of context.pages)- (page as any)[contextSymbol] = context;- for (let i = 0; i < context.actions.length; ++i) {- const action = context.actions[i] as any;- action[contextSymbol] = context;- }- let lastNonRouteAction = undefined;- for (let i = context.actions.length - 1; i >= 0; i--) {- const action = context.actions[i] as ActionTraceEvent;- (action as any)[nextInContextSymbol] = lastNonRouteAction;- if (action.class !== 'Route')- lastNonRouteAction = action;- }- for (const event of context.events)- (event as any)[contextSymbol] = context;- for (const resource of context.resources)- (resource as any)[contextSymbol] = context;-}-function mergeActionsAndUpdateTiming(contexts: ContextEntry[]) {- const result: ActionTraceEventInContext[] = [];- const actions = mergeActionsAndUpdateTimingSameTrace(contexts);- result.push(...actions);+ const result = mergeActionsAndUpdateTimingSameTrace(contexts);result.sort((a1, a2) => {if (a2.parentId === a1.callId)@@ -250,8 +251,8 @@ function mergeActionsAndUpdateTiming(contexts: ContextEntry[]) {let lastTmpStepId = 0;-function mergeActionsAndUpdateTimingSameTrace(contexts: ContextEntry[]): ActionTraceEventInContext[] {- const map = new Map<string, ActionTraceEventInContext>();+function mergeActionsAndUpdateTimingSameTrace(contexts: ContextEntry[]): ActionEntry[] {+ const map = new Map<string, ActionEntry>();const libraryContexts = contexts.filter(context => context.origin === 'library');const testRunnerContexts = contexts.filter(context => context.origin === 'testRunner');@@ -259,25 +260,24 @@ function mergeActionsAndUpdateTimingSameTrace(contexts: ContextEntry[]): ActionT// With library-only or test-runner-only traces there is nothing to match.if (!testRunnerContexts.length || !libraryContexts.length) {return contexts.map(context => {- return context.actions.map(action => ({ ...action, context }));+ return context.actions.map(action => ({ ...action }));}).flat();}+ const timeOrigin = (context: ContextEntry) => context.wallTime - context.monotonicTime;+ const runnerContext = testRunnerContexts.find(context => context.monotonicTime);+ for (const context of libraryContexts) {+ if (runnerContext && context.monotonicTime)+ adjustMonotonicTime(context, timeOrigin(context) - timeOrigin(runnerContext));+ }+for (const context of libraryContexts) {for (const action of context.actions) {// Never merge stepless events.- map.set(action.stepId || `tmp-step@${++lastTmpStepId}`, { ...action, context });+ map.set(action.stepId || `tmp-step@${++lastTmpStepId}`, { ...action });}}- // Protocol call aka library contexts have startTime/endTime as server-side times.- // Step aka test runner contexts have startTime/endTime as client-side times.- // Adjust startTime/endTime on the library contexts to align them with the test- // runner steps.- const delta = monotonicTimeDeltaBetweenLibraryAndRunner(testRunnerContexts, map);- if (delta)- adjustMonotonicTime(libraryContexts, delta);-const nonPrimaryIdToPrimaryId = new Map<string, string>();for (const context of testRunnerContexts) {for (const action of context.actions) {@@ -302,56 +302,39 @@ function mergeActionsAndUpdateTimingSameTrace(contexts: ContextEntry[]): ActionT}if (action.parentId)action.parentId = nonPrimaryIdToPrimaryId.get(action.parentId) ?? action.parentId;- map.set(action.stepId || `tmp-step@${++lastTmpStepId}`, { ...action, context });+ map.set(action.stepId || `tmp-step@${++lastTmpStepId}`, { ...action });}}return [...map.values()];}-function adjustMonotonicTime(contexts: ContextEntry[], monotonicTimeDelta: number) {- for (const context of contexts) {- context.startTime += monotonicTimeDelta;- context.endTime += monotonicTimeDelta;- for (const action of context.actions) {- if (action.startTime)- action.startTime += monotonicTimeDelta;- if (action.endTime)- action.endTime += monotonicTimeDelta;- }- for (const event of context.events)- event.time += monotonicTimeDelta;- for (const event of context.stdio)- event.timestamp += monotonicTimeDelta;- for (const page of context.pages) {- for (const frame of page.screencastFrames)- frame.timestamp += monotonicTimeDelta;- }- for (const resource of context.resources) {- if (resource._monotonicTime)- resource._monotonicTime += monotonicTimeDelta;- }+function adjustMonotonicTime(context: ContextEntry, monotonicTimeDelta: number) {+ if (!monotonicTimeDelta)+ return;+ context.startTime += monotonicTimeDelta;+ context.endTime += monotonicTimeDelta;+ context.monotonicTime += monotonicTimeDelta;+ for (const action of context.actions) {+ if (action.startTime)+ action.startTime += monotonicTimeDelta;+ if (action.endTime)+ action.endTime += monotonicTimeDelta;}-}--function monotonicTimeDeltaBetweenLibraryAndRunner(nonPrimaryContexts: ContextEntry[], libraryActions: Map<string, ActionTraceEventInContext>) {- // We cannot rely on wall time or monotonic time to be the in sync- // between library and test runner contexts. So we find first action- // that is present in both runner and library contexts and use it- // to calculate the time delta, assuming the two events happened at the- // same instant.- for (const context of nonPrimaryContexts) {- for (const action of context.actions) {- if (!action.startTime)- continue;- const libraryAction = action.stepId ? libraryActions.get(action.stepId) : undefined;- if (libraryAction)- return action.startTime - libraryAction.startTime;- }+ for (const event of context.events)+ event.time += monotonicTimeDelta;+ for (const event of context.stdio)+ event.timestamp += monotonicTimeDelta;+ for (const page of context.pages) {+ for (const frame of page.screencastFrames)+ frame.timestamp += monotonicTimeDelta;+ }+ for (const resource of context.resources) {+ if (resource._monotonicTime)+ resource._monotonicTime += monotonicTimeDelta;}- return 0;}-export function buildActionTree(actions: ActionTraceEventInContext[]): { rootItem: ActionTreeItem, itemMap: Map<string, ActionTreeItem> } {+export function buildActionTree(actions: ActionEntry[]): { rootItem: ActionTreeItem, itemMap: Map<string, ActionTreeItem> } {const itemMap = new Map<string, ActionTreeItem>();for (const action of actions) {@@ -383,14 +366,6 @@ export function buildActionTree(actions: ActionTraceEventInContext[]): { rootItereturn { rootItem, itemMap };}-export function context(action: ActionTraceEvent | trace.EventTraceEvent | ResourceSnapshot): ContextEntry {- return (action as any)[contextSymbol];-}--function nextInContext(action: ActionTraceEvent): ActionTraceEvent {- return (action as any)[nextInContextSymbol];-}-export function previousActionByEndTime(action: ActionTraceEvent): ActionTraceEvent {return (action as any)[prevByEndTimeSymbol];}@@ -399,36 +374,6 @@ export function nextActionByStartTime(action: ActionTraceEvent): ActionTraceEvenreturn (action as any)[nextByStartTimeSymbol];}-export function stats(action: ActionTraceEvent): { errors: number, warnings: number } {- let errors = 0;- let warnings = 0;- for (const event of eventsForAction(action)) {- if (event.type === 'console') {- const type = event.messageType;- if (type === 'warning')- ++warnings;- else if (type === 'error')- ++errors;- }- if (event.type === 'event' && event.method === 'pageError')- ++errors;- }- return { errors, warnings };-}--export function eventsForAction(action: ActionTraceEvent): (trace.EventTraceEvent | trace.ConsoleMessageTraceEvent)[] {- let result: (trace.EventTraceEvent | trace.ConsoleMessageTraceEvent)[] = (action as any)[eventsSymbol];- if (result)- return result;-- const nextAction = nextInContext(action);- result = context(action).events.filter(event => {- return event.time >= action.startTime && (!nextAction || event.time < nextAction.startTime);- });- (action as any)[eventsSymbol] = result;- return result;-}-function collectSources(actions: trace.ActionTraceEvent[], errorDescriptors: ErrorDescription[]): Map<string, SourceModel> {const result = new Map<string, SourceModel>();for (const action of actions) {@@ -453,7 +398,7 @@ function collectSources(actions: trace.ActionTraceEvent[], errorDescriptors: Errreturn result;}-const kFakeRootAction: ActionTraceEventInContext = {+const kFakeRootAction: ActionEntry = {type: 'action',callId: '',startTime: 0,@@ -462,20 +407,4 @@ const kFakeRootAction: ActionTraceEventInContext = {method: '',params: {},log: [],- context: {- origin: 'library',- startTime: 0,- endTime: 0,- browserName: '',- wallTime: 0,- options: {},- pages: [],- resources: [],- actions: [],- events: [],- stdio: [],- errors: [],- hasSource: false,- contextId: '',- },};diff --git a/packages/isomorphic/trace/traceModernizer.ts b/packages/isomorphic/trace/traceModernizer.tsindex 5b3a43b8bf..a1ddaf3dd2 100644--- a/packages/isomorphic/trace/traceModernizer.ts+++ b/packages/isomorphic/trace/traceModernizer.ts@@ -93,11 +93,11 @@ export class TraceModernizer {contextEntry.platform = event.platform;contextEntry.playwrightVersion = event.playwrightVersion;contextEntry.wallTime = event.wallTime;+ contextEntry.monotonicTime = event.monotonicTime;contextEntry.startTime = event.monotonicTime;contextEntry.sdkLanguage = event.sdkLanguage;contextEntry.options = event.options;contextEntry.testIdAttributeName = event.testIdAttributeName;- contextEntry.contextId = event.contextId ?? '';contextEntry.testTimeout = event.testTimeout;contextEntry.annotations = event.annotations;break;@@ -164,11 +164,11 @@ export class TraceModernizer {break;}case 'resource-snapshot':- this._snapshotStorage.addResource(this._contextEntry.contextId, event.snapshot);+ this._snapshotStorage.addResource(event.snapshot);contextEntry.resources.push(event.snapshot);break;case 'frame-snapshot':- this._snapshotStorage.addFrameSnapshot(this._contextEntry.contextId, event.snapshot, this._pageEntry(event.snapshot.pageId).screencastFrames);+ this._snapshotStorage.addFrameSnapshot(event.snapshot, this._pageEntry(event.snapshot.pageId).screencastFrames);break;}// Make sure there is a page entry for each page, even without screencast frames,@@ -446,9 +446,10 @@ export class TraceModernizer {continue;}if (event.type === 'before' || event.type === 'action') {- // Take wall and monotonic time from the first event.- if (!this._contextEntry.wallTime)+ if (!this._contextEntry.monotonicTime) {+ this._contextEntry.monotonicTime = (event as traceV6.BeforeActionTraceEvent).startTime;this._contextEntry.wallTime = event.wallTime;+ }const eventAsV6 = event as traceV6.BeforeActionTraceEvent;const eventAsV7 = event as traceV7.BeforeActionTraceEvent;eventAsV7.stepId = `${eventAsV6.apiName}@${eventAsV6.wallTime}`;diff --git a/packages/playwright-core/src/server/trace/recorder/tracing.ts b/packages/playwright-core/src/server/trace/recorder/tracing.tsindex 1cf41c9424..ccf6d038fd 100644--- a/packages/playwright-core/src/server/trace/recorder/tracing.ts+++ b/packages/playwright-core/src/server/trace/recorder/tracing.ts@@ -125,7 +125,6 @@ export class Tracing extends SdkObject implements InstrumentationListener, SnapsmonotonicTime: 0,sdkLanguage: this._sdkLanguage(),testIdAttributeName,- contextId: context.guid,};if (context instanceof BrowserContext) {this._snapshotter = new Snapshotter(context, this);diff --git a/packages/playwright-core/src/tools/trace/traceActions.ts b/packages/playwright-core/src/tools/trace/traceActions.tsindex 2e11a78157..3b75d9c1bd 100644--- a/packages/playwright-core/src/tools/trace/traceActions.ts+++ b/packages/playwright-core/src/tools/trace/traceActions.ts@@ -21,7 +21,7 @@ import { asLocatorDescription } from '@isomorphic/locatorGenerators';import { msToString } from '@isomorphic/formatUtils';import { loadTrace, formatTimestamp, actionTitle } from './traceUtils';-import type { ActionTraceEventInContext } from '@isomorphic/trace/traceModel';+import type { ActionEntry } from '@isomorphic/trace/entries';import type { Language } from '@isomorphic/locatorGenerators';export async function traceActions(options: { grep?: string, errorsOnly?: boolean }) {@@ -37,8 +37,8 @@ export async function traceActions(options: { grep?: string, errorsOnly?: booleaconst ordinal = trace.callIdToOrdinal.get(action.callId) ?? '?';const ts = formatTimestamp(action.startTime, trace.model.startTime);const duration = action.endTime ? msToString(action.endTime - action.startTime) : 'running';- const title = actionTitle(action as ActionTraceEventInContext);- const locator = actionLocator(action as ActionTraceEventInContext);+ const title = actionTitle(action);+ const locator = actionLocator(action);const error = action.error ? ' ✗' : '';const prefix = ` ${(ordinal + '.').padStart(4)} ${ts} ${indent}`;console.log(`${prefix}${title.padEnd(Math.max(1, 55 - indent.length))} ${duration.padStart(8)}${error}`);@@ -51,7 +51,7 @@ export async function traceActions(options: { grep?: string, errorsOnly?: booleavisit(child, '');}-function filterActions(actions: ActionTraceEventInContext[], options: { grep?: string, errorsOnly?: boolean }): ActionTraceEventInContext[] {+function filterActions(actions: ActionEntry[], options: { grep?: string, errorsOnly?: boolean }): ActionEntry[] {let result = actions.filter(a => a.group !== 'configuration');if (options.grep) {const pattern = new RegExp(options.grep, 'i');@@ -62,7 +62,7 @@ function filterActions(actions: ActionTraceEventInContext[], options: { grep?: sreturn result;}-function actionLocator(action: ActionTraceEventInContext, sdkLanguage?: Language): string | undefined {+function actionLocator(action: ActionEntry, sdkLanguage?: Language): string | undefined {return action.params.selector ? asLocatorDescription(sdkLanguage || 'javascript', action.params.selector) : undefined;}diff --git a/packages/playwright-core/src/tools/trace/traceUtils.ts b/packages/playwright-core/src/tools/trace/traceUtils.tsindex 83e5b36f22..4a93dd3f12 100644--- a/packages/playwright-core/src/tools/trace/traceUtils.ts+++ b/packages/playwright-core/src/tools/trace/traceUtils.ts@@ -23,7 +23,7 @@ import { renderTitleForCall } from '@isomorphic/protocolFormatter';import { resolveWithinRoot } from '@utils/fileUtils';import { DirTraceLoaderBackend, extractTrace } from './traceParser';-import type { ActionTraceEventInContext } from '@isomorphic/trace/traceModel';+import type { ActionEntry } from '@isomorphic/trace/entries';const traceDir = path.join('.playwright-cli', 'trace');const cliOutputDir = '.playwright-cli';@@ -41,7 +41,7 @@ export class LoadedTrace {this.callIdToOrdinal = ordinals.callIdToOrdinal;}- resolveActionId(actionId: string): ActionTraceEventInContext | undefined {+ resolveActionId(actionId: string): ActionEntry | undefined {const ordinal = parseInt(actionId, 10);if (!isNaN(ordinal)) {const callId = this.ordinalToCallId.get(ordinal);@@ -105,7 +105,7 @@ export function formatTimestamp(ms: number, base: number): string {return `${minutes}:${seconds.toString().padStart(2, '0')}.${millis.toString().padStart(3, '0')}`;}-export function actionTitle(action: ActionTraceEventInContext): string {+export function actionTitle(action: ActionEntry): string {return renderTitleForCall({ ...action, type: action.class }) || `${action.class}.${action.method}`;}diff --git a/packages/trace-viewer/src/ui/actionList.tsx b/packages/trace-viewer/src/ui/actionList.tsxindex 07d1d12297..a9c871a9b3 100644--- a/packages/trace-viewer/src/ui/actionList.tsx+++ b/packages/trace-viewer/src/ui/actionList.tsx@@ -19,11 +19,13 @@ import { clsx } from '@web/uiUtils';import { msToString } from '@isomorphic/formatUtils';import * as React from 'react';import './actionList.css';-import { stats, buildActionTree } from '@isomorphic/trace/traceModel';+import { buildActionTree } from '@isomorphic/trace/traceModel';import { asLocatorDescription, type Language } from '@isomorphic/locatorGenerators';import type { TreeState } from '@web/components/treeView';import { TreeView } from '@web/components/treeView';-import type { ActionTraceEventInContext, ActionTreeItem } from '@isomorphic/trace/traceModel';+import type { ActionTreeItem, TraceModel } from '@isomorphic/trace/traceModel';+import type { ActionEntry } from '@isomorphic/trace/entries';+import { useTraceModel } from './traceModelContext';import type { Boundaries } from './geometry';import { ToolbarButton } from '@web/components/toolbarButton';import { testStatusIcon } from './testUtils';@@ -31,15 +33,15 @@ import { getMetainfo } from '@isomorphic/protocolMetainfo';import { formatProtocolParam } from '@isomorphic/protocolFormatter';export interface ActionListProps {- actions: ActionTraceEventInContext[],- selectedAction: ActionTraceEventInContext | undefined,+ actions: ActionEntry[],+ selectedAction: ActionEntry | undefined,selectedTime: Boundaries | undefined,setSelectedTime: (time: Boundaries | undefined) => void,treeState: TreeState,setTreeState: React.Dispatch<React.SetStateAction<TreeState>>,sdkLanguage: Language | undefined;- onSelected?: (action: ActionTraceEventInContext) => void,- onHighlighted?: (action: ActionTraceEventInContext | undefined) => void,+ onSelected?: (action: ActionEntry) => void,+ onHighlighted?: (action: ActionEntry | undefined) => void,revealConsole?: () => void,revealActionAttachment?(callId: string): void,isLive?: boolean,@@ -63,6 +65,7 @@ export const ActionList: React.FC<ActionListProps> = ({isLive,actionFilterText,}) => {+ const model = useTraceModel();const { rootItem, itemMap } = React.useMemo(() => buildActionTree(actions), [actions]);const { selectedItem } = React.useMemo(() => {@@ -80,8 +83,8 @@ export const ActionList: React.FC<ActionListProps> = ({const render = React.useCallback((item: ActionTreeItem) => {const showAttachments = !!revealActionAttachment && !!item.action.attachments?.length;- return renderAction(item.action, { sdkLanguage, revealConsole, revealActionAttachment: () => revealActionAttachment?.(item.action.callId), isLive, showDuration: true, showBadges: true, showAttachments });- }, [isLive, revealConsole, revealActionAttachment, sdkLanguage]);+ return renderAction(item.action, { model, sdkLanguage, revealConsole, revealActionAttachment: () => revealActionAttachment?.(item.action.callId), isLive, showDuration: true, showBadges: true, showAttachments });+ }, [model, isLive, revealConsole, revealActionAttachment, sdkLanguage]);const isVisible = React.useCallback((item: ActionTreeItem) => {const timeVisible = !selectedTime || !item.action || (item.action.startTime <= selectedTime.maximum && item.action.endTime >= selectedTime.minimum);@@ -129,8 +132,9 @@ export const ActionList: React.FC<ActionListProps> = ({};export const renderAction = (- action: ActionTraceEvent,+ action: ActionEntry,options: {+ model?: TraceModel,sdkLanguage?: Language,revealConsole?: () => void,revealActionAttachment?(): void,@@ -139,8 +143,8 @@ export const renderAction = (showBadges?: boolean,showAttachments?: boolean,}) => {- const { sdkLanguage, revealConsole, revealActionAttachment, isLive, showDuration, showBadges, showAttachments } = options;- const { errors, warnings } = stats(action);+ const { model, sdkLanguage, revealConsole, revealActionAttachment, isLive, showDuration, showBadges, showAttachments } = options;+ const { errors, warnings } = model?.stats(action) ?? { errors: 0, warnings: 0 };const locator = action.params.selector ? asLocatorDescription(sdkLanguage || 'javascript', action.params.selector) : undefined;diff --git a/packages/trace-viewer/src/ui/callTab.tsx b/packages/trace-viewer/src/ui/callTab.tsxindex fccc857224..2465f90a72 100644--- a/packages/trace-viewer/src/ui/callTab.tsx+++ b/packages/trace-viewer/src/ui/callTab.tsx@@ -23,11 +23,11 @@ import { CopyToClipboard } from './copyToClipboard';import { asLocator } from '@isomorphic/locatorGenerators';import type { Language } from '@isomorphic/locatorGenerators';import { PlaceholderPanel } from './placeholderPanel';-import type { ActionTraceEventInContext } from '@isomorphic/trace/traceModel';+import type { ActionEntry } from '@isomorphic/trace/entries';import { renderTitleForCall } from './actionList';export const CallTab: React.FunctionComponent<{- action: ActionTraceEventInContext | undefined,+ action: ActionEntry | undefined,startTimeOffset: number,sdkLanguage: Language | undefined,}> = ({ action, startTimeOffset, sdkLanguage }) => {@@ -73,7 +73,7 @@ type Property = {text: string;};-function renderDuration(action: ActionTraceEventInContext): string {+function renderDuration(action: ActionEntry): string {if (action.endTime)return msToString(action.endTime - action.startTime);else if (!!action.error)diff --git a/packages/trace-viewer/src/ui/filmStrip.tsx b/packages/trace-viewer/src/ui/filmStrip.tsxindex 93ccc7df18..5974d9efbc 100644--- a/packages/trace-viewer/src/ui/filmStrip.tsx+++ b/packages/trace-viewer/src/ui/filmStrip.tsx@@ -18,8 +18,7 @@ import './filmStrip.css';import type { Boundaries, Size } from './geometry';import * as React from 'react';import { useMeasure, upperBound } from '@web/uiUtils';-import type { PageEntry } from '@isomorphic/trace/entries';-import type { ActionTraceEventInContext } from '@isomorphic/trace/traceModel';+import type { ActionEntry, PageEntry } from '@isomorphic/trace/entries';import { renderAction } from './actionList';import type { Language } from '@isomorphic/locatorGenerators';import { useTraceModel } from './traceModelContext';@@ -27,7 +26,7 @@ import { useTraceModel } from './traceModelContext';export type FilmStripPreviewPoint = {x: number;clientY: number;- action?: ActionTraceEventInContext;+ action?: ActionEntry;sdkLanguage: Language;};diff --git a/packages/trace-viewer/src/ui/logTab.tsx b/packages/trace-viewer/src/ui/logTab.tsxindex 7f0ac6acfa..0436ad9dae 100644--- a/packages/trace-viewer/src/ui/logTab.tsx+++ b/packages/trace-viewer/src/ui/logTab.tsx@@ -14,24 +14,26 @@* limitations under the License.*/-import type { ActionTraceEventInContext } from '@isomorphic/trace/traceModel';+import type { ActionEntry } from '@isomorphic/trace/entries';import * as React from 'react';import { ListView } from '@web/components/listView';import { PlaceholderPanel } from './placeholderPanel';import { msToString } from '@isomorphic/formatUtils';+import { useTraceModel } from './traceModelContext';import './logTab.css';const LogList = ListView<{ message: string, time: string }>;export const LogTab: React.FunctionComponent<{- action: ActionTraceEventInContext | undefined,+ action: ActionEntry | undefined,isLive: boolean | undefined,}> = ({ action, isLive }) => {+ const model = useTraceModel();const entries = React.useMemo(() => {if (!action || !action.log.length)return [];const log = action.log;- const wallTimeOffset = action.context.wallTime - action.context.startTime;+ const wallTimeOffset = model ? (model.wallTime ?? 0) - model.startTime : 0;const entries: { message: string, time: string }[] = [];for (let i = 0; i < log.length; ++i) {let time = '';@@ -52,7 +54,7 @@ export const LogTab: React.FunctionComponent<{});}return entries;- }, [action, isLive]);+ }, [model, action, isLive]);if (!entries.length)return <PlaceholderPanel text='No log entries' />;diff --git a/packages/trace-viewer/src/ui/networkTab.tsx b/packages/trace-viewer/src/ui/networkTab.tsxindex 954cc83cb3..d7b4d1a078 100644--- a/packages/trace-viewer/src/ui/networkTab.tsx+++ b/packages/trace-viewer/src/ui/networkTab.tsx@@ -20,7 +20,6 @@ import './networkTab.css';import { NetworkResourceDetails, WebSocketResourceDetails } from './networkResourceDetails';import { bytesToString, msToString } from '@isomorphic/formatUtils';import { PlaceholderPanel } from './placeholderPanel';-import { context } from '@isomorphic/trace/traceModel';import type { ResourceEntry, TraceModel } from '@isomorphic/trace/traceModel';import { GridView, type RenderedGridCell } from '@web/components/gridView';import { SplitView } from '@web/components/splitView';@@ -221,10 +220,8 @@ function resourceContextId(model: TraceModel | undefined, resource: ResourceEntrreturn '';if (resource.pageref)return model.pagerefToTitle.get(resource.pageref) || '';- if (resource._apiRequest) {- const contextEntry = context(resource);- return (contextEntry && model.contextToTitle.get(contextEntry)) || '';- }+ if (resource._apiRequest)+ return resource.contextTitle;return '';}diff --git a/packages/trace-viewer/src/ui/playbackControl.tsx b/packages/trace-viewer/src/ui/playbackControl.tsxindex a478ed2394..35aea8ef85 100644--- a/packages/trace-viewer/src/ui/playbackControl.tsx+++ b/packages/trace-viewer/src/ui/playbackControl.tsx@@ -16,7 +16,7 @@import { ToolbarButton } from '@web/components/toolbarButton';import * as React from 'react';-import type { ActionTraceEventInContext } from '@isomorphic/trace/traceModel';+import type { ActionEntry } from '@isomorphic/trace/entries';import type { Boundaries } from './geometry';import './playbackControl.css';@@ -43,9 +43,9 @@ export type PlaybackState = {};export function usePlayback(- actions: ActionTraceEventInContext[],- selectedAction: ActionTraceEventInContext | undefined,- onActionSelected: (action: ActionTraceEventInContext) => void,+ actions: ActionEntry[],+ selectedAction: ActionEntry | undefined,+ onActionSelected: (action: ActionEntry) => void,timeWindow: Boundaries | undefined,boundaries: Boundaries,): PlaybackState {diff --git a/packages/trace-viewer/src/ui/timeline.tsx b/packages/trace-viewer/src/ui/timeline.tsxindex 458fae7bd7..787a407aa9 100644--- a/packages/trace-viewer/src/ui/timeline.tsx+++ b/packages/trace-viewer/src/ui/timeline.tsx@@ -21,7 +21,8 @@ import * as React from 'react';import type { Boundaries } from './geometry';import { FilmStrip } from './filmStrip';import type { FilmStripPreviewPoint } from './filmStrip';-import type { ActionTraceEventInContext, TraceModel } from '@isomorphic/trace/traceModel';+import type { TraceModel } from '@isomorphic/trace/traceModel';+import type { ActionEntry } from '@isomorphic/trace/entries';import './timeline.css';import type { Language } from '@isomorphic/locatorGenerators';import type { ActionGroup } from '@isomorphic/protocolFormatter';@@ -29,7 +30,7 @@ import type { ActionGroup } from '@isomorphic/protocolFormatter';export const Timeline: React.FunctionComponent<{model: TraceModel | undefined,boundaries: Boundaries,- onSelected: (action: ActionTraceEventInContext) => void,+ onSelected: (action: ActionEntry) => void,selectedTime: Boundaries | undefined,setSelectedTime: (time: Boundaries | undefined) => void,highlightedTime?: Boundaries,diff --git a/packages/trace-viewer/src/ui/workbench.tsx b/packages/trace-viewer/src/ui/workbench.tsxindex 640f6c69f0..bc65849aec 100644--- a/packages/trace-viewer/src/ui/workbench.tsx+++ b/packages/trace-viewer/src/ui/workbench.tsx@@ -21,7 +21,8 @@ import { CallTab } from './callTab';import { LogTab } from './logTab';import { ErrorsTab, useErrorsTabModel } from './errorsTab';import { ConsoleTab, useConsoleTabModel } from './consoleTab';-import type { TraceModel, SourceLocation, ActionTraceEventInContext, SourceModel } from '@isomorphic/trace/traceModel';+import type { TraceModel, SourceLocation, SourceModel } from '@isomorphic/trace/traceModel';+import type { ActionEntry } from '@isomorphic/trace/entries';import { NetworkTab, useNetworkTabModel } from './networkTab';import { SnapshotTabsView } from './snapshotTab';import { SourceTab } from './sourceTab';@@ -99,7 +100,7 @@ const PartitionedWorkbench: React.FunctionComponent<WorkbenchProps & { partitionconst [isInspecting, setIsInspectingState] = React.useState(false);const [highlightedTime, setHighlightedTime] = React.useState<Boundaries | undefined>(undefined);- const setSelectedAction = React.useCallback((action: ActionTraceEventInContext | undefined) => {+ const setSelectedAction = React.useCallback((action: ActionEntry | undefined) => {setSelectedCallId(action?.callId);setRevealedErrorKey(undefined);}, [setSelectedCallId, setRevealedErrorKey]);@@ -111,7 +112,7 @@ const PartitionedWorkbench: React.FunctionComponent<WorkbenchProps & { partitionreturn actions?.find(a => a.callId === highlightedCallId);}, [actions, highlightedCallId]);- const setHighlightedAction = React.useCallback((highlightedAction: ActionTraceEventInContext | undefined) => {+ const setHighlightedAction = React.useCallback((highlightedAction: ActionEntry | undefined) => {setHighlightedCallId(highlightedAction?.callId);}, [setHighlightedCallId]);@@ -150,7 +151,7 @@ const PartitionedWorkbench: React.FunctionComponent<WorkbenchProps & { partitionreturn highlightedAction || selectedAction;}, [selectedAction, highlightedAction]);- const onActionSelected = React.useCallback((action: ActionTraceEventInContext) => {+ const onActionSelected = React.useCallback((action: ActionEntry) => {setSelectedAction(action);setHighlightedAction(undefined);}, [setSelectedAction, setHighlightedAction]);diff --git a/packages/trace/src/trace.ts b/packages/trace/src/trace.tsindex bfba3d3923..dd10371f94 100644--- a/packages/trace/src/trace.ts+++ b/packages/trace/src/trace.ts@@ -92,7 +92,6 @@ export type ContextCreatedTraceEvent = {options: BrowserContextEventOptions,sdkLanguage?: Language,testIdAttributeName?: string,- contextId?: string,testTimeout?: number,annotations?: TraceEventAnnotation[],};diff --git a/tests/playwright-test/playwright.trace.spec.ts b/tests/playwright-test/playwright.trace.spec.tsindex 563afff537..6d0eb8f2ab 100644--- a/tests/playwright-test/playwright.trace.spec.ts+++ b/tests/playwright-test/playwright.trace.spec.ts@@ -214,19 +214,14 @@ test('should not mixup network files between contexts', async ({ runInlineTest,prefix: name.slice(0, -'.trace'.length),contextOptions: JSON.parse(content.toString().split('\n')[0]),})).filter(entry => entry.contextOptions.origin === 'library');- const traceEntriesByContextId = new Map<string, typeof traceEntries>();- for (const entry of traceEntries) {- const entries = traceEntriesByContextId.get(entry.contextOptions.contextId) || [];- entries.push(entry);- traceEntriesByContextId.set(entry.contextOptions.contextId, entries);- }- const contextTraces = [...traceEntriesByContextId.values()];- const browserTraces = contextTraces.filter(entries => entries[0].contextOptions.browserName);- const apiTraces = contextTraces.filter(entries => !entries[0].contextOptions.browserName);- expect(browserTraces).toHaveLength(3);- expect(apiTraces).toHaveLength(3);- for (const entries of browserTraces) {- const network = entries.map(entry => resources.get(entry.prefix + '.network')!.toString()).join('\n');+ // Each of the 3 browser contexts and 3 api request contexts produces+ // a trace chunk per test phase it was recording during.+ const browserTraces = traceEntries.filter(entry => entry.contextOptions.browserName);+ const apiTraces = traceEntries.filter(entry => !entry.contextOptions.browserName);+ expect(browserTraces.length).toBeGreaterThanOrEqual(3);+ expect(apiTraces.length).toBeGreaterThanOrEqual(3);+ for (const entry of browserTraces) {+ const network = resources.get(entry.prefix + '.network')!.toString();expect(network).not.toContain('?context=');}const apiURLs = [@@ -234,11 +229,13 @@ test('should not mixup network files between contexts', async ({ runInlineTest,server.PREFIX + '/simple.json?context=2',server.PREFIX + '/simple.json?context=3',];- const apiURLsByTrace = apiTraces.map(entries => {- const network = entries.map(entry => resources.get(entry.prefix + '.network')!.toString()).join('\n');+ // Api request context network files are chunk-specific, so each of the requests+ // must show up in exactly one network file.+ const apiURLsByTrace = apiTraces.map(entry => {+ const network = resources.get(entry.prefix + '.network')!.toString();return apiURLs.filter(url => network.includes(url));});- expect(apiURLsByTrace.map(urls => urls.length)).toEqual([1, 1, 1]);+ expect(apiURLsByTrace.every(urls => urls.length <= 1)).toBe(true);expect(apiURLsByTrace.flat().sort()).toEqual(apiURLs);const trace = await parseTrace(tracePath);expect(trace.model.resources.filter(resource => resource._apiRequest).map(resource => resource.request.url).sort()).toEqual(apiURLs);