import { Button, Group, Menu, Modal, Skeleton, Stack, Text, Textarea, Tooltip } from '@mantine/core'; import { NavTabs } from '../../components/NavTabs'; import './run.css'; import { notifications } from '@mantine/notifications'; import { useMutation, useQueryClient } from '@tanstack/react-query'; import { IconArrowLeft, IconChevronDown, IconLayoutSidebarRight, IconLayoutSidebarRightCollapse, IconPlayerPlay } from '@/components/icons'; import { useEffect, useRef, useState, type ReactNode } from 'react'; import { Link, useNavigate, useParams, useSearchParams } from 'react-router-dom'; import { MODULE_NAMES } from '../../domain/agents'; import { api, unwrap } from '../../api/client'; import { useEvidence, useGate, useLive, usePods, useRun, useRunAction, useRunFailures, useRunReadiness } from '../../api/hooks'; import type { ApproveGate } from '../../api/types'; import { useAuth } from '../../auth/AuthContext'; import { Can, DecisionBadge, ErrorAlert, GlossaryList } from '../../components/common'; import { EmptyState } from '../../components/shell/EmptyState'; import { envKind, useChosenEnv } from '../../components/shell/EnvSwitcher'; import { ExcelPanel, ReportSummary, ScenarioSteps } from '../../components/shell/panelTabs'; import { PANEL_TABS, useShell, type PanelTab } from '../../components/shell/prefs'; import { SidePanel, SidePanelProvider, useSidePanel } from '../../components/shell/SidePanel'; import { TopBar } from '../../components/shell/TopBar'; import { runAreas, runTitle, shortWhen } from '../../domain/runName'; import { rowWords, runStatusWords } from '../../components/shell/RunListItem'; import { runState } from '../../components/shell/StatusDot'; import { useWaitsOnMe } from '../../domain/waiting'; import { TextShimmer } from '../../components/wensity/text-shimmer'; import { RunStages } from './RunStages'; import { FailureReview } from './FailureReview'; import { LiveView, NowTesting, useCanWatch } from './LiveView'; import { RunData, RunScripts } from './RunData'; import { Activity, LEGACY_TAB, NextStep, Overview, RunChanges, TERMINAL } from './RunPage'; import { guideStage } from './RunGuide'; import { RunProof, type ProofFilter } from './RunProof'; import { RunReport } from './RunReport'; import { RunResearch } from './RunResearch'; import { RunWorkflow } from './RunWorkflow'; import { ScenarioReview } from './ScenarioReview'; import { SignOffReport } from './SignOffReport'; /** Routes that keep the conversation in the center and open the side panel on a tab. */ const PANEL_ROUTE: Record = { live: 'live', proof: 'screens', script: 'excel' }; const MORE_ALL: Record = { process: 'By business process', changes: 'What the patch changes', activity: 'Activity log' }; const MORE_ADMIN: Record = { research: 'Coverage map', data: 'Data plan', scripts: 'Scripts', technical: 'Technical report' }; const VIEW_TITLE: Record = { scenarios: 'Scenarios', failures: 'Failures', workflow: 'Team board', report: 'Report & sign-off', ...MORE_ALL, ...MORE_ADMIN }; const DETAIL = new Set(Object.keys(VIEW_TITLE)); /** The test run workspace: the conversation (or a detail view) in the center, the evidence on the right. * Owns /runs/new, /runs/:id and /runs/:id/:tab. */ export function RunWorkspace() { return ( ); } function Workspace() { const { id, tab: rawTab } = useParams(); const nav = useNavigate(); const { can } = useAuth(); const panel = useSidePanel(); const { size } = useShell(); const canWatch = useCanWatch(); const run = useRun(id ?? '', !!id); const rd = useRunReadiness(id ?? ''); const pods = usePods().data ?? []; const chosen = useChosenEnv().pod; const action = useRunAction(); const r = id ? run.data : undefined; const tab = rawTab ? LEGACY_TAB[rawTab] ?? rawTab : undefined; const detail = tab && DETAIL.has(tab) ? tab : null; const browserRun = !!r && r.playwright_mode !== 'stub'; const watching = browserRun && canWatch && !!r?.live_view && ['queued', 'running'].includes(r?.status ?? ''); const live = useLive(id ?? '', !!id && watching); const evidence = useEvidence(id ?? ''); const scenarios = (rd.data?.modules ?? []).reduce((n, m) => n + m.counts.scenarios, 0); const stage = r ? guideStage(r, scenarios) : null; const pod = r ? pods.find((p) => p.id === r.pod_id) : chosen; const fusion = envKind(pod?.kind) === 'fusion'; const [proofFilter, setProofFilter] = useState('all'); const [params] = useSearchParams(); const [glossary, setGlossary] = useState(false); const [note, setNote] = useState(false); const [cancelling, setCancelling] = useState(false); const gate = useGate(id ?? '', !!id && r?.pending_gate === 'approve_cases'); const failures = useRunFailures(id ?? '', !!id && r?.status === 'waiting_review' && !browserRun); // Opening a run: pick the panel tab from the run's state, unless the URL names a tab or the person chose one in this run. const initFor = useRef(null); useEffect(() => { if (!id || !r || initFor.current === id) return; if ((tab && PANEL_ROUTE[tab]) || panel.chosenInRun()) { initFor.current = id; return; } if (params.get('scenario')) { initFor.current = id; panel.pick('steps'); return; } const STOPPED = ['failed', 'killed', 'cancelled', 'interrupted']; let choice: { tab: PanelTab; scenario?: string; filter?: ProofFilter } | null = null; if (r.status === 'completed') choice = { tab: 'report' }; else if (r.status === 'waiting_review' || r.pending_gate === 'human_review') { if (browserRun) choice = { tab: 'screens', filter: 'failed' }; else if (failures.data) { const f = failures.data.find((x) => x.pending) ?? failures.data[0]; choice = f ? { tab: 'steps', scenario: f.case_id } : { tab: 'report' }; } } else if (r.status === 'waiting_approval' || r.pending_gate === 'approve_cases') { if (gate.data !== undefined) { const pend = gate.data?.gate === 'approve_cases' ? (gate.data as ApproveGate).pending : []; const p = pend.find((x) => x.origin === 'ai') ?? pend.find((x) => x.changed_by_patch || x.new_or_changed); choice = p ? { tab: 'steps', scenario: p.id } : { tab: 'excel' }; } } else if (['queued', 'running'].includes(r.status)) choice = { tab: browserRun && r.live_view ? 'live' : 'excel' }; else if (STOPPED.includes(r.status)) choice = { tab: browserRun ? 'screens' : 'report' }; else choice = { tab: 'excel' }; if (!choice) return; // waiting for the gate or the failures to load initFor.current = id; if (choice.filter) setProofFilter(choice.filter); panel.pick(choice.tab, { scenario: choice.scenario }); }, [id, r?.status, r?.pending_gate, gate.data, failures.data]); // eslint-disable-line react-hooks/exhaustive-deps // /runs/:id/live, /proof, /script open the panel on that tab useEffect(() => { if (tab && PANEL_ROUTE[tab]) panel.show(PANEL_ROUTE[tab]); }, [id, tab]); // eslint-disable-line react-hooks/exhaustive-deps -- on navigation only // the panel follows the run (unless the person picked a tab in the last minute) const prev = useRef<{ id?: string; stage: string | null; status?: string }>({ id, stage: null }); useEffect(() => { if (!r || !stage) return; const p = prev.current; if (p.id === id && p.stage) { if (p.stage !== 'testing' && stage === 'testing' && watching) panel.autoShow('live'); if (p.status !== 'waiting_review' && r.status === 'waiting_review') { setProofFilter('failed'); panel.autoShow('screens'); } if (p.status !== 'completed' && r.status === 'completed') panel.autoShow('report'); } prev.current = { id, stage, status: r.status }; }, [id, stage, r?.status, watching]); // eslint-disable-line react-hooks/exhaustive-deps // Alt+3 focuses the panel's tabs useEffect(() => { const onKey = (e: KeyboardEvent) => { if (e.altKey && !e.ctrlKey && !e.metaKey && e.key === '3') { e.preventDefault(); if (!panel.open) panel.show(panel.tab); window.setTimeout(() => document.querySelector('.fpt-panel [role="tab"][aria-selected="true"], .mantine-Drawer-content [role="tab"][aria-selected="true"]')?.focus(), 50); } }; window.addEventListener('keydown', onKey); return () => window.removeEventListener('keydown', onKey); }, [panel]); const shots = new Set((evidence.data ?? []).filter((e) => e.case_id && e.content_type.startsWith('image/')).map((e) => e.case_id)).size; const badges: Partial> = { live: live.data?.active ? : undefined, screens: browserRun && shots ? {shots} : undefined, }; const none = () => ; const render: Partial ReactNode>> = { live: () => (r ? : none()), screens: () => (r ? : none()), report: () => (r ? : none()), excel: () => (r ? : none()), steps: () => (id ? : none()), }; // ------------------------------------------------------------------ toolbar const panelToggle = ( ); let top: ReactNode; const back = { label: 'Test runs', to: '/runs' }; if (!id) { top = ; } else if (!r) { top = : undefined} actions={panelToggle} />; } else { const menuGo = (v: string) => nav(`/runs/${r.run_id}/${v}`); const detailItems = ( <> {browserRun && menuGo('live')}>Watch the test live} menuGo('proof')}>Screens menuGo('scenarios')}>Scenarios menuGo('failures')}>Failures menuGo('workflow')}>Team board menuGo('report')}>Report and sign-off menuGo('script')}>Excel test script {Object.entries(MORE_ALL).map(([v, label]) => menuGo(v)}>{label})} {can('run.note') && setNote(true)}>Add a note for the team} setGlossary(true)}>What do these words mean? {can('admin') && Engineering views (admin)} {can('admin') && Object.entries(MORE_ADMIN).map(([v, label]) => menuGo(v)}>{label})} ); const caption = [r.patch_id ? `Update ${r.patch_id}` : '', r.pod_name ?? pod?.name ?? '', r.created_at ? `started ${shortWhen(r.created_at)}` : ''].filter(Boolean).join(' · '); top = ( 1 ? `: ${r.modules.map((m) => MODULE_NAMES[m] ?? m).join(', ')}` : ''}`}>{runAreas(r)}} plainTitle honesty={false} back={back} sub={{caption}} middle={Object.keys(r.decisions ?? {}).length ? ( <>{Object.entries(r.decisions ?? {}).map(([m, d]) => ( {r.modules.length > 1 && {MODULE_NAMES[m] ?? m}} ))} ) : undefined} actions={<> {detailItems} {['interrupted', 'failed'].includes(r.status) && } {!TERMINAL.includes(r.status) && } {panelToggle} } /> ); } return (
{top} {action.error && !cancelling ?
: null} {r?.test_data?.left?.length ? : null} {detail && r ? : detail && run.error ?
: id ? : null}
setGlossary(false)} title="Words used in this app" size="lg"> {r && setNote(false)} />} {r && setCancelling(false)} name={`${runAreas(r)}${r.pod_name ? ` on ${r.pod_name}` : ''}${r.created_at ? `, started ${shortWhen(r.created_at)}` : ''}`} pending={action.isPending} error={action.error} onConfirm={(reason) => action.mutate({ id: r.run_id, action: 'cancel', reason: reason || 'cancelled from the run page' }, { onSuccess: () => setCancelling(false) })} />}
); } /** Fusion test data this run created that could not be cancelled automatically (run stopped early, pod unreachable): * listed so someone cancels it by hand in Oracle Fusion. */ function LeftTestData({ left, pod }: { left: { number: string; test?: string | null; why?: string | null }[]; pod: string | null }) { return (
{left.length === 1 ? '1 test document was' : `${left.length} test documents were`} left on {pod ?? 'the Oracle Fusion pod'}.{' '} The run stopped before it could cancel {left.length === 1 ? 'it' : 'them'}. Cancel {left.length === 1 ? 'it' : 'them'} in Oracle Fusion (Payables, Manage Invoices):{' '} {left.map((x) => `${x.number}${x.why ? ` (${x.why})` : ''}`).join(', ')}.
); } /** Confirm before cancelling a test run: names the run and takes an optional reason (saved with the run and in the audit log). */ function CancelRunSheet({ opened, onClose, name, onConfirm, pending, error }: { opened: boolean; onClose: () => void; name: string; onConfirm: (reason: string) => void; pending: boolean; error: unknown; }) { const [reason, setReason] = useState(''); return ( {name} Testing stops and the run cannot be resumed. Results so far are kept, but there is no report or sign-off for a cancelled run.