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
feat(dashboard): add a debugger actions panel (#41711)
Dmitry Gozmanc28b53e62423
diff --git a/packages/dashboard/src/dashboard.css b/packages/dashboard/src/dashboard.cssindex 288a4fbdce..2da2f34e02 100644--- a/packages/dashboard/src/dashboard.css+++ b/packages/dashboard/src/dashboard.css@@ -53,6 +53,23 @@box-shadow: 0 0 0 2px rgb(var(--recording-red) / 0.35);}+.mode-toggle.toolbar-button.toggled.mode-debugger,+.mode-toggle.toolbar-button.toggled.mode-debugger > .codicon {+ color: var(--color-accent-fg);+}++.mode-toggle.toolbar-button.toggled.mode-debugger {+ background: var(--color-accent-subtle);+ box-shadow: none;+}++.debugger-paused-label {+ flex: none;+ font-weight: 600;+ color: var(--color-attention-fg);+ white-space: nowrap;+}+.mode-toggle.flash {animation: mode-toggle-flash 0.45s ease-in-out 4;}@@ -75,7 +92,7 @@height: 40px;min-height: 40px;background: var(--color-canvas-overlay);- padding: 0 8px;+ padding: 0 12px;position: relative;z-index: 100;border-bottom: 1px solid var(--color-border-muted);diff --git a/packages/dashboard/src/dashboard.tsx b/packages/dashboard/src/dashboard.tsxindex d4a0adf380..e9f5473344 100644--- a/packages/dashboard/src/dashboard.tsx+++ b/packages/dashboard/src/dashboard.tsx@@ -20,8 +20,10 @@ import { ChevronLeftIcon, ChevronRightIcon, LockIcon, LockOpenIcon, ReloadIcon,import { clientToViewport, getImageLayout } from './imageLayout';import { Recording } from './recording';import { AnnotateSidebar, AnnotateOverlay } from './annotateView';+import { DebuggerPanel } from './debuggerPanel';import { ToolbarButton } from '@web/components/toolbarButton';+import { SplitView } from '@web/components/splitView';import { useMeasureForRef } from '@web/uiUtils';import type { DashboardModel } from './dashboardModel';@@ -66,7 +68,7 @@ export const Dashboard: React.FC<DashboardProps> = ({ model }) => {const [, setRevision] = React.useState(0);React.useEffect(() => model.subscribe(() => setRevision(r => r + 1)), [model]);- const { tabs, mode, recording, liveFrame, annotateSession, pendingCapture } = model.state;+ const { tabs, mode, recording, liveFrame, annotateSession, pendingCapture, debuggerPanelOpen, debuggerPaused, apiCalls } = model.state;const interactive = mode === 'interactive';const annotateActive = !!annotateSession;const selectedFrame = annotateSession?.frames.find(f => f.id === annotateSession.selectedFrameId) ?? null;@@ -234,145 +236,175 @@ export const Dashboard: React.FC<DashboardProps> = ({ model }) => {const modeLabel = annotateActive ? 'Dashboard: annotate' : isRecording ? 'Dashboard: record' : 'Dashboard';const overlayOpen = !!selectedFrame;++ let actionPointStyle: React.CSSProperties | undefined;+ if (debuggerPanelOpen && liveFrame?.viewportWidth && liveFrame?.viewportHeight) {+ const call = [...apiCalls].reverse().find(c => c.actionPoint && c.status === 'running');+ if (call?.actionPoint) {+ actionPointStyle = {+ left: `${(call.actionPoint.x / liveFrame.viewportWidth) * 100}%`,+ top: `${(call.actionPoint.y / liveFrame.viewportHeight) * 100}%`,+ };+ }+ }+return (<main className={'dashboard-view' + (interactive ? ' interactive' : '') + (annotateActive ? ' has-annotate-sidebar' : '')} aria-label={modeLabel}>- <div className='dashboard-main'>- {/* Toolbar */}- <div ref={toolbarRef} className='toolbar' hidden={overlayOpen}>- <ToolbarButton- ref={interactiveBtnRef}- className='mode-toggle mode-interactive'- title={interactive ? 'Disable interactive mode' : 'Enable interactive mode'}- toggled={interactive}- disabled={!ready}- onClick={() => {- if (interactive)- model.toggleInteractive();- else- model.enterInteractive();- }}- >- {interactive ? <LockOpenIcon /> : <LockIcon />}- </ToolbarButton>- <ToolbarButton- className='mode-annotate'- title={annotateActive ? 'Add screenshot' : 'Take screenshot'}- disabled={!ready || pendingCapture}- onClick={() => {- if (annotateActive)- model.addAnnotateFrame();- else- model.enterAnnotate('user');- }}- >- <ScreenshotRegionIcon />- </ToolbarButton>- <ToolbarButton- className='mode-toggle mode-record'- title={isRecording ? 'Stop recording' : 'Record video'}- icon='record'- toggled={isRecording}- disabled={!ready || showRecording}- onClick={() => {- if (isRecording)- model.stopRecording();- else- model.startRecording();- }}- >- {isRecording && <span className='mode-record-label'>Recording...</span>}- </ToolbarButton>- </div>-- {/* Viewport */}- <div className='viewport-wrapper'>- <div ref={viewportMainRef} className='viewport-main'>- <div className='browser-window' style={windowStyle}>- {showBrowserChrome && (- <div ref={browserChromeRef} className='browser-chrome'>- <button className='nav-btn' title='Back' aria-disabled={!interactive || undefined} onClick={() => {- if (!interactive) {- flashInteractiveHint();- return;- }- model.back();- }}>- <ChevronLeftIcon />- </button>- <button className='nav-btn' title='Forward' aria-disabled={!interactive || undefined} onClick={() => {- if (!interactive) {- flashInteractiveHint();- return;- }- model.forward();- }}>- <ChevronRightIcon />- </button>- <button className='nav-btn' title='Reload' aria-disabled={!interactive || undefined} onClick={() => {- if (!interactive) {- flashInteractiveHint();- return;- }- model.reload();- }}>- <ReloadIcon />- </button>- <div className='omnibox-wrap'>- <input- id='omnibox'- className='omnibox'- type='text'- placeholder='Search or enter URL'- spellCheck={false}- autoComplete='off'- value={omniboxValue}- onChange={e => setOmniboxValue(e.target.value)}- onKeyDown={e => {- if (!interactive)- return;- onOmniboxKeyDown(e);- }}- onFocus={e => {- if (!interactive) {- flashInteractiveHint();- e.target.blur();- return;- }- e.target.select();- }}- aria-disabled={!interactive || undefined}- aria-label={interactive ? 'Search or enter URL' : 'URL input - enable interactive mode to use this field'}- readOnly={!interactive}- />+ <SplitView+ orientation='vertical'+ sidebarSize={260}+ minSidebarSize={140}+ settingName='dashboardActionsPanel'+ sidebarHidden={!debuggerPanelOpen}+ sidebar={<DebuggerPanel model={model} />}+ main={<div className='dashboard-main'>+ {/* Toolbar */}+ <div ref={toolbarRef} className='toolbar' hidden={overlayOpen}>+ <ToolbarButton+ ref={interactiveBtnRef}+ className='mode-toggle mode-interactive'+ title={interactive ? 'Disable interactive mode' : 'Enable interactive mode'}+ toggled={interactive}+ disabled={!ready}+ onClick={() => {+ if (interactive)+ model.toggleInteractive();+ else+ model.enterInteractive();+ }}+ >+ {interactive ? <LockOpenIcon /> : <LockIcon />}+ </ToolbarButton>+ <ToolbarButton+ className='mode-annotate'+ title={annotateActive ? 'Add screenshot' : 'Take screenshot'}+ disabled={!ready || pendingCapture}+ onClick={() => {+ if (annotateActive)+ model.addAnnotateFrame();+ else+ model.enterAnnotate('user');+ }}+ >+ <ScreenshotRegionIcon />+ </ToolbarButton>+ <ToolbarButton+ className='mode-toggle mode-record'+ title={isRecording ? 'Stop recording' : 'Record video'}+ icon='record'+ toggled={isRecording}+ disabled={!ready || showRecording}+ onClick={() => {+ if (isRecording)+ model.stopRecording();+ else+ model.startRecording();+ }}+ >+ {isRecording && <span className='mode-record-label'>Recording...</span>}+ </ToolbarButton>+ <ToolbarButton+ className='mode-toggle mode-debugger'+ title={debuggerPanelOpen ? 'Hide actions panel' : 'Show actions panel'}+ icon='list-unordered'+ toggled={debuggerPanelOpen}+ onClick={() => model.toggleDebuggerPanel()}+ />+ {debuggerPaused && <span className='debugger-paused-label'>Paused</span>}+ <div style={{ flex: 'auto' }}></div>+ </div>++ {/* Viewport */}+ <div className='viewport-wrapper'>+ <div ref={viewportMainRef} className='viewport-main'>+ <div className='browser-window' style={windowStyle}>+ {showBrowserChrome && (+ <div ref={browserChromeRef} className='browser-chrome'>+ <button className='nav-btn' title='Back' aria-disabled={!interactive || undefined} onClick={() => {+ if (!interactive) {+ flashInteractiveHint();+ return;+ }+ model.back();+ }}>+ <ChevronLeftIcon />+ </button>+ <button className='nav-btn' title='Forward' aria-disabled={!interactive || undefined} onClick={() => {+ if (!interactive) {+ flashInteractiveHint();+ return;+ }+ model.forward();+ }}>+ <ChevronRightIcon />+ </button>+ <button className='nav-btn' title='Reload' aria-disabled={!interactive || undefined} onClick={() => {+ if (!interactive) {+ flashInteractiveHint();+ return;+ }+ model.reload();+ }}>+ <ReloadIcon />+ </button>+ <div className='omnibox-wrap'>+ <input+ id='omnibox'+ className='omnibox'+ type='text'+ placeholder='Search or enter URL'+ spellCheck={false}+ autoComplete='off'+ value={omniboxValue}+ onChange={e => setOmniboxValue(e.target.value)}+ onKeyDown={e => {+ if (!interactive)+ return;+ onOmniboxKeyDown(e);+ }}+ onFocus={e => {+ if (!interactive) {+ flashInteractiveHint();+ e.target.blur();+ return;+ }+ e.target.select();+ }}+ aria-disabled={!interactive || undefined}+ aria-label={interactive ? 'Search or enter URL' : 'URL input - enable interactive mode to use this field'}+ readOnly={!interactive}+ />+ </div></div>+ )}+ <div+ ref={screenRef}+ className='screen'+ tabIndex={0}+ style={{ display: liveFrame ? '' : 'none' }}+ onMouseDown={onScreenMouseDown}+ onMouseUp={onScreenMouseUp}+ onMouseMove={onScreenMouseMove}+ onWheel={onScreenWheel}+ onKeyDown={onScreenKeyDown}+ onKeyUp={onScreenKeyUp}+ onContextMenu={e => e.preventDefault()}+ >+ <img+ ref={displayRef}+ id='display'+ className='display'+ alt='screencast'+ src={liveFrame ? 'data:image/jpeg;base64,' + liveFrame.data : undefined}+ />+ {actionPointStyle && <div className='debugger-action-point' style={actionPointStyle}></div>}</div>- )}- <div- ref={screenRef}- className='screen'- tabIndex={0}- style={{ display: liveFrame ? '' : 'none' }}- onMouseDown={onScreenMouseDown}- onMouseUp={onScreenMouseUp}- onMouseMove={onScreenMouseMove}- onWheel={onScreenWheel}- onKeyDown={onScreenKeyDown}- onKeyUp={onScreenKeyUp}- onContextMenu={e => e.preventDefault()}- >- <img- ref={displayRef}- id='display'- className='display'- alt='screencast'- src={liveFrame ? 'data:image/jpeg;base64,' + liveFrame.data : undefined}- />+ {overlayText && <div className={'screen-overlay' + (liveFrame ? ' has-frame' : '')}><span>{overlayText}</span></div>}</div>- {overlayText && <div className={'screen-overlay' + (liveFrame ? ' has-frame' : '')}><span>{overlayText}</span></div>}</div></div>- </div>- </div>+ </div>}+ />{selectedFrame && (<AnnotateOverlaykey={selectedFrame.id + (annotateSession?.focusAnnotationId ?? '')}diff --git a/packages/dashboard/src/dashboardChannel.ts b/packages/dashboard/src/dashboardChannel.tsindex b09fc47e66..8f003cf049 100644--- a/packages/dashboard/src/dashboardChannel.ts+++ b/packages/dashboard/src/dashboardChannel.ts@@ -49,6 +49,27 @@ export type DashboardChannelEvents = {frame: { data: string; viewportWidth: number; viewportHeight: number };annotate: {};cancelAnnotate: {};+ apiCalls: { apiCalls: ApiCall[] };+ debuggerPaused: { paused: boolean };+ debuggerSource: { source: DebuggerSource | null };+};++export type ApiCall = {+ id: string;+ title: string;+ location?: { file: string; line?: number; column?: number };+ logs: string[];+ actionPoint?: { x: number; y: number };+ status: 'running' | 'success' | 'error';+ error?: string;+};++export type DebuggerSource = {+ file: string;+ language: 'javascript' | 'python' | 'java' | 'csharp';+ text: string;+ highlight: { line: number; type: 'running' | 'paused' | 'error' }[];+ revealLine?: number;};export type MouseButton = 'left' | 'middle' | 'right';@@ -76,6 +97,9 @@ export interface DashboardChannel {screenshot(): Promise<{ data: string; viewportWidth: number; viewportHeight: number; ariaSnapshot: string }>;submitAnnotation(params: { frames: SubmittedAnnotationFrame[]; feedback: string }): Promise<void>;cancelAnnotation(): Promise<void>;+ debuggerResume(): Promise<void>;+ debuggerPause(): Promise<void>;+ debuggerStep(): Promise<void>;on<K extends keyof DashboardChannelEvents>(event: K, listener: (params: DashboardChannelEvents[K]) => void): void;off<K extends keyof DashboardChannelEvents>(event: K, listener: (params: DashboardChannelEvents[K]) => void): void;diff --git a/packages/dashboard/src/dashboardModel.ts b/packages/dashboard/src/dashboardModel.tsindex 30f4c38bf0..ecb05edf33 100644--- a/packages/dashboard/src/dashboardModel.ts+++ b/packages/dashboard/src/dashboardModel.ts@@ -18,7 +18,7 @@ import { buildAnnotatedImage, saveAnnotationAsDownload } from './annotationImageimport { buildAnnotationZip } from './annotationZip';import type { Annotation } from './annotations';-import type { DashboardChannel, DashboardChannelEvents, MouseButton, SessionStatus, SubmittedAnnotationFrame, Tab } from './dashboardChannel';+import type { ApiCall, DashboardChannel, DashboardChannelEvents, DebuggerSource, MouseButton, SessionStatus, SubmittedAnnotationFrame, Tab } from './dashboardChannel';import type { ClientInfo } from '../../playwright-core/src/tools/cli-client/registry';import type { BrowserDescriptor } from '../../playwright-core/src/serverRegistry';@@ -62,6 +62,14 @@ export type DashboardState = {pendingCapture: boolean;mode: Mode;recording: RecordingState | null;+ // Debugger / actions panel.+ debuggerPanelOpen: boolean;+ apiCalls: ApiCall[];+ debuggerPaused: boolean;+ // Pause was requested, but the debugger has not paused yet — it engages+ // before the next action.+ debuggerPauseRequested: boolean;+ debuggerSource: DebuggerSource | null;};type Listener = () => void;@@ -76,6 +84,11 @@ const initialState: DashboardState = {pendingCapture: false,mode: 'readonly',recording: null,+ debuggerPanelOpen: false,+ apiCalls: [],+ debuggerPaused: false,+ debuggerPauseRequested: false,+ debuggerSource: null,};export class DashboardModel {@@ -94,6 +107,9 @@ export class DashboardModel {client.on('frame', params => this._emit({ liveFrame: params }));client.on('annotate', () => this.enterAnnotate('cli'));client.on('cancelAnnotate', () => this.cancelAnnotate(false));+ client.on('apiCalls', params => this._emit({ apiCalls: params.apiCalls }));+ client.on('debuggerPaused', params => this._emit({ debuggerPaused: params.paused, debuggerPauseRequested: params.paused ? false : this.state.debuggerPauseRequested }));+ client.on('debuggerSource', params => this._emit({ debuggerSource: params.source }));}subscribe(listener: Listener): () => void {@@ -268,6 +284,26 @@ export class DashboardModel {void this._discardRecording();}+ // Debugger / actions panel.++ toggleDebuggerPanel() {+ this._emit({ debuggerPanelOpen: !this.state.debuggerPanelOpen });+ }++ debuggerResume() {+ this._emit({ debuggerPauseRequested: false });+ void this._client.debuggerResume();+ }++ debuggerPause() {+ this._emit({ debuggerPauseRequested: true });+ void this._client.debuggerPause();+ }++ debuggerStep() {+ void this._client.debuggerStep();+ }+cancelAnnotate(notifyServer = true) {this._requestId++;const s = this.state;diff --git a/packages/dashboard/src/debuggerPanel.css b/packages/dashboard/src/debuggerPanel.cssnew file mode 100644index 0000000000..7ddff7631a--- /dev/null+++ b/packages/dashboard/src/debuggerPanel.css@@ -0,0 +1,170 @@+/**+ * 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.+ */++.debugger-panel {+ display: flex;+ flex-direction: column;+ flex: auto;+ width: 100%;+ height: 100%;+ background: var(--color-canvas-default);+ overflow: hidden;+}++.debugger-panel-title {+ font-weight: 600;+ padding: 0 4px;+}++.debugger-panel .debugger-run-control:not(:disabled),+.debugger-panel .debugger-run-control:not(:disabled) .codicon {+ color: var(--color-success-fg);+}++.debugger-panel.paused .toolbar,+.debugger-panel.pause-pending .toolbar {+ background: var(--color-attention-subtle);+}++.debugger-status {+ flex: none;+ padding: 0 8px;+ font-weight: 500;+ color: var(--color-attention-fg);+ white-space: nowrap;+}++.debugger-call-log {+ display: flex;+ flex-direction: column;+ flex: auto;+ width: 100%;+ min-width: 0;+ min-height: 0;+ line-height: 20px;+ white-space: pre;+ overflow: auto;+}++.debugger-source {+ display: flex;+ flex-direction: column;+ flex: auto;+ width: 100%;+ min-width: 0;+ min-height: 0;+ overflow: hidden;+}++.debugger-source-header {+ flex: none;+ padding: 2px 8px;+ font-weight: 500;+ color: var(--color-fg-muted);+ border-bottom: 1px solid var(--color-border-muted);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.debugger-source .cm-wrapper,+.debugger-source .CodeMirror {+ flex: auto;+ min-height: 0;+}++.debugger-empty {+ padding: 12px;+ color: var(--color-fg-muted);+ white-space: normal;+}++.debugger-call {+ display: flex;+ flex: none;+ flex-direction: column;+ border-top: 1px solid var(--color-border-muted);+}++.debugger-call-header {+ min-height: 24px;+ display: flex;+ align-items: center;+ padding: 0 2px;+ gap: 2px;+}++.debugger-call-header.expandable {+ cursor: pointer;+}++.debugger-call-header.expandable:hover {+ background: var(--color-canvas-subtle);+}++.debugger-call .codicon {+ padding: 0 4px;+ flex: none;+}++.debugger-call-title {+ flex: none;+ font-weight: 500;+}++.debugger-call-location {+ flex: 0 1 auto;+ overflow: hidden;+ text-overflow: ellipsis;+ color: var(--color-fg-muted);+}++.debugger-call .codicon-loading {+ margin-left: auto;+}++.debugger-call .codicon-error {+ color: var(--color-danger-fg, #cd3131);+ margin-left: auto;+}++.debugger-call.error {+ background-color: var(--color-danger-subtle, rgba(205, 49, 49, 0.1));+}++.debugger-call-message {+ flex: none;+ padding: 3px 0 3px 36px;+ display: flex;+ align-items: center;+ color: var(--color-fg-muted);+}++.debugger-call-message.error {+ color: var(--color-danger-fg, #cd3131);+ white-space: pre-wrap;+}++.debugger-action-point {+ position: absolute;+ width: 2%;+ aspect-ratio: 1;+ transform: translate(-50%, -50%);+ background: red;+ border-radius: 50%;+ pointer-events: none;+ z-index: 11;+}diff --git a/packages/dashboard/src/debuggerPanel.tsx b/packages/dashboard/src/debuggerPanel.tsxnew file mode 100644index 0000000000..e8a4659500--- /dev/null+++ b/packages/dashboard/src/debuggerPanel.tsx@@ -0,0 +1,152 @@+/**+ * 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 React from 'react';+import './debuggerPanel.css';+import { Toolbar } from '@web/components/toolbar';+import { ToolbarButton } from '@web/components/toolbarButton';+import { SplitView } from '@web/components/splitView';+import { CodeMirrorWrapper } from '@web/components/codeMirrorWrapper';+import { clsx } from '@web/uiUtils';++import type { ApiCall, DebuggerSource } from './dashboardChannel';+import type { DashboardModel } from './dashboardModel';++type DebuggerPanelProps = {+ model: DashboardModel;+};++// Modeled after the recorder's CallLogView + debug toolbar (packages/recorder/src).+export const DebuggerPanel: React.FC<DebuggerPanelProps> = ({ model }) => {+ const { apiCalls, debuggerPaused, debuggerPauseRequested, debuggerSource } = model.state;+ const callLogRef = React.useRef<HTMLDivElement>(null);+ const messagesEndRef = React.useRef<HTMLDivElement>(null);+ // Follow the log only while the user is already near the bottom, so that+ // live updates do not steal a scrolled-up position.+ const stickToBottomRef = React.useRef(true);+ // Explicit expand/collapse overrides per call id; when absent, the default is+ // driven by status (running/error expanded, success collapsed).+ const [expandOverrides, setExpandOverrides] = React.useState<Map<string, boolean>>(new Map());++ React.useLayoutEffect(() => {+ if (stickToBottomRef.current)+ messagesEndRef.current?.scrollIntoView({ block: 'nearest', inline: 'nearest' });+ }, [apiCalls]);++ React.useEffect(() => {+ const handleKeyDown = (event: KeyboardEvent) => {+ if (event.key === 'F8') {+ event.preventDefault();+ if (debuggerPaused)+ model.debuggerResume();+ else+ model.debuggerPause();+ } else if (event.key === 'F10' && debuggerPaused) {+ event.preventDefault();+ model.debuggerStep();+ }+ };+ document.addEventListener('keydown', handleKeyDown);+ return () => document.removeEventListener('keydown', handleKeyDown);+ }, [debuggerPaused, model]);++ const pausePending = debuggerPauseRequested && !debuggerPaused;+ return (+ <div className={clsx('debugger-panel', debuggerPaused && 'paused', pausePending && 'pause-pending')}>+ <Toolbar>+ <div className='debugger-panel-title'>Actions</div>+ <ToolbarButton className='debugger-run-control' icon='debug-continue' title='Resume (F8)' ariaLabel='Resume' disabled={!debuggerPaused} onClick={() => model.debuggerResume()} />+ <ToolbarButton icon='debug-pause' title='Pause (F8)' ariaLabel='Pause' disabled={debuggerPaused} toggled={pausePending} onClick={() => model.debuggerPause()} />+ <ToolbarButton className='debugger-run-control' icon='debug-step-over' title='Step over (F10)' ariaLabel='Step over' disabled={!debuggerPaused} onClick={() => model.debuggerStep()} />+ {debuggerPaused && <div className='debugger-status'>Paused</div>}+ {pausePending && <div className='debugger-status'>Pausing before the next action…</div>}+ <div style={{ flex: 'auto' }}></div>+ </Toolbar>+ <SplitView+ orientation='horizontal'+ sidebarSize={380}+ minSidebarSize={220}+ settingName='dashboardDebuggerSource'+ sidebarHidden={!debuggerSource}+ main={<div className='debugger-call-log' ref={callLogRef} onScroll={() => {+ const element = callLogRef.current!;+ stickToBottomRef.current = element.scrollTop + element.clientHeight >= element.scrollHeight - 40;+ }}>+ {apiCalls.length === 0 && <div className='debugger-empty'>No actions yet</div>}+ {apiCalls.map(call => {+ const hasDetails = call.logs.length > 0 || !!call.error;+ const override = expandOverrides.get(call.id);+ const isExpanded = hasDetails && (typeof override === 'boolean' ? override : call.status !== 'success');+ return (+ <div className={clsx('debugger-call', call.status)} key={call.id}>+ <div className={clsx('debugger-call-header', hasDetails && 'expandable')} onClick={() => {+ if (!hasDetails)+ return;+ const next = new Map(expandOverrides);+ next.set(call.id, !isExpanded);+ setExpandOverrides(next);+ }}>+ <span className={clsx('codicon', `codicon-chevron-${isExpanded ? 'down' : 'right'}`)} style={{ visibility: hasDetails ? 'visible' : 'hidden' }}></span>+ <span className='debugger-call-title'>{call.title}</span>+ {call.location && <span className='debugger-call-location'>{locationLabel(call.location)}</span>}+ {call.status !== 'success' && <span className={clsx('codicon', iconClass(call.status))}></span>}+ </div>+ {isExpanded && call.logs.map((message, i) => (+ <div className='debugger-call-message' key={i}>{message.trim()}</div>+ ))}+ {!!call.error && <div className='debugger-call-message error' hidden={!isExpanded}>{call.error}</div>}+ </div>+ );+ })}+ <div ref={messagesEndRef}></div>+ </div>}+ sidebar={<SourceView source={debuggerSource} />}+ />+ </div>+ );+};++const SourceView: React.FC<{ source: DebuggerSource | null }> = ({ source }) => {+ if (!source) {+ return <div className='debugger-source'>+ <div className='debugger-empty'>No source</div>+ </div>;+ }+ const file = source.file.split(/[\\/]/).pop() ?? source.file;+ return <div className='debugger-source'>+ <div className='debugger-source-header' title={source.file}>{file}</div>+ <CodeMirrorWrapper+ text={source.text}+ highlighter={source.language}+ highlight={source.highlight}+ revealLine={source.revealLine}+ readOnly={true}+ lineNumbers={true}+ />+ </div>;+};++function iconClass(status: Exclude<ApiCall['status'], 'success'>): string {+ switch (status) {+ case 'running': return 'codicon-loading codicon-modifier-spin';+ case 'error': return 'codicon-error';+ }+}++function locationLabel(location: NonNullable<ApiCall['location']>): string {+ const file = location.file.split(/[\\/]/).pop() ?? location.file;+ return location.line ? `${file}:${location.line}` : file;+}diff --git a/packages/isomorphic/protocolMetainfo.ts b/packages/isomorphic/protocolMetainfo.tsindex c8897fdf9f..29fbd276b6 100644--- a/packages/isomorphic/protocolMetainfo.ts+++ b/packages/isomorphic/protocolMetainfo.ts@@ -331,6 +331,7 @@ export const methodMetainfo = new Map<string, MethodMetainfo>([['Debugger.resume', { title: 'Resume', group: 'configuration', }],['Debugger.next', { title: 'Step to next call', group: 'configuration', }],['Debugger.runTo', { title: 'Run to location', group: 'configuration', }],+ ['Debugger.enable', { internal: true, }],['Dialog.accept', { title: 'Accept dialog', }],['Dialog.dismiss', { title: 'Dismiss dialog', }],['Tracing.tracingStart', { title: 'Start tracing', group: 'configuration', }],diff --git a/packages/playwright-core/src/client/channels.d.ts b/packages/playwright-core/src/client/channels.d.tsindex 5f00e88585..ddc8a9125c 100644--- a/packages/playwright-core/src/client/channels.d.ts+++ b/packages/playwright-core/src/client/channels.d.ts@@ -5000,6 +5000,7 @@ export interface BindingCallEvents {export type DebuggerInitializer = {};export interface DebuggerEventTarget {on(event: 'pausedStateChanged', callback: (params: DebuggerPausedStateChangedEvent) => void): this;+ on(event: 'apiCallsUpdated', callback: (params: DebuggerApiCallsUpdatedEvent) => void): this;}export interface DebuggerChannel extends DebuggerEventTarget, Channel {_type_Debugger: boolean;@@ -5007,6 +5008,7 @@ export interface DebuggerChannel extends DebuggerEventTarget, Channel {resume(params: DebuggerResumeParams, options: TimeoutOptions): Promise<DebuggerResumeResult>;next(params: DebuggerNextParams, options: TimeoutOptions): Promise<DebuggerNextResult>;runTo(params: DebuggerRunToParams, options: TimeoutOptions): Promise<DebuggerRunToResult>;+ enable(params: DebuggerEnableParams, options: TimeoutOptions): Promise<DebuggerEnableResult>;}export type DebuggerPausedStateChangedEvent = {pausedDetails?: {@@ -5019,6 +5021,21 @@ export type DebuggerPausedStateChangedEvent = {stack?: string,},};+export type DebuggerApiCallsUpdatedEvent = {+ apiCalls: {+ id: string,+ title: string,+ location?: {+ file: string,+ line?: number,+ column?: number,+ },+ newLogEntries: string[],+ actionPoint?: Point,+ status: 'running' | 'success' | 'error',+ error?: string,+ }[],+};export type DebuggerRequestPauseParams = {};export type DebuggerRequestPauseOptions = {};export type DebuggerRequestPauseResult = void;@@ -5039,9 +5056,13 @@ export type DebuggerRunToOptions = {};export type DebuggerRunToResult = void;+export type DebuggerEnableParams = {};+export type DebuggerEnableOptions = {};+export type DebuggerEnableResult = void;export interface DebuggerEvents {'pausedStateChanged': DebuggerPausedStateChangedEvent;+ 'apiCallsUpdated': DebuggerApiCallsUpdatedEvent;}// ----------- Dialog -----------diff --git a/packages/playwright-core/src/client/debugger.ts b/packages/playwright-core/src/client/debugger.tsindex 7c68e1ee91..4fb2e6f372 100644--- a/packages/playwright-core/src/client/debugger.ts+++ b/packages/playwright-core/src/client/debugger.ts@@ -36,6 +36,13 @@ export class Debugger extends ChannelOwner<channels.DebuggerChannel> implementsthis._pausedDetails = pausedDetails ?? null;this.emit(Events.Debugger.PausedStateChanged);});+ this._channel.on('apiCallsUpdated', ({ apiCalls }) => {+ this.emit(Events.Debugger.ApiCallsUpdated, apiCalls);+ });+ }++ async _enable(): Promise<void> {+ await this._channel.enable({}, kNoTimeout);}async requestPause(): Promise<void> {diff --git a/packages/playwright-core/src/client/events.ts b/packages/playwright-core/src/client/events.tsindex c69b3aa5a4..86ee9201d1 100644--- a/packages/playwright-core/src/client/events.ts+++ b/packages/playwright-core/src/client/events.ts@@ -36,7 +36,8 @@ export const Events = {},Debugger: {- PausedStateChanged: 'pausedstatechanged'+ PausedStateChanged: 'pausedstatechanged',+ ApiCallsUpdated: 'apicallsupdated',},BrowserContext: {diff --git a/packages/playwright-core/src/server/channels.d.ts b/packages/playwright-core/src/server/channels.d.tsindex bb47a21310..9ce45772cb 100644--- a/packages/playwright-core/src/server/channels.d.ts+++ b/packages/playwright-core/src/server/channels.d.ts@@ -5001,6 +5001,7 @@ export interface BindingCallEvents {export type DebuggerInitializer = {};export interface DebuggerEventTarget {_dispatchEvent(event: 'pausedStateChanged', params?: DebuggerPausedStateChangedEvent): void;+ _dispatchEvent(event: 'apiCallsUpdated', params?: DebuggerApiCallsUpdatedEvent): void;}export interface DebuggerChannel extends DebuggerEventTarget, Channel {_type_Debugger: boolean;@@ -5008,6 +5009,7 @@ export interface DebuggerChannel extends DebuggerEventTarget, Channel {resume(params: DebuggerResumeParams, progress: Progress): Promise<DebuggerResumeResult>;next(params: DebuggerNextParams, progress: Progress): Promise<DebuggerNextResult>;runTo(params: DebuggerRunToParams, progress: Progress): Promise<DebuggerRunToResult>;+ enable(params: DebuggerEnableParams, progress: Progress): Promise<DebuggerEnableResult>;}export type DebuggerPausedStateChangedEvent = {pausedDetails?: {@@ -5020,6 +5022,21 @@ export type DebuggerPausedStateChangedEvent = {stack?: string,},};+export type DebuggerApiCallsUpdatedEvent = {+ apiCalls: {+ id: string,+ title: string,+ location?: {+ file: string,+ line?: number,+ column?: number,+ },+ newLogEntries: string[],+ actionPoint?: Point,+ status: 'running' | 'success' | 'error',+ error?: string,+ }[],+};export type DebuggerRequestPauseParams = {};export type DebuggerRequestPauseOptions = {};export type DebuggerRequestPauseResult = void;@@ -5040,9 +5057,13 @@ export type DebuggerRunToOptions = {};export type DebuggerRunToResult = void;+export type DebuggerEnableParams = {};+export type DebuggerEnableOptions = {};+export type DebuggerEnableResult = void;export interface DebuggerEvents {'pausedStateChanged': DebuggerPausedStateChangedEvent;+ 'apiCallsUpdated': DebuggerApiCallsUpdatedEvent;}// ----------- Dialog -----------diff --git a/packages/playwright-core/src/server/debugger.ts b/packages/playwright-core/src/server/debugger.tsindex aec3ecbdee..32ce4fa5cc 100644--- a/packages/playwright-core/src/server/debugger.ts+++ b/packages/playwright-core/src/server/debugger.ts@@ -15,27 +15,59 @@*/import { getMetainfo } from '@isomorphic/protocolMetainfo';+import { renderTitleForCall } from '@isomorphic/protocolFormatter';import { monotonicTime } from '@isomorphic/time';import { SdkObject } from './instrumentation';import { BrowserContext } from './browserContext';import type { CallMetadata, InstrumentationListener } from './instrumentation';import type { Progress } from './progress';+import type { Point } from './types';const symbol = Symbol('Debugger');+const kApiCallsFlushDelay = 500;++const DebuggerEvent = {+ PausedStateChanged: 'pausedstatechanged',+ ApiCallsUpdated: 'apicallsupdated',+} as const;type PauseAt = { next?: boolean, location?: { file: string, line?: number, column?: number } };-export class Debugger extends SdkObject implements InstrumentationListener {+export type ApiCallUpdate = {+ id: string;+ title: string;+ location?: { file: string, line?: number, column?: number };+ newLogEntries: string[];+ actionPoint?: Point;+ status: 'running' | 'success' | 'error';+ error?: string;+};++type OngoingCall = {+ metadata: CallMetadata;+ actionPoint?: Point;+ sentLogCount: number;+ status: 'running' | 'success' | 'error';+};++type DebuggerEventMap = {+ [DebuggerEvent.PausedStateChanged]: [];+ [DebuggerEvent.ApiCallsUpdated]: [apiCalls: ApiCallUpdate[]];+};++export class Debugger extends SdkObject<DebuggerEventMap> implements InstrumentationListener {+ static Events = DebuggerEvent;+private _pauseAt: PauseAt = {};private _pausedCall: { metadata: CallMetadata, sdkObject: SdkObject, resolve: () => void } | undefined;private _enabled = false;private _pauseBeforeWaitingActions = false; // instead of inside input actionsprivate _context: BrowserContext;-- static Events = {- PausedStateChanged: 'pausedstatechanged'- };+ private _apiCallsEnabled = false;+ private _ongoingCalls = new Map<string, OngoingCall>();+ private _apiCallsWithPendingUpdates = new Set<string>();+ private _apiCallsFlushTimer: NodeJS.Timeout | undefined;private _muted = false;constructor(context: BrowserContext) {@@ -47,6 +79,8 @@ export class Debugger extends SdkObject implements InstrumentationListener {context.instrumentation.addListener(this, context, { order: 'last' });this._context.once(BrowserContext.Events.Close, () => {this._context.instrumentation.removeListener(this);+ if (this._apiCallsFlushTimer)+ clearTimeout(this._apiCallsFlushTimer);});}@@ -84,6 +118,12 @@ export class Debugger extends SdkObject implements InstrumentationListener {}async onBeforeCall(sdkObject: SdkObject, metadata: CallMetadata): Promise<void> {+ if (!metadata.internal && metadata.method)+ this._ongoingCalls.set(metadata.id, { metadata, sentLogCount: 0, status: 'running' });+ if (this._apiCallsEnabled) {+ this._apiCallsWithPendingUpdates.add(metadata.id);+ this._flushApiCalls();+ }if (this._muted || metadata.internal)return;const metainfo = getMetainfo(metadata);@@ -94,7 +134,15 @@ export class Debugger extends SdkObject implements InstrumentationListener {await this._pause(sdkObject, metadata);}- async onBeforeInputAction(sdkObject: SdkObject, metadata: CallMetadata): Promise<void> {+ async onBeforeInputAction(sdkObject: SdkObject, metadata: CallMetadata, point?: Point): Promise<void> {+ const call = this._ongoingCalls.get(metadata.id);+ if (call) {+ call.actionPoint = point;+ if (this._apiCallsEnabled) {+ this._apiCallsWithPendingUpdates.add(metadata.id);+ this._flushApiCalls();+ }+ }if (this._muted || metadata.internal)return;const metainfo = getMetainfo(metadata);@@ -103,6 +151,67 @@ export class Debugger extends SdkObject implements InstrumentationListener {await this._pause(sdkObject, metadata);}+ async onAfterCall(sdkObject: SdkObject, metadata: CallMetadata): Promise<void> {+ const call = this._ongoingCalls.get(metadata.id);+ if (!call)+ return;+ call.status = metadata.error ? 'error' : 'success';+ if (this._apiCallsEnabled) {+ this._apiCallsWithPendingUpdates.add(metadata.id);+ this._flushApiCalls();+ }+ this._ongoingCalls.delete(metadata.id);+ }++ onCallLog(sdkObject: SdkObject, metadata: CallMetadata, logName: string, message: string): void {+ if (this._apiCallsEnabled && this._ongoingCalls.has(metadata.id)) {+ this._apiCallsWithPendingUpdates.add(metadata.id);+ this._scheduleApiCallsFlush();+ }+ }++ enableApiCalls() {+ if (this._apiCallsEnabled)+ return;+ this._apiCallsEnabled = true;+ this._pauseBeforeWaitingActions = false;+ for (const id of this._ongoingCalls.keys())+ this._apiCallsWithPendingUpdates.add(id);+ this._flushApiCalls();+ }++ private _scheduleApiCallsFlush() {+ if (this._apiCallsFlushTimer || !this._apiCallsWithPendingUpdates.size)+ return;+ this._apiCallsFlushTimer = setTimeout(() => this._flushApiCalls(), kApiCallsFlushDelay);+ }++ private _flushApiCalls() {+ if (this._apiCallsFlushTimer) {+ clearTimeout(this._apiCallsFlushTimer);+ this._apiCallsFlushTimer = undefined;+ }+ const updates: ApiCallUpdate[] = [];+ for (const id of this._apiCallsWithPendingUpdates) {+ const call = this._ongoingCalls.get(id);+ if (!call)+ continue;+ updates.push({+ id: call.metadata.id,+ title: renderTitleForCall(call.metadata) ?? '',+ location: call.metadata.location,+ newLogEntries: call.metadata.log.slice(call.sentLogCount),+ actionPoint: call.actionPoint,+ status: call.metadata.error ? 'error' : call.status,+ error: call.metadata.error?.error?.message,+ });+ call.sentLogCount = call.metadata.log.length;+ }+ this._apiCallsWithPendingUpdates.clear();+ if (updates.length)+ this.emit(Debugger.Events.ApiCallsUpdated, updates);+ }+private async _pause(sdkObject: SdkObject, metadata: CallMetadata) {if (this._muted || metadata.internal)return;@@ -128,6 +237,8 @@ export class Debugger extends SdkObject implements InstrumentationListener {}setPauseBeforeWaitingActions() {+ if (this._apiCallsEnabled)+ return;this._pauseBeforeWaitingActions = true;}diff --git a/packages/playwright-core/src/server/dispatchers/debuggerDispatcher.ts b/packages/playwright-core/src/server/dispatchers/debuggerDispatcher.tsindex 40626750b1..1c95224156 100644--- a/packages/playwright-core/src/server/dispatchers/debuggerDispatcher.ts+++ b/packages/playwright-core/src/server/dispatchers/debuggerDispatcher.ts@@ -19,6 +19,7 @@ import { Dispatcher } from './dispatcher';import { Debugger } from '../debugger';import type { BrowserContextDispatcher } from './browserContextDispatcher';+import type { ApiCallUpdate } from '../debugger';import type * as channels from '../channels';import type { Progress } from '../progress';@@ -35,6 +36,9 @@ export class DebuggerDispatcher extends Dispatcher<Debugger, channels.DebuggerChthis.addObjectListener(Debugger.Events.PausedStateChanged, () => {this._dispatchEvent('pausedStateChanged', { pausedDetails: this._serializePausedDetails() });});+ this.addObjectListener(Debugger.Events.ApiCallsUpdated, (apiCalls: ApiCallUpdate[]) => {+ this._dispatchEvent('apiCallsUpdated', { apiCalls });+ });this._dispatchEvent('pausedStateChanged', { pausedDetails: this._serializePausedDetails() });}@@ -68,4 +72,8 @@ export class DebuggerDispatcher extends Dispatcher<Debugger, channels.DebuggerChasync runTo(params: channels.DebuggerRunToParams, progress: Progress): Promise<void> {this._object.runTo(progress, params.location);}++ async enable(params: channels.DebuggerEnableParams, progress: Progress): Promise<void> {+ this._object.enableApiCalls();+ }}diff --git a/packages/playwright-core/src/tools/dashboard/dashboardController.ts b/packages/playwright-core/src/tools/dashboard/dashboardController.tsindex 2105868022..0e263c65e9 100644--- a/packages/playwright-core/src/tools/dashboard/dashboardController.ts+++ b/packages/playwright-core/src/tools/dashboard/dashboardController.ts@@ -27,10 +27,36 @@ import { SessionProviderEvent } from './sessionProvider';import type * as api from '../../..';import type { Transport } from '@utils/httpServer';-import type { SubmittedAnnotationFrame, Tab } from '@dashboard/dashboardChannel';+import type { ApiCall, DebuggerSource, SubmittedAnnotationFrame, Tab } from '@dashboard/dashboardChannel';import type { BrowserDescriptor } from '../../serverRegistry';import type { SessionProvider } from './sessionProvider';+// Incremental API-call payload emitted by the (private) Debugger.apiCallsUpdated event.+type ApiCallDelta = {+ id: string;+ title: string;+ location?: { file: string; line?: number; column?: number };+ newLogEntries: string[];+ actionPoint?: { x: number; y: number };+ status: 'running' | 'success' | 'error';+ error?: string;+};++function languageForFile(file: string): DebuggerSource['language'] {+ if (file.endsWith('.py'))+ return 'python';+ if (file.endsWith('.java'))+ return 'java';+ if (file.endsWith('.cs'))+ return 'csharp';+ return 'javascript';+}++function wrapInternal<R>(target: api.BrowserContext | api.Page, func: () => Promise<R>): Promise<R> {+ // eslint-disable-next-line no-restricted-syntax+ return (target as any)._wrapApiCall(func, { internal: true });+}+export type AnnotateResult =| { type: 'submitted', frames: SubmittedAnnotationFrame[], feedback: string }| { type: 'cancelled' };@@ -41,6 +67,8 @@ export class DashboardConnection implements Transport {private _provider: SessionProvider;private _attachedPage: AttachedPage | undefined;+ private _contextDebuggers = new Map<api.BrowserContext, ContextDebugger>();+ private _activeContextDebugger: ContextDebugger | undefined;private _onclose: () => void;private _onconnected?: () => void;private _pushTabsScheduled = false;@@ -68,6 +96,13 @@ export class DashboardConnection implements Transport {void this._tryRevealPending();});this._provider.on(SessionProviderEvent.ContextClosed, context => {+ const contextDebugger = this._contextDebuggers.get(context);+ if (contextDebugger) {+ contextDebugger.dispose();+ this._contextDebuggers.delete(context);+ if (this._activeContextDebugger === contextDebugger)+ this._activeContextDebugger = undefined;+ }if (this._attachedPage?.page.context() === context) {this._attachedPage.dispose();this._attachedPage = undefined;@@ -82,6 +117,10 @@ export class DashboardConnection implements Transport {this._provider.dispose();this._attachedPage?.dispose();this._attachedPage = undefined;+ for (const contextDebugger of this._contextDebuggers.values())+ contextDebugger.dispose();+ this._contextDebuggers.clear();+ this._activeContextDebugger = undefined;this._pendingReveal = undefined;this._resolvePendingAnnotate({ type: 'cancelled' });for (const stream of this._streams.values()) {@@ -120,14 +159,15 @@ export class DashboardConnection implements Transport {const context = this._provider.findContext(params);if (!context)return;- const page = await context.newPage();+ const page = await wrapInternal(context, () => context.newPage());await this._switchAttachedTo(page);this._pushTabs();}async closeTab(params: { browser: string; context: string; page: string }) {const page = this._provider.findPage(params);- await page?.close({ reason: 'Closed in Dashboard' });+ if (page)+ await wrapInternal(page, () => page.close({ reason: 'Closed in Dashboard' }));}async closeSession(params: { browser: string }) {@@ -141,6 +181,22 @@ export class DashboardConnection implements Transport {await this._attachedPage?.setScreencastActive(params.visible);}+ async debuggerResume() {+ await this._activeContextDebugger?.resume();+ }++ async debuggerPause() {+ await this._activeContextDebugger?.pause();+ }++ async debuggerStep() {+ await this._activeContextDebugger?.step();+ }++ activeContextDebugger(): ContextDebugger | undefined {+ return this._activeContextDebugger;+ }+revealSession(sessionName: string, workspaceDir?: string) {this._pendingReveal = { sessionName, workspaceDir };void this._tryRevealPending();@@ -228,6 +284,18 @@ export class DashboardConnection implements Transport {this.sendEvent?.('frame', { data, viewportWidth, viewportHeight });}+ emitApiCalls(apiCalls: ApiCall[]) {+ this.sendEvent?.('apiCalls', { apiCalls });+ }++ emitDebuggerPaused(paused: boolean) {+ this.sendEvent?.('debuggerPaused', { paused });+ }++ emitDebuggerSource(source: DebuggerSource | null) {+ this.sendEvent?.('debuggerSource', { source });+ }+emitAnnotate({ signal }: { signal: AbortSignal }): Promise<AnnotateResult> {return new Promise<AnnotateResult>(resolve => {if (signal.aborted) {@@ -282,8 +350,7 @@ export class DashboardConnection implements Transport {queueMicrotask(async () => {this._pushTabsScheduled = false;try {- const tabs = await this._aggregateTabs();- this.emitTabs(tabs);+ this.emitTabs(await this._aggregateTabs());} catch {// best-effort}@@ -310,7 +377,7 @@ export class DashboardConnection implements Transport {browser: browserId(browser),context: contextId(context),page: pageId(page),- title: await page.title().catch(() => ''),+ title: await wrapInternal(page, () => page.title()).catch(() => ''),url: page.url(),selected: page === attachedPage,faviconUrl: await faviconUrl(page),@@ -334,8 +401,24 @@ export class DashboardConnection implements Transport {attached.dispose();throw e;}- if (this._attachedPage === attached)+ if (this._attachedPage === attached) {+ this._setActiveContextDebugger(this._contextDebuggerFor(page.context()));this._tryFireAnnotate();+ }+ }++ private _contextDebuggerFor(context: api.BrowserContext): ContextDebugger {+ let contextDebugger = this._contextDebuggers.get(context);+ if (!contextDebugger) {+ contextDebugger = new ContextDebugger(this, context);+ this._contextDebuggers.set(context, contextDebugger);+ }+ return contextDebugger;+ }++ private _setActiveContextDebugger(contextDebugger: ContextDebugger) {+ this._activeContextDebugger = contextDebugger;+ contextDebugger.activate();}_handleAttachedPageClose(context: api.BrowserContext) {@@ -348,6 +431,147 @@ export class DashboardConnection implements Transport {}}+class ContextDebugger {+ private _owner: DashboardConnection;+ private _context: api.BrowserContext;+ private _listeners: Disposable[] = [];+ private _apiCalls = new Map<string, ApiCall>();+ private _source: DebuggerSource | null = null;+ private _sourceCache = new Map<string, string>();+ private _lastSourceKey: string | undefined;++ constructor(owner: DashboardConnection, context: api.BrowserContext) {+ this._owner = owner;+ this._context = context;+ this._listeners.push(+ eventsHelper.addEventListener(this._context.debugger, 'apicallsupdated', (apiCalls: ApiCallDelta[]) => this._onApiCallsUpdated(apiCalls)),+ eventsHelper.addEventListener(this._context.debugger, 'pausedstatechanged', () => this._onPausedStateChanged()),+ );+ // eslint-disable-next-line no-restricted-syntax+ const dbg = this._context.debugger as any;+ if (typeof dbg._enable === 'function')+ void dbg._enable().catch(() => {});+ }++ dispose() {+ this._listeners.forEach(d => d.dispose());+ this._listeners = [];+ }++ apiCalls(): ApiCall[] {+ return [...this._apiCalls.values()];+ }++ paused(): boolean {+ return this._context.debugger.pausedDetails() !== null;+ }++ activate() {+ this._owner.emitApiCalls(this.apiCalls());+ this._owner.emitDebuggerPaused(this.paused());+ this._updateSource(true);+ }++ async resume() {+ await wrapInternal(this._context, () => this._context.debugger.resume()).catch(() => {});+ }++ async pause() {+ await wrapInternal(this._context, () => this._context.debugger.requestPause()).catch(() => {});+ }++ async step() {+ await wrapInternal(this._context, () => this._context.debugger.next()).catch(() => {});+ }++ private _isActive(): boolean {+ return this._owner.activeContextDebugger() === this;+ }++ private _onApiCallsUpdated(deltas: ApiCallDelta[]) {+ for (const delta of deltas) {+ const existing = this._apiCalls.get(delta.id);+ this._apiCalls.set(delta.id, {+ id: delta.id,+ title: delta.title,+ location: delta.location,+ logs: [...(existing?.logs ?? []), ...delta.newLogEntries],+ actionPoint: delta.actionPoint ?? existing?.actionPoint,+ status: delta.status,+ error: delta.error,+ });+ }+ if (!this._isActive())+ return;+ this._owner.emitApiCalls(this.apiCalls());+ this._updateSource();+ }++ private _onPausedStateChanged() {+ if (!this._isActive())+ return;+ this._owner.emitDebuggerPaused(this.paused());+ this._updateSource();+ }++ private _updateSource(force = false) {+ const paused = this._context.debugger.pausedDetails();+ let location: { file: string; line?: number } | undefined;+ let type: DebuggerSource['highlight'][number]['type'] = 'running';+ let active = false;+ if (paused?.location) {+ location = paused.location;+ type = 'paused';+ active = true;+ } else {+ const calls = [...this._apiCalls.values()].reverse();+ const running = calls.find(c => c.status === 'running' && c.location?.file);+ if (running) {+ location = running.location;+ type = 'running';+ active = true;+ } else {+ const last = calls.find(c => c.location?.file);+ location = last?.location;+ type = last?.status === 'error' ? 'error' : 'running';+ }+ }++ const text = location?.file && location.file !== '<unknown>' ? this._readSource(location.file) : undefined;+ if (location?.file && text !== undefined) {+ const key = `${location.file}:${location.line}:${type}:${active}`;+ if (key !== this._lastSourceKey) {+ this._lastSourceKey = key;+ const highlight = active && location.line ? [{ line: location.line, type }] : [];+ this._source = {+ file: location.file,+ language: languageForFile(location.file),+ text,+ highlight,+ revealLine: location.line,+ };+ this._owner.emitDebuggerSource(this._source);+ return;+ }+ }+ if (force)+ this._owner.emitDebuggerSource(this._source);+ }++ private _readSource(file: string): string | undefined {+ let text = this._sourceCache.get(file);+ if (text === undefined) {+ try {+ text = fs.readFileSync(file, 'utf-8');+ } catch {+ return undefined;+ }+ this._sourceCache.set(file, text);+ }+ return text;+ }+}+class AttachedPage {private _owner: DashboardConnection;private _page: api.Page;@@ -385,7 +609,7 @@ class AttachedPage {this._listeners.forEach(d => d.dispose());this._listeners = [];if (this._screencastRunning)- this._page.screencast.stop().catch(() => {});+ wrapInternal(this._page, () => this._page.screencast.stop()).catch(() => {});this._screencastRunning = false;this._recordingPath = null;}@@ -396,52 +620,52 @@ class AttachedPage {await this._startScreencast(this._page);} else if (!active && this._screencastRunning) {this._screencastRunning = false;- await this._page.screencast.stop().catch(() => {});+ await wrapInternal(this._page, () => this._page.screencast.stop()).catch(() => {});}}async navigate(params: { url: string }) {if (!params.url)return;- await this._page.goto(params.url);+ await wrapInternal(this._page, () => this._page.goto(params.url));}async back() {- await this._page.goBack();+ await wrapInternal(this._page, () => this._page.goBack());}async forward() {- await this._page.goForward();+ await wrapInternal(this._page, () => this._page.goForward());}async reload() {- await this._page.reload();+ await wrapInternal(this._page, () => this._page.reload());}async mousemove(params: { x: number; y: number }) {- await this._page.mouse.move(params.x, params.y);+ await wrapInternal(this._page, () => this._page.mouse.move(params.x, params.y));}async mousedown(params: { x: number; y: number; button?: 'left' | 'middle' | 'right' }) {- await this._page.mouse.move(params.x, params.y);- await this._page.mouse.down({ button: params.button || 'left' });+ await wrapInternal(this._page, () => this._page.mouse.move(params.x, params.y));+ await wrapInternal(this._page, () => this._page.mouse.down({ button: params.button || 'left' }));}async mouseup(params: { x: number; y: number; button?: 'left' | 'middle' | 'right' }) {- await this._page.mouse.move(params.x, params.y);- await this._page.mouse.up({ button: params.button || 'left' });+ await wrapInternal(this._page, () => this._page.mouse.move(params.x, params.y));+ await wrapInternal(this._page, () => this._page.mouse.up({ button: params.button || 'left' }));}async wheel(params: { deltaX: number; deltaY: number }) {- await this._page.mouse.wheel(params.deltaX, params.deltaY);+ await wrapInternal(this._page, () => this._page.mouse.wheel(params.deltaX, params.deltaY));}async keydown(params: { key: string }) {- await this._page.keyboard.down(params.key);+ await wrapInternal(this._page, () => this._page.keyboard.down(params.key));}async keyup(params: { key: string }) {- await this._page.keyboard.up(params.key);+ await wrapInternal(this._page, () => this._page.keyboard.up(params.key));}async startRecording() {@@ -465,8 +689,8 @@ class AttachedPage {}async screenshot(): Promise<{ data: string; viewportWidth: number; viewportHeight: number; ariaSnapshot: string }> {- const buffer = await this._page.screenshot({ type: 'png' });- const ariaSnapshot = await this._page.ariaSnapshot({ boxes: true, mode: 'ai' });+ const buffer = await wrapInternal(this._page, () => this._page.screenshot({ type: 'png' }));+ const ariaSnapshot = await wrapInternal(this._page, () => this._page.ariaSnapshot({ boxes: true, mode: 'ai' }));const vp = await this._viewportSize();return {data: buffer.toString('base64'),@@ -482,11 +706,11 @@ class AttachedPage {const vp = this._page.viewportSize();if (vp)return vp;- return await this._page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight }));+ return await wrapInternal(this._page, () => this._page.evaluate(() => ({ width: window.innerWidth, height: window.innerHeight })));}private async _startScreencast(page: api.Page) {- await page.screencast.start({+ await wrapInternal(page, () => page.screencast.start({onFrame: ({ data, viewportWidth, viewportHeight }) => {if (this._disposed)return;@@ -494,11 +718,11 @@ class AttachedPage {},size: { width: 1280, height: 800 },...(this._recordingPath ? { path: this._recordingPath } : {}),- });+ }));}private async _restartScreencast(page: api.Page) {- await page.screencast.stop().catch(() => {});+ await wrapInternal(page, () => page.screencast.stop()).catch(() => {});await this._startScreencast(page);}}@@ -519,7 +743,7 @@ function contextId(c: api.BrowserContext): string {}async function faviconUrl(page: api.Page): Promise<string | undefined> {- const url = page.evaluate(async () => {+ const url = wrapInternal(page, () => page.evaluate(async () => {const response = await fetch(document.querySelector<HTMLLinkElement>('link[rel~="icon"]')?.href ?? '/favicon.ico');if (!response.ok)return undefined;@@ -532,7 +756,7 @@ async function faviconUrl(page: api.Page): Promise<string | undefined> {reader.onerror = reject;reader.readAsDataURL(blob);});- }).catch(() => undefined);+ })).catch(() => undefined);const timeout = new Promise<undefined>(resolve => setTimeout(() => resolve(undefined), 3000));return await Promise.race([url, timeout]);}diff --git a/packages/protocol/spec/playwright.yml b/packages/protocol/spec/playwright.ymlindex 287f3714d4..de3634d75b 100644--- a/packages/protocol/spec/playwright.yml+++ b/packages/protocol/spec/playwright.yml@@ -456,6 +456,9 @@ Debugger:line: int?column: int?+ enable:+ internal: true+events:pausedStateChanged:@@ -472,6 +475,33 @@ Debugger:title: stringstack: string?+ apiCallsUpdated:+ parameters:+ apiCalls:+ type: array+ items:+ type: object+ properties:+ id: string+ title: string+ location:+ type: object?+ properties:+ file: string+ line: int?+ column: int?+ newLogEntries:+ type: array+ items: string+ actionPoint: Point?+ status:+ type: enum+ literals:+ - running+ - success+ - error+ error: string?+Dialog:type: interfacediff --git a/packages/protocol/src/validator.ts b/packages/protocol/src/validator.tsindex 0445d88627..00ac25e317 100644--- a/packages/protocol/src/validator.ts+++ b/packages/protocol/src/validator.ts@@ -2939,6 +2939,21 @@ scheme.DebuggerPausedStateChangedEvent = tObject({stack: tOptional(tString),})),});+scheme.DebuggerApiCallsUpdatedEvent = tObject({+ apiCalls: tArray(tObject({+ id: tString,+ title: tString,+ location: tOptional(tObject({+ file: tString,+ line: tOptional(tInt),+ column: tOptional(tInt),+ })),+ newLogEntries: tArray(tString),+ actionPoint: tOptional(tType('Point')),+ status: tEnum(['running', 'success', 'error']),+ error: tOptional(tString),+ })),+});scheme.DebuggerRequestPauseParams = tOptional(tObject({}));scheme.DebuggerRequestPauseResult = tOptional(tObject({}));scheme.DebuggerResumeParams = tOptional(tObject({}));@@ -2953,6 +2968,8 @@ scheme.DebuggerRunToParams = tObject({}),});scheme.DebuggerRunToResult = tOptional(tObject({}));+scheme.DebuggerEnableParams = tOptional(tObject({}));+scheme.DebuggerEnableResult = tOptional(tObject({}));scheme.DialogInitializer = tObject({page: tOptional(tChannel(['Page'])),type: tString,diff --git a/tests/library/debugger.spec.ts b/tests/library/debugger.spec.tsindex 172de6bcdb..36df139bc6 100644--- a/tests/library/debugger.spec.ts+++ b/tests/library/debugger.spec.ts@@ -15,6 +15,9 @@*/import { contextTest as it, expect } from '../config/browserTest';+import type * as channels from '../../packages/playwright-core/src/client/channels';++type ApiCall = channels.DebuggerApiCallsUpdatedEvent['apiCalls'][number];it('should pause at next and resume', async ({ context, server }) => {const page = await context.newPage();@@ -93,3 +96,177 @@ it('should run to location', async ({ context, server }) => {await dbg.resume();await clickPromise;});++it('should stream api calls via _enable', async ({ context, server }) => {+ const page = await context.newPage();+ await page.setContent('<button>click me</button>');+ const dbg = context.debugger as any;++ // Accumulate deltas by id, appending newLogEntries — mirrors the dashboard bridge.+ const calls = new Map<string, { title: string; status: string; location?: any; actionPoint?: any; logs: string[] }>();+ const statusHistory = new Map<string, string[]>();+ dbg.on('apicallsupdated', (apiCalls: ApiCall[]) => {+ for (const call of apiCalls) {+ const existing = calls.get(call.id);+ calls.set(call.id, {+ title: call.title,+ status: call.status,+ location: call.location,+ actionPoint: call.actionPoint ?? existing?.actionPoint,+ logs: [...(existing?.logs ?? []), ...call.newLogEntries],+ });+ statusHistory.set(call.id, [...(statusHistory.get(call.id) ?? []), call.status]);+ }+ });+ await dbg._enable();++ await page.click('button');++ const clickCall = () => [...calls.values()].find(c => c.title.includes('Click'));+ await expect.poll(() => clickCall()?.status).toBe('success');++ const call = clickCall()!;+ expect(call.location).toEqual(expect.objectContaining({ file: expect.stringContaining('debugger.spec') }));+ expect(call.actionPoint).toEqual(expect.objectContaining({ x: expect.any(Number), y: expect.any(Number) }));+ expect(call.logs.length).toBeGreaterThan(0);++ // The status streamed running -> success (not just a single terminal event).+ const clickId = [...calls.entries()].find(([, c]) => c.title.includes('Click'))![0];+ const history = statusHistory.get(clickId)!;+ expect(history[0]).toBe('running');+ expect(history[history.length - 1]).toBe('success');+});++it('should report error status for failed api calls', async ({ context, server }) => {+ const page = await context.newPage();+ await page.setContent('<div>no button here</div>');+ const dbg = context.debugger as any;++ const calls = new Map<string, ApiCall>();+ dbg.on('apicallsupdated', (apiCalls: ApiCall[]) => {+ for (const call of apiCalls)+ calls.set(call.id, call);+ });+ await dbg._enable();++ await page.click('button', { timeout: 1000 }).catch(() => {});++ await expect.poll(() => [...calls.values()].find(c => c.title.includes('Click'))?.status).toBe('error');+ const call = [...calls.values()].find(c => c.title.includes('Click'))!;+ expect(call.error).toBeTruthy();+});++it('should not stream internal api calls', async ({ context, server }) => {+ const page = await context.newPage();+ await page.setContent('<button>click me</button>');+ const dbg = context.debugger as any;+ const calls: ApiCall[] = [];+ dbg.on('apicallsupdated', (apiCalls: ApiCall[]) => calls.push(...apiCalls));+ await dbg._enable();++ // A call wrapped as internal (mirrors the dashboard's own traffic) is excluded.+ await (page as any)._wrapApiCall(() => page.click('button'), { internal: true });+ // A normal call is still streamed.+ await page.click('button');++ await expect.poll(() => calls.some(c => c.title.includes('Click'))).toBe(true);+ const clickIds = new Set(calls.filter(c => c.title.includes('Click')).map(c => c.id));+ expect(clickIds.size).toBe(1);+});++it('should not pause at internal api calls', async ({ context, server }) => {+ const page = await context.newPage();+ await page.setContent('<button>click me</button>');+ const dbg = context.debugger as any;++ await dbg.requestPause();+ // The internal call must not trip the pause, and must not consume the arming.+ await (page as any)._wrapApiCall(() => page.click('button'), { internal: true });+ expect(dbg.pausedDetails()).toBeNull();++ // The next normal call still pauses.+ const clickPromise = page.click('button');+ await new Promise<void>(resolve => dbg.once('pausedstatechanged', resolve));+ expect(dbg.pausedDetails()).toBeTruthy();+ await Promise.all([+ dbg.resume(),+ new Promise<void>(resolve => dbg.once('pausedstatechanged', resolve)),+ clickPromise,+ ]);+});++it('should expose the action point while paused on an input action', async ({ context, server }) => {+ const page = await context.newPage();+ await page.setContent('<button style="position:absolute; left:40px; top:60px">click me</button>');+ const dbg = context.debugger as any;+ const calls = new Map<string, ApiCall & { actionPoint?: { x: number; y: number } }>();+ dbg.on('apicallsupdated', (apiCalls: ApiCall[]) => {+ for (const c of apiCalls) {+ const existing = calls.get(c.id);+ calls.set(c.id, { ...c, actionPoint: c.actionPoint ?? existing?.actionPoint });+ }+ });+ await dbg._enable();++ // With api calls enabled, requestPause pauses inside the action (after auto-waiting),+ // so the action point is known — unlike the default "pause before waiting" behavior.+ await dbg.requestPause();+ const clickPromise = page.click('button');+ await new Promise<void>(resolve => dbg.once('pausedstatechanged', resolve));++ expect(dbg.pausedDetails()).toEqual(expect.objectContaining({ title: expect.stringContaining('Click') }));+ const clickCall = [...calls.values()].find(c => c.title.includes('Click'))!;+ expect(clickCall.status).toBe('running');+ expect(clickCall.actionPoint).toEqual(expect.objectContaining({ x: expect.any(Number), y: expect.any(Number) }));++ await Promise.all([+ dbg.resume(),+ new Promise<void>(resolve => dbg.once('pausedstatechanged', resolve)),+ clickPromise,+ ]);+});++it('should replay ongoing calls when enabled late', async ({ context, server }) => {+ const page = await context.newPage();+ await page.setContent('<button>click me</button>');+ const dbg = context.debugger as any;++ // Start a call and pause on it, so it is definitely in-flight — but do NOT enable yet.+ await dbg.requestPause();+ const clickPromise = page.click('button');+ await new Promise<void>(resolve => dbg.once('pausedstatechanged', resolve));++ // Enabling now must replay the already-ongoing call right away.+ const calls: ApiCall[] = [];+ dbg.on('apicallsupdated', (apiCalls: ApiCall[]) => calls.push(...apiCalls));+ await dbg._enable();++ await expect.poll(() => calls.find(c => c.title.includes('Click'))?.status).toBe('running');+ const clickCall = calls.find(c => c.title.includes('Click'))!;+ expect(clickCall.location).toEqual(expect.objectContaining({ file: expect.stringContaining('debugger.spec') }));++ await Promise.all([+ dbg.resume(),+ new Promise<void>(resolve => dbg.once('pausedstatechanged', resolve)),+ clickPromise,+ ]);+});++it('should keep pause working when api calls are enabled', async ({ context, server }) => {+ const page = await context.newPage();+ await page.setContent('<div>click me</div>');+ const dbg = context.debugger as any;+ await dbg._enable();++ await dbg.requestPause();+ const clickPromise = page.click('div');+ await new Promise<void>(resolve => dbg.once('pausedstatechanged', resolve));+ expect(dbg.pausedDetails()).toEqual(expect.objectContaining({ title: expect.stringContaining('Click') }));++ await Promise.all([+ dbg.resume(),+ new Promise<void>(resolve => dbg.once('pausedstatechanged', resolve)),+ clickPromise,+ ]);+ expect(dbg.pausedDetails()).toBeNull();+});