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
0.9.7 Pre-push grant UI: the card follows the push after Retry or Push anyway; one Needs you item per branch (#576)
Oleksandr Ivanchenko99570bba9437
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex d23dc416..906dd1b9 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -569,7 +569,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({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 prepushWaiting = prepushNeedsYou(prepush.cards, prepush.acted).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);@@ -2304,10 +2304,14 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({};// The card call first; a 409 means the card moved on, so fetch it again (Rigel QA 1). Then the// chat message: if only that fails, say the change applied (Ada Later 7).+ // 0.9.7 prepush-grant: the Inbox item goes the moment the person presses, before the server answers;+ // it comes back only if the press didn't apply.const prepushAct = async (c: PrepushCardData, act: () => Promise<PrepushCardData>, message: string) => {+ prepush.setActed(c.id, true);try {prepush.put(await act());} catch (e) {+ prepush.setActed(c.id, false);if (e instanceof DevModeError && e.status === 409) void prepush.refresh(c.id);throw e;}@@ -3972,7 +3976,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({}}top={<>- <PrepushNeedsYou cards={prepush.cards} names={kwantNames} onOpen={openPrepush} />+ <PrepushNeedsYou cards={prepush.cards} names={kwantNames} onOpen={openPrepush} acted={prepush.acted} /><SpendStopNeedsYou refreshKey={spendStopSeq} onOpenSettings={openUsageSettings} /><BudgetNeedsYou onRaise={raiseBudget} /></>@@ -4064,7 +4068,16 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({pendingApprovals={approvalsHere}prepush={devOn && currentKwant && !viewingHistory ? (- <PrepushThread cards={threadCards(prepush.cards, currentKwant.id)} bot={currentKwant.name} live={prepush.live} onRetry={prepushRetry} onOverride={prepushOverride} />+ <PrepushThread+ cards={threadCards(prepush.cards, currentKwant.id)}+ all={prepush.cards}+ bot={currentKwant.name}+ live={prepush.live}+ onRetry={prepushRetry}+ onOverride={prepushOverride}+ approvals={approvalsHere}+ onOpenApproval={setHighlightMessageId}+ />) : devOn && isChannel && !viewingHistory && pointerMemberIds.length > 0 ? (// 0.8.1 F3: team chats and channels get one pointer line per member bot; the card stays in the 1:1.<PrepushPointersdiff --git a/frontend/src/components/dev/PrepushCard.tsx b/frontend/src/components/dev/PrepushCard.tsxindex da0a53c8..346e79a8 100644--- a/frontend/src/components/dev/PrepushCard.tsx+++ b/frontend/src/components/dev/PrepushCard.tsx@@ -4,7 +4,7 @@// 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 { ArrowDown, ArrowUp, ArrowUpFromLine, ChevronDown, ChevronRight, GitBranch } from 'lucide-react';import { DiffStat, Led } from './parts';import { DevModeError } from '../../devMode';import {@@ -16,6 +16,7 @@ import {foldLine,foldable,footer,+ storyOf,needsYouLead,openCount,overriddenLine,@@ -26,6 +27,9 @@ import {rowFindings,statusChip,toolLine,+ afterRetryLine,+ pushedLine,+ type Story,MIN_REASON,MAX_REASON,type PrepushCard as Card,@@ -57,6 +61,14 @@ export interface PrepushCardProps {startOverride?: boolean;/** Start with the folded passing rows open on phone (screenshots and tests). */startUnfolded?: boolean;+ /** 0.9.7: after a retry or override, what happens next, following the bot's new push live. */+ story?: Story | null;+ /** 0.9.7: this card is the new push after the person's retry on `after`: one story, linked both ways. */+ after?: Card | null;+ /** Scroll to another pre-push card in this thread. */+ onOpenCard?: (id: string) => void;+ /** Open the approval the push still needs (floor, payment) in this chat. */+ onOpenApproval?: (id: string) => void;}const where = (f: PrepushFinding) => (f.file ? `${f.file}${f.line !== null ? `:${f.line}` : ''}` : null);@@ -112,6 +124,82 @@ const Row: React.FC<{ k: PrepushCheck; card: Card; hidePhone: boolean }> = ({ k,);};+/** Text with the branch rendered as code (Mira Later 6), at its first appearance. */+const withBranch = (text: string, branch: string): React.ReactNode => {+ const i = text.indexOf(branch);+ if (i < 0) return text;+ return (+ <>+ {text.slice(0, i)}+ <code className="dv-sha dv-sha-wrap">{branch}</code>+ {text.slice(i + branch.length)}+ </>+ );+};++const STORY_LED: Record<Story['step'], 'ok' | 'off' | 'run' | 'bad' | 'warn'> = {+ fixing: 'run',+ checking: 'run',+ pushing: 'run',+ asks: 'warn',+ pushed: 'ok',+ blocked: 'bad',+ expired: 'off',+ replaced: 'off',+};++/**+ * 0.9.7: where the push is after the person's press. One live line under the lead; the new card and an+ * approval the floor still needs are one link away, so the person never has to hunt for them.+ */+const StoryLine: React.FC<{ story: Story; card: Card; bot: string; onOpenCard?: (id: string) => void; onOpenApproval?: (id: string) => void }> = ({+ story,+ card,+ bot,+ onOpenCard,+ onOpenApproval,+}) => (+ <div data-story={story.step} className="mt-1.5 flex min-w-0 flex-col gap-1">+ {story.step === 'asks' && story.approval ? (+ // One amber line that says it and links to the approval (no second status line repeating it).+ <p+ role="status"+ data-story-approval={story.approval.id}+ className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 rounded-lg border border-amber-400/40 bg-amber-400/[.06] px-2.5 py-1.5 text-meta text-zinc-200"+ >+ <Led s={STORY_LED.asks} className="shrink-0 dv-led-still" />+ <span data-story-now className="min-w-0 flex-1 [overflow-wrap:anywhere]">{withBranch(story.now, card.branch)}</span>+ {onOpenApproval && (+ <button type="button" className={LINK} onClick={() => onOpenApproval(story.approval!.id)}>+ Open it <ArrowDown size={12} aria-hidden="true" />+ </button>+ )}+ </p>+ ) : (+ <p role="status" className="flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 text-meta">+ {/* The light stays beside the first line of text when a long line wraps on a phone (round 2). */}+ <span data-story-text className="flex min-w-0 items-start gap-2">+ <Led s={STORY_LED[story.step]} className={`mt-[5px] shrink-0 ${story.step === 'pushed' || story.step === 'blocked' ? '' : 'dv-led-still'}`} />+ <span data-story-now className={`min-w-0 [overflow-wrap:anywhere] ${story.step === 'pushed' ? 'font-medium text-emerald-300' : story.step === 'blocked' ? 'text-rose-300' : 'text-zinc-200'}`}>+ {story.step === 'asks' ? `${bot}'s push still needs your OK.` : story.now}+ </span>+ </span>+ {story.approval && onOpenApproval && story.step !== 'asks' && (+ // Round 3: an expired story still links the approval that waits for this push.+ <button type="button" data-story-approval={story.approval.id} className={LINK} onClick={() => onOpenApproval(story.approval!.id)}>+ Open it <ArrowDown size={12} aria-hidden="true" />+ </button>+ )}+ {story.next && onOpenCard && story.step !== 'asks' && !(story.approval && onOpenApproval) && (+ <button type="button" data-story-next={story.next.id} className={LINK} onClick={() => onOpenCard(story.next!.id)}>+ {story.step === 'blocked' ? 'See what it found' : story.step === 'pushed' ? 'See the push' : story.step === 'replaced' ? 'See the newer check' : 'See the new check'} <ArrowDown size={12} aria-hidden="true" />+ </button>+ )}+ </p>+ )}+ </div>+);+/** 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; error?: string }> = ({children,@@ -138,7 +226,19 @@ const Line: React.FC<{ children: React.ReactNode; led?: 'ok' | 'off'; status?: b</div>);-export const PrepushCard: React.FC<PrepushCardProps> = ({ card, bot, onRetry, onOverride, live = false, startOverride = false, startUnfolded = false }) => {+export const PrepushCard: React.FC<PrepushCardProps> = ({+ card,+ bot,+ onRetry,+ onOverride,+ live = false,+ startOverride = false,+ startUnfolded = false,+ story = null,+ after = null,+ onOpenCard,+ onOpenApproval,+}) => {const phase = phaseOf(card);const [form, setForm] = useState(startOverride && canOverride(card));const [reason, setReason] = useState('');@@ -221,13 +321,41 @@ export const PrepushCard: React.FC<PrepushCardProps> = ({ card, bot, onRetry, on</Line>);}- if (phase === 'RT') {+ if (phase === 'SS') {return (- <Line phase="RT" error={error?.text}>- You asked for a new check of <code className="dv-sha dv-sha-wrap">{card.branch}</code>. {bot}'s next push of this commit is checked again from try 1.+ <Line+ phase="SS"+ extra={+ card.superseded_by && onOpenCard ? (+ <button type="button" data-superseded-by={card.superseded_by} className={LINK} onClick={() => onOpenCard(card.superseded_by!)}>+ See the newer push <ArrowDown size={12} aria-hidden="true" />+ </button>+ ) : undefined+ }+ >+ Replaced by a newer push of <code className="dv-sha dv-sha-wrap">{card.branch}</code>. Nothing waits for you here.</Line>);}+ if (phase === 'RT') {+ // 0.9.7: the press is the approval. The card says at once what happens next and follows the new push.+ const lead = story?.lead ?? storyOf(card, [card], bot)?.lead ?? footer(card, bot);+ return (+ <div+ data-prepush-phase="RT"+ className="flex max-w-[640px] flex-col rounded-xl border border-hairline bg-surface-main px-3 py-2 text-meta text-zinc-400"+ >+ <p className="min-w-0 text-zinc-300 [overflow-wrap:anywhere]">{withBranch(lead, card.branch)}</p>+ {story && <StoryLine story={story} card={card} bot={bot} onOpenCard={onOpenCard} onOpenApproval={onOpenApproval} />}+ {error && (+ // A retry that applied but whose chat message failed lands here, on the retried line (#475 review 2).+ <p role="alert" className="mt-1 w-full text-meta text-bad [overflow-wrap:anywhere]">+ {error.text}+ </p>+ )}+ </div>+ );+ }if (phase === 'P2' && collapsed) {return (<Line@@ -241,6 +369,17 @@ export const PrepushCard: React.FC<PrepushCardProps> = ({ card, bot, onRetry, on>{(() => {const p = clearedParts(card);+ const used = card.grant?.used_at ?? null;+ if (used !== null)+ return (+ <span data-pushed>+ {/* Mira FIX 4: keyed on the grant, so it reads the same when the pressed card is out of view. */}+ <span className="font-medium text-emerald-300">{pushedLine(used)}</span> · <code className="dv-sha dv-sha-wrap">{p.branch}</code>+ {card.grant?.kind === 'override'+ ? " · your Push anyway was the OK, so it didn't ask again."+ : " · your retry was the OK, so it didn't ask again."}+ </span>+ );return (<>{p.before}@@ -287,6 +426,16 @@ export const PrepushCard: React.FC<PrepushCardProps> = ({ card, bot, onRetry, onaria-labelledby={titleId}className="kw-card w-full max-w-[640px] p-3 sm:p-4">+ {after && (+ <p data-after-retry={after.id} className="-mt-0.5 mb-2 flex min-w-0 flex-wrap items-center gap-x-1.5 text-meta text-zinc-400">+ <span className="min-w-0 [overflow-wrap:anywhere]">{afterRetryLine(card)}</span>+ {onOpenCard && (+ <button type="button" className={LINK} onClick={() => onOpenCard(after.id)}>+ See your request <ArrowUp size={12} aria-hidden="true" />+ </button>+ )}+ </p>+ )}<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} />@@ -458,7 +607,8 @@ export const PrepushCard: React.FC<PrepushCardProps> = ({ card, bot, onRetry, on{phase === 'P6' && (<div className="mt-3 text-meta text-zinc-300">- <p>{overriddenLine(card)}</p>+ <p>{story ? story.lead : overriddenLine(card, bot)}</p>+ {story && <StoryLine story={story} card={card} bot={bot} onOpenCard={onOpenCard} onOpenApproval={onOpenApproval} />}{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>diff --git a/frontend/src/components/dev/PrepushPointers.tsx b/frontend/src/components/dev/PrepushPointers.tsxindex 197487b1..701f55c1 100644--- a/frontend/src/components/dev/PrepushPointers.tsx+++ b/frontend/src/components/dev/PrepushPointers.tsx@@ -14,7 +14,7 @@ export const POINTER_LINES = 3;export const POINTER_WINDOW_MS = 24 * 60 * 60 * 1000;/** P2, P6 and P0 lines leave 10 min after the card's last update. */export const POINTER_SETTLED_MS = 10 * 60 * 1000;-const SETTLED: ReadonlySet<Phase> = new Set(['P2', 'P6', 'P0']);+const SETTLED: ReadonlySet<Phase> = new Set(['P2', 'P6', 'P0', 'SS']);export interface PointerPick {lines: Card[];@@ -91,6 +91,8 @@ export function pointerParts(c: Card, bot: string): Part[] {return [T('You let '), Bs, T(' push of '), R, T(' go anyway')];case 'P0':return [T('Nothing to push: '), R, T(' has no new commits')];+ case 'SS':+ return [Bs, T(' push of '), R, T(' was replaced by a newer push')];case 'UN':return [B, T(" has a push check this version can't show · update the app to see where it is")];}@@ -110,6 +112,7 @@ const LED: Record<Phase, 'run' | 'bad' | 'warn' | 'ok' | 'off'> = {P2: 'ok',P6: 'off',P0: 'off',+ SS: 'off',UN: 'off',};diff --git a/frontend/src/components/dev/PrepushThread.tsx b/frontend/src/components/dev/PrepushThread.tsxindex c7adf24b..a8db2d2b 100644--- a/frontend/src/components/dev/PrepushThread.tsx+++ b/frontend/src/components/dev/PrepushThread.tsx@@ -6,7 +6,19 @@import React, { useCallback, useEffect, useRef, useState } from 'react';import { ArrowUpFromLine } from 'lucide-react';import { PrepushCard } from './PrepushCard';-import { PREPUSH_EVENT, inboxLine, mergeList, needsYou, prepushApi, upsert, type PrepushCard as Card } from '../../dev/prepush';+import {+ PREPUSH_EVENT,+ inboxLine,+ mergeList,+ needsYou,+ prepushApi,+ pressedBefore,+ pushApproval,+ liveCard,+ storyOf,+ upsert,+ type PrepushCard as Card,+} from '../../dev/prepush';export interface PrepushEventDetail {space_id: string;@@ -22,6 +34,10 @@ export interface PrepushState {put: (c: Card) => void;/** Fetch one card again (after a 409, so the card shows where it really is). */refresh: (id: string) => Promise<void>;+ /** 0.9.7: cards the person just retried or overrode. They leave Needs you at once, before the server answers. */+ acted: ReadonlySet<string>;+ /** Mark a card acted on (true) or put it back when the call failed (false). */+ setActed: (id: string, on: boolean) => void;}type Api = Pick<typeof prepushApi, 'list' | 'get'>;@@ -29,6 +45,16 @@ 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 [acted, setActedState] = useState<ReadonlySet<string>>(new Set());+ const setActed = useCallback((id: string, on: boolean) => {+ setActedState((s) => {+ if (s.has(id) === on) return s;+ const n = new Set(s);+ if (on) n.add(id);+ else n.delete(id);+ return n;+ });+ }, []);const seen = useRef(new Map<string, string>());// A list or card load that failed: load the list again on the next event or window focus, so a// card waiting for the person doesn't stay hidden until its own next event (Ada Later 1).@@ -58,6 +84,7 @@ export function usePrepushCards(spaceId: string, on: boolean, api: Api = prepushuseEffect(() => {setCards([]);setLive(new Set());+ setActedState(new Set());seen.current = new Map();stale.current = false;if (!on || !spaceId) {@@ -110,7 +137,7 @@ export function usePrepushCards(spaceId: string, on: boolean, api: Api = prepush};}, [spaceId, on, api, put]);- return { cards, live, put, refresh };+ return { cards, live, put, refresh, acted, setActed };}/** How many of a bot's cards the thread shows: the newest few, oldest first like the chat. */@@ -125,28 +152,70 @@ export function threadCards(cards: Card[], kwantId: string): Card[] {.reverse();}+type ApprovalLike = Parameters<typeof pushApproval>[1][number];++/** Scroll to a card in the open chat and ring it, like an Inbox item does (none under reduced motion, in CSS). */+export function jumpToCard(id: string): void {+ const el = document.getElementById(`prepush-${id}`);+ if (!el) return;+ el.scrollIntoView?.({ block: 'center' });+ el.classList.remove('kw-prepush-flash');+ void el.offsetWidth;+ el.classList.add('kw-prepush-flash');+ window.setTimeout(() => el.classList.remove('kw-prepush-flash'), 1300);+}+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 }) => {+ /** 0.9.7: every card of the space, so a pressed card can follow the new push its retry led to. */+ all?: Card[];+ /** The chat's pending approvals: a floor or payment approval the pressed push still needs is linked. */+ approvals?: readonly ApprovalLike[];+ onOpenApproval?: (id: string) => void;+}> = ({ cards, bot, live, onRetry, onOverride, all, approvals = [], onOpenApproval }) => {if (cards.length === 0) return null;+ const every = all ?? cards;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="relative max-w-[640px] scroll-mt-4 rounded-xl">- <PrepushCard card={c} bot={bot} live={live.has(c.id)} onRetry={onRetry} onOverride={onOverride} />- </div>- ))}+ {cards.map((c) => {+ const story = storyOf(c, every, bot, pushApproval(c, approvals));+ const after = pressedBefore(c, every);+ return (+ <div key={c.id} id={`prepush-${c.id}`} className="relative max-w-[640px] scroll-mt-4 rounded-xl">+ <PrepushCard+ card={c}+ bot={bot}+ live={live.has(c.id)}+ onRetry={onRetry}+ onOverride={onOverride}+ story={story}+ after={after}+ onOpenCard={(id) => {+ // Round 3: a "newer" link lands on the live card, never on one that is itself replaced.+ const t = every.find((x) => x.id === id);+ jumpToCard(t ? liveCard(t, every).id : id);+ }}+ onOpenApproval={onOpenApproval}+ />+ </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);+export const PrepushNeedsYou: React.FC<{ cards: Card[]; names: Record<string, string>; onOpen: (c: Card) => void; acted?: ReadonlySet<string> }> = ({+ cards,+ names,+ onOpen,+ acted,+}) => {+ const list = needsYou(cards, acted);if (list.length === 0) return null;return (<section aria-labelledby="needs-prepush-h" data-needs-prepush data-needs-you>@@ -164,8 +233,11 @@ export const PrepushNeedsYou: React.FC<{ cards: Card[]; names: Record<string, stclassName="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>+ <span className="min-w-0 flex-1">+ <span className="block [overflow-wrap:anywhere]">{inboxLine(c, names[c.kwant_id] || 'A bot')}</span>+ {/* One item per branch: the branch goes under the line at every width, since it is what tells two items apart (Mira FIX 5). */}+ <code data-needs-branch title={c.branch} className="dv-sha mt-1 inline-block max-w-full truncate align-top">{c.branch}</code>+ </span></button></li>))}diff --git a/frontend/src/dev/prepush.ts b/frontend/src/dev/prepush.tsindex ac6f48e5..f485b167 100644--- a/frontend/src/dev/prepush.ts+++ b/frontend/src/dev/prepush.ts@@ -19,8 +19,8 @@ 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;-/** `unknown`: a status this build can't read yet (e.g. §4.4b `pushed`). Shown as a read-only grey line,+export const PREPUSH_STATUSES = ['checking', 'clear', 'blocked', 'failed', 'overridden', 'pushed', 'retried', 'superseded'] as const;+/** `unknown`: a status this build can't read yet. Shown as a read-only grey line,* never dropped, so a card doesn't vanish from the thread when the server learns a new state. */export type PrepushStatus = (typeof PREPUSH_STATUSES)[number] | 'unknown';export const CHECK_KEYS = ['secrets', 'pkgs', 'tests', 'risk', 'review', 'semgrep'] as const;@@ -47,10 +47,29 @@ export interface PrepushFinding {open: boolean;}+/**+ * 0.9.7 prepush-grant: the person's press is the approval. "Ask {bot} to try again" (retry) covers the+ * bot's next push of the branch once its card comes back clear; "Push anyway" (override) covers the one+ * push of that commit. Both the card the person pressed and the card the covered push makes carry it.+ */+export interface PrepushGrant {+ kind: 'retry' | 'override';+ at: number | null;+ expires_at: number | null;+ /** When the push it covered went; null while it's still waiting. */+ used_at: number | null;+ /** The card the person pressed, when the server names it. */+ card_id: string | null;+ /** The newest card a push of the branch made while the grant waited, then the card of the push it let go. */+ next_card_id: string | null;+}+export interface PrepushCard {id: string;space_id: string | null;kwant_id: string;+ /** The folder the push runs in, when the server sends it (Needs you is one item per bot, folder, branch). */+ folder: string | null;branch: string;head_sha: string | null;status: PrepushStatus;@@ -65,6 +84,9 @@ export interface PrepushCard {reviewer: { name: string; engine: string | null; model: string | null } | null;fresh_eyes: FreshEyes | null;error: string | null;+ grant: PrepushGrant | null;+ /** On a superseded card: the newer card that replaced it. */+ superseded_by: string | null;created_at: number | null;updated_at: number | null;}@@ -106,6 +128,13 @@ function diffstat(v: unknown): PrepushCard['diffstat'] {return { files, add, del };}+function grant(v: unknown): PrepushGrant | null {+ if (!isObj(v)) return null;+ const kind = v.kind === 'retry' || v.kind === 'override' ? v.kind : null;+ if (!kind) return null;+ return { kind, at: num(v.at), expires_at: num(v.expires_at), used_at: num(v.used_at), card_id: str(v.card_id, 120), next_card_id: str(v.next_card_id, 120) };+}+/** 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;@@ -128,6 +157,7 @@ export function parsePrepush(raw: unknown): PrepushCard | null {id,space_id: str(raw.space_id, 120),kwant_id: kwant,+ folder: str(raw.folder, 400),branch,head_sha: str(raw.head_sha, 64),status,@@ -142,6 +172,8 @@ export function parsePrepush(raw: unknown): PrepushCard | null {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,+ grant: grant(raw.grant),+ superseded_by: status === 'superseded' ? str(raw.superseded_by, 120) : null,created_at: num(raw.created_at),updated_at: num(raw.updated_at),};@@ -161,9 +193,10 @@ export type Phase =| 'P2' // all clear| 'P3' // blocked, the bot is fixing| 'P4' // needs you- | 'P6' // pushed anyway (overridden)+ | 'P6' // pushed anyway (overridden, or pushed: its one push went)| 'P7' // a check couldn't run (failed, before needs_you)| 'RT' // the person asked for a re-check (retried)+ | 'SS' // superseded: a newer push of the branch replaced it| 'UN'; // a status this build can't read yet: a read-only lineexport function phaseOf(c: PrepushCard): Phase {@@ -177,9 +210,12 @@ export function phaseOf(c: PrepushCard): Phase {case 'failed':return c.needs_you ? 'P4' : 'P7';case 'overridden':+ case 'pushed':return 'P6';case 'retried':return 'RT';+ case 'superseded':+ return 'SS';case 'unknown':return 'UN';}@@ -219,11 +255,12 @@ export function statusChip(c: PrepushCard): StatusChip | null {case 'P4':return { tone: 'warn', text: 'Needs you', led: null };case 'P6':- return { tone: 'plain', text: 'Pushed anyway', led: null };+ return { tone: 'plain', text: c.status === 'pushed' ? 'Pushed' : '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 };+ case 'SS':case 'UN':return null;}@@ -360,7 +397,9 @@ export function footer(c: PrepushCard, bot: string): string {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.`;+ return `You asked ${bot} to fix this and push again.`;+ case 'SS':+ return `Replaced by a newer push of ${c.branch}.`;case 'UN':return `This version of the app can't show where the check of ${c.branch} is yet. Update the app to see it.`;}@@ -384,10 +423,17 @@ export function clearedLine(c: PrepushCard): string {return `${p.before}${p.branch}${p.after}`;}-export function overriddenLine(c: PrepushCard): string {+// The override's first sentence on its own: what the person did, with no promise about the next push.+export function overriddenHead(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.`;+ return `You let this push go${at ? ` at ${at}` : ''} with ${plural(openCount(c), 'finding')} open.`;+}++export function overriddenLine(c: PrepushCard, bot: string): string {+ const head = overriddenHead(c);+ // Mira FIX 2: with a grant, the press was the OK, and the card says so.+ if (c.grant) return `${head} That was your OK: ${bot}'s push of this commit goes without asking you.`;+ return `${head} It covers this commit only.`;}export function inboxLine(c: PrepushCard, bot: string): string {@@ -398,10 +444,10 @@ export function inboxLine(c: PrepushCard, bot: string): string {/** 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.`;+ `Fix what the pre-push check found on ${c.branch}, commit, and push again. I've given my OK for that push, so once the checks pass it goes without asking me.`;export const overrideMessage = (c: PrepushCard): string =>- `I let your push of ${c.branch} go anyway, for this commit only. Run the same push again.`;+ `I let your push of ${c.branch} go anyway, for this commit only. That was my OK, so run the same push again without asking me.`;/** Characters as the server counts them (code points, not UTF-16 units: Ada Later 6). */export const reasonLength = (s: string): number => [...s.trim()].length;@@ -410,12 +456,213 @@ export const reasonOk = (s: string): boolean => reasonLength(s) >= MIN_REASON &&/** The card changed but the chat message to the bot didn't go (Ada Later 7). */export const messageNotSent = (bot: string): string => `Done, but the message to ${bot} didn't send. Tell ${bot} in the chat.`;+// ---------------------------------------------------------------------------------------------+// After the press (0.9.7 prepush-grant): one story from the person's press to the push++/** The cards of one push target: the same bot, folder (when the server sends it) and branch. */+export const branchKey = (c: PrepushCard): string => JSON.stringify([c.space_id ?? '', c.kwant_id, c.folder ?? '', c.branch]);++/** Whether the person pressed this card (retry, override) and the press still tells a story. */+export const pressed = (c: PrepushCard): boolean => c.status === 'retried' || c.status === 'overridden' || c.status === 'pushed';++/**+ * The card the bot's next push made after the person pressed `c`: named by the grant's `card_id` when+ * the server sends it, otherwise the newest later card of the same push target. Null while the bot is+ * still fixing. An override's push goes on the same card, so it has none.+ */+export function followUp(c: PrepushCard, cards: PrepushCard[]): PrepushCard | null {+ if (c.status !== 'retried') return null;+ const named = c.grant?.next_card_id ? cards.find((x) => x.id === c.grant!.next_card_id && x.id !== c.id) : undefined;+ if (named) return named;+ const key = branchKey(c);+ const after = c.grant?.at ?? c.updated_at ?? c.created_at ?? 0;+ const later = cards+ .filter((x) => x.id !== c.id && branchKey(x) === key)+ .filter((x) => (x.grant?.card_id ? x.grant.card_id === c.id : (x.created_at ?? 0) >= after))+ .sort((a, b) => (b.created_at ?? 0) - (a.created_at ?? 0));+ return later[0] ?? null;+}++/** The card a follow-up card came from, for its "after your retry" line. */+export function pressedBefore(c: PrepushCard, cards: PrepushCard[]): PrepushCard | null {+ if (pressed(c)) return null;+ return cards.find((x) => x.status === 'retried' && followUp(x, cards)?.id === c.id) ?? null;+}++/** An approval still waiting for this push (production floor, payment): the card links to it. */+export interface PushApproval {+ id: string;+ /** Why this kind of push always asks (the floor's why, or the payment reason); null when neither says. */+ reason: string | null;+}++export type StoryStep =+ | 'fixing' // retry: the bot hasn't pushed again yet+ | 'checking' // its new push is being checked+ | 'pushing' // clear (or overridden): the push goes now, no card asks+ | 'asks' // a floor or payment approval still has to be answered+ | 'pushed' // the push went+ | 'blocked' // the new push was blocked again+ | 'expired' // the grant's window ran out before the push it covered+ | 'replaced'; // a newer push replaced this one before it went++export interface Story {+ step: StoryStep;+ /** The first line: what the person did, and what it lets happen. */+ lead: string;+ /** Where it is now. */+ now: string;+ /** The new card, to link to (retry only). */+ next: PrepushCard | null;+ /** When `step` is 'pushed'. */+ at: number | null;+ approval: PushApproval | null;+}++const usedAt = (...cs: (PrepushCard | null)[]): number | null => {+ for (const c of cs) if (c?.grant?.used_at) return c.grant.used_at;+ return null;+};++/**+ * What the card says after the person pressed it, and how it follows the bot's new push live.+ * Retry: fixing → checking the new push → Pushed · HH:MM, or blocked again. Override: pushing → Pushed.+ * `now` is the clock (ms), so a retry window that ran out says so instead of "fixing" for ever.+ */+export function storyOf(c: PrepushCard, cards: PrepushCard[], bot: string, approval: PushApproval | null = null, now = Date.now()): Story | null {+ if (!pressed(c)) return null;+ const covered = !!c.grant;+ if (c.status === 'overridden' || c.status === 'pushed') {+ const at = c.status === 'pushed' ? (usedAt(c) ?? c.updated_at) : null;+ // One source for the override's first line: the card renders it as the lead (Mira FIX 2).+ const lead = overriddenLine(c, bot);+ if (at !== null || c.status === 'pushed') return { step: 'pushed', lead, now: pushedLine(at), next: null, at, approval: null };+ const exp = c.grant?.expires_at ?? null;+ if (c.grant && c.grant.used_at === null && exp !== null && now >= exp)+ // Ada (Nov 13), Mira's FIX 7 rule: in an expired step the lead drops its promise.+ return { step: 'expired', lead: overriddenHead(c), now: `${bot} didn't push within 2 hours, so your OK ran out. Its push asks you as usual.`, next: null, at: null, approval: null };+ // Round 3: while a floor or payment approval waits, the lead promises nothing (same rule as expired).+ if (approval) return { step: 'asks', lead: overriddenHead(c), now: asksLine(bot, approval), next: null, at: null, approval };+ return { step: 'pushing', lead, now: `${bot} can push it now.`, next: null, at: null, approval: null };+ }+ // retried+ const lead = covered+ ? `You asked ${bot} to fix this and push again. That was your OK: once the checks pass, its next push of ${c.branch} goes without asking you.`+ : `You asked ${bot} to fix this and push again. Its next push of ${c.branch} is checked from try 1.`;+ const next = followUp(c, cards);+ const at = usedAt(next, c);+ const base = { lead, next, approval: null, at: null };+ if (at !== null) return { ...base, step: 'pushed', now: pushedLine(at), at };+ // The lead says only what the person did once its promise no longer holds (Mira FIX 7, Ada round 3).+ const plain = `You asked ${bot} to fix this and push again.`;+ const exp = c.grant?.expires_at ?? null;+ const blockedNext = next !== null && (next.status === 'blocked' || next.status === 'failed');+ // Round 3 (Rigel QA 5): an unused grant past its window has run out, even when a later push made a card+ // (that push asked as usual). A blocked follow-up still says "Blocked again": that card needs the person anyway.+ if (covered && c.grant!.used_at === null && exp !== null && now >= exp && !blockedNext)+ return {+ ...base,+ lead: plain,+ step: 'expired',+ now: `No fixed push came within 2 hours, so your OK ran out. ${bot}'s next push asks you as usual.`,+ approval,+ };+ // Round 3 (Rigel QA 4): a production-floor push makes no pre-push card, so the floor's own approval is+ // the only sign of it. Show it while the card would otherwise still say "fixing" or "checking".+ if (approval && (!next || next.status === 'checking' || next.status === 'clear'))+ return { ...base, lead: plain, step: 'asks', now: asksLine(bot, approval), approval };+ if (!next) return { ...base, step: 'fixing', now: `${bot} is fixing it…` };+ switch (next.status) {+ case 'checking':+ return { ...base, step: 'checking', now: `Checking ${bot}'s new push…` };+ case 'clear':+ return { ...base, step: 'pushing', now: `The checks passed. ${bot} is pushing…` };+ case 'blocked':+ case 'failed': {+ const n = openCount(next);+ const what = next.status === 'failed' && n === 0 ? "a check couldn't run" : plural(Math.max(n, 1), 'finding');+ return { ...base, step: 'blocked', now: `Blocked again: ${what}. Nothing was pushed.` };+ }+ case 'superseded':+ // Round 3: link the live end of the chain, not a card that is itself "Replaced".+ return { ...base, next: liveCard(next, cards), step: 'replaced', now: `${bot} pushed again, so a newer check replaced this one.` };+ default:+ return { ...base, step: 'checking', now: `Checking ${bot}'s new push…` };+ }+}++/**+ * The live card at the end of a superseded chain: follows `superseded_by` at most 10 hops and stops on a+ * cycle or a card the list doesn't have, returning the last card it reached.+ */+export function liveCard(c: PrepushCard, cards: PrepushCard[]): PrepushCard {+ const seen = new Set<string>([c.id]);+ let cur = c;+ for (let i = 0; i < 10 && cur.superseded_by; i++) {+ const nx = cards.find((x) => x.id === cur.superseded_by);+ if (!nx || seen.has(nx.id)) break;+ seen.add(nx.id);+ cur = nx;+ }+ return cur;+}++export const pushedLine = (at: number | null): string => (hhmm(at) ? `Pushed · ${hhmm(at)}` : 'Pushed');+/** Mira FIX 3: "still" and "always ask" say the press covered the usual OK, not this kind. */+export const asksLine = (bot: string, a: PushApproval): string =>+ a.reason ? `${bot}'s push still needs your OK. ${a.reason.charAt(0).toUpperCase()}${a.reason.slice(1)}. Pushes like this always ask, every time.` : `${bot}'s push still needs your OK. Pushes like this always ask, every time.`;++/** A follow-up card's own lead line, so the two cards read as one story. */+export const afterRetryLine = (c: PrepushCard): string => {+ const at = hhmm(c.grant?.at ?? null);+ return `After you asked for a fix${at ? ` at ${at}` : ''}.`;+};++/**+ * The approval a push the person already let go still has to get (floor or payment), from the chat's+ * pending approvals: the same bot, asked after the press, and one the floor raised. Never the ordinary+ * approval: the grant replaces that one, so if one shows up it isn't this push's.+ */+export function pushApproval(+ c: PrepushCard,+ approvals: readonly { id: string; tool_name: string; details: Record<string, unknown>; asked_at?: string; kwant_id?: string | null }[],+): PushApproval | null {+ if (!pressed(c) || (c.status === 'pushed')) return null;+ const after = c.grant?.at ?? c.updated_at ?? 0;+ for (const a of approvals) {+ const kw = a.kwant_id ?? (typeof a.details.kwant_id === 'string' ? a.details.kwant_id : null);+ if (kw !== c.kwant_id) continue;+ const asked = a.asked_at ? Date.parse(a.asked_at) : NaN;+ if (Number.isFinite(asked) && asked + 5_000 < after) continue;+ const floor = isObj(a.details.prod_floor) ? a.details.prod_floor : null;+ const pay = str(a.details.payment_reason, 300);+ if (!floor && !pay) continue;+ const reason = ((floor && str(floor.why, 300)) || pay || '').replace(/[.\s]+$/, '');+ return { id: a.id, reason: reason || null };+ }+ return null;+}+// ---------------------------------------------------------------------------------------------// 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));+/**+ * The Inbox's pushes waiting for the person, newest first: at most one per push target (bot, folder,+ * branch), and only when the newest card there is the one waiting. An older blocked card on a branch the+ * bot has pushed again since (or that the server marked superseded) never shows. `hidden`: cards the+ * person just retried or overrode, which leave at once, before the server answers. A superseded card never+ * counts as the newest: the server can revive an older commit the bot pushes again and supersede the newer+ * card instead (impl.md, server deviation 5), and the revived one is then the one waiting.+ */+export function needsYou(cards: PrepushCard[], hidden: ReadonlySet<string> = new Set()): PrepushCard[] {+ const newest = new Map<string, PrepushCard>();+ for (const c of cards) {+ if (c.status === 'superseded') continue;+ const k = branchKey(c);+ const h = newest.get(k);+ if (!h || (c.created_at ?? 0) > (h.created_at ?? 0) || ((c.created_at ?? 0) === (h.created_at ?? 0) && (c.updated_at ?? 0) > (h.updated_at ?? 0))) newest.set(k, c);+ }+ return [...newest.values()].filter((c) => c.needs_you && !hidden.has(c.id)).sort((a, b) => (b.updated_at ?? 0) - (a.updated_at ?? 0));}/**diff --git a/frontend/src/dev/prepushFixtures.ts b/frontend/src/dev/prepushFixtures.tsindex 908647ee..f79dc5ea 100644--- a/frontend/src/dev/prepushFixtures.ts+++ b/frontend/src/dev/prepushFixtures.ts@@ -127,6 +127,24 @@ export const PP_OVERRIDDEN = {export const PP_RETRIED = { ...PP_NEEDS_YOU, id: 'pp_retried', status: 'retried', needs_you: false };+// 0.9.7 prepush-grant: the person's press is the approval (autonomy/prepush-retry/brief.md).+const GRANT_AT = PP_T0 + 10 * min;+const grant = (kind: 'retry' | 'override', card_id: string, used_at: number | null = null) => ({ kind, at: GRANT_AT, expires_at: GRANT_AT + 120 * min, used_at, card_id });+const NEXT_SHA = '9d8c7b6a5f4e3d2c1b0a99887766554433221100';++/** The person pressed "Ask Pixel to try again" on PP_NEEDS_YOU. */+export const PP_RETRIED_GRANT = { ...PP_NEEDS_YOU, id: 'pp_rg', status: 'retried', needs_you: false, updated_at: GRANT_AT, grant: grant('retry', 'pp_rg') };+const nextBase = { head_sha: NEXT_SHA, tries: 1, created_at: GRANT_AT + 4 * min, updated_at: GRANT_AT + 4 * min, grant: grant('retry', 'pp_rg') };+export const PP_NEXT_CHECKING = { ...PP_CHECKING, ...nextBase, id: 'pp_next', updated_at: GRANT_AT + 4 * min };+export const PP_NEXT_CLEAR = { ...PP_CLEAR, ...nextBase, id: 'pp_next', updated_at: GRANT_AT + 5 * min };+export const PP_NEXT_PUSHED = { ...PP_NEXT_CLEAR, grant: grant('retry', 'pp_rg', GRANT_AT + 5 * min + 20_000) };+export const PP_NEXT_BLOCKED = { ...PP_BLOCKED, ...nextBase, id: 'pp_next', updated_at: GRANT_AT + 5 * min };+/** An older blocked card on the branch, replaced by a newer push. */+export const PP_SUPERSEDED = { ...PP_BLOCKED, id: 'pp_super', status: 'superseded', needs_you: false };+/** "Push anyway" on PP_NEEDS_YOU, before and after its one push went. */+export const PP_OVERRIDDEN_GRANT = { ...PP_OVERRIDDEN, id: 'pp_og', grant: { ...grant('override', 'pp_og'), at: PP_T0 + 9 * min } };+export const PP_PUSHED = { ...PP_OVERRIDDEN_GRANT, status: 'pushed', updated_at: PP_T0 + 9 * min + 30_000, grant: { ...PP_OVERRIDDEN_GRANT.grant, used_at: PP_T0 + 9 * min + 30_000 } };+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)diff --git a/frontend/tests/prepush.test.mjs b/frontend/tests/prepush.test.mjsindex 3d5afe5e..8a481c0d 100644--- a/frontend/tests/prepush.test.mjs+++ b/frontend/tests/prepush.test.mjs@@ -89,7 +89,7 @@ test('every fixture parses and maps to Mira\'s phase', () => {test('the parser refuses cards it cannot show honestly', () => {assert.equal(m.parsePrepush(null), null);- assert.equal(m.parsePrepush({ ...fx.PP_CLEAR, status: 'pushed' }).status, 'unknown', 'a newer status is kept, read-only (Ada Later 2)');+ assert.equal(m.parsePrepush({ ...fx.PP_CLEAR, status: 'merged_later' }).status, 'unknown', 'a newer status is kept, read-only (Ada Later 2)');assert.equal(m.parsePrepush({ ...fx.PP_CLEAR, status: 7 }), null, 'a status that is not a word is refused');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');@@ -130,7 +130,7 @@ test('counts come from the server: open findings are its blockers, never a checkassert.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.');+ assert.equal(m.overriddenLine(card(fx.PP_OVERRIDDEN), 'Pixel'), 'You let this push go at 14:09 with 1 finding open. It covers this commit only.', 'old server, no grant: unchanged');});test('a check that could not run never reads as passed', () => {@@ -284,7 +284,7 @@ test('P7 a check could not run: plain buttons, Run the checks again', async () =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\./);+ assert.match(out, /You asked Pixel to fix this and push again\. Its next push of .*pixel\/inbox-empty-state.* is checked from try 1\./);});test('read-only cards (no handlers) show no buttons', () => {@@ -348,10 +348,12 @@ test('threadCards: this bot only, newest three, oldest first', () => {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)];+ // 0.9.7: PP_FAILED_NEEDS_YOU is an older card on the same branch, so only the newest (PP_NEEDS_YOU) shows.+ const cards = [card(fx.PP_NEEDS_YOU), card(fx.PP_BLOCKED), card(fx.PP_CLEAR), card(fx.PP_FAILED_NEEDS_YOU), card({ ...fx.PP_FAILED_NEEDS_YOU, id: 'pp_other', branch: 'pixel/other' })];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.deepEqual(items.map((i) => i.getAttribute('data-needs-prepush-item')).sort(), ['pp_needs', 'pp_other']);assert.match(text(items[0]), /Needs you.*Pixel's push is waiting for you/);await click(items[0]);assert.equal(opened.length, 1);@@ -558,12 +560,12 @@ test('Ada 6: the reason counts characters as the server does, not UTF-16 units',});test('Ada 2: an unknown status shows as a read-only grey line, never dropped or actionable', async () => {- const c = card({ ...fx.PP_OVERRIDDEN, status: 'pushed' });+ const c = card({ ...fx.PP_OVERRIDDEN, status: 'merged_later' });assert.equal(m.phaseOf(c), 'UN');assert.equal(m.statusChip(c), null);assert.equal(m.canOverride(c), false);assert.equal(c.needs_you, false);- assert.equal(m.parsePrepushList({ cards: [{ ...fx.PP_CLEAR, status: 'pushed' }] }).length, 1);+ assert.equal(m.parsePrepushList({ cards: [{ ...fx.PP_CLEAR, status: 'merged_later' }] }).length, 1);const out = html(m.PrepushCard, { card: c, bot: 'Pixel', onRetry: async () => {}, onOverride: async () => {} });assert.match(out, /data-prepush-phase="UN"/);assert.match(out, /can't show where it is yet/);@@ -746,7 +748,7 @@ test('#475 review 2: a retry that applied but whose message failed shows the aletest('#475 Mira must-fix 1: the branch on one-line cards wraps; "fixing it" with one blocker', async () => {const long = 'pixel/inbox-empty-state-for-new-spaces-with-no-bots';- for (const c of [fx.PP_NO_CHANGE, fx.PP_RETRIED, { ...fx.PP_CLEAR, status: 'pushed' }, fx.PP_CLEAR]) {+ for (const c of [fx.PP_NO_CHANGE, fx.PP_RETRIED, { ...fx.PP_CLEAR, status: 'merged_later' }, fx.PP_CLEAR]) {const out = html(m.PrepushCard, { card: card({ ...c, branch: long }), bot: 'Pixel' });assert.match(out, new RegExp(`<code class="dv-sha dv-sha-wrap">${long}</code>`), c.id);}diff --git a/frontend/tests/prepushGrant.test.mjs b/frontend/tests/prepushGrant.test.mjsnew file mode 100644index 00000000..c8db7286--- /dev/null+++ b/frontend/tests/prepushGrant.test.mjs@@ -0,0 +1,455 @@+// 0.9.7 prepush-grant (Pixel): the card after retry/override, one Needs-you item per branch, superseded.+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 { DevModeError } from './src/devMode';+ 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();+};++// ---------------------------------------------------------------------------------------------------+// 0.9.7 prepush-grant (autonomy/prepush-retry/brief.md, Frontend): the press is the approval.++const HM = (ms) => new Date(ms).toISOString().slice(11, 16);+const all = (...ks) => ks.map((k) => card(fx[k]));++test('grant and superseded parse; pushed is a known status now; a junk grant is dropped', () => {+ const r = card(fx.PP_RETRIED_GRANT);+ assert.deepEqual(r.grant, { kind: 'retry', at: fx.PP_RETRIED_GRANT.grant.at, expires_at: fx.PP_RETRIED_GRANT.grant.expires_at, used_at: null, card_id: 'pp_rg', next_card_id: null });+ assert.equal(card({ ...fx.PP_RETRIED_GRANT, grant: { ...fx.PP_RETRIED_GRANT.grant, next_card_id: 'pp_next' } }).grant.next_card_id, 'pp_next');+ assert.equal(card({ ...fx.PP_RETRIED_GRANT, grant: { kind: 'always', at: 1 } }).grant, null, 'only retry or override');+ assert.equal(card({ ...fx.PP_RETRIED_GRANT, grant: null }).grant, null);+ assert.equal(card(fx.PP_CLEAR).grant, null, 'old servers send no grant');+ assert.equal(card(fx.PP_CLEAR).folder, null);+ assert.equal(card({ ...fx.PP_CLEAR, folder: 'kwant' }).folder, 'kwant');+ const s = card(fx.PP_SUPERSEDED);+ assert.equal(s.status, 'superseded');+ assert.equal(m.phaseOf(s), 'SS');+ assert.equal(card({ ...fx.PP_SUPERSEDED, needs_you: true }).needs_you, false, 'a superseded card never needs you');+ assert.equal(m.canRetry(s), false);+ assert.equal(m.statusChip(s), null);+ assert.equal(s.superseded_by, null);+ assert.equal(card({ ...fx.PP_SUPERSEDED, superseded_by: 'pp_new' }).superseded_by, 'pp_new');+ assert.equal(card({ ...fx.PP_BLOCKED, superseded_by: 'pp_new' }).superseded_by, null, 'only a superseded card names its replacement');+ const p = card(fx.PP_PUSHED);+ assert.equal(p.status, 'pushed');+ assert.equal(m.phaseOf(p), 'P6');+ assert.equal(m.statusChip(p).text, 'Pushed');+});++test('superseded renders folded: one grey line, no checks, no buttons', () => {+ const out = html(m.PrepushCard, { card: card(fx.PP_SUPERSEDED), bot: 'Pixel', onRetry: async () => {}, onOverride: async () => {} });+ assert.match(out, /data-prepush-phase="SS"/);+ assert.match(out, /Replaced by a newer push of <code[^>]*>pixel\/inbox-empty-state<\/code>/);+ assert.doesNotMatch(out, /<button/);+ assert.doesNotMatch(out, /data-check=/);+ const linked = html(m.PrepushCard, { card: card({ ...fx.PP_SUPERSEDED, superseded_by: 'pp_new' }), bot: 'Pixel', onOpenCard: () => {} });+ assert.match(linked, /data-superseded-by="pp_new"[^>]*>See the newer push/, 'the server names the newer card: link to it');+});++test('needsYou: one item per bot, folder and branch, the newest; an older card on a pushed-again branch never shows', () => {+ const older = card({ ...fx.PP_FAILED_NEEDS_YOU, id: 'a', created_at: 1, updated_at: 1 });+ const mid = card({ ...fx.PP_NEEDS_YOU, id: 'b', created_at: 2, updated_at: 2 });+ const newest = card({ ...fx.PP_NEEDS_YOU, id: 'c', created_at: 3, updated_at: 3 });+ assert.deepEqual(m.needsYou([older, mid, newest]).map((c) => c.id), ['c'], "Oleks's four items become one");+ const clearAfter = card({ ...fx.PP_CLEAR, id: 'd', created_at: 4, updated_at: 4 });+ assert.deepEqual(m.needsYou([older, mid, newest, clearAfter]), [], 'the bot pushed again and it went clear: nothing waits');+ const otherBot = card({ ...fx.PP_NEEDS_YOU, id: 'e', kwant_id: 'k_iris', created_at: 1, updated_at: 5 });+ const otherFolder = card({ ...fx.PP_NEEDS_YOU, id: 'f', folder: 'site', created_at: 1, updated_at: 6 });+ const otherBranch = card({ ...fx.PP_NEEDS_YOU, id: 'g', branch: 'pixel/x', created_at: 1, updated_at: 7 });+ assert.deepEqual(m.needsYou([newest, otherBot, otherFolder, otherBranch]).map((c) => c.id), ['g', 'f', 'e', 'c'], 'separate targets each keep one, newest update first');+ const sup = card({ ...fx.PP_SUPERSEDED, id: 'h', created_at: 2 });+ assert.deepEqual(m.needsYou([sup, newest]).map((c) => c.id), ['c']);+ const revived = card({ ...fx.PP_NEEDS_YOU, id: 'old', created_at: 1, updated_at: 9 });+ const newer = card({ ...fx.PP_SUPERSEDED, id: 'new', created_at: 5, updated_at: 8, branch: revived.branch, kwant_id: revived.kwant_id, space_id: revived.space_id, folder: revived.folder });+ assert.deepEqual(m.needsYou([revived, newer]).map((c) => c.id), ['old'], 'a revived older card waits even though a newer card exists, when that newer one is superseded');+});++test('needsYou: a card the person just pressed leaves at once, and comes back if the press failed', async () => {+ const c = card(fx.PP_NEEDS_YOU);+ assert.deepEqual(m.needsYou([c], new Set(['pp_needs'])), []);+ const { host, rerender } = await mount(m.PrepushNeedsYou, { cards: [c], names: { k_pixel: 'Pixel' }, onOpen: () => {}, acted: new Set() });+ assert.equal(host.querySelectorAll('[data-needs-prepush-item]').length, 1);+ // The branch tells two items apart, so it goes under the line at every width (Mira FIX 5): one chip, never hidden.+ const branches = host.querySelectorAll('[data-needs-prepush-item] code');+ assert.equal(branches.length, 1, 'no second, clipped chip beside the line');+ const branch = host.querySelector('[data-needs-branch]');+ assert.equal(branch?.textContent, c.branch);+ assert.equal(branch.getAttribute('title'), c.branch, 'the full name on hover when it is truncated');+ assert.doesNotMatch(branch.className, /hidden/);+ await rerender({ cards: [c], names: { k_pixel: 'Pixel' }, onOpen: () => {}, acted: new Set(['pp_needs']) });+ assert.equal(host.querySelector('[data-needs-prepush]'), null, 'gone before the server answers');+ await rerender({ cards: [c], names: { k_pixel: 'Pixel' }, onOpen: () => {}, acted: new Set() });+ assert.equal(host.querySelectorAll('[data-needs-prepush-item]').length, 1, 'back when the call failed');+});++test('usePrepushCards: setActed marks and unmarks a card', async () => {+ let state;+ const api = { list: async () => [card(fx.PP_NEEDS_YOU)], get: async () => card(fx.PP_NEEDS_YOU) };+ const Probe = () => {+ state = m.usePrepushCards('s_demo', true, api);+ return null;+ };+ await mount(Probe, {});+ assert.equal(state.acted.size, 0);+ state.setActed('pp_needs', true);+ await settle();+ assert.ok(state.acted.has('pp_needs'));+ state.setActed('pp_needs', false);+ await settle();+ assert.equal(state.acted.size, 0);+});++test('followUp: the new card the retry led to, by the grant\'s card id, else the newest later card of the same target', () => {+ const r = card(fx.PP_RETRIED_GRANT);+ assert.equal(m.followUp(r, [r]), null);+ assert.equal(m.followUp(r, all('PP_RETRIED_GRANT', 'PP_NEXT_CHECKING', 'PP_NEEDS_YOU')).id, 'pp_next');+ const noId = card({ ...fx.PP_NEXT_CHECKING, grant: null });+ assert.equal(m.followUp(r, [r, noId]).id, 'pp_next', 'old server: matched by branch and time');+ assert.equal(m.followUp(r, [r, card({ ...fx.PP_NEXT_CHECKING, branch: 'other' })]), null, 'another branch is another story');+ const named = card({ ...fx.PP_RETRIED_GRANT, grant: { ...fx.PP_RETRIED_GRANT.grant, next_card_id: 'pp_named' } });+ const newer = card({ ...fx.PP_NEXT_CHECKING, id: 'pp_newer', created_at: fx.PP_NEXT_CHECKING.created_at + 60000 });+ assert.equal(m.followUp(named, [named, newer, card({ ...fx.PP_NEXT_CLEAR, id: 'pp_named' })]).id, 'pp_named', "the server's next_card_id wins");+ assert.equal(m.followUp(r, [r, card({ ...fx.PP_NEXT_CHECKING, grant: { ...fx.PP_NEXT_CHECKING.grant, card_id: 'someone_else' } })]), null);+ assert.equal(m.pressedBefore(card(fx.PP_NEXT_CHECKING), all('PP_RETRIED_GRANT', 'PP_NEXT_CHECKING')).id, 'pp_rg');+ assert.equal(m.pressedBefore(card(fx.PP_CLEAR), [card(fx.PP_CLEAR)]), null);+});++test('story after a retry: fixing → checking the new push → Pushed · HH:MM, or blocked again', () => {+ const r = card(fx.PP_RETRIED_GRANT);+ const at = fx.PP_RETRIED_GRANT.grant.at;+ const s0 = m.storyOf(r, [r], 'Quant', null, at + 1000);+ assert.equal(s0.step, 'fixing');+ assert.equal(s0.lead, 'You asked Quant to fix this and push again. That was your OK: once the checks pass, its next push of pixel/inbox-empty-state goes without asking you.');+ assert.equal(s0.now, 'Quant is fixing it…');+ const s1 = m.storyOf(r, all('PP_RETRIED_GRANT', 'PP_NEXT_CHECKING'), 'Quant', null, at);+ assert.equal(s1.step, 'checking');+ assert.equal(s1.now, "Checking Quant's new push…");+ assert.equal(s1.next.id, 'pp_next');+ assert.equal(m.storyOf(r, all('PP_RETRIED_GRANT', 'PP_NEXT_CLEAR'), 'Quant', null, at).step, 'pushing');+ const s3 = m.storyOf(r, all('PP_RETRIED_GRANT', 'PP_NEXT_PUSHED'), 'Quant', null, at);+ assert.equal(s3.step, 'pushed');+ assert.equal(s3.now, `Pushed · ${HM(fx.PP_NEXT_PUSHED.grant.used_at)}`);+ const s4 = m.storyOf(r, all('PP_RETRIED_GRANT', 'PP_NEXT_BLOCKED'), 'Quant', null, at);+ assert.equal(s4.step, 'blocked');+ assert.equal(s4.now, 'Blocked again: 1 finding. Nothing was pushed.');+ const sx = m.storyOf(r, [r], 'Quant', null, fx.PP_RETRIED_GRANT.grant.expires_at + 1);+ assert.equal(sx.step, 'expired', 'a window that ran out says so');+ assert.equal(sx.lead, 'You asked Quant to fix this and push again.', 'the lead stops promising (Mira FIX 7)');+ assert.doesNotMatch(sx.lead, /without asking/);+ assert.equal(sx.now, "No fixed push came within 2 hours, so your OK ran out. Quant's next push asks you as usual.");+ const replacedNext = card({ ...fx.PP_NEXT_BLOCKED, status: 'superseded', needs_you: false });+ const rp = m.storyOf(r, [r, replacedNext], 'Quant', null, at);+ assert.equal(rp.step, 'replaced');+ assert.equal(rp.now, 'Quant pushed again, so a newer check replaced this one.', 'says what replaced what (Mira FIX 6)');+ const outR = html(m.PrepushCard, { card: r, bot: 'Quant', story: rp, onOpenCard: () => {} });+ assert.match(outR, /See the newer check/);+ const old = card({ ...fx.PP_RETRIED_GRANT, grant: null });+ assert.match(m.storyOf(old, [old], 'Quant').lead, /is checked from try 1\.$/, 'without a grant the card promises nothing it can\'t keep');+ assert.equal(m.storyOf(card(fx.PP_NEEDS_YOU), [], 'Quant'), null, 'only pressed cards tell the story');+});++test('story after Push anyway: pushing → Pushed · HH:MM', () => {+ const o = card(fx.PP_OVERRIDDEN_GRANT);+ const s = m.storyOf(o, [o], 'Quant', null, fx.PP_OVERRIDDEN_GRANT.grant.at);+ assert.equal(s.step, 'pushing');+ assert.equal(s.lead, `You let this push go at ${HM(fx.PP_OVERRIDDEN_GRANT.override.at)} with 1 finding open. That was your OK: Quant's push of this commit goes without asking you.`);+ assert.equal(s.lead, m.overriddenLine(o, 'Quant'), 'one source for the override line');+ assert.equal(s.now, 'Quant can push it now.');+ // Mira FIX 2: an override grant runs out too; the card says so instead of "can push it now" for ever.+ const sx = m.storyOf(o, [o], 'Quant', null, fx.PP_OVERRIDDEN_GRANT.grant.expires_at);+ assert.equal(sx.step, 'expired');+ assert.equal(sx.lead, `You let this push go at ${HM(fx.PP_OVERRIDDEN_GRANT.override.at)} with 1 finding open.`, 'an expired override drops the promise from the lead');+ assert.doesNotMatch(sx.lead, /without asking/);+ const outX = html(m.PrepushCard, { card: o, bot: 'Quant', story: sx });+ assert.doesNotMatch(outX, /without asking/, 'the expired override card promises nothing anywhere');+ assert.equal(sx.now, "Quant didn't push within 2 hours, so your OK ran out. Its push asks you as usual.");+ const p = card(fx.PP_PUSHED);+ const sp = m.storyOf(p, [p], 'Quant');+ assert.equal(sp.step, 'pushed');+ assert.equal(sp.now, `Pushed · ${HM(fx.PP_PUSHED.grant.used_at)}`);+});++test('a floor or payment approval the push still needs gets one line with a link; an ordinary approval does not', () => {+ const r = card(fx.PP_RETRIED_GRANT);+ const after = new Date(fx.PP_RETRIED_GRANT.grant.at + 60_000).toISOString();+ const floor = { id: 'ap1', tool_name: 'Bash', kwant_id: 'k_pixel', asked_at: after, details: { prod_floor: { kind: 'push_main', why: 'This push goes to main, a watched branch.' } } };+ const pay = { id: 'ap2', tool_name: 'stripe', kwant_id: 'k_pixel', asked_at: after, details: { payment_reason: 'It charges a card' } };+ const plain = { id: 'ap3', tool_name: 'Bash', kwant_id: 'k_pixel', asked_at: after, details: { command: 'git push' } };+ const otherBot = { ...floor, id: 'ap4', kwant_id: 'k_iris' };+ const before = { ...floor, id: 'ap5', asked_at: new Date(fx.PP_RETRIED_GRANT.grant.at - 600_000).toISOString() };+ assert.deepEqual(m.pushApproval(r, [plain, otherBot, before, floor]), { id: 'ap1', reason: 'This push goes to main, a watched branch' });+ assert.deepEqual(m.pushApproval(r, [pay]), { id: 'ap2', reason: 'It charges a card' });+ const bare = { ...floor, id: 'ap6', details: { prod_floor: { kind: 'push_main' } } };+ assert.deepEqual(m.pushApproval(r, [bare]), { id: 'ap6', reason: null }, 'no made-up reason');+ assert.equal(m.pushApproval(r, [plain]), null);+ assert.equal(m.pushApproval(card(fx.PP_NEEDS_YOU), [floor]), null, 'only after a press');+ assert.equal(m.pushApproval(card(fx.PP_PUSHED), [floor]), null, 'a push that went needs nothing');+ const s = m.storyOf(r, all('PP_RETRIED_GRANT', 'PP_NEXT_CLEAR'), 'Quant', { id: 'ap1', reason: 'This push goes to main' }, fx.PP_RETRIED_GRANT.grant.at + 600_000);+ assert.equal(s.lead, 'You asked Quant to fix this and push again.', 'an asking push promises nothing in the lead (round 3)');+ assert.equal(s.step, 'asks');+ assert.equal(s.now, "Quant's push still needs your OK. This push goes to main. Pushes like this always ask, every time.");+ assert.equal(m.asksLine('Quant', { id: 'x', reason: null }), "Quant's push still needs your OK. Pushes like this always ask, every time.");+});++test('the retried card shows the new state at once and links to the new card', async () => {+ const r = card(fx.PP_RETRIED_GRANT);+ const out0 = html(m.PrepushCard, { card: r, bot: 'Quant', story: m.storyOf(r, [r], 'Quant', null, fx.PP_RETRIED_GRANT.grant.at) });+ assert.match(out0, /data-prepush-phase="RT"/);+ assert.match(out0, /You asked Quant to fix this and push again\. That was your OK: once the checks pass, its next push of <code[^>]*>pixel\/inbox-empty-state<\/code> goes without asking you\./);+ assert.match(out0, /data-story="fixing"/);+ assert.match(out0, /role="status"[^>]*>.*Quant is fixing it…/);+ const opened = [];+ const cards = all('PP_RETRIED_GRANT', 'PP_NEXT_BLOCKED');+ const { host } = await mount(m.PrepushCard, { card: r, bot: 'Quant', story: m.storyOf(r, cards, 'Quant'), onOpenCard: (id) => opened.push(id) });+ assert.match(text(host), /Blocked again: 1 finding\. Nothing was pushed\./);+ await click(button(host, 'See what it found'));+ assert.deepEqual(opened, ['pp_next']);+});++test('the story line follows the new push live, and a floor approval line opens that approval', async () => {+ const r = card(fx.PP_RETRIED_GRANT);+ const at = fx.PP_RETRIED_GRANT.grant.at;+ const props = (cards, approval = null) => ({ card: r, bot: 'Quant', story: m.storyOf(r, cards, 'Quant', approval, at), onOpenCard: () => {}, onOpenApproval: (id) => openedA.push(id) });+ const openedA = [];+ const { host, rerender } = await mount(m.PrepushCard, props([r]));+ const now = () => text(host.querySelector('[data-story-now]'));+ assert.equal(now(), 'Quant is fixing it…');+ await rerender(props(all('PP_RETRIED_GRANT', 'PP_NEXT_CHECKING')));+ assert.equal(now(), "Checking Quant's new push…");+ assert.ok(host.querySelector('[data-story-next="pp_next"]'), 'links to the new card');+ await rerender(props(all('PP_RETRIED_GRANT', 'PP_NEXT_CLEAR'), { id: 'ap1', reason: 'This push goes to main' }));+ const line = host.querySelector('[data-story-approval="ap1"]');+ assert.ok(line);+ assert.equal(text(line).replace(/Open it.*$/, '').trim(), "Quant's push still needs your OK. This push goes to main. Pushes like this always ask, every time.");+ assert.equal(line.querySelector('.dv-led')?.getAttribute('data-s'), 'warn', 'amber light in the amber box, not the running violet');+ // Said once: the amber line is the only status line, not a second "needs your OK." above it.+ assert.equal((text(host).match(/needs your OK/g) ?? []).length, 1);+ assert.equal(host.querySelectorAll('[role="status"]').length, 1);+ assert.equal(line.getAttribute('role'), 'status');+ await click(button(line, 'Open it'));+ assert.deepEqual(openedA, ['ap1']);+ await rerender(props(all('PP_RETRIED_GRANT', 'PP_NEXT_PUSHED')));+ assert.equal(now(), `Pushed · ${HM(fx.PP_NEXT_PUSHED.grant.used_at)}`);+ assert.equal(host.querySelector('[data-story-approval]'), null);+});++test('the new card links back to the request, and once its push went it folds to "Pushed · HH:MM"', async () => {+ const cards = all('PP_RETRIED_GRANT', 'PP_NEXT_CHECKING');+ const next = cards[1];+ const opened = [];+ const { host } = await mount(m.PrepushCard, { card: next, bot: 'Quant', after: cards[0], onOpenCard: (id) => opened.push(id) });+ assert.match(text(host.querySelector('[data-after-retry="pp_rg"]')), new RegExp(`After you asked for a fix at ${HM(fx.PP_RETRIED_GRANT.grant.at)}\\.`));+ await click(button(host, 'See your request'));+ assert.deepEqual(opened, ['pp_rg']);+ const out = html(m.PrepushCard, { card: card(fx.PP_NEXT_PUSHED), bot: 'Quant', after: cards[0] });+ assert.match(out, /data-prepush-phase="P2b"/);+ assert.match(out, new RegExp(`Pushed · ${HM(fx.PP_NEXT_PUSHED.grant.used_at)}`));+ assert.match(out, /· your retry was the OK, so it didn't ask again\.|· your retry was the OK, so it didn't ask again\./);+ assert.doesNotMatch(out, /no second OK/);+});++test('Push anyway: the card follows its one push to "Pushed · HH:MM"', () => {+ const o = card(fx.PP_OVERRIDDEN_GRANT);+ const out = html(m.PrepushCard, { card: o, bot: 'Quant', story: m.storyOf(o, [o], 'Quant', null, fx.PP_OVERRIDDEN_GRANT.grant.at) });+ assert.match(out, /data-story="pushing"/);+ assert.match(out, /Quant can push it now\./);+ const p = card(fx.PP_PUSHED);+ const outP = html(m.PrepushCard, { card: p, bot: 'Quant', story: m.storyOf(p, [p], 'Quant') });+ assert.match(outP, /data-story="pushed"/);+ assert.match(outP, new RegExp(`Pushed · ${HM(fx.PP_PUSHED.grant.used_at)}`));+ assert.doesNotMatch(outP, /<button[^>]*>(Push anyway…|Ask Quant)/);+});++test('PrepushThread wires the story: the retried card follows the new card from the whole list', async () => {+ // The thread reads the real clock, so keep the retry's window open for this test (round 3 expires late pushes).+ const open = card({ ...fx.PP_RETRIED_GRANT, grant: { ...fx.PP_RETRIED_GRANT.grant, expires_at: Date.now() + 3_600_000 } });+ const every = [open, card(fx.PP_NEXT_CHECKING)];+ const { host } = await mount(m.PrepushThread, { cards: every, all: every, bot: 'Quant', live: new Set(), approvals: [] });+ assert.equal(text(host.querySelector('#prepush-pp_rg [data-story-now]')), "Checking Quant's new push…");+ assert.ok(host.querySelector('#prepush-pp_next [data-after-retry="pp_rg"]'));+});++test('the chat messages to the bot say its next push needs no second OK (Mira FIX 8)', () => {+ const c = card(fx.PP_NEEDS_YOU);+ assert.equal(+ m.retryMessage(c),+ `Fix what the pre-push check found on ${c.branch}, commit, and push again. I've given my OK for that push, so once the checks pass it goes without asking me.`,+ );+ assert.equal(+ m.overrideMessage(c),+ `I let your push of ${c.branch} go anyway, for this commit only. That was my OK, so run the same push again without asking me.`,+ );+});++test('the new card after an override push names Push anyway as the OK (Mira FIX 4)', () => {+ const p = card({ ...fx.PP_NEXT_PUSHED, grant: { ...fx.PP_NEXT_PUSHED.grant, kind: 'override' } });+ const out = html(m.PrepushCard, { card: p, bot: 'Quant' });+ assert.match(out, /your Push anyway was the OK, so it didn('|')t ask again\./);+});++test('a long story line keeps its light beside the text, so it never sits alone on a row on a phone', () => {+ const r = card(fx.PP_RETRIED_GRANT);+ const out = html(m.PrepushCard, { card: r, bot: 'Quant', story: m.storyOf(r, [r], 'Quant', null, fx.PP_RETRIED_GRANT.grant.expires_at + 1) });+ assert.match(out, /<span data-story-text="true" class="flex min-w-0 items-start gap-2"><span aria-hidden="true" data-s="off" class="dv-led mt-\[5px\] shrink-0 dv-led-still"><\/span><span data-story-now/);+});++// ---------------------------------------------------------------------------------------------+// Round 3 (Rigel QA, Nov 13): floor after a retry, a late push after the window, the replaced chain.++const floorAfter = (c, extra = 60_000) => ({+ id: 'ap_floor', tool_name: 'Bash', kwant_id: c.kwant_id, asked_at: new Date(c.grant.at + extra).toISOString(),+ details: { command: 'git push origin HEAD:main', prod_floor: { kind: 'push_main', why: 'git push sends new commits to main' } },+});++test('round 3: a production-floor push after a retry makes no card, and the retried card shows the amber line with Open it', async () => {+ const r = card(fx.PP_RETRIED_GRANT);+ const at = fx.PP_RETRIED_GRANT.grant.at + 120_000;+ const ap = m.pushApproval(r, [floorAfter(r)]);+ assert.deepEqual(ap, { id: 'ap_floor', reason: 'git push sends new commits to main' });+ const s = m.storyOf(r, [r], 'Quant', ap, at);+ assert.equal(s.step, 'asks', 'not "fixing": the floor approval is the follow-up');+ assert.equal(s.now, "Quant's push still needs your OK. Git push sends new commits to main. Pushes like this always ask, every time.");+ assert.equal(s.lead, 'You asked Quant to fix this and push again.');+ assert.doesNotMatch(s.lead, /without asking/);+ const sc = m.storyOf(r, all('PP_RETRIED_GRANT', 'PP_NEXT_CHECKING'), 'Quant', ap, at);+ assert.equal(sc.step, 'asks', 'a check still running does not hide the floor approval');+ assert.equal(m.storyOf(r, [r], 'Quant', null, at).step, 'fixing', 'no approval: still fixing');+ const opened = [];+ const { host } = await mount(m.PrepushCard, { card: r, bot: 'Quant', story: s, onOpenCard: () => {}, onOpenApproval: (id) => opened.push(id) });+ assert.doesNotMatch(text(host), /without asking/);+ assert.equal(host.querySelector('[data-story="asks"] .dv-led')?.getAttribute('data-s'), 'warn', 'amber light, not a spinner');+ await click(button(host, 'Open it'));+ assert.deepEqual(opened, ['ap_floor']);+ // An override with a floor approval waiting: the lead drops its promise too.+ const o = card(fx.PP_OVERRIDDEN_GRANT);+ const so = m.storyOf(o, [o], 'Quant', ap, fx.PP_OVERRIDDEN_GRANT.grant.at);+ assert.equal(so.step, 'asks');+ assert.equal(so.lead, `You let this push go at ${HM(fx.PP_OVERRIDDEN_GRANT.override.at)} with 1 finding open.`);+});++test('round 3: the asks line capitalises the reason it is given', () => {+ assert.equal(m.asksLine('Quant', { id: 'x', reason: 'a stripe CLI command that changes something' }),+ "Quant's push still needs your OK. A stripe CLI command that changes something. Pushes like this always ask, every time.");+});++test('round 3: an unused grant past its window is expired even when a later push made a card, and links the approval', async () => {+ const r = card(fx.PP_RETRIED_GRANT);+ const late = fx.PP_RETRIED_GRANT.grant.expires_at + 60_000;+ for (const k of ['PP_NEXT_CLEAR', 'PP_NEXT_CHECKING']) {+ const s = m.storyOf(r, all('PP_RETRIED_GRANT', k), 'Quant', null, late);+ assert.equal(s.step, 'expired', `${k} after the window: not "pushing"`);+ assert.equal(s.lead, 'You asked Quant to fix this and push again.');+ assert.doesNotMatch(s.lead, /without asking/);+ assert.equal(s.now, "No fixed push came within 2 hours, so your OK ran out. Quant's next push asks you as usual.");+ }+ assert.equal(m.storyOf(r, all('PP_RETRIED_GRANT', 'PP_NEXT_BLOCKED'), 'Quant', null, late).step, 'blocked', 'blocked again still says so');+ assert.equal(m.storyOf(r, all('PP_RETRIED_GRANT', 'PP_NEXT_PUSHED'), 'Quant', null, late).step, 'pushed', 'a used grant never expires');+ const ap = m.pushApproval(r, [floorAfter(r, 125 * 60_000)]);+ const s = m.storyOf(r, all('PP_RETRIED_GRANT', 'PP_NEXT_CLEAR'), 'Quant', ap, late);+ assert.equal(s.step, 'expired');+ assert.equal(s.approval.id, 'ap_floor');+ const opened = [];+ const { host } = await mount(m.PrepushCard, { card: r, bot: 'Quant', story: s, onOpenCard: () => {}, onOpenApproval: (id) => opened.push(id) });+ assert.match(text(host), /your OK ran out/);+ assert.doesNotMatch(text(host), /without asking|is pushing/);+ await click(button(host, 'Open it'));+ assert.deepEqual(opened, ['ap_floor']);+});++test('round 3: "See the newer check" follows superseded_by to the live card, at most 10 hops, and stops on a cycle', () => {+ const r = card({ ...fx.PP_RETRIED_GRANT, grant: { ...fx.PP_RETRIED_GRANT.grant, next_card_id: 'pp_next' } });+ const mid = card({ ...fx.PP_NEXT_BLOCKED, status: 'superseded', needs_you: false, superseded_by: 'pp_live' });+ const live = card({ ...fx.PP_NEXT_BLOCKED, id: 'pp_live', created_at: (fx.PP_NEXT_BLOCKED.created_at ?? 0) + 1 });+ const s = m.storyOf(r, [r, mid, live], 'Quant', null, fx.PP_RETRIED_GRANT.grant.at + 600_000);+ assert.equal(s.step, 'replaced');+ assert.equal(s.next.id, 'pp_live', 'the link lands on the live card, not on one that is itself replaced');+ const sup = (id, to) => card({ ...fx.PP_SUPERSEDED, id, superseded_by: to });+ const a = sup('a', 'b');+ assert.equal(m.liveCard(a, [a, sup('b', 'c'), sup('c', 'a')]).id, 'c', 'a cycle stops at the last new card');+ const chain = Array.from({ length: 15 }, (_, i) => sup(`n${i}`, `n${i + 1}`));+ assert.equal(m.liveCard(chain[0], chain).id, 'n10', 'at most 10 hops');+ assert.equal(m.liveCard(sup('x', 'gone'), []).id, 'x', 'a missing card keeps the last one found');+});++test('round 3: in the thread, a "newer" link lands on the live card at the end of the chain', async () => {+ const r = card({ ...fx.PP_RETRIED_GRANT, grant: { ...fx.PP_RETRIED_GRANT.grant, next_card_id: 'pp_next', expires_at: Date.now() + 3_600_000 } });+ const mid = card({ ...fx.PP_NEXT_BLOCKED, status: 'superseded', needs_you: false, superseded_by: 'pp_mid' });+ const mid2 = card({ ...fx.PP_NEXT_BLOCKED, id: 'pp_mid', status: 'superseded', needs_you: false, superseded_by: 'pp_live', created_at: (fx.PP_NEXT_BLOCKED.created_at ?? 0) + 1 });+ const live = card({ ...fx.PP_NEXT_BLOCKED, id: 'pp_live', created_at: (fx.PP_NEXT_BLOCKED.created_at ?? 0) + 2 });+ const every = [r, mid, mid2, live];+ const { host } = await mount(m.PrepushThread, { cards: every, all: every, bot: 'Quant', live: new Set(), approvals: [] });+ await click(button(host.querySelector('#prepush-pp_rg'), 'See the newer check'));+ assert.ok(host.querySelector('#prepush-pp_live').classList.contains('kw-prepush-flash'), 'the live card rings');+ assert.ok(!host.querySelector('#prepush-pp_mid').classList.contains('kw-prepush-flash'), 'not a card that is itself replaced');+ host.querySelector('#prepush-pp_live').classList.remove('kw-prepush-flash');+ const ss = host.querySelector('#prepush-pp_next [data-superseded-by]');+ if (ss) { await click(ss); assert.ok(host.querySelector('#prepush-pp_live').classList.contains('kw-prepush-flash'), 'the Replaced card\'s own link too'); }+});diff --git a/frontend/tests/prepushPointers.test.mjs b/frontend/tests/prepushPointers.test.mjsindex ecd5a4b2..5ce128d6 100644--- a/frontend/tests/prepushPointers.test.mjs+++ b/frontend/tests/prepushPointers.test.mjs@@ -113,7 +113,8 @@ test("each phase's copy matches Mira's table", () => {assert.equal(T(fx.PP_CLEAR), 'Cleared: Ann can push qa-skip · 5 checks passed');assert.equal(T(fx.PP_OVERRIDDEN), "You let Ann's push of qa-skip go anyway");assert.equal(T(fx.PP_NO_CHANGE), 'Nothing to push: qa-skip has no new commits');- assert.equal(T(fx.PP_CHECKING, { status: 'pushed' }), "Ann has a push check this version can't show · update the app to see where it is");+ assert.equal(T(fx.PP_OVERRIDDEN, { status: 'pushed' }), "You let Ann's push of qa-skip go anyway", '0.9.7: pushed is known now');+ assert.equal(T(fx.PP_CHECKING, { status: 'merged_later' }), "Ann has a push check this version can't show · update the app to see where it is");const two = card({ ...fx.PP_BLOCKED, branch: 'qa-skip', blockers: [fx.PP_BLOCKED.blockers[0], { ...fx.PP_BLOCKED.blockers[0], id: 'f2' }] });assert.equal(m.openCount(two), 2);assert.equal(m.pointerText(two, 'Ann'), 'Ann is fixing 2 findings before pushing qa-skip · Try 1 of 2');