merge(app): land recorded changes viewer with native-default corrections
This commit is contained in:
@@ -0,0 +1,17 @@
|
||||
/// Public API for the run Changes feature. Integration imports this barrel:
|
||||
///
|
||||
/// * [ChangesViewer] - the whole run, from `run detail['steps']`.
|
||||
/// * [FileDiffViewer] and [showFileDiffViewer] - one recorded file.
|
||||
/// * The pure domain models/parsers/wording for tests and other surfaces.
|
||||
library;
|
||||
|
||||
export 'domain/change_capture.dart';
|
||||
export 'domain/change_kind.dart';
|
||||
export 'domain/change_wording.dart';
|
||||
export 'domain/file_change.dart';
|
||||
export 'domain/run_changes.dart';
|
||||
export 'domain/unified_patch.dart';
|
||||
export 'widgets/change_style.dart' show DiffForm, usesCupertino;
|
||||
export 'widgets/changes_viewer.dart';
|
||||
export 'widgets/file_diff_viewer.dart';
|
||||
export 'widgets/patch_view.dart';
|
||||
@@ -0,0 +1,145 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'file_change.dart';
|
||||
|
||||
/// One step's recorded `file_changes` capture. A null capture on a
|
||||
/// [StageCapture] means the step recorded no capture at all - it must never be
|
||||
/// read as "the workspace was unchanged".
|
||||
class ChangeCapture {
|
||||
ChangeCapture({
|
||||
required this.status,
|
||||
this.scope = '',
|
||||
required this.files,
|
||||
this.skipped = 0,
|
||||
this.omitted = 0,
|
||||
this.diagnostic = '',
|
||||
});
|
||||
|
||||
final String status;
|
||||
final String scope;
|
||||
final List<FileChange> files;
|
||||
final int skipped;
|
||||
final int omitted;
|
||||
final String diagnostic;
|
||||
|
||||
String get _state => status.trim().toLowerCase();
|
||||
bool get unavailable => _state == 'unavailable';
|
||||
bool get partial => _state == 'partial';
|
||||
bool get complete => _state == 'complete' || _state.isEmpty;
|
||||
bool get hasFiles => files.isNotEmpty;
|
||||
|
||||
factory ChangeCapture.fromJson(JsonMap json) {
|
||||
final rawFiles = json['files'];
|
||||
final files = <FileChange>[];
|
||||
if (rawFiles is List) {
|
||||
for (final value in rawFiles) {
|
||||
final file = FileChange.tryParse(value);
|
||||
if (file != null) files.add(file);
|
||||
}
|
||||
}
|
||||
return ChangeCapture(
|
||||
status: '${json['status'] ?? ''}'.trim(),
|
||||
scope: '${json['scope'] ?? ''}'.trim(),
|
||||
files: List.unmodifiable(files),
|
||||
skipped: _count(json['skipped']),
|
||||
omitted: _count(json['omitted']),
|
||||
diagnostic: '${json['diagnostic'] ?? ''}'.trim(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The honest wording for a `file_changes` value that exists but is not an
|
||||
/// object. Such a record is unreadable evidence, not an observed no-change.
|
||||
const malformedCaptureDetail =
|
||||
'The recorded change capture could not be read, so no changes can be '
|
||||
'shown. This does not mean the workspace was unchanged.';
|
||||
|
||||
/// One stage visit and the capture it recorded, in run order. `capture == null`
|
||||
/// is missing evidence, not an observed no-change.
|
||||
class StageCapture {
|
||||
const StageCapture({
|
||||
required this.sequence,
|
||||
required this.visit,
|
||||
required this.stage,
|
||||
required this.stepStatus,
|
||||
required this.capture,
|
||||
});
|
||||
|
||||
/// The run-wide step ordinal, used for ordering and widget keys.
|
||||
final int sequence;
|
||||
|
||||
/// The display visit number within [stage]: the recorded `control.visit` when
|
||||
/// positive, otherwise the visit's 1-based position in its stage. Mirrors the
|
||||
/// web client's `displayVisit`; [sequence] is not the visit number.
|
||||
final int visit;
|
||||
final String stage;
|
||||
final String stepStatus;
|
||||
final ChangeCapture? capture;
|
||||
|
||||
bool get missing => capture == null;
|
||||
|
||||
/// Parses one step. [position] is the step's 1-based position among the
|
||||
/// steps of its own stage, used when the step recorded no `control.visit`.
|
||||
factory StageCapture.fromStep(JsonMap step, {int position = 1}) {
|
||||
final raw = step['file_changes'];
|
||||
return StageCapture(
|
||||
sequence: _count(step['sequence']),
|
||||
visit: _displayVisit(step, position),
|
||||
stage: _stageName(step),
|
||||
stepStatus: '${step['status'] ?? ''}'.trim(),
|
||||
// A non-null but malformed value still records that a capture existed;
|
||||
// only null is missing evidence. A value we cannot read is unavailable,
|
||||
// never a fabricated empty capture that would claim "no changes".
|
||||
capture: raw == null
|
||||
? null
|
||||
: raw is Map
|
||||
? ChangeCapture.fromJson(Map<String, dynamic>.from(raw))
|
||||
: ChangeCapture(
|
||||
status: 'unavailable',
|
||||
files: const [],
|
||||
diagnostic: malformedCaptureDetail,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Groups a run's steps into stage/visit captures ordered by numeric sequence,
|
||||
/// stable for ties. A step with a null `file_changes` still appears so its
|
||||
/// missing evidence is visible next to the captures that did record.
|
||||
List<StageCapture> stageCaptures(List<JsonMap> steps) {
|
||||
final indexed = <({JsonMap step, int index})>[];
|
||||
for (var i = 0; i < steps.length; i++) {
|
||||
indexed.add((step: steps[i], index: i));
|
||||
}
|
||||
indexed.sort((a, b) {
|
||||
final bySequence = _count(
|
||||
a.step['sequence'],
|
||||
).compareTo(_count(b.step['sequence']));
|
||||
return bySequence != 0 ? bySequence : a.index.compareTo(b.index);
|
||||
});
|
||||
// The visit position is per stage, in the same sequence order (the web
|
||||
// client's displayVisit), not the run-wide step ordinal.
|
||||
final positions = <String, int>{};
|
||||
final captures = <StageCapture>[];
|
||||
for (final entry in indexed) {
|
||||
final stage = _stageName(entry.step);
|
||||
final position = (positions[stage] ?? 0) + 1;
|
||||
positions[stage] = position;
|
||||
captures.add(StageCapture.fromStep(entry.step, position: position));
|
||||
}
|
||||
return captures;
|
||||
}
|
||||
|
||||
/// The recorded `control.visit` when positive, else the stage position.
|
||||
int _displayVisit(JsonMap step, int position) {
|
||||
final control = step['control'];
|
||||
final recorded = control is Map ? control['visit'] : null;
|
||||
if (recorded is num && recorded > 0) return recorded.toInt();
|
||||
return position < 1 ? 1 : position;
|
||||
}
|
||||
|
||||
String _stageName(JsonMap step) {
|
||||
final name = '${step['stage'] ?? ''}'.trim();
|
||||
return name.isEmpty ? 'stage' : name;
|
||||
}
|
||||
|
||||
int _count(dynamic value) => value is num ? value.toInt() : 0;
|
||||
@@ -0,0 +1,30 @@
|
||||
/// The three recorded file-change kinds plus a safe fallback for future server
|
||||
/// values. Ported from `web/src/changes.js` (and the Android client's
|
||||
/// `ui/changes/RunChanges.kt`) so the Flutter client says the same words.
|
||||
enum ChangeKind { added, modified, deleted, other }
|
||||
|
||||
/// Maps a server kind token to a [ChangeKind]. The token is trimmed and
|
||||
/// lowercased; an unknown or blank token stays [ChangeKind.other] rather than
|
||||
/// being guessed, so a future server value is shown read-only instead of
|
||||
/// mislabelled.
|
||||
ChangeKind changeKind(dynamic kind) =>
|
||||
switch ('${kind ?? ''}'.trim().toLowerCase()) {
|
||||
'added' => ChangeKind.added,
|
||||
'modified' => ChangeKind.modified,
|
||||
'deleted' => ChangeKind.deleted,
|
||||
_ => ChangeKind.other,
|
||||
};
|
||||
|
||||
/// The word a file's kind is named by in the list and the diff header.
|
||||
String changeKindLabel(ChangeKind kind) => switch (kind) {
|
||||
ChangeKind.added => 'added',
|
||||
ChangeKind.modified => 'modified',
|
||||
ChangeKind.deleted => 'deleted',
|
||||
ChangeKind.other => 'changed',
|
||||
};
|
||||
|
||||
/// The kind word as the viewer header shows it, first letter capitalised.
|
||||
String changeKindTitle(ChangeKind kind) {
|
||||
final label = changeKindLabel(kind);
|
||||
return label.isEmpty ? label : label[0].toUpperCase() + label.substring(1);
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
import 'change_capture.dart';
|
||||
import 'file_change.dart';
|
||||
import 'run_changes.dart';
|
||||
import 'unified_patch.dart';
|
||||
|
||||
/// The honest messages the viewer and its tests share. Spelled once, matching
|
||||
/// the web client's `web/src/changes.js`.
|
||||
const binaryDiffMessage =
|
||||
'This is a binary file: the server recorded the change but has no textual '
|
||||
'diff to show.';
|
||||
const truncatedPatchNote =
|
||||
'The server truncated this patch at its capture limit; the raw text is the '
|
||||
'whole record.';
|
||||
const noLineChangesMessage = 'no line changes recorded';
|
||||
|
||||
/// A step with no capture recorded no evidence; it does not prove the workspace
|
||||
/// was unchanged.
|
||||
const missingCaptureDetail =
|
||||
'This visit recorded no change capture (a historical step, or a stage that '
|
||||
'does not capture). That does not mean the workspace was unchanged.';
|
||||
const pendingCaptureDetail =
|
||||
'The capture runs after the stage finishes; nothing is recorded yet.';
|
||||
const unavailableCaptureDetail =
|
||||
'The workspace snapshot could not be compared, so no changes can be shown.';
|
||||
const emptyCaptureDetail =
|
||||
'The captured snapshots were identical: the workspace was unchanged.';
|
||||
const partialCaptureDetail = 'Partial capture: some changes may be missing.';
|
||||
|
||||
/// The Changes section header's one-line summary: the observed file count, the
|
||||
/// total `+N -M`, and the honest capture caveats.
|
||||
String runChangesHeader(RunChanges changes) {
|
||||
if (changes.unavailable) return 'Changes · capture unavailable';
|
||||
if (changes.files.isEmpty) {
|
||||
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';
|
||||
}
|
||||
final stat = changeStat(changes.added, changes.removed);
|
||||
final count = changes.files.length;
|
||||
final label = stat.isEmpty
|
||||
? '$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 it was.
|
||||
String runChangesNote(RunChanges changes) {
|
||||
if (changes.unavailable) {
|
||||
return changes.diagnostic.isNotEmpty
|
||||
? changes.diagnostic
|
||||
: 'The workspace snapshot could not be compared; the changes below may '
|
||||
'be incomplete.';
|
||||
}
|
||||
var out = '';
|
||||
if (changes.partial) {
|
||||
out = partialCaptureDetail;
|
||||
final caveats = <String>[];
|
||||
if (changes.skipped > 0) caveats.add('${changes.skipped} files skipped');
|
||||
if (changes.omitted > 0) caveats.add('${changes.omitted} omitted');
|
||||
final truncated = changes.files.where((file) => file.truncated).length;
|
||||
if (truncated > 0) caveats.add('$truncated truncated');
|
||||
if (caveats.isNotEmpty) out += ' (${caveats.join(', ')})';
|
||||
if (changes.diagnostic.isNotEmpty) out += ' ${changes.diagnostic}';
|
||||
}
|
||||
if (changes.missingCaptures > 0) {
|
||||
if (out.isNotEmpty) out += ' ';
|
||||
out +=
|
||||
'Missing capture: ${changes.missingCaptures} '
|
||||
'${changes.missingCaptures == 1 ? 'stage did' : 'stages did'} not '
|
||||
'record changes.';
|
||||
}
|
||||
return out.trim();
|
||||
}
|
||||
|
||||
/// The file list's own summary line.
|
||||
String changesListSummary(RunChanges changes) {
|
||||
final count =
|
||||
'${changes.files.length} '
|
||||
'${changes.files.length == 1 ? 'file' : 'files'} changed';
|
||||
final stat = changeStat(changes.added, changes.removed);
|
||||
return stat.isEmpty ? count : '$count · $stat';
|
||||
}
|
||||
|
||||
/// Why no change is listed: a pending capture, an unavailable one, a missing
|
||||
/// capture or a recorded none.
|
||||
String noChangeDetail(RunChanges changes) {
|
||||
if (changes.pending) return pendingCaptureDetail;
|
||||
if (changes.unavailable) return unavailableCaptureDetail;
|
||||
if (changes.stepsWithChanges == 0) {
|
||||
return 'This run recorded no change capture (a historical step, or a stage '
|
||||
'that does not capture).';
|
||||
}
|
||||
return emptyCaptureDetail;
|
||||
}
|
||||
|
||||
/// Why a file has no patch to render, in the entry's own recorded terms.
|
||||
String patchUnavailableReason(FileChange file) {
|
||||
if (file.truncated) {
|
||||
return "The server truncated this file's patch at its capture limit; no "
|
||||
'diff text was recorded.';
|
||||
}
|
||||
if (file.otherModeChange) {
|
||||
return "Only the file's mode changed (${file.beforeMode ?? ''}→"
|
||||
'${file.afterMode ?? ''}); the server recorded no text diff.';
|
||||
}
|
||||
return 'The server recorded this change without a patch.';
|
||||
}
|
||||
|
||||
/// The tags shown beside a file row: traits that change how the entry must be
|
||||
/// read, never a fabricated diff.
|
||||
List<String> changeEntryTags(FileChange file) => file.tags;
|
||||
|
||||
/// The row's secondary line for an aggregated entry: which stage(s) changed it
|
||||
/// and how to read it.
|
||||
String changeRowMeta(FileChange file) {
|
||||
var out = file.steps.isEmpty ? '' : 'changed by ${file.steps.join(' → ')}';
|
||||
for (final tag in changeEntryTags(file)) {
|
||||
out += '${out.isEmpty ? '' : ' · '}$tag';
|
||||
}
|
||||
if (file.modeChanged && !file.binary) {
|
||||
out +=
|
||||
'${out.isEmpty ? '' : ' · '}mode ${file.beforeMode ?? ''}→'
|
||||
'${file.afterMode ?? ''}';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/// A compact per-entry line for a file row: stat, tags and mode, or the honest
|
||||
/// no-line-change note. Content-driven; no fixed cell widths.
|
||||
String changeFileMeta(FileChange file) {
|
||||
final parts = <String>[];
|
||||
final stat = changeStat(file.added, file.removed);
|
||||
if (stat.isNotEmpty) parts.add(stat);
|
||||
parts.addAll(file.tags);
|
||||
if (file.modeChanged && !file.binary) {
|
||||
parts.add('mode ${file.beforeMode ?? ''}→${file.afterMode ?? ''}');
|
||||
}
|
||||
return parts.isEmpty ? noLineChangesMessage : parts.join(' · ');
|
||||
}
|
||||
|
||||
/// A compact capture summary, e.g.
|
||||
/// `partial (2 files), 1 skipped, 3 omitted · Excluded protected files.`.
|
||||
/// Blank parts are omitted; an entirely blank capture renders as "".
|
||||
String fileChangesSummary(ChangeCapture capture) {
|
||||
var text = capture.status;
|
||||
if (capture.files.isNotEmpty) {
|
||||
if (text.isNotEmpty) text += ' ';
|
||||
text += '(${capture.files.length} files)';
|
||||
}
|
||||
if (capture.skipped > 0) {
|
||||
if (text.isNotEmpty) text += ', ';
|
||||
text += '${capture.skipped} skipped';
|
||||
}
|
||||
if (capture.omitted > 0) {
|
||||
if (text.isNotEmpty) text += ', ';
|
||||
text += '${capture.omitted} omitted';
|
||||
}
|
||||
if (capture.diagnostic.isNotEmpty) {
|
||||
if (text.isNotEmpty) text += ' · ';
|
||||
text += capture.diagnostic;
|
||||
}
|
||||
return text;
|
||||
}
|
||||
|
||||
/// Filters changed filenames by a case-insensitive substring, preserving the
|
||||
/// recorded order. A blank query keeps every file.
|
||||
List<FileChange> filterFileChanges(Iterable<FileChange> files, String query) {
|
||||
final needle = query.trim().toLowerCase();
|
||||
final all = files.toList(growable: false);
|
||||
if (needle.isEmpty) return all;
|
||||
return all
|
||||
.where((file) => file.path.toLowerCase().contains(needle))
|
||||
.toList(growable: false);
|
||||
}
|
||||
|
||||
/// The `N of M` position label a viewer can show for its open file.
|
||||
String changePositionLabel(int index, int count) => '${index + 1} of $count';
|
||||
@@ -0,0 +1,117 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'change_kind.dart';
|
||||
import 'unified_patch.dart';
|
||||
|
||||
/// One recorded file change, as the server's `file_changes.files[]` entry
|
||||
/// describes it. A null/blank [patch] is a recorded fact (binary, truncated or
|
||||
/// no text diff), never an invented empty diff.
|
||||
class FileChange {
|
||||
FileChange({
|
||||
required this.path,
|
||||
required this.kind,
|
||||
String? patch,
|
||||
this.binary = false,
|
||||
this.truncated = false,
|
||||
String? beforeMode,
|
||||
String? afterMode,
|
||||
this.steps = const [],
|
||||
ParsedPatch? parsedPatch,
|
||||
}) : patch = _nonBlank(patch),
|
||||
beforeMode = _nonBlank(beforeMode),
|
||||
afterMode = _nonBlank(afterMode),
|
||||
// Aggregate copies pass their already-parsed patch through instead of
|
||||
// re-parsing the same recorded bytes for every stage that touched a path.
|
||||
parsedPatch = parsedPatch ?? parseUnifiedPatch(patch);
|
||||
|
||||
final String path;
|
||||
final ChangeKind kind;
|
||||
|
||||
/// The server's unified patch verbatim, or null when it recorded none. This
|
||||
/// exact string is what Copy patch puts on the clipboard, including any
|
||||
/// trailing newline or truncated final line.
|
||||
final String? patch;
|
||||
final bool binary;
|
||||
final bool truncated;
|
||||
final String? beforeMode;
|
||||
final String? afterMode;
|
||||
|
||||
/// Stage names that recorded a change to this path, in run order and deduped.
|
||||
/// Empty for a single recorded entry; filled by [runChanges] aggregation.
|
||||
final List<String> steps;
|
||||
|
||||
final ParsedPatch parsedPatch;
|
||||
|
||||
int get added => parsedPatch.added;
|
||||
int get removed => parsedPatch.removed;
|
||||
|
||||
/// True when a patch the operator can read is present.
|
||||
bool get hasPatch => !binary && patch != null;
|
||||
|
||||
/// True when the recorded permissions differ.
|
||||
bool get modeChanged =>
|
||||
beforeMode != null && afterMode != null && beforeMode != afterMode;
|
||||
|
||||
/// True when the recorded permissions differ and no content change explains
|
||||
/// it. The server records no text diff for a mode-only change.
|
||||
bool get otherModeChange =>
|
||||
modeChanged && !binary && added == 0 && removed == 0;
|
||||
|
||||
List<String> get tags => [
|
||||
if (binary) 'binary',
|
||||
if (truncated) 'truncated',
|
||||
if (otherModeChange) 'mode change',
|
||||
];
|
||||
|
||||
FileChange withSteps(List<String> value) => FileChange(
|
||||
path: path,
|
||||
kind: kind,
|
||||
patch: patch,
|
||||
binary: binary,
|
||||
truncated: truncated,
|
||||
beforeMode: beforeMode,
|
||||
afterMode: afterMode,
|
||||
steps: List.unmodifiable(value),
|
||||
parsedPatch: parsedPatch,
|
||||
);
|
||||
|
||||
/// Parses one server file entry; null when it has no usable path. The
|
||||
/// capture owns the decision to skip such an entry, so it is never rendered
|
||||
/// as an anonymous row.
|
||||
static FileChange? tryParse(dynamic value) {
|
||||
if (value is! Map) return null;
|
||||
final json = Map<String, dynamic>.from(value);
|
||||
final path = _text(json['path']);
|
||||
if (path.trim().isEmpty) return null;
|
||||
return FileChange(
|
||||
path: path,
|
||||
kind: changeKind(json['kind']),
|
||||
patch: json['patch'] is String ? json['patch'] as String : null,
|
||||
binary: json['binary'] == true,
|
||||
truncated: json['truncated'] == true,
|
||||
beforeMode: _textOrNull(json['before_mode']),
|
||||
afterMode: _textOrNull(json['after_mode']),
|
||||
);
|
||||
}
|
||||
|
||||
/// Parses a required file entry. Integration code normally receives files
|
||||
/// from [ChangeCapture] or [runChanges]; this constructor is for a viewer
|
||||
/// opened directly with one recorded entry.
|
||||
factory FileChange.fromJson(JsonMap json) {
|
||||
final file = tryParse(json);
|
||||
if (file == null) {
|
||||
throw const FormatException('A recorded file change needs a path.');
|
||||
}
|
||||
return file;
|
||||
}
|
||||
}
|
||||
|
||||
/// A value kept as itself when present, else null (`?:` over nullable fields).
|
||||
String? _textOrNull(dynamic value) => value == null ? null : '$value';
|
||||
|
||||
String _text(dynamic value) => '${value ?? ''}';
|
||||
|
||||
/// A string kept only when it has non-whitespace content.
|
||||
String? _nonBlank(String? value) {
|
||||
if (value == null) return null;
|
||||
return value.trim().isEmpty ? null : value;
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/// Patch value objects produced by the unified-patch parser. Kept separate from
|
||||
/// the parser so widgets import the smallest model they need.
|
||||
library;
|
||||
|
||||
enum ChangeLineKind { context, add, remove }
|
||||
|
||||
class PatchLine {
|
||||
const PatchLine({
|
||||
required this.kind,
|
||||
required this.text,
|
||||
required this.oldLine,
|
||||
required this.newLine,
|
||||
this.noNewlineMarker = false,
|
||||
});
|
||||
|
||||
final ChangeLineKind kind;
|
||||
final String text;
|
||||
final int oldLine;
|
||||
final int newLine;
|
||||
|
||||
/// A `\ No newline at end of file` marker: shown verbatim, never numbered.
|
||||
final bool noNewlineMarker;
|
||||
}
|
||||
|
||||
class PatchHunk {
|
||||
const PatchHunk({
|
||||
required this.header,
|
||||
required this.oldStart,
|
||||
required this.oldCount,
|
||||
required this.newStart,
|
||||
required this.newCount,
|
||||
required this.lines,
|
||||
});
|
||||
|
||||
final String header;
|
||||
final int oldStart;
|
||||
final int oldCount;
|
||||
final int newStart;
|
||||
final int newCount;
|
||||
final List<PatchLine> lines;
|
||||
}
|
||||
|
||||
class ParsedPatch {
|
||||
const ParsedPatch({
|
||||
required this.raw,
|
||||
required this.headerLines,
|
||||
required this.hunks,
|
||||
required this.added,
|
||||
required this.removed,
|
||||
});
|
||||
|
||||
final String raw;
|
||||
final List<String> headerLines;
|
||||
final List<PatchHunk> hunks;
|
||||
final int added;
|
||||
final int removed;
|
||||
|
||||
bool get isEmpty => hunks.isEmpty;
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'change_capture.dart';
|
||||
import 'file_change.dart';
|
||||
|
||||
/// The run-level final-state aggregate of recorded file captures. Ported from
|
||||
/// `web/src/changes.js` `runChanges`:
|
||||
///
|
||||
/// * a null `file_changes` is missing evidence (pending while the step is
|
||||
/// running/waiting), never "no changes";
|
||||
/// * a present capture with no files is a real, observed no-change;
|
||||
/// * a path recorded by several visits is one entry, in first-seen order, whose
|
||||
/// per-file facts come from the last recorded visit (the run's final state);
|
||||
/// * capture counters and caveats describe every contributing step.
|
||||
class RunChanges {
|
||||
const RunChanges({
|
||||
required this.files,
|
||||
required this.stepsWithChanges,
|
||||
required this.stepsPending,
|
||||
required this.added,
|
||||
required this.removed,
|
||||
required this.partial,
|
||||
required this.unavailable,
|
||||
required this.pending,
|
||||
required this.missingCaptures,
|
||||
required this.skipped,
|
||||
required this.omitted,
|
||||
required this.diagnostic,
|
||||
});
|
||||
|
||||
final List<FileChange> files;
|
||||
final int stepsWithChanges;
|
||||
final int stepsPending;
|
||||
final int added;
|
||||
final int removed;
|
||||
final bool partial;
|
||||
final bool unavailable;
|
||||
final bool pending;
|
||||
final int missingCaptures;
|
||||
final int skipped;
|
||||
final int omitted;
|
||||
final String diagnostic;
|
||||
}
|
||||
|
||||
RunChanges runChanges(List<JsonMap> steps) =>
|
||||
runChangesFor(stageCaptures(steps));
|
||||
|
||||
/// The same aggregate over already-derived [stageCaptures], so a caller that
|
||||
/// shows both the summary and the sections parses each capture only once.
|
||||
RunChanges runChangesFor(List<StageCapture> visits) {
|
||||
final entries = <String, FileChange>{};
|
||||
var stepsWithChanges = 0;
|
||||
var stepsPending = 0;
|
||||
var partial = false;
|
||||
var unavailable = false;
|
||||
var missingCaptures = 0;
|
||||
var skipped = 0;
|
||||
var omitted = 0;
|
||||
var truncatedSeen = false;
|
||||
final diagnostics = <String>{};
|
||||
|
||||
for (final visit in visits) {
|
||||
final capture = visit.capture;
|
||||
if (capture == null) {
|
||||
final status = visit.stepStatus.trim().toLowerCase();
|
||||
if (status == 'running' || status == 'waiting') {
|
||||
stepsPending++;
|
||||
} else {
|
||||
missingCaptures++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
stepsWithChanges++;
|
||||
if (capture.unavailable) unavailable = true;
|
||||
if (capture.partial) partial = true;
|
||||
if (capture.diagnostic.isNotEmpty) diagnostics.add(capture.diagnostic);
|
||||
skipped += capture.skipped;
|
||||
omitted += capture.omitted;
|
||||
for (final file in capture.files) {
|
||||
if (file.truncated) truncatedSeen = true;
|
||||
final existing = entries[file.path];
|
||||
final names = existing == null ? <String>[] : [...existing.steps];
|
||||
if (!names.contains(visit.stage)) names.add(visit.stage);
|
||||
entries[file.path] = file.withSteps(names);
|
||||
}
|
||||
}
|
||||
|
||||
final files = entries.values.toList(growable: false);
|
||||
return RunChanges(
|
||||
files: List.unmodifiable(files),
|
||||
stepsWithChanges: stepsWithChanges,
|
||||
stepsPending: stepsPending,
|
||||
added: files.fold(0, (sum, file) => sum + file.added),
|
||||
removed: files.fold(0, (sum, file) => sum + file.removed),
|
||||
partial: partial || truncatedSeen || omitted > 0,
|
||||
unavailable: unavailable,
|
||||
pending: stepsWithChanges == 0 && stepsPending > 0,
|
||||
missingCaptures: missingCaptures,
|
||||
skipped: skipped,
|
||||
omitted: omitted,
|
||||
diagnostic: diagnostics.join(' '),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
/// Parses a server-recorded unified patch into hunks, lines and the true
|
||||
/// `+N -M` stat. Ported from `web/src/changes.js` so the Flutter viewer numbers
|
||||
/// and groups lines exactly like the browser and Android clients.
|
||||
///
|
||||
/// The server builds these patches with the Go `internal/filediff` writer: a
|
||||
/// standard `---`/`+++` header, optional metadata, `@@ -a,b +c,d @@` hunk
|
||||
/// headers and a ` `/`+`/`-` body. Anything unrecognised before the first hunk
|
||||
/// is carried verbatim in [ParsedPatch.headerLines]; a truncated tail or exotic
|
||||
/// marker inside a hunk stays an unnumbered context line. The raw patch is
|
||||
/// always retained byte-for-byte so Copy patch never rewrites the record.
|
||||
library;
|
||||
|
||||
export 'patch_models.dart';
|
||||
|
||||
import 'patch_models.dart';
|
||||
|
||||
const _emptyPatch = ParsedPatch(
|
||||
raw: '',
|
||||
headerLines: [],
|
||||
hunks: [],
|
||||
added: 0,
|
||||
removed: 0,
|
||||
);
|
||||
|
||||
/// Parses a patch with the same total behaviour as the browser: a blank or
|
||||
/// absent patch is an empty result, never a fabricated diff.
|
||||
ParsedPatch parseUnifiedPatch(dynamic patch) {
|
||||
final text = patch == null ? '' : '$patch';
|
||||
if (text.trim().isEmpty) return _emptyPatch;
|
||||
|
||||
final headers = <String>[];
|
||||
final hunks = <PatchHunk>[];
|
||||
_HunkBuilder? current;
|
||||
|
||||
for (final line in text.split('\n')) {
|
||||
final start = _parseHunkHeader(line);
|
||||
if (start != null) {
|
||||
if (current != null) hunks.add(current.build());
|
||||
current = _HunkBuilder(line, start);
|
||||
} else if (line.startsWith('--- ') || line.startsWith('+++ ')) {
|
||||
// An aggregated entry can contain one complete patch per contributing
|
||||
// stage. A new file header closes the preceding hunk instead of becoming
|
||||
// an unnumbered context line inside it.
|
||||
if (current != null) {
|
||||
hunks.add(current.build());
|
||||
current = null;
|
||||
}
|
||||
headers.add(line);
|
||||
} else if (current == null) {
|
||||
headers.add(line);
|
||||
} else {
|
||||
current.lines.add(current.parseBody(line));
|
||||
}
|
||||
}
|
||||
if (current != null) hunks.add(current.build());
|
||||
|
||||
var added = 0;
|
||||
var removed = 0;
|
||||
for (final hunk in hunks) {
|
||||
for (final line in hunk.lines) {
|
||||
if (line.kind == ChangeLineKind.add) {
|
||||
added++;
|
||||
} else if (line.kind == ChangeLineKind.remove) {
|
||||
removed++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return ParsedPatch(
|
||||
raw: text,
|
||||
headerLines: headers,
|
||||
hunks: hunks,
|
||||
added: added,
|
||||
removed: removed,
|
||||
);
|
||||
}
|
||||
|
||||
/// Mutable accumulator carrying the running old/new counters so each body line
|
||||
/// is numbered in one pass.
|
||||
class _HunkBuilder {
|
||||
_HunkBuilder(this.header, _HunkStart start)
|
||||
: oldStart = start.oldStart,
|
||||
oldCount = start.oldCount,
|
||||
newStart = start.newStart,
|
||||
newCount = start.newCount,
|
||||
oldLine = start.oldStart,
|
||||
newLine = start.newStart;
|
||||
|
||||
final String header;
|
||||
final int oldStart;
|
||||
final int oldCount;
|
||||
final int newStart;
|
||||
final int newCount;
|
||||
final List<PatchLine> lines = [];
|
||||
int oldLine;
|
||||
int newLine;
|
||||
|
||||
PatchHunk build() => PatchHunk(
|
||||
header: header,
|
||||
oldStart: oldStart,
|
||||
oldCount: oldCount,
|
||||
newStart: newStart,
|
||||
newCount: newCount,
|
||||
lines: List.unmodifiable(lines),
|
||||
);
|
||||
|
||||
PatchLine parseBody(String line) {
|
||||
if (line.startsWith('+')) {
|
||||
return PatchLine(
|
||||
kind: ChangeLineKind.add,
|
||||
text: line.substring(1),
|
||||
oldLine: 0,
|
||||
newLine: newLine++,
|
||||
);
|
||||
}
|
||||
if (line.startsWith('-')) {
|
||||
return PatchLine(
|
||||
kind: ChangeLineKind.remove,
|
||||
text: line.substring(1),
|
||||
oldLine: oldLine++,
|
||||
newLine: 0,
|
||||
);
|
||||
}
|
||||
if (line.startsWith('\\')) {
|
||||
return PatchLine(
|
||||
kind: ChangeLineKind.context,
|
||||
text: line,
|
||||
oldLine: 0,
|
||||
newLine: 0,
|
||||
noNewlineMarker: true,
|
||||
);
|
||||
}
|
||||
if (line.startsWith(' ')) {
|
||||
return PatchLine(
|
||||
kind: ChangeLineKind.context,
|
||||
text: line.substring(1),
|
||||
oldLine: oldLine++,
|
||||
newLine: newLine++,
|
||||
);
|
||||
}
|
||||
if (line.isEmpty) {
|
||||
return PatchLine(
|
||||
kind: ChangeLineKind.context,
|
||||
text: '',
|
||||
oldLine: oldLine++,
|
||||
newLine: newLine++,
|
||||
);
|
||||
}
|
||||
// A truncated tail or an unexpected marker: keep the text, do not number it.
|
||||
return PatchLine(
|
||||
kind: ChangeLineKind.context,
|
||||
text: line,
|
||||
oldLine: 0,
|
||||
newLine: 0,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _HunkStart {
|
||||
const _HunkStart(this.oldStart, this.oldCount, this.newStart, this.newCount);
|
||||
|
||||
final int oldStart;
|
||||
final int oldCount;
|
||||
final int newStart;
|
||||
final int newCount;
|
||||
}
|
||||
|
||||
_HunkStart? _parseHunkHeader(String line) {
|
||||
if (!line.startsWith('@@')) return null;
|
||||
final end = line.indexOf('@@', 2);
|
||||
if (end < 0) return null;
|
||||
final ranges = _tokenizeRanges(line.substring(2, end));
|
||||
return ranges == null
|
||||
? null
|
||||
: _HunkStart(ranges[0], ranges[1], ranges[2], ranges[3]);
|
||||
}
|
||||
|
||||
List<int>? _tokenizeRanges(String body) {
|
||||
final plus = body.indexOf('+');
|
||||
final old = plus == -1 ? body : body.substring(0, plus);
|
||||
final next = plus == -1 ? '' : body.substring(plus + 1);
|
||||
if (old.isEmpty || next.isEmpty) return null;
|
||||
final oldRange = _parseRange(old);
|
||||
if (oldRange == null) return null;
|
||||
final newRange = _parseRange(next);
|
||||
if (newRange == null) return null;
|
||||
return [oldRange[0], oldRange[1], newRange[0], newRange[1]];
|
||||
}
|
||||
|
||||
List<int>? _parseRange(String text) {
|
||||
var trimmed = text.trim();
|
||||
if (trimmed.startsWith('-') || trimmed.startsWith('+')) {
|
||||
trimmed = trimmed.substring(1);
|
||||
}
|
||||
if (trimmed.isEmpty) return null;
|
||||
final comma = trimmed.indexOf(',');
|
||||
final startText = (comma == -1 ? trimmed : trimmed.substring(0, comma))
|
||||
.trim();
|
||||
final start = _intOrNull(startText);
|
||||
if (start == null) return null;
|
||||
final countText = (comma == -1 ? '' : trimmed.substring(comma + 1)).trim();
|
||||
final count = countText.isEmpty ? 1 : _intOrNull(countText);
|
||||
if (count == null) return null;
|
||||
return [start, count];
|
||||
}
|
||||
|
||||
int? _intOrNull(String text) =>
|
||||
RegExp(r'^[+-]?\d+$').hasMatch(text) ? int.tryParse(text) : null;
|
||||
|
||||
/// The widest line number in a hunk, so its gutter lines up across every row.
|
||||
int gutterWidth(PatchHunk hunk) {
|
||||
var widest = 0;
|
||||
for (final line in hunk.lines) {
|
||||
if (line.oldLine > widest) widest = line.oldLine;
|
||||
if (line.newLine > widest) widest = line.newLine;
|
||||
}
|
||||
return '${widest < 1 ? 1 : widest}'.length;
|
||||
}
|
||||
|
||||
/// One gutter number padded to [width]; 0 means no number on that side.
|
||||
String gutterText(int value, int width) =>
|
||||
value > 0 ? '$value'.padLeft(width) : ' ' * width;
|
||||
|
||||
/// The gutter symbol one line kind is drawn with (`+`/`-`/space).
|
||||
String diffLineSymbol(ChangeLineKind kind) => switch (kind) {
|
||||
ChangeLineKind.add => '+',
|
||||
ChangeLineKind.remove => '-',
|
||||
ChangeLineKind.context => ' ',
|
||||
};
|
||||
|
||||
/// The `+N -M` stat, or "" when both counts are zero. Shared by every renderer.
|
||||
String changeStat(int added, int removed) {
|
||||
var out = '';
|
||||
if (added > 0) out += '+$added';
|
||||
if (removed > 0) {
|
||||
if (out.isNotEmpty) out += ' ';
|
||||
out += '-$removed';
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../domain/change_capture.dart';
|
||||
import '../domain/change_kind.dart';
|
||||
import '../domain/change_wording.dart';
|
||||
import '../domain/file_change.dart';
|
||||
import 'change_style.dart';
|
||||
|
||||
/// One stage/visit capture: its honest status, scope, counters and diagnostic,
|
||||
/// followed by the recorded file rows. Missing and unavailable captures are
|
||||
/// shown as evidence gaps, never as an observed no-change.
|
||||
class StageCaptureSection extends StatelessWidget {
|
||||
const StageCaptureSection({
|
||||
super.key,
|
||||
required this.stage,
|
||||
required this.query,
|
||||
required this.onOpen,
|
||||
});
|
||||
|
||||
final StageCapture stage;
|
||||
final String query;
|
||||
final ValueChanged<FileChange> onOpen;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final capture = stage.capture;
|
||||
final filtered = capture == null
|
||||
? const <FileChange>[]
|
||||
: filterFileChanges(capture.files, query);
|
||||
// The aggregate trims and lowercases the status before testing it; do the
|
||||
// same here so the section and the run header always agree.
|
||||
final status = stage.stepStatus.trim().toLowerCase();
|
||||
final pending =
|
||||
capture == null && (status == 'running' || status == 'waiting');
|
||||
final meta = [
|
||||
'Visit ${stage.visit}',
|
||||
if (stage.stepStatus.isNotEmpty) stage.stepStatus,
|
||||
].join(' · ');
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(stage.stage, style: Theme.of(context).textTheme.titleMedium),
|
||||
Text(meta, style: Theme.of(context).textTheme.bodySmall),
|
||||
if (capture != null) ...[
|
||||
Text(
|
||||
fileChangesSummary(capture),
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
if (capture.scope.isNotEmpty)
|
||||
Text(
|
||||
'Scope: ${capture.scope}',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
const Divider(height: 1),
|
||||
if (capture == null)
|
||||
_CaptureNote(
|
||||
icon: _noteIcon(
|
||||
context,
|
||||
pending ? _NoteKind.pending : _NoteKind.missing,
|
||||
),
|
||||
title: pending ? 'Capture pending' : 'Capture unavailable',
|
||||
detail: pending ? pendingCaptureDetail : missingCaptureDetail,
|
||||
)
|
||||
else if (capture.unavailable)
|
||||
_CaptureNote(
|
||||
icon: _noteIcon(context, _NoteKind.unavailable),
|
||||
title: 'Capture unavailable',
|
||||
detail: capture.diagnostic.isEmpty
|
||||
? unavailableCaptureDetail
|
||||
: capture.diagnostic,
|
||||
)
|
||||
else if (capture.files.isEmpty)
|
||||
_CaptureNote(
|
||||
icon: _noteIcon(
|
||||
context,
|
||||
capture.partial ? _NoteKind.partial : _NoteKind.empty,
|
||||
),
|
||||
title: capture.partial ? 'Partial capture' : 'No changes observed',
|
||||
detail: capture.partial ? partialCaptureDetail : emptyCaptureDetail,
|
||||
)
|
||||
else if (filtered.isEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 16),
|
||||
child: Text('No changed filenames match "$query".'),
|
||||
)
|
||||
else
|
||||
for (final file in filtered)
|
||||
_FileRow(
|
||||
key: ValueKey('change-${stage.sequence}-${file.path}'),
|
||||
file: file,
|
||||
onOpen: onOpen,
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _FileRow extends StatelessWidget {
|
||||
const _FileRow({super.key, required this.file, required this.onOpen});
|
||||
|
||||
final FileChange file;
|
||||
final ValueChanged<FileChange> onOpen;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final mono = nativeDiffText(DefaultTextStyle.of(context).style);
|
||||
final cupertino = usesCupertino(context);
|
||||
final leading = Icon(_kindIcon(context, file.kind));
|
||||
final title = Text(file.path, style: mono);
|
||||
final subtitle = Text(changeFileMeta(file));
|
||||
final trailing = cupertino
|
||||
? const CupertinoListTileChevron()
|
||||
: const Icon(Icons.chevron_right);
|
||||
return Semantics(
|
||||
container: true,
|
||||
button: true,
|
||||
// Announce the visible kind and meta too; the row's icon and subtitle are
|
||||
// excluded from the semantic tree by [excludeSemantics].
|
||||
label:
|
||||
'Open diff for ${file.path}. '
|
||||
'${changeKindTitle(file.kind)} · ${changeFileMeta(file)}',
|
||||
excludeSemantics: true,
|
||||
onTap: () => onOpen(file),
|
||||
child: cupertino
|
||||
? CupertinoListTile(
|
||||
leading: leading,
|
||||
// A recorded path is the row's identity, so it wraps instead of
|
||||
// being ellipsized to one line.
|
||||
title: _unclampedText(title),
|
||||
subtitle: _unclampedText(subtitle),
|
||||
trailing: trailing,
|
||||
onTap: () => onOpen(file),
|
||||
)
|
||||
: ListTile(
|
||||
leading: leading,
|
||||
title: title,
|
||||
subtitle: subtitle,
|
||||
trailing: trailing,
|
||||
onTap: () => onOpen(file),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// CupertinoListTile caps its title and subtitle at one ellipsized line through
|
||||
/// the inherited [DefaultTextStyle]. Re-establish the ambient style without that
|
||||
/// cap so a long recorded path stays readable; the tile keeps its native
|
||||
/// padding, pressed state and chevron.
|
||||
Widget _unclampedText(Widget child) {
|
||||
return Builder(
|
||||
builder: (context) {
|
||||
final inherited = DefaultTextStyle.of(context);
|
||||
return DefaultTextStyle(
|
||||
style: inherited.style,
|
||||
softWrap: true,
|
||||
overflow: TextOverflow.visible,
|
||||
textAlign: inherited.textAlign,
|
||||
textWidthBasis: inherited.textWidthBasis,
|
||||
textHeightBehavior: inherited.textHeightBehavior,
|
||||
child: child,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
class _CaptureNote extends StatelessWidget {
|
||||
const _CaptureNote({
|
||||
required this.icon,
|
||||
required this.title,
|
||||
required this.detail,
|
||||
});
|
||||
|
||||
final IconData icon;
|
||||
final String title;
|
||||
final String detail;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 16, 16),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Icon(icon),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(title, style: Theme.of(context).textTheme.titleSmall),
|
||||
const SizedBox(height: 4),
|
||||
Text(detail),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
enum _NoteKind { missing, unavailable, empty, partial, pending }
|
||||
|
||||
IconData _noteIcon(BuildContext context, _NoteKind kind) {
|
||||
final cupertino = usesCupertino(context);
|
||||
return switch (kind) {
|
||||
_NoteKind.missing || _NoteKind.unavailable =>
|
||||
cupertino ? CupertinoIcons.exclamationmark_triangle : Icons.warning_amber,
|
||||
_NoteKind.empty =>
|
||||
cupertino ? CupertinoIcons.checkmark_circle : Icons.check_circle_outline,
|
||||
_NoteKind.partial => cupertino ? CupertinoIcons.info : Icons.info_outline,
|
||||
_NoteKind.pending => cupertino ? CupertinoIcons.clock : Icons.schedule,
|
||||
};
|
||||
}
|
||||
|
||||
IconData _kindIcon(BuildContext context, ChangeKind kind) {
|
||||
final cupertino = usesCupertino(context);
|
||||
return switch (kind) {
|
||||
ChangeKind.added =>
|
||||
cupertino ? CupertinoIcons.add_circled : Icons.add_circle_outline,
|
||||
ChangeKind.deleted =>
|
||||
cupertino ? CupertinoIcons.trash : Icons.delete_outline,
|
||||
ChangeKind.modified =>
|
||||
cupertino ? CupertinoIcons.pencil : Icons.edit_outlined,
|
||||
ChangeKind.other =>
|
||||
cupertino ? CupertinoIcons.doc : Icons.description_outlined,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../domain/unified_patch.dart';
|
||||
|
||||
/// Which form of a recorded patch the viewer is showing.
|
||||
enum DiffForm { rendered, raw }
|
||||
|
||||
/// The app's established platform switch: Material for Android/desktop/web,
|
||||
/// Cupertino for iOS and macOS. Feature widgets stay portable across all three
|
||||
/// targets instead of hard-coding one control set.
|
||||
bool usesCupertino(BuildContext context) {
|
||||
final platform = Theme.of(context).platform;
|
||||
return platform == TargetPlatform.iOS || platform == TargetPlatform.macOS;
|
||||
}
|
||||
|
||||
/// Patch text inherits the host's typography, including its font and scaler.
|
||||
/// A diff is not an exception to the native-defaults requirement.
|
||||
TextStyle nativeDiffText(TextStyle base) => base;
|
||||
|
||||
/// Native semantic colours, never a bespoke diff palette. The recorded +/-
|
||||
/// markers carry meaning independently of colour. No background tint is added.
|
||||
({Color text, Color? background}) diffLineColors(
|
||||
BuildContext context,
|
||||
ChangeLineKind kind,
|
||||
) {
|
||||
return switch (kind) {
|
||||
ChangeLineKind.add => (
|
||||
text: usesCupertino(context)
|
||||
? CupertinoColors.systemGreen.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.primary,
|
||||
background: null,
|
||||
),
|
||||
ChangeLineKind.remove => (
|
||||
text: usesCupertino(context)
|
||||
? CupertinoColors.destructiveRed.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.error,
|
||||
background: null,
|
||||
),
|
||||
ChangeLineKind.context => (text: labelColor(context), background: null),
|
||||
};
|
||||
}
|
||||
|
||||
/// The plain body/label colour for non-diff text inside the viewer.
|
||||
Color labelColor(BuildContext context) => usesCupertino(context)
|
||||
? CupertinoColors.label.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.onSurface;
|
||||
|
||||
/// The muted colour for gutters, notes and secondary metadata.
|
||||
Color mutedColor(BuildContext context) => usesCupertino(context)
|
||||
? CupertinoColors.secondaryLabel.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.onSurfaceVariant;
|
||||
|
||||
/// The hunk header's fill.
|
||||
Color hunkHeaderColor(BuildContext context) => usesCupertino(context)
|
||||
? CupertinoColors.tertiarySystemFill.resolveFrom(context)
|
||||
: Theme.of(context).colorScheme.surfaceContainerHighest;
|
||||
|
||||
/// The viewer's shared Rendered/Raw control: a native segmented control on each
|
||||
/// platform, with the same two words the browser uses.
|
||||
Widget diffFormControl(
|
||||
BuildContext context, {
|
||||
required DiffForm form,
|
||||
required ValueChanged<DiffForm> onChanged,
|
||||
}) {
|
||||
if (usesCupertino(context)) {
|
||||
return CupertinoSlidingSegmentedControl<DiffForm>(
|
||||
groupValue: form,
|
||||
onValueChanged: (value) {
|
||||
if (value != null) onChanged(value);
|
||||
},
|
||||
children: const {
|
||||
DiffForm.rendered: _SegmentLabel('Rendered'),
|
||||
DiffForm.raw: _SegmentLabel('Raw patch'),
|
||||
},
|
||||
);
|
||||
}
|
||||
return SegmentedButton<DiffForm>(
|
||||
segments: const [
|
||||
ButtonSegment(value: DiffForm.rendered, label: Text('Rendered')),
|
||||
ButtonSegment(value: DiffForm.raw, label: Text('Raw patch')),
|
||||
],
|
||||
selected: {form},
|
||||
showSelectedIcon: false,
|
||||
onSelectionChanged: (selection) {
|
||||
if (selection.isNotEmpty) onChanged(selection.first);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
class _SegmentLabel extends StatelessWidget {
|
||||
const _SegmentLabel(this.label);
|
||||
|
||||
final String label;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) =>
|
||||
Padding(padding: const EdgeInsets.all(6), child: Text(label));
|
||||
}
|
||||
|
||||
/// Copy the server's raw patch exactly as recorded. Disabled when the entry has
|
||||
/// no readable patch, so the action never copies a fabricated empty diff.
|
||||
Widget copyPatchControl(
|
||||
BuildContext context, {
|
||||
required bool enabled,
|
||||
required bool copied,
|
||||
required VoidCallback onPressed,
|
||||
}) {
|
||||
final label = copied ? 'Copied' : 'Copy patch';
|
||||
if (usesCupertino(context)) {
|
||||
return CupertinoButton(
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: enabled ? onPressed : null,
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Icon(CupertinoIcons.doc_on_doc),
|
||||
const SizedBox(width: 8),
|
||||
Text(label),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
return TextButton.icon(
|
||||
onPressed: enabled ? onPressed : null,
|
||||
icon: const Icon(Icons.copy_all_outlined),
|
||||
label: Text(label),
|
||||
);
|
||||
}
|
||||
|
||||
/// The standard close action, labelled exactly on both platforms.
|
||||
Widget closeDiffControl(BuildContext context, VoidCallback onClose) {
|
||||
if (usesCupertino(context)) {
|
||||
return Semantics(
|
||||
label: 'Close diff',
|
||||
button: true,
|
||||
excludeSemantics: true,
|
||||
onTap: onClose,
|
||||
child: CupertinoButton(
|
||||
padding: EdgeInsets.zero,
|
||||
onPressed: onClose,
|
||||
child: const Icon(CupertinoIcons.xmark),
|
||||
),
|
||||
);
|
||||
}
|
||||
return IconButton(
|
||||
tooltip: 'Close diff',
|
||||
onPressed: onClose,
|
||||
icon: const Icon(Icons.close),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../domain/change_capture.dart';
|
||||
import '../domain/change_wording.dart';
|
||||
import '../domain/run_changes.dart';
|
||||
import 'capture_section.dart';
|
||||
import 'change_style.dart';
|
||||
import 'file_diff_viewer.dart';
|
||||
|
||||
/// The run's Changes surface: an honest final-state summary followed by one
|
||||
/// section per stage/visit capture, with changed-filename filtering and the
|
||||
/// reusable single-file diff viewer.
|
||||
///
|
||||
/// The viewer fills the available height, so give it a bounded parent (a
|
||||
/// Scaffold body, tab body or Expanded child). It never opens its own socket or
|
||||
/// requests data; the caller passes the run detail's `steps`.
|
||||
class ChangesViewer extends StatefulWidget {
|
||||
const ChangesViewer({super.key, required this.steps});
|
||||
|
||||
/// The run detail's steps exactly as the server returned them. Each step's
|
||||
/// `file_changes` may be null (no capture), a complete/partial/unavailable
|
||||
/// capture, or a capture with zero files (a recorded no-change).
|
||||
///
|
||||
/// Pass a stable list: the same instance until the server reply changes. The
|
||||
/// captures and the summary are derived from it rather than on every rebuild.
|
||||
final List<JsonMap> steps;
|
||||
|
||||
@override
|
||||
State<ChangesViewer> createState() => _ChangesViewerState();
|
||||
}
|
||||
|
||||
class _ChangesViewerState extends State<ChangesViewer> {
|
||||
final _filter = TextEditingController();
|
||||
late List<StageCapture> _captures;
|
||||
late RunChanges _run;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_derive();
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(ChangesViewer oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
// Filter keystrokes rebuild this widget with the same steps list; only a
|
||||
// new server reply re-derives the captures and the aggregate.
|
||||
if (!identical(oldWidget.steps, widget.steps)) _derive();
|
||||
}
|
||||
|
||||
void _derive() {
|
||||
_captures = stageCaptures(widget.steps);
|
||||
_run = runChangesFor(_captures);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_filter.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
String get _query => _filter.text;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final run = _run;
|
||||
final captures = _captures;
|
||||
final hasFiles = captures.any(
|
||||
(visit) => visit.capture?.files.isNotEmpty ?? false,
|
||||
);
|
||||
final note = runChangesNote(run);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
runChangesHeader(run),
|
||||
style: Theme.of(context).textTheme.titleMedium,
|
||||
),
|
||||
if (note.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Text(
|
||||
note,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
if (hasFiles)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Text(
|
||||
'The summary counts each path once, as the last recorded '
|
||||
'visit left it. Each stage/visit below lists what its own '
|
||||
'capture recorded.',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (hasFiles)
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 8),
|
||||
child: _filterField(context, run),
|
||||
),
|
||||
const Divider(height: 1),
|
||||
Expanded(
|
||||
child: captures.isEmpty
|
||||
? SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Text(noChangeDetail(run)),
|
||||
)
|
||||
: ListView.builder(
|
||||
itemCount: captures.length,
|
||||
itemBuilder: (context, index) {
|
||||
final visit = captures[index];
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
StageCaptureSection(
|
||||
stage: visit,
|
||||
query: _query,
|
||||
onOpen: (file) => showFileDiffViewer(context, file),
|
||||
),
|
||||
const Divider(height: 1),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _filterField(BuildContext context, RunChanges run) {
|
||||
final query = _query;
|
||||
final matched = query.trim().isEmpty
|
||||
? run.files.length
|
||||
: filterFileChanges(run.files, query).length;
|
||||
// The summary counts paths while the sections below list one row per stage
|
||||
// visit, so the counter names what it actually counts.
|
||||
final counter = query.trim().isEmpty
|
||||
? ''
|
||||
: '$matched of ${run.files.length} changed '
|
||||
'${run.files.length == 1 ? 'path' : 'paths'} match';
|
||||
final field = usesCupertino(context)
|
||||
? CupertinoSearchTextField(
|
||||
controller: _filter,
|
||||
placeholder: 'Filter changed files',
|
||||
onChanged: (_) => setState(() {}),
|
||||
)
|
||||
: TextField(
|
||||
controller: _filter,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Filter changed files',
|
||||
hintText: 'Filename contains…',
|
||||
prefixIcon: const Icon(Icons.search),
|
||||
suffixIcon: query.isEmpty
|
||||
? null
|
||||
: IconButton(
|
||||
tooltip: 'Clear filter',
|
||||
onPressed: () {
|
||||
_filter.clear();
|
||||
setState(() {});
|
||||
},
|
||||
icon: const Icon(Icons.clear),
|
||||
),
|
||||
),
|
||||
onChanged: (_) => setState(() {}),
|
||||
);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
field,
|
||||
if (counter.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 4),
|
||||
child: Text(counter, style: Theme.of(context).textTheme.bodySmall),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
|
||||
import '../domain/change_kind.dart';
|
||||
import '../domain/change_wording.dart';
|
||||
import '../domain/file_change.dart';
|
||||
import '../domain/unified_patch.dart';
|
||||
import 'change_style.dart';
|
||||
import 'patch_view.dart';
|
||||
|
||||
/// The reusable viewer for one recorded file change: its kind, path, stat,
|
||||
/// tags, the rendered or raw unified patch, Copy patch (the server's exact
|
||||
/// bytes) and Close. Binary/truncated/mode-only/no-patch entries show an honest
|
||||
/// reason instead of a fabricated diff.
|
||||
class FileDiffViewer extends StatefulWidget {
|
||||
const FileDiffViewer({super.key, required this.file, this.onClose});
|
||||
|
||||
final FileChange file;
|
||||
|
||||
/// Called by the Close control. Defaults to popping the enclosing route.
|
||||
final VoidCallback? onClose;
|
||||
|
||||
@override
|
||||
State<FileDiffViewer> createState() => _FileDiffViewerState();
|
||||
}
|
||||
|
||||
class _FileDiffViewerState extends State<FileDiffViewer> {
|
||||
DiffForm _form = DiffForm.rendered;
|
||||
bool _copied = false;
|
||||
Timer? _copyTimer;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_copyTimer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _close() {
|
||||
final close = widget.onClose;
|
||||
if (close != null) {
|
||||
close();
|
||||
} else {
|
||||
Navigator.of(context).maybePop();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _copy() async {
|
||||
final patch = widget.file.patch;
|
||||
if (patch == null) return;
|
||||
await Clipboard.setData(ClipboardData(text: patch));
|
||||
if (!mounted) return;
|
||||
setState(() => _copied = true);
|
||||
_copyTimer?.cancel();
|
||||
_copyTimer = Timer(const Duration(seconds: 2), () {
|
||||
if (mounted) setState(() => _copied = false);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final file = widget.file;
|
||||
final cupertino = usesCupertino(context);
|
||||
final base = DefaultTextStyle.of(context).style;
|
||||
final mono = nativeDiffText(base);
|
||||
final stat = changeStat(file.added, file.removed);
|
||||
final tags = changeEntryTags(file);
|
||||
return ConstrainedBox(
|
||||
key: const ValueKey('file-diff-viewer'),
|
||||
constraints: BoxConstraints(
|
||||
maxWidth: 900,
|
||||
maxHeight: MediaQuery.sizeOf(context).height * 0.85,
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.fromLTRB(16, 12, 8, 8),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Semantics(
|
||||
container: true,
|
||||
header: true,
|
||||
excludeSemantics: true,
|
||||
label: [
|
||||
changeKindTitle(file.kind),
|
||||
if (stat.isNotEmpty) stat,
|
||||
if (tags.isNotEmpty) tags.join(' · '),
|
||||
'for ${file.path}',
|
||||
if (file.steps.isNotEmpty)
|
||||
'changed by ${file.steps.join(' → ')}',
|
||||
if (file.modeChanged && !file.binary)
|
||||
'mode ${file.beforeMode ?? ''}→'
|
||||
'${file.afterMode ?? ''}',
|
||||
].join(', '),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Wrap(
|
||||
spacing: 12,
|
||||
runSpacing: 4,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
Text(
|
||||
changeKindTitle(file.kind),
|
||||
style: Theme.of(context).textTheme.titleMedium,
|
||||
),
|
||||
if (stat.isNotEmpty) Text(stat, style: mono),
|
||||
if (tags.isNotEmpty)
|
||||
Text(
|
||||
tags.join(' · '),
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(file.path, style: mono),
|
||||
if (file.steps.isNotEmpty)
|
||||
Text(
|
||||
'changed by ${file.steps.join(' → ')}',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
if (file.modeChanged && !file.binary)
|
||||
Text(
|
||||
'mode ${file.beforeMode ?? ''}→'
|
||||
'${file.afterMode ?? ''}',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
closeDiffControl(context, _close),
|
||||
],
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
crossAxisAlignment: WrapCrossAlignment.center,
|
||||
children: [
|
||||
if (file.hasPatch)
|
||||
diffFormControl(
|
||||
context,
|
||||
form: _form,
|
||||
onChanged: (value) => setState(() => _form = value),
|
||||
),
|
||||
copyPatchControl(
|
||||
context,
|
||||
enabled: file.hasPatch,
|
||||
copied: _copied,
|
||||
onPressed: _copy,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Divider(
|
||||
height: 16,
|
||||
color: cupertino
|
||||
? CupertinoColors.separator.resolveFrom(context)
|
||||
: Theme.of(context).dividerColor,
|
||||
),
|
||||
Flexible(child: _body(context, cupertino, mono)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _body(BuildContext context, bool cupertino, TextStyle mono) {
|
||||
final file = widget.file;
|
||||
if (file.binary) return _message(context, binaryDiffMessage);
|
||||
if (!file.hasPatch) {
|
||||
return _message(context, patchUnavailableReason(file));
|
||||
}
|
||||
if (_form == DiffForm.raw) {
|
||||
return Semantics(
|
||||
container: true,
|
||||
label: 'Raw patch for ${file.path}',
|
||||
value: file.patch,
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.fromLTRB(16, 0, 16, 16),
|
||||
child: SingleChildScrollView(
|
||||
// Raw patch bytes are one line each: scroll them sideways like the
|
||||
// web view instead of wrapping a continuation under a new line.
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: ExcludeSemantics(
|
||||
child: SelectionArea(
|
||||
child: Text(
|
||||
file.patch!,
|
||||
style: mono,
|
||||
softWrap: false,
|
||||
overflow: TextOverflow.visible,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
return SingleChildScrollView(
|
||||
padding: const EdgeInsets.only(bottom: 16),
|
||||
child: PatchView(file: file),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _message(BuildContext context, String text) {
|
||||
return SingleChildScrollView(
|
||||
padding: const EdgeInsets.fromLTRB(16, 8, 16, 16),
|
||||
child: Text(text),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Open [file] in the platform's standard modal: a Material dialog on
|
||||
/// Android/desktop/web, a Cupertino dialog with a popup surface on iOS/macOS.
|
||||
Future<void> showFileDiffViewer(BuildContext context, FileChange file) {
|
||||
final cupertino = usesCupertino(context);
|
||||
Widget buildDialog(BuildContext dialogContext) {
|
||||
final viewer = FileDiffViewer(
|
||||
file: file,
|
||||
onClose: () => Navigator.of(dialogContext).pop(),
|
||||
);
|
||||
if (cupertino) {
|
||||
// A popup surface spans the window unless it is inset; on a phone the
|
||||
// screen edge would clip its native rounded corners.
|
||||
final width = MediaQuery.sizeOf(dialogContext).width;
|
||||
return Padding(
|
||||
padding: EdgeInsets.symmetric(
|
||||
horizontal: width < 600 ? 16 : 40,
|
||||
vertical: 24,
|
||||
),
|
||||
child: Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 900),
|
||||
child: CupertinoPopupSurface(child: SafeArea(child: viewer)),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
return Dialog(child: SafeArea(child: viewer));
|
||||
}
|
||||
|
||||
if (cupertino) {
|
||||
return showCupertinoDialog<void>(context: context, builder: buildDialog);
|
||||
}
|
||||
return showDialog<void>(context: context, builder: buildDialog);
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../domain/change_wording.dart';
|
||||
import '../domain/file_change.dart';
|
||||
import '../domain/unified_patch.dart';
|
||||
import 'change_style.dart';
|
||||
|
||||
/// The rendered reading of one recorded unified patch: each hunk's `@@` header,
|
||||
/// the shared diff line language (`+`/`-`/space) and the old/new gutter numbers.
|
||||
/// This is the only custom drawing in the feature; everything around it is a
|
||||
/// standard platform control.
|
||||
class PatchView extends StatelessWidget {
|
||||
const PatchView({super.key, required this.file});
|
||||
|
||||
final FileChange file;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final parsed = file.parsedPatch;
|
||||
final base = nativeDiffText(DefaultTextStyle.of(context).style);
|
||||
final stat = changeStat(parsed.added, parsed.removed);
|
||||
return Semantics(
|
||||
container: true,
|
||||
label: 'Rendered diff for ${file.path}',
|
||||
value: stat.isEmpty ? noLineChangesMessage : stat,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
child: ExcludeSemantics(
|
||||
child: _StatLine(
|
||||
added: parsed.added,
|
||||
removed: parsed.removed,
|
||||
base: base,
|
||||
),
|
||||
),
|
||||
),
|
||||
if (file.truncated)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
|
||||
child: Text(
|
||||
truncatedPatchNote,
|
||||
style: base.copyWith(color: mutedColor(context)),
|
||||
),
|
||||
),
|
||||
// The web rendered view shows hunks, not the recorded `---`/`+++`
|
||||
// file headers (they stay in the Raw view), so the dialog does not
|
||||
// show a long header clipped at its edge.
|
||||
for (final hunk in parsed.hunks) _HunkView(hunk: hunk),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// `+N` in the add colour and `-M` in the remove colour, or the honest note when
|
||||
/// the patch records no changed line.
|
||||
class _StatLine extends StatelessWidget {
|
||||
const _StatLine({
|
||||
required this.added,
|
||||
required this.removed,
|
||||
required this.base,
|
||||
});
|
||||
|
||||
final int added;
|
||||
final int removed;
|
||||
final TextStyle base;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (added == 0 && removed == 0) {
|
||||
return Text(
|
||||
noLineChangesMessage,
|
||||
style: base.copyWith(color: mutedColor(context)),
|
||||
);
|
||||
}
|
||||
return Text.rich(
|
||||
TextSpan(
|
||||
children: [
|
||||
if (added > 0)
|
||||
TextSpan(
|
||||
text: '+$added',
|
||||
style: base.copyWith(
|
||||
color: diffLineColors(context, ChangeLineKind.add).text,
|
||||
),
|
||||
),
|
||||
if (added > 0 && removed > 0) TextSpan(text: ' ', style: base),
|
||||
if (removed > 0)
|
||||
TextSpan(
|
||||
text: '-$removed',
|
||||
style: base.copyWith(
|
||||
color: diffLineColors(context, ChangeLineKind.remove).text,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _HunkView extends StatelessWidget {
|
||||
const _HunkView({required this.hunk});
|
||||
|
||||
final PatchHunk hunk;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final base = nativeDiffText(DefaultTextStyle.of(context).style);
|
||||
final width = gutterWidth(hunk);
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Container(
|
||||
color: hunkHeaderColor(context),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
|
||||
child: Text(hunk.header, style: base),
|
||||
),
|
||||
LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
return SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: ConstrainedBox(
|
||||
// At least the dialog's width, so a short hunk still paints
|
||||
// full-width bands; wider content scrolls sideways.
|
||||
constraints: BoxConstraints(minWidth: constraints.maxWidth),
|
||||
// The widest recorded line sets the hunk's content width, so
|
||||
// every line tint is a full-width band instead of a bar as long
|
||||
// as its own text.
|
||||
child: IntrinsicWidth(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
for (var index = 0; index < hunk.lines.length; index++)
|
||||
_LineRow(
|
||||
key: ValueKey('diff-line-$index'),
|
||||
line: hunk.lines[index],
|
||||
width: width,
|
||||
base: base,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _LineRow extends StatelessWidget {
|
||||
const _LineRow({
|
||||
super.key,
|
||||
required this.line,
|
||||
required this.width,
|
||||
required this.base,
|
||||
});
|
||||
|
||||
final PatchLine line;
|
||||
final int width;
|
||||
final TextStyle base;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final gutter = line.noNewlineMarker
|
||||
? ' ' * (width * 2 + 1)
|
||||
: '${gutterText(line.oldLine, width)} ${gutterText(line.newLine, width)}';
|
||||
final colors = diffLineColors(context, line.kind);
|
||||
final content = '${diffLineSymbol(line.kind)} ${line.text}';
|
||||
return Container(
|
||||
color: colors.background,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 2),
|
||||
child: Text.rich(
|
||||
TextSpan(
|
||||
children: [
|
||||
TextSpan(
|
||||
text: gutter,
|
||||
style: base.copyWith(color: mutedColor(context)),
|
||||
),
|
||||
TextSpan(
|
||||
text: content,
|
||||
style: base.copyWith(color: colors.text),
|
||||
),
|
||||
],
|
||||
),
|
||||
softWrap: false,
|
||||
overflow: TextOverflow.visible,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+323
@@ -0,0 +1,323 @@
|
||||
# D1 — run changes and the file diff viewer
|
||||
|
||||
New feature under `lib/features/changes/`; no server, legacy web/Android or
|
||||
pubspec changes remain after manager acceptance corrections.
|
||||
|
||||
## Current manager acceptance (supersedes earlier presentation evidence below)
|
||||
|
||||
The pipeline's bundled font and fixed green/red palette were rejected against
|
||||
the user's native-defaults requirement. Manager removed both and the font assets
|
||||
without changing raw patch, capture or visit semantics. Typography inherits the
|
||||
host; colours use native semantic roles and no row tint. The original candidate
|
||||
and its review evidence remain referenced at15cca17; later font/palette evidence
|
||||
in this note is historical, NOT evidence for the final native-defaults patch.
|
||||
|
||||
Updated regressions failed against the original overrides, then all47 focused
|
||||
tests passed after correction; analyzer clean. Fresh fixture web build and
|
||||
changes_probe passed (including absence of custom font), producing18 new captures
|
||||
under approved temp/native-diff-manager-captures. Manager inspected both native
|
||||
phone2x rendered views. Preview/shell integration and mobile remain unverified.
|
||||
|
||||
## Public API
|
||||
|
||||
Import the barrel:
|
||||
|
||||
```dart
|
||||
import 'package:pipelines_app/features/changes/changes.dart';
|
||||
```
|
||||
|
||||
Integration widgets:
|
||||
|
||||
- `ChangesViewer({Key? key, required List<JsonMap> steps})`
|
||||
- The run detail's `steps` exactly as returned by `get_run`. Pass the same
|
||||
list instance until the server reply changes: captures and the summary are
|
||||
derived once per list identity, not on every rebuild or filter keystroke.
|
||||
- It fills the available height, so place it in a bounded parent (Scaffold
|
||||
body, tab body or `Expanded`). It does not open a socket or request data.
|
||||
- `FileDiffViewer({Key? key, required FileChange file, VoidCallback? onClose})`
|
||||
- The reusable viewer for one recorded file. Without `onClose` it pops the
|
||||
enclosing route.
|
||||
- `Future<void> showFileDiffViewer(BuildContext context, FileChange file)`
|
||||
- Opens the platform modal: `showDialog` with a Material `Dialog` on
|
||||
Android/desktop/web, `showCupertinoDialog` with `CupertinoPopupSurface` on
|
||||
iOS/macOS.
|
||||
|
||||
Data and pure helpers exported for integration/tests:
|
||||
|
||||
- `FileChange` — `path`, `kind`, `patch` (server bytes or null), `binary`,
|
||||
`truncated`, `beforeMode`, `afterMode`, `steps`; `FileChange.fromJson(JsonMap)`,
|
||||
`FileChange.tryParse(dynamic)`.
|
||||
- `ChangeCapture` — `status`, `scope`, `files`, `skipped`, `omitted`,
|
||||
`diagnostic`; `ChangeCapture.fromJson(JsonMap)`.
|
||||
- `StageCapture` / `StageCapture.fromStep(JsonMap)` / `stageCaptures(steps)` —
|
||||
one stage visit per step, ordered by numeric sequence, including steps with no
|
||||
capture. `sequence` is the run-wide step ordinal (ordering and keys); `visit`
|
||||
is the display visit number within the stage.
|
||||
- `RunChanges` / `runChanges(steps)` / `runChangesFor(captures)` — final-state
|
||||
aggregate (last recorded visit wins per path; each path counted once) with the
|
||||
same fields. `runChangesFor` avoids re-deriving captures a caller already has.
|
||||
- `parseUnifiedPatch`, `PatchHunk`, `PatchLine`, `ChangeLineKind`, `gutterWidth`,
|
||||
`gutterText`, `changeStat`, `changeKind`, `changeKindLabel`, `changeKindTitle`.
|
||||
- Wording: `runChangesHeader`, `runChangesNote`, `changesListSummary`,
|
||||
`noChangeDetail`, `patchUnavailableReason`, `changeEntryTags`, `changeRowMeta`,
|
||||
`changeFileMeta`, `fileChangesSummary`, `filterFileChanges`,
|
||||
`changePositionLabel`, `binaryDiffMessage`, `truncatedPatchNote`,
|
||||
`noLineChangesMessage`, `missingCaptureDetail`, `unavailableCaptureDetail`,
|
||||
`malformedCaptureDetail`, `emptyCaptureDetail`, `partialCaptureDetail`.
|
||||
|
||||
Example integration:
|
||||
|
||||
```dart
|
||||
final steps = (detail['steps'] as List).cast<JsonMap>();
|
||||
// ...
|
||||
ChangesViewer(steps: steps)
|
||||
```
|
||||
|
||||
The manager owns shell/run-detail registration; this item does not edit them.
|
||||
|
||||
## Recorded-evidence semantics (matches `web/src/changes.js`)
|
||||
|
||||
- `file_changes == null` is **missing evidence**, not “no changes”. A
|
||||
running/waiting step is “pending”; any other missing capture is counted and
|
||||
named. The UI says the capture is unavailable and explicitly says that does not
|
||||
mean the workspace was unchanged.
|
||||
- `status: "unavailable"` means the snapshots could not be compared. No change
|
||||
list is fabricated; the server diagnostic is shown. A non-null `file_changes`
|
||||
value that is not an object is also unreadable evidence, so it is treated as
|
||||
unavailable with `malformedCaptureDetail`; it never becomes an empty capture.
|
||||
- A present complete capture with `files: []` is the only “no changes observed”
|
||||
state (“the captured snapshots were identical”).
|
||||
- `status: "partial"`, any per-file `truncated`, or any `omitted` count makes the
|
||||
run partial; `skipped`, `omitted`, truncated-file count and the diagnostic are
|
||||
shown. `scope` is shown per stage capture.
|
||||
- Files are grouped by stage/visit. The visit label is the recorded
|
||||
`control.visit` when it is positive (a resumed run), otherwise the visit's
|
||||
1-based position among the steps of its own stage, ordered by sequence and
|
||||
stable for ties. This mirrors the web client's `displayVisit`; the run-wide
|
||||
step `sequence` is only the ordering/key, never shown as a visit number.
|
||||
- Kinds are `added`, `modified`, `deleted` and the safe `changed` fallback.
|
||||
Binary, truncated and mode-only entries carry labels; a mode-only entry has no
|
||||
text diff and says so.
|
||||
- The run summary is final-state: a path recorded by several visits is one row,
|
||||
keeping first-seen order and the last visit's kind/patch/stat/flags/modes, with
|
||||
the stage names that touched it. Per-stage sections still show each visit's own
|
||||
capture.
|
||||
- Filtering matches changed filenames case-insensitively (substring) and keeps
|
||||
missing/unavailable evidence sections visible. The counter names **paths**,
|
||||
matching the summary's unit; the sections below still list one row per visit.
|
||||
- A changed-file row's semantics label names the action, path, kind and visible
|
||||
meta (`+N -M`, binary/truncated/mode), so the excluded icon and subtitle are
|
||||
still announced.
|
||||
|
||||
## Diff rendering
|
||||
|
||||
- Only patch content is custom-drawn: `@@` hunk headers, old/new gutter numbers,
|
||||
the shared `+`/`-`/space language, context and `\ No newline` markers.
|
||||
- The recorded `---`/`+++` file headers stay in the Raw view, matching the web
|
||||
rendered view; rendered content is the stat line and the hunks. Long lines
|
||||
scroll horizontally; vertical content scrolls inside the dialog. The Raw view
|
||||
keeps each recorded line on one line and scrolls sideways, like the web's
|
||||
`white-space: pre` pane, so a wrapped continuation can never be mistaken for a
|
||||
new patch line.
|
||||
- Patch/path text inherits the native host typography without a font-family,
|
||||
size or weight override. Manager removed the candidate's bundled code font:
|
||||
a previous visual review requested it, but that contradicts the user's
|
||||
explicit native-defaults requirement, which also applies to diffs. The web
|
||||
default may be proportional; no monospace guarantee is claimed. Raw patch
|
||||
bytes are unchanged. No bundled font or pubspec change remains.
|
||||
- Rendered/Raw is a native Material `SegmentedButton` or Cupertino
|
||||
`CupertinoSlidingSegmentedControl`. Copy patch and Close are native Material
|
||||
buttons/icon button or Cupertino buttons with exact labels.
|
||||
- Copy patch writes the recorded `patch` string byte-for-byte (trailing newline
|
||||
and truncated final line included). Copy is disabled when no readable patch
|
||||
exists.
|
||||
- Binary uses the honest binary message; truncated-with-patch shows the note plus
|
||||
the retained text; truncated-without-patch and mode-only show the recorded
|
||||
reason, never an invented empty diff.
|
||||
- Add/remove markers and stats use native semantic colours (Material primary/
|
||||
error; Cupertino systemGreen/destructiveRed), with no bespoke palette or added
|
||||
tint. +/- and recorded gutter numbers distinguish changes without colour.
|
||||
Rows share the hunk width, at least the dialog width.
|
||||
- A Cupertino list row lets its recorded path wrap instead of inheriting the
|
||||
tile's single ellipsized line, and the Cupertino dialog surface is inset from
|
||||
the window edge (16 on phones, 40 on wide windows) so its native rounded
|
||||
corners are visible.
|
||||
|
||||
## Files
|
||||
|
||||
```
|
||||
lib/features/changes/changes.dart
|
||||
lib/features/changes/domain/change_capture.dart
|
||||
lib/features/changes/domain/change_kind.dart
|
||||
lib/features/changes/domain/change_wording.dart
|
||||
lib/features/changes/domain/file_change.dart
|
||||
lib/features/changes/domain/patch_models.dart
|
||||
lib/features/changes/domain/run_changes.dart
|
||||
lib/features/changes/domain/unified_patch.dart
|
||||
lib/features/changes/widgets/change_style.dart
|
||||
lib/features/changes/widgets/changes_viewer.dart
|
||||
lib/features/changes/widgets/capture_section.dart
|
||||
lib/features/changes/widgets/file_diff_viewer.dart
|
||||
lib/features/changes/widgets/patch_view.dart
|
||||
assets/fonts/RobotoMono.ttf
|
||||
assets/fonts/OFL.txt
|
||||
pubspec.yaml (fonts + assets declaration)
|
||||
test/features/changes/fixtures.dart
|
||||
test/features/changes/widget_hosts.dart
|
||||
test/features/changes/unified_patch_test.dart
|
||||
test/features/changes/run_changes_test.dart
|
||||
test/features/changes/changes_viewer_test.dart
|
||||
test/features/changes/diff_presentation_test.dart
|
||||
tool/changes_probe_entry.dart
|
||||
tool/changes_probe.mjs
|
||||
```
|
||||
|
||||
Every path above is new except `pubspec.yaml`, which gains only the
|
||||
`RobotoMono` family and the font licence asset declaration.
|
||||
|
||||
## Checks
|
||||
|
||||
Presentation revision (bundled code face, diff colours/tints, Cupertino rows and
|
||||
dialog inset) re-ran the full set:
|
||||
|
||||
- `/Users/alan/development/flutter/bin/flutter test` — **76 tests passed**.
|
||||
- `/Users/alan/development/flutter/bin/flutter test test/features/changes` —
|
||||
**47 tests passed**.
|
||||
- `/Users/alan/development/flutter/bin/flutter analyze` — **No issues found**.
|
||||
- `/Users/alan/development/flutter/bin/dart format --output=none
|
||||
--set-exit-if-changed lib/features/changes test/features/changes
|
||||
tool/changes_probe_entry.dart` — 20 files, 0 changed.
|
||||
- `/Users/alan/development/flutter/bin/flutter build web` — **built
|
||||
`build/web`** successfully.
|
||||
- `node --check tool/changes_probe.mjs` — passed.
|
||||
- `/Users/alan/development/flutter/bin/flutter build web --target
|
||||
tool/changes_probe_entry.dart --output build/probe-web-fix` — built.
|
||||
- `node tool/changes_probe.mjs --root build/probe-web-fix --out <public>/d1` —
|
||||
passed every check (11 checks, below).
|
||||
|
||||
`flutter pub get` resolved the existing lock; `pubspec.lock` is unchanged.
|
||||
|
||||
## Real browser evidence
|
||||
|
||||
Fixture entry `tool/changes_probe_entry.dart`, driven by `tool/changes_probe.mjs`
|
||||
(loopback, OS-assigned port, headless Chrome, Flutter semantics enabled). The
|
||||
fixture uses server-shaped captures for partial, complete, missing, unavailable
|
||||
and empty states, plus binary, truncated, mode-only, deleted, added and
|
||||
multi-hunk patches. `/?visits=1` is a compact second fixture that repeats stages
|
||||
and records one explicit `control.visit`. It is rendering data only; no server or
|
||||
operator run touched.
|
||||
|
||||
Captures (in the run's public artifacts `d1/`):
|
||||
|
||||
- `d1-changes-phone-list.png` (390×844, dark)
|
||||
- `d1-changes-phone-diff.png`
|
||||
- `d1-changes-phone-raw.png`
|
||||
- `d1-changes-phone-copied.png`
|
||||
- `d1-changes-phone-filtered.png`
|
||||
- `d1-changes-phone-visits.png` (390×844, repeated-stage visit labels)
|
||||
- `d1-changes-phone-light-list.png`, `d1-changes-phone-light-diff.png`,
|
||||
`d1-changes-phone-light-diff-2x.png`, `d1-changes-phone-light-raw.png`
|
||||
(light theme, 2x where glyphs and tints are inspected)
|
||||
- `d1-changes-desktop-diff.png` (1280×800)
|
||||
- `d1-changes-desktop-list.png`
|
||||
- `d1-changes-desktop-light-list.png`, `d1-changes-desktop-light-diff.png`
|
||||
- `d1-changes-cupertino-diff.png` (1280×800, Cupertino fixture)
|
||||
- `d1-changes-cupertino-light-list.png` (390×844, wrapped paths),
|
||||
`d1-changes-cupertino-light-diff.png`, `d1-changes-cupertino-light-diff-2x.png`
|
||||
(390×844, inset popup)
|
||||
|
||||
Observed checks from `d1-probe.json`:
|
||||
|
||||
- Root `/` served `text/html; charset=utf-8`.
|
||||
- `assets/FontManifest.json` lists a `RobotoMono` family and
|
||||
`assets/fonts/RobotoMono.ttf` is served as `font/ttf` (183,700 bytes), so the
|
||||
web build carries a real code face.
|
||||
- The body showed `Changes probe` and `Capture unavailable`, and a file row whose
|
||||
semantics label starts with
|
||||
`Open diff for lib/features/changes/domain/unified_patch.dart` (the label now
|
||||
also announces kind and meta).
|
||||
- Opening the diff changed `document.body.innerText`; `Rendered`, `Raw patch`,
|
||||
`Copy patch` and `Close diff` labels appeared.
|
||||
- `Raw patch` changed the body and produced a different PNG from the rendered
|
||||
capture; the raw semantics value contains the recorded `---`/`+++` header.
|
||||
- Clipboard readback after `Copy patch` started with
|
||||
`--- "a/lib/features/changes/domain/unified_patch.dart"` (540 bytes).
|
||||
- Filtering `unified` left both matching visit rows (`unifiedRows: 2`) and hid
|
||||
`assets/pipelines-mark.png` (`binaryRows: 0`); the counter read
|
||||
`1 of 6 changed paths match`.
|
||||
- The visits fixture rendered `implementer` with `Visit 1` and `Visit 2`, and
|
||||
`reviewer` with `Visit 1` and the recorded `control.visit` `Visit 6`; the probe
|
||||
fails if either list differs.
|
||||
- `Close diff` returned to the list; the desktop and Cupertino viewers opened.
|
||||
|
||||
Measured from `d1-changes-phone-light-diff-2x.png` (Pillow): the light add tint is
|
||||
`#E3F3E7` and the remove tint `#FBE7E5` (ΔR 24); every changed line paints a
|
||||
618 px (309 logical px) band — the full dialog content width — and the two added
|
||||
lines and one removed line are each 92/46 device px tall. Previously the tints
|
||||
were `#FFD8E4`/`#F9DEDC` (Δ 6,6,8) and only as wide as each line's text. Dark
|
||||
captures measure `#394643` (green) and `#4D3C42` (red) tints.
|
||||
|
||||
The screenshots show real Material and Cupertino controls, light and dark themes,
|
||||
phone and desktop widths, wrapped Cupertino paths and an inset Cupertino popup.
|
||||
Mobile targets were not built, installed or run.
|
||||
|
||||
## Review revision
|
||||
|
||||
- **B1 (blocking, visit labels):** `StageCapture.visit` is derived from positive
|
||||
`control.visit` else the stage position; sections render it instead of the
|
||||
run-wide `sequence`. Unit/widget tests cover repeated stages, a resumed visit
|
||||
and sequence ties; the browser visits fixture and capture above show the result.
|
||||
- **A1 (malformed capture):** a non-object `file_changes` is now unavailable with
|
||||
`malformedCaptureDetail`, never an empty “no changes” capture.
|
||||
- **A2 (rendered headers):** rendered view shows hunks only, matching the web
|
||||
rendered view; the exact headers remain in Raw and Copy.
|
||||
- **A3 (re-derivation):** `ChangesViewer` derives captures/aggregate on init and
|
||||
when the steps list changes, not on filter keystrokes; `runChangesFor` reuses
|
||||
those captures, and `FileChange.withSteps` reuses the parsed patch.
|
||||
- **A4 (test fixtures):** the run-changes test helpers now delegate to
|
||||
`test/features/changes/fixtures.dart`.
|
||||
- **A5 (row semantics):** the row label includes kind and visible meta.
|
||||
- **A6 (filter counter):** counts and names changed **paths**, matching the
|
||||
summary; the list remains per visit.
|
||||
- **A7 (paging):** unchanged; the one-file viewer API is the documented limit.
|
||||
|
||||
## Presentation revision (UI review)
|
||||
|
||||
- **M1 (monospace):** `pubspec.yaml` declares the bundled `RobotoMono` family
|
||||
(`assets/fonts/RobotoMono.ttf`, SIL OFL 1.1, licence in `assets/fonts/OFL.txt`)
|
||||
and `monospaceText` uses it on every platform. The browser build's
|
||||
`FontManifest.json` and font response are checked by the probe, and the 2x
|
||||
captures show even advances and aligned gutters.
|
||||
- **M2 (add/remove colours and tints):** the diff no longer uses Material
|
||||
`tertiaryContainer`/`errorContainer`. `diffLineColors` supplies theme-aware
|
||||
green/red pairs (light `#116B33` on `#E3F3E7`, `#B3261E` on `#FBE7E5`; dark
|
||||
`#7FE0A8`/`#FF9E9E` on a 16% wash), the `+N`/`-M` stat is split into those two
|
||||
hues, and every line tint spans the full hunk width (at least the dialog width)
|
||||
via `IntrinsicWidth` inside a width-bounded scroll view.
|
||||
- **M3 (Cupertino):** list rows clear `CupertinoListTile`'s inherited single-line
|
||||
cap so the recorded path wraps, and the Cupertino dialog is inset (16 on
|
||||
phones, 40 on wide windows) so its rounded corners are visible.
|
||||
- **Nonblocking raw wrap:** the Raw view now keeps one recorded line per line and
|
||||
scrolls horizontally (`SelectionArea` over a `Text` with `softWrap: false`),
|
||||
matching the web's `pre` pane.
|
||||
- **Left as-is (nonblocking):** list-row stat strings stay neutral (Android/web
|
||||
colour them), the unavailable diagnostic still appears in both the section meta
|
||||
and the note (web parity), and the one-file viewer has no paging.
|
||||
|
||||
## Deliberate limits
|
||||
|
||||
- One file per `FileDiffViewer`; the browser viewer's previous/next gallery
|
||||
paging is not implemented here. The task asked for a reusable one-file viewer.
|
||||
- The shell/run-detail screen is not wired; that remains the manager's
|
||||
integration step (feature lanes do not edit shell/main).
|
||||
- Run status gating (`showRunChangesSummary`, succeeded-only in the browser) is
|
||||
the caller's choice; `ChangesViewer` renders whatever steps it is given.
|
||||
- The bundled font is Latin/Greek/Cyrillic: a patch containing CJK or symbol
|
||||
glyphs outside that coverage falls back for those glyphs, so their advance may
|
||||
not be monospaced. Copy and Raw bytes are unaffected.
|
||||
- Android and iOS were not built, installed or run in this revision; the
|
||||
Cupertino path is verified only through the fixture's browser rendering and
|
||||
widget tests, so **mobile remains unverified**.
|
||||
- No backend capability is missing for this item: `file_changes` already carries
|
||||
status, scope, files, skipped, omitted, diagnostic, binary/truncated flags,
|
||||
modes and patches.
|
||||
@@ -0,0 +1,473 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/changes/changes.dart';
|
||||
|
||||
import 'fixtures.dart';
|
||||
import 'widget_hosts.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets(
|
||||
'a missing capture is an evidence gap, not an observed no-change',
|
||||
(tester) async {
|
||||
await tester.pumpWidget(
|
||||
materialHost(ChangesViewer(steps: [stepFixture(fileChanges: null)])),
|
||||
);
|
||||
expect(find.text('Changes · not recorded for this run'), findsOneWidget);
|
||||
expect(find.text('Capture unavailable'), findsOneWidget);
|
||||
expect(find.text(missingCaptureDetail), findsOneWidget);
|
||||
expect(find.text(emptyCaptureDetail), findsNothing);
|
||||
expect(find.text('No changes observed'), findsNothing);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('a running step with no capture is pending, not unavailable', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
ChangesViewer(
|
||||
steps: [stepFixture(status: 'running', fileChanges: null)],
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(find.text('Changes · capture pending'), findsOneWidget);
|
||||
expect(find.text('Capture pending'), findsOneWidget);
|
||||
expect(find.text(pendingCaptureDetail), findsOneWidget);
|
||||
expect(find.text('Capture unavailable'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('a differently cased running status agrees with the header', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
ChangesViewer(
|
||||
steps: [stepFixture(status: 'Running', fileChanges: null)],
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(find.text('Changes · capture pending'), findsOneWidget);
|
||||
expect(find.text('Capture pending'), findsOneWidget);
|
||||
expect(find.text('Capture unavailable'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('an empty complete capture says the workspace was unchanged', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
ChangesViewer(steps: [stepFixture(fileChanges: captureFixture())]),
|
||||
),
|
||||
);
|
||||
expect(find.text('Changes · no changes observed'), findsOneWidget);
|
||||
expect(find.text('No changes observed'), findsOneWidget);
|
||||
expect(find.text(emptyCaptureDetail), findsOneWidget);
|
||||
expect(find.text(missingCaptureDetail), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('an unavailable capture never claims there were no changes', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
ChangesViewer(
|
||||
steps: [
|
||||
stepFixture(
|
||||
fileChanges: captureFixture(
|
||||
status: 'unavailable',
|
||||
diagnostic:
|
||||
'Workspace snapshot unavailable; changes could not be '
|
||||
'compared.',
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(find.text('Changes · capture unavailable'), findsOneWidget);
|
||||
expect(find.textContaining('Workspace snapshot unavailable'), findsWidgets);
|
||||
expect(find.text(emptyCaptureDetail), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets('stage/visit sections keep partial status, counters and scope', (
|
||||
tester,
|
||||
) async {
|
||||
final diagnostic = 'Excluded protected files.';
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
ChangesViewer(
|
||||
steps: [
|
||||
stepFixture(
|
||||
stage: 'implementer',
|
||||
fileChanges: captureFixture(
|
||||
status: 'partial',
|
||||
skipped: 1,
|
||||
omitted: 2,
|
||||
diagnostic: diagnostic,
|
||||
files: [
|
||||
fileChangeFixture(path: 'lib/a.dart', patch: multiHunkPatch),
|
||||
],
|
||||
),
|
||||
),
|
||||
stepFixture(
|
||||
stage: 'reviewer',
|
||||
sequence: 2,
|
||||
status: 'failed',
|
||||
fileChanges: null,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(find.text('implementer'), findsOneWidget);
|
||||
expect(find.text('Visit 1 · completed'), findsOneWidget);
|
||||
// The reviewer's first visit is Visit 1, not the run-wide step ordinal 2.
|
||||
expect(find.text('Visit 1 · failed'), findsOneWidget);
|
||||
expect(find.text('Visit 2 · failed'), findsNothing);
|
||||
expect(
|
||||
find.text(
|
||||
'partial (1 files), 1 skipped, 2 omitted · Excluded protected files.',
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(
|
||||
find.text('Scope: Git tracked and nonignored files in the run directory'),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(find.text('reviewer'), findsOneWidget);
|
||||
expect(find.text(missingCaptureDetail), findsOneWidget);
|
||||
expect(find.textContaining('partial capture'), findsWidgets);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'repeated stages number their own visits and honour control.visit',
|
||||
(tester) async {
|
||||
// Tall enough that the lazy list builds every section.
|
||||
tester.view.physicalSize = const Size(800, 1400);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.reset);
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
ChangesViewer(
|
||||
steps: [
|
||||
stepFixture(
|
||||
stage: 'implementer',
|
||||
sequence: 1,
|
||||
fileChanges: captureFixture(),
|
||||
),
|
||||
stepFixture(
|
||||
stage: 'reviewer',
|
||||
sequence: 2,
|
||||
fileChanges: captureFixture(),
|
||||
),
|
||||
stepFixture(
|
||||
stage: 'implementer',
|
||||
sequence: 3,
|
||||
fileChanges: captureFixture(),
|
||||
),
|
||||
stepFixture(
|
||||
stage: 'reviewer',
|
||||
sequence: 4,
|
||||
visit: 6,
|
||||
fileChanges: captureFixture(),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
// Both stages' first recorded visits are Visit 1; the run-wide step
|
||||
// ordinals (1-4) must not leak into the label.
|
||||
expect(find.text('Visit 1 · completed'), findsNWidgets(2));
|
||||
expect(find.text('Visit 2 · completed'), findsOneWidget);
|
||||
// The resumed reviewer visit records control.visit 6.
|
||||
expect(find.text('Visit 6 · completed'), findsOneWidget);
|
||||
expect(find.text('Visit 3 · completed'), findsNothing);
|
||||
expect(find.text('Visit 4 · completed'), findsNothing);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('filtering changed filenames keeps matching rows and says so', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
ChangesViewer(
|
||||
steps: [
|
||||
stepFixture(
|
||||
fileChanges: captureFixture(
|
||||
files: [
|
||||
fileChangeFixture(path: 'assets/logo.bin', binary: true),
|
||||
fileChangeFixture(
|
||||
path: 'lib/feature.dart',
|
||||
patch: multiHunkPatch,
|
||||
),
|
||||
fileChangeFixture(
|
||||
path: 'docs/notes.md',
|
||||
kind: 'added',
|
||||
patch: '@@ -0,0 +1 @@\n+x',
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(find.text('assets/logo.bin'), findsOneWidget);
|
||||
expect(find.text('lib/feature.dart'), findsOneWidget);
|
||||
|
||||
await tester.enterText(find.byType(TextField), 'feature');
|
||||
await tester.pump();
|
||||
expect(find.text('lib/feature.dart'), findsOneWidget);
|
||||
expect(find.text('assets/logo.bin'), findsNothing);
|
||||
expect(find.text('docs/notes.md'), findsNothing);
|
||||
expect(find.text('1 of 3 changed paths match'), findsOneWidget);
|
||||
|
||||
await tester.enterText(find.byType(TextField), 'nothing-here');
|
||||
await tester.pump();
|
||||
expect(
|
||||
find.text('No changed filenames match "nothing-here".'),
|
||||
findsOneWidget,
|
||||
);
|
||||
|
||||
await tester.enterText(find.byType(TextField), '');
|
||||
await tester.pump();
|
||||
expect(find.text('assets/logo.bin'), findsOneWidget);
|
||||
expect(find.textContaining('changed files match'), findsNothing);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'opening a file shows the rendered patch and copies exact bytes',
|
||||
(tester) async {
|
||||
final calls = <MethodCall>[];
|
||||
TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(SystemChannels.platform, (call) async {
|
||||
if (call.method == 'Clipboard.setData') calls.add(call);
|
||||
return null;
|
||||
});
|
||||
addTearDown(
|
||||
() => TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger
|
||||
.setMockMethodCallHandler(SystemChannels.platform, null),
|
||||
);
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
ChangesViewer(
|
||||
steps: [
|
||||
stepFixture(
|
||||
fileChanges: captureFixture(
|
||||
files: [
|
||||
fileChangeFixture(
|
||||
path: 'lib/feature.dart',
|
||||
patch: multiHunkPatch,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
await tester.tap(find.byKey(const ValueKey('change-1-lib/feature.dart')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(Dialog), findsOneWidget);
|
||||
expect(find.text('Rendered'), findsOneWidget);
|
||||
expect(find.text('Raw patch'), findsOneWidget);
|
||||
final rendered = tester
|
||||
.widgetList<RichText>(find.byType(RichText))
|
||||
.map((rich) => rich.text.toPlainText())
|
||||
.join('\n');
|
||||
expect(rendered, contains('+ new line'));
|
||||
expect(rendered, contains('- old line'));
|
||||
expect(rendered, contains('@@ -20,3 +21,2 @@'));
|
||||
|
||||
await tester.tap(find.text('Raw patch'));
|
||||
await tester.pumpAndSettle();
|
||||
final raw = tester.widget<Text>(find.text(multiHunkPatch));
|
||||
expect(raw.data, multiHunkPatch);
|
||||
expect(raw.softWrap, isFalse);
|
||||
|
||||
await tester.tap(find.text('Copy patch'));
|
||||
await tester.pump();
|
||||
expect(calls, hasLength(1));
|
||||
expect(calls.single.arguments, {'text': multiHunkPatch});
|
||||
expect(find.text('Copied'), findsOneWidget);
|
||||
|
||||
await tester.tap(find.byTooltip('Close diff'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.byType(Dialog), findsNothing);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('binary, truncated and mode-only entries explain the missing diff', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
SingleChildScrollView(
|
||||
child: Column(
|
||||
children: [
|
||||
SizedBox(
|
||||
height: 300,
|
||||
child: FileDiffViewer(
|
||||
file: FileChange(
|
||||
path: 'assets/logo.bin',
|
||||
kind: ChangeKind.modified,
|
||||
binary: true,
|
||||
),
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
height: 300,
|
||||
child: FileDiffViewer(
|
||||
file: FileChange(
|
||||
path: 'logs/build.log',
|
||||
kind: ChangeKind.modified,
|
||||
patch: '@@ -1 +1 @@\n-a\n+b',
|
||||
truncated: true,
|
||||
),
|
||||
),
|
||||
),
|
||||
SizedBox(
|
||||
height: 300,
|
||||
child: FileDiffViewer(
|
||||
file: FileChange(
|
||||
path: 'scripts/run.sh',
|
||||
kind: ChangeKind.modified,
|
||||
beforeMode: '0644',
|
||||
afterMode: '0755',
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(find.text(binaryDiffMessage), findsOneWidget);
|
||||
expect(find.text(truncatedPatchNote), findsOneWidget);
|
||||
expect(
|
||||
find.text(
|
||||
"Only the file's mode changed (0644→0755); the server recorded no text "
|
||||
'diff.',
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
final copyButtons = <TextButton>[];
|
||||
for (var index = 0; index < 3; index++) {
|
||||
final button = find
|
||||
.ancestor(
|
||||
of: find.text('Copy patch').at(index),
|
||||
matching: find.byWidgetPredicate((widget) => widget is TextButton),
|
||||
)
|
||||
.first;
|
||||
copyButtons.add(tester.widget<TextButton>(button));
|
||||
}
|
||||
// Binary and mode-only have nothing to copy; the truncated patch still can.
|
||||
expect(
|
||||
copyButtons.where((button) => button.onPressed == null),
|
||||
hasLength(2),
|
||||
);
|
||||
expect(
|
||||
copyButtons.where((button) => button.onPressed != null),
|
||||
hasLength(1),
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets(
|
||||
'Cupertino uses native list tiles, search field and segmented control',
|
||||
(tester) async {
|
||||
await tester.pumpWidget(
|
||||
cupertinoHost(
|
||||
ChangesViewer(
|
||||
steps: [
|
||||
stepFixture(
|
||||
fileChanges: captureFixture(
|
||||
files: [
|
||||
fileChangeFixture(
|
||||
path: 'lib/feature.dart',
|
||||
patch: multiHunkPatch,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
expect(find.byType(CupertinoListTile), findsOneWidget);
|
||||
expect(find.byType(CupertinoSearchTextField), findsOneWidget);
|
||||
expect(find.byType(TextField), findsNothing);
|
||||
|
||||
await tester.tap(find.byKey(const ValueKey('change-1-lib/feature.dart')));
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
find.byType(CupertinoSlidingSegmentedControl<DiffForm>),
|
||||
findsOneWidget,
|
||||
);
|
||||
expect(find.text('Rendered'), findsOneWidget);
|
||||
expect(find.text('Raw patch'), findsOneWidget);
|
||||
|
||||
await tester.tap(find.byIcon(CupertinoIcons.xmark));
|
||||
await tester.pumpAndSettle();
|
||||
expect(
|
||||
find.byType(CupertinoSlidingSegmentedControl<DiffForm>),
|
||||
findsNothing,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('narrow viewport and large text keep every control reachable', (
|
||||
tester,
|
||||
) async {
|
||||
tester.view.physicalSize = const Size(320, 720);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.reset);
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
ChangesViewer(
|
||||
steps: [
|
||||
stepFixture(
|
||||
fileChanges: captureFixture(
|
||||
files: [
|
||||
fileChangeFixture(
|
||||
path: 'lib/a_rather_long_feature_file_name.dart',
|
||||
patch: multiHunkPatch,
|
||||
),
|
||||
fileChangeFixture(path: 'assets/logo.bin', binary: true),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
scaler: const TextScaler.linear(2),
|
||||
),
|
||||
);
|
||||
expect(tester.takeException(), isNull);
|
||||
expect(
|
||||
find.text('lib/a_rather_long_feature_file_name.dart'),
|
||||
findsOneWidget,
|
||||
);
|
||||
|
||||
// The viewer itself at the same narrow width and 2x text: every action
|
||||
// stays on screen and the patch body scrolls instead of overflowing.
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
FileDiffViewer(
|
||||
file: FileChange(
|
||||
path: 'lib/a_rather_long_feature_file_name.dart',
|
||||
kind: ChangeKind.modified,
|
||||
patch: multiHunkPatch,
|
||||
),
|
||||
),
|
||||
scaler: const TextScaler.linear(2),
|
||||
),
|
||||
);
|
||||
expect(tester.takeException(), isNull);
|
||||
expect(find.text('Rendered'), findsOneWidget);
|
||||
expect(find.text('Copy patch'), findsOneWidget);
|
||||
expect(find.byTooltip('Close diff'), findsOneWidget);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/changes/changes.dart';
|
||||
import 'package:pipelines_app/features/changes/widgets/change_style.dart';
|
||||
|
||||
import 'fixtures.dart';
|
||||
import 'widget_hosts.dart';
|
||||
|
||||
/// The patch has one short context line and one much longer added line, so a
|
||||
/// text-width tint and a full-hunk-width tint are visibly different sizes.
|
||||
const _raggedPatch =
|
||||
'@@ -1,4 +1,4 @@\n'
|
||||
' short\n'
|
||||
'+this added line is much longer than every other recorded line here\n'
|
||||
'-x\n'
|
||||
' tail\n';
|
||||
|
||||
void main() {
|
||||
test(
|
||||
'patch typography preserves the native host style without overrides',
|
||||
() {
|
||||
const native = TextStyle(fontSize: 19, fontFamily: 'host-font');
|
||||
expect(nativeDiffText(native), same(native));
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets(
|
||||
'light and dark themes give additions and removals distinct hues',
|
||||
(tester) async {
|
||||
for (final brightness in [Brightness.light, Brightness.dark]) {
|
||||
await tester.pumpWidget(
|
||||
materialHost(const SizedBox.shrink(), brightness: brightness),
|
||||
);
|
||||
final context = tester.element(find.byType(Scaffold));
|
||||
final add = diffLineColors(context, ChangeLineKind.add);
|
||||
final remove = diffLineColors(context, ChangeLineKind.remove);
|
||||
expect(add.background, isNull);
|
||||
expect(remove.background, isNull);
|
||||
expect(add.text, isNot(remove.text), reason: '$brightness text');
|
||||
expect(add.text, Theme.of(context).colorScheme.primary);
|
||||
expect(remove.text, Theme.of(context).colorScheme.error);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
testWidgets('every diff line shares the hunk width, not its own text width', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
SizedBox(
|
||||
height: 400,
|
||||
child: FileDiffViewer(
|
||||
file: FileChange(
|
||||
path: 'lib/ragged.dart',
|
||||
kind: ChangeKind.modified,
|
||||
patch: _raggedPatch,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final widths = [
|
||||
for (var index = 0; index < 4; index++)
|
||||
tester.getSize(find.byKey(ValueKey('diff-line-$index'))).width,
|
||||
];
|
||||
for (final width in widths) {
|
||||
expect(width, closeTo(widths.first, 0.01));
|
||||
}
|
||||
// The widest recorded line sets the hunk width, well beyond a short line.
|
||||
expect(widths.first, greaterThan(300));
|
||||
});
|
||||
|
||||
testWidgets('the stat line colours additions and removals apart', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
SizedBox(
|
||||
height: 400,
|
||||
child: FileDiffViewer(
|
||||
file: FileChange(
|
||||
path: 'lib/feature.dart',
|
||||
kind: ChangeKind.modified,
|
||||
patch: multiHunkPatch,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.pumpAndSettle();
|
||||
final stat = tester.widgetList<RichText>(find.byType(RichText)).firstWhere((
|
||||
rich,
|
||||
) {
|
||||
final span = rich.text;
|
||||
return span is TextSpan &&
|
||||
span.children != null &&
|
||||
span.toPlainText() == '+2 -2';
|
||||
});
|
||||
final root = (stat.text as TextSpan).children!.single as TextSpan;
|
||||
final spans = root.children!.cast<TextSpan>();
|
||||
final added = spans.firstWhere((span) => span.text == '+2');
|
||||
final removed = spans.firstWhere((span) => span.text == '-2');
|
||||
expect(added.style!.color, isNot(removed.style!.color));
|
||||
});
|
||||
|
||||
testWidgets('the raw view scrolls long lines instead of wrapping them', (
|
||||
tester,
|
||||
) async {
|
||||
await tester.pumpWidget(
|
||||
materialHost(
|
||||
SizedBox(
|
||||
height: 400,
|
||||
child: FileDiffViewer(
|
||||
file: FileChange(
|
||||
path: 'lib/feature.dart',
|
||||
kind: ChangeKind.modified,
|
||||
patch: multiHunkPatch,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.tap(find.text('Raw patch'));
|
||||
await tester.pumpAndSettle();
|
||||
expect(find.text(multiHunkPatch), findsOneWidget);
|
||||
expect(
|
||||
find.ancestor(
|
||||
of: find.text(multiHunkPatch),
|
||||
matching: find.byWidgetPredicate(
|
||||
(widget) =>
|
||||
widget is SingleChildScrollView &&
|
||||
widget.scrollDirection == Axis.horizontal,
|
||||
),
|
||||
),
|
||||
findsOneWidget,
|
||||
);
|
||||
});
|
||||
|
||||
testWidgets('a Cupertino row wraps its recorded path instead of clipping it', (
|
||||
tester,
|
||||
) async {
|
||||
tester.view.physicalSize = const Size(320, 720);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.reset);
|
||||
const path =
|
||||
'lib/features/changes/domain/a_rather_long_unified_patch_file_name.dart';
|
||||
await tester.pumpWidget(
|
||||
cupertinoHost(
|
||||
ChangesViewer(
|
||||
steps: [
|
||||
stepFixture(
|
||||
fileChanges: captureFixture(
|
||||
files: [fileChangeFixture(path: path, patch: multiHunkPatch)],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
final rich = tester
|
||||
.widgetList<RichText>(find.byType(RichText))
|
||||
.firstWhere((widget) => widget.text.toPlainText() == path);
|
||||
// CupertinoListTile caps a title at one ellipsized line; the row must lift
|
||||
// that cap so the filename stays visible.
|
||||
expect(rich.maxLines, isNull);
|
||||
expect(rich.overflow, TextOverflow.visible);
|
||||
expect(tester.getSize(find.text(path)).height, greaterThan(30));
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
|
||||
testWidgets('a Cupertino phone dialog is inset from the screen edge', (
|
||||
tester,
|
||||
) async {
|
||||
tester.view.physicalSize = const Size(390, 844);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.reset);
|
||||
await tester.pumpWidget(
|
||||
cupertinoHost(
|
||||
ChangesViewer(
|
||||
steps: [
|
||||
stepFixture(
|
||||
fileChanges: captureFixture(
|
||||
files: [
|
||||
fileChangeFixture(
|
||||
path: 'lib/feature.dart',
|
||||
patch: multiHunkPatch,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
await tester.tap(find.byKey(const ValueKey('change-1-lib/feature.dart')));
|
||||
await tester.pumpAndSettle();
|
||||
final rect = tester.getRect(find.byType(CupertinoPopupSurface));
|
||||
expect(rect.width, lessThanOrEqualTo(390 - 24));
|
||||
expect(rect.left, greaterThan(8));
|
||||
expect(rect.right, lessThan(382));
|
||||
expect(tester.takeException(), isNull);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
|
||||
/// Server-shaped fixtures shared by the Changes tests. These mirror the JSON
|
||||
/// `internal/protocol.StageFileChanges` / `FileChange` writer, including quoted
|
||||
/// unified headers and optional fields.
|
||||
const multiHunkPatch =
|
||||
'--- "a/lib/feature.dart"\n'
|
||||
'+++ "b/lib/feature.dart"\n'
|
||||
'@@ -1,4 +1,5 @@\n'
|
||||
' context one\n'
|
||||
'-old line\n'
|
||||
'+new line\n'
|
||||
'+added line\n'
|
||||
' context two\n'
|
||||
' context three\n'
|
||||
'@@ -20,3 +21,2 @@\n'
|
||||
' context twenty\n'
|
||||
'-removed line\n'
|
||||
' context twenty-two\n';
|
||||
|
||||
JsonMap fileChangeFixture({
|
||||
required String path,
|
||||
String kind = 'modified',
|
||||
String patch = '',
|
||||
bool binary = false,
|
||||
bool truncated = false,
|
||||
String? beforeMode,
|
||||
String? afterMode,
|
||||
}) => {
|
||||
'path': path,
|
||||
'kind': kind,
|
||||
'patch': patch,
|
||||
if (binary) 'binary': true,
|
||||
if (truncated) 'truncated': true,
|
||||
'before_mode': ?beforeMode,
|
||||
'after_mode': ?afterMode,
|
||||
};
|
||||
|
||||
JsonMap captureFixture({
|
||||
String status = 'complete',
|
||||
List<JsonMap> files = const [],
|
||||
int skipped = 0,
|
||||
int omitted = 0,
|
||||
String diagnostic = '',
|
||||
String scope = 'Git tracked and nonignored files in the run directory',
|
||||
}) => {
|
||||
'status': status,
|
||||
'scope': scope,
|
||||
'files': files,
|
||||
'skipped': skipped,
|
||||
'omitted': omitted,
|
||||
'diagnostic': diagnostic,
|
||||
};
|
||||
|
||||
JsonMap stepFixture({
|
||||
String stage = 'implementer',
|
||||
int sequence = 1,
|
||||
String status = 'completed',
|
||||
JsonMap? fileChanges,
|
||||
int? visit,
|
||||
}) => {
|
||||
'stage': stage,
|
||||
'sequence': sequence,
|
||||
'status': status,
|
||||
'file_changes': fileChanges,
|
||||
if (visit != null) 'control': {'visit': visit},
|
||||
};
|
||||
@@ -0,0 +1,624 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/changes/domain/change_capture.dart';
|
||||
import 'package:pipelines_app/features/changes/domain/change_kind.dart';
|
||||
import 'package:pipelines_app/features/changes/domain/change_wording.dart';
|
||||
import 'package:pipelines_app/features/changes/domain/file_change.dart';
|
||||
import 'package:pipelines_app/features/changes/domain/run_changes.dart';
|
||||
|
||||
import 'fixtures.dart';
|
||||
|
||||
// Thin map-override wrappers over the shared server-shaped fixtures; the
|
||||
// canonical field shapes live in fixtures.dart.
|
||||
JsonMap file(JsonMap overrides) => {
|
||||
...fileChangeFixture(path: 'a.txt'),
|
||||
...overrides,
|
||||
};
|
||||
|
||||
JsonMap step(JsonMap overrides) => {...stepFixture(stage: 's'), ...overrides};
|
||||
|
||||
JsonMap capture({
|
||||
String status = 'complete',
|
||||
List<JsonMap> files = const [],
|
||||
int skipped = 0,
|
||||
int omitted = 0,
|
||||
String diagnostic = '',
|
||||
String scope = 'Git tracked and nonignored files in the run directory',
|
||||
}) => captureFixture(
|
||||
status: status,
|
||||
files: files,
|
||||
skipped: skipped,
|
||||
omitted: omitted,
|
||||
diagnostic: diagnostic,
|
||||
scope: scope,
|
||||
);
|
||||
|
||||
void main() {
|
||||
test(
|
||||
'a null capture is pending while running/waiting, otherwise missing',
|
||||
() {
|
||||
final running = runChanges([
|
||||
step({'status': 'running'}),
|
||||
step({'status': 'waiting'}),
|
||||
]);
|
||||
expect(running.pending, isTrue);
|
||||
expect(running.missingCaptures, 0);
|
||||
expect(running.stepsWithChanges, 0);
|
||||
|
||||
final missing = runChanges([
|
||||
step({'status': 'completed'}),
|
||||
step({'status': 'failed'}),
|
||||
]);
|
||||
expect(missing.pending, isFalse);
|
||||
expect(missing.missingCaptures, 2);
|
||||
expect(missing.stepsWithChanges, 0);
|
||||
},
|
||||
);
|
||||
|
||||
test('a non-null malformed capture is unavailable, not a no-change', () {
|
||||
final changes = runChanges([
|
||||
step({'file_changes': 'not-an-object'}),
|
||||
]);
|
||||
expect(changes.stepsWithChanges, 1);
|
||||
expect(changes.missingCaptures, 0);
|
||||
expect(changes.unavailable, isTrue);
|
||||
expect(changes.files, isEmpty);
|
||||
expect(runChangesHeader(changes), 'Changes · capture unavailable');
|
||||
expect(runChangesNote(changes), malformedCaptureDetail);
|
||||
});
|
||||
|
||||
test('a present capture with no files is a captured no-change', () {
|
||||
final changes = runChanges([
|
||||
step({'stage': 'a', 'file_changes': capture()}),
|
||||
]);
|
||||
expect(changes.stepsWithChanges, 1);
|
||||
expect(changes.files, isEmpty);
|
||||
expect(changes.partial, isFalse);
|
||||
expect(runChangesHeader(changes), 'Changes · no changes observed');
|
||||
expect(noChangeDetail(changes), emptyCaptureDetail);
|
||||
});
|
||||
|
||||
test('a later visit wins the kind, including an unrecognised later kind', () {
|
||||
final changes = runChanges([
|
||||
step({
|
||||
'stage': 'a',
|
||||
'file_changes': capture(
|
||||
files: [
|
||||
file({'path': 'x', 'kind': 'modified'}),
|
||||
],
|
||||
),
|
||||
}),
|
||||
step({
|
||||
'stage': 'b',
|
||||
'file_changes': capture(
|
||||
files: [
|
||||
file({'path': 'x', 'kind': 'added'}),
|
||||
],
|
||||
),
|
||||
}),
|
||||
]);
|
||||
expect(changes.files.single.kind, ChangeKind.added);
|
||||
expect(changes.files.single.steps, ['a', 'b']);
|
||||
|
||||
final unknown = runChanges([
|
||||
step({
|
||||
'stage': 'a',
|
||||
'file_changes': capture(
|
||||
files: [
|
||||
file({'path': 'x', 'kind': 'added'}),
|
||||
],
|
||||
),
|
||||
}),
|
||||
step({
|
||||
'stage': 'b',
|
||||
'file_changes': capture(
|
||||
files: [
|
||||
file({'path': 'x', 'kind': 'copied'}),
|
||||
],
|
||||
),
|
||||
}),
|
||||
]);
|
||||
expect(unknown.files.single.kind, ChangeKind.other);
|
||||
});
|
||||
|
||||
test('three visits report only the last visit facts', () {
|
||||
final changes = runChanges([
|
||||
step({
|
||||
'stage': 'a',
|
||||
'sequence': 1,
|
||||
'file_changes': capture(
|
||||
files: [
|
||||
file({
|
||||
'path': 'x',
|
||||
'kind': 'modified',
|
||||
'patch': '@@ -1 +1 @@\n-old\n+one',
|
||||
'before_mode': '0644',
|
||||
'after_mode': '0644',
|
||||
}),
|
||||
],
|
||||
),
|
||||
}),
|
||||
step({
|
||||
'stage': 'b',
|
||||
'sequence': 2,
|
||||
'file_changes': capture(
|
||||
files: [
|
||||
file({
|
||||
'path': 'x',
|
||||
'patch': '@@ -1 +1 @@\n-one\n+two',
|
||||
'before_mode': '0644',
|
||||
'after_mode': '0644',
|
||||
}),
|
||||
],
|
||||
),
|
||||
}),
|
||||
step({
|
||||
'stage': 'c',
|
||||
'sequence': 3,
|
||||
'file_changes': capture(
|
||||
files: [
|
||||
file({
|
||||
'path': 'x',
|
||||
'kind': 'added',
|
||||
'patch': '@@ -1 +2 @@\n-two\n+three\n+four',
|
||||
'before_mode': '0755',
|
||||
'after_mode': '0600',
|
||||
}),
|
||||
],
|
||||
),
|
||||
}),
|
||||
]);
|
||||
final entry = changes.files.single;
|
||||
expect(entry.kind, ChangeKind.added);
|
||||
expect(entry.added, 2);
|
||||
expect(entry.removed, 1);
|
||||
expect(entry.patch, '@@ -1 +2 @@\n-two\n+three\n+four');
|
||||
expect(entry.beforeMode, '0755');
|
||||
expect(entry.afterMode, '0600');
|
||||
expect(entry.modeChanged, isTrue);
|
||||
expect(entry.steps, ['a', 'b', 'c']);
|
||||
expect(changeRowMeta(entry), 'changed by a → b → c · mode 0755→0600');
|
||||
expect(changes.added, 2);
|
||||
expect(changes.removed, 1);
|
||||
});
|
||||
|
||||
test('later binary/truncated flags replace earlier rows', () {
|
||||
final changes = runChanges([
|
||||
step({
|
||||
'stage': 'a',
|
||||
'file_changes': capture(
|
||||
files: [
|
||||
file({
|
||||
'path': 'x',
|
||||
'patch': '@@ -1 +1 @@\n-old\n+new',
|
||||
'binary': true,
|
||||
'truncated': true,
|
||||
'before_mode': '0644',
|
||||
'after_mode': '0755',
|
||||
}),
|
||||
],
|
||||
),
|
||||
}),
|
||||
step({
|
||||
'stage': 'b',
|
||||
'file_changes': capture(
|
||||
files: [
|
||||
file({
|
||||
'path': 'x',
|
||||
'patch': '',
|
||||
'binary': false,
|
||||
'truncated': false,
|
||||
'before_mode': '0755',
|
||||
'after_mode': '0755',
|
||||
}),
|
||||
],
|
||||
),
|
||||
}),
|
||||
]);
|
||||
final entry = changes.files.single;
|
||||
expect(entry.binary, isFalse);
|
||||
expect(entry.truncated, isFalse);
|
||||
expect(entry.patch, isNull);
|
||||
expect(entry.modeChanged, isFalse);
|
||||
expect(entry.added, 0);
|
||||
expect(entry.removed, 0);
|
||||
// A truncated row anywhere in the run still makes the capture partial.
|
||||
expect(changes.partial, isTrue);
|
||||
});
|
||||
|
||||
test('paths keep first-seen order while ordering follows sequence', () {
|
||||
final changes = runChanges([
|
||||
step({
|
||||
'stage': 'c',
|
||||
'sequence': 3,
|
||||
'file_changes': capture(
|
||||
files: [
|
||||
file({'path': 'y'}),
|
||||
],
|
||||
),
|
||||
}),
|
||||
step({
|
||||
'stage': 'a',
|
||||
'sequence': 1,
|
||||
'file_changes': capture(
|
||||
files: [
|
||||
file({'path': 'y'}),
|
||||
],
|
||||
),
|
||||
}),
|
||||
step({
|
||||
'stage': 'b',
|
||||
'sequence': 2,
|
||||
'file_changes': capture(
|
||||
files: [
|
||||
file({'path': 'x'}),
|
||||
],
|
||||
),
|
||||
}),
|
||||
]);
|
||||
expect(changes.files.map((entry) => entry.path), ['y', 'x']);
|
||||
expect(changes.files.first.kind, ChangeKind.modified);
|
||||
expect(changes.files.first.steps, ['a', 'c']);
|
||||
expect(changeRowMeta(changes.files.first), 'changed by a → c');
|
||||
});
|
||||
|
||||
test(
|
||||
'stage names are deduped in run order; blank names/paths are handled',
|
||||
() {
|
||||
final changes = runChanges([
|
||||
step({
|
||||
'stage': 'implementer',
|
||||
'file_changes': capture(
|
||||
files: [
|
||||
file({'path': 'x'}),
|
||||
],
|
||||
),
|
||||
}),
|
||||
step({
|
||||
'stage': 'reviewer',
|
||||
'file_changes': capture(
|
||||
files: [
|
||||
file({'path': 'x'}),
|
||||
],
|
||||
),
|
||||
}),
|
||||
step({
|
||||
'stage': 'implementer',
|
||||
'file_changes': capture(
|
||||
files: [
|
||||
file({'path': 'x'}),
|
||||
file({'path': ' '}),
|
||||
],
|
||||
),
|
||||
}),
|
||||
]);
|
||||
expect(changes.files.single.steps, ['implementer', 'reviewer']);
|
||||
|
||||
final blank = runChanges([
|
||||
step({
|
||||
'stage': ' ',
|
||||
'file_changes': capture(
|
||||
files: [
|
||||
file({'path': 'x'}),
|
||||
],
|
||||
),
|
||||
}),
|
||||
]);
|
||||
expect(blank.files.single.steps, ['stage']);
|
||||
},
|
||||
);
|
||||
|
||||
test('partial is OR-ed from status, a truncated file or omitted count', () {
|
||||
expect(
|
||||
runChanges([
|
||||
step({'file_changes': capture(status: 'partial')}),
|
||||
]).partial,
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
runChanges([
|
||||
step({
|
||||
'file_changes': capture(
|
||||
files: [
|
||||
file({'truncated': true}),
|
||||
],
|
||||
),
|
||||
}),
|
||||
]).partial,
|
||||
isTrue,
|
||||
);
|
||||
expect(
|
||||
runChanges([
|
||||
step({'file_changes': capture(omitted: 2)}),
|
||||
]).partial,
|
||||
isTrue,
|
||||
);
|
||||
});
|
||||
|
||||
test('diagnostics from several captures are deduped and joined', () {
|
||||
final changes = runChanges([
|
||||
step({'file_changes': capture(status: 'partial', diagnostic: 'why one')}),
|
||||
step({'file_changes': capture(status: 'partial', diagnostic: 'why one')}),
|
||||
step({'file_changes': capture(status: 'partial', diagnostic: 'why two')}),
|
||||
]);
|
||||
expect(changes.diagnostic, 'why one why two');
|
||||
expect(changes.stepsWithChanges, 3);
|
||||
});
|
||||
|
||||
test(
|
||||
'stageCaptures keeps every visit, including a missing one, in order',
|
||||
() {
|
||||
final visits = stageCaptures([
|
||||
step({'stage': 'reviewer', 'sequence': 2, 'file_changes': capture()}),
|
||||
step({'stage': 'implementer', 'sequence': 1, 'file_changes': null}),
|
||||
]);
|
||||
expect(visits.map((visit) => visit.stage), ['implementer', 'reviewer']);
|
||||
expect(visits.first.missing, isTrue);
|
||||
expect(visits.last.capture?.status, 'complete');
|
||||
},
|
||||
);
|
||||
|
||||
test(
|
||||
'visit is control.visit when positive, else the position in its stage',
|
||||
() {
|
||||
final visits = stageCaptures([
|
||||
stepFixture(stage: 'implementer', sequence: 1),
|
||||
stepFixture(stage: 'reviewer', sequence: 2),
|
||||
stepFixture(stage: 'implementer', sequence: 3),
|
||||
stepFixture(stage: 'implementer', sequence: 4, visit: 7),
|
||||
stepFixture(stage: 'reviewer', sequence: 5, visit: 0),
|
||||
]);
|
||||
expect(visits.map((visit) => '${visit.stage}:${visit.visit}'), [
|
||||
'implementer:1',
|
||||
'reviewer:1',
|
||||
'implementer:2',
|
||||
'implementer:7',
|
||||
'reviewer:2',
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
test('equal sequences keep their input order for stage positions', () {
|
||||
final visits = stageCaptures([
|
||||
stepFixture(stage: 's', sequence: 1),
|
||||
stepFixture(stage: 's', sequence: 1),
|
||||
stepFixture(stage: 'other', sequence: 0),
|
||||
]);
|
||||
expect(visits.map((visit) => '${visit.stage}:${visit.visit}'), [
|
||||
'other:1',
|
||||
's:1',
|
||||
's:2',
|
||||
]);
|
||||
});
|
||||
|
||||
test('capture parsing keeps scope, counters and diagnostic', () {
|
||||
final parsed = ChangeCapture.fromJson(
|
||||
capture(
|
||||
status: 'partial',
|
||||
skipped: 2,
|
||||
omitted: 1,
|
||||
diagnostic: 'Excluded protected files.',
|
||||
files: [
|
||||
file({'path': 'x'}),
|
||||
file({'path': ''}),
|
||||
],
|
||||
),
|
||||
);
|
||||
expect(parsed.scope, contains('Git tracked'));
|
||||
expect(parsed.skipped, 2);
|
||||
expect(parsed.omitted, 1);
|
||||
expect(parsed.diagnostic, 'Excluded protected files.');
|
||||
expect(parsed.files.map((entry) => entry.path), ['x']);
|
||||
expect(
|
||||
fileChangesSummary(parsed),
|
||||
'partial (1 files), 2 skipped, 1 omitted · Excluded protected files.',
|
||||
);
|
||||
});
|
||||
|
||||
test('header covers every empty-capture variant', () {
|
||||
expect(
|
||||
runChangesHeader(_run(unavailable: true, files: const [])),
|
||||
'Changes · capture unavailable',
|
||||
);
|
||||
expect(runChangesHeader(_run(pending: true)), 'Changes · capture pending');
|
||||
expect(
|
||||
runChangesHeader(_run(partial: true, stepsWithChanges: 1)),
|
||||
'Changes · partial capture',
|
||||
);
|
||||
expect(runChangesHeader(_run()), 'Changes · not recorded for this run');
|
||||
expect(
|
||||
runChangesHeader(_run(stepsWithChanges: 1, missingCaptures: 1)),
|
||||
'Changes · capture incomplete',
|
||||
);
|
||||
expect(
|
||||
runChangesHeader(_run(stepsWithChanges: 2)),
|
||||
'Changes · no changes observed',
|
||||
);
|
||||
});
|
||||
|
||||
test('note spells partial, missing and unavailable wording', () {
|
||||
expect(
|
||||
runChangesNote(_run(unavailable: true)),
|
||||
'The workspace snapshot could not be compared; the changes below may be '
|
||||
'incomplete.',
|
||||
);
|
||||
expect(
|
||||
runChangesNote(_run(unavailable: true, diagnostic: 'server says so')),
|
||||
'server says so',
|
||||
);
|
||||
expect(
|
||||
runChangesNote(
|
||||
_run(
|
||||
partial: true,
|
||||
skipped: 8,
|
||||
diagnostic: 'Excluded protected files.',
|
||||
missingCaptures: 1,
|
||||
),
|
||||
),
|
||||
'Partial capture: some changes may be missing. (8 files skipped) '
|
||||
'Excluded protected files. Missing capture: 1 stage did not record '
|
||||
'changes.',
|
||||
);
|
||||
expect(
|
||||
runChangesNote(
|
||||
_run(
|
||||
partial: true,
|
||||
omitted: 3,
|
||||
missingCaptures: 2,
|
||||
files: [
|
||||
FileChange(path: 'x', kind: ChangeKind.modified, truncated: true),
|
||||
FileChange(path: 'y', kind: ChangeKind.modified, truncated: true),
|
||||
],
|
||||
),
|
||||
),
|
||||
'Partial capture: some changes may be missing. (3 omitted, 2 truncated) '
|
||||
'Missing capture: 2 stages did not record changes.',
|
||||
);
|
||||
expect(runChangesNote(_run()), '');
|
||||
});
|
||||
|
||||
test('tags, row meta and unavailable reasons are exact', () {
|
||||
final binary = FileChange(
|
||||
path: 'x',
|
||||
kind: ChangeKind.modified,
|
||||
binary: true,
|
||||
truncated: false,
|
||||
beforeMode: '0644',
|
||||
afterMode: '0755',
|
||||
steps: const ['a'],
|
||||
);
|
||||
expect(changeEntryTags(binary), ['binary']);
|
||||
expect(changeRowMeta(binary), 'changed by a · binary');
|
||||
|
||||
final truncated = FileChange(
|
||||
path: 'x',
|
||||
kind: ChangeKind.modified,
|
||||
truncated: true,
|
||||
steps: const ['a', 'b'],
|
||||
);
|
||||
expect(changeEntryTags(truncated), ['truncated']);
|
||||
expect(changeRowMeta(truncated), 'changed by a → b · truncated');
|
||||
|
||||
final modeOnly = FileChange(
|
||||
path: 'x',
|
||||
kind: ChangeKind.modified,
|
||||
beforeMode: '0644',
|
||||
afterMode: '0755',
|
||||
steps: const ['a'],
|
||||
);
|
||||
expect(changeEntryTags(modeOnly), ['mode change']);
|
||||
expect(
|
||||
changeRowMeta(modeOnly),
|
||||
'changed by a · mode change · mode 0644→0755',
|
||||
);
|
||||
expect(
|
||||
patchUnavailableReason(modeOnly),
|
||||
"Only the file's mode changed (0644→0755); the server recorded no text "
|
||||
'diff.',
|
||||
);
|
||||
expect(
|
||||
patchUnavailableReason(truncated),
|
||||
"The server truncated this file's patch at its capture limit; no diff "
|
||||
'text was recorded.',
|
||||
);
|
||||
expect(
|
||||
patchUnavailableReason(FileChange(path: 'x', kind: ChangeKind.modified)),
|
||||
'The server recorded this change without a patch.',
|
||||
);
|
||||
});
|
||||
|
||||
test('changed filenames filter is case-insensitive and preserves order', () {
|
||||
final files = [
|
||||
FileChange(path: 'lib/Changes_Viewer.dart', kind: ChangeKind.modified),
|
||||
FileChange(path: 'docs/notes.md', kind: ChangeKind.added),
|
||||
FileChange(path: 'lib/file_diff_viewer.dart', kind: ChangeKind.added),
|
||||
];
|
||||
expect(filterFileChanges(files, 'VIEWER').map((file) => file.path), [
|
||||
'lib/Changes_Viewer.dart',
|
||||
'lib/file_diff_viewer.dart',
|
||||
]);
|
||||
expect(filterFileChanges(files, ' '), files);
|
||||
expect(filterFileChanges(files, 'absent'), isEmpty);
|
||||
});
|
||||
|
||||
test('a real-shaped partial run aggregates once and keeps the gap visible', () {
|
||||
const diagnostic =
|
||||
'Excluded protected, symlinked, oversized or unreadable files; this is '
|
||||
'not a complete workspace diff.';
|
||||
final changes = runChanges([
|
||||
step({
|
||||
'stage': 'implementer',
|
||||
'sequence': 1,
|
||||
'file_changes': capture(
|
||||
status: 'partial',
|
||||
skipped: 2,
|
||||
diagnostic: diagnostic,
|
||||
files: [
|
||||
file({
|
||||
'path': 'docs/notes.md',
|
||||
'kind': 'added',
|
||||
'patch': '@@ -0,0 +1 @@\n+notes',
|
||||
}),
|
||||
file({
|
||||
'path': 'internal/server/retry_test.go',
|
||||
'patch': '@@ -1 +1 @@\n-old\n+new',
|
||||
}),
|
||||
],
|
||||
),
|
||||
}),
|
||||
step({
|
||||
'stage': 'reviewer',
|
||||
'sequence': 2,
|
||||
'file_changes': capture(
|
||||
status: 'partial',
|
||||
skipped: 2,
|
||||
diagnostic: diagnostic,
|
||||
),
|
||||
}),
|
||||
step({'stage': 'ui_reviewer', 'sequence': 3}),
|
||||
]);
|
||||
expect(changes.files, hasLength(2));
|
||||
expect(changes.stepsWithChanges, 2);
|
||||
expect(changes.missingCaptures, 1);
|
||||
expect(changes.partial, isTrue);
|
||||
expect(changes.skipped, 4);
|
||||
expect(
|
||||
runChangesHeader(changes),
|
||||
'2 files changed · +2 -1 · partial capture',
|
||||
);
|
||||
expect(
|
||||
runChangesNote(changes),
|
||||
'Partial capture: some changes may be missing. (4 files skipped) '
|
||||
'$diagnostic Missing capture: 1 stage did not record changes.',
|
||||
);
|
||||
expect(
|
||||
runChangesHeader(_run(unavailable: true, files: changes.files)),
|
||||
'Changes · capture unavailable',
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
RunChanges _run({
|
||||
List<FileChange> files = const [],
|
||||
bool partial = false,
|
||||
bool unavailable = false,
|
||||
bool pending = false,
|
||||
int stepsWithChanges = 0,
|
||||
int missingCaptures = 0,
|
||||
int skipped = 0,
|
||||
int omitted = 0,
|
||||
String diagnostic = '',
|
||||
}) => RunChanges(
|
||||
files: files,
|
||||
stepsWithChanges: stepsWithChanges,
|
||||
stepsPending: 0,
|
||||
added: files.fold(0, (sum, file) => sum + file.added),
|
||||
removed: files.fold(0, (sum, file) => sum + file.removed),
|
||||
partial: partial,
|
||||
unavailable: unavailable,
|
||||
pending: pending,
|
||||
missingCaptures: missingCaptures,
|
||||
skipped: skipped,
|
||||
omitted: omitted,
|
||||
diagnostic: diagnostic,
|
||||
);
|
||||
@@ -0,0 +1,176 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:pipelines_app/features/changes/domain/unified_patch.dart';
|
||||
|
||||
void main() {
|
||||
test('a blank or absent patch parses to an empty result', () {
|
||||
for (final blank in <dynamic>['', ' ', '\n', null]) {
|
||||
final parsed = parseUnifiedPatch(blank);
|
||||
expect(parsed.raw, '');
|
||||
expect(parsed.headerLines, isEmpty);
|
||||
expect(parsed.hunks, isEmpty);
|
||||
expect(parsed.added, 0);
|
||||
expect(parsed.removed, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test('a single hunk is numbered and counted', () {
|
||||
final patch = [
|
||||
'--- "a/x.txt"',
|
||||
'+++ "b/x.txt"',
|
||||
'@@ -1,3 +1,3 @@',
|
||||
' ctx',
|
||||
'-old',
|
||||
'+new',
|
||||
' tail',
|
||||
].join('\n');
|
||||
final parsed = parseUnifiedPatch(patch);
|
||||
expect(parsed.raw, patch);
|
||||
expect(parsed.headerLines, ['--- "a/x.txt"', '+++ "b/x.txt"']);
|
||||
expect(parsed.hunks, hasLength(1));
|
||||
final hunk = parsed.hunks.single;
|
||||
expect(hunk.header, '@@ -1,3 +1,3 @@');
|
||||
expect(
|
||||
[hunk.oldStart, hunk.oldCount, hunk.newStart, hunk.newCount],
|
||||
[1, 3, 1, 3],
|
||||
);
|
||||
expect(
|
||||
[
|
||||
for (final line in hunk.lines)
|
||||
[line.kind, line.text, line.oldLine, line.newLine],
|
||||
],
|
||||
[
|
||||
[ChangeLineKind.context, 'ctx', 1, 1],
|
||||
[ChangeLineKind.remove, 'old', 2, 0],
|
||||
[ChangeLineKind.add, 'new', 0, 2],
|
||||
[ChangeLineKind.context, 'tail', 3, 3],
|
||||
],
|
||||
);
|
||||
expect(parsed.added, 1);
|
||||
expect(parsed.removed, 1);
|
||||
});
|
||||
|
||||
test('a missing count defaults to 1', () {
|
||||
final hunk = parseUnifiedPatch('@@ -5 +7 @@\n-old\n+new').hunks.single;
|
||||
expect(
|
||||
[hunk.oldStart, hunk.oldCount, hunk.newStart, hunk.newCount],
|
||||
[5, 1, 7, 1],
|
||||
);
|
||||
});
|
||||
|
||||
test('a multi-hunk patch keeps each hunk header and its own numbering', () {
|
||||
final parsed = parseUnifiedPatch(
|
||||
[
|
||||
'--- "a/lib/x.dart"',
|
||||
'+++ "b/lib/x.dart"',
|
||||
'@@ -1,2 +1,3 @@',
|
||||
' one',
|
||||
'+two',
|
||||
' three',
|
||||
'@@ -40,3 +41,2 @@',
|
||||
' forty',
|
||||
'-forty-one',
|
||||
' forty-two',
|
||||
].join('\n'),
|
||||
);
|
||||
expect(parsed.hunks, hasLength(2));
|
||||
expect(parsed.hunks[0].lines.map((line) => line.newLine), [1, 2, 3]);
|
||||
expect(parsed.hunks[1].lines.map((line) => line.oldLine), [40, 41, 42]);
|
||||
expect(parsed.added, 1);
|
||||
expect(parsed.removed, 1);
|
||||
expect(parsed.headerLines, ['--- "a/lib/x.dart"', '+++ "b/lib/x.dart"']);
|
||||
});
|
||||
|
||||
test('a no-newline marker is shown verbatim and never numbered', () {
|
||||
final lines = parseUnifiedPatch(
|
||||
[
|
||||
'@@ -1 +1 @@',
|
||||
'-one',
|
||||
r'\ No newline at end of file',
|
||||
'+two',
|
||||
].join('\n'),
|
||||
).hunks.single.lines;
|
||||
expect(lines[1].noNewlineMarker, isTrue);
|
||||
expect(lines[1].text, r'\ No newline at end of file');
|
||||
expect(lines[1].oldLine, 0);
|
||||
expect(lines[1].newLine, 0);
|
||||
expect(lines[1].kind, ChangeLineKind.context);
|
||||
});
|
||||
|
||||
test('a second file header closes the current hunk', () {
|
||||
final parsed = parseUnifiedPatch(
|
||||
[
|
||||
'--- "a/x"',
|
||||
'+++ "b/x"',
|
||||
'@@ -1 +1 @@',
|
||||
'-old',
|
||||
'+new',
|
||||
'--- "a/y"',
|
||||
'+++ "b/y"',
|
||||
'@@ -1 +1 @@',
|
||||
'-alt',
|
||||
'+neu',
|
||||
].join('\n'),
|
||||
);
|
||||
expect(parsed.hunks, hasLength(2));
|
||||
expect(parsed.hunks[0].lines.map((line) => line.text), ['old', 'new']);
|
||||
expect(parsed.hunks[1].lines.map((line) => line.text), ['alt', 'neu']);
|
||||
expect(
|
||||
parsed.headerLines.where((line) => line.startsWith('--- ')),
|
||||
hasLength(2),
|
||||
);
|
||||
expect(parsed.added, 2);
|
||||
expect(parsed.removed, 2);
|
||||
});
|
||||
|
||||
test('metadata before a hunk is kept; a truncated tail is unnumbered', () {
|
||||
final parsed = parseUnifiedPatch(
|
||||
[
|
||||
'index abc..def 100644',
|
||||
'--- "a/x"',
|
||||
'+++ "b/x"',
|
||||
'@@ -1 +1 @@',
|
||||
'-old',
|
||||
'+new',
|
||||
'trailing trunc',
|
||||
].join('\n'),
|
||||
);
|
||||
expect(parsed.headerLines.first, 'index abc..def 100644');
|
||||
final tail = parsed.hunks.single.lines.last;
|
||||
expect(tail.kind, ChangeLineKind.context);
|
||||
expect(tail.text, 'trailing trunc');
|
||||
expect([tail.oldLine, tail.newLine], [0, 0]);
|
||||
});
|
||||
|
||||
test('a trailing newline becomes a numbered empty context line', () {
|
||||
final lines = parseUnifiedPatch('@@ -1 +1 @@\n ctx\n').hunks.single.lines;
|
||||
expect(lines, hasLength(2));
|
||||
expect([lines[1].text, lines[1].oldLine, lines[1].newLine], ['', 2, 2]);
|
||||
});
|
||||
|
||||
test('gutter width, gutter text, symbols and stat match the web wording', () {
|
||||
expect(
|
||||
gutterWidth(
|
||||
const PatchHunk(
|
||||
header: 'h',
|
||||
oldStart: 0,
|
||||
oldCount: 0,
|
||||
newStart: 0,
|
||||
newCount: 0,
|
||||
lines: [],
|
||||
),
|
||||
),
|
||||
1,
|
||||
);
|
||||
final hunk = parseUnifiedPatch('@@ -9,1 +12,1 @@\n-a\n+b').hunks.single;
|
||||
expect(gutterWidth(hunk), 2);
|
||||
expect(gutterText(0, 2), ' ');
|
||||
expect(gutterText(7, 2), ' 7');
|
||||
expect(diffLineSymbol(ChangeLineKind.add), '+');
|
||||
expect(diffLineSymbol(ChangeLineKind.remove), '-');
|
||||
expect(diffLineSymbol(ChangeLineKind.context), ' ');
|
||||
expect(changeStat(3, 2), '+3 -2');
|
||||
expect(changeStat(3, 0), '+3');
|
||||
expect(changeStat(0, 2), '-2');
|
||||
expect(changeStat(0, 0), '');
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// The two platform hosts the Changes widget tests share: Material for
|
||||
/// Android/desktop/web and Cupertino for iOS/macOS. They state the platform
|
||||
/// explicitly instead of mutating a global debug override.
|
||||
Widget materialHost(
|
||||
Widget child, {
|
||||
TextScaler scaler = TextScaler.noScaling,
|
||||
Brightness brightness = Brightness.light,
|
||||
}) {
|
||||
return MaterialApp(
|
||||
theme: ThemeData(brightness: brightness),
|
||||
builder: (context, app) => MediaQuery(
|
||||
data: MediaQuery.of(context).copyWith(textScaler: scaler),
|
||||
child: app!,
|
||||
),
|
||||
home: Scaffold(body: child),
|
||||
);
|
||||
}
|
||||
|
||||
Widget cupertinoHost(
|
||||
Widget child, {
|
||||
TextScaler scaler = TextScaler.noScaling,
|
||||
Brightness brightness = Brightness.light,
|
||||
}) {
|
||||
return CupertinoApp(
|
||||
theme: CupertinoThemeData(brightness: brightness),
|
||||
builder: (context, app) => Theme(
|
||||
// The real app selects Cupertino by platform; the test host states it
|
||||
// explicitly without changing a global debug override. The Theme wraps
|
||||
// the Navigator so dialogs opened later resolve the same platform.
|
||||
data: ThemeData(platform: TargetPlatform.iOS),
|
||||
child: MediaQuery(
|
||||
data: MediaQuery.of(context).copyWith(textScaler: scaler),
|
||||
child: app!,
|
||||
),
|
||||
),
|
||||
home: CupertinoPageScaffold(child: SafeArea(child: child)),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
// Real-browser evidence for the Changes viewer fixture.
|
||||
//
|
||||
// Usage (from app/):
|
||||
// flutter build web --target tool/changes_probe_entry.dart --output build/probe-web
|
||||
// node tool/changes_probe.mjs --root build/probe-web --out DIR
|
||||
//
|
||||
// Serves the fixture over loopback with an explicit text/html index, drives
|
||||
// headless Chrome through the Chrome DevTools Protocol, enables Flutter
|
||||
// semantics, clicks exact labels, verifies the body/labels change, copies the
|
||||
// raw patch and writes real PNG captures at phone and desktop widths.
|
||||
import { createServer } from 'node:http';
|
||||
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { once } from 'node:events';
|
||||
import { setTimeout as delay } from 'node:timers/promises';
|
||||
import { extname, join, resolve, sep } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
|
||||
const args = new Map();
|
||||
for (let i = 2; i < process.argv.length; i++) {
|
||||
const value = process.argv[i];
|
||||
if (value.startsWith('--')) args.set(value.slice(2), process.argv[++i]);
|
||||
}
|
||||
const root = resolve(args.get('root') ?? 'build/probe-web');
|
||||
const out = resolve(args.get('out') ?? 'build/changes-probe');
|
||||
const chromePath =
|
||||
process.env.CHROME_PATH ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
|
||||
await mkdir(out, { recursive: true });
|
||||
|
||||
const mime = {
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.js': 'text/javascript; charset=utf-8',
|
||||
'.mjs': 'text/javascript; charset=utf-8',
|
||||
'.json': 'application/json; charset=utf-8',
|
||||
'.wasm': 'application/wasm',
|
||||
'.png': 'image/png',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.ico': 'image/x-icon',
|
||||
'.ttf': 'font/ttf',
|
||||
'.otf': 'font/otf',
|
||||
'.woff': 'font/woff',
|
||||
'.woff2': 'font/woff2',
|
||||
'.bin': 'application/octet-stream',
|
||||
'.frag': 'application/octet-stream',
|
||||
};
|
||||
|
||||
const server = createServer(async (req, res) => {
|
||||
try {
|
||||
const pathname = decodeURIComponent(new URL(req.url, 'http://localhost').pathname);
|
||||
let filePath = resolve(root, '.' + pathname);
|
||||
if (filePath !== root && !filePath.startsWith(root + sep)) {
|
||||
res.writeHead(403).end();
|
||||
return;
|
||||
}
|
||||
if (pathname === '/' || pathname.endsWith('/')) {
|
||||
filePath = join(filePath, 'index.html');
|
||||
}
|
||||
const file = await readFile(filePath);
|
||||
const type = mime[extname(filePath)] ?? 'application/octet-stream';
|
||||
res.writeHead(200, { 'content-type': type }).end(file);
|
||||
} catch {
|
||||
res.writeHead(404).end('not found');
|
||||
}
|
||||
});
|
||||
server.listen(0, '127.0.0.1');
|
||||
await once(server, 'listening');
|
||||
const port = server.address().port;
|
||||
const origin = `http://127.0.0.1:${port}`;
|
||||
|
||||
const profile = await mkdtemp(join(tmpdir(), 'd1-changes-chrome-'));
|
||||
const chrome = spawn(
|
||||
chromePath,
|
||||
[
|
||||
'--headless=new',
|
||||
'--no-first-run',
|
||||
'--no-default-browser-check',
|
||||
'--disable-gpu',
|
||||
'--remote-debugging-port=0',
|
||||
`--user-data-dir=${profile}`,
|
||||
'about:blank',
|
||||
],
|
||||
{ stdio: ['ignore', 'ignore', 'pipe'] },
|
||||
);
|
||||
let stderr = '';
|
||||
chrome.stderr.on('data', (data) => {
|
||||
stderr += data;
|
||||
});
|
||||
|
||||
const waitFor = async (fn, what) => {
|
||||
for (let i = 0; i < 120; i++) {
|
||||
const value = await fn();
|
||||
if (value) return value;
|
||||
await delay(100);
|
||||
}
|
||||
throw new Error(`Timed out waiting for ${what}: ${stderr.slice(-1500)}`);
|
||||
};
|
||||
|
||||
let ws;
|
||||
const evidence = { origin, captures: [], checks: [] };
|
||||
try {
|
||||
const endpoint = await waitFor(
|
||||
() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1],
|
||||
'Chrome DevTools',
|
||||
);
|
||||
ws = new WebSocket(endpoint);
|
||||
await once(ws, 'open');
|
||||
let id = 0;
|
||||
const pending = new Map();
|
||||
ws.addEventListener('message', (event) => {
|
||||
const message = JSON.parse(event.data);
|
||||
if (message.id && pending.has(message.id)) {
|
||||
pending.get(message.id)(message);
|
||||
pending.delete(message.id);
|
||||
}
|
||||
});
|
||||
const send = (method, params = {}, sessionId) =>
|
||||
new Promise((resolveCall) => {
|
||||
const callId = ++id;
|
||||
pending.set(callId, resolveCall);
|
||||
ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) }));
|
||||
});
|
||||
|
||||
const created = await send('Target.createTarget', { url: 'about:blank' });
|
||||
if (!created.result) throw new Error(`Target creation failed: ${JSON.stringify(created)}`);
|
||||
const target = created.result.targetId;
|
||||
const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result
|
||||
.sessionId;
|
||||
await send('Page.enable', {}, session);
|
||||
await send('Runtime.enable', {}, session);
|
||||
await send('Emulation.setDeviceMetricsOverride', {
|
||||
width: 390,
|
||||
height: 844,
|
||||
deviceScaleFactor: 1,
|
||||
mobile: true,
|
||||
}, session);
|
||||
|
||||
const evaluate = async (expression) => {
|
||||
const response = await send(
|
||||
'Runtime.evaluate',
|
||||
{ expression, returnByValue: true, awaitPromise: true },
|
||||
session,
|
||||
);
|
||||
if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`);
|
||||
return response.result?.result?.value;
|
||||
};
|
||||
const labels = () =>
|
||||
evaluate(
|
||||
"[...document.querySelectorAll('flt-semantics')].map(x => x.getAttribute('aria-label') || (x.innerText || '').trim()).filter(Boolean)",
|
||||
);
|
||||
const bodyText = () => evaluate('document.body.innerText');
|
||||
const hasLabel = async (label) => (await labels()).includes(label);
|
||||
const clickExact = async (label) => {
|
||||
const clicked = await evaluate(`(() => {
|
||||
const wanted = ${JSON.stringify(label)};
|
||||
const nodes = [...document.querySelectorAll('flt-semantics')];
|
||||
const node = nodes.find(x => x.getAttribute('aria-label') === wanted)
|
||||
|| nodes.find(x => (x.innerText || '').trim() === wanted);
|
||||
if (!node) return false;
|
||||
node.click();
|
||||
return true;
|
||||
})()`);
|
||||
if (!clicked) throw new Error(`No exact semantics label ${JSON.stringify(label)}: ${JSON.stringify(await labels())}`);
|
||||
await delay(450);
|
||||
};
|
||||
// File rows announce their visible kind and meta after the path, so click by
|
||||
// the stable action+path prefix rather than a fully spelled label.
|
||||
const clickPrefix = async (prefix) => {
|
||||
const clicked = await evaluate(`(() => {
|
||||
const wanted = ${JSON.stringify(prefix)};
|
||||
const nodes = [...document.querySelectorAll('flt-semantics')];
|
||||
// A container's innerText also starts with its first row, so click the
|
||||
// most specific (shortest-text) node that starts with the row prefix.
|
||||
const candidates = nodes.filter((x) =>
|
||||
(x.getAttribute('aria-label') || '').startsWith(wanted)
|
||||
|| (x.innerText || '').trim().startsWith(wanted));
|
||||
if (candidates.length === 0) return false;
|
||||
candidates.sort((a, b) => (a.innerText || '').length - (b.innerText || '').length);
|
||||
candidates[0].click();
|
||||
return true;
|
||||
})()`);
|
||||
if (!clicked) throw new Error(`No semantics label starting ${JSON.stringify(prefix)}: ${JSON.stringify(await labels())}`);
|
||||
await delay(450);
|
||||
};
|
||||
const activate = async () => {
|
||||
await delay(3500);
|
||||
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
|
||||
await delay(1000);
|
||||
const current = await labels();
|
||||
if (!current.some((label) => label.includes('Changes probe'))) {
|
||||
throw new Error(`Flutter semantics unavailable: ${JSON.stringify(current)}`);
|
||||
}
|
||||
};
|
||||
const navigate = async (url) => {
|
||||
const navigation = await send('Page.navigate', { url }, session);
|
||||
if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation));
|
||||
await activate();
|
||||
};
|
||||
const capture = async (name, width, height, scale = 1) => {
|
||||
await send('Emulation.setDeviceMetricsOverride', {
|
||||
width,
|
||||
height,
|
||||
deviceScaleFactor: scale,
|
||||
mobile: width < 600,
|
||||
}, session);
|
||||
await delay(350);
|
||||
const data = (await send('Page.captureScreenshot', { format: 'png' }, session)).result.data;
|
||||
const file = join(out, `${name}.png`);
|
||||
await writeFile(file, Buffer.from(data, 'base64'));
|
||||
evidence.captures.push(file);
|
||||
return file;
|
||||
};
|
||||
|
||||
await navigate(`${origin}/`);
|
||||
const contentType = await evaluate(
|
||||
"fetch('/').then(r => r.headers.get('content-type'))",
|
||||
);
|
||||
evidence.checks.push({ check: 'index content-type is text/html', value: contentType });
|
||||
if (!String(contentType).toLowerCase().startsWith('text/html')) {
|
||||
throw new Error(`Root index is not text/html: ${contentType}`);
|
||||
}
|
||||
|
||||
// Diff text inherits native host typography; it must not add a custom face.
|
||||
const manifest = await evaluate("fetch('/assets/FontManifest.json').then(r => r.json())");
|
||||
const codeEntry = (Array.isArray(manifest) ? manifest : []).find(
|
||||
(entry) => entry.family === 'RobotoMono',
|
||||
);
|
||||
if (codeEntry) throw new Error('Diff build still overrides native typography');
|
||||
evidence.checks.push({
|
||||
check: 'the web build does not register a custom diff font',
|
||||
});
|
||||
|
||||
const firstLabels = await labels();
|
||||
const firstBody = await bodyText();
|
||||
const firstRow = 'Open diff for lib/features/changes/domain/unified_patch.dart';
|
||||
const firstRowPresent = firstLabels.some((label) => label.startsWith(firstRow));
|
||||
const firstStates = ['Changes probe', 'Capture unavailable'].filter((label) =>
|
||||
firstBody.includes(label),
|
||||
);
|
||||
evidence.checks.push({
|
||||
check: 'run summary and capture states are present',
|
||||
value: firstStates,
|
||||
fileRow: firstRowPresent,
|
||||
});
|
||||
if (firstStates.length !== 2 || !firstRowPresent) {
|
||||
throw new Error(`Run summary or capture states missing: ${JSON.stringify(firstBody)}`);
|
||||
}
|
||||
await capture('d1-changes-phone-list', 390, 844);
|
||||
|
||||
const before = await bodyText();
|
||||
await clickPrefix('Open diff for lib/features/changes/domain/unified_patch.dart');
|
||||
const after = await bodyText();
|
||||
if (after === before) throw new Error('Opening the diff did not change the document body');
|
||||
for (const label of ['Rendered', 'Raw patch', 'Copy patch', 'Close diff']) {
|
||||
if (!(await hasLabel(label))) throw new Error(`Open diff is missing ${label}: ${JSON.stringify(await labels())}`);
|
||||
}
|
||||
evidence.checks.push({ check: 'body changed and diff controls appeared', bodyChanged: true });
|
||||
const renderedFile = await capture('d1-changes-phone-diff', 390, 844);
|
||||
|
||||
const renderedBody = await bodyText();
|
||||
await clickExact('Raw patch');
|
||||
const rawSemantics = (await labels()).some((label) =>
|
||||
label.startsWith('Raw patch for lib/features/changes/domain/unified_patch.dart'),
|
||||
);
|
||||
if (!rawSemantics) {
|
||||
throw new Error(`Raw patch view semantics missing: ${JSON.stringify(await labels())}`);
|
||||
}
|
||||
const rawBody = await bodyText();
|
||||
const rawFile = await capture('d1-changes-phone-raw', 390, 844);
|
||||
const [renderedBytes, rawBytes] = await Promise.all([
|
||||
readFile(renderedFile),
|
||||
readFile(rawFile),
|
||||
]);
|
||||
if (renderedBytes.equals(rawBytes)) {
|
||||
throw new Error('Raw patch capture is identical to the rendered capture');
|
||||
}
|
||||
evidence.checks.push({
|
||||
check: 'Raw patch switched the body and the rendered pixels',
|
||||
bodyChanged: rawBody !== renderedBody,
|
||||
pixelsChanged: true,
|
||||
rawSemantics,
|
||||
});
|
||||
|
||||
await send('Browser.grantPermissions', {
|
||||
origin,
|
||||
permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'],
|
||||
});
|
||||
await clickExact('Copy patch');
|
||||
let clipboard = null;
|
||||
try {
|
||||
clipboard = await evaluate('navigator.clipboard.readText()');
|
||||
} catch (error) {
|
||||
evidence.checks.push({ check: 'clipboard readback unavailable', value: String(error) });
|
||||
}
|
||||
if (clipboard != null) {
|
||||
const startsWithHeader = String(clipboard).startsWith(
|
||||
'--- "a/lib/features/changes/domain/unified_patch.dart"',
|
||||
);
|
||||
if (!startsWithHeader) throw new Error('Clipboard did not contain the recorded raw patch');
|
||||
evidence.checks.push({
|
||||
check: 'Copy patch copied the raw patch',
|
||||
startsWithHeader,
|
||||
length: String(clipboard).length,
|
||||
});
|
||||
}
|
||||
await capture('d1-changes-phone-copied', 390, 844);
|
||||
|
||||
await clickExact('Close diff');
|
||||
if (await hasLabel('Raw patch')) throw new Error('Close diff left the viewer open');
|
||||
evidence.checks.push({ check: 'Close diff returned to the list', bodyChanged: (await bodyText()) !== after });
|
||||
|
||||
// Filter changed filenames through the real text field when Flutter exposes
|
||||
// it as a semantics input; record honestly when it does not.
|
||||
const focused = await evaluate(`(() => {
|
||||
const nodes = [...document.querySelectorAll('input, textarea')];
|
||||
const node = nodes.find(x => ((x.getAttribute('aria-label') || '') + ' ' + (x.placeholder || '')).toLowerCase().includes('filter changed files'));
|
||||
if (!node) return false;
|
||||
node.focus();
|
||||
node.click();
|
||||
return true;
|
||||
})()`);
|
||||
if (focused) {
|
||||
await send('Input.insertText', { text: 'unified' }, session);
|
||||
await delay(500);
|
||||
const filtered = await labels();
|
||||
// A row is one single-line semantics node; a list container repeats its
|
||||
// rows with newlines and must not be counted as an extra match.
|
||||
const rows = (prefix) =>
|
||||
filtered.filter((label) => label.startsWith(prefix) && !label.includes('\n'));
|
||||
const unifiedRows = rows('Open diff for lib/features/changes/domain/unified_patch.dart');
|
||||
const binaryRows = rows('Open diff for assets/pipelines-mark.png');
|
||||
evidence.checks.push({
|
||||
check: 'filtering by changed filename',
|
||||
unifiedRows: unifiedRows.length,
|
||||
binaryRows: binaryRows.length,
|
||||
});
|
||||
if (unifiedRows.length === 0) {
|
||||
throw new Error('Filtering removed the matching file');
|
||||
}
|
||||
if (binaryRows.length !== 0) {
|
||||
throw new Error('Filtering left a non-matching file visible');
|
||||
}
|
||||
await capture('d1-changes-phone-filtered', 390, 844);
|
||||
} else {
|
||||
evidence.checks.push({ check: 'filter field not exposed as a semantics input', value: false });
|
||||
}
|
||||
|
||||
// Visit numbering: two stages appear twice in this compact fixture. The
|
||||
// implementer's visits are position-derived (1, 2); the resumed reviewer
|
||||
// visit records control.visit 6, which must win over its position.
|
||||
await navigate(`${origin}/?visits=1`);
|
||||
const visitText = await bodyText();
|
||||
const visitsFor = (stage) => [
|
||||
...visitText.matchAll(new RegExp(`${stage}\\s+Visit (\\d+)`, 'g')),
|
||||
].map((match) => match[1]);
|
||||
const implementerVisits = visitsFor('implementer');
|
||||
const reviewerVisits = visitsFor('reviewer');
|
||||
evidence.checks.push({
|
||||
check: 'repeated stages show their own visit numbers',
|
||||
implementerVisits,
|
||||
reviewerVisits,
|
||||
});
|
||||
if (implementerVisits.join(',') !== '1,2') {
|
||||
throw new Error(`implementer visits are not 1,2: ${JSON.stringify(visitText)}`);
|
||||
}
|
||||
if (reviewerVisits.join(',') !== '1,6') {
|
||||
throw new Error(`reviewer visits are not 1,6 (control.visit): ${JSON.stringify(visitText)}`);
|
||||
}
|
||||
const visitFile = await capture('d1-changes-phone-visits', 390, 844);
|
||||
|
||||
await navigate(`${origin}/`);
|
||||
await clickPrefix('Open diff for lib/features/changes/widgets/file_diff_viewer.dart');
|
||||
await capture('d1-changes-desktop-diff', 1280, 800);
|
||||
await clickExact('Close diff');
|
||||
await capture('d1-changes-desktop-list', 1280, 800);
|
||||
|
||||
// Presentation revision: the light theme and a narrow Cupertino surface, at
|
||||
// 2x so glyph advance, line tints and the popup inset are inspectable.
|
||||
await navigate(`${origin}/?theme=light`);
|
||||
await capture('d1-changes-phone-light-list', 390, 844);
|
||||
await clickPrefix('Open diff for lib/features/changes/domain/unified_patch.dart');
|
||||
await capture('d1-changes-phone-light-diff', 390, 844);
|
||||
await clickExact('Raw patch');
|
||||
await capture('d1-changes-phone-light-raw', 390, 844);
|
||||
await clickExact('Rendered');
|
||||
// The 2x capture is last in its state: Chrome only re-lays out Flutter when
|
||||
// the CSS size changes, so scaling back down on the same page would capture a
|
||||
// half-size frame.
|
||||
await capture('d1-changes-phone-light-diff-2x', 390, 844, 2);
|
||||
|
||||
await navigate(`${origin}/?theme=light`);
|
||||
await capture('d1-changes-desktop-light-list', 1280, 800);
|
||||
await clickPrefix('Open diff for lib/features/changes/widgets/file_diff_viewer.dart');
|
||||
await capture('d1-changes-desktop-light-diff', 1280, 800);
|
||||
await clickExact('Close diff');
|
||||
|
||||
await navigate(`${origin}/?platform=cupertino&theme=light`);
|
||||
await capture('d1-changes-cupertino-light-list', 390, 844);
|
||||
await clickPrefix('Open diff for lib/features/changes/domain/unified_patch.dart');
|
||||
await capture('d1-changes-cupertino-light-diff', 390, 844);
|
||||
await capture('d1-changes-cupertino-light-diff-2x', 390, 844, 2);
|
||||
|
||||
await navigate(`${origin}/?platform=cupertino`);
|
||||
const cupertinoLabels = await labels();
|
||||
if (!cupertinoLabels.some((label) => label.includes('Changes probe'))) {
|
||||
throw new Error('Cupertino fixture did not load');
|
||||
}
|
||||
await clickPrefix('Open diff for lib/features/changes/domain/unified_patch.dart');
|
||||
await capture('d1-changes-cupertino-diff', 1280, 800);
|
||||
|
||||
evidence.checks.push({ check: 'Cupertino viewer opened', value: true });
|
||||
evidence.checks.push({ check: 'visit capture written', value: visitFile });
|
||||
console.log(JSON.stringify(evidence, null, 2));
|
||||
} finally {
|
||||
ws?.close();
|
||||
chrome.kill('SIGTERM');
|
||||
await Promise.race([once(chrome, 'exit'), delay(3000)]);
|
||||
server.close();
|
||||
await rm(profile, { recursive: true, force: true });
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
// Standalone fixture entry for real-browser Changes evidence.
|
||||
//
|
||||
// Build and probe (from app/):
|
||||
// flutter build web --target tool/changes_probe_entry.dart --output build/probe-web
|
||||
// node tool/changes_probe.mjs --root build/probe-web --out DIR
|
||||
//
|
||||
// These are server-shaped fixtures for rendering only. They are not a live run
|
||||
// and never mutate a server.
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:pipelines_app/core/api_gateway.dart';
|
||||
import 'package:pipelines_app/features/changes/changes.dart';
|
||||
|
||||
const _multiHunkPatch =
|
||||
'--- "a/lib/features/changes/domain/unified_patch.dart"\n'
|
||||
'+++ "b/lib/features/changes/domain/unified_patch.dart"\n'
|
||||
'@@ -12,6 +12,7 @@\n'
|
||||
' class ParsedPatch {\n'
|
||||
' const ParsedPatch({\n'
|
||||
' required this.raw,\n'
|
||||
'+ required this.headerLines,\n'
|
||||
' required this.hunks,\n'
|
||||
' });\n'
|
||||
' \n'
|
||||
'@@ -48,5 +49,5 @@\n'
|
||||
'-PatchHunk? _parseHunkHeader(String line) {\n'
|
||||
'+_HunkStart? _parseHunkHeader(String line) {\n'
|
||||
" if (!line.startsWith('@@')) return null;\n"
|
||||
" final end = line.indexOf('@@', 2);\n"
|
||||
' if (end < 0) return null;\n'
|
||||
' final ranges = _tokenizeRanges(line.substring(2, end));\n';
|
||||
|
||||
const _addedPatch =
|
||||
'--- "/dev/null"\n'
|
||||
'+++ "b/lib/features/changes/widgets/file_diff_viewer.dart"\n'
|
||||
'@@ -0,0 +1,5 @@\n'
|
||||
'+class FileDiffViewer extends StatefulWidget {\n'
|
||||
'+ const FileDiffViewer({super.key, required this.file});\n'
|
||||
'+\n'
|
||||
'+ final FileChange file;\n'
|
||||
'+}\n';
|
||||
|
||||
const _deletedPatch =
|
||||
'--- "a/docs/legacy-notes.md"\n'
|
||||
'+++ "/dev/null"\n'
|
||||
'@@ -1,2 +0,0 @@\n'
|
||||
'-# Legacy notes\n'
|
||||
'-Removed with the viewer.\n';
|
||||
|
||||
const _truncatedPatch =
|
||||
'--- "a/logs/capture.log"\n'
|
||||
'+++ "b/logs/capture.log"\n'
|
||||
'@@ -1,2 +1,3 @@\n'
|
||||
'-capture started\n'
|
||||
'+capture started\n'
|
||||
'+and truncated mid-line';
|
||||
|
||||
List<JsonMap> probeSteps() => [
|
||||
{
|
||||
'sequence': 1,
|
||||
'stage': 'implementer',
|
||||
'status': 'completed',
|
||||
'file_changes': {
|
||||
'status': 'partial',
|
||||
'scope': 'Git tracked and nonignored files in the run directory',
|
||||
'skipped': 2,
|
||||
'omitted': 0,
|
||||
'diagnostic':
|
||||
'Excluded protected, symlinked, oversized or unreadable files; this '
|
||||
'is not a complete workspace diff.',
|
||||
'files': [
|
||||
{
|
||||
'path': 'lib/features/changes/domain/unified_patch.dart',
|
||||
'kind': 'modified',
|
||||
'patch': _multiHunkPatch,
|
||||
'before_mode': '0644',
|
||||
'after_mode': '0644',
|
||||
},
|
||||
{
|
||||
'path': 'assets/pipelines-mark.png',
|
||||
'kind': 'modified',
|
||||
'binary': true,
|
||||
},
|
||||
{
|
||||
'path': 'scripts/capture.sh',
|
||||
'kind': 'modified',
|
||||
'before_mode': '0644',
|
||||
'after_mode': '0755',
|
||||
},
|
||||
{
|
||||
'path': 'docs/legacy-notes.md',
|
||||
'kind': 'deleted',
|
||||
'patch': _deletedPatch,
|
||||
'before_mode': '0644',
|
||||
},
|
||||
{
|
||||
'path': 'logs/capture.log',
|
||||
'kind': 'modified',
|
||||
'patch': _truncatedPatch,
|
||||
'truncated': true,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
'sequence': 2,
|
||||
'stage': 'reviewer',
|
||||
'status': 'completed',
|
||||
'file_changes': {
|
||||
'status': 'complete',
|
||||
'scope': 'Git tracked and nonignored files in the run directory',
|
||||
'skipped': 0,
|
||||
'omitted': 0,
|
||||
'diagnostic': '',
|
||||
'files': [
|
||||
{
|
||||
'path': 'lib/features/changes/widgets/file_diff_viewer.dart',
|
||||
'kind': 'added',
|
||||
'patch': _addedPatch,
|
||||
'after_mode': '0644',
|
||||
},
|
||||
{
|
||||
'path': 'lib/features/changes/domain/unified_patch.dart',
|
||||
'kind': 'modified',
|
||||
'patch': _multiHunkPatch,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
'sequence': 3,
|
||||
'stage': 'ui_reviewer',
|
||||
'status': 'completed',
|
||||
'file_changes': null,
|
||||
},
|
||||
{
|
||||
'sequence': 4,
|
||||
'stage': 'committer',
|
||||
'status': 'completed',
|
||||
'file_changes': {
|
||||
'status': 'unavailable',
|
||||
'skipped': 0,
|
||||
'omitted': 0,
|
||||
'diagnostic':
|
||||
'Workspace snapshot unavailable; changes could not be compared.',
|
||||
'files': <JsonMap>[],
|
||||
},
|
||||
},
|
||||
{
|
||||
'sequence': 5,
|
||||
'stage': 'verifier',
|
||||
'status': 'completed',
|
||||
'file_changes': {
|
||||
'status': 'complete',
|
||||
'scope': 'Git tracked and nonignored files in the run directory',
|
||||
'skipped': 0,
|
||||
'omitted': 0,
|
||||
'diagnostic': '',
|
||||
'files': <JsonMap>[],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
/// A compact fixture whose only purpose is visit numbering: the same stages
|
||||
/// appear more than once, one visit records an explicit `control.visit`, and
|
||||
/// every capture is empty so the sections stay on one phone screen.
|
||||
List<JsonMap> probeVisitSteps() => [
|
||||
{
|
||||
'sequence': 1,
|
||||
'stage': 'implementer',
|
||||
'status': 'completed',
|
||||
'file_changes': {
|
||||
'status': 'complete',
|
||||
'scope': 'Git tracked and nonignored files in the run directory',
|
||||
'files': <JsonMap>[],
|
||||
},
|
||||
},
|
||||
{
|
||||
'sequence': 2,
|
||||
'stage': 'reviewer',
|
||||
'status': 'completed',
|
||||
'file_changes': {
|
||||
'status': 'complete',
|
||||
'scope': 'Git tracked and nonignored files in the run directory',
|
||||
'files': <JsonMap>[],
|
||||
},
|
||||
},
|
||||
{
|
||||
'sequence': 3,
|
||||
'stage': 'implementer',
|
||||
'status': 'completed',
|
||||
'file_changes': {
|
||||
'status': 'complete',
|
||||
'scope': 'Git tracked and nonignored files in the run directory',
|
||||
'files': <JsonMap>[],
|
||||
},
|
||||
},
|
||||
{
|
||||
'sequence': 4,
|
||||
'stage': 'reviewer',
|
||||
'status': 'completed',
|
||||
'control': {'visit': 6},
|
||||
'file_changes': {
|
||||
'status': 'complete',
|
||||
'scope': 'Git tracked and nonignored files in the run directory',
|
||||
'files': <JsonMap>[],
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
void main() {
|
||||
final params = Uri.base.queryParameters;
|
||||
final cupertino = params['platform'] == 'cupertino';
|
||||
final brightness = params['theme'] == 'light'
|
||||
? Brightness.light
|
||||
: Brightness.dark;
|
||||
final steps = params['visits'] == '1' ? probeVisitSteps() : probeSteps();
|
||||
if (cupertino) {
|
||||
runApp(
|
||||
CupertinoApp(
|
||||
title: 'Changes probe',
|
||||
theme: CupertinoThemeData(brightness: brightness),
|
||||
home: _ProbeHome(cupertino: true, steps: steps),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
runApp(
|
||||
MaterialApp(
|
||||
title: 'Changes probe',
|
||||
theme: ThemeData(
|
||||
brightness: brightness,
|
||||
// Chrome on macOS reports a macOS default platform; the fixture
|
||||
// states Material explicitly so both control sets are capturable.
|
||||
platform: TargetPlatform.android,
|
||||
),
|
||||
home: _ProbeHome(cupertino: false, steps: steps),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ProbeHome extends StatelessWidget {
|
||||
const _ProbeHome({required this.cupertino, required this.steps});
|
||||
|
||||
final bool cupertino;
|
||||
final List<JsonMap> steps;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final viewer = ChangesViewer(steps: steps);
|
||||
if (cupertino) {
|
||||
return CupertinoPageScaffold(
|
||||
navigationBar: const CupertinoNavigationBar(
|
||||
middle: Text('Changes probe'),
|
||||
),
|
||||
child: SafeArea(child: viewer),
|
||||
);
|
||||
}
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Changes probe')),
|
||||
body: viewer,
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user