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
92 changes: 92 additions & 0 deletions packages/playwright/src/mcp/browser/logFile.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/**
* Copyright (c) Microsoft Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import fs from 'fs';

import { dateAsFileName } from './tools/utils';
import { logUnhandledError } from '../log';

import type { Context } from './context';

export type LogChunk = {
type: string;
file: string;
fromLine: number;
toLine: number;
entryCount: number;
};

export class LogFile {
private _startTime: number;
private _context: Context;
private _filePrefix: string;
private _title: string;

private _file: string | undefined;
private _stopped: boolean = false;

private _line: number = 0;
private _entries: number = 0;
private _lastLine: number = 0;
private _lastEntries: number = 0;

private _writeChain: Promise<void> = Promise.resolve();

constructor(context: Context, startTime: number, filePrefix: string, title: string) {
this._context = context;
this._startTime = startTime;
this._filePrefix = filePrefix;
this._title = title;
}

appendLine(wallTime: number, text: () => string | Promise<string>) {
this._writeChain = this._writeChain.then(() => this._write(wallTime, text)).catch(logUnhandledError);
}

stop() {
this._stopped = true;
}

async take(): Promise<LogChunk | undefined> {
await this._writeChain;
if (!this._file || this._entries === this._lastEntries)
return undefined;
const chunk: LogChunk = {
type: this._title.toLowerCase(),
file: this._file,
fromLine: this._lastLine + 1,
toLine: this._line,
entryCount: this._entries - this._lastEntries,
};
this._lastLine = this._line;
this._lastEntries = this._entries;
return chunk;
}

private async _write(wallTime: number, text: () => string | Promise<string>) {
if (this._stopped)
return;
this._file ??= await this._context.outputFile(dateAsFileName(this._filePrefix, 'log', new Date(this._startTime)), { origin: 'code', title: this._title });
const relativeTime = Math.round(wallTime - this._startTime);
const renderedText = await text();
const logLine = `[${String(relativeTime).padStart(8, ' ')}ms] ${renderedText}\n`;
await fs.promises.appendFile(this._file, logLine);

const lineCount = logLine.split('\n').length - 1;
this._line += lineCount;
this._entries++;
}
}
13 changes: 7 additions & 6 deletions packages/playwright/src/mcp/browser/response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ import { renderModalStates, shouldIncludeMessage } from './tab';
import { dateAsFileName } from './tools/utils';
import { scaleImageToFitMessage } from './tools/screenshot';

import type { LogChunk, TabHeader } from './tab';
import type { TabHeader } from './tab';
import type { LogChunk } from './logFile';
import type { CallToolResult, ImageContent, TextContent } from '@modelcontextprotocol/sdk/types.js';
import type { Context } from './context';

Expand All @@ -40,7 +41,7 @@ type ResolvedFile = {
printableLink: string;
};

export type Section = {
type Section = {
title: string;
content: string[];
isError?: boolean;
Expand Down Expand Up @@ -217,21 +218,21 @@ export class Response {
}

// Handle tab log
const text: string[] = renderLogChunk(tabSnapshot?.logChunk, 'console', file => this._computRelativeTo(file));
const text: string[] = tabSnapshot?.logs?.map(log => renderLogChunk(log, log.type, file => this._computRelativeTo(file))).flat() ?? [];
if (tabSnapshot?.events.filter(event => event.type !== 'request').length) {
for (const event of tabSnapshot.events) {
if (event.type === 'console' && !tabSnapshot.logChunk) {
if (event.type === 'console' && this._context.config.outputMode !== 'file') {
if (shouldIncludeMessage(this._context.config.console.level, event.message.type))
text.push(`- ${trimMiddle(event.message.toString(), 100)}`);
} else if (event.type === 'download-start') {

text.push(`- Downloading file ${event.download.download.suggestedFilename()} ...`);
} else if (event.type === 'download-finish') {
text.push(`- Downloaded file ${event.download.download.suggestedFilename()} to "${this._computRelativeTo(event.download.outputFile)}"`);
}
}
}
addSection('Events', text);
if (text.length)
addSection('Events', text);
return sections;
}
}
Expand Down
Loading
Loading