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): pass trace param to sha1 requests (#37788)
Pavel Feldmanea3fab65d84f
diff --git a/packages/trace-viewer/src/sw/main.ts b/packages/trace-viewer/src/sw/main.tsindex 5c3a6ed852..79b928d062 100644--- a/packages/trace-viewer/src/sw/main.ts+++ b/packages/trace-viewer/src/sw/main.ts@@ -20,7 +20,27 @@ import { TraceModel } from './traceModel';import { FetchTraceModelBackend, traceFileURL, ZipTraceModelBackend } from './traceModelBackends';import { TraceVersionError } from './traceModernizer';-// @ts-ignore+type Client = {+ id: string;+ url: string;+ postMessage(message: any): void;+};++type ServiceWorkerGlobalScope = {+ addEventListener(event: 'install', listener: (event: any) => void): void;+ addEventListener(event: 'activate', listener: (event: any) => void): void;+ addEventListener(event: 'fetch', listener: (event: any) => void): void;+ registration: {+ scope: string;+ };+ clients: {+ claim(): Promise<void>;+ get(id: string): Promise<Client | undefined>;+ matchAll(): Promise<Client[]>;+ };+ skipWaiting(): Promise<void>;+};+declare const self: ServiceWorkerGlobalScope;self.addEventListener('install', function(event: any) {@@ -31,19 +51,27 @@ self.addEventListener('activate', function(event: any) {event.waitUntil(self.clients.claim());});+type LoadedTrace = {+ traceModel: TraceModel;+ snapshotServer: SnapshotServer;+};+const scopePath = new URL(self.registration.scope).pathname;-const loadedTraces = new Map<string, { traceModel: TraceModel, snapshotServer: SnapshotServer }>();+const loadedTraces = new Map<string, LoadedTrace>();const clientIdToTraceUrls = new Map<string, string>();+const isDeployedAsHttps = self.registration.scope.startsWith('https://');-async function loadTrace(traceUrl: string, traceFileName: string | null, client: any | undefined, progress: (done: number, total: number) => undefined): Promise<TraceModel> {- const clientId = client?.id ?? '';+async function loadTrace(traceUrl: string, traceFileName: string | null, client: Client): Promise<TraceModel> {+ const clientId = client.id;clientIdToTraceUrls.set(clientId, traceUrl);await gc();const traceModel = new TraceModel();try {// Allow 10% to hop from sw to page.- const [fetchProgress, unzipProgress] = splitProgress(progress, [0.5, 0.4, 0.1]);+ const [fetchProgress, unzipProgress] = splitProgress((done: number, total: number) => {+ client.postMessage({ method: 'progress', params: { done, total } });+ }, [0.5, 0.4, 0.1]);const backend = traceUrl.endsWith('json') ? new FetchTraceModelBackend(traceUrl) : new ZipTraceModelBackend(traceUrl, fetchProgress);await traceModel.load(backend, unzipProgress);} catch (error: any) {@@ -75,93 +103,89 @@ async function doFetch(event: FetchEvent): Promise<Response> {}const request = event.request;- const client = await self.clients.get(event.clientId);+ const client = await self.clients.get(event.clientId) as Client | undefined;// When trace viewer is deployed over https, we will force upgrade// insecure http subresources to https. Otherwise, these will fail// to load inside our https snapshots.// In this case, we also match http resources from the archive by// the https urls.- const isDeployedAsHttps = self.registration.scope.startsWith('https://');-- if (request.url.startsWith(self.registration.scope)) {- const url = new URL(request.url);- const relativePath = url.pathname.substring(scopePath.length - 1);- if (relativePath === '/ping') {- await gc();- return new Response(null, { status: 200 });- }+ const url = new URL(request.url);- const traceUrl = url.searchParams.get('trace');+ let relativePath: string | undefined;+ if (request.url.startsWith(self.registration.scope))+ relativePath = url.pathname.substring(scopePath.length - 1);- if (relativePath === '/contexts') {- try {- const traceModel = await loadTrace(traceUrl!, url.searchParams.get('traceFileName'), client, (done: number, total: number) => {- client.postMessage({ method: 'progress', params: { done, total } });- });- return new Response(JSON.stringify(traceModel!.contextEntries), {- status: 200,- headers: { 'Content-Type': 'application/json' }- });- } catch (error: any) {- return new Response(JSON.stringify({ error: error?.message }), {- status: 500,- headers: { 'Content-Type': 'application/json' }- });- }- }+ if (relativePath === '/ping')+ return new Response(null, { status: 200 });- if (relativePath.startsWith('/snapshotInfo/')) {- const { snapshotServer } = loadedTraces.get(traceUrl!) || {};- if (!snapshotServer)- return new Response(null, { status: 404 });- const pageOrFrameId = relativePath.substring('/snapshotInfo/'.length);- return snapshotServer.serveSnapshotInfo(pageOrFrameId, url.searchParams);+ if (relativePath === '/contexts') {+ const traceUrl = url.searchParams.get('trace');+ if (!client || !traceUrl) {+ return new Response('Something went wrong, trace is requested as a part of the navigation', {+ status: 500,+ headers: { 'Content-Type': 'application/json' }+ });}- if (relativePath.startsWith('/snapshot/')) {- const { snapshotServer } = loadedTraces.get(traceUrl!) || {};- if (!snapshotServer)- return new Response(null, { status: 404 });- const pageOrFrameId = relativePath.substring('/snapshot/'.length);- const response = snapshotServer.serveSnapshot(pageOrFrameId, url.searchParams, url.href);- if (isDeployedAsHttps)- response.headers.set('Content-Security-Policy', 'upgrade-insecure-requests');- return response;+ try {+ const traceModel = await loadTrace(traceUrl, url.searchParams.get('traceFileName'), client);+ return new Response(JSON.stringify(traceModel.contextEntries), {+ status: 200,+ headers: { 'Content-Type': 'application/json' }+ });+ } catch (error: any) {+ return new Response(JSON.stringify({ error: error?.message }), {+ status: 500,+ headers: { 'Content-Type': 'application/json' }+ });}+ }- if (relativePath.startsWith('/closest-screenshot/')) {- const { snapshotServer } = loadedTraces.get(traceUrl!) || {};- if (!snapshotServer)- return new Response(null, { status: 404 });- const pageOrFrameId = relativePath.substring('/closest-screenshot/'.length);- return snapshotServer.serveClosestScreenshot(pageOrFrameId, url.searchParams);- }+ if (relativePath?.startsWith('/snapshotInfo/')) {+ const { snapshotServer } = loadedTrace(url);+ if (!snapshotServer)+ return new Response(null, { status: 404 });+ const pageOrFrameId = relativePath.substring('/snapshotInfo/'.length);+ return snapshotServer.serveSnapshotInfo(pageOrFrameId, url.searchParams);+ }- if (relativePath.startsWith('/sha1/')) {- // Sha1 for sources is based on the file path, can't load it of a random model.- const sha1 = relativePath.slice('/sha1/'.length);- for (const trace of loadedTraces.values()) {- const blob = await trace.traceModel.resourceForSha1(sha1);- if (blob)- return new Response(blob, { status: 200, headers: downloadHeaders(url.searchParams) });- }+ if (relativePath?.startsWith('/snapshot/')) {+ const { snapshotServer } = loadedTrace(url);+ if (!snapshotServer)return new Response(null, { status: 404 });- }+ const pageOrFrameId = relativePath.substring('/snapshot/'.length);+ const response = snapshotServer.serveSnapshot(pageOrFrameId, url.searchParams, url.href);+ if (isDeployedAsHttps)+ response.headers.set('Content-Security-Policy', 'upgrade-insecure-requests');+ return response;+ }- if (relativePath.startsWith('/file/')) {- const path = url.searchParams.get('path')!;- const fileURL = traceFileURL(path);- const response = await fetch(fileURL);- if (response.status === 404)- return new Response(null, { status: 404 });- return response;- }+ if (relativePath?.startsWith('/closest-screenshot/')) {+ const { snapshotServer } = loadedTrace(url);+ if (!snapshotServer)+ return new Response(null, { status: 404 });+ const pageOrFrameId = relativePath.substring('/closest-screenshot/'.length);+ return snapshotServer.serveClosestScreenshot(pageOrFrameId, url.searchParams);+ }- // Fallback for static assets.- return fetch(event.request);+ if (relativePath?.startsWith('/sha1/')) {+ const { traceModel } = loadedTrace(url);+ const blob = await traceModel?.resourceForSha1(relativePath.slice('/sha1/'.length));+ if (blob)+ return new Response(blob, { status: 200, headers: downloadHeaders(url.searchParams) });+ return new Response(null, { status: 404 });+ }++ if (relativePath?.startsWith('/file/')) {+ const path = url.searchParams.get('path')!;+ return await fetch(traceFileURL(path));}+ // Fallback for static assets.+ if (relativePath)+ return fetch(event.request);+const snapshotUrl = client!.url;const traceUrl = new URL(snapshotUrl).searchParams.get('trace')!;const { snapshotServer } = loadedTraces.get(traceUrl) || {};@@ -186,6 +210,13 @@ function downloadHeaders(searchParams: URLSearchParams): Headers | undefined {return headers;}+const emptyLoadedTrace = { traceModel: undefined, snapshotServer: undefined };++function loadedTrace(url: URL): LoadedTrace | { traceModel: undefined, snapshotServer: undefined } {+ const traceUrl = url.searchParams.get('trace');+ return traceUrl ? loadedTraces.get(traceUrl) ?? emptyLoadedTrace : emptyLoadedTrace;+}+async function gc() {const clients = await self.clients.matchAll();const usedTraces = new Set<string>();diff --git a/packages/trace-viewer/src/ui/attachmentsTab.tsx b/packages/trace-viewer/src/ui/attachmentsTab.tsxindex fbe67b6d93..3a9322ecdc 100644--- a/packages/trace-viewer/src/ui/attachmentsTab.tsx+++ b/packages/trace-viewer/src/ui/attachmentsTab.tsx@@ -17,14 +17,16 @@import * as React from 'react';import './attachmentsTab.css';import { ImageDiffView } from '@web/shared/imageDiffView';-import type { Attachment, MultiTraceModel } from './modelUtil';import { PlaceholderPanel } from './placeholderPanel';-import type { AfterActionTraceEventAttachment } from '@trace/trace';import { CodeMirrorWrapper, lineHeight } from '@web/components/codeMirrorWrapper';import { isTextualMimeType } from '@isomorphic/mimeType';import { Expandable } from '@web/components/expandable';import { linkifyText } from '@web/renderUtils';import { clsx, useFlash } from '@web/uiUtils';+import { TraceModelContext } from './traceModelContext';++import type { Attachment, MultiTraceModel } from './modelUtil';+import type { AfterActionTraceEventAttachment } from '@trace/trace';type ExpandableAttachmentProps = {attachment: Attachment;@@ -32,6 +34,7 @@ type ExpandableAttachmentProps = {};const ExpandableAttachment: React.FunctionComponent<ExpandableAttachmentProps> = ({ attachment, reveal }) => {+ const model = React.useContext(TraceModelContext);const [expanded, setExpanded] = React.useState(false);const [attachmentText, setAttachmentText] = React.useState<string | null>(null);const [placeholder, setPlaceholder] = React.useState<string | null>(null);@@ -51,14 +54,14 @@ const ExpandableAttachment: React.FunctionComponent<ExpandableAttachmentProps> =React.useEffect(() => {if (expanded && attachmentText === null && placeholder === null) {setPlaceholder('Loading ...');- fetch(attachmentURL(attachment)).then(response => response.text()).then(text => {+ fetch(attachmentURL(model, attachment)).then(response => response.text()).then(text => {setAttachmentText(text);setPlaceholder(null);}).catch(e => {setPlaceholder('Failed to load: ' + e.message);});}- }, [expanded, attachmentText, placeholder, attachment]);+ }, [model, expanded, attachmentText, placeholder, attachment]);const snippetHeight = React.useMemo(() => {const lineCount = attachmentText ? attachmentText.split('\n').length : 0;@@ -67,7 +70,7 @@ const ExpandableAttachment: React.FunctionComponent<ExpandableAttachmentProps> =const title = <span style={{ marginLeft: 5 }} ref={ref} aria-label={attachment.name}><span>{linkifyText(attachment.name)}</span>- {hasContent && <a style={{ marginLeft: 5 }} href={downloadURL(attachment)}>download</a>}+ {hasContent && <a style={{ marginLeft: 5 }} href={downloadURL(model, attachment)}>download</a>}</span>;if (!isTextAttachment || !hasContent)@@ -91,9 +94,9 @@ const ExpandableAttachment: React.FunctionComponent<ExpandableAttachmentProps> =};export const AttachmentsTab: React.FunctionComponent<{- model: MultiTraceModel | undefined,revealedAttachment?: [AfterActionTraceEventAttachment, number],-}> = ({ model, revealedAttachment }) => {+}> = ({ revealedAttachment }) => {+ const model = React.useContext(TraceModelContext);const { diffMap, screenshots, attachments } = React.useMemo(() => {const attachments = new Set(model?.visibleAttachments ?? []);const screenshots = new Set<Attachment>();@@ -127,15 +130,15 @@ export const AttachmentsTab: React.FunctionComponent<{{expected && actual && <div className='attachments-section'>Image diff</div>}{expected && actual && <ImageDiffView noTargetBlank={true} diff={{name: 'Image diff',- expected: { attachment: { ...expected, path: downloadURL(expected) }, title: 'Expected' },- actual: { attachment: { ...actual, path: downloadURL(actual) } },- diff: diff ? { attachment: { ...diff, path: downloadURL(diff) } } : undefined,+ expected: { attachment: { ...expected, path: downloadURL(model, expected) }, title: 'Expected' },+ actual: { attachment: { ...actual, path: downloadURL(model, actual) } },+ diff: diff ? { attachment: { ...diff, path: downloadURL(model, diff) } } : undefined,}} />}</>;})}{screenshots.size ? <div className='attachments-section'>Screenshots</div> : undefined}{[...screenshots.values()].map((a, i) => {- const url = attachmentURL(a);+ const url = attachmentURL(model, a);return <div className='attachment-item' key={`screenshot-${i}`}><div><img draggable='false' src={url} /></div><div><a target='_blank' href={url} rel='noreferrer'>{a.name}</a></div>@@ -157,21 +160,17 @@ function isEqualAttachment(a: Attachment, b: AfterActionTraceEventAttachment): breturn a.name === b.name && a.path === b.path && a.sha1 === b.sha1;}-export function attachmentURL(attachment: Attachment, queryParams: Record<string, string> = {}) {- const params = new URLSearchParams(queryParams);- if (attachment.sha1) {- params.set('trace', attachment.traceUrl);- return 'sha1/' + attachment.sha1 + '?' + params.toString();- }- params.set('path', attachment.path!);- return 'file?' + params.toString();+export function attachmentURL(model: MultiTraceModel | undefined, attachment: Attachment) {+ if (model && attachment.sha1)+ return model.createRelativeUrl(`sha1/${attachment.sha1}`) ;+ return `file?path=${encodeURIComponent(attachment.path!)}`;}-function downloadURL(attachment: Attachment) {- const params = { dn: attachment.name } as Record<string, string>;+function downloadURL(model: MultiTraceModel | undefined, attachment: Attachment) {+ let suffix = attachment.contentType ? `&dn=${encodeURIComponent(attachment.name)}` : '';if (attachment.contentType)- params.dct = attachment.contentType;- return attachmentURL(attachment, params);+ suffix += `&dct=${encodeURIComponent(attachment.contentType)}`;+ return attachmentURL(model, attachment) + suffix;}function attachmentKey(attachment: Attachment, index: number) {diff --git a/packages/trace-viewer/src/ui/errorsTab.tsx b/packages/trace-viewer/src/ui/errorsTab.tsxindex 3b67545af8..717714a827 100644--- a/packages/trace-viewer/src/ui/errorsTab.tsx+++ b/packages/trace-viewer/src/ui/errorsTab.tsx@@ -27,6 +27,7 @@ import { copyPrompt, stripAnsiEscapes } from '@web/shared/prompts';import { MetadataWithCommitInfo } from '@testIsomorphic/types';import { calculateSha1 } from './sourceTab';import type { StackFrame } from '@protocol/channels';+import { TraceModelContext } from './traceModelContext';const CopyPromptButton: React.FC<{ prompt: string }> = ({ prompt }) => {return (@@ -85,17 +86,17 @@ function ErrorView({ message, error, sdkLanguage, revealInSource }: { message: sexport const ErrorsTab: React.FunctionComponent<{errorsModel: ErrorsTabModel,- model?: modelUtil.MultiTraceModel,wallTime: number,sdkLanguage: Language,revealInSource: (error: modelUtil.ErrorDescription) => void,testRunMetadata: MetadataWithCommitInfo | undefined,-}> = ({ errorsModel, model, sdkLanguage, revealInSource, wallTime, testRunMetadata }) => {+}> = ({ errorsModel, sdkLanguage, revealInSource, wallTime, testRunMetadata }) => {+ const model = React.useContext(TraceModelContext);const errorContext = useAsyncMemo(async () => {const attachment = model?.attachments.find(a => a.name === 'error-context');if (!attachment)return;- return await fetch(attachmentURL(attachment)).then(r => r.text());+ return await fetch(attachmentURL(model, attachment)).then(r => r.text());}, [model], undefined);const buildCodeFrame = React.useCallback(async (error: modelUtil.ErrorDescription) => {@@ -103,8 +104,8 @@ export const ErrorsTab: React.FunctionComponent<{if (!location)return;- let response = await fetch(`sha1/src@${await calculateSha1(location.file)}.txt`);- if (response.status === 404)+ let response = model ? await fetch(model.createRelativeUrl(`sha1/src@${await calculateSha1(location.file)}.txt`)) : undefined;+ if (!response || response.status === 404)response = await fetch(`file?path=${encodeURIComponent(location.file)}`);if (response.status >= 400)return;@@ -118,7 +119,7 @@ export const ErrorsTab: React.FunctionComponent<{linesAbove: 100,linesBelow: 100,});- }, []);+ }, [model]);const prompt = useAsyncMemo(() => copyPrompt(diff --git a/packages/trace-viewer/src/ui/filmStrip.tsx b/packages/trace-viewer/src/ui/filmStrip.tsxindex 19ed90505d..73b8b1410c 100644--- a/packages/trace-viewer/src/ui/filmStrip.tsx+++ b/packages/trace-viewer/src/ui/filmStrip.tsx@@ -19,9 +19,10 @@ import type { Boundaries, Size } from './geometry';import * as React from 'react';import { useMeasure, upperBound } from '@web/uiUtils';import type { PageEntry } from '../types/entries';-import type { ActionTraceEventInContext, MultiTraceModel } from './modelUtil';+import type { ActionTraceEventInContext } from './modelUtil';import { renderAction } from './actionList';import type { Language } from '@isomorphic/locatorGenerators';+import { TraceModelContext } from './traceModelContext';export type FilmStripPreviewPoint = {x: number;@@ -35,10 +36,10 @@ const frameMargin = 2.5;const rowHeight = tileSize.height + frameMargin * 2;export const FilmStrip: React.FunctionComponent<{- model?: MultiTraceModel,boundaries: Boundaries,previewPoint?: FilmStripPreviewPoint,-}> = ({ model, boundaries, previewPoint }) => {+}> = ({ boundaries, previewPoint }) => {+ const model = React.useContext(TraceModelContext);const [measure, ref] = useMeasure<HTMLDivElement>();const lanesRef = React.useRef<HTMLDivElement>(null);@@ -70,14 +71,14 @@ export const FilmStrip: React.FunctionComponent<{key={index}/> : null)}</div>- {previewPoint?.x !== undefined &&+ {model && previewPoint?.x !== undefined &&<div className='film-strip-hover' style={{top: measure.bottom + 5,left: Math.min(previewPoint!.x, measure.width - (previewSize ? previewSize.width : 0) - 10),}}>{previewPoint.action && <div className='film-strip-hover-title'>{renderAction(previewPoint.action, previewPoint)}</div>}{previewImage && previewSize && <div style={{ width: previewSize.width, height: previewSize.height }}>- <img src={`sha1/${previewImage.sha1}`} width={previewSize.width} height={previewSize.height} />+ <img src={model.createRelativeUrl(`sha1/${previewImage.sha1}`)} width={previewSize.width} height={previewSize.height} /></div>}</div>}@@ -89,6 +90,7 @@ const FilmStripLane: React.FunctionComponent<{page: PageEntry,width: number,}> = ({ boundaries, page, width }) => {+ const model = React.useContext(TraceModelContext);const viewportSize = { width: 0, height: 0 };const screencastFrames = page.screencastFrames;for (const frame of screencastFrames) {@@ -113,7 +115,7 @@ const FilmStripLane: React.FunctionComponent<{frames.push(<div className='film-strip-frame' key={i} style={{width: frameSize.width,height: frameSize.height,- backgroundImage: `url(sha1/${screencastFrames[index].sha1})`,+ backgroundImage: `url(${model?.createRelativeUrl('sha1/' + screencastFrames[index].sha1)})`,backgroundSize: `${frameSize.width}px ${frameSize.height}px`,margin: frameMargin,marginRight: frameMargin,@@ -123,7 +125,7 @@ const FilmStripLane: React.FunctionComponent<{frames.push(<div className='film-strip-frame' key={frames.length} style={{width: frameSize.width,height: frameSize.height,- backgroundImage: `url(sha1/${screencastFrames[screencastFrames.length - 1].sha1})`,+ backgroundImage: `url(${model?.createRelativeUrl('sha1/' + screencastFrames[screencastFrames.length - 1].sha1)})`,backgroundSize: `${frameSize.width}px ${frameSize.height}px`,margin: frameMargin,marginRight: frameMargin,diff --git a/packages/trace-viewer/src/ui/liveWorkbenchLoader.tsx b/packages/trace-viewer/src/ui/liveWorkbenchLoader.tsxindex 608ece9fc1..e97bc0f7d6 100644--- a/packages/trace-viewer/src/ui/liveWorkbenchLoader.tsx+++ b/packages/trace-viewer/src/ui/liveWorkbenchLoader.tsx@@ -20,6 +20,7 @@ import './workbenchLoader.css';import { Workbench } from './workbench';import type { ContextEntry } from '../types/entries';+import { TraceModelContext } from './traceModelContext';export const LiveWorkbenchLoader: React.FC<{ traceJson: string }> = ({ traceJson }) => {const [model, setModel] = React.useState<MultiTraceModel | undefined>(undefined);@@ -48,7 +49,9 @@ export const LiveWorkbenchLoader: React.FC<{ traceJson: string }> = ({ traceJson};}, [traceJson, counter]);- return <Workbench model={model} isLive={true} />;+ return <TraceModelContext.Provider value={model}>+ <Workbench isLive={true} />+ </TraceModelContext.Provider>;};async function loadSingleTraceFile(traceJson: string): Promise<MultiTraceModel> {diff --git a/packages/trace-viewer/src/ui/modelUtil.ts b/packages/trace-viewer/src/ui/modelUtil.tsindex 4db70cd4c1..c78bee156f 100644--- a/packages/trace-viewer/src/ui/modelUtil.ts+++ b/packages/trace-viewer/src/ui/modelUtil.ts@@ -59,7 +59,7 @@ export type ErrorDescription = {message: string;};-export type Attachment = trace.AfterActionTraceEventAttachment & { traceUrl: string };+export type Attachment = trace.AfterActionTraceEventAttachment;export class MultiTraceModel {readonly startTime: number;@@ -128,6 +128,12 @@ export class MultiTraceModel {}}+ createRelativeUrl(path: string) {+ const url = new URL('http://localhost/' + path);+ url.searchParams.set('trace', this.traceUrl);+ return url.toString().substring('http://localhost/'.length);+ }+failedAction() {// This find innermost action for nested ones.return this.actions.findLast(a => a.error);diff --git a/packages/trace-viewer/src/ui/networkResourceDetails.tsx b/packages/trace-viewer/src/ui/networkResourceDetails.tsxindex 5c87cb8d75..b0a257b1e1 100644--- a/packages/trace-viewer/src/ui/networkResourceDetails.tsx+++ b/packages/trace-viewer/src/ui/networkResourceDetails.tsx@@ -26,6 +26,7 @@ import { getAPIRequestCodeGen } from './codegen';import type { Language } from '@isomorphic/locatorGenerators';import { msToString, useAsyncMemo } from '@web/uiUtils';import type { Entry } from '@trace/har';+import { TraceModelContext } from './traceModelContext';type RequestBody = { text: string, mimeType?: string } | null;@@ -37,13 +38,14 @@ export const NetworkResourceDetails: React.FunctionComponent<{onClose: () => void;}> = ({ resource, sdkLanguage, startTimeOffset, onClose }) => {const [selectedTab, setSelectedTab] = React.useState('request');+ const model = React.useContext(TraceModelContext);const requestBody = useAsyncMemo<RequestBody>(async () => {- if (resource.request.postData) {+ if (model && resource.request.postData) {const requestContentTypeHeader = resource.request.headers.find(q => q.name.toLowerCase() === 'content-type');const requestContentType = requestContentTypeHeader ? requestContentTypeHeader.value : '';if (resource.request.postData._sha1) {- const response = await fetch(`sha1/${resource.request.postData._sha1}`);+ const response = await fetch(model.createRelativeUrl(`sha1/${resource.request.postData._sha1}`));return { text: formatBody(await response.text(), requestContentType), mimeType: requestContentType };} else {return { text: formatBody(resource.request.postData.text, requestContentType), mimeType: requestContentType };@@ -145,14 +147,15 @@ const ResponseTab: React.FunctionComponent<{const BodyTab: React.FunctionComponent<{resource: ResourceSnapshot;}> = ({ resource }) => {+ const model = React.useContext(TraceModelContext);const [responseBody, setResponseBody] = React.useState<{ dataUrl?: string, text?: string, mimeType?: string, font?: BufferSource } | null>(null);React.useEffect(() => {const readResources = async () => {- if (resource.response.content._sha1) {+ if (model && resource.response.content._sha1) {const useBase64 = resource.response.content.mimeType.includes('image');const isFont = resource.response.content.mimeType.includes('font');- const response = await fetch(`sha1/${resource.response.content._sha1}`);+ const response = await fetch(model.createRelativeUrl(`sha1/${resource.response.content._sha1}`));if (useBase64) {const blob = await response.blob();const reader = new FileReader();@@ -172,7 +175,7 @@ const BodyTab: React.FunctionComponent<{};readResources();- }, [resource]);+ }, [resource, model]);return <div className='network-request-details-tab'>{!resource.response.content._sha1 && <div>Response body is not available for this request.</div>}diff --git a/packages/trace-viewer/src/ui/sourceTab.tsx b/packages/trace-viewer/src/ui/sourceTab.tsxindex 4b03fd8c15..11c7c571f7 100644--- a/packages/trace-viewer/src/ui/sourceTab.tsx+++ b/packages/trace-viewer/src/ui/sourceTab.tsx@@ -26,8 +26,10 @@ import type { StackFrame } from '@protocol/channels';import { CopyToClipboard } from './copyToClipboard';import { ToolbarButton } from '@web/components/toolbarButton';import { Toolbar } from '@web/components/toolbar';+import { TraceModelContext } from './traceModelContext';function useSources(stack: StackFrame[] | undefined, selectedFrame: number, sources: Map<string, SourceModel>, rootDir?: string, fallbackLocation?: SourceLocation) {+ const model = React.useContext(TraceModelContext);return useAsyncMemo<{ source: SourceModel, targetLine?: number, fileName?: string, highlight: SourceHighlight[], location?: SourceLocation }>(async () => {const actionLocation = stack?.[selectedFrame];const location = actionLocation?.file ? actionLocation : fallbackLocation;@@ -53,8 +55,8 @@ function useSources(stack: StackFrame[] | undefined, selectedFrame: number, sour} else if (source.content === undefined || (location === fallbackLocation)) {const sha1 = await calculateSha1(file);try {- let response = await fetch(`sha1/src@${sha1}.txt`);- if (response.status === 404)+ let response = model ? await fetch(model.createRelativeUrl(`sha1/src@${sha1}.txt`)) : undefined;+ if (!response || response.status === 404)response = await fetch(`file?path=${encodeURIComponent(file)}`);if (response.status >= 400)source.content = `<Unable to read "${file}">`;@@ -64,7 +66,7 @@ function useSources(stack: StackFrame[] | undefined, selectedFrame: number, soursource.content = `<Unable to read "${file}">`;}}- return { source, highlight, targetLine, fileName, location };+ return { model, source, highlight, targetLine, fileName, location };}, [stack, selectedFrame, rootDir, fallbackLocation], { source: { errors: [], content: 'Loading\u2026' }, highlight: [] });}diff --git a/packages/trace-viewer/src/ui/timeline.tsx b/packages/trace-viewer/src/ui/timeline.tsxindex 05da35e444..6b3344d99d 100644--- a/packages/trace-viewer/src/ui/timeline.tsx+++ b/packages/trace-viewer/src/ui/timeline.tsx@@ -250,7 +250,7 @@ export const Timeline: React.FunctionComponent<{})}</div><div style={{ height: 8 }}></div>- <FilmStrip model={model} boundaries={boundaries} previewPoint={previewPoint} />+ <FilmStrip boundaries={boundaries} previewPoint={previewPoint} /><div className='timeline-bars'>{bars.filter(bar => !bar.action || bar.action.class !== 'Test')diff --git a/packages/trace-viewer/src/ui/traceModelContext.tsx b/packages/trace-viewer/src/ui/traceModelContext.tsxnew file mode 100644index 0000000000..ab4adf95ab--- /dev/null+++ b/packages/trace-viewer/src/ui/traceModelContext.tsx@@ -0,0 +1,20 @@+/*+ 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 * as React from 'react';+import type { MultiTraceModel } from './modelUtil';++export const TraceModelContext = React.createContext<MultiTraceModel | undefined>(undefined);diff --git a/packages/trace-viewer/src/ui/uiModeTraceView.tsx b/packages/trace-viewer/src/ui/uiModeTraceView.tsxindex 382e6e669f..e72a40a77b 100644--- a/packages/trace-viewer/src/ui/uiModeTraceView.tsx+++ b/packages/trace-viewer/src/ui/uiModeTraceView.tsx@@ -24,6 +24,7 @@ import type { ContextEntry } from '../types/entries';import type { SourceLocation } from './modelUtil';import { MultiTraceModel } from './modelUtil';import { Workbench } from './workbench';+import { TraceModelContext } from './traceModelContext';export const TraceView: React.FC<{item: { treeItem?: TreeItem, testFile?: SourceLocation, testCase?: reporterTypes.TestCase },@@ -88,18 +89,19 @@ export const TraceView: React.FC<{};}, [outputDir, item, setModel, counter, setCounter, pathSeparator]);- return <Workbench- key='workbench'- model={model?.model}- showSourcesFirst={true}- rootDir={rootDir}- fallbackLocation={item.testFile}- isLive={model?.isLive}- status={item.treeItem?.status}- annotations={item.testCase?.annotations ?? []}- onOpenExternally={onOpenExternally}- revealSource={revealSource}- />;+ return <TraceModelContext.Provider value={model?.model}>+ <Workbench+ key='workbench'+ showSourcesFirst={true}+ rootDir={rootDir}+ fallbackLocation={item.testFile}+ isLive={model?.isLive}+ status={item.treeItem?.status}+ annotations={item.testCase?.annotations ?? []}+ onOpenExternally={onOpenExternally}+ revealSource={revealSource}+ />;+ </TraceModelContext.Provider>;};const outputDirForTestCase = (testCase: reporterTypes.TestCase): string | undefined => {diff --git a/packages/trace-viewer/src/ui/workbench.tsx b/packages/trace-viewer/src/ui/workbench.tsxindex 86ce06f046..bd23dcac77 100644--- a/packages/trace-viewer/src/ui/workbench.tsx+++ b/packages/trace-viewer/src/ui/workbench.tsx@@ -47,9 +47,9 @@ import { MetadataWithCommitInfo } from '@testIsomorphic/types';import type { ActionGroup } from '@isomorphic/protocolFormatter';import { DialogToolbarButton } from '@web/components/dialogToolbarButton';import { SettingsView } from './settingsView';+import { TraceModelContext } from './traceModelContext';export const Workbench: React.FunctionComponent<{- model?: modelUtil.MultiTraceModel,showSourcesFirst?: boolean,rootDir?: string,fallbackLocation?: modelUtil.SourceLocation,@@ -61,7 +61,8 @@ export const Workbench: React.FunctionComponent<{onOpenExternally?: (location: modelUtil.SourceLocation) => void,revealSource?: boolean,testRunMetadata?: MetadataWithCommitInfo,-}> = ({ model, showSourcesFirst, rootDir, fallbackLocation, isLive, hideTimeline, status, annotations, inert, onOpenExternally, revealSource, testRunMetadata }) => {+}> = ({ showSourcesFirst, rootDir, fallbackLocation, isLive, hideTimeline, status, annotations, inert, onOpenExternally, revealSource, testRunMetadata }) => {+ const model = React.useContext(TraceModelContext);const [selectedCallId, setSelectedCallId] = React.useState<string | undefined>(undefined);const [revealedError, setRevealedError] = React.useState<modelUtil.ErrorDescription | undefined>(undefined);const [revealedAttachment, setRevealedAttachment] = React.useState<[attachment: AfterActionTraceEventAttachment, renderCounter: number] | undefined>(undefined);@@ -199,7 +200,7 @@ export const Workbench: React.FunctionComponent<{id: 'errors',title: 'Errors',errorCount: errorsModel.errors.size,- render: () => <ErrorsTab errorsModel={errorsModel} model={model} testRunMetadata={testRunMetadata} sdkLanguage={sdkLanguage} revealInSource={error => {+ render: () => <ErrorsTab errorsModel={errorsModel} testRunMetadata={testRunMetadata} sdkLanguage={sdkLanguage} revealInSource={error => {if (error.action)setSelectedAction(error.action);else@@ -249,7 +250,7 @@ export const Workbench: React.FunctionComponent<{id: 'attachments',title: 'Attachments',count: model?.visibleAttachments.length,- render: () => <AttachmentsTab model={model} revealedAttachment={revealedAttachment} />+ render: () => <AttachmentsTab revealedAttachment={revealedAttachment} />};const tabs: TabbedPaneTabModel[] = [diff --git a/packages/trace-viewer/src/ui/workbenchLoader.tsx b/packages/trace-viewer/src/ui/workbenchLoader.tsxindex 9def0cfdb9..19da4a51eb 100644--- a/packages/trace-viewer/src/ui/workbenchLoader.tsx+++ b/packages/trace-viewer/src/ui/workbenchLoader.tsx@@ -22,6 +22,7 @@ import { TestServerConnection, WebSocketTestServerTransport } from '@testIsomorpimport { DialogToolbarButton } from '@web/components/dialogToolbarButton';import { Dialog } from '@web/shared/dialog';import { DefaultSettingsView } from './defaultSettingsView';+import { TraceModelContext } from './traceModelContext';export const WorkbenchLoader: React.FunctionComponent<{}> = () => {@@ -189,7 +190,9 @@ export const WorkbenchLoader: React.FunctionComponent<{<DefaultSettingsView /></DialogToolbarButton></div>- <Workbench model={model} inert={showFileUploadDropArea} />+ <TraceModelContext.Provider value={model}>+ <Workbench inert={showFileUploadDropArea} />+ </TraceModelContext.Provider>{fileForLocalModeError && <div className='drop-target'><div>Trace Viewer uses Service Workers to show traces. To view trace:</div><div style={{ paddingTop: 20 }}>