patchwise-agent-studio / web /src /pages /run /RunGuide.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.6 kB
import { LazyGlobe } from '../../components/three/LazyGlobe';
import { Alert, Button, Group, Progress, Stack, Stepper, Text, TextInput, UnstyledButton } from '@mantine/core';
import { notifications } from '@mantine/notifications';
import { IconArrowLeft, IconEye, IconCircleCheck, IconCircleDashed, IconFileSpreadsheet, IconFileReport, IconListDetails, IconLoader2, IconPhotoOff } from '@/components/icons';
import { useState, type ReactNode } from 'react';
import { Link } from 'react-router-dom';
import type { Schemas } from '../../api/client';
import { useApproveCases, useGate, usePods, useHumanReview, useRunAction, useRunFailures, useRunReadiness } from '../../api/hooks';
import type { ApproveGate, Failure } from '../../api/types';
import { Can, ErrorAlert, Pill } from '../../components/common';
import { decisionWords, failureCause, plainReason, reviewAnswer, type FailureChoice } from '../../domain/glossary';
import { FailedScreen } from './FailedScreen';
import { useSidePanelOptional } from '../../components/shell/SidePanel';
import { LiveView } from './LiveView';
import { Presence } from './RunStage';
import { ScenarioReview } from './ScenarioReview';
import { SignInPanel } from './SignInPanel';
type Run = Schemas['RunDetail'];
export const PREPARE_NODES = ['scout', 'research_module', 'synthesizer', 'test_generator', 'approval_gate'];
const STOPPED = ['failed', 'killed', 'cancelled', 'interrupted'];
/** Which of the four steps the test run is on. Everything the guide shows follows from this. */
export function guideStage(r: Pick<Run, 'status' | 'pending_gate' | 'current_node'>, scenarios: number): 'prepare' | 'approve' | 'testing' | 'judge' | 'result' | 'stopped' {
if (r.status === 'completed') return 'result';
if (STOPPED.includes(r.status)) return 'stopped';
if (r.pending_gate === 'approve_cases') return 'approve';
if (r.pending_gate === 'human_review') return 'judge';
if (!scenarios || (r.current_node && PREPARE_NODES.includes(r.current_node))) return 'prepare';
return 'testing';
}
/** What the coworker at a step is doing, as the end of "{Name} is …". */
const DOING: Record<string, string> = {
scout: 'reading the test environment', research_module: 'reading what this patch changes', synthesizer: 'weighing what the patch changes',
test_generator: 'choosing the scenarios worth testing', script_builder: 'writing the test scripts', data_planner: 'preparing the test data',
data_executor: 'preparing the test data', self_heal: 'repairing a broken step and trying again', triage: 'sorting a failure', reporter: 'writing the report',
};
export const scriptUrl = (id: string) => `/api/runs/${encodeURIComponent(id)}/test-script.xlsx`;
function ExcelButton({ id, label = 'Download as Excel' }: { id: string; label?: string }) {
return (
<Button component="a" href={scriptUrl(id)} download variant="subtle" leftSection={<IconFileSpreadsheet size={15} />} data-testid="excel-script">
{label}
</Button>
);
}
function Tick({ state, children }: { state: 'done' | 'now' | 'todo'; children: React.ReactNode }) {
return (
<Group gap={8} wrap="nowrap">
{state === 'done' ? <IconCircleCheck size={18} color="var(--pill-green-fg)" /> : state === 'now' ? <IconLoader2 size={18} className="fpt-spin" /> : <IconCircleDashed size={18} color="var(--fpt-dim)" />}
<Text size="sm" c={state === 'todo' ? 'dimmed' : undefined} fw={state === 'now' ? 500 : undefined}>{children}</Text>
</Group>
);
}
export function Prepare({ r }: { r: Run }) {
const at = Math.max(0, PREPARE_NODES.indexOf(r.current_node ?? 'scout'));
const st = (from: number, to: number) => (at > to ? 'done' : at >= from ? 'now' : 'todo');
return (
<Stack gap="sm">
<h3 className="trio-card-h">Getting the test ready</h3>
<Presence node={r.current_node ?? 'scout'} doing={DOING[r.current_node ?? 'scout'] ?? 'getting the test ready'} />
<p className="trio-lede">Nothing to do yet. This usually takes about a minute, and you will be asked for your approval next.</p>
<Tick state={st(0, 0)}>Reading the test environment: which business areas are switched on</Tick>
<Tick state={st(1, 2)}>Reading what this patch changes</Tick>
<Tick state={st(3, 3)}>Choosing the scenarios worth testing</Tick>
</Stack>
);
}
export function Approve({ r }: { r: Run }) {
const gate = useGate(r.run_id, true);
const approve = useApproveCases(r.run_id);
const [look, setLook] = useState(false);
const g = gate.data?.gate === 'approve_cases' ? (gate.data as ApproveGate) : null;
const ids = (g?.pending ?? []).map((p) => p.id);
const changed = (g?.pending ?? []).filter((p) => p.changed_by_patch).length;
const byAi = (g?.pending ?? []).filter((p) => p.origin === 'ai').length;
const aiFailed = (g?.ai_not_runnable ?? []).length;
const browser = r.playwright_mode !== 'stub';
const go = () => approve.mutate({ approved: ids, rejected: [], comments: {} }, {
onSuccess: () => notifications.show({ color: 'green', autoClose: 4200, message: (
<span>Approved {ids.length} scenario{ids.length === 1 ? '' : 's'}. Testing has started.{browser && <> <Link to={`/runs/${r.run_id}/live`}>Watch live</Link></>}</span>) }),
});
return (
<Stack gap="sm">
<h3 className="trio-card-h">{ids.length} scenario{ids.length === 1 ? '' : 's'} {ids.length === 1 ? 'is' : 'are'} ready to test</h3>
<Presence node="approval_gate" doing="waiting for your approval" waiting />
<p className="trio-lede">
A scenario is one business check, for example “a requisition below the limit is approved by the first approver”.
{changed > 0 ? ` ${changed} of them cover something this patch changes.` : ''} We recommend testing all of them.
</p>
{(byAi > 0 || aiFailed > 0) && (
<p className="trio-lede" data-testid="guide-ai-count">
{byAi > 0 ? `${byAi} ${byAi === 1 ? 'is a new scenario' : 'are new scenarios'} written by the AI model that passed a dry run; read ${byAi === 1 ? 'it' : 'them'} before approving.` : ''}
{aiFailed > 0 ? ` ${aiFailed} more written by the AI model failed the dry run and ${aiFailed === 1 ? 'is' : 'are'} not offered.` : ''}
</p>
)}
<ErrorAlert error={approve.error || gate.error} />
<Can perm="gate.approve_cases" fallback={<Alert color="gray">Approving scenarios needs the consultant or admin role. You can still read them and download the test script.</Alert>}>
<div className="trio-acts">
<Button size="md" variant="filled" onClick={go} loading={approve.isPending} disabled={!ids.length || approve.isSuccess} data-testid="guide-approve-all">
Approve all {ids.length} and start testing
</Button>
{approve.isSuccess && <Text size="sm" c="teal" role="status">Approved. Testing is starting…</Text>}
<Button variant="default" size="md" onClick={() => setLook((v) => !v)} aria-expanded={look}>{look ? 'Hide the scenarios' : 'Let me look at them first'}</Button>
<ExcelButton id={r.run_id} />
</div>
</Can>
<p className="trio-foot" style={{ margin: 0 }}>Prefer to check on paper? The Excel file lists every step and the result we expect, with columns for your verdict and comments.</p>
{look && <div style={{ marginTop: 8 }}><ScenarioReview id={r.run_id} waiting /></div>}
</Stack>
);
}
export function Testing({ r, watch }: { r: Run; watch: boolean }) {
const rd = useRunReadiness(r.run_id);
// one live stream at a time: when the details panel already shows Live, the step shows a pointer to it instead
const panel = useSidePanelOptional();
const onPanel = !!panel && panel.open && panel.tab === 'live';
const c = (rd.data?.modules ?? []).reduce((a, m) => ({ n: a.n + m.counts.scenarios, done: a.done + m.counts.passed + m.counts.passed_on_retry + m.counts.failing,
fail: a.fail + m.counts.failing }), { n: 0, done: 0, fail: 0 });
if (r.pending_gate === 'sign_in') return <SignInPanel runId={r.run_id} />; // assisted sign-in: a person signs in first
return (
<Stack gap="sm">
<h3 className="trio-card-h">{c.n ? `Running scenario ${Math.min(c.done + 1, c.n)} of ${c.n}` : 'Testing in progress'}</h3>
<Presence node={r.current_node ?? 'executor'} doing={r.current_node && DOING[r.current_node] ? DOING[r.current_node] : c.n ? `testing scenario ${Math.min(c.done + 1, c.n)} of ${c.n}` : 'testing'} />
<p className="trio-lede">You are asked only if one fails. {watch ? (onPanel ? 'Watch it on the right, or keep working.' : 'Watch it below or on the right, or keep working.') : 'Keep working meanwhile.'} We will tell you when something needs you.</p>
<div className="trio-testing-row">
<div className="trio-testing-main">
<div className="trio-progress-top">
<Text size="sm" data-testid="guide-progress">{c.done} of {c.n} scenarios tested</Text>
<span className="trio-dim fpt-num">{c.done - c.fail} passed, {c.fail} failed</span>
</div>
<Progress value={c.n ? (c.done / c.n) * 100 : 0} size="sm" radius="xl" aria-label="scenarios tested" />
</div>
{c.n > 0 && <LazyGlobe counts={{ passed: c.done - c.fail, failed: c.fail, waiting: 0, notRun: c.n - c.done }} live size={112} />}
</div>
{watch && onPanel
? (
<div className="trio-live-elsewhere" data-testid="live-on-panel" role="note">
<IconEye size={16} aria-hidden />
<span>Watching on the right, in the details panel.</span>
<Button size="compact-xs" variant="subtle" onClick={() => panel?.hide()}>Watch here instead</Button>
</div>
)
: watch
? <LiveView id={r.run_id} status={r.status} gate={r.pending_gate} variant="inline" />
: r.playwright_mode === 'stub' && <p className="trio-foot" style={{ margin: 0 }} data-testid="no-live-note">This is a quick simulation, so there is no browser to watch. Choose “Full browser run” next time to see the test live.</p>}
</Stack>
);
}
const CHOICES: { value: FailureChoice; title: string; body: string }[] = [
{ value: 'real_defect', title: 'Yes, this is a real defect', body: 'Something is broken after the patch. A ticket is raised for it.' },
{ value: 'not_defect', title: 'No, not a defect', body: 'The test itself or its test data was wrong. Nothing is raised.' },
{ value: 'expected_change', title: 'The patch changed this on purpose', body: 'The new behaviour is correct. The scenario is marked to be updated.' },
];
/** Failures one at a time: what we expected, what happened, our suggestion, and three plain choices. */
export function Judge({ r, onShowScreen, onShowSteps }: { r: Run; onShowScreen?: (caseId: string) => void; onShowSteps?: (caseId: string) => void }) {
const q = useRunFailures(r.run_id);
const submit = useHumanReview(r.run_id);
const pending = (q.data ?? []).filter((f) => f.pending);
const [i, setI] = useState(0);
const [answers, setAnswers] = useState<Record<string, { choice?: FailureChoice; owner?: string }>>({});
const suggested = (f: Failure): FailureChoice => (f.category === 'real_defect' ? 'real_defect' : 'not_defect');
const f = pending[Math.min(i, Math.max(0, pending.length - 1))];
if (q.isLoading) return <Text size="sm" c="dimmed">Loading the failures…</Text>;
if (!f) return <Text size="sm" c="dimmed">Nothing is waiting for your decision.</Text>;
const a = answers[f.case_id] ?? {};
const choice = a.choice ?? suggested(f);
const set = (patch: { choice?: FailureChoice; owner?: string }) => setAnswers((s) => ({ ...s, [f.case_id]: { ...s[f.case_id], ...patch } }));
const last = i >= pending.length - 1;
const ownersMissing = pending.filter((x) => x.ask === 'owner' && !answers[x.case_id]?.owner?.trim()).length;
const send = () => {
if (ownersMissing) return;
const review = Object.fromEntries(pending.map((x) => {
const d = answers[x.case_id] ?? {};
return [x.case_id, x.ask === 'owner' ? reviewAnswer(undefined, { owner: d.owner?.trim() }) : reviewAnswer(d.choice ?? suggested(x), {})];
}));
submit.mutate({ review });
};
return (
<Stack gap="sm" aria-label="failure decisions">
<Group justify="space-between" wrap="wrap">
<h3 className="trio-card-h">{pending.length === 1 ? 'One scenario needs your decision' : `${pending.length} scenarios need your decision`}</h3>
{pending.length > 1 && <Text size="sm" c="dimmed" className="fpt-num" data-testid="guide-judge-count">{Math.min(i + 1, pending.length)} of {pending.length}</Text>}
</Group>
<Presence node="human_review" doing="waiting for your decision" waiting />
<div className="fpt-judge trio-judge" data-testid={`guide-failure-${f.case_id}`}>
<div className="fpt-judge-text">
<Text fw={600}>{f.title ?? f.case_id}</Text>
{f.ask !== 'owner' && <Pill tone={failureCause(f.category).tone} testId={`guide-cause-${f.case_id}`}>{failureCause(f.category).words}</Pill>}
{f.step && <Text size="xs" c="dimmed" mb="sm">It stopped at: {f.step}</Text>}
{f.ask === 'owner' ? (
<>
<Text size="sm" mb="xs">This scenario failed the first time and passed when it was tried again. That usually means the test is unstable, not that something is broken.</Text>
<TextInput label="Who should look into it?" placeholder="a name or a team" required withAsterisk value={a.owner ?? ''} onChange={(e) => set({ owner: e.currentTarget.value })}
error={a.owner !== undefined && !a.owner.trim() ? 'Enter a name or a team' : undefined} />
</>
) : (
<>
<div className="trio-diff">
<div><small>We expected</small>{f.expected ?? 'the step to complete'}</div>
<div data-bad><small>What happened</small>{f.actual ?? 'it did not complete'}</div>
</div>
{r.playwright_mode === 'stub' && (
<Text size="sm" c="dimmed" mt={6} className="fpt-judge-noscreen"><IconPhotoOff size={14} style={{ verticalAlign: -2 }} aria-hidden /> No screen: quick simulations don&apos;t open a browser.</Text>
)}
{onShowSteps && <Button variant="subtle" size="compact-xs" mt={6} px={0} leftSection={<IconListDetails size={14} />} onClick={() => onShowSteps(f.case_id)}>Show the steps</Button>}
<Text size="sm" mt="sm"><b>Our suggestion:</b> {f.suggestion || 'No suggestion for this failure.'}</Text>
<Text size="sm" fw={600} mt="md" mb={2}>Is this a real problem?</Text>
<div className="trio-radiolist" role="radiogroup" aria-label="Is this a real problem?">
{CHOICES.map((c) => (
<UnstyledButton key={c.value} role="radio" aria-checked={choice === c.value} onClick={() => set({ choice: c.value })} className="trio-radio" data-active={choice === c.value}>
<span className="trio-rd" aria-hidden />
<span className="trio-radio-t"><b>{c.title}{c.value === suggested(f) ? <span className="trio-chip" data-tone="ink">Suggested</span> : null}</b><span>{c.body}</span></span>
</UnstyledButton>
))}
</div>
</>
)}
</div>
{f.ask !== 'owner' && (
<div className="fpt-judge-screen">
<FailedScreen f={f} quick={r.playwright_mode === 'stub'} onSeeAll={onShowScreen ? () => onShowScreen(f.case_id) : undefined} />
</div>
)}
</div>
<ErrorAlert error={submit.error} />
<Can perm="gate.human_review" fallback={<Alert color="gray">Deciding on failures needs the QA approver or admin role.</Alert>}>
<Group justify="space-between">
<Button variant="default" leftSection={<IconArrowLeft size={14} />} disabled={i === 0} onClick={() => setI((n) => n - 1)}>Back</Button>
{last
? <Button variant="filled" size="md" onClick={send} loading={submit.isPending} disabled={submit.isSuccess || ownersMissing > 0} title={ownersMissing ? 'Name who looks into each unstable scenario first' : undefined}
data-testid="guide-submit-decisions">Submit {pending.length === 1 ? 'my decision' : `my ${pending.length} decisions`}</Button>
: <Button variant="filled" onClick={() => setI((n) => n + 1)} data-primary="next">Next</Button>}
</Group>
</Can>
{ownersMissing > 0 && !submit.isSuccess && <Text size="sm" c="dimmed" data-testid="guide-open">{ownersMissing} not decided yet: name who looks into {ownersMissing === 1 ? 'the unstable scenario' : 'each unstable scenario'}.</Text>}
<Text size="xs" c="dimmed">Want the full picture first? <Link to={`/runs/${r.run_id}/failures`}>Open all failure details</Link>.</Text>
</Stack>
);
}
export function Result({ r, after }: { r: Run; after?: ReactNode }) {
const rd = useRunReadiness(r.run_id);
const fusion = (usePods().data ?? []).find((p) => p.id === r.pod_id)?.kind === 'fusion';
const d = r.decision ?? Object.values(r.decisions ?? {})[0] ?? null;
const mods = rd.data?.modules ?? [];
const failing = mods.reduce((n, m) => n + m.counts.failing, 0);
const tested = mods.reduce((n, m) => n + m.counts.passed + m.counts.passed_on_retry + m.counts.failing, 0);
const notRun = mods.reduce((n, m) => n + m.counts.not_run, 0);
const defects = mods.reduce((n, m) => n + m.confirmed_defects.length, 0);
const gaps = mods.reduce((n, m) => n + m.steps.filter((s) => s.state === 'gap').length, 0);
const tone = d === 'GO' ? 'green' : d === 'HELD' ? 'amber' : 'red';
return (
<Stack gap="sm">
<div className="fpt-result" data-tone={tone} data-testid="guide-result">
<div className="fpt-verdict">{decisionWords(d)}</div>
<p className="trio-lede" style={{ marginTop: 4 }}>
{d === 'GO' ? 'Every required check passed. This business area is ready for the patch.'
: d === 'HELD' ? 'These tests are on hold, so no decision was made.'
: 'At least one required check failed or is not covered yet, so this is not ready for the patch.'}
</p>
</div>
<Text size="sm" className="fpt-num fpt-result-facts" title={gaps > 0 ? `${gaps} part${gaps === 1 ? '' : 's'} of the process have no test yet` : undefined}>
{tested} tested · <span data-fail={failing > 0 || undefined}>{failing} failing</span> · {notRun} not run · {defects ? <Link to="/tickets">{defects} defect{defects === 1 ? '' : 's'}</Link> : '0 defects'}
</Text>
{rd.data?.signoff && <Text size="sm" c="dimmed">Signed off by {rd.data.signoff.by}.</Text>}
<div className="trio-acts">
<Button variant="filled" size="md" component={Link} to={`/runs/${r.run_id}/report`} leftSection={<IconFileReport size={16} />}>{rd.data?.signoff ? 'Open the report' : 'Open the report and sign off'}</Button>
<ExcelButton id={r.run_id} label="Download the results (Excel)" />
{r.playwright_mode !== 'stub' && <Button component={Link} to={`/runs/${r.run_id}/proof`} variant="default" size="md">See the screens</Button>}
</div>
<Text size="xs" c="dimmed">{fusion ? `Results come from the Oracle Fusion pod ${r.pod_name ?? ''}.` : 'Results come from the practice environment (the mock app), not Oracle Fusion.'}</Text>
{after}
</Stack>
);
}
export function Stopped({ r }: { r: Run }) {
const action = useRunAction();
return (
<Stack gap="sm">
<h3 className="trio-card-h">{r.status === 'cancelled' ? 'This test run was cancelled' : r.status === 'killed' ? 'This test run was stopped by the emergency stop' : 'This test run stopped before it finished'}</h3>
{plainReason(r.error) && <p className="trio-lede">Reason: {plainReason(r.error)}</p>}
<ErrorAlert error={action.error} />
<Can perm="run.control">
{['interrupted', 'failed'].includes(r.status) && <Button w="fit-content" variant="filled" onClick={() => action.mutate({ id: r.run_id, action: 'resume' })} loading={action.isPending}>Carry on from where it stopped</Button>}
</Can>
</Stack>
);
}
/** The test run as a four-step journey: one screen, one main action, a recommended choice already made. */
export function RunGuide({ r, watch }: { r: Run; watch: boolean }) {
const rd = useRunReadiness(r.run_id);
const scenarios = (rd.data?.modules ?? []).reduce((n, m) => n + m.counts.scenarios, 0);
const stage = guideStage(r, scenarios);
const active = { prepare: 0, approve: 1, testing: 2, judge: 2, result: 4, stopped: -1 }[stage];
return (
<div className="fpt-card" style={{ padding: 20 }} data-testid="run-guide" data-stage={stage}>
{stage !== 'stopped' && (
<Stepper active={active} size="sm" mb="lg" allowNextStepsSelect={false} aria-label="Progress of this test run">
<Stepper.Step label="Prepare" description="We get the test ready" />
<Stepper.Step label="Approve" description="You approve the scenarios" />
<Stepper.Step label="Testing" description={stage === 'judge' ? 'Needs your decision' : 'We run the scenarios'} color={stage === 'judge' ? 'orange' : undefined} />
<Stepper.Step label="Result" description="Ready or not ready" />
</Stepper>
)}
{stage === 'prepare' && <Prepare r={r} />}
{stage === 'approve' && <Approve r={r} />}
{stage === 'testing' && <Testing r={r} watch={watch} />}
{stage === 'judge' && <Judge r={r} />}
{stage === 'result' && <Result r={r} />}
{stage === 'stopped' && <Stopped r={r} />}
</div>
);
}