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
Fix it: Send to… picker and Goes to line (frontend for #609) (#615)
Oleksandr Ivanchenkof5462a14698b
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex 05c1cd50..9f3ba23b 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -4404,7 +4404,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({/>);const attentionRankOf = new Map((attention ?? []).map((a) => [a.kwant.id, a.rank]));- const devDeskPage = <DevDeskView key={space.id} spaceId={space.id} spaceName={space.name} onBack={backToList} onOpenLooseEnds={connectDevGitHub} teams={devTeamRefs(teams, kwants)} bots={kwants.map((k) => ({ id: k.id, name: k.name, role: k.title, rank: attentionRankOf.get(k.id) }))} defaultBotId={!isChannel ? selectedId : null} onOpenChat={(id, thread) => { if (thread) { openThread(id, thread); return; } if (!openTarget({ channel_id: null, kwant_id: id })) pushToast('That bot no longer exists.'); }} />;+ const devDeskPage = <DevDeskView key={space.id} spaceId={space.id} spaceName={space.name} onBack={backToList} onOpenLooseEnds={connectDevGitHub} teams={devTeamRefs(teams, kwants)} bots={kwants.map((k) => ({ id: k.id, name: k.name, role: k.title, rank: attentionRankOf.get(k.id) }))} defaultBotId={!isChannel ? selectedId : null} onOpenTask={missionBoard ? (id) => { setPendingTaskId(id); showPage('board'); } : undefined} onOpenChat={(id, thread) => { if (thread) { openThread(id, thread); return; } if (!openTarget({ channel_id: null, kwant_id: id })) pushToast('That bot no longer exists.'); }} />;const mainPane = needsSetup ? setupChecklist : page === 'parallel' ? parallel : page === 'board' && missionBoard ? missionsPage : page === 'dev' && devOn ? devDeskPage : page === 'jar' ? jarPage : page === 'inbox' ? inbox : !loaded ? (<main className="flex-1 flex items-center justify-center text-xs text-zinc-500"><Loader2 size={14} className="mr-2 animate-spin motion-reduce:animate-none" aria-hidden="true" /> Opening {space.name}…diff --git a/frontend/src/components/DevDesk.tsx b/frontend/src/components/DevDesk.tsxindex d80215cd..4093fbef 100644--- a/frontend/src/components/DevDesk.tsx+++ b/frontend/src/components/DevDesk.tsx@@ -19,7 +19,15 @@ import { personFetch } from '../auth';import { WorktreesPanel, useWorktrees } from './dev/WorktreesTab';import { worktreeCount, worktreeStore } from '../dev/worktrees';import { usePhoneLayout } from '../usePhoneLayout';-+import { parseRecipients, type DevRecipients } from '../dev/types';++/** Fix it "Send to…" (#609): the card's recipients. Module-level, so each card fetches once. */+const RECIPIENTS = (cardId: string): Promise<DevRecipients> =>+ devApi.recipients(cardId).then((v) => {+ const r = parseRecipients(v);+ if (!r) throw new Error('bad recipients answer');+ return r;+ });/** 0.9.0 G1: the review cards' line notes, over the person's session. */const LINE_NOTES = lineNotesApi(fetchCaller((input, init) => personFetch(input as string, init)));@@ -223,9 +231,11 @@ export interface DevDeskViewProps {onOpenChat?: (botId: string, threadId?: string | null) => void;/** 0.9.0 H1: the create dialog's default bot. */defaultBotId?: string | null;+ /** Fix it "Send to…": "Open task ›" on a sent finding opens it on the board. */+ onOpenTask?: (taskId: string) => void;}-export const DevDeskView: React.FC<DevDeskViewProps> = ({ spaceId, onBack, onSaveToNotion, initialTab = 'landed', now, onOpenLooseEnds, teams, bots, onOpenChat, defaultBotId }) => {+export const DevDeskView: React.FC<DevDeskViewProps> = ({ spaceId, onBack, onSaveToNotion, initialTab = 'landed', now, onOpenLooseEnds, teams, bots, onOpenChat, defaultBotId, onOpenTask }) => {const dev = useDevMode(spaceId);const connect = (anchor?: HTMLElement) => (onOpenLooseEnds ? onOpenLooseEnds(anchor) : openGitHubConnect({ space: spaceId, anchor }));// 0.7.2: with several repos, both lists filter by one (All · app · site) through `?repo=`.@@ -595,7 +605,7 @@ export const DevDeskView: React.FC<DevDeskViewProps> = ({ spaceId, onBack, onSav) : reviews.length ? (<>{freshLine && <FreshLine text={freshLine} />}- {reviews.map((c) => <ReviewCard key={c.id} card={c} onFinding={onFinding} onPost={onPost} forge={dev?.forge ?? null} forgeLogin={dev?.forge_login ?? null} gitOnly={gitOnly(typeof c.repo === 'string' ? c.repo : null)} now={now} repoLabel={repoLabel} jiraOrigins={jiraOrigins} lineNotes={LINE_NOTES} onOpenChat={onOpenChat} />)}+ {reviews.map((c) => <ReviewCard key={c.id} card={c} onFinding={onFinding} onPost={onPost} forge={dev?.forge ?? null} forgeLogin={dev?.forge_login ?? null} gitOnly={gitOnly(typeof c.repo === 'string' ? c.repo : null)} now={now} repoLabel={repoLabel} jiraOrigins={jiraOrigins} lineNotes={LINE_NOTES} onOpenChat={onOpenChat} recipients={RECIPIENTS} onOpenTask={onOpenTask} />)}</>) : (desk.reviews && (diff --git a/frontend/src/components/DevDeskSlots.tsx b/frontend/src/components/DevDeskSlots.tsxindex 2007130c..36f1b121 100644--- a/frontend/src/components/DevDeskSlots.tsx+++ b/frontend/src/components/DevDeskSlots.tsx@@ -59,6 +59,9 @@ export interface ReviewCardProps {lineNotes?: import('../dev/lineNotesApi').LineNotesApi;/** 0.9.0 G1: "Open {bot}'s chat" after a send. */onOpenChat?: (botId: string) => void;+ /** Fix it "Send to…" (#609): the card's recipients, and "Open task ›" after a send. */+ recipients?: (cardId: string) => Promise<import('../dev/types').DevRecipients>;+ onOpenTask?: (taskId: string) => void;}export interface ReleaseNotesSheetProps {@@ -92,7 +95,7 @@ export const LandedList: React.FC<LandedListProps> = ({ cards, reviews, now, onO);};-export const ReviewCard: React.FC<ReviewCardProps> = ({ card, onFinding, onPost, forge, forgeLogin, sample, now, repoLabel, gitOnly = false, jiraOrigins, lineNotes, onOpenChat }) => {+export const ReviewCard: React.FC<ReviewCardProps> = ({ card, onFinding, onPost, forge, forgeLogin, sample, now, repoLabel, gitOnly = false, jiraOrigins, lineNotes, onOpenChat, recipients, onOpenTask }) => {const parsed = useMemo(() => parseReview(card), [card]);if (!parsed) return <CardFallback raw={card} />;const send = async (cardId: string, findingId: string, action: FindingAction): Promise<Review> => {@@ -107,7 +110,7 @@ export const ReviewCard: React.FC<ReviewCardProps> = ({ card, onFinding, onPost,return next;}: undefined;- return <IrisReviewCard card={parsed} onFinding={send} onPost={post} forge={gitOnly ? null : forge} forgeLogin={forgeLogin} sample={sample} now={now} repoLabel={repoLabel} jiraOrigins={jiraOrigins} lineNotes={lineNotes} onOpenChat={onOpenChat} />;+ return <IrisReviewCard card={parsed} onFinding={send} onPost={post} forge={gitOnly ? null : forge} forgeLogin={forgeLogin} sample={sample} now={now} repoLabel={repoLabel} jiraOrigins={jiraOrigins} lineNotes={lineNotes} onOpenChat={onOpenChat} recipients={recipients} onOpenTask={onOpenTask} />;};export const ReleaseNotesSheet: React.FC<ReleaseNotesSheetProps> = ({ card, onSaveToNotion, onDiscard, onClose }) => {diff --git a/frontend/src/components/dev/LineNotes.tsx b/frontend/src/components/dev/LineNotes.tsxindex c85af1bf..02fc340e 100644--- a/frontend/src/components/dev/LineNotes.tsx+++ b/frontend/src/components/dev/LineNotes.tsx@@ -49,6 +49,9 @@ import {summaryLine,} from '../../dev/lineNotes';import { LineNotesError, newSendId, type LineNotesApi } from '../../dev/lineNotesApi';+import { BarTrigger, type RecipientsLoad, type SendTo } from './RecipientPicker';+import { badRecipientNotes, noDefaultNotes, target, toFor } from '../../dev/recipients';+import type { RecipientBot } from '../../dev/types';/** The app re-sends the `dev_card` SSE as this window event (DevDesk.tsx DEV_CARD_EVENT). */const DEV_CARD_EVENT = 'kwant:dev-card';@@ -75,6 +78,8 @@ export interface ChangesSectionProps {defaultOpen?: boolean;/** Tests: force the phone layout (default: the 640 px breakpoint). */phone?: boolean;+ /** Fix it "Send to…" (#609): the card's list and pick; notes go to the same bot as Fix it. */+ sendTo?: SendTo | null;}type Load = { s: 'idle' } | { s: 'loading' } | { s: 'error' } | { s: 'ready'; changes: Changes };@@ -96,13 +101,15 @@ type Bar =| { s: 'confirm' }| { s: 'sending' }| { s: 'sent'; n: number; bot: string; botId: string | null; at: string | null }- | { s: 'failed' };+ | { s: 'failed' }+ /** §5: the picked bot left the space; the notes stay as drafts. */+ | { s: 'bad'; name: string | null };const marker = (k: FlatLine['line']['kind']) => (k === 'add' ? '+' : k === 'del' ? '-' : ' ');const quote = (lines: FlatLine[], a: number, b: number): DiffLine[] => lines.slice(a, b + 1).map((x) => x.line);const base = (p: string) => p.split('/').pop() || p;-export const ChangesSection: React.FC<ChangesSectionProps> = ({ cardId, api, stat, notesCount = null, headSha = null, prUrl = null, onOpenChat, defaultOpen = false, phone: forcePhone }) => {+export const ChangesSection: React.FC<ChangesSectionProps> = ({ cardId, api, stat, notesCount = null, headSha = null, prUrl = null, onOpenChat, defaultOpen = false, phone: forcePhone, sendTo = null }) => {const media = useMedia('(max-width: 639px)');const phone = forcePhone ?? media;const ids = useId();@@ -124,8 +131,11 @@ export const ChangesSection: React.FC<ChangesSectionProps> = ({ cardId, api, staconst loadedHead = useRef<string | null>(null);const changes = load.s === 'ready' ? load.changes : null;- const bot = changes?.author_bot?.name ?? null;- const canNote = !!changes && !!changes.author_bot && changes.pr_state === 'open';+ // Notes go where Fix it goes: the card's pick, else the server's default, else the PR's author bot.+ const list = sendTo?.load.s === 'ready' ? sendTo.load.r : null;+ const to: RecipientBot | null = target(list, sendTo?.pick ?? null) ?? changes?.author_bot ?? null;+ const bot = to?.name ?? null;+ const canNote = !!changes && changes.pr_state === 'open' && (!!changes.author_bot || (list?.bots.length ?? 0) > 0);const drafts = useMemo(() => (notes ?? []).filter((n) => n.state === 'draft'), [notes]);// -------------------------------------------------------------------------------------------------@@ -298,21 +308,39 @@ export const ChangesSection: React.FC<ChangesSectionProps> = ({ cardId, api, sta// -------------------------------------------------------------------------------------------------// Sending- const send = async (only?: string[]) => {- if (!changes?.author_bot || bar.s === 'sending') return;+ const send = async (only?: string[], el?: HTMLElement | null, chosen?: RecipientBot) => {+ if (!changes || bar.s === 'sending') return;const n = only ? only.length : drafts.length;if (n === 0 || n > MAX_SEND) return;+ // §7: no default and no pick: "Send N notes…" opens the picker and sends after the pick.+ const goTo = chosen ?? to;+ if (!goTo) {+ if (sendTo && el) sendTo.open(el, (b) => void send(only, null, b));+ return;+ }+ // `to` with a pick (or the pick just made); once the picker has been shown on this card, always (N1).+ const picked = chosen ?? sendTo?.pick ?? null;+ const toId = toFor(list, picked, !!chosen || !!sendTo?.pinned);sendId.current ??= newSendId();setBar({ s: 'sending' });try {- const r = await api.send(cardId, sendId.current, only);+ const r = await api.send(cardId, sendId.current, only, toId);sendId.current = null;const back = new Map(r.notes.map((x) => [x.id, x]));setNotes((all) => (all ?? []).map((x) => back.get(x.id) ?? x));- const name = r.kwant_name ?? changes.author_bot.name;- setBar({ s: 'sent', n: r.sent, bot: name, botId: r.kwant_id ?? changes.author_bot.id, at: clock(r.sent_at) });+ const name = r.kwant_name ?? goTo.name;+ setBar({ s: 'sent', n: r.sent, bot: name, botId: r.kwant_id ?? goTo.id, at: clock(r.sent_at) });setSaid(`Sent ${notesWord(r.sent)} to ${name}.`);- } catch {+ } catch (e) {+ if (e instanceof LineNotesError && e.code === 'bad_recipient') {+ // Nothing went out: a fresh send id for the next try, the list refetched, the pick dropped.+ sendId.current = null;+ const name = picked?.name ?? null;+ setBar({ s: 'bad', name });+ setSaid(badRecipientNotes(name));+ sendTo?.reset();+ return;+ }// The send id is kept, so Try again can't post the batch twice (ask 6).setBar({ s: 'failed' });setSaid(SEND_FAILED);@@ -335,7 +363,7 @@ export const ChangesSection: React.FC<ChangesSectionProps> = ({ cardId, api, sta// -------------------------------------------------------------------------------------------------const draftCount = notes ? drafts.length : notesCount?.drafts ?? 0;- const showBar = canNote && (drafts.length > 0 || bar.s === 'sent' || bar.s === 'failed');+ const showBar = canNote && (drafts.length > 0 || bar.s === 'sent' || bar.s === 'failed' || bar.s === 'bad');return (<section data-line-notes={cardId} aria-label="Changes" className="relative mt-4">@@ -397,7 +425,12 @@ export const ChangesSection: React.FC<ChangesSectionProps> = ({ cardId, api, sta)}{open && changes && (<div className="mt-2">- {!changes.author_bot && (+ {!changes.author_bot && list && list.bots.length > 0 && !list.default && changes.pr_state === 'open' && (+ <Banner>+ <span data-ln-no-default>{noDefaultNotes(changes.author_login)}</span>+ </Banner>+ )}+ {!changes.author_bot && !(list && list.bots.length > 0) && (<Banner>{notBotLine(changes.author_login).split(changes.author_login ?? '\u0000').map((part, i, all) => (<React.Fragment key={i}>@@ -434,7 +467,7 @@ export const ChangesSection: React.FC<ChangesSectionProps> = ({ cardId, api, stasubmit={() => void submit()}onEdit={startEditing}onDelete={(n) => void remove(n)}- onSendOne={(n) => void send([n.id])}+ onSendOne={(n, el) => void send([n.id], el)}folded={folded}toggleFold={(id) =>setFolded((s) => {@@ -505,9 +538,11 @@ export const ChangesSection: React.FC<ChangesSectionProps> = ({ cardId, api, stabar={bar}setBar={setBar}drafts={drafts.length}- bot={bot ?? ''}+ bot={bot}phone={phone}- onSend={() => void send()}+ sendTo={sendTo}+ fallback={changes?.author_bot?.name ?? null}+ onSend={(el) => void send(undefined, el)}onDiscard={() => void discardAll()}onOpenChat={onOpenChat}/>@@ -553,7 +588,7 @@ interface FileBlockProps {submit: () => void;onEdit: (n: Note) => void;onDelete: (n: Note) => void;- onSendOne: (n: Note) => void;+ onSendOne: (n: Note, el: HTMLElement) => void;folded: Set<string>;toggleFold: (id: string) => void;}@@ -691,7 +726,7 @@ const FileBlock: React.FC<FileBlockProps> = (p) => {onFold={() => p.toggleFold(note.id)}onEdit={() => p.onEdit(note)}onDelete={() => p.onDelete(note)}- onSendOne={() => p.onSendOne(note)}+ onSendOne={(el) => p.onSendOne(note, el)}movedTo={note.moved && note.at_head ? note.at_head.end.line : null}/>);@@ -962,7 +997,7 @@ interface NoteBoxProps {onFold: () => void;onEdit: () => void;onDelete: () => void;- onSendOne: () => void;+ onSendOne: (el: HTMLElement) => void;movedTo: number | null;}@@ -1044,7 +1079,7 @@ const NoteBox: React.FC<NoteBoxProps> = ({ note, bot, editable, folded, onFold,{goneLine(note.seen_sha)}{editable && (<>- <button type="button" onClick={onSendOne} className={`rounded font-medium text-violet-300 hover:text-violet-200 max-sm:min-h-11 ${RING}`}>+ <button type="button" onClick={(e) => onSendOne(e.currentTarget)} className={`rounded font-medium text-violet-300 hover:text-violet-200 max-sm:min-h-11 ${RING}`}>Send it anyway</button><span aria-hidden="true">·</span>@@ -1114,7 +1149,7 @@ const Composer: React.FC<ComposerProps> = ({ writing: w, setWriting, bot, onCancreturn (<div data-ln-writing className="my-1.5 ml-2.5 mr-2.5 rounded-[10px] border border-violet-500 bg-surface-raised px-3 py-2.5 font-sans ring-[3px] ring-violet-500/15 sm:ml-16"><p id={label} className="text-[11.5px] text-zinc-400">- <span className="font-semibold text-zinc-100">{w.editing ? 'Edit note' : `Note for ${bot}`}</span> {lineWords(w.start, w.end)}+ <span className="font-semibold text-zinc-100">{w.editing ? 'Edit note' : bot ? `Note for ${bot}` : 'Note'}</span> {lineWords(w.start, w.end)}</p><textareadata-ln-text@@ -1172,7 +1207,7 @@ const NoteSheet: React.FC<{ writing: Writing; setWriting: ComposerProps['setWrit><div aria-hidden="true" className="mx-auto mb-3 h-1 w-9 rounded-full bg-white/20" /><h2 id={title} className="flex flex-wrap items-baseline gap-x-2 text-[15px] font-semibold text-zinc-50">- {w.editing ? 'Edit note' : `Note for ${bot}`}+ {w.editing ? 'Edit note' : bot ? `Note for ${bot}` : 'Note'}<span className="text-[13px] font-normal text-zinc-400 [overflow-wrap:anywhere]">{base(w.path)} · {lineWords(w.start, w.end)}</span>@@ -1235,17 +1270,36 @@ interface SendBarProps {bar: Bar;setBar: (b: Bar) => void;drafts: number;- bot: string;+ /** Who the notes go to now; null with no default and no pick. */+ bot: string | null;phone: boolean;- onSend: () => void;+ /** The card's list and pick: the bar's trigger opens the same picker as Fix it. */+ sendTo?: SendTo | null;+ /** The author bot, while the list loads. */+ fallback?: string | null;+ onSend: (el: HTMLElement) => void;onDiscard: () => void;onOpenChat?: (botId: string) => void;}-const SendBar: React.FC<SendBarProps> = ({ bar, setBar, drafts, bot, phone, onSend, onDiscard, onOpenChat }) => {+const SendBar: React.FC<SendBarProps> = ({ bar, setBar, drafts, bot, phone, sendTo = null, fallback = null, onSend, onDiscard, onOpenChat }) => {const [menu, setMenu] = useState(false);const tooMany = drafts > MAX_SEND;- const failed = bar.s === 'failed';+ const failed = bar.s === 'failed' || bar.s === 'bad';+ const load: RecipientsLoad = sendTo?.load ?? { s: 'failed' };+ const trigger = (+ <BarTrigger+ load={load}+ pick={sendTo?.pick ?? null}+ fallback={bot ?? fallback}+ phone={phone}+ expanded={!!sendTo?.anchor && sendTo.anchor.dataset.goesFor === 'notes'}+ onOpen={(el) => {+ el.dataset.goesFor = 'notes';+ sendTo?.open(el);+ }}+ />+ );const where = phone? 'fixed inset-x-0 bottom-0 z-40 px-4 pb-[max(.625rem,env(safe-area-inset-bottom))]': 'sticky bottom-0 z-10 -mx-4 mt-3 rounded-b-[inherit] px-4';@@ -1273,13 +1327,25 @@ const SendBar: React.FC<SendBarProps> = ({ bar, setBar, drafts, bot, phone, onSe</button>)}</>+ ) : bar.s === 'bad' ? (+ <>+ <span data-ln-bad className="inline-flex min-w-0 flex-1 flex-wrap items-center gap-x-2 gap-y-1 text-meta text-zinc-200">+ <AlertTriangle size={14} aria-hidden="true" className="shrink-0 text-rose-300" />+ <span className="min-w-0 [overflow-wrap:anywhere]">{badRecipientNotes(bar.name)}</span>+ {trigger}+ </span>+ <button type="button" data-ln-send disabled={tooMany} onClick={(e) => onSend(e.currentTarget)} aria-label={sendLabel(drafts, bot)} className={`kw-btn-primary ${phone ? 'min-h-11 !text-[15px]' : ''}`}>+ <ArrowUp size={14} aria-hidden="true" />+ {phone ? sendShort(drafts) : sendLabel(drafts, bot)}+ </button>+ </>) : failed ? (<><span className="inline-flex min-w-0 flex-1 items-center gap-2 text-meta text-zinc-200"><AlertTriangle size={14} aria-hidden="true" className="shrink-0 text-rose-300" />{SEND_FAILED}</span>- <button type="button" onClick={onSend} className="kw-btn-primary max-sm:min-h-11">+ <button type="button" onClick={(e) => onSend(e.currentTarget)} className="kw-btn-primary max-sm:min-h-11">Try again</button></>@@ -1296,11 +1362,13 @@ const SendBar: React.FC<SendBarProps> = ({ bar, setBar, drafts, bot, phone, onSe) : (<><span className="inline-flex min-w-0 flex-1 items-center gap-2 text-meta text-zinc-300">- <span aria-hidden="true" className="inline-flex shrink-0">- <ModernAvatar name={bot} size={22} />- </span>+ {!sendTo && bot && (+ <span aria-hidden="true" className="inline-flex shrink-0">+ <ModernAvatar name={bot} size={22} />+ </span>+ )}<span className="min-w-0 [overflow-wrap:anywhere]">- <strong className="font-semibold text-zinc-100">{notesWord(drafts)}</strong> for {bot}+ <strong className="font-semibold text-zinc-100">{notesWord(drafts)}</strong> for {sendTo ? trigger : bot}{!phone && <span className="text-zinc-400"> · drafts, only you see them</span>}{tooMany && <span className="block text-zinc-400">{TOO_MANY}</span>}</span>@@ -1343,7 +1411,7 @@ const SendBar: React.FC<SendBarProps> = ({ bar, setBar, drafts, bot, phone, onSetype="button"data-ln-senddisabled={bar.s === 'sending' || tooMany}- onClick={onSend}+ onClick={(e) => onSend(e.currentTarget)}aria-label={bar.s === 'sending' ? 'Sending…' : sendLabel(drafts, bot)}className={`kw-btn-primary ${phone ? 'min-h-11 !text-[15px]' : ''}`}>diff --git a/frontend/src/components/dev/RecipientPicker.tsx b/frontend/src/components/dev/RecipientPicker.tsxnew file mode 100644index 00000000..530c92c7--- /dev/null+++ b/frontend/src/components/dev/RecipientPicker.tsx@@ -0,0 +1,546 @@+// Fix it "Send to…" (Mira, autonomy/fix-it-send-to/design.md §1–§3, §6, §8; Juno's #609 API). `GoesTo` is the+// quiet line under an open finding (and in the line-notes bar) that says who Fix it goes to and opens the+// picker. `RecipientPicker` is "Who fixes this PR?": a popover on desktop, a bottom sheet on phone. Picking a+// row only sets the card's pick; it never sends. Text from the server is rendered as text.++import React, { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'react';+import { createPortal } from 'react-dom';+import { AlertTriangle, Check, ChevronDown, Search, X } from 'lucide-react';+import { ModernAvatar } from '../ModernAvatar';+import type { DevRecipients, RecipientBot } from '../../dev/types';+import {+ LIST_FAILED,+ PICKER_CAPTION,+ PICKER_TITLE,+ SEARCH_FROM,+ filterBots,+ goesLabel,+ keepPick,+ loadPick,+ noMatch,+ nobodyFooter,+ pickedSay,+ pickerRows,+ rowMeta,+ savePick,+ target,+ whyLabel,+ loadShown,+ saveShown,+} from '../../dev/recipients';++const RING = 'outline-none focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-sky-400';++/** The card's list: loading, failed, or loaded. */+export type RecipientsLoad = { s: 'loading' } | { s: 'failed' } | { s: 'ready'; r: DevRecipients };++export interface GoesToProps {+ load: RecipientsLoad;+ pick: RecipientBot | null;+ /** `sm`: the one shared line under "Matches the ticket". */+ size?: 'md' | 'sm';+ phone?: boolean;+ /** The picker is open from this trigger. */+ expanded?: boolean;+ onOpen: (el: HTMLElement) => void;+ onRetry: () => void;+}++const Skel: React.FC<{ w: number; h?: number; round?: boolean }> = ({ w, h = 10, round }) => (+ <span aria-hidden="true" className={`inline-block bg-white/[.08] ${round ? 'rounded' : 'rounded'}`} style={{ width: w, height: h }} />+);++/** "Goes to {bot} · {why} ▾" (design §1), "No default bot · Pick who fixes it ▾" (§3), and the §6 states. */+export const GoesTo: React.FC<GoesToProps> = ({ load, pick, size = 'md', phone = false, expanded = false, onOpen, onRetry }) => {+ const box = phone+ ? 'order-first w-full min-h-[44px] justify-start'+ : size === 'sm'+ ? 'min-h-[28px]'+ : 'min-h-[28px]';+ const base = `inline-flex max-w-full items-center gap-1.5 rounded-lg px-2 text-meta ${box}`;+ if (load.s === 'loading') {+ return (+ <span data-goes-to="loading" className={`${base} text-zinc-400`}>+ Goes to <Skel w={16} h={16} /> <Skel w={56} />+ <span className="sr-only">: loading who fixes go to</span>+ </span>+ );+ }+ if (load.s === 'failed') {+ return (+ <span data-goes-to="failed" className={`${base} flex-wrap text-zinc-400`}>+ <span className="min-w-0 [overflow-wrap:anywhere]">Goes to the PR’s usual bot · {LIST_FAILED}</span>+ <button type="button" onClick={onRetry} className={`kw-btn-ghost min-h-[44px] px-2 py-0.5 text-meta sm:min-h-[28px] ${RING}`}>+ Try again+ </button>+ </span>+ );+ }+ const r = load.r;+ if (r.bots.length === 0) {+ return (+ <span data-goes-to="nobody" className={`${base} text-zinc-400 [overflow-wrap:anywhere]`}>+ {r.nobody ?? 'There’s no bot in this space to send it to.'}+ </span>+ );+ }+ const to = target(r, pick);+ const why = whyLabel(r.default, pick);+ const chosen = why === 'your pick';+ const common = {+ type: 'button' as const,+ 'aria-haspopup': 'listbox' as const,+ 'aria-expanded': expanded,+ onClick: (e: React.MouseEvent<HTMLButtonElement>) => onOpen(e.currentTarget),+ className: `${base} text-left hover:bg-white/[.06] ${RING}`,+ };+ if (!to) {+ return (+ <button {...common} data-goes-to="none" aria-label="No default bot. Pick who fixes it">+ <AlertTriangle size={14} aria-hidden="true" className="shrink-0 text-[#fcd34d]" />+ <span className="text-zinc-300">No default bot</span>+ <span aria-hidden="true" className="text-zinc-500">·</span>+ <span className="font-semibold text-violet-300">Pick who fixes it</span>+ <ChevronDown size={14} aria-hidden="true" className="shrink-0 text-zinc-400" />+ </button>+ );+ }+ return (+ <button {...common} data-goes-to={chosen ? 'pick' : r.default?.via ?? 'pick'} data-goes-to-id={to.id} aria-label={goesLabel(to.name, why)}>+ <span className="shrink-0 text-zinc-400">Goes to</span>+ <span aria-hidden="true" className="inline-flex shrink-0">+ <ModernAvatar name={to.name} size={16} />+ </span>+ <span className="min-w-0 truncate font-semibold text-zinc-100">{to.name}</span>+ {why && <span className={`min-w-0 truncate ${chosen ? 'text-[#c4b5fd]' : 'text-zinc-400'}`}>· {why}</span>}+ <ChevronDown size={14} aria-hidden="true" className="shrink-0 text-zinc-400" />+ </button>+ );+};++/** The line-notes bar's trigger (design §7): avatar · Ana ▾, or "Pick a bot ▾". */+export const BarTrigger: React.FC<{ load: RecipientsLoad; pick: RecipientBot | null; fallback: string | null; phone: boolean; expanded: boolean; onOpen: (el: HTMLElement) => void }> = ({+ load,+ pick,+ fallback,+ phone,+ expanded,+ onOpen,+}) => {+ const r = load.s === 'ready' ? load.r : null;+ const name = target(r, pick)?.name ?? (r ? null : fallback);+ if (!r || r.bots.length === 0) {+ // No list to pick from: the name stays plain text, as before #609.+ return name ? <span className="font-semibold text-zinc-100">{name}</span> : null;+ }+ return (+ <button+ type="button"+ data-ln-to={name ? 'bot' : 'none'}+ aria-haspopup="listbox"+ aria-expanded={expanded}+ aria-label={name ? `Notes go to ${name}. Change` : 'Pick a bot for the notes'}+ onClick={(e) => onOpen(e.currentTarget)}+ className={`inline-flex items-center gap-1 rounded-lg px-1 align-middle hover:bg-white/[.06] ${phone ? 'min-h-[44px]' : 'min-h-[28px]'} ${RING}`}+ >+ {name ? (+ <>+ <span aria-hidden="true" className="inline-flex shrink-0">+ <ModernAvatar name={name} size={phone ? 22 : 18} />+ </span>+ <span className="font-semibold text-zinc-100">{name}</span>+ </>+ ) : (+ <span className="font-semibold text-violet-300">Pick a bot</span>+ )}+ <ChevronDown size={14} aria-hidden="true" className="shrink-0 text-zinc-400" />+ </button>+ );+};++// ---------------------------------------------------------------------------------------------------++export interface RecipientPickerProps {+ r: DevRecipients;+ pick: RecipientBot | null;+ anchor: HTMLElement | null;+ phone: boolean;+ /** `owner/name` for the no-default footer. */+ repo: string | null;+ onPick: (bot: RecipientBot) => void;+ /** `false` skips putting focus back on the trigger (closed by scrolling). */+ onClose: (refocus?: boolean) => void;+}++const POP_W = 320;++/** "Who fixes this PR?" (design §2): a listbox, keyboard and pointer. */+export const RecipientPicker: React.FC<RecipientPickerProps> = ({ r, pick, anchor, phone, repo, onPick, onClose }) => {+ const id = useId();+ const listId = `${id}-list`;+ const titleId = `${id}-title`;+ const rows = useMemo(() => pickerRows(r), [r]);+ const [q, setQ] = useState('');+ const shown = useMemo(() => filterBots(rows, q), [rows, q]);+ const current = target(r, pick)?.id ?? null;+ // The current pick (or default) starts active, but with no ring; nothing is active when there's neither (Mira #615 fix 2).+ const [active, setActive] = useState(() => rows.findIndex((b) => b.id === current));+ // The sky ring is for the keyboard: on after arrows, Home/End or typing; off on pointer movement.+ const [kbd, setKbd] = useState(false);+ const search = rows.length > SEARCH_FROM;+ const inputRef = useRef<HTMLInputElement>(null);+ const listRef = useRef<HTMLUListElement>(null);+ const panelRef = useRef<HTMLDivElement>(null);+ const [pos, setPos] = useState<{ left: number; top?: number; bottom?: number } | null>(null);+ const onCloseRef = useRef(onClose);+ onCloseRef.current = onClose;++ // Typing keeps the active row on the first match (not on open: that would preselect the first row).+ const typed = useRef(false);+ useEffect(() => {+ if (!typed.current) {+ typed.current = true;+ return;+ }+ setActive(0);+ setKbd(true);+ }, [q]);+ // Desktop: the panel is visibility:hidden until it's placed, and a hidden element can't take focus, so wait for pos.+ const placed = phone || pos !== null;+ useEffect(() => {+ if (placed) (search ? inputRef.current : listRef.current)?.focus({ preventScroll: true });+ }, [search, placed]);+ useEffect(() => {+ // Scroll the list only, never the page: a page scroll would close the popover (fix 1).+ const list = listRef.current;+ const row = list?.querySelector<HTMLElement>(`[data-i="${active}"]`);+ if (!list || !row) return;+ const top = row.getBoundingClientRect().top - list.getBoundingClientRect().top + list.scrollTop;+ if (top < list.scrollTop) list.scrollTop = top;+ else if (top + row.offsetHeight > list.scrollTop + list.clientHeight) list.scrollTop = top + row.offsetHeight - list.clientHeight;+ }, [active]);++ // Desktop: under the trigger, flipped above it when there's no room below.+ useLayoutEffect(() => {+ if (phone || !anchor) return;+ const place = () => {+ const a = anchor.getBoundingClientRect();+ const vw = window.innerWidth;+ const vh = window.innerHeight;+ const left = Math.max(8, Math.min(a.left, vw - POP_W - 8));+ const h = panelRef.current?.offsetHeight ?? 420;+ if (a.bottom + 6 + h > vh - 8 && a.top - 6 - h > 8) setPos({ left, bottom: vh - a.top + 6 });+ else setPos({ left, top: a.bottom + 6 });+ };+ // Scrolling the page under the trigger closes it, like every other popover (Mira #615 fix 1); the list's own+ // scroll doesn't. No refocus: the person is scrolling.+ const scrolled = (e: Event) => {+ const t = e.target;+ if (t === document || (t instanceof Node && t.contains(anchor))) onCloseRef.current(false);+ };+ place();+ window.addEventListener('resize', place);+ window.addEventListener('scroll', scrolled, true);+ return () => {+ window.removeEventListener('resize', place);+ window.removeEventListener('scroll', scrolled, true);+ };+ }, [phone, anchor]);++ // A press outside the popover closes it (the sheet has its own backdrop).+ useEffect(() => {+ if (phone) return;+ const down = (e: PointerEvent) => {+ const t = e.target as Node;+ if (panelRef.current?.contains(t) || anchor?.contains(t)) return;+ onClose();+ };+ document.addEventListener('pointerdown', down);+ return () => document.removeEventListener('pointerdown', down);+ }, [phone, anchor, onClose]);++ const choose = (b: RecipientBot | undefined) => {+ if (b) onPick(b);+ };+ const onKey = (e: React.KeyboardEvent) => {+ const n = shown.length;+ if (e.key === 'Escape') {+ e.preventDefault();+ e.stopPropagation();+ onClose();+ } else if (e.key === 'ArrowDown' && n) {+ e.preventDefault();+ setKbd(true);+ setActive((i) => Math.min(n - 1, i + 1));+ } else if (e.key === 'ArrowUp' && n) {+ e.preventDefault();+ setKbd(true);+ setActive((i) => Math.max(0, i - 1));+ } else if (e.key === 'Home' && n && e.currentTarget === listRef.current) {+ e.preventDefault();+ setKbd(true);+ setActive(0);+ } else if (e.key === 'End' && n && e.currentTarget === listRef.current) {+ e.preventDefault();+ setKbd(true);+ setActive(n - 1);+ } else if (e.key === 'Enter') {+ e.preventDefault();+ if (active >= 0) choose(shown[active]);+ } else if (e.key === 'Tab' && !phone) {+ onClose();+ }+ };+ const optId = (i: number) => `${id}-o${i}`;+ const def = r.default;++ const body = (+ <>+ <div className={phone ? 'flex items-start gap-2 px-4 pt-1' : 'px-3 pt-3'}>+ <div className="min-w-0 flex-1">+ <h2 id={titleId} className="text-[15px] font-semibold leading-[22px] text-zinc-50">+ {PICKER_TITLE}+ </h2>+ <p className="text-meta text-zinc-400">{PICKER_CAPTION}</p>+ </div>+ {phone && (+ <button type="button" aria-label="Close" onClick={() => onClose()} className={`-mr-2 -mt-1 inline-flex h-11 w-11 shrink-0 items-center justify-center rounded-xl text-zinc-300 hover:bg-white/[.06] ${RING}`}>+ <X size={18} aria-hidden="true" />+ </button>+ )}+ </div>+ {search && (+ <div className={phone ? 'px-4 pt-3' : 'px-2 pt-2.5'}>+ <label className="flex items-center gap-2 rounded-lg border border-hairline bg-[#120e26] px-2.5 focus-within:outline focus-within:outline-2 focus-within:outline-sky-400">+ <Search size={14} aria-hidden="true" className="shrink-0 text-zinc-400" />+ <span className="sr-only">Find a bot or team</span>+ <input+ ref={inputRef}+ value={q}+ onChange={(e) => setQ(e.target.value)}+ onKeyDown={onKey}+ placeholder="Find a bot or team"+ role="combobox"+ aria-expanded="true"+ aria-controls={listId}+ aria-activedescendant={shown.length && active >= 0 ? optId(active) : undefined}+ aria-autocomplete="list"+ className={`min-w-0 flex-1 bg-transparent py-2 text-zinc-100 placeholder:text-zinc-500 outline-none ${phone ? 'text-[16px]' : 'text-[13px]'}`}+ />+ </label>+ </div>+ )}+ {shown.length === 0 ? (+ <p data-picker-empty className="px-4 py-4 text-meta text-zinc-400">+ {noMatch(q)}+ </p>+ ) : (+ <ul+ ref={listRef}+ id={listId}+ role="listbox"+ tabIndex={search ? -1 : 0}+ aria-labelledby={titleId}+ aria-activedescendant={search || active < 0 ? undefined : optId(active)}+ onKeyDown={search ? undefined : onKey}+ className={`mt-2 overflow-y-auto px-1.5 pb-1.5 outline-none ${phone ? 'max-h-[calc(82vh-140px)]' : 'max-h-[300px]'} focus-visible:outline focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-sky-400`}+ >+ {shown.map((b, i) => {+ const isDefault = !!def && b.id === def.id;+ const meta = rowMeta(b, def);+ const sel = b.id === current;+ return (+ <React.Fragment key={b.id}>+ <li+ id={optId(i)}+ data-i={i}+ data-bot={b.id}+ role="option"+ aria-selected={sel}+ onPointerMove={() => {+ setActive(i);+ setKbd(false);+ }}+ onClick={() => choose(b)}+ className={`flex cursor-pointer items-center gap-2.5 rounded-lg px-2 ${phone ? 'min-h-[52px]' : 'min-h-[40px]'} py-1 ${i === active ? `bg-white/[.07]${kbd ? ' outline outline-1 outline-sky-400/60' : ''}` : ''}`}+ >+ <span aria-hidden="true" className="inline-flex shrink-0">+ <ModernAvatar name={b.name} size={24} />+ </span>+ {isDefault ? (+ <span className="min-w-0 flex-1">+ <span className="block truncate text-[14px] font-medium text-zinc-100">{b.name}</span>+ <span className="block text-meta text-zinc-400 [overflow-wrap:anywhere]">{meta}</span>+ </span>+ ) : (+ <>+ <span className="min-w-0 flex-1 truncate text-[14px] font-medium text-zinc-100">{b.name}</span>+ {meta && <span className="max-w-[45%] shrink-0 truncate text-meta text-zinc-400">{meta}</span>}+ </>+ )}+ <span className="inline-flex w-4 shrink-0 justify-center">{sel && <Check size={15} aria-hidden="true" className="text-[#a78bfa]" />}</span>+ </li>+ {isDefault && !q.trim() && i === 0 && shown.length > 1 && <li role="presentation" aria-hidden="true" className="mx-2 my-1 border-t border-hairline" />}+ </React.Fragment>+ );+ })}+ </ul>+ )}+ {!def && (+ <p data-picker-footer className="border-t border-hairline px-3 py-2.5 text-meta text-zinc-400 [overflow-wrap:anywhere]">+ {nobodyFooter(repo)}+ </p>+ )}+ </>+ );++ const node = phone ? (+ <div className="fixed inset-0 z-[60]" data-recipient-picker="sheet">+ <div aria-hidden="true" className="absolute inset-0 bg-black/50" onClick={() => onClose()} />+ <div+ ref={panelRef}+ role="dialog"+ aria-modal="true"+ aria-labelledby={titleId}+ onKeyDown={(e) => e.key === 'Escape' && onKey(e)}+ className="kw-st-sheet absolute inset-x-0 bottom-0 flex max-h-[82vh] flex-col rounded-t-2xl border-t border-hairline-strong bg-surface-overlay pb-[env(safe-area-inset-bottom)] shadow-xl"+ >+ <span aria-hidden="true" className="mx-auto mb-1 mt-2 block h-1 w-9 rounded-full bg-white/20" />+ {body}+ </div>+ </div>+ ) : (+ <div+ ref={panelRef}+ role="dialog"+ aria-labelledby={titleId}+ data-recipient-picker="popover"+ style={pos ? { position: 'fixed', left: pos.left, top: pos.top, bottom: pos.bottom, width: POP_W } : { position: 'fixed', visibility: 'hidden', width: POP_W }}+ className="kw-st-pop z-[60] rounded-xl border border-hairline-strong bg-surface-overlay shadow-xl"+ >+ {body}+ </div>+ );+ return typeof document === 'undefined' ? node : createPortal(node, document.body);+};++// ---------------------------------------------------------------------------------------------------+// The card's "send to" state (design §1): the list (fetched once per card), the pick (sessionStorage), and the+// one picker, anchored to whichever trigger opened it. ReviewCard owns it; FindingRow, TicketMatches and the+// line-notes bar read it.++export interface SendTo {+ load: RecipientsLoad;+ pick: RecipientBot | null;+ /** N1: the picker has been shown on this card, or a finding went to a chosen bot: every send carries `to`. */+ pinned: boolean;+ phone: boolean;+ /** The trigger the picker is open from, if any. */+ anchor: HTMLElement | null;+ /** Open the picker from `el`; `after` runs with the pick (line notes' "Send N notes…"). */+ open: (el: HTMLElement, after?: (to: RecipientBot) => void) => void;+ retry: () => void;+ /** After a bad_recipient: refetch, and drop the pick. */+ reset: () => void;+ /** After a send_error: refetch, and keep the pick only if it's still listed. */+ refresh: () => void;+}++const PHONE = '(max-width: 639px)';++export function useSendTo(+ cardId: string,+ fetcher: ((cardId: string) => Promise<DevRecipients>) | undefined,+ repo: string | null,+ phone: boolean,+ /** The card already has a finding with `sent_to_id`. */+ sentToChosen = false,+): { st: SendTo | null; picker: React.ReactNode; say: string } {+ const [load, setLoad] = useState<RecipientsLoad>({ s: 'loading' });+ const [pick, setPickState] = useState<RecipientBot | null>(() => loadPick(cardId));+ const [shown, setShown] = useState<boolean>(() => loadShown(cardId));+ const [anchor, setAnchor] = useState<HTMLElement | null>(null);+ const after = useRef<((to: RecipientBot) => void) | null>(null);+ const [say, setSay] = useState('');+ const seq = useRef(0);++ const setPick = (p: RecipientBot | null) => {+ setPickState(p);+ savePick(cardId, p);+ };++ const fetchList = (drop: boolean) => {+ if (!fetcher) return;+ const n = ++seq.current;+ if (!drop) setLoad((l) => (l.s === 'ready' ? l : { s: 'loading' }));+ fetcher(cardId).then(+ (r) => {+ if (n !== seq.current) return;+ setLoad({ s: 'ready', r });+ setPickState((p) => {+ const kept = drop ? null : keepPick(p, r);+ savePick(cardId, kept);+ return kept;+ });+ },+ () => {+ if (n === seq.current) setLoad({ s: 'failed' });+ },+ );+ };++ useEffect(() => {+ setPickState(loadPick(cardId));+ setShown(loadShown(cardId));+ fetchList(false);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [cardId, fetcher]);++ const anchorRef = useRef<HTMLElement | null>(null);+ anchorRef.current = anchor;+ // Closing gives focus back to the trigger that opened the picker (design §2).+ const close = React.useCallback((refocus: boolean = true) => {+ const a = anchorRef.current;+ setAnchor(null);+ after.current = null;+ if (a && refocus) window.setTimeout(() => a.isConnected && a.focus({ preventScroll: true }), 0);+ }, []);++ if (!fetcher) return { st: null, picker: null, say: '' };++ const r = load.s === 'ready' ? load.r : null;+ const st: SendTo = {+ load,+ pick,+ pinned: shown || sentToChosen,+ phone,+ anchor,+ open: (el, then) => {+ if (!r || r.bots.length === 0) return;+ after.current = then ?? null;+ setShown(true);+ saveShown(cardId);+ setAnchor(el);+ },+ retry: () => fetchList(false),+ reset: () => {+ setPick(null);+ fetchList(true);+ },+ refresh: () => fetchList(false),+ };++ const onPick = (b: RecipientBot) => {+ const isDefault = !!r?.default && r.default.id === b.id;+ setPick(isDefault ? null : b);+ setSay(pickedSay(b.name));+ const then = after.current;+ close();+ then?.(b);+ };++ const picker = r && anchor ? <RecipientPicker r={r} pick={pick} anchor={anchor} phone={phone} repo={repo} onPick={onPick} onClose={close} /> : null;+ return { st, picker, say };+}++export const SEND_TO_PHONE = PHONE;diff --git a/frontend/src/components/dev/ReviewCard.tsx b/frontend/src/components/dev/ReviewCard.tsxindex 2711fe08..5958ad92 100644--- a/frontend/src/components/dev/ReviewCard.tsx+++ b/frontend/src/components/dev/ReviewCard.tsx@@ -14,6 +14,9 @@ import {} from 'lucide-react';import { FreshEyesChip } from './FreshEyesChip';import { ChangesSection } from './LineNotes';+import { GoesTo, SEND_TO_PHONE, useSendTo, type SendTo } from './RecipientPicker';+import { useMedia } from '../../useMedia';+import { badRecipientFix, toFor } from '../../dev/recipients';import { verdictShort } from '../../api/inbox';import { inboxNav, openReview, reviewForPr, useInbox } from '../../inboxStore';import type { DevFinding, FindingAction, Forge, ReviewCard as Review, ReviewCardProps, Severity, TamperFlag } from '../../dev/types';@@ -151,9 +154,13 @@ interface FindingRowProps {now: number;busy: boolean;act: (f: DevFinding, a: FindingAction) => Promise<void>;+ /** Fix it "Send to…" (#609): who Fix it goes to; null without the recipients route. */+ st?: SendTo | null;+ onFix?: (f: DevFinding, el: HTMLElement) => void;+ onOpenTask?: (taskId: string) => void;}-const FindingRow: React.FC<FindingRowProps> = ({ f, author, now, busy, act }) => {+const FindingRow: React.FC<FindingRowProps> = ({ f, author, now, busy, act, st = null, onFix, onOpenTask }) => {const dismiss = useDismiss(f, act);const { draft, send } = dismiss;const formId = `dismiss-${f.id}`;@@ -169,6 +176,10 @@ const FindingRow: React.FC<FindingRowProps> = ({ f, author, now, busy, act }) =>}const left = undoLeft(f, now);+ // §3: no bot at all in the space: Fix it is off, with the server's sentence as its title.+ const nobody = st?.load.s === 'ready' && st.load.r.bots.length === 0 ? st.load.r.nobody ?? 'There’s no bot in this space to send it to.' : null;+ // One message per state (Mira #615 fix 3): the send error waits for the list, and goes when nobody can receive.+ const showSendError = !st || (st.load.s === 'ready' && st.load.r.bots.length > 0);return (<li data-finding={f.id} data-state={f.state} className={`rounded-xl border border-zinc-700/60 border-l-[3px] bg-zinc-900/60 p-3 text-xs shadow-[var(--kws-shadow)] ${STRIPE[f.severity]}`}>@@ -197,16 +208,24 @@ const FindingRow: React.FC<FindingRowProps> = ({ f, author, now, busy, act }) =><div className="mt-2 flex flex-wrap items-center gap-2" aria-live="polite">{f.state === 'open' && !draft.open && (<>- <button type="button" disabled={busy} onClick={() => void act(f, { action: 'fix' })} className="kw-btn-primary min-h-[44px] px-2.5 py-1 text-xs sm:min-h-0">+ <button+ type="button"+ data-fix-it+ disabled={busy || !!nobody}+ title={nobody ?? undefined}+ onClick={(e) => (onFix ? onFix(f, e.currentTarget) : void act(f, { action: 'fix' }))}+ className="kw-btn-primary min-h-[44px] px-2.5 py-1 text-xs sm:min-h-0"+ ><Wrench size={13} aria-hidden="true" />Fix it</button><button type="button" disabled={busy} aria-expanded={false} aria-controls={formId} onClick={() => send({ type: 'open' })} className="kw-btn-ghost min-h-[44px] px-2.5 py-1 text-xs sm:min-h-0">Dismiss</button>+ {st && <GoesTo load={st.load} pick={st.pick} phone={st.phone} expanded={!!st.anchor && st.anchor.dataset.goesFor === f.id} onOpen={(el) => { el.dataset.goesFor = f.id; st.open(el); }} onRetry={st.retry} />}</>)}- {f.state === 'open' && f.send_error && <span className="text-bad">Couldn’t send it: {f.send_error}</span>}+ {f.state === 'open' && f.send_error && showSendError && <span className="text-bad">Couldn’t send it: {f.send_error}</span>}{f.state === 'sent' && (<><span className="inline-flex items-center gap-1 text-ok">@@ -218,6 +237,16 @@ const FindingRow: React.FC<FindingRowProps> = ({ f, author, now, busy, act }) =>Undo <span className="text-zinc-400">({Math.ceil(left / 1000)} s)</span></button>)}+ {left <= 0 && f.task_id && onOpenTask && (+ <button+ type="button"+ data-open-task={f.task_id}+ onClick={() => onOpenTask(f.task_id as string)}+ className="inline-flex min-h-[44px] items-center rounded px-1 font-semibold text-violet-300 hover:underline sm:min-h-0 outline-none focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400"+ >+ Open task ›+ </button>+ )}</>)}</div>@@ -417,7 +446,7 @@ const Stamp: React.FC<{ id: string; reviewer: string }> = ({ id, reviewer }) =>};/** One PR in review: risk, intent, tests, security and findings (design §5, parts 1–7). */-export const ReviewCard: React.FC<ReviewCardProps> = ({ card: given, onFinding, sample = false, now: fixedNow, onPost, forge = null, forgeLogin = null, repoLabel, jiraOrigins = [], lineNotes, onOpenChat }) => {+export const ReviewCard: React.FC<ReviewCardProps> = ({ card: given, onFinding, sample = false, now: fixedNow, onPost, forge = null, forgeLogin = null, repoLabel, jiraOrigins = [], lineNotes, onOpenChat, recipients, onOpenTask }) => {const [card, setCard] = useState<Review>(given);const [busy, setBusy] = useState<string | null>(null);const [tick, setTick] = useState(() => Date.now());@@ -437,6 +466,32 @@ export const ReviewCard: React.FC<ReviewCardProps> = ({ card: given, onFinding,return () => window.clearInterval(t);}, [undoing]);+ // Fix it "Send to…" (#609, design §1–§6): the card's list and pick, and its one picker.+ const phone = useMedia(SEND_TO_PHONE);+ const sentToChosen = card.findings.some((f) => !!f.sent_to_id);+ const { st, picker, say } = useSendTo(given.id, sample ? undefined : recipients, given.repo_name ?? given.repo, phone, sentToChosen);+ // §5: a chosen bot deleted in the Undo window comes back from the server (a card update) as an open+ // finding with a send_error: refetch, so a pick that's gone falls back to the default.+ const errKey = given.findings.filter((f) => f.state === 'open' && f.send_error).map((f) => `${f.id}:${f.send_error}`).join('|');+ const lastErr = useRef(errKey);+ useEffect(() => {+ if (errKey && errKey !== lastErr.current) st?.refresh();+ lastErr.current = errKey;+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [errKey]);++ /** One tap to the default; a pick adds `to`, and so does every press once the picker has been shown (N1);+ * no default and no pick opens the picker instead (§3). */+ const fix = (f: DevFinding, el: HTMLElement) => {+ const r = st?.load.s === 'ready' ? st.load.r : null;+ if (st && r && r.bots.length > 0 && !r.default && !st.pick) {+ st.open(el);+ return;+ }+ const to = st ? toFor(r, st.pick, st.pinned) : undefined;+ void act(f, to ? { action: 'fix', to } : { action: 'fix' });+ };+const act = async (f: DevFinding, a: FindingAction) => {if (busy) return;setBusy(f.id);@@ -445,7 +500,13 @@ export const ReviewCard: React.FC<ReviewCardProps> = ({ card: given, onFinding,setTick(Date.now());} catch (err) {if (a.action === 'dismiss') throw err;- const msg = err instanceof Error ? err.message : 'it didn’t go through';+ const bad = (err as { code?: unknown } | null)?.code === 'bad_recipient';+ let msg = err instanceof Error ? err.message : 'it didn’t go through';+ if (bad) {+ // §5: name the picked bot from the cached list, then refetch and fall back to the default.+ msg = badRecipientFix(st?.pick?.name ?? null).replace(/^Couldn’t send it: /, '');+ st?.reset();+ }setCard((c) => ({...c,findings: c.findings.map((x) => (x.id === f.id ? { ...x, send_error: msg } : x)),@@ -589,6 +650,7 @@ export const ReviewCard: React.FC<ReviewCardProps> = ({ card: given, onFinding,headSha={card.head_sha}prUrl={card.links.pr ?? null}onOpenChat={onOpenChat}+ sendTo={st}/>)}@@ -631,7 +693,21 @@ export const ReviewCard: React.FC<ReviewCardProps> = ({ card: given, onFinding,{/* 3. Intent, or Matches the ticket (0.7.6) */}{ticketMatches && (- <TicketMatches matches={ticketMatches} now={now} origins={jiraOrigins} lead={author?.name ?? null} busy={busy !== null} act={act} />+ <TicketMatches+ matches={ticketMatches}+ now={now}+ origins={jiraOrigins}+ lead={author?.name ?? null}+ busy={busy !== null}+ act={act}+ onFix={st ? fix : undefined}+ showSendError={!st || (st.load.s === 'ready' && st.load.r.bots.length > 0)}+ goesTo={+ st && ticketMatches.items.some((it) => itemFinding(it)?.state === 'open') ? (+ <GoesTo size="sm" load={st.load} pick={st.pick} phone={st.phone} expanded={!!st.anchor && st.anchor.dataset.goesFor === 'matches'} onOpen={(el) => { el.dataset.goesFor = 'matches'; st.open(el); }} onRetry={st.retry} />+ ) : null+ }+ />)}{card.intent && !ticketMatches && (<section className="mt-4" aria-label="Did it do what was asked?">@@ -718,7 +794,7 @@ export const ReviewCard: React.FC<ReviewCardProps> = ({ card: given, onFinding,) : (<ul role="list" className="space-y-1.5">{listed.map((f) => (- <FindingRow key={f.id} f={f} author={author?.name ?? null} now={now} busy={busy !== null} act={act} />+ <FindingRow key={f.id} f={f} author={author?.name ?? null} now={now} busy={busy !== null} act={act} st={st} onFix={st ? fix : undefined} onOpenTask={sample ? undefined : onOpenTask} />))}</ul>)}@@ -764,6 +840,12 @@ export const ReviewCard: React.FC<ReviewCardProps> = ({ card: given, onFinding,onPost={() => void post()}/>)}+ {st && (+ <p className="sr-only" aria-live="polite" data-send-to-say>+ {say}+ </p>+ )}+ {picker}</article>);};diff --git a/frontend/src/components/dev/TicketMatches.tsx b/frontend/src/components/dev/TicketMatches.tsxindex f0d56232..7c1c976d 100644--- a/frontend/src/components/dev/TicketMatches.tsx+++ b/frontend/src/components/dev/TicketMatches.tsx@@ -54,7 +54,9 @@ const MRow: React.FC<{now: number;busy: boolean;act?: (f: DevFinding, a: FindingAction) => Promise<void> | void;-}> = ({ r, i, now, busy, act }) => {+ onFix?: (f: DevFinding, el: HTMLElement) => void;+ showSendError: boolean;+}> = ({ r, i, now, busy, act, onFix, showSendError }) => {const st = STATE[r.state];const f = itemFinding(r);// api-decisions 25: the findings' own Dismiss-with-a-reason, on the item's k{n}.@@ -99,7 +101,7 @@ const MRow: React.FC<{)}</p>)}- {f?.send_error && f.state === 'open' && (+ {f?.send_error && f.state === 'open' && showSendError && (<p className="tk-err" role="alert">Couldn’t send it: {f.send_error}</p>@@ -131,7 +133,7 @@ const MRow: React.FC<{act &&!dismiss.draft.open && (<>- <button type="button" className="tk-btn-sm" disabled={busy} onClick={() => void act(f, { action: 'fix' })} aria-label={`Fix it: line ${i + 1}`} data-fix={f.id}>+ <button type="button" className="tk-btn-sm" disabled={busy} onClick={(e) => (onFix ? onFix(f, e.currentTarget) : void act(f, { action: 'fix' }))} aria-label={`Fix it: line ${i + 1}`} data-fix={f.id}>{busy ? <Loader2 size={12} className="tk-spin" aria-hidden="true" /> : null}{f.send_error ? 'Try again' : 'Fix it'}</button>@@ -167,9 +169,15 @@ export interface TicketMatchesProps {lead?: string | null;busy?: boolean;act?: (f: DevFinding, a: FindingAction) => Promise<void> | void;+ /** Fix it "Send to…" (#609): ReviewCard's Fix it, which adds the card's pick. */+ onFix?: (f: DevFinding, el: HTMLElement) => void;+ /** The one shared "Goes to" line under the section head (design §1). */+ goesTo?: React.ReactNode;+ /** False while the bot list loads or when nobody can receive: the send error would contradict the screen. */+ showSendError?: boolean;}-export const TicketMatches: React.FC<TicketMatchesProps> = ({ matches, now = Date.now(), origins = [], lead = null, busy = false, act }) => {+export const TicketMatches: React.FC<TicketMatchesProps> = ({ matches, now = Date.now(), origins = [], lead = null, busy = false, act, onFix, goesTo = null, showSendError = true }) => {const { met, total } = matchCount(matches.items);const all = matches.verdict === 'met' && total > 0 && met === total;const url = onSite(matches.url, origins);@@ -194,6 +202,11 @@ export const TicketMatches: React.FC<TicketMatchesProps> = ({ matches, now = Dat</span>)}</div>+ {goesTo && (+ <div data-matches-goes-to className="mb-1 flex flex-wrap items-center">+ {goesTo}+ </div>+ )}<p className="tk-asked">Checked against the <b>Done when</b> lines in {lead ? `${lead}’s brief` : 'the brief'}, not against the PR’s own description.</p>@@ -203,7 +216,7 @@ export const TicketMatches: React.FC<TicketMatchesProps> = ({ matches, now = Dat<SiteOrigins.Provider value={origins}><ul className="tk-mrows" role="list">{matches.items.map((r, i) => (- <MRow key={r.id ?? i} r={r} i={i} now={now} busy={busy} act={act} />+ <MRow key={r.id ?? i} r={r} i={i} now={now} busy={busy} act={act} onFix={onFix} showSendError={showSendError} />))}</ul></SiteOrigins.Provider>diff --git a/frontend/src/dev/lineNotes.ts b/frontend/src/dev/lineNotes.tsindex 98b4d710..a75a653f 100644--- a/frontend/src/dev/lineNotes.ts+++ b/frontend/src/dev/lineNotes.ts@@ -339,7 +339,9 @@ export const filesWord = (n: number) => plural(n, 'file');export const notesWord = (n: number) => plural(n, 'note');export const draftsWord = (n: number) => plural(n, 'draft');export const addAria = (l: DiffLine) => (l.kind === 'del' ? `Add a note on removed line ${l.old}` : `Add a note on line ${l.new}`);-export const sendLabel = (n: number, bot: string) => (n === 1 ? `Send note to ${bot}` : `Send ${n} notes to ${bot}`);+/** With no bot yet (no default, no pick: Fix it "Send to…" §7) the label ends in "…" and opens the picker. */+export const sendLabel = (n: number, bot: string | null) =>+ bot ? (n === 1 ? `Send note to ${bot}` : `Send ${n} notes to ${bot}`) : n === 1 ? 'Send note…' : `Send ${n} notes…`;export const sendShort = (n: number) => `Send ${n}`;export const sentLine = (n: number, bot: string, at: string | null) => `Sent ${notesWord(n)} to ${bot}${at ? ` · ${at}` : ''}`;export const discardAsk = (n: number) => (n === 1 ? 'Discard 1 draft?' : `Discard ${n} drafts?`);diff --git a/frontend/src/dev/lineNotesApi.ts b/frontend/src/dev/lineNotesApi.tsindex 581d6c11..f84519c0 100644--- a/frontend/src/dev/lineNotesApi.ts+++ b/frontend/src/dev/lineNotesApi.ts@@ -29,8 +29,8 @@ export interface LineNotesApi {remove(noteId: string): Promise<void>;restore(noteId: string): Promise<Note>;discardAll(cardId: string): Promise<number>;- /** `sendId` makes a Try again after a timeout safe (ask 6). */- send(cardId: string, sendId: string, ids?: string[]): Promise<SendResult>;+ /** `sendId` makes a Try again after a timeout safe (ask 6). `to` (#609): a bot the person picked. */+ send(cardId: string, sendId: string, ids?: string[], to?: string): Promise<SendResult>;}/** (url, method, body) → parsed JSON, or throws LineNotesError. */@@ -122,8 +122,8 @@ export function lineNotesApi(call: Caller): LineNotesApi {const n = r && typeof r === 'object' ? (r as Record<string, unknown>).discarded : null;return typeof n === 'number' && Number.isInteger(n) && n >= 0 ? n : 0;},- send: async (id, sendId, ids) =>- need(parseSendResult(await call(`${card(id)}/notes/send`, 'POST', ids ? { ids, send_id: sendId } : { send_id: sendId }))),+ send: async (id, sendId, ids, to) =>+ need(parseSendResult(await call(`${card(id)}/notes/send`, 'POST', { ...(ids ? { ids } : {}), send_id: sendId, ...(to ? { to } : {}) }))),};}diff --git a/frontend/src/dev/recipients.ts b/frontend/src/dev/recipients.tsnew file mode 100644index 00000000..e9c001ee--- /dev/null+++ b/frontend/src/dev/recipients.ts@@ -0,0 +1,138 @@+// Fix it "Send to…" (Mira, autonomy/fix-it-send-to/design.md; Juno's #609 API). Pure helpers for the+// "Goes to" line and the picker: the why words, a row's meta, the client-side search, the per-card pick in+// sessionStorage, and the plain error lines. No React here, so the tests can call them directly.++import type { DevRecipients, RecipientBot, RecipientDefault } from './types';++/** The `{why}` after the name (design §1): "wrote it", "lead of Edge", or "your pick". */+export function whyLabel(def: RecipientDefault | null, pick: RecipientBot | null): string | null {+ if (pick && (!def || pick.id !== def.id)) return 'your pick';+ if (!def) return null;+ if (def.via === 'author') return 'wrote it';+ return def.team ? `lead of ${def.team}` : 'team lead';+}++/** Who Fix it goes to right now: the pick, else the default, else nobody. */+export const target = (r: DevRecipients | null, pick: RecipientBot | null): RecipientBot | null => pick ?? r?.default ?? null;++/**+ * The `to` a Fix it press or a line-notes send carries (Rigel's N1 on #609). Before the picker has been shown on+ * the card, only a pick needs `to`. Once it has been shown, or the card already has a finding sent to a chosen bot+ * (`sent_to_id`), every press names its bot, the default included: a second press with no `to` would make the+ * server swap the person's pick for the default while the first fix is still waiting to go out.+ */+export function toFor(r: DevRecipients | null, pick: RecipientBot | null, pinned: boolean): string | undefined {+ const t = target(r, pick);+ if (!t) return undefined;+ if (pinned) return t.id;+ return pick && !(r?.default && r.default.id === pick.id) ? pick.id : undefined;+}++/** A picker row's meta (design §2): the default's reason, "Edge · owns this repo", the team, or nothing. */+export function rowMeta(bot: RecipientBot, def: RecipientDefault | null): string | null {+ if (def && bot.id === def.id) {+ if (def.via === 'author') return 'Default · wrote it';+ return def.team ? `Default · lead of ${def.team}, which owns this repo` : 'Default · team lead';+ }+ if (def && def.via === 'team_lead' && def.team && bot.team === def.team) return `${bot.team} · owns this repo`;+ return bot.team ?? null;+}++/** The picker's rows: the default pinned first, then the rest in the server's order. */+export function pickerRows(r: DevRecipients): RecipientBot[] {+ const d = r.default;+ if (!d) return r.bots;+ const first = r.bots.find((b) => b.id === d.id) ?? { id: d.id, name: d.name, ...(d.team ? { team: d.team } : {}) };+ return [first, ...r.bots.filter((b) => b.id !== d.id)];+}++/** Search by name or team, case-insensitive (design §2). */+export function filterBots(bots: readonly RecipientBot[], q: string): RecipientBot[] {+ const s = q.trim().toLowerCase();+ if (!s) return [...bots];+ return bots.filter((b) => b.name.toLowerCase().includes(s) || (b.team ?? '').toLowerCase().includes(s));+}++export const SEARCH_FROM = 8;+export const noMatch = (q: string) => `No bot matches "${q.trim()}".`;+export const PICKER_TITLE = 'Who fixes this PR?';+export const PICKER_CAPTION = 'Fix it and line notes on this PR go here.';+export const nobodyFooter = (repo: string | null) =>+ `No bot wrote this PR and no team owns ${repo ?? 'this repo'}, so there’s no default. To set one, add the repo to a team (Manage team › Git Repo).`;+export const LIST_FAILED = 'couldn’t load the list';+export const goesLabel = (name: string, why: string | null) => `Fixes go to ${name}${why ? `, ${why}` : ''}. Change`;+export const pickedSay = (name: string) => `Fixes go to ${name}`;++/** Fix it's 400 bad_recipient (design §5). */+export const badRecipientFix = (name: string | null) =>+ `Couldn’t send it: ${name ? `${name} isn’t in this space` : 'That bot isn’t in this space'}. Pick another bot and press Fix it again.`;+/** Line notes' 400 bad_recipient (design §5). */+export const badRecipientNotes = (name: string | null) =>+ `The notes didn’t send: ${name ? `${name} isn’t in this space` : 'That bot isn’t in this space'}. Pick another bot.`;+/** Line notes with no default bot (design §7). */+export const noDefaultNotes = (login: string | null) =>+ `This PR is by ${login ?? 'a person'} and no team owns this repo, so notes have no default bot. Pick one when you send, or add the repo to a team (Manage team › Git Repo).`;++// ---- The pick, per card, in sessionStorage (design §1) ----++export const pickKey = (cardId: string) => `kwnt:fix-to:${cardId}`;++function store(): Storage | null {+ try {+ return typeof sessionStorage === 'undefined' ? null : sessionStorage;+ } catch {+ return null;+ }+}++export function loadPick(cardId: string): RecipientBot | null {+ try {+ const raw = store()?.getItem(pickKey(cardId));+ if (!raw) return null;+ const v = JSON.parse(raw) as unknown;+ if (!v || typeof v !== 'object') return null;+ const o = v as Record<string, unknown>;+ return typeof o.id === 'string' && typeof o.name === 'string' ? { id: o.id, name: o.name, ...(typeof o.team === 'string' ? { team: o.team } : {}) } : null;+ } catch {+ return null;+ }+}++export function savePick(cardId: string, pick: RecipientBot | null): void {+ try {+ const s = store();+ if (!s) return;+ if (pick) s.setItem(pickKey(cardId), JSON.stringify(pick));+ else s.removeItem(pickKey(cardId));+ } catch {+ /* private mode: the pick lasts until the card unmounts */+ }+}++/** "The picker has been shown on this card", kept beside the pick so a reload keeps sending `to` (N1). */+export const shownKey = (cardId: string) => `kwnt:fix-to-shown:${cardId}`;++export function loadShown(cardId: string): boolean {+ try {+ return store()?.getItem(shownKey(cardId)) === '1';+ } catch {+ return false;+ }+}++export function saveShown(cardId: string): void {+ try {+ store()?.setItem(shownKey(cardId), '1');+ } catch {+ /* private mode: it lasts until the card unmounts */+ }+}++/** A stored pick holds only while the bot is still in the list; picking the default is no pick. */+export function keepPick(pick: RecipientBot | null, r: DevRecipients | null): RecipientBot | null {+ if (!pick || !r) return pick;+ const b = r.bots.find((x) => x.id === pick.id);+ if (!b) return null;+ if (r.default && r.default.id === b.id) return null;+ return b;+}diff --git a/frontend/src/dev/types.ts b/frontend/src/dev/types.tsindex 537917aa..75603816 100644--- a/frontend/src/dev/types.ts+++ b/frontend/src/dev/types.ts@@ -96,6 +96,10 @@ export interface DevFinding {sent_at: string | null;/** §3.6 item 4. */sent_to: string | null;+ /** Fix it "Send to…" (#609): how the bot was picked; `chosen` when the person picked it. */+ sent_via?: 'author' | 'team_lead' | 'chosen';+ /** #609: the chosen bot's id (only with `sent_via: 'chosen'`). */+ sent_to_id?: string | null;task_id: string | null;send_error: string | null;dismissed: { reason: DismissReason; note: string; by: string; at: string | null } | null;@@ -225,7 +229,7 @@ export interface BackupResult {// ---- Props (agreed with Pixel through this file) -----export type FindingAction = { action: 'fix' } | { action: 'undo_fix' } | { action: 'dismiss'; reason: DismissReason; note?: string };+export type FindingAction = { action: 'fix'; to?: string } | { action: 'undo_fix' } | { action: 'dismiss'; reason: DismissReason; note?: string };export interface RollupProps {rollup: DevRollup;@@ -282,6 +286,48 @@ export interface ReviewCardProps {lineNotes?: import('./lineNotesApi').LineNotesApi;/** 0.9.0 G1: "Open {bot}'s chat" after a send. */onOpenChat?: (botId: string) => void;+ /** Fix it "Send to…" (#609): `GET /api/dev/cards/:id/recipients`. Without it there is no "Goes to" line and+ * Fix it sends to the server's default, as before. */+ recipients?: (cardId: string) => Promise<DevRecipients>;+ /** #609: "Open task ›" after the Undo window (App's pending task). Without it the link hides. */+ onOpenTask?: (taskId: string) => void;+}++// ---- Fix it "Send to…" (#609, impl.md "API for Mira and Iris" §1) ----++export type RecipientVia = 'author' | 'team_lead';+export interface RecipientBot {+ id: string;+ name: string;+ team?: string;+}+export interface RecipientDefault extends RecipientBot {+ via: RecipientVia;+}+export interface DevRecipients {+ default: RecipientDefault | null;+ nobody: string | null;+ bots: RecipientBot[];+}++/** The `/recipients` answer, or null when it isn't one. A bot without an id or name is skipped. */+export function parseRecipients(v: unknown): DevRecipients | null {+ if (!isObj(v) || !Array.isArray(v.bots)) return null;+ const bot = (b: unknown): RecipientBot | null => {+ if (!isObj(b)) return null;+ const id = str(b.id, 200);+ const name = str(b.name, 80);+ if (!id || !name) return null;+ const team = str(b.team, 80);+ return team ? { id, name, team } : { id, name };+ };+ const d = isObj(v.default) ? bot(v.default) : null;+ const via = isObj(v.default) && v.default.via === 'author' ? 'author' : 'team_lead';+ return {+ default: d ? { ...d, via } : null,+ nobody: str(v.nobody, 400),+ bots: v.bots.map(bot).filter((b): b is RecipientBot => !!b),+ };}export interface ReleaseNotesSheetProps {@@ -397,6 +443,8 @@ export function finding(v: unknown): DevFinding | null {state: oneOf(v.state, ['open', 'sent', 'dismissed'] as const, 'open'),sent_at: str(v.sent_at, 64),sent_to: str(v.sent_to, 80),+ ...(v.sent_via === 'author' || v.sent_via === 'team_lead' || v.sent_via === 'chosen' ? { sent_via: v.sent_via } : {}),+ ...(str(v.sent_to_id, 200) ? { sent_to_id: str(v.sent_to_id, 200) } : {}),task_id: str(v.task_id, 80),send_error: str(v.send_error, 200),dismissed: ddiff --git a/frontend/src/devMode.ts b/frontend/src/devMode.tsindex 0da336d1..09a30d1b 100644--- a/frontend/src/devMode.ts+++ b/frontend/src/devMode.ts@@ -1219,7 +1219,9 @@ export const devApi = {/** Flow F6 (Juno): the person opened the Dev desk, so new_reviews goes back to 0 on every device. */deskSeen: (space: string) => call<unknown>(`/api/spaces/${enc(space)}/dev_mode/seen`, 'POST').then((r) => r.data),reviews: (space: string, repo?: string | null) => call<unknown>(`/api/spaces/${enc(space)}/dev/reviews${repo ? `?repo=${enc(repo)}` : ''}`).then((r) => r.data),- finding: (card: string, fid: string, body: { action: string; reason?: string; note?: string }) =>+ /** #609: who Fix it and line notes on this card can go to (raw; `parseRecipients` in dev/types.ts). */+ recipients: (card: string) => call<unknown>(`/api/dev/cards/${enc(card)}/recipients`).then((r) => r.data),+ finding: (card: string, fid: string, body: { action: string; reason?: string; note?: string; to?: string }) =>call<unknown>(`/api/dev/cards/${enc(card)}/findings/${enc(fid)}`, 'POST', body).then((r) => r.data),/** 0.7.1 Post to {Forge}: one PR review from this card. 200 with the card, `post_error` set when the forge refused. */post: (card: string) => call<unknown>(`/api/dev/cards/${enc(card)}/post`, 'POST', {}).then((r) => r.data),diff --git a/frontend/src/styles/modern.css b/frontend/src/styles/modern.cssindex ecffcb4e..7d1ec5f1 100644--- a/frontend/src/styles/modern.css+++ b/frontend/src/styles/modern.css@@ -1020,3 +1020,11 @@ button.dv-sha { cursor: copy; } button.dv-sha:hover { color: var(--accent); bord@media (prefers-reduced-motion: no-preference) {.kw-pin-enter { animation: kw-pin-enter 160ms ease-out; }}++/* Fix it "Send to…" (#609, design §8): the picker's popover and phone sheet. Static under reduced motion. */+@keyframes kw-st-pop { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: none; } }+@keyframes kw-st-sheet { from { transform: translateY(100%); } to { transform: none; } }+@media (prefers-reduced-motion: no-preference) {+ .kw-st-pop { animation: kw-st-pop 140ms ease-out both; }+ .kw-st-sheet { animation: kw-st-sheet 180ms ease-out both; }+}diff --git a/frontend/tests/fixItSendTo.test.mjs b/frontend/tests/fixItSendTo.test.mjsnew file mode 100644index 00000000..b913a4f4--- /dev/null+++ b/frontend/tests/fixItSendTo.test.mjs@@ -0,0 +1,643 @@+// Fix it "Send to…" (Mira, autonomy/fix-it-send-to/design.md; Juno's #609 /recipients API). The pure helpers,+// the review card's "Goes to" line, picker and Fix it, and the line-notes bar, against fake routes.+// Demo data only (bots Ana, Ben, Cy, Mo; team Edge); no network.+import assert from 'node:assert/strict';+import test from 'node:test';+import { JSDOM } from 'jsdom';+import { loadBundled } from './bundle.mjs';++const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/s/spc_demo', pretendToBeVisual: true });+const g = globalThis;+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLButtonElement', 'HTMLTextAreaElement', 'HTMLInputElement', 'Element', 'Node', 'Event', 'CustomEvent', 'MouseEvent', 'KeyboardEvent', 'FocusEvent', 'PointerEvent', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'localStorage', 'sessionStorage', 'CSS']) {+ if (!(k in dom.window)) continue;+ Object.defineProperty(g, k, { value: dom.window[k], configurable: true, writable: true });+}+if (!g.CSS) g.CSS = { escape: (s) => String(s).replace(/["\\]/g, '\\$&') };+g.IS_REACT_ACT_ENVIRONMENT = false;++const m = await loadBundled(`+ export { default as React } from 'react';+ export { createRoot } from 'react-dom/client';+ export * from './src/dev/recipients';+ export { parseRecipients, parseReview, finding } from './src/dev/types';+ export { sendLabel, parseChanges, parseNote } from './src/dev/lineNotes';+ export { LineNotesError } from './src/dev/lineNotesApi';+ export { ReviewCard } from './src/components/dev/ReviewCard';+ export { ChangesSection } from './src/components/dev/LineNotes';+ export * as fx from './src/dev/fixtures';+`);+const { React, createRoot } = m;+const h = React.createElement;+const settle = async (n = 12) => {+ for (let i = 0; i < n; i++) await new Promise((r) => setTimeout(r, 0));+};+const $ = (s) => document.querySelector(s);+const $$ = (s) => [...document.querySelectorAll(s)];+const click = (el) => el.dispatchEvent(new window.MouseEvent('click', { bubbles: true }));+const key = (el, k) => el.dispatchEvent(new window.KeyboardEvent('keydown', { key: k, bubbles: true }));++// ---------------------------------------------------------------------------------------------------+// Demo data++const ANA = { id: 'bot_ana', name: 'Ana', team: 'Edge' };+const BEN = { id: 'bot_ben', name: 'Ben', team: 'Edge' };+const CY = { id: 'bot_cy', name: 'Cy' };+const MO = { id: 'bot_mo', name: 'Mo', team: 'Ops' };+const LEAD = { default: { ...ANA, via: 'team_lead' }, nobody: null, bots: [ANA, BEN, CY, MO] };+const AUTHOR = { default: { id: 'bot_pixel', name: 'Pixel', via: 'author' }, nobody: null, bots: [{ id: 'bot_pixel', name: 'Pixel' }, ANA, BEN] };+const NONE = { default: null, nobody: null, bots: [ANA, BEN, CY] };+const EMPTY = { default: null, nobody: 'There’s no bot in this space to send it to. Add one in Manage team.', bots: [] };++const rec = (raw) => m.parseRecipients(raw);++// ---------------------------------------------------------------------------------------------------+// Pure helpers++test('whyLabel: wrote it, lead of the team, your pick', () => {+ assert.equal(m.whyLabel(rec(AUTHOR).default, null), 'wrote it');+ assert.equal(m.whyLabel(rec(LEAD).default, null), 'lead of Edge');+ assert.equal(m.whyLabel(rec(LEAD).default, BEN), 'your pick');+ assert.equal(m.whyLabel(rec(LEAD).default, ANA), 'lead of Edge', 'picking the default is no pick');+ assert.equal(m.whyLabel(null, null), null);+ assert.equal(m.whyLabel(null, CY), 'your pick');+});++test('rowMeta and pickerRows: the default pinned first, its team owns the repo', () => {+ const r = rec({ ...LEAD, bots: [BEN, CY, ANA, MO] });+ assert.deepEqual(m.pickerRows(r).map((b) => b.name), ['Ana', 'Ben', 'Cy', 'Mo']);+ assert.equal(m.rowMeta(ANA, r.default), 'Default · lead of Edge, which owns this repo');+ assert.equal(m.rowMeta(BEN, r.default), 'Edge · owns this repo');+ assert.equal(m.rowMeta(MO, r.default), 'Ops');+ assert.equal(m.rowMeta(CY, r.default), null);+ assert.equal(m.rowMeta({ id: 'bot_pixel', name: 'Pixel' }, rec(AUTHOR).default), 'Default · wrote it');+ assert.deepEqual(m.pickerRows(rec(NONE)).map((b) => b.name), ['Ana', 'Ben', 'Cy']);+});++test('filterBots matches name or team, any case; noMatch quotes the query', () => {+ assert.deepEqual(m.filterBots([ANA, BEN, CY, MO], 'edge').map((b) => b.name), ['Ana', 'Ben']);+ assert.deepEqual(m.filterBots([ANA, BEN, CY, MO], ' mO ').map((b) => b.name), ['Mo']);+ assert.equal(m.filterBots([ANA], '').length, 1);+ assert.equal(m.noMatch(' xyz '), 'No bot matches "xyz".');+});++test('keepPick drops a pick that left the list, and a pick of the default', () => {+ const r = rec(LEAD);+ assert.deepEqual(m.keepPick(BEN, r), BEN);+ assert.equal(m.keepPick({ id: 'bot_gone', name: 'Gone' }, r), null);+ assert.equal(m.keepPick(ANA, r), null);+ assert.equal(m.keepPick(null, r), null);+});++test('parseRecipients skips bad rows and reads the default', () => {+ const r = m.parseRecipients({ default: { id: 'bot_ana', name: 'Ana', via: 'team_lead', team: 'Edge' }, nobody: null, bots: [ANA, { id: 'x' }, 3, BEN] });+ assert.equal(r.default.via, 'team_lead');+ assert.equal(r.default.team, 'Edge');+ assert.deepEqual(r.bots.map((b) => b.id), ['bot_ana', 'bot_ben']);+ assert.equal(m.parseRecipients({ nope: 1 }), null);+ assert.equal(m.parseRecipients({ default: null, nobody: 'No bots.', bots: [] }).nobody, 'No bots.');+});++test('a finding reads sent_via and sent_to_id', () => {+ const f = m.finding({ id: 'f1', severity: 'high', title: 'x', state: 'sent', sent_to: 'Ben', sent_to_id: 'bot_ben', sent_via: 'chosen', task_id: 'tsk_1' });+ assert.equal(f.sent_via, 'chosen');+ assert.equal(f.sent_to_id, 'bot_ben');+});++test('the copy: bad recipient lines, the no-default banner, the send label', () => {+ assert.equal(m.badRecipientFix('Mo'), 'Couldn’t send it: Mo isn’t in this space. Pick another bot and press Fix it again.');+ assert.equal(m.badRecipientFix(null), 'Couldn’t send it: That bot isn’t in this space. Pick another bot and press Fix it again.');+ assert.equal(m.badRecipientNotes('Mo'), 'The notes didn’t send: Mo isn’t in this space. Pick another bot.');+ assert.match(m.noDefaultNotes('sam'), /^This PR is by sam and no team owns this repo, so notes have no default bot\./);+ assert.equal(m.sendLabel(2, 'Ana'), 'Send 2 notes to Ana');+ assert.equal(m.sendLabel(2, null), 'Send 2 notes…');+ assert.equal(m.sendLabel(1, null), 'Send note…');+ assert.equal(m.goesLabel('Ana', 'lead of Edge'), 'Fixes go to Ana, lead of Edge. Change');+});++// ---------------------------------------------------------------------------------------------------+// The review card++const RAW = m.fx.REVIEW_294; // f1 and f3 open, f2 sent+const CARD = m.parseReview(RAW);+let root = null;+let host = null;++function fakeRoutes({ list = LEAD, fail = false } = {}) {+ const s = { list, fail, gets: 0, acts: [], throwOnce: null, reply: null };+ const recipients = async () => {+ s.gets++;+ if (s.fail) throw new Error('offline');+ const r = m.parseRecipients(s.list);+ return r;+ };+ const onFinding = async (cardId, fid, action) => {+ s.acts.push({ fid, action });+ if (s.throwOnce) {+ const e = s.throwOnce;+ s.throwOnce = null;+ throw e;+ }+ const to = action.to ? s.list.bots.find((b) => b.id === action.to) : s.list.default;+ return s.reply ?? { ...CARD, findings: CARD.findings.map((f) => (f.id === fid ? { ...f, state: 'sent', sent_to: to?.name ?? 'Pixel', sent_at: '2026-11-05T00:59:59Z', task_id: 'tsk_9' } : f)) };+ };+ return { s, recipients, onFinding };+}++async function card(props) {+ if (root) root.unmount();+ host?.remove();+ host = document.createElement('div');+ document.body.appendChild(host);+ root = createRoot(host);+ root.render(h(m.ReviewCard, { card: CARD, now: m.fx.FIXTURE_NOW, ...props }));+ await settle();+}+const rerender = async (props) => {+ root.render(h(m.ReviewCard, { card: CARD, now: m.fx.FIXTURE_NOW, ...props }));+ await settle();+};+const goes = (fid) => $(`[data-finding="${fid}"] [data-goes-to]`);+const fixBtn = (fid) => $(`[data-finding="${fid}"] [data-fix-it]`);+const errLine = (fid) => $(`[data-finding="${fid}"] .text-bad`)?.textContent ?? null;++test('1. the default line: wrote it, lead of Edge, and no default', async () => {+ sessionStorage.clear();+ let r = fakeRoutes({ list: AUTHOR });+ await card({ recipients: r.recipients, onFinding: r.onFinding });+ assert.equal(goes('f1').dataset.goesTo, 'author');+ assert.match(goes('f1').textContent, /Goes to\s*Pixel\s*· wrote it/);+ assert.equal(goes('f1').getAttribute('aria-label'), 'Fixes go to Pixel, wrote it. Change');+ assert.equal(goes('f1').getAttribute('aria-haspopup'), 'listbox');+ assert.ok(!goes('f2'), 'a sent finding has no line');++ r = fakeRoutes({ list: LEAD });+ await card({ recipients: r.recipients, onFinding: r.onFinding });+ assert.match(goes('f1').textContent, /Ana\s*· lead of Edge/);+ assert.equal(r.s.gets, 1, 'fetched once per card, not per finding');++ r = fakeRoutes({ list: NONE });+ await card({ recipients: r.recipients, onFinding: r.onFinding });+ assert.equal(goes('f1').dataset.goesTo, 'none');+ assert.match(goes('f1').textContent, /No default bot\s*·\s*Pick who fixes it/);++ r = fakeRoutes({ list: EMPTY });+ await card({ recipients: r.recipients, onFinding: r.onFinding });+ assert.equal(goes('f1').dataset.goesTo, 'nobody');+ assert.ok(fixBtn('f1').disabled, 'no bot at all: Fix it is off');+ assert.equal(fixBtn('f1').title, EMPTY.nobody);+});++test('2. a pick persists and covers a second finding; to is sent with it', async () => {+ sessionStorage.clear();+ const r = fakeRoutes();+ await card({ recipients: r.recipients, onFinding: r.onFinding });+ click(goes('f1'));+ await settle();+ const picker = $('[data-recipient-picker]');+ assert.ok(picker, 'the picker opens');+ assert.equal(goes('f1').getAttribute('aria-expanded'), 'true');+ assert.match(picker.textContent, /Who fixes this PR\?/);+ assert.ok(!picker.querySelector('input'), 'no search with 8 bots or fewer');+ const opts = $$('[role="option"]');+ assert.deepEqual(opts.map((o) => o.dataset.bot), ['bot_ana', 'bot_ben', 'bot_cy', 'bot_mo']);+ assert.equal(opts[0].getAttribute('aria-selected'), 'true', 'the default is selected');+ // Keyboard: down to Ben, Enter picks.+ const list = $('[role="listbox"]');+ key(list, 'ArrowDown');+ await settle();+ key(list, 'Enter');+ await settle();+ assert.ok(!$('[data-recipient-picker]'), 'picking closes the picker');+ assert.equal(r.s.acts.length, 0, 'picking never sends');+ assert.match($('[data-send-to-say]').textContent, /Fixes go to Ben/);+ assert.match(goes('f1').textContent, /Ben\s*· your pick/);+ assert.match(goes('f3').textContent, /Ben\s*· your pick/, 'the pick covers every finding on the card');+ assert.deepEqual(JSON.parse(sessionStorage.getItem('kwnt:fix-to:dvr_294')), BEN);++ click(fixBtn('f3'));+ await settle();+ assert.deepEqual(r.s.acts[0], { fid: 'f3', action: { action: 'fix', to: 'bot_ben' } });+ assert.match($('[data-finding="f3"]').textContent, /Sent to Ben as a task/);++ // A new mount of the same card keeps the pick.+ const r2 = fakeRoutes();+ await card({ recipients: r2.recipients, onFinding: r2.onFinding });+ assert.match(goes('f1').textContent, /Ben\s*· your pick/);+});++test('3. Fix it with no default and no pick opens the picker, and sends after a pick and a second press', async () => {+ sessionStorage.clear();+ const r = fakeRoutes({ list: NONE });+ await card({ recipients: r.recipients, onFinding: r.onFinding });+ click(fixBtn('f1'));+ await settle();+ assert.ok($('[data-recipient-picker]'), 'the picker opens');+ assert.equal(r.s.acts.length, 0, 'nothing sent');+ assert.match($('[data-picker-footer]').textContent, /no team owns/);+ click($('[data-bot="bot_cy"]'));+ await settle();+ assert.equal(r.s.acts.length, 0, 'the pick alone doesn’t send');+ click(fixBtn('f1'));+ await settle();+ assert.deepEqual(r.s.acts[0].action, { action: 'fix', to: 'bot_cy' });+});++test('4. to is sent only with a pick until the picker shows; picking the default clears the pick', async () => {+ sessionStorage.clear();+ const r = fakeRoutes();+ await card({ recipients: r.recipients, onFinding: r.onFinding });+ click(fixBtn('f1'));+ await settle();+ assert.deepEqual(r.s.acts[0].action, { action: 'fix' });++ sessionStorage.setItem('kwnt:fix-to:dvr_294', JSON.stringify(BEN));+ const r2 = fakeRoutes();+ await card({ recipients: r2.recipients, onFinding: r2.onFinding });+ click(goes('f1'));+ await settle();+ click($('[data-bot="bot_ana"]'));+ await settle();+ assert.equal(sessionStorage.getItem('kwnt:fix-to:dvr_294'), null);+ click(fixBtn('f1'));+ await settle();+ // The picker was shown, so the press to the default names it (N1).+ assert.deepEqual(r2.s.acts[0].action, { action: 'fix', to: 'bot_ana' });+});++test('N1: once the picker has shown (or a finding went to a chosen bot), every Fix it press sends to', async () => {+ // The pure rule.+ const L = m.parseRecipients(LEAD);+ assert.equal(m.toFor(L, null, false), undefined, 'one tap to the default, picker never shown: no to');+ assert.equal(m.toFor(L, BEN, false), 'bot_ben');+ assert.equal(m.toFor(L, null, true), 'bot_ana', 'shown: the default is named');+ assert.equal(m.toFor(L, BEN, true), 'bot_ben');+ assert.equal(m.toFor(m.parseRecipients(NONE), null, true), undefined, 'nobody to name');+ assert.equal(m.toFor(null, BEN, true), 'bot_ben', 'list failed: the stored pick still goes');++ // Pick Ben, Fix it f1; then back to the default and Fix it f3 while f1 may still be waiting: f3 names Ana.+ sessionStorage.clear();+ const r = fakeRoutes();+ await card({ recipients: r.recipients, onFinding: r.onFinding });+ click(goes('f1'));+ await settle();+ click($('[data-bot="bot_ben"]'));+ await settle();+ assert.equal(sessionStorage.getItem('kwnt:fix-to-shown:dvr_294'), '1');+ click(fixBtn('f1'));+ await settle();+ assert.deepEqual(r.s.acts[0].action, { action: 'fix', to: 'bot_ben' });+ click(goes('f3'));+ await settle();+ click($('[data-bot="bot_ana"]'));+ await settle();+ click(fixBtn('f3'));+ await settle();+ assert.deepEqual(r.s.acts[1].action, { action: 'fix', to: 'bot_ana' });++ // A reload of the card keeps it: no pick, but the picker was shown here, so the one tap names the default.+ const r2 = fakeRoutes();+ await card({ recipients: r2.recipients, onFinding: r2.onFinding });+ click(fixBtn('f1'));+ await settle();+ assert.deepEqual(r2.s.acts[0].action, { action: 'fix', to: 'bot_ana' });++ // A fresh tab that never showed the picker, on a card with a finding already sent to a chosen bot.+ sessionStorage.clear();+ const chosen = { ...CARD, findings: CARD.findings.map((f) => (f.id === 'f2' ? { ...f, sent_via: 'chosen', sent_to_id: 'bot_ben' } : f)) };+ const r3 = fakeRoutes();+ await card({ card: chosen, recipients: r3.recipients, onFinding: r3.onFinding });+ click(fixBtn('f1'));+ await settle();+ assert.deepEqual(r3.s.acts[0].action, { action: 'fix', to: 'bot_ana' });++ // Line notes follow the same rule: shown on the card, the default is named on send.+ const n = notesApi(changes({ author_bot: { id: 'bot_ana', name: 'Ana' } }));+ await notes({ api: n.api, sendTo: sendTo(LEAD, { pinned: true }) });+ click($('[data-ln-send]'));+ await settle();+ assert.deepEqual(n.s.sends[0], { ids: null, to: 'bot_ana' });+});++test('5. bad_recipient: plain words, the list refetched, the pick back to the default', async () => {+ sessionStorage.setItem('kwnt:fix-to:dvr_294', JSON.stringify(MO));+ const r = fakeRoutes();+ await card({ recipients: r.recipients, onFinding: r.onFinding });+ assert.match(goes('f1').textContent, /Mo\s*· your pick/);+ r.s.throwOnce = Object.assign(new Error('to: no such bot in this space'), { status: 400, code: 'bad_recipient' });+ r.s.list = { ...LEAD, bots: [ANA, BEN, CY] };+ click(fixBtn('f1'));+ await settle();+ assert.equal(errLine('f1'), 'Couldn’t send it: Mo isn’t in this space. Pick another bot and press Fix it again.');+ assert.equal(r.s.gets, 2, 'refetched');+ assert.match(goes('f1').textContent, /Ana\s*· lead of Edge/);+ assert.equal(sessionStorage.getItem('kwnt:fix-to:dvr_294'), null);+});++test('6. a chosen bot deleted in the Undo window: the server’s send_error shows, the list is refetched', async () => {+ sessionStorage.setItem('kwnt:fix-to:dvr_294', JSON.stringify(BEN));+ const r = fakeRoutes();+ await card({ recipients: r.recipients, onFinding: r.onFinding });+ r.s.list = { ...LEAD, bots: [ANA, CY, MO] };+ const back = { ...CARD, findings: CARD.findings.map((f) => (f.id === 'f1' ? { ...f, state: 'open', send_error: 'Ben was removed from this space before the task started.' } : f)) };+ await rerender({ card: back, recipients: r.recipients, onFinding: r.onFinding });+ assert.equal(errLine('f1'), 'Couldn’t send it: Ben was removed from this space before the task started.');+ assert.equal(r.s.gets, 2, 'refetched');+ assert.match(goes('f1').textContent, /Ana\s*· lead of Edge/, 'the pick is gone, so the default');+});++test('7. Open task › after the Undo window, when the finding has a task', async () => {+ sessionStorage.clear();+ const r = fakeRoutes();+ const opened = [];+ const sent = { ...CARD, findings: CARD.findings.map((f) => (f.id === 'f1' ? { ...f, state: 'sent', sent_to: 'Ben', sent_at: '2026-11-05T00:50:00Z', task_id: 'tsk_7' } : f)) };+ await card({ card: sent, recipients: r.recipients, onFinding: r.onFinding, onOpenTask: (id) => opened.push(id) });+ const b = $('[data-finding="f1"] [data-open-task]');+ assert.ok(b);+ assert.equal(b.textContent, 'Open task ›');+ click(b);+ assert.deepEqual(opened, ['tsk_7']);+ assert.ok(!$('[data-finding="f2"] [data-open-task]'), 'no task id, no link');+});++test('8. the list fails: Try again shows, and Fix it still sends without to', async () => {+ sessionStorage.clear();+ const r = fakeRoutes({ fail: true });+ await card({ recipients: r.recipients, onFinding: r.onFinding });+ assert.equal(goes('f1').dataset.goesTo, 'failed');+ assert.match(goes('f1').textContent, /Goes to the PR’s usual bot · couldn’t load the list/);+ click(fixBtn('f1'));+ await settle();+ assert.deepEqual(r.s.acts[0].action, { action: 'fix' });+ r.s.fail = false;+ click(goes('f3').querySelector('button'));+ await settle();+ assert.match(goes('f3').textContent, /Ana\s*· lead of Edge/);+});++test('loading: a static skeleton, and Fix it is enabled', async () => {+ sessionStorage.clear();+ let release;+ const recipients = () => new Promise((res) => (release = res));+ const acts = [];+ await card({ recipients, onFinding: async (_c, fid, action) => (acts.push(action), CARD) });+ assert.equal(goes('f1').dataset.goesTo, 'loading');+ assert.ok(!fixBtn('f1').disabled);+ click(fixBtn('f1'));+ await settle();+ assert.deepEqual(acts[0], { action: 'fix' });+ release(rec(LEAD));+ await settle();+});++test('no recipients route (an older server or the sample card): no line, Fix it as before', async () => {+ const acts = [];+ await card({ onFinding: async (_c, fid, action) => (acts.push(action), CARD) });+ assert.ok(!goes('f1'));+ click(fixBtn('f1'));+ await settle();+ assert.deepEqual(acts[0], { action: 'fix' });+});++test('the picker: Esc closes and gives focus back; search shows from 9 bots and filters', async () => {+ sessionStorage.clear();+ const many = Array.from({ length: 9 }, (_, i) => ({ id: `bot_${i}`, name: ['Ana', 'Ben', 'Cy', 'Dot', 'Juno', 'Mo', 'Pia', 'Rex', 'Sol'][i], team: i < 3 ? 'Edge' : 'Ops' }));+ const r = fakeRoutes({ list: { default: { ...many[0], via: 'team_lead' }, nobody: null, bots: many } });+ await card({ recipients: r.recipients, onFinding: r.onFinding });+ const trigger = goes('f1');+ click(trigger);+ await settle();+ const input = $('[data-recipient-picker] input');+ assert.ok(input, 'search with more than 8 bots');+ assert.equal(document.activeElement, input);+ const set = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;+ set.call(input, 'ops');+ input.dispatchEvent(new window.Event('input', { bubbles: true }));+ await settle();+ assert.equal($$('[role="option"]').length, 6);+ set.call(input, 'zzz');+ input.dispatchEvent(new window.Event('input', { bubbles: true }));+ await settle();+ assert.equal($('[data-picker-empty]').textContent, 'No bot matches "zzz".');+ key(input, 'Escape');+ await settle();+ assert.ok(!$('[data-recipient-picker]'));+ assert.equal(document.activeElement, trigger, 'focus back on the trigger');+});++// ---------------------------------------------------------------------------------------------------+// Line notes++const HEAD = 'c3d9a18f00000000000000000000000000000000';+const changes = (over = {}) => ({+ card_id: 'dvr_31',+ repo: 'demo-org/edge',+ pr: 31,+ head_sha: HEAD,+ pr_url: 'https://github.com/demo-org/edge/pull/31',+ pr_state: 'open',+ author_bot: null,+ author_login: 'sam',+ files: [{ path: 'src/a.rs', status: 'modified', additions: 1, deletions: 0, hunks: [{ header: '@@ -1 +1 @@', lines: [{ kind: 'add', new: 1, text: 'let a = 1;' }] }] }],+ ...over,+});+const note = (id) => ({ id, path: 'src/a.rs', start: { side: 'new', line: 1 }, end: { side: 'new', line: 1 }, at_head: { start: { side: 'new', line: 1 }, end: { side: 'new', line: 1 } }, code: [], text: 'Name it.', state: 'draft', head_sha: HEAD, created_at: '2026-11-10T09:12:00Z', seen_sha: null });++function notesApi(c) {+ const s = { sends: [], fail: null };+ const api = {+ changes: async () => m.parseChanges(c),+ notes: async () => ({ notes: [m.parseNote(note('ln_1')), m.parseNote(note('ln_2'))], summary: null }),+ send: async (cardId, sendId, ids, to) => {+ s.sends.push({ ids: ids ?? null, to: to ?? null });+ if (s.fail) {+ const e = s.fail;+ s.fail = null;+ throw e;+ }+ return { sent: 2, message_id: 'msg_1', kwant_id: to ?? 'bot_ana', kwant_name: to === 'bot_ben' ? 'Ben' : 'Ana', sent_at: '2026-11-10T09:30:00Z', notes: [] };+ },+ };+ return { api, s };+}+const sendTo = (r, over = {}) => {+ const st = { load: { s: 'ready', r: rec(r) }, pick: null, phone: false, anchor: null, opened: [], resets: 0, ...over };+ st.open = (el, after) => st.opened.push({ el, after });+ st.retry = () => {};+ st.reset = () => st.resets++;+ st.refresh = () => {};+ return st;+};+async function notes(props) {+ if (root) root.unmount();+ host?.remove();+ host = document.createElement('div');+ document.body.appendChild(host);+ root = createRoot(host);+ root.render(h(m.ChangesSection, { cardId: 'dvr_31', stat: { files: 1, additions: 1, deletions: 0 }, defaultOpen: true, phone: false, ...props }));+ await settle();+}++test('9. line notes with no author bot but bots in the space: allowed, Pick a bot, then send with to', async () => {+ const { api, s } = notesApi(changes());+ const st = sendTo(NONE);+ await notes({ api, sendTo: st });+ assert.ok($('[data-ln-no-default]'), 'the new banner');+ assert.match($('[data-ln-no-default]').textContent, /^This PR is by sam and no team owns this repo/);+ assert.ok($('[data-ln-bar]'), 'notes can be sent');+ assert.equal($('[data-ln-to]').dataset.lnTo, 'none');+ assert.match($('[data-ln-to]').textContent, /Pick a bot/);+ const send = $('[data-ln-send]');+ assert.match(send.textContent, /Send 2 notes…/);+ click(send);+ await settle();+ assert.equal(s.sends.length, 0, 'opens the picker instead');+ assert.equal(st.opened.length, 1);+ st.opened[0].after(BEN);+ await settle();+ assert.deepEqual(s.sends[0], { ids: null, to: 'bot_ben' });+ assert.match($('[data-ln-bar]').textContent, /Sent 2 notes to Ben/);++ // Without the list (an older server), author_bot null still means no notes.+ const old = notesApi(changes());+ await notes({ api: old.api });+ assert.ok(!$('[data-ln-bar]'));+ assert.ok(!$('[data-ln-no-default]'));+});++test('10. line notes: the default needs no to, a pick sends it, bad_recipient shows the bar', async () => {+ const { api, s } = notesApi(changes({ author_bot: { id: 'bot_ana', name: 'Ana' } }));+ await notes({ api, sendTo: sendTo(LEAD) });+ assert.match($('[data-ln-send]').textContent, /Send 2 notes to Ana/);+ assert.match($('[data-ln-to]').textContent, /Ana/);+ click($('[data-ln-send]'));+ await settle();+ assert.deepEqual(s.sends[0], { ids: null, to: null });++ const b = notesApi(changes({ author_bot: { id: 'bot_ana', name: 'Ana' } }));+ const st = sendTo(LEAD, { pick: MO });+ await notes({ api: b.api, sendTo: st });+ assert.match($('[data-ln-send]').textContent, /Send 2 notes to Mo/);+ b.s.fail = new m.LineNotesError('to: no such bot', 400, 'bad_recipient');+ click($('[data-ln-send]'));+ await settle();+ assert.deepEqual(b.s.sends[0], { ids: null, to: 'bot_mo' });+ assert.equal($('[data-ln-bar]').dataset.lnBar, 'bad');+ assert.match($('[data-ln-bad]').textContent, /The notes didn’t send: Mo isn’t in this space\. Pick another bot\./);+ assert.equal(st.resets, 1, 'refetch and drop the pick');+});++// ---------------------------------------------------------------------------------------------------+// Mira's design check (design-check.md fixes 1-3)++test('fix 1: scrolling the page under the trigger closes the popover, without refocusing; the list’s own scroll doesn’t', async () => {+ sessionStorage.clear();+ const r = fakeRoutes();+ await card({ recipients: r.recipients, onFinding: r.onFinding });+ click(goes('f1'));+ await settle();+ const list = $('[data-recipient-picker] [role="listbox"]');+ list.dispatchEvent(new window.Event('scroll'));+ await settle();+ assert.ok($('[data-recipient-picker]'), 'scrolling inside the list keeps it open');+ const trigger = goes('f1');+ document.dispatchEvent(new window.Event('scroll'));+ await settle();+ assert.ok(!$('[data-recipient-picker]'), 'page scroll closes it');+ await new Promise((res) => setTimeout(res, 5));+ assert.notEqual(document.activeElement, trigger, 'focus is not pulled back to the trigger');+ // an ancestor of the trigger scrolling closes it too+ click(goes('f1'));+ await settle();+ assert.ok($('[data-recipient-picker]'));+ host.dispatchEvent(new window.Event('scroll'));+ await settle();+ assert.ok(!$('[data-recipient-picker]'));+});++test('fix 2: no ring when the picker opens; with no default no row is active; arrows bring the ring, the pointer takes it away', async () => {+ sessionStorage.clear();+ const r = fakeRoutes({ list: NONE });+ await card({ recipients: r.recipients, onFinding: r.onFinding });+ click(goes('f1'));+ await settle();+ const list = $('[data-recipient-picker] [role="listbox"]');+ const ringed = () => $$('[role="option"]').filter((o) => o.className.includes('outline-sky-400/60')).map((o) => o.dataset.bot);+ const lit = () => $$('[role="option"]').filter((o) => o.className.includes('bg-white/[.07]')).map((o) => o.dataset.bot);+ assert.deepEqual(ringed(), []);+ assert.deepEqual(lit(), [], 'nothing preselected with no default');+ assert.equal(list.getAttribute('aria-activedescendant'), null);+ key(list, 'Enter');+ await settle();+ assert.ok($('[data-recipient-picker]'), 'Enter with nothing active does nothing');+ key(list, 'ArrowDown');+ await settle();+ assert.deepEqual(ringed(), ['bot_ana'], 'the first arrow goes to row 0, with the ring');+ $('[data-bot="bot_ben"]').dispatchEvent(new window.MouseEvent('pointermove', { bubbles: true }));+ await settle();+ assert.deepEqual(ringed(), [], 'the pointer takes the ring away');+ assert.deepEqual(lit(), ['bot_ben']);+ key(list, 'Escape');+ await settle();+ // with a default: it starts lit (its ✓ says chosen) but without the ring+ sessionStorage.clear();+ const r2 = fakeRoutes();+ await card({ recipients: r2.recipients, onFinding: r2.onFinding });+ click(goes('f1'));+ await settle();+ assert.deepEqual(lit(), ['bot_ana']);+ assert.deepEqual(ringed(), []);+});++test('fix 3: a send error waits for the list, and stays hidden when nobody can receive', async () => {+ sessionStorage.clear();+ const errCard = { ...CARD, findings: CARD.findings.map((f) => (f.id === 'f1' ? { ...f, state: 'open', send_error: 'Ben was removed from this space before the task started.' } : f)) };+ let release;+ const slow = () => new Promise((res) => (release = res));+ await card({ card: errCard, recipients: slow, onFinding: async () => errCard });+ assert.equal(goes('f1').dataset.goesTo, 'loading');+ assert.equal(errLine('f1'), null, 'hidden while the list loads');+ release(rec(LEAD));+ await settle();+ assert.equal(errLine('f1'), 'Couldn’t send it: Ben was removed from this space before the task started.');+ sessionStorage.clear();+ const r = fakeRoutes({ list: EMPTY });+ await card({ card: errCard, recipients: r.recipients, onFinding: r.onFinding });+ assert.ok(fixBtn('f1').disabled);+ assert.equal(errLine('f1'), null, 'nobody can receive: the disabled Fix it says why');+ // no recipients route at all: as before+ await card({ card: errCard, onFinding: async () => errCard });+ assert.match(errLine('f1'), /Ben was removed/);+});++test('fix 1: moving through the list never scrolls the page (that would close the popover)', async () => {+ sessionStorage.clear();+ const r = fakeRoutes();+ await card({ recipients: r.recipients, onFinding: r.onFinding });+ let calls = 0;+ const orig = window.HTMLElement.prototype.scrollIntoView;+ window.HTMLElement.prototype.scrollIntoView = function () { calls++; };+ try {+ click(goes('f1'));+ await settle();+ const list = $('[data-recipient-picker] [role="listbox"]');+ key(list, 'ArrowDown');+ await settle();+ key(list, 'End');+ await settle();+ assert.equal(calls, 0, 'no scrollIntoView: only the list scrolls');+ assert.ok($('[data-recipient-picker]'), 'still open');+ } finally {+ window.HTMLElement.prototype.scrollIntoView = orig;+ }+});++test('opening the desktop popover puts focus in it (once it is placed and visible)', async () => {+ sessionStorage.clear();+ const r = fakeRoutes();+ await card({ recipients: r.recipients, onFinding: r.onFinding });+ click(goes('f1'));+ await settle();+ const pop = $('[data-recipient-picker]');+ assert.ok(pop.style.visibility !== 'hidden', 'placed');+ assert.ok(pop.contains(document.activeElement), 'focus moved into the popover');+});