From db4c7bbd211d3bc83124e1a37ce86604c6fdeb71 Mon Sep 17 00:00:00 2001 From: pulk17 Date: Tue, 24 Nov 2026 12:04:30 +0530 Subject: [PATCH 1/4] highlight what changed in the diff drawer Caption failures usually differ by one space or a single frame of timing, which a block of red lines over a block of green lines hides. Pair each removed line with the line that replaced it and mark only the tokens that differ. Long lines now wrap inside the box instead of running past it. The console diff gets the same treatment, labelled previous run / this run. Playback flags cues whose text or timing differs from the same cue on the other side, showing exact millisecond timings where they disagree. --- web/src/components/DiffDrawer.test.tsx | 9 +- web/src/components/DiffDrawer.tsx | 174 ++++++++++++++++++++----- web/src/lib/diff.test.ts | 34 +++++ web/src/lib/diff.ts | 118 +++++++++++++++++ 4 files changed, 298 insertions(+), 37 deletions(-) create mode 100644 web/src/lib/diff.test.ts create mode 100644 web/src/lib/diff.ts diff --git a/web/src/components/DiffDrawer.test.tsx b/web/src/components/DiffDrawer.test.tsx index 8089fae2..3047b654 100644 --- a/web/src/components/DiffDrawer.test.tsx +++ b/web/src/components/DiffDrawer.test.tsx @@ -44,8 +44,13 @@ describe("DiffDrawer", () => { expect(screen.getByText("Test #7")).toBeInTheDocument(); expect(screen.getByText(/pal\.ts/)).toBeInTheDocument(); - expect(await screen.findByText("-old caption")).toBeInTheDocument(); - expect(screen.getByText("+new caption")).toBeInTheDocument(); + // The pair sits one above the other with only the changed word marked. + const removed = await screen.findByText("old"); + expect(removed.tagName).toBe("MARK"); + expect(removed.closest("div")?.textContent).toBe("−old caption"); + const added = screen.getByText("new"); + expect(added.tagName).toBe("MARK"); + expect(added.closest("div")?.textContent).toBe("+new caption"); }); it("explains when the output file is missing from storage", async () => { diff --git a/web/src/components/DiffDrawer.tsx b/web/src/components/DiffDrawer.tsx index 4f15a164..37d5b08c 100644 --- a/web/src/components/DiffDrawer.tsx +++ b/web/src/components/DiffDrawer.tsx @@ -5,6 +5,7 @@ import { useEffect, useMemo, useRef, useState } from "react"; import { AnimatedSheet, SheetDescription, SheetTitle } from "@/components/ui/sheet"; import { fetchConsoleDiff, fetchDiff, outputText, sampleFile } from "@/lib/api"; import { clock, cuesToVtt, parseCues, type Cue } from "@/lib/cues"; +import { diffRows, wordDiff, type DiffRow, type Seg } from "@/lib/diff"; import { cn } from "@/lib/utils"; export interface OutputDiffTarget { @@ -123,9 +124,33 @@ function ViewTab({ ); } -/** Pair each line with a stable id, so the render key is never an index. */ -function numbered(lines: string[]): { id: string; line: string }[] { - return lines.map((line, i) => ({ id: `line-${i}`, line })); +const ROW_TONE: Record = { + del: "bg-destructive/8 text-destructive", + add: "bg-success/8 text-success", + hunk: "text-accent-foreground", + ctx: "", +}; +const MARK_TONE: Record<"del" | "add", string> = { + del: "bg-destructive/35 text-foreground", + add: "bg-success/35 text-foreground", +}; + +/** A line's segments, with the tokens that differ from its twin marked. */ +function Segs({ segs, kind }: Readonly<{ segs: Seg[]; kind: "del" | "add" }>) { + return ( + <> + {segs.map((s, i) => + s.changed ? ( + // Index keys are safe: segments are rebuilt whole, never reordered. + + {s.text} + + ) : ( + {s.text} + ), + )} + + ); } function DiffPane({ target }: Readonly<{ target: DiffTarget }>) { @@ -143,9 +168,10 @@ function DiffPane({ target }: Readonly<{ target: DiffTarget }>) { return fetchDiff(target); }, }); + const rows = useMemo(() => (data ? diffRows(data.content) : []), [data]); return ( -
+
{isLoading && } {isError && ( @@ -156,29 +182,47 @@ function DiffPane({ target }: Readonly<{ target: DiffTarget }>) { )} {data && ( -
-          {data.content.trim() === "" ? (
-            Diff is empty.
-          ) : (
-            numbered(data.content.split("\n")).map(({ id, line }) => (
-              
- {line || " "} -
- )) - )} -
+ <> +
+ + −{" "} + {consoleTarget ? "previous run" : "expected"} + + + + {consoleTarget ? "this run" : "actual"} + + highlighted = the part that changed +
+ {/* Wrapped, not scrolled: caption lines run long, and a sideways + scroll pushed the text past the tinted line backgrounds. */} +
+ {rows.length === 0 ? ( + Diff is empty. + ) : ( + rows.map((row, i) => ( +
+ + {row.kind === "del" ? "−" : row.kind === "add" ? "+" : ""} + + + {row.kind === "del" || row.kind === "add" ? ( + + ) : ( + row.segs[0].text || " " + )} + +
+ )) + )} +
+ )}
); @@ -220,6 +264,25 @@ function PlaybackPane({ target }: Readonly<{ target: OutputDiffTarget }>) { }, [expected.data]); useEffect(() => () => URL.revokeObjectURL(captions), [captions]); + // Cue n of the baseline against cue n of the output, so the columns mark + // what changed. ponytail: paired by position; an inserted or dropped cue + // shifts every later pair, align by timing if that turns out common. + const marks = useMemo(() => { + const e = expected.data?.cues ?? []; + const a = actual.data?.cues ?? []; + const left = e.map((c) => cueMark(c, undefined)); + const right = a.map((c) => cueMark(c, undefined)); + for (let k = 0; k < Math.min(e.length, a.length); k++) { + const [l, r] = wordDiff(e[k].text, a[k].text); + left[k] = cueMark(e[k], a[k], l); + right[k] = cueMark(a[k], e[k], r); + // Flag both sides: an inserted space only has a changed token on one. + const differs = left[k].timing !== null || [...l, ...r].some((s) => s.changed); + left[k].differs = right[k].differs = differs; + } + return { left, right }; + }, [expected.data, actual.data]); + const seek = (t: number) => { if (!video.current) return; video.current.currentTime = t; @@ -270,13 +333,34 @@ function PlaybackPane({ target }: Readonly<{ target: OutputDiffTarget }>) { )}
- - + +
); } +/** How one cue differs from the cue in the same position on the other side. */ +interface CueMark { + segs: Seg[]; + /** Exact timing of both sides when they disagree, else null. */ + timing: string | null; + /** Text or timing differs from the twin cue. */ + differs: boolean; +} + +/** Second-and-millisecond stamp, since timing drift is usually one frame. */ +const exact = (t: number) => `${clock(t)}.${String(Math.round((t % 1) * 1000)).padStart(3, "0")}`; + +function cueMark(c: Cue, twin: Cue | undefined, segs?: Seg[]): CueMark { + const shifted = twin && (twin.start !== c.start || twin.end !== c.end); + return { + segs: segs ?? [{ text: c.text, changed: false }], + timing: shifted ? `${exact(c.start)} → ${exact(c.end)}` : null, + differs: false, + }; +} + function useOutput(target: OutputDiffTarget, which: "expected" | "actual") { return useQuery({ queryKey: ["output-text", target.runId, target.regressionId, target.outputId, which], @@ -295,12 +379,14 @@ function CueColumn({ title, tone, q, + marks, at, onSeek, }: Readonly<{ title: string; tone: "ok" | "bad"; q: OutputQuery; + marks: CueMark[]; at: number; onSeek: (t: number) => void; }>) { @@ -343,8 +429,15 @@ function CueColumn({ {q.data.content.trim() || Empty file.} )} - {q.data?.cues.map((c) => ( - = c.start && at < c.end} onSeek={onSeek} /> + {q.data?.cues.map((c, i) => ( + = c.start && at < c.end} + onSeek={onSeek} + /> ))} {q.data?.truncated && (

Truncated at 1 MiB.

@@ -356,13 +449,18 @@ function CueColumn({ function CueRow({ cue, + mark, + kind, active, onSeek, }: Readonly<{ cue: Cue; + mark: CueMark | undefined; + kind: "del" | "add"; active: boolean; onSeek: (t: number) => void; }>) { + const differs = !!mark?.differs; return ( ); diff --git a/web/src/lib/diff.test.ts b/web/src/lib/diff.test.ts new file mode 100644 index 00000000..d3681471 --- /dev/null +++ b/web/src/lib/diff.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from "vitest"; + +import { diffRows, wordDiff, type Seg } from "@/lib/diff"; + +const changed = (segs: Seg[]) => segs.filter((s) => s.changed).map((s) => s.text); + +describe("wordDiff", () => { + it("marks only the digits of a one-frame timing shift", () => { + const [l, r] = wordDiff( + "00:00:01,480|00:00:03,520|TLT|hi", + "00:00:01,480|00:00:03,560|TLT|hi", + ); + expect(changed(l)).toEqual(["520"]); + expect(changed(r)).toEqual(["560"]); + }); + + it("marks an inserted space on the side that has it", () => { + const [l, r] = wordDiff("My,um...", "My, um..."); + expect(changed(l)).toEqual([]); + expect(changed(r)).toEqual([" "]); + }); +}); + +describe("diffRows", () => { + it("interleaves removed and added lines, drops the header, keeps a -- line", () => { + const rows = diffRows( + ["--- expected", "+++ actual", "@@ -1,3 +1,3 @@", " same", "-a 1", "-b 1", "--- x", "+a 2", "+b 2"].join( + "\n", + ), + ); + expect(rows.map((x) => x.kind)).toEqual(["hunk", "ctx", "del", "add", "del", "add", "del"]); + expect(rows[6].segs[0].text).toBe("-- x"); + }); +}); diff --git a/web/src/lib/diff.ts b/web/src/lib/diff.ts new file mode 100644 index 00000000..92daa188 --- /dev/null +++ b/web/src/lib/diff.ts @@ -0,0 +1,118 @@ +/** + * Word-level highlighting for the diff drawer. + * + * The API returns a line-level unified diff. For caption files the changed + * line usually differs by one space or a few milliseconds, which a whole red + * line next to a whole green line hides. Pairing each removed line with the + * added line that replaced it and marking only the tokens that differ is what + * makes those visible. + */ + +export interface Seg { + text: string; + changed: boolean; +} + +export interface DiffRow { + kind: "ctx" | "del" | "add" | "hunk"; + segs: Seg[]; +} + +// Runs of letters/digits, runs of whitespace, and single punctuation marks: +// "03,520" splits into 03 , 520 so a timing change marks only the digits. +const TOKEN = /\s+|\w+|[^\w\s]/g; + +// Beyond this many token pairs a line is not a caption line; mark it whole. +const MAX_CELLS = 250_000; + +function push(out: Seg[], text: string, changed: boolean) { + const last = out.at(-1); + if (last && last.changed === changed) last.text += text; + else out.push({ text, changed }); +} + +/** Split two lines into segments, marking the tokens not in their LCS. */ +export function wordDiff(a: string, b: string): [Seg[], Seg[]] { + const x = a.match(TOKEN) ?? []; + const y = b.match(TOKEN) ?? []; + const n = x.length; + const m = y.length; + if (n * m > MAX_CELLS) { + return [[{ text: a, changed: true }], [{ text: b, changed: true }]]; + } + + // L[i][j] = LCS length of x[i..] and y[j..]. Values never exceed + // min(n, m) <= 500 under MAX_CELLS, so 16 bits is plenty. + const L = Array.from({ length: n + 1 }, () => new Uint16Array(m + 1)); + for (let i = n - 1; i >= 0; i--) { + for (let j = m - 1; j >= 0; j--) { + L[i][j] = x[i] === y[j] ? L[i + 1][j + 1] + 1 : Math.max(L[i + 1][j], L[i][j + 1]); + } + } + + const left: Seg[] = []; + const right: Seg[] = []; + let i = 0; + let j = 0; + while (i < n && j < m) { + if (x[i] === y[j]) { + push(left, x[i++], false); + push(right, y[j++], false); + } else if (L[i + 1][j] >= L[i][j + 1]) { + push(left, x[i++], true); + } else { + push(right, y[j++], true); + } + } + while (i < n) push(left, x[i++], true); + while (j < m) push(right, y[j++], true); + return [left, right]; +} + +const plain = (text: string): Seg[] => [{ text, changed: false }]; + +/** + * Unified diff text to display rows. Within a hunk, each run of removed lines + * is paired in order with the run of added lines after it, and the pairs are + * interleaved (-a +a -b +b) so each old line sits directly above its new one. + */ +export function diffRows(unified: string): DiffRow[] { + const rows: DiffRow[] = []; + let del: string[] = []; + let add: string[] = []; + + const flush = () => { + for (let k = 0; k < Math.max(del.length, add.length); k++) { + const a = del[k]; + const b = add[k]; + if (a !== undefined && b !== undefined) { + const [l, r] = wordDiff(a, b); + rows.push({ kind: "del", segs: l }, { kind: "add", segs: r }); + } else if (a !== undefined) { + rows.push({ kind: "del", segs: plain(a) }); + } else { + rows.push({ kind: "add", segs: plain(b) }); + } + } + del = []; + add = []; + }; + + unified.split("\n").forEach((line, idx) => { + // The "--- expected" / "+++ actual" file header is always the first two + // lines; anything later starting with "---" is a removed "--" line. + if (idx < 2 && /^(---|\+\+\+) /.test(line)) return; + if (line.startsWith("-")) { + if (add.length) flush(); + del.push(line.slice(1)); + } else if (line.startsWith("+")) { + add.push(line.slice(1)); + } else { + flush(); + const hunk = line.startsWith("@@"); + rows.push({ kind: hunk ? "hunk" : "ctx", segs: plain(hunk ? line : line.replace(/^ /, "")) }); + } + }); + flush(); + return rows; +} From 82e40487832ab80b11c36eaa14c3087091236d94 Mon Sep 17 00:00:00 2001 From: pulk17 Date: Tue, 24 Nov 2026 12:07:50 +0530 Subject: [PATCH 2/4] key diff rows and segments by stable ids Rows carry the position diffRows assigns them and segments their offset in the line, so neither list is keyed by its render index. Replace the nested ternary for the gutter sign with a lookup, and use an optional chain when merging segments. --- web/src/components/DiffDrawer.tsx | 18 +++++++++--------- web/src/lib/diff.test.ts | 3 +++ web/src/lib/diff.ts | 25 ++++++++++++++++--------- 3 files changed, 28 insertions(+), 18 deletions(-) diff --git a/web/src/components/DiffDrawer.tsx b/web/src/components/DiffDrawer.tsx index 37d5b08c..05e5e515 100644 --- a/web/src/components/DiffDrawer.tsx +++ b/web/src/components/DiffDrawer.tsx @@ -5,7 +5,7 @@ import { useEffect, useMemo, useRef, useState } from "react"; import { AnimatedSheet, SheetDescription, SheetTitle } from "@/components/ui/sheet"; import { fetchConsoleDiff, fetchDiff, outputText, sampleFile } from "@/lib/api"; import { clock, cuesToVtt, parseCues, type Cue } from "@/lib/cues"; -import { diffRows, wordDiff, type DiffRow, type Seg } from "@/lib/diff"; +import { diffRows, whole, wordDiff, type DiffRow, type Seg } from "@/lib/diff"; import { cn } from "@/lib/utils"; export interface OutputDiffTarget { @@ -130,6 +130,7 @@ const ROW_TONE: Record = { hunk: "text-accent-foreground", ctx: "", }; +const ROW_SIGN: Record = { del: "−", add: "+", hunk: "", ctx: "" }; const MARK_TONE: Record<"del" | "add", string> = { del: "bg-destructive/35 text-foreground", add: "bg-success/35 text-foreground", @@ -139,14 +140,13 @@ const MARK_TONE: Record<"del" | "add", string> = { function Segs({ segs, kind }: Readonly<{ segs: Seg[]; kind: "del" | "add" }>) { return ( <> - {segs.map((s, i) => + {segs.map((s) => s.changed ? ( - // Index keys are safe: segments are rebuilt whole, never reordered. - + {s.text} ) : ( - {s.text} + {s.text} ), )} @@ -199,9 +199,9 @@ function DiffPane({ target }: Readonly<{ target: DiffTarget }>) { {rows.length === 0 ? ( Diff is empty. ) : ( - rows.map((row, i) => ( + rows.map((row) => (
) { )} > - {row.kind === "del" ? "−" : row.kind === "add" ? "+" : ""} + {ROW_SIGN[row.kind]} {row.kind === "del" || row.kind === "add" ? ( @@ -355,7 +355,7 @@ const exact = (t: number) => `${clock(t)}.${String(Math.round((t % 1) * 1000)).p function cueMark(c: Cue, twin: Cue | undefined, segs?: Seg[]): CueMark { const shifted = twin && (twin.start !== c.start || twin.end !== c.end); return { - segs: segs ?? [{ text: c.text, changed: false }], + segs: segs ?? whole(c.text), timing: shifted ? `${exact(c.start)} → ${exact(c.end)}` : null, differs: false, }; diff --git a/web/src/lib/diff.test.ts b/web/src/lib/diff.test.ts index d3681471..c9c8e0f0 100644 --- a/web/src/lib/diff.test.ts +++ b/web/src/lib/diff.test.ts @@ -12,6 +12,9 @@ describe("wordDiff", () => { ); expect(changed(l)).toEqual(["520"]); expect(changed(r)).toEqual(["560"]); + // Offsets are the render keys: each is where its segment starts in the line. + expect(l.map((s) => s.at)).toEqual([0, 22, 25]); + expect(l.map((s) => s.text).join("")).toBe("00:00:01,480|00:00:03,520|TLT|hi"); }); it("marks an inserted space on the side that has it", () => { diff --git a/web/src/lib/diff.ts b/web/src/lib/diff.ts index 92daa188..8b876941 100644 --- a/web/src/lib/diff.ts +++ b/web/src/lib/diff.ts @@ -11,9 +11,13 @@ export interface Seg { text: string; changed: boolean; + /** Offset of the segment in its line: unique per line, so a stable key. */ + at: number; } export interface DiffRow { + /** Position in the rendered diff, assigned once here as the row's key. */ + id: number; kind: "ctx" | "del" | "add" | "hunk"; segs: Seg[]; } @@ -27,10 +31,13 @@ const MAX_CELLS = 250_000; function push(out: Seg[], text: string, changed: boolean) { const last = out.at(-1); - if (last && last.changed === changed) last.text += text; - else out.push({ text, changed }); + if (last?.changed === changed) last.text += text; + else out.push({ text, changed, at: last ? last.at + last.text.length : 0 }); } +/** A whole line as one segment. */ +export const whole = (text: string, changed = false): Seg[] => [{ text, changed, at: 0 }]; + /** Split two lines into segments, marking the tokens not in their LCS. */ export function wordDiff(a: string, b: string): [Seg[], Seg[]] { const x = a.match(TOKEN) ?? []; @@ -38,7 +45,7 @@ export function wordDiff(a: string, b: string): [Seg[], Seg[]] { const n = x.length; const m = y.length; if (n * m > MAX_CELLS) { - return [[{ text: a, changed: true }], [{ text: b, changed: true }]]; + return [whole(a, true), whole(b, true)]; } // L[i][j] = LCS length of x[i..] and y[j..]. Values never exceed @@ -69,8 +76,6 @@ export function wordDiff(a: string, b: string): [Seg[], Seg[]] { return [left, right]; } -const plain = (text: string): Seg[] => [{ text, changed: false }]; - /** * Unified diff text to display rows. Within a hunk, each run of removed lines * is paired in order with the run of added lines after it, and the pairs are @@ -80,6 +85,7 @@ export function diffRows(unified: string): DiffRow[] { const rows: DiffRow[] = []; let del: string[] = []; let add: string[] = []; + const row = (kind: DiffRow["kind"], segs: Seg[]) => rows.push({ id: rows.length, kind, segs }); const flush = () => { for (let k = 0; k < Math.max(del.length, add.length); k++) { @@ -87,11 +93,12 @@ export function diffRows(unified: string): DiffRow[] { const b = add[k]; if (a !== undefined && b !== undefined) { const [l, r] = wordDiff(a, b); - rows.push({ kind: "del", segs: l }, { kind: "add", segs: r }); + row("del", l); + row("add", r); } else if (a !== undefined) { - rows.push({ kind: "del", segs: plain(a) }); + row("del", whole(a)); } else { - rows.push({ kind: "add", segs: plain(b) }); + row("add", whole(b)); } } del = []; @@ -110,7 +117,7 @@ export function diffRows(unified: string): DiffRow[] { } else { flush(); const hunk = line.startsWith("@@"); - rows.push({ kind: hunk ? "hunk" : "ctx", segs: plain(hunk ? line : line.replace(/^ /, "")) }); + row(hunk ? "hunk" : "ctx", whole(hunk ? line : line.replace(/^ /, ""))); } }); flush(); From f474059dc8e17322a17088e6644a2319f327061f Mon Sep 17 00:00:00 2001 From: pulk17 Date: Tue, 24 Nov 2026 12:25:58 +0530 Subject: [PATCH 3/4] promote a baseline from the diff drawer Promotion was only reachable from the overflow menu on Home's triage cards, which list the three most recent failing runs and at most five tests per category, so an older run or a longer list had no way in. Move it into the diff drawer, where a failure is judged and which opens from every run: Home, the run page's results and its artifacts. Same admin-only button and the same confirm dialog; the dialog now points at variants for single-platform differences. Home's rows reach it through their diff button, so the separate menu there goes. --- web/src/components/DiffDrawer.test.tsx | 43 ++++++++++++++ web/src/components/DiffDrawer.tsx | 82 ++++++++++++++++++++++++-- web/src/pages/Triage.tsx | 72 ++-------------------- 3 files changed, 125 insertions(+), 72 deletions(-) diff --git a/web/src/components/DiffDrawer.test.tsx b/web/src/components/DiffDrawer.test.tsx index 3047b654..93f3ceaa 100644 --- a/web/src/components/DiffDrawer.test.tsx +++ b/web/src/components/DiffDrawer.test.tsx @@ -1,4 +1,5 @@ import { render, screen } from "@testing-library/react"; +import userEvent from "@testing-library/user-event"; import { afterEach, describe, expect, it, vi } from "vitest"; import { DiffDrawer, type DiffTarget } from "@/components/DiffDrawer"; @@ -22,6 +23,7 @@ function jsonResponse(status: number, body: unknown): Response { afterEach(() => { vi.unstubAllGlobals(); + localStorage.clear(); }); describe("DiffDrawer", () => { @@ -63,4 +65,45 @@ describe("DiffDrawer", () => { await screen.findByText(/output file for this result isn't present in storage/i), ).toBeInTheDocument(); }); + + it("offers promotion to admins only, and confirms before posting it", async () => { + const fetchMock = vi.fn(async (input: RequestInfo | URL, _init?: RequestInit) => + String(input).includes("/baseline-approval") + ? jsonResponse(200, { status: "approved" }) + : jsonResponse(200, { content: "" }), + ); + vi.stubGlobal("fetch", fetchMock); + + const { wrapper } = createWrapper(); + const view = render(, { wrapper }); + expect(screen.queryByText(/promote to baseline/i)).toBeNull(); + view.unmount(); + + signIn("admin"); + render(, { wrapper }); + const user = userEvent.setup(); + await user.click(screen.getByRole("button", { name: /promote to baseline/i })); + expect(fetchMock.mock.calls.some(([u]) => String(u).includes("baseline-approval"))).toBe(false); + + await user.click(await screen.findByRole("button", { name: "Replace baseline" })); + expect(await screen.findByText("Baseline promoted.")).toBeInTheDocument(); + const [url, init] = fetchMock.mock.calls.find(([u]) => String(u).includes("baseline-approval"))!; + expect(String(url)).toContain("/runs/21/samples/14/baseline-approval"); + expect(JSON.parse(String(init?.body))).toMatchObject({ + regression_id: 7, + output_id: 3, + }); + }); }); + +function signIn(role: string) { + localStorage.setItem( + "sp-session", + JSON.stringify({ + token: "t", + email: "a@example.com", + role, + expires_at: new Date(Date.now() + 60_000).toISOString(), + }), + ); +} diff --git a/web/src/components/DiffDrawer.tsx b/web/src/components/DiffDrawer.tsx index 05e5e515..feaac640 100644 --- a/web/src/components/DiffDrawer.tsx +++ b/web/src/components/DiffDrawer.tsx @@ -1,9 +1,18 @@ -import { useQuery } from "@tanstack/react-query"; -import { Download, FileText, PlayCircle } from "lucide-react"; +import { useQuery, useQueryClient } from "@tanstack/react-query"; +import { BadgeCheck, Download, FileText, PlayCircle } from "lucide-react"; import { useEffect, useMemo, useRef, useState } from "react"; +import { Button } from "@/components/ui/button"; +import { ConfirmDialog } from "@/components/ui/confirm"; import { AnimatedSheet, SheetDescription, SheetTitle } from "@/components/ui/sheet"; -import { fetchConsoleDiff, fetchDiff, outputText, sampleFile } from "@/lib/api"; +import { + fetchConsoleDiff, + fetchDiff, + outputText, + promoteBaseline, + sampleFile, +} from "@/lib/api"; +import { getSession } from "@/lib/auth"; import { clock, cuesToVtt, parseCues, type Cue } from "@/lib/cues"; import { diffRows, whole, wordDiff, type DiffRow, type Seg } from "@/lib/diff"; import { cn } from "@/lib/utils"; @@ -71,7 +80,7 @@ export function DiffDrawer({ : `${target.command} · ${target.sampleName} · run ${target.runId}`} {!isConsole(target) && ( -
+
setView("playback")} /> + {getSession()?.role === "admin" && ( + + )}
)}
@@ -98,6 +113,65 @@ export function DiffDrawer({ ); } +/** + * Make the output this run produced the expected baseline. + * + * It sits here because the drawer is where a failure gets judged, and the + * drawer opens from any run (Home, the run page, its artifacts), not only the + * few recent ones Home lists. Admin-only, as the endpoint is, and confirmed + * first: it applies to every future run on all platforms. + */ +function PromoteBaseline({ target }: Readonly<{ target: OutputDiffTarget }>) { + const qc = useQueryClient(); + const [confirming, setConfirming] = useState(false); + const [busy, setBusy] = useState(false); + const [result, setResult] = useState<{ ok: boolean; message: string } | null>(null); + + const promote = async () => { + setBusy(true); + const res = await promoteBaseline(target); + setBusy(false); + setConfirming(false); + setResult(res); + if (res.ok) { + // The test's baselines list shows the new hash on its next open. + await qc.invalidateQueries({ queryKey: ["regression-test", target.regressionId] }); + } + }; + + return ( +
+ {result && ( + + {result.message} + + )} + {!result?.ok && ( + + )} + + The output run {target.runId} produced becomes the expected baseline{" "} + for every future run, on all platforms. The current baseline hash + is discarded, and the only way back is promoting another output. If only + one platform differs, adding a variant from the test's Baselines keeps + the current one. + + } + confirmLabel={busy ? "Promoting…" : "Replace baseline"} + busy={busy} + onConfirm={promote} + /> +
+ ); +} + function ViewTab({ icon: Icon, label, diff --git a/web/src/pages/Triage.tsx b/web/src/pages/Triage.tsx index edee4163..144d6c1a 100644 --- a/web/src/pages/Triage.tsx +++ b/web/src/pages/Triage.tsx @@ -1,5 +1,5 @@ import { Link } from "@tanstack/react-router"; -import { ExternalLink, MoreHorizontal, ShieldCheck } from "lucide-react"; +import { ExternalLink, ShieldCheck } from "lucide-react"; import { AnimatePresence, motion } from "motion/react"; import { useMemo, useState } from "react"; @@ -7,9 +7,7 @@ import { DiffDrawer, type DiffTarget } from "@/components/DiffDrawer"; import { Sparkline } from "@/components/Sparkline"; import { Badge } from "@/components/ui/badge"; import { Button } from "@/components/ui/button"; -import { ConfirmDialog } from "@/components/ui/confirm"; import { - promoteBaseline, useHealth, useQueue, useRegressionTests, @@ -19,7 +17,6 @@ import { useTestHistory, type RunFailure, } from "@/lib/api"; -import { getSession } from "@/lib/auth"; import { githubUrl } from "@/lib/validate"; import type { LogicalRun } from "@/lib/types"; import { cn } from "@/lib/utils"; @@ -28,9 +25,9 @@ import { cn } from "@/lib/utils"; * Home: an inbox of recent runs that finished with failures. Each card pulls * that run's failing tests and groups them by category. * - * Baseline promotion hides behind a per-row overflow menu and a warning - * dialog. There is intentionally no bulk accept — replacing baselines should - * take one deliberate click per test. + * Baseline promotion lives in the diff drawer each row opens, behind a + * warning dialog. There is intentionally no bulk accept — replacing + * baselines should take one deliberate click per test. */ export function Triage() { const { data: runs = [], isLoading } = useRuns(); @@ -368,31 +365,12 @@ function FailureCard({ } function FailureRow({ f, runId }: Readonly<{ f: RunFailure; runId: number }>) { - const admin = getSession()?.role === "admin"; - const [menu, setMenu] = useState(false); - const [confirming, setConfirming] = useState(false); - const [busy, setBusy] = useState(false); - const [result, setResult] = useState(null); const [diff, setDiff] = useState(null); // Shares the query the tests list already made, so this costs no fetch. const { data: history } = useTestHistory(); const past = history?.get(f.regression_test_id); const output = f.outputs.find((o) => o.status === "fail") ?? f.outputs[0]; - const doPromote = async () => { - if (!output) return; - setBusy(true); - const res = await promoteBaseline({ - runId, - sampleId: f.sample_id, - regressionId: f.regression_test_id, - outputId: output.output_id, - }); - setBusy(false); - setConfirming(false); - setResult(res.ok ? "Baseline promoted." : res.message); - }; - return (
) { )} - {result && {result}} - {output && ( )} - {admin && output && !result && ( -
- - {menu && ( -
- -
- )} -
- )} - - - The output this run produced becomes the expected baseline{" "} - for every future run, on all platforms. The current baseline hash - is discarded, and the only way back is promoting another output. - - } - confirmLabel={busy ? "Promoting…" : "Replace baseline"} - busy={busy} - onConfirm={doPromote} - /> - setDiff(null)} />
); From 320a10d4a4d9ae0f4f0547aea9086da207d852e0 Mon Sep 17 00:00:00 2001 From: pulk17 Date: Tue, 24 Nov 2026 12:59:52 +0530 Subject: [PATCH 4/4] look up a connected account's missing GitHub login The account page printed "Connected as @" with nothing after it. The login is stored once, by the OAuth callback, and if that lookup failed (or the account was connected before the column existed) nothing filled it in again; GET /auth/me/github returned the null as it was. Add github_login_of(), which returns the stored login or asks GitHub for it and keeps the answer, and use it in that endpoint and in the fork-run permission check, which had its own copy of the same lookup. The page says the account name could not be read instead of a bare "@" when GitHub does not answer either. --- mod_api/routes/auth.py | 3 ++- mod_api/routes/runs.py | 12 ++---------- mod_auth/controllers.py | 21 +++++++++++++++++++++ tests/api/test_routes_auth.py | 31 +++++++++++++++++++++++++++++++ web/src/pages/Account.tsx | 12 ++++++++++-- 5 files changed, 66 insertions(+), 13 deletions(-) diff --git a/mod_api/routes/auth.py b/mod_api/routes/auth.py index 5c06e466..22a356c8 100644 --- a/mod_api/routes/auth.py +++ b/mod_api/routes/auth.py @@ -651,13 +651,14 @@ def get_github_link(): The stored token is never part of this response. The URL carries only the client id and the scope asked for, both of which are public. """ + from mod_auth.controllers import github_login_of from run import config user = g.api_user client_id = config.get('GITHUB_CLIENT_ID', '') return single_response({ 'linked': user.github_token is not None, - 'github_login': user.github_login, + 'github_login': github_login_of(user), 'authorize_url': ( 'https://github.com/login/oauth/authorize' f'?client_id={client_id}&scope=public_repo'), diff --git a/mod_api/routes/runs.py b/mod_api/routes/runs.py index 66d5d547..947e22d8 100644 --- a/mod_api/routes/runs.py +++ b/mod_api/routes/runs.py @@ -171,16 +171,8 @@ def _validate_run_permissions(user, target_repo, main_repo_full): ) else: owner = target_repo.split('/')[0] - github_login = getattr(user, 'github_login', None) - - if not github_login and getattr(user, 'github_token', None): - from mod_auth.controllers import fetch_username_from_token - github_login = fetch_username_from_token(user) - if github_login: - user.github_login = github_login - g.db.add(user) - - github_login = github_login or '' + from mod_auth.controllers import github_login_of + github_login = github_login_of(user) or '' if not github_login or owner.lower() != github_login.lower(): return make_error_response( diff --git a/mod_auth/controllers.py b/mod_auth/controllers.py index a1f77377..fee4c09d 100755 --- a/mod_auth/controllers.py +++ b/mod_auth/controllers.py @@ -192,6 +192,27 @@ def fetch_username_from_token(user=None) -> Any: return None +def github_login_of(user) -> Optional[str]: + """ + Return the GitHub login of a connected account, looking it up if missing. + + The login is normally stored by the OAuth callback, but that lookup can + fail, and accounts connected before the column existed never had one. + Asking GitHub again the next time the login is needed repairs them. + + :param user: the account to read and, when the lookup succeeds, update + :return: the login, or None when not connected or GitHub did not answer + """ + if user.github_login or user.github_token is None: + return user.github_login + login = fetch_username_from_token(user) + if login: + user.github_login = login + g.db.add(user) + g.db.commit() + return login + + @mod_auth.route('/github_callback', methods=['GET', 'POST']) @template_renderer() def github_callback(): diff --git a/tests/api/test_routes_auth.py b/tests/api/test_routes_auth.py index ce8806c4..0883a8b7 100644 --- a/tests/api/test_routes_auth.py +++ b/tests/api/test_routes_auth.py @@ -745,6 +745,37 @@ def test_github_link_reports_status_without_the_token(self): res.json['authorize_url']) self.assertNotIn('client_secret', res.json['authorize_url']) + @patch('mod_auth.controllers.fetch_username_from_token', return_value='found-later') + def test_github_link_looks_up_a_missing_login_and_keeps_it(self, mock_fetch): + user = User.query.filter(User.id == self.user_id).first() + user.github_token = 'gho_secret_value' + user.github_login = None + g.db.commit() + + res = self.client.get( + '/api/v1/auth/me/github', headers=self._auth(name='gh3')) + + self.assertEqual(res.json['github_login'], 'found-later') + user = User.query.filter(User.id == self.user_id).first() + self.assertEqual(user.github_login, 'found-later') + + # Stored now, so the next request does not ask GitHub again. + self.client.get('/api/v1/auth/me/github', headers=self._auth(name='gh4')) + mock_fetch.assert_called_once() + + @patch('mod_auth.controllers.fetch_username_from_token', return_value=None) + def test_github_link_without_a_login_when_github_does_not_answer(self, mock_fetch): + user = User.query.filter(User.id == self.user_id).first() + user.github_token = 'gho_secret_value' + user.github_login = None + g.db.commit() + + res = self.client.get( + '/api/v1/auth/me/github', headers=self._auth(name='gh5')) + + self.assertTrue(res.json['linked']) + self.assertIsNone(res.json['github_login']) + def test_github_unlink_forgets_the_connection(self): user = User.query.filter(User.id == self.user_id).first() user.github_token = 'gho_secret_value' diff --git a/web/src/pages/Account.tsx b/web/src/pages/Account.tsx index b197bbf6..c00ad4d3 100644 --- a/web/src/pages/Account.tsx +++ b/web/src/pages/Account.tsx @@ -265,8 +265,16 @@ function GithubSection() {

{data.linked ? ( <> - Connected as{" "} - @{data.github_login}. + {data.github_login ? ( + <> + Connected as{" "} + @{data.github_login}. + + ) : ( + // GitHub did not say who the token belongs to; reconnecting + // from the classic page stores the name again. + "Connected to GitHub, but the account name could not be read." + )}{" "} Runs on your own forks and pull requests use this. ) : (