import { Button, Group, Stack, Text } from '@mantine/core';
import { IconCheck, IconExternalLink } from '@/components/icons';
import { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import { errorMessage } from '../api/client';
import { useRun, useRunReadiness } from '../api/hooks';
import { Pill } from '../components/common';
import { ProcessFlow } from '../components/ProcessFlow';
import { RUN_STATUS_WORDS, VERDICT_TONE } from '../domain/glossary';
import { ScenarioCard } from '../pages/run/ScenarioReview';
import { runTitle } from '../domain/runName';
import { cancelAction, confirmAction, type ChatAction, type ChatCard, type ChatLink, type ChatSource } from './api';
const hhmm = (iso?: string | null) => {
if (!iso) return '';
const d = new Date(iso);
return Number.isNaN(d.getTime()) ? '' : `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;
};
/** Answer cards: the existing components at compact size. Built only from structured tool results, never from text. */
export function AnswerCard({ card }: { card: ChatCard }) {
if (card.type === 'readiness') {
return (
{card.name}
{card.verdict}
);
}
if (card.type === 'run') {
return (
{card.title}
{card.status_words}
{card.counts.tested}/{card.counts.scenarios} tested
{card.counts.failing > 0 && {card.counts.failing} failing }
);
}
if (card.type === 'failures') {
return (
{card.items.map((f) => (
{f.title ?? f.case_id}
{f.step &&
failed at: {f.step} }
Expected
{f.expected ?? 'not stated in the test output'}
Actual
{f.actual ?? 'not stated in the test output'}
Suggested cause: {f.suggestion}
))}
);
}
if (card.type === 'scenario') return
;
if (card.type === 'changes') {
return (
{card.items.map((c) => (
{c.area}
{c.summary}
{c.affected_steps.slice(0, 3).map((s) => {s} )}
{c.gap ? No test covers this yet : {c.covering} scenario(s) cover it }
))}
);
}
if (card.type === 'runs') {
return (
{card.items.map((r) => (
{r.title}
{r.pending_gate ? 'your review' : r.status_words}
))}
);
}
return (
{card.items.map((p) => {p.name} {p.runnable ? 'can run tests' : 'not set up yet'} )}
);
}
export function ScreenLinks({ links }: { links: ChatLink[] }) {
if (!links.length) return null;
return {links.map((l) => }>{l.label})} ;
}
/** Where the answer comes from. No source = say so. */
export function Sources({ sources, noSource }: { sources: ChatSource[]; noSource?: boolean }) {
if (!sources.length) return noSource ? No source for this answer. : null;
return (
Source: {sources.map((s, i) => {i > 0 ? '; ' : ''}{s.to ? {s.label} : s.label} )}
);
}
/** One live line for a test run started from chat; it updates in place, never one message per step. */
export function RunProgress({ runId }: { runId: string }) {
const run = useRun(runId);
const rd = useRunReadiness(runId);
const r = run.data;
if (!r) return null;
const c = (rd.data?.modules ?? []).reduce((a, m) => ({ scen: a.scen + m.counts.scenarios, done: a.done + m.counts.passed + m.counts.passed_on_retry + m.counts.failing, fail: a.fail + m.counts.failing }), { scen: 0, done: 0, fail: 0 });
const waiting = r.pending_gate === 'approve_cases' ? 'scenarios' : r.pending_gate === 'human_review' ? 'failures' : null;
return (
{runTitle(r)}
{RUN_STATUS_WORDS[r.status] ?? r.status} · {c.done}/{c.scen} tested{c.fail ? ` · ${c.fail} failing` : ''}
Open the test run
{waiting && {waiting === 'scenarios' ? 'Open scenario review' : 'Open failure review'} }
{r.status === 'running' && r.playwright_mode !== 'stub' && r.live_view && Watch live }
);
}
const DONE_WORDS: Record string> = {
start_run: () => 'test run started',
approve_scenarios: (a) => `approved ${a.result?.approved ?? a.counts?.approve ?? ''}${a.result?.skipped ? `, skipped ${a.result.skipped}` : ''}`,
cancel_run: () => 'test run cancelled',
add_note: () => 'note saved',
};
/** A proposed action: nothing changes until the user confirms. Cancel has the default focus; the primary button names
* the verb and the number. After execution the card collapses to one "Done" line. */
export function ConfirmCard({ action, onChange }: { action: ChatAction; onChange: (a: ChatAction) => void }) {
const [busy, setBusy] = useState(false);
const [error, setError] = useState(null);
const [open, setOpen] = useState(false);
const boxRef = useRef(null);
useEffect(() => { if (open) boxRef.current?.scrollIntoView?.({ block: 'nearest' }); }, [open]);
const cancelRef = useRef(null);
useEffect(() => { if (action.status === 'proposed') cancelRef.current?.focus({ preventScroll: true }); }, [action.action_id, action.status]);
if (action.status === 'confirmed') {
return (
Done · {DONE_WORDS[action.tool](action)} · by {action.result?.by ?? 'you'} · {hhmm(action.result?.at ?? action.executed_at)}
{action.tool === 'start_run' && action.result?.run_id && }
{action.tool !== 'start_run' && action.result?.to && }
);
}
if (action.status !== 'proposed') {
const why = action.status === 'cancelled' ? 'Cancelled. Nothing was changed.' : action.status === 'expired' ? 'This expired after 10 minutes. Nothing was changed; ask again if you still want it.'
: `It could not be done${action.result?.detail ? `: ${action.result.detail}` : '.'} Nothing else was changed.`;
return {why} ;
}
const run = async (fn: () => Promise) => { setBusy(true); setError(null); try { await fn(); } catch (e) { setError(errorMessage(e)); } finally { setBusy(false); } };
const confirm = () => run(async () => {
try {
const r = await confirmAction(action.action_id);
onChange({ ...action, status: 'confirmed', result: r.result });
} catch (e) {
const code = (e as { code?: string }).code;
if (code === 'EXPIRED') onChange({ ...action, status: 'expired' });
else if (code === 'ALREADY_USED') onChange({ ...action, status: 'failed', result: { detail: 'it was already used' } });
else if (code && code !== 'FORBIDDEN' && code !== 'HTTP_ERROR') onChange({ ...action, status: 'failed', result: { code, detail: errorMessage(e) } });
else throw e;
}
});
const cancel = () => run(async () => { await cancelAction(action.action_id); onChange({ ...action, status: 'cancelled' }); });
const approve = action.items.filter((i) => i.decision !== 'skip');
const skip = action.items.filter((i) => i.decision === 'skip');
return (
{action.tool === 'approve_scenarios' ? (
<>
{approve.length} to approve{skip.length ? <> · {skip.length} skipped for this patch> : null}
setOpen((o) => !o)} aria-expanded={open}>{open ? 'Hide the list' : 'Show the list'}
{open && (
{approve.map((i) => Approve · {i.label}: {i.value} )}
{skip.map((i) => Skip · {i.label}: {i.value} )}
)}
>
) : (
{action.items.map((i) =>
{i.label} {i.value} )}
)}
{error &&
{error} }
void confirm()} loading={busy} data-testid="chat-confirm-button">{action.verb}
{action.review && {action.review.label} }
void cancel()} disabled={busy}>Cancel
Expires at {hhmm(action.expires_at)}. You can do the same on the screens.
);
}