Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

0.9.0 V1: ReviewItemView (review item view) (#503)

Oleksandr Ivanchenko668fbcb5983a
diff --git a/frontend/src/api/inbox.ts b/frontend/src/api/inbox.ts
index a89b1704..5128e0fa 100644
--- a/frontend/src/api/inbox.ts
+++ b/frontend/src/api/inbox.ts
@@ -107,6 +107,11 @@ export interface ReviewFields {
in_review_since: string;
round: { n: number; max: number };
verdict: InboxVerdict;
+ /**
+ * D7: a verifier hold is pending and there is no verdict yet (Lin, #504). Missing reads as false.
+ * Approve stays enabled in the pane; inline Approve and Approve all still leave it out.
+ */
+ being_checked?: boolean;
risk: { level: RiskLevel | null; reasons: string[] };
criteria: InboxCriterion[];
criteria_summary: { met: number; total: number; not_met: number; not_checked: number };
@@ -210,6 +215,17 @@ export async function denyPendingHeld(item: Pick<ReviewFields, 'held_actions'>):
/** The verdict word Mira's spec shows. */
export const VERDICT_WORD: Record<VerdictResult, string> = { pass: 'Pass', fail: 'Fail', needs_you: 'Needs you', none: 'Not checked yet' };
+/** D7: true only while the verifier holds it and there is no verdict; a missing field is false. */
+export const isBeingChecked = (i: Pick<ReviewFields, 'verdict'> & { being_checked?: unknown }): boolean =>
+ i.being_checked === true && i.verdict.result === 'none';
+
+/** The status word for a review item: "Being checked" (D7) instead of "Not checked yet" while the verifier holds it. */
+export const reviewWord = (i: Pick<ReviewFields, 'verdict'> & { being_checked?: unknown }): string =>
+ isBeingChecked(i) ? 'Being checked' : VERDICT_WORD[i.verdict.result];
+
+/** The pane's line under "Being checked" (D7). */
+export const BEING_CHECKED_LINE = 'The verifier is checking this now. You can still approve it yourself.';
+
/** "Pass · high" for the board card, or null with no verdict. */
export function verdictShort(v: Pick<InboxVerdict, 'result' | 'confidence'> | null | undefined): string | null {
if (!v || v.result === 'none') return null;
@@ -370,6 +386,17 @@ const notChecked = review({
round: { n: 1, max: 2 },
});
+/** D7: the same kind of item while the verifier holds it: "Being checked", Approve enabled, never one-tap or batched. */
+const beingChecked = review({
+ id: 'r-being', kwant_id: 'k-juno', kwant_name: 'Juno', title: 'Weekly digest email', group: 'to_review', sort_key: [3, 1, 4, 'Juno', 'r-being'],
+ verdict: { id: null, result: 'none', confidence: null, line: '2 of 2 required checks passed. The checker hasn’t looked at this one.', checker: null, checked_at: null, steps_run: null, steps_total: null },
+ being_checked: true,
+ risk: { level: null, reasons: [] },
+ criteria: [{ index: 1, text: 'Digest goes out on Mondays', status: 'not_checked', source: 'task', evidence: null, note: null, round_added: 1 }],
+ criteria_summary: { met: 0, total: 1, not_met: 0, not_checked: 1 },
+ round: { n: 1, max: 2 },
+});
+
/** Pass · high, high risk, held refund still pending: To review, Approve disabled, not one-tap. */
const passHeld = review({
id: 'r-refund', kwant_id: 'k-vega', kwant_name: 'Vega', title: 'Refund the double charge', group: 'to_review', sort_key: [3, 0, 1, 'Vega', 'r-refund'],
@@ -441,7 +468,7 @@ const finished: InboxItem = {
/** Every review state, one item each (for ReviewItemView stories and tests). */
export const FIXTURE_REVIEW_ITEMS: Record<string, ReviewItem> = {
- needsYou, failRoundLimit, notChecked, passHeld, heldAllowed, heldDenied, oneTap, stale, approveError, noRollback, batchFirst: FIXTURE_BATCH[0],
+ needsYou, failRoundLimit, notChecked, beingChecked, passHeld, heldAllowed, heldDenied, oneTap, stale, approveError, noRollback, batchFirst: FIXTURE_BATCH[0],
};
/** A full GET /api/inbox answer in H5 + V1 order, with the Low-risk card. */
diff --git a/frontend/src/components/Attachments.tsx b/frontend/src/components/Attachments.tsx
index 84f9a00d..f95219ed 100644
--- a/frontend/src/components/Attachments.tsx
+++ b/frontend/src/components/Attachments.tsx
@@ -136,12 +136,15 @@ export const FileTile: React.FC<{
* closes it; focus starts on Close, Tab stays inside, the page behind doesn't scroll, and pinch-zoom
* is left to the browser. It fades in over 150 ms, with no motion under reduced motion.
*/
-export const ImageViewer: React.FC<{ file: AttachmentRef; sharedBy?: string; at?: string | null; onClose: () => void }> = ({
- file,
- sharedBy,
- at = null,
- onClose,
-}) => {
+export const ImageViewer: React.FC<{
+ file: AttachmentRef;
+ sharedBy?: string;
+ at?: string | null;
+ onClose: () => void;
+ /** A picture that isn't a chat attachment (V1 review evidence): its own URL instead of the attachment's. */
+ src?: string;
+}> = ({ file, sharedBy, at = null, onClose, src }) => {
+ const url = src ?? attachmentUrl(file.id);
const closeRef = useRef<HTMLButtonElement>(null);
const boxRef = useRef<HTMLDivElement>(null);
// The chat re-renders on every streamed token: keep the latest onClose in a ref so the setup below
@@ -207,7 +210,7 @@ export const ImageViewer: React.FC<{ file: AttachmentRef; sharedBy?: string; at?
</button>
<div className="flex-1 min-h-0 flex items-center justify-center sm:p-6" style={{ paddingTop: 'calc(env(safe-area-inset-top, 0px) + 3.5rem)' }} onClick={closeOnScrim}>
<img
- src={attachmentUrl(file.id)}
+ src={url}
alt={sharedBy ? `${file.name}, shared by ${sharedBy}` : file.name}
className="block max-w-[100vw] max-h-full object-contain"
style={{ touchAction: 'pinch-zoom' }}
@@ -228,7 +231,7 @@ export const ImageViewer: React.FC<{ file: AttachmentRef; sharedBy?: string; at?
)}
</p>
<a
- href={attachmentUrl(file.id)}
+ href={url}
target="_blank"
rel="noopener"
className="inline-flex items-center gap-1.5 shrink-0 min-h-[44px] px-3 rounded-lg text-xs font-medium text-sky-300 hover:bg-white/10 focus-visible:outline focus-visible:outline-2 focus-visible:outline-violet-400"
diff --git a/frontend/src/components/InboxNew.tsx b/frontend/src/components/InboxNew.tsx
index ba5b4e30..479a7f6f 100644
--- a/frontend/src/components/InboxNew.tsx
+++ b/frontend/src/components/InboxNew.tsx
@@ -9,6 +9,7 @@ import {
CheckCircle2,
ChevronLeft,
CircleDashed,
+ Eye,
Hand,
Info,
Layers,
@@ -22,10 +23,11 @@ import {
} from 'lucide-react';
import { ModernAvatar } from './ModernAvatar';
import { ModernApprovalCard } from './ModernApprovalCard';
-import { ReviewDone, ReviewItemSlot, VERDICT_STYLE } from './ReviewItemStub';
+import { ReviewDone, VERDICT_STYLE } from './ReviewItemStub';
+import { ReviewItemView } from './ReviewItemView';
import { approvalFromAway, awayTitle, lateAnswerText } from '../approvals';
import { ApprovalDecision, AwayError, AwayItem, actionFailureNotice, awayApi, awaySummary, itemLabel, windowLabel } from '../away';
-import { INBOX_GROUPS, InboxGroup, InboxItem, ReviewItem, VERDICT_WORD, groupItems, isReview } from '../api/inbox';
+import { INBOX_GROUPS, InboxGroup, InboxItem, ReviewItem, groupItems, isBeingChecked, isReview, pendingHeld, reviewWord } from '../api/inbox';
import {
BatchRow,
Crumb,
@@ -40,6 +42,7 @@ import {
select,
setCrumb,
comeBack,
+ markHeld,
findItem,
setNotice,
stopAfterThisOne,
@@ -102,11 +105,17 @@ const names = (xs: string[]): string => {
// ---------- Rows ----------
+/** D7 "Being checked": the verifier holds it and there is no verdict yet. */
+const BEING_CHECKED_STYLE = { icon: Eye, text: 'text-zinc-200' } as const;
+
const ReviewSubline: React.FC<{ item: ReviewItem }> = ({ item }) => {
if (item.stale) return <span className="text-rose-300">{staleLine(item.stale.paths)}</span>;
if (item.approve_error) return <span className="text-rose-300">{item.approve_error.message}</span>;
- const v = VERDICT_STYLE[item.verdict.result];
+ const checking = isBeingChecked(item);
+ const v = checking ? BEING_CHECKED_STYLE : VERDICT_STYLE[item.verdict.result];
const Icon = v.icon;
+ // V1-3: only held actions still waiting count; a denied or allowed one is done.
+ const heldOpen = pendingHeld(item).length;
const lastRoundFail = item.verdict.result === 'fail' && item.round.n >= item.round.max;
return (
<span className="flex flex-wrap items-center gap-x-1.5 gap-y-1">
@@ -115,9 +124,9 @@ const ReviewSubline: React.FC<{ item: ReviewItem }> = ({ item }) => {
Round {item.round.n}
</span>
)}
- <span className={`inline-flex items-center gap-1 font-semibold ${v.text}`}>
+ <span className={`inline-flex items-center gap-1 font-semibold ${v.text}`} data-verdict-word={checking ? 'being_checked' : item.verdict.result}>
<Icon size={12} aria-hidden="true" />
- {VERDICT_WORD[item.verdict.result]}
+ {reviewWord(item)}
</span>
{item.verdict.confidence && <span className="text-zinc-400">· {item.verdict.confidence}</span>}
{lastRoundFail && (
@@ -127,7 +136,7 @@ const ReviewSubline: React.FC<{ item: ReviewItem }> = ({ item }) => {
)}
{item.risk.level === 'high' && <span className="px-1.5 rounded-md border border-amber-500/40 bg-amber-500/10 text-amber-200 text-[11px]">High risk</span>}
{item.risk.level === 'low' && <span className="px-1.5 rounded-md border border-zinc-600 text-zinc-300 text-[11px]">Low risk</span>}
- {item.held_actions.length > 0 && <span className="text-zinc-400">{item.held_actions.length} held</span>}
+ {heldOpen > 0 && <span className="text-zinc-400" data-held-count>{heldOpen} held</span>}
</span>
);
};
@@ -159,7 +168,8 @@ interface RowProps {
const QueueRow: React.FC<RowProps> = ({ item, selected, focusable, wide, busy, onPick, onAnswer, onResolve }) => {
const review = isReview(item) ? item : null;
const title = rowTitle(item);
- const oneTap = !!review && review.one_tap && !review.stale && !review.approve_error;
+ // The server decides one_tap; an item with no verdict (Not checked yet, Being checked) never gets inline Approve.
+ const oneTap = !!review && review.one_tap && !review.stale && !review.approve_error && review.verdict.result !== 'none' && !isBeingChecked(review);
const stale = !!review?.stale;
const disabled = busy !== null;
const tint = selected ? 'border-violet-400/70 bg-violet-500/10' : GROUP_STYLE[item.group].row;
@@ -416,7 +426,8 @@ export const BatchPane: React.FC<{ wide: boolean; onOpenItem: (id: string) => vo
<span className="text-xs text-zinc-400"> · {r.kwant_name}{r.status !== 'came_back' && r.status !== 'error' ? ' · pass, high' : ''}</span>
{r.note && <span className="block text-[11px] text-rose-300">{r.note}</span>}
</span>
- <span className={`shrink-0 text-[11px] ${s.tone}`}>{back ? '' : s.word}</span>
+ {/* V1-4: "Came back" is drawn; an error row's note already starts with "Couldn’t approve". */}
+ <span className={`shrink-0 text-[11px] ${s.tone}`} data-batch-word>{r.status === 'error' ? '' : s.word}</span>
</button>
</li>
);
@@ -627,6 +638,7 @@ export const InboxNew: React.FC<InboxNewProps> = ({ onOpen, onCounts, onApproval
const s = inboxStore.get();
setNotice({ text: r.text, tone: r.kind === 'stale' ? 'error' : 'ok' });
if (r.kind === 'stale') {
+ // r.text leaves out the paths: the row in Failed or stuck (and the pane) say what changed, once.
const it = findItem(s.data, r.task_id) ?? findItem(s.data, s.selectedId);
if (it) comeBack(it, r.paths ?? []);
return;
@@ -761,7 +773,7 @@ export const InboxNew: React.FC<InboxNewProps> = ({ onOpen, onCounts, onApproval
selectedId === 'batch' && selValid ? (
<BatchPane wide={wide} onOpenItem={openFromBatch} />
) : selItem && isReview(selItem) ? (
- <ReviewItemSlot item={selItem} entry={crumb ?? 'inbox'} onDone={onDone} onApprove={(i) => void approveOne(i)} busy={busy === selItem.id} />
+ <ReviewItemView item={selItem} entry={crumb ?? 'inbox'} onDone={onDone} onHeldResolved={(approvalId, status) => markHeld(selItem.id, approvalId, status)} />
) : empty ? (
<div className="h-full grid place-items-center text-center" data-pane-empty>
<div className="space-y-1.5">
diff --git a/frontend/src/components/ReviewItemStub.tsx b/frontend/src/components/ReviewItemStub.tsx
index ecfe4d27..21ecda86 100644
--- a/frontend/src/components/ReviewItemStub.tsx
+++ b/frontend/src/components/ReviewItemStub.tsx
@@ -6,7 +6,7 @@ import { CheckCircle2, Hand, Loader2, MinusCircle, XCircle } from 'lucide-react'
import { ModernAvatar } from './ModernAvatar';
import { ReviewItem, VERDICT_WORD, approveState } from '../api/inbox';
-// Same shapes as Iris's reviewItem.ts (PR #503), so swapping ReviewItemSlot is one line.
+// Same shapes as Iris's reviewItem.ts (PR #503), so the inbox mounts ReviewItemView directly.
export type ReviewEntry = 'inbox' | 'board' | 'dev';
export interface ReviewDone {
kind: 'approved' | 'sent_back' | 'rolled_back' | 'stale';
@@ -100,6 +100,3 @@ export const ReviewItemStub: React.FC<ReviewItemViewProps> = ({ item, onApprove,
</div>
);
};
-
-/** The one item view every entry point mounts. Swap this for Iris's ReviewItemView when it lands. */
-export const ReviewItemSlot = ReviewItemStub;
diff --git a/frontend/src/components/ReviewItemView.tsx b/frontend/src/components/ReviewItemView.tsx
new file mode 100644
index 00000000..fe5767cd
--- /dev/null
+++ b/frontend/src/components/ReviewItemView.tsx
@@ -0,0 +1,1305 @@
+// 0.9.0 V1: one item view for a review, used by the Inbox pane, the phone page, the Mission board and the
+// Dev desk (Mira, release-090/designs/v1-review-inbox.md §3-§9 and "ENG (Iris)"; Ada's D2, D3, D5).
+// Verdict and buttons first; Couldn't check open when it has anything; Decisions, What done looks like and
+// Evidence folded. Approve never runs a held action (D3): the held action keeps its own Deny / Allow once,
+// and Approve waits for it. Data from the server is shown as text only, never as HTML.
+
+import React, { useCallback, useEffect, useId, useRef, useState } from 'react';
+import {
+ AlertTriangle,
+ Check,
+ CheckCircle2,
+ ChevronDown,
+ ChevronLeft,
+ CornerUpLeft,
+ EyeOff,
+ ExternalLink,
+ Eye,
+ FolderOpen,
+ GitBranch,
+ GitPullRequest,
+ Hand,
+ ListChecks,
+ Loader2,
+ MessageSquare,
+ MinusCircle,
+ RotateCcw,
+ ShieldCheck,
+ SquareKanban,
+ Terminal,
+ X,
+ XCircle,
+ type LucideIcon,
+} from 'lucide-react';
+import { type InboxItem, type ReviewItem, type HeldAction, type HeldStatus, type InboxCriterion, BEING_CHECKED_LINE, InboxError, approveState, inboxApi, isBeingChecked, reviewWord } from '../api/inbox';
+import { AwayError } from '../away';
+import { type Checkpoint, type RestorePreview, MissionError, RESTORE_ACTION_LABELS, conflictText, missionsApi, newIdempotencyKey, restoreErrorText } from '../missions';
+import { usePhoneLayout } from '../usePhoneLayout';
+import { ImageViewer } from './Attachments';
+import { ModernAvatar } from './ModernAvatar';
+import {
+ CRITERION_WORD,
+ GATE_TEXT,
+ NOT_UNDONE_UNKNOWN,
+ RISK_WORD,
+ type ReviewDone,
+ type ReviewEntry,
+ changePrefill,
+ checkerMeta,
+ clock,
+ confidenceText,
+ criteriaSummaryText,
+ decisionsSummaryText,
+ evidenceSummaryText,
+ lastRound,
+ nextCriterionIndex,
+ notUndoneTitle,
+ rollBackLabel,
+ rolledBackForkText,
+ rolledBackText,
+ sendBackSteps,
+ stepDownText,
+ tailLines,
+ validReviewItem,
+} from '../reviewItem';
+
+export type { ReviewDone, ReviewEntry } from '../reviewItem';
+
+/** The calls the view makes; tests and screenshots pass a fake. */
+export interface ReviewItemApi {
+ verify: (taskId: string, verdictId?: string | null) => Promise<unknown>;
+ reject: (taskId: string, reason: string) => Promise<unknown>;
+ runChecks: (taskId: string) => Promise<unknown>;
+ resolveHeld: (approvalId: string, decision: 'allow_once' | 'deny') => Promise<unknown>;
+ checkpoints: (taskId: string) => Promise<Checkpoint[]>;
+ restorePreview: (taskId: string, checkpointId: string) => Promise<RestorePreview>;
+ restore: typeof missionsApi.restore;
+ forkFromCheckpoint: typeof missionsApi.forkFromCheckpoint;
+}
+
+export const defaultReviewApi: ReviewItemApi = {
+ verify: inboxApi.verify,
+ reject: inboxApi.reject,
+ runChecks: inboxApi.runChecks,
+ resolveHeld: inboxApi.resolveHeld,
+ checkpoints: missionsApi.checkpoints,
+ restorePreview: missionsApi.restorePreview,
+ restore: missionsApi.restore,
+ forkFromCheckpoint: missionsApi.forkFromCheckpoint,
+};
+
+export interface ReviewItemViewProps {
+ item: ReviewItem | InboxItem;
+ entry: ReviewEntry;
+ onDone: (result: ReviewDone) => void;
+ api?: ReviewItemApi;
+ /** "‹ Back to Mission board" / "‹ Back to Dev desk" above the header (desktop), when given. */
+ onBack?: () => void;
+ onOpenChat?: () => void;
+ onOpenBoard?: () => void;
+ /** After a roll back after approval: open the copy. */
+ onOpenTask?: (taskId: string) => void;
+ /** A held action was denied, allowed or found expired here, so the list can stop counting it (V1-3). */
+ onHeldResolved?: (approvalId: string, status: Exclude<HeldStatus, 'pending'>) => void;
+ /** The phone page draws its own top bar with the title; the view then starts at the chips. */
+ hideTitle?: boolean;
+}
+
+const BACK_LABEL: Record<ReviewEntry, string | null> = { inbox: null, board: 'Back to Mission board', dev: 'Back to Dev desk' };
+
+const btnBase =
+ 'inline-flex items-center justify-center gap-1.5 rounded-xl px-3.5 min-h-[36px] max-md:min-h-[44px] text-meta font-semibold transition-colors kw-focus disabled:cursor-not-allowed';
+const btnApprove = `${btnBase} bg-accent-gradient text-white aria-disabled:opacity-[.42] aria-disabled:cursor-not-allowed`;
+const btnQuiet = `${btnBase} border border-hairline-strong bg-white/[0.03] text-zinc-200 hover:bg-white/[0.08] disabled:opacity-50`;
+const btnRose = `${btnBase} border border-rose-400/40 bg-rose-500/[0.06] text-rose-200 hover:bg-rose-500/[0.12] disabled:opacity-50`;
+const btnRoseFill = `${btnBase} bg-rose-600 text-white hover:bg-rose-500 disabled:opacity-50`;
+const btnAllow = `${btnBase} bg-[#059669] text-white hover:bg-emerald-500 disabled:opacity-50`;
+const spin = 'motion-safe:animate-spin';
+
+// ---- Folds: open or closed per section for the session (Mira §3.5), not per item ----
+
+type FoldKey = 'decisions' | 'criteria' | 'evidence';
+const FOLD_KEY = 'kw-review-folds';
+function readFolds(): Record<FoldKey, boolean> {
+ try {
+ const v = JSON.parse(sessionStorage.getItem(FOLD_KEY) ?? '{}');
+ return { decisions: v.decisions === true, criteria: v.criteria === true, evidence: v.evidence === true };
+ } catch {
+ return { decisions: false, criteria: false, evidence: false };
+ }
+}
+function writeFolds(f: Record<FoldKey, boolean>) {
+ try {
+ sessionStorage.setItem(FOLD_KEY, JSON.stringify(f));
+ } catch {
+ // private mode: the fold just forgets
+ }
+}
+
+type HeldState = { state: 'open' | 'allowed' | 'denied' | 'expired'; at?: string | null; busy?: boolean; error?: string | null; ran?: string | null };
+const HELD_STATE = { pending: 'open', allowed: 'allowed', denied: 'denied', expired: 'expired' } as const;
+/** The server's own status for a held action; resolved ones stay listed with their result line. */
+const heldFrom = (h: HeldAction): HeldState => ({ state: HELD_STATE[h.status] ?? 'open', at: h.resolved_at, ran: h.result_line });
+
+const typingIn = (t: EventTarget | null) => {
+ const el = t as HTMLElement | null;
+ if (!el || !el.tagName) return false;
+ return el.tagName === 'INPUT' || el.tagName === 'TEXTAREA' || el.tagName === 'SELECT' || el.isContentEditable;
+};
+
+/** The plain card for an item the view can't draw (not a review, or a field missing): title and summary as text. */
+const FallbackCard: React.FC<{ item: InboxItem }> = ({ item }) => (
+ <section role="region" aria-label={item.title || 'Inbox item'} className="kw-card p-4 space-y-1" data-review-fallback>
+ <h2 className="text-[16px] font-semibold text-zinc-100 break-words">{item.title}</h2>
+ {item.summary && <p className="text-body text-zinc-300 whitespace-pre-wrap break-words">{item.summary}</p>}
+ </section>
+);
+
+export const ReviewItemView: React.FC<ReviewItemViewProps> = (props) => {
+ if (!validReviewItem(props.item)) return <FallbackCard item={props.item} />;
+ // A new item starts fresh: no leftover panel, notice or held state from the last one.
+ return <ReviewBody key={props.item.id} {...props} item={props.item} />;
+};
+
+export default ReviewItemView;
+
+const ReviewBody: React.FC<ReviewItemViewProps & { item: ReviewItem }> = ({
+ item,
+ entry,
+ onDone,
+ api = defaultReviewApi,
+ onBack,
+ onOpenChat,
+ onOpenBoard,
+ onOpenTask,
+ onHeldResolved,
+ hideTitle = false,
+}) => {
+ const phone = usePhoneLayout();
+ const uid = useId();
+ const titleId = `${uid}-title`;
+ const [held, setHeld] = useState<Record<string, HeldState>>(() => Object.fromEntries(item.held_actions.map((h) => [h.approval_id, heldFrom(h)])));
+ const openHeld = item.held_actions.filter((h) => held[h.approval_id]?.state === 'open');
+ const blocked = openHeld.length > 0 ? approveState({ held_actions: openHeld }).blocked : null;
+ const [busy, setBusy] = useState<null | 'approve' | 'send' | 'check'>(null);
+ const [notice, setNotice] = useState<{ text: string; tone: 'ok' | 'bad' | 'info'; undo?: string | null; copy?: string | null } | null>(null);
+ const [done, setDone] = useState(false);
+ /** A stale 409 seen here, until the parent's copy of the item carries `stale` (drawn once either way, V1-4). */
+ const [staleHere, setStaleHere] = useState<string[] | null>(null);
+ const [sendOpen, setSendOpen] = useState(false);
+ const [note, setNote] = useState('');
+ const [sendErr, setSendErr] = useState<string | null>(null);
+ const [rollOpen, setRollOpen] = useState<null | { undoFrom?: string }>(null);
+ const [folds, setFolds] = useState(readFolds);
+ const firstDenyRef = useRef<HTMLButtonElement>(null);
+ const sendBtnRef = useRef<HTMLButtonElement>(null);
+ const rollBtnRef = useRef<HTMLButtonElement>(null);
+ const approveRef = useRef<HTMLButtonElement>(null);
+ const inFlight = useRef(false);
+
+ const toggleFold = (k: FoldKey) =>
+ setFolds((f) => {
+ const n = { ...f, [k]: !f[k] };
+ writeFolds(n);
+ return n;
+ });
+
+ const finish = useCallback(
+ (r: ReviewDone, tone: 'ok' | 'bad' | 'info', extra: { undo?: string | null; copy?: string | null } = {}) => {
+ setDone(r.kind !== 'stale');
+ // A stale approve is shown by the stale box below, not a second notice saying the same (V1-4).
+ if (r.kind === 'stale') setStaleHere(r.paths ?? []);
+ else setNotice({ text: r.text, tone, ...extra });
+ onDone(r);
+ },
+ [onDone],
+ );
+
+ // ---- Held actions: today's resolve call, one at a time ----
+ const resolveHeld = async (h: HeldAction, decision: 'allow_once' | 'deny'): Promise<boolean> => {
+ const id = h.approval_id;
+ setHeld((s) => ({ ...s, [id]: { ...s[id], busy: true, error: null } }));
+ try {
+ const r = await api.resolveHeld(id, decision);
+ const o = r && typeof r === 'object' ? (r as Record<string, unknown>) : {};
+ const ran = typeof o.result_line === 'string' ? o.result_line : typeof o.result === 'string' ? o.result : null;
+ setHeld((s) => ({ ...s, [id]: { state: decision === 'deny' ? 'denied' : 'allowed', at: new Date().toISOString(), ran } }));
+ onHeldResolved?.(id, decision === 'deny' ? 'denied' : 'allowed');
+ return true;
+ } catch (e) {
+ const status = e instanceof AwayError || e instanceof InboxError ? e.status : 0;
+ if (status === 404 || status === 409) {
+ setHeld((s) => ({ ...s, [id]: { state: 'expired' } }));
+ onHeldResolved?.(id, 'expired');
+ return true;
+ }
+ setHeld((s) => ({ ...s, [id]: { ...s[id], busy: false, error: e instanceof Error ? e.message : 'Something went wrong.' } }));
+ return false;
+ }
+ };
+ /** Send back and Roll back deny every open held action first; one failing stops the whole step. */
+ const denyAllOpen = async (): Promise<string | null> => {
+ for (const h of openHeld) {
+ const ok = await resolveHeld(h, 'deny');
+ if (!ok) return `Couldn’t deny the held action, so nothing was sent. Try again.`;
+ }
+ return null;
+ };
+
+ // ---- Approve ----
+ const approve = async () => {
+ if (inFlight.current || done) return;
+ if (blocked) {
+ firstDenyRef.current?.focus();
+ return;
+ }
+ inFlight.current = true;
+ setBusy('approve');
+ setNotice(null);
+ try {
+ await api.verify(item.task_id, item.verdict.id);
+ finish({ kind: 'approved', text: `Approved: “${item.title}”.`, task_id: item.task_id }, 'ok');
+ } catch (e) {
+ if (e instanceof InboxError && e.stale) {
+ // The paths go in the stale box and the list row, not in this text (the Inbox status line), V1-4.
+ finish({ kind: 'stale', text: `Couldn’t approve “${item.title}”. It’s back in Failed or stuck, and nothing was approved.`, task_id: item.task_id, paths: e.paths }, 'bad');
+ } else {
+ const why = e instanceof Error ? e.message.replace(/\.$/, '') : 'Something went wrong';
+ setNotice({ text: `Couldn’t approve “${item.title}”. ${why}. Nothing was approved.`, tone: 'bad' });
+ }
+ } finally {
+ inFlight.current = false;
+ setBusy(null);
+ }
+ };
+
+ // ---- Check again (stale) ----
+ const checkAgain = async () => {
+ if (inFlight.current) return;
+ inFlight.current = true;
+ setBusy('check');
+ setNotice(null);
+ try {
+ await api.runChecks(item.task_id);
+ setNotice({ text: 'Checking again. When the checks pass it goes back to To review.', tone: 'info' });
+ } catch (e) {
+ setNotice({ text: `Couldn’t run the checks. ${e instanceof Error ? e.message : ''}`.trim(), tone: 'bad' });
+ } finally {
+ inFlight.current = false;
+ setBusy(null);
+ }
+ };
+
+ // ---- Send back ----
+ const openSend = (prefill?: string) => {
+ if (done) return;
+ if (prefill !== undefined) setNote(prefill);
+ setSendErr(null);
+ setSendOpen(true);
+ };
+ const closeSend = () => {
+ setSendOpen(false);
+ setSendErr(null);
+ requestAnimationFrame(() => sendBtnRef.current?.focus());
+ };
+ const sendBack = async () => {
+ const reason = note.trim();
+ if (!reason || inFlight.current) return;
+ inFlight.current = true;
+ setBusy('send');
+ setSendErr(null);
+ try {
+ const err = await denyAllOpen();
+ if (err) {
+ setSendErr(err);
+ return;
+ }
+ await api.reject(item.task_id, reason);
+ setSendOpen(false);
+ finish({ kind: 'sent_back', text: `Sent back to ${item.kwant_name}. Round ${item.round.n + 1} starts now.`, task_id: item.task_id }, 'ok');
+ } catch (e) {
+ setSendErr(`Couldn’t send it back. ${e instanceof Error ? e.message : ''}`.trim());
+ } finally {
+ inFlight.current = false;
+ setBusy(null);
+ }
+ };
+
+ // ---- Keyboard: A approves (never a held action), S opens Send back, Esc closes a panel ----
+ const keyState = useRef({ approve, openSend, sendOpen, rollOpen, done });
+ keyState.current = { approve, openSend, sendOpen, rollOpen, done };
+ useEffect(() => {
+ if (phone) return;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.defaultPrevented || e.metaKey || e.ctrlKey || e.altKey || typingIn(e.target)) return;
+ const s = keyState.current;
+ if (s.rollOpen) return; // the dialog owns the keys
+ if (e.key === 'Escape' && s.sendOpen) {
+ e.preventDefault();
+ closeSend();
+ return;
+ }
+ if (s.done || s.sendOpen) return;
+ if (e.key === 'a' || e.key === 'A') {
+ e.preventDefault();
+ void s.approve();
+ } else if (e.key === 's' || e.key === 'S') {
+ e.preventDefault();
+ s.openSend();
+ }
+ };
+ document.addEventListener('keydown', onKey);
+ return () => document.removeEventListener('keydown', onKey);
+ }, [phone]);
+
+ const v = item.verdict;
+ const checking = isBeingChecked(item);
+ const tone = checking ? BEING_CHECKED_TONE : VERDICT_TONE[v.result];
+ const stalePaths = item.stale ? item.stale.paths : staleHere;
+ const VIcon = tone.icon;
+ const meta = checkerMeta(item);
+ const conf = confidenceText(v);
+ const since = clock(item.in_review_since);
+ const back = BACK_LABEL[entry];
+ const lockAll = done || busy !== null;
+ const rollbackShown = item.rollback_ok;
+
+ return (
+ <section role="region" aria-labelledby={titleId} className="space-y-4 min-w-0" data-review-item={item.id} data-entry={entry}>
+ {/* Header */}
+ {back && onBack && !phone && (
+ <button type="button" onClick={onBack} className="inline-flex items-center gap-1 text-meta text-zinc-400 hover:text-zinc-200 rounded kw-focus" data-review-back>
+ <ChevronLeft size={14} aria-hidden="true" /> {back}
+ </button>
+ )}
+ <header className="flex items-start gap-3 min-w-0">
+ {!hideTitle && <ModernAvatar role={item.kwant_name} name={item.kwant_name} size={34} kwantId={item.kwant_id} />}
+ <div className="min-w-0 flex-1 space-y-1">
+ <h2 id={titleId} className={hideTitle ? 'sr-only' : 'text-[16px] leading-snug font-[650] text-zinc-50 break-words'}>
+ {item.title}
+ </h2>
+ <div className="flex flex-wrap items-center gap-1.5 text-meta text-zinc-400">
+ {item.round.n > 1 && (
+ <span className="kw-chip border-violet-400/40 bg-violet-500/15 text-violet-200 !py-0" data-round-chip>
+ Round {item.round.n}
+ </span>
+ )}
+ {item.risk.level && (
+ <span className={`kw-chip !py-0 ${item.risk.level === 'high' ? 'kw-chip-warn' : ''}`} data-risk={item.risk.level}>
+ {RISK_WORD[item.risk.level]}
+ </span>
+ )}
+ <span className="min-w-0 break-words">
+ {[item.project, since ? `in Review since ${since}` : null, `round ${item.round.n} of ${item.round.max}`].filter(Boolean).join(' · ')}
+ </span>
+ </div>
+ </div>
+ {!phone && (onOpenChat || onOpenBoard) && (
+ <div className="flex shrink-0 gap-2">
+ {onOpenChat && (
+ <button type="button" onClick={onOpenChat} className={btnQuiet}>
+ <MessageSquare size={14} aria-hidden="true" /> Open chat
+ </button>
+ )}
+ {onOpenBoard && (
+ <button type="button" onClick={onOpenBoard} className={btnQuiet}>
+ <SquareKanban size={14} aria-hidden="true" /> Mission board
+ </button>
+ )}
+ </div>
+ )}
+ </header>
+
+ {/* Verdict */}
+ <div className={`rounded-2xl border px-4 py-3 space-y-1 ${tone.box}`} data-verdict={checking ? 'being_checked' : v.result}>
+ <p className="text-[15px] font-semibold flex flex-wrap items-center gap-x-1.5">
+ <VIcon size={17} className={tone.text} aria-hidden="true" />
+ <span className={tone.text}>{reviewWord(item)}</span>
+ {conf && <span className="font-normal text-zinc-400">· {conf}</span>}
+ </p>
+ <p className="text-body text-zinc-100 break-words" data-verdict-line>{checking ? BEING_CHECKED_LINE : v.line}</p>
+ {meta && (
+ <p className="flex items-start gap-1.5 text-meta text-zinc-400" data-checker-meta>
+ <Eye size={13} className="mt-0.5 shrink-0" aria-hidden="true" />
+ <span className="min-w-0">{meta}</span>
+ </p>
+ )}
+ </div>
+
+ {/* Stale and approve_error, from the server */}
+ {stalePaths && (
+ <div className="rounded-xl border border-rose-400/30 bg-rose-500/[0.06] px-3 py-2 space-y-2" data-stale>
+ <p className="text-body text-rose-200 break-words">
+ <AlertTriangle size={14} className="inline -mt-0.5 mr-1" aria-hidden="true" />
+ Couldn’t approve: {item.title}. {stalePaths.length ? `${stalePaths.join(', ')} changed after its check.` : 'The work changed after its check.'}
+ </p>
+ <button type="button" onClick={() => void checkAgain()} disabled={lockAll} className={btnQuiet} data-check-again>
+ {busy === 'check' ? <Loader2 size={14} className={spin} aria-hidden="true" /> : <RotateCcw size={14} aria-hidden="true" />} Check again
+ </button>
+ </div>
+ )}
+ {item.approve_error && (
+ <p className="rounded-xl border border-rose-400/30 bg-rose-500/[0.06] px-3 py-2 text-body text-rose-200 break-words" data-approve-error={item.approve_error.code}>
+ <AlertTriangle size={14} className="inline -mt-0.5 mr-1" aria-hidden="true" />
+ {item.approve_error.message}
+ </p>
+ )}
+
+ {/* Actions: held, then Approve · Send back · Roll back */}
+ <div className="kw-card p-3 sm:p-4 space-y-3" data-actions>
+ {item.held_actions.length > 0 && (
+ <ol className="space-y-2" aria-label="Held actions">
+ {item.held_actions.map((h, i) => (
+ <HeldBox
+ key={h.approval_id}
+ h={h}
+ n={item.held_actions.length > 1 ? i + 1 : null}
+ bot={item.kwant_name}
+ st={held[h.approval_id] ?? heldFrom(h)}
+ phone={phone}
+ lock={done || busy === 'send'}
+ denyRef={openHeld[0]?.approval_id === h.approval_id ? firstDenyRef : undefined}
+ onResolve={(d) => void resolveHeld(h, d)}
+ />
+ ))}
+ </ol>
+ )}
+ <div className={phone ? 'grid grid-cols-2 gap-2' : 'flex flex-wrap items-center gap-2'}>
+ <button
+ ref={approveRef}
+ type="button"
+ onClick={() => void approve()}
+ aria-disabled={!!blocked || lockAll || undefined}
+ aria-keyshortcuts={phone ? undefined : 'A'}
+ aria-describedby={blocked ? `${uid}-blocked` : undefined}
+ className={`${btnApprove} ${phone ? 'col-span-2' : ''}`}
+ data-approve
+ >
+ {busy === 'approve' ? <Loader2 size={14} className={spin} aria-hidden="true" /> : <Check size={14} aria-hidden="true" />}
+ {busy === 'approve' ? 'Approving…' : 'Approve'}
+ </button>
+ {phone && blocked && <BlockedLine id={`${uid}-blocked`} text={blocked} className="col-span-2" />}
+ <button
+ ref={sendBtnRef}
+ type="button"
+ onClick={() => openSend()}
+ disabled={lockAll}
+ aria-expanded={sendOpen}
+ aria-keyshortcuts={phone ? undefined : 'S'}
+ className={btnQuiet}
+ data-send-back
+ >
+ <CornerUpLeft size={14} aria-hidden="true" /> Send back
+ </button>
+ {rollbackShown && (
+ <button ref={rollBtnRef} type="button" onClick={() => setRollOpen({})} disabled={lockAll} aria-haspopup="dialog" className={btnRose} data-roll-back>
+ <RotateCcw size={14} aria-hidden="true" /> Roll back
+ </button>
+ )}
+ {!phone && lastRound(item.round) && item.round.n > 1 && (
+ <span className="text-meta text-zinc-400 max-w-[14rem]" data-last-round>
+ Last round. Sending back again asks you how to go on.
+ </span>
+ )}
+ {!phone && (
+ <span className="ml-auto hidden lg:flex items-center gap-1" aria-hidden="true">
+ {['A', 'S', 'J', 'K'].map((k) => (
+ <kbd key={k} className="rounded border border-hairline-strong px-1 text-[10px] leading-4 text-zinc-400">
+ {k}
+ </kbd>
+ ))}
+ </span>
+ )}
+ </div>
+ {!phone && blocked && <BlockedLine id={`${uid}-blocked`} text={blocked} />}
+ {phone && lastRound(item.round) && item.round.n > 1 && <p className="text-meta text-zinc-400">Last round. Sending back again asks you how to go on.</p>}
+ </div>
+
+ {/* Status line: approved, sent back, rolled back, or an action error */}
+ <div role="status" aria-live="polite" className="empty:hidden" data-review-status>
+ {notice && (
+ <p
+ className={`rounded-xl border px-3 py-2 text-body break-words ${
+ notice.tone === 'bad' ? 'border-rose-400/30 bg-rose-500/[0.06] text-rose-200' : notice.tone === 'ok' ? 'border-teal-400/25 bg-teal-400/[0.05] text-zinc-100' : 'border-hairline-strong bg-white/[0.03] text-zinc-200'
+ }`}
+ data-notice={notice.tone}
+ >
+ {notice.tone === 'bad' ? <AlertTriangle size={14} className="inline -mt-0.5 mr-1" aria-hidden="true" /> : <CheckCircle2 size={14} className="inline -mt-0.5 mr-1 text-ok" aria-hidden="true" />}
+ {notice.text}
+ {notice.undo && (
+ <>
+ {' '}
+ <button type="button" onClick={() => setRollOpen({ undoFrom: notice.undo ?? undefined })} className="text-violet-300 underline-offset-2 hover:underline rounded kw-focus kw-hit" data-undo-rollback>
+ Undo the roll back
+ </button>
+ </>
+ )}
+ {notice.copy && onOpenTask && (
+ <>
+ {' '}
+ <button type="button" onClick={() => onOpenTask(notice.copy!)} className="text-violet-300 underline-offset-2 hover:underline rounded kw-focus kw-hit" data-open-copy>
+ Open the copy
+ </button>
+ </>
+ )}
+ </p>
+ )}
+ </div>
+
+ {/* Send back: inline panel on desktop, sheet on phone */}
+ {sendOpen &&
+ (phone ? (
+ <Sheet title={`Send back to ${item.kwant_name}`} onClose={closeSend}>
+ <SendBackForm item={item} note={note} setNote={setNote} err={sendErr} busy={busy === 'send'} openHeld={openHeld.length} onSend={() => void sendBack()} onCancel={closeSend} phone />
+ </Sheet>
+ ) : (
+ <div className="rounded-2xl border border-violet-400/40 bg-surface-raised p-4 space-y-3 kw-fade-in" data-send-panel>
+ <h3 className="flex items-center gap-2 text-body font-semibold text-zinc-100">
+ <CornerUpLeft size={15} aria-hidden="true" /> Send back to {item.kwant_name}
+ </h3>
+ <SendBackForm item={item} note={note} setNote={setNote} err={sendErr} busy={busy === 'send'} openHeld={openHeld.length} onSend={() => void sendBack()} onCancel={closeSend} />
+ </div>
+ ))}
+
+ {/* Round 2: what changed since round 1 */}
+ {item.previous_round && <RoundBox item={item} />}
+
+ {/* Couldn't check: open whenever it isn't empty */}
+ {item.couldnt_verify.length > 0 && (
+ <section aria-labelledby={`${uid}-cc`} className="space-y-2" data-couldnt-check>
+ <h3 id={`${uid}-cc`} className="flex items-center gap-1.5 text-meta font-semibold uppercase tracking-wide text-zinc-300">
+ <EyeOff size={14} aria-hidden="true" /> Couldn’t check <span className="font-normal text-zinc-500">{item.couldnt_verify.length}</span>
+ </h3>
+ <ul className="rounded-xl border border-dashed border-hairline-strong px-4 py-2.5 space-y-1 list-disc pl-8 text-body">
+ {item.couldnt_verify.map((c, i) => (
+ <li key={i} className="break-words text-zinc-100">
+ {c.what}
+ {c.what && !/[.!?]$/.test(c.what) ? '.' : ''} <span className="text-zinc-400">{c.why}</span>
+ </li>
+ ))}
+ </ul>
+ </section>
+ )}
+
+ {/* Folds */}
+ <div className="space-y-2">
+ {item.decisions.total > 0 && (
+ <Fold id={`${uid}-dec`} icon={GitBranch} label="Decisions" summary={decisionsSummaryText(item.decisions)} open={folds.decisions} onToggle={() => toggleFold('decisions')}>
+ <ul className="space-y-2">
+ {item.decisions.top.map((d) => (
+ <li key={d.index} className="rounded-xl border border-hairline bg-white/[0.02] px-3 py-2 flex items-start gap-3" data-decision={d.index}>
+ <div className="min-w-0 flex-1 text-body">
+ <p className="font-semibold text-zinc-100 break-words">{d.question}</p>
+ <p className="text-zinc-300 break-words">
+ Picked: <span className="font-semibold text-zinc-100">{d.picked}</span>
+ </p>
+ {d.why && <p className="text-meta text-zinc-400 break-words">{d.why}</p>}
+ </div>
+ <button type="button" onClick={() => openSend(changePrefill(d.question))} disabled={lockAll} className={btnQuiet} data-decision-change>
+ Change
+ </button>
+ </li>
+ ))}
+ </ul>
+ </Fold>
+ )}
+ <Fold
+ id={`${uid}-crit`}
+ icon={ListChecks}
+ label="What done looks like"
+ summary={criteriaSummaryText(item.criteria_summary)}
+ summaryBad={item.criteria_summary.not_met > 0}
+ open={folds.criteria}
+ onToggle={() => toggleFold('criteria')}
+ >
+ {item.criteria.length ? (
+ <ul className="rounded-xl border border-hairline divide-y divide-hairline">
+ {item.criteria.map((c) => (
+ <CriterionRow key={c.index} c={c} />
+ ))}
+ </ul>
+ ) : (
+ <p className="text-meta text-zinc-400">No criteria were set for this task.</p>
+ )}
+ </Fold>
+ <Fold id={`${uid}-ev`} icon={Terminal} label="Evidence" summary={evidenceSummaryText(item.evidence)} open={folds.evidence} onToggle={() => toggleFold('evidence')}>
+ <Evidence item={item} />
+ </Fold>
+ </div>
+
+ {rollOpen && (
+ <RollBackDialog
+ item={item}
+ api={api}
+ phone={phone}
+ undoFrom={rollOpen.undoFrom}
+ openHeld={openHeld.length}
+ denyAllOpen={denyAllOpen}
+ onClose={() => {
+ setRollOpen(null);
+ requestAnimationFrame(() => rollBtnRef.current?.focus());
+ }}
+ onDone={(r, extra) => {
+ setRollOpen(null);
+ finish(r, 'ok', extra);
+ }}
+ />
+ )}
+ </section>
+ );
+};
+
+/** D7 "Being checked": neutral, a still icon (nothing spins, so reduced motion needs nothing). */
+const BEING_CHECKED_TONE = { icon: Eye, text: 'text-zinc-200', box: 'border-hairline-strong bg-white/[0.02]' } as const;
+
+const VERDICT_TONE = {
+ pass: { icon: CheckCircle2, text: 'text-ok', box: 'border-teal-400/25 bg-teal-400/[0.05]' },
+ fail: { icon: XCircle, text: 'text-bad', box: 'border-rose-400/30 bg-rose-500/[0.06]' },
+ needs_you: { icon: Hand, text: 'text-warn', box: 'border-amber-500/[0.32] bg-amber-950/[0.24]' },
+ none: { icon: MinusCircle, text: 'text-zinc-400', box: 'border-hairline-strong bg-white/[0.02]' },
+} as const;
+
+const BlockedLine: React.FC<{ id: string; text: string; className?: string }> = ({ id, text, className = '' }) => (
+ <p id={id} className={`flex items-center gap-1.5 text-[11.5px] text-warn ${className}`} data-approve-blocked>
+ <Hand size={13} aria-hidden="true" /> {text}
+ </p>
+);
+
+const HeldBox: React.FC<{
+ h: HeldAction;
+ n: number | null;
+ bot: string;
+ st: HeldState;
+ phone: boolean;
+ lock: boolean;
+ denyRef?: React.Ref<HTMLButtonElement>;
+ onResolve: (d: 'allow_once' | 'deny') => void;
+}> = ({ h, n, bot, st, phone, lock, denyRef, onResolve }) => {
+ const at = clock(st.at);
+ const box =
+ st.state === 'allowed'
+ ? 'border-teal-400/30 bg-teal-400/[0.05]'
+ : st.state === 'open'
+ ? 'border-amber-500/[0.32] bg-amber-950/[0.24]'
+ : 'border-hairline-strong bg-white/[0.02]';
+ const head =
+ st.state === 'allowed' ? (
+ <span className="text-ok">
+ <Check size={13} className="inline -mt-0.5 mr-1" aria-hidden="true" />
+ You allowed this{at ? ` at ${at}` : ''}. It ran:
+ </span>
+ ) : st.state === 'denied' ? (
+ <span className="text-zinc-300">You denied this{at ? ` at ${at}` : ''}. It didn’t run.</span>
+ ) : st.state === 'expired' ? (
+ <span className="text-zinc-300">{st.ran || `This request expired. ${bot} will ask again if it still needs it.`}</span>
+ ) : (
+ <span className="text-warn">
+ <Hand size={13} className="inline -mt-0.5 mr-1" aria-hidden="true" />
+ Held: {bot} wants to run this, exactly:
+ </span>
+ );
+ return (
+ <li className={`rounded-xl border px-3 py-2.5 space-y-2 ${box}`} data-held={h.approval_id} data-held-state={st.state}>
+ <div className="flex items-start justify-between gap-3 text-meta font-semibold">
+ <p className="min-w-0">
+ {n !== null && <span className="text-zinc-400 mr-1">{n}.</span>}
+ {head}
+ </p>
+ {!phone && <span className="shrink-0 font-normal text-zinc-400">{GATE_TEXT[h.gate]}</span>}
+ </div>
+ {st.state !== 'expired' && (
+ <pre className="font-mono text-[12.5px] leading-5 text-zinc-100 whitespace-pre-wrap break-words" data-held-args>
+ {h.args_display}
+ </pre>
+ )}
+ {st.state === 'allowed' && st.ran && <p className="text-meta text-zinc-300">{st.ran}</p>}
+ {st.error && <p className="text-meta text-rose-200">{st.error}</p>}
+ {st.state === 'open' && (
+ <div className={phone ? 'grid grid-cols-2 gap-2' : 'flex gap-2'}>
+ <button ref={denyRef} type="button" onClick={() => onResolve('deny')} disabled={st.busy || lock} className={btnQuiet} data-held-deny>
+ <X size={14} aria-hidden="true" /> Deny
+ </button>
+ <button type="button" onClick={() => onResolve('allow_once')} disabled={st.busy || lock} className={btnAllow} data-held-allow>
+ <Check size={14} aria-hidden="true" /> Allow once
+ </button>
+ </div>
+ )}
+ </li>
+ );
+};
+
+const SendBackForm: React.FC<{
+ item: ReviewItem;
+ note: string;
+ setNote: (s: string) => void;
+ err: string | null;
+ busy: boolean;
+ openHeld: number;
+ onSend: () => void;
+ onCancel: () => void;
+ phone?: boolean;
+}> = ({ item, note, setNote, err, busy, openHeld, onSend, onCancel, phone = false }) => {
+ const ta = useRef<HTMLTextAreaElement>(null);
+ const id = useId();
+ useEffect(() => {
+ const el = ta.current;
+ if (!el) return;
+ el.focus();
+ el.setSelectionRange(el.value.length, el.value.length);
+ }, []);
+ const empty = !note.trim();
+ return (
+ <div className="space-y-3" data-send-form>
+ <label htmlFor={`${id}-note`} className="block text-meta text-zinc-300">
+ What still needs doing?
+ </label>
+ <textarea
+ id={`${id}-note`}
+ ref={ta}
+ value={note}
+ onChange={(e) => setNote(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
+ e.preventDefault();
+ if (!empty && !busy) onSend();
+ } else if (e.key === 'Escape') {
+ e.preventDefault();
+ e.stopPropagation();
+ onCancel();
+ }
+ }}
+ rows={3}
+ className="block w-full min-h-[76px] rounded-xl border border-violet-400/40 bg-surface-main px-3 py-2 text-body text-zinc-100 placeholder:text-zinc-500 kw-focus"
+ data-send-note
+ />
+ {!empty && (
+ <div className="flex flex-col sm:flex-row sm:items-start gap-1.5 sm:gap-3" data-becomes>
+ <span className="shrink-0 text-meta text-zinc-400 sm:pt-2">Becomes criterion {nextCriterionIndex(item.criteria)}:</span>
+ <p className="min-w-0 flex-1 rounded-xl border border-dashed border-violet-400/40 px-3 py-2 text-body text-zinc-100 break-words whitespace-pre-wrap">
+ {note.trim()}{' '}
+ <span className="kw-chip border-violet-400/40 bg-violet-500/15 text-violet-200 !py-0 align-middle">Your note</span>
+ </p>
+ </div>
+ )}
+ <ul className="list-disc pl-5 space-y-0.5 text-meta text-zinc-400">
+ {sendBackSteps(item, openHeld).map((s) => (
+ <li key={s}>{s}</li>
+ ))}
+ </ul>
+ {err && (
+ <p className="text-meta text-rose-200" role="alert">
+ {err}
+ </p>
+ )}
+ <div className={phone ? 'grid grid-cols-2 gap-2' : 'flex flex-wrap items-center gap-2'}>
+ <button type="button" onClick={onSend} disabled={empty || busy} className={`${btnBase} bg-accent-gradient text-white disabled:opacity-50`} data-send-submit>
+ {busy ? <Loader2 size={14} className={spin} aria-hidden="true" /> : <CornerUpLeft size={14} aria-hidden="true" />} Send back
+ </button>
+ <button type="button" onClick={onCancel} className={btnQuiet} data-send-cancel>
+ Cancel
+ </button>
+ {!phone && (
+ <span className="ml-auto text-[11px] text-zinc-500" aria-hidden="true">
+ <kbd className="rounded border border-hairline-strong px-1">⌘ Enter</kbd> send · <kbd className="rounded border border-hairline-strong px-1">Esc</kbd> cancel
+ </span>
+ )}
+ </div>
+ </div>
+ );
+};
+
+const RoundBox: React.FC<{ item: ReviewItem }> = ({ item }) => {
+ const p = item.previous_round!;
+ const at = clock(p.sent_back_at);
+ const mine = [...item.criteria].reverse().find((c) => c.source === 'person_note' && c.round_added === item.round.n) ?? null;
+ const word = (s: InboxCriterion['status']) => (
+ <strong className={s === 'met' ? 'text-ok' : s === 'not_met' ? 'text-bad' : 'text-zinc-300'}>{CRITERION_WORD[s]}</strong>
+ );
+ return (
+ <section className="rounded-2xl border border-violet-400/40 bg-surface-raised px-4 py-3 space-y-2" aria-label={`Round ${item.round.n}, what changed since round ${item.round.n - 1}`} data-round-box>
+ <h3 className="flex items-center gap-1.5 text-body font-semibold text-zinc-100">
+ <RotateCcw size={14} aria-hidden="true" /> Round {item.round.n} · what changed since round {item.round.n - 1}
+ </h3>
+ <p className="text-meta text-zinc-400">You sent it back{at ? ` at ${at}` : ''}:</p>
+ <blockquote className="border-l-2 border-violet-400/60 bg-white/[0.03] px-3 py-2 text-body text-zinc-100 break-words whitespace-pre-wrap">{p.note}</blockquote>
+ <ul className="list-disc pl-5 space-y-0.5 text-meta text-zinc-300">
+ {mine && (
+ <li>
+ Your note is now criterion {mine.index}, and it’s {mine.status === 'met' ? word('met') : mine.status === 'not_met' ? word('not_met') : word(mine.status)}.
+ </li>
+ )}
+ {p.flips.map((f) => (
+ <li key={f.index}>
+ Criterion {f.index} went {word(f.from)} → {word(f.to)}.
+ </li>
+ ))}
+ {(p.diff.add > 0 || p.diff.del > 0 || p.diff.files > 0) && (
+ <li>
+ <span className="text-ok">+{p.diff.add}</span> <span className="text-bad">−{p.diff.del}</span> in {p.diff.files === 1 ? '1 file' : `${p.diff.files} files`} since round {item.round.n - 1}
+ {item.evidence.pr && (
+ <>
+ {' · '}
+ <a href={item.evidence.pr.url} target="_blank" rel="noopener noreferrer" className="text-violet-300 hover:underline rounded kw-focus">
+ see the changes
+ </a>
+ </>
+ )}
+ </li>
+ )}
+ {p.bot_summary && (
+ <li className="break-words">
+ {item.kwant_name}: {p.bot_summary}
+ </li>
+ )}
+ </ul>
+ </section>
+ );
+};
+
+const Fold: React.FC<{
+ id: string;
+ icon: LucideIcon;
+ label: string;
+ summary: string;
+ summaryBad?: boolean;
+ open: boolean;
+ onToggle: () => void;
+ children: React.ReactNode;
+}> = ({ id, icon: Icon, label, summary, summaryBad = false, open, onToggle, children }) => (
+ <div className="rounded-xl border border-hairline bg-surface-raised" data-fold={label}>
+ <button
+ type="button"
+ onClick={onToggle}
+ aria-expanded={open}
+ aria-controls={`${id}-body`}
+ className="flex w-full items-center gap-2.5 min-h-[40px] max-md:min-h-[44px] px-3 text-left rounded-xl kw-focus"
+ >
+ <Icon size={15} className="shrink-0 text-zinc-300" aria-hidden="true" />
+ <span className="shrink-0 text-body font-semibold text-zinc-100">{label}</span>
+ <span className={`min-w-0 flex-1 truncate text-meta ${summaryBad ? 'text-bad' : 'text-zinc-400'}`}>{summary}</span>
+ <ChevronDown size={16} className={`shrink-0 text-zinc-400 ${open ? 'rotate-180' : ''}`} aria-hidden="true" />
+ </button>
+ <div id={`${id}-body`} hidden={!open} className={open ? 'px-3 pb-3 kw-fade-in' : undefined}>
+ {open && children}
+ </div>
+ </div>
+);
+
+const CRIT_ICON = {
+ met: { icon: Check, cls: 'text-ok' },
+ not_met: { icon: X, cls: 'text-bad' },
+ not_checked: { icon: MinusCircle, cls: 'text-zinc-400' },
+ claim_only: { icon: MinusCircle, cls: 'text-zinc-400' },
+} as const;
+
+const CriterionRow: React.FC<{ c: InboxCriterion }> = ({ c }) => {
+ const s = CRIT_ICON[c.status];
+ const Icon = s.icon;
+ return (
+ <li className="flex items-start gap-2.5 px-3 py-2" data-criterion={c.index} data-status={c.status}>
+ <Icon size={14} className={`mt-1 shrink-0 ${s.cls}`} aria-hidden="true" />
+ <div className="min-w-0 flex-1">
+ <p className="text-body text-zinc-100 break-words">
+ {c.text}{' '}
+ {c.source === 'person_note' && (
+ <span className="kw-chip border-violet-400/40 bg-violet-500/15 text-violet-200 !py-0 align-middle text-[11px]">Your note · round {c.round_added}</span>
+ )}
+ {c.source === 'must_not_change' && <span className="kw-chip !py-0 align-middle text-[11px]">Must not change</span>}
+ </p>
+ {c.evidence ? (
+ <p className="text-meta text-zinc-400 break-words">
+ Evidence: <span className="text-zinc-200">{c.evidence.label}</span>
+ </p>
+ ) : null}
+ {c.note && <p className="text-meta text-zinc-400 break-words">{c.note}</p>}
+ </div>
+ <span className={`shrink-0 text-meta font-semibold ${s.cls}`}>{CRITERION_WORD[c.status]}</span>
+ </li>
+ );
+};
+
+const Evidence: React.FC<{ item: ReviewItem }> = ({ item }) => {
+ const e = item.evidence;
+ const [viewing, setViewing] = useState<number | null>(null);
+ const thumbs = useRef<(HTMLButtonElement | null)[]>([]);
+ if (!e.checks.length && !e.screenshots.length && !e.pr) return <p className="text-meta text-zinc-400">No evidence was attached.</p>;
+ const shot = viewing !== null ? e.screenshots[viewing] : null;
+ return (
+ <div className="space-y-3">
+ {e.checks.map((c, i) => (
+ <CheckOutput key={`${c.name}-${i}`} c={c} />
+ ))}
+ {e.screenshots.length > 0 && (
+ <ul className="flex flex-wrap gap-2" aria-label="Screenshots">
+ {e.screenshots.map((s, i) => (
+ <li key={`${s.url}-${i}`}>
+ <button
+ ref={(el) => (thumbs.current[i] = el)}
+ type="button"
+ onClick={() => setViewing(i)}
+ className="block overflow-hidden rounded-lg border border-hairline-strong bg-black/30 kw-focus"
+ aria-label={`Open screenshot ${s.caption || i + 1}`}
+ data-shot
+ >
+ <img src={s.url} alt="" width={120} height={72} className="block h-[72px] w-[120px] object-cover" loading="lazy" />
+ </button>
+ {s.caption && <p className="mt-0.5 w-[120px] truncate text-[11px] text-zinc-400">{s.caption}</p>}
+ </li>
+ ))}
+ </ul>
+ )}
+ {shot && (
+ <ImageViewer
+ file={{ id: `review-shot-${viewing}`, name: shot.caption || 'Screenshot', mime: 'image/png', size: 0 }}
+ src={shot.url}
+ sharedBy={item.kwant_name}
+ onClose={() => {
+ const i = viewing;
+ setViewing(null);
+ if (i !== null) thumbs.current[i]?.focus();
+ }}
+ />
+ )}
+ {e.pr && (
+ <a
+ href={e.pr.url}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="flex items-center gap-3 rounded-xl border border-hairline bg-white/[0.02] px-3 py-2 hover:bg-white/[0.05] kw-focus"
+ data-pr-card
+ >
+ <GitPullRequest size={16} className="shrink-0 text-violet-300" aria-hidden="true" />
+ <span className="min-w-0 flex-1">
+ <span className="block text-body font-semibold text-zinc-100 truncate">
+ {e.pr.repo} #{e.pr.number}
+ </span>
+ <span className="block text-meta text-zinc-400">
+ <span className="text-ok">+{e.pr.add}</span> <span className="text-bad">−{e.pr.del}</span> · {e.pr.files === 1 ? '1 file' : `${e.pr.files} files`}
+ {e.pr.ci ? ` · CI ${e.pr.ci}` : ''}
+ </span>
+ </span>
+ <ExternalLink size={14} className="shrink-0 text-zinc-400" aria-label="Opens in a new tab" />
+ </a>
+ )}
+ </div>
+ );
+};
+
+const CheckOutput: React.FC<{ c: ReviewItem['evidence']['checks'][number] }> = ({ c }) => {
+ const [all, setAll] = useState(false);
+ const t = tailLines(c.output_tail);
+ return (
+ <div className="space-y-1" data-check={c.name}>
+ <p className="flex flex-wrap items-center gap-x-2 text-meta">
+ {c.result === 'pass' ? <CheckCircle2 size={13} className="text-ok" aria-hidden="true" /> : <XCircle size={13} className="text-bad" aria-hidden="true" />}
+ <span className={`font-semibold ${c.result === 'pass' ? 'text-ok' : 'text-bad'}`}>{c.result === 'pass' ? 'Passed' : 'Failed'}</span>
+ <span className="font-semibold text-zinc-100">{c.name}</span>
+ <code className="font-mono text-zinc-300 break-all">{c.command}</code>
+ <span className="text-zinc-400">
+ · {c.summary} · ran by {c.ran_by === 'checker' ? 'the checker' : 'the author'}
+ </span>
+ </p>
+ {c.output_tail && (
+ <pre className="max-h-72 overflow-auto rounded-lg border border-hairline bg-black/30 px-3 py-2 font-mono text-[12px] leading-[18px] text-zinc-200 whitespace-pre-wrap break-words" tabIndex={0} aria-label={`${c.name} output`}>
+ {all ? c.output_tail : t.lines}
+ </pre>
+ )}
+ {t.more && (
+ <button type="button" onClick={() => setAll((x) => !x)} className="text-meta text-violet-300 hover:underline rounded kw-focus kw-hit" aria-expanded={all}>
+ {all ? 'Show the last 12 lines' : 'Show all'}
+ </button>
+ )}
+ </div>
+ );
+};
+
+/** A modal: a 560 px dialog on desktop, a bottom sheet with a grab handle on phone. Focus stays inside. */
+const Modal: React.FC<{ title: string; titleIcon?: React.ReactNode; phone: boolean; onClose: () => void; children: React.ReactNode; footer?: React.ReactNode }> = ({
+ title,
+ titleIcon,
+ phone,
+ onClose,
+ children,
+ footer,
+}) => {
+ const box = useRef<HTMLDivElement>(null);
+ const id = useId();
+ const onCloseRef = useRef(onClose);
+ onCloseRef.current = onClose;
+ useEffect(() => {
+ const el = box.current;
+ (el?.querySelector<HTMLElement>('[data-autofocus]') ?? el)?.focus();
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') {
+ e.preventDefault();
+ e.stopPropagation();
+ onCloseRef.current();
+ return;
+ }
+ if (e.key !== 'Tab' || !box.current) return;
+ const stops = Array.from(box.current.querySelectorAll<HTMLElement>('a[href], button:not([disabled]), textarea, input, [tabindex="0"]'));
+ if (!stops.length) return;
+ const first = stops[0];
+ const last = stops[stops.length - 1];
+ if (e.shiftKey && document.activeElement === first) {
+ e.preventDefault();
+ last.focus();
+ } else if (!e.shiftKey && document.activeElement === last) {
+ e.preventDefault();
+ first.focus();
+ }
+ };
+ document.addEventListener('keydown', onKey, true);
+ return () => document.removeEventListener('keydown', onKey, true);
+ }, []);
+ return (
+ <div className={`fixed inset-0 z-[150] flex bg-black/60 ${phone ? 'items-end' : 'items-center justify-center p-4'}`} onClick={(e) => e.target === e.currentTarget && onClose()}>
+ <div
+ ref={box}
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby={`${id}-t`}
+ tabIndex={-1}
+ className={`flex flex-col bg-surface-overlay border border-hairline-strong shadow-raised outline-none ${
+ phone ? 'w-full max-h-[92dvh] rounded-t-2xl' : 'w-full max-w-[560px] max-h-[88vh] rounded-2xl'
+ }`}
+ data-review-dialog
+ >
+ {phone && <div className="mx-auto mt-2 h-1 w-10 shrink-0 rounded-full bg-zinc-600" aria-hidden="true" />}
+ <div className="flex items-center gap-2 px-4 pt-3 pb-2">
+ {titleIcon}
+ <h2 id={`${id}-t`} className="min-w-0 flex-1 text-[15px] font-semibold text-zinc-50 break-words">
+ {title}
+ </h2>
+ {!phone && (
+ <button type="button" onClick={onClose} aria-label="Close" className="inline-flex h-8 w-8 items-center justify-center rounded-lg text-zinc-400 hover:bg-white/[0.06] kw-focus">
+ <X size={16} aria-hidden="true" />
+ </button>
+ )}
+ </div>
+ <div className="min-h-0 flex-1 overflow-y-auto px-4 pb-3">{children}</div>
+ {footer && <div className="border-t border-hairline px-4 py-3" style={phone ? { paddingBottom: 'calc(env(safe-area-inset-bottom, 0px) + 0.75rem)' } : undefined}>{footer}</div>}
+ </div>
+ </div>
+ );
+};
+
+const Sheet: React.FC<{ title: string; onClose: () => void; children: React.ReactNode }> = ({ title, onClose, children }) => (
+ <Modal title={title} titleIcon={<CornerUpLeft size={15} aria-hidden="true" />} phone onClose={onClose}>
+ {children}
+ </Modal>
+);
+
+/** Roll back (Mira §8): the before-the-run preview, Files, Not undone, the safety line, then restore or fork. */
+const RollBackDialog: React.FC<{
+ item: ReviewItem;
+ api: ReviewItemApi;
+ phone: boolean;
+ /** Undo a roll back: preview and restore this safety checkpoint instead. */
+ undoFrom?: string;
+ openHeld: number;
+ denyAllOpen: () => Promise<string | null>;
+ onClose: () => void;
+ onDone: (r: ReviewDone, extra: { undo?: string | null; copy?: string | null }) => void;
+}> = ({ item, api, phone, undoFrom, openHeld, denyAllOpen, onClose, onDone }) => {
+ const [cp, setCp] = useState<Checkpoint | null>(null);
+ const [preview, setPreview] = useState<RestorePreview | null>(null);
+ const [err, setErr] = useState<string | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [noCheckpoint, setNoCheckpoint] = useState(false);
+ const keys = useRef<Record<string, string>>({});
+ const inFlight = useRef(false);
+
+ const load = useCallback(
+ async (keepErr = false) => {
+ if (!keepErr) setErr(null);
+ setPreview(null);
+ try {
+ const list = await api.checkpoints(item.task_id);
+ const pick = undoFrom
+ ? list.find((c) => c.id === undoFrom) ?? null
+ : [...list].reverse().find((c) => c.kind === 'before_run' && c.restorable) ?? null;
+ if (!pick) {
+ setNoCheckpoint(true);
+ return;
+ }
+ setCp(pick);
+ setPreview(await api.restorePreview(item.task_id, pick.id));
+ } catch (e) {
+ setErr(restoreErrorText(e));
+ }
+ },
+ [api, item.task_id, undoFrom],
+ );
+ useEffect(() => {
+ void load();
+ }, [load]);
+
+ const fork = preview?.via === 'fork';
+ const run = async () => {
+ if (!cp || !preview || inFlight.current) return;
+ inFlight.current = true;
+ setBusy(true);
+ setErr(null);
+ try {
+ if (openHeld > 0 && !undoFrom) {
+ const e = await denyAllOpen();
+ if (e) {
+ setErr(e.replace('nothing was sent', 'nothing was rolled back'));
+ return;
+ }
+ }
+ const k = `${cp.id}|${preview.preview_sha256}|${fork ? 'fork' : 'restore'}`;
+ keys.current[k] ??= newIdempotencyKey();
+ if (fork) {
+ const t = await api.forkFromCheckpoint(item.task_id, { reason: `Rolled back after approval: ${item.title}`.slice(0, 500), from_checkpoint: cp.id, preview_sha256: preview.preview_sha256 }, keys.current[k]);
+ const stepped = t.stepped_down !== undefined ? t.stepped_down : preview.step_down ?? null;
+ onDone({ kind: 'rolled_back', text: rolledBackForkText(item.kwant_name, stepped), task_id: item.task_id, copy_task_id: t.id }, { copy: t.id });
+ } else {
+ const r = await api.restore(item.task_id, cp.id, { preview_sha256: preview.preview_sha256, rerun: false }, keys.current[k]);
+ const text = undoFrom ? `Roll back undone. ${rolledBackText(r).replace(/^Rolled back:?\s*/, '')}` : rolledBackText(r);
+ onDone({ kind: 'rolled_back', text, task_id: item.task_id, undo_checkpoint_id: undoFrom ? null : r.before_restore_checkpoint_id }, { undo: undoFrom ? null : r.before_restore_checkpoint_id });
+ }
+ } catch (e) {
+ setErr(restoreErrorText(e));
+ if (e instanceof MissionError && e.code === 'stale_preview') void load(true);
+ } finally {
+ inFlight.current = false;
+ setBusy(false);
+ }
+ };
+
+ const title = undoFrom ? `Undo the roll back of “${item.title}”?` : `Roll back “${item.title}”?`;
+ const nu = preview ? notUndoneTitle(preview) : null;
+ const step = preview ? stepDownText(preview.step_down ?? null) : null;
+ const cpTime = clock(cp?.created_at);
+ const approvedAt = clock(preview?.verified_at);
+ const canRun = !!preview && !preview.refused && preview.changes.length > 0 && !busy;
+
+ const footer = (
+ <div className={phone ? 'grid grid-cols-2 gap-2' : 'flex justify-end gap-2'}>
+ <button type="button" onClick={onClose} className={btnQuiet} data-autofocus data-keep-work>
+ {phone ? 'Cancel' : 'Keep the work'}
+ </button>
+ <button type="button" onClick={() => void run()} disabled={!canRun} className={btnRoseFill} data-rollback-confirm>
+ {busy ? <Loader2 size={14} className={spin} aria-hidden="true" /> : <RotateCcw size={14} aria-hidden="true" />}
+ {preview ? (undoFrom ? 'Undo the roll back' : rollBackLabel(preview)) : 'Roll back'}
+ </button>
+ </div>
+ );
+
+ return (
+ <Modal title={title} titleIcon={<RotateCcw size={16} className="text-zinc-200" aria-hidden="true" />} phone={phone} onClose={onClose} footer={footer}>
+ <div className="space-y-3 text-body" data-rollback-body>
+ {err && (
+ <p className="flex items-start gap-1.5 rounded-xl border border-rose-400/30 bg-rose-500/[0.08] px-3 py-2 text-rose-200" role="alert" data-rollback-error>
+ <AlertTriangle size={14} className="mt-1 shrink-0" aria-hidden="true" /> {err}
+ </p>
+ )}
+ {noCheckpoint && <p className="text-zinc-300">There’s no checkpoint from before the run, so this task can’t be rolled back here.</p>}
+ {!preview && !noCheckpoint && !err && (
+ <p className="flex items-center gap-2 text-zinc-400" data-rollback-loading>
+ <Loader2 size={14} className={spin} aria-hidden="true" /> Loading what changes…
+ </p>
+ )}
+ {preview && (
+ <>
+ {preview.refused && (
+ <p className="flex items-start gap-1.5 rounded-xl border border-rose-400/30 bg-rose-500/[0.08] px-3 py-2 text-rose-200" data-rollback-refused={preview.refused}>
+ <AlertTriangle size={14} className="mt-1 shrink-0" aria-hidden="true" />
+ {preview.refused === 'running' ? 'A bot is working on it now. Roll back once it stops.' : restoreErrorText(new MissionError('', 409, preview.refused))}
+ </p>
+ )}
+ {fork ? (
+ <p className="text-zinc-200" data-after-approval>
+ This was approved{approvedAt ? <> at <strong>{approvedAt}</strong></> : null}. The approved record stays. A copy of the task is made from{' '}
+ <strong>before the run{cpTime ? ` · ${cpTime}` : ''}</strong> with the files put back, and the copy waits on hold until you press Run.
+ </p>
+ ) : undoFrom ? (
+ <p className="text-zinc-300">Puts the files back to how they were just before the roll back (the safety checkpoint{cpTime ? ` · ${cpTime}` : ''}).</p>
+ ) : (
+ <p className="text-zinc-300">
+ Puts this task’s files back to how they were before {item.kwant_name} started (checkpoint <strong className="text-zinc-100">before the run{cpTime ? ` · ${cpTime}` : ''}</strong>). Only files
+ this task changed are touched.
+ </p>
+ )}
+ {step && (
+ <p className="rounded-xl border border-amber-500/40 px-3 py-2 text-zinc-100" data-step-down>
+ {item.kwant_name} moves down one Flight School tier for <strong>{step.cls}</strong>: <strong>{step.from} → {step.to}</strong>.
+ </p>
+ )}
+ <section aria-labelledby="rb-files" className="space-y-1.5">
+ <h3 id="rb-files" className="flex items-center gap-1.5 text-meta font-semibold uppercase tracking-wide text-zinc-300">
+ <FolderOpen size={13} aria-hidden="true" /> Files{' '}
+ <span className="font-normal normal-case tracking-normal text-zinc-500">
+ {preview.changes.length} {preview.changes.length === 1 ? 'change' : 'changes'}
+ {preview.conflicts.length + preview.skipped.length > 0 ? ` · ${preview.conflicts.length + preview.skipped.length} skipped` : ''}
+ </span>
+ </h3>
+ {preview.changes.length + preview.conflicts.length + preview.skipped.length > 0 ? (
+ <ul className="rounded-xl border border-hairline divide-y divide-hairline text-meta">
+ {preview.changes.map((c) => (
+ <li key={c.path} className="flex flex-wrap items-baseline gap-x-3 gap-y-0.5 px-3 py-1.5" data-rb-change={c.action}>
+ <span className={`w-24 shrink-0 font-semibold ${c.action === 'delete' ? 'text-bad' : 'text-zinc-200'}`}>{RESTORE_ACTION_LABELS[c.action]}</span>
+ <span className="min-w-0 flex-1 break-all font-mono text-zinc-100">{c.path}</span>
+ </li>
+ ))}
+ {preview.conflicts.map((c) => (
+ <li key={`c-${c.path}`} className="flex flex-wrap items-baseline gap-x-3 gap-y-0.5 px-3 py-1.5" data-rb-skipped>
+ <span className="w-24 shrink-0 font-semibold text-warn">Skipped</span>
+ <span className="min-w-0 flex-1 break-all font-mono text-zinc-100">{c.path}</span>
+ <span className="text-zinc-400">{conflictText(c).toLowerCase()}</span>
+ </li>
+ ))}
+ {preview.skipped.map((s) => (
+ <li key={`s-${s.path}`} className="flex flex-wrap items-baseline gap-x-3 gap-y-0.5 px-3 py-1.5" data-rb-skipped>
+ <span className="w-24 shrink-0 font-semibold text-warn">Skipped</span>
+ <span className="min-w-0 flex-1 break-all font-mono text-zinc-100">{s.path}</span>
+ <span className="text-zinc-400">{s.why}</span>
+ </li>
+ ))}
+ </ul>
+ ) : (
+ <p className="text-meta text-zinc-400">No files need putting back.</p>
+ )}
+ </section>
+ {nu ? (
+ <section className="rounded-xl border border-rose-400/35 bg-rose-500/[0.07] px-3 py-2 space-y-1" data-not-undone={preview.effects_known ? 'known' : 'unknown'}>
+ <p className="flex items-center gap-1.5 font-semibold text-rose-100">
+ <AlertTriangle size={14} aria-hidden="true" /> {nu}
+ </p>
+ {preview.effects_known ? (
+ <>
+ <p className="text-meta text-rose-100/90">{preview.not_undone_note || 'These can’t be undone from here. Check them yourself.'}</p>
+ <ul className="list-disc pl-5 text-meta text-zinc-200 space-y-0.5">
+ {preview.external_not_undone.map((x, i) => (
+ <li key={`${x.at}-${i}`} className="break-words">
+ <span className="font-mono">{x.summary}</span>
+ {clock(x.at) ? <span className="text-zinc-400"> · {clock(x.at)}</span> : null}
+ </li>
+ ))}
+ </ul>
+ </>
+ ) : (
+ <p className="text-meta text-rose-100/90">{NOT_UNDONE_UNKNOWN}</p>
+ )}
+ </section>
+ ) : (
+ <p className="flex items-center gap-1.5 rounded-xl border border-hairline bg-white/[0.02] px-3 py-2 text-meta text-zinc-400" data-not-undone="none">
+ <ShieldCheck size={13} aria-hidden="true" /> Nothing left this computer. Everything this task did is undone.
+ </p>
+ )}
+ <p className="flex items-start gap-1.5 text-meta text-zinc-400">
+ <ShieldCheck size={13} className="mt-0.5 shrink-0" aria-hidden="true" />
+ <span>
+ A safety checkpoint is taken first, so you can undo this roll back.
+ {openHeld > 0 && !undoFrom ? (openHeld === 1 ? ' The held action is denied first.' : ' The held actions are denied first.') : ''} Afterwards the{' '}
+ {fork ? 'copy' : 'task'} waits on hold until you press Run.
+ </span>
+ </p>
+ </>
+ )}
+ </div>
+ </Modal>
+ );
+};
diff --git a/frontend/src/inboxStore.ts b/frontend/src/inboxStore.ts
index d5f3bfcc..0aa143ef 100644
--- a/frontend/src/inboxStore.ts
+++ b/frontend/src/inboxStore.ts
@@ -7,7 +7,7 @@
import { useSyncExternalStore } from 'react';
import { AwayItem, AwayResponse, AwaySection, awayApi, sortAwaySection } from './away';
-import { InboxError, InboxGroup, InboxItem, InboxResponse, ReviewItem, cmpSortKey, inboxApi, isReview } from './api/inbox';
+import { HeldStatus, InboxError, InboxGroup, InboxItem, InboxResponse, ReviewItem, cmpSortKey, inboxApi, isBeingChecked, isReview } from './api/inbox';
export type Crumb = 'board' | 'dev' | null;
@@ -226,7 +226,10 @@ export function reviewForTask(taskId: string): ReviewItem | null {
export function batchItems(data: InboxResponse | null): InboxItem[] {
if (!data?.batch) return [];
const pool = [...(data.batch_items ?? []), ...data.items];
- return data.batch.ids.map((id) => pool.find((i) => i.id === id)).filter((i): i is InboxItem => !!i);
+ return data.batch.ids
+ .map((id) => pool.find((i) => i.id === id))
+ .filter((i): i is InboxItem => !!i)
+ .filter((i) => !isReview(i) || (i.verdict.result !== 'none' && !isBeingChecked(i))); // no verdict, no batch (D7), even if the server sent it
}
// ---- Approve ----
@@ -236,6 +239,9 @@ function staleNote(paths: string[]): string {
return `${paths[0]}${paths.length > 1 ? ` and ${paths.length - 1} more` : ''} changed after its check`;
}
+/** The status line after a stale approve: no paths, the row says what changed (V1-4). */
+export const staleStatus = (title: string): string => `Couldn’t approve “${title}”. It’s back in Failed or stuck, and nothing was approved.`;
+
/** Puts an item that failed freshness into Failed or stuck, locally, until the next load agrees. */
export function comeBack(item: InboxItem, paths: string[]) {
const back: InboxItem = {
@@ -250,6 +256,17 @@ export function comeBack(item: InboxItem, paths: string[]) {
set((s) => (s.data ? { data: { ...s.data, items: [...s.data.items.filter((i) => i.id !== item.id), back].sort(cmpSortKey) } } : {}));
}
+/**
+ * V1-3: a held action the pane just denied or allowed, written into the list's copy of the item so the row's
+ * "N held" drops at once instead of on the next load. The next load replaces it with the server's word.
+ */
+export function markHeld(itemId: string, approvalId: string, status: Exclude<HeldStatus, 'pending'>) {
+ const at = new Date().toISOString();
+ const patch = (i: InboxItem): InboxItem =>
+ i.id === itemId && isReview(i) ? { ...i, held_actions: i.held_actions.map((h) => (h.approval_id === approvalId ? { ...h, status, resolved_at: h.resolved_at ?? at } : h)) } : i;
+ set((s) => (s.data ? { data: { ...s.data, items: s.data.items.map(patch), batch_items: s.data.batch_items?.map(patch) } } : {}));
+}
+
function dropItem(id: string) {
set((s) => {
if (!s.data) return {};
@@ -280,7 +297,8 @@ export async function approveOne(item: InboxItem): Promise<void> {
} catch (e) {
if (e instanceof InboxError && e.stale) {
comeBack(item, e.paths);
- set({ busy: null, notice: { text: `Couldn’t approve: ${title}. ${staleNote(e.paths)}, so nothing was approved.`, tone: 'error' } });
+ // V1-4: what changed is said once, on the item's own row in Failed or stuck; the status line doesn't repeat it.
+ set({ busy: null, notice: { text: staleStatus(title), tone: 'error' } });
} else {
const why = e instanceof Error ? e.message : 'Something went wrong';
set({ busy: null, notice: { text: `Couldn’t approve “${title}”. ${why}. Nothing was approved.`, tone: 'error' } });
@@ -346,7 +364,7 @@ async function runBatch(items: ReviewItem[]) {
if (e instanceof InboxError && e.stale) {
comeBack(item, e.paths);
patchRow(i, { status: 'came_back', note: `${staleNote(e.paths)} · back in Failed or stuck` });
- announce(`“${item.title}” came back: ${staleNote(e.paths)}.`);
+ announce(`“${item.title}” came back to Failed or stuck. Nothing was approved.`);
continue;
}
const status = e instanceof InboxError ? e.status : 0;
diff --git a/frontend/src/missions.ts b/frontend/src/missions.ts
index fb6a4a16..dc948344 100644
--- a/frontend/src/missions.ts
+++ b/frontend/src/missions.ts
@@ -271,6 +271,8 @@ export interface RestorePreview {
via?: 'fork' | 'restore';
/** What the roll back would do to the owner's tier, or null (nothing written by the preview). */
step_down?: { kwant_id: string; class: string; from: string; to: string } | null;
+ /** When the task was approved, when the server sends it (roll back after approval). */
+ verified_at?: string | null;
}
/** `POST /api/tasks/:id/checkpoints/:cid/restore` (person-only; `Idempotency-Key` header required). */
@@ -1829,6 +1831,17 @@ export const missionsApi = {
call<ResolveFlagResult>(`/api/tasks/${enc(taskId)}/flags/${enc(flagId)}/resolve`, 'POST', note ? { resolution, note } : { resolution }, { 'Idempotency-Key': key }),
/** Copy a task to redo it; the same key returns the same copy. */
fork: (taskId: string, reason: string, key: string) => call<Task>(`/api/tasks/${enc(taskId)}/fork`, 'POST', { reason }, { 'Idempotency-Key': key }),
+ /**
+ * 0.9 D2: roll back after approval. A copy of the task from `from_checkpoint`, with the original's
+ * task-owned paths put back first; it waits on hold until Run. 409 `stale_preview` on a changed preview.
+ */
+ forkFromCheckpoint: (taskId: string, body: { reason: string; from_checkpoint: string; preview_sha256: string }, key: string) =>
+ call<Task & { restore?: RestoreResult | null; stepped_down?: { kwant_id: string; class: string; from: string; to: string } | null }>(
+ `/api/tasks/${enc(taskId)}/fork`,
+ 'POST',
+ body,
+ { 'Idempotency-Key': key },
+ ),
/** Let a task a restore held run again (person only). */
/** Take a held task off hold. The same key replays the first 200, so a double press is a success. */
runHeld: (id: string, key: string) => call<{ task: Task }>(`/api/tasks/${enc(id)}/run`, 'POST', {}, { 'Idempotency-Key': key }).then((r) => r.task),
diff --git a/frontend/src/reviewItem.ts b/frontend/src/reviewItem.ts
new file mode 100644
index 00000000..d31dcdfb
--- /dev/null
+++ b/frontend/src/reviewItem.ts
@@ -0,0 +1,183 @@
+// 0.9.0 V1: the words and small rules behind ReviewItemView (Mira, release-090/designs/v1-review-inbox.md
+// §3-§9; Ada's D2/D3). Pure functions, so tests can pin the copy. Nothing here computes a new number:
+// every count shown comes from the server (criteria_summary, decisions.total, preview rows) or is the
+// length of a list the server sent.
+
+import type { CriterionStatus, InboxItem, ReviewItem, VerdictResult } from './api/inbox';
+import { VERDICT_WORD } from './api/inbox';
+import type { RestorePreview, RestoreResult } from './missions';
+import { TIER_LABELS } from './flightSchool';
+
+/** What the item view hands back when an action is done (Pixel's pane removes the item, opens the next). */
+export interface ReviewDone {
+ kind: 'approved' | 'sent_back' | 'rolled_back' | 'stale';
+ /** The status-line sentence, already worded. */
+ text: string;
+ task_id: string;
+ /** rolled_back by restore: the safety checkpoint, for "Undo the roll back". */
+ undo_checkpoint_id?: string | null;
+ /** rolled_back after approval: the copy waiting on hold. */
+ copy_task_id?: string | null;
+ /** stale: the paths that changed after the check. */
+ paths?: string[];
+}
+
+export type ReviewEntry = 'inbox' | 'board' | 'dev';
+
+const isStr = (v: unknown): v is string => typeof v === 'string';
+const isNum = (v: unknown): v is number => typeof v === 'number' && Number.isFinite(v);
+const isArr = Array.isArray;
+
+/**
+ * Whether the item has every field the view draws. Anything else falls back to the plain card (title and
+ * summary as text), never a half-drawn verdict.
+ */
+export function validReviewItem(i: InboxItem | null | undefined): i is ReviewItem {
+ if (!i || i.kind !== 'review' || !isStr(i.task_id) || !i.task_id || !isStr(i.title)) return false;
+ const v = i.verdict;
+ if (!v || !(v.result in VERDICT_WORD) || !isStr(v.line)) return false;
+ if (!i.round || !isNum(i.round.n) || !isNum(i.round.max)) return false;
+ if (!i.criteria_summary || !isNum(i.criteria_summary.met) || !isNum(i.criteria_summary.total)) return false;
+ if (!i.decisions || !isNum(i.decisions.total) || !isArr(i.decisions.top)) return false;
+ if (!i.evidence || !isArr(i.evidence.checks) || !isArr(i.evidence.screenshots)) return false;
+ return isArr(i.criteria) && isArr(i.couldnt_verify) && isArr(i.held_actions) && !!i.risk;
+}
+
+/** "14:41" in the person's own clock, or null for a missing or bad time. */
+export function clock(iso: string | null | undefined): string | null {
+ if (!iso) return null;
+ const d = new Date(iso);
+ if (Number.isNaN(d.getTime())) return null;
+ return d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false });
+}
+
+/** "Needs you · medium confidence"'s second half, or null (no verdict, or no confidence). */
+export function confidenceText(v: ReviewItem['verdict']): string | null {
+ if (v.result === 'none' || !v.confidence) return null;
+ return `${v.confidence} confidence`;
+}
+
+/**
+ * The verdict box's meta line (Mira §3.2): who checked it, on what, when, and how many steps. Null with
+ * no checker (Not checked yet).
+ */
+export function checkerMeta(i: Pick<ReviewItem, 'verdict' | 'risk'>): string | null {
+ const v = i.verdict;
+ if (!v.checker || v.result === 'none') return null;
+ const at = clock(v.checked_at);
+ const parts: string[] = [];
+ if (v.checker.tier_note === 'different_tier') parts.push(`Checked on a different tier of ${v.checker.engine} (no other engine set up)`);
+ else parts.push(`Checked by fresh eyes on ${v.checker.engine}${at ? ` at ${at}` : ''}`);
+ if (isNum(v.steps_run) && isNum(v.steps_total) && v.steps_total > 0) {
+ if (v.steps_run === v.steps_total) parts.push(i.risk.level === 'high' ? `all ${v.steps_total} steps, because it’s high risk` : `all ${v.steps_total} steps`);
+ else parts.push(`${v.steps_run} of ${v.steps_total} steps`);
+ }
+ return parts.join(' · ');
+}
+
+export const RISK_WORD: Record<'low' | 'medium' | 'high', string> = { low: 'Low risk', medium: 'Medium risk', high: 'High risk' };
+
+export const CRITERION_WORD: Record<CriterionStatus, string> = { met: 'Met', not_met: 'Not met', not_checked: 'Not checked', claim_only: 'Claim only' };
+
+/** "3 of 4 met · 1 not met · 1 not checked", from the server's summary. */
+export function criteriaSummaryText(s: ReviewItem['criteria_summary']): string {
+ const parts = [`${s.met} of ${s.total} met`];
+ if (s.not_met) parts.push(`${s.not_met} not met`);
+ if (s.not_checked) parts.push(`${s.not_checked} not checked`);
+ return parts.join(' · ');
+}
+
+/** "2 for you, of 4". */
+export const decisionsSummaryText = (d: ReviewItem['decisions']): string => `${d.top.length} for you, of ${d.total}`;
+
+const plural = (n: number, one: string, many: string) => `${n} ${n === 1 ? one : many}`;
+
+/** "3 checks · 1 screenshot · shop #512". */
+export function evidenceSummaryText(e: ReviewItem['evidence']): string {
+ const parts: string[] = [];
+ if (e.checks.length) parts.push(plural(e.checks.length, 'check', 'checks'));
+ if (e.screenshots.length) parts.push(plural(e.screenshots.length, 'screenshot', 'screenshots'));
+ if (e.pr) parts.push(`${e.pr.repo} #${e.pr.number}`);
+ return parts.length ? parts.join(' · ') : 'Nothing attached';
+}
+
+/** The last `n` lines of a check's output, and whether there was more. */
+export function tailLines(out: string, n = 12): { lines: string; more: boolean } {
+ const all = out.replace(/\s+$/, '').split('\n');
+ return all.length > n ? { lines: all.slice(-n).join('\n'), more: true } : { lines: all.join('\n'), more: false };
+}
+
+/**
+ * The criterion number a send-back note becomes ("Becomes criterion 5"): one after the highest index the
+ * server sent.
+ */
+export const nextCriterionIndex = (criteria: ReviewItem['criteria']): number => criteria.reduce((m, c) => Math.max(m, c.index), 0) + 1;
+
+/** "Change: {question} → ", the Send back prefill from a decision's Change button. */
+export const changePrefill = (question: string): string => `Change: ${question} → `;
+
+export const lastRound = (r: ReviewItem['round']): boolean => r.n >= r.max;
+
+/** The Send back panel's "what happens" list (Mira §6), in order. */
+export function sendBackSteps(i: Pick<ReviewItem, 'kwant_name' | 'round' | 'held_actions' | 'evidence'>, openHeld: number): string[] {
+ const out: string[] = [];
+ if (openHeld > 0) out.push(heldDeniedFirst(i, openHeld));
+ out.push(`${i.kwant_name} starts round ${i.round.n + 1} with your note, the checker’s findings and the work so far.`);
+ out.push('The checker then checks everything again, including what passed.');
+ out.push(`This is round ${i.round.n} of ${i.round.max}. After round ${i.round.max} it comes back to you, whatever the verdict.`);
+ return out;
+}
+
+function heldDeniedFirst(i: Pick<ReviewItem, 'held_actions' | 'evidence'>, openHeld: number): string {
+ const h = i.held_actions.find((x) => x.status === 'pending');
+ if (openHeld === 1 && h?.gate === 'merge' && i.evidence.pr) return `The held merge of #${i.evidence.pr.number} is denied first, so nothing runs.`;
+ return openHeld === 1 ? 'The held action is denied first, so nothing runs.' : 'The held actions are denied first, so nothing runs.';
+}
+
+export const GATE_TEXT: Record<'merge' | 'payment' | 'approval', string> = {
+ merge: 'held at the merge gate',
+ payment: 'payment floor',
+ approval: 'held for your approval',
+};
+
+// ---- Roll back ----
+
+/** "Not undone: …" heading for the roll back dialog, or null when nothing left the computer and kwant knows it. */
+export function notUndoneTitle(p: Pick<RestorePreview, 'effects_known' | 'external_not_undone'>): string | null {
+ if (!p.effects_known) return 'Not undone: unknown';
+ const n = p.external_not_undone.length;
+ if (!n) return null;
+ return `Not undone: ${n === 1 ? '1 thing' : `${n} things`} already left this computer`;
+}
+
+export const NOT_UNDONE_UNKNOWN =
+ 'Files changed, but no logged call explains the change, so something may have left this computer. Check the chat before you rely on this roll back.';
+
+/** "Roll back 3 files" (the preview's own change rows). */
+export const rollBackLabel = (p: Pick<RestorePreview, 'changes'>): string => (p.changes.length === 1 ? 'Roll back 1 file' : `Roll back ${p.changes.length} files`);
+
+/** The step-down line after approval, or null. */
+export function stepDownText(s: RestorePreview['step_down']): { cls: string; from: string; to: string } | null {
+ if (!s) return null;
+ const word = (t: string) => (TIER_LABELS as Record<string, string>)[t] ?? t;
+ return { cls: s.class, from: word(s.from), to: word(s.to) };
+}
+
+/** "Rolled back: 2 files put back, 1 removed. The task is on hold until you press Run." */
+export function rolledBackText(r: Pick<RestoreResult, 'restored' | 'deleted' | 'failed' | 'task'>): string {
+ const parts: string[] = [];
+ if (r.restored.length) parts.push(`${plural(r.restored.length, 'file', 'files')} put back`);
+ if (r.deleted.length) parts.push(`${r.deleted.length} removed`);
+ const what = parts.length ? `Rolled back: ${parts.join(', ')}.` : 'Rolled back. No files needed changing.';
+ const failed = r.failed.length ? ` ${plural(r.failed.length, 'file', 'files')} couldn’t be written.` : '';
+ const held = r.task?.held_at ? ' The task is on hold until you press Run.' : '';
+ return `${what}${failed}${held}`;
+}
+
+/** After approval: "Rolled back. The copy is on hold until you press Run. Lin is now at Sandbox for auth changes." */
+export function rolledBackForkText(bot: string, stepped: RestorePreview['step_down']): string {
+ const s = stepDownText(stepped ?? null);
+ return `Rolled back. The copy is on hold until you press Run.${s ? ` ${bot} is now at ${s.to} for ${s.cls}.` : ''}`;
+}
+
+export const verdictWord = (r: VerdictResult): string => VERDICT_WORD[r];
diff --git a/frontend/tests/inboxV1.test.mjs b/frontend/tests/inboxV1.test.mjs
index b267d805..3f86dafa 100644
--- a/frontend/tests/inboxV1.test.mjs
+++ b/frontend/tests/inboxV1.test.mjs
@@ -14,7 +14,7 @@ const m = await loadBundled(`
export { default as React } from 'react';
export { renderToStaticMarkup } from 'react-dom/server.browser';
export * as store from './src/inboxStore';
- export { inboxApi, InboxError, inboxBadge, verdictShort, INBOX_FIXTURE, INBOX_FIXTURE_EMPTY, FIXTURE_BATCH } from './src/api/inbox';
+ export { inboxApi, InboxError, inboxBadge, verdictShort, cmpSortKey, INBOX_FIXTURE, INBOX_FIXTURE_EMPTY, FIXTURE_BATCH, FIXTURE_REVIEW_ITEMS } from './src/api/inbox';
export { attentionRows, attentionRank, PINNED_RANK, rollupLabel } from './src/chatsTab';
export { InboxNew } from './src/components/InboxNew';
export { TaskCard } from './src/components/MissionBoardView';
@@ -147,3 +147,93 @@ test('Mission board card in Review: one "Review" button (verdict under the title
assert.equal(old.querySelector('[data-card-review]'), null, 'without the Inbox the old buttons stay');
assert.ok(old.querySelector('[data-card-action="verify"]'));
});
+
+// ---- D7 Being checked, V1-3 held count, V1-4 stale notice once ----
+
+const withItems = (...extra) => {
+ const data = clone(m.INBOX_FIXTURE);
+ data.items = [...data.items.filter((i) => !extra.some((e) => e.id === i.id)), ...clone(extra)].sort(m.cmpSortKey);
+ return seed(data);
+};
+const rowOf = (d, id) => d.querySelector(`[data-row="${id}"]`);
+const wide = () => doc(html(React.createElement(m.InboxNew, { noLoad: true, wide: true, now: Date.parse(m.INBOX_FIXTURE.now) })));
+
+test('D7: the list row says "Being checked" while the verifier holds it, "Not checked yet" without a hold', () => {
+ const FX = m.FIXTURE_REVIEW_ITEMS;
+ withItems(FX.beingChecked, FX.notChecked);
+ const d = wide();
+ const being = rowOf(d, FX.beingChecked.id);
+ assert.equal(being.querySelector('[data-verdict-word]').getAttribute('data-verdict-word'), 'being_checked');
+ assert.match(being.textContent, /Being checked/);
+ assert.doesNotMatch(being.textContent, /Not checked yet/);
+ assert.match(rowOf(d, FX.notChecked.id).textContent, /Not checked yet/);
+ assert.equal(being.querySelector('[data-inline-approve]'), null);
+});
+
+test('D7: inline Approve and Approve all leave a Being checked item out, even if the server offers it', async () => {
+ const FX = m.FIXTURE_REVIEW_ITEMS;
+ const offered = { ...FX.beingChecked, one_tap: true, batchable: true };
+ const data = withItems(offered);
+ data.batch = { ...data.batch, ids: [...data.batch.ids.slice(0, 2), offered.id, ...data.batch.ids.slice(2)] };
+ s.inboxStore.patch({ data });
+ assert.equal(rowOf(wide(), offered.id).querySelector('[data-inline-approve]'), null, 'no inline Approve');
+ assert.equal(s.batchItems(data).some((i) => i.id === offered.id), false);
+ const calls = [];
+ inboxApi.verify = async (taskId) => calls.push(taskId);
+ await s.approveAll();
+ assert.deepEqual(calls, m.FIXTURE_BATCH.map((i) => i.task_id), 'only the five checked items');
+ assert.equal(calls.includes(offered.task_id), false);
+});
+
+test('V1-3: denying every held action drops "N held" from the row at once, without a refresh', () => {
+ const FX = m.FIXTURE_REVIEW_ITEMS;
+ const two = {
+ ...FX.passHeld,
+ held_actions: [FX.passHeld.held_actions[0], { ...FX.passHeld.held_actions[0], approval_id: 'a-refund-2', summary: 'create second refund' }],
+ };
+ withItems(two);
+ assert.equal(rowOf(wide(), two.id).querySelector('[data-held-count]').textContent, '2 held');
+ s.markHeld(two.id, 'a-refund', 'denied');
+ assert.equal(rowOf(wide(), two.id).querySelector('[data-held-count]').textContent, '1 held');
+ s.markHeld(two.id, 'a-refund-2', 'denied');
+ assert.equal(rowOf(wide(), two.id).querySelector('[data-held-count]'), null);
+ assert.doesNotMatch(rowOf(wide(), two.id).textContent, /held/);
+ // Resolved ones the server still lists (heldDenied: denied + expired) are not counted either.
+ withItems(FX.heldDenied);
+ assert.equal(rowOf(wide(), FX.heldDenied.id).querySelector('[data-held-count]'), null);
+});
+
+test('V1-4: a stale inline Approve says "changed after its check" once, on the row, not again in the status line', async () => {
+ const data = seed();
+ const one = data.items.find((i) => i.kind === 'review' && i.one_tap);
+ inboxApi.verify = async () => {
+ throw new InboxError(409, 'stale', 'stale', ['README.md']);
+ };
+ s.select(null);
+ await s.approveOne(one);
+ const st = s.inboxStore.get();
+ assert.doesNotMatch(st.notice.text, /changed after its check/);
+ assert.match(st.notice.text, /back in Failed or stuck, and nothing was approved/);
+ s.select(null);
+ const d = wide();
+ const row = rowOf(d, one.id);
+ assert.equal(row.getAttribute('data-group'), 'failed_or_stuck');
+ assert.match(row.textContent, /README\.md changed after its check/);
+ assert.doesNotMatch(d.querySelector('[data-inbox-status]').textContent, /changed after its check/);
+});
+
+test('V1-4: the batch row of an item that came back shows "Came back"', async () => {
+ seed();
+ inboxApi.verify = async (taskId) => {
+ if (taskId === m.FIXTURE_BATCH[1].task_id) throw new InboxError(409, 'stale', 'stale', ['src/a.ts']);
+ };
+ await s.approveAll();
+ s.select('batch');
+ const d = wide();
+ const row = d.querySelector(`[data-batch-row="${m.FIXTURE_BATCH[1].id}"]`);
+ assert.equal(row.getAttribute('data-status'), 'came_back');
+ assert.equal(row.querySelector('[data-batch-word]').textContent, 'Came back');
+ assert.match(row.textContent, /src\/a\.ts changed after its check/);
+ assert.doesNotMatch(s.inboxStore.get().notice.text, /changed after its check/);
+ assert.equal(d.querySelector(`[data-batch-row="${m.FIXTURE_BATCH[0].id}"] [data-batch-word]`).textContent, 'Approved');
+});
diff --git a/frontend/tests/reviewItemView.test.mjs b/frontend/tests/reviewItemView.test.mjs
new file mode 100644
index 00000000..c04dfd71
--- /dev/null
+++ b/frontend/tests/reviewItemView.test.mjs
@@ -0,0 +1,414 @@
+// 0.9.0 V1 ReviewItemView (Mira, release-090/designs/v1-review-inbox.md; Ada's D2, D3): the copy helpers,
+// and the component against Pixel's fixtures with an injected fake api. Demo data only; no network.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/inbox', pretendToBeVisual: true });
+const g = globalThis;
+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLButtonElement', 'HTMLTextAreaElement', 'HTMLInputElement', 'Element', 'Node', 'Event', 'CustomEvent', 'MouseEvent', 'KeyboardEvent', 'FocusEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage']) {
+ if (!(k in dom.window)) continue;
+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });
+}
+g.IS_REACT_ACT_ENVIRONMENT = false;
+
+const m = await loadBundled(`
+ export { default as React } from 'react';
+ export { createRoot } from 'react-dom/client';
+ export * from './src/reviewItem';
+ export { ReviewItemView } from './src/components/ReviewItemView';
+ export { FIXTURE_REVIEW_ITEMS, InboxError } from './src/api/inbox';
+ export { MissionError } from './src/missions';
+`);
+const { React, createRoot, ReviewItemView, FIXTURE_REVIEW_ITEMS: FX, InboxError, MissionError } = m;
+const h = React.createElement;
+const settle = async (n = 12) => {
+ for (let i = 0; i < n; i++) await new Promise((r) => setTimeout(r, 0));
+};
+
+function fakeApi(over = {}) {
+ const calls = [];
+ const rec = (name, ret) => async (...a) => {
+ calls.push([name, ...a]);
+ return typeof ret === 'function' ? ret(...a) : ret;
+ };
+ const cps = [
+ { id: 'cp-before', kind: 'before_run', attempt: 1, created_at: '2026-11-10T14:02:00Z', created_by: 'kwant', files: 3, bytes: 10, skipped: 0, git_head: null, error: null, restorable: true, effects_after: { workspace: 1, external: [] } },
+ ];
+ const preview = {
+ checkpoint_id: 'cp-before', preview_sha256: 'sha-1',
+ changes: [{ path: 'src/auth/limit.rs', action: 'overwrite' }, { path: 'src/auth/new.rs', action: 'delete' }],
+ conflicts: [], skipped: [], external_not_undone: [], not_undone_note: 'kwant can’t undo these. Check them yourself.',
+ effects_known: true, task_state_after: 'ready', refused: null, via: 'restore', step_down: null,
+ };
+ const api = {
+ verify: rec('verify', {}),
+ reject: rec('reject', {}),
+ runChecks: rec('runChecks', {}),
+ resolveHeld: rec('resolveHeld', (id, d) => ({ result_line: d === 'allow_once' ? 'Merged #512 into main.' : null })),
+ checkpoints: rec('checkpoints', cps),
+ restorePreview: rec('restorePreview', preview),
+ restore: rec('restore', { restored: ['src/auth/limit.rs'], deleted: ['src/auth/new.rs'], failed: [], before_restore_checkpoint_id: 'cp-safety', task: { held_at: '2026-11-10T15:30:00Z' } }),
+ forkFromCheckpoint: rec('forkFromCheckpoint', { id: 't-copy', stepped_down: { kwant_id: 'k-lin', class: 'auth changes', from: 'trusted', to: 'sandbox' } }),
+ ...over,
+ };
+ return { api, calls, preview };
+}
+
+async function mount(item, api, extra = {}) {
+ document.body.innerHTML = '';
+ sessionStorage.clear();
+ const el = document.createElement('div');
+ document.body.appendChild(el);
+ const done = [];
+ const root = createRoot(el);
+ root.render(h(ReviewItemView, { item, entry: 'inbox', onDone: (r) => done.push(r), api, ...extra }));
+ await settle();
+ return { el, done, root, q: (s) => document.querySelector(s), qa: (s) => [...document.querySelectorAll(s)] };
+}
+const click = async (b) => {
+ b.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await settle();
+};
+const key = async (k, target = document.body) => {
+ target.dispatchEvent(new KeyboardEvent('keydown', { key: k, bubbles: true }));
+ await settle();
+};
+const type = async (ta, text) => {
+ const set = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value').set;
+ set.call(ta, text);
+ ta.dispatchEvent(new Event('input', { bubbles: true }));
+ await settle();
+};
+
+// ---- helpers ----
+
+test('helpers: summaries come from the server numbers, tail keeps 12 lines', () => {
+ assert.equal(m.criteriaSummaryText({ met: 1, total: 4, not_met: 1, not_checked: 2 }), '1 of 4 met · 1 not met · 2 not checked');
+ assert.equal(m.decisionsSummaryText(FX.needsYou.decisions), '2 for you, of 4');
+ assert.equal(m.evidenceSummaryText(FX.needsYou.evidence), '1 check · 1 screenshot · shop #512');
+ const out = Array.from({ length: 20 }, (_, i) => `line ${i + 1}`).join('\n');
+ const t = m.tailLines(out);
+ assert.equal(t.more, true);
+ assert.equal(t.lines.split('\n').length, 12);
+ assert.equal(t.lines.split('\n')[0], 'line 9');
+ assert.equal(m.nextCriterionIndex(FX.failRoundLimit.criteria), 7);
+ assert.equal(m.notUndoneTitle({ effects_known: false, external_not_undone: [] }), 'Not undone: unknown');
+ assert.equal(m.notUndoneTitle({ effects_known: true, external_not_undone: [] }), null);
+ assert.equal(m.sendBackSteps(FX.needsYou, 1)[0], 'The held merge of #512 is denied first, so nothing runs.');
+ assert.equal(m.sendBackSteps(FX.heldDenied, 0).some((s) => /denied first/.test(s)), false);
+});
+
+test('invalid data falls back to the plain card with the title and summary as text', async () => {
+ const { api } = fakeApi();
+ const bad = { ...FX.needsYou, verdict: null, summary: '<b>not html</b>' };
+ const { q } = await mount(bad, api);
+ assert.ok(q('[data-review-fallback]'));
+ assert.equal(q('[data-review-fallback] b'), null);
+ assert.match(q('[data-review-fallback]').textContent, /<b>not html<\/b>/);
+ const { q: q2 } = await mount({ kind: 'question', id: 'q1', title: 'Ship tonight?', summary: 'Choices', group: 'waiting_on_you', sort_key: [] }, api);
+ assert.ok(q2('[data-review-fallback]'));
+});
+
+test('every fixture renders without throwing, with a verdict box', async () => {
+ for (const [name, item] of Object.entries(FX)) {
+ const { api } = fakeApi();
+ const { q } = await mount(item, api);
+ assert.ok(q(`[data-verdict="${item.being_checked && item.verdict.result === 'none' ? 'being_checked' : item.verdict.result}"]`), name);
+ }
+});
+
+test('held action: Approve is aria-disabled with the reason; A focuses Deny and never approves or allows', async () => {
+ const { api, calls } = fakeApi();
+ const { q, done } = await mount(FX.needsYou, api);
+ const ap = q('[data-approve]');
+ assert.equal(ap.getAttribute('aria-disabled'), 'true');
+ assert.equal(q('[data-approve-blocked]').textContent.trim(), 'Allow or deny the held action first');
+ assert.equal(ap.getAttribute('aria-keyshortcuts'), 'A');
+ await key('a');
+ assert.ok(document.activeElement === q('[data-held-deny]'), 'focus');
+ await click(ap);
+ assert.ok(document.activeElement === q('[data-held-deny]'), 'focus');
+ assert.deepEqual(calls, []);
+ assert.equal(done.length, 0);
+ // Allow once: the held box shows what ran, Approve comes back.
+ await click(q('[data-held-allow]'));
+ assert.deepEqual(calls[0], ['resolveHeld', 'a-merge', 'allow_once']);
+ assert.equal(q('[data-held]').getAttribute('data-held-state'), 'allowed');
+ assert.match(q('[data-held]').textContent, /Merged #512 into main\./);
+ assert.equal(q('[data-approve]').getAttribute('aria-disabled'), null);
+ await key('a');
+ assert.deepEqual(calls[1], ['verify', 't-r-needs', 'v-needs']);
+ assert.equal(done[0].kind, 'approved');
+ assert.equal(done[0].task_id, 't-r-needs');
+});
+
+test('resolved held actions from the server keep their result and do not block Approve', async () => {
+ const { api } = fakeApi();
+ const { q, qa } = await mount(FX.heldDenied, api);
+ assert.deepEqual(qa('[data-held]').map((e) => e.getAttribute('data-held-state')), ['denied', 'expired']);
+ assert.equal(qa('[data-held-deny]').length, 0);
+ assert.equal(q('[data-approve]').getAttribute('aria-disabled'), null);
+ assert.match(qa('[data-held]')[1].textContent, /Expired before anyone answered/);
+});
+
+test('a held action that expired under us (409) is shown expired, not as an error', async () => {
+ const { api } = fakeApi({ resolveHeld: async () => { throw new InboxError(409, 'gone'); } });
+ const { q } = await mount(FX.passHeld, api);
+ await click(q('[data-held-deny]'));
+ assert.equal(q('[data-held]').getAttribute('data-held-state'), 'expired');
+ assert.equal(q('[data-approve]').getAttribute('aria-disabled'), null);
+});
+
+test('stale 409 on approve: onDone stale with the paths, nothing approved', async () => {
+ const { api } = fakeApi({ verify: async () => { throw new InboxError(409, 'stale', 'stale', ['README.md']); } });
+ const { q, done } = await mount(FX.oneTap, api);
+ await click(q('[data-approve]'));
+ assert.equal(done[0].kind, 'stale');
+ assert.deepEqual(done[0].paths, ['README.md']);
+ assert.match(done[0].text, /back in Failed or stuck, and nothing was approved\./);
+ // V1-4: "changed after its check" is said once: in the stale box, not again in a notice or in the text the Inbox shows.
+ assert.doesNotMatch(done[0].text, /changed after its check/);
+ assert.match(q('[data-stale]').textContent, /README\.md changed after its check\./);
+ assert.equal(document.body.textContent.split('changed after its check').length - 1, 1);
+ assert.equal(q('[data-notice]'), null);
+ // When the Inbox hands back the item with `stale` set, it is still drawn once.
+ const { q: q2 } = await mount({ ...FX.oneTap, stale: { paths: ['README.md'], at: '2026-11-10T15:00:00Z' } }, api);
+ assert.equal(document.body.textContent.split('changed after its check').length - 1, 1);
+ assert.ok(q2('[data-check-again]'));
+});
+
+test('D7 Being checked: the word and line, Approve stays enabled and A sends verify with no verdict id', async () => {
+ const { api, calls } = fakeApi();
+ const { q, done } = await mount(FX.beingChecked, api);
+ assert.ok(q('[data-verdict="being_checked"]'));
+ assert.match(q('[data-verdict]').textContent, /Being checked/);
+ assert.doesNotMatch(q('[data-verdict]').textContent, /Not checked yet/);
+ assert.equal(q('[data-verdict-line]').textContent, 'The verifier is checking this now. You can still approve it yourself.');
+ assert.equal(q('[data-approve]').getAttribute('aria-disabled'), null);
+ assert.equal(q('[data-approve-blocked]'), null);
+ await key('a');
+ assert.deepEqual(calls, [['verify', 't-r-being', null]]);
+ assert.equal(done[0].kind, 'approved');
+});
+
+test('D7: no hold (field missing or false) stays "Not checked yet"; a verdict wins over the flag', async () => {
+ const { api } = fakeApi();
+ assert.equal(FX.notChecked.being_checked, undefined, 'the fixture has no field: missing reads as false');
+ const { q } = await mount(FX.notChecked, api);
+ assert.ok(q('[data-verdict="none"]'));
+ assert.match(q('[data-verdict]').textContent, /Not checked yet/);
+ assert.equal(q('[data-verdict-line]').textContent, FX.notChecked.verdict.line);
+ const { q: q2 } = await mount({ ...FX.beingChecked, being_checked: false }, api);
+ assert.match(q2('[data-verdict]').textContent, /Not checked yet/);
+ const { q: q3 } = await mount({ ...FX.oneTap, being_checked: true }, api);
+ assert.ok(q3('[data-verdict="pass"]'));
+ assert.equal(m.verdictWord('none'), 'Not checked yet');
+});
+
+test('V1-3: denying, allowing or finding a held action expired tells the list (onHeldResolved)', async () => {
+ const seen = [];
+ const { api } = fakeApi();
+ const { q } = await mount(FX.passHeld, api, { onHeldResolved: (id, st) => seen.push([id, st]) });
+ await click(q('[data-held-deny]'));
+ assert.deepEqual(seen, [['a-refund', 'denied']]);
+ const { api: gone } = fakeApi({ resolveHeld: async () => { throw new InboxError(404, 'gone'); } });
+ const { q: q2 } = await mount(FX.needsYou, gone, { onHeldResolved: (id, st) => seen.push([id, st]) });
+ await click(q2('[data-held-deny]'));
+ assert.deepEqual(seen[1], ['a-merge', 'expired']);
+ const { api: bad } = fakeApi({ resolveHeld: async () => { throw new InboxError(500, 'HTTP 500'); } });
+ const { q: q3 } = await mount(FX.needsYou, bad, { onHeldResolved: (id, st) => seen.push([id, st]) });
+ await click(q3('[data-held-deny]'));
+ assert.equal(seen.length, 2, 'a failed deny is not reported');
+});
+
+test('approve error that is not stale stays in the view; nothing reported done', async () => {
+ const { api } = fakeApi({ verify: async () => { throw new InboxError(500, 'HTTP 500'); } });
+ const { q, done } = await mount(FX.oneTap, api);
+ await click(q('[data-approve]'));
+ assert.equal(done.length, 0);
+ assert.equal(q('[data-notice]').getAttribute('data-notice'), 'bad');
+});
+
+test('send back denies the held action first, then rejects with the note; Becomes criterion N', async () => {
+ const { api, calls } = fakeApi();
+ const { q, done } = await mount(FX.needsYou, api);
+ await key('s');
+ const ta = q('[data-send-note]');
+ assert.ok(ta);
+ assert.equal(document.activeElement, ta);
+ assert.equal(q('[data-send-submit]').disabled, true);
+ await type(ta, 'Count per account too');
+ assert.match(q('[data-becomes]').textContent, /Becomes criterion 5:/);
+ assert.match(q('[data-send-form]').textContent, /The held merge of #512 is denied first/);
+ await click(q('[data-send-submit]'));
+ assert.deepEqual(calls.map((c) => c[0]), ['resolveHeld', 'reject']);
+ assert.deepEqual(calls[0], ['resolveHeld', 'a-merge', 'deny']);
+ assert.deepEqual(calls[1], ['reject', 't-r-needs', 'Count per account too']);
+ assert.equal(done[0].kind, 'sent_back');
+ assert.equal(done[0].text, 'Sent back to Lin. Round 2 starts now.');
+});
+
+test('send back stops when the deny fails: no reject, the error shows in the panel', async () => {
+ const { api, calls } = fakeApi({ resolveHeld: async () => { throw new InboxError(500, 'HTTP 500'); } });
+ const { q, done } = await mount(FX.needsYou, api);
+ await click(q('[data-send-back]'));
+ await type(q('[data-send-note]'), 'Again');
+ await click(q('[data-send-submit]'));
+ assert.equal(calls.some((c) => c[0] === 'reject'), false);
+ assert.equal(done.length, 0);
+ assert.match(q('[data-send-form] [role="alert"]').textContent, /nothing was sent/);
+});
+
+test('decision Change prefills the send back note', async () => {
+ const { api } = fakeApi();
+ const { q } = await mount(FX.needsYou, api);
+ await click(q('[data-fold="Decisions"] button'));
+ await click(q('[data-decision-change]'));
+ assert.equal(q('[data-send-note]').value, 'Change: Count failed sign-ins per IP or per account? → ');
+});
+
+test('folds: closed by default, aria-expanded and controls, remembered for the session', async () => {
+ const { api } = fakeApi();
+ const { q } = await mount(FX.needsYou, api);
+ const b = q('[data-fold="Evidence"] button');
+ assert.equal(b.getAttribute('aria-expanded'), 'false');
+ assert.ok(document.getElementById(b.getAttribute('aria-controls')).hidden);
+ await click(b);
+ assert.equal(b.getAttribute('aria-expanded'), 'true');
+ assert.ok(q('[data-pr-card]'));
+ assert.ok(q('[data-shot]'));
+ assert.ok(q('[data-check="unit"] pre'));
+ assert.equal(JSON.parse(sessionStorage.getItem('kw-review-folds')).evidence, true);
+ // Couldn't check is open when it has anything.
+ assert.match(q('[data-couldnt-check]').textContent, /Safari login/);
+});
+
+test('round 2 box: your note, the flips and the diff, from the server', async () => {
+ const { api } = fakeApi();
+ const { q } = await mount(FX.failRoundLimit, api);
+ const t = q('[data-round-box]').textContent;
+ assert.match(t, /Round 2 · what changed since round 1/);
+ assert.match(t, /Your note is now criterion 5, and it’s Met\./);
+ assert.match(t, /Criterion 2 went Not met → Met\./);
+ assert.match(t, /\+14 −6 in 2 files since round 1/);
+ assert.ok(q('[data-last-round]'));
+ assert.ok(q('[data-round-chip]'));
+});
+
+test('roll back: preview rows, restore with the preview sha and an idempotency key, then Undo', async () => {
+ const { api, calls } = fakeApi();
+ const { q, done } = await mount(FX.oneTap, api);
+ await click(q('[data-roll-back]'));
+ assert.ok(q('[role="dialog"]'));
+ assert.equal(q('[data-rollback-confirm]').textContent.trim(), 'Roll back 2 files');
+ assert.equal(q('[data-not-undone]').getAttribute('data-not-undone'), 'none');
+ assert.ok(document.activeElement === q('[data-keep-work]'), 'focus');
+ await click(q('[data-rollback-confirm]'));
+ const r = calls.find((c) => c[0] === 'restore');
+ assert.equal(r[1], 't-r-onetap');
+ assert.equal(r[2], 'cp-before');
+ assert.equal(r[3].preview_sha256, 'sha-1');
+ assert.ok(typeof r[4] === 'string' && r[4].length > 8);
+ assert.equal(done[0].kind, 'rolled_back');
+ assert.equal(done[0].undo_checkpoint_id, 'cp-safety');
+ assert.match(done[0].text, /1 file put back, 1 removed\. The task is on hold until you press Run\./);
+ assert.ok(q('[data-undo-rollback]'));
+});
+
+test('roll back shows "Not undone: unknown" when effects_known is false', async () => {
+ const base = fakeApi();
+ const { api } = fakeApi({ restorePreview: async () => ({ ...base.preview, effects_known: false }) });
+ const { q } = await mount(FX.oneTap, api);
+ await click(q('[data-roll-back]'));
+ const nu = q('[data-not-undone]');
+ assert.equal(nu.getAttribute('data-not-undone'), 'unknown');
+ assert.match(nu.textContent, /Not undone: unknown/);
+});
+
+test('roll back with a held action denies it first; a stale preview reloads', async () => {
+ let n = 0;
+ const base = fakeApi();
+ const { api, calls } = fakeApi({
+ restore: async () => {
+ n++;
+ throw new MissionError('stale', 409, 'stale_preview');
+ },
+ });
+ const { q } = await mount(FX.needsYou, api);
+ await click(q('[data-roll-back]'));
+ assert.match(q('[data-review-dialog]').textContent, /The held action is denied first\./);
+ await click(q('[data-rollback-confirm]'));
+ assert.deepEqual(calls.find((c) => c[0] === 'resolveHeld'), ['resolveHeld', 'a-merge', 'deny']);
+ assert.equal(n, 1);
+ assert.match(q('[data-rollback-error]').textContent, /Files changed since this preview/);
+ assert.equal(calls.filter((c) => c[0] === 'restorePreview').length, 2);
+ void base;
+});
+
+test('roll back after approval (via fork): after-approval lines, step-down, fork call, copy', async () => {
+ const base = fakeApi();
+ const { api, calls } = fakeApi({
+ restorePreview: async () => ({ ...base.preview, via: 'fork', verified_at: '2026-11-10T14:50:00Z', step_down: { kwant_id: 'k-mira', class: 'copy changes', from: 'trusted', to: 'sandbox' } }),
+ });
+ const opened = [];
+ const { q, done } = await mount(FX.oneTap, api, { onOpenTask: (id) => opened.push(id) });
+ await click(q('[data-roll-back]'));
+ assert.ok(q('[data-after-approval]'));
+ assert.match(q('[data-step-down]').textContent, /Mira moves down one Flight School tier for copy changes/);
+ await click(q('[data-rollback-confirm]'));
+ const f = calls.find((c) => c[0] === 'forkFromCheckpoint');
+ assert.equal(f[1], 't-r-onetap');
+ assert.equal(f[2].from_checkpoint, 'cp-before');
+ assert.equal(f[2].preview_sha256, 'sha-1');
+ assert.ok(f[2].reason.length > 0 && f[2].reason.length <= 500);
+ assert.equal(calls.some((c) => c[0] === 'restore'), false);
+ assert.equal(done[0].copy_task_id, 't-copy');
+ await click(q('[data-open-copy]'));
+ assert.deepEqual(opened, ['t-copy']);
+});
+
+test('roll back by restore (in review, person check passed) still shows the step-down; none when step_down is null', async () => {
+ const base = fakeApi();
+ const { api, calls } = fakeApi({
+ restorePreview: async () => ({ ...base.preview, via: 'restore', step_down: { kwant_id: 'k-mira', class: 'copy changes', from: 'trusted', to: 'sandbox' } }),
+ });
+ const { q } = await mount(FX.oneTap, api);
+ await click(q('[data-roll-back]'));
+ assert.equal(q('[data-after-approval]'), null);
+ assert.match(q('[data-step-down]').textContent, /Mira moves down one Flight School tier for copy changes: trusted → sandbox/i);
+ await click(q('[data-rollback-confirm]'));
+ assert.ok(calls.some((c) => c[0] === 'restore'));
+ assert.equal(calls.some((c) => c[0] === 'forkFromCheckpoint'), false);
+ const { api: api2 } = fakeApi();
+ const { q: q2 } = await mount(FX.oneTap, api2);
+ await click(q2('[data-roll-back]'));
+ assert.equal(q2('[data-step-down]'), null);
+});
+
+test('no roll back button when rollback_ok is false; Escape closes the dialog', async () => {
+ const { api } = fakeApi();
+ const { q } = await mount(FX.noRollback, api);
+ assert.equal(q('[data-roll-back]'), null);
+ const { q: q2 } = await mount(FX.oneTap, api);
+ await click(q2('[data-roll-back]'));
+ await key('Escape', q2('[role="dialog"]'));
+ assert.equal(q2('[role="dialog"]'), null);
+});
+
+test('stale item: Check again runs the checks', async () => {
+ const { api, calls } = fakeApi();
+ const { q } = await mount(FX.stale, api);
+ assert.match(q('[data-stale]').textContent, /README\.md changed after its check/);
+ await click(q('[data-check-again]'));
+ assert.deepEqual(calls[0], ['runChecks', 't-r-stale']);
+});
+
+test('copy has no emoji and no HTML from data', async () => {
+ const { api } = fakeApi();
+ for (const item of Object.values(FX)) {
+ const { el } = await mount(item, api);
+ assert.doesNotMatch(el.textContent, /\p{Extended_Pictographic}/u);
+ }
+});