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
21 changes: 18 additions & 3 deletions packages/playwright-core/src/server/launchApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,19 +98,34 @@ async function installAppIcon(page: Page) {
});
}

// The settings file is data. Only an object with string values gets into the page.
function parseSettings(text: string): Record<string, string> {
try {
const parsed = JSON.parse(text);
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
return {};
return Object.fromEntries(Object.entries(parsed).filter(([, value]) => typeof value === 'string')) as Record<string, string>;
} catch {
return {};
}
}

export async function syncLocalStorageWithSettings(page: Page, appName: string) {
if (isUnderTest())
return;
const settingsFile = path.join(registryDirectory, '.settings', `${appName}.json`);

const controller = new ProgressController();
await controller.run(async progress => {
await page.exposeBinding(progress, '_saveSerializedSettings', (_, settings) => {
await page.exposeBinding(progress, '_saveSerializedSettings', (source, settings) => {
// Only the application saves settings. A frame can have content from a different origin.
if (source.frame !== page.mainFrame())
return;
fs.mkdirSync(path.dirname(settingsFile), { recursive: true });
fs.writeFileSync(settingsFile, settings);
fs.writeFileSync(settingsFile, JSON.stringify(parseSettings(String(settings))));
});

const settings = await progress.race(fs.promises.readFile(settingsFile, 'utf-8').catch(() => ('{}')));
const settings = JSON.stringify(parseSettings(await progress.race(fs.promises.readFile(settingsFile, 'utf-8').catch(() => ('{}')))));
await page.addInitScript(progress,
`(${String((settings: any) => {
// iframes w/ snapshots, etc.
Expand Down
21 changes: 18 additions & 3 deletions packages/playwright-core/src/tools/dashboard/dashboardApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -174,15 +174,30 @@ async function launchApp(appName: string, options?: { onClose?: () => void }) {
return { context, page };
}

// The settings file is data. Only an object with string values gets into the page.
function parseSettings(text: string): Record<string, string> {
try {
const parsed = JSON.parse(text);
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
return {};
return Object.fromEntries(Object.entries(parsed).filter(([, value]) => typeof value === 'string')) as Record<string, string>;
} catch {
return {};
}
}

export async function syncLocalStorageWithSettings(page: api.Page, appName: string) {
const settingsFile = process.env.PWTEST_DASHBOARD_SETTINGS_FILE ?? path.join(registryDirectory, '.settings', `${appName}.json`);

await page.exposeBinding('_saveSerializedSettings', (_, settings) => {
await page.exposeBinding('_saveSerializedSettings', (source, settings) => {
// Only the application saves settings. A frame can have content from a different origin.
if (source.frame !== page.mainFrame())
return;
fs.mkdirSync(path.dirname(settingsFile), { recursive: true });
fs.writeFileSync(settingsFile, settings);
fs.writeFileSync(settingsFile, JSON.stringify(parseSettings(String(settings))));
});

const settings = await fs.promises.readFile(settingsFile, 'utf-8').catch(() => ('{}'));
const settings = JSON.stringify(parseSettings(await fs.promises.readFile(settingsFile, 'utf-8').catch(() => ('{}'))));
await page.addInitScript(
`(${String((settings: any) => {
// iframes w/ snapshots, etc.
Expand Down
36 changes: 30 additions & 6 deletions packages/playwright/src/runner/testServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ class TestServer {
this._configCLIOverrides = configCLIOverrides;
}

// One server has the trace viewer and the WebSocket. The client is a tool, for example an IDE.
async start(options: { host?: string, port?: number }): Promise<HttpServer> {
this._dispatcher = new TestServerDispatcher(this._configLocation, this._configCLIOverrides);
return await coreServer.startTraceViewerServer({
Expand All @@ -69,6 +70,26 @@ class TestServer {
});
}

// UI mode embeds the trace viewer, which shows content from the pages under test.
// The trace viewer has its own server on a different port, so the browser keeps it in a different origin.
// The UI mode server has the WebSocket, and it does not give files.
async startUIMode(options: { host?: string, port?: number }): Promise<{ server: HttpServer, traceViewerServer: HttpServer }> {
this._dispatcher = new TestServerDispatcher(this._configLocation, this._configCLIOverrides);
const [server, traceViewerServer] = await Promise.all([
coreServer.startTraceViewerServer({
host: options.host,
port: options.port,
allowedFileRoots: () => [],
transport: this._dispatcher.transport,
}),
coreServer.startTraceViewerServer({
host: options.host,
allowedFileRoots: () => this._allowedFileRoots(),
}),
]);
return { server, traceViewerServer };
}

private _allowedFileRoots(): string[] {
const roots = new Set<string>([process.cwd(), this._configLocation.configDir]);
const config = this._dispatcher?._testRunner.lastLoadedConfig();
Expand Down Expand Up @@ -279,8 +300,11 @@ export class TestServerDispatcher implements TestServerInterface {

export async function runUIMode(configFile: string | undefined, configCLIOverrides: ipc.ConfigCLIOverrides, options: TraceViewerServerOptions & TraceViewerRedirectOptions): Promise<reporterTypes.FullResult['status']> {
const configLocation = configLoader.resolveConfigLocation(configFile);
return await innerRunTestServer(configLocation, configCLIOverrides, options, async (server: HttpServer, cancelPromise: ManualPromise<void>) => {
const uiModePath = coreServer.traceViewerPath(undefined, { ...options, webApp: 'uiMode.html' });
return await innerRunTestServer(configLocation, configCLIOverrides, async (testServer, cancelPromise) => {
const { server, traceViewerServer } = await testServer.startUIMode(options);
// The page gets to the two servers through the same host, so it only needs the port and the path.
const traceViewerPath = traceViewerServer.urlPrefix('precise').substring(traceViewerServer.rootUrl('precise').length) + '/trace/';
const uiModePath = coreServer.traceViewerPath(undefined, { ...options, webApp: 'uiMode.html' }) + '&traceViewer=' + encodeURIComponent(traceViewerServer.port() + traceViewerPath);
if (options.host !== undefined || options.port !== undefined) {
server.installRootRedirect(uiModePath);
await coreServer.openTraceInBrowser(server.rootUrl('human-readable'));
Expand Down Expand Up @@ -314,21 +338,21 @@ async function installedChromiumChannelForUI(configLocation: ConfigLocation, con

export async function runTestServer(configFile: string | undefined, configCLIOverrides: ipc.ConfigCLIOverrides, options: { host?: string, port?: number }): Promise<reporterTypes.FullResult['status']> {
const configLocation = configLoader.resolveConfigLocation(configFile);
return await innerRunTestServer(configLocation, configCLIOverrides, options, async server => {
return await innerRunTestServer(configLocation, configCLIOverrides, async testServer => {
const server = await testServer.start(options);
// eslint-disable-next-line no-console
console.log('Listening on ' + server.urlPrefix('precise').replace('http:', 'ws:') + '/ws');
});
}

async function innerRunTestServer(configLocation: ConfigLocation, configCLIOverrides: ipc.ConfigCLIOverrides, options: { host?: string, port?: number }, openUI: (server: HttpServer, cancelPromise: ManualPromise<void>) => Promise<void>): Promise<reporterTypes.FullResult['status']> {
async function innerRunTestServer(configLocation: ConfigLocation, configCLIOverrides: ipc.ConfigCLIOverrides, openUI: (testServer: TestServer, cancelPromise: ManualPromise<void>) => Promise<void>): Promise<reporterTypes.FullResult['status']> {
const testServer = new TestServer(configLocation, configCLIOverrides);
const cancelPromise = new ManualPromise<void>();
const sigintWatcher = new SigIntWatcher();
process.stdin.on('close', () => gracefullyProcessExitDoNotHang(0));
void sigintWatcher.promise().then(() => cancelPromise.resolve());
try {
const server = await testServer.start(options);
await openUI(server, cancelPromise);
await openUI(testServer, cancelPromise);
await cancelPromise;
} finally {
await testServer.stop();
Expand Down
16 changes: 3 additions & 13 deletions packages/trace-viewer/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,26 +18,16 @@ import '@web/common.css';
import { applyTheme } from '@web/theme';
import '@web/third_party/vscode/codicon.css';
import * as ReactDOM from 'react-dom/client';
import { startServiceWorker } from './ui/serviceWorker';
import { WorkbenchLoader } from './ui/workbenchLoader';
import { LiveWorkbenchLoader } from './ui/liveWorkbenchLoader';

(async () => {
const queryParams = new URLSearchParams(window.location.search);

applyTheme();
if (window.location.protocol !== 'file:') {
if (!navigator.serviceWorker)
throw new Error(`Service workers are not supported.\nMake sure to serve the Trace Viewer (${window.location}) via HTTPS or localhost.`);
navigator.serviceWorker.register('sw.bundle.js');
if (!navigator.serviceWorker.controller) {
await new Promise<void>(f => {
navigator.serviceWorker.oncontrollerchange = () => f();
});
}

// Keep SW running.
setInterval(function() { fetch('ping'); }, 10000);
}
if (window.location.protocol !== 'file:')

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.

drop this check?

await startServiceWorker();

const trace = queryParams.get('trace');
const traceIsLive = trace?.endsWith('.json');
Expand Down
3 changes: 2 additions & 1 deletion packages/trace-viewer/src/sw/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,8 @@ async function doFetch(event: FetchEvent): Promise<Response> {

if (relativePath.startsWith('/file/')) {
// The trace viewer never shows these files in a frame. Only a snapshot that navigates itself does.
if (['iframe', 'frame', 'embed', 'object'].includes(request.destination))
// A trace viewer that is in a frame itself still downloads attachments, and a download has a file name.
if (['iframe', 'frame', 'embed', 'object'].includes(request.destination) && !url.searchParams.has('dn'))
return new Response(null, { status: 403 });
const blob = await loadedTrace!.traceLoader.resourceEntry(relativePath.slice('/file/'.length));
if (blob)
Expand Down
6 changes: 4 additions & 2 deletions packages/trace-viewer/src/ui/ariaModeView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,13 @@ export type AriaModeTargets = {
after?: AriaModeTarget;
};

export function canToggleAriaMode(model: TraceModel | undefined): boolean {
export type AriaModeInfo = Pick<TraceModel, 'hasDomSnapshots' | 'hasAriaSnapshots'>;

export function canToggleAriaMode(model: AriaModeInfo | undefined): boolean {
return !!model?.hasDomSnapshots && !!model?.hasAriaSnapshots;
}

export function shouldDisplayAriaMode(model: TraceModel | undefined, setting: boolean): boolean {
export function shouldDisplayAriaMode(model: AriaModeInfo | undefined, setting: boolean): boolean {
return canToggleAriaMode(model) ? setting : !!model?.hasAriaSnapshots;
}

Expand Down
4 changes: 2 additions & 2 deletions packages/trace-viewer/src/ui/defaultSettingsView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,15 @@ import { type Setting, SettingsView } from './settingsView';
import { kThemeOptions, type Theme, useThemeSetting } from '@web/theme';
import { useSetting } from '@web/uiUtils';
import { canToggleAriaMode, shouldDisplayAriaMode } from './ariaModeView';
import type { AriaModeInfo } from './ariaModeView';

import type { TraceModel } from '@isomorphic/trace/traceModel';

/**
* A view of the collection of standard settings used between various applications
*/
export const DefaultSettingsView: React.FC<{
location: 'ui-mode' | 'trace-viewer',
model?: TraceModel,
model?: AriaModeInfo,
}> = ({ location, model }) => {
const [
shouldPopulateCanvasFromScreenshot,
Expand Down
30 changes: 30 additions & 0 deletions packages/trace-viewer/src/ui/serviceWorker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/**
* 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.
*/

// The service worker gives the trace data to the trace viewer.
export async function startServiceWorker() {
if (!navigator.serviceWorker)
throw new Error(`Service workers are not supported.\nMake sure to serve the Trace Viewer (${window.location}) via HTTPS or localhost.`);
navigator.serviceWorker.register('sw.bundle.js');
if (!navigator.serviceWorker.controller) {
await new Promise<void>(f => {
navigator.serviceWorker.oncontrollerchange = () => f();
});
}

// Keep SW running.
setInterval(function() { fetch('ping'); }, 10000);
}
121 changes: 121 additions & 0 deletions packages/trace-viewer/src/ui/uiModeTraceFrame.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
/**
* 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 { artifactsFolderName } from '@testIsomorphic/folders';
import React from 'react';
import type { ContextEntry } from '@isomorphic/trace/entries';
import { TraceModel } from '@isomorphic/trace/traceModel';
import type { UIModeTraceEvent, UIModeTraceParams } from './uiModeTraceProtocol';
import { Workbench } from './workbench';

// The trace viewer side of the UI mode frame.
export const UIModeTraceFrame: React.FC<{
params: UIModeTraceParams,
sendEvent: (event: UIModeTraceEvent) => void,
}> = ({ params, sendEvent }) => {
const [model, setModel] = React.useState<{ model: TraceModel, isLive: boolean } | undefined>(undefined);
const [counter, setCounter] = React.useState(0);

// Only load the trace again when the test result is different.
const { result, testId, outputDir, pathSeparator } = params;
const errorsRef = React.useRef<string[]>([]);
errorsRef.current = result?.errors ?? [];
const hasResult = !!result;
const { startTime, duration, workerIndex, tracePath } = result ?? {};

React.useEffect(() => {
if (!hasResult) {
setModel(undefined);
return;
}

const abortController = new AbortController();
const { signal } = abortController;

// Test finished.
if (duration! >= 0 && tracePath) {
loadSingleTraceFile(tracePath, startTime!, signal).then(model => setModel({ model, isLive: false })).catch(e => {
if (!signal.aborted)
throw e;
});
return () => abortController.abort();
}

if (!outputDir) {
setModel(undefined);
return;
}

const traceLocation = [
outputDir,
artifactsFolderName(workerIndex!),
'traces',
`${testId}.json`
].join(pathSeparator);
// Start polling running test.
const pollTimer = setTimeout(async () => {
try {
const model = await loadSingleTraceFile(traceLocation, Date.now(), signal);
setModel({ model, isLive: true });
} catch {
if (signal.aborted)
return;
const model = new TraceModel('', []);
model.errorDescriptors.push(...errorsRef.current.map(message => ({ message })));
setModel({ model, isLive: false });
}
setCounter(counter + 1);
}, 500);
return () => {
clearTimeout(pollTimer);
abortController.abort();
};
}, [hasResult, startTime, duration, workerIndex, tracePath, testId, outputDir, pathSeparator, setModel, counter, setCounter]);

// A live trace gives a new model on each poll. Only send the values that are different.
const hasModel = !!model;
const hasDomSnapshots = !!model?.model.hasDomSnapshots;
const hasAriaSnapshots = !!model?.model.hasAriaSnapshots;
React.useEffect(() => {
sendEvent({ method: 'traceInfo', info: hasModel ? { hasDomSnapshots, hasAriaSnapshots } : undefined });
}, [hasModel, hasDomSnapshots, hasAriaSnapshots, sendEvent]);

const onOpenExternally = React.useCallback(({ file, line, column }: { file: string, line: number, column: number }) => {
sendEvent({ method: 'openExternally', location: { file, line, column } });
}, [sendEvent]);

return <Workbench
model={model?.model}
key='workbench'
showSourcesFirst={true}
rootDir={params.rootDir}
fallbackLocation={params.testFile}
isLive={model?.isLive}
status={params.status}
defaultAnnotations={params.annotations}
onOpenExternally={onOpenExternally}
revealSource={params.revealSource}
/>;
};

async function loadSingleTraceFile(absolutePath: string, timestamp: number, signal: AbortSignal): Promise<TraceModel> {
const traceUri = `file?path=${encodeURIComponent(absolutePath)}&timestamp=${timestamp}`;
const params = new URLSearchParams();
params.set('trace', traceUri);
const response = await fetch(`contexts?${params.toString()}`, { signal });
const contextEntries = await response.json() as ContextEntry[];
return new TraceModel(traceUri, contextEntries);
}
Loading
Loading