feat(app): add native pipelines list and detail screen

Read-only Pipelines screen for the Flutter client:

- list_pipelines and list_runs with a last-run join, plus get_pipeline
  with an explicit version (0 = latest); no mutation requests.
- Name, run-presence, last-run-status and schedule filters; six sort
  orders; clear filters; truthful loading, empty and error states.
- Detail Summary, selectable Source and version history with selection
  and return to latest.
- Sequenced list/detail requests so stale replies cannot replace a newer
  selection or open a cleared one; refresh keeps the selected pipeline
  and version.
- Material controls on Android/desktop and Cupertino on iOS; a
  per-label segmented tab row at narrow widths and scaled text, with the
  native control kept wherever an equal share fits.
- Fixture probe entry and Chrome scripts for the rendered evidence;
  widget tests cover filters, sorting, formatting, sequencing, layout
  and the tab row.

Graph rendering remains P2: the Graph tab states that it is pending and
exposes a host hook. PipelinesScreen is not yet registered in the shell.

Evidence and limits: app/notes/P1.md.
This commit is contained in:
2026-10-21 19:09:29 +01:00
parent 718442d73d
commit a44f31b989
38 changed files with 5583 additions and 0 deletions
@@ -0,0 +1,167 @@
import 'pipeline_format.dart';
import 'pipeline_models.dart';
/// The has/no-runs narrowing offered by the filter's Runs section.
enum RunPresence {
any('Any'),
hasRuns('Has runs'),
noRuns('No runs');
const RunPresence(this.label);
final String label;
}
/// Configured schedule narrowing; paused schedules still count as configured.
enum ScheduleFilter {
any('Any schedule'),
scheduled('Has schedules'),
unscheduled('No schedules');
const ScheduleFilter(this.label);
final String label;
}
/// The server's own run vocabulary offered by the last-run status filter. The
/// app-only `active` bucket and stage outcome words are deliberately excluded.
const runStatusFilters = <String>[
'queued',
'running',
'waiting',
'succeeded',
'failed',
'canceled',
'interrupted',
];
/// The default, no-narrowing filter.
const emptyPipelineFilters = PipelineFilters();
/// One immutable capture of the list's filter controls.
class PipelineFilters {
const PipelineFilters({
this.name = '',
this.presence = RunPresence.any,
this.lastRunStatuses = const <String>{},
this.schedule = ScheduleFilter.any,
});
final String name;
final RunPresence presence;
final Set<String> lastRunStatuses;
final ScheduleFilter schedule;
bool get hasRunFacets =>
presence != RunPresence.any || lastRunStatuses.isNotEmpty;
bool get active =>
hasRunFacets || name.trim().isNotEmpty || schedule != ScheduleFilter.any;
int get count =>
(presence != RunPresence.any ? 1 : 0) +
(lastRunStatuses.isNotEmpty ? 1 : 0) +
(name.trim().isNotEmpty ? 1 : 0) +
(schedule != ScheduleFilter.any ? 1 : 0);
PipelineFilters copyWith({
String? name,
RunPresence? presence,
Set<String>? lastRunStatuses,
ScheduleFilter? schedule,
}) => PipelineFilters(
name: name ?? this.name,
presence: presence ?? this.presence,
lastRunStatuses: lastRunStatuses ?? this.lastRunStatuses,
schedule: schedule ?? this.schedule,
);
}
/// The empty-state sentence for the list plus its optional reset action.
class PipelineEmptyState {
const PipelineEmptyState(this.message, {this.clearAction});
final String message;
final String? clearAction;
}
bool _matchesName(String needle, String pipelineName) {
final query = needle.trim().toLowerCase();
return query.isEmpty || pipelineName.toLowerCase().contains(query);
}
bool _matchesSchedule(PipelineScheduleState state, ScheduleFilter filter) {
switch (filter) {
case ScheduleFilter.any:
return true;
case ScheduleFilter.scheduled:
return state == PipelineScheduleState.scheduled;
case ScheduleFilter.unscheduled:
return state == PipelineScheduleState.unscheduled;
}
}
bool _matchesPresence(RunPresence presence, bool hasRun) {
switch (presence) {
case RunPresence.any:
return true;
case RunPresence.hasRuns:
return hasRun;
case RunPresence.noRuns:
return !hasRun;
}
}
/// Narrows [pipelines] by [filters] with AND. Run facets are skipped until the
/// run history is known, so a slow runs read never briefly hides everything.
List<PipelineSummary> filterPipelines(
List<PipelineSummary> pipelines,
PipelineFilters filters,
Map<int, PipelineRun> latestRuns,
bool runsKnown,
) {
if (!filters.active) return pipelines;
return pipelines
.where((pipeline) {
if (!_matchesName(filters.name, pipeline.name)) return false;
if (!_matchesSchedule(pipeline.scheduleState, filters.schedule)) {
return false;
}
if (filters.hasRunFacets && runsKnown) {
final latestRun = latestRuns[pipeline.id];
if (!_matchesPresence(filters.presence, latestRun != null)) {
return false;
}
if (filters.lastRunStatuses.isNotEmpty) {
if (latestRun == null) return false;
if (!filters.lastRunStatuses.contains(
runStateOf(latestRun.status),
)) {
return false;
}
}
}
return true;
})
.toList(growable: false);
}
PipelineEmptyState? pipelineListEmptyState(
List<PipelineSummary> all,
List<PipelineSummary> items,
PipelineFilters filters,
) {
if (items.isNotEmpty) return null;
if (all.isEmpty) {
return const PipelineEmptyState('No pipelines are defined on this server.');
}
final name = filters.name;
final onlyName =
name.trim().isNotEmpty &&
!filters.hasRunFacets &&
filters.schedule == ScheduleFilter.any;
final message = onlyName
? 'No pipelines match "$name".'
: 'No pipelines match the current filters.';
return PipelineEmptyState(message, clearAction: 'Clear filters');
}
@@ -0,0 +1,105 @@
/// Formatting shared by the pipeline list and detail.
///
/// The wording mirrors the web client (`src/pipelines.js`), which in turn
/// mirrors the Android app: one date shape, one duration shape, one status
/// vocabulary and one singular/plural rule.
library;
const _monthNames = <String>[
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
/// Parses an RFC3339 timestamp, or null when blank or unparseable.
DateTime? parseInstant(String? text) {
final trimmed = text?.trim() ?? '';
if (trimmed.isEmpty) return null;
return DateTime.tryParse(trimmed);
}
/// `d MMM HH:mm` in local time, e.g. `17 Oct 21:26`, or null when the
/// timestamp is unusable so callers omit the value instead of printing blank.
String? formatLocalTimestamp(String? text) {
final instant = parseInstant(text);
if (instant == null) return null;
final local = instant.toLocal();
final hour = local.hour.toString().padLeft(2, '0');
final minute = local.minute.toString().padLeft(2, '0');
return '${local.day} ${_monthNames[local.month - 1]} $hour:$minute';
}
/// `45s`, `2m 5s`, `1h 2m`. Negative values clamp to `0s`.
String formatDuration(int totalSeconds) {
final seconds = totalSeconds < 0 ? 0 : totalSeconds;
if (seconds < 60) return '${seconds}s';
if (seconds < 3600) return '${seconds ~/ 60}m ${seconds % 60}s';
return '${seconds ~/ 3600}h ${(seconds % 3600) ~/ 60}m';
}
/// Whole non-negative seconds between two timestamps, or null when either is
/// unusable or the end precedes the start.
int? durationSeconds(String? start, String? end) {
final from = parseInstant(start);
final to = parseInstant(end);
if (from == null || to == null) return null;
final seconds = to.difference(from).inSeconds;
return seconds >= 0 ? seconds : null;
}
/// `just now`, `Nm ago`, `Nh ago`, `Nd ago`; a future timestamp reads as
/// `just now`, never a negative age.
String? formatRanAgo(String? createdAt, DateTime now) {
final start = parseInstant(createdAt);
if (start == null) return null;
final seconds = now.difference(start).inSeconds;
if (seconds < 60) return 'just now';
if (seconds < 3600) return '${seconds ~/ 60}m ago';
if (seconds < 86400) return '${seconds ~/ 3600}h ago';
return '${seconds ~/ 86400}d ago';
}
/// `1 stage` / `n stages`.
String stageCountText(int count) => '$count ${count == 1 ? 'stage' : 'stages'}';
const _runStateAliases = <String, String>{
'running': 'running',
'queued': 'queued',
'waiting': 'waiting',
'active': 'active',
'succeeded': 'succeeded',
'success': 'succeeded',
'completed': 'succeeded',
'done': 'succeeded',
'failed': 'failed',
'error': 'failed',
'canceled': 'canceled',
'cancelled': 'canceled',
'interrupted': 'interrupted',
'blocked': 'blocked',
'skipped': 'skipped',
};
/// Maps a server status word to the shared run-state vocabulary. Unknown or
/// blank values become `unknown` rather than crashing a row.
String runStateOf(String? status) {
final key = (status ?? '').trim().toLowerCase();
return _runStateAliases[key] ?? 'unknown';
}
/// `Running`-style title for a run state.
String runStateLabel(String? status) {
final state = runStateOf(status);
return state.isEmpty
? state
: '${state[0].toUpperCase()}${state.substring(1)}';
}
@@ -0,0 +1,28 @@
import 'package:flutter/widgets.dart';
import 'pipeline_models.dart';
/// Optional graph integration supplied by the later graph item (P2).
///
/// [onStageSelected] reports the graph's stage key with the pipeline identity
/// this detail was loaded for, so a host can route to a stage view without the
/// pipelines feature owning the graph.
typedef PipelineGraphBuilder =
Widget Function(
BuildContext context,
PipelineDetail detail,
ValueChanged<String> onStageSelected,
);
/// One stage selected in a hosted graph.
class PipelineStageRef {
const PipelineStageRef({
required this.pipelineId,
required this.version,
required this.stageKey,
});
final int pipelineId;
final int version;
final String stageKey;
}
@@ -0,0 +1,225 @@
import 'package:flutter/foundation.dart';
/// The shared decoded-envelope type from the transport contract.
typedef PipelineJson = Map<String, dynamic>;
/// Whether a pipeline currently has configured schedules.
///
/// Configuration is not run provenance: an unknown older record stays
/// [unclassified] rather than being reported as unscheduled.
enum PipelineScheduleState { scheduled, unscheduled, unclassified }
/// One row of `list_pipelines`.
@immutable
class PipelineSummary {
const PipelineSummary({
required this.id,
required this.name,
required this.version,
required this.stages,
required this.createdAt,
required this.updatedAt,
required this.scheduled,
required this.scheduleCount,
required this.enabledScheduleCount,
});
factory PipelineSummary.fromJson(PipelineJson json) {
final scheduleCount = _optionalInt(json['schedule_count']);
final scheduled = json['scheduled'];
return PipelineSummary(
id: _int(json['id']),
name: _string(json['name']),
version: _int(json['version']),
stages: _int(json['stages']),
createdAt: _string(json['created_at']),
updatedAt: _string(json['updated_at']),
scheduled: scheduled is bool ? scheduled : null,
scheduleCount: scheduleCount,
enabledScheduleCount: _optionalInt(json['enabled_schedule_count']),
);
}
final int id;
final String name;
final int version;
final int stages;
final String createdAt;
final String updatedAt;
final bool? scheduled;
final int? scheduleCount;
final int? enabledScheduleCount;
String get displayName => name.isEmpty ? 'pipeline $id' : name;
/// Mirrors the web's schedule configuration rule, including its fallbacks
/// for peers that predate the schedule fields.
PipelineScheduleState get scheduleState {
if (scheduleCount != null && scheduleCount! > 0) {
return PipelineScheduleState.scheduled;
}
if (scheduled != null) {
return scheduled!
? PipelineScheduleState.scheduled
: PipelineScheduleState.unscheduled;
}
if (scheduleCount == 0) return PipelineScheduleState.unscheduled;
return PipelineScheduleState.unclassified;
}
/// The configured-schedule label, or an empty string when unscheduled.
String get scheduleLabel {
if (scheduleState != PipelineScheduleState.scheduled) return '';
final count = scheduleCount;
if (count != null && count > 0) {
return '$count ${count == 1 ? 'schedule' : 'schedules'}';
}
return 'Has schedules';
}
}
/// One entry of a pipeline detail's version history.
@immutable
class PipelineVersion {
const PipelineVersion({
required this.version,
required this.stages,
required this.createdAt,
});
factory PipelineVersion.fromJson(PipelineJson json) => PipelineVersion(
version: _int(json['version']),
stages: _int(json['stages']),
createdAt: _string(json['created_at']),
);
final int version;
final int stages;
final String createdAt;
}
/// The `detail` payload of a `get_pipeline` reply.
@immutable
class PipelineDetail extends PipelineSummary {
const PipelineDetail({
required super.id,
required super.name,
required super.version,
required super.stages,
required super.createdAt,
required super.updatedAt,
required super.scheduled,
required super.scheduleCount,
required super.enabledScheduleCount,
required this.latestVersion,
required this.versionCreatedAt,
required this.contentHash,
required this.source,
required this.versions,
});
factory PipelineDetail.fromJson(PipelineJson json) {
final summary = PipelineSummary.fromJson(json);
final versions = json['versions'];
return PipelineDetail(
id: summary.id,
name: summary.name,
version: summary.version,
stages: summary.stages,
createdAt: summary.createdAt,
updatedAt: summary.updatedAt,
scheduled: summary.scheduled,
scheduleCount: summary.scheduleCount,
enabledScheduleCount: summary.enabledScheduleCount,
latestVersion: _int(json['latest_version']),
versionCreatedAt: _string(json['version_created_at']),
contentHash: _string(json['content_hash']),
source: _string(json['source']),
versions: versions is List
? List.unmodifiable(
versions.whereType<Map>().map(
(version) => PipelineVersion.fromJson(
Map<String, dynamic>.from(version),
),
),
)
: const <PipelineVersion>[],
);
}
final int latestVersion;
final String versionCreatedAt;
final String contentHash;
final String source;
final List<PipelineVersion> versions;
/// The concrete version this detail describes. A request for version 0 asks
/// for latest, so the reply's own `version` is authoritative for display.
int get resolvedVersion => version > 0 ? version : latestVersion;
}
/// The subset of a run summary the pipeline list needs for its last-run join.
@immutable
class PipelineRun {
const PipelineRun({
required this.id,
required this.pipelineId,
required this.status,
required this.createdAt,
required this.finishedAt,
required this.executing,
});
factory PipelineRun.fromJson(PipelineJson json) => PipelineRun(
id: _int(json['id']),
pipelineId: _int(json['pipeline_id']),
status: _string(json['status']),
createdAt: _string(json['created_at']),
finishedAt: _string(json['finished_at']),
executing: json['executing'] == true,
);
final int id;
final int pipelineId;
final String status;
final String createdAt;
final String finishedAt;
final bool executing;
}
/// Timestamps decide recency; a higher run id breaks an exact tie or two bad
/// timestamps. This is the one recency rule shared by the list's join and the
/// "Most recent run" ordering.
bool isMoreRecent(PipelineRun candidate, PipelineRun current) {
final a = DateTime.tryParse(candidate.createdAt);
final b = DateTime.tryParse(current.createdAt);
if (a != null && b != null && a != b) return a.isAfter(b);
return candidate.id > current.id;
}
/// The latest run per pipeline id.
Map<int, PipelineRun> latestRunByPipeline(Iterable<PipelineRun> runs) {
final latest = <int, PipelineRun>{};
for (final run in runs) {
final current = latest[run.pipelineId];
if (current == null || isMoreRecent(run, current)) {
latest[run.pipelineId] = run;
}
}
return latest;
}
int _int(Object? value) {
if (value is int) return value;
if (value is num) return value.toInt();
return int.tryParse('${value ?? ''}') ?? 0;
}
int? _optionalInt(Object? value) {
if (value == null) return null;
if (value is int) return value;
if (value is num) return value.toInt();
return int.tryParse('$value');
}
String _string(Object? value) => value is String ? value : '';
@@ -0,0 +1,92 @@
import 'pipeline_format.dart';
import 'pipeline_models.dart';
export 'pipeline_filter.dart';
export 'pipeline_sort.dart';
/// One Summary key/value row.
class PipelineField {
const PipelineField(this.key, this.value, {this.monospace = false});
final String key;
final String value;
final bool monospace;
}
/// The last-run values a row displays.
class RunBadge {
const RunBadge({
required this.runId,
required this.state,
required this.ranAgo,
required this.duration,
});
final int runId;
final String state;
final String? ranAgo;
final String? duration;
/// `2h ago · 1m 5s · run 42`; missing fragments are omitted.
String get metaLine => [
ranAgo,
duration,
'run $runId',
].whereType<String>().where((fragment) => fragment.isNotEmpty).join(' · ');
}
RunBadge runBadge(PipelineRun run, DateTime now) {
final duration = run.executing
? _liveDuration(run, now)
: _finishedDuration(run);
return RunBadge(
runId: run.id,
state: runStateOf(run.status),
ranAgo: formatRanAgo(run.createdAt, now),
duration: duration,
);
}
String? _liveDuration(PipelineRun run, DateTime now) {
final start = parseInstant(run.createdAt);
if (start == null) return null;
final seconds = now.difference(start).inSeconds;
return formatDuration(seconds < 0 ? 0 : seconds);
}
String? _finishedDuration(PipelineRun run) {
final seconds = durationSeconds(run.createdAt, run.finishedAt);
return seconds == null ? null : formatDuration(seconds);
}
/// `id {id} · v{version} · {N stages}`.
String pipelineSubtitle(PipelineSummary pipeline) =>
'id ${pipeline.id} · v${pipeline.version} · '
'${stageCountText(pipeline.stages)}';
/// `updated d MMM HH:mm`, or null when the timestamp is unusable.
String? pipelineUpdatedLine(PipelineSummary pipeline) {
final formatted = formatLocalTimestamp(pipeline.updatedAt);
return formatted == null ? null : 'updated $formatted';
}
/// The Summary tab's rows in the app's order.
List<PipelineField> pipelineSummaryFields(PipelineDetail detail) => [
PipelineField('Content hash', detail.contentHash, monospace: true),
PipelineField(
'Latest version',
detail.latestVersion > 0 ? 'v${detail.latestVersion}' : '',
),
PipelineField(
'Version created',
formatLocalTimestamp(detail.versionCreatedAt) ?? '',
),
PipelineField(
'Pipeline created',
formatLocalTimestamp(detail.createdAt) ?? '',
),
PipelineField(
'Pipeline updated',
formatLocalTimestamp(detail.updatedAt) ?? '',
),
];
@@ -0,0 +1,98 @@
import '../../core/api_gateway.dart';
import 'pipeline_models.dart';
/// A refusal or malformed reply with a message that is safe to show verbatim.
class PipelineRequestException implements Exception {
const PipelineRequestException(this.message);
final String message;
@override
String toString() => message;
}
/// Read-only pipeline requests. Request shapes mirror `web/src/repository.js`
/// exactly; no mutation of server state is offered here.
class PipelinesRepository {
PipelinesRepository(this._gateway);
final ApiGateway _gateway;
/// `list_pipelines` -> the whole `pipelines` array.
Future<List<PipelineSummary>> listPipelines() async {
final envelope = await _gateway.call('list_pipelines');
_throwIfError(envelope, 'The server returned no pipeline list.');
final type = envelope['type'];
if (type != null && type != 'pipelines') {
throw const PipelineRequestException(
'The server returned no pipeline list.',
);
}
final raw = envelope['pipelines'];
if (raw == null) {
if (type == 'pipelines') return const <PipelineSummary>[];
throw const PipelineRequestException(
'The server returned no pipeline list.',
);
}
if (raw is! List) {
throw const PipelineRequestException(
'The server returned no pipeline list.',
);
}
return List.unmodifiable(
raw.whereType<Map>().map(
(item) => PipelineSummary.fromJson(Map<String, dynamic>.from(item)),
),
);
}
/// `get_pipeline` with the web's exact `pipeline_id`/`version` fields.
/// Version 0 asks the server for the latest version.
Future<PipelineDetail> getPipeline(int id, int version) async {
final envelope = await _gateway.call('get_pipeline', {
'pipeline_id': id,
'version': version,
});
_throwIfError(envelope, 'The server returned no pipeline detail.');
if (envelope['type'] != null && envelope['type'] != 'pipeline') {
throw const PipelineRequestException(
'The server returned no pipeline detail.',
);
}
final detail = envelope['detail'];
if (detail is! Map) {
throw const PipelineRequestException(
'The server returned no pipeline detail.',
);
}
return PipelineDetail.fromJson(Map<String, dynamic>.from(detail));
}
/// `list_runs` is read only here for the pipeline list's last-run join.
Future<List<PipelineRun>> listRuns() async {
final envelope = await _gateway.call('list_runs');
_throwIfError(envelope, 'The server returned no run list.');
if (envelope['type'] != null && envelope['type'] != 'runs') {
throw const PipelineRequestException('The server returned no run list.');
}
final raw = envelope['runs'];
if (raw == null) return const <PipelineRun>[];
if (raw is! List) {
throw const PipelineRequestException('The server returned no run list.');
}
return List.unmodifiable(
raw.whereType<Map>().map(
(item) => PipelineRun.fromJson(Map<String, dynamic>.from(item)),
),
);
}
void _throwIfError(JsonMap envelope, String fallback) {
final error = envelope['error'];
if (envelope['type'] == 'error' || (error is String && error.isNotEmpty)) {
final message = error is String ? error.trim() : '';
throw PipelineRequestException(message.isEmpty ? fallback : message);
}
}
}
@@ -0,0 +1,97 @@
import 'pipeline_format.dart';
import 'pipeline_models.dart';
/// The pipeline-list orderings offered by the sort control.
enum PipelineSort {
serverOrder('Server order'),
nameAsc('Name A\u2013Z'),
nameDesc('Name Z\u2013A'),
recentRun('Most recent run'),
fewestStages('Fewest stages'),
mostStages('Most stages');
const PipelineSort(this.label);
final String label;
}
/// Case-insensitive primary comparison, then a case-sensitive tie-break.
int _compareInsensitive(String a, String b) {
final x = a.toUpperCase();
final y = b.toUpperCase();
final primary = x.compareTo(y);
return primary != 0 ? primary : a.compareTo(b);
}
/// The pure comparator for [sort], with an original-index final tie-break so
/// equal rows keep the server's order regardless of sort stability.
int _compare(
PipelineSummary a,
PipelineSummary b,
PipelineSort sort,
Map<int, PipelineRun> latestRuns,
int indexA,
int indexB,
) {
final stable = indexA - indexB;
switch (sort) {
case PipelineSort.serverOrder:
return stable;
case PipelineSort.nameAsc:
final name = _compareInsensitive(a.name, b.name);
if (name != 0) return name;
return a.id != b.id ? a.id - b.id : stable;
case PipelineSort.nameDesc:
final folded = -a.name.toUpperCase().compareTo(b.name.toUpperCase());
if (folded != 0) return folded;
final sensitive = a.name.compareTo(b.name);
if (sensitive != 0) return sensitive;
return a.id != b.id ? a.id - b.id : stable;
case PipelineSort.recentRun:
final ra = latestRuns[a.id];
final rb = latestRuns[b.id];
if ((ra == null) != (rb == null)) return ra == null ? 1 : -1;
final timeA = ra == null ? null : parseInstant(ra.createdAt);
final timeB = rb == null ? null : parseInstant(rb.createdAt);
if (timeA != timeB) {
if (timeA == null) return 1;
if (timeB == null) return -1;
return timeA.isAfter(timeB) ? -1 : 1;
}
final idA = ra?.id ?? -1;
final idB = rb?.id ?? -1;
if (idA != idB) return idA > idB ? -1 : 1;
return a.id != b.id ? a.id - b.id : stable;
case PipelineSort.fewestStages:
final stages = a.stages - b.stages;
if (stages != 0) return stages;
final name = _compareInsensitive(a.name, b.name);
if (name != 0) return name;
return a.id != b.id ? a.id - b.id : stable;
case PipelineSort.mostStages:
final stages = b.stages - a.stages;
if (stages != 0) return stages;
final name = _compareInsensitive(a.name, b.name);
if (name != 0) return name;
return a.id != b.id ? a.id - b.id : stable;
}
}
/// Orders [pipelines] without mutating the input; server order is preserved
/// exactly, including when the underlying sort is unstable.
List<PipelineSummary> sortPipelines(
List<PipelineSummary> pipelines,
PipelineSort sort,
Map<int, PipelineRun> latestRuns,
) {
if (sort == PipelineSort.serverOrder) return List.of(pipelines);
final indexed = List.generate(
pipelines.length,
(index) => (index: index, pipeline: pipelines[index]),
);
indexed.sort(
(a, b) =>
_compare(a.pipeline, b.pipeline, sort, latestRuns, a.index, b.index),
);
return [for (final entry in indexed) entry.pipeline];
}
@@ -0,0 +1,223 @@
import 'package:flutter/foundation.dart';
import 'pipeline_models.dart';
import 'pipeline_query.dart';
import 'pipeline_repository.dart';
/// The user-facing message for a request failure, keeping server refusals
/// verbatim and removing only the generic `Exception:` prefix.
String pipelineErrorMessage(Object error) {
if (error is PipelineRequestException) return error.message;
final text = error.toString();
return text.startsWith('Exception: ') ? text.substring(11) : text;
}
/// Owns the pipeline list/detail state. The screen only renders this object;
/// every request is sequenced here so a late reply can never replace a newer
/// selection.
class PipelinesController extends ChangeNotifier {
PipelinesController(this._repository);
final PipelinesRepository _repository;
List<PipelineSummary> _pipelines = const <PipelineSummary>[];
List<PipelineRun> _runs = const <PipelineRun>[];
PipelineFilters _filters = emptyPipelineFilters;
PipelineSort _sort = PipelineSort.serverOrder;
int? _selectedId;
int _selectedVersion = 0;
PipelineDetail? _detail;
bool _listLoading = false;
bool _pipelinesLoaded = false;
bool _runsLoaded = false;
String? _listError;
String? _runsError;
bool _detailLoading = false;
String? _detailError;
int _listSequence = 0;
int _runsSequence = 0;
int _detailSequence = 0;
bool _disposed = false;
List<PipelineRun>? _latestSource;
Map<int, PipelineRun>? _latestCache;
List<PipelineSummary> get pipelines => _pipelines;
PipelineFilters get filters => _filters;
PipelineSort get sort => _sort;
bool get listLoading => _listLoading;
bool get pipelinesLoaded => _pipelinesLoaded;
bool get runsLoaded => _runsLoaded;
String? get listError => _listError;
String? get runsError => _runsError;
bool get detailLoading => _detailLoading;
String? get detailError => _detailError;
PipelineDetail? get detail => _detail;
int? get selectedId => _selectedId;
int get selectedVersion => _selectedVersion;
bool get hasSelection => _selectedId != null;
bool get initialListLoading => _listLoading && !_pipelinesLoaded;
Map<int, PipelineRun> get latestRuns {
final cache = _latestCache;
if (cache != null && identical(_latestSource, _runs)) return cache;
_latestSource = _runs;
return _latestCache = latestRunByPipeline(_runs);
}
/// The rows after sorting and filtering, using the same pure rules as web.
List<PipelineSummary> get visiblePipelines {
final runs = latestRuns;
final sorted = sortPipelines(_pipelines, _sort, runs);
return filterPipelines(sorted, _filters, runs, _runsLoaded);
}
PipelineEmptyState? get emptyState =>
pipelineListEmptyState(_pipelines, visiblePipelines, _filters);
/// Reloads the list and runs and re-reads the current detail. The selection
/// (pipeline id and requested version) is deliberately preserved.
Future<void> load() async {
final listToken = ++_listSequence;
final runsToken = ++_runsSequence;
_listLoading = true;
_listError = null;
_runsError = null;
_notify();
await Future.wait([_readList(listToken), _readRuns(runsToken)]);
if (_selectedId != null) await _reloadDetail();
}
Future<void> _readList(int token) async {
try {
final rows = await _repository.listPipelines();
if (!_current(_listSequence, token)) return;
_pipelines = rows;
_pipelinesLoaded = true;
_listError = null;
} catch (error) {
if (!_current(_listSequence, token)) return;
_listError = pipelineErrorMessage(error);
} finally {
if (_current(_listSequence, token)) {
_listLoading = false;
_notify();
}
}
}
Future<void> _readRuns(int token) async {
try {
final runs = await _repository.listRuns();
if (!_current(_runsSequence, token)) return;
_runs = runs;
_runsLoaded = true;
_runsError = null;
} catch (error) {
if (!_current(_runsSequence, token)) return;
// Retain any previously successful run history: a failed refresh must
// not silently change the meaning of an active last-run filter.
_runsError = pipelineErrorMessage(error);
}
if (_current(_runsSequence, token)) _notify();
}
/// Opens [id] at [version] (0 asks for latest), discarding the previous
/// detail immediately so no unrelated entity sits under the new selection.
Future<void> openPipeline(int id, {int version = 0}) async {
final requestedVersion = version > 0 ? version : 0;
_selectedId = id;
_selectedVersion = requestedVersion;
_detail = null;
_detailError = null;
await _requestDetail(id, requestedVersion);
}
/// Selects a recorded version by its version number; 0 returns to latest.
Future<void> selectVersion(int version) async {
final id = _selectedId;
if (id == null) return;
await openPipeline(id, version: version);
}
Future<void> retryDetail() async {
final id = _selectedId;
if (id == null) return;
await _requestDetail(id, _selectedVersion);
}
Future<void> _reloadDetail() async {
final id = _selectedId;
if (id == null) return;
await _requestDetail(id, _selectedVersion);
}
Future<void> _requestDetail(int id, int version) async {
final token = ++_detailSequence;
_detailLoading = true;
_detailError = null;
_notify();
try {
final detail = await _repository.getPipeline(id, version);
if (!_currentDetail(token, id, version)) return;
_detail = detail;
_detailError = null;
} catch (error) {
if (!_currentDetail(token, id, version)) return;
_detail = null;
_detailError = pipelineErrorMessage(error);
} finally {
if (_currentDetail(token, id, version)) {
_detailLoading = false;
_notify();
}
}
}
/// Clears the selection for narrow-layout Back and for an explicit close.
void clearSelection() {
_detailSequence++;
_selectedId = null;
_selectedVersion = 0;
_detail = null;
_detailError = null;
_detailLoading = false;
_notify();
}
void setFilters(PipelineFilters filters) {
_filters = filters;
_notify();
}
void clearFilters() {
_filters = emptyPipelineFilters;
_notify();
}
void setSort(PipelineSort sort) {
_sort = sort;
_notify();
}
bool _current(int sequence, int token) => !_disposed && sequence == token;
bool _currentDetail(int token, int id, int version) =>
!_disposed &&
token == _detailSequence &&
id == _selectedId &&
version == _selectedVersion;
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}
+155
View File
@@ -0,0 +1,155 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../core/api_gateway.dart';
import 'pipeline_graph_hook.dart';
import 'pipeline_repository.dart';
import 'pipelines_controller.dart';
import 'widgets/pipeline_controls.dart';
import 'widgets/pipeline_detail_panel.dart';
import 'widgets/pipeline_list_panel.dart';
export 'pipeline_graph_hook.dart';
export 'pipeline_models.dart' show PipelineDetail, PipelineVersion;
/// Below this width the list and detail are separate pages; above it they sit
/// side by side. One local breakpoint, not a styling system.
const double kPipelinesWideBreakpoint = 720;
/// The read-only Pipelines destination: list, filters/sort, detail, source and
/// version history.
///
/// [graphBuilder] is the optional integration hook for the later graph item.
/// Without it the Graph tab states that graph rendering is pending.
class PipelinesScreen extends StatefulWidget {
const PipelinesScreen({
super.key,
required this.gateway,
this.graphBuilder,
this.onStageSelected,
});
final ApiGateway gateway;
final PipelineGraphBuilder? graphBuilder;
final ValueChanged<PipelineStageRef>? onStageSelected;
@override
State<PipelinesScreen> createState() => _PipelinesScreenState();
}
class _PipelinesScreenState extends State<PipelinesScreen> {
late PipelinesController _controller;
@override
void initState() {
super.initState();
_controller = PipelinesController(PipelinesRepository(widget.gateway))
..load();
}
@override
void didUpdateWidget(PipelinesScreen oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.gateway != widget.gateway) {
_controller.dispose();
_controller = PipelinesController(PipelinesRepository(widget.gateway))
..load();
}
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _controller,
builder: (context, _) {
final body = LayoutBuilder(
builder: (context, constraints) {
final wide = constraints.maxWidth >= kPipelinesWideBreakpoint;
if (!wide) {
return _controller.hasSelection
? PipelineDetailPanel(
controller: _controller,
showBack: true,
graphBuilder: widget.graphBuilder,
onStageSelected: widget.onStageSelected,
)
: PipelineListPanel(controller: _controller);
}
return Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Expanded(
flex: 2,
child: PipelineListPanel(controller: _controller),
),
_divider(context),
Expanded(
flex: 3,
child: PipelineDetailPanel(
controller: _controller,
showBack: false,
graphBuilder: widget.graphBuilder,
onStageSelected: widget.onStageSelected,
),
),
],
);
},
);
return useCupertinoControls(context)
? _cupertinoShell(context, body)
: _materialShell(context, body);
},
);
}
Widget _divider(BuildContext context) {
if (useCupertinoControls(context)) {
return Container(
width: 1,
color: CupertinoColors.separator.resolveFrom(context),
);
}
return const VerticalDivider(width: 1);
}
Widget _materialShell(BuildContext context, Widget body) {
return Scaffold(
appBar: AppBar(
title: const Text('Pipelines'),
actions: [
IconButton(
tooltip: 'Refresh',
onPressed: _controller.load,
icon: const Icon(Icons.refresh),
),
],
),
body: SafeArea(child: body),
);
}
Widget _cupertinoShell(BuildContext context, Widget body) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: const Text('Pipelines'),
trailing: Semantics(
button: true,
label: 'Refresh',
child: CupertinoButton(
padding: EdgeInsets.zero,
onPressed: _controller.load,
child: const Icon(CupertinoIcons.refresh),
),
),
),
child: SafeArea(top: false, child: body),
);
}
}
@@ -0,0 +1,177 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import '../pipeline_query.dart';
/// The one platform decision for this feature. The screen itself receives no
/// platform flag, so tests and integration obey Flutter's target platform.
bool useCupertinoControls(BuildContext context) =>
defaultTargetPlatform == TargetPlatform.iOS;
/// Standard platform activity indicator with an accessible status label.
class PipelineProgress extends StatelessWidget {
const PipelineProgress({super.key, this.label = 'Loading'});
final String label;
@override
Widget build(BuildContext context) {
return Semantics(
label: label,
liveRegion: true,
child: useCupertinoControls(context)
? const CupertinoActivityIndicator()
: const CircularProgressIndicator(),
);
}
}
/// A standard text action in the current platform's style.
class PipelineTextButton extends StatelessWidget {
const PipelineTextButton({
super.key,
required this.label,
required this.onPressed,
});
final String label;
final VoidCallback? onPressed;
@override
Widget build(BuildContext context) {
if (useCupertinoControls(context)) {
return CupertinoButton(
padding: EdgeInsets.zero,
onPressed: onPressed,
child: Text(label),
);
}
return TextButton(onPressed: onPressed, child: Text(label));
}
}
/// Native back affordance used by the narrow list/detail layout.
class PipelineBackButton extends StatelessWidget {
const PipelineBackButton({super.key, required this.onPressed});
final VoidCallback onPressed;
@override
Widget build(BuildContext context) {
if (useCupertinoControls(context)) {
return Semantics(
button: true,
label: 'Back to pipelines',
child: CupertinoButton(
padding: EdgeInsets.zero,
onPressed: onPressed,
child: const Icon(CupertinoIcons.back),
),
);
}
return IconButton(
tooltip: 'Back to pipelines',
onPressed: onPressed,
icon: const Icon(Icons.arrow_back),
);
}
}
/// The list's sort control: a Material menu on Android/desktop, an action
/// sheet on iOS. The label is the current choice, exactly as on web.
class PipelineSortButton extends StatelessWidget {
const PipelineSortButton({
super.key,
required this.sort,
required this.onSelected,
});
final PipelineSort sort;
final ValueChanged<PipelineSort> onSelected;
@override
Widget build(BuildContext context) {
final label = 'Sort: ${sort.label}';
if (useCupertinoControls(context)) {
return CupertinoButton(
padding: EdgeInsets.zero,
onPressed: () => _showCupertinoSheet(context),
child: Text(label),
);
}
return MenuAnchor(
menuChildren: [
for (final option in PipelineSort.values)
MenuItemButton(
onPressed: () => onSelected(option),
child: Text(option.label),
),
],
builder: (context, menu, child) => TextButton(
onPressed: () => menu.isOpen ? menu.close() : menu.open(),
child: Text(label),
),
);
}
Future<void> _showCupertinoSheet(BuildContext context) {
return showCupertinoModalPopup<void>(
context: context,
builder: (sheetContext) => CupertinoActionSheet(
title: const Text('Sort pipelines'),
actions: [
for (final option in PipelineSort.values)
CupertinoActionSheetAction(
onPressed: () {
Navigator.of(sheetContext).pop();
onSelected(option);
},
child: Text(option.label),
),
],
cancelButton: CupertinoActionSheetAction(
isDefaultAction: true,
onPressed: () => Navigator.of(sheetContext).pop(),
child: const Text('Cancel'),
),
),
);
}
}
/// A truthful, non-blocking error line with an optional retry action.
class PipelineErrorBanner extends StatelessWidget {
const PipelineErrorBanner({
super.key,
required this.message,
this.retryLabel = 'Retry',
this.onRetry,
});
final String message;
final String retryLabel;
final VoidCallback? onRetry;
@override
Widget build(BuildContext context) {
final cupertino = useCupertinoControls(context);
final color = cupertino
? CupertinoColors.systemRed.resolveFrom(context)
: Theme.of(context).colorScheme.error;
return Semantics(
liveRegion: true,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(message, style: TextStyle(color: color)),
if (onRetry != null)
PipelineTextButton(label: retryLabel, onPressed: onRetry),
],
),
),
);
}
}
@@ -0,0 +1,175 @@
import 'package:flutter/material.dart';
import '../pipeline_graph_hook.dart';
import '../pipeline_models.dart';
import '../pipeline_query.dart';
import '../pipelines_controller.dart';
import 'pipeline_controls.dart';
import 'pipeline_detail_styles.dart';
import 'pipeline_summary_view.dart';
import 'pipeline_tabs.dart';
/// The right/bottom pane: Summary, Source and the optional graph hook.
class PipelineDetailPanel extends StatefulWidget {
const PipelineDetailPanel({
super.key,
required this.controller,
required this.showBack,
this.graphBuilder,
this.onStageSelected,
});
final PipelinesController controller;
final bool showBack;
final PipelineGraphBuilder? graphBuilder;
final ValueChanged<PipelineStageRef>? onStageSelected;
@override
State<PipelineDetailPanel> createState() => _PipelineDetailPanelState();
}
class _PipelineDetailPanelState extends State<PipelineDetailPanel> {
PipelineDetailTab _tab = PipelineDetailTab.summary;
PipelinesController get _controller => widget.controller;
@override
Widget build(BuildContext context) {
final detail = _controller.detail;
if (detail == null) return _withoutDetail(context);
return ListView(
key: const Key('pipeline-detail'),
children: [
_header(context, detail),
if (_controller.detailLoading)
const Padding(
padding: EdgeInsets.symmetric(horizontal: 16),
child: PipelineProgress(label: 'Refreshing pipeline detail'),
),
if (_controller.detailError != null)
PipelineErrorBanner(
message: _controller.detailError!,
onRetry: _controller.retryDetail,
),
PipelineDetailTabs(
selected: _tab,
onSelected: (tab) => setState(() => _tab = tab),
),
switch (_tab) {
PipelineDetailTab.summary => PipelineSummaryView(
controller: _controller,
detail: detail,
),
PipelineDetailTab.graph => _graph(context, detail),
PipelineDetailTab.source => _source(context, detail),
},
const SizedBox(height: 24),
],
);
}
Widget _withoutDetail(BuildContext context) {
if (!_controller.hasSelection) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Text('Select a pipeline.', style: pipelineMutedStyle(context)),
),
);
}
return ListView(
children: [
if (widget.showBack) _backRow(context),
if (_controller.detailLoading)
Padding(
padding: const EdgeInsets.all(24),
child: Column(
children: [
const PipelineProgress(label: 'Loading pipeline'),
const SizedBox(height: 12),
Text('Loading pipeline…', style: pipelineMutedStyle(context)),
],
),
),
if (_controller.detailError != null)
PipelineErrorBanner(
message: _controller.detailError!,
onRetry: _controller.retryDetail,
),
],
);
}
Widget _backRow(BuildContext context) => Padding(
padding: const EdgeInsets.fromLTRB(4, 4, 16, 0),
child: Row(
children: [
PipelineBackButton(onPressed: _controller.clearSelection),
const SizedBox(width: 4),
Expanded(child: Text('Pipeline', style: pipelineTitleStyle(context))),
],
),
);
Widget _header(BuildContext context, PipelineDetail detail) {
final title = Text(detail.displayName, style: pipelineTitleStyle(context));
final subtitle = Text(
pipelineSubtitle(detail),
style: pipelineMutedStyle(context),
);
return Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
child: widget.showBack
? Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
PipelineBackButton(onPressed: _controller.clearSelection),
const SizedBox(width: 4),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [title, subtitle],
),
),
],
)
: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [title, subtitle],
),
);
}
Widget _graph(BuildContext context, PipelineDetail detail) {
final builder = widget.graphBuilder;
if (builder == null) {
return Padding(
padding: const EdgeInsets.all(16),
child: Text(
'Graph rendering is pending (P2).',
style: pipelineMutedStyle(context),
),
);
}
return builder(
context,
detail,
(stageKey) => widget.onStageSelected?.call(
PipelineStageRef(
pipelineId: detail.id,
version: detail.resolvedVersion,
stageKey: stageKey,
),
),
);
}
Widget _source(BuildContext context, PipelineDetail detail) {
return Padding(
padding: const EdgeInsets.all(16),
child: detail.source.isEmpty
? Text('No source recorded.', style: pipelineMutedStyle(context))
: SelectableText(detail.source, style: pipelineValueStyle(context)),
);
}
}
@@ -0,0 +1,35 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'pipeline_controls.dart';
TextStyle? pipelineTitleStyle(BuildContext context) =>
useCupertinoControls(context)
? CupertinoTheme.of(context).textTheme.navLargeTitleTextStyle
: Theme.of(context).textTheme.headlineSmall;
TextStyle? pipelineSectionStyle(BuildContext context) =>
useCupertinoControls(context)
? CupertinoTheme.of(context).textTheme.navTitleTextStyle
: Theme.of(context).textTheme.titleMedium;
TextStyle? pipelineValueStyle(BuildContext context, {bool monospace = false}) {
final base = useCupertinoControls(context)
// SelectableText requires an explicit baseline when it inherits no style;
// merge the Cupertino system style with the ambient text style.
? CupertinoTheme.of(context).textTheme.textStyle.copyWith(inherit: true)
: Theme.of(context).textTheme.bodyMedium;
return monospace ? base?.copyWith(fontFamily: 'monospace') : base;
}
TextStyle? pipelineMutedStyle(BuildContext context) {
if (useCupertinoControls(context)) {
return CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith(
color: CupertinoColors.secondaryLabel.resolveFrom(context),
);
}
final theme = Theme.of(context);
return theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
);
}
@@ -0,0 +1,11 @@
/// The detail sections. Graph rendering is owned by the later graph item; the
/// tab row provides the tab and an optional integration hook.
enum PipelineDetailTab {
summary('Summary'),
graph('Graph'),
source('Source');
const PipelineDetailTab(this.label);
final String label;
}
@@ -0,0 +1,125 @@
import 'package:flutter/cupertino.dart';
import '../pipeline_filter.dart';
/// Cupertino filter form using native grouped lists and checkboxes.
class PipelineFilterCupertinoBody extends StatelessWidget {
const PipelineFilterCupertinoBody({
super.key,
required this.filters,
required this.name,
required this.hasUnclassified,
required this.onChanged,
required this.onClear,
});
final PipelineFilters filters;
final TextEditingController name;
final bool hasUnclassified;
final ValueChanged<PipelineFilters> onChanged;
final VoidCallback onClear;
@override
Widget build(BuildContext context) {
return ListView(
children: [
Padding(
padding: const EdgeInsets.all(16),
child: CupertinoTextField(
controller: name,
placeholder: 'Pipeline name contains',
),
),
CupertinoListSection.insetGrouped(
header: const Text('RUNS'),
children: [
for (final presence in RunPresence.values)
_choice(
label: presence.label,
selected: filters.presence == presence,
onTap: () => onChanged(filters.copyWith(presence: presence)),
),
],
),
CupertinoListSection.insetGrouped(
header: const Text('LAST RUN STATUS'),
children: [
for (final status in runStatusFilters)
_check(
label: status,
checked: filters.lastRunStatuses.contains(status),
onChanged: (checked) {
final next = {...filters.lastRunStatuses};
if (checked) {
next.add(status);
} else {
next.remove(status);
}
onChanged(filters.copyWith(lastRunStatuses: next));
},
),
],
),
CupertinoListSection.insetGrouped(
header: const Text('SCHEDULING'),
footer: const Text('Configured schedules, including paused.'),
children: [
for (final schedule in ScheduleFilter.values)
_choice(
label: schedule.label,
selected: filters.schedule == schedule,
onTap: () => onChanged(filters.copyWith(schedule: schedule)),
),
],
),
Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (hasUnclassified)
const Padding(
padding: EdgeInsets.only(bottom: 12),
child: Text(
'Some records have no scheduling metadata; they stay unclassified.',
),
),
CupertinoButton(
padding: EdgeInsets.zero,
onPressed: onClear,
child: const Text('Clear filters'),
),
],
),
),
],
);
}
Widget _choice({
required String label,
required bool selected,
required VoidCallback onTap,
}) {
return CupertinoListTile(
title: Text(label),
trailing: CupertinoCheckbox(value: selected, onChanged: (_) => onTap()),
onTap: onTap,
);
}
Widget _check({
required String label,
required bool checked,
required ValueChanged<bool> onChanged,
}) {
return CupertinoListTile(
title: Text(label),
trailing: CupertinoCheckbox(
value: checked,
onChanged: (value) => onChanged(value ?? false),
),
onTap: () => onChanged(!checked),
);
}
}
@@ -0,0 +1,108 @@
import 'package:flutter/material.dart';
import '../pipeline_filter.dart';
import 'pipeline_controls.dart';
/// Material filter form. Every change is reported to the page's draft; Done
/// applies the draft and leaving discards it.
class PipelineFilterMaterialBody extends StatelessWidget {
const PipelineFilterMaterialBody({
super.key,
required this.filters,
required this.name,
required this.hasUnclassified,
required this.onChanged,
required this.onClear,
});
final PipelineFilters filters;
final TextEditingController name;
final bool hasUnclassified;
final ValueChanged<PipelineFilters> onChanged;
final VoidCallback onClear;
@override
Widget build(BuildContext context) {
return ListView(
padding: const EdgeInsets.all(16),
children: [
TextField(
controller: name,
decoration: const InputDecoration(
labelText: 'Pipeline name contains',
),
),
_section(context, 'Runs'),
RadioGroup<RunPresence>(
groupValue: filters.presence,
onChanged: (value) {
if (value != null) {
onChanged(filters.copyWith(presence: value));
}
},
child: Column(
children: [
for (final presence in RunPresence.values)
RadioListTile<RunPresence>(
value: presence,
title: Text(presence.label),
),
],
),
),
_section(context, 'Last run status'),
for (final status in runStatusFilters)
CheckboxListTile(
value: filters.lastRunStatuses.contains(status),
onChanged: (checked) {
final next = {...filters.lastRunStatuses};
if (checked == true) {
next.add(status);
} else {
next.remove(status);
}
onChanged(filters.copyWith(lastRunStatuses: next));
},
title: Text(status),
),
_section(context, 'Scheduling'),
Text(
'Configured schedules, including paused.',
style: Theme.of(context).textTheme.bodySmall,
),
RadioGroup<ScheduleFilter>(
groupValue: filters.schedule,
onChanged: (value) {
if (value != null) onChanged(filters.copyWith(schedule: value));
},
child: Column(
children: [
for (final schedule in ScheduleFilter.values)
RadioListTile<ScheduleFilter>(
value: schedule,
title: Text(schedule.label),
),
],
),
),
if (hasUnclassified)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(
'Some records have no scheduling metadata; they stay unclassified.',
style: Theme.of(context).textTheme.bodySmall,
),
),
Align(
alignment: Alignment.centerLeft,
child: PipelineTextButton(label: 'Clear filters', onPressed: onClear),
),
],
);
}
Widget _section(BuildContext context, String title) => Padding(
padding: const EdgeInsets.only(top: 20, bottom: 4),
child: Text(title, style: Theme.of(context).textTheme.titleSmall),
);
}
@@ -0,0 +1,121 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../pipeline_filter.dart';
import 'pipeline_controls.dart';
import 'pipeline_filter_cupertino_body.dart';
import 'pipeline_filter_material_body.dart';
/// Opens the platform's native full-screen filter editor.
Future<void> openPipelineFilters(
BuildContext context, {
required PipelineFilters initial,
required bool hasUnclassified,
required ValueChanged<PipelineFilters> onApply,
}) {
final cupertino = useCupertinoControls(context);
final route = cupertino
? CupertinoPageRoute<void>(
fullscreenDialog: true,
builder: (_) => PipelineFilterPage(
initial: initial,
hasUnclassified: hasUnclassified,
onApply: onApply,
cupertino: true,
),
)
: MaterialPageRoute<void>(
fullscreenDialog: true,
builder: (_) => PipelineFilterPage(
initial: initial,
hasUnclassified: hasUnclassified,
onApply: onApply,
cupertino: false,
),
);
return Navigator.of(context).push(route);
}
/// A draft copy of the filters. Changes take effect on Done; leaving the page
/// discards them, so a half-edited filter never silently narrows the list.
class PipelineFilterPage extends StatefulWidget {
const PipelineFilterPage({
super.key,
required this.initial,
required this.hasUnclassified,
required this.onApply,
required this.cupertino,
});
final PipelineFilters initial;
final bool hasUnclassified;
final ValueChanged<PipelineFilters> onApply;
final bool cupertino;
@override
State<PipelineFilterPage> createState() => _PipelineFilterPageState();
}
class _PipelineFilterPageState extends State<PipelineFilterPage> {
late PipelineFilters _draft = widget.initial;
late final TextEditingController _name = TextEditingController(
text: widget.initial.name,
);
@override
void dispose() {
_name.dispose();
super.dispose();
}
void _apply() {
widget.onApply(_draft.copyWith(name: _name.text));
Navigator.of(context).pop();
}
void _clear() {
setState(() {
_draft = emptyPipelineFilters;
_name.text = '';
});
}
@override
Widget build(BuildContext context) {
final body = widget.cupertino
? PipelineFilterCupertinoBody(
filters: _draft,
name: _name,
hasUnclassified: widget.hasUnclassified,
onChanged: (filters) => setState(() => _draft = filters),
onClear: _clear,
)
: PipelineFilterMaterialBody(
filters: _draft,
name: _name,
hasUnclassified: widget.hasUnclassified,
onChanged: (filters) => setState(() => _draft = filters),
onClear: _clear,
);
if (widget.cupertino) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
middle: const Text('Filter pipelines'),
trailing: CupertinoButton(
padding: EdgeInsets.zero,
onPressed: _apply,
child: const Text('Done'),
),
),
child: SafeArea(child: body),
);
}
return Scaffold(
appBar: AppBar(
title: const Text('Filter pipelines'),
actions: [TextButton(onPressed: _apply, child: const Text('Done'))],
),
body: SafeArea(child: body),
);
}
}
@@ -0,0 +1,220 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../pipeline_format.dart';
import '../pipeline_models.dart';
import '../pipeline_query.dart';
import '../pipelines_controller.dart';
import 'pipeline_controls.dart';
import 'pipeline_filter_page.dart';
/// The left/top pane: filter and sort controls, then the truthful list states.
class PipelineListPanel extends StatelessWidget {
const PipelineListPanel({super.key, required this.controller});
final PipelinesController controller;
@override
Widget build(BuildContext context) {
final filters = controller.filters;
final hasUnclassified = controller.pipelines.any(
(pipeline) =>
pipeline.scheduleState == PipelineScheduleState.unclassified,
);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 8, 16, 4),
child: Wrap(
spacing: 8,
runSpacing: 4,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
PipelineTextButton(
key: const Key('pipeline-filter'),
label: filters.count == 0
? 'Filter'
: 'Filter (${filters.count})',
onPressed: () => openPipelineFilters(
context,
initial: filters,
hasUnclassified: hasUnclassified,
onApply: controller.setFilters,
),
),
PipelineSortButton(
key: const Key('pipeline-sort'),
sort: controller.sort,
onSelected: controller.setSort,
),
if (filters.active)
PipelineTextButton(
key: const Key('pipeline-clear-filters'),
label: 'Clear filters',
onPressed: controller.clearFilters,
),
],
),
),
if (controller.listError != null)
PipelineErrorBanner(
message: controller.listError!,
onRetry: controller.load,
),
if (controller.runsError != null)
PipelineErrorBanner(
message:
'${controller.runsLoaded ? 'Last runs could not be refreshed' : 'Last runs unavailable'}: '
'${controller.runsError}',
onRetry: controller.load,
),
if (controller.listLoading && controller.pipelinesLoaded)
const Padding(
padding: EdgeInsets.symmetric(horizontal: 16),
child: PipelineProgress(label: 'Refreshing pipelines'),
),
Expanded(child: _content(context)),
],
);
}
Widget _content(BuildContext context) {
if (controller.initialListLoading) {
return _centered(context, const ['Loading pipelines…']);
}
if (!controller.pipelinesLoaded) {
if (controller.listError != null) return const SizedBox.shrink();
return _centered(context, const ['Loading pipelines…']);
}
final items = controller.visiblePipelines;
if (items.isEmpty) {
final empty = controller.emptyState;
if (empty == null) return const SizedBox.shrink();
return _empty(context, empty);
}
return useCupertinoControls(context)
? _cupertinoList(context, items)
: _materialList(context, items);
}
Widget _centered(BuildContext context, List<String> messages) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const PipelineProgress(label: 'Loading pipelines'),
for (final message in messages)
Padding(
padding: const EdgeInsets.only(top: 12),
child: Text(message),
),
],
),
),
);
}
Widget _empty(BuildContext context, PipelineEmptyState empty) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
empty.message,
textAlign: TextAlign.center,
style: _mutedStyle(context),
),
if (empty.clearAction != null)
PipelineTextButton(
label: empty.clearAction!,
onPressed: controller.clearFilters,
),
],
),
),
);
}
Widget _materialList(BuildContext context, List<PipelineSummary> items) {
final now = DateTime.now();
return ListView.builder(
key: const Key('pipeline-list'),
itemCount: items.length,
itemBuilder: (context, index) {
final pipeline = items[index];
return ListTile(
key: Key('pipeline-row-${pipeline.id}'),
selected: controller.selectedId == pipeline.id,
onTap: () =>
controller.openPipeline(pipeline.id, version: pipeline.version),
title: Text(pipeline.displayName),
subtitle: _subtitle(context, pipeline, now),
);
},
);
}
Widget _cupertinoList(BuildContext context, List<PipelineSummary> items) {
final now = DateTime.now();
return ListView(
key: const Key('pipeline-list'),
children: [
CupertinoListSection.insetGrouped(
children: [
for (final pipeline in items)
CupertinoListTile(
key: Key('pipeline-row-${pipeline.id}'),
title: Text(pipeline.displayName),
subtitle: _subtitle(context, pipeline, now),
trailing: const CupertinoListTileChevron(),
onTap: () => controller.openPipeline(
pipeline.id,
version: pipeline.version,
),
),
],
),
],
);
}
Widget _subtitle(
BuildContext context,
PipelineSummary pipeline,
DateTime now,
) {
final rows = <Widget>[Text(pipelineSubtitle(pipeline))];
final updated = pipelineUpdatedLine(pipeline);
if (updated != null) rows.add(Text(updated));
if (pipeline.scheduleLabel.isNotEmpty) {
rows.add(Text(pipeline.scheduleLabel));
}
if (controller.runsLoaded) {
final run = controller.latestRuns[pipeline.id];
if (run == null) {
rows.add(Text('no runs recorded', style: _mutedStyle(context)));
} else {
final badge = runBadge(run, now);
rows.add(Text('${runStateLabel(badge.state)} · ${badge.metaLine}'));
}
}
return Column(crossAxisAlignment: CrossAxisAlignment.start, children: rows);
}
TextStyle? _mutedStyle(BuildContext context) {
if (useCupertinoControls(context)) {
return CupertinoTheme.of(context).textTheme.tabLabelTextStyle.copyWith(
color: CupertinoColors.secondaryLabel.resolveFrom(context),
);
}
final theme = Theme.of(context);
return theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
);
}
}
@@ -0,0 +1,151 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../pipeline_format.dart';
import '../pipeline_models.dart';
import '../pipeline_query.dart';
import '../pipelines_controller.dart';
import 'pipeline_controls.dart';
import 'pipeline_detail_styles.dart';
/// Summary tab: key/value facts plus the version history. Version rows are
/// selectable; the latest version's row is marked and a historical selection
/// offers an explicit return to latest.
class PipelineSummaryView extends StatelessWidget {
const PipelineSummaryView({
super.key,
required this.controller,
required this.detail,
});
final PipelinesController controller;
final PipelineDetail detail;
@override
Widget build(BuildContext context) {
final historical = detail.resolvedVersion != detail.latestVersion;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
if (historical)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: Text(
'Viewing v${detail.resolvedVersion} '
'(latest v${detail.latestVersion}).',
style: pipelineMutedStyle(context),
),
),
_fields(context),
_versions(context),
],
);
}
Widget _fields(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
for (final field in pipelineSummaryFields(detail))
Padding(
padding: const EdgeInsets.only(bottom: 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(field.key, style: pipelineMutedStyle(context)),
SelectableText(
field.value,
style: pipelineValueStyle(
context,
monospace: field.monospace,
),
),
],
),
),
],
),
);
}
Widget _versions(BuildContext context) {
final effective = detail.resolvedVersion;
final showingLatest = effective == detail.latestVersion;
final rows = <Widget>[
if (!showingLatest)
_versionTile(
context,
key: const Key('pipeline-latest-version'),
subtitle: 'Return to the latest version',
selected: false,
label: 'View latest v${detail.latestVersion}',
onTap: () => controller.selectVersion(0),
),
for (final version in detail.versions)
_versionTile(
context,
key: Key('pipeline-version-${version.version}'),
subtitle: [
stageCountText(version.stages),
?formatLocalTimestamp(version.createdAt),
].join(' · '),
selected: version.version == effective,
label: 'v${version.version}',
onTap: () => controller.selectVersion(version.version),
),
if (detail.versions.isEmpty)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: Text(
'No versions recorded.',
style: pipelineMutedStyle(context),
),
),
];
if (useCupertinoControls(context)) {
return CupertinoListSection.insetGrouped(
header: const Text('VERSIONS'),
children: rows,
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 4),
child: Text('Versions', style: pipelineSectionStyle(context)),
),
...rows,
],
);
}
Widget _versionTile(
BuildContext context, {
required Key key,
required String subtitle,
required bool selected,
required String label,
required VoidCallback onTap,
}) {
if (useCupertinoControls(context)) {
return CupertinoListTile(
key: key,
title: Text(label),
subtitle: Text(subtitle),
trailing: selected ? const Icon(CupertinoIcons.check_mark) : null,
onTap: onTap,
);
}
return ListTile(
key: key,
selected: selected,
title: Text(label),
subtitle: Text(subtitle),
trailing: selected ? const Icon(Icons.check) : null,
onTap: onTap,
);
}
}
@@ -0,0 +1,193 @@
import 'dart:math' as math;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'pipeline_detail_tab.dart';
/// Horizontal inset a label needs on each side in the per-label row.
const double pipelineTabSegmentPadding = 8;
/// The style the platform segmented control renders its labels in, so a
/// measured width is the width the label really paints.
TextStyle pipelineTabLabelStyle(
BuildContext context, {
required bool cupertino,
}) {
if (cupertino) return CupertinoTheme.of(context).textTheme.textStyle;
return Theme.of(context).textTheme.labelLarge ?? const TextStyle();
}
/// Measures every label for the current text style and text scaler.
List<Size> measurePipelineTabLabels(BuildContext context, TextStyle style) {
return [
for (final tab in PipelineDetailTab.values)
_measureLabel(context, tab.label, style),
];
}
Size _measureLabel(BuildContext context, String label, TextStyle style) {
final painter = TextPainter(
text: TextSpan(text: label, style: style),
textDirection: Directionality.of(context),
textScaler: MediaQuery.textScalerOf(context),
maxLines: 1,
)..layout();
final size = painter.size;
painter.dispose();
return size;
}
/// A segmented row whose segments are as wide as their own labels. It keeps
/// the platform segmented control's shape and theme colors, but not its
/// equal-share sizing.
///
/// [PipelineDetailTabs] uses it only when an equal share of the pane is too
/// narrow for the widest label or wider than the labels need together.
class PipelineTabRow extends StatelessWidget {
const PipelineTabRow({
super.key,
required this.selected,
required this.onSelected,
required this.labelSizes,
required this.labelStyle,
required this.rowHeight,
required this.available,
required this.cupertino,
});
final PipelineDetailTab selected;
final ValueChanged<PipelineDetailTab> onSelected;
final List<Size> labelSizes;
final TextStyle labelStyle;
final double rowHeight;
final double available;
final bool cupertino;
@override
Widget build(BuildContext context) {
final scheme = Theme.of(context).colorScheme;
final CupertinoThemeData cupertinoTheme = CupertinoTheme.of(context);
final Color borderColor = cupertino
? cupertinoTheme.primaryColor
: scheme.outline;
final Color selectedFill = cupertino
? cupertinoTheme.primaryColor
: scheme.secondaryContainer;
final Color selectedText = cupertino
? cupertinoTheme.primaryContrastingColor
: scheme.onSecondaryContainer;
final Color textColor = cupertino
? CupertinoColors.label.resolveFrom(context)
: scheme.onSurface;
final widths = [
for (final size in labelSizes) size.width + 2 * pipelineTabSegmentPadding,
];
final content = widths.fold<double>(0, (total, width) => total + width);
// The outer border takes one pixel on each side; spread any remaining
// width evenly so a row whose labels fit still fills the pane.
final inner = available.isFinite
? math.max(0, available - 2)
: double.infinity;
final extra = content < inner ? (inner - content) / widths.length : 0;
final tabs = PipelineDetailTab.values;
return Container(
decoration: BoxDecoration(
color: cupertino
? cupertinoTheme.primaryContrastingColor
: scheme.surface,
border: Border.all(color: borderColor),
borderRadius: BorderRadius.circular(20),
),
clipBehavior: Clip.antiAlias,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
for (var index = 0; index < tabs.length; index++)
_PerLabelSegment(
tab: tabs[index],
width: widths[index] + extra,
height: rowHeight,
selected: tabs[index] == selected,
labelStyle: labelStyle.copyWith(
color: tabs[index] == selected ? selectedText : textColor,
),
fillColor: tabs[index] == selected ? selectedFill : null,
dividerColor: index == tabs.length - 1 ? null : borderColor,
cupertino: cupertino,
onTap: () => onSelected(tabs[index]),
),
],
),
);
}
}
class _PerLabelSegment extends StatelessWidget {
const _PerLabelSegment({
required this.tab,
required this.width,
required this.height,
required this.selected,
required this.labelStyle,
required this.fillColor,
required this.dividerColor,
required this.cupertino,
required this.onTap,
});
final PipelineDetailTab tab;
final double width;
final double height;
final bool selected;
final TextStyle labelStyle;
final Color? fillColor;
final Color? dividerColor;
final bool cupertino;
final VoidCallback onTap;
@override
Widget build(BuildContext context) {
final label = Padding(
padding: const EdgeInsets.symmetric(
horizontal: pipelineTabSegmentPadding,
),
child: Text(tab.label, maxLines: 1, softWrap: false, style: labelStyle),
);
final Widget button = cupertino
? CupertinoButton(
padding: EdgeInsets.zero,
minimumSize: Size.zero,
onPressed: onTap,
child: label,
)
: Material(
type: MaterialType.transparency,
child: InkWell(
onTap: onTap,
child: Center(child: label),
),
);
return SizedBox(
key: ValueKey('pipeline-tab-${tab.name}'),
width: width,
height: height,
child: DecoratedBox(
decoration: BoxDecoration(
color: fillColor,
border: dividerColor == null
? null
: Border(right: BorderSide(color: dividerColor!)),
),
child: Semantics(
button: true,
inMutuallyExclusiveGroup: true,
selected: selected,
child: button,
),
),
);
}
}
@@ -0,0 +1,145 @@
import 'dart:math' as math;
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'pipeline_controls.dart';
import 'pipeline_detail_tab.dart';
import 'pipeline_tab_row.dart';
export 'pipeline_detail_tab.dart';
/// Platform tabs: a Material segmented button or a Cupertino segmented control.
///
/// Both platform controls give every segment the width of the widest label. At
/// narrow widths and scaled text that share is narrower than a label, so the
/// labels would wrap or be cut at the pane edge. When the equal share still
/// fits, the platform control is used unchanged. Otherwise a per-label row
/// gives every segment exactly its label's width and fills the pane when the
/// three labels fit; only a row that genuinely needs more room scrolls.
class PipelineDetailTabs extends StatelessWidget {
const PipelineDetailTabs({
super.key,
required this.selected,
required this.onSelected,
});
final PipelineDetailTab selected;
final ValueChanged<PipelineDetailTab> onSelected;
/// A safe upper bound for the padding the platform segmented controls add
/// inside each segment; the equal-share layout is only used when every label
/// still fits with this much room.
static const double _controlSegmentPadding = 32;
/// Smallest visual height, matching the platform controls at normal text.
static const double _minHeight = 32;
@override
Widget build(BuildContext context) {
final cupertino = useCupertinoControls(context);
final labelStyle = pipelineTabLabelStyle(context, cupertino: cupertino);
final labelSizes = measurePipelineTabLabels(context, labelStyle);
return Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
child: LayoutBuilder(
builder: (context, constraints) {
final available = constraints.hasBoundedWidth
? constraints.maxWidth
: double.infinity;
final widest = labelSizes.map((size) => size.width).reduce(math.max);
final equalShareFits =
!available.isFinite ||
available >= 3 * (widest + _controlSegmentPadding);
final control = equalShareFits
? (cupertino ? _cupertinoControl() : _materialControl())
: PipelineTabRow(
selected: selected,
onSelected: onSelected,
labelSizes: labelSizes,
labelStyle: labelStyle,
rowHeight: math.max(_minHeight, labelSizes.first.height),
available: available,
cupertino: cupertino,
);
return _ScrollWhenOverflowing(
child: KeyedSubtree(
key: const Key('pipeline-detail-tabs'),
child: control,
),
);
},
),
);
}
Widget _materialControl() {
return SegmentedButton<PipelineDetailTab>(
segments: [
for (final tab in PipelineDetailTab.values)
ButtonSegment(value: tab, label: _label(tab)),
],
selected: {selected},
showSelectedIcon: false,
onSelectionChanged: (selection) => onSelected(selection.single),
);
}
Widget _cupertinoControl() {
return CupertinoSegmentedControl<PipelineDetailTab>(
groupValue: selected,
onValueChanged: onSelected,
children: {
for (final tab in PipelineDetailTab.values)
tab: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: _label(tab),
),
},
);
}
Widget _label(PipelineDetailTab tab) {
// One line, and let the control size the segment to the whole word rather
// than wrapping inside it when scaled text is wider than the pane.
return Text(tab.label, maxLines: 1, softWrap: false);
}
}
/// Gives [child] the full available width as a minimum, then scrolls instead of
/// squeezing it below its content width.
class _ScrollWhenOverflowing extends StatelessWidget {
const _ScrollWhenOverflowing({required this.child});
final Widget child;
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
if (!constraints.hasBoundedWidth) return child;
return ScrollConfiguration(
// Desktop pointer scrolling is vertical only, so allow dragging the
// tab row with a mouse as well as touch and trackpad.
behavior: ScrollConfiguration.of(context).copyWith(
dragDevices: const {
PointerDeviceKind.touch,
PointerDeviceKind.mouse,
PointerDeviceKind.stylus,
PointerDeviceKind.invertedStylus,
PointerDeviceKind.trackpad,
},
),
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: ConstrainedBox(
constraints: BoxConstraints(minWidth: constraints.maxWidth),
child: child,
),
),
);
},
);
}
}
+239
View File
@@ -0,0 +1,239 @@
# P1 — Pipelines list, detail, source and versions
Candidate implementation for run 34 / Task v6. All work is under `app/`; no
commit, push, deployment or shell/main/pubspec edit was made.
## Implemented
- Public `PipelinesScreen({required ApiGateway gateway, graphBuilder,
onStageSelected})` in `lib/features/pipelines/screen.dart`.
- Read-only repository calls, with the web's exact request shapes:
- `list_pipelines` with no fields -> `pipelines` array;
- `list_runs` with no fields -> last-run join;
- `get_pipeline` `{pipeline_id, version}` -> `detail` (`version: 0` = latest).
No start, submit, schedule or other mutation exists in this feature.
- List: name, `id {id} · v{version} · {N stages}`, `updated d MMM HH:mm`,
configured-schedule label, and the latest run's state/ago/duration/id
(`no runs recorded` when absent). Rows request their own summary version.
- Filter: name contains, Runs Any/Has runs/No runs, seven last-run statuses,
Scheduling Any/Has/No schedules (paused counts as configured; older records
without metadata stay unclassified and are not matched by Has/No).
Run facets wait until `list_runs` has succeeded, matching web.
- Sort: Server order, Name A–Z/Z–A, Most recent run, Fewest/Most stages, with
the web's tie-breaks and server-order preservation.
- Clear filters and truthful filtered/no-pipeline empty wording.
- Detail: Summary (content hash, latest version, version created, pipeline
created/updated), Source as `SelectableText`, Versions always shown and
selectable, an explicit `View latest vN` return, and the selected row marked.
Historical selection shows `Viewing vN (latest vM).`
- Loading, empty, run-history, list and detail errors are explicit. Server
refusal text is shown verbatim; malformed replies get a fixed honest message.
- Request sequencing: a late detail reply cannot paint over a newer selection
or a cleared selection; late list refreshes cannot replace newer rows. Refresh
preserves the selected pipeline id and requested version and re-reads detail.
A failed refresh keeps already-loaded rows/history rather than inventing empty
data; a failed runs refresh keeps the previous successful run history and says
it could not be refreshed.
- Platform controls via `defaultTargetPlatform`: Material `Scaffold`/`ListTile`/
`SegmentedButton`/menu on Android/desktop; `CupertinoPageScaffold`/
`CupertinoListTile`/`CupertinoSegmentedControl`/action sheet/grouped lists on
iOS. One local 720px wide/narrow breakpoint; no custom palette, CSS tokens or
fixed button/row sizes.
- Graph remains P2. The Graph tab states `Graph rendering is pending (P2).` and
`graphBuilder`/`onStageSelected` provide the integration hook with pipeline
id, resolved version and stage key.
## Files
Source (all new, none ignored):
- `lib/features/pipelines/screen.dart`
- `lib/features/pipelines/pipelines_controller.dart`
- `lib/features/pipelines/pipeline_repository.dart`
- `lib/features/pipelines/pipeline_models.dart`
- `lib/features/pipelines/pipeline_format.dart`
- `lib/features/pipelines/pipeline_filter.dart`
- `lib/features/pipelines/pipeline_sort.dart`
- `lib/features/pipelines/pipeline_query.dart`
- `lib/features/pipelines/pipeline_graph_hook.dart`
- `lib/features/pipelines/widgets/pipeline_controls.dart`
- `lib/features/pipelines/widgets/pipeline_list_panel.dart`
- `lib/features/pipelines/widgets/pipeline_detail_panel.dart`
- `lib/features/pipelines/widgets/pipeline_detail_styles.dart`
- `lib/features/pipelines/widgets/pipeline_summary_view.dart`
- `lib/features/pipelines/widgets/pipeline_detail_tab.dart`
- `lib/features/pipelines/widgets/pipeline_tab_row.dart`
- `lib/features/pipelines/widgets/pipeline_tabs.dart`
- `lib/features/pipelines/widgets/pipeline_filter_page.dart`
- `lib/features/pipelines/widgets/pipeline_filter_material_body.dart`
- `lib/features/pipelines/widgets/pipeline_filter_cupertino_body.dart`
Tests (fake gateway only; no sockets):
- `test/features/pipelines/fixtures.dart`
- `test/features/pipelines/test_helpers.dart`
- `test/features/pipelines/pipeline_format_test.dart`
- `test/features/pipelines/pipeline_sort_test.dart`
- `test/features/pipelines/pipeline_filter_test.dart`
- `test/features/pipelines/pipelines_controller_load_test.dart`
- `test/features/pipelines/pipelines_controller_detail_test.dart`
- `test/features/pipelines/pipelines_screen_test.dart`
- `test/features/pipelines/pipelines_screen_filter_test.dart`
- `test/features/pipelines/pipelines_adaptive_test.dart`
- `test/features/pipelines/pipeline_tabs_test.dart` (added with the scaled-text tab fix)
Tooling:
- `tool/pipelines_probe_entry.dart` — separate fixture entry, main untouched
- `tool/pipelines_probe_fixture.dart`
- `tool/pipelines_probe_cdp.mjs`
- `tool/pipelines_probe_cdp_lib.mjs`
- `tool/pipelines_probe_cdp_input.mjs`
- `tool/pipelines_probe_tabs_scale.mjs` (added with the scaled-text tab fix)
## Checks actually run
| Check | Result |
| --- | --- |
| `flutter pub get` | completed |
| `flutter analyze` | `No issues found!` |
| `flutter test` (all app tests) | **52 passed** |
| `flutter test test/features/pipelines` (feature only) | **51 passed** |
| `flutter test test/features/pipelines/pipeline_tabs_test.dart` | **12 passed** |
| `dart format --output=none --set-exit-if-changed` (changed Dart files) | 0 changed |
| `flutter build web` (default `lib/main.dart`) | `✓ Built build/web` |
| `flutter build web -t tool/pipelines_probe_entry.dart --output .../private/web-fit` | `✓ Built` |
| `node --check` on all four probe scripts | passed |
| real Chrome fixture probe (`tool/pipelines_probe_cdp.mjs`) | exit 0; 7 AX checks + 9 PNGs, `probe.json` has no error |
| real Chrome tab-scale probe (`tool/pipelines_probe_tabs_scale.mjs`) | exit 0; 29 checks + 10 PNGs, `probe.json` has no error |
Coverage includes exact list/get/list_runs envelopes and request fields, filter/
sort/schedule wording and behavior, version selection, server refusals and
malformed detail, out-of-order detail replies (including after Back), stale list
refresh, refresh selection retention, narrow 390px, 2x text at 390px and
1100px, iOS Cupertino controls, graph-pending message, the graph hook, and
whole plus at-rest-visible tab labels at 150%/320px and 200%/320/390/720px
(including scrolling to the last tab with a mouse drag and by keyboard).
## Browser captures (real Chrome, fixture bundle)
Directory: `/Users/alan/.local/share/pipelines/data/artifacts/34/public/p1-captures`
- `01-list-desktop.png` — 1200×900 list with all rows, schedules, last runs.
- `02-detail-summary.png` — list→detail Summary, fields and Versions.
- `03-source-latest.png` — Source tab with latest (v3) source.
- `04-source-selection.png` — the first source line visibly selected by a real
mouse drag, proving the source is selectable text.
- `05-version-v1.png` — after selecting v1: `Viewing v1 (latest v3).`, v1 hash/
stage count, `View latest v3`, and v1 checked.
- `06-source-v1.png` — Source tab after the version change, ending in
`# selected version 1`.
- `07-list-390.png` — 390×844 list.
- `08-detail-390.png` — 390×844 Hotfix triage detail with versions.
- `09-filter-390.png` — 390×844 native filter page (name, Runs, last statuses,
Scheduling).
- `probe.json` — actions, AX checks and capture paths.
The probe uses the fixture gateway from `tool/pipelines_probe_fixture.dart`; it
never contacts a server. The version row was clicked at the fixed fixture layout
position `(620, 489)` for the 1200×900 viewport because Flutter's web semantics
tree in this build exposes the tabs/heading/list rows but omits the detail-body
rows. Version selection evidence is the rendered `05`/`06` captures inspected
after the run, not an AX assertion.
## Scaled-text tab sizing (UI review findings)
The UI review found two successive defects in the detail tabs
(`pipeline_tabs.dart`):
1. Labels broke inside words when scaled text no longer fitted the
equal-width segments (`Summa`/`ry`, `Sourc`/`e`).
2. After making labels single-line and the row scrollable, the row was still
3 × the widest label wide. At rest it cut the third tab to `Sour` at
320/150%, `Sourc` at 390/200%, and an empty 16 px cell at 320/200%.
Cause: `SegmentedButton` (and `CupertinoSegmentedControl`) give every segment
the width of the widest label. That share is both narrow enough to wrap a
different label and up to a third wider than the labels need together.
Fix: `PipelineDetailTabs` measures each label with the control's own text
style and text scaler and picks one of two layouts:
- When `3 × (widest label + the control's inner padding)` still fits the pane,
the standard Material `SegmentedButton` / Cupertino `CupertinoSegmentedControl`
is used unchanged, filling the pane as before. This is the normal-text and
wide-pane path.
- Otherwise a per-label segmented row gives every segment exactly its own
label width plus 8 px on each side. If the three labels fit, the spare width
is spread evenly and the row fills the pane; if they do not, only the row's
real minimum overflow scrolls (mouse drag, trackpad/Shift+wheel and keyboard
traversal on desktop; touch elsewhere). The row keeps the platform
segmented control's shape and theme colors (`secondaryContainer`/
`onSecondaryContainer`/`outline`, or the Cupertino primary/contrasting
colors) and uses standard `InkWell`/`CupertinoButton` segments, so no
palette, font size or wording is hard-coded. Labels stay single-line: no
intra-word break and no ellipsis.
Acceptance checks (real Chrome, fixture bundle):
| State | Result |
| --- | --- |
| 320×640 @150% | All three labels fully visible at rest; row fills the 288 px pane. |
| 390×844 @200% | All three labels fully visible at rest; row fills the 358 px pane. |
| 720×900 @200% | All three labels fully visible at rest; row fills the 401 px detail pane. |
| 320×640 @200% | `Source` is a recognisable partial label at rest (60.1 px visible, `Sour`), not an empty cell; a mouse drag reveals it fully. |
| 1200×900 @100% | Row still 687.4 px wide, matching the previous layout exactly. |
| Selection | Mouse drag + click switches to the source text; keyboard Tab traversal reaches and scrolls `Source` into view. |
Widget tests cover: no intra-word wrap at the four states; per-label segment
widths when overflowing; a row whose labels fit fills the pane with every
label inside it; an overflowing row scrolls only by its measured overflow and
selects the last tab; the standard Material/Cupertino control is still used
where it fits; Cupertino at 320/2× uses per-label standard Cupertino buttons.
The Flutter test font (Ahem) is much wider than Roboto, so at-rest visibility
at the exact acceptance widths is browser evidence, not widget-test evidence.
Evidence (real Chrome, fixture bundle):
`/Users/alan/.local/share/pipelines/data/artifacts/34/public/p1-tabs-fit`
- `01-320-text150-atrest.png`, `02-320-text200-atrest.png`
- `03-390-text200-atrest.png`, `04-720-text200-atrest.png`
- `05-320-text150-atrest-dark.png`, `06-390-text200-atrest-dark.png`
- `07-320-text200-scrolled.png`, `08-320-text200-source.png`
- `09-320-text200-keyboard.png`, `10-1200-text100-detail.png`
- `README.md`, `probe.json`, reproduced by
`node tool/pipelines_probe_tabs_scale.mjs <build-dir> <capture-dir>`.
The probe asserts at-rest visibility directly, not only label heights: for
every full-visibility state it drags the row to its limit and fails if that
exposes any extra label width (a clipped accessibility box still reports an
edge inside the pane), and it checks the allowed partial `Source` at 320/200%.
The Cupertino path is covered by widget tests only: the web build reports
Material.
## Explicitly not done / unverified
- Graph nodes, edges and stage panes are **not implemented** (P2); only the tab
message and host hook exist. No list mini-graphs either.
- No live-server or authenticated preview was used. Browser evidence is against
an in-memory fixture; it does not claim live parity.
- Android and iOS were not built, installed or run. Only web was tested; mobile
remains unverified. 2x text and narrow layout are widget-test evidence, not a
real-device claim.
- No schedules editor, templates, create/submit/run actions, live events or
search integration.
- Versions are rendered always visible rather than the web's collapsed-by-
default section. This is a layout choice; selection/history behavior and
wording are preserved.
- The browser semantics omission means no automated AX assertion exists for the
detail fields/source/version row; those are proven by captures and widget
tests.
## Repository state
`git diff --stat` is empty because every file is new and untracked. `git status
--short --untracked-files=all` lists all 38 source/test/tool files above; `git
ls-files --others --exclude-standard` returns the same set and `git check-ignore`
reports none of them ignored. No tracked file (including `main.dart`,
`pubspec.*`, shell/web) was modified. Not committed, pushed or deployed, per the
stage rules.
+219
View File
@@ -0,0 +1,219 @@
import 'dart:async';
import 'package:pipelines_app/core/api_gateway.dart';
/// One recorded gateway call, so tests can assert exact request shapes.
class GatewayCall {
GatewayCall(this.type, this.fields);
final String type;
final JsonMap fields;
@override
String toString() => '$type $fields';
}
/// A hand-written gateway. Tests decide every reply; nothing here touches a
/// server, socket or shared state.
class FakeGateway implements ApiGateway {
FakeGateway(this.handler);
final FutureOr<JsonMap> Function(String type, JsonMap fields) handler;
final List<GatewayCall> calls = <GatewayCall>[];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
calls.add(GatewayCall(type, Map<String, dynamic>.from(fields)));
return handler(type, fields);
}
@override
Stream<JsonMap> get frames => const Stream<JsonMap>.empty();
List<GatewayCall> callsOf(String type) =>
calls.where((call) => call.type == type).toList(growable: false);
}
Map<String, dynamic> pipelineSummary({
required int id,
required String name,
int version = 1,
int stages = 1,
String updatedAt = '2026-10-17T21:26:00',
int? scheduleCount = 0,
bool? scheduled = false,
}) => {
'id': id,
'name': name,
'version': version,
'stages': stages,
'created_at': '2026-10-01T09:00:00',
'updated_at': updatedAt,
'scheduled': scheduled,
'schedule_count': scheduleCount,
'enabled_schedule_count': scheduleCount,
};
Map<String, dynamic> pipelineDetail({
required int id,
required String name,
required int version,
required int latestVersion,
String source = 'name: alpha',
int stages = 1,
String contentHash = 'abc123',
int? scheduleCount = 0,
bool? scheduled = false,
List<Map<String, dynamic>> versions = const [],
}) => {
...pipelineSummary(
id: id,
name: name,
version: version,
stages: stages,
scheduleCount: scheduleCount,
scheduled: scheduled,
),
'latest_version': latestVersion,
'version_created_at': '2026-10-17T21:24:00',
'content_hash': contentHash,
'source': source,
'versions': versions,
};
Map<String, dynamic> versionSummary(
int version, {
int stages = 1,
String createdAt = '2026-10-17T21:24:00',
}) => {'version': version, 'stages': stages, 'created_at': createdAt};
Map<String, dynamic> pipelineRun({
required int id,
required int pipelineId,
String status = 'succeeded',
String createdAt = '2026-10-17T19:00:00',
String finishedAt = '2026-10-17T19:01:05',
bool executing = false,
}) => {
'id': id,
'pipeline_id': pipelineId,
'status': status,
'created_at': createdAt,
'finished_at': finishedAt,
'executing': executing,
};
JsonMap pipelineListReply(List<Map<String, dynamic>> pipelines) => {
'type': 'pipelines',
'pipelines': pipelines,
};
JsonMap pipelineDetailReply(Map<String, dynamic> detail) => {
'type': 'pipeline',
'detail': detail,
};
JsonMap runListReply(List<Map<String, dynamic>> runs) => {
'type': 'runs',
'runs': runs,
};
JsonMap errorReply(String message) => {'type': 'error', 'error': message};
/// A small complete fixture used by widget/browser-facing tests.
class PipelineFixture {
PipelineFixture({this.now});
final DateTime? now;
late final List<Map<String, dynamic>> summaries = [
pipelineSummary(
id: 1,
name: 'Alpha review',
version: 2,
stages: 2,
scheduleCount: 1,
scheduled: true,
),
pipelineSummary(
id: 2,
name: 'Beta deploy',
version: 1,
stages: 1,
updatedAt: '2026-10-16T08:05:00',
scheduleCount: 0,
scheduled: false,
),
pipelineSummary(
id: 3,
name: 'Gamma legacy',
version: 1,
stages: 3,
updatedAt: '2026-10-15T12:00:00',
scheduleCount: null,
scheduled: null,
),
];
late final List<Map<String, dynamic>> details = [
pipelineDetail(
id: 1,
name: 'Alpha review',
version: 2,
latestVersion: 2,
stages: 2,
contentHash: 'hash-alpha',
scheduleCount: 1,
scheduled: true,
source: 'name: Alpha review\nstages:\n review:\n type: model',
versions: [versionSummary(1, stages: 1), versionSummary(2, stages: 2)],
),
pipelineDetail(
id: 2,
name: 'Beta deploy',
version: 1,
latestVersion: 1,
contentHash: 'hash-beta',
source: 'name: Beta deploy\nstages:\n deploy:\n type: human',
versions: [versionSummary(1)],
),
pipelineDetail(
id: 3,
name: 'Gamma legacy',
version: 1,
latestVersion: 1,
stages: 3,
contentHash: 'hash-gamma',
scheduleCount: null,
scheduled: null,
source: 'name: Gamma legacy',
versions: [versionSummary(1, stages: 3)],
),
];
late final List<Map<String, dynamic>> runs = [
pipelineRun(id: 42, pipelineId: 1),
pipelineRun(
id: 41,
pipelineId: 2,
status: 'failed',
createdAt: '2026-10-16T08:10:00',
finishedAt: '2026-10-16T08:11:00',
),
];
Map<String, dynamic>? detailFor(int id, int version) {
final match = details.where((detail) => detail['id'] == id);
if (match.isEmpty) return null;
final detail = Map<String, dynamic>.from(match.first);
if (version > 0) {
detail['version'] = version;
for (final row in detail['versions'] as List<Map<String, dynamic>>) {
if (row['version'] == version) detail['stages'] = row['stages'];
}
if (version < (detail['latest_version'] as int)) {
detail['source'] = '${detail['source']}\n# selected version $version';
}
}
return detail;
}
}
@@ -0,0 +1,160 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/pipelines/pipeline_models.dart';
import 'package:pipelines_app/features/pipelines/pipeline_query.dart';
import 'fixtures.dart';
void main() {
final alpha = PipelineSummary.fromJson(
pipelineSummary(
id: 1,
name: 'Alpha review',
stages: 2,
scheduleCount: 1,
scheduled: true,
),
);
final beta = PipelineSummary.fromJson(
pipelineSummary(
id: 2,
name: 'Beta deploy',
scheduleCount: 0,
scheduled: false,
),
);
final gamma = PipelineSummary.fromJson(
pipelineSummary(
id: 3,
name: 'Gamma legacy',
scheduleCount: null,
scheduled: null,
),
);
final all = [alpha, beta, gamma];
final latestRuns = latestRunByPipeline([
PipelineRun.fromJson(pipelineRun(id: 5, pipelineId: 1)),
PipelineRun.fromJson(pipelineRun(id: 6, pipelineId: 2, status: 'failed')),
]);
test('name and schedule narrow independently', () {
expect(
filterPipelines(
all,
const PipelineFilters(name: 'ALPHA'),
latestRuns,
true,
).map((pipeline) => pipeline.id),
[1],
);
expect(
filterPipelines(
all,
const PipelineFilters(schedule: ScheduleFilter.scheduled),
latestRuns,
true,
).map((pipeline) => pipeline.id),
[1],
);
expect(
filterPipelines(
all,
const PipelineFilters(schedule: ScheduleFilter.unscheduled),
latestRuns,
true,
).map((pipeline) => pipeline.id),
[2],
);
});
test('run facets are skipped until the run history is known', () {
const filters = PipelineFilters(presence: RunPresence.noRuns);
expect(
filterPipelines(
all,
filters,
latestRuns,
false,
).map((pipeline) => pipeline.id),
[1, 2, 3],
);
expect(
filterPipelines(
all,
filters,
latestRuns,
true,
).map((pipeline) => pipeline.id),
[3],
);
});
test('last run status needs a matching run', () {
expect(
filterPipelines(
all,
const PipelineFilters(lastRunStatuses: {'failed'}),
latestRuns,
true,
).map((pipeline) => pipeline.id),
[2],
);
expect(
filterPipelines(
all,
const PipelineFilters(lastRunStatuses: {'waiting'}),
latestRuns,
true,
),
isEmpty,
);
});
test('facet counting and empty-state wording', () {
const filters = PipelineFilters(
name: 'nope',
presence: RunPresence.hasRuns,
schedule: ScheduleFilter.scheduled,
);
expect(filters.active, isTrue);
expect(filters.count, 3);
final empty = pipelineListEmptyState(all, const [], filters);
expect(empty?.message, 'No pipelines match the current filters.');
expect(empty?.clearAction, 'Clear filters');
final onlyName = pipelineListEmptyState(
all,
const [],
const PipelineFilters(name: 'nope'),
);
expect(onlyName?.message, 'No pipelines match "nope".');
expect(
pipelineListEmptyState(
const [],
const [],
const PipelineFilters(),
)?.message,
'No pipelines are defined on this server.',
);
expect(pipelineListEmptyState(all, all, const PipelineFilters()), isNull);
});
test('run badge omits unusable fragments but keeps the run id', () {
final run = PipelineRun.fromJson(
pipelineRun(id: 9, pipelineId: 1, createdAt: '', finishedAt: ''),
);
expect(runBadge(run, DateTime(2026, 10, 17)).metaLine, 'run 9');
final executing = PipelineRun.fromJson(
pipelineRun(
id: 10,
pipelineId: 1,
status: 'running',
createdAt: '2026-10-17T21:00:00',
finishedAt: '',
executing: true,
),
);
expect(
runBadge(executing, DateTime(2026, 10, 17, 21, 2)).metaLine,
contains('2m 0s'),
);
});
}
@@ -0,0 +1,95 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/pipelines/pipeline_format.dart';
import 'package:pipelines_app/features/pipelines/pipeline_models.dart';
import 'package:pipelines_app/features/pipelines/pipeline_query.dart';
import 'fixtures.dart';
void main() {
group('formatting', () {
test('renders local timestamps, durations and ages', () {
expect(formatLocalTimestamp('2026-10-17T21:26:00'), '17 Oct 21:26');
expect(formatLocalTimestamp(''), isNull);
expect(formatLocalTimestamp('not a time'), isNull);
expect(formatDuration(0), '0s');
expect(formatDuration(45), '45s');
expect(formatDuration(125), '2m 5s');
expect(formatDuration(3720), '1h 2m');
expect(formatDuration(-4), '0s');
expect(stageCountText(1), '1 stage');
expect(stageCountText(2), '2 stages');
final now = DateTime(2026, 10, 17, 21, 30);
expect(formatRanAgo('2026-10-17T21:29:40', now), 'just now');
expect(formatRanAgo('2026-10-17T21:25:00', now), '5m ago');
expect(formatRanAgo('2026-10-17T19:30:00', now), '2h ago');
expect(formatRanAgo('2026-10-14T21:30:00', now), '3d ago');
expect(formatRanAgo('2026-10-17T22:00:00', now), 'just now');
});
test('maps the server status vocabulary and unknown values', () {
expect(runStateOf('success'), 'succeeded');
expect(runStateOf('CANCELLED'), 'canceled');
expect(runStateOf('error'), 'failed');
expect(runStateOf('mystery'), 'unknown');
expect(runStateOf(null), 'unknown');
expect(runStateLabel('running'), 'Running');
});
});
group('pipeline detail', () {
test('parses the get_pipeline detail and resolves latest', () {
final detail = PipelineDetail.fromJson(
pipelineDetail(
id: 7,
name: 'Seven',
version: 0,
latestVersion: 3,
source: 'name: seven',
versions: [versionSummary(1), versionSummary(2), versionSummary(3)],
),
);
expect(detail.id, 7);
expect(detail.latestVersion, 3);
expect(detail.resolvedVersion, 3);
expect(detail.source, 'name: seven');
expect(detail.versions.map((version) => version.version), [1, 2, 3]);
expect(pipelineSubtitle(detail), 'id 7 · v0 · 1 stage');
expect(pipelineSummaryFields(detail).first.key, 'Content hash');
expect(
pipelineSummaryFields(
detail,
).firstWhere((field) => field.key == 'Latest version').value,
'v3',
);
});
test(
'schedule state distinguishes configured, absent and unknown peers',
() {
expect(
PipelineSummary.fromJson(
pipelineSummary(id: 1, name: 'a', scheduleCount: 2),
).scheduleState,
PipelineScheduleState.scheduled,
);
expect(
PipelineSummary.fromJson(
pipelineSummary(
id: 1,
name: 'a',
scheduleCount: null,
scheduled: null,
),
).scheduleState,
PipelineScheduleState.unclassified,
);
expect(
PipelineSummary.fromJson(
pipelineSummary(id: 1, name: 'a'),
).scheduleLabel,
'',
);
},
);
});
}
@@ -0,0 +1,82 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/pipelines/pipeline_models.dart';
import 'package:pipelines_app/features/pipelines/pipeline_query.dart';
import 'fixtures.dart';
void main() {
final alpha = PipelineSummary.fromJson(
pipelineSummary(id: 3, name: 'alpha', version: 1, stages: 2),
);
final beta = PipelineSummary.fromJson(
pipelineSummary(id: 2, name: 'Beta', version: 1, stages: 1),
);
final gamma = PipelineSummary.fromJson(
pipelineSummary(id: 1, name: 'gamma', version: 1, stages: 3),
);
final original = [alpha, beta, gamma];
test('server order is untouched', () {
expect(
sortPipelines(original, PipelineSort.serverOrder, {}),
equals(original),
);
});
test('name order is case-insensitive with a stable tie-break', () {
expect(
sortPipelines(
original,
PipelineSort.nameAsc,
{},
).map((pipeline) => pipeline.name),
['alpha', 'Beta', 'gamma'],
);
expect(
sortPipelines(
original,
PipelineSort.nameDesc,
{},
).map((pipeline) => pipeline.name),
['gamma', 'Beta', 'alpha'],
);
});
test('stage order uses the name then id tie-break', () {
expect(
sortPipelines(
original,
PipelineSort.fewestStages,
{},
).map((pipeline) => pipeline.id),
[2, 3, 1],
);
expect(
sortPipelines(
original,
PipelineSort.mostStages,
{},
).map((pipeline) => pipeline.id),
[1, 3, 2],
);
});
test('most recent run puts pipelines without runs last', () {
final runs = latestRunByPipeline([
PipelineRun.fromJson(pipelineRun(id: 10, pipelineId: 3)),
PipelineRun.fromJson(
pipelineRun(id: 12, pipelineId: 3, createdAt: '2026-10-18T18:00:00'),
),
PipelineRun.fromJson(pipelineRun(id: 11, pipelineId: 2)),
]);
expect(runs[3]?.id, 12);
expect(
sortPipelines(
original,
PipelineSort.recentRun,
runs,
).map((pipeline) => pipeline.id),
[3, 2, 1],
);
});
}
@@ -0,0 +1,253 @@
import 'dart:math' as math;
import 'dart:ui' show PointerDeviceKind;
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/pipelines/widgets/pipeline_tabs.dart';
const double _paneInset = 16;
/// A label that wrapped inside its word renders narrower than the width the
/// paragraph needs on one line.
void expectWholeLabel(WidgetTester tester, String label) {
final paragraph = tester.renderObject<RenderParagraph>(find.text(label));
expect(
paragraph.size.width,
greaterThanOrEqualTo(
paragraph.getMaxIntrinsicWidth(double.infinity) - 0.01,
),
reason: '"$label" must not wrap inside the word',
);
}
double labelWidth(WidgetTester tester, String label) =>
tester.getSize(find.text(label)).width;
Rect tabRect(WidgetTester tester, PipelineDetailTab tab) =>
tester.getRect(find.byKey(ValueKey('pipeline-tab-${tab.name}')));
Future<void> pumpTabs(
WidgetTester tester, {
required double width,
required double textScale,
bool cupertino = false,
ValueChanged<PipelineDetailTab>? onSelected,
}) async {
tester.view.physicalSize = Size(width, 640);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final tabs = StatefulBuilder(
builder: (context, setState) => PipelineDetailTabs(
selected: PipelineDetailTab.summary,
onSelected: (tab) {
onSelected?.call(tab);
setState(() {});
},
),
);
final content = Align(alignment: Alignment.topLeft, child: tabs);
Widget scaled(BuildContext context, Widget? child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(textScale)),
child: child!,
);
await tester.pumpWidget(
cupertino
? CupertinoApp(
builder: scaled,
home: CupertinoPageScaffold(child: content),
)
: MaterialApp(
builder: scaled,
home: Scaffold(body: content),
),
);
await tester.pumpAndSettle();
}
void main() {
for (final (width, scale) in [
(320.0, 1.5),
(320.0, 2.0),
(390.0, 2.0),
(720.0, 2.0),
]) {
testWidgets(
'Material tab labels stay whole at ${width.toInt()}px and ${scale}x text',
(tester) async {
await pumpTabs(tester, width: width, textScale: scale);
expect(tester.takeException(), isNull);
for (final tab in PipelineDetailTab.values) {
expect(find.text(tab.label), findsOneWidget);
expectWholeLabel(tester, tab.label);
}
},
);
}
testWidgets('per-label segments size to their own labels', (tester) async {
await pumpTabs(tester, width: 320, textScale: 2);
final widths = {
for (final tab in PipelineDetailTab.values)
tab: tabRect(tester, tab).width,
};
expect(
widths[PipelineDetailTab.summary],
isNot(widths[PipelineDetailTab.graph]),
);
expect(
widths[PipelineDetailTab.graph],
isNot(widths[PipelineDetailTab.source]),
);
for (final tab in PipelineDetailTab.values) {
expect(
widths[tab],
closeTo(labelWidth(tester, tab.label) + 2 * 8, 0.5),
reason: '"${tab.label}" must not get the widest-label share',
);
}
});
testWidgets('a fitting tab row shows every label inside the pane', (
tester,
) async {
await pumpTabs(tester, width: 320, textScale: 2);
final contentWidth =
tabRect(tester, PipelineDetailTab.source).right -
tabRect(tester, PipelineDetailTab.summary).left;
final width = contentWidth + 2 * _paneInset + 2;
await pumpTabs(tester, width: width, textScale: 2);
expect(tester.takeException(), isNull);
for (final tab in PipelineDetailTab.values) {
expectWholeLabel(tester, tab.label);
final rect = tester.getRect(find.text(tab.label));
expect(rect.left, greaterThanOrEqualTo(_paneInset - 0.5));
expect(rect.right, lessThanOrEqualTo(width - _paneInset + 0.5));
}
expect(
tester.getSize(find.byKey(const Key('pipeline-detail-tabs'))).width,
closeTo(width - 2 * _paneInset, 0.5),
reason: 'a row whose labels fit still fills the pane',
);
});
testWidgets('a tab row that overflows only scrolls by the labels\' need', (
tester,
) async {
PipelineDetailTab? selected;
await pumpTabs(tester, width: 320, textScale: 2);
final contentWidth =
tabRect(tester, PipelineDetailTab.source).right -
tabRect(tester, PipelineDetailTab.summary).left;
final width = contentWidth + 2 * _paneInset - 20;
await pumpTabs(
tester,
width: width,
textScale: 2,
onSelected: (tab) => selected = tab,
);
final paneRight = width - _paneInset;
final source = tester.getRect(find.text('Source'));
expect(
tabRect(tester, PipelineDetailTab.source).left,
lessThan(paneRight),
reason: 'the third tab must not be an empty cell',
);
expect(
math.min(source.right, paneRight) - math.max(source.left, _paneInset),
greaterThan(20),
reason: 'a readable share of the last label stays in the pane',
);
expect(source.right, greaterThan(paneRight));
final row = find.byType(SingleChildScrollView);
await tester.drag(
row,
const Offset(-400, 0),
kind: PointerDeviceKind.mouse,
);
await tester.pumpAndSettle();
expect(
tester.getRect(find.text('Source')).right,
lessThanOrEqualTo(paneRight + 0.01),
reason: 'the last tab is fully visible after dragging',
);
await tester.tap(find.text('Source'));
await tester.pumpAndSettle();
expect(selected, PipelineDetailTab.source);
});
testWidgets('720px at 2x text shows all three labels at rest', (
tester,
) async {
await pumpTabs(tester, width: 720, textScale: 2);
for (final tab in PipelineDetailTab.values) {
final rect = tester.getRect(find.text(tab.label));
expect(rect.left, greaterThanOrEqualTo(_paneInset - 0.5));
expect(rect.right, lessThanOrEqualTo(720 - _paneInset + 0.5));
}
});
testWidgets('a fitting tab row still fills the pane at 1x', (tester) async {
await pumpTabs(tester, width: 400, textScale: 1);
expect(
tester.getSize(find.byKey(const Key('pipeline-detail-tabs'))).width,
closeTo(368, 0.5),
);
});
testWidgets('the wide row keeps the platform Material control', (
tester,
) async {
await pumpTabs(tester, width: 1200, textScale: 1);
expect(find.byType(SegmentedButton<PipelineDetailTab>), findsOneWidget);
expect(
tester.getSize(find.byKey(const Key('pipeline-detail-tabs'))).width,
closeTo(1168, 0.5),
);
});
testWidgets('Cupertino tab labels stay whole at 320px and 2x text', (
tester,
) async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
try {
await pumpTabs(tester, width: 320, textScale: 2, cupertino: true);
expect(tester.takeException(), isNull);
// The labels do not fit an equal-share control here, so the per-label
// row of standard Cupertino buttons is used.
expect(
find.byType(CupertinoButton),
findsNWidgets(PipelineDetailTab.values.length),
);
for (final tab in PipelineDetailTab.values) {
expectWholeLabel(tester, tab.label);
}
} finally {
debugDefaultTargetPlatformOverride = null;
}
});
testWidgets('Cupertino keeps its native segmented control where it fits', (
tester,
) async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
try {
await pumpTabs(tester, width: 1200, textScale: 1, cupertino: true);
expect(
find.byType(CupertinoSegmentedControl<PipelineDetailTab>),
findsOneWidget,
);
for (final tab in PipelineDetailTab.values) {
expectWholeLabel(tester, tab.label);
}
} finally {
debugDefaultTargetPlatformOverride = null;
}
});
}
@@ -0,0 +1,178 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/pipelines/screen.dart';
import 'package:pipelines_app/features/pipelines/widgets/pipeline_tabs.dart';
import 'fixtures.dart';
import 'test_helpers.dart';
void main() {
testWidgets('narrow layout is list then detail with a native back', (
tester,
) async {
tester.view.physicalSize = const Size(390, 844);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final fixture = PipelineFixture();
await tester.pumpWidget(
MaterialApp(home: PipelinesScreen(gateway: gatewayFor(fixture))),
);
await tester.pumpAndSettle();
expect(find.byKey(const Key('pipeline-list')), findsOneWidget);
expect(find.byKey(const Key('pipeline-detail')), findsNothing);
await tester.tap(find.byKey(const Key('pipeline-row-1')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('pipeline-list')), findsNothing);
expect(find.byKey(const Key('pipeline-detail')), findsOneWidget);
await tester.tap(find.byTooltip('Back to pipelines'));
await tester.pumpAndSettle();
expect(find.byKey(const Key('pipeline-list')), findsOneWidget);
});
testWidgets(
'2x text at 390px keeps list and detail scrollable without overflow',
(tester) async {
tester.view.physicalSize = const Size(390, 844);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final fixture = PipelineFixture();
await tester.pumpWidget(
MaterialApp(
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: const TextScaler.linear(2)),
child: child!,
),
home: PipelinesScreen(gateway: gatewayFor(fixture)),
),
);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(find.text('Alpha review'), findsOneWidget);
await tester.tap(find.byKey(const Key('pipeline-row-1')));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
await tester.ensureVisible(find.text('Source'));
await tester.pumpAndSettle();
await tester.tap(find.text('Source'));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(
selectableText(
'name: Alpha review\nstages:\n review:\n type: model',
),
findsOneWidget,
);
},
);
testWidgets('wide layout at 2x text renders both panes', (tester) async {
tester.view.physicalSize = const Size(1100, 900);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final fixture = PipelineFixture();
await tester.pumpWidget(
MaterialApp(
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: const TextScaler.linear(2)),
child: child!,
),
home: PipelinesScreen(gateway: gatewayFor(fixture)),
),
);
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('pipeline-row-1')));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(find.byKey(const Key('pipeline-list')), findsOneWidget);
expect(find.byKey(const Key('pipeline-detail')), findsOneWidget);
});
testWidgets('iOS uses Cupertino scaffolds, list tiles and segmented tabs', (
tester,
) async {
debugDefaultTargetPlatformOverride = TargetPlatform.iOS;
tester.view.physicalSize = const Size(1100, 900);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final fixture = PipelineFixture();
try {
await tester.pumpWidget(
CupertinoApp(home: PipelinesScreen(gateway: gatewayFor(fixture))),
);
await tester.pumpAndSettle();
expect(find.byType(CupertinoPageScaffold), findsOneWidget);
expect(find.byType(CupertinoListTile), findsWidgets);
expect(find.byType(CupertinoActionSheet), findsNothing);
await tester.tap(find.byKey(const Key('pipeline-row-1')));
await tester.pumpAndSettle();
expect(
find.byType(CupertinoSegmentedControl<PipelineDetailTab>),
findsOneWidget,
);
expect(find.byType(CupertinoListTile), findsWidgets);
await tester.tap(find.byKey(const Key('pipeline-version-1')));
await tester.pumpAndSettle();
expect(find.text('Viewing v1 (latest v2).'), findsOneWidget);
await tester.tap(find.text('Source'));
await tester.pump();
expect(
selectableText(
'name: Alpha review\nstages:\n review:\n type: model\n'
'# selected version 1',
),
findsOneWidget,
);
} finally {
debugDefaultTargetPlatformOverride = null;
}
});
testWidgets('hosted graph hook receives the selected pipeline and stage', (
tester,
) async {
final fixture = PipelineFixture();
PipelineStageRef? selected;
await tester.pumpWidget(
MaterialApp(
home: PipelinesScreen(
gateway: gatewayFor(fixture),
graphBuilder: (context, detail, onStageSelected) => Column(
children: [
Text('HOSTED GRAPH ${detail.id} v${detail.resolvedVersion}'),
TextButton(
onPressed: () => onStageSelected('review'),
child: const Text('Stage review'),
),
],
),
onStageSelected: (ref) => selected = ref,
),
),
);
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('pipeline-row-1')));
await tester.pumpAndSettle();
await tester.tap(find.text('Graph'));
await tester.pump();
expect(find.text('HOSTED GRAPH 1 v2'), findsOneWidget);
await tester.tap(find.text('Stage review'));
expect(selected?.pipelineId, 1);
expect(selected?.version, 2);
expect(selected?.stageKey, 'review');
});
}
@@ -0,0 +1,153 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/pipelines/pipeline_repository.dart';
import 'package:pipelines_app/features/pipelines/pipelines_controller.dart';
import 'fixtures.dart';
PipelinesController controllerFor(FakeGateway gateway) =>
PipelinesController(PipelinesRepository(gateway));
void main() {
test(
'opening a pipeline requests the row version and parses detail',
() async {
final fixture = PipelineFixture();
final gateway = FakeGateway(
(type, fields) => switch (type) {
'list_pipelines' => pipelineListReply(fixture.summaries),
'list_runs' => runListReply(fixture.runs),
'get_pipeline' => pipelineDetailReply(
fixture.detailFor(
fields['pipeline_id'] as int,
fields['version'] as int,
)!,
),
_ => errorReply('unexpected $type'),
},
);
final controller = controllerFor(gateway);
await controller.load();
await controller.openPipeline(1, version: 2);
expect(gateway.callsOf('get_pipeline').single.fields, {
'pipeline_id': 1,
'version': 2,
});
expect(controller.detail?.id, 1);
expect(controller.detail?.resolvedVersion, 2);
expect(controller.selectedVersion, 2);
},
);
test('a stale detail reply cannot replace the newer selection', () async {
final fixture = PipelineFixture();
final first = Completer<Map<String, dynamic>>();
final second = Completer<Map<String, dynamic>>();
final gateway = FakeGateway(
(type, fields) => switch (type) {
'list_pipelines' => pipelineListReply(fixture.summaries),
'list_runs' => runListReply(fixture.runs),
'get_pipeline' =>
fields['pipeline_id'] == 1 ? first.future : second.future,
_ => errorReply('unexpected $type'),
},
);
final controller = controllerFor(gateway);
await controller.load();
final firstRequest = controller.openPipeline(1, version: 2);
final secondRequest = controller.openPipeline(2, version: 1);
expect(controller.selectedId, 2);
first.complete(pipelineDetailReply(fixture.details[0]));
await firstRequest;
expect(
controller.detail,
isNull,
reason: 'the late reply belongs to the discarded selection',
);
expect(controller.detailLoading, isTrue);
second.complete(pipelineDetailReply(fixture.details[1]));
await secondRequest;
expect(controller.detail?.id, 2);
expect(controller.detail?.name, 'Beta deploy');
});
test('a late reply after Back cannot reopen the cleared detail', () async {
final fixture = PipelineFixture();
final reply = Completer<Map<String, dynamic>>();
final gateway = FakeGateway(
(type, fields) => switch (type) {
'list_pipelines' => pipelineListReply(fixture.summaries),
'list_runs' => runListReply(fixture.runs),
'get_pipeline' => reply.future,
_ => errorReply('unexpected $type'),
},
);
final controller = controllerFor(gateway);
await controller.load();
final request = controller.openPipeline(1, version: 2);
controller.clearSelection();
reply.complete(pipelineDetailReply(fixture.details[0]));
await request;
expect(controller.detail, isNull);
expect(controller.selectedId, isNull);
});
test(
'version selection requests that exact version and latest again',
() async {
final fixture = PipelineFixture();
final gateway = FakeGateway(
(type, fields) => switch (type) {
'list_pipelines' => pipelineListReply(fixture.summaries),
'list_runs' => runListReply(fixture.runs),
'get_pipeline' => pipelineDetailReply(
fixture.detailFor(
fields['pipeline_id'] as int,
fields['version'] as int,
)!,
),
_ => errorReply('unexpected $type'),
},
);
final controller = controllerFor(gateway);
await controller.load();
await controller.openPipeline(1, version: 2);
await controller.selectVersion(1);
expect(controller.selectedVersion, 1);
expect(controller.detail?.source, contains('# selected version 1'));
expect(gateway.callsOf('get_pipeline').last.fields, {
'pipeline_id': 1,
'version': 1,
});
await controller.selectVersion(0);
expect(controller.selectedVersion, 0);
expect(gateway.callsOf('get_pipeline').last.fields, {
'pipeline_id': 1,
'version': 0,
});
},
);
test('a detail refusal keeps the selection and names the reason', () async {
final fixture = PipelineFixture();
final gateway = FakeGateway(
(type, fields) => switch (type) {
'list_pipelines' => pipelineListReply(fixture.summaries),
'list_runs' => runListReply(fixture.runs),
'get_pipeline' => errorReply('pipeline 9 was not found'),
_ => errorReply('unexpected $type'),
},
);
final controller = controllerFor(gateway);
await controller.load();
await controller.openPipeline(9);
expect(controller.detailError, 'pipeline 9 was not found');
expect(controller.selectedId, 9);
});
}
@@ -0,0 +1,163 @@
import 'dart:async';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/pipelines/pipeline_query.dart';
import 'package:pipelines_app/features/pipelines/pipeline_repository.dart';
import 'package:pipelines_app/features/pipelines/pipelines_controller.dart';
import 'fixtures.dart';
PipelinesController controllerFor(FakeGateway gateway) =>
PipelinesController(PipelinesRepository(gateway));
Future<void> settle() => Future<void>.delayed(Duration.zero);
void main() {
test(
'load sends exact list and runs requests and parses the envelopes',
() async {
final fixture = PipelineFixture();
final gateway = FakeGateway(
(type, fields) => switch (type) {
'list_pipelines' => pipelineListReply(fixture.summaries),
'list_runs' => runListReply(fixture.runs),
_ => errorReply('unexpected $type'),
},
);
final controller = controllerFor(gateway);
await controller.load();
expect(gateway.calls.map((call) => call.type).toList(), [
'list_pipelines',
'list_runs',
]);
expect(gateway.calls[0].fields, isEmpty);
expect(gateway.calls[1].fields, isEmpty);
expect(controller.pipelines.map((pipeline) => pipeline.id), [1, 2, 3]);
expect(controller.pipelinesLoaded, isTrue);
expect(controller.runsLoaded, isTrue);
expect(controller.latestRuns[1]?.id, 42);
expect(controller.listError, isNull);
expect(controller.runsError, isNull);
},
);
test('refresh keeps the selected pipeline and requested version', () async {
final fixture = PipelineFixture();
final summaries = List<Map<String, dynamic>>.of(fixture.summaries);
final gateway = FakeGateway(
(type, fields) => switch (type) {
'list_pipelines' => pipelineListReply(summaries),
'list_runs' => runListReply(fixture.runs),
'get_pipeline' => pipelineDetailReply(
fixture.detailFor(
fields['pipeline_id'] as int,
fields['version'] as int,
)!,
),
_ => errorReply('unexpected $type'),
},
);
final controller = controllerFor(gateway);
await controller.load();
await controller.openPipeline(2, version: 1);
summaries[1] = pipelineSummary(id: 2, name: 'Beta deploy renamed');
await controller.load();
expect(controller.selectedId, 2);
expect(controller.selectedVersion, 1);
expect(controller.detail?.id, 2);
expect(controller.pipelines[1].name, 'Beta deploy renamed');
expect(gateway.callsOf('get_pipeline').last.fields, {
'pipeline_id': 2,
'version': 1,
});
});
test(
'server refusals are shown verbatim and a list failure is retryable',
() async {
final gateway = FakeGateway(
(type, fields) => errorReply('server offline'),
);
final controller = controllerFor(gateway);
await controller.load();
expect(controller.listError, 'server offline');
expect(controller.pipelinesLoaded, isFalse);
expect(controller.runsError, 'server offline');
},
);
test('a runs failure is truthful without discarding pipelines', () async {
final fixture = PipelineFixture();
final gateway = FakeGateway(
(type, fields) => switch (type) {
'list_pipelines' => pipelineListReply(fixture.summaries),
'list_runs' => errorReply('runs unavailable'),
_ => errorReply('unexpected $type'),
},
);
final controller = controllerFor(gateway);
await controller.load();
expect(controller.pipelinesLoaded, isTrue);
expect(controller.pipelines, isNotEmpty);
expect(controller.runsLoaded, isFalse);
expect(controller.runsError, 'runs unavailable');
});
test('run facets wait for a known run history', () async {
final fixture = PipelineFixture();
final runsReply = Completer<Map<String, dynamic>>();
final gateway = FakeGateway(
(type, fields) => switch (type) {
'list_pipelines' => pipelineListReply(fixture.summaries),
'list_runs' => runsReply.future,
_ => errorReply('unexpected $type'),
},
);
final controller = controllerFor(gateway);
controller.setFilters(const PipelineFilters(presence: RunPresence.noRuns));
final loading = controller.load();
await settle();
expect(controller.pipelinesLoaded, isTrue);
expect(controller.runsLoaded, isFalse);
expect(controller.visiblePipelines.length, 3);
runsReply.complete(runListReply(fixture.runs));
await loading;
expect(controller.runsLoaded, isTrue);
expect(controller.visiblePipelines.map((pipeline) => pipeline.id), [3]);
});
test('a stale list refresh cannot overwrite newer rows', () async {
final first = Completer<Map<String, dynamic>>();
final second = Completer<Map<String, dynamic>>();
var listCalls = 0;
final gateway = FakeGateway((type, fields) {
if (type == 'list_runs') return runListReply(const []);
if (type == 'list_pipelines') {
listCalls++;
return listCalls == 1 ? first.future : second.future;
}
return errorReply('unexpected $type');
});
final controller = controllerFor(gateway);
final firstLoad = controller.load();
final secondLoad = controller.load();
second.complete(pipelineListReply([pipelineSummary(id: 2, name: 'Newer')]));
await secondLoad;
first.complete(pipelineListReply([pipelineSummary(id: 1, name: 'Older')]));
await firstLoad;
expect(controller.pipelines.single.name, 'Newer');
expect(controller.listLoading, isFalse);
});
test('pipeline errors keep a readable message', () {
expect(
pipelineErrorMessage(const PipelineRequestException('exact refusal')),
'exact refusal',
);
expect(pipelineErrorMessage(Exception('broken')), 'broken');
});
}
@@ -0,0 +1,120 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/pipelines/screen.dart';
import 'fixtures.dart';
import 'test_helpers.dart';
void main() {
testWidgets('filter page narrows by name, schedule and last run status', (
tester,
) async {
final fixture = PipelineFixture();
await pumpWide(tester, gatewayFor(fixture));
await tester.tap(find.byKey(const Key('pipeline-filter')));
await tester.pumpAndSettle();
expect(find.text('Filter pipelines'), findsOneWidget);
await tester.enterText(find.byType(TextField), 'beta');
await tester.tap(find.text('Done'));
await tester.pumpAndSettle();
expect(find.text('Filter (1)'), findsOneWidget);
expect(find.text('Beta deploy'), findsOneWidget);
expect(find.text('Alpha review'), findsNothing);
await tester.tap(find.byKey(const Key('pipeline-clear-filters')));
await tester.pumpAndSettle();
expect(find.text('Alpha review'), findsOneWidget);
expect(find.text('Gamma legacy'), findsOneWidget);
await tester.tap(find.byKey(const Key('pipeline-filter')));
await tester.pumpAndSettle();
await tester.ensureVisible(find.text('No schedules'));
await tester.pumpAndSettle();
await tester.tap(find.text('No schedules'));
await tester.pump();
await tester.tap(find.text('Done'));
await tester.pumpAndSettle();
expect(find.text('Beta deploy'), findsOneWidget);
expect(find.text('Alpha review'), findsNothing);
expect(find.text('Gamma legacy'), findsNothing);
await tester.tap(find.byKey(const Key('pipeline-clear-filters')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('pipeline-filter')));
await tester.pumpAndSettle();
await tester.ensureVisible(find.text('failed'));
await tester.pumpAndSettle();
await tester.tap(find.text('failed'));
await tester.pump();
await tester.tap(find.text('Done'));
await tester.pumpAndSettle();
expect(find.text('Beta deploy'), findsOneWidget);
expect(find.text('Alpha review'), findsNothing);
});
testWidgets('sort menu changes visible order', (tester) async {
final fixture = PipelineFixture();
await pumpWide(tester, gatewayFor(fixture));
await tester.tap(find.byKey(const Key('pipeline-sort')));
await tester.pumpAndSettle();
await tester.tap(find.text('Name Z\u2013A'));
await tester.pumpAndSettle();
expect(find.text('Sort: Name Z\u2013A'), findsOneWidget);
final gamma = tester.getTopLeft(find.text('Gamma legacy')).dy;
final beta = tester.getTopLeft(find.text('Beta deploy')).dy;
final alpha = tester.getTopLeft(find.text('Alpha review')).dy;
expect(gamma, lessThan(beta));
expect(beta, lessThan(alpha));
});
testWidgets('empty and error states are truthful and retryable', (
tester,
) async {
final fixture = PipelineFixture();
var fails = true;
final gateway = FakeGateway((type, fields) {
if (type == 'list_runs') return runListReply(fixture.runs);
if (type == 'list_pipelines') {
return fails
? errorReply('server offline')
: pipelineListReply(fixture.summaries);
}
return errorReply('unexpected $type');
});
await pumpWide(tester, gateway);
expect(find.text('server offline'), findsOneWidget);
expect(find.text('Loading pipelines…'), findsNothing);
fails = false;
await tester.tap(find.text('Retry'));
await tester.pumpAndSettle();
expect(find.text('Alpha review'), findsOneWidget);
final emptyGateway = gatewayFor(fixture, summaries: const []);
await tester.pumpWidget(
MaterialApp(home: PipelinesScreen(gateway: emptyGateway)),
);
await tester.pumpAndSettle();
expect(
find.text('No pipelines are defined on this server.'),
findsOneWidget,
);
});
testWidgets('a detail refusal keeps the selection and offers retry', (
tester,
) async {
final fixture = PipelineFixture();
final gateway = gatewayFor(fixture, detailFails: true);
await pumpWide(tester, gateway);
await tester.tap(find.byKey(const Key('pipeline-row-2')));
await tester.pumpAndSettle();
expect(find.text('pipeline 2 was not found'), findsOneWidget);
expect(find.text('Retry'), findsOneWidget);
expect(find.text('Select a pipeline.'), findsNothing);
});
}
@@ -0,0 +1,140 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/pipelines/screen.dart';
import 'fixtures.dart';
import 'test_helpers.dart';
void main() {
testWidgets('list renders web wording, filters, opens detail and source', (
tester,
) async {
final fixture = PipelineFixture();
final gateway = gatewayFor(fixture);
await pumpWide(tester, gateway);
expect(find.text('Pipelines'), findsOneWidget);
expect(find.text('Alpha review'), findsOneWidget);
expect(find.text('id 1 · v2 · 2 stages'), findsOneWidget);
expect(find.text('updated 17 Oct 21:26'), findsOneWidget);
expect(find.text('1 schedule'), findsOneWidget);
expect(find.textContaining('run 42'), findsOneWidget);
expect(find.text('no runs recorded'), findsOneWidget);
expect(find.text('Select a pipeline.'), findsOneWidget);
await tester.tap(find.byKey(const Key('pipeline-row-1')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('pipeline-detail')), findsOneWidget);
expect(find.text('hash-alpha'), findsOneWidget);
expect(find.text('id 1 · v2 · 2 stages'), findsNWidgets(2));
expect(gateway.callsOf('get_pipeline').single.fields, {
'pipeline_id': 1,
'version': 2,
});
await tester.tap(find.text('Source'));
await tester.pump();
expect(
selectableText('name: Alpha review\nstages:\n review:\n type: model'),
findsOneWidget,
);
});
testWidgets('version rows select an exact version and return to latest', (
tester,
) async {
final fixture = PipelineFixture();
final gateway = gatewayFor(fixture);
await pumpWide(tester, gateway);
await tester.tap(find.byKey(const Key('pipeline-row-1')));
await tester.pumpAndSettle();
expect(find.text('v1'), findsOneWidget);
expect(find.text('v2'), findsNWidgets(2));
await tester.tap(find.byKey(const Key('pipeline-version-1')));
await tester.pumpAndSettle();
expect(gateway.callsOf('get_pipeline').last.fields, {
'pipeline_id': 1,
'version': 1,
});
expect(find.text('Viewing v1 (latest v2).'), findsOneWidget);
await tester.tap(find.text('Source'));
await tester.pump();
expect(
selectableText(
'name: Alpha review\nstages:\n review:\n type: model\n'
'# selected version 1',
),
findsOneWidget,
);
await tester.tap(find.text('Summary'));
await tester.pump();
await tester.tap(find.byKey(const Key('pipeline-latest-version')));
await tester.pumpAndSettle();
expect(gateway.callsOf('get_pipeline').last.fields, {
'pipeline_id': 1,
'version': 0,
});
expect(find.text('Viewing v1 (latest v2).'), findsNothing);
});
testWidgets('refresh keeps the selected row and its detail', (tester) async {
final fixture = PipelineFixture();
final gateway = gatewayFor(fixture);
await pumpWide(tester, gateway);
await tester.tap(find.byKey(const Key('pipeline-row-1')));
await tester.pumpAndSettle();
await tester.tap(find.byTooltip('Refresh'));
await tester.pumpAndSettle();
final row = tester.widget<ListTile>(
find.byKey(const Key('pipeline-row-1')),
);
expect(row.selected, isTrue);
expect(find.byKey(const Key('pipeline-detail')), findsOneWidget);
expect(gateway.callsOf('get_pipeline').length, greaterThanOrEqualTo(2));
});
testWidgets('initial loading is shown until both list reads settle', (
tester,
) async {
final fixture = PipelineFixture();
final list = Completer<JsonMap>();
final runs = Completer<JsonMap>();
final gateway = FakeGateway(
(type, fields) => switch (type) {
'list_pipelines' => list.future,
'list_runs' => runs.future,
_ => errorReply('unexpected $type'),
},
);
await tester.pumpWidget(
MaterialApp(home: PipelinesScreen(gateway: gateway)),
);
await tester.pump();
expect(find.text('Loading pipelines…'), findsOneWidget);
list.complete(pipelineListReply(fixture.summaries));
runs.complete(runListReply(fixture.runs));
await tester.pumpAndSettle();
expect(find.text('Alpha review'), findsOneWidget);
});
testWidgets('graph tab states it is pending without a hook', (tester) async {
final fixture = PipelineFixture();
await pumpWide(tester, gatewayFor(fixture));
await tester.tap(find.byKey(const Key('pipeline-row-1')));
await tester.pumpAndSettle();
await tester.tap(find.text('Graph'));
await tester.pump();
expect(find.text('Graph rendering is pending (P2).'), findsOneWidget);
});
}
@@ -0,0 +1,45 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/pipelines/screen.dart';
import 'fixtures.dart';
FakeGateway gatewayFor(
PipelineFixture fixture, {
bool listFails = false,
bool runsFail = false,
bool detailFails = false,
List<Map<String, dynamic>>? summaries,
}) => FakeGateway(
(type, fields) => switch (type) {
'list_pipelines' =>
listFails
? errorReply('server offline')
: pipelineListReply(summaries ?? fixture.summaries),
'list_runs' =>
runsFail ? errorReply('runs down') : runListReply(fixture.runs),
'get_pipeline' =>
detailFails
? errorReply('pipeline ${fields['pipeline_id']} was not found')
: pipelineDetailReply(
fixture.detailFor(
fields['pipeline_id'] as int,
fields['version'] as int,
)!,
),
_ => errorReply('unexpected $type'),
},
);
Future<void> pumpWide(WidgetTester tester, FakeGateway gateway) async {
tester.view.physicalSize = const Size(1100, 900);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(MaterialApp(home: PipelinesScreen(gateway: gateway)));
await tester.pumpAndSettle();
}
Finder selectableText(String text) => find.byWidgetPredicate(
(widget) => widget is SelectableText && widget.data == text,
);
+132
View File
@@ -0,0 +1,132 @@
// Real-Chrome fixture probe for the Pipelines P1 screen.
//
// It serves a prebuilt Flutter web bundle, drives it through Chrome DevTools
// (accessibility tree + real mouse events), and writes PNGs and a JSON log.
// No live server, socket or operator data is involved.
//
// Usage: node tool/pipelines_probe_cdp.mjs <build-dir> <capture-dir>
import { mkdir, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { tmpdir } from "node:os";
import {
connect,
launchChrome,
sleep,
startServer,
waitForPage,
waitForPort,
} from "./pipelines_probe_cdp_lib.mjs";
import {
assertName,
axNodes,
capture,
click,
clickAt,
dragSelect,
enableSemantics,
waitFor,
} from "./pipelines_probe_cdp_input.mjs";
const CHROME =
process.env.CHROME_PATH ??
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
const buildDir = resolve(process.argv[2] ?? "build/web");
const captureDir = resolve(process.argv[3] ?? "p1-captures");
const { server, url } = await startServer(buildDir);
await mkdir(captureDir, { recursive: true });
const profile = join(tmpdir(), `pipelines-p1-chrome-${process.pid}`);
const chrome = launchChrome(CHROME, profile, url);
let connection;
const log = { url, captures: [], checks: [], axSamples: [] };
try {
const devtoolsPort = await waitForPort(join(profile, "DevToolsActivePort"));
const target = await waitForPage(devtoolsPort);
connection = await connect(target.webSocketDebuggerUrl);
await connection.send("Page.enable");
await connection.send("Runtime.enable");
await connection.send("DOM.enable");
await connection.send("Accessibility.enable");
await connection.send("Emulation.setDeviceMetricsOverride", {
width: 1200,
height: 900,
deviceScaleFactor: 1,
mobile: false,
});
await waitFor(
() => connection.evaluate("document.querySelector('flutter-view') !== null"),
20000,
);
await sleep(1200);
await enableSemantics(connection);
const nodes = await axNodes(connection);
log.axSamples = nodes
.filter((node) => node.name?.value)
.slice(0, 40)
.map((node) => `${node.role?.value}: ${node.name.value}`);
await assertName(connection, "Release verification", "list row", log);
await capture(connection, captureDir, log, "01-list-desktop");
await click(connection, "Release verification");
await assertName(connection, "Content hash", "summary detail", log);
await capture(connection, captureDir, log, "02-detail-summary");
await click(connection, "Source");
await capture(connection, captureDir, log, "03-source-latest");
// Select the first source line with a real drag. The capture shows the
// browser's text selection, proving the source is selectable.
await dragSelect(connection, 500, 194, 880, 194);
await capture(connection, captureDir, log, "04-source-selection");
log.checks.push("source drag selection");
await click(connection, "Summary");
// The detail body is drawn on the canvas and Flutter's semantics tree omits
// its list rows in this build, so the v1 row is clicked at the fixture layout
// position for the fixed 1200x900 viewport.
await clickAt(connection, 620, 489);
await sleep(800);
await capture(connection, captureDir, log, "05-version-v1");
await click(connection, "Source");
await capture(connection, captureDir, log, "06-source-v1");
await connection.send("Emulation.setDeviceMetricsOverride", {
width: 390,
height: 844,
deviceScaleFactor: 1,
mobile: true,
});
await sleep(500);
await click(connection, "Back to pipelines");
await assertName(connection, "Release verification", "mobile list", log);
await capture(connection, captureDir, log, "07-list-390");
await click(connection, "Hotfix triage");
await assertName(connection, "Content hash", "mobile detail", log);
await capture(connection, captureDir, log, "08-detail-390");
await click(connection, "Back to pipelines");
await assertName(connection, "Release verification", "mobile list again", log);
await click(connection, "Filter");
await assertName(connection, "Filter pipelines", "mobile filter", log);
await capture(connection, captureDir, log, "09-filter-390");
} catch (error) {
log.error = String(error?.stack ?? error);
try {
const nodes = await axNodes(connection);
log.failureAx = nodes
.filter((node) => node.name?.value)
.map((node) => `${node.role?.value}: ${node.name.value}`)
.slice(0, 120);
} catch {
// The browser may already be gone; the error itself is still recorded.
}
process.exitCode = 1;
} finally {
await writeFile(join(captureDir, "probe.json"), JSON.stringify(log, null, 2));
connection?.close();
chrome.kill("SIGTERM");
server.close();
}
+155
View File
@@ -0,0 +1,155 @@
// Chrome DevTools input, accessibility and capture helpers for the Pipelines
// P1 fixture probe.
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { sleep } from "./pipelines_probe_cdp_lib.mjs";
const ENABLE_SEMANTICS = `(() => {
const visit = (root) => {
const placeholder = root.querySelector?.('flt-semantics-placeholder');
if (placeholder) { placeholder.click(); return true; }
for (const element of root.querySelectorAll?.('*') ?? []) {
if (element.shadowRoot && visit(element.shadowRoot)) return true;
}
return false;
};
return visit(document);
})()`;
export async function enableSemantics(connection) {
await connection.evaluate(ENABLE_SEMANTICS);
await sleep(1000);
}
function axLabel(node) {
return [node?.name?.value, node?.value?.value]
.filter((value) => typeof value === "string" && value !== "")
.join("\n");
}
export async function axNodes(connection) {
const { nodes } = await connection.send("Accessibility.getFullAXTree", {
depth: -1,
});
return nodes;
}
export async function waitFor(probe, timeout) {
const deadline = Date.now() + timeout;
while (Date.now() < deadline) {
const value = await probe();
if (value) return value;
await sleep(120);
}
return null;
}
export async function assertName(connection, text, label, log) {
const nodes = await waitFor(async () => {
const current = await axNodes(connection);
return current.some((node) => axLabel(node).includes(text))
? current
: false;
}, 12000);
if (!nodes) throw new Error(`Missing ${label}: ${text}`);
log.checks.push(label);
}
export async function capture(connection, directory, log, name) {
const shot = await connection.send("Page.captureScreenshot", {
format: "png",
captureBeyondViewport: false,
});
const file = join(directory, `${name}.png`);
await writeFile(file, Buffer.from(shot.data, "base64"));
log.captures.push(file);
}
export async function click(connection, text) {
const nodes = await axNodes(connection);
const interactive = new Set([
"button",
"link",
"tab",
"radio",
"checkbox",
"menuitem",
"option",
"switch",
"toggleButton",
"listitem",
]);
const byId = new Map(nodes.map((node) => [node.nodeId, node]));
const clickable = (node) => {
let current = node;
while (current) {
if (interactive.has(current.role?.value) && current.backendDOMNodeId) {
return current;
}
current = byId.get(current.parentId);
}
return null;
};
const matches = nodes.filter((node) => {
const name = axLabel(node);
return (
name.includes(text) &&
(node.role?.value === "button" ||
node.role?.value === "StaticText" ||
interactive.has(node.role?.value))
);
});
const target = matches.map(clickable).find(Boolean);
if (!target) throw new Error(`No clickable semantics node for ${text}`);
const { model } = await connection.send("DOM.getBoxModel", {
backendNodeId: target.backendDOMNodeId,
});
const [x1, y1, , , x3, y3] = model.content;
await clickAt(connection, (x1 + x3) / 2, (y1 + y3) / 2);
}
export async function clickAt(connection, x, y) {
await connection.send("Input.dispatchMouseEvent", {
type: "mousePressed",
x,
y,
button: "left",
clickCount: 1,
});
await connection.send("Input.dispatchMouseEvent", {
type: "mouseReleased",
x,
y,
button: "left",
clickCount: 1,
});
await sleep(500);
}
export async function dragSelect(connection, x1, y1, x2, y2) {
await connection.send("Input.dispatchMouseEvent", {
type: "mousePressed",
x: x1,
y: y1,
button: "left",
clickCount: 1,
});
for (let step = 1; step <= 8; step++) {
await connection.send("Input.dispatchMouseEvent", {
type: "mouseMoved",
x: x1 + ((x2 - x1) * step) / 8,
y: y1 + ((y2 - y1) * step) / 8,
button: "left",
buttons: 1,
});
await sleep(30);
}
await connection.send("Input.dispatchMouseEvent", {
type: "mouseReleased",
x: x2,
y: y2,
button: "left",
clickCount: 1,
});
await sleep(400);
}
+127
View File
@@ -0,0 +1,127 @@
// Chrome DevTools connection and fixture-server helpers for the Pipelines P1
// probe. No live server or operator data is involved.
import { spawn } from "node:child_process";
import { createServer } from "node:http";
import { readFile, stat } from "node:fs/promises";
import { extname, join, normalize } from "node:path";
export const sleep = (ms) =>
new Promise((resolve) => setTimeout(resolve, ms));
const MIME = {
".html": "text/html; charset=utf-8",
".js": "text/javascript; charset=utf-8",
".mjs": "text/javascript; charset=utf-8",
".css": "text/css; charset=utf-8",
".json": "application/json",
".png": "image/png",
".jpg": "image/jpeg",
".svg": "image/svg+xml",
".ttf": "font/ttf",
".otf": "font/otf",
".wasm": "application/wasm",
".map": "application/json",
};
export async function startServer(buildDir) {
const root = normalize(buildDir);
const server = createServer(async (request, response) => {
try {
const url = new URL(request.url ?? "/", "http://127.0.0.1");
let file = normalize(join(root, decodeURIComponent(url.pathname)));
if (!file.startsWith(root)) throw new Error("outside build");
let info = await stat(file).catch(() => null);
if (!info || info.isDirectory()) {
file = join(root, "index.html");
info = await stat(file);
}
response.writeHead(200, {
"content-type": MIME[extname(file)] ?? "application/octet-stream",
"cache-control": "no-store",
});
response.end(await readFile(file));
} catch {
response.writeHead(404).end("not found");
}
});
await new Promise((done) => server.listen(0, "127.0.0.1", done));
return { server, url: `http://127.0.0.1:${server.address().port}/` };
}
export function launchChrome(chromePath, profile, url) {
return spawn(
chromePath,
[
"--headless=new",
"--remote-debugging-port=0",
`--user-data-dir=${profile}`,
"--no-first-run",
"--no-default-browser-check",
"--disable-background-networking",
"--disable-sync",
"--hide-scrollbars",
"--force-device-scale-factor=1",
"--window-size=1200,900",
url,
],
{ stdio: "ignore" },
);
}
export async function waitForPort(file) {
for (let attempt = 0; attempt < 200; attempt++) {
const text = await readFile(file, "utf8").catch(() => "");
if (text) return text.split("\n")[0].trim();
await sleep(100);
}
throw new Error("Chrome DevTools did not start");
}
export async function waitForPage(devtoolsPort) {
for (let attempt = 0; attempt < 100; attempt++) {
const targets = await fetch(
`http://127.0.0.1:${devtoolsPort}/json/list`,
).then((response) => response.json());
const page = targets.find((target) => target.type === "page");
if (page) return page;
await sleep(100);
}
throw new Error("No page target");
}
export async function connect(webSocketUrl) {
const socket = new WebSocket(webSocketUrl);
await new Promise((done, fail) => {
socket.addEventListener("open", done, { once: true });
socket.addEventListener("error", fail, { once: true });
});
let nextId = 1;
const pending = new Map();
socket.addEventListener("message", (event) => {
const message = JSON.parse(event.data);
if (!message.id) return;
const entry = pending.get(message.id);
if (!entry) return;
pending.delete(message.id);
if (message.error) entry.reject(new Error(message.error.message));
else entry.resolve(message.result);
});
const send = (method, params = {}) =>
new Promise((resolve, reject) => {
const id = nextId++;
pending.set(id, { resolve, reject });
socket.send(JSON.stringify({ id, method, params }));
});
return {
send,
close: () => socket.close(),
evaluate: async (expression) => {
const result = await send("Runtime.evaluate", {
expression,
awaitPromise: true,
returnByValue: true,
});
return result.result?.value;
},
};
}
+26
View File
@@ -0,0 +1,26 @@
import 'package:flutter/material.dart';
import 'package:pipelines_app/features/pipelines/screen.dart';
import 'pipelines_probe_fixture.dart';
/// Browser fixture preview for the Pipelines item. It is a separate entry
/// point, so the app's main/shell stay untouched. All replies come from
/// [PipelinesProbeGateway]; no server or live data is involved.
void main() {
runApp(const PipelinesProbeApp());
}
class PipelinesProbeApp extends StatelessWidget {
const PipelinesProbeApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Pipelines P1 probe',
debugShowCheckedModeBanner: false,
theme: ThemeData(),
darkTheme: ThemeData(brightness: Brightness.dark),
home: PipelinesScreen(gateway: PipelinesProbeGateway()),
);
}
}
+242
View File
@@ -0,0 +1,242 @@
import 'dart:async';
import 'package:pipelines_app/core/api_gateway.dart';
/// Deterministic in-memory data for the browser fixture preview. This is not a
/// live connection and is used only by `tool/pipelines_probe_entry.dart`.
class PipelinesProbeGateway implements ApiGateway {
PipelinesProbeGateway({this.delay = const Duration(milliseconds: 120)});
final Duration delay;
static const _pipelines = <Map<String, dynamic>>[
{
'id': 3,
'name': 'Release verification',
'version': 3,
'stages': 4,
'created_at': '2026-09-28T10:12:00',
'updated_at': '2026-10-21T09:40:00',
'scheduled': true,
'schedule_count': 2,
'enabled_schedule_count': 1,
},
{
'id': 7,
'name': 'Nightly documentation',
'version': 1,
'stages': 2,
'created_at': '2026-10-02T18:20:00',
'updated_at': '2026-10-20T22:05:00',
'scheduled': true,
'schedule_count': 1,
'enabled_schedule_count': 1,
},
{
'id': 11,
'name': 'Hotfix triage',
'version': 2,
'stages': 3,
'created_at': '2026-10-11T08:00:00',
'updated_at': '2026-10-19T16:32:00',
'scheduled': false,
'schedule_count': 0,
'enabled_schedule_count': 0,
},
{
'id': 14,
'name': 'Legacy import (no schedule metadata)',
'version': 1,
'stages': 1,
'created_at': '2026-08-04T11:45:00',
'updated_at': '2026-10-14T12:10:00',
'scheduled': null,
'schedule_count': null,
'enabled_schedule_count': null,
},
];
static const _runs = <Map<String, dynamic>>[
{
'id': 488,
'pipeline_id': 3,
'status': 'succeeded',
'created_at': '2026-10-21T09:30:00',
'finished_at': '2026-10-21T09:34:12',
'executing': false,
},
{
'id': 487,
'pipeline_id': 7,
'status': 'running',
'created_at': '2026-10-21T09:20:00',
'finished_at': '',
'executing': true,
},
{
'id': 486,
'pipeline_id': 11,
'status': 'failed',
'created_at': '2026-10-19T16:20:00',
'finished_at': '2026-10-19T16:28:40',
'executing': false,
},
{
'id': 480,
'pipeline_id': 3,
'status': 'waiting',
'created_at': '2026-10-18T13:00:00',
'finished_at': '',
'executing': false,
},
];
static const _versionRows = <int, List<Map<String, dynamic>>>{
3: [
{'version': 1, 'stages': 2, 'created_at': '2026-09-28T10:12:00'},
{'version': 2, 'stages': 3, 'created_at': '2026-10-08T15:44:00'},
{'version': 3, 'stages': 4, 'created_at': '2026-10-21T09:12:00'},
],
7: [
{'version': 1, 'stages': 2, 'created_at': '2026-10-02T18:20:00'},
],
11: [
{'version': 1, 'stages': 2, 'created_at': '2026-10-11T08:00:00'},
{'version': 2, 'stages': 3, 'created_at': '2026-10-18T09:30:00'},
],
14: [
{'version': 1, 'stages': 1, 'created_at': '2026-08-04T11:45:00'},
],
};
static const _sources = <int, String>{
3: '''
name: Release verification
stages:
inspect:
type: model
output: report
edges:
pass: verify
fail: '#failure'
verify:
type: model
output: verdict
edges:
pass: package
fail: '#failure'
package:
type: human
output: approval
edges:
approve: publish
hold: '#success'
publish:
type: model
output: release
edges:
done: '#success'
''',
7: '''
name: Nightly documentation
stages:
collect:
type: model
output: notes
edges:
done: write
write:
type: model
output: report
edges:
done: '#success'
''',
11: '''
name: Hotfix triage
stages:
classify:
type: model
output: severity
edges:
urgent: patch
normal: document
patch:
type: model
output: change
edges:
done: '#success'
document:
type: human
output: note
edges:
done: '#success'
''',
14: '''
name: Legacy import
stages:
import:
type: model
output: summary
edges:
done: '#success'
''',
};
@override
Stream<JsonMap> get frames => const Stream<JsonMap>.empty();
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
if (delay > Duration.zero) await Future<void>.delayed(delay);
switch (type) {
case 'list_pipelines':
return {'type': 'pipelines', 'pipelines': _pipelines};
case 'list_runs':
return {'type': 'runs', 'runs': _runs};
case 'get_pipeline':
return _detail(
fields['pipeline_id'] as int? ?? 0,
fields['version'] as int? ?? 0,
);
}
return {'type': 'error', 'error': 'The fixture does not answer $type.'};
}
JsonMap _detail(int id, int requestedVersion) {
final summary = _pipelines.where((pipeline) => pipeline['id'] == id).first;
final versions = _versionRows[id] ?? const <Map<String, dynamic>>[];
final latest = versions.isEmpty
? summary['version'] as int
: versions.last['version'] as int;
final resolved = requestedVersion > 0 ? requestedVersion : latest;
final version = versions.firstWhere(
(row) => row['version'] == resolved,
orElse: () => versions.isEmpty ? summary : versions.last,
);
return {
'type': 'pipeline',
'detail': {
...summary,
'version': resolved,
'stages': version['stages'] as int,
'latest_version': latest,
'version_created_at': _versionCreatedAt(versions, resolved),
'content_hash': 'sha256:fixture-$id-v$resolved',
'source': '${_sources[id]}\n# selected version $resolved\n',
'versions': versions,
},
};
}
static String _versionCreatedAt(
List<Map<String, dynamic>> versions,
int resolved,
) {
for (final version in versions) {
if (version['version'] == resolved) {
return version['created_at'] as String;
}
}
return versions.isEmpty ? '' : versions.last['created_at'] as String;
}
}
+403
View File
@@ -0,0 +1,403 @@
// Real-Chrome probe for the detail tab labels under narrow widths and scaled
// text. It serves a prebuilt Flutter web bundle, drives it through Chrome
// DevTools and writes PNGs plus a JSON log. No live server or operator data is
// involved.
//
// Usage: node tool/pipelines_probe_tabs_scale.mjs <build-dir> <capture-dir>
import { mkdir, writeFile } from "node:fs/promises";
import { join, resolve } from "node:path";
import { tmpdir } from "node:os";
import {
connect,
launchChrome,
sleep,
startServer,
waitForPage,
waitForPort,
} from "./pipelines_probe_cdp_lib.mjs";
import {
assertName,
axNodes,
capture,
click,
enableSemantics,
waitFor,
} from "./pipelines_probe_cdp_input.mjs";
const CHROME =
process.env.CHROME_PATH ??
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
const buildDir = resolve(process.argv[2] ?? "build/web");
const captureDir = resolve(process.argv[3] ?? "p1-tabs-fix");
const { server, url } = await startServer(buildDir);
await mkdir(captureDir, { recursive: true });
const profile = join(tmpdir(), `pipelines-tabs-chrome-${process.pid}`);
const chrome = launchChrome(CHROME, profile, url);
let connection;
const log = { url, captures: [], checks: [], states: [] };
const LABELS = ["Summary", "Graph", "Source"];
// The tab row sits inside the detail pane's 16 px horizontal padding.
const PANE_INSET = 16;
function paneRight(width) {
return width - PANE_INSET;
}
// At rest, every label must be fully inside the pane, except in the one state
// the acceptance allows to scroll: 320 px at 200 % still has to show a
// recognisable share of the last label instead of an empty cell.
function checkAtRest(name, boxes, width, { partialLast = false } = {}) {
const right = paneRight(width);
for (const label of LABELS) {
const box = boxes[label];
if (box.x + box.width <= PANE_INSET - 0.5) {
throw new Error(`${name}: ${label} starts outside the pane`);
}
if (box.width < 24) {
throw new Error(`${name}: ${label} has only ${box.width}px visible`);
}
if (!partialLast || label !== "Source") {
if (box.x + box.width > right + 0.5) {
throw new Error(
`${name}: ${label} is cut by the pane edge ` +
`(${box.x} + ${box.width} > ${right})`,
);
}
}
}
if (partialLast) {
const source = boxes.Source;
if (source.x >= right) {
throw new Error(`${name}: Source is an empty cell`);
}
if (source.width < 40) {
throw new Error(
`${name}: only ${source.width}px of Source is readable at rest`,
);
}
log.checks.push(
`${name}: Source is partly visible at rest (${source.width}px, ` +
'scrolling still allowed)',
);
} else {
log.checks.push(`${name}: all three labels fully visible at rest`);
}
}
async function setViewport(width, height) {
await connection.send("Emulation.setDeviceMetricsOverride", {
width,
height,
deviceScaleFactor: 1,
mobile: width < 720,
});
await sleep(800);
}
async function setTextScale(fontPx) {
await connection.evaluate(
`document.documentElement.style.fontSize = '${fontPx}px'; true`,
);
await sleep(1300);
}
async function setTheme(value) {
await connection.send("Emulation.setEmulatedMedia", {
features: [{ name: "prefers-color-scheme", value }],
});
await sleep(600);
}
// The accessibility tree reports the whole label even when the paragraph wraps
// inside a word, so the actual painted boxes are measured through the DOM.
async function tabBoxes() {
const nodes = await axNodes(connection);
const boxes = {};
for (const name of LABELS) {
const node = nodes.find(
(candidate) =>
candidate.role?.value === "button" && candidate.name?.value === name,
);
if (!node?.backendDOMNodeId) {
throw new Error(`No accessibility button named ${name}`);
}
const { model } = await connection.send("DOM.getBoxModel", {
backendNodeId: node.backendDOMNodeId,
});
const [x1, y1, , , x3, y3] = model.content;
boxes[name] = {
x: Math.round(x1 * 10) / 10,
y: Math.round(y1 * 10) / 10,
width: Math.round((x3 - x1) * 10) / 10,
height: Math.round((y3 - y1) * 10) / 10,
};
}
return boxes;
}
async function axHas(text) {
const nodes = await axNodes(connection);
return nodes.some(
(node) =>
node.name?.value?.includes(text) || node.value?.value?.includes(text),
);
}
async function pressTab() {
for (const type of ["keyDown", "keyUp"]) {
await connection.send("Input.dispatchKeyEvent", {
type,
key: "Tab",
code: "Tab",
windowsVirtualKeyCode: 9,
nativeVirtualKeyCode: 9,
});
}
await sleep(400);
}
async function dragRow(x, y, deltaX) {
await connection.send("Input.dispatchMouseEvent", {
type: "mousePressed",
x,
y,
button: "left",
clickCount: 1,
});
for (let step = 1; step <= 10; step++) {
await connection.send("Input.dispatchMouseEvent", {
type: "mouseMoved",
x: x + (deltaX * step) / 10,
y,
button: "left",
buttons: 1,
});
await sleep(25);
}
await connection.send("Input.dispatchMouseEvent", {
type: "mouseReleased",
x: x + deltaX,
y,
button: "left",
clickCount: 1,
});
await sleep(700);
}
async function openDetail() {
await connection.send("Page.reload");
await waitFor(
() => connection.evaluate("document.querySelector('flutter-view') !== null"),
20000,
);
await sleep(1500);
await enableSemantics(connection);
await setViewport(1200, 900);
await click(connection, "Release verification");
await assertName(connection, "Content hash", "detail selected", log);
}
async function state({ name, width, height, fontPx, partialLast = false, theme }) {
await openDetail();
if (theme) await setTheme(theme);
await setViewport(width, height);
await setTextScale(fontPx);
const boxes = await tabBoxes();
for (const label of LABELS) {
if (!boxes[label]) throw new Error(`Tab ${label} missing at ${name}`);
}
checkAtRest(name, boxes, width, { partialLast });
await capture(connection, captureDir, log, name);
if (!partialLast) {
// A box clipped by the scroll viewport still reports a right edge inside
// the pane, so scrolling the row to its limit must not uncover any extra
// label width. If it does, a label was cut at rest.
await dragRow(
boxes.Summary.x + boxes.Summary.width / 2,
boxes.Summary.y + boxes.Summary.height / 2,
-240,
);
const scrolled = await tabBoxes();
for (const label of LABELS) {
if (scrolled[label].width > boxes[label].width + 1) {
throw new Error(
`${name}: ${label} was clipped at rest ` +
`(${boxes[label].width} of ${scrolled[label].width}px visible)`,
);
}
}
log.checks.push(`${name}: scrolling exposes no hidden label width`);
}
const heights = LABELS.map((label) => boxes[label].height);
log.states.push({
name,
width,
height,
fontPx,
boxes,
equalRowHeight: heights.every((value) => value === heights[0]),
});
return boxes;
}
try {
const devtoolsPort = await waitForPort(join(profile, "DevToolsActivePort"));
const target = await waitForPage(devtoolsPort);
connection = await connect(target.webSocketDebuggerUrl);
await connection.send("Page.enable");
await connection.send("Runtime.enable");
await connection.send("DOM.enable");
await connection.send("Accessibility.enable");
await setTheme("light");
// Single-line height references at each scale, measured in the wide pane
// where every label fits on one line.
await openDetail();
await setTextScale(24);
const wide150 = await tabBoxes();
await setTextScale(32);
const wide200 = await tabBoxes();
log.states.push({ name: "wide-baseline", wide150, wide200 });
await sleep(200);
const text150 = await state({
name: "01-320-text150-atrest",
width: 320,
height: 640,
fontPx: 24,
});
const text200 = await state({
name: "02-320-text200-atrest",
width: 320,
height: 640,
fontPx: 32,
partialLast: true,
});
const text390 = await state({
name: "03-390-text200-atrest",
width: 390,
height: 844,
fontPx: 32,
});
const text720 = await state({
name: "04-720-text200-atrest",
width: 720,
height: 900,
fontPx: 32,
});
await state({
name: "05-320-text150-atrest-dark",
width: 320,
height: 640,
fontPx: 24,
theme: "dark",
});
await state({
name: "06-390-text200-atrest-dark",
width: 390,
height: 844,
fontPx: 32,
theme: "dark",
});
await setTheme("light");
for (const [label, boxes, reference] of [
["320x640 @150%", text150, wide150],
["320x640 @200%", text200, wide200],
["390x844 @200%", text390, wide200],
["720x900 @200%", text720, wide200],
]) {
const heights = LABELS.map((name) => boxes[name].height);
const singleLine = heights.every(
(value) => Math.abs(value - reference.Summary.height) <= 1,
);
if (!singleLine) {
throw new Error(
`${label}: tab row is ${heights.join("/")} high, single-line ` +
`reference is ${reference.Summary.height}`,
);
}
log.checks.push(`${label}: all three tab labels on one line`);
}
// The third tab must stay reachable when the row is wider than the pane.
await openDetail();
await setViewport(320, 640);
await setTextScale(32);
const before = await tabBoxes();
await dragRow(
before.Summary.x + before.Summary.width / 2,
before.Summary.y + before.Summary.height / 2,
-320,
);
const after = await tabBoxes();
log.states.push({ name: "drag", before, after });
if (!(after.Source.x + after.Source.width <= paneRight(320) + 0.5)) {
throw new Error(
`Source is not fully visible after dragging: ` +
`${after.Source.x} + ${after.Source.width}`,
);
}
log.checks.push("320x640 @200%: mouse drag reveals the Source tab");
await capture(connection, captureDir, log, "07-320-text200-scrolled");
await click(connection, "Source");
// The source text is canvas-drawn and absent from the accessibility tree, so
// selection is confirmed by the Summary body leaving the tree and the source
// content by inspecting the PNG.
if (!(await waitFor(async () => !(await axHas("Content hash")), 6000))) {
throw new Error("Source tab did not replace the Summary body");
}
log.checks.push("320x640 @200%: Source tab selects after scrolling");
await sleep(600);
await capture(connection, captureDir, log, "08-320-text200-source");
// Keyboard traversal must reach the third tab and scroll it into view.
await openDetail();
await setViewport(320, 640);
await setTextScale(32);
await click(connection, "Summary");
await pressTab();
await pressTab();
const keyboard = await tabBoxes();
log.states.push({ name: "keyboard-320-text200", boxes: keyboard });
if (!(keyboard.Source.x + keyboard.Source.width <= paneRight(320) + 0.5)) {
throw new Error(
`Keyboard traversal did not reveal Source: ` +
`${keyboard.Source.x} + ${keyboard.Source.width}`,
);
}
log.checks.push("320x640 @200%: keyboard traversal reveals the Source tab");
await capture(connection, captureDir, log, "09-320-text200-keyboard");
// A fitting row still spans the pane at 100% (no regression from scrolling).
await openDetail();
await setViewport(1200, 900);
await setTextScale(16);
const full = await tabBoxes();
const rowWidth = full.Source.x + full.Source.width - full.Summary.x;
log.states.push({ name: "wide-100", full, rowWidth });
if (Math.abs(rowWidth - 687.4) > 8) {
throw new Error(`Wide row width changed: ${rowWidth}`);
}
log.checks.push("1200x900 @100%: tab row still fills the detail pane");
await capture(connection, captureDir, log, "10-1200-text100-detail");
} catch (error) {
log.error = String(error?.stack ?? error);
try {
const nodes = await axNodes(connection);
log.failureAx = nodes
.filter((node) => node.name?.value)
.map((node) => `${node.role?.value}: ${node.name.value}`)
.slice(0, 160);
} catch {
// The browser may already be gone; the error itself is still recorded.
}
process.exitCode = 1;
} finally {
await writeFile(join(captureDir, "probe.json"), JSON.stringify(log, null, 2));
connection?.close();
chrome.kill("SIGTERM");
server.close();
}