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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/playwright-core/src/cli/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ program
.action(async options => {
const { program: cliProgram } = await import('../tools/cli-client/program');
process.argv.splice(process.argv.indexOf('cli'), 1);
cliProgram();
cliProgram().catch(logErrorAndExit);
});

function logErrorAndExit(e: Error) {
Expand Down
5 changes: 5 additions & 0 deletions packages/playwright-core/src/tools/backend/tracing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,11 @@ const tracingStop = defineTool({
await browserContext.tracing.stop();
// eslint-disable-next-line no-restricted-syntax
const traceLegend = (browserContext.tracing as any)[traceLegendSymbol];
if (!traceLegend)
throw new Error('Tracing is not started');
// eslint-disable-next-line no-restricted-syntax
delete (browserContext.tracing as any)[traceLegendSymbol];

response.addTextResult(`Trace recording stopped.`);
response.addFileLink('Trace', `${traceLegend.tracesDir}/${traceLegend.name}.trace`);
response.addFileLink('Network log', `${traceLegend.tracesDir}/${traceLegend.name}.network`);
Expand Down
21 changes: 17 additions & 4 deletions packages/playwright-core/src/tools/trace/traceUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,15 +68,28 @@ export async function openTrace(traceFile: string) {
throw new Error(`Trace file not found: ${filePath}`);
await closeTrace();
await fs.promises.mkdir(traceDir, { recursive: true });
await extractTrace(filePath, traceDir);
if (filePath.endsWith('.zip'))
await extractTrace(filePath, traceDir);
else
await fs.promises.writeFile(path.join(traceDir, '.link'), filePath, 'utf-8');
}

export async function loadTrace(): Promise<LoadedTrace> {
const dir = ensureTraceOpen();
const backend = new DirTraceLoaderBackend(dir);
const linkFile = path.join(dir, '.link');
let traceDir: string;
let traceFile: string | undefined;
if (fs.existsSync(linkFile)) {
const tracePath = await fs.promises.readFile(linkFile, 'utf-8');
traceDir = path.dirname(tracePath);
traceFile = path.basename(tracePath);
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe support path to a dir too?

} else {
traceDir = dir;
}
const backend = new DirTraceLoaderBackend(traceDir);
const loader = new TraceLoader();
await loader.load(backend, () => undefined);
const model = new TraceModel(dir, loader.contextEntries);
await loader.load(backend, traceFile);
const model = new TraceModel(traceDir, loader.contextEntries);
return new LoadedTrace(model, loader, buildOrdinalMap(model));
}

Expand Down
27 changes: 14 additions & 13 deletions packages/playwright-core/src/utils/isomorphic/trace/traceLoader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,38 +38,39 @@ export class TraceLoader {
constructor() {
}

async load(backend: TraceLoaderBackend, unzipProgress: (done: number, total: number) => void) {
async load(backend: TraceLoaderBackend, traceFile?: string, unzipProgress?: (done: number, total: number) => void) {
this._backend = backend;

const ordinals: string[] = [];
const prefix = traceFile?.match(/(.+)\.trace$/)?.[1];
const prefixes: string[] = [];
let hasSource = false;
for (const entryName of await this._backend.entryNames()) {
const match = entryName.match(/(.+)\.trace$/);
if (match)
ordinals.push(match[1] || '');
if (match && (!prefix || prefix === match[1]))
prefixes.push(match[1] || '');
if (entryName.includes('src@'))
hasSource = true;
}
if (!ordinals.length)
if (!prefixes.length)
throw new Error('Cannot find .trace file');

this._snapshotStorage = new SnapshotStorage();

// 3 * ordinals progress increments below.
const total = ordinals.length * 3;
const total = prefixes.length * 3;
let done = 0;
for (const ordinal of ordinals) {
for (const prefix of prefixes) {
const contextEntry = createEmptyContext();
contextEntry.hasSource = hasSource;
const modernizer = new TraceModernizer(contextEntry, this._snapshotStorage);

const trace = await this._backend.readText(ordinal + '.trace') || '';
const trace = await this._backend.readText(prefix + '.trace') || '';
modernizer.appendTrace(trace);
unzipProgress(++done, total);
unzipProgress?.(++done, total);

const network = await this._backend.readText(ordinal + '.network') || '';
const network = await this._backend.readText(prefix + '.network') || '';
modernizer.appendTrace(network);
unzipProgress(++done, total);
unzipProgress?.(++done, total);

contextEntry.actions = modernizer.actions().sort((a1, a2) => a1.startTime - a2.startTime);

Expand All @@ -87,13 +88,13 @@ export class TraceLoader {
}
}

const stacks = await this._backend.readText(ordinal + '.stacks');
const stacks = await this._backend.readText(prefix + '.stacks');
if (stacks) {
const callMetadata = parseClientSideCallMetadata(JSON.parse(stacks));
for (const action of contextEntry.actions)
action.stack = action.stack || callMetadata.get(action.callId);
}
unzipProgress(++done, total);
unzipProgress?.(++done, total);

for (const resource of contextEntry.resources) {
if (resource.request.postData?._sha1)
Expand Down
2 changes: 1 addition & 1 deletion packages/trace-viewer/src/sw/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ async function innerLoadTrace(traceUri: string, progress: Progress): Promise<Loa
// Allow 10% to hop from sw to page.
const [fetchProgress, unzipProgress] = splitProgress(progress, [0.5, 0.4, 0.1]);
const backend = isLiveTrace(traceUri) || traceUri.endsWith('traces.dir') ? new FetchTraceLoaderBackend(traceUri) : new ZipTraceLoaderBackend(traceUri, fetchProgress);
await traceLoader.load(backend, unzipProgress);
await traceLoader.load(backend, undefined, unzipProgress);
} catch (error: any) {
// eslint-disable-next-line no-console
console.error(error);
Expand Down
2 changes: 1 addition & 1 deletion tests/config/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ export async function parseTrace(file: string): Promise<{ snapshots: SnapshotSto
await extractTrace(file, dir);
const backend = new DirTraceLoaderBackend(dir);
const loader = new TraceLoader();
await loader.load(backend, () => {});
await loader.load(backend);
return { model: new TraceModel(dir, loader.contextEntries), snapshots: loader.storage() };
}

Expand Down
25 changes: 25 additions & 0 deletions tests/mcp/trace-cli.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,31 @@ test('trace close removes extracted trace', async ({ traceFile, runTraceCli }) =
expect(exitCode3).toBe(0);
});

test('trace open with .trace file creates link', async ({ traceFile, traceCwd, runTraceCli }) => {
// Extract the zip using the CLI to get raw trace files.
const extractCwd = path.join(path.dirname(traceFile), 'extracted');
fs.mkdirSync(extractCwd, { recursive: true });
const cliPath = path.resolve(__dirname, '../../packages/playwright-core/cli.js');
const { execFileSync } = require('child_process');
execFileSync(process.execPath, [cliPath, 'trace', 'open', traceFile], { cwd: extractCwd });
const extractDir = path.join(extractCwd, '.playwright-cli', 'trace');

const traceEntries = fs.readdirSync(extractDir).filter((f: string) => f.endsWith('.trace'));
expect(traceEntries.length).toBeGreaterThan(0);
const dotTraceFile = path.join(extractDir, traceEntries[0]);
const { exitCode } = await runTraceCli(['open', dotTraceFile]);
expect(exitCode).toBe(0);

const linkFile = path.join(traceCwd, '.playwright-cli', 'trace', '.link');
expect(fs.existsSync(linkFile)).toBe(true);
expect(fs.readFileSync(linkFile, 'utf-8')).toBe(dotTraceFile);

const { stdout: actionsOutput, exitCode: actionsExitCode } = await runTraceCli(['actions']);
expect(actionsExitCode).toBe(0);
expect(actionsOutput).toContain('Navigate');
expect(actionsOutput).toContain('Click');
});

test('trace attachments lists attachments', async ({ runTraceCli }) => {
const { stdout, exitCode } = await runTraceCli(['attachments']);
expect(exitCode).toBe(0);
Expand Down
Loading