import { fireEvent, screen, waitFor, within } from '@testing-library/react'; import { afterEach, describe, expect, it, vi } from 'vitest'; import { jsonResponse, renderUi } from '../../test/utils'; import { FailedScreen } from '../run/FailedScreen'; import { ScenarioReview } from '../run/ScenarioReview'; const urlOf = (input: RequestInfo | URL) => (typeof input === 'string' ? input : input instanceof URL ? input.href : input.url); const scen = (id: string, title: string, step: string, priority = 'P1', origin = 'library') => ({ id, title, module: 'P2P', process: step, step, priority, priority_words: priority === 'P1' ? 'Critical' : 'High', roles: [], preconditions: [], steps: [{ n: 1, text: 'Sign in', expected: '' }], expected_result: 'Done', test_data: [], why: [], verification: 'UNVERIFIED', map_ids: [], approval_status: 'draft', origin, pending: true, outcome: null }); const pend = (id: string, changed: boolean, priority = 'P1', origin = 'library', ai?: Record) => ({ id, title: id, module: 'P2P', priority, origin, changed_by_patch: changed, new_or_changed: changed, yaml_path: 'x', diff: null, ai }); const dry = { status: 'passed', failed_step: null, message: null, pod: 'Local mock pod', at: '2026-10-17T11:23:00', simulated: false }; const aiDraft = { id: 'P2P-AI-001', title: 'AI requisition', module: 'P2P', priority: 'P1', written_by: 'ai', model: 'mistral-large', why: null, status: 'staged', runnable: true, dry_run: dry, problems: [], steps: [{ n: 1, action: 'open', field: null, value: null, expected: null, text: 'Open' }, { n: 2, action: 'fill', field: 'Amount', value: '900', expected: null, text: 'Fill' }], expected_result: 'Approved' }; function mockGate(posts: unknown[]) { vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => { const req = input instanceof Request ? input : new Request(new URL(urlOf(input), 'http://localhost'), init); if (req.method === 'POST') { posts.push(await req.json()); return jsonResponse({ status: 'queued' }); } if (req.url.includes('/gate')) return jsonResponse({ gate: 'approve_cases', policy: 'L0', auto_approved: [], pending: [pend('P2P-APR-001', true), pend('P2P-APR-002', true, 'P2'), pend('P2P-AI-001', true, 'P1', 'ai', aiDraft), pend('P2P-PAY-001', false, 'P2')], ai_not_runnable: [{ ...aiDraft, id: 'P2P-AI-009', title: 'AI draft that failed', runnable: false, dry_run: { ...dry, status: 'failed', failed_step: '2', message: 'field not found' } }] }); if (req.url.includes('/scenarios')) return jsonResponse({ scenarios: [scen('P2P-APR-001', 'Below threshold', 'Requisition'), scen('P2P-APR-002', 'Rejected requisition', 'Requisition', 'P2'), scen('P2P-AI-001', 'AI requisition', 'Requisition', 'P1', 'ai'), scen('P2P-PAY-001', 'Payment run', 'Payment', 'P2')], deferred: [] }); if (req.url.endsWith('/api/auth/me')) return jsonResponse({ id: 1, username: 'c', role: 'consultant', permissions: ['read', 'gate.approve_cases'] }); return jsonResponse({}); }); } describe('step 4: approvals and failure decision', () => { afterEach(() => vi.restoreAllMocks()); it('filter chips only hide rows: decisions, the review bar and the approve payload are unchanged', async () => { const posts: unknown[] = []; mockGate(posts); renderUi(, { auth: true }); const chips = await screen.findByRole('group', { name: 'Show scenarios' }); expect(within(chips).getByRole('button', { name: /^All/ })).toHaveAttribute('aria-pressed', 'true'); expect(within(chips).getByRole('button', { name: /Written by the AI model/ })).toHaveTextContent('1'); expect(within(chips).getByRole('button', { name: /Critical/ })).toHaveTextContent('2'); fireEvent.click(within(chips).getByRole('button', { name: /Critical/ })); expect(screen.getByTestId('review-count')).toHaveTextContent('0 of 4 approved'); // still counts every pending scenario expect(screen.queryByRole('button', { name: /Approve all \d+ unchanged/ })).not.toBeInTheDocument(); // Payment run is High, hidden fireEvent.click(within(chips).getByRole('button', { name: /^All/ })); fireEvent.click(screen.getByRole('button', { name: 'Approve all 2 Requisition scenarios' })); // the AI scenario is its card, listed once fireEvent.click(screen.getByRole('button', { name: 'Approve AI requisition' })); fireEvent.click(screen.getByRole('button', { name: 'Approve all 1 unchanged' })); expect(screen.getByTestId('review-count')).toHaveTextContent('4 of 4 approved'); fireEvent.click(screen.getByRole('button', { name: 'Submit review' })); await waitFor(() => expect(posts).toHaveLength(1)); expect(posts[0]).toEqual({ approved: ['P2P-APR-001', 'P2P-APR-002', 'P2P-AI-001', 'P2P-PAY-001'], rejected: [], comments: {} }); }); it('AI-written scenarios get a card with the dry run, listed once', async () => { mockGate([]); renderUi(, { auth: true }); const card = await screen.findByTestId('approval-card-P2P-AI-001'); expect(card).toHaveTextContent('Dry run passed on Local mock pod'); expect(card).toHaveTextContent('2 steps'); expect(card).toHaveTextContent(/model mistral-large/i); fireEvent.click(within(card).getByRole('button', { name: 'Skip AI requisition for this patch' })); expect(card).toHaveAttribute('data-decision', 'skip'); expect(screen.queryByTestId('scenario-P2P-AI-001')).not.toBeInTheDocument(); // each scenario is listed once: the AI one as its card expect(screen.getByTestId('review-count')).toHaveTextContent('1 skipped'); // drafts that failed their dry run are folded away, but stay in the page expect(screen.getByTestId('ai-not-runnable')).toHaveTextContent('Written by the AI model, not offered'); expect(screen.getByTestId('ai-failed-P2P-AI-009')).toBeInTheDocument(); expect(screen.getByRole('button', { name: /Written by the AI model, not offered/ })).toHaveAttribute('aria-expanded', 'false'); }); it('keyboard: Down moves between rows, A approves and S skips the focused row', async () => { mockGate([]); renderUi(, { auth: true }); await screen.findByTestId('step-group-changed-Requisition'); const first = screen.getByTestId('scenario-P2P-APR-001').querySelector('[data-row-title]')!; expect(first).toHaveAttribute('tabindex', '0'); expect(screen.getByTestId('scenario-P2P-APR-002').querySelector('[data-row-title]')).toHaveAttribute('tabindex', '-1'); first.focus(); fireEvent.keyDown(first, { key: 'a' }); expect(screen.getByTestId('scenario-P2P-APR-001')).toHaveAttribute('data-decision', 'approve'); fireEvent.keyDown(first, { key: 'ArrowDown' }); const second = screen.getByTestId('scenario-P2P-APR-002').querySelector('[data-row-title]')!; expect(second).toHaveFocus(); fireEvent.keyDown(second, { key: 's' }); expect(screen.getByTestId('scenario-P2P-APR-002')).toHaveAttribute('data-decision', 'skip'); }); it('the failed-screen column: quick simulations say there is no screen; browser runs show the latest attempt', () => { vi.spyOn(globalThis, 'fetch').mockImplementation(async (input) => (urlOf(input).endsWith('/api/auth/me') ? jsonResponse({ id: 1, username: 'q', role: 'qa_approver', permissions: ['read', 'evidence.read'] }) : jsonResponse({}))); const f = { case_id: 'P2P-APR-001', title: 'Three-way match', screenshots: [ { evidence_id: 7, case_id: 'P2P-APR-001', attempt: 0, name: 'a.png', content_type: 'image/png', size: 1, expires_at: '' }, { evidence_id: 9, case_id: 'P2P-APR-001', attempt: 1, name: 'b.png', content_type: 'image/png', size: 1, expires_at: '' }] }; const { unmount } = renderUi(, { auth: true }); expect(screen.getByText("Quick simulations don't open a browser, so there is no screen.")).toBeInTheDocument(); unmount(); renderUi( undefined} />, { auth: true }); return waitFor(() => { expect(screen.getByRole('img', { name: 'Screen of Three-way match at the moment it failed' })).toHaveAttribute('src', '/api/evidence/9'); expect(screen.getByRole('button', { name: 'See all screens' })).toBeInTheDocument(); }); }); });