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.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Fresh eyes UI: pre-push card, Needs you item, fresh-eyes chip (0.8.0 B3) (#458)
Oleksandr Ivanchenkoa75d21d6ba28
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 07743322..eb6c0b6a 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -146,6 +146,8 @@ import { JiraSetupHost } from './components/JiraSetup';import { useDevModeOn } from './components/DevModeSwitch';import { DEV_CARD_EVENT, DevDeskView, type DevCardEvent } from './components/DevDesk';import { DEV_TICKET_EVENT, DEV_TICKET_PROGRESS_EVENT } from './components/dev/TicketsTab';+import { PrepushNeedsYou, PrepushThread, threadCards, usePrepushCards, type PrepushEventDetail } from './components/dev/PrepushThread';+import { PREPUSH_EVENT, needsYou as prepushNeedsYou, overrideMessage, prepushApi, retryMessage, type PrepushCard as PrepushCardData } from './dev/prepush';import { StepReview } from './components/ShowOnce';import { inDesktopApp, leaveForSignIn, mcpSignIn, pollUntil, signInChanged } from './externalLinks';@@ -495,6 +497,10 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({// Dev mode (0.7): the open space's state, read by the switch, the hats and the grid.useEffect(() => devStore.setCurrent(space.id), [space.id]);const devOn = useDevModeOn(space.id);+ // 0.8.0 B3: the space's pre-push cards (Dev mode only): the bot's thread and the Inbox read them.+ const prepush = usePrepushCards(space.id, devOn);+ const prepushWaiting = prepushNeedsYou(prepush.cards).length;+ const kwantNames = useMemo(() => Object.fromEntries(kwants.map((k) => [k.id, k.name])), [kwants]);// A task to open on the board once it shows (from a lesson on a bot's Memory tab).const [pendingTaskId, setPendingTaskId] = useState<string | null>(null);const [awayCount, setAwayCount] = useState(0);@@ -1252,6 +1258,17 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({}break;}+ // 0.8.0 B3: a pre-push card changed; the space's list refetches that card.+ case 'dev_prepush':+ case 'DevPrepush': {+ const d = event.data ?? {};+ if (typeof d.space_id === 'string' && typeof d.id === 'string') {+ window.dispatchEvent(+ new CustomEvent<PrepushEventDetail>(PREPUSH_EVENT, { detail: { space_id: d.space_id, id: d.id, kwant_id: typeof d.kwant_id === 'string' ? d.kwant_id : undefined, status: typeof d.status === 'string' ? d.status : undefined } }),+ );+ }+ break;+ }// 0.7.6 Work from Jira: the Tickets tab refetches on `dev_ticket`; a reading card folds in `dev_ticket_progress`.case 'dev_ticket':case 'dev_ticket_progress': {@@ -2005,6 +2022,21 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({setPage('chat');};+ /** 0.8.0 B3: a pre-push Inbox item opens the bot's chat at its card. */+ const openPrepush = (c: PrepushCardData) => {+ if (!openTarget({ channel_id: null, kwant_id: c.kwant_id })) return pushToast('That bot no longer exists.');+ setPage('chat');+ window.setTimeout(() => document.getElementById(`prepush-${c.id}`)?.scrollIntoView?.({ block: 'center' }), 250);+ };+ const prepushRetry = async (c: PrepushCardData) => {+ prepush.put(await prepushApi.retry(c.id));+ await handleSendMessage(retryMessage(c));+ };+ const prepushOverride = async (c: PrepushCardData, reason: string) => {+ prepush.put(await prepushApi.override(c.id, reason));+ await handleSendMessage(overrideMessage(c));+ };+const openDirectChat = () => {if (!openThreadId) return;setOpenThreadId(null);@@ -3561,7 +3593,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({setIsNewChannelOpen(true);playSfx('click');}}- inboxCount={awayCount}+ inboxCount={awayCount + prepushWaiting}inboxActive={page === 'inbox'}onOpenInbox={() => {showPage('inbox');@@ -3600,7 +3632,12 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({const away = (<AwayPage since={awaySinceRef.current} onSince={(t) => (awaySinceRef.current = t)} onOpen={openAwayItem} onCounts={setAwayCount} onApprovalResolved={dropApproval}- top={<SpendStopNeedsYou refreshKey={spendStopSeq} onOpenSettings={openUsageSettings} />}+ top={+ <>+ <PrepushNeedsYou cards={prepush.cards} names={kwantNames} onOpen={openPrepush} />+ <SpendStopNeedsYou refreshKey={spendStopSeq} onOpenSettings={openUsageSettings} />+ </>+ }/>);const backToList = isPhone ? () => { setPage('chat'); setPhoneView('list'); } : undefined;@@ -3656,7 +3693,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({addImap={looseAddImap > 0}/>);- const inbox = <InboxPage tab={inboxTab} onTab={setInboxTab} count={awayCount} onBack={backToList} newPage={away} loosePage={loose} />;+ const inbox = <InboxPage tab={inboxTab} onTab={setInboxTab} count={awayCount + prepushWaiting} onBack={backToList} newPage={away} loosePage={loose} />;const chat = (<ChatViewtitle={chatTitle}@@ -3669,6 +3706,11 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({streamingText={isCurrentContextStreaming ? streamingText : ''}streamingThinking={isCurrentContextStreaming ? streamingThinking : ''}pendingApprovals={approvalsHere}+ prepush={+ devOn && currentKwant && !viewingHistory ? (+ <PrepushThread cards={threadCards(prepush.cards, currentKwant.id)} bot={currentKwant.name} live={prepush.live} onRetry={prepushRetry} onOverride={prepushOverride} />+ ) : undefined+ }settledApprovals={approvalsForChat(settledApprovals, openChat)}home={chatHome}isStreaming={isCurrentContextStreaming}@@ -3877,7 +3919,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({badgeTone: 'violet',badgeNoun: ideaJarCount === 1 ? 'take ready' : 'takes ready',},- { id: 'inbox', label: 'Inbox', icon: <Inbox size={20} aria-hidden="true" />, badge: awayCount },+ { id: 'inbox', label: 'Inbox', icon: <Inbox size={20} aria-hidden="true" />, badge: awayCount + prepushWaiting },{ id: 'space', label: 'Space', icon: <Settings size={20} aria-hidden="true" /> },];const showPhoneList = isPhone && phoneView === 'list' && !needsSetup;diff --git a/frontend/src/auditor.ts b/frontend/src/auditor.tsindex 1db55a17..b2b44d99 100644--- a/frontend/src/auditor.ts+++ b/frontend/src/auditor.ts@@ -41,6 +41,8 @@ export interface Audit {created_at: string;finished_at: string | null;risks: Risk[];+ /** 0.8.0 B3: the raw fresh-eyes label (fresh-eyes-audit.md §3.2); read with parseFreshEyes. */+ fresh_eyes?: unknown;}export interface TaskRisks {diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsxindex 5031f0e6..487777f0 100644--- a/frontend/src/components/ChatView.tsx+++ b/frontend/src/components/ChatView.tsx@@ -177,6 +177,8 @@ export interface ChatViewProps {streamingThinking: string;/** Tool approvals waiting in this chat, oldest first. */pendingApprovals: PendingApproval[];+ /** 0.8.0 B3: this bot's pre-push cards (Dev mode), shown above its approvals. */+ prepush?: React.ReactNode;/** Approvals answered in Telegram while this chat was open (G4): kept as a resolved row. */settledApprovals?: PendingApproval[];isStreaming: boolean;@@ -425,6 +427,7 @@ export const ChatView: React.FC<ChatViewProps> = ({streamingText,streamingThinking,pendingApprovals,+ prepush,settledApprovals = [],isStreaming,streamingSpeakerName,@@ -1846,6 +1849,9 @@ export const ChatView: React.FC<ChatViewProps> = ({<AllowedFromTelegram key={approval.id} lead={approvalLead(approval)} />))}+ {/* 0.8.0 B3: checks before this bot pushes */}+ {prepush}+{/* Pending Security Approval Ticket */}{pendingApprovals.map((approval) => (<ModernApprovalCard key={approval.id} approval={approval} onResolve={onResolveApproval} />diff --git a/frontend/src/components/RisksSection.tsx b/frontend/src/components/RisksSection.tsxindex 106d1544..24777d3d 100644--- a/frontend/src/components/RisksSection.tsx+++ b/frontend/src/components/RisksSection.tsx@@ -17,6 +17,8 @@ import {unresolved,} from '../auditor';import { formatTokens } from '../missions';+import { chipState, parseFreshEyes } from '../dev/freshEyes';+import { FreshEyesChip } from './dev/FreshEyesChip';const TONE: Record<string, string> = {amber: 'bg-amber-500/15 text-amber-200 border-amber-500/30',@@ -91,6 +93,7 @@ const AuditBlock: React.FC<{const challenger = names[a.challenger_kwant_id] || 'A bot';const owner = names[a.owner_kwant_id] || 'The owner';const tokens = auditTokens(a);+ const fresh = parseFreshEyes(a.fresh_eyes);return (<li className="space-y-2" data-audit={a.id} data-audit-status={a.status}><div className="text-[11px] text-zinc-400 break-words">@@ -101,6 +104,11 @@ const AuditBlock: React.FC<{{auditStatusText(a, names)}</span></div>+ {chipState(fresh) !== 'R3' && (+ <div className="relative flex flex-wrap gap-1.5">+ <FreshEyesChip label={fresh} reviewer={(fresh?.reviewer_kwant_id && names[fresh.reviewer_kwant_id]) || challenger} author={names[a.owner_kwant_id] || null} />+ </div>+ )}{a.risks.length > 0 && (<ul className="space-y-1.5">{a.risks.map((r) => (diff --git a/frontend/src/components/dev/FreshEyesChip.tsx b/frontend/src/components/dev/FreshEyesChip.tsxnew file mode 100644index 00000000..ab9384f4--- /dev/null+++ b/frontend/src/components/dev/FreshEyesChip.tsx@@ -0,0 +1,113 @@+// 0.8.0 B3: "Checked with fresh eyes" (Mira b3-fresh-eyes.md §1). A plain grey chip, never+// holographic: it describes how the review was run. R1 opens a small, non-modal popover listing+// what the reviewer saw; R2 is a grey chip that isn't a button; R3 shows nothing.+//+// The popover is a flex item of the chip row: it wraps onto its own line, in flow, on phone, and+// floats under the row from 640 px up. Give the row `relative` so it has something to float under.++import React, { useEffect, useId, useRef, useState } from 'react';+import { Check, Eye, X } from 'lucide-react';+import { chipState, popoverTitle, sawLines, type FreshEyes } from '../../dev/freshEyes';++export interface FreshEyesChipProps {+ label: FreshEyes | null | undefined;+ reviewer: string | null;+ author: string | null;+ diff?: { files: number; add: number; del: number } | null;+ /** "#212" when the review was against a ticket. */+ specRef?: string | null;+}++export const FreshEyesChip: React.FC<FreshEyesChipProps> = ({ label, reviewer, author, diff = null, specRef = null }) => {+ const [open, setOpen] = useState(false);+ const btn = useRef<HTMLButtonElement>(null);+ const pop = useRef<HTMLDivElement>(null);+ const id = useId();+ const state = chipState(label);++ useEffect(() => {+ if (!open) return;+ const onDown = (e: MouseEvent | TouchEvent) => {+ const t = e.target as Node | null;+ if (t && (btn.current?.contains(t) || pop.current?.contains(t))) return;+ setOpen(false);+ };+ const onKey = (e: KeyboardEvent) => {+ if (e.key !== 'Escape') return;+ e.stopPropagation();+ setOpen(false);+ btn.current?.focus();+ };+ document.addEventListener('mousedown', onDown);+ document.addEventListener('touchstart', onDown);+ document.addEventListener('keydown', onKey);+ return () => {+ document.removeEventListener('mousedown', onDown);+ document.removeEventListener('touchstart', onDown);+ document.removeEventListener('keydown', onKey);+ };+ }, [open]);++ if (state === 'R3' || !label) return null;+ if (state === 'R2') {+ return (+ <span data-fresh-eyes="R2" className="kw-chip">+ Saw the author's chat+ </span>+ );+ }++ const lines = sawLines(label, { author, diff, ref: specRef });+ const onBlur = (e: React.FocusEvent) => {+ const next = e.relatedTarget as Node | null;+ if (next && (btn.current?.contains(next) || pop.current?.contains(next))) return;+ setOpen(false);+ };++ return (+ <>+ <button+ ref={btn}+ type="button"+ data-fresh-eyes="R1"+ aria-expanded={open}+ aria-controls={id}+ onClick={() => setOpen((o) => !o)}+ onBlur={onBlur}+ className="kw-chip fe-chip cursor-pointer outline-none hover:bg-white/[0.07] focus-visible:ring-2 focus-visible:ring-sky-400 focus-visible:ring-offset-2 focus-visible:ring-offset-zinc-900"+ >+ <Eye size={12} className="text-sky-300" aria-hidden="true" />+ Checked with fresh eyes+ </button>+ {open && (+ <div+ ref={pop}+ id={id}+ role="dialog"+ aria-label="How this review was run"+ tabIndex={-1}+ onBlur={onBlur}+ data-fresh-eyes-pop+ className="fe-pop kw-card w-full basis-full p-3 text-xs leading-[18px] text-zinc-300 sm:absolute sm:left-0 sm:top-full sm:z-20 sm:mt-2 sm:w-auto sm:max-w-[300px] sm:basis-auto sm:bg-[#231d4b] sm:shadow-lg"+ >+ <p className="text-zinc-200 [overflow-wrap:anywhere]">{popoverTitle(reviewer)}</p>+ <ul role="list" className="mt-2 space-y-1">+ {lines.map((l) => (+ <li key={l.text} className={`flex items-start gap-1.5 [overflow-wrap:anywhere] ${l.ok ? 'text-zinc-300' : 'text-zinc-400'}`}>+ {l.ok ? (+ <Check size={12} className="mt-[3px] shrink-0 text-emerald-300" aria-hidden="true" />+ ) : (+ <X size={12} className="mt-[3px] shrink-0 text-zinc-500" aria-hidden="true" />+ )}+ <span className="min-w-0">+ {l.ok && <span className="sr-only">Saw </span>}+ {l.text}+ </span>+ </li>+ ))}+ </ul>+ </div>+ )}+ </>+ );+};diff --git a/frontend/src/components/dev/PrepushCard.tsx b/frontend/src/components/dev/PrepushCard.tsxnew file mode 100644index 00000000..7942e480--- /dev/null+++ b/frontend/src/components/dev/PrepushCard.tsx@@ -0,0 +1,404 @@+// 0.8.0 B3: the pre-push card in the author bot's thread (Mira b3-fresh-eyes.md §2–§4, Juno+// fresh-eyes-audit.md §4). Every state and number comes from the server card; the client only+// picks the words. Amber appears only where the person must act (Needs you, Push anyway). There is+// never an "always allow" or "skip this check": an override covers one push of one commit.++import React, { useEffect, useId, useRef, useState } from 'react';+import { ArrowUpFromLine, ChevronDown, ChevronRight, GitBranch } from 'lucide-react';+import { DiffStat, Led } from './parts';+import {+ CHECK_NAME,+ STATE_LED,+ STATE_WORD,+ canOverride,+ clearedLine,+ foldLine,+ foldable,+ footer,+ needsYouLead,+ overriddenLine,+ passedRows,+ phaseOf,+ reasonOk,+ rowFindings,+ statusChip,+ toolLine,+ MIN_REASON,+ MAX_REASON,+ type PrepushCard as Card,+ type PrepushCheck,+ type PrepushFinding,+} from '../../dev/prepush';++const BTN =+ 'inline-flex items-center justify-center gap-1.5 rounded-lg px-3 text-xs font-medium transition-colors min-h-11 sm:min-h-[32px] max-sm:w-full outline-none focus-visible:ring-2 focus-visible:ring-sky-400 focus-visible:ring-offset-2 focus-visible:ring-offset-zinc-900 disabled:cursor-not-allowed disabled:opacity-50';+const PLAIN = `${BTN} border border-hairline-strong bg-zinc-800 text-zinc-200 hover:bg-zinc-700`;+const PRIMARY = `${BTN} text-white`;+const AMBER = `${BTN} bg-amber-600 text-white shadow-sm hover:bg-amber-500`;+const AMBER_OUTLINE = `${BTN} border border-amber-400/60 bg-transparent text-amber-200 hover:bg-amber-400/10`;+const LINK = 'inline-flex items-center gap-0.5 rounded px-1 text-meta font-medium text-accent outline-none hover:underline focus-visible:ring-2 focus-visible:ring-sky-400 min-h-11 sm:min-h-0';++const CHIP: Record<string, string> = { plain: 'kw-chip', ok: 'kw-chip kw-chip-ok', bad: 'kw-chip kw-chip-bad', warn: 'kw-chip kw-chip-warn' };++export interface PrepushCardProps {+ card: Card;+ /** The author bot's name, from the space's bot list. */+ bot: string;+ /** "Ask {bot} to try again" / "Run the checks again": /retry, then tell the bot. Absent: read-only. */+ onRetry?: (c: Card) => Promise<void>;+ /** "Push anyway": /override with the reason, then tell the bot. Absent: read-only. */+ onOverride?: (c: Card, reason: string) => Promise<void>;+ /** The card turned clear while the thread was open: show P2 for about 2 s, then fold to P2b. */+ live?: boolean;+ /** Start with the reason form open (screenshots and tests). */+ startOverride?: boolean;+ /** Start with the folded passing rows open on phone (screenshots and tests). */+ startUnfolded?: boolean;+}++const where = (f: PrepushFinding) => (f.file ? `${f.file}${f.line !== null ? `:${f.line}` : ''}` : null);++const Finding: React.FC<{ f: PrepushFinding }> = ({ f }) => (+ <li className="min-w-0 text-meta text-zinc-300 [overflow-wrap:anywhere]">+ <span className="text-rose-300">{f.title}</span>+ {where(f) && <code className="dv-sha ml-1.5 inline-block max-w-full align-middle [overflow-wrap:anywhere]">{where(f)}</code>}+ {f.detail && <span className="mt-0.5 block text-zinc-400">{f.detail}</span>}+ </li>+);++const Row: React.FC<{ k: PrepushCheck; card: Card; hidePhone: boolean }> = ({ k, card, hidePhone }) => {+ const [show, setShow] = useState(false);+ const id = useId();+ const found = k.state === 'hit' ? rowFindings(card, k.key) : [];+ const dim = k.state === 'not_installed';+ const tone = k.state === 'hit' ? 'text-rose-300' : dim ? 'text-zinc-500' : 'text-zinc-300';+ const ledClass = k.state === 'running' ? 'dv-led-still mt-[5px]' : k.state === 'not_installed' ? 'dv-led-dashed mt-[5px]' : 'mt-[5px]';+ return (+ <li data-check={k.key} data-state={k.state} className={`border-t border-hairline py-2 first:border-t-0 ${hidePhone ? 'max-sm:hidden' : ''}`}>+ <div className="flex min-w-0 items-start gap-2.5">+ <Led s={STATE_LED[k.state]} className={ledClass} />+ <span className="sr-only">{STATE_WORD[k.state]}:</span>+ <div className="flex min-w-0 flex-1 flex-col gap-0.5 sm:flex-row sm:items-start sm:gap-3">+ <div className="min-w-0 sm:w-[168px] sm:shrink-0">+ <p className={`text-[13px] leading-[18px] ${dim ? 'text-zinc-500' : 'text-zinc-100'}`}>{CHECK_NAME[k.key]}</p>+ <p className="text-[11px] leading-[15px] text-zinc-500 [overflow-wrap:anywhere]">{toolLine(k.key, card)}</p>+ </div>+ <p className={`min-w-0 flex-1 text-meta [overflow-wrap:anywhere] ${tone}`}>{k.text}</p>+ </div>+ {found.length > 0 && (+ <button type="button" className={LINK} aria-expanded={show} aria-controls={id} onClick={() => setShow((s) => !s)}>+ {show ? 'Hide' : 'Show'}+ <span className="sr-only"> {CHECK_NAME[k.key]} findings</span>+ </button>+ )}+ </div>+ {show && found.length > 0 && (+ <ul id={id} role="list" className="mt-1.5 space-y-1 pl-[18px] sm:pl-[198px]">+ {found.map((f, i) => (+ <Finding key={f.id ?? `${f.title}-${i}`} f={f} />+ ))}+ </ul>+ )}+ </li>+ );+};++/** A one-line card (P0, retried, cleared and folded). */+const Line: React.FC<{ children: React.ReactNode; led?: 'ok' | 'off'; status?: boolean; extra?: React.ReactNode; phase: string }> = ({ children, led = 'off', status, extra, phase }) => (+ <div+ data-prepush-phase={phase}+ role={status ? 'status' : undefined}+ className="flex max-w-[640px] flex-wrap items-center gap-x-2.5 gap-y-1 rounded-xl border border-hairline bg-surface-main px-3 py-2 text-meta text-zinc-400"+ >+ <Led s={led} className="shrink-0" />+ <span className="min-w-0 flex-1 [overflow-wrap:anywhere]">{children}</span>+ {extra}+ </div>+);++export const PrepushCard: React.FC<PrepushCardProps> = ({ card, bot, onRetry, onOverride, live = false, startOverride = false, startUnfolded = false }) => {+ const phase = phaseOf(card);+ const [form, setForm] = useState(startOverride && canOverride(card));+ const [reason, setReason] = useState('');+ const [busy, setBusy] = useState<null | 'retry' | 'override'>(null);+ const [error, setError] = useState<string | null>(null);+ const [collapsed, setCollapsed] = useState(phase === 'P2' && !live);+ const [unfold, setUnfold] = useState(startUnfolded);+ const cardRef = useRef<HTMLElement>(null);+ const area = useRef<HTMLTextAreaElement>(null);+ const hintId = useId();+ const titleId = useId();++ // P2 → P2b: a card that turned clear while watched folds after about 2 s; history starts folded.+ useEffect(() => {+ if (phase !== 'P2') return;+ if (!live) {+ setCollapsed(true);+ return;+ }+ setCollapsed(false);+ const t = window.setTimeout(() => setCollapsed(true), 2000);+ return () => window.clearTimeout(t);+ }, [phase, live]);++ // The server moved the card on: drop a form that no longer applies.+ useEffect(() => {+ if (!canOverride(card)) setForm(false);+ setError(null);+ }, [card.status, card.id]);++ useEffect(() => {+ if (!form) return;+ area.current?.focus({ preventScroll: true });+ cardRef.current?.scrollIntoView?.({ block: 'nearest' });+ }, [form]);++ if (phase === 'P0') {+ return (+ <Line phase="P0" status>+ Nothing to check: <code className="dv-sha">{card.branch}</code> has no new commits. Nothing was pushed.+ </Line>+ );+ }+ if (phase === 'RT') {+ return (+ <Line phase="RT">+ You asked for a new check of <code className="dv-sha">{card.branch}</code>. {bot}'s next push of this commit is checked again from try 1.+ </Line>+ );+ }+ if (phase === 'P2' && collapsed) {+ return (+ <Line+ phase="P2b"+ led="ok"+ extra={+ <button type="button" className={LINK} aria-expanded={false} onClick={() => setCollapsed(false)}>+ Show checks <ChevronRight size={12} aria-hidden="true" />+ </button>+ }+ >+ {clearedLine(card)}+ </Line>+ );+ }++ const chip = statusChip(card);+ const fold = foldable(card) && passedRows(card).length > 1;+ const run = async (kind: 'retry' | 'override') => {+ if (busy) return;+ setBusy(kind);+ setError(null);+ try {+ if (kind === 'retry') await onRetry?.(card);+ else {+ await onOverride?.(card, reason);+ setForm(false);+ setReason('');+ }+ } catch (e) {+ setError(e instanceof Error && e.message ? e.message : 'Something went wrong. Try again.');+ } finally {+ setBusy(null);+ }+ };+ const retryLabel = card.status === 'failed' ? 'Run the checks again' : `Ask ${bot} to try again`;+ const ok = reasonOk(reason);++ return (+ <article+ ref={cardRef}+ data-prepush={card.id}+ data-prepush-phase={form ? 'P5' : phase}+ aria-labelledby={titleId}+ className="kw-card w-full max-w-[640px] p-3 sm:p-4"+ >+ <header className="flex flex-wrap items-start gap-x-3 gap-y-2">+ <span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg bg-zinc-800 text-zinc-300" aria-hidden="true">+ <ArrowUpFromLine size={15} />+ </span>+ <div className="min-w-0 flex-1 max-[420px]:min-w-[150px]">+ <h3 id={titleId} className="text-sm font-semibold text-zinc-100 [overflow-wrap:anywhere]">+ Before {bot} pushes+ </h3>+ <p className="mt-1 flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-meta text-zinc-400">+ <code className="dv-branch max-w-full">+ <GitBranch size={11} className="i" aria-hidden="true" />+ <span className="h [overflow-wrap:anywhere]">{card.branch}</span>+ </code>+ {card.diffstat && (+ <span className="inline-flex items-center gap-1.5 whitespace-nowrap">+ <span>+ {card.diffstat.files} {card.diffstat.files === 1 ? 'file' : 'files'}+ </span>+ <span aria-hidden="true">·</span>+ <DiffStat add={card.diffstat.add} del={card.diffstat.del} />+ </span>+ )}+ </p>+ </div>+ {chip && (+ <span data-prepush-chip aria-live="polite" className={`${CHIP[chip.tone]} shrink-0 max-[420px]:order-last max-[420px]:ml-10`}>+ {chip.led && <Led s={chip.led} className="dv-led-still" />}+ {chip.text}+ </span>+ )}+ </header>++ {card.checks.length > 0 && (+ <ul role="list" aria-label="Checks" className="mt-3 rounded-xl border border-hairline bg-[var(--dv-code-bg)] px-3">+ {fold && (+ <li data-fold className="border-t border-hairline py-2 first:border-t-0 sm:hidden">+ <div className="flex items-center gap-2.5">+ <Led s="ok" className="shrink-0" />+ <span className="min-w-0 flex-1 text-meta text-zinc-300 [overflow-wrap:anywhere]">{foldLine(card)}</span>+ <button type="button" className={LINK} aria-expanded={unfold} onClick={() => setUnfold((u) => !u)}>+ {unfold ? 'Hide' : 'Show'}+ <span className="sr-only"> passed checks</span>+ <ChevronDown size={12} aria-hidden="true" className={unfold ? 'rotate-180' : ''} />+ </button>+ </div>+ </li>+ )}+ {card.checks.map((k) => (+ <Row key={k.key} k={k} card={card} hidePhone={(fold && k.state === 'pass' && !unfold) || k.state === 'not_installed'} />+ ))}+ </ul>+ )}++ {/* Footer per phase */}+ {!form && phase === 'P1' && <p className="mt-3 text-meta text-zinc-400">{footer(card, bot)}</p>}++ {!form && phase === 'P2' && (+ <p className="mt-3 flex items-center gap-2 text-meta text-zinc-300">+ <span className="min-w-0 flex-1">{footer(card, bot)}</span>+ {!live && (+ <button type="button" className={LINK} onClick={() => setCollapsed(true)}>+ Hide checks+ </button>+ )}+ </p>+ )}++ {!form && phase === 'P3' && (+ <div className="mt-3 flex flex-col gap-2 sm:flex-row sm:items-center sm:gap-3">+ <p className="flex min-w-0 flex-1 items-start gap-2 text-meta text-zinc-300">+ <Led s="run" className="dv-led-still mt-[5px] shrink-0" />+ <span className="min-w-0">+ <strong className="font-semibold text-zinc-100">{bot} is fixing them.</strong> {footer(card, bot)}+ </span>+ </p>+ {onOverride && (+ <button type="button" className={PLAIN} onClick={() => setForm(true)}>+ Push anyway…+ </button>+ )}+ </div>+ )}++ {!form && phase === 'P7' && (+ <div className="mt-3 flex flex-col gap-2">+ <p className="text-meta text-zinc-300">{footer(card, bot)}</p>+ <div className="flex flex-col gap-2 sm:flex-row">+ {onRetry && (+ <button type="button" className={PLAIN} disabled={busy !== null} onClick={() => void run('retry')}>+ {busy === 'retry' ? 'Asking…' : 'Run the checks again'}+ </button>+ )}+ {onOverride && (+ <button type="button" className={PLAIN} onClick={() => setForm(true)}>+ Push anyway…+ </button>+ )}+ </div>+ </div>+ )}++ {!form && phase === 'P4' && (+ <div data-needs-you role="alert" className="mt-3 rounded-xl border border-amber-400/40 bg-amber-400/[.06] p-3">+ <p className="text-meta text-zinc-200">+ <strong className="font-semibold text-amber-200">{needsYouLead(card, bot)}</strong> {footer(card, bot)}+ </p>+ {(onRetry || onOverride) && (+ <div className="mt-2.5 flex flex-col gap-2 sm:flex-row">+ {onRetry && (+ <button type="button" className={PRIMARY} style={{ background: 'var(--accent-gradient)' }} disabled={busy !== null} onClick={() => void run('retry')}>+ {busy === 'retry' ? 'Asking…' : retryLabel}+ </button>+ )}+ {onOverride && (+ <button type="button" className={AMBER_OUTLINE} disabled={busy !== null} onClick={() => setForm(true)}>+ Push anyway…+ </button>+ )}+ </div>+ )}+ </div>+ )}++ {form && (+ <form+ data-override-form+ className="mt-3 rounded-xl border border-amber-400/40 bg-amber-400/[.06] p-3"+ onSubmit={(e) => {+ e.preventDefault();+ if (ok) void run('override');+ }}+ >+ <p className="text-sm font-semibold text-zinc-100">Push anyway?</p>+ <p className="mt-1 text-meta text-zinc-300">Say why. Your reason is saved on this card, so anyone who looks at this push later sees it.</p>+ <label htmlFor={`${hintId}-r`} className="mt-2.5 block text-meta font-medium text-zinc-200">+ Your reason+ </label>+ <textarea+ id={`${hintId}-r`}+ ref={area}+ required+ rows={3}+ maxLength={MAX_REASON}+ value={reason}+ aria-describedby={hintId}+ placeholder="e.g. the key is a revoked test key"+ onChange={(e) => setReason(e.target.value)}+ onKeyDown={(e) => {+ if (e.key === 'Escape') {+ e.stopPropagation();+ setForm(false);+ }+ }}+ className="mt-1 block w-full resize-y rounded-lg border border-hairline-strong bg-zinc-950/60 px-2.5 py-2 text-base text-zinc-100 placeholder:text-zinc-500 outline-none focus-visible:ring-2 focus-visible:ring-sky-400 sm:text-sm"+ />+ <p id={hintId} className="mt-1 text-[11px] leading-[15px] text-zinc-400">+ Needed, at least {MIN_REASON} characters. This push only; next time the checks run again.+ </p>+ <div className="mt-2.5 flex flex-col gap-2 sm:flex-row">+ <button type="submit" className={AMBER} disabled={!ok || busy !== null}>+ {busy === 'override' ? 'Letting it go…' : 'Push anyway'}+ </button>+ <button type="button" className={PLAIN} disabled={busy !== null} onClick={() => setForm(false)}>+ Cancel+ </button>+ </div>+ </form>+ )}++ {phase === 'P6' && (+ <div className="mt-3 text-meta text-zinc-300">+ <p>{overriddenLine(card)}</p>+ {card.override?.reason && (+ <blockquote className="mt-1.5 border-l-2 border-zinc-600 pl-2 italic text-zinc-300 [overflow-wrap:anywhere]">+ <span className="sr-only">Your reason: </span>+ {card.override.reason}+ </blockquote>+ )}+ </div>+ )}++ {error && (+ <p role="alert" className="mt-2 text-meta text-bad [overflow-wrap:anywhere]">+ {error}+ </p>+ )}+ </article>+ );+};diff --git a/frontend/src/components/dev/PrepushThread.tsx b/frontend/src/components/dev/PrepushThread.tsxnew file mode 100644index 00000000..c6aa992c--- /dev/null+++ b/frontend/src/components/dev/PrepushThread.tsx@@ -0,0 +1,127 @@+// 0.8.0 B3: where pre-push cards live. One hook per space keeps the list (GET on open, then one+// GET per `dev_prepush` event); the bot's thread shows that bot's cards, and the Inbox shows the+// ones that need the person. The Inbox item is derived here from `needs_you` (the server makes+// none: fresh-eyes-audit.md §4.6, open question 7), so it resolves as soon as the card moves on.++import React, { useCallback, useEffect, useRef, useState } from 'react';+import { ArrowUpFromLine } from 'lucide-react';+import { PrepushCard } from './PrepushCard';+import { PREPUSH_EVENT, inboxLine, needsYou, prepushApi, upsert, type PrepushCard as Card } from '../../dev/prepush';++export interface PrepushEventDetail {+ space_id: string;+ id: string;+ kwant_id?: string;+ status?: string;+}++export interface PrepushState {+ cards: Card[];+ /** Ids that turned clear while this page was open (P2 shows, then folds). */+ live: ReadonlySet<string>;+ put: (c: Card) => void;+}++type Api = Pick<typeof prepushApi, 'list' | 'get'>;++export function usePrepushCards(spaceId: string, on: boolean, api: Api = prepushApi): PrepushState {+ const [cards, setCards] = useState<Card[]>([]);+ const [live, setLive] = useState<ReadonlySet<string>>(new Set());+ const seen = useRef(new Map<string, string>());++ const put = useCallback((c: Card) => {+ const before = seen.current.get(c.id);+ seen.current.set(c.id, c.status);+ if (c.status === 'clear' && before !== undefined && before !== 'clear') setLive((s) => new Set(s).add(c.id));+ setCards((list) => upsert(list, c));+ }, []);++ useEffect(() => {+ setCards([]);+ setLive(new Set());+ seen.current = new Map();+ if (!on || !spaceId) return;+ let alive = true;+ api.list(spaceId).then(+ (list) => {+ if (!alive) return;+ for (const c of list) seen.current.set(c.id, c.status);+ setCards(list);+ },+ () => undefined,+ );+ const onEvent = (e: Event) => {+ const d = (e as CustomEvent<PrepushEventDetail>).detail;+ if (!d || d.space_id !== spaceId || typeof d.id !== 'string') return;+ api.get(d.id).then((c) => alive && put(c), () => undefined);+ };+ window.addEventListener(PREPUSH_EVENT, onEvent);+ return () => {+ alive = false;+ window.removeEventListener(PREPUSH_EVENT, onEvent);+ };+ }, [spaceId, on, api, put]);++ return { cards, live, put };+}++/** How many of a bot's cards the thread shows: the newest few, oldest first like the chat. */+export const THREAD_CARDS = 3;++export function threadCards(cards: Card[], kwantId: string): Card[] {+ return cards+ .filter((c) => c.kwant_id === kwantId)+ .slice()+ .sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0))+ .slice(0, THREAD_CARDS)+ .reverse();+}++export const PrepushThread: React.FC<{+ cards: Card[];+ bot: string;+ live: ReadonlySet<string>;+ onRetry?: (c: Card) => Promise<void>;+ onOverride?: (c: Card, reason: string) => Promise<void>;+}> = ({ cards, bot, live, onRetry, onOverride }) => {+ if (cards.length === 0) return null;+ return (+ <section aria-label={`Checks before ${bot} pushes`} data-prepush-thread className="space-y-2">+ {cards.map((c) => (+ <div key={c.id} id={`prepush-${c.id}`} className="scroll-mt-4">+ <PrepushCard card={c} bot={bot} live={live.has(c.id)} onRetry={onRetry} onOverride={onOverride} />+ </div>+ ))}+ </section>+ );+};++/** The Inbox's "Needs you" rows for pushes waiting on the person (Mira P4). */+export const PrepushNeedsYou: React.FC<{ cards: Card[]; names: Record<string, string>; onOpen: (c: Card) => void }> = ({ cards, names, onOpen }) => {+ const list = needsYou(cards);+ if (list.length === 0) return null;+ return (+ <section aria-labelledby="needs-prepush-h" data-needs-prepush>+ <h3 id="needs-prepush-h" className="mb-2 flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-wider text-zinc-500">+ <ArrowUpFromLine size={12} aria-hidden="true" />+ Needs you+ </h3>+ <ul role="list" className="space-y-2">+ {list.map((c) => (+ <li key={c.id}>+ <button+ type="button"+ data-needs-prepush-item={c.id}+ onClick={() => onOpen(c)}+ className="flex min-h-11 w-full items-center gap-2.5 rounded-xl border border-amber-500/30 bg-amber-950/20 px-3.5 py-2.5 text-left text-sm text-zinc-200 outline-none hover:bg-amber-950/30 focus-visible:ring-2 focus-visible:ring-sky-400 sm:px-4"+ >+ <span className="kw-chip kw-chip-warn shrink-0">Needs you</span>+ <span className="min-w-0 flex-1 [overflow-wrap:anywhere]">{inboxLine(c, names[c.kwant_id] || 'A bot')}</span>+ <code className="dv-sha max-w-[40%] shrink truncate max-sm:hidden">{c.branch}</code>+ </button>+ </li>+ ))}+ </ul>+ </section>+ );+};diff --git a/frontend/src/components/dev/ReviewCard.tsx b/frontend/src/components/dev/ReviewCard.tsxindex 653e145b..5b51f03b 100644--- a/frontend/src/components/dev/ReviewCard.tsx+++ b/frontend/src/components/dev/ReviewCard.tsx@@ -12,6 +12,7 @@ import {X,GitBranch,} from 'lucide-react';+import { FreshEyesChip } from './FreshEyesChip';import type { DevFinding, FindingAction, Forge, ReviewCard as Review, ReviewCardProps, Severity, TamperFlag } from '../../dev/types';import {clock,@@ -126,6 +127,16 @@ const SecTile: React.FC<{ name: string; tool: string; mono: string; state: 'pass);};+/** 0.8.0 B3: the semgrep tile from the real run. Not installed (or no repo rules) is the dashed+ * `later` look, "Not installed. Optional."; a PR card that never ran it says so plainly. */+export function semgrepTile(s: Review['security']['semgrep'] | undefined): { state: 'pass' | 'hit' | 'not_run' | 'later'; text: string } {+ if (!s) return { state: 'later', text: 'Runs before a push, not on pull requests' };+ if (s.state === 'pass') return { state: 'pass', text: 'No matches' };+ if (s.state === 'hit') return { state: 'hit', text: `${s.count} ${s.count === 1 ? 'match' : 'matches'} · see finding` };+ if (s.reason && /isn't installed|no \.semgrep/.test(s.reason)) return { state: 'later', text: 'Not installed. Optional.' };+ return { state: 'not_run', text: s.reason ? `Didn't run: ${s.reason}` : "Didn't run" };+}+const scanText = (s: { state: 'pass' | 'hit' | 'not_run'; count: number }, one: string, many: string, clean: string) =>s.state === 'not_run' ? 'Not run' : s.state === 'pass' ? clean : `${s.count} ${s.count === 1 ? one : many} · see finding`;@@ -476,7 +487,7 @@ export const ReviewCard: React.FC<ReviewCardProps> = ({ card: given, onFinding,const onRows = matchFindingIds(ticketMatches);const listed = onRows.size ? card.findings.filter((f) => !onRows.has(f.id)) : card.findings;const summary = findingsSummary(listed);- const sec = card.security as Review['security'] & { osv?: unknown; semgrep?: unknown };+ const sec = card.security as Review['security'] & { osv?: unknown };const stamp = lgtm(card) && card.reviewer ? card.reviewer.name : null;const repoChip = repoLabel ? repoLabel(card.repo, card.repo_name) : null;@@ -553,8 +564,10 @@ export const ReviewCard: React.FC<ReviewCardProps> = ({ card: given, onFinding,</span>)}</div>- <div className="mt-1.5 flex flex-wrap gap-1.5">+ <div className="relative mt-1.5 flex flex-wrap gap-1.5">{card.reviewer && (card.same_engine ? <span className="kw-chip kw-chip-warn">Same engine as the author</span> : <span className="kw-chip kw-chip-accent">Different engine from the author</span>)}+ {/* 0.8.0 B3: how the review was run, right after the engine chip (Mira b3 §1). */}+ <FreshEyesChip label={card.fresh_eyes} reviewer={card.reviewer?.name ?? null} author={author?.name ?? null} specRef={ticketMatches?.key ?? null} />{!card.reviewer && <span className="kw-chip kw-chip-warn">{card.note ?? 'No reviewer yet'}</span>}</div></div>@@ -674,7 +687,7 @@ export const ReviewCard: React.FC<ReviewCardProps> = ({ card: given, onFinding,<SecTile name="Secrets" tool="Gitleaks" mono="gitleaks" state={sec.secrets.state} text={scanText(sec.secrets, 'secret', 'secrets', 'None found')} /><SecTile name="New packages" tool="Registry check" mono="registry" state={sec.packages.state} text={scanText(sec.packages, 'package', 'packages', 'All real')} /><SecTile name="Dependencies" tool="OSV" mono="osv" state="later" text="in 0.7.x" />- <SecTile name="Code patterns" tool="Semgrep" mono="semgrep" state="later" text="in 0.7.x" />+ <SecTile name="Code patterns" tool="Semgrep" mono="semgrep" {...semgrepTile(sec.semgrep)} /></ul></section>diff --git a/frontend/src/dev/freshEyes.ts b/frontend/src/dev/freshEyes.tsnew file mode 100644index 00000000..b3c40557--- /dev/null+++ b/frontend/src/dev/freshEyes.ts@@ -0,0 +1,88 @@+// 0.8.0 B3: the "Checked with fresh eyes" label (Mira b3-fresh-eyes.md §1, Juno fresh-eyes-audit.md §3).+// It says how a review was run; it isn't earned, so it never looks like a badge.++const isObj = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);++export const SAW_PARTS = ['brief', 'spec', 'result', 'diff'] as const;+export type SawPart = (typeof SAW_PARTS)[number];+export const SPEC_SOURCES = ['written', 'acceptance', 'brief', 'ticket', 'pr', 'none'] as const;+export type SpecSource = (typeof SPEC_SOURCES)[number];++export interface FreshEyes {+ checked: boolean;+ saw: SawPart[];+ spec_source: SpecSource;+ reviewer_kwant_id: string | null;+}++/** null for anything that isn't a label (cards from before 0.8.0 have none: R3). */+export function parseFreshEyes(v: unknown): FreshEyes | null {+ if (!isObj(v) || typeof v.checked !== 'boolean') return null;+ const saw: SawPart[] = [];+ for (const s of Array.isArray(v.saw) ? v.saw : []) {+ const p = SAW_PARTS.find((x) => x === s);+ if (p && !saw.includes(p)) saw.push(p);+ }+ const src = SPEC_SOURCES.find((x) => x === v.spec_source) ?? 'none';+ const rk = typeof v.reviewer_kwant_id === 'string' && v.reviewer_kwant_id.trim() ? v.reviewer_kwant_id.slice(0, 120) : null;+ return { checked: v.checked, saw, spec_source: src, reviewer_kwant_id: rk };+}++/** R1: the chip with its popover. R2: a grey "Saw the author's chat". R3: no chip. */+export type ChipState = 'R1' | 'R2' | 'R3';++export function chipState(fe: FreshEyes | null | undefined): ChipState {+ if (!fe) return 'R3';+ if (fe.checked) return 'R1';+ // A failed review is checked:false with nothing seen: no chip, never R2 (contract §3.3).+ return fe.saw.length > 0 ? 'R2' : 'R3';+}++export interface SawLine {+ ok: boolean;+ text: string;+}++const SPEC_TEXT: Record<SpecSource, string | null> = {+ ticket: "the ticket's brief and done-when lines",+ brief: "the task's brief",+ written: "the owner's written spec",+ acceptance: "the task's acceptance lines",+ pr: "only the PR's title and description, in the author's own words",+ none: null,+};++/**+ * The popover's list, in the server's order. `diff` is the diffstat the card already shows+ * (never recounted here); `ref` names the ticket when the card has one ("#212").+ */+export function sawLines(+ fe: FreshEyes,+ opts: { author: string | null; diff?: { files: number; add: number; del: number } | null; ref?: string | null },+): SawLine[] {+ const out: SawLine[] = [];+ let briefDone = false;+ for (const part of fe.saw) {+ if (part === 'brief' || part === 'spec') {+ if (briefDone) continue;+ briefDone = true;+ const base = SPEC_TEXT[fe.spec_source] ?? (part === 'spec' ? 'the spec' : 'the brief');+ out.push({ ok: true, text: opts.ref && fe.spec_source === 'ticket' ? `${base} (${opts.ref})` : base });+ } else if (part === 'diff') {+ const d = opts.diff;+ out.push({+ ok: true,+ text: d ? `the diff (${d.files} ${d.files === 1 ? 'file' : 'files'}, +${d.add} −${d.del})` : 'the diff',+ });+ } else if (part === 'result') {+ out.push({ ok: true, text: 'the result' });+ }+ }+ // `pr` reviews see no brief entry in `saw`, only the diff; still say what the brief was.+ if (!briefDone && fe.spec_source === 'pr') out.unshift({ ok: true, text: SPEC_TEXT.pr! });+ if (fe.checked) out.push({ ok: false, text: `Not ${opts.author ?? "the author"}'s conversation or reasoning` });+ return out;+}++export const popoverTitle = (reviewer: string | null): string =>+ `${reviewer ?? 'The reviewer'} reviewed with fresh eyes. They saw only what a new teammate would get:`;diff --git a/frontend/src/dev/prepush.ts b/frontend/src/dev/prepush.tsnew file mode 100644index 00000000..103e5a07--- /dev/null+++ b/frontend/src/dev/prepush.ts@@ -0,0 +1,434 @@+// 0.8.0 B3: the pre-push card (Mira's design b3-fresh-eyes.md §2, Juno's contract+// fresh-eyes-audit.md §4). The server decides every state and every number; this module only+// reads the card, maps it to Mira's P0–P7, and calls the four routes.++import { personFetch } from '../auth';+import { DevModeError } from '../devMode';+import { parseFreshEyes, type FreshEyes } from './freshEyes';++const isObj = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v);+const str = (v: unknown, max = 2000): string | null => (typeof v === 'string' && v.trim() !== '' ? v.slice(0, max) : null);+const num = (v: unknown): number | null => (typeof v === 'number' && Number.isFinite(v) ? v : null);+const oneOf = <T extends string>(v: unknown, all: readonly T[], fallback: T): T => (all.includes(v as T) ? (v as T) : fallback);+const arr = (v: unknown): unknown[] => (Array.isArray(v) ? v : []);++/** The event the app re-dispatches when the stream sends `dev_prepush`. */+export const PREPUSH_EVENT = 'kwant:dev-prepush';+export const MIN_REASON = 10;+export const MAX_REASON = 2000;+/** Server rule: needs_you once a blocked or failed card reaches this try. */+export const NEEDS_YOU_TRIES = 2;++export const PREPUSH_STATUSES = ['checking', 'clear', 'blocked', 'failed', 'overridden', 'retried'] as const;+export type PrepushStatus = (typeof PREPUSH_STATUSES)[number];+export const CHECK_KEYS = ['secrets', 'pkgs', 'tests', 'risk', 'review', 'semgrep'] as const;+export type CheckKey = (typeof CHECK_KEYS)[number];+export const CHECK_STATES = ['running', 'pass', 'hit', 'error', 'not_installed'] as const;+export type CheckState = (typeof CHECK_STATES)[number];+export type FindingSource = 'review' | 'gitleaks' | 'packages' | 'tamper' | 'semgrep' | 'kwant';++export interface PrepushCheck {+ key: CheckKey;+ state: CheckState;+ text: string;+ required: boolean;+}++export interface PrepushFinding {+ id: string | null;+ source: FindingSource;+ severity: 'critical' | 'high' | 'medium' | 'low';+ title: string;+ file: string | null;+ line: number | null;+ detail: string | null;+ open: boolean;+}++export interface PrepushCard {+ id: string;+ space_id: string | null;+ kwant_id: string;+ branch: string;+ head_sha: string | null;+ status: PrepushStatus;+ tries: number;+ needs_you: boolean;+ no_change: boolean;+ diffstat: { files: number; add: number; del: number } | null;+ checks: PrepushCheck[];+ blockers: PrepushFinding[];+ override: { by: string | null; reason: string; at: number | null } | null;+ findings: PrepushFinding[];+ reviewer: { name: string; engine: string | null; model: string | null } | null;+ fresh_eyes: FreshEyes | null;+ error: string | null;+ created_at: number | null;+ updated_at: number | null;+}++const SOURCES = ['review', 'gitleaks', 'packages', 'tamper', 'semgrep', 'kwant'] as const;++function pfinding(v: unknown): PrepushFinding | null {+ if (!isObj(v)) return null;+ const title = str(v.title, 300);+ if (!title) return null;+ const line = num(v.line);+ return {+ id: str(v.id, 80),+ source: oneOf(v.source, SOURCES, 'kwant'),+ severity: oneOf(v.severity, ['critical', 'high', 'medium', 'low'] as const, 'high'),+ title,+ file: str(v.file, 400),+ line: line !== null && line > 0 ? Math.floor(line) : null,+ detail: str(v.detail, 1200),+ open: (str(v.state, 20) ?? 'open') === 'open',+ };+}++function check(v: unknown): PrepushCheck | null {+ if (!isObj(v)) return null;+ const key = CHECK_KEYS.find((k) => k === v.key);+ const state = CHECK_STATES.find((s) => s === v.state);+ const text = str(v.text, 400);+ if (!key || !state || !text) return null;+ return { key, state, text, required: v.required !== false && key !== 'semgrep' };+}++function diffstat(v: unknown): PrepushCard['diffstat'] {+ if (!isObj(v)) return null;+ const files = num(v.files);+ const add = num(v.add);+ const del = num(v.del);+ if (files === null || add === null || del === null || files < 0 || add < 0 || del < 0) return null;+ return { files, add, del };+}++/** One card from the server, or null when it isn't one we can show honestly. */+export function parsePrepush(raw: unknown): PrepushCard | null {+ if (!isObj(raw)) return null;+ const id = str(raw.id, 120);+ const kwant = str(raw.kwant_id, 120);+ const branch = str(raw.branch, 200);+ const status = PREPUSH_STATUSES.find((s) => s === raw.status);+ if (!id || !kwant || !branch || !status) return null;+ const rawChecks = arr(raw.checks);+ const checks = rawChecks.map(check).filter((c): c is PrepushCheck => !!c);+ // A row we can't read would be a check we'd silently drop: refuse the card instead.+ if (checks.length !== rawChecks.length) return null;+ const inner = isObj(raw.card) ? raw.card : null;+ const ov = isObj(raw.override) ? raw.override : null;+ const rv = inner && isObj(inner.reviewer) ? inner.reviewer : null;+ const tries = num(raw.tries);+ return {+ id,+ space_id: str(raw.space_id, 120),+ kwant_id: kwant,+ branch,+ head_sha: str(raw.head_sha, 64),+ status,+ tries: tries !== null && tries >= 1 ? Math.floor(tries) : 1,+ needs_you: raw.needs_you === true && (status === 'blocked' || status === 'failed'),+ no_change: raw.no_change === true,+ diffstat: diffstat(raw.diffstat),+ checks,+ blockers: arr(raw.blockers).map(pfinding).filter((f): f is PrepushFinding => !!f),+ override: ov ? { by: str(ov.by, 80), reason: str(ov.reason, MAX_REASON) ?? '', at: num(ov.at) } : null,+ findings: inner ? arr(inner.findings).map(pfinding).filter((f): f is PrepushFinding => !!f) : [],+ reviewer: rv && str(rv.name, 80) ? { name: str(rv.name, 80)!, engine: str(rv.engine, 40), model: str(rv.model, 80) } : null,+ fresh_eyes: inner ? parseFreshEyes(inner.fresh_eyes) : null,+ error: inner ? str(inner.error, 400) : null,+ created_at: num(raw.created_at),+ updated_at: num(raw.updated_at),+ };+}++export function parsePrepushList(raw: unknown): PrepushCard[] {+ const list = isObj(raw) ? arr(raw.cards) : arr(raw);+ return list.map(parsePrepush).filter((c): c is PrepushCard => !!c);+}++// ---------------------------------------------------------------------------------------------+// Mira's phases++export type Phase =+ | 'P0' // nothing to push+ | 'P1' // running+ | 'P2' // all clear+ | 'P3' // blocked, the bot is fixing+ | 'P4' // needs you+ | 'P6' // pushed anyway (overridden)+ | 'P7' // a check couldn't run (failed, before needs_you)+ | 'RT'; // the person asked for a re-check (retried)++export function phaseOf(c: PrepushCard): Phase {+ switch (c.status) {+ case 'checking':+ return 'P1';+ case 'clear':+ return c.no_change ? 'P0' : 'P2';+ case 'blocked':+ return c.needs_you ? 'P4' : 'P3';+ case 'failed':+ return c.needs_you ? 'P4' : 'P7';+ case 'overridden':+ return 'P6';+ case 'retried':+ return 'RT';+ }+}++/** Phases where "Push anyway…" is offered: the server only takes an override on blocked or failed. */+export const canOverride = (c: PrepushCard): boolean => c.status === 'blocked' || c.status === 'failed';+export const canRetry = canOverride;++/** Open findings that hold the push. The server's `blockers` list; counted, never computed further. */+export const openCount = (c: PrepushCard): number => {+ // "kwant couldn't check" and "the review didn't finish" hold the push too, but they aren't findings.+ const reviewFailed = c.checks.some((k) => k.key === 'review' && k.state === 'error');+ return c.blockers.filter((b) => b.source !== 'kwant' && !(reviewFailed && b.source === 'review')).length;+};++export type ChipTone = 'plain' | 'ok' | 'bad' | 'warn';+export interface StatusChip {+ tone: ChipTone;+ text: string;+ led: 'run' | null;+}++const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;++export function statusChip(c: PrepushCard): StatusChip | null {+ switch (phaseOf(c)) {+ case 'P0':+ return null;+ case 'P1':+ // The server marks every row running until the check settles, so there's no partial count.+ return { tone: 'plain', text: 'Checking', led: 'run' };+ case 'P2':+ return { tone: 'ok', text: 'Clear', led: null };+ case 'P3':+ return { tone: 'bad', text: openCount(c) > 0 ? `${openCount(c)} to fix` : 'Blocked', led: null };+ case 'P4':+ return { tone: 'warn', text: 'Needs you', led: null };+ case 'P6':+ return { tone: 'plain', text: 'Pushed anyway', led: null };+ case 'P7':+ return { tone: 'plain', text: "Couldn't check", led: null };+ case 'RT':+ return { tone: 'plain', text: 'Checking again', led: null };+ }+}++// ---------------------------------------------------------------------------------------------+// Rows++export const CHECK_NAME: Record<CheckKey, string> = {+ secrets: 'Secrets',+ pkgs: 'New packages',+ tests: 'Tests',+ risk: 'Risk rules',+ review: 'Fresh-eyes review',+ semgrep: 'Code patterns',+};++/** Mira's tool line. The review row names the reviewer when the card has one. */+export function toolLine(key: CheckKey, c: PrepushCard): string {+ switch (key) {+ case 'secrets':+ return 'gitleaks';+ case 'pkgs':+ return 'package registry';+ case 'tests':+ return 'tamper check';+ case 'risk':+ return 'built-in rules';+ case 'review':+ return c.reviewer ? (c.reviewer.engine ? `${c.reviewer.name} on ${c.reviewer.engine}` : c.reviewer.name) : 'another bot';+ case 'semgrep':+ return 'semgrep · optional';+ }+}++/** Short tool names for the folded "N checks passed · …" row on phone. */+export const FOLD_TOOL: Record<CheckKey, string> = {+ secrets: 'gitleaks',+ pkgs: 'registry',+ tests: 'tamper',+ risk: 'rules',+ review: 'review',+ semgrep: 'semgrep',+};++/** The visually hidden word next to each LED (colour is never the only signal). */+export const STATE_WORD: Record<CheckState, string> = {+ pass: 'passed',+ hit: 'found a problem',+ running: 'running',+ error: 'could not run',+ not_installed: 'not installed',+};++export const STATE_LED: Record<CheckState, 'ok' | 'bad' | 'run' | 'off'> = {+ pass: 'ok',+ hit: 'bad',+ running: 'run',+ error: 'off',+ not_installed: 'off',+};++const ROW_SOURCES: Record<CheckKey, FindingSource[]> = {+ secrets: ['gitleaks'],+ pkgs: ['packages'],+ tests: ['tamper'],+ risk: [],+ review: ['review'],+ semgrep: ['semgrep'],+};++/** What "Show" opens on a row that found something: the open findings behind it, from the card. */+export function rowFindings(c: PrepushCard, key: CheckKey): PrepushFinding[] {+ const src = ROW_SOURCES[key];+ if (src.length === 0) return [];+ const fromFindings = c.findings.filter((f) => f.open && src.includes(f.source));+ if (fromFindings.length > 0) return fromFindings;+ return c.blockers.filter((f) => src.includes(f.source));+}++/** Rows folded into one on phone (P3–P6): passing rows only; findings always show. */+export function foldable(c: PrepushCard): boolean {+ const p = phaseOf(c);+ return p === 'P3' || p === 'P4' || p === 'P6' || p === 'P7';+}++export function passedRows(c: PrepushCard): PrepushCheck[] {+ return c.checks.filter((k) => k.state === 'pass');+}++export function foldLine(c: PrepushCard): string {+ const passed = passedRows(c);+ return [`${plural(passed.length, 'check')} passed`, ...passed.map((k) => FOLD_TOOL[k.key])].join(' · ');+}++/** Required rows that passed: what P2b's "after N checks passed" counts. Server states only. */+export const requiredPassed = (c: PrepushCard): number => c.checks.filter((k) => k.required && k.state === 'pass').length;++// ---------------------------------------------------------------------------------------------+// Copy++export function hhmm(ms: number | null): string | null {+ if (ms === null) return null;+ const d = new Date(ms);+ if (Number.isNaN(d.getTime())) return null;+ return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`;+}++export function footer(c: PrepushCard, bot: string): string {+ switch (phaseOf(c)) {+ case 'P0':+ return `Nothing to check: ${c.branch} has no new commits. Nothing was pushed.`;+ case 'P1':+ return 'The push waits until these finish. Usually under a minute; the review takes longest.';+ case 'P2':+ return `All clear. ${bot} can push now.`;+ case 'P3':+ return `The push waits, then every check runs again. Try ${c.tries} of ${NEEDS_YOU_TRIES}.`;+ case 'P4':+ return `The push is waiting for you. It's also in your Inbox.`;+ case 'P6':+ return '';+ case 'P7':+ return "A check couldn't run, so this push can't count as checked. Run the checks again, or push anyway with a reason.";+ case 'RT':+ return `You asked for a new check. ${bot}'s next push of this commit is checked again from try 1.`;+ }+}++export function needsYouLead(c: PrepushCard, bot: string): string {+ const n = openCount(c);+ if (n === 0)+ return `${bot}'s push couldn't be checked after ${plural(c.tries, 'try', 'tries')}.`;+ return `${bot} couldn't clear ${plural(Math.max(n, 1), 'finding')} after ${plural(c.tries, 'try', 'tries')}.`;+}++export function clearedLine(c: PrepushCard): string {+ const at = hhmm(c.updated_at);+ return `Cleared to push ${c.branch} after ${plural(requiredPassed(c), 'check')} passed${at ? ` · ${at}` : ''}`;+}++export function overriddenLine(c: PrepushCard): string {+ const at = hhmm(c.override?.at ?? null);+ const n = openCount(c);+ return `You let this push go${at ? ` at ${at}` : ''} with ${plural(n, 'finding')} open. It covers this commit only.`;+}++export function inboxLine(c: PrepushCard, bot: string): string {+ const n = openCount(c);+ if (n === 0) return `${bot}'s push is waiting for you: the checks couldn't run`;+ return `${bot}'s push is waiting for you: ${plural(n, 'finding')} open`;+}++/** What "Ask {bot} to try again" sends through the normal chat send after /retry. */+export const retryMessage = (c: PrepushCard): string =>+ `I asked for a new check of your push of ${c.branch}. Fix what the pre-push card found, commit, and run the same push again.`;++export const overrideMessage = (c: PrepushCard): string =>+ `I let your push of ${c.branch} go anyway, for this commit only. Run the same push again.`;++export const reasonOk = (s: string): boolean => s.trim().length >= MIN_REASON && s.trim().length <= MAX_REASON;++// ---------------------------------------------------------------------------------------------+// Needs you (Inbox)++/** One Inbox item per card that needs the person, newest first. Derived from the cards only. */+export function needsYou(cards: PrepushCard[]): PrepushCard[] {+ return cards.filter((c) => c.needs_you).sort((a, b) => (b.updated_at ?? 0) - (a.updated_at ?? 0));+}++/** Merge a fetched card into a list (newest first), replacing the same id. */+export function upsert(list: PrepushCard[], c: PrepushCard): PrepushCard[] {+ const rest = list.filter((x) => x.id !== c.id);+ return [c, ...rest].sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0));+}++// ---------------------------------------------------------------------------------------------+// API++async function call(url: string, method = 'GET', body?: unknown): Promise<unknown> {+ let res: Response;+ try {+ res = await personFetch(url, {+ method,+ cache: 'no-store',+ headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },+ body: body === undefined ? undefined : JSON.stringify(body),+ });+ } catch {+ throw new DevModeError('Couldn’t reach the server. Check your connection and try again.', 0);+ }+ const data: unknown = await res.json().catch(() => null);+ if (res.ok) return data;+ const o = isObj(data) ? data : {};+ const code = typeof o.code === 'string' ? o.code : null;+ const msg =+ code === 'reason_needed'+ ? `Give a reason of at least ${MIN_REASON} characters.`+ : res.status === 409+ ? 'This card moved on in the meantime. It shows where it is now.'+ : `Something went wrong (HTTP ${res.status}).`;+ throw new DevModeError(msg, res.status, code);+}++function one(data: unknown): PrepushCard {+ const c = parsePrepush(data);+ if (!c) throw new DevModeError('The server sent a card this page can’t read.', 200, 'bad_card');+ return c;+}++export const prepushApi = {+ list: async (spaceId: string): Promise<PrepushCard[]> => parsePrepushList(await call(`/api/spaces/${encodeURIComponent(spaceId)}/dev/prepush`)),+ get: async (id: string): Promise<PrepushCard> => one(await call(`/api/dev/prepush/${encodeURIComponent(id)}`)),+ override: async (id: string, reason: string): Promise<PrepushCard> =>+ one(await call(`/api/dev/prepush/${encodeURIComponent(id)}/override`, 'POST', { reason: reason.trim() })),+ retry: async (id: string): Promise<PrepushCard> => one(await call(`/api/dev/prepush/${encodeURIComponent(id)}/retry`, 'POST')),+};diff --git a/frontend/src/dev/prepushFixtures.ts b/frontend/src/dev/prepushFixtures.tsnew file mode 100644index 00000000..908647ee--- /dev/null+++ b/frontend/src/dev/prepushFixtures.ts@@ -0,0 +1,138 @@+// 0.8.0 B3 demo data: pre-push cards shaped exactly like Juno's `card_json` (ba2157a5,+// src/server/dev/prepush.rs) and fresh-eyes labels from fresh-eyes-audit.md §3. Demo names only+// (bot Pixel, reviewer Iris, branch pixel/inbox-empty-state, a fake key in a fixture file).++export const PP_T0 = Date.UTC(2026, 10, 9, 14, 0);+const min = 60_000;++const reviewer = { name: 'Iris', engine: 'claude', model: 'Claude Opus' };+const fe = { checked: true, saw: ['diff'], spec_source: 'pr', reviewer_kwant_id: 'k_iris' };+const diffstat = { files: 4, add: 86, del: 21 };++const KEY_FINDING = {+ id: 'g1', source: 'gitleaks', severity: 'critical', title: 'A key-shaped string in a test fixture',+ file: 'frontend/tests/fixtures/inbox.json', line: 14, detail: 'Looks like an API key (sk-demo…). Use a placeholder.', state: 'open',+};+const NIT = { id: 'r1', source: 'review', severity: 'low', title: 'The empty state copy says "No items" twice', file: 'frontend/src/components/InboxPage.tsx', line: 88, detail: null, state: 'open' };++const pass = (key: string, text: string) => ({ key, state: 'pass', text, required: key !== 'semgrep' });+const row = (key: string, state: string, text: string) => ({ key, state, text, required: key !== 'semgrep' });++const ALL_PASS = [+ pass('secrets', 'No keys or tokens in the diff'),+ pass('pkgs', "No new package that doesn't exist"),+ pass('tests', 'No tests removed, skipped or weakened'),+ pass('risk', 'Low risk'),+ pass('review', 'Nothing to fix, 1 note'),+ row('semgrep', 'not_installed', 'Not installed. Optional, never blocks a push.'),+];++const KEY_HIT = [row('secrets', 'hit', '1 possible secret in the diff'), ...ALL_PASS.slice(1)];++const inner = (findings: unknown[], extra: Record<string, unknown> = {}) => ({+ kind: 'prepush',+ reviewer,+ fresh_eyes: fe,+ findings,+ diffstat,+ security: { secrets: { state: 'pass', count: 0 }, packages: { state: 'pass', count: 0 }, semgrep: { state: 'not_run', count: 0, reason: "semgrep isn't installed on the server" } },+ error: null,+ ...extra,+});++const base = {+ space_id: 's_demo',+ kwant_id: 'k_pixel',+ branch: 'pixel/inbox-empty-state',+ head_sha: '3f9c2a1b7e5d4c3b2a1908f7e6d5c4b3a2918070',+ base_sha: '1a2b3c4d5e6f708192a3b4c5d6e7f8091a2b3c4d',+ tries: 1,+ needs_you: false,+ no_change: false,+ diffstat,+ blockers: [] as unknown[],+ override: null as unknown,+ overridden_by: null as string | null,+ overridden_at: null as number | null,+ created_at: PP_T0,+ updated_at: PP_T0 + 2 * min,+};++export const PP_CHECKING = {+ ...base, id: 'pp_check', status: 'checking', diffstat: null, card: null, updated_at: PP_T0,+ checks: ['secrets', 'pkgs', 'tests', 'risk', 'review', 'semgrep'].map((k) => row(k, 'running', 'Checking…')),+};++export const PP_NO_CHANGE = {+ ...base, id: 'pp_none', status: 'clear', no_change: true, diffstat: { files: 0, add: 0, del: 0 }, checks: [],+ card: { kind: 'prepush', no_change: true, diffstat: { files: 0, add: 0, del: 0 }, blockers: [] },+};++export const PP_CLEAR = { ...base, id: 'pp_clear', status: 'clear', checks: ALL_PASS, card: inner([NIT]) };++const keyBlocker = { source: 'gitleaks', severity: 'critical', title: KEY_FINDING.title, file: KEY_FINDING.file, line: KEY_FINDING.line };++export const PP_BLOCKED = {+ ...base, id: 'pp_blocked', status: 'blocked', checks: KEY_HIT, blockers: [keyBlocker],+ card: inner([KEY_FINDING, NIT], { security: { secrets: { state: 'hit', count: 1 }, packages: { state: 'pass', count: 0 }, semgrep: { state: 'not_run', count: 0, reason: "semgrep isn't installed on the server" } } }),+};++export const PP_NEEDS_YOU = { ...PP_BLOCKED, id: 'pp_needs', tries: 2, needs_you: true, created_at: PP_T0 + 6 * min, updated_at: PP_T0 + 8 * min };++/** Several rows hit: the tests row and the review row, plus semgrep with the repo's own rules. */+export const PP_MANY = {+ ...base, id: 'pp_many', status: 'blocked',+ checks: [+ pass('secrets', 'No keys or tokens in the diff'),+ pass('pkgs', "No new package that doesn't exist"),+ row('tests', 'hit', '1 test removed, skipped or weakened'),+ row('risk', 'hit', 'High risk: touches sign-in'),+ row('review', 'hit', '1 finding to fix'),+ row('semgrep', 'hit', '1 match'),+ ],+ blockers: [+ { source: 'review', severity: 'high', title: 'Sign-in redirect drops the return path', file: 'frontend/src/auth.ts', line: 42 },+ ],+ card: inner([+ { id: 't1', source: 'tamper', severity: 'medium', title: 'A test now skips the empty inbox case', file: 'frontend/tests/inbox.test.mjs', line: 31, state: 'open' },+ { id: 'r2', source: 'review', severity: 'high', title: 'Sign-in redirect drops the return path', file: 'frontend/src/auth.ts', line: 42, detail: 'After sign-in the person lands on Home, not the Inbox they opened.', state: 'open' },+ { id: 's1', source: 'semgrep', severity: 'low', title: 'innerHTML set from a variable', file: 'frontend/src/components/InboxPage.tsx', line: 120, state: 'open' },+ ]),+};++const why = 'Didn\'t run: the checks took longer than 12 minutes';+export const PP_FAILED = {+ ...base, id: 'pp_failed', status: 'failed', diffstat: null,+ checks: ['secrets', 'pkgs', 'tests', 'risk', 'review', 'semgrep'].map((k) => row(k, 'error', why)),+ blockers: [{ source: 'kwant', severity: 'high', title: "kwant couldn’t check this push: the checks took longer than 12 minutes", file: null, line: null }],+ card: { kind: 'prepush', error: 'the checks took longer than 12 minutes', blockers: [{ source: 'kwant', severity: 'high', title: "kwant couldn’t check this push: the checks took longer than 12 minutes", file: null, line: null }] },+};++/** The reviewer's turn didn't finish: one error row, the rest passed (a check that couldn't run never passes). */+export const PP_REVIEW_ERROR = {+ ...base, id: 'pp_rerr', status: 'failed',+ checks: [...ALL_PASS.slice(0, 4), row('review', 'error', "Didn't finish: the reviewer's turn didn't answer"), ALL_PASS[5]],+ blockers: [{ source: 'review', severity: 'high', title: "The fresh-eyes review didn't finish: the reviewer's turn didn't answer", file: null, line: null }],+ card: inner([], { error: "the reviewer's turn didn't answer", fresh_eyes: { checked: false, saw: [], spec_source: 'pr', reviewer_kwant_id: 'k_iris' } }),+};++export const PP_FAILED_NEEDS_YOU = { ...PP_FAILED, id: 'pp_failed2', tries: 2, needs_you: true };++const REASON = 'The key is a revoked test key from the fixture generator.';+export const PP_OVERRIDDEN = {+ ...PP_NEEDS_YOU, id: 'pp_over', status: 'overridden', needs_you: false,+ override: { by: 'person', reason: REASON, at: PP_T0 + 9 * min },+ overridden_by: 'person', overridden_at: PP_T0 + 9 * min, updated_at: PP_T0 + 9 * min,+};++export const PP_RETRIED = { ...PP_NEEDS_YOU, id: 'pp_retried', status: 'retried', needs_you: false };++export const PP_ALL = { PP_CHECKING, PP_NO_CHANGE, PP_CLEAR, PP_BLOCKED, PP_NEEDS_YOU, PP_MANY, PP_FAILED, PP_REVIEW_ERROR, PP_FAILED_NEEDS_YOU, PP_OVERRIDDEN, PP_RETRIED };++// Fresh-eyes labels (contract §3.2)+export const FE_TICKET = { checked: true, saw: ['spec', 'diff'], spec_source: 'ticket', reviewer_kwant_id: 'k_iris' };+export const FE_TASK = { checked: true, saw: ['brief', 'diff'], spec_source: 'brief', reviewer_kwant_id: 'k_iris' };+export const FE_PR = fe;+export const FE_AUDIT_WRITTEN = { checked: true, saw: ['spec', 'result'], spec_source: 'written', reviewer_kwant_id: 'k_iris' };+export const FE_SAW_CHAT = { checked: false, saw: ['brief', 'diff'], spec_source: 'brief', reviewer_kwant_id: 'k_iris' };+export const FE_FAILED = { checked: false, saw: [], spec_source: 'none', reviewer_kwant_id: 'k_iris' };diff --git a/frontend/src/dev/types.ts b/frontend/src/dev/types.tsindex 0877a397..b218666f 100644--- a/frontend/src/dev/types.ts+++ b/frontend/src/dev/types.ts@@ -7,6 +7,7 @@// row (`CardFallback`). Strings are trimmed to a sane length and never rendered as HTML.import { parseMatches } from './tickets';+import { parseFreshEyes, type FreshEyes } from './freshEyes';import type { ReviewMatches } from './tickets';export type CardStatus = 'pending' | 'ready' | 'failed' | 'stale';@@ -89,7 +90,7 @@ export interface DevFinding {line: number | null;detail: string | null;fix: string | null;- source: 'review' | 'gitleaks' | 'packages' | 'tamper';+ source: 'review' | 'gitleaks' | 'packages' | 'tamper' | 'semgrep';state: 'open' | 'sent' | 'dismissed';sent_at: string | null;/** §3.6 item 4. */@@ -130,7 +131,11 @@ export interface ReviewCard extends CardBase {security: {secrets: { state: ScanState; count: number };packages: { state: ScanState; count: number };+ /** 0.8.0 B2/B3: only pre-push cards run it today (fresh-eyes-audit.md §3, q8); absent on forge PR cards. */+ semgrep: { state: ScanState; count: number; reason: string | null } | null;};+ /** 0.8.0 B3: how the review was run (fresh-eyes-audit.md §3.1). null on cards from before 0.8.0. */+ fresh_eyes: FreshEyes | null;findings: DevFinding[];cut: string | null;links: DevLinks;@@ -363,7 +368,7 @@ export function parseLanded(raw: unknown): LandedCard | null {};}-function finding(v: unknown): DevFinding | null {+export function finding(v: unknown): DevFinding | null {if (!isObj(v)) return null;const id = str(v.id, 80);const title = str(v.title, 200);@@ -377,7 +382,7 @@ function finding(v: unknown): DevFinding | null {line: num(v.line),detail: str(v.detail, 1200),fix: str(v.fix, 600),- source: oneOf(v.source, ['review', 'gitleaks', 'packages', 'tamper'] as const, 'review'),+ source: oneOf(v.source, ['review', 'gitleaks', 'packages', 'tamper', 'semgrep'] as const, 'review'),state: oneOf(v.state, ['open', 'sent', 'dismissed'] as const, 'open'),sent_at: str(v.sent_at, 64),sent_to: str(v.sent_to, 80),@@ -442,7 +447,12 @@ export function parseReview(raw: unknown): ReviewCard | null {.map((p) => str(p, 400)).filter((p): p is string => !!p),},- security: { secrets: scan(sec.secrets), packages: scan(sec.packages) },+ security: {+ secrets: scan(sec.secrets),+ packages: scan(sec.packages),+ semgrep: isObj(sec.semgrep) && ['pass', 'hit', 'not_run'].includes(sec.semgrep.state as string) ? { ...scan(sec.semgrep), reason: str(sec.semgrep.reason, 300) } : null,+ },+ fresh_eyes: parseFreshEyes(raw.fresh_eyes),findings: arr(raw.findings).map(finding).filter((f): f is DevFinding => !!f),cut: str(raw.cut, 120),links: links(raw.links),diff --git a/frontend/src/styles/modern.css b/frontend/src/styles/modern.cssindex 3b53dd97..1c11844b 100644--- a/frontend/src/styles/modern.css+++ b/frontend/src/styles/modern.css@@ -865,6 +865,17 @@ a.kw-sticker:hover { transform: rotate(var(--kw-tilt)) scale(1.04); box-shadow:.dv-led[data-ping]::after { content: ''; position: absolute; inset: 0; border-radius: 50%; border: 1.5px solid var(--c); animation: dv-ping 200ms var(--kw-ease) 1 both; }@keyframes dv-ping { from { transform: scale(1); opacity: .9; } to { transform: scale(2.4); opacity: 0; } }+/* 0.8.0 B3: the pre-push card's running LED is static (Mira b3 "no spinner, no pulse"), and+ "not installed" is a dashed hollow LED. */+.dv-led.dv-led-still::after { animation: none !important; opacity: .5; transform: scale(1.6); }+.dv-led.dv-led-dashed { box-shadow: none; border: 1.5px dashed var(--c); background: transparent; }+/* The fresh-eyes chip keeps its size; its hit area grows on touch (b3 §3). */+.fe-chip { position: relative; }+.fe-chip::after { content: ''; position: absolute; inset: -6px; }+.fe-pop { animation: fe-in 150ms var(--kw-ease) both; }+@keyframes fe-in { from { opacity: 0; } to { opacity: 1; } }+@media (prefers-reduced-motion: reduce) { .fe-pop { animation: none; } }+/* §2.2 Diff stat: mono numbers plus a 32x4 split bar (add | del). Our own shape, not a block meter. */.dv-stat { display: inline-flex; align-items: center; gap: 6px; font: 500 11.5px/1 'JetBrains Mono', monospace; white-space: nowrap; }.dv-stat .a { color: var(--dv-add); } .dv-stat .d { color: var(--dv-del); }diff --git a/frontend/tests/devCards.test.mjs b/frontend/tests/devCards.test.mjsindex e80144ca..64f37ce5 100644--- a/frontend/tests/devCards.test.mjs+++ b/frontend/tests/devCards.test.mjs@@ -554,7 +554,8 @@ test('the review card: sample chip, tamper, security tiles in 0.7.x, no Post butassert.match(out, /Different engine from the author/);assert.match(out, /data-sec="OSV" data-state="later"/);assert.match(out, /data-sec="Semgrep" data-state="later"/);- assert.equal((out.match(/in 0\.7\.x/g) ?? []).length >= 2, true);+ assert.equal((out.match(/in 0\.7\.x/g) ?? []).length >= 1, true);+ assert.match(out, /Runs before a push, not on pull requests/, '0.8.0 B3: semgrep runs before a push, not on PR reviews');assert.doesNotMatch(out, /Post to GitHub/, 'S2: no button that can never be pressed');assert.match(out, /Nothing is posted until you press it\./);assert.match(out, /data-post-state="none"/);diff --git a/frontend/tests/prepush.test.mjs b/frontend/tests/prepush.test.mjsnew file mode 100644index 00000000..0ea8ecad--- /dev/null+++ b/frontend/tests/prepush.test.mjs@@ -0,0 +1,526 @@+// 0.8.0 B3 (Iris): the pre-push card (every state P0–P7, retried, the reason form, phone folding),+// the Inbox "Needs you" item, the "Checked with fresh eyes" chip (R1–R3) and the semgrep tile.+// Data is shaped like Juno's card_json (ba2157a5); see src/dev/prepushFixtures.ts.+process.env.TZ = 'UTC';++import assert from 'node:assert/strict';+import test, { afterEach } 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/', pretendToBeVisual: true });+const g = globalThis;+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'Element', 'Node', 'Event', 'MouseEvent', 'KeyboardEvent', 'CustomEvent', '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.window.matchMedia ??= () => ({ matches: false, addEventListener() {}, removeEventListener() {} });+g.IS_REACT_ACT_ENVIRONMENT = false;++const m = await loadBundled(`+ export * from './src/dev/prepush';+ export * from './src/dev/freshEyes';+ export * as fx from './src/dev/prepushFixtures';+ export { parseReview } from './src/dev/types';+ export * as dfx from './src/dev/fixtures';+ export { PrepushCard } from './src/components/dev/PrepushCard';+ export { PrepushNeedsYou, PrepushThread, threadCards, usePrepushCards } from './src/components/dev/PrepushThread';+ export { FreshEyesChip } from './src/components/dev/FreshEyesChip';+ export { ReviewCard, semgrepTile } from './src/components/dev/ReviewCard';+ export { renderToStaticMarkup } from 'react-dom/server.browser';+ export { createRoot } from 'react-dom/client';+ export { createElement } from 'react';+`);+const { fx } = m;+const h = m.createElement;+const html = (C, props) => m.renderToStaticMarkup(h(C, props));+const card = (raw) => {+ const c = m.parsePrepush(raw);+ assert.ok(c, 'fixture parses');+ return c;+};++const mounted = new Set();+afterEach(() => {+ for (const u of mounted) u();+ document.body.replaceChildren();+});+const settle = async () => {+ for (let i = 0; i < 20; i++) await new Promise((r) => setTimeout(r, 0));+};+const mount = async (C, props) => {+ const host = document.createElement('div');+ document.body.appendChild(host);+ const root = m.createRoot(host);+ root.render(h(C, props));+ await settle();+ const u = () => {+ if (!mounted.delete(u)) return;+ root.unmount();+ host.remove();+ };+ mounted.add(u);+ return { host, rerender: async (p) => { root.render(h(C, p)); await settle(); } };+};+const text = (el) => el.textContent.replace(/\s+/g, ' ').trim();+const button = (host, t) => [...host.querySelectorAll('button')].find((b) => text(b).startsWith(t));+const click = async (el) => {+ el.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));+ await settle();+};+const type = async (el, value) => {+ const set = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value').set;+ set.call(el, value);+ el.dispatchEvent(new window.Event('input', { bubbles: true }));+ await settle();+};++// ---------------------------------------------------------------------------------------------------+// Parsing and phases++test('every fixture parses and maps to Mira\'s phase', () => {+ const want = {+ PP_CHECKING: 'P1', PP_NO_CHANGE: 'P0', PP_CLEAR: 'P2', PP_BLOCKED: 'P3', PP_NEEDS_YOU: 'P4', PP_MANY: 'P3',+ PP_FAILED: 'P7', PP_REVIEW_ERROR: 'P7', PP_FAILED_NEEDS_YOU: 'P4', PP_OVERRIDDEN: 'P6', PP_RETRIED: 'RT',+ };+ for (const [k, phase] of Object.entries(want)) assert.equal(m.phaseOf(card(fx[k])), phase, k);+});++test('the parser refuses cards it cannot show honestly', () => {+ assert.equal(m.parsePrepush(null), null);+ assert.equal(m.parsePrepush({ ...fx.PP_CLEAR, status: 'pushed' }), null, 'no pushed status on the server');+ assert.equal(m.parsePrepush({ ...fx.PP_CLEAR, branch: '' }), null);+ assert.equal(m.parsePrepush({ ...fx.PP_CLEAR, checks: [...fx.PP_CLEAR.checks, { key: 'osv', state: 'pass', text: 'x' }] }), null, 'an unknown row is never dropped silently');+ assert.equal(m.parsePrepush({ ...fx.PP_CLEAR, checks: [{ key: 'secrets', state: 'queued', text: 'Waiting' }] }), null, 'no queued state in the contract');+ const c = card({ ...fx.PP_BLOCKED, needs_you: true, tries: 1 });+ assert.equal(c.needs_you, true, 'needs_you is the server\'s word');+ assert.equal(card({ ...fx.PP_CLEAR, needs_you: true }).needs_you, false, 'only blocked or failed cards can need you');+ assert.equal(card({ ...fx.PP_CLEAR, diffstat: { files: -1, add: 1, del: 1 } }).diffstat, null);+ assert.equal(card(fx.PP_CLEAR).checks.find((k) => k.key === 'semgrep').required, false, 'semgrep never counts as required');+ assert.equal(card(fx.PP_CLEAR).reviewer.name, 'Iris');+ assert.equal(card(fx.PP_CLEAR).fresh_eyes.checked, true);+ assert.equal(m.parsePrepushList({ cards: [fx.PP_CLEAR, { junk: 1 }, fx.PP_BLOCKED] }).length, 2);+});++test('status chip: plain while checking, ok when clear, rose while the bot fixes, amber only when the person must act', () => {+ const chip = (k) => m.statusChip(card(fx[k]));+ assert.equal(chip('PP_NO_CHANGE'), null);+ assert.deepEqual(chip('PP_CHECKING'), { tone: 'plain', text: 'Checking', led: 'run' });+ assert.deepEqual(chip('PP_CLEAR'), { tone: 'ok', text: 'Clear', led: null });+ assert.deepEqual(chip('PP_BLOCKED'), { tone: 'bad', text: '1 to fix', led: null });+ assert.deepEqual(chip('PP_NEEDS_YOU'), { tone: 'warn', text: 'Needs you', led: null });+ assert.deepEqual(chip('PP_FAILED_NEEDS_YOU'), { tone: 'warn', text: 'Needs you', led: null });+ assert.equal(chip('PP_FAILED').tone, 'plain');+ assert.equal(chip('PP_OVERRIDDEN').text, 'Pushed anyway');+ assert.equal(chip('PP_OVERRIDDEN').tone, 'plain');+ for (const k of Object.keys(fx.PP_ALL)) {+ const c = chip(k);+ if (c?.tone === 'warn') assert.equal(m.phaseOf(card(fx[k])), 'P4', `${k}: amber only in P4`);+ }+});++test('counts come from the server: open findings are its blockers, never a check that could not run', () => {+ assert.equal(m.openCount(card(fx.PP_NEEDS_YOU)), 1);+ assert.equal(m.openCount(card(fx.PP_FAILED)), 0, "kwant couldn't check is not a finding");+ assert.equal(m.openCount(card(fx.PP_REVIEW_ERROR)), 0, "a review that didn't finish is not a finding");+ assert.equal(m.inboxLine(card(fx.PP_NEEDS_YOU), 'Pixel'), "Pixel's push is waiting for you: 1 finding open");+ assert.equal(m.inboxLine(card(fx.PP_FAILED_NEEDS_YOU), 'Pixel'), "Pixel's push is waiting for you: the checks couldn't run");+ assert.equal(m.requiredPassed(card(fx.PP_CLEAR)), 5, 'semgrep not installed is not a passed check');+ assert.equal(m.clearedLine(card(fx.PP_CLEAR)), 'Cleared to push pixel/inbox-empty-state after 5 checks passed · 14:02');+ assert.equal(m.foldLine(card(fx.PP_NEEDS_YOU)), '4 checks passed · registry · tamper · rules · review');+ assert.equal(m.overriddenLine(card(fx.PP_OVERRIDDEN)), 'You let this push go at 14:09 with 1 finding open. It covers this commit only.');+});++test('a check that could not run never reads as passed', () => {+ for (const k of ['PP_FAILED', 'PP_REVIEW_ERROR', 'PP_FAILED_NEEDS_YOU']) {+ const c = card(fx[k]);+ for (const row of c.checks.filter((r) => r.state === 'error')) {+ assert.equal(m.STATE_LED[row.state], 'off');+ assert.equal(m.STATE_WORD[row.state], 'could not run');+ assert.ok(!m.passedRows(c).includes(row));+ }+ }+ const out = html(m.PrepushCard, { card: card(fx.PP_FAILED), bot: 'Pixel' });+ assert.doesNotMatch(out, /data-state="pass"/);+ assert.equal((out.match(/could not run:/g) || []).length, 6);+});++// ---------------------------------------------------------------------------------------------------+// Rendering, one state at a time++test('P0 nothing to push: one grey status line, no checks', () => {+ const out = html(m.PrepushCard, { card: card(fx.PP_NO_CHANGE), bot: 'Pixel' });+ assert.match(out, /data-prepush-phase="P0"/);+ assert.match(out, /role="status"/);+ assert.match(out, /has no new commits\. Nothing was pushed\./);+ assert.doesNotMatch(out, /data-check=/);+});++test('P1 running: every row runs with a static LED, the chip alone is live', () => {+ const out = html(m.PrepushCard, { card: card(fx.PP_CHECKING), bot: 'Pixel' });+ assert.match(out, /Before Pixel pushes/);+ assert.equal((out.match(/data-state="running"/g) || []).length, 6);+ assert.equal((out.match(/aria-live="polite"/g) || []).length, 1, 'only the status chip is live');+ assert.match(out, /data-prepush-chip[^>]*aria-live="polite"/);+ assert.match(out, /dv-led dv-led-still/);+ assert.match(out, /The push waits until these finish/);+ assert.doesNotMatch(out, /Push anyway/);+});++test('P2 clear: a card seen live shows Clear, then folds to P2b after about 2 s; history starts folded', async () => {+ const live = await mount(m.PrepushCard, { card: card(fx.PP_CLEAR), bot: 'Pixel', live: true });+ assert.equal(live.host.querySelector('[data-prepush-phase]').dataset.prepushPhase, 'P2');+ assert.match(text(live.host), /All clear\. Pixel can push now\./);+ assert.doesNotMatch(text(live.host), /Pushing now|Pushed /, 'kwant never sees the push itself');+ await new Promise((r) => setTimeout(r, 2100));+ await settle();+ assert.equal(live.host.querySelector('[data-prepush-phase]').dataset.prepushPhase, 'P2b');++ const hist = await mount(m.PrepushCard, { card: card(fx.PP_CLEAR), bot: 'Pixel' });+ assert.equal(hist.host.querySelector('[data-prepush-phase]').dataset.prepushPhase, 'P2b');+ assert.match(text(hist.host), /Cleared to push pixel\/inbox-empty-state after 5 checks passed · 14:02/);+ await click(button(hist.host, 'Show checks'));+ assert.equal(hist.host.querySelector('[data-prepush-phase]').dataset.prepushPhase, 'P2');+ assert.equal(hist.host.querySelectorAll('[data-check]').length, 6);+});++test('P3 blocked: rose chip, the bot is fixing, a plain Push anyway, no amber', () => {+ const out = html(m.PrepushCard, { card: card(fx.PP_BLOCKED), bot: 'Pixel', onRetry: async () => {}, onOverride: async () => {} });+ assert.match(out, /kw-chip kw-chip-bad[^"]*"[^>]*>1 to fix/);+ assert.match(out, /Pixel is fixing them\./);+ assert.match(out, /Try 1 of 2\./);+ assert.match(out, />Push anyway…</);+ assert.doesNotMatch(out, /amber/);+ assert.doesNotMatch(out, /role="alert"/);+ assert.doesNotMatch(out, /always|skip this check/i);+});++test('P4 needs you: amber box with role=alert, retry first, amber-outline Push anyway', async () => {+ const calls = [];+ const { host } = await mount(m.PrepushCard, { card: card(fx.PP_NEEDS_YOU), bot: 'Pixel', onRetry: async (c) => calls.push(['retry', c.id]), onOverride: async () => {} });+ const box = host.querySelector('[data-needs-you]');+ assert.equal(box.getAttribute('role'), 'alert');+ assert.match(text(box), /Pixel couldn't clear 1 finding after 2 tries\. The push is waiting for you\. It's also in your Inbox\./);+ const btns = [...box.querySelectorAll('button')].map(text);+ assert.deepEqual(btns, ['Ask Pixel to try again', 'Push anyway…']);+ assert.match(box.querySelectorAll('button')[1].className, /border-amber-400/);+ for (const b of box.querySelectorAll('button')) assert.match(b.className, /min-h-11/, '44 px on phone');+ await click(button(host, 'Ask Pixel to try again'));+ assert.deepEqual(calls, [['retry', 'pp_needs']]);+});++test('P4 after failed checks: the primary is Run the checks again', () => {+ const out = html(m.PrepushCard, { card: card(fx.PP_FAILED_NEEDS_YOU), bot: 'Pixel', onRetry: async () => {}, onOverride: async () => {} });+ assert.match(out, /Pixel's push couldn't be checked after 2 tries\.<\/strong> The push is waiting for you\./);+ assert.match(out, />Run the checks again</);+});++test('P5 push anyway: required, autofocused, labelled; disabled under 10 characters; Cancel goes back', async () => {+ const sent = [];+ const { host } = await mount(m.PrepushCard, { card: card(fx.PP_NEEDS_YOU), bot: 'Pixel', onRetry: async () => {}, onOverride: async (c, r) => sent.push([c.id, r]) });+ await click(button(host, 'Push anyway…'));+ const form = host.querySelector('[data-override-form]');+ assert.ok(form);+ assert.equal(host.querySelector('[data-prepush-phase]').dataset.prepushPhase, 'P5');+ const area = form.querySelector('textarea');+ assert.equal(document.activeElement, area, 'autofocused');+ assert.ok(area.required);+ assert.match(area.className, /text-base/, 'no iOS zoom');+ assert.equal(form.querySelector(`label[for="${area.id}"]`).textContent, 'Your reason');+ const hint = document.getElementById(area.getAttribute('aria-describedby'));+ assert.match(hint.textContent, /at least 10 characters\. This push only; next time the checks run again\./);+ assert.doesNotMatch(text(form), /pull request/, 'the reason is not copied into the PR yet (contract q10)');+ const go = [...form.querySelectorAll('button')].find((b) => text(b) === 'Push anyway');+ assert.match(go.className, /bg-amber-600/);+ assert.equal(go.disabled, true);+ await type(area, ' short ');+ assert.equal(go.disabled, true, '"short" trimmed is under 10');+ await type(area, 'revoked test key');+ assert.equal(go.disabled, false);+ await click(button(form, 'Cancel'));+ assert.equal(host.querySelector('[data-override-form]'), null);+ assert.equal(host.querySelector('[data-prepush-phase]').dataset.prepushPhase, 'P4', 'Cancel returns to P4');+ await click(button(host, 'Push anyway…'));+ await type(host.querySelector('textarea'), 'the key is a revoked test key');+ host.querySelector('[data-override-form]').dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }));+ await settle();+ assert.deepEqual(sent, [['pp_needs', 'the key is a revoked test key']]);+});++test('P5 shows the server\'s refusal and keeps the reason', async () => {+ const { host } = await mount(m.PrepushCard, {+ card: card(fx.PP_NEEDS_YOU), bot: 'Pixel', startOverride: true,+ onOverride: async () => { throw new Error('Give a reason of at least 10 characters.'); },+ });+ await type(host.querySelector('textarea'), '0123456789');+ host.querySelector('[data-override-form]').dispatchEvent(new window.Event('submit', { bubbles: true, cancelable: true }));+ await settle();+ assert.match(text(host.querySelector('p[role="alert"]')), /at least 10 characters/);+ assert.equal(host.querySelector('textarea').value, '0123456789');+});++test('P6 pushed anyway: neutral chip, the time and the quoted reason; open findings stay rose; no actions', () => {+ const out = html(m.PrepushCard, { card: card(fx.PP_OVERRIDDEN), bot: 'Pixel', onRetry: async () => {}, onOverride: async () => {} });+ assert.match(out, /class="kw-chip shrink-0[^"]*"[^>]*>Pushed anyway/);+ assert.match(out, /You let this push go at 14:09 with 1 finding open\./);+ assert.match(out, /<blockquote[^>]*>.*The key is a revoked test key/);+ assert.match(out, /data-check="secrets" data-state="hit"/);+ assert.doesNotMatch(out, /<button[^>]*>Push anyway/);+ assert.doesNotMatch(out, /Ask Pixel/);+});++test('P7 a check could not run: plain buttons, Run the checks again', async () => {+ const calls = [];+ const { host } = await mount(m.PrepushCard, { card: card(fx.PP_FAILED), bot: 'Pixel', onRetry: async (c) => calls.push(c.id), onOverride: async () => {} });+ assert.match(text(host), /Couldn't check/);+ assert.match(text(host), /A check couldn't run, so this push can't count as checked\./);+ assert.ok(!host.innerHTML.includes('amber'));+ await click(button(host, 'Run the checks again'));+ assert.deepEqual(calls, ['pp_failed']);+});++test('retried: one grey line', () => {+ const out = html(m.PrepushCard, { card: card(fx.PP_RETRIED), bot: 'Pixel' });+ assert.match(out, /data-prepush-phase="RT"/);+ assert.match(out, /You asked for a new check of .*pixel\/inbox-empty-state.*Pixel's next push of this commit is checked again from try 1\./);+});++test('read-only cards (no handlers) show no buttons', () => {+ for (const k of ['PP_BLOCKED', 'PP_NEEDS_YOU', 'PP_FAILED']) {+ const out = html(m.PrepushCard, { card: card(fx[k]), bot: 'Pixel' });+ assert.doesNotMatch(out, /<button[^>]*>(Push anyway…|Ask Pixel|Run the checks again)/, k);+ }+});++test('rows: names, tool lines, hidden state words, Show opens the findings behind a hit', async () => {+ const { host } = await mount(m.PrepushCard, { card: card(fx.PP_MANY), bot: 'Pixel' });+ const rows = [...host.querySelectorAll('[data-check]')];+ assert.deepEqual(rows.map((r) => r.dataset.check), ['secrets', 'pkgs', 'tests', 'risk', 'review', 'semgrep']);+ assert.match(text(rows[4]), /Fresh-eyes review.*Iris on claude.*1 finding to fix/);+ assert.match(text(rows[5]), /semgrep · optional/);+ assert.match(text(rows[0]), /^passed:/);+ assert.match(text(rows[2]), /^found a problem:/);+ assert.equal(rows[3].querySelector('button'), null, 'risk has nothing to Show');+ const show = rows[4].querySelector('button');+ assert.equal(show.getAttribute('aria-expanded'), 'false');+ await click(show);+ assert.equal(show.getAttribute('aria-expanded'), 'true');+ assert.match(text(rows[4]), /Sign-in redirect drops the return path/);+ assert.match(text(rows[4]), /frontend\/src\/auth\.ts:42/);+ await click(rows[5].querySelector('button'));+ assert.match(text(rows[5]), /innerHTML set from a variable/, 'finding text is shown as text, never HTML');+});++test('phone: passing rows fold into one, findings always show, not-installed semgrep is hidden', async () => {+ const { host } = await mount(m.PrepushCard, { card: card(fx.PP_NEEDS_YOU), bot: 'Pixel' });+ const fold = host.querySelector('[data-fold]');+ assert.match(fold.className, /sm:hidden/, 'the fold row is phone only');+ assert.match(text(fold), /4 checks passed · registry · tamper · rules · review/);+ const hidden = (k) => /max-sm:hidden/.test(host.querySelector(`[data-check="${k}"]`).className);+ assert.equal(hidden('secrets'), false, 'the finding stays');+ assert.equal(hidden('pkgs'), true);+ assert.equal(hidden('semgrep'), true);+ const t = fold.querySelector('button');+ await click(t);+ assert.equal(t.getAttribute('aria-expanded'), 'true');+ assert.equal(hidden('pkgs'), false);+ assert.equal(hidden('semgrep'), true, 'not installed stays hidden on phone');+ // P1 and P2 never fold+ assert.equal(html(m.PrepushCard, { card: card(fx.PP_CHECKING), bot: 'Pixel' }).includes('data-fold'), false);+});++test('the card never renders HTML from data', () => {+ const evil = { ...fx.PP_BLOCKED, branch: '<img src=x onerror=alert(1)>', blockers: [{ source: 'gitleaks', severity: 'critical', title: '<b>x</b>', file: null, line: null }] };+ const out = html(m.PrepushCard, { card: card(evil), bot: '<i>Pixel</i>' });+ assert.doesNotMatch(out, /<img|<b>x|<i>Pixel/);+});++// ---------------------------------------------------------------------------------------------------+// Thread, Inbox and the event++test('threadCards: this bot only, newest three, oldest first', () => {+ const cards = ['a', 'b', 'c', 'd'].map((id, i) => card({ ...fx.PP_CLEAR, id, created_at: 1000 + i }));+ cards.push(card({ ...fx.PP_CLEAR, id: 'other', kwant_id: 'k_vega', created_at: 5000 }));+ assert.deepEqual(m.threadCards(cards, 'k_pixel').map((c) => c.id), ['b', 'c', 'd']);+});++test('Inbox: one amber item per card that needs you; it resolves when the card moves on', async () => {+ const opened = [];+ const cards = [card(fx.PP_NEEDS_YOU), card(fx.PP_BLOCKED), card(fx.PP_CLEAR), card(fx.PP_FAILED_NEEDS_YOU)];+ const { host, rerender } = await mount(m.PrepushNeedsYou, { cards, names: { k_pixel: 'Pixel' }, onOpen: (c) => opened.push(c.id) });+ const items = [...host.querySelectorAll('[data-needs-prepush-item]')];+ assert.equal(items.length, 2);+ assert.match(text(items[0]), /Needs you.*Pixel's push is waiting for you/);+ await click(items[0]);+ assert.equal(opened.length, 1);+ await rerender({ cards: [card(fx.PP_OVERRIDDEN), card(fx.PP_RETRIED)], names: { k_pixel: 'Pixel' }, onOpen: () => {} });+ assert.equal(host.querySelector('[data-needs-prepush]'), null);+});++test('usePrepushCards: lists once, refetches one card per dev_prepush event, and marks a card that turned clear as live', async () => {+ const calls = [];+ let next = fx.PP_CHECKING;+ const api = {+ list: async (s) => { calls.push(['list', s]); return [card(fx.PP_CHECKING)]; },+ get: async (id) => { calls.push(['get', id]); return card({ ...next, id }); },+ };+ let state;+ const Probe = () => { state = m.usePrepushCards('s_demo', true, api); return null; };+ await mount(Probe, {});+ assert.deepEqual(calls, [['list', 's_demo']]);+ assert.equal(state.cards[0].status, 'checking');+ window.dispatchEvent(new window.CustomEvent(m.PREPUSH_EVENT, { detail: { space_id: 'other', id: 'pp_check' } }));+ await settle();+ assert.equal(calls.length, 1, 'another space is ignored');+ next = fx.PP_CLEAR;+ window.dispatchEvent(new window.CustomEvent(m.PREPUSH_EVENT, { detail: { space_id: 's_demo', id: 'pp_check', status: 'clear' } }));+ await settle();+ assert.deepEqual(calls[1], ['get', 'pp_check']);+ assert.equal(state.cards.length, 1);+ assert.equal(state.cards[0].status, 'clear');+ assert.ok(state.live.has('pp_check'));+});++test('usePrepushCards does nothing with Dev mode off', async () => {+ const calls = [];+ const api = { list: async () => { calls.push('list'); return []; }, get: async () => { calls.push('get'); return null; } };+ const Probe = () => { m.usePrepushCards('s_demo', false, api); return null; };+ await mount(Probe, {});+ window.dispatchEvent(new window.CustomEvent(m.PREPUSH_EVENT, { detail: { space_id: 's_demo', id: 'x' } }));+ await settle();+ assert.deepEqual(calls, []);+});++test('API: override trims the reason; 400 reason_needed and 409 read plainly', async () => {+ const sent = [];+ const realFetch = g.fetch;+ const respond = [];+ g.fetch = async (url, init) => {+ sent.push([String(url), init?.method, init?.body]);+ const [status, body] = respond.shift();+ return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });+ };+ try {+ respond.push([200, fx.PP_OVERRIDDEN]);+ const c = await m.prepushApi.override('pp_needs', ' the key is revoked ');+ assert.equal(c.status, 'overridden');+ assert.equal(sent[0][0], '/api/dev/prepush/pp_needs/override');+ assert.equal(sent[0][1], 'POST');+ assert.deepEqual(JSON.parse(sent[0][2]), { reason: 'the key is revoked' });+ respond.push([400, { error: 'too short', code: 'reason_needed' }]);+ await assert.rejects(m.prepushApi.override('pp_needs', 'short'), /at least 10 characters/);+ respond.push([409, { error: 'only a blocked or failed card can be checked again', code: 'conflict' }]);+ await assert.rejects(m.prepushApi.retry('pp_clear'), /moved on/);+ respond.push([200, { cards: [fx.PP_CLEAR] }]);+ assert.equal((await m.prepushApi.list('s demo')).length, 1);+ assert.equal(sent.at(-1)[0], '/api/spaces/s%20demo/dev/prepush');+ } finally {+ g.fetch = realFetch;+ }+});++test('reasonOk: 10 trimmed characters, one push only', () => {+ assert.equal(m.reasonOk('123456789'), false);+ assert.equal(m.reasonOk(' 123456789 '), false);+ assert.equal(m.reasonOk('1234567890'), true);+ assert.equal(m.MIN_REASON, 10);+});++// ---------------------------------------------------------------------------------------------------+// Checked with fresh eyes++test('fresh-eyes label: R1, R2 and R3 follow the contract', () => {+ const p = (v) => m.chipState(m.parseFreshEyes(v));+ assert.equal(p(fx.FE_TICKET), 'R1');+ assert.equal(p(fx.FE_SAW_CHAT), 'R2');+ assert.equal(p(fx.FE_FAILED), 'R3', 'a failed review shows no chip, never R2');+ assert.equal(p(null), 'R3');+ assert.equal(p(undefined), 'R3');+ assert.equal(p({ saw: ['diff'] }), 'R3', 'no checked flag');+ assert.deepEqual(m.parseFreshEyes({ checked: true, saw: ['diff', 'tests', 'diff', 'chat'], spec_source: 'odd' }).saw, ['diff'], 'unknown parts dropped');+});++test('popover lines come from saw and spec_source; no test-results line', () => {+ const lines = (v, o = {}) => m.sawLines(m.parseFreshEyes(v), { author: 'Pixel', ...o }).map((l) => `${l.ok ? '+' : '-'} ${l.text}`);+ assert.deepEqual(lines(fx.FE_TICKET, { ref: 'KW-212', diff: { files: 4, add: 86, del: 21 } }), [+ "+ the ticket's brief and done-when lines (KW-212)",+ '+ the diff (4 files, +86 −21)',+ "- Not Pixel's conversation or reasoning",+ ]);+ assert.deepEqual(lines(fx.FE_TASK), ["+ the task's brief", '+ the diff', "- Not Pixel's conversation or reasoning"]);+ assert.deepEqual(lines(fx.FE_PR), ["+ only the PR's title and description, in the author's own words", '+ the diff', "- Not Pixel's conversation or reasoning"]);+ assert.deepEqual(lines(fx.FE_AUDIT_WRITTEN), ["+ the owner's written spec", '+ the result', "- Not Pixel's conversation or reasoning"]);+ for (const v of [fx.FE_TICKET, fx.FE_TASK, fx.FE_PR, fx.FE_AUDIT_WRITTEN]) assert.ok(lines(v).every((l) => !/test/.test(l)));+ assert.equal(m.popoverTitle('Iris'), 'Iris reviewed with fresh eyes. They saw only what a new teammate would get:');+});++test('R1 chip: a real button; opens a labelled dialog; Esc closes it and focus returns', async () => {+ const { host } = await mount(m.FreshEyesChip, { label: m.parseFreshEyes(fx.FE_TICKET), reviewer: 'Iris', author: 'Pixel', specRef: 'KW-212' });+ const chip = host.querySelector('[data-fresh-eyes="R1"]');+ assert.equal(chip.tagName, 'BUTTON');+ assert.equal(chip.type, 'button');+ assert.equal(chip.getAttribute('aria-expanded'), 'false');+ assert.match(chip.className, /kw-chip/);+ assert.doesNotMatch(chip.className, /holo|accent|kw-chip-ok/, 'plain grey, never earned-looking');+ assert.match(chip.className, /focus-visible:ring-sky-400/);+ chip.focus();+ await click(chip);+ const pop = host.querySelector('[role="dialog"]');+ assert.equal(pop.getAttribute('aria-label'), 'How this review was run');+ assert.equal(chip.getAttribute('aria-controls'), pop.id);+ assert.equal(chip.getAttribute('aria-expanded'), 'true');+ assert.match(text(pop), /Iris reviewed with fresh eyes\. They saw only what a new teammate would get:/);+ assert.match(text(pop), /Not Pixel's conversation or reasoning/);+ document.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));+ await settle();+ assert.equal(host.querySelector('[role="dialog"]'), null);+ assert.equal(document.activeElement, chip);+});++test('R1 chip closes on a click outside and when focus leaves it', async () => {+ const { host } = await mount(m.FreshEyesChip, { label: m.parseFreshEyes(fx.FE_PR), reviewer: 'Iris', author: 'Pixel' });+ const chip = host.querySelector('button');+ await click(chip);+ assert.ok(host.querySelector('[role="dialog"]'));+ document.body.dispatchEvent(new window.MouseEvent('mousedown', { bubbles: true }));+ await settle();+ assert.equal(host.querySelector('[role="dialog"]'), null);+ await click(chip);+ const out = document.createElement('button');+ document.body.appendChild(out);+ chip.dispatchEvent(new window.FocusEvent('focusout', { bubbles: true, relatedTarget: out }));+ await settle();+ assert.equal(host.querySelector('[role="dialog"]'), null);+});++test('R2 is a grey chip that is not a button; R3 renders nothing', () => {+ const r2 = html(m.FreshEyesChip, { label: m.parseFreshEyes(fx.FE_SAW_CHAT), reviewer: 'Iris', author: 'Pixel' });+ assert.match(r2, /^<span data-fresh-eyes="R2" class="kw-chip">Saw the author's chat<\/span>$/);+ assert.equal(html(m.FreshEyesChip, { label: m.parseFreshEyes(fx.FE_FAILED), reviewer: 'Iris', author: 'Pixel' }), '');+ assert.equal(html(m.FreshEyesChip, { label: null, reviewer: 'Iris', author: 'Pixel' }), '');+});++test('review card: the chip sits right after the engine chip; old cards show none', () => {+ const raw = { ...m.dfx.REVIEW_294, fresh_eyes: fx.FE_TICKET };+ const r = m.parseReview(raw);+ assert.equal(r.fresh_eyes.checked, true);+ const out = html(m.ReviewCard, { card: r, now: m.dfx.FIXTURE_NOW });+ const engine = out.search(/(Different|Same) engine/);+ const fresh = out.indexOf('Checked with fresh eyes');+ assert.ok(engine > 0 && fresh > engine, 'after the engine chip');+ assert.equal(m.parseReview(m.dfx.REVIEW_294).fresh_eyes, null);+ assert.doesNotMatch(html(m.ReviewCard, { card: m.parseReview(m.dfx.REVIEW_294), now: m.dfx.FIXTURE_NOW }), /fresh eyes/);+});++test('semgrep tile: the real run, not installed is optional, and no more "in 0.7.x"', () => {+ assert.deepEqual(m.semgrepTile({ state: 'pass', count: 0, reason: null }), { state: 'pass', text: 'No matches' });+ assert.deepEqual(m.semgrepTile({ state: 'hit', count: 2, reason: null }), { state: 'hit', text: '2 matches · see finding' });+ assert.deepEqual(m.semgrepTile({ state: 'not_run', count: 0, reason: "semgrep isn't installed on the server" }), { state: 'later', text: 'Not installed. Optional.' });+ assert.deepEqual(m.semgrepTile({ state: 'not_run', count: 0, reason: 'the repo has no .semgrep.yml of its own' }), { state: 'later', text: 'Not installed. Optional.' });+ assert.deepEqual(m.semgrepTile({ state: 'not_run', count: 0, reason: 'semgrep took longer than 2 minutes' }), { state: 'not_run', text: "Didn't run: semgrep took longer than 2 minutes" });+ assert.equal(m.semgrepTile(null).state, 'later');+ const out = html(m.ReviewCard, { card: m.parseReview(m.dfx.REVIEW_294), now: m.dfx.FIXTURE_NOW });+ assert.doesNotMatch(out, /data-sec="Semgrep"[^]*?in 0\.7\.x/);+ const r = m.parseReview({ ...m.dfx.REVIEW_294, security: { ...m.dfx.REVIEW_294.security, semgrep: { state: 'hit', count: 1 } } });+ assert.deepEqual(r.security.semgrep, { state: 'hit', count: 1, reason: null });+});diff --git a/frontend/tests/spendStop.test.mjs b/frontend/tests/spendStop.test.mjsindex 0c1bf901..c578d995 100644--- a/frontend/tests/spendStop.test.mjs+++ b/frontend/tests/spendStop.test.mjs@@ -239,7 +239,7 @@ test('with the app open: the worker’s message for a stop opens Needs you; otheconst app = src('App.tsx');assert.match(app, /const place = placeOfNotification\(m\);\s*if \(place === 'spend_stop'\) return openSpendStopRef\.current\(\);[\s\S]*?if \(place === 'home'\) return openHomeRef\.current\(\);\s*if \(!m\.kwant_id\) return;/);assert.match(app, /const place = placeOfNotification\(n\);\s*if \(place === 'spend_stop'\) openSpendStop\(\);\s*else if \(place === 'home'\) openHome\(\);/);- assert.match(app, /top=\{<SpendStopNeedsYou refreshKey=\{spendStopSeq\}/);+ assert.match(app, /top=\{\s*<>\s*<PrepushNeedsYou [^\n]*\/>\s*<SpendStopNeedsYou refreshKey=\{spendStopSeq\}/);});test('the stop’s notification is a kind to tick, only where the server has the stop, and shows on this device', () => {