import './App.less'; import { InfoCircleOutlined } from '@ant-design/icons'; import { Alert, App as AntdApp, ConfigProvider, Empty, message, theme, } from 'antd'; import { useEffect, useMemo, useRef, useState } from 'react'; import { Panel, PanelGroup, PanelResizeHandle } from 'react-resizable-panels'; import { GroupedActionDump, type IReportActionDump, type TestRunReportDump, dedupeExecutionsKeepLatest, reportToMarkdown, restoreImageReferences, } from '@midscene/core'; import { antiEscapeScriptTag } from '@midscene/shared/utils'; import { Player, globalThemeConfig, useGlobalPreference, } from '@midscene/visualizer'; import AgentScreenshotView from './components/agent-screenshot-view'; import DetailPanel from './components/detail-panel'; import DetailSide from './components/detail-side'; import GlobalHoverPreview from './components/global-hover-preview'; import { Logo } from './components/logo'; import { useMarkdownScrollSync } from './components/markdown-scroll-sync'; import Sidebar from './components/sidebar'; import { type DumpStoreType, useExecutionDump } from './components/store'; import { useTaskHashAnchor } from './components/store/use-task-hash-anchor'; import TestRunnerReport from './components/test-runner'; import Timeline from './components/timeline'; import RecordVideocameraIcon from './icons/record-videocamera.svg?react'; import ThemeDarkIcon from './icons/theme-dark.svg?react'; import ThemeLightIcon from './icons/theme-light.svg?react'; import type { PlaywrightTaskAttributes, PlaywrightTasks, ReportViewMode, VisualizerProps, } from './types'; import { hydrateDirectoryReport } from './utils/directory-report'; import { downloadMarkdownZip, getReportMarkdownView, markdownArchiveBaseName, } from './utils/markdown-export'; import { formatModelBriefText } from './utils/model-brief'; import { getPlayerViewOptions } from './utils/player-only'; import { getEmptyDumpDescription, parseDumpAttributes, } from './utils/report-dump'; import { parseTestRunReportDump } from './utils/test-run-report'; const MOBILE_REPORT_MEDIA_QUERY = '(max-width: 640px), (max-width: 932px) and (max-height: 500px) and (pointer: coarse)'; // Shared image cache across all test cases — resolved images are cached by id const imageCache = new Map(); function resolveImageFromDom( refOrId: string | { id: string; storage?: 'inline' | 'file'; path?: string }, ): string { const id = typeof refOrId === 'string' ? refOrId : refOrId.id; const cached = imageCache.get(id); if (cached) return cached; const el = document.querySelector( `script[type="midscene-image"][data-id="${CSS.escape(id)}"]`, ); if (el?.textContent) { const data = antiEscapeScriptTag(el.textContent); imageCache.set(id, data); return data; } if (typeof refOrId === 'object' && refOrId?.storage === 'file') { return refOrId.path || `./screenshots/${id}.png`; } // Fallback to directory path return `./screenshots/${id}.png`; } let globalRenderCount = 1; const SIDEBAR_WIDTH_KEY = 'midscene-sidebar-width'; const DEFAULT_SIDEBAR_WIDTH = 280; const MIN_SIDEBAR_WIDTH = 200; const MIN_PLAYER_WIDTH = 320; const SIDEBAR_KEYBOARD_STEP = 24; const clampSidebarWidth = (width: number, layoutWidth: number): number => { const maxWidth = Math.max(MIN_SIDEBAR_WIDTH, layoutWidth - MIN_PLAYER_WIDTH); return Math.min(maxWidth, Math.max(MIN_SIDEBAR_WIDTH, width)); }; function Visualizer(props: VisualizerProps): JSX.Element { const { dumps, embedded = false } = props; const executionDump = useExecutionDump((store: DumpStoreType) => store.dump); const executionDumpLoadId = useExecutionDump( (store) => store._executionDumpLoadId, ); const setReplayAllMode = useExecutionDump((store) => store.setReplayAllMode); const replayAllScripts = useExecutionDump( (store) => store.allExecutionAnimation, ); const activeExecutionAnimation = useExecutionDump( (store) => store.activeExecutionAnimation, ); const insightWidth = useExecutionDump((store) => store.insightWidth); const insightHeight = useExecutionDump((store) => store.insightHeight); const replayAllMode = useExecutionDump((store) => store.replayAllMode); const setPlayingTaskId = useExecutionDump((store) => store.setPlayingTaskId); const setGroupedDump = useExecutionDump((store) => store.setGroupedDump); const sdkVersion = useExecutionDump((store) => store.sdkVersion); const modelBriefs = useExecutionDump((store) => store.modelBriefs); const playwrightAttributes = useExecutionDump( (store) => store.playwrightAttributes, ); const modelBriefText = formatModelBriefText(modelBriefs); const reset = useExecutionDump((store) => store.reset); const [mainLayoutChangeFlag, setMainLayoutChangeFlag] = useState(0); const [sidebarWidth, setSidebarWidth] = useState(() => { const savedWidth = Number(localStorage.getItem(SIDEBAR_WIDTH_KEY)); return Number.isFinite(savedWidth) && savedWidth > 0 ? Math.max(MIN_SIDEBAR_WIDTH, savedWidth) : DEFAULT_SIDEBAR_WIDTH; }); const dump = useExecutionDump((store) => store.dump); const [timelineCollapsed, setTimelineCollapsed] = useState( () => typeof window !== 'undefined' && window.matchMedia(MOBILE_REPORT_MEDIA_QUERY).matches, ); const [mobilePane, setMobilePane] = useState<'steps' | 'player'>('steps'); const [isMobileReport, setIsMobileReport] = useState( () => typeof window !== 'undefined' && window.matchMedia(MOBILE_REPORT_MEDIA_QUERY).matches, ); const [mobileDetailOpen, setMobileDetailOpen] = useState(false); const [reportViewMode, setReportViewMode] = useState('human'); const [selectedMarkdownImagePath, setSelectedMarkdownImagePath] = useState< string | null >(null); const [selectedMarkdownImageRequestId, setSelectedMarkdownImageRequestId] = useState(0); const markdownScrollRef = useRef(null); const screenshotScrollRef = useRef(null); const { modelCallDetailsEnabled: proModeEnabled, setModelCallDetailsEnabled: setProModeEnabled, darkModeEnabled: isDarkMode, setDarkModeEnabled: setIsDarkMode, } = useGlobalPreference(); // Player view flags from the URL. `player-only=1` strips all report chrome // (nav, sidebar, timeline, detail side) and keeps just the Player; in that // mode `play-control=1` shows the control bar. `auto-play` is independent of // player-only and applies to every report player (on by default, `=0` off). const { playerOnly, playControl, autoPlay } = useMemo(() => { const options = getPlayerViewOptions(); return { ...options, playerOnly: embedded ? false : options.playerOnly }; }, [embedded]); // Keep the URL hash in sync with the selected sidebar task (deep-linking). useTaskHashAnchor({ namespaced: embedded }); useEffect(() => { document.documentElement.setAttribute( 'data-theme', isDarkMode ? 'dark' : 'light', ); }, [isDarkMode]); useEffect(() => { const mediaQuery = window.matchMedia(MOBILE_REPORT_MEDIA_QUERY); const updateMobileReport = () => setIsMobileReport(mediaQuery.matches); updateMobileReport(); mediaQuery.addEventListener('change', updateMobileReport); return () => mediaQuery.removeEventListener('change', updateMobileReport); }, []); useEffect(() => { if (!mobileDetailOpen) return; const closeOnEscape = (event: KeyboardEvent) => { if (event.key === 'Escape') setMobileDetailOpen(false); }; window.addEventListener('keydown', closeOnEscape); return () => window.removeEventListener('keydown', closeOnEscape); }, [mobileDetailOpen]); useEffect(() => { if (dumps && dumps.length > 0) { const first = dumps[0]; setGroupedDump(first.get(), first.attributes); } return () => { reset(); }; }, [dumps, reset, setGroupedDump]); useEffect(() => { let resizeThrottler = false; const onResize = () => { if (resizeThrottler) { return; } resizeThrottler = true; setTimeout(() => { resizeThrottler = false; setMainLayoutChangeFlag((prev) => prev + 1); }, 300); }; window.addEventListener('resize', onResize); return () => { window.removeEventListener('resize', onResize); }; }, []); const allSkipped = useMemo( () => dumps && dumps.length > 0 && dumps.every((d) => d.attributes?.playwright_test_status === 'skipped'), [dumps], ); const reportMarkdownView = useMemo(() => { if (reportViewMode !== 'markdown') { return null; } return getReportMarkdownView(dump, (report) => reportToMarkdown(report, { wallTimeFallbackMs: playwrightAttributes?.playwright_test_duration, }), ); }, [dump, playwrightAttributes, reportViewMode]); const readyReportMarkdown = reportMarkdownView?.status === 'ready' ? reportMarkdownView : null; const reportArchiveBaseName = useMemo( () => markdownArchiveBaseName(dump), [dump], ); const resetMarkdownImageSelection = () => { setSelectedMarkdownImagePath(null); setSelectedMarkdownImageRequestId(0); }; const handleReportViewModeChange = (mode: ReportViewMode) => { if (mode === reportViewMode) { return; } setReportViewMode(mode); resetMarkdownImageSelection(); }; const handleCopyReportMarkdown = async () => { if (!readyReportMarkdown) { return; } try { await navigator.clipboard.writeText(readyReportMarkdown.markdown); message.success('Markdown copied'); } catch { message.error('Copy failed'); } }; const handleDownloadReportMarkdownZip = async () => { if (!readyReportMarkdown) { return; } try { const result = await downloadMarkdownZip( readyReportMarkdown.markdown, readyReportMarkdown.attachments, reportArchiveBaseName, ); if (result.missingAttachmentCount > 0) { message.warning( `${result.missingAttachmentCount} screenshot link${ result.missingAttachmentCount === 1 ? '' : 's' } kept as markdown reference${ result.missingAttachmentCount === 1 ? '' : 's' } but not packaged.`, ); } else { message.success('Markdown and images downloaded'); } } catch { message.error('Download failed'); } }; const handleMarkdownImageClick = (markdownPath: string) => { setSelectedMarkdownImagePath(markdownPath); setSelectedMarkdownImageRequestId((current) => current + 1); }; const openMobilePlayer = () => { setMobileDetailOpen(false); setMobilePane('player'); }; useMarkdownScrollSync({ enabled: reportViewMode === 'markdown' && Boolean(readyReportMarkdown), contentKey: executionDumpLoadId, markdownScrollRef, screenshotScrollRef, }); const renderContent = () => { if (dump && dump.executions.length === 0) { return ( ); } if (replayAllMode) { return (
); } return ( <>
setMobileDetailOpen(false)} /> ); }; // Skip building the report chrome entirely when only the Player is requested. let mainContent: JSX.Element | null = null; if (playerOnly) { // Player-only mode renders `playerOnlyContent`; leave `mainContent` unused. } else if (allSkipped && (!dump || dump.executions.length === 0)) { mainContent = (
); } else if (!executionDump) { mainContent = (
); } else { // On phones the Player must not mount behind the Steps pane. In // particular, autoPlay starts inside the Player hook and display:none // cannot pause its requestAnimationFrame loop. const shouldMountPlayerPane = !isMobileReport || mobilePane === 'player'; const content = shouldMountPlayerPane ? renderContent() : null; mainContent = (
void handleCopyReportMarkdown()} onDownloadReportMarkdownZip={() => void handleDownloadReportMarkdownZip() } onReportCaseChange={resetMarkdownImageSelection} onOpenPlayer={openMobilePlayer} />
{ e.preventDefault(); const startX = e.clientX; const startWidth = sidebarWidth; const layoutWidth = e.currentTarget.parentElement?.getBoundingClientRect().width ?? window.innerWidth; let latestWidth = startWidth; const onMouseMove = (ev: MouseEvent) => { latestWidth = clampSidebarWidth( startWidth + ev.clientX - startX, layoutWidth, ); setSidebarWidth(latestWidth); }; const onMouseUp = () => { document.removeEventListener('mousemove', onMouseMove); document.removeEventListener('mouseup', onMouseUp); localStorage.setItem(SIDEBAR_WIDTH_KEY, String(latestWidth)); setMainLayoutChangeFlag((prev) => prev + 1); }; document.addEventListener('mousemove', onMouseMove); document.addEventListener('mouseup', onMouseUp); }} onKeyDown={(event) => { if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return; event.preventDefault(); const layoutWidth = event.currentTarget.parentElement?.getBoundingClientRect() .width ?? window.innerWidth; const maximumWidth = Math.max( MIN_SIDEBAR_WIDTH, layoutWidth - MIN_PLAYER_WIDTH, ); const nextWidth = event.key === 'Home' ? MIN_SIDEBAR_WIDTH : event.key === 'End' ? maximumWidth : clampSidebarWidth( sidebarWidth + (event.key === 'ArrowLeft' ? -SIDEBAR_KEYBOARD_STEP : SIDEBAR_KEYBOARD_STEP), layoutWidth, ); setSidebarWidth(nextWidth); localStorage.setItem(SIDEBAR_WIDTH_KEY, String(nextWidth)); setMainLayoutChangeFlag((previous) => previous + 1); }} />
{shouldMountPlayerPane && (reportViewMode === 'markdown' ? ( ) : ( <>
{!replayAllMode && ( )}
{!timelineCollapsed && }
{content}
))}
); } const [containerHeight, setContainerHeight] = useState('100%'); useEffect(() => { if (embedded) { setContainerHeight('100%'); return; } const ifInRspressPage = document.querySelector('.rspress-nav'); const navHeightKey = '--rp-nav-height'; const originalNavHeight = getComputedStyle( document.documentElement, ).getPropertyValue(navHeightKey); if (ifInRspressPage) { const newNavHeight = '42px'; setContainerHeight(`calc(100vh - ${newNavHeight})`); document.documentElement.style.setProperty(navHeightKey, newNavHeight); } return () => { if (ifInRspressPage) { document.documentElement.style.setProperty( navHeightKey, originalNavHeight, ); } }; }, [embedded]); useEffect(() => { return () => { globalRenderCount += 1; }; }, []); // In player-only mode, skip every piece of chrome and render just the Player. // Mirror the main view's script source: the report opens in "replay all" mode // by default (whole-flow animation); deep-linking to a `#task-` anchor // switches to that single task's replay. const playerOnlyScripts = (replayAllMode ? replayAllScripts : activeExecutionAnimation) || []; let playerOnlyContent: JSX.Element; if (!executionDump) { playerOnlyContent = ; } else if (playerOnlyScripts.length === 0) { // Player renders nothing for empty scripts; show feedback instead of a blank // page (e.g. the active task is not a Planning step with a replay animation). playerOnlyContent = ( ); } else { playerOnlyContent = ( ); } return (
{playerOnly ? (
{playerOnlyContent}
) : ( <> {!embedded && (
Report
{sdkVersion ? `v${sdkVersion}` : 'unknown version'} {modelBriefText ? ` | ${modelBriefText}` : ''}
)} {mainContent} )}
); } export function App() { /** * Parse attributes from a dump script element. */ function parseAttributesFromElement(el: Element): PlaywrightTaskAttributes { return parseDumpAttributes( Array.from(el.attributes).map(({ name, value }) => ({ name, value })), ); } function getDumpElements(): PlaywrightTasks[] { const dumpElements = document.querySelectorAll( 'script[type="midscene_web_dump"]', ); const validElements = Array.from(dumpElements).filter((el) => { const textContent = el.textContent; if (!textContent) { console.warn('empty content in script tag', el); } return !!textContent; }); // Group elements by data-group-id. // For backward compatibility with older reports that lack data-group-id, // each element without the attribute is treated as its own group. const groupMap = new Map(); let ungroupedCounter = 0; for (const el of validElements) { const groupId = el.getAttribute('data-group-id'); const decodedGroupId = groupId ? decodeURIComponent(groupId) : `__ungrouped_${ungroupedCounter++}`; if (!groupMap.has(decodedGroupId)) { groupMap.set(decodedGroupId, []); } groupMap.get(decodedGroupId)!.push(el); } const result: PlaywrightTasks[] = []; // Process grouped dump tags — merge into one PlaywrightTasks per group for (const [groupId, elements] of groupMap) { const attributes = parseAttributesFromElement(elements[0]); const reportIdAttribute = elements[0].getAttribute('data-report-id'); const runnerScopeAttribute = elements[0].getAttribute( 'data-runner-scope-id', ); let cachedJsonContent: GroupedActionDump | null = null; let isParsed = false; result.push({ get: () => { if (!isParsed) { console.time('parse_grouped_dump'); const allExecutions: any[] = []; let baseDump: GroupedActionDump | null = null; for (const el of elements) { const content = antiEscapeScriptTag(el.textContent || ''); const parsed = JSON.parse(content); const restored = restoreImageReferences( parsed, resolveImageFromDom, ) as IReportActionDump; const dump = GroupedActionDump.fromJSON(restored); if (!baseDump) { baseDump = dump; } allExecutions.push(...dump.executions); } // Deduplicate executions by id — keep only the last one. // Only executions with a stable id are deduped; old-format entries // without id are always kept (they may be distinct despite same name). baseDump!.executions = dedupeExecutionsKeepLatest(allExecutions); cachedJsonContent = baseDump!; console.timeEnd('parse_grouped_dump'); (cachedJsonContent as any).attributes = attributes; isParsed = true; } return cachedJsonContent!; }, attributes, reportId: reportIdAttribute ? decodeURIComponent(reportIdAttribute) : groupId, ...(runnerScopeAttribute ? { runnerScopeId: decodeURIComponent(runnerScopeAttribute) } : {}), }); } return result; } const [reportDump, setReportDump] = useState([]); const [runnerDump, setRunnerDump] = useState(null); const [error, setError] = useState(null); const dumpsLoadedRef = useRef(false); useEffect(() => { // Check if document is already loaded const loadDumpElements = () => { const currentElements = document.querySelectorAll( 'script[type="midscene_web_dump"]', ); // If it has been loaded and the number of elements has not changed, skip it. if ( dumpsLoadedRef.current && currentElements.length === reportDump.length ) { return; } dumpsLoadedRef.current = true; if ( currentElements.length === 1 && currentElements[0].textContent?.trim() === '' ) { setError('There is no dump data to display.'); setReportDump([]); return; } setError(null); const dumpElements = getDumpElements(); setReportDump(dumpElements); const runnerElements = document.querySelectorAll( 'script[type="midscene_test_run_dump"]', ); if (runnerElements.length > 1) { throw new Error('The report contains multiple Midscene Test dumps.'); } if (runnerElements.length === 1) { const content = runnerElements[0].textContent; if (!content) throw new Error('The Midscene Test report dump is empty.'); setRunnerDump(parseTestRunReportDump(content)); } else { setRunnerDump(null); } }; const controller = new AbortController(); let timer: ReturnType | undefined; const loadDumps = async () => { console.time('loading_dump'); try { await hydrateDirectoryReport(document, fetch, controller.signal); } catch (error) { if (!controller.signal.aborted) setError(error instanceof Error ? error.message : String(error)); console.timeEnd('loading_dump'); return; } try { if (controller.signal.aborted) return; loadDumpElements(); } catch (error) { setError(error instanceof Error ? error.message : String(error)); } console.timeEnd('loading_dump'); }; // If DOM is already loaded (React mounts after DOMContentLoaded in most cases) if ( document.readyState === 'complete' || document.readyState === 'interactive' ) { // Use a small timeout to ensure all scripts are parsed timer = setTimeout(loadDumps, 0); } else { // Wait for DOM content to be fully loaded document.addEventListener('DOMContentLoaded', loadDumps); } return () => { controller.abort(); clearTimeout(timer); document.removeEventListener('DOMContentLoaded', loadDumps); }; }, []); if (error) { return (
); } return runnerDump ? ( } /> ) : ( ); } export { Visualizer };