File size: 26,325 Bytes
fb62a97
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
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<string, PanelTab> = { live: 'live', proof: 'screens', script: 'excel' };
const MORE_ALL: Record<string, string> = { process: 'By business process', changes: 'What the patch changes', activity: 'Activity log' };
const MORE_ADMIN: Record<string, string> = { research: 'Coverage map', data: 'Data plan', scripts: 'Scripts', technical: 'Technical report' };
const VIEW_TITLE: Record<string, string> = { 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 (
    <SidePanelProvider tabs={PANEL_TABS} runId={useParams().id}>
      <Workspace />
    </SidePanelProvider>
  );
}

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<ProofFilter>('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<string | null>(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<HTMLElement>('.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<Record<PanelTab, ReactNode>> = {
    live: live.data?.active ? <span className="fpt-sdot fpt-panel-livedot" data-state="done" data-pulse="true" aria-hidden /> : undefined,
    screens: browserRun && shots ? <span className="fpt-panel-count fpt-num">{shots}</span> : undefined,

  };
  const none = () => <EmptyState title="Nothing here yet" body="Your test run's evidence appears here: the live browser, each scenario's screens, the report and the Excel files." />;
  const render: Partial<Record<PanelTab, () => ReactNode>> = {
    live: () => (r ? <LiveView id={r.run_id} status={r.status} gate={r.pending_gate} reasonQuick={!browserRun} compact /> : none()),
    screens: () => (r ? <RunProof key={proofFilter} id={r.run_id} quick={!browserRun} oneColumn fusionPod={fusion ? r.pod_name ?? pod?.name ?? '' : null} filter={proofFilter} /> : none()),
    report: () => (r ? <ReportSummary runId={r.run_id} hideVerdict={tab === 'report'} /> : none()),
    excel: () => (r ? <ExcelPanel runId={r.run_id} finished={r.status === 'completed'} /> : none()),
    steps: () => (id ? <ScenarioSteps runId={r?.run_id} scenarioId={panel.scenario} /> : none()),
  };

  // ------------------------------------------------------------------ toolbar
  const panelToggle = (
    <Tooltip label={`${panel.open ? 'Hide' : 'Show'} the run details panel (Ctrl+\\)`}>
      <button type="button" className="fpt-iconbtn fpt-iconbtn-md" aria-label={panel.open ? 'Hide the run details panel' : 'Show the run details panel'} aria-expanded={panel.open} onClick={panel.toggle}>
        {panel.open ? <IconLayoutSidebarRightCollapse size={16} /> : <IconLayoutSidebarRight size={16} />}
      </button>
    </Tooltip>
  );
  let top: ReactNode;
  const back = { label: 'Test runs', to: '/runs' };
  if (!id) {
    top = <TopBar title="New test run" plainTitle honesty={false} back={back} actions={panelToggle} />;
  } else if (!r) {
    top = <TopBar title="Test run" plainTitle honesty={false} back={back} middle={run.isLoading ? <Skeleton height={22} width={150} radius="xl" /> : undefined} actions={panelToggle} />;
  } else {
    const menuGo = (v: string) => nav(`/runs/${r.run_id}/${v}`);
    const detailItems = (
      <>
        {browserRun && <Menu.Item onClick={() => menuGo('live')}>Watch the test live</Menu.Item>}
        <Menu.Item onClick={() => menuGo('proof')}>Screens</Menu.Item>
        <Menu.Item onClick={() => menuGo('scenarios')}>Scenarios</Menu.Item>
        <Menu.Item onClick={() => menuGo('failures')}>Failures</Menu.Item>
        <Menu.Item onClick={() => menuGo('workflow')}>Team board</Menu.Item>
        <Menu.Item onClick={() => menuGo('report')}>Report and sign-off</Menu.Item>
        <Menu.Item onClick={() => menuGo('script')}>Excel test script</Menu.Item>
        {Object.entries(MORE_ALL).map(([v, label]) => <Menu.Item key={v} onClick={() => menuGo(v)}>{label}</Menu.Item>)}
        {can('run.note') && <Menu.Item onClick={() => setNote(true)}>Add a note for the team</Menu.Item>}
        <Menu.Item onClick={() => setGlossary(true)}>What do these words mean?</Menu.Item>
        {can('admin') && <Menu.Label>Engineering views (admin)</Menu.Label>}
        {can('admin') && Object.entries(MORE_ADMIN).map(([v, label]) => <Menu.Item key={v} onClick={() => menuGo(v)}>{label}</Menu.Item>)}
      </>
    );
    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 = (
      <TopBar
        title={<span title={`${browserRun ? 'Full browser run' : 'Quick simulation (no browser)'}${r.modules.length > 1 ? `: ${r.modules.map((m) => MODULE_NAMES[m] ?? m).join(', ')}` : ''}`}>{runAreas(r)}</span>}
        plainTitle honesty={false} back={back}
        sub={<span className="fpt-topbar-caption" title={caption}>{caption}</span>}
        middle={Object.keys(r.decisions ?? {}).length ? (
          <>{Object.entries(r.decisions ?? {}).map(([m, d]) => (
            <Group key={m} gap={4} wrap="nowrap">{r.modules.length > 1 && <Text size="xs" fw={600}>{MODULE_NAMES[m] ?? m}</Text>}<DecisionBadge decision={d} size="sm" /></Group>
          ))}</>
        ) : undefined}
        actions={<>
          <Menu position="bottom-end" withArrow={false}>
            <Menu.Target><Button variant="default" rightSection={<IconChevronDown size={13} />} data-testid="all-details">All details</Button></Menu.Target>
            <Menu.Dropdown>{detailItems}</Menu.Dropdown>
          </Menu>
          <Can perm="run.control">
            {['interrupted', 'failed'].includes(r.status) && <Button variant="filled" onClick={() => action.mutate({ id: r.run_id, action: 'resume' })} leftSection={<IconPlayerPlay size={13} />}>Resume</Button>}
            {!TERMINAL.includes(r.status) && <Button color="red" variant="subtle" className="ws-cancel" title="Cancel this test run" onClick={() => setCancelling(true)}>Cancel run</Button>}
          </Can>
          {panelToggle}
        </>}
      />
    );
  }

  return (
    <div className="fpt-ws" data-testid="assistant-page" data-size={size}>
      <div className="fpt-ws-center">
        {top}
        {action.error && !cancelling ? <div style={{ padding: '8px 16px 0' }}><ErrorAlert error={action.error} /></div> : null}
        {r?.test_data?.left?.length ? <LeftTestData left={r.test_data.left} pod={r.pod_name ?? null} /> : null}
        {detail && r ? <DetailView id={r.run_id} tab={detail} r={r} watching={watching} browserRun={browserRun} fusionPod={fusion ? r.pod_name ?? null : null} />
          : detail && run.error ? <div className="fpt-ws-detail"><ErrorAlert error={run.error} /><Button component={Link} to="/runs" variant="default" mt="sm">Back to test runs</Button></div>
            : id ? <RunStages id={id} /> : null}
      </div>
      <SidePanel tabs={PANEL_TABS} runId={id} scenarioId={panel.scenario} render={render} badges={badges} />
      <Modal opened={glossary} onClose={() => setGlossary(false)} title="Words used in this app" size="lg"><GlossaryList /></Modal>
      {r && <TeamNoteSheet id={r.run_id} opened={note} onClose={() => setNote(false)} />}
      {r && <CancelRunSheet key={cancelling ? 'open' : 'closed'} opened={cancelling} onClose={() => 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) })} />}
    </div>
  );
}

