import { Button, Modal, Text } from '@mantine/core'; import { IconArrowsMaximize, IconCheck, IconEye, IconLock, IconPlayerPause, IconPlayerPlay, IconRefresh, IconShieldLock, IconUserCheck, IconX } from '@/components/icons'; import { useEffect, useRef, useState, type ReactElement } from 'react'; import { Link } from 'react-router-dom'; import { useLive } from '../../api/hooks'; import type { LiveStatus } from '../../api/types'; import { useAuth } from '../../auth/AuthContext'; import { useSidePanelOptional } from '../../components/shell/SidePanel'; const WAITING = ['waiting_approval', 'waiting_sign_in', 'waiting_review']; const RUNNING = ['queued', 'running']; export const SLOW_START_MS = 60_000; // Oracle Fusion sign-in is slow, but a minute without a picture needs an explanation export const RELOAD_AFTER_MS = 30_000; // while reconnecting, offer "Reload the picture" after this long const MARK: Record = { passed: { icon: , tone: 'green', word: 'passed' }, failed: { icon: , tone: 'red', word: 'failed' }, skipped: { icon: –, tone: 'neutral', word: 'not run' }, }; /** True for the people who may watch (the API enforces the same rule). */ export function useCanWatch() { return useAuth().can('evidence.read'); } // ------------------------------------------------------------------ the states of the live browser, as one pure function /** starting | live | masked (sign-in hidden) | reconnecting | paused (waiting for you) | frozen (you paused the view) | preparing (next batch) | * ended | unavailable | nopermission | quick (a quick simulation has no browser) */ export type LiveKind = 'starting' | 'live' | 'masked' | 'reconnecting' | 'paused' | 'frozen' | 'preparing' | 'ended' | 'unavailable' | 'nopermission' | 'quick'; export interface LiveOverlay { kind: LiveKind; /** headline over the picture (empty when the picture is shown clean) */ title: string; text: string; /** the state badge; the word is always present, colour is never the only signal */ badge: { label: string; tone: 'red' | 'grey' | 'orange' } | null; controls: { pause: boolean; jump: boolean; fullscreen: boolean; reload: boolean }; /** the frame area is replaced by an empty state */ replaces: boolean; } export interface LiveCtx { status: string; gate?: string | null; canWatch: boolean; quick: boolean; /** the browser has been active at some point in this view */ everActive: boolean; slow: boolean; frozen: boolean; /** milliseconds the stream has been reconnecting (0 when it is not) */ reconnectingFor: number; /** seconds since the last picture, when known */ frameAgeS: number | null; } const NONE = { pause: false, jump: false, fullscreen: false, reload: false }; /** The ladder of states of the live browser panel (UI-APPLE 8.4.4), driven only by data the server already sends. */ export function liveOverlay(l: LiveStatus | undefined, c: LiveCtx): LiveOverlay { if (c.quick) return { kind: 'quick', replaces: true, badge: null, controls: NONE, title: 'No browser to watch', text: 'Quick simulation runs don’t open a browser, so there is nothing to watch. Choose Full browser run when you start a test run to see it live.' }; if (!c.canWatch) return { kind: 'nopermission', replaces: true, badge: null, controls: NONE, title: 'Watching needs a role', text: 'Watching the test needs the consultant, QA approver or admin role.' }; if (l && !l.available) return { kind: 'unavailable', replaces: true, badge: null, controls: NONE, title: 'Live view is not available', text: l.reason ?? 'Live view is not available for this test run.' }; if (c.frozen) return { kind: 'frozen', replaces: false, badge: { label: 'PAUSED', tone: 'grey' }, controls: { ...NONE, jump: true, fullscreen: true }, title: 'View paused', text: 'View paused. The test is still running.' }; if (WAITING.includes(c.status)) return { kind: 'paused', replaces: false, badge: { label: 'PAUSED', tone: 'grey' }, controls: NONE, title: 'Paused for your review', text: `Paused for your review. Testing ${c.gate === 'human_review' ? 'continues after you decide the failure' : 'starts after you approve the scenarios'}.` }; if (l?.active && l.masked) return { kind: 'masked', replaces: false, badge: { label: 'LIVE', tone: 'red' }, controls: { ...NONE, fullscreen: true }, title: 'Sign-in screen hidden', text: 'Sign-in screen hidden. Passwords are never shown here.' }; if (l?.active && l.stale) return { kind: 'reconnecting', replaces: false, badge: { label: 'RECONNECTING', tone: 'orange' }, controls: { ...NONE, fullscreen: true, reload: c.reconnectingFor >= RELOAD_AFTER_MS }, title: 'Reconnecting to the test browser…', text: `The test keeps running. We show the last picture we received${c.frameAgeS !== null ? ` (${c.frameAgeS} s ago)` : ''}.` }; if (l?.active && !l.frame_ts) return { kind: 'starting', replaces: false, badge: { label: 'STARTING', tone: 'grey' }, controls: NONE, title: 'Starting the browser…', text: c.slow ? 'The browser is taking longer than usual to show a picture. Oracle Fusion can be slow to sign in. If nothing appears soon, cancel the test run and start it again; the activity log shows the error if the browser could not open.' : 'This takes a few seconds. The first screen appears here.' }; if (l?.active) return { kind: 'live', replaces: false, badge: { label: 'LIVE', tone: 'red' }, controls: { ...NONE, pause: true, fullscreen: true }, title: '', text: '' }; if (RUNNING.includes(c.status)) return { kind: 'preparing', replaces: false, badge: { label: 'STARTING', tone: 'grey' }, controls: NONE, title: 'Getting ready', text: c.everActive ? 'Preparing the next batch of scenarios…' : 'The agents are preparing the test run. The browser opens when the scenarios start.' }; return { kind: 'ended', replaces: false, badge: { label: 'ENDED', tone: 'grey' }, controls: NONE, title: 'Testing has finished', text: 'Testing has finished. Open the report for the results.' }; } /** A tick every second while something is counting (picture age, reconnect timer). */ function useNow(on: boolean) { const [now, setNow] = useState(() => Date.now()); useEffect(() => { if (!on) return; const t = window.setInterval(() => setNow(Date.now()), 1000); return () => window.clearInterval(t); }, [on]); return now; } export function LiveBadge({ badge }: { badge: LiveOverlay['badge'] }) { if (!badge) return null; return {badge.label}; } /** The test environment's browser as a window: three quiet dots, the page address, and the picture. Light chrome even in dark mode. */ export function BrowserFrame({ url, children, frameRef, testId, dim }: { url?: string | null; children: React.ReactNode; frameRef?: React.Ref; testId?: string; dim?: boolean }) { return (
{url || 'test environment'}
{children}
); } /** One line in the run header on every tab: what is being tested right now, with a Watch button. */ export function NowTesting({ id, enabled }: { id: string; enabled: boolean }) { const live = useLive(id, enabled); const l = live.data; if (!enabled || !l?.active) return null; return (
LIVE Now testing: {l.scenario_title ?? 'starting the browser…'} {l.progress.total ? · {Math.min(l.progress.done + 1, l.progress.total)} of {l.progress.total} : null} {l.results.failed ? · {l.results.failed} failing : null}
); } function Results({ id, l, sawFailure, gate }: { id: string; l?: LiveStatus; sawFailure: boolean; gate?: string | null }) { const [open, setOpen] = useState(false); const failed = l?.failed; const recent = l?.results.recent ?? []; return (

Results so far{l?.results.passed ?? 0} passed · {l?.results.failed ?? 0} failed

{failed && ( )}
{recent.length === 0 &&
No scenario has finished yet.
} {recent.map((r, i) => { const m = MARK[r.status] ?? MARK.skipped; return (
{m.icon}{m.word} {r.title}
); })}

Up next

{(l?.up_next ?? []).length === 0 ? {l?.active ? 'This is the last scenario of this batch.' : 'Nothing is queued right now.'} :
{l!.up_next.map((u) => {u.title})}
} setOpen(false)} title={failed ? `Failed screen: ${failed.title}` : ''} size="xl" centered> {failed && {`Screen} Test data only. This picture is kept only while this part of the test run is running; the saved screenshot is in the failure review. {sawFailure && gate === 'human_review' && }
); } /** "Watch the test": the test environment's browser, view only. Scenario-level caption; no control of the test. * `variant="inline"` is the small copy inside the Testing step; it uses suffixed test ids so the panel keeps the plain ones. */ export function LiveView({ id, status, gate, reasonQuick, compact, variant = 'panel' }: { id: string; status: string; gate?: string | null; reasonQuick?: boolean; compact?: boolean; variant?: 'panel' | 'inline'; }) { const inline = variant === 'inline'; const sfx = inline ? '-inline' : ''; const canWatch = useCanWatch(); const panel = useSidePanelOptional(); const live = useLive(id, canWatch && !reasonQuick); const l = live.data; const frameRef = useRef(null); const imgRef = useRef(null); const [conn, setConn] = useState(0); // bump to reconnect the stream (new attempt or batch, or after an error) const [everActive, setEverActive] = useState(false); const [still, setStill] = useState(null); // "Pause view": a frozen copy of the last frame const [sawFailure, setSawFailure] = useState(false); const [showFailed, setShowFailed] = useState(false); const [streamDown, setStreamDown] = useState(null); // when the stream last failed (for the reconnect timer) const wasActive = useRef(false); // the browser was asked to open but no picture has arrived for a while: say so instead of showing "Starting…" forever const starting = !!l?.active && !l.frame_ts; const [slow, setSlow] = useState(false); useEffect(() => { if (!starting) { setSlow(false); return; } const t = window.setTimeout(() => setSlow(true), SLOW_START_MS); return () => window.clearTimeout(t); }, [starting, l?.scenario_id]); useEffect(() => { if (l?.active && !wasActive.current) { setEverActive(true); setConn((c) => c + 1); } wasActive.current = !!l?.active; }, [l?.active]); useEffect(() => { if (l?.failed || l?.results.failed) setSawFailure(true); }, [l?.failed, l?.results.failed]); const reconnecting = !!l?.active && (l.stale || streamDown !== null); const now = useNow(!!l?.active); const [staleSince, setStaleSince] = useState(null); useEffect(() => { setStaleSince((s) => (reconnecting ? s ?? Date.now() : null)); }, [reconnecting]); const frameAgeS = l?.frame_ts ? Math.max(0, Math.round((now - Date.parse(l.frame_ts)) / 1000)) : null; const ov = liveOverlay(l && reconnecting && !l.stale ? { ...l, stale: true } : l, { status, gate, canWatch, quick: !!reasonQuick, everActive, slow, frozen: !!still, reconnectingFor: staleSince ? now - staleSince : 0, frameAgeS, }); const body = ov.replaces; const pause = () => { const img = imgRef.current; if (!img || !img.naturalWidth) return; const c = document.createElement('canvas'); c.width = img.naturalWidth; c.height = img.naturalHeight; c.getContext('2d')?.drawImage(img, 0, 0); try { setStill(c.toDataURL('image/jpeg', 0.8)); } catch { /* keep streaming */ } }; if (body) { const unavailable = ov.kind === 'unavailable' || ov.kind === 'quick'; return (
{ov.kind === 'nopermission' ? : } {ov.title} {ov.text} {unavailable && !inline && }
{ov.kind}
); } const caption = ov.kind === 'live' && frameAgeS !== null ? (frameAgeS < 5 ? 'Updated just now' : `Last picture ${frameAgeS} s ago`) : ov.kind === 'reconnecting' && frameAgeS !== null ? `Last picture ${frameAgeS} s ago` : ''; const url = l?.path ? `${l.path}` : l?.page_title ?? null; const showOverlay = ov.kind !== 'live' && ov.kind !== 'frozen'; return (
{ov.kind}
{l?.active ? l.scenario_title ?? 'Starting the browser…' : ov.kind === 'paused' ? 'Paused for your review' : RUNNING.includes(status) ? 'Getting ready' : 'Testing has finished'} {l?.active && ( {[[l.area, l.step].filter(Boolean).join(' › '), l.role ? `Signed in as: ${l.role}` : '', l.progress.total ? `scenario ${Math.min(l.progress.done + 1, l.progress.total)} of ${l.progress.total}` : ''].filter(Boolean).join(' · ')} )}
{l?.active && (l.masked || l.action) && (
Now: {l.masked ? 'Signing in (the sign-in screen is not shown)' : l.action} {!l.masked && l.action_n > 0 && · action {l.action_n}}
)} {sawFailure && (
This step failed. Testing continues with the next scenario. {l?.failed && } {gate === 'human_review' && }
)} {everActive && !still && ( {`Live setStreamDown(null)} onError={() => { setStreamDown((s) => s ?? Date.now()); if (wasActive.current) window.setTimeout(() => setConn((c) => c + 1), 2000); }} /> )} {still && Paused picture of the test browser} {showOverlay && (
{ov.kind === 'masked' ? : ov.kind === 'paused' ? : ov.kind === 'ended' ? : ov.kind === 'reconnecting' ? : } {ov.title} {ov.text} {(ov.kind === 'starting' || ov.kind === 'preparing') && }
)} {still && (
View paused View paused. The test is still running.
)}
{!inline ? (
{still ? : } {ov.controls.reload && } {caption && {caption}}
) : (
View only. Test data only. {caption && {caption}} {panel && }
)} {!inline && (

Test data only. This is the test environment's browser, not your own session.{l?.page_title ? ` Page: ${l.page_title}.` : ''}

)} {!inline && } setShowFailed(false)} title={l?.failed ? `Failed screen: ${l.failed.title}` : ''} size="xl" centered> {l?.failed && {`Screen}
); }