patchwise-agent-studio / web /src /pages /run /LiveView.tsx
EnergyVenom's picture
Astra: PO/GL actions, usage coverage, assisted sign-in, self-healing, recorder, new top navigation and theme (172a4e22a2bf)
fb62a97 verified
Raw History Blame Contribute Delete
21 kB
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<string, { icon: ReactElement; tone: string; word: string }> = {
passed: { icon: <IconCheck size={12} aria-hidden />, tone: 'green', word: 'passed' },
failed: { icon: <IconX size={12} aria-hidden />, tone: 'red', word: 'failed' },
skipped: { icon: <span aria-hidden>–</span>, 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 <span className="trio-livebadge" data-tone={badge.tone} data-testid="live-badge">{badge.label}</span>;
}
/** 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<HTMLDivElement>; testId?: string; dim?: boolean }) {
return (
<div className="trio-browser">
<div className="trio-bchrome"><span className="trio-bdots" aria-hidden><i /><i /><i /></span>
<span className="trio-burl"><IconLock size={10} aria-hidden />{url || 'test environment'}</span></div>
<div ref={frameRef} className="fpt-live-frame trio-viewport" data-dim={dim || undefined} data-testid={testId}>{children}</div>
</div>
);
}
/** 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 (
<div className="trio-nowtesting" data-testid="now-testing" role="status">
<span className="trio-livebadge" data-tone="red">LIVE</span>
<Text size="sm" truncate style={{ minWidth: 0, flex: '1 1 auto' }}>
<b>Now testing:</b> {l.scenario_title ?? 'starting the browser…'}
{l.progress.total ? <Text span c="dimmed"> · {Math.min(l.progress.done + 1, l.progress.total)} of {l.progress.total}</Text> : null}
{l.results.failed ? <Text span c="red"> · {l.results.failed} failing</Text> : null}
</Text>
<Button component={Link} to={`/runs/${id}/live`} size="compact-xs" leftSection={<IconEye size={12} />}>Watch</Button>
</div>
);
}
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 (
<div className="trio-live-results" aria-label="results so far" role="region">
<h4><span>Results so far</span><span className="fpt-num">{l?.results.passed ?? 0} passed · {l?.results.failed ?? 0} failed</span></h4>
{failed && (
<button type="button" className="fpt-failed-frame" onClick={() => setOpen(true)} aria-label={`See the failed screen of ${failed.title}`}>
<img src={`/api/runs/${encodeURIComponent(id)}/live/failed?t=${encodeURIComponent(failed.ts)}`} alt={`Screen of ${failed.title} at the moment it failed`} />
<Text size="xs" fw={600} p={6} ta="left">Failed: {failed.title}</Text>
</button>
)}
<div className="trio-group trio-group-flat">
{recent.length === 0 && <div className="trio-row trio-row-sm"><span className="trio-row-body"><span>No scenario has finished yet.</span></span></div>}
{recent.map((r, i) => {
const m = MARK[r.status] ?? MARK.skipped;
return (
<div key={`${r.scenario_id}${i}`} className="trio-row trio-row-sm">
<span className="trio-ico" data-tone={m.tone} title={m.word}>{m.icon}<span className="fpt-sr-only">{m.word}</span></span>
<span className="trio-row-body"><b>{r.title}</b></span>
</div>
);
})}
</div>
<h4><span>Up next</span></h4>
{(l?.up_next ?? []).length === 0
? <Text size="xs" c="dimmed">{l?.active ? 'This is the last scenario of this batch.' : 'Nothing is queued right now.'}</Text>
: <div className="trio-upnext">{l!.up_next.map((u) => <span key={u.scenario_id}>{u.title}</span>)}</div>}
<Modal opened={open && !!failed} onClose={() => setOpen(false)} title={failed ? `Failed screen: ${failed.title}` : ''} size="xl" centered>
{failed && <img src={`/api/runs/${encodeURIComponent(id)}/live/failed?t=${encodeURIComponent(failed.ts)}`} alt={`Screen of ${failed.title} at the moment it failed`} style={{ width: '100%', borderRadius: 8 }} />}
<Text size="xs" c="dimmed" mt={6}>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.</Text>
</Modal>
{sawFailure && gate === 'human_review' && <Button component={Link} to={`/runs/${id}/failures`} size="xs" variant="light" color="red">Open in failure review</Button>}
</div>
);
}
/** "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<HTMLDivElement>(null);
const imgRef = useRef<HTMLImageElement>(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<string | null>(null); // "Pause view": a frozen copy of the last frame
const [sawFailure, setSawFailure] = useState(false);
const [showFailed, setShowFailed] = useState(false);
const [streamDown, setStreamDown] = useState<number | null>(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<number | null>(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 (
<div className="trio-live" data-testid={`live-view${sfx}`} data-live-state={ov.kind}>
<div className="trio-live-empty" data-testid={ov.kind === 'unavailable' ? `live-unavailable${sfx}` : undefined} role="status">
<span className="trio-live-ic">{ov.kind === 'nopermission' ? <IconLock size={22} /> : <IconEye size={22} />}</span>
<b>{ov.title}</b>
<span>{ov.text}</span>
{unavailable && !inline && <Button component={Link} to="/?new=1" size="xs">New test run</Button>}
</div>
<span className="fpt-sr-only" data-testid={`live-state${sfx}`}>{ov.kind}</span>
</div>
);
}
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 (
<div className="trio-live" data-testid={`live-view${sfx}`} data-compact={compact || undefined} data-live-state={ov.kind} data-variant={variant}>
<span className="fpt-sr-only" data-testid={`live-state${sfx}`}>{ov.kind}</span>
<div className="trio-live-top">
<div className="trio-live-t">
<b data-testid={`live-title${sfx}`}>{l?.active ? l.scenario_title ?? 'Starting the browser…' : ov.kind === 'paused' ? 'Paused for your review' : RUNNING.includes(status) ? 'Getting ready' : 'Testing has finished'}</b>
{l?.active && (
<span>
{[[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(' · ')}
</span>
)}
</div>
<LiveBadge badge={ov.badge} />
</div>
{l?.active && (l.masked || l.action) && (
<div className="trio-nowline" data-testid={`live-action${sfx}`} aria-live="off">
<IconPlayerPlay size={13} aria-hidden />
<span><b>Now:</b> {l.masked ? 'Signing in (the sign-in screen is not shown)' : l.action}
{!l.masked && l.action_n > 0 && <span className="trio-dim"> · action {l.action_n}</span>}</span>
</div>
)}
{sawFailure && (
<div className="trio-banner" data-tone="red" role="status" data-testid={`live-failure-banner${sfx}`}>
<span style={{ flex: 1 }}>This step failed. Testing continues with the next scenario.</span>
<span className="trio-banner-acts">
{l?.failed && <Button size="compact-xs" variant="white" onClick={() => setShowFailed(true)}>See the failed screen</Button>}
{gate === 'human_review' && <Button size="compact-xs" variant="white" component={Link} to={`/runs/${id}/failures`}>Open in failure review</Button>}
</span>
</div>
)}
<BrowserFrame url={url} frameRef={frameRef} testId={`live-frame${sfx}`} dim={showOverlay && !still}>
{everActive && !still && (
<img key={conn} ref={imgRef} src={`/api/runs/${encodeURIComponent(id)}/live/stream?c=${conn}`} alt={`Live picture of the test browser: ${l?.scenario_title ?? 'test in progress'}`}
onLoad={() => setStreamDown(null)}
onError={() => { setStreamDown((s) => s ?? Date.now()); if (wasActive.current) window.setTimeout(() => setConn((c) => c + 1), 2000); }} />
)}
{still && <img src={still} alt="Paused picture of the test browser" />}
{showOverlay && (
<div className="fpt-live-overlay" role="status" data-kind={ov.kind}>
<span className="trio-ov-ic" data-tone={ov.kind === 'paused' ? 'orange' : undefined} aria-hidden>
{ov.kind === 'masked' ? <IconShieldLock size={22} /> : ov.kind === 'paused' ? <IconUserCheck size={22} /> : ov.kind === 'ended' ? <IconCheck size={22} /> : ov.kind === 'reconnecting' ? <IconRefresh size={22} className="fpt-spin" /> : <IconEye size={22} />}
</span>
<b>{ov.title}</b>
<span className="trio-ov-s">{ov.text}</span>
{(ov.kind === 'starting' || ov.kind === 'preparing') && <span className="trio-skelline" aria-hidden />}
</div>
)}
{still && (
<div className="fpt-live-overlay" data-kind="frozen" role="status">
<b>View paused</b>
<span className="trio-ov-s">View paused. The test is still running.</span>
<Button size="compact-sm" onClick={() => setStill(null)} leftSection={<IconPlayerPlay size={12} />}>Jump to live</Button>
</div>
)}
</BrowserFrame>
{!inline ? (
<div className="trio-live-ctrls">
{still
? <Button size="compact-sm" onClick={() => setStill(null)} leftSection={<IconPlayerPlay size={13} />}>Jump to live</Button>
: <Button size="compact-sm" onClick={pause} disabled={!ov.controls.pause} leftSection={<IconPlayerPause size={13} />}>Pause view</Button>}
<Button size="compact-sm" onClick={() => void frameRef.current?.requestFullscreen?.()} disabled={!ov.controls.fullscreen} leftSection={<IconArrowsMaximize size={13} />}>Fullscreen</Button>
{ov.controls.reload && <Button size="compact-sm" onClick={() => { setStreamDown(null); setConn((c) => c + 1); }} leftSection={<IconRefresh size={13} />}>Reload the picture</Button>}
<span className="trio-live-sp" />
{caption && <span className="trio-live-cap fpt-num">{caption}</span>}
</div>
) : (
<div className="trio-live-ctrls">
<span className="trio-live-cap">View only. Test data only.</span>
<span className="trio-live-sp" />
{caption && <span className="trio-live-cap fpt-num">{caption}</span>}
{panel && <Button size="compact-xs" onClick={() => panel.show('live')}>Open in the side panel</Button>}
</div>
)}
{!inline && (
<p className="trio-honest"><IconShieldLock size={14} aria-hidden /><span>Test data only. This is the test environment&apos;s browser, not your own session.{l?.page_title ? ` Page: ${l.page_title}.` : ''}</span></p>
)}
{!inline && <Results id={id} l={l} sawFailure={sawFailure} gate={gate} />}
<Modal opened={showFailed && !!l?.failed} onClose={() => setShowFailed(false)} title={l?.failed ? `Failed screen: ${l.failed.title}` : ''} size="xl" centered>
{l?.failed && <img src={`/api/runs/${encodeURIComponent(id)}/live/failed?t=${encodeURIComponent(l.failed.ts)}`} alt={`Screen of ${l.failed.title} at the moment it failed`} style={{ width: '100%', borderRadius: 8 }} />}
</Modal>
</div>
);
}