/** 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 (
    <div style={{ padding: '8px 16px 0' }}>
      <div className="trio-banner" data-tone="orange" role="alert" data-testid="left-test-data">
        <span>
          <b>{left.length === 1 ? '1 test document was' : `${left.length} test documents were`} left on {pod ?? 'the Oracle Fusion pod'}.</b>{' '}
          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(', ')}.
        </span>
      </div>
    </div>
  );
}

/** 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 (
    <Modal opened={opened} onClose={onClose} title="Cancel this test run?" size={480} centered>
      <Stack gap="sm">
        <Text size="sm" data-testid="cancel-run-name"><b>{name}</b></Text>
        <Text size="sm" c="dimmed">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.</Text>
        <Textarea label="Reason (optional)" description="Saved with the test run and in the audit log." autosize minRows={2} maxRows={5} maxLength={500}
          value={reason} onChange={(e) => setReason(e.currentTarget.value)} data-autofocus />
        {opened && <ErrorAlert error={error} title="Could not cancel the test run" />}
        <div className="trio-sheet-foot">
          <Button variant="default" onClick={onClose}>Keep it running</Button><span className="trio-sheet-sp" />
          <Button color="red" variant="filled" loading={pending} onClick={() => onConfirm(reason.trim())}>Cancel test run</Button>
        </div>
      </Stack>
    </Modal>
  );
}

/** "Add a note for the team": saved to the activity log and the audit log. */
function TeamNoteSheet({ id, opened, onClose }: { id: string; opened: boolean; onClose: () => void }) {
  const qc = useQueryClient();
  const [text, setText] = useState('');
  const save = useMutation({
    mutationFn: (t: string) => unwrap(api.POST('/api/runs/{run_id}/notes', { params: { path: { run_id: id } }, body: { text: t } })),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ['run', id] }); notifications.show({ message: 'Saved your note for the team. It is in the Activity log and the audit log.', color: 'green' }); setText(''); onClose(); },
  });
  return (
    <Modal opened={opened} onClose={onClose} title="Add a note for the team" size={520}>
      <Stack gap="sm">
        <Text className="trio-lede" style={{ marginTop: 0 }}>The note is saved with this test run in the Activity log and the audit log. It never changes a result.</Text>
        <Textarea aria-label="Note for the team" autosize minRows={3} maxRows={8} maxLength={2000} value={text} onChange={(e) => setText(e.currentTarget.value)} data-autofocus />
        <ErrorAlert error={save.error} />
        <div className="trio-sheet-foot">
          <Button variant="default" onClick={onClose}>Cancel</Button><span className="trio-sheet-sp" />
          <Button variant="filled" onClick={() => save.mutate(text.trim())} loading={save.isPending} disabled={!text.trim()}>Save the note</Button>
        </div>
      </Stack>
    </Modal>
  );
}

type RunDetail = NonNullable<ReturnType<typeof useRun>['data']>;

/** A former tab of the run page, in the center with "← Conversation" and the view switcher. */

type RunLike = NonNullable<ReturnType<typeof useRun>['data']>;

/** The run's header on every view (after Testomat.io's run report header): where it sits (Runs / patch), its name, its
 * state, its short id, its results as one bar when it has them, and who started it where. */
function RunHead({ r }: { r: RunLike }) {
  const mine = useWaitsOnMe();
  const st = runState(r);
  const tone = st === 'waiting' || st === 'done-held' || st === 'paused' ? 'orange' : st === 'running' || st === 'queued' ? 'blue'
    : st === 'done-ready' || st === 'done' ? 'green' : st === 'done-notready' || st === 'failed' || r.status === 'killed' ? 'red' : 'neutral';
  const c = (r.counts ?? {}) as Record<string, number>;
  const total = (c.passed ?? 0) + (c.failed ?? 0) + (c.skipped ?? 0);
  const pct = (n?: number) => `${((n ?? 0) / (total || 1)) * 100}%`;
  const by = r.trigger === 'agent_studio' ? 'Oracle AI Agent Studio' : r.created_by ?? r.trigger;
  return (
    <header className="rw-head">
      <nav className="rw-crumb" aria-label="Where this test run is"><Link to="/runs">Test runs</Link>{r.patch_id ? <><span aria-hidden>/</span><span>Patch {r.patch_id}</span></> : null}</nav>
      <div className="rw-title">
        <b>{runTitle(r)}</b>
        <span className="pw-status" data-tone={tone} title={runStatusWords(r, mine(r))}>
          {/* a live run's words shimmer (Wensity UI) */}
          {st === 'running'
            ? <TextShimmer text={rowWords(r, null, mine(r))} as="span" baseColor="var(--blue)" shimmerColor="#ffffff" duration={1.8} />
            : rowWords(r, r.decision ?? Object.values(r.decisions ?? {})[0] ?? null, mine(r))}
        </span>
        <span className="fpt-idpill" title={r.run_id}>{r.run_id.slice(-6)}</span>
      </div>
      <div className="rw-meta">
        {total > 0 && (
          <span className="rw-res">
            <span className="rg-bar rw-bar" role="img" aria-label={`${c.passed ?? 0} passed, ${c.failed ?? 0} failed, ${c.skipped ?? 0} skipped`}>
              <i data-k="pass" style={{ width: pct(c.passed) }} /><i data-k="fail" style={{ width: pct(c.failed) }} /><i data-k="skip" style={{ width: pct(c.skipped) }} />
            </span>
            <span><b data-k="pass">{c.passed ?? 0}</b> passed · <b data-k="fail">{c.failed ?? 0}</b> failed · {c.skipped ?? 0} skipped</span>
          </span>
        )}
        <span>{r.pod_name ?? 'Test environment'}</span><span>Started by {by}</span><span>{shortWhen(r.created_at)}</span>
        <span>{r.playwright_mode === 'stub' ? 'Quick simulation' : 'Full browser run'}</span>
      </div>
    </header>
  );
}

function DetailView({ id, tab, r, watching, browserRun, fusionPod }: { id: string; tab: string; r: RunDetail; watching: boolean; browserRun: boolean; fusionPod: string | null }) {
  const nav = useNavigate();
  const { can } = useAuth();
  const MORE: Record<string, string> = { ...MORE_ALL, ...MORE_ADMIN };
  const your = (v: string) => (v === 'scenarios' && r.pending_gate === 'approve_cases') || (v === 'failures' && r.pending_gate === 'human_review') ? ' • your review' : '';
  const body: Record<string, () => ReactNode> = {
    scenarios: () => <ScenarioReview id={id} waiting={r.pending_gate === 'approve_cases'} />,
    failures: () => <FailureReview id={id} waiting={r.pending_gate === 'human_review'} />,
    workflow: () => <RunWorkflow id={id} status={r.status} gate={r.pending_gate} error={r.error} quick={!browserRun} llmCalls={r.llm_calls}
      decision={r.decision ?? Object.values(r.decisions ?? {})[0] ?? null} />,
    report: () => <SignOffReport id={id} />,
    process: () => <Overview id={id} quick={!browserRun} status={r.status} gate={r.pending_gate} />,
    changes: () => <RunChanges id={id} />,
    activity: () => <Activity id={id} />,
    research: () => <RunResearch id={id} />,
    data: () => <RunData id={id} />,
    scripts: () => <RunScripts id={id} />,
    technical: () => <RunReport id={id} done={r.status === 'completed'} />,
  };
  void fusionPod;
  // keep the active view visible in the switcher row when it scrolls (phones)
  const switcher = useRef<HTMLElement>(null);
  useEffect(() => {
    const el = switcher.current?.querySelector<HTMLElement>('[aria-current="page"]') ?? switcher.current?.querySelector<HTMLElement>('[aria-label="More views of this test run"]');
    el?.scrollIntoView?.({ inline: 'nearest', block: 'nearest' });   // nearest: the first view stays in sight when it fits
  }, [tab]);
  const VIEW: Record<string, string> = { scenarios: 'Scenarios', failures: 'Failures', workflow: 'Team board', activity: 'Activity', report: 'Report and sign-off' };
  return (
    <div className="fpt-ws-scroll" tabIndex={-1}>
      {/* one h1 per view: the run, then the view (the toolbar shows the run's name as plain text) */}
      <h1 className="fpt-sr-only">{runAreas(r)} test run: {VIEW[tab] ?? MORE[tab] ?? tab}</h1>
      <RunHead r={r} />
      <div className="fpt-detail-head">
        <Button component={Link} to={`/runs/${id}`} variant="subtle" color="gray" size="compact-sm" leftSection={<IconArrowLeft size={14} />} style={{ flex: '0 0 auto' }}>Test run</Button>
        <NavTabs ref={switcher} label="Views of this test run" className="fpt-detail-switch"
          items={[['scenarios', `Scenarios${your('scenarios')}`], ['failures', `Failures${your('failures')}`], ['workflow', 'Team'], ['activity', 'Activity'], ['report', 'Report & sign-off']]
            .map(([v, label]) => ({ to: `/runs/${id}/${v}`, label, active: tab === v }))}
          extra={(
            <Menu position="bottom-end" withArrow>
              <Menu.Target>
                <Button variant={MORE[tab] && tab !== 'activity' ? 'filled' : 'subtle'} color={MORE[tab] && tab !== 'activity' ? undefined : 'gray'} size="compact-sm" radius="xl" ml={4} style={{ alignSelf: 'center' }}
                  rightSection={<IconChevronDown size={12} />} aria-label="More views of this test run">{MORE[tab] && tab !== 'activity' ? `More: ${MORE[tab]}` : 'More'}</Button>
              </Menu.Target>
              <Menu.Dropdown>
                {Object.entries(MORE_ALL).filter(([v]) => v !== 'activity').map(([v, label]) => <Menu.Item key={v} onClick={() => nav(`/runs/${id}/${v}`)}>{label}</Menu.Item>)}
                {can('admin') && <Menu.Label>Engineering views (admin)</Menu.Label>}
                {can('admin') && Object.entries(MORE_ADMIN).map(([v, label]) => <Menu.Item key={v} onClick={() => nav(`/runs/${id}/${v}`)}>{label}</Menu.Item>)}
              </Menu.Dropdown>
            </Menu>
          )} />
      </div>
      <div className="fpt-ws-detail">
        {tab !== 'workflow' && tab !== 'report' && <NextStep r={r} here={tab} compact={tab === 'scenarios' || tab === 'failures'} />}   {/* on the Team view the Coordinator card is the action (R2-S3) */}
        <NowTesting id={id} enabled={watching} />
        {body[tab]?.()}
      </div>
    </div>
  );
}