Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion server/frontend/src/__tests__/text-snapshot.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
},
}
Expand Down Expand Up @@ -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', () => {
Expand Down
34 changes: 34 additions & 0 deletions server/frontend/src/__tests__/text-views.test.tsx
Original file line number Diff line number Diff line change
@@ -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(<TextSnapshot data={d} hunks={[]} trailing={0} full={false} loadingFull={false} onToggleFull={() => {}} 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')
})
})
3 changes: 3 additions & 0 deletions server/frontend/src/api/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down
82 changes: 70 additions & 12 deletions server/frontend/src/components/TextSnapshot.tsx
Original file line number Diff line number Diff line change
@@ -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. */
Expand All @@ -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[]
Expand All @@ -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<TextView | null>(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 (
<section className="text-snap" aria-label="Text diff">
Expand All @@ -64,7 +84,17 @@ export function TextSnapshot({ data, hunks, trailing, full, loadingFull, onToggl
{removed > 0 && <span className="td-del">−{removed}</span>}
</span>
)}
{!isNew && lines.length > 0 && (full || folded) && (
{noChanges && <Pill tone="neutral">No changes</Pill>}
{views.length > 1 && (
<span className="seg seg-sm text-snap-views" role="radiogroup" aria-label="View">
{views.map((v) => (
<button key={v} type="button" role="radio" aria-checked={view === v} className="seg-btn" onClick={() => setView(v)}>
{v === 'diff' ? 'Diff' : v === 'head' ? 'This build' : 'Baseline'}
</button>
))}
</span>
)}
{view === 'diff' && !isNew && lines.length > 0 && (full || folded) && (
<Button size="sm" variant="ghost" loading={loadingFull} onClick={onToggleFull} className="text-snap-toggle">
{full ? <ArrowsInLineVerticalIcon size={14} /> : <ArrowsOutLineVerticalIcon size={14} />}
{full ? 'Fold unchanged lines' : 'Show every line'}
Expand All @@ -80,16 +110,21 @@ export function TextSnapshot({ data, hunks, trailing, full, loadingFull, onToggl

{text.json_changes.length > 0 && <JsonChanges changes={text.json_changes} truncated={text.json_changes_truncated} />}

{state === 'removed' ? (
<div className="empty">
<h3>Removed</h3>
</div>
) : lines.length === 0 ? (
<div className="empty">
<h3>
No differences <Help>Compared after normalizing and the ignore rules.</Help>
</h3>
</div>
{view !== 'diff' && (view === 'base' ? base : head) == null ? (
<p className="notice">This version's text isn't available.</p>
) : view !== 'diff' ? (
<WholeText
text={(view === 'base' ? base : head) ?? ''}
label={
view === 'base'
? state === 'removed'
? 'Baseline: removed in this build'
: 'Baseline at that time'
: noChanges
? 'This build, the same as the baseline (compared after normalizing and the ignore rules)'
: 'This build'
}
/>
) : (
<div className="tdiff" data-new={isNew || undefined}>
{isNew && <p className="tdiff-banner muted">New snapshot</p>}
Expand Down Expand Up @@ -190,3 +225,26 @@ function JsonChanges({ changes, truncated }: { changes: PathChange[]; truncated:
</section>
)
}

/** 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 (
<div className="tdiff tdiff-whole">
<p className="tdiff-banner muted">{label}</p>
{lines.map((l, i) => (
<div key={i} className="td-line" data-tag="ctx">
<span className="td-num" aria-hidden />
<span className="td-num" aria-hidden>
{i + 1}
</span>
<span className="td-gutter" aria-hidden>
{' '}
</span>
<span className="td-text">{l || ' '}</span>
</div>
))}
</div>
)
}
41 changes: 34 additions & 7 deletions server/frontend/src/pages/SnapshotPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<Mode, string> = { side: 'Side by side', diff: 'Diff', slider: 'Slider' }
const modeLabel: Record<Mode, string> = {
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. */
Expand Down Expand Up @@ -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':
Expand Down Expand Up @@ -255,7 +263,7 @@ export function SnapshotPage() {
canComment={q.data.can_review !== false}
canResolve={q.data.can_review !== false}
>
<OldSide.Provider value={comparedPrevious ? `Build #${previous.build}` : 'Base'}>
<OldSide.Provider value={comparedPrevious ? `Build #${previous.build}` : 'Baseline'}>
<div className="review">
<div className="review-bar" ref={reviewBar}>
<div className="review-bar-id">
Expand Down Expand Up @@ -540,7 +548,7 @@ function ShortcutHelp({ onClose, canReview, isText }: { onClose: () => void; can
]
: [
[<><Kbd>j</Kbd> <Kbd>k</Kbd></>, 'Next and previous page'],
[<><Kbd>1</Kbd> <Kbd>2</Kbd> <Kbd>3</Kbd></>, 'Side by side, diff, slider'],
[<><Kbd>1</Kbd> to <Kbd>5</Kbd></>, 'Side by side, diff, slider, baseline, this build'],
[<Kbd>h</Kbd>, 'Turn the highlight of changed regions off or on'],
[<><Kbd>[</Kbd> <Kbd>]</Kbd></>, 'Previous and next snapshot'],
]
Expand Down Expand Up @@ -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 <div className="missing">{text}</div>
Expand Down Expand Up @@ -826,7 +834,26 @@ function PageImages({
if (p.op === 'unchanged') {
return (
<div className="frames frames-one">
<Frame label="Unchanged">{head}</Frame>
<Frame label="No changes">{head}</Frame>
</div>
)
}

// 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 (
<div className="frames frames-one">
<Frame label={old === 'Baseline' ? 'Baseline at that time' : old}>{base}</Frame>
</div>
)
}
if ((mode === 'head' && p.head_url) || (mode === 'base' && !p.base_url && p.head_url)) {
return (
<div className="frames frames-one">
<Frame label="This build" tone="accent">
{head}
</Frame>
</div>
)
}
Expand Down Expand Up @@ -859,7 +886,7 @@ function PageImages({
<Frame label={old} tone={p.op === 'removed' ? 'removed' : undefined}>
{base}
</Frame>
<Frame label={p.op === 'inserted' ? 'Head, inserted' : 'Head'} tone={p.op === 'inserted' ? 'added' : 'accent'}>
<Frame label={p.op === 'inserted' ? 'This build, inserted' : 'This build'} tone={p.op === 'inserted' ? 'added' : 'accent'}>
{head}
</Frame>
</div>
Expand Down
12 changes: 12 additions & 0 deletions server/frontend/src/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
32 changes: 29 additions & 3 deletions server/src/mcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<i32>>,
/// 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<String>,
/// Scale images down to this width in pixels (default 1200). Large ones come back as JPEG.
pub max_width: Option<u32>,
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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<i32> = 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<i32> = 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");
Expand Down
11 changes: 10 additions & 1 deletion server/src/models/snapshots.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>,
pub head: Option<String>,
}

pub const JSON_CHANGE_LIMIT: usize = 200;
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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,
}
}

Expand Down
Loading
Loading