Skip to content

armgit / kwant

Public Imported from GitHub
0

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

0.9.0 G1: line notes on a diff (frontend) (#488)

Oleksandr Ivanchenko68730cbd5ce7
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index a09179a3..7ab53942 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -4040,7 +4040,7 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({
}}
/>
);
- 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 }))} />;
+ 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 }))} onOpenChat={(id) => { 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.tsx
index ca5995a1..b018a55b 100644
--- a/frontend/src/components/DevDesk.tsx
+++ b/frontend/src/components/DevDesk.tsx
@@ -14,6 +14,11 @@ import { siteOrigins } from '../dev/tickets';
import { openGitHubConnect } from './GitHubConnect';
import { JiraHint, useJira } from './JiraSettings';
import { deskBadge } from '../dev/jiraSetup';
+import { fetchCaller, lineNotesApi } from '../dev/lineNotesApi';
+import { personFetch } from '../auth';
+
+/** 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)));
/** App re-sends the `dev_card` SSE as this window event: detail `{space_id, id, kind, status}`. */
export const DEV_CARD_EVENT = 'kwant:dev-card';
@@ -210,9 +215,11 @@ export interface DevDeskViewProps {
teams?: DevTeamRef[];
/** 0.7.6: the space's bots, so a ticket's work reads "Built by Ann and Ben", not ids. */
bots?: { id: string; name: string }[];
+ /** 0.9.0 G1: "Open {bot}'s chat" after line notes are sent: opens that bot's 1:1. */
+ onOpenChat?: (botId: string) => void;
}
-export const DevDeskView: React.FC<DevDeskViewProps> = ({ spaceId, onBack, onSaveToNotion, initialTab = 'landed', now, onOpenLooseEnds, teams, bots }) => {
+export const DevDeskView: React.FC<DevDeskViewProps> = ({ spaceId, onBack, onSaveToNotion, initialTab = 'landed', now, onOpenLooseEnds, teams, bots, onOpenChat }) => {
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=`.
@@ -572,7 +579,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} />)}
+ {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} />)}
</>
) : (
desk.reviews && (
diff --git a/frontend/src/components/DevDeskSlots.tsx b/frontend/src/components/DevDeskSlots.tsx
index 56362c1b..2007130c 100644
--- a/frontend/src/components/DevDeskSlots.tsx
+++ b/frontend/src/components/DevDeskSlots.tsx
@@ -55,6 +55,10 @@ export interface ReviewCardProps {
gitOnly?: boolean;
/** 0.7.6: the saved Jira site's origins, for "Matches the ticket" links (api-decisions 18). */
jiraOrigins?: readonly string[];
+ /** 0.9.0 G1: the line-notes routes; without it the card has no Changes section. */
+ lineNotes?: import('../dev/lineNotesApi').LineNotesApi;
+ /** 0.9.0 G1: "Open {bot}'s chat" after a send. */
+ onOpenChat?: (botId: string) => void;
}
export interface ReleaseNotesSheetProps {
@@ -88,7 +92,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 }) => {
+export const ReviewCard: React.FC<ReviewCardProps> = ({ card, onFinding, onPost, forge, forgeLogin, sample, now, repoLabel, gitOnly = false, jiraOrigins, lineNotes, onOpenChat }) => {
const parsed = useMemo(() => parseReview(card), [card]);
if (!parsed) return <CardFallback raw={card} />;
const send = async (cardId: string, findingId: string, action: FindingAction): Promise<Review> => {
@@ -103,7 +107,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} />;
+ 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} />;
};
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.tsx
new file mode 100644
index 00000000..c85af1bf
--- /dev/null
+++ b/frontend/src/components/dev/LineNotes.tsx
@@ -0,0 +1,1366 @@
+// 0.9.0 G1: the review card's Changes section (Mira, release-090/designs/g1-line-notes.md). The unified
+// diff, a gutter + per line, ranges, notes kept as drafts on the server, and one send bar that sends them
+// to the PR's author bot as one message. Sent notes say "Changed in {sha}" or "Still open" after the bot's
+// next push. Everything goes through the injected LineNotesApi (lineNotesApi.ts), so tests and the shot
+// harness pass a fake one. Text from the server is rendered as text, never as HTML.
+
+import React, { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
+import { AlertTriangle, ArrowUp, Check, ChevronDown, ChevronRight, Code2, Info, Loader2, MessageSquare, MoreHorizontal, Pencil, Plus, Trash2 } from 'lucide-react';
+import { ModernAvatar } from '../ModernAvatar';
+import { DiffStat, OutLink } from './parts';
+import { clock } from '../../dev/logic';
+import { isMacPlatform } from '../../browserInput';
+import { useMedia } from '../../useMedia';
+import type { ChangedFile, Changes, DiffLine, FlatLine, LinePoint, Note, NotesSummary } from '../../dev/lineNotes';
+import {
+ codeText,
+ LOAD_FAILED,
+ MAX_SEND,
+ NO_DIFF,
+ SEND_FAILED,
+ TOO_MANY,
+ addAria,
+ addedSay,
+ changedIn,
+ clampRange,
+ cutLine,
+ discardAsk,
+ filesWord,
+ flatLines,
+ goneLine,
+ indexOfPoint,
+ lineWords,
+ movedLine,
+ notBotLine,
+ notesWord,
+ draftsWord,
+ pointOf,
+ positionIn,
+ readOnlyLine,
+ resolvedSay,
+ sendLabel,
+ sendShort,
+ sentLine,
+ sentNoteLine,
+ showLines,
+ shownNo,
+ startsCollapsed,
+ stillOpen,
+ summaryLine,
+} from '../../dev/lineNotes';
+import { LineNotesError, newSendId, type LineNotesApi } from '../../dev/lineNotesApi';
+
+/** The app re-sends the `dev_card` SSE as this window event (DevDesk.tsx DEV_CARD_EVENT). */
+const DEV_CARD_EVENT = 'kwant:dev-card';
+const SENT_STAYS_MS = 8000;
+const UNDO_MS = 5000;
+const RESOLVED_FOLDS_MS = 3000;
+
+const RING = 'outline-none focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-sky-300';
+const HEAD = 'text-[11px] font-bold uppercase tracking-[.06em] text-zinc-400';
+const ICON_BTN = `inline-flex h-6 w-6 items-center justify-center rounded-md text-zinc-400 hover:bg-white/[.06] hover:text-zinc-100 max-sm:h-11 max-sm:w-11 ${RING}`;
+
+export interface ChangesSectionProps {
+ cardId: string;
+ api: LineNotesApi;
+ /** The card's own counts (ask 1), so the collapsed row needs no fetch. */
+ stat: { files: number; additions: number; deletions: number };
+ notesCount?: { drafts: number; total: number } | null;
+ /** The card's head; a new one reloads the changes while they're open. */
+ headSha?: string | null;
+ prUrl?: string | null;
+ /** Opens the author bot's 1:1 chat after a send. */
+ onOpenChat?: (botId: string) => void;
+ /** Shots and tests: start open. */
+ defaultOpen?: boolean;
+ /** Tests: force the phone layout (default: the 640 px breakpoint). */
+ phone?: boolean;
+}
+
+type Load = { s: 'idle' } | { s: 'loading' } | { s: 'error' } | { s: 'ready'; changes: Changes };
+/** A note being written: where (by anchor, so a reload keeps it), the code it quotes, and the text. */
+interface Writing {
+ path: string;
+ start: LinePoint;
+ end: LinePoint;
+ code: DiffLine[];
+ text: string;
+ /** Editing a draft in place. */
+ editing: string | null;
+ asking: boolean;
+ busy: boolean;
+ error: string | null;
+}
+type Bar =
+ | { s: 'idle' }
+ | { s: 'confirm' }
+ | { s: 'sending' }
+ | { s: 'sent'; n: number; bot: string; botId: string | null; at: string | null }
+ | { s: 'failed' };
+
+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 }) => {
+ const media = useMedia('(max-width: 639px)');
+ const phone = forcePhone ?? media;
+ const ids = useId();
+ const bodyId = `${ids}-changes`;
+ const [open, setOpen] = useState(defaultOpen);
+ const [load, setLoad] = useState<Load>({ s: 'idle' });
+ const [notes, setNotes] = useState<Note[] | null>(null);
+ const [summary, setSummary] = useState<NotesSummary | null>(null);
+ const [fileOpen, setFileOpen] = useState<Record<string, boolean>>({});
+ const [sel, setSel] = useState<{ path: string; anchor: number; from: number; to: number } | null>(null);
+ const [writing, setWriting] = useState<Writing | null>(null);
+ const [rangeMode, setRangeMode] = useState(false);
+ const [bar, setBar] = useState<Bar>({ s: 'idle' });
+ const [deleted, setDeleted] = useState<{ id: string; note: Note } | null>(null);
+ const [folded, setFolded] = useState<Set<string>>(() => new Set());
+ const [said, setSaid] = useState('');
+ const sendId = useRef<string | null>(null);
+ const lastSummary = useRef<NotesSummary | null>(null);
+ const 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';
+ const drafts = useMemo(() => (notes ?? []).filter((n) => n.state === 'draft'), [notes]);
+
+ // -------------------------------------------------------------------------------------------------
+ // Loading
+
+ const fetchNotes = useCallback(async () => {
+ const page = await api.notes(cardId);
+ setNotes(page.notes);
+ // Say it once when the bot's push changed the count (not on the first load).
+ const before = lastSummary.current;
+ const s = page.summary;
+ if (s && s.total > 0 && s.sha && before && before.sha !== s.sha) setSaid(resolvedSay(s));
+ lastSummary.current = s;
+ setSummary(s);
+ }, [api, cardId]);
+
+ const fetchAll = useCallback(async () => {
+ setLoad({ s: 'loading' });
+ try {
+ const [c] = await Promise.all([api.changes(cardId), fetchNotes()]);
+ loadedHead.current = c.head_sha;
+ setFileOpen(Object.fromEntries(c.files.map((f) => [f.path, !startsCollapsed(f)])));
+ setLoad({ s: 'ready', changes: c });
+ } catch {
+ setLoad({ s: 'error' });
+ }
+ }, [api, cardId, fetchNotes]);
+
+ useEffect(() => {
+ if (open && load.s === 'idle') void fetchAll();
+ }, [open, load.s, fetchAll]);
+
+ // Ask 2: the `dev_card` event refetches the notes; a new head refetches the changes too.
+ useEffect(() => {
+ const on = (e: Event) => {
+ const d = (e as CustomEvent<{ id?: string }>).detail;
+ if (!d || d.id !== cardId || load.s !== 'ready') return;
+ void fetchNotes().catch(() => undefined);
+ };
+ window.addEventListener(DEV_CARD_EVENT, on);
+ return () => window.removeEventListener(DEV_CARD_EVENT, on);
+ }, [cardId, load.s, fetchNotes]);
+ useEffect(() => {
+ if (load.s !== 'ready' || !headSha || headSha === loadedHead.current) return;
+ loadedHead.current = headSha;
+ void api
+ .changes(cardId)
+ .then((c) => setLoad({ s: 'ready', changes: c }))
+ .catch(() => undefined);
+ void fetchNotes().catch(() => undefined);
+ }, [headSha, load.s, api, cardId, fetchNotes]);
+
+ // Resolved notes fold to their header line once they've been on screen 3 s.
+ const resolvedKey = (notes ?? [])
+ .filter((n) => n.state === 'resolved' && !folded.has(n.id))
+ .map((n) => n.id)
+ .join(',');
+ useEffect(() => {
+ if (!open || !resolvedKey) return;
+ const t = window.setTimeout(() => setFolded((f) => new Set([...f, ...resolvedKey.split(',')])), RESOLVED_FOLDS_MS);
+ return () => window.clearTimeout(t);
+ }, [open, resolvedKey]);
+
+ // The Sent bar leaves after 8 s; the Undo after 5 s.
+ useEffect(() => {
+ if (bar.s !== 'sent') return;
+ const t = window.setTimeout(() => setBar({ s: 'idle' }), SENT_STAYS_MS);
+ return () => window.clearTimeout(t);
+ }, [bar]);
+ useEffect(() => {
+ if (!deleted) return;
+ const t = window.setTimeout(() => setDeleted(null), UNDO_MS);
+ return () => window.clearTimeout(t);
+ }, [deleted]);
+
+ // -------------------------------------------------------------------------------------------------
+ // Writing
+
+ const startWriting = (f: ChangedFile, lines: FlatLine[], a: number, b: number) => {
+ if (!canNote) return;
+ setSel({ path: f.path, anchor: a, from: a, to: b });
+ setRangeMode(false);
+ if (bar.s === 'sent') setBar({ s: 'idle' });
+ setWriting((w) => ({
+ path: f.path,
+ start: pointOf(lines[a].line),
+ end: pointOf(lines[b].line),
+ code: quote(lines, a, b),
+ text: w && !w.editing ? w.text : '',
+ editing: null,
+ asking: false,
+ busy: false,
+ error: null,
+ }));
+ };
+
+ const startEditing = (n: Note) => {
+ setSel(null);
+ setWriting({ path: n.path, start: n.start, end: n.end, code: n.code, text: n.text, editing: n.id, asking: false, busy: false, error: null });
+ };
+
+ const focusLine = (path: string, p: LinePoint | null) => {
+ window.setTimeout(() => {
+ const grid = document.querySelector<HTMLElement>(`[data-ln-grid="${CSS.escape(path)}"]`);
+ const btn = p ? grid?.querySelector<HTMLElement>(`[data-ln-point="${p.side}:${p.line}"] button`) : null;
+ (btn ?? grid?.querySelector<HTMLElement>('button[tabindex="0"]'))?.focus();
+ }, 0);
+ };
+
+ const stopWriting = () => {
+ const w = writing;
+ setWriting(null);
+ setSel(null);
+ if (w) focusLine(w.path, w.end);
+ };
+
+ const submit = async () => {
+ const w = writing;
+ if (!w || !w.text.trim() || w.busy || !changes) return;
+ setWriting({ ...w, busy: true, error: null });
+ try {
+ const note = w.editing ? await api.edit(w.editing, w.text) : await api.create(cardId, { path: w.path, start: w.start, end: w.end, head_sha: changes.head_sha, text: w.text });
+ const next = (notes ?? []).filter((n) => n.id !== note.id).concat(note);
+ setNotes(next);
+ if (!w.editing && bot) setSaid(addedSay(lineWords(note.start, note.end), next.filter((n) => n.state === 'draft').length, bot));
+ if (bar.s === 'sent' || bar.s === 'failed') setBar({ s: 'idle' });
+ sendId.current = null;
+ setWriting(null);
+ setSel(null);
+ focusLine(w.path, w.end);
+ } catch (e) {
+ const err = e instanceof LineNotesError ? e : null;
+ // Ask 4: the card moved on. Reload the diff; the note stays where it was written, with its text.
+ if (err?.code === 'stale_head') {
+ void api
+ .changes(cardId)
+ .then((c) => {
+ loadedHead.current = c.head_sha;
+ setLoad({ s: 'ready', changes: c });
+ })
+ .catch(() => undefined);
+ }
+ setWriting({ ...w, busy: false, error: err ? err.message : 'The note didn’t save. Try again.' });
+ }
+ };
+
+ const remove = async (n: Note) => {
+ try {
+ await api.remove(n.id);
+ setNotes((all) => (all ?? []).filter((x) => x.id !== n.id));
+ setDeleted({ id: n.id, note: n });
+ setSaid('Note deleted.');
+ } catch (e) {
+ setSaid(e instanceof Error ? e.message : 'The note wasn’t deleted.');
+ }
+ };
+ const undoDelete = async () => {
+ const d = deleted;
+ if (!d) return;
+ setDeleted(null);
+ try {
+ const back = await api.restore(d.id);
+ setNotes((all) => (all ?? []).filter((x) => x.id !== back.id).concat(back));
+ setSaid('Note restored.');
+ } catch (e) {
+ setSaid(e instanceof Error ? e.message : 'The note couldn’t be restored.');
+ }
+ };
+
+ // -------------------------------------------------------------------------------------------------
+ // Sending
+
+ const send = async (only?: string[]) => {
+ if (!changes?.author_bot || bar.s === 'sending') return;
+ const n = only ? only.length : drafts.length;
+ if (n === 0 || n > MAX_SEND) return;
+ sendId.current ??= newSendId();
+ setBar({ s: 'sending' });
+ try {
+ const r = await api.send(cardId, sendId.current, only);
+ 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) });
+ setSaid(`Sent ${notesWord(r.sent)} to ${name}.`);
+ } catch {
+ // The send id is kept, so Try again can't post the batch twice (ask 6).
+ setBar({ s: 'failed' });
+ setSaid(SEND_FAILED);
+ }
+ };
+
+ const discardAll = async () => {
+ try {
+ await api.discardAll(cardId);
+ setNotes((all) => (all ?? []).filter((x) => x.state !== 'draft'));
+ setBar({ s: 'idle' });
+ sendId.current = null;
+ setSaid('Drafts discarded.');
+ } catch (e) {
+ setBar({ s: 'idle' });
+ setSaid(e instanceof Error ? e.message : 'The drafts weren’t discarded.');
+ }
+ };
+
+ // -------------------------------------------------------------------------------------------------
+
+ const draftCount = notes ? drafts.length : notesCount?.drafts ?? 0;
+ const showBar = canNote && (drafts.length > 0 || bar.s === 'sent' || bar.s === 'failed');
+
+ return (
+ <section data-line-notes={cardId} aria-label="Changes" className="relative mt-4">
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1">
+ <h4 className={`flex min-w-0 flex-1 flex-wrap items-center gap-1.5 ${HEAD}`}>
+ <Code2 size={13} aria-hidden="true" />
+ <span>Changes</span>
+ <span className="font-mono text-[12px] font-medium normal-case tracking-normal text-zinc-400 max-sm:order-1">{filesWord(stat.files)}</span>
+ <DiffStat add={stat.additions} del={stat.deletions} className="max-sm:order-1 max-sm:[&_.dv-bar]:hidden" />
+ {draftCount > 0 && <span className="normal-case tracking-normal text-violet-200">· {draftsWord(draftCount)}</span>}
+ </h4>
+ <button
+ type="button"
+ aria-expanded={open}
+ aria-controls={bodyId}
+ onClick={() => setOpen((o) => !o)}
+ className={`inline-flex min-h-8 items-center gap-1 self-start rounded-md px-1.5 text-[12px] font-medium text-violet-300 hover:text-violet-200 max-sm:min-h-11 ${RING}`}
+ >
+ {open ? 'Hide' : 'Show'}
+ <span className="sr-only"> the changes</span>
+ <ChevronDown size={14} aria-hidden="true" className={`transition-transform duration-[160ms] motion-reduce:transition-none ${open ? 'rotate-180' : ''}`} />
+ </button>
+ </div>
+ {summary && summary.total > 0 && summary.sha && (summary.changed > 0 || summary.open > 0) && (
+ <p data-ln-summary className="mt-1 text-meta text-zinc-400">
+ {summaryLine(summary)}
+ </p>
+ )}
+ <p aria-live="polite" className="sr-only" data-ln-live>
+ {said}
+ </p>
+
+ <div id={bodyId} hidden={!open}>
+ {open && load.s === 'loading' && (
+ <div data-ln-loading className="mt-2 rounded-[10px] border border-hairline p-3">
+ <p role="status" className="flex items-center gap-2 text-meta text-zinc-400">
+ <Loader2 size={13} aria-hidden="true" className="motion-safe:animate-spin" />
+ Loading the changes…
+ </p>
+ <div aria-hidden="true" className="mt-3 grid gap-2">
+ <div className="h-2.5 w-[62%] rounded-full bg-[var(--kw-hairline-strong)]" />
+ <div className="h-2.5 w-[40%] rounded-full bg-[var(--kw-hairline-strong)]" />
+ </div>
+ </div>
+ )}
+ {open && load.s === 'error' && (
+ <p data-ln-error className="mt-2 flex flex-wrap items-center gap-x-3 gap-y-1 rounded-[10px] border border-hairline px-3 py-2.5 text-meta text-zinc-300">
+ <span className="inline-flex items-center gap-1.5">
+ <AlertTriangle size={13} aria-hidden="true" className="text-zinc-400" />
+ {LOAD_FAILED}
+ </span>
+ <span className="ml-auto inline-flex flex-wrap items-center gap-3">
+ <button type="button" onClick={() => void fetchAll()} className={`min-h-8 rounded font-medium text-violet-300 hover:text-violet-200 max-sm:min-h-11 ${RING}`}>
+ Try again
+ </button>
+ {prUrl && /^https:\/\//.test(prUrl) && <OutLink href={prUrl}>Open on GitHub</OutLink>}
+ </span>
+ </p>
+ )}
+ {open && changes && (
+ <div className="mt-2">
+ {!changes.author_bot && (
+ <Banner>
+ {notBotLine(changes.author_login).split(changes.author_login ?? '\u0000').map((part, i, all) => (
+ <React.Fragment key={i}>
+ {part}
+ {i < all.length - 1 && <strong className="font-semibold text-zinc-100">{changes.author_login}</strong>}
+ </React.Fragment>
+ ))}
+ </Banner>
+ )}
+ {changes.author_bot && changes.pr_state !== 'open' && <Banner>{readOnlyLine(changes.pr_state)}</Banner>}
+ {changes.files.length === 0 ? (
+ <Banner>{NO_DIFF}</Banner>
+ ) : (
+ <div data-ln-files className="flex flex-col gap-2 sm:max-h-[min(70vh,720px)] sm:overflow-y-auto sm:pr-0.5">
+ {changes.files.map((f) => (
+ <FileBlock
+ key={f.path}
+ file={f}
+ open={fileOpen[f.path] ?? true}
+ onToggle={() => setFileOpen((o) => ({ ...o, [f.path]: !(o[f.path] ?? true) }))}
+ notes={(notes ?? []).filter((n) => n.path === f.path)}
+ headSha={changes.head_sha}
+ canNote={canNote}
+ phone={phone}
+ bot={bot ?? ''}
+ prUrl={changes.pr_url ?? prUrl}
+ sel={sel && sel.path === f.path ? sel : null}
+ setSel={(s) => setSel(s ? { path: f.path, ...s } : null)}
+ writing={writing && writing.path === f.path ? writing : null}
+ setWriting={setWriting}
+ rangeMode={rangeMode}
+ startWriting={(lines, a, b) => startWriting(f, lines, a, b)}
+ stopWriting={stopWriting}
+ submit={() => void submit()}
+ onEdit={startEditing}
+ onDelete={(n) => void remove(n)}
+ onSendOne={(n) => void send([n.id])}
+ folded={folded}
+ toggleFold={(id) =>
+ setFolded((s) => {
+ const next = new Set(s);
+ if (next.has(id)) next.delete(id);
+ else next.add(id);
+ return next;
+ })
+ }
+ />
+ ))}
+ </div>
+ )}
+ {changes.cut && <p className="mt-2 text-meta text-[#8a8a96]">{cutLine(changes.cut)}</p>}
+ </div>
+ )}
+
+ {deleted && (
+ <p role="status" data-ln-undo className="mt-2 flex items-center gap-2 text-meta text-zinc-300">
+ Note deleted
+ <span aria-hidden="true">·</span>
+ <button type="button" onClick={() => void undoDelete()} className={`min-h-8 rounded font-medium text-violet-300 hover:text-violet-200 max-sm:min-h-11 ${RING}`}>
+ Undo
+ </button>
+ </p>
+ )}
+
+ {/* Phone: a range is chosen by tapping its last line. */}
+ {open && phone && rangeMode && sel && (
+ <div data-ln-range-bar className="fixed inset-x-0 bottom-0 z-40 flex items-center gap-3 border-t border-white/10 bg-[#1a1538]/95 px-4 py-2.5 backdrop-blur pb-[max(.625rem,env(safe-area-inset-bottom))]">
+ <span className="min-w-0 flex-1 text-[15px] text-zinc-200">Line {lineAt(changes, sel)} · tap the last line</span>
+ <button
+ type="button"
+ onClick={() => {
+ const f = changes?.files.find((x) => x.path === sel.path);
+ if (f) {
+ const lines = flatLines(f);
+ startWriting(f, lines, sel.from, sel.to);
+ }
+ }}
+ className="kw-btn-primary min-h-11"
+ >
+ Done
+ </button>
+ </div>
+ )}
+
+ {/* Phone: the note sheet. */}
+ {open && phone && writing && !rangeMode && (
+ <NoteSheet
+ writing={writing}
+ setWriting={setWriting}
+ bot={bot ?? ''}
+ onCancel={stopWriting}
+ onSubmit={() => void submit()}
+ onExtend={
+ writing.editing
+ ? null
+ : () => {
+ setRangeMode(true);
+ }
+ }
+ />
+ )}
+
+ {open && showBar && (
+ <SendBar
+ bar={bar}
+ setBar={setBar}
+ drafts={drafts.length}
+ bot={bot ?? ''}
+ phone={phone}
+ onSend={() => void send()}
+ onDiscard={() => void discardAll()}
+ onOpenChat={onOpenChat}
+ />
+ )}
+ </div>
+ </section>
+ );
+};
+
+function lineAt(changes: Changes | null, sel: { path: string; from: number }): number | string {
+ const f = changes?.files.find((x) => x.path === sel.path);
+ const l = f ? flatLines(f)[sel.from] : null;
+ return l ? shownNo(l.line) : '';
+}
+
+const Banner: React.FC<{ children: React.ReactNode }> = ({ children }) => (
+ <p data-ln-banner className="mb-2 flex items-start gap-2 rounded-[10px] border border-hairline px-3 py-2.5 text-meta text-zinc-300 [overflow-wrap:anywhere]">
+ <Info size={13} aria-hidden="true" className="mt-[3px] shrink-0 text-zinc-400" />
+ <span className="min-w-0">{children}</span>
+ </p>
+);
+
+// ---------------------------------------------------------------------------------------------------
+// One file
+
+interface FileBlockProps {
+ file: ChangedFile;
+ open: boolean;
+ onToggle: () => void;
+ notes: Note[];
+ headSha: string | null;
+ canNote: boolean;
+ phone: boolean;
+ bot: string;
+ prUrl: string | null;
+ sel: { anchor: number; from: number; to: number } | null;
+ setSel: (s: { anchor: number; from: number; to: number } | null) => void;
+ writing: Writing | null;
+ setWriting: React.Dispatch<React.SetStateAction<Writing | null>>;
+ rangeMode: boolean;
+ startWriting: (lines: FlatLine[], a: number, b: number) => void;
+ stopWriting: () => void;
+ submit: () => void;
+ onEdit: (n: Note) => void;
+ onDelete: (n: Note) => void;
+ onSendOne: (n: Note) => void;
+ folded: Set<string>;
+ toggleFold: (id: string) => void;
+}
+
+/** Renders a file's lines once it scrolls near the viewport (no virtualiser). */
+function useNear(ref: React.RefObject<HTMLElement>, on: boolean): boolean {
+ const [near, setNear] = useState(() => typeof IntersectionObserver === 'undefined');
+ useEffect(() => {
+ if (near || !on || !ref.current || typeof IntersectionObserver === 'undefined') return;
+ const io = new IntersectionObserver((es) => es.some((e) => e.isIntersecting) && setNear(true), { rootMargin: '600px 0px' });
+ io.observe(ref.current);
+ return () => io.disconnect();
+ }, [near, on, ref]);
+ return near;
+}
+
+const FileBlock: React.FC<FileBlockProps> = (p) => {
+ const { file: f, notes, sel, writing, canNote, phone } = p;
+ const lines = useMemo(() => flatLines(f), [f]);
+ const [active, setActive] = useState(0);
+ const [shown, setShown] = useState(false);
+ const wrap = useRef<HTMLDivElement>(null);
+ const near = useNear(wrap, p.open);
+ const drag = useRef<number | null>(null);
+ const bodyId = useId();
+
+ // Where each note sits: under the last line of its range, or at the top of the file.
+ const { under, top, noted } = useMemo(() => {
+ const under = new Map<number, Note[]>();
+ const top: Note[] = [];
+ const noted = new Set<number>();
+ for (const n of notes) {
+ const at = positionIn(lines, n);
+ if (!at) {
+ top.push(n);
+ continue;
+ }
+ for (let i = at[0]; i <= at[1]; i++) noted.add(i);
+ under.set(at[1], [...(under.get(at[1]) ?? []), n]);
+ }
+ return { under, top, noted };
+ }, [notes, lines]);
+
+ const writeAt = writing ? indexOfPoint(lines, writing.end) : -1;
+ const editingId = writing?.editing ?? null;
+
+ useEffect(() => {
+ const up = () => {
+ const a = drag.current;
+ drag.current = null;
+ if (a === null || !sel) return;
+ p.startWriting(lines, sel.from, sel.to);
+ };
+ window.addEventListener('pointerup', up);
+ return () => window.removeEventListener('pointerup', up);
+ });
+
+ const focusAt = (i: number) => {
+ const n = Math.max(0, Math.min(lines.length - 1, i));
+ setActive(n);
+ window.setTimeout(() => wrap.current?.querySelector<HTMLElement>(`[data-ln-i="${n}"] button`)?.focus(), 0);
+ return n;
+ };
+
+ const onKey = (e: React.KeyboardEvent) => {
+ if (!(e.target instanceof HTMLButtonElement) || !e.target.closest('[data-ln-i]')) return;
+ const i = active;
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
+ e.preventDefault();
+ const n = focusAt(i + (e.key === 'ArrowDown' ? 1 : -1));
+ if (e.shiftKey) {
+ const anchor = sel?.anchor ?? i;
+ const [a, b] = clampRange(lines, anchor, n);
+ p.setSel({ anchor, from: a, to: b });
+ } else p.setSel(null);
+ } else if (e.key === 'Home' || e.key === 'End') {
+ e.preventDefault();
+ focusAt(e.key === 'Home' ? 0 : lines.length - 1);
+ p.setSel(null);
+ } else if (e.key === ']' || e.key === '[') {
+ e.preventDefault();
+ const grids = [...document.querySelectorAll<HTMLElement>('[data-ln-grid]')];
+ const at = grids.findIndex((g) => g.contains(e.target as Node));
+ grids[at + (e.key === ']' ? 1 : -1)]?.querySelector<HTMLElement>('button[tabindex="0"]')?.focus();
+ } else if ((e.key === 'n' || e.key === 'N') && canNote) {
+ e.preventDefault();
+ open(i, false);
+ }
+ };
+
+ /** A click (or Enter, or N) on line i: a note on the selected range when i ends it, else on line i. */
+ const open = (i: number, shift: boolean) => {
+ if (!canNote) return;
+ if (shift && sel) {
+ const [a, b] = clampRange(lines, sel.anchor, i);
+ p.startWriting(lines, a, b);
+ return;
+ }
+ if (sel && i === sel.to && sel.from !== sel.to) {
+ p.startWriting(lines, sel.from, sel.to);
+ return;
+ }
+ p.setSel({ anchor: i, from: i, to: i });
+ p.startWriting(lines, i, i);
+ };
+
+ /** Phone: tap a line. In range mode it sets the range's last line. */
+ const tap = (i: number) => {
+ if (!canNote) return;
+ if (p.rangeMode && sel) {
+ const [a, b] = clampRange(lines, sel.anchor, i);
+ p.setSel({ anchor: sel.anchor, from: a, to: b });
+ p.startWriting(lines, a, b);
+ return;
+ }
+ open(i, false);
+ };
+
+ const omitted = f.omitted;
+ const renamedOnly = !omitted && lines.length === 0 && !!f.old_path;
+ const hasBody = !omitted && lines.length > 0;
+ const big = hasBody && !p.open;
+ const n = notes.length;
+
+ const noteBox = (note: Note) =>
+ editingId === note.id && !phone ? (
+ <Composer key={note.id} writing={writing!} setWriting={p.setWriting} bot={p.bot} onCancel={p.stopWriting} onSubmit={p.submit} />
+ ) : (
+ <NoteBox
+ key={note.id}
+ note={note}
+ bot={p.bot}
+ editable={canNote && note.state === 'draft'}
+ folded={p.folded.has(note.id)}
+ onFold={() => p.toggleFold(note.id)}
+ onEdit={() => p.onEdit(note)}
+ onDelete={() => p.onDelete(note)}
+ onSendOne={() => p.onSendOne(note)}
+ movedTo={note.moved && note.at_head ? note.at_head.end.line : null}
+ />
+ );
+
+ return (
+ <div ref={wrap} data-ln-file={f.path}>
+ <div
+ className={`flex flex-wrap items-center gap-x-2 gap-y-1 border border-hairline bg-white/[.02] px-2.5 py-[7px] font-mono text-[12px] text-zinc-200 ${hasBody && p.open ? 'rounded-t-[10px] border-b-0' : 'rounded-[10px]'}`}
+ >
+ {hasBody ? (
+ <button
+ type="button"
+ aria-expanded={p.open}
+ aria-controls={bodyId}
+ onClick={p.onToggle}
+ className={`inline-flex min-h-6 min-w-0 flex-1 items-center gap-1.5 rounded text-left [overflow-wrap:anywhere] max-sm:min-h-11 ${RING}`}
+ >
+ <ChevronRight size={13} aria-hidden="true" className={`shrink-0 text-zinc-500 transition-transform duration-[160ms] motion-reduce:transition-none ${p.open ? 'rotate-90' : ''}`} />
+ <FileName file={f} phone={phone} />
+ <DiffStat add={f.additions} del={f.deletions} className="shrink-0" />
+ </button>
+ ) : (
+ <span className="inline-flex min-w-0 flex-1 flex-wrap items-center gap-1.5 [overflow-wrap:anywhere]">
+ <Code2 size={13} aria-hidden="true" className="shrink-0 text-zinc-500" />
+ <FileName file={f} phone={phone} />
+ {!renamedOnly && <DiffStat add={f.additions} del={f.deletions} className="shrink-0" />}
+ </span>
+ )}
+ {n > 0 && (
+ <span className="inline-flex shrink-0 items-center gap-1 font-sans text-[12px] text-violet-200">
+ <MessageSquare size={12} aria-hidden="true" />
+ {notesWord(n)}
+ </span>
+ )}
+ {omitted === 'binary' && <span className="w-full font-sans text-meta text-[#8a8a96] sm:w-auto">Binary file, not shown</span>}
+ {omitted === 'too_large' && (
+ <span className="w-full font-sans text-meta text-[#8a8a96] sm:w-auto">
+ Too big to show here
+ {p.prUrl && /^https:\/\//.test(p.prUrl) && (
+ <>
+ {' · '}
+ <OutLink href={p.prUrl}>Open on GitHub</OutLink>
+ </>
+ )}
+ </span>
+ )}
+ {renamedOnly && <span className="w-full font-sans text-meta text-[#8a8a96] sm:w-auto">Renamed, no changes</span>}
+ {big && !shown && (
+ <button
+ type="button"
+ onClick={() => {
+ setShown(true);
+ p.onToggle();
+ }}
+ className={`ml-auto min-h-6 rounded font-sans text-[12px] font-medium text-violet-300 hover:text-violet-200 max-sm:min-h-11 ${RING}`}
+ >
+ {showLines(lines.length)}
+ </button>
+ )}
+ </div>
+
+ {/* Notes whose lines aren't in this diff stay at the top of their file, with the code as written. */}
+ {top.length > 0 && (
+ <div className={`flex flex-col gap-1.5 border-x border-hairline bg-[var(--dv-code-bg)] py-1.5 ${hasBody && p.open ? '' : 'rounded-b-[10px] border-b'}`}>
+ {top.map((note) => (
+ <div key={note.id} className="px-2.5">
+ {note.code.length > 0 && (
+ <pre className="mb-1 overflow-x-auto rounded-md bg-black/20 px-2 py-1 font-mono text-[12px] leading-5 text-zinc-400 max-sm:whitespace-pre-wrap max-sm:break-words">
+ {codeText(note.code)}
+ </pre>
+ )}
+ {noteBox(note)}
+ </div>
+ ))}
+ </div>
+ )}
+
+ {hasBody && p.open && (
+ <div
+ id={bodyId}
+ role="grid"
+ aria-label={`Changes in ${f.path}`}
+ aria-readonly={!canNote}
+ data-ln-grid={f.path}
+ tabIndex={canNote ? undefined : 0}
+ onKeyDown={onKey}
+ className={`overflow-x-auto rounded-b-[10px] border border-hairline bg-[var(--dv-code-bg)] font-mono text-[12px] leading-5 [container-type:inline-size] max-sm:text-[13px] ${canNote ? '' : RING}`}
+ >
+ {!near ? (
+ <div aria-hidden="true" style={{ height: Math.min(lines.length, 400) * 20 }} />
+ ) : (
+ <div className="sm:w-max sm:min-w-full">
+ {f.hunks.map((h, hi) => (
+ <React.Fragment key={hi}>
+ <div role="row" className="grid grid-cols-[34px_1fr] bg-violet-500/[.06] text-[#8a8a96] sm:grid-cols-[26px_38px_38px_1fr]">
+ <span role="gridcell" className="max-sm:hidden" />
+ <span role="gridcell" className="max-sm:hidden" />
+ <span role="gridcell" />
+ <span role="gridcell" className="whitespace-pre px-1 max-sm:whitespace-pre-wrap max-sm:break-words">
+ {h.header}
+ </span>
+ </div>
+ {lines
+ .filter((x) => x.hunk === hi)
+ .map((x) => (
+ <React.Fragment key={x.i}>
+ <Row
+ x={x}
+ selected={!!sel && x.i >= sel.from && x.i <= sel.to}
+ noted={noted.has(x.i)}
+ active={x.i === active}
+ canNote={canNote}
+ phone={phone}
+ onFocus={() => setActive(x.i)}
+ onPress={(shift) => (phone ? tap(x.i) : open(x.i, shift))}
+ onDragStart={() => {
+ if (!canNote || phone) return;
+ drag.current = x.i;
+ p.setSel({ anchor: x.i, from: x.i, to: x.i });
+ }}
+ onDragOver={() => {
+ if (drag.current === null) return;
+ const [a, b] = clampRange(lines, drag.current, x.i);
+ p.setSel({ anchor: drag.current, from: a, to: b });
+ }}
+ />
+ {(under.get(x.i) ?? []).map((note) => (
+ <div key={note.id} role="row" className="sticky left-0 w-full sm:w-[100cqw]">
+ <div role="gridcell">{noteBox(note)}</div>
+ </div>
+ ))}
+ {!phone && writing && !writing.editing && writeAt === x.i && (
+ <div role="row" className="sticky left-0 w-full sm:w-[100cqw]">
+ <div role="gridcell">
+ <Composer writing={writing} setWriting={p.setWriting} bot={p.bot} onCancel={p.stopWriting} onSubmit={p.submit} />
+ </div>
+ </div>
+ )}
+ </React.Fragment>
+ ))}
+ </React.Fragment>
+ ))}
+ </div>
+ )}
+ </div>
+ )}
+ {/* A note being written whose line left the diff (the bot pushed meanwhile): it stays, at the top. */}
+ {!phone && writing && !writing.editing && writeAt < 0 && (
+ <div className="mt-1">
+ <Composer writing={writing} setWriting={p.setWriting} bot={p.bot} onCancel={p.stopWriting} onSubmit={p.submit} />
+ </div>
+ )}
+ </div>
+ );
+};
+
+const FileName: React.FC<{ file: ChangedFile; phone: boolean }> = ({ file, phone }) => (
+ <span className="min-w-0 [overflow-wrap:anywhere]" title={file.path}>
+ {file.old_path && file.old_path !== file.path ? (
+ <>
+ {phone ? base(file.old_path) : file.old_path}
+ <span aria-hidden="true" className="text-zinc-500">
+ {' → '}
+ </span>
+ <span className="sr-only"> renamed to </span>
+ {phone ? base(file.path) : file.path}
+ </>
+ ) : phone ? (
+ <>
+ <span className="sr-only">{file.path}</span>
+ <span aria-hidden="true">{base(file.path)}</span>
+ </>
+ ) : (
+ file.path
+ )}
+ </span>
+);
+
+// ---------------------------------------------------------------------------------------------------
+// One line
+
+const LINE_TONE = {
+ add: 'bg-[var(--dv-add-bg)] text-[var(--dv-add)]',
+ del: 'bg-[var(--dv-del-bg)] text-[var(--dv-del)]',
+ ctx: 'text-zinc-300',
+} as const;
+
+interface RowProps {
+ x: FlatLine;
+ selected: boolean;
+ noted: boolean;
+ active: boolean;
+ canNote: boolean;
+ phone: boolean;
+ onFocus: () => void;
+ onPress: (shift: boolean) => void;
+ onDragStart: () => void;
+ onDragOver: () => void;
+}
+
+const Row: React.FC<RowProps> = React.memo(({ x, selected, noted, active, canNote, phone, onFocus, onPress, onDragStart, onDragOver }) => {
+ const l = x.line;
+ const p = pointOf(l);
+ return (
+ <div
+ role="row"
+ data-ln-i={x.i}
+ data-ln-point={`${p.side}:${p.line}`}
+ data-ln-kind={l.kind}
+ aria-selected={selected || undefined}
+ onPointerEnter={onDragOver}
+ className={`group relative grid grid-cols-[34px_1fr] sm:grid-cols-[26px_38px_38px_1fr] ${selected ? 'bg-violet-500/[.14] shadow-[inset_3px_0_0_theme(colors.violet.400)]' : LINE_TONE[l.kind]}`}
+ >
+ <span role="gridcell" className="flex items-center justify-center max-sm:absolute max-sm:inset-0 max-sm:z-10">
+ {canNote ? (
+ <button
+ type="button"
+ tabIndex={active ? 0 : -1}
+ aria-label={`${addAria(l)}${noted ? '. It has a note' : ''}`}
+ onFocus={onFocus}
+ onPointerDown={(e) => {
+ if (e.button === 0 && !phone) onDragStart();
+ }}
+ onClick={(e) => onPress(e.shiftKey)}
+ className={`inline-flex h-[18px] w-5 items-center justify-center rounded-[5px] max-sm:h-full max-sm:w-full max-sm:!min-h-0 max-sm:!min-w-0 max-sm:rounded-none max-sm:opacity-0 ${
+ noted ? 'text-violet-300' : 'bg-violet-600 text-white opacity-0 group-hover:opacity-100 focus-visible:opacity-100'
+ } ${selected && !noted ? 'opacity-100' : ''} ${RING}`}
+ >
+ {noted ? <MessageSquare size={13} aria-hidden="true" /> : <Plus size={12} aria-hidden="true" />}
+ </button>
+ ) : noted ? (
+ <MessageSquare size={13} aria-hidden="true" className="text-violet-300 max-sm:hidden" />
+ ) : null}
+ </span>
+ <span role="gridcell" className="select-none pr-2 text-right text-[#8a8a96] max-sm:hidden" aria-hidden="true">
+ {l.old ?? ''}
+ </span>
+ <span role="gridcell" className={`select-none pr-2 text-right ${l.kind === 'del' ? 'text-[#8a8a96] max-sm:text-rose-300/70' : 'text-[#8a8a96]'}`} aria-hidden="true">
+ <span className="max-sm:hidden">{l.new ?? ''}</span>
+ <span className="sm:hidden">{shownNo(l)}</span>
+ </span>
+ <span role="gridcell" className={`whitespace-pre pr-3 max-sm:whitespace-pre-wrap max-sm:break-words ${selected ? 'text-zinc-100' : ''}`}>
+ {l.kind === 'add' && <span className="sr-only">Added: </span>}
+ {l.kind === 'del' && <span className="sr-only">Removed: </span>}
+ <span aria-hidden="true">{marker(l.kind)} </span>
+ {l.text}
+ </span>
+ </div>
+ );
+});
+Row.displayName = 'Row';
+
+// ---------------------------------------------------------------------------------------------------
+// Notes
+
+const STATE_BAR: Record<Note['state'], string> = {
+ draft: 'border-white/10',
+ sent: 'border-white/10 shadow-[inset_3px_0_0_theme(colors.violet.400)]',
+ resolved: 'border-white/10 bg-teal-400/[.04] shadow-[inset_3px_0_0_var(--ok,theme(colors.teal.300))]',
+ open: 'border-white/10 shadow-[inset_3px_0_0_theme(colors.zinc.500)]',
+};
+
+interface NoteBoxProps {
+ note: Note;
+ bot: string;
+ editable: boolean;
+ folded: boolean;
+ onFold: () => void;
+ onEdit: () => void;
+ onDelete: () => void;
+ onSendOne: () => void;
+ movedTo: number | null;
+}
+
+const NoteBox: React.FC<NoteBoxProps> = ({ note, bot, editable, folded, onFold, onEdit, onDelete, onSendOne, movedTo }) => {
+ const where = lineWords(note.start, note.end);
+ const words =
+ note.state === 'sent'
+ ? sentNoteLine(clock(note.sent_at), bot || 'the bot')
+ : note.state === 'resolved'
+ ? changedIn(note.checked_sha)
+ : note.state === 'open'
+ ? stillOpen(note.checked_sha)
+ : 'Draft';
+ const resolved = note.state === 'resolved';
+ const label =
+ note.state === 'draft' ? `Draft note on ${where}` : `Note on ${where}, ${words}`;
+ return (
+ <div
+ data-ln-note={note.id}
+ data-ln-state={note.state}
+ role="group"
+ aria-label={label}
+ tabIndex={editable ? 0 : undefined}
+ onKeyDown={(e) => {
+ if (!editable || e.target !== e.currentTarget) return;
+ if (e.key === 'e' || e.key === 'E') {
+ e.preventDefault();
+ onEdit();
+ } else if (e.key === 'Delete' || e.key === 'Backspace') {
+ e.preventDefault();
+ onDelete();
+ }
+ }}
+ className={`my-1.5 ml-2.5 mr-2.5 rounded-[10px] border bg-surface-raised px-3 py-2.5 font-sans sm:ml-16 ${STATE_BAR[note.state]} ${editable ? RING : ''}`}
+ >
+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-[11.5px] text-zinc-400">
+ <span className="font-semibold text-zinc-100">You</span>
+ <span>{where}</span>
+ {note.state === 'draft' ? (
+ <span className="rounded-full border border-dashed border-zinc-500 px-1.5 text-[11px] font-medium text-zinc-200">Draft</span>
+ ) : resolved ? (
+ <button
+ type="button"
+ aria-expanded={!folded}
+ onClick={onFold}
+ className={`inline-flex items-center gap-1 rounded-full border border-teal-400/30 bg-teal-400/10 px-1.5 text-[11px] font-medium text-teal-200 max-sm:min-h-8 ${RING}`}
+ >
+ <Check size={11} aria-hidden="true" />
+ {words}
+ </button>
+ ) : (
+ <span className={`rounded-full border px-1.5 text-[11px] font-medium ${note.state === 'sent' ? 'border-violet-400/30 text-violet-200' : 'border-zinc-500/40 text-zinc-300'}`}>
+ {words}
+ </span>
+ )}
+ {editable && (
+ <span className="ml-auto inline-flex items-center gap-0.5">
+ <button type="button" aria-label={`Edit the note on ${where}`} onClick={onEdit} className={ICON_BTN}>
+ <Pencil size={13} aria-hidden="true" />
+ </button>
+ <button type="button" aria-label={`Delete the note on ${where}`} onClick={onDelete} className={ICON_BTN}>
+ <Trash2 size={13} aria-hidden="true" />
+ </button>
+ </span>
+ )}
+ </div>
+ {!(resolved && folded) && (
+ <p className="mt-1 whitespace-pre-wrap text-[13px] leading-5 text-zinc-200 [overflow-wrap:anywhere]">{note.text}</p>
+ )}
+ {note.state === 'draft' && note.moved && (
+ <p className="mt-1.5 flex items-start gap-1.5 text-[11.5px] text-zinc-400">
+ <Info size={12} aria-hidden="true" className="mt-[2px] shrink-0" />
+ {movedLine(bot || 'The bot', note.seen_sha, movedTo)}
+ </p>
+ )}
+ {note.state === 'draft' && note.gone && (
+ <p className="mt-1.5 flex flex-wrap items-center gap-x-2 gap-y-1 text-[11.5px] text-zinc-400">
+ <Info size={12} aria-hidden="true" className="shrink-0" />
+ {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}`}>
+ Send it anyway
+ </button>
+ <span aria-hidden="true">·</span>
+ <button type="button" onClick={onDelete} className={`rounded font-medium text-violet-300 hover:text-violet-200 max-sm:min-h-11 ${RING}`}>
+ Delete
+ </button>
+ </>
+ )}
+ </p>
+ )}
+ </div>
+ );
+};
+
+interface ComposerProps {
+ writing: Writing;
+ setWriting: React.Dispatch<React.SetStateAction<Writing | null>>;
+ bot: string;
+ onCancel: () => void;
+ onSubmit: () => void;
+}
+
+const keyHint = () => (isMacPlatform() ? '⌘ Enter adds · Esc cancels' : 'Ctrl Enter adds · Esc cancels');
+
+/** Shared by the inline box and the phone sheet. */
+function useComposerKeys(w: Writing, setWriting: ComposerProps['setWriting'], onCancel: () => void, onSubmit: () => void) {
+ return (e: React.KeyboardEvent<HTMLTextAreaElement>) => {
+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
+ e.preventDefault();
+ onSubmit();
+ } else if (e.key === 'Escape') {
+ e.preventDefault();
+ e.stopPropagation();
+ if (w.text.trim() && w.text !== '' && !w.asking) setWriting((x) => (x ? { ...x, asking: true } : x));
+ else if (!w.text.trim()) onCancel();
+ }
+ };
+}
+
+const AskThrowAway: React.FC<{ setWriting: ComposerProps['setWriting']; onCancel: () => void; big?: boolean }> = ({ setWriting, onCancel, big }) => {
+ const keep = useRef<HTMLButtonElement>(null);
+ useEffect(() => keep.current?.focus(), []);
+ return (
+ <div role="alertdialog" aria-label="Throw away this note?" className="mt-2 flex flex-wrap items-center gap-2 text-meta text-zinc-200">
+ <span className="mr-auto">Throw away this note?</span>
+ <button type="button" onClick={onCancel} className={`kw-btn-ghost ${big ? 'min-h-11' : ''}`}>
+ Throw away
+ </button>
+ <button
+ ref={keep}
+ type="button"
+ onClick={() => {
+ setWriting((x) => (x ? { ...x, asking: false } : x));
+ window.setTimeout(() => document.querySelector<HTMLTextAreaElement>('[data-ln-text]')?.focus(), 0);
+ }}
+ className={`kw-btn-primary ${big ? 'min-h-11' : ''}`}
+ >
+ Keep writing
+ </button>
+ </div>
+ );
+};
+
+const Composer: React.FC<ComposerProps> = ({ writing: w, setWriting, bot, onCancel, onSubmit }) => {
+ const onKey = useComposerKeys(w, setWriting, onCancel, onSubmit);
+ const label = useId();
+ return (
+ <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)}
+ </p>
+ <textarea
+ data-ln-text
+ autoFocus
+ aria-labelledby={label}
+ placeholder="Say what to change"
+ value={w.text}
+ maxLength={4000}
+ onChange={(e) => setWriting((x) => (x ? { ...x, text: e.target.value, asking: false } : x))}
+ onKeyDown={onKey}
+ className="mt-1.5 block min-h-[52px] w-full resize-y rounded-lg border border-hairline bg-[var(--dv-code-bg)] px-2.5 py-2 text-[13px] leading-5 text-zinc-100 placeholder:text-[#8a8a96] focus:border-violet-400 focus:outline-none"
+ />
+ {w.error && (
+ <p role="alert" className="mt-1.5 text-meta text-rose-300">
+ {w.error}
+ </p>
+ )}
+ {w.asking ? (
+ <AskThrowAway setWriting={setWriting} onCancel={onCancel} />
+ ) : (
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ <button type="button" disabled={!w.text.trim() || w.busy} onClick={onSubmit} className="kw-btn-primary !px-3 !py-1 !text-meta">
+ {w.busy && <Loader2 size={13} aria-hidden="true" className="motion-safe:animate-spin" />}
+ {w.editing ? 'Save' : 'Add note'}
+ </button>
+ <button type="button" onClick={onCancel} className="kw-btn-ghost !py-1">
+ Cancel
+ </button>
+ <span className="ml-auto text-[11.5px] text-[#8a8a96] max-sm:hidden">{keyHint()}</span>
+ </div>
+ )}
+ </div>
+ );
+};
+
+const NoteSheet: React.FC<{ writing: Writing; setWriting: ComposerProps['setWriting']; bot: string; onCancel: () => void; onSubmit: () => void; onExtend: (() => void) | null }> = ({
+ writing: w,
+ setWriting,
+ bot,
+ onCancel,
+ onSubmit,
+ onExtend,
+}) => {
+ const onKey = useComposerKeys(w, setWriting, onCancel, onSubmit);
+ const title = useId();
+ return (
+ <div className="fixed inset-0 z-50 flex flex-col justify-end bg-black/40" onClick={(e) => e.target === e.currentTarget && !w.text.trim() && onCancel()}>
+ <div
+ role="dialog"
+ aria-modal="true"
+ aria-labelledby={title}
+ data-ln-sheet
+ onKeyDown={(e) => e.key === 'Escape' && !w.text.trim() && onCancel()}
+ className="max-h-[85vh] overflow-y-auto rounded-t-2xl border-t border-white/10 bg-surface-raised px-4 pb-[max(1rem,env(safe-area-inset-bottom))] pt-2.5"
+ >
+ <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}`}
+ <span className="text-[13px] font-normal text-zinc-400 [overflow-wrap:anywhere]">
+ {base(w.path)} · {lineWords(w.start, w.end)}
+ </span>
+ </h2>
+ {w.code.length > 0 && (
+ <pre className="mt-2 max-h-32 overflow-y-auto whitespace-pre-wrap break-words rounded-lg border border-hairline bg-[var(--dv-code-bg)] px-2.5 py-1.5 font-mono text-[12.5px] leading-5 text-zinc-300">
+ {codeText(w.code)}
+ </pre>
+ )}
+ <textarea
+ data-ln-text
+ autoFocus
+ aria-labelledby={title}
+ placeholder="Say what to change"
+ value={w.text}
+ maxLength={4000}
+ onChange={(e) => setWriting((x) => (x ? { ...x, text: e.target.value, asking: false } : x))}
+ onKeyDown={onKey}
+ className="mt-2.5 block min-h-[76px] w-full resize-none rounded-xl border border-violet-400/70 bg-[var(--dv-code-bg)] px-3 py-2.5 text-[15px] leading-6 text-zinc-100 placeholder:text-[#8a8a96] focus:outline-none focus:ring-[3px] focus:ring-violet-500/20"
+ />
+ {w.error && (
+ <p role="alert" className="mt-1.5 text-meta text-rose-300">
+ {w.error}
+ </p>
+ )}
+ {onExtend && (
+ <p className="mt-2 text-[13px] text-zinc-400">
+ Tap another line first to note a range.{' '}
+ <button type="button" onClick={onExtend} className={`min-h-11 rounded font-medium text-violet-300 ${RING}`}>
+ Extend to line…
+ </button>
+ </p>
+ )}
+ {w.asking ? (
+ <AskThrowAway setWriting={setWriting} onCancel={onCancel} big />
+ ) : (
+ <div className="mt-2 grid grid-cols-2 gap-2.5">
+ <button
+ type="button"
+ onClick={() => (w.text.trim() ? setWriting((x) => (x ? { ...x, asking: true } : x)) : onCancel())}
+ className="kw-btn-ghost min-h-11 !text-[15px]"
+ >
+ Cancel
+ </button>
+ <button type="button" disabled={!w.text.trim() || w.busy} onClick={onSubmit} className="kw-btn-primary min-h-11 !text-[15px]">
+ {w.busy && <Loader2 size={15} aria-hidden="true" className="motion-safe:animate-spin" />}
+ {w.editing ? 'Save' : 'Add note'}
+ </button>
+ </div>
+ )}
+ </div>
+ </div>
+ );
+};
+
+// ---------------------------------------------------------------------------------------------------
+// The send bar
+
+interface SendBarProps {
+ bar: Bar;
+ setBar: (b: Bar) => void;
+ drafts: number;
+ bot: string;
+ phone: boolean;
+ onSend: () => void;
+ onDiscard: () => void;
+ onOpenChat?: (botId: string) => void;
+}
+
+const SendBar: React.FC<SendBarProps> = ({ bar, setBar, drafts, bot, phone, onSend, onDiscard, onOpenChat }) => {
+ const [menu, setMenu] = useState(false);
+ const tooMany = drafts > MAX_SEND;
+ const failed = bar.s === 'failed';
+ 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';
+ const keep = useRef<HTMLButtonElement>(null);
+ useEffect(() => {
+ if (bar.s === 'confirm') keep.current?.focus();
+ }, [bar.s]);
+ return (
+ <div
+ data-ln-bar={bar.s}
+ role="region"
+ aria-label="Notes to send"
+ className={`${where} flex flex-wrap items-center gap-x-3 gap-y-2 border-t py-2.5 backdrop-blur ${failed ? 'border-rose-300/35 bg-[#1a1538]/95' : 'border-white/10 bg-[#1a1538]/95'}`}
+ >
+ {bar.s === 'sent' ? (
+ <>
+ <span className="inline-flex min-w-0 flex-1 items-center gap-2 text-meta text-zinc-200">
+ <Check size={14} aria-hidden="true" className="shrink-0 text-teal-300" />
+ {sentLine(bar.n, bar.bot, bar.at)}
+ </span>
+ {onOpenChat && bar.botId && (
+ <button type="button" onClick={() => onOpenChat(bar.botId!)} className={`inline-flex min-h-8 items-center gap-0.5 rounded text-[12px] font-medium text-violet-300 hover:text-violet-200 max-sm:min-h-11 ${RING}`}>
+ Open {bar.bot}’s chat
+ <ChevronRight size={14} aria-hidden="true" />
+ </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">
+ Try again
+ </button>
+ </>
+ ) : bar.s === 'confirm' ? (
+ <>
+ <span className="min-w-0 flex-1 text-meta text-zinc-200">{discardAsk(drafts)}</span>
+ <button type="button" onClick={onDiscard} className="kw-btn-ghost max-sm:min-h-11">
+ Discard
+ </button>
+ <button ref={keep} type="button" onClick={() => setBar({ s: 'idle' })} className="kw-btn-primary max-sm:min-h-11">
+ Keep
+ </button>
+ </>
+ ) : (
+ <>
+ <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>
+ <span className="min-w-0 [overflow-wrap:anywhere]">
+ <strong className="font-semibold text-zinc-100">{notesWord(drafts)}</strong> for {bot}
+ {!phone && <span className="text-zinc-400"> · drafts, only you see them</span>}
+ {tooMany && <span className="block text-zinc-400">{TOO_MANY}</span>}
+ </span>
+ </span>
+ {phone ? (
+ <span className="relative">
+ <button
+ type="button"
+ aria-label="More"
+ aria-haspopup="menu"
+ aria-expanded={menu}
+ onClick={() => setMenu((m) => !m)}
+ className={`inline-flex h-11 w-11 items-center justify-center rounded-xl text-zinc-300 hover:bg-white/[.06] ${RING}`}
+ >
+ <MoreHorizontal size={18} aria-hidden="true" />
+ </button>
+ {menu && (
+ <span role="menu" className="absolute bottom-12 right-0 min-w-[10rem] rounded-xl border border-white/10 bg-surface-raised p-1 shadow-card">
+ <button
+ type="button"
+ role="menuitem"
+ autoFocus
+ onClick={() => {
+ setMenu(false);
+ setBar({ s: 'confirm' });
+ }}
+ className={`flex min-h-11 w-full items-center rounded-lg px-3 text-left text-[15px] text-zinc-200 hover:bg-white/[.06] ${RING}`}
+ >
+ Discard all
+ </button>
+ </span>
+ )}
+ </span>
+ ) : (
+ <button type="button" disabled={bar.s === 'sending'} onClick={() => setBar({ s: 'confirm' })} className="kw-btn-ghost">
+ Discard all
+ </button>
+ )}
+ <button
+ type="button"
+ data-ln-send
+ disabled={bar.s === 'sending' || tooMany}
+ onClick={onSend}
+ aria-label={bar.s === 'sending' ? 'Sending…' : sendLabel(drafts, bot)}
+ className={`kw-btn-primary ${phone ? 'min-h-11 !text-[15px]' : ''}`}
+ >
+ {bar.s === 'sending' ? (
+ <>
+ <Loader2 size={14} aria-hidden="true" className="motion-safe:animate-spin" />
+ Sending…
+ </>
+ ) : (
+ <>
+ <ArrowUp size={14} aria-hidden="true" />
+ {phone ? sendShort(drafts) : sendLabel(drafts, bot)}
+ </>
+ )}
+ </button>
+ </>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/components/dev/ReviewCard.tsx b/frontend/src/components/dev/ReviewCard.tsx
index b9a33612..58133ffd 100644
--- a/frontend/src/components/dev/ReviewCard.tsx
+++ b/frontend/src/components/dev/ReviewCard.tsx
@@ -13,6 +13,7 @@ import {
GitBranch,
} from 'lucide-react';
import { FreshEyesChip } from './FreshEyesChip';
+import { ChangesSection } from './LineNotes';
import type { DevFinding, FindingAction, Forge, ReviewCard as Review, ReviewCardProps, Severity, TamperFlag } from '../../dev/types';
import {
clock,
@@ -414,7 +415,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 = [] }) => {
+export const ReviewCard: React.FC<ReviewCardProps> = ({ card: given, onFinding, sample = false, now: fixedNow, onPost, forge = null, forgeLogin = null, repoLabel, jiraOrigins = [], lineNotes, onOpenChat }) => {
const [card, setCard] = useState<Review>(given);
const [busy, setBusy] = useState<string | null>(null);
const [tick, setTick] = useState(() => Date.now());
@@ -573,6 +574,19 @@ export const ReviewCard: React.FC<ReviewCardProps> = ({ card: given, onFinding,
</div>
</header>
+ {/* 0.9.0 G1: the diff, with line notes for the author bot (g1-line-notes.md §1). */}
+ {lineNotes && card.changes && (
+ <ChangesSection
+ cardId={card.id}
+ api={lineNotes}
+ stat={card.changes}
+ notesCount={card.line_notes}
+ headSha={card.head_sha}
+ prUrl={card.links.pr ?? null}
+ onOpenChat={onOpenChat}
+ />
+ )}
+
{card.status === 'pending' && (
<div data-reading>
<p role="status" className="mt-3 flex items-center gap-2.5 rounded-[10px] border border-hairline bg-[var(--dv-code-bg)] px-3 py-2.5 font-mono text-[12.5px] leading-[18px] text-zinc-300 [overflow-wrap:anywhere]">
diff --git a/frontend/src/dev/lineNotes.ts b/frontend/src/dev/lineNotes.ts
new file mode 100644
index 00000000..4aa5bd7f
--- /dev/null
+++ b/frontend/src/dev/lineNotes.ts
@@ -0,0 +1,382 @@
+// 0.9.0 G1 line notes on a diff (Mira, release-090/designs/g1-line-notes.md; Juno's routes in
+// release-090/g1-api.md). Types, parsers and the pure logic behind the Changes section of a review card.
+// Every parse* takes the route's raw JSON and returns typed data (strings trimmed, never rendered as
+// HTML), or null when it can't be drawn honestly. Nothing here computes a new figure for display: the
+// counts on screen are the server's, or the length of a list the person can see.
+//
+// Built to Juno's answers (g1-api.md, 07:20 UTC), all 12 asks accepted:
+// - A note's anchor: `start`/`end` objects ({side, line}, ask 3); `code` is the noted lines as diff lines.
+// - Where a note sits in the current diff: `at_head` (ask 5), null when its lines aren't there; `seen_sha`
+// is the newer head (draft: "pushed … after you wrote this" with at_head, "gone" without).
+// - Errors: `{error, code}` (ask 7); the UI branches on `code`.
+// - Omitted patches: `omitted` (ask 8). `cut`: `{files_not_read}` (ask 9).
+
+export type Side = 'new' | 'old';
+export type LineKind = 'ctx' | 'add' | 'del';
+export type NoteState = 'draft' | 'sent' | 'resolved' | 'open';
+export type PrState = 'open' | 'merged' | 'closed';
+
+export interface DiffLine {
+ kind: LineKind;
+ old: number | null;
+ new: number | null;
+ text: string;
+}
+export interface Hunk {
+ header: string;
+ lines: DiffLine[];
+}
+export interface ChangedFile {
+ path: string;
+ old_path: string | null;
+ status: string;
+ additions: number;
+ deletions: number;
+ omitted: 'binary' | 'too_large' | null;
+ big: boolean;
+ notes: number;
+ hunks: Hunk[];
+}
+export interface Changes {
+ card_id: string;
+ repo: string | null;
+ pr: number | null;
+ head_sha: string | null;
+ pr_url: string | null;
+ pr_state: PrState;
+ author_bot: { id: string; name: string } | null;
+ author_login: string | null;
+ files: ChangedFile[];
+ /** Files the server didn't read (ask 9). */
+ cut: { files_not_read: number } | null;
+}
+
+export interface LinePoint {
+ side: Side;
+ line: number;
+}
+export interface Note {
+ id: string;
+ path: string;
+ start: LinePoint;
+ end: LinePoint;
+ /** The noted lines as written on, in the /changes line shape (the UI draws the markers). */
+ code: DiffLine[];
+ text: string;
+ state: NoteState;
+ head_sha: string | null;
+ created_at: string | null;
+ updated_at: string | null;
+ sent_at: string | null;
+ message_id: string | null;
+ checked_sha: string | null;
+ /** Where the note sits in the card's current head diff; null: not in it (shown at the top of its file). */
+ at_head: { start: LinePoint; end: LinePoint } | null;
+ /** The card's head when it differs from the note's own head_sha. */
+ seen_sha: string | null;
+ /** A draft written on an older head whose lines are still in the diff (maybe at other numbers). */
+ moved: boolean;
+ gone: boolean;
+}
+export interface NotesSummary {
+ total: number;
+ changed: number;
+ open: number;
+ sha: string | null;
+}
+export interface NotesPage {
+ notes: Note[];
+ summary: NotesSummary | null;
+}
+export interface SendResult {
+ sent: number;
+ message_id: string | null;
+ kwant_id: string | null;
+ kwant_name: string | null;
+ sent_at: string | null;
+ notes: Note[];
+}
+
+// ---------------------------------------------------------------------------------------------------
+// Parsing
+
+const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
+const arr = (v: unknown): unknown[] => (Array.isArray(v) ? v : []);
+const str = (v: unknown, max: number): string | null => (typeof v === 'string' && v.trim() ? v.slice(0, max) : null);
+/** Code keeps its spaces: an empty or blank line is a line too. */
+const code = (v: unknown, max = 2000): string | null => (typeof v === 'string' ? v.slice(0, max) : null);
+const whole = (v: unknown): number | null => (typeof v === 'number' && Number.isInteger(v) && v >= 0 ? v : null);
+const lineNo = (v: unknown): number | null => (typeof v === 'number' && Number.isInteger(v) && v >= 1 ? v : null);
+const side = (v: unknown): Side | null => (v === 'new' || v === 'old' ? v : null);
+
+/** Lines past this are not drawn (the server cuts big files long before). */
+export const MAX_LINES_PER_FILE = 5000;
+
+function diffLine(v: unknown): DiffLine | null {
+ if (!isObj(v)) return null;
+ const kind = v.kind === 'ctx' || v.kind === 'add' || v.kind === 'del' ? v.kind : null;
+ const text = code(v.text);
+ if (!kind || text === null) return null;
+ const oldN = lineNo(v.old);
+ const newN = lineNo(v.new);
+ // Every line needs the number of the side it lives on.
+ if (kind === 'add' && newN === null) return null;
+ if (kind === 'del' && oldN === null) return null;
+ if (kind === 'ctx' && (newN === null || oldN === null)) return null;
+ return { kind, old: kind === 'add' ? null : oldN, new: kind === 'del' ? null : newN, text };
+}
+
+function changedFile(v: unknown): ChangedFile | null {
+ if (!isObj(v)) return null;
+ const path = str(v.path, 600);
+ if (!path) return null;
+ const omitted = v.omitted === 'binary' || v.omitted === 'too_large' ? v.omitted : null;
+ let budget = MAX_LINES_PER_FILE;
+ const hunks: Hunk[] = [];
+ for (const h of arr(v.hunks)) {
+ if (!isObj(h) || budget <= 0) continue;
+ const lines = arr(h.lines)
+ .map(diffLine)
+ .filter((l): l is DiffLine => !!l)
+ .slice(0, budget);
+ budget -= lines.length;
+ if (lines.length) hunks.push({ header: str(h.header, 400) ?? '', lines });
+ }
+ return {
+ path,
+ old_path: str(v.old_path, 600),
+ status: str(v.status, 20) ?? 'modified',
+ additions: whole(v.additions) ?? 0,
+ deletions: whole(v.deletions) ?? 0,
+ omitted,
+ big: v.big === true,
+ notes: whole(v.notes) ?? 0,
+ hunks: omitted ? [] : hunks,
+ };
+}
+
+export function parseChanges(raw: unknown): Changes | null {
+ if (!isObj(raw) || !Array.isArray(raw.files)) return null;
+ const ab = isObj(raw.author_bot) ? raw.author_bot : null;
+ const abId = ab ? str(ab.id, 120) : null;
+ const abName = ab ? str(ab.name, 80) : null;
+ const notRead = isObj(raw.cut) ? whole(raw.cut.files_not_read) : null;
+ return {
+ card_id: str(raw.card_id, 200) ?? '',
+ repo: str(raw.repo, 300),
+ pr: whole(raw.pr),
+ head_sha: str(raw.head_sha, 64),
+ pr_url: str(raw.pr_url, 600) && /^https:\/\//.test(raw.pr_url as string) ? (raw.pr_url as string).slice(0, 600) : null,
+ pr_state: raw.pr_state === 'merged' || raw.pr_state === 'closed' ? raw.pr_state : 'open',
+ author_bot: abId && abName ? { id: abId, name: abName } : null,
+ author_login: str(raw.author_login, 80),
+ files: raw.files.map(changedFile).filter((f): f is ChangedFile => !!f),
+ cut: notRead ? { files_not_read: notRead } : null,
+ };
+}
+
+function point(v: unknown): LinePoint | null {
+ if (!isObj(v)) return null;
+ const s = side(v.side);
+ const l = lineNo(v.line);
+ return s && l ? { side: s, line: l } : null;
+}
+
+/** `{start, end}` objects (ask 3). */
+function span(v: Record<string, unknown>): { start: LinePoint; end: LinePoint } | null {
+ const a = point(v.start);
+ const b = point(v.end);
+ return a && b ? { start: a, end: b } : null;
+}
+
+export function parseNote(v: unknown): Note | null {
+ if (!isObj(v)) return null;
+ const id = str(v.id, 120);
+ const path = str(v.path, 600);
+ const where = span(v);
+ if (!id || !path || !where) return null;
+ const state: NoteState = v.state === 'sent' || v.state === 'resolved' || v.state === 'open' ? v.state : 'draft';
+ const headSha = str(v.head_sha, 64);
+ const atHead = isObj(v.at_head) ? span(v.at_head) : null;
+ const seen = str(v.seen_sha, 64);
+ return {
+ id,
+ path,
+ start: where.start,
+ end: where.end,
+ code: arr(v.code)
+ .map(diffLine)
+ .filter((c): c is DiffLine => !!c)
+ .slice(0, 200),
+ text: typeof v.text === 'string' ? v.text.slice(0, 4000) : '',
+ state,
+ head_sha: headSha,
+ created_at: str(v.created_at, 64),
+ updated_at: str(v.updated_at, 64),
+ sent_at: str(v.sent_at, 64),
+ message_id: str(v.message_id, 120),
+ checked_sha: str(v.checked_sha, 64),
+ at_head: atHead,
+ seen_sha: seen,
+ moved: state === 'draft' && !!seen && !!atHead,
+ gone: state === 'draft' && !!seen && !atHead,
+ };
+}
+
+export function parseNotes(raw: unknown): NotesPage | null {
+ if (!isObj(raw) || !Array.isArray(raw.notes)) return null;
+ const s = isObj(raw.summary) ? raw.summary : null;
+ const total = s ? whole(s.total) : null;
+ return {
+ notes: raw.notes.map(parseNote).filter((n): n is Note => !!n),
+ summary:
+ s && total !== null ? { total, changed: whole(s.changed) ?? 0, open: whole(s.open) ?? 0, sha: str(s.sha, 64) } : null,
+ };
+}
+
+export function parseSendResult(raw: unknown): SendResult | null {
+ if (!isObj(raw)) return null;
+ const sent = whole(raw.sent);
+ if (sent === null) return null;
+ return {
+ sent,
+ message_id: str(raw.message_id, 120),
+ kwant_id: str(raw.kwant_id, 120),
+ kwant_name: str(raw.kwant_name, 80),
+ sent_at: str(raw.sent_at, 64),
+ notes: arr(raw.notes)
+ .map(parseNote)
+ .filter((n): n is Note => !!n),
+ };
+}
+
+/** Ask 1: the card's own `changes` and `notes` counts, so the collapsed row needs no fetch. */
+export function parseCardChanges(v: unknown): { files: number; additions: number; deletions: number } | null {
+ if (!isObj(v)) return null;
+ const files = whole(v.files);
+ if (files === null) return null;
+ return { files, additions: whole(v.additions) ?? 0, deletions: whole(v.deletions) ?? 0 };
+}
+export function parseCardNotes(v: unknown): { drafts: number; total: number } | null {
+ if (!isObj(v)) return null;
+ const total = whole(v.total);
+ if (total === null) return null;
+ return { drafts: whole(v.drafts) ?? 0, total };
+}
+
+// ---------------------------------------------------------------------------------------------------
+// Lines and ranges
+
+/** The side and number a line is anchored by: removed lines on the old side, the rest on the new. */
+export function pointOf(l: DiffLine): LinePoint {
+ return l.kind === 'del' ? { side: 'old', line: l.old! } : { side: 'new', line: l.new! };
+}
+
+const MARK: Record<LineKind, string> = { add: '+', del: '-', ctx: ' ' };
+/** Quoted code as plain text, one diff marker per line (never HTML). */
+export const codeText = (lines: readonly DiffLine[]) => lines.map((l) => `${MARK[l.kind]} ${l.text}`).join('\n');
+
+/** The number shown for a line on the phone (new side; removed lines show their old number). */
+export const shownNo = (l: DiffLine): number => (l.kind === 'del' ? l.old! : l.new!);
+
+/** A file's lines in order, with the hunk each belongs to. Hunk headers are not lines. */
+export interface FlatLine {
+ i: number;
+ hunk: number;
+ line: DiffLine;
+}
+export function flatLines(f: ChangedFile): FlatLine[] {
+ const out: FlatLine[] = [];
+ f.hunks.forEach((h, hi) => h.lines.forEach((line) => out.push({ i: out.length, hunk: hi, line })));
+ return out;
+}
+
+const samePoint = (a: LinePoint, b: LinePoint) => a.side === b.side && a.line === b.line;
+
+/** Index of the line with this anchor, or -1. */
+export function indexOfPoint(lines: FlatLine[], p: LinePoint): number {
+ return lines.findIndex((x) => samePoint(pointOf(x.line), p));
+}
+
+/** Design board: a range covers at most 40 lines. */
+export const MAX_RANGE = 40;
+
+/**
+ * The range from `anchor` toward `to`, kept inside the anchor's hunk (a note never crosses hunks) and at
+ * most MAX_RANGE lines. Returns [from, to] in order.
+ */
+export function clampRange(lines: FlatLine[], anchor: number, to: number): [number, number] {
+ const hunk = lines[anchor]?.hunk;
+ let t = Math.max(0, Math.min(lines.length - 1, to));
+ while (t !== anchor && lines[t].hunk !== hunk) t += t > anchor ? -1 : 1;
+ if (Math.abs(t - anchor) >= MAX_RANGE) t = anchor + (t > anchor ? MAX_RANGE - 1 : -(MAX_RANGE - 1));
+ return t < anchor ? [t, anchor] : [anchor, t];
+}
+
+/** "line 42" / "lines 40–42", by the numbers shown in the gutter. */
+export function lineWords(a: LinePoint, b: LinePoint): string {
+ return samePoint(a, b) ? `line ${a.line}` : `lines ${a.line}–${b.line}`;
+}
+
+/** Where a note sits in the diff being shown: [first, last] indexes, or null (top of the file). */
+export function positionIn(lines: FlatLine[], n: Note): [number, number] | null {
+ if (!n.at_head) return null;
+ const a = indexOfPoint(lines, n.at_head.start);
+ const b = indexOfPoint(lines, n.at_head.end);
+ if (a < 0 || b < 0 || b < a) return null;
+ return [a, b];
+}
+
+// ---------------------------------------------------------------------------------------------------
+// Copy (Mira's "Copy (all)"; no emoji, no HTML)
+
+const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
+
+export const MAX_SEND = 20;
+export const sha7 = (s: string | null) => (s ? s.trim().slice(0, 7) : '');
+
+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}`);
+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?`);
+export const SEND_FAILED = 'The notes didn’t send. They’re still here.';
+export const TOO_MANY = 'Up to 20 notes per send';
+export const LOAD_FAILED = 'Couldn’t load the changes.';
+export const NO_DIFF = 'No changes to show: GitHub sent no diff for these files.';
+export const notBotLine = (login: string | null) =>
+ `Notes go to bots in this space. This PR is by ${login ?? 'someone outside this space'}, so there’s nothing to send them to.`;
+export const readOnlyLine = (s: PrState) => (s === 'merged' ? 'This PR is merged. Notes are read-only.' : 'This PR is closed. Notes are read-only.');
+export const sentNoteLine = (at: string | null, bot: string) => `Sent${at ? ` ${at}` : ''} · waiting for ${bot}’s next push`;
+export const changedIn = (sha: string | null) => `Changed in ${sha7(sha)}`.trimEnd();
+export const stillOpen = (sha: string | null) => `Still open · line unchanged in ${sha7(sha)}`.trimEnd();
+export const movedLine = (bot: string, sha: string | null, to: number | null) =>
+ `${bot} pushed ${sha7(sha) || 'a new commit'} after you wrote this.${to !== null ? ` The line is now ${to}.` : ''}`;
+export const goneLine = (sha: string | null) => `This line is gone in ${sha7(sha) || 'the newest push'}.`;
+export const summaryLine = (s: NotesSummary) =>
+ `${notesWord(s.total)} · ${s.changed} changed in ${sha7(s.sha)} · ${s.open} still open`;
+export const addedSay = (at: string, drafts: number, bot: string) => `Note added on ${at}. ${notesWord(drafts)} for ${bot}.`;
+export const resolvedSay = (s: NotesSummary) => `${s.changed} ${s.changed === 1 ? 'note' : 'notes'} changed in ${sha7(s.sha)}, ${s.open} still open.`;
+export const showLines = (n: number) => `Show ${n.toLocaleString('en-US')} ${n === 1 ? 'line' : 'lines'}`;
+export const cutLine = (c: NonNullable<Changes['cut']>) => `${plural(c.files_not_read, 'file')} not read: the diff was cut.`;
+
+/** The note's state line for its header (drafts say "Draft"). */
+export function stateWords(n: Note, bot: string, clockOf: (iso: string | null) => string | null): string {
+ switch (n.state) {
+ case 'draft':
+ return 'Draft';
+ case 'sent':
+ return sentNoteLine(clockOf(n.sent_at), bot);
+ case 'resolved':
+ return changedIn(n.checked_sha);
+ case 'open':
+ return stillOpen(n.checked_sha);
+ }
+}
+
+/** Lockfiles start collapsed like big files (design "Big file"). */
+export const LOCKFILE = /(^|\/)(package-lock\.json|yarn\.lock|pnpm-lock\.yaml|Cargo\.lock|Gemfile\.lock|poetry\.lock|composer\.lock|go\.sum|bun\.lockb?)$/;
+export const startsCollapsed = (f: ChangedFile) => f.big || LOCKFILE.test(f.path);
diff --git a/frontend/src/dev/lineNotesApi.ts b/frontend/src/dev/lineNotesApi.ts
new file mode 100644
index 00000000..5952ef20
--- /dev/null
+++ b/frontend/src/dev/lineNotesApi.ts
@@ -0,0 +1,135 @@
+// 0.9.0 G1: the line-notes routes (Juno, release-090/g1-api.md). The card's Changes section only talks to
+// this interface, so tests and the shot harness pass a fake one. Every answer goes through the parsers in
+// lineNotes.ts; an answer the app can't read is an error with code `bad_shape`.
+
+import type { Changes, LinePoint, Note, NotesPage, SendResult } from './lineNotes';
+import { parseChanges, parseNote, parseNotes, parseSendResult } from './lineNotes';
+
+/** A failed call: `code` is Juno's machine code (ask 7), `status` the HTTP status (0: no connection). */
+export class LineNotesError extends Error {
+ constructor(message: string, public status: number, public code: string | null = null, public data: Record<string, unknown> | null = null) {
+ super(message);
+ }
+}
+
+export interface NewNote {
+ path: string;
+ start: LinePoint;
+ end: LinePoint;
+ /** The head the person was looking at (ask 4: 409 stale_head when the card moved on). */
+ head_sha: string | null;
+ text: string;
+}
+
+export interface LineNotesApi {
+ changes(cardId: string): Promise<Changes>;
+ notes(cardId: string): Promise<NotesPage>;
+ create(cardId: string, n: NewNote): Promise<Note>;
+ edit(noteId: string, text: string): Promise<Note>;
+ 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>;
+}
+
+/** (url, method, body) → parsed JSON, or throws LineNotesError. */
+export type Caller = (url: string, method: string, body?: unknown) => Promise<unknown>;
+
+const enc = encodeURIComponent;
+
+/** The words for a code the person can act on; anything else is the server's own sentence or a generic one. */
+export function errorWords(code: string | null, fallback: string | null, status: number): string {
+ switch (code) {
+ case 'too_many':
+ return 'Up to 20 notes per send';
+ case 'too_long':
+ return 'A note can be up to 4,000 characters.';
+ case 'range_too_big':
+ return 'A note can cover up to 200 lines.';
+ case 'empty':
+ return 'Say what to change first.';
+ case 'stale_head':
+ return 'The bot pushed again. The changes reloaded; your note is still here.';
+ case 'no_author':
+ return 'This PR has no bot to send the notes to.';
+ case 'pr_merged':
+ return 'This PR is merged. Notes are read-only.';
+ case 'pr_closed':
+ return 'This PR is closed. Notes are read-only.';
+ case 'not_draft':
+ return 'This note was already sent.';
+ case 'forge_failed':
+ return 'Couldn’t load the changes.';
+ case 'cross_hunk':
+ return 'A note can cover lines from one block of changes only.';
+ case 'not_found':
+ return 'That note is gone. It can only be restored for a minute after deleting.';
+ case 'send_id_reused':
+ return 'These notes changed while sending. Try sending again.';
+ case 'bad_request':
+ return 'Something went wrong sending this. Try again.';
+ }
+ if (status === 0) return 'Couldn’t reach the server. Check your connection and try again.';
+ return fallback && !/^[a-z_]+$/.test(fallback) ? fallback : `Something went wrong (HTTP ${status}).`;
+}
+
+/** The default caller: same-origin fetch with the person's session (the app passes personFetch). */
+export function fetchCaller(send: typeof fetch): Caller {
+ return async (url, method, body) => {
+ let res: Response;
+ try {
+ res = await send(url, {
+ method,
+ cache: 'no-store',
+ headers: body === undefined ? undefined : { 'Content-Type': 'application/json' },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+ } catch {
+ throw new LineNotesError(errorWords(null, null, 0), 0);
+ }
+ const data: unknown = await res.json().catch(() => null);
+ if (res.ok) return data;
+ const o = data && typeof data === 'object' ? (data as Record<string, unknown>) : {};
+ const code = typeof o.code === 'string' ? o.code : typeof o.error === 'string' && /^[a-z_]+$/.test(o.error) ? o.error : null;
+ throw new LineNotesError(errorWords(code, typeof o.error === 'string' ? o.error : null, res.status), res.status, code, o);
+ };
+}
+
+const shape = () => new LineNotesError('The server sent notes in a shape this app doesn’t know.', 200, 'bad_shape');
+function need<T>(v: T | null): T {
+ if (v === null) throw shape();
+ return v;
+}
+
+/** Ask 3: start and end each name their side, so a range may cross added and removed lines. */
+const createBody = (n: NewNote) => ({ path: n.path, start: n.start, end: n.end, head_sha: n.head_sha, text: n.text });
+
+export function lineNotesApi(call: Caller): LineNotesApi {
+ const card = (id: string) => `/api/dev/cards/${enc(id)}`;
+ const note = (id: string) => `/api/dev/notes/${enc(id)}`;
+ return {
+ changes: async (id) => need(parseChanges(await call(`${card(id)}/changes`, 'GET'))),
+ notes: async (id) => need(parseNotes(await call(`${card(id)}/notes`, 'GET'))),
+ create: async (id, n) => need(parseNote(await call(`${card(id)}/notes`, 'POST', createBody(n)))),
+ edit: async (id, text) => need(parseNote(await call(note(id), 'PATCH', { text }))),
+ remove: async (id) => {
+ await call(note(id), 'DELETE');
+ },
+ restore: async (id) => need(parseNote(await call(`${note(id)}/restore`, 'POST', {}))),
+ discardAll: async (id) => {
+ const r = await call(`${card(id)}/notes`, 'DELETE');
+ 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 }))),
+ };
+}
+
+/** A send id per batch: a Try again reuses it, a new batch gets a new one. */
+export function newSendId(): string {
+ const c = (globalThis as { crypto?: Crypto }).crypto;
+ if (c?.randomUUID) return c.randomUUID();
+ return `snd_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
+}
diff --git a/frontend/src/dev/types.ts b/frontend/src/dev/types.ts
index b218666f..537917aa 100644
--- a/frontend/src/dev/types.ts
+++ b/frontend/src/dev/types.ts
@@ -8,6 +8,7 @@
import { parseMatches } from './tickets';
import { parseFreshEyes, type FreshEyes } from './freshEyes';
+import { parseCardChanges, parseCardNotes } from './lineNotes';
import type { ReviewMatches } from './tickets';
export type CardStatus = 'pending' | 'ready' | 'failed' | 'stale';
@@ -143,6 +144,12 @@ export interface ReviewCard extends CardBase {
posted: ReviewPosted | null;
/** Why the last post didn't go through; a successful post clears it. */
post_error: PostError | null;
+ /** 0.9.0 G1 (g1-api.md ask 1): the PR head the card was built at. null from an older server. */
+ head_sha: string | null;
+ /** 0.9.0 G1: the diff's counts for the collapsed Changes row; null hides the section. */
+ changes: { files: number; additions: number; deletions: number } | null;
+ /** 0.9.0 G1: the person's line notes on this card (drafts are theirs only); the payload's `notes`. */
+ line_notes: { drafts: number; total: number } | null;
}
export type Forge = 'github' | 'gitlab' | 'gitea' | 'forgejo';
@@ -271,6 +278,10 @@ export interface ReviewCardProps {
repoLabel?: (repo: string | null, name?: string | null) => string | null;
/** 0.7.6: the saved Jira site's origins; "Matches the ticket" links to Jira only there (api-decisions 18). */
jiraOrigins?: readonly string[];
+ /** 0.9.0 G1: the line-notes routes; without it the card has no Changes section. */
+ lineNotes?: import('./lineNotesApi').LineNotesApi;
+ /** 0.9.0 G1: "Open {bot}'s chat" after a send. */
+ onOpenChat?: (botId: string) => void;
}
export interface ReleaseNotesSheetProps {
@@ -458,6 +469,9 @@ export function parseReview(raw: unknown): ReviewCard | null {
links: links(raw.links),
posted: posted(raw.posted),
post_error: postError(raw.post_error),
+ head_sha: str(raw.head_sha, 64),
+ changes: parseCardChanges(raw.changes),
+ line_notes: parseCardNotes(raw.notes),
};
}
diff --git a/frontend/tests/lineNotes.test.mjs b/frontend/tests/lineNotes.test.mjs
new file mode 100644
index 00000000..dfc5e4a4
--- /dev/null
+++ b/frontend/tests/lineNotes.test.mjs
@@ -0,0 +1,664 @@
+// 0.9.0 G1 line notes on a diff (Mira, release-090/designs/g1-line-notes.md; Juno, release-090/g1-api.md).
+// The parsers, the range logic, the copy, the API client against a fake caller, and the Changes section
+// against an injected fake api. Demo data only; no network.
+import assert from 'node:assert/strict';
+import test from 'node:test';
+import { JSDOM } from 'jsdom';
+import { loadBundled } from './bundle.mjs';
+
+const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/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 { flushSync } from 'react-dom';
+ export * from './src/dev/lineNotes';
+ export * from './src/dev/lineNotesApi';
+ export { ChangesSection } from './src/components/dev/LineNotes';
+ export { ReviewCard } from './src/components/DevDeskSlots';
+ export { parseReview } from './src/dev/types';
+ 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));
+};
+
+// ---------------------------------------------------------------------------------------------------
+// Demo data
+
+const HEAD = 'c3d9a18f00000000000000000000000000000000';
+const NEXT = 'e81f2c4a00000000000000000000000000000000';
+const rawChanges = (over = {}) => ({
+ card_id: 'dvr_312',
+ repo: 'demo-org/app',
+ pr: 312,
+ head_sha: HEAD,
+ pr_url: 'https://github.com/demo-org/app/pull/312',
+ pr_state: 'open',
+ author_bot: { id: 'bot_vega', name: 'Vega' },
+ author_login: 'vega-bot',
+ files: [
+ {
+ path: 'src/server/auth.rs',
+ status: 'modified',
+ additions: 3,
+ deletions: 1,
+ hunks: [
+ {
+ header: '@@ -40,4 +40,6 @@ fn check_token',
+ lines: [
+ { kind: 'ctx', old: 40, new: 40, text: 'fn check_token(t: &str) -> bool {' },
+ { kind: 'del', old: 41, text: ' t.len() > 8' },
+ { kind: 'add', new: 41, text: ' let t = t.trim();' },
+ { kind: 'add', new: 42, text: ' t.len() >= 12' },
+ { kind: 'add', new: 43, text: ' && t.is_ascii()' },
+ { kind: 'ctx', old: 42, new: 44, text: '}' },
+ ],
+ },
+ {
+ header: '@@ -90,2 +92,2 @@',
+ lines: [
+ { kind: 'ctx', old: 90, new: 92, text: '// end' },
+ { kind: 'ctx', old: 91, new: 93, text: '' },
+ ],
+ },
+ ],
+ },
+ { path: 'Cargo.lock', status: 'modified', additions: 40, deletions: 12, big: false, hunks: [{ header: '@@ -1 +1 @@', lines: [{ kind: 'ctx', old: 1, new: 1, text: '# lock' }] }] },
+ { path: 'docs/logo.png', status: 'added', additions: 0, deletions: 0, omitted: 'binary', hunks: [] },
+ ],
+ ...over,
+});
+// Juno's final Note: every note has at_head (its place in the current diff); by default its own lines.
+const rawNote = (over = {}) => {
+ const n = {
+ id: 'ln_1',
+ path: 'src/server/auth.rs',
+ start: { side: 'new', line: 42 },
+ end: { side: 'new', line: 42 },
+ code: [{ kind: 'add', old: null, new: 42, text: ' t.len() >= 12' }],
+ text: 'Use a constant for the minimum length.',
+ state: 'draft',
+ head_sha: HEAD,
+ created_at: '2026-11-10T09:12:00Z',
+ seen_sha: null,
+ ...over,
+ };
+ return 'at_head' in over ? n : { ...n, at_head: { start: n.start, end: n.end } };
+};
+
+/** An in-memory api: records every call, can be told to fail. */
+function fakeApi({ changes = rawChanges(), notes = [], summary = null } = {}) {
+ const calls = [];
+ const s = { changes, notes: notes.map((n) => m.parseNote(n)), summary, fail: {}, seq: 1, deleted: new Map() };
+ const maybe = async (name) => {
+ calls.push(name);
+ const f = s.fail[name];
+ if (f) {
+ if (typeof f === 'number') s.fail[name] = f - 1 || undefined;
+ throw new m.LineNotesError('Nope.', 500, 'boom');
+ }
+ };
+ const api = {
+ async changes() {
+ await maybe('changes');
+ return m.parseChanges(s.changes);
+ },
+ async notes() {
+ await maybe('notes');
+ return { notes: s.notes.slice(), summary: s.summary };
+ },
+ async create(cardId, n) {
+ await maybe('create');
+ calls.push(['create', n]);
+ const note = m.parseNote({ id: `ln_new${s.seq++}`, path: n.path, start: n.start, end: n.end, code: [], text: n.text, state: 'draft', head_sha: n.head_sha, at_head: { start: n.start, end: n.end } });
+ s.notes.push(note);
+ return note;
+ },
+ async edit(id, text) {
+ await maybe('edit');
+ const i = s.notes.findIndex((x) => x.id === id);
+ s.notes[i] = { ...s.notes[i], text };
+ return s.notes[i];
+ },
+ async remove(id) {
+ await maybe('remove');
+ s.deleted.set(id, s.notes.find((x) => x.id === id));
+ s.notes = s.notes.filter((x) => x.id !== id);
+ },
+ async restore(id) {
+ await maybe('restore');
+ const n = s.deleted.get(id);
+ s.notes.push(n);
+ return n;
+ },
+ async discardAll() {
+ await maybe('discardAll');
+ const n = s.notes.filter((x) => x.state === 'draft').length;
+ s.notes = s.notes.filter((x) => x.state !== 'draft');
+ return n;
+ },
+ async send(cardId, sendId, ids) {
+ calls.push(['send', sendId, ids ?? null]);
+ await maybe('send');
+ const out = s.notes.filter((x) => x.state === 'draft' && (!ids || ids.includes(x.id))).map((x) => ({ ...x, state: 'sent', sent_at: '2026-11-10T09:30:00Z' }));
+ s.notes = s.notes.map((x) => out.find((o) => o.id === x.id) ?? x);
+ return { sent: out.length, message_id: 'msg_1', kwant_id: 'bot_vega', kwant_name: 'Vega', sent_at: '2026-11-10T09:30:00Z', notes: out };
+ },
+ };
+ return { api, calls, s };
+}
+
+let root = null;
+let host = null;
+async function mount(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_312', stat: { files: 3, additions: 43, deletions: 13 }, ...props }));
+ await settle();
+ return host;
+}
+const $ = (sel) => host.querySelector(sel);
+const $$ = (sel) => [...host.querySelectorAll(sel)];
+const click = async (el, init = {}) => {
+ assert.ok(el, 'element to click');
+ el.dispatchEvent(new window.MouseEvent('click', { bubbles: true, ...init }));
+ await settle();
+};
+const key = async (el, k, init = {}) => {
+ el.dispatchEvent(new window.KeyboardEvent('keydown', { key: k, bubbles: true, cancelable: true, ...init }));
+ await settle();
+};
+const byText = (text, sel = 'button') => $$(sel).find((b) => b.textContent.trim() === text);
+/** React's controlled textarea: set through the native setter so onChange fires. */
+const type = async (ta, value) => {
+ const set = Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value').set;
+ set.call(ta, value);
+ ta.dispatchEvent(new window.Event('input', { bubbles: true }));
+ await settle();
+};
+const plus = (side, line) => $(`[data-ln-point="${side}:${line}"] button`);
+
+// ---------------------------------------------------------------------------------------------------
+// Parsers
+
+test('parseChanges: keeps files, lines and counts; drops lines without their side number; reads omitted and the cut', () => {
+ const c = m.parseChanges(rawChanges({ cut: { files_not_read: 2 } }));
+ assert.equal(c.files.length, 3);
+ assert.deepEqual(c.author_bot, { id: 'bot_vega', name: 'Vega' });
+ const [auth, , png] = c.files;
+ assert.deepEqual(auth.hunks[0].lines[1], { kind: 'del', old: 41, new: null, text: ' t.len() > 8' });
+ assert.equal(auth.hunks[1].lines[1].text, '', 'a blank code line stays a line');
+ assert.equal(png.omitted, 'binary');
+ assert.deepEqual(c.cut, { files_not_read: 2 });
+ const bad = m.parseChanges(rawChanges({ files: [{ path: 'a', hunks: [{ header: '', lines: [{ kind: 'add', text: 'x' }, { kind: 'ctx', new: 1, text: 'y' }, { kind: 'zap', new: 1, old: 1, text: 'z' }] }] }] }));
+ assert.equal(bad.files[0].hunks.length, 0, 'every line missing its number is dropped');
+ assert.equal(m.parseChanges(rawChanges({ files: [{ path: 'b', omitted: 'too_large' }] })).files[0].omitted, 'too_large');
+ assert.equal(m.parseChanges(rawChanges({ cut: { files_not_read: 0 } })).cut, null, 'nothing cut');
+ assert.equal(m.parseChanges(rawChanges({ pr_url: 'javascript:alert(1)' })).pr_url, null, 'only https links');
+ assert.equal(m.parseChanges(rawChanges({ pr_state: 'weird' })).pr_state, 'open');
+ assert.equal(m.parseChanges(rawChanges({ author_bot: null })).author_bot, null);
+ assert.equal(m.parseChanges({ files: 'no' }), null);
+ assert.equal(m.parseChanges(null), null);
+});
+
+test('parseNote: start/end objects, code as diff lines, at_head and seen_sha make moved and gone', () => {
+ const a = m.parseNote(rawNote());
+ assert.deepEqual([a.start, a.end, a.at_head.end.line, a.moved, a.gone], [{ side: 'new', line: 42 }, { side: 'new', line: 42 }, 42, false, false]);
+ assert.deepEqual(a.code, [{ kind: 'add', old: null, new: 42, text: ' t.len() >= 12' }]);
+ assert.equal(m.codeText([...a.code, { kind: 'del', old: 41, new: null, text: 'x' }]), '+ t.len() >= 12\n- x');
+ assert.equal(m.parseNote({ id: 'x', path: 'p', side: 'old', start_line: 3, end_line: 5, text: 't' }), null, 'draft 1 anchors are gone');
+ assert.equal(m.parseNote({ id: 'x', path: 'p' }), null);
+ assert.equal(m.parseNote(rawNote({ at_head: null })).at_head, null, 'the server says it is not in the diff');
+ const moved = m.parseNote(rawNote({ seen_sha: NEXT, at_head: { start: { side: 'new', line: 44 }, end: { side: 'new', line: 44 } } }));
+ assert.deepEqual([moved.moved, moved.gone, moved.at_head.end.line, moved.seen_sha], [true, false, 44, NEXT]);
+ const gone = m.parseNote(rawNote({ seen_sha: NEXT, at_head: null }));
+ assert.deepEqual([gone.gone, gone.at_head, gone.moved], [true, null, false]);
+ assert.equal(m.parseNote(rawNote({ state: 'resolved', seen_sha: NEXT, at_head: null })).gone, false, 'only drafts are gone');
+ assert.equal(m.parseNote(rawNote({ state: 'nope' })).state, 'draft');
+ assert.equal(m.parseNote(rawNote({ text: '<b>hi</b>' })).text, '<b>hi</b>', 'text stays text');
+});
+
+test('parseNotes, parseSendResult and the card counts', () => {
+ const p = m.parseNotes({ notes: [rawNote(), { bad: 1 }], summary: { total: 3, changed: 2, open: 1, sha: NEXT } });
+ assert.equal(p.notes.length, 1);
+ assert.deepEqual(p.summary, { total: 3, changed: 2, open: 1, sha: NEXT });
+ assert.equal(m.parseNotes({ notes: [] }).summary, null);
+ assert.equal(m.parseNotes({}), null);
+ const r = m.parseSendResult({ sent: 2, message_id: 'msg', kwant_id: 'bot_vega', kwant_name: 'Vega', sent_at: 'x', notes: [rawNote({ state: 'sent' })] });
+ assert.deepEqual([r.sent, r.notes[0].state], [2, 'sent']);
+ assert.equal(m.parseSendResult({ sent: -1 }), null);
+ assert.deepEqual(m.parseCardChanges({ files: 3, additions: 43, deletions: 13 }), { files: 3, additions: 43, deletions: 13 });
+ assert.equal(m.parseCardChanges({ files: 1.5 }), null);
+ assert.equal(m.parseCardChanges(undefined), null);
+ assert.deepEqual(m.parseCardNotes({ drafts: 2, total: 5 }), { drafts: 2, total: 5 });
+ assert.equal(m.parseCardNotes({}), null);
+});
+
+test('parseReview: head_sha, changes and notes (counts) are optional; an older card has none and no Changes section', () => {
+ const older = m.parseReview(m.fx.REVIEW_312 ?? m.fx.REVIEW_289);
+ assert.deepEqual([older.head_sha, older.changes, older.line_notes], [null, null, null]);
+ const raw = { ...(m.fx.REVIEW_312 ?? m.fx.REVIEW_289), head_sha: HEAD, changes: { files: 3, additions: 43, deletions: 13 }, notes: { drafts: 1, total: 1 } };
+ const c = m.parseReview(raw);
+ assert.deepEqual([c.head_sha, c.changes.files, c.line_notes.drafts], [HEAD, 3, 1]);
+});
+
+// ---------------------------------------------------------------------------------------------------
+// Lines, ranges and copy
+
+test('clampRange stays in the anchor hunk, orders the ends and caps at 40 lines', () => {
+ const lines = m.flatLines(m.parseChanges(rawChanges()).files[0]);
+ assert.equal(lines.length, 8);
+ assert.deepEqual(m.clampRange(lines, 2, 4), [2, 4]);
+ assert.deepEqual(m.clampRange(lines, 4, 1), [1, 4]);
+ assert.deepEqual(m.clampRange(lines, 3, 7), [3, 5], 'stops at the end of its hunk');
+ assert.deepEqual(m.clampRange(lines, 6, 0), [6, 6], 'does not cross into the hunk above');
+ const long = m.flatLines(m.parseChanges(rawChanges({ files: [{ path: 'a', hunks: [{ header: '', lines: Array.from({ length: 60 }, (_, i) => ({ kind: 'add', new: i + 1, text: 'x' })) }] }] })).files[0]);
+ assert.deepEqual(m.clampRange(long, 0, 59), [0, 39]);
+ assert.deepEqual(m.clampRange(long, 59, 0), [20, 59]);
+});
+
+test('positionIn: a note sits where at_head says, even across a removed and an added line', () => {
+ const lines = m.flatLines(m.parseChanges(rawChanges()).files[0]);
+ assert.deepEqual(m.positionIn(lines, m.parseNote(rawNote())), [3, 3]);
+ const placed = m.parseNote(rawNote({ head_sha: 'old', at_head: { start: { side: 'old', line: 41 }, end: { side: 'new', line: 42 } } }));
+ assert.deepEqual(m.positionIn(lines, placed), [1, 3], 'a range across a removed and an added line');
+ assert.equal(m.positionIn(lines, m.parseNote(rawNote({ at_head: { start: { side: 'new', line: 999 }, end: { side: 'new', line: 999 } } }))), null);
+ assert.equal(m.positionIn(lines, m.parseNote(rawNote({ at_head: null }))), null);
+});
+
+test('copy: Mira’s words, singular for 1, short shas, no emoji', () => {
+ assert.equal(m.sendLabel(1, 'Vega'), 'Send note to Vega');
+ assert.equal(m.sendLabel(3, 'Vega'), 'Send 3 notes to Vega');
+ assert.equal(m.draftsWord(1), '1 draft');
+ assert.equal(m.draftsWord(2), '2 drafts');
+ assert.equal(m.sendShort(3), 'Send 3');
+ assert.equal(m.sentLine(3, 'Vega', '09:30'), 'Sent 3 notes to Vega · 09:30');
+ assert.equal(m.discardAsk(1), 'Discard 1 draft?');
+ assert.equal(m.discardAsk(4), 'Discard 4 drafts?');
+ assert.equal(m.changedIn(NEXT), 'Changed in e81f2c4');
+ assert.equal(m.stillOpen(NEXT), 'Still open · line unchanged in e81f2c4');
+ assert.equal(m.lineWords({ side: 'new', line: 40 }, { side: 'new', line: 42 }), 'lines 40–42');
+ assert.equal(m.lineWords({ side: 'new', line: 40 }, { side: 'new', line: 40 }), 'line 40');
+ assert.equal(m.addAria({ kind: 'del', old: 41, new: null, text: '' }), 'Add a note on removed line 41');
+ assert.equal(m.summaryLine({ total: 3, changed: 2, open: 1, sha: NEXT }), '3 notes · 2 changed in e81f2c4 · 1 still open');
+ assert.equal(m.movedLine('Vega', NEXT, 44), 'Vega pushed e81f2c4 after you wrote this. The line is now 44.');
+ assert.equal(m.goneLine(NEXT), 'This line is gone in e81f2c4.');
+ assert.equal(m.cutLine({ files_not_read: 1, text: null }), '1 file not read: the diff was cut.');
+ assert.equal(m.showLines(1284), 'Show 1,284 lines');
+ assert.equal(m.showLines(1), 'Show 1 line');
+ assert.ok(m.startsCollapsed({ path: 'web/package-lock.json', big: false }));
+ assert.ok(!m.startsCollapsed({ path: 'src/lock.rs', big: false }));
+ const all = [m.SEND_FAILED, m.TOO_MANY, m.LOAD_FAILED, m.NO_DIFF, m.notBotLine('oleks'), m.readOnlyLine('merged'), m.sentNoteLine('09:30', 'Vega')].join(' ');
+ assert.doesNotMatch(all, /\p{Extended_Pictographic}/u);
+});
+
+// ---------------------------------------------------------------------------------------------------
+// The API client
+
+test('lineNotesApi: routes, bodies and send_id; errors carry the server code', async () => {
+ const seen = [];
+ const answers = {
+ 'GET /api/dev/cards/dvr_312/changes': rawChanges(),
+ 'GET /api/dev/cards/dvr_312/notes': { notes: [rawNote()] },
+ 'POST /api/dev/cards/dvr_312/notes': rawNote({ id: 'ln_9' }),
+ 'PATCH /api/dev/notes/ln_9': rawNote({ id: 'ln_9', text: 'new' }),
+ 'DELETE /api/dev/notes/ln_9': { ok: true },
+ 'POST /api/dev/notes/ln_9/restore': rawNote({ id: 'ln_9' }),
+ 'DELETE /api/dev/cards/dvr_312/notes': { discarded: 2 },
+ 'POST /api/dev/cards/dvr_312/notes/send': { sent: 1, notes: [] },
+ };
+ const api = m.lineNotesApi(async (url, method, body) => {
+ seen.push([method, url, body]);
+ return answers[`${method} ${url}`];
+ });
+ assert.equal((await api.changes('dvr_312')).files.length, 3);
+ assert.equal((await api.notes('dvr_312')).notes.length, 1);
+ await api.create('dvr_312', { path: 'a.rs', start: { side: 'old', line: 41 }, end: { side: 'new', line: 42 }, head_sha: HEAD, text: 'x' });
+ assert.deepEqual(seen.at(-1)[2], { path: 'a.rs', start: { side: 'old', line: 41 }, end: { side: 'new', line: 42 }, head_sha: HEAD, text: 'x' });
+ assert.equal((await api.edit('ln_9', 'new')).text, 'new');
+ await api.remove('ln_9');
+ assert.equal((await api.restore('ln_9')).id, 'ln_9');
+ assert.equal(await api.discardAll('dvr_312'), 2);
+ await api.send('dvr_312', 'snd_1');
+ assert.deepEqual(seen.at(-1)[2], { send_id: 'snd_1' });
+ await api.send('dvr_312', 'snd_2', ['ln_9']);
+ assert.deepEqual(seen.at(-1)[2], { ids: ['ln_9'], send_id: 'snd_2' });
+ await assert.rejects(m.lineNotesApi(async () => ({ nope: 1 })).notes('x'), (e) => e.code === 'bad_shape');
+
+ const http = m.fetchCaller(async () => new Response(JSON.stringify({ error: 'stale_head', code: 'stale_head' }), { status: 409 }));
+ await assert.rejects(http('/x', 'POST', {}), (e) => e instanceof m.LineNotesError && e.status === 409 && e.code === 'stale_head' && /pushed again/.test(e.message));
+ const down = m.fetchCaller(async () => {
+ throw new TypeError('fetch failed');
+ });
+ await assert.rejects(down('/x', 'GET'), (e) => e.status === 0 && /reach the server/.test(e.message));
+ const plain = m.fetchCaller(async () => new Response(JSON.stringify({ error: 'The PR was force-pushed.' }), { status: 422 }));
+ await assert.rejects(plain('/x', 'GET'), (e) => e.message === 'The PR was force-pushed.' && e.code === null);
+ assert.notEqual(m.newSendId(), m.newSendId());
+});
+
+// ---------------------------------------------------------------------------------------------------
+// The section
+
+test('collapsed: the card’s own counts, no fetch; Show loads the diff and Hide keeps it', async () => {
+ const { api, calls } = fakeApi();
+ await mount({ api, notesCount: { drafts: 2, total: 2 } });
+ const head = $('h4').textContent;
+ assert.match(head, /Changes/);
+ assert.match(head, /3 files/);
+ assert.match(head, /· 2 drafts/);
+ assert.equal(calls.length, 0, 'nothing is fetched until it opens');
+ const toggle = byText('Show the changes');
+ assert.equal(toggle.getAttribute('aria-expanded'), 'false');
+ await click(toggle);
+ assert.equal(toggle.getAttribute('aria-expanded'), 'true');
+ assert.deepEqual(calls.slice().sort(), ['changes', 'notes']);
+ assert.ok($('[data-ln-grid="src/server/auth.rs"]'));
+ assert.equal($('[data-ln-grid="src/server/auth.rs"]').getAttribute('aria-label'), 'Changes in src/server/auth.rs');
+ assert.ok(!$('[data-ln-grid="Cargo.lock"]'), 'lockfiles start collapsed');
+ assert.match($('[data-ln-file="docs/logo.png"]').textContent, /Binary file, not shown/);
+ await click(byText('Hide the changes'));
+ assert.ok(document.getElementById(toggle.getAttribute('aria-controls')).hidden);
+ await click(byText('Show the changes'));
+ assert.equal(calls.length, 2, 'opening again does not refetch');
+});
+
+test('load error: Couldn’t load the changes, Try again refetches', async () => {
+ const { api, s, calls } = fakeApi();
+ s.fail.changes = 1;
+ await mount({ api, defaultOpen: true });
+ assert.match($('[data-ln-error]').textContent, /Couldn’t load the changes\./);
+ await click(byText('Try again'));
+ assert.ok(!$('[data-ln-error]'));
+ assert.equal(calls.filter((c) => c === 'changes').length, 2);
+});
+
+test('gutter +: one tab stop per file, arrows move, Enter opens the box; ⌘/Ctrl+Enter adds a draft', async () => {
+ const { api, calls } = fakeApi();
+ await mount({ api, defaultOpen: true });
+ const grid = $('[data-ln-grid="src/server/auth.rs"]');
+ const tabbable = [...grid.querySelectorAll('button')].filter((b) => b.tabIndex === 0);
+ assert.equal(tabbable.length, 1, 'roving tabindex');
+ assert.equal(plus('old', 41).getAttribute('aria-label'), 'Add a note on removed line 41');
+ tabbable[0].focus();
+ await key(tabbable[0], 'ArrowDown');
+ await key(document.activeElement, 'ArrowDown');
+ await key(document.activeElement, 'ArrowDown');
+ assert.equal(document.activeElement, plus('new', 42));
+ await click(document.activeElement);
+ const box = $('[data-ln-writing]');
+ assert.ok(box, 'the writing box opens under the line');
+ assert.match(box.textContent, /Note for Vega line 42/);
+ const ta = box.querySelector('textarea');
+ assert.equal(byText('Add note').disabled, true, 'nothing to add yet');
+ await type(ta, 'Use a constant.');
+ await key(ta, 'Enter', { ctrlKey: true });
+ const create = calls.find((c) => Array.isArray(c) && c[0] === 'create')[1];
+ assert.deepEqual([create.path, create.start, create.end, create.head_sha, create.text], ['src/server/auth.rs', { side: 'new', line: 42 }, { side: 'new', line: 42 }, HEAD, 'Use a constant.']);
+ assert.ok(!$('[data-ln-writing]'));
+ const note = $('[data-ln-state="draft"]');
+ assert.ok(note);
+ assert.equal(note.getAttribute('aria-label'), 'Draft note on line 42');
+ assert.match($('[data-ln-live]').textContent, /Note added on line 42\. 1 note for Vega\./);
+ assert.match(plus('new', 42).getAttribute('aria-label'), /It has a note/);
+});
+
+test('ranges: Shift+Down widens inside the hunk, Shift-click ends it; the box says lines a–b', async () => {
+ const { api, calls } = fakeApi();
+ await mount({ api, defaultOpen: true });
+ const first = plus('new', 41);
+ first.focus();
+ first.dispatchEvent(new window.FocusEvent('focus', { bubbles: true }));
+ await settle();
+ // Focus the line, then widen.
+ await click(first);
+ await click(byText('Cancel'));
+ plus('new', 41).focus();
+ await key(plus('new', 41), 'ArrowDown', { shiftKey: true });
+ await key(document.activeElement, 'ArrowDown', { shiftKey: true });
+ assert.deepEqual($$('[aria-selected="true"]').map((r) => r.dataset.lnPoint), ['new:41', 'new:42', 'new:43']);
+ await click(document.activeElement);
+ assert.match($('[data-ln-writing]').textContent, /lines 41–43/);
+ await type($('[data-ln-writing] textarea'), 'Split this.');
+ await click(byText('Add note'));
+ const create = calls.filter((c) => Array.isArray(c) && c[0] === 'create').at(-1)[1];
+ assert.deepEqual([create.start.line, create.end.line], [41, 43]);
+ // Shift-click from a selected line stops at the hunk's end.
+ await click(plus('new', 40));
+ await click(plus('new', 93), { shiftKey: true });
+ assert.match($('[data-ln-writing]').textContent, /lines 40–44/, 'a range never crosses hunks');
+});
+
+test('Esc in a box with text asks first; Keep writing returns, Throw away closes', async () => {
+ const { api } = fakeApi();
+ await mount({ api, defaultOpen: true });
+ await click(plus('new', 43));
+ const ta = $('[data-ln-writing] textarea');
+ await type(ta, 'half a thought');
+ await key(ta, 'Escape');
+ assert.equal($('[role="alertdialog"]').getAttribute('aria-label'), 'Throw away this note?');
+ assert.equal(document.activeElement, byText('Keep writing'), 'the safe choice has focus');
+ await click(byText('Keep writing'));
+ assert.ok(!$('[role="alertdialog"]'));
+ assert.equal($('[data-ln-writing] textarea').value, 'half a thought');
+ await key($('[data-ln-writing] textarea'), 'Escape');
+ await click(byText('Throw away'));
+ assert.ok(!$('[data-ln-writing]'));
+ await click(plus('new', 43));
+ await key($('[data-ln-writing] textarea'), 'Escape');
+ assert.ok(!$('[data-ln-writing]'), 'an empty box closes at once');
+});
+
+test('send bar: Send {n} notes to {bot}, one send with a send_id, then Sent with Open chat', async () => {
+ const { api, calls } = fakeApi({ notes: [rawNote(), rawNote({ id: 'ln_2', start: { side: 'new', line: 43 }, end: { side: 'new', line: 43 } })] });
+ const opened = [];
+ await mount({ api, defaultOpen: true, onOpenChat: (id) => opened.push(id) });
+ const bar = $('[data-ln-bar]');
+ assert.equal(bar.getAttribute('aria-label'), 'Notes to send');
+ assert.match(bar.textContent, /2 notes for Vega · drafts, only you see them/);
+ const send = $('[data-ln-send]');
+ assert.equal(send.textContent.trim(), 'Send 2 notes to Vega');
+ await click(send);
+ const sends = calls.filter((c) => Array.isArray(c) && c[0] === 'send');
+ assert.equal(sends.length, 1);
+ assert.ok(sends[0][1], 'a send id');
+ assert.equal($('[data-ln-bar]').dataset.lnBar, 'sent');
+ assert.match($('[data-ln-bar]').textContent, /Sent 2 notes to Vega/);
+ assert.equal($$('[data-ln-state="sent"]').length, 2);
+ assert.match($('[data-ln-state="sent"]').textContent, /waiting for Vega’s next push/);
+ await click(byText('Open Vega’s chat'));
+ assert.deepEqual(opened, ['bot_vega']);
+});
+
+test('a failed send keeps the drafts; Try again reuses the same send_id', async () => {
+ const { api, s, calls } = fakeApi({ notes: [rawNote()] });
+ s.fail.send = 1;
+ await mount({ api, defaultOpen: true });
+ await click($('[data-ln-send]'));
+ assert.equal($('[data-ln-bar]').dataset.lnBar, 'failed');
+ assert.match($('[data-ln-bar]').textContent, /The notes didn’t send\. They’re still here\./);
+ assert.equal($$('[data-ln-state="draft"]').length, 1);
+ await click(byText('Try again'));
+ const sends = calls.filter((c) => Array.isArray(c) && c[0] === 'send');
+ assert.equal(sends.length, 2);
+ assert.equal(sends[0][1], sends[1][1], 'same send id, so the batch posts once');
+ assert.equal($('[data-ln-bar]').dataset.lnBar, 'sent');
+});
+
+test('more than 20 drafts: Send is off and the bar says why', async () => {
+ const many = Array.from({ length: 21 }, (_, i) => rawNote({ id: `ln_${i}`, start: { side: 'new', line: 41 + (i % 3) }, end: { side: 'new', line: 41 + (i % 3) } }));
+ const { api } = fakeApi({ notes: many });
+ await mount({ api, defaultOpen: true });
+ assert.equal($('[data-ln-send]').disabled, true);
+ assert.match($('[data-ln-bar]').textContent, /Up to 20 notes per send/);
+});
+
+test('Discard all asks first; Keep keeps them', async () => {
+ const { api, calls } = fakeApi({ notes: [rawNote(), rawNote({ id: 'ln_2' })] });
+ await mount({ api, defaultOpen: true });
+ await click(byText('Discard all'));
+ assert.match($('[data-ln-bar]').textContent, /Discard 2 drafts\?/);
+ assert.equal(document.activeElement, byText('Keep'));
+ await click(byText('Keep'));
+ assert.equal($$('[data-ln-state="draft"]').length, 2);
+ await click(byText('Discard all'));
+ await click(byText('Discard'));
+ assert.ok(calls.includes('discardAll'));
+ assert.equal($$('[data-ln-state="draft"]').length, 0);
+ assert.ok(!$('[data-ln-bar]'), 'no drafts, no bar');
+});
+
+test('a draft: E edits in place, Delete deletes with a 5 s Undo that restores it', async () => {
+ const { api, calls } = fakeApi({ notes: [rawNote()] });
+ await mount({ api, defaultOpen: true });
+ const note = $('[data-ln-note="ln_1"]');
+ assert.equal(note.tabIndex, 0);
+ note.focus();
+ await key(note, 'e');
+ const ta = $('[data-ln-writing] textarea');
+ assert.equal(ta.value, 'Use a constant for the minimum length.');
+ await type(ta, 'Use MIN_TOKEN_LEN.');
+ await click(byText('Save'));
+ assert.ok(calls.includes('edit'));
+ assert.match($('[data-ln-note="ln_1"]').textContent, /Use MIN_TOKEN_LEN\./);
+ await key($('[data-ln-note="ln_1"]'), 'Delete');
+ assert.ok(!$('[data-ln-note="ln_1"]'));
+ assert.match($('[data-ln-undo]').textContent, /Note deleted/);
+ await click(byText('Undo'));
+ assert.ok(calls.includes('restore'));
+ assert.ok($('[data-ln-note="ln_1"]'));
+});
+
+test('after the bot’s push: Changed in {sha} and Still open, with the summary line', async () => {
+ const { api } = fakeApi({
+ notes: [
+ rawNote({ state: 'resolved', checked_sha: NEXT, sent_at: '2026-11-10T09:30:00Z' }),
+ rawNote({ id: 'ln_2', start: { side: 'new', line: 43 }, end: { side: 'new', line: 43 }, state: 'open', checked_sha: NEXT }),
+ ],
+ summary: { total: 2, changed: 1, open: 1, sha: NEXT },
+ });
+ await mount({ api, defaultOpen: true });
+ assert.equal($('[data-ln-summary]').textContent, '2 notes · 1 changed in e81f2c4 · 1 still open');
+ const done = $('[data-ln-state="resolved"]');
+ assert.match(done.textContent, /Changed in e81f2c4/);
+ assert.equal(done.getAttribute('aria-label'), 'Note on line 42, Changed in e81f2c4');
+ assert.match($('[data-ln-state="open"]').textContent, /Still open · line unchanged in e81f2c4/);
+ assert.equal(done.tabIndex, -1, 'sent notes are not editable');
+ assert.ok(!$('[data-ln-bar]'), 'no drafts, no bar');
+});
+
+test('a dev_card event for this card refetches the notes and announces the result', async () => {
+ const { api, s, calls } = fakeApi({ notes: [rawNote({ state: 'sent' })], summary: { total: 1, changed: 0, open: 0, sha: HEAD } });
+ await mount({ api, defaultOpen: true });
+ s.notes = [m.parseNote(rawNote({ state: 'resolved', checked_sha: NEXT }))];
+ s.summary = { total: 1, changed: 1, open: 0, sha: NEXT };
+ window.dispatchEvent(new window.CustomEvent('kwant:dev-card', { detail: { id: 'other' } }));
+ await settle();
+ assert.equal(calls.filter((c) => c === 'notes').length, 1, 'another card: nothing');
+ window.dispatchEvent(new window.CustomEvent('kwant:dev-card', { detail: { id: 'dvr_312' } }));
+ await settle();
+ assert.equal(calls.filter((c) => c === 'notes').length, 2);
+ assert.ok($('[data-ln-state="resolved"]'));
+ assert.equal($('[data-ln-live]').textContent, '1 note changed in e81f2c4, 0 still open.');
+});
+
+test('a draft whose line moved or went: it says so; a gone draft can be sent alone', async () => {
+ const { api, calls } = fakeApi({
+ notes: [
+ rawNote({ seen_sha: NEXT, at_head: { start: { side: 'new', line: 43 }, end: { side: 'new', line: 43 } } }),
+ rawNote({ id: 'ln_2', seen_sha: NEXT, at_head: null }),
+ ],
+ });
+ await mount({ api, defaultOpen: true });
+ assert.match($('[data-ln-note="ln_1"]').textContent, /Vega pushed e81f2c4 after you wrote this\. The line is now 43\./);
+ const gone = $('[data-ln-note="ln_2"]');
+ assert.match(gone.textContent, /This line is gone in e81f2c4\./);
+ await click([...gone.querySelectorAll('button')].find((b) => b.textContent === 'Send it anyway'));
+ const send = calls.find((c) => Array.isArray(c) && c[0] === 'send');
+ assert.deepEqual(send[2], ['ln_2']);
+});
+
+test('read-only: a merged PR and a PR not by a bot have no + and no bar', async () => {
+ const { api } = fakeApi({ changes: rawChanges({ pr_state: 'merged' }), notes: [rawNote({ state: 'sent' })] });
+ await mount({ api, defaultOpen: true });
+ assert.match($('[data-ln-banner]').textContent, /This PR is merged\. Notes are read-only\./);
+ assert.equal($$('[data-ln-grid] button').length, 0);
+ assert.ok(!$('[data-ln-bar]'));
+ assert.equal($('[data-ln-grid]').tabIndex, 0, 'the read-only diff still scrolls by keyboard');
+
+ const other = fakeApi({ changes: rawChanges({ author_bot: null, author_login: 'oleks' }) });
+ await mount({ api: other.api, defaultOpen: true });
+ assert.equal($('[data-ln-banner]').textContent, 'Notes go to bots in this space. This PR is by oleks, so there’s nothing to send them to.');
+ assert.equal($('[data-ln-banner] strong').textContent, 'oleks');
+ assert.equal($$('[data-ln-grid] button').length, 0);
+});
+
+test('a stale head on create keeps the text and reloads the diff', async () => {
+ const { api, calls } = fakeApi();
+ api.create = async () => {
+ calls.push('create');
+ throw new m.LineNotesError('The bot pushed again. The changes reloaded; your note is still here.', 409, 'stale_head');
+ };
+ await mount({ api, defaultOpen: true });
+ await click(plus('new', 42));
+ await type($('[data-ln-writing] textarea'), 'keep me');
+ await click(byText('Add note'));
+ assert.equal($('[data-ln-writing] [role="alert"]').textContent, 'The bot pushed again. The changes reloaded; your note is still here.');
+ assert.equal($('[data-ln-writing] textarea').value, 'keep me');
+ assert.equal(calls.filter((c) => c === 'changes').length, 2);
+});
+
+test('phone: tapping a line opens a sheet; the bar is short with Discard in a menu', async () => {
+ const { api } = fakeApi({ notes: [rawNote()] });
+ await mount({ api, defaultOpen: true, phone: true });
+ assert.equal($('[data-ln-send]').textContent.trim(), 'Send 1');
+ assert.equal($('[data-ln-send]').getAttribute('aria-label'), 'Send note to Vega');
+ assert.ok(!byText('Discard all'));
+ await click($('[aria-label="More"]'));
+ assert.ok(byText('Discard all'));
+ await click(plus('new', 43));
+ const sheet = $('[data-ln-sheet]');
+ assert.equal(sheet.getAttribute('role'), 'dialog');
+ assert.match(sheet.textContent, /Note for Vega/);
+ assert.match(sheet.textContent, /auth\.rs · line 43/);
+ assert.ok(!$('[data-ln-writing]'), 'no inline box on the phone');
+ await click(byText('Extend to line…'));
+ assert.match($('[data-ln-range-bar]').textContent, /tap the last line/);
+ await click(plus('new', 42));
+ // Tapping above the anchor makes the range 42–43.
+ assert.match($('[data-ln-sheet]').textContent, /lines 42–43/);
+});
+
+test('the review card shows Changes only with an api and the card’s counts', async () => {
+ const raw = { ...(m.fx.REVIEW_312 ?? m.fx.REVIEW_289), head_sha: HEAD, changes: { files: 3, additions: 43, deletions: 13 } };
+ const { api } = fakeApi();
+ const render = async (props) => {
+ if (root) root.unmount();
+ host?.remove();
+ host = document.createElement('div');
+ document.body.appendChild(host);
+ root = createRoot(host);
+ root.render(h(m.ReviewCard, { onFinding: async () => raw, ...props }));
+ await settle();
+ };
+ await render({ card: raw, lineNotes: api });
+ assert.ok($('[data-line-notes]'));
+ await render({ card: raw });
+ assert.ok(!$('[data-line-notes]'), 'no api, no section');
+ await render({ card: { ...raw, changes: undefined }, lineNotes: api });
+ assert.ok(!$('[data-line-notes]'), 'an older server: no section');
+ root.unmount();
+ root = null;
+});