diff --git a/server/frontend/src/__tests__/text-snapshot.test.tsx b/server/frontend/src/__tests__/text-snapshot.test.tsx index dac09980..745e9e02 100644 --- a/server/frontend/src/__tests__/text-snapshot.test.tsx +++ b/server/frontend/src/__tests__/text-snapshot.test.tsx @@ -25,6 +25,7 @@ function data(over: { state?: SnapshotData['snapshot']['state']; lines: TextLine moved_lines: [], text: { format: 'json', base_lines: 9, head_lines: 9, json_changes: [], json_changes_truncated: false, note: null, + base: null, head: null, ...over.text, }, } @@ -87,7 +88,8 @@ describe('TextSnapshot', () => { }) it('no differences after normalizing', () => { - expect(view(data({ state: 'unchanged', lines: [], text: { note: 'Compared with keys sorted.' } }))).toMatchSnapshot() + const json = '{\n "id": 1042,\n "items": [\n "Desk lamp",\n "Notebook"\n ],\n "status": "paid",\n "total": 65\n}' + expect(view(data({ state: 'unchanged', lines: [], text: { note: 'Compared with keys sorted.', base: json, head: json } }))).toMatchSnapshot() }) it('removed', () => { diff --git a/server/frontend/src/__tests__/text-views.test.tsx b/server/frontend/src/__tests__/text-views.test.tsx new file mode 100644 index 00000000..1dc6bc5f --- /dev/null +++ b/server/frontend/src/__tests__/text-views.test.tsx @@ -0,0 +1,34 @@ +import { describe, expect, it } from 'vitest' +import { fireEvent, render } from '@testing-library/react' +import { TextSnapshot } from '../components/TextSnapshot' +import type { SnapshotData } from '../api/types' + +const data = (state: string, text_diff: unknown[], base: string | null, head: string | null) => + ({ + snapshot: { state }, + pages: [{ text_diff }], + text: { format: 'json', base_lines: 3, head_lines: 3, json_changes: [], json_changes_truncated: false, note: null, base, head }, + }) as unknown as SnapshotData + +const view = (d: SnapshotData) => + render( {}} active={0} hunkRef={() => {}} />) + +describe('text snapshot views', () => { + it('shows an unchanged snapshot as it is, with a No changes badge', () => { + const json = '{\n "total": 65\n}' + const { container, getByText } = view(data('unchanged', [], json, json)) + expect(getByText('No changes')).toBeTruthy() + expect(container.textContent).toContain('"total": 65') + expect(container.textContent).not.toContain('No differences') + }) + + it('offers each version of a changed snapshot', () => { + const lines = [{ tag: '-', text: '"total": 65', base_line: 2, head_line: null }, { tag: '+', text: '"total": 71', base_line: null, head_line: 2 }] + const { container, getByRole } = view(data('changed', lines, '{\n "total": 65\n}', '{\n "total": 71\n}')) + fireEvent.click(getByRole('radio', { name: 'Baseline' })) + expect(container.textContent).toContain('Baseline at that time') + expect(container.textContent).toContain('"total": 65') + fireEvent.click(getByRole('radio', { name: 'This build' })) + expect(container.textContent).toContain('"total": 71') + }) +}) diff --git a/server/frontend/src/api/types.ts b/server/frontend/src/api/types.ts index 215a032d..a9162488 100644 --- a/server/frontend/src/api/types.ts +++ b/server/frontend/src/api/types.ts @@ -382,6 +382,9 @@ export type TextDetail = { json_changes: PathChange[] json_changes_truncated: boolean note: string | null + /** Each side's whole normalized text, to show either version as it was. Null for a side the snapshot doesn't have. */ + base: string | null + head: string | null } export type PageRow = { diff --git a/server/frontend/src/components/TextSnapshot.tsx b/server/frontend/src/components/TextSnapshot.tsx index 3596b8df..eefa473c 100644 --- a/server/frontend/src/components/TextSnapshot.tsx +++ b/server/frontend/src/components/TextSnapshot.tsx @@ -1,7 +1,7 @@ import { useState } from 'react' import { ArrowsInLineVerticalIcon, ArrowsOutLineVerticalIcon } from '@phosphor-icons/react' import type { PathChange, SnapshotData, TextLine } from '../api/types' -import { Button, Help, Pill } from './ui' +import { Button, Pill } from './ui' import { n, plural } from '../lib/format' /** A run of diff lines with no unchanged lines left out inside it, and how many were left out before it. */ @@ -28,6 +28,9 @@ export function textHunks(lines: TextLine[], headLines: number): { hunks: Hunk[] const formatName = { json: 'JSON', html: 'HTML', text: 'Plain text' } as const +/** What the text snapshot shows: the diff, or one whole version as it was. */ +type TextView = 'diff' | 'head' | 'base' + type Props = { data: SnapshotData hunks: Hunk[] @@ -48,6 +51,23 @@ export function TextSnapshot({ data, hunks, trailing, full, loadingFull, onToggl const removed = lines.filter((l) => l.tag === '-').length const isNew = state === 'added' const folded = hunks.some((h) => h.gapBefore > 0) || trailing > 0 + const isRemoved = state === 'removed' + const noChanges = !isNew && !isRemoved && lines.length === 0 + // Each whole version: the server's, else rebuilt from the diff's lines (which hold every line of an added or a + // removed snapshot). + const head = isRemoved ? null : (text.head ?? (lines.length ? lines.filter((l) => l.tag !== '-').map((l) => l.text).join('\n') : null)) + const base = isNew ? null : (text.base ?? (lines.length ? lines.filter((l) => l.tag !== '+').map((l) => l.text).join('\n') : null)) + // Which views make sense: a diff only for a changed snapshot; each version only when the snapshot has it (an added + // one has no baseline, a removed one no new version). + const views: TextView[] = [ + ...(lines.length > 0 && !isNew && !isRemoved ? (['diff'] as const) : []), + ...(head != null ? (['head'] as const) : []), + ...(base != null && !noChanges ? (['base'] as const) : []), + ] + const [chosen, setView] = useState(null) + // By default: the diff when there is one, else the version there is (unchanged and added: this build; removed: the + // baseline). + const view: TextView = chosen && views.includes(chosen) ? chosen : (views[0] ?? 'head') return (
@@ -64,7 +84,17 @@ export function TextSnapshot({ data, hunks, trailing, full, loadingFull, onToggl {removed > 0 && −{removed}} )} - {!isNew && lines.length > 0 && (full || folded) && ( + {noChanges && No changes} + {views.length > 1 && ( + + {views.map((v) => ( + + ))} + + )} + {view === 'diff' && !isNew && lines.length > 0 && (full || folded) && (
) } + +/** One whole version of a text snapshot, normalized as it was compared, with line numbers. */ +function WholeText({ text, label }: { text: string; label: string }) { + const lines = text.split('\n') + if (lines.length > 1 && lines[lines.length - 1] === '') lines.pop() + return ( +
+

{label}

+ {lines.map((l, i) => ( +
+ + + {i + 1} + + + {' '} + + {l || ' '} +
+ ))} +
+ ) +} diff --git a/server/frontend/src/pages/SnapshotPage.tsx b/server/frontend/src/pages/SnapshotPage.tsx index 5e034b9d..28f650ab 100644 --- a/server/frontend/src/pages/SnapshotPage.tsx +++ b/server/frontend/src/pages/SnapshotPage.tsx @@ -23,9 +23,15 @@ import { TextSnapshot, textHunks } from '../components/TextSnapshot' const route = getRouteApi('/_app/$org/$project/builds/$number/snapshots/$id') -const MODES = ['side', 'diff', 'slider'] as const +const MODES = ['side', 'diff', 'slider', 'base', 'head'] as const type Mode = (typeof MODES)[number] -const modeLabel: Record = { side: 'Side by side', diff: 'Diff', slider: 'Slider' } +const modeLabel: Record = { + side: 'Side by side', + diff: 'Diff', + slider: 'Slider', + base: 'Baseline', + head: 'This build', +} /** How changed regions are marked on a page's images: filled boxes, rings around them, everything else dimmed, or * nothing. */ @@ -197,6 +203,8 @@ export function SnapshotPage() { case 'k': goTo(Math.max(active - 1, 0)) break + case '4': + case '5': case '1': case '2': case '3': @@ -255,7 +263,7 @@ export function SnapshotPage() { canComment={q.data.can_review !== false} canResolve={q.data.can_review !== false} > - +
@@ -540,7 +548,7 @@ function ShortcutHelp({ onClose, canReview, isText }: { onClose: () => void; can ] : [ [<>j k, 'Next and previous page'], - [<>1 2 3, 'Side by side, diff, slider'], + [<>1 to 5, 'Side by side, diff, slider, baseline, this build'], [h, 'Turn the highlight of changed regions off or on'], [<>[ ], 'Previous and next snapshot'], ] @@ -770,7 +778,7 @@ function Frame({ label, children, tone }: { label: string; children: ReactNode; } /** What the old side is called: the baseline ("Base"), or the previous build while comparing with it. */ -const OldSide = createContext('Base') +const OldSide = createContext('Baseline') function Missing({ text }: { text: string }) { return
{text}
@@ -826,7 +834,26 @@ function PageImages({ if (p.op === 'unchanged') { return (
- {head} + {head} +
+ ) + } + + // One version full size: the baseline as it was for this build, or this build's. An added page has no baseline and a + // removed one no new version, so they show the side they have. + if ((mode === 'base' && p.base_url) || (mode === 'head' && !p.head_url && p.base_url)) { + return ( +
+ {base} +
+ ) + } + if ((mode === 'head' && p.head_url) || (mode === 'base' && !p.base_url && p.head_url)) { + return ( +
+ + {head} +
) } @@ -859,7 +886,7 @@ function PageImages({ {base} - + {head}
diff --git a/server/frontend/src/styles.css b/server/frontend/src/styles.css index 109c691b..f429cadb 100644 --- a/server/frontend/src/styles.css +++ b/server/frontend/src/styles.css @@ -3667,6 +3667,18 @@ svg.regions-dim { } } + +/* On a phone the view modes wrap rather than widen the page, and drop their keyboard hints (no keyboard). */ +@media (max-width: 640px) { + .review-bar .seg { + flex-wrap: wrap; + max-width: 100%; + } + + .review-bar .seg .kbd { + display: none; + } +} @media (max-width: 900px) { .lp-hero, .lp-split, diff --git a/server/src/mcp.rs b/server/src/mcp.rs index 6a1667b6..f5a3c1f1 100644 --- a/server/src/mcp.rs +++ b/server/src/mcp.rs @@ -246,7 +246,8 @@ pub struct SnapshotArgs { pub platform: String, /// Positions of the pages to include images for (from a previous answer). Default: the first three changed pages. pub pages: Option>, - /// Which images to include: `all` (base, head, diff; the default), `diff`, `head`, `base`, or `none`. + /// Which images to include: `all` (base, head, diff; the default), `diff`, `head`, `base`, or `none`. For text, + /// JSON and HTML: `head`, `base` or `all` adds that whole version's text. pub images: Option, /// Scale images down to this width in pixels (default 1200). Large ones come back as JPEG. pub max_width: Option, @@ -1652,7 +1653,7 @@ impl VisualCi { } #[tool( - description = "Look at one snapshot's comparison. Documents and images: for every page its operation (unchanged, changed, inserted, removed), the diff's changed pixels and regions, and the text diff; lines that moved to another page; and the base, head and diff images of changed pages (the first three, or the pages you name). Each page's `embed_url` has week-long links to its images, for a pull request comment or a report. Text, JSON and HTML snapshots: the format, the changes by JSON path (`items[3].price: 10 → 12`) and a unified diff of the normalized text (sorted JSON keys, one HTML node per line, ignore rules applied). Also the snapshot's open comment threads, each with the build it was drawn on. `against: \"previous\"` compares with the branch's previous build instead of the baseline, to check a fix against a comment left there.", + description = "Look at one snapshot's comparison. Documents and images: for every page its operation (unchanged, changed, inserted, removed), the diff's changed pixels and regions, and the text diff; lines that moved to another page; and the base, head and diff images of changed pages (the first three, or the pages you name). Each page's `embed_url` has week-long links to its images, for a pull request comment or a report. Text, JSON and HTML snapshots: the format, the changes by JSON path (`items[3].price: 10 → 12`) and a unified diff of the normalized text (sorted JSON keys, one HTML node per line, ignore rules applied); `images: head`, `base` or `all` adds that whole version. An unchanged snapshot's images come too (its first pages), so any build's version can be looked at. Also the snapshot's open comment threads, each with the build it was drawn on. `against: \"previous\"` compares with the branch's previous build instead of the baseline, to check a fix against a comment left there.", annotations(title = "Get snapshot", read_only_hint = true, idempotent_hint = true, open_world_hint = false) )] async fn get_snapshot( @@ -1754,14 +1755,39 @@ impl VisualCi { head.unwrap_or_default() ))); } + // Either version as it was, on request: `images: head`, `base` or `all` (any snapshot, unchanged too). + let asked = args.images.as_deref(); + let side = |name: &str| asked == Some(name) || asked == Some("all"); + if side("head") + && !added + && let Some(head) = &text.head + { + content.push(Content::text(format!("This build's version:\n{head}"))); + } + if side("base") + && let Some(base) = &text.base + { + content.push(Content::text(format!("The baseline's version:\n{base}"))); + } return Ok(CallToolResult::success(content)); } let (pages, moved) = (detail.pages, detail.moved); + // Changed pages first; with none (an unchanged snapshot), the first pages, so any snapshot can be looked at. let wanted: Vec = match &args.pages { Some(p) => p.clone(), None => { - pages.iter().filter(|p| p.state == "changed").take(DEFAULT_IMAGE_PAGES).map(|p| p.position).collect() + let changed: Vec = pages + .iter() + .filter(|p| p.state == "changed") + .take(DEFAULT_IMAGE_PAGES) + .map(|p| p.position) + .collect(); + if changed.is_empty() { + pages.iter().take(DEFAULT_IMAGE_PAGES).map(|p| p.position).collect() + } else { + changed + } } }; let which = args.images.as_deref().unwrap_or("all"); diff --git a/server/src/models/snapshots.rs b/server/src/models/snapshots.rs index e22857fe..791303dc 100644 --- a/server/src/models/snapshots.rs +++ b/server/src/models/snapshots.rs @@ -740,6 +740,10 @@ pub struct TextDetail { /// The unified diff (`@@` hunks), for agents. Left out of the web app's JSON, which has the lines. #[serde(skip)] pub unified: String, + /// Each side's whole normalized text, to show either version as it was: `None` for a side the snapshot doesn't + /// have (an added snapshot has no base, a removed one no head). + pub base: Option, + pub head: Option, } pub const JSON_CHANGE_LIMIT: usize = 200; @@ -982,7 +986,10 @@ impl Model { let row = rows.first(); let base = row.and_then(|r| r.base_text.as_deref()).unwrap_or(""); let head = row.and_then(|r| r.head_text.as_deref()).unwrap_or(""); - text_detail(format, base, head, row.is_some_and(|r| r.base_text.is_some())) + let mut detail = text_detail(format, base, head, row.is_some_and(|r| r.base_text.is_some())); + detail.base = row.and_then(|r| r.base_text.clone()); + detail.head = row.and_then(|r| r.head_text.clone()).filter(|_| self.state != "removed"); + detail }); let moved = if text.is_some() { Vec::new() @@ -1024,6 +1031,8 @@ fn text_detail(format: Format, base: &str, head: &str, has_base: bool) -> TextDe json_changes_truncated: truncated, note, unified: snapshot_text::unified(base, head, DEFAULT_CONTEXT), + base: None, + head: None, } } diff --git a/server/tests/requests/baselines.rs b/server/tests/requests/baselines.rs index b3293265..67c1a712 100644 --- a/server/tests/requests/baselines.rs +++ b/server/tests/requests/baselines.rs @@ -635,3 +635,43 @@ async fn a_version_approved_on_another_branch_is_pointed_out() { }) .await; } + +/// Any snapshot can be looked at as it was, unchanged ones too: `get_snapshot` gives an unchanged JSON snapshot's text +/// (`images: head`) and an unchanged screenshot's image. +#[tokio::test] +#[serial] +async fn get_snapshot_shows_unchanged_snapshots_as_they_are() { + request::(|request, ctx| async move { + let Some(w) = world(&ctx).await else { return }; + let json = "{\"orders\": [{\"id\": 1, \"total\": 65}]}\n"; + let files = || [("orders.json", File::Text(json)), ("shot", File::Image(RED))]; + w.build("A", "main", &[], "ci", &files()).await; + let b = w.build("B", "main", &["A"], "ci", &files()).await; + assert_eq!(w.states(&b).await, st(&[("orders.json", "unchanged"), ("shot", "unchanged")])); + let (_, token) = + visualci_server::models::project_tokens::Model::generate(w.db, w.project.id, "test").await.unwrap(); + let get = |args: serde_json::Value| { + let request = &request; + let token = token.clone(); + async move { + let res = request + .post("/mcp") + .add_header("authorization", format!("Bearer {token}")) + .add_header("accept", "application/json, text/event-stream") + .json(&serde_json::json!({ + "jsonrpc": "2.0", "id": 1, "method": "tools/call", + "params": { "name": "get_snapshot", "arguments": args }, + })) + .await; + let body: serde_json::Value = res.json(); + body["result"]["content"].as_array().cloned().unwrap_or_default() + } + }; + let text = get(serde_json::json!({ "build": b.number, "name": "orders.json", "images": "head" })).await; + let all: String = text.iter().filter_map(|c| c["text"].as_str()).collect::>().join("\n"); + assert!(all.contains("This build's version:") && all.contains("\"total\": 65"), "{all}"); + let image = get(serde_json::json!({ "build": b.number, "name": "shot", "images": "head" })).await; + assert!(image.iter().any(|c| c["type"] == "image"), "an unchanged screenshot's image: {image:?}"); + }) + .await; +}