Files
pipelines/web/src/changes.js
T
alan 9d1745da1d web: run Summary Changes section with rendered/raw diff viewer (R4)
Add a collapsed-by-default Changes section to the run Summary tab and a
full-screen diff viewer, ported from the Android RunChanges/ChangeDiffViewer
wording. Pure aggregation and unified-patch parsing live in src/changes.js;
app.js wires the section/viewer and sets every server string with textContent.
Unit tests cover the header variants, kind merge, stat sums and hunk parsing;
ui-smoke captures the collapsed/expanded section, rendered and raw viewer,
paging, Escape/backdrop close, binary, truncated and a running run's header.
2026-10-19 04:06:44 +01:00

555 lines
22 KiB
JavaScript

// Pure, DOM-free logic for the run summary's Changes section and its diff
// viewer, ported from the Android client so the browser says and shows exactly
// the same things:
// ui/changes/RunChanges.kt changeKind, changeKindLabel, parseUnifiedPatch,
// runChanges, runChangesHeader, runChangesNote,
// changesListSummary, noChangeDetail,
// patchUnavailableReason, changeEntryTags,
// changeRowMeta, changePositionLabel, gutterWidth
// ui/changes/ChangeDiffViewer.kt the file row, the viewer header/controls/body
// and the honest no-diff/reason wording
// ui/chat/ChatDiffCard.kt diffLineSymbol / diffLineColor (the one diff
// line language shared with the chat edit card)
//
// Nothing here touches the DOM or imports the app: every function is pure so the
// wording, ordering, counting and patch parsing can be unit-tested without a
// browser. The section/viewer wiring lives in app.js. Every server-provided
// string is only ever compared or rendered, never parsed as markup; the caller
// sets it with textContent.
// ---------------------------------------------------------------------------
// Change kind
// ---------------------------------------------------------------------------
/** The three recorded kinds plus the safe `other` fallback for anything else. */
export const ChangeKind = Object.freeze({
Added: "added",
Modified: "modified",
Deleted: "deleted",
Other: "other",
});
/**
* Maps the server's kind token to a ChangeKind. The token is trimmed and
* lowercased; an unrecognised or blank kind stays `other` rather than being
* guessed, so a future server value is shown read-only instead of mislabelled.
* Pure.
*/
export function changeKind(kind) {
switch (str(kind).trim().toLowerCase()) {
case "added":
return ChangeKind.Added;
case "modified":
return ChangeKind.Modified;
case "deleted":
return ChangeKind.Deleted;
default:
return ChangeKind.Other;
}
}
/** The word a file's kind is named by in the list and the diff header. */
export function changeKindLabel(kind) {
switch (kind) {
case ChangeKind.Added:
return "added";
case ChangeKind.Modified:
return "modified";
case ChangeKind.Deleted:
return "deleted";
default:
return "changed";
}
}
/** The kind word as the viewer header shows it, first letter capitalised. */
export function changeKindTitle(kind) {
const label = changeKindLabel(kind);
return label.charAt(0).toUpperCase() + label.slice(1);
}
// ---------------------------------------------------------------------------
// Unified patch parsing
// ---------------------------------------------------------------------------
/** Which kind of line this is within a unified patch. */
export const ChangeLineKind = Object.freeze({
Context: "context",
Add: "add",
Remove: "remove",
});
/**
* Parses a server-recorded unified patch into hunks, lines, line numbers and
* the true `+N -M` stat. The server builds these patches with a Go unified-diff
* writer (internal/filediff), so the shape is a standard `---`/`+++` header,
* optional metadata lines, `@@ -a,b +c,d @@` hunk headers and a ` `/`+`/`-`
* body. Anything unrecognised (a truncated tail, an exotic header) is carried
* verbatim in `headerLines` when it sits before the first hunk, and otherwise
* kept as an unnumbered context line, so the raw view always has the exact
* source while the rendered view shows only lines it can stand behind. A blank
* patch parses to an empty result rather than a fabricated one.
*/
export function parseUnifiedPatch(patch) {
const text = patch == null ? "" : String(patch);
if (text.trim() === "") {
return { raw: "", headerLines: [], hunks: [], added: 0, removed: 0 };
}
const rawLines = text.split("\n");
const headers = [];
const hunks = [];
let current = null;
for (const line of rawLines) {
const hunkStart = parseHunkHeader(line);
if (hunkStart != null) {
if (current) hunks.push(current.build());
current = new HunkBuilder(line, hunkStart.oldStart, hunkStart.oldCount, hunkStart.newStart, hunkStart.newCount);
} else if (line.startsWith("--- ") || line.startsWith("+++ ")) {
// An aggregated entry can contain one complete patch from each
// contributing stage. A new file header closes the preceding hunk
// instead of being rendered as an unnumbered context line in it.
if (current) {
hunks.push(current.build());
current = null;
}
headers.push(line);
} else if (current == null) {
headers.push(line);
} else {
current.lines.push(parseBodyLine(line, current));
}
}
if (current) hunks.push(current.build());
let added = 0;
let removed = 0;
for (const hunk of hunks) {
for (const line of hunk.lines) {
if (line.kind === ChangeLineKind.Add) added++;
else if (line.kind === ChangeLineKind.Remove) removed++;
}
}
return { raw: text, headerLines: headers, hunks, added, removed };
}
/**
* Mutable accumulator for one hunk as it is parsed, carrying the running old/new
* line counters so each body line gets its gutter numbers without a second pass.
*/
class HunkBuilder {
constructor(header, oldStart, oldCount, newStart, newCount) {
this.header = header;
this.oldStart = oldStart;
this.oldCount = oldCount;
this.newStart = newStart;
this.newCount = newCount;
this.lines = [];
this.oldLine = oldStart;
this.newLine = newStart;
}
build() {
return {
header: this.header,
oldStart: this.oldStart,
oldCount: this.oldCount,
newStart: this.newStart,
newCount: this.newCount,
lines: this.lines,
};
}
nextOld() {
return this.oldLine++;
}
nextNew() {
return this.newLine++;
}
}
/**
* The parsed `@@ -oldStart,oldCount +newStart,newCount @@` of a hunk header, or
* null when `line` is not one. A missing count defaults to 1 (the unified-diff
* rule) so a single-line hunk header is still read exactly. Pure.
*/
function parseHunkHeader(line) {
if (!line.startsWith("@@")) return null;
const end = line.indexOf("@@", 2);
if (end < 0) return null;
const ranges = tokenizeRanges(line.substring(2, end));
return ranges == null ? null : { oldStart: ranges[0], oldCount: ranges[1], newStart: ranges[2], newCount: ranges[3] };
}
/** The four numbers of a hunk header's range text, or null when malformed. Pure. */
function tokenizeRanges(body) {
const plus = body.indexOf("+");
const old = plus === -1 ? body : body.slice(0, plus);
const next = plus === -1 ? "" : body.slice(plus + 1);
if (old === "" || next === "") return null;
const oldRange = parseRange(old);
if (oldRange == null) return null;
const newRange = parseRange(next);
if (newRange == null) return null;
return [oldRange[0], oldRange[1], newRange[0], newRange[1]];
}
/** One `-start,count` / `+start,count` side of a hunk header. Pure. */
function parseRange(text) {
let trimmed = text.trim();
if (trimmed.startsWith("-")) trimmed = trimmed.slice(1);
else if (trimmed.startsWith("+")) trimmed = trimmed.slice(1);
if (trimmed === "") return null;
const comma = trimmed.indexOf(",");
const startText = (comma === -1 ? trimmed : trimmed.slice(0, comma)).trim();
const start = intOrNull(startText);
if (start == null) return null;
const countText = (comma === -1 ? "" : trimmed.slice(comma + 1)).trim();
const count = countText === "" ? 1 : intOrNull(countText);
if (count == null) return null;
return [start, count];
}
/** One body line of a hunk, tagged and numbered from `builder`'s counters. */
function parseBodyLine(line, builder) {
if (line.startsWith("+")) {
return { kind: ChangeLineKind.Add, text: line.slice(1), oldLine: 0, newLine: builder.nextNew(), noNewlineMarker: false };
}
if (line.startsWith("-")) {
return { kind: ChangeLineKind.Remove, text: line.slice(1), oldLine: builder.nextOld(), newLine: 0, noNewlineMarker: false };
}
if (line.startsWith("\\")) {
return { kind: ChangeLineKind.Context, text: line, oldLine: 0, newLine: 0, noNewlineMarker: true };
}
if (line.startsWith(" ")) {
return { kind: ChangeLineKind.Context, text: line.slice(1), oldLine: builder.nextOld(), newLine: builder.nextNew(), noNewlineMarker: false };
}
if (line === "") {
return { kind: ChangeLineKind.Context, text: "", oldLine: builder.nextOld(), newLine: builder.nextNew(), noNewlineMarker: false };
}
// A truncated tail or an unexpected marker: keep the text, don't number it.
return { kind: ChangeLineKind.Context, text: line, oldLine: 0, newLine: 0, noNewlineMarker: false };
}
/** The widest line number in a hunk, so its gutter lines up across every row. */
export function gutterWidth(hunk) {
let widest = 0;
for (const line of hunk?.lines ?? []) {
widest = Math.max(widest, Math.max(line.oldLine, line.newLine));
}
return String(Math.max(widest, 1)).length;
}
/** One gutter number padded to `width`; 0 means no number on that side. */
export function gutterText(value, width) {
return value > 0 ? String(value).padStart(width) : " ".repeat(width);
}
// ---------------------------------------------------------------------------
// Change aggregation (ui/changes/RunChanges.kt runChanges)
// ---------------------------------------------------------------------------
/**
* Aggregates a run's stage steps into its Changes state. Pure and total over its
* input: a null `file_changes` on a step is a historical (or non-capturing) step
* and contributes nothing (it is never "no changes"); a present capture with no
* files is a real, observed no-change. Files are keyed by path and keep
* first-seen order, so a path several steps changed is one entry naming all of
* them. Later steps win the kind unless they only say "other", added/removed
* line counts sum, binary/truncated are OR'd, before_mode is first-seen and
* after_mode last-seen.
*/
export function runChanges(steps) {
const entries = new Map();
let stepsWithChanges = 0;
let stepsPending = 0;
let partial = false;
let unavailable = false;
let missingCaptures = 0;
let skipped = 0;
let omitted = 0;
const diagnostics = new Set();
for (const step of steps ?? []) {
const changes = step?.file_changes;
if (changes == null) {
if (step?.status === "running" || step?.status === "waiting") stepsPending++;
else missingCaptures++;
continue;
}
stepsWithChanges++;
if (changes.status === "unavailable") unavailable = true;
if (changes.status === "partial") partial = true;
if (str(changes.diagnostic).trim() !== "") diagnostics.add(str(changes.diagnostic).trim());
skipped += Number(changes.skipped) || 0;
omitted += Number(changes.omitted) || 0;
const stageText = str(step?.stage);
const stage = stageText.trim() === "" ? "stage" : stageText;
for (const file of changes.files ?? []) {
const path = str(file?.path);
if (path.trim() === "") continue;
const kind = changeKind(file?.kind);
const parsed = parseUnifiedPatch(file?.patch);
const existing = entries.get(path);
const mergedSteps = existing ? [...existing.steps] : [];
if (!mergedSteps.includes(stage)) mergedSteps.push(stage);
const patchParts = [];
if (existing && existing.patch != null) patchParts.push(existing.patch);
if (typeof file?.patch === "string" && file.patch.trim() !== "") patchParts.push(file.patch);
const joinedPatch = patchParts.join("\n");
entries.set(path, {
path,
// A later step wins the kind: it is the observed state the run left.
kind: existing == null || kind !== ChangeKind.Other ? kind : existing.kind,
added: (existing?.added ?? 0) + parsed.added,
removed: (existing?.removed ?? 0) + parsed.removed,
binary: existing?.binary === true || file?.binary === true,
truncated: existing?.truncated === true || file?.truncated === true,
// Keep the first-seen before-mode and the last-seen after-mode, so the
// pair describes the run's net effect on the file.
beforeMode: existing && existing.beforeMode != null ? existing.beforeMode : nullable(file?.before_mode),
afterMode: file?.after_mode != null ? file.after_mode : existing?.afterMode ?? null,
otherModeChange:
existing?.otherModeChange === true ||
(file?.before_mode != null &&
file?.after_mode != null &&
file.before_mode !== file.after_mode &&
!file.binary &&
parsed.added === 0 &&
parsed.removed === 0),
steps: mergedSteps,
// Preserve every recorded textual patch for a path. A file may be
// changed by several stages, and retaining only the first one would
// make the displayed hunks disagree with the aggregate stat.
patch: joinedPatch.trim() !== "" ? joinedPatch : null,
});
}
}
const files = [...entries.values()];
const pending = stepsWithChanges === 0 && stepsPending > 0;
const totalPartial = partial || files.some((file) => file.truncated) || omitted > 0;
return {
files,
stepsWithChanges,
stepsPending,
added: files.reduce((sum, file) => sum + file.added, 0),
removed: files.reduce((sum, file) => sum + file.removed, 0),
partial: totalPartial,
unavailable,
pending,
missingCaptures,
skipped,
omitted,
diagnostic: [...diagnostics].join(" "),
};
}
// ---------------------------------------------------------------------------
// Entry helpers (FileChangeEntry derived properties)
// ---------------------------------------------------------------------------
/** True when a patch the operator can read is present. */
export function entryHasPatch(entry) {
return !!(entry && entry.patch != null && entry.patch.trim() !== "" && !entry.binary);
}
/** True when the recorded permissions differ and no content change explains it. */
export function entryModeChanged(entry) {
return !!(entry && entry.beforeMode != null && entry.afterMode != null && entry.beforeMode !== entry.afterMode);
}
/** The number of stages that changed this file. */
export function entryStepCount(entry) {
return (entry?.steps ?? []).length;
}
// ---------------------------------------------------------------------------
// Wording (ui/changes/RunChanges.kt + ChangeDiffViewer.kt)
// ---------------------------------------------------------------------------
/**
* The Changes section header's one-line summary: the observed file count, the
* total `+N -M`, and the honest capture caveats. Wording never implies the
* server proved authorship — it reports the workspace change it observed. A run
* with no recorded change, an unavailable capture and a still-running one each
* say exactly that rather than showing a fabricated zero.
*/
export function runChangesHeader(changes) {
if (changes.unavailable) return "Changes · capture unavailable";
if (changes.files.length === 0) {
if (changes.pending) return "Changes · capture pending";
if (changes.partial) return "Changes · partial capture";
if (changes.stepsWithChanges === 0) return "Changes · not recorded for this run";
if (changes.missingCaptures > 0) return "Changes · capture incomplete";
return "Changes · no changes observed";
}
const stat = changeStat(changes.added, changes.removed);
const count = changes.files.length;
const label =
stat === ""
? `${count} ${count === 1 ? "file" : "files"} changed`
: `${count} ${count === 1 ? "file" : "files"} changed · ${stat}`;
if (changes.partial) return `${label} · partial capture`;
if (changes.missingCaptures > 0) return `${label} · capture incomplete`;
return label;
}
/**
* The honest one-line note under the header for a capture that is not complete,
* or "" when the capture was. The wording distinguishes an unavailable capture, a
* partial one (with its counts) and a capture that has recorded nothing yet.
*/
export function runChangesNote(changes) {
if (changes.unavailable) {
return str(changes.diagnostic).trim() !== ""
? str(changes.diagnostic)
: "The workspace snapshot could not be compared; the changes below may be incomplete.";
}
let out = "";
if (changes.partial) {
out = "Partial capture: some changes may be missing.";
const caveats = [];
if (changes.skipped > 0) caveats.push(`${changes.skipped} files skipped`);
if (changes.omitted > 0) caveats.push(`${changes.omitted} omitted`);
const truncated = changes.files.filter((file) => file.truncated).length;
if (truncated > 0) caveats.push(`${truncated} truncated`);
if (caveats.length > 0) out += ` (${caveats.join(", ")})`;
if (str(changes.diagnostic).trim() !== "") out += ` ${str(changes.diagnostic)}`;
}
if (changes.missingCaptures > 0) {
if (out !== "") out += " ";
out += `Missing capture: ${changes.missingCaptures} `;
out += changes.missingCaptures === 1 ? "stage did" : "stages did";
out += " not record changes.";
}
return out.trim();
}
/** The `+N -M` stat, or "" when both counts are zero. Shared by header and row. */
export function changeStat(added, removed) {
let out = "";
if (added > 0) out += `+${added}`;
if (removed > 0) {
if (out !== "") out += " ";
out += `-${removed}`;
}
return out;
}
/**
* The tags shown beside a file row: the traits that change how the entry must be
* read (binary, truncated, a mode-only change), never a fabricated diff.
*/
export function changeEntryTags(entry) {
const tags = [];
if (entry?.binary) tags.push("binary");
if (entry?.truncated) tags.push("truncated");
if (entry?.otherModeChange && !entry.binary) tags.push("mode change");
return tags;
}
/** The row's secondary line: which stage(s) changed it, and how to read it. */
export function changeRowMeta(entry) {
let out = `changed by ${(entry?.steps ?? []).join(" → ")}`;
for (const tag of changeEntryTags(entry)) out += ` · ${tag}`;
if (entryModeChanged(entry) && !entry.binary) {
out += ` · mode ${entry.beforeMode ?? ""}→${entry.afterMode ?? ""}`;
}
return out;
}
/**
* The file list's own summary line: the observed file count and the aggregate
* stat, with the same ambiguity-free wording as the header.
*/
export function changesListSummary(changes) {
const count = `${changes.files.length} ${changes.files.length === 1 ? "file" : "files"} changed`;
const stat = changeStat(changes.added, changes.removed);
return stat === "" ? count : `${count} · ${stat}`;
}
/** Why no change is listed: a pending capture, an unavailable one, or a recorded none. */
export function noChangeDetail(changes) {
if (changes.pending) return "The capture runs after the stage finishes; nothing is recorded yet.";
if (changes.unavailable) return "The workspace snapshot could not be compared, so no changes can be shown.";
if (changes.stepsWithChanges === 0) {
return "This run recorded no change capture (a historical step, or a stage that does not capture).";
}
return "The captured snapshots were identical: the workspace was unchanged.";
}
/** Why a file has no patch to render, in the entry's own recorded terms. */
export function patchUnavailableReason(entry) {
if (entry?.truncated) {
return "The server truncated this file's patch at its capture limit; no diff text was recorded.";
}
if (entry?.otherModeChange) {
return `Only the file's mode changed (${entry.beforeMode ?? ""}→${entry.afterMode ?? ""}); the server recorded no text diff.`;
}
return "The server recorded this change without a patch.";
}
/** The `N of M` position label the viewer shows for its open file. Pure. */
export function changePositionLabel(index, count) {
return `${index + 1} of ${count}`;
}
// The viewer's honest messages, exported so the renderer and the tests share one
// spelling of each.
export const BINARY_DIFF_MESSAGE =
"This is a binary file: the server recorded the change but has no textual diff to show.";
export const TRUNCATED_PATCH_NOTE =
"The server truncated this patch at its capture limit; the raw text is the whole record.";
export const NO_LINE_CHANGES_MESSAGE = "no line changes recorded";
// ---------------------------------------------------------------------------
// Diff line language (ui/chat/ChatDiffCard.kt diffLineSymbol/diffLineColor)
// ---------------------------------------------------------------------------
/** The gutter symbol one line kind is drawn with (`+`/`-`/space). Pure. */
export function diffLineSymbol(kind) {
switch (kind) {
case ChangeLineKind.Add:
return "+";
case ChangeLineKind.Remove:
return "-";
default:
return " ";
}
}
/**
* The CSS class one line kind is drawn in: the app's success hue for an addition,
* its failure hue for a removal and the secondary on-surface role for context.
* The one place a diff line's class is decided, shared by every renderer.
*/
export function diffLineClass(kind) {
switch (kind) {
case ChangeLineKind.Add:
return "diff-add";
case ChangeLineKind.Remove:
return "diff-remove";
default:
return "diff-context";
}
}
// ---------------------------------------------------------------------------
// Internals
// ---------------------------------------------------------------------------
/** An integer parsed from a strictly-numeric string, or null. */
function intOrNull(text) {
return /^[+-]?\d+$/.test(text) ? Number.parseInt(text, 10) : null;
}
/** A value kept as itself when present, else null (`?:` over nullable fields). */
function nullable(value) {
return value == null ? null : value;
}
/** A nullable value as a string ("" for null/undefined), for blank checks. */
function str(value) {
return value == null ? "" : String(value);
}