feat(app): render the pinned definition graph in the pipeline Graph tab

This commit is contained in:
2026-10-22 00:07:53 +01:00
parent 2bc2358b9a
commit 0176720fe5
15 changed files with 1562 additions and 140 deletions
@@ -1,28 +0,0 @@
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;
}
@@ -116,6 +116,8 @@ class PipelineDetail extends PipelineSummary {
required this.contentHash,
required this.source,
required this.versions,
this.graph,
this.shape,
});
factory PipelineDetail.fromJson(PipelineJson json) {
@@ -144,6 +146,8 @@ class PipelineDetail extends PipelineSummary {
),
)
: const <PipelineVersion>[],
graph: _jsonObject(json['graph']),
shape: _jsonObject(json['shape']),
);
}
@@ -153,6 +157,15 @@ class PipelineDetail extends PipelineSummary {
final String source;
final List<PipelineVersion> versions;
/// The exact definition graph this reply pinned for [resolvedVersion].
///
/// Raw JSON: its fields are never normalised here. Null means the reply
/// carried no graph, which is not the same as a definition with no stages.
final PipelineJson? graph;
/// The optional compact graph summary some replies add, kept verbatim.
final PipelineJson? shape;
/// 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;
@@ -223,3 +236,7 @@ int? _optionalInt(Object? value) {
}
String _string(Object? value) => value is String ? value : '';
/// A raw JSON object exactly as a reply carried it, or null when absent.
PipelineJson? _jsonObject(Object? value) =>
value is Map ? Map<String, dynamic>.from(value) : null;
+1 -17
View File
@@ -2,14 +2,12 @@ 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
@@ -19,9 +17,6 @@ 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.
///
/// Standalone use keeps the screen's own native scaffolding. The application
/// shell sets [embedded] because it already owns the one navigation bar, and
/// supplies [syncToken] so a reconnect refreshes in place.
@@ -29,15 +24,11 @@ class PipelinesScreen extends StatefulWidget {
const PipelinesScreen({
super.key,
required this.gateway,
this.graphBuilder,
this.onStageSelected,
this.embedded = false,
this.syncToken = 0,
});
final ApiGateway gateway;
final PipelineGraphBuilder? graphBuilder;
final ValueChanged<PipelineStageRef>? onStageSelected;
/// True under the application shell, which owns the single navigation bar.
final bool embedded;
@@ -90,12 +81,7 @@ class _PipelinesScreenState extends State<PipelinesScreen> {
final wide = constraints.maxWidth >= kPipelinesWideBreakpoint;
if (!wide) {
return _controller.hasSelection
? PipelineDetailPanel(
controller: _controller,
showBack: true,
graphBuilder: widget.graphBuilder,
onStageSelected: widget.onStageSelected,
)
? PipelineDetailPanel(controller: _controller, showBack: true)
: PipelineListPanel(controller: _controller);
}
return Row(
@@ -111,8 +97,6 @@ class _PipelinesScreenState extends State<PipelinesScreen> {
child: PipelineDetailPanel(
controller: _controller,
showBack: false,
graphBuilder: widget.graphBuilder,
onStageSelected: widget.onStageSelected,
),
),
],
@@ -1,28 +1,35 @@
import 'dart:math' as math;
import 'package:flutter/material.dart';
import '../pipeline_graph_hook.dart';
import '../../graph/widgets/stage_definition_view.dart';
import '../pipeline_models.dart';
import '../pipeline_query.dart';
import '../pipelines_controller.dart';
import 'pipeline_controls.dart';
import 'pipeline_detail_styles.dart';
import 'pipeline_graph_tab.dart';
import 'pipeline_summary_view.dart';
import 'pipeline_tabs.dart';
/// The right/bottom pane: Summary, Source and the optional graph hook.
/// The least height the selected tab keeps for its own content.
///
/// A header, banners and tabs that would leave the tab less than this may
/// scroll instead: content-driven layout must not let scaled title text squeeze
/// the tab away. Ordinary sizes never reach this reserve, so the header keeps
/// its natural height there.
const double kPipelineDetailMinContentHeight = 160;
/// The right/bottom pane: Summary, Graph, Source and version history.
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();
@@ -31,43 +38,127 @@ class PipelineDetailPanel extends StatefulWidget {
class _PipelineDetailPanelState extends State<PipelineDetailPanel> {
PipelineDetailTab _tab = PipelineDetailTab.summary;
/// The node selected in the Graph tab, kept here (not in the tab) so a
/// Summary/Source round trip cannot drop it. The web keeps its
/// `pipelineGraphSelection` across in-place tab changes for the same reason.
String? _graphSelection;
/// The pinned identity [_graphSelection] belongs to. A different pipeline or
/// version is a different definition, so its mark is cleared.
String? _graphPin;
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),
],
_retainGraphSelection(detail);
return LayoutBuilder(
builder: (context, constraints) {
final headerLimit = _headerLimit(constraints);
return Column(
key: const Key('pipeline-detail'),
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
ConstrainedBox(
constraints: BoxConstraints(maxHeight: headerLimit),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
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),
),
],
),
),
),
// Every tab gets the bounded remaining height. Summary/source
// scroll their own content; the graph fills the slot so its canvas
// is never asked for an unbounded extent inside a scroll view.
Expanded(
child: switch (_tab) {
PipelineDetailTab.summary => _scrolling(
PipelineSummaryView(controller: _controller, detail: detail),
),
PipelineDetailTab.graph => PipelineGraphTab(
detail: detail,
selectedStage: _graphSelection,
onSelected: (stageKey) =>
_openGraphStage(context, detail, stageKey),
),
PipelineDetailTab.source => _source(context, detail),
},
),
],
);
},
);
}
/// The header keeps its natural height while at least
/// [kPipelineDetailMinContentHeight] remains for the tab, and never more than
/// the panel itself; past that it scrolls.
double _headerLimit(BoxConstraints constraints) {
if (!constraints.hasBoundedHeight) return double.infinity;
final height = constraints.maxHeight;
// Below twice the reserve the two shares meet at 40%, so the header stays
// reachable even in a panel shorter than the reserve itself.
final floorShare = height * 0.4;
final reserve = height - kPipelineDetailMinContentHeight;
return math.max(floorShare, reserve).clamp(0.0, height);
}
/// Clears a selection whose pinned definition is no longer the one shown.
///
/// This runs during build because detail replies arrive through the
/// controller's notifier (a reconnect can replace a detail without ever
/// nulling it), not through a new widget. The cleared value is used by this
/// same build, so no extra frame is needed.
void _retainGraphSelection(PipelineDetail detail) {
final pin = '${detail.id}@${detail.resolvedVersion}';
if (pin == _graphPin) return;
_graphPin = pin;
_graphSelection = null;
}
/// Selects a node and opens the landed definition page for the pinned graph.
void _openGraphStage(
BuildContext context,
PipelineDetail detail,
String stageKey,
) {
final graph = detail.graph;
if (graph == null) return;
setState(() => _graphSelection = stageKey);
openStageDefinition(
context,
graph: graph,
stageKey: stageKey,
pipelineId: detail.id,
pipelineName: detail.name,
version: detail.resolvedVersion,
);
}
Widget _scrolling(Widget child) =>
ListView(children: [child, const SizedBox(height: 24)]);
Widget _withoutDetail(BuildContext context) {
if (!_controller.hasSelection) {
return Center(
@@ -140,36 +231,15 @@ class _PipelineDetailPanelState extends State<PipelineDetailPanel> {
);
}
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(
return ListView(
padding: const EdgeInsets.all(16),
child: detail.source.isEmpty
? Text('No source recorded.', style: pipelineMutedStyle(context))
: SelectableText(detail.source, style: pipelineValueStyle(context)),
children: [
if (detail.source.isEmpty)
Text('No source recorded.', style: pipelineMutedStyle(context))
else
SelectableText(detail.source, style: pipelineValueStyle(context)),
],
);
}
}
@@ -1,5 +1,4 @@
/// The detail sections. Graph rendering is owned by the later graph item; the
/// tab row provides the tab and an optional integration hook.
/// The detail sections: Summary, the pinned definition Graph and Source.
enum PipelineDetailTab {
summary('Summary'),
graph('Graph'),
@@ -0,0 +1,225 @@
import 'dart:math' as math;
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../graph/widgets/definition_graph_view.dart';
import '../pipeline_models.dart';
import 'pipeline_controls.dart';
import 'pipeline_detail_styles.dart';
/// The Graph tab's guidance note. Gestures stay the host's own: wheel or pinch
/// zoom, drag pan, and an ordinary tap/click selects a node.
const String pipelineGraphNote =
'Scroll or pinch to zoom, drag to pan, select a stage for details. '
'Edges are labelled with their outcome; error* is the implicit fallback.';
/// A reply that carried no definition graph: nothing is reconstructed from the
/// source and no empty graph stands in for the missing definition.
const String pipelineGraphMissing =
'This reply did not include the pipeline definition graph, so it cannot be '
'drawn. No graph has been reconstructed from the source.';
/// The most of the tab's slot the guidance note may take.
///
/// The graph is the tab's content and the note is guidance, so the note starts
/// from one third. When the whole note does not fit it keeps whole lines only
/// and scrolls behind a native, visible scrollbar instead of ending on a
/// half-drawn row. A share shorter than two lines grows to two whole lines (one
/// line for very large text), and never past half the tab, so the canvas always
/// keeps at least half of it.
const double pipelineGraphNoteShare = 1 / 3;
/// The detail Graph tab: the pinned definition as a bounded native canvas.
///
/// The graph comes from [PipelineDetail.graph] exactly as the reply pinned it
/// for the selected version. Selecting any node, including a terminal, reports
/// its key so the host can open the landed full-screen stage-definition page
/// for that same pipeline id, name and resolved version. No run evidence is
/// read, so nodes and terminals can never look visited.
class PipelineGraphTab extends StatelessWidget {
const PipelineGraphTab({
super.key,
required this.detail,
required this.selectedStage,
required this.onSelected,
});
final PipelineDetail detail;
/// The selected node key, kept by the detail panel so it survives a tab
/// switch. Null means nothing is selected.
final String? selectedStage;
/// Reports the exact node key activated, including `#success`/`#failure`.
final ValueChanged<String> onSelected;
@override
Widget build(BuildContext context) {
final graph = detail.graph;
if (graph == null) {
return ListView(
key: const Key('pipeline-graph-missing'),
padding: const EdgeInsets.all(16),
children: [
Text(pipelineGraphMissing, style: pipelineMutedStyle(context)),
],
);
}
return LayoutBuilder(
builder: (context, constraints) {
// The panel gives this tab the remaining bounded height. Cap the note
// against that same slot so a short window or scaled text can only
// scroll the note, never overflow the column or leave the canvas at
// zero height.
final noteLimit = constraints.hasBoundedHeight
? constraints.maxHeight * pipelineGraphNoteShare
: double.infinity;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_GraphGuidanceNote(
maxHeight: noteLimit,
slotHeight: constraints.hasBoundedHeight
? constraints.maxHeight
: double.infinity,
),
Expanded(
child: DefinitionGraphView(
key: const Key('pipeline-definition-graph'),
graph: graph,
selectedStage: selectedStage,
onSelected: onSelected,
),
),
],
);
},
);
}
}
/// The guidance note, kept to a readable share of the tab without ever cutting
/// a text line.
///
/// An earlier cap let the note end on a partially drawn row with no hint that
/// more guidance existed. The note is measured with the same style, width and
/// text scale its [Text] will use, so the visible part is always a whole number
/// of lines, and the hidden rest scrolls behind the host's own scrollbar. That
/// keeps a visible affordance while the graph below keeps at least half the
/// slot.
class _GraphGuidanceNote extends StatefulWidget {
const _GraphGuidanceNote({required this.maxHeight, required this.slotHeight});
/// The note's starting share of the tab (see [pipelineGraphNoteShare]).
final double maxHeight;
/// The whole tab slot, so two whole lines may exceed [maxHeight] while the
/// canvas still keeps at least half of it.
final double slotHeight;
@override
State<_GraphGuidanceNote> createState() => _GraphGuidanceNoteState();
}
class _GraphGuidanceNoteState extends State<_GraphGuidanceNote> {
final ScrollController _scrollController = ScrollController();
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final style = DefaultTextStyle.of(
context,
).style.merge(pipelineMutedStyle(context));
return LayoutBuilder(
builder: (context, constraints) {
final painter = TextPainter(
text: TextSpan(text: pipelineGraphNote, style: style),
textDirection: Directionality.of(context),
textScaler: MediaQuery.textScalerOf(context),
)..layout(maxWidth: math.max(0, constraints.maxWidth - 32));
final totalHeight = painter.height;
final limit = _noteLimit(painter);
final truncated = totalHeight > limit + 0.5;
final visibleHeight = truncated
? _wholeLineHeight(painter, limit)
: totalHeight;
final text = Padding(
padding: EdgeInsets.fromLTRB(16, 0, 16, truncated ? 0 : 8),
child: Text(pipelineGraphNote, style: style),
);
return SizedBox(
key: const Key('pipeline-graph-note'),
height: truncated ? visibleHeight : totalHeight + 8,
child: truncated
? _scrollbar(
SingleChildScrollView(
key: const Key('pipeline-graph-note-scroll'),
controller: _scrollController,
primary: false,
padding: const EdgeInsets.only(bottom: 8),
child: text,
),
)
: text,
);
},
);
}
/// The note's slot: its [pipelineGraphNoteShare] of the tab, or two whole
/// lines when that share is shorter, and never more than half the tab so the
/// canvas always keeps the other half.
double _noteLimit(TextPainter painter) {
if (!widget.slotHeight.isFinite) return widget.maxHeight;
final lines = painter.computeLineMetrics();
final lineHeight = lines.isEmpty
? painter.preferredLineHeight
: lines.first.height;
return math.max(
widget.maxHeight,
math.min(lineHeight * 2, widget.slotHeight * 0.5),
);
}
/// The largest whole-line height that fits in [limit].
///
/// Whole lines keep the clipped edge from cutting through a glyph row. If
/// even the first line is taller than the limit the row is clipped anyway:
/// that only happens when the whole tab is barely two lines tall.
double _wholeLineHeight(TextPainter painter, double limit) {
final lines = painter.computeLineMetrics();
var consumed = 0.0;
for (final line in lines) {
final next = consumed + line.height;
if (next > limit + 0.5) break;
consumed = next;
}
if (consumed > 0 || lines.isEmpty) return consumed;
return math.min(lines.first.height, limit);
}
/// The host's own scrollbar: visible whenever the note is clipped, and
/// draggable with the pointer, so the rest is discoverable without a wheel.
Widget _scrollbar(Widget child) {
if (useCupertinoControls(context)) {
return CupertinoScrollbar(
key: const Key('pipeline-graph-note-scrollbar'),
controller: _scrollController,
thumbVisibility: true,
child: child,
);
}
return Scrollbar(
key: const Key('pipeline-graph-note-scrollbar'),
controller: _scrollController,
thumbVisibility: true,
child: child,
);
}
}
+75
View File
@@ -0,0 +1,75 @@
# Pipeline detail Graph tab — pinned definition wiring
Candidate for the graph-tab slice. All work is under `app/`; no commit, push,
deployment or production mutation was made.
## Implemented
- `PipelineDetail` retains `graph` and optional `shape` as raw JSON from the
reply. Source, versions and every existing field keep their previous parsing;
an absent graph stays `null` rather than becoming an empty definition.
- The detail panel gives its tabs the remaining bounded height: Summary and
Source scroll inside that slot, the Graph tab fills it.
- `PipelineGraphTab` renders the landed `DefinitionGraphView` (measured nodes,
routed edges/labels, stock pan/zoom) and the web's guidance vocabulary adapted
to host gestures. Selecting any node, including `Success`/`Failure`, opens the
landed `openStageDefinition` pane with the pinned pipeline id, name and
resolved version. No run status or visited styling is read.
- The selected node key lives in `PipelineDetailPanel`, not in the tab, so a
Summary/Source round trip keeps the mark (the web keeps its
`pipelineGraphSelection` across in-place tab changes). A different pipeline or
resolved version clears it, including an in-place reconnect reload that keeps
a detail rather than nulling it.
- A reply without `graph` states that the definition is missing and draws
nothing. Empty definitions still get `This pipeline has no stages.` from the
graph view.
- The obsolete P2 `graphBuilder`/`PipelineStageRef` hook and its pending-state
test were removed; the production shell never supplied one.
## Bounded-height fix (review must-fix)
The first candidate made the guidance note a fixed child above
`Expanded(DefinitionGraphView)`. When the tab slot was shorter than the note,
the column overflowed and the canvas was laid out at 0 height (390x600 @2x,
1100x400 @2x, 1100x900 @3x), and the note also took most of the slot at
390x844 @2x.
- `PipelineGraphTab` now measures the slot with `LayoutBuilder` and caps the note
at `pipelineGraphNoteShare` (one third). A note longer than its share scrolls
inside it, so the canvas always keeps at least two thirds and can never be
zero. At ordinary sizes the note keeps its natural height.
- `PipelineDetailPanel` keeps a `kPipelineDetailMinContentHeight` reserve for the
selected tab and lets the header/banners/tabs scroll when a very short panel
(for example 390x300 @3x) would otherwise squeeze the tab away. Normal sizes
keep the header's natural height.
- Regression tests cover 390x844 @2x, 390x600 @2x, 1100x400 @2x, 1100x900 @3x,
an empty definition in a 200 px slot, and the 390x300 @3x panel header.
- The test fixture now pins a distinct v1 graph, so the version-switch test
proves the mark is cleared rather than reusing the newer definition.
## Checks
- `flutter analyze` — no issues.
- `flutter test test/features/pipelines test/features/graph` — 198 pass.
- `flutter test` — 788 pass.
- `flutter build web` — pass.
- Review repro (`public/review/graph_tab_overflow_repro_test.dart`): all 4
cases now pass, including the three that failed before the fix.
- Browser fixture (`tool/pipeline_graph_tab_probe.dart`,
`tool/pipeline_graph_tab_probe.mjs`), actual `PipelinesScreen` with the
in-memory fixture gateway, dark, both hosts, at 1280x900 @2x, plus Material at
390x844 @2x, 390x600 @2x and 1100x900 @3x: every run 4 checks and 3 PNG
captures. Captures and JSON:
`/Users/alan/.local/share/pipelines/data/artifacts/85/public/pipeline-graph-tab-probe-fixed/`
- Not verified: live authenticated server, Android/iOS builds or devices, shell
URL routing for graph selection. Initial fit-to-viewport is not implemented
(the web auto-fits on mount); pan/zoom and the guidance note cover discovering
off-screen nodes, and the now-larger canvas keeps more of the graph in view.
## Manager completion after the Code deadline
The last Code visit reached its deadline while active; the retained tree is
complete and its pipelines suite passes (62 tests), including the 390x844/2x,
short-slot and pinned-definition cases. Manager merged it directly: the Graph tab
now renders the measured definition canvas in a bounded slot and opening a node
shows its authored definition for the pinned version. No run evidence is implied.
+56
View File
@@ -65,6 +65,8 @@ Map<String, dynamic> pipelineDetail({
int? scheduleCount = 0,
bool? scheduled = false,
List<Map<String, dynamic>> versions = const [],
Map<String, dynamic>? graph,
Map<String, dynamic>? shape,
}) => {
...pipelineSummary(
id: id,
@@ -79,6 +81,50 @@ Map<String, dynamic> pipelineDetail({
'content_hash': contentHash,
'source': source,
'versions': versions,
'graph': ?graph,
'shape': ?shape,
};
/// The two-stage definition pinned into the Alpha detail fixture.
Map<String, dynamic> reviewGraph() => {
'name': 'Alpha review',
'settings': {'schedules': <dynamic>[]},
'stages': <dynamic>[
{
'key': 'review',
'type': 'model',
'prompt': 'Review the change.',
'output': 'notes',
'edges': {'success': 'publish', 'error': '#'},
'fallback_error': true,
'future_field': {'kept': true},
},
{
'key': 'publish',
'type': 'model',
'output': 'release',
'edges': {'success': '#success', 'error': '#failure'},
},
],
};
/// The one-stage definition pinned by Alpha review v1.
///
/// A real version pin never reuses the newer graph, so the fixture keeps a
/// distinct v1 definition too: a version switch must not keep a newer node's
/// selection merely because the node key survived.
Map<String, dynamic> reviewGraphV1() => {
'name': 'Alpha review',
'settings': {'schedules': <dynamic>[]},
'stages': <dynamic>[
{
'key': 'review',
'type': 'model',
'prompt': 'Review the change.',
'output': 'notes',
'edges': {'success': '#success', 'error': '#'},
},
],
};
Map<String, dynamic> versionSummary(
@@ -166,6 +212,8 @@ class PipelineFixture {
scheduled: true,
source: 'name: Alpha review\nstages:\n review:\n type: model',
versions: [versionSummary(1, stages: 1), versionSummary(2, stages: 2)],
graph: reviewGraph(),
shape: reviewGraph(),
),
pipelineDetail(
id: 2,
@@ -201,6 +249,12 @@ class PipelineFixture {
),
];
/// The graph pinned by each recorded version, when it differs from latest.
late final Map<String, Map<String, dynamic>> versionGraphs = {
'1@1': reviewGraphV1(),
'1@2': reviewGraph(),
};
Map<String, dynamic>? detailFor(int id, int version) {
final match = details.where((detail) => detail['id'] == id);
if (match.isEmpty) return null;
@@ -210,6 +264,8 @@ class PipelineFixture {
for (final row in detail['versions'] as List<Map<String, dynamic>>) {
if (row['version'] == version) detail['stages'] = row['stages'];
}
final graph = versionGraphs['$id@$version'];
if (graph != null) detail['graph'] = graph;
if (version < (detail['latest_version'] as int)) {
detail['source'] = '${detail['source']}\n# selected version $version';
}
@@ -0,0 +1,152 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/widgets/definition_graph_view.dart';
import 'package:pipelines_app/features/pipelines/pipeline_models.dart';
import 'package:pipelines_app/features/pipelines/widgets/pipeline_graph_tab.dart';
import 'fixtures.dart';
/// The note is measured and clipped by this tab, so these cases pump it at the
/// tab slots the real panel gives it (390x312 and 660x168 are the measured
/// slots at 390x600 and 1100x400 on a 2x text scale).
Future<void> _pumpTab(
WidgetTester tester,
Size size, {
double scale = 2,
}) async {
await tester.pumpWidget(
MaterialApp(
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(scale)),
child: child!,
),
home: Scaffold(
body: Center(
child: SizedBox(
width: size.width,
height: size.height,
child: PipelineGraphTab(
detail: _detail(),
selectedStage: null,
onSelected: (_) {},
),
),
),
),
),
);
await tester.pumpAndSettle();
}
PipelineDetail _detail() => PipelineDetail.fromJson(
pipelineDetail(
id: 1,
name: 'Alpha review',
version: 2,
latestVersion: 2,
graph: reviewGraph(),
),
);
/// The line heights the rendered [Text] actually uses at the current scale.
List<double> _lineHeights(WidgetTester tester) {
final note = tester.widget<Text>(find.text(pipelineGraphNote));
final noteSize = tester.getSize(find.byKey(const Key('pipeline-graph-note')));
final painter = TextPainter(
text: TextSpan(text: pipelineGraphNote, style: note.style),
textDirection: TextDirection.ltr,
textScaler: MediaQuery.textScalerOf(
tester.element(find.byType(PipelineGraphTab)),
),
)..layout(maxWidth: noteSize.width - 32);
return [for (final line in painter.computeLineMetrics()) line.height];
}
void main() {
for (final (size, tabSlot, scale, withinShare) in <(Size, double, double, bool)>[
(const Size(390, 312), 312, 2, true),
// Two whole lines are kept even though a third of the slot is only 56 px,
// so the note stays readable and the canvas keeps over half.
(const Size(660, 168), 168, 2, false),
// A 4x line is taller than a third of this tab; one whole line is kept and
// the canvas still gets more than half.
(const Size(390, 160), 160, 4, false),
]) {
testWidgets('a clipped note keeps whole lines and a visible scrollbar at '
'${size.width.toInt()}x${tabSlot.toInt()} @${scale}x', (tester) async {
await _pumpTab(tester, size, scale: scale);
final noteSize = tester.getSize(
find.byKey(const Key('pipeline-graph-note')),
);
final canvas = tester.getSize(find.byType(DefinitionGraphView));
expect(noteSize.height, greaterThan(0));
expect(
find.byKey(const Key('pipeline-graph-note-scrollbar')),
findsOneWidget,
);
if (withinShare) {
expect(
noteSize.height,
lessThanOrEqualTo(tabSlot * pipelineGraphNoteShare + 0.5),
);
}
// The clipped viewport ends on a line boundary: no half-drawn row.
final heights = _lineHeights(tester);
var whole = 0.0;
for (final height in heights) {
if (whole + height > noteSize.height + 0.5) break;
whole += height;
}
expect(whole, greaterThan(0));
expect(noteSize.height, closeTo(whole, 0.5));
expect(
noteSize.height,
lessThan(heights.fold<double>(0, (a, b) => a + b)),
);
// The hidden tail is really scrollable: a standard scrollbar plus wheel
// and drag, not an inert clipped label.
final scrollbar = tester.widget<Scrollbar>(
find.byKey(const Key('pipeline-graph-note-scrollbar')),
);
final controller = scrollbar.controller!;
expect(controller.position.maxScrollExtent, greaterThan(0));
await tester.drag(
find.byKey(const Key('pipeline-graph-note-scroll')),
const Offset(0, -400),
);
await tester.pumpAndSettle();
expect(controller.position.pixels, greaterThan(0));
// The canvas keeps the rest of the slot throughout.
expect(canvas.height, greaterThan(0));
expect(canvas.height, greaterThanOrEqualTo(tabSlot * 0.5));
expect(tester.takeException(), isNull);
});
}
testWidgets('a note that fits keeps its natural height and no scrollbar', (
tester,
) async {
await _pumpTab(tester, const Size(1000, 700), scale: 1);
expect(
find.byKey(const Key('pipeline-graph-note-scrollbar')),
findsNothing,
);
expect(find.byKey(const Key('pipeline-graph-note-scroll')), findsNothing);
expect(
tester.getSize(find.byKey(const Key('pipeline-graph-note'))).height,
lessThan(120),
);
expect(
tester.getSize(find.byType(DefinitionGraphView)).height,
greaterThan(500),
);
expect(tester.takeException(), isNull);
});
}
@@ -0,0 +1,293 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/widgets/definition_graph_view.dart';
import 'package:pipelines_app/features/graph/widgets/graph_stage_node.dart';
import 'package:pipelines_app/features/graph/widgets/stage_definition_view.dart';
import 'package:pipelines_app/features/pipelines/screen.dart';
import 'package:pipelines_app/features/pipelines/widgets/pipeline_graph_tab.dart';
import 'fixtures.dart';
import 'test_helpers.dart';
Finder _node(String key) => find.byWidgetPredicate(
(widget) => widget is GraphStageNode && widget.node.key == key,
);
/// Taps a node, panning the stock canvas first when the node starts offscreen.
Future<void> _tapNode(WidgetTester tester, String key) async {
final viewport = tester.getRect(find.byType(InteractiveViewer));
final node = tester.getRect(_node(key));
if (!viewport.contains(node.center)) {
await tester.drag(
find.byType(InteractiveViewer),
viewport.center - node.center,
);
await tester.pumpAndSettle();
}
await tester.tap(_node(key));
await tester.pump();
}
Future<void> _pumpScreen(
WidgetTester tester,
Size size, {
double scale = 1,
FakeGateway? gateway,
int syncToken = 0,
}) async {
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(
MaterialApp(
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(scale)),
child: child!,
),
home: PipelinesScreen(
gateway: gateway ?? gatewayFor(PipelineFixture()),
syncToken: syncToken,
),
),
);
await tester.pumpAndSettle();
}
Future<void> _openGraphTab(WidgetTester tester, int pipelineId) async {
await tester.tap(find.byKey(Key('pipeline-row-$pipelineId')));
await tester.pumpAndSettle();
await tester.tap(find.text('Graph'));
await tester.pump();
await tester.pump();
}
void main() {
test('detail keeps the pinned graph verbatim without touching source', () {
final graph = reviewGraph();
final detail = PipelineDetail.fromJson(
pipelineDetail(
id: 9,
name: 'Pinned review',
version: 4,
latestVersion: 5,
source: 'exact: authored source',
stages: 2,
versions: [versionSummary(4, stages: 2)],
graph: graph,
shape: graph,
),
);
expect(detail.graph, graph);
expect(detail.shape, graph);
expect(detail.graph!['settings'], {'schedules': <dynamic>[]});
expect((detail.graph!['stages'] as List<dynamic>).first['future_field'], {
'kept': true,
});
expect(detail.source, 'exact: authored source');
expect(detail.versions.single.version, 4);
expect(detail.resolvedVersion, 4);
});
test('a reply without a graph keeps null instead of inventing one', () {
final detail = PipelineDetail.fromJson(
pipelineDetail(id: 2, name: 'Beta deploy', version: 1, latestVersion: 1),
);
expect(detail.graph, isNull);
expect(detail.shape, isNull);
});
// The note must never take the canvas away: a short window (390x600), a short
// wide split pane (1100x400) and a large accessibility text scale (3x) all
// used to overflow the tab and lay the canvas out at zero height.
for (final (size, scale) in <(Size, double)>[
(const Size(390, 844), 2),
(const Size(390, 600), 2),
(const Size(1100, 400), 2),
(const Size(1100, 900), 3),
]) {
testWidgets('graph tab keeps a usable canvas at '
'${size.width.toInt()}x${size.height.toInt()} @${scale}x', (
tester,
) async {
await _pumpScreen(tester, size, scale: scale);
await _openGraphTab(tester, 1);
expect(tester.takeException(), isNull);
expect(find.text(pipelineGraphNote), findsOneWidget);
expect(find.byType(DefinitionGraphView), findsOneWidget);
final tab = tester.getSize(find.byType(PipelineGraphTab));
final note = tester.getSize(find.byKey(const Key('pipeline-graph-note')));
final canvas = tester.getSize(find.byType(DefinitionGraphView));
expect(canvas.height, greaterThan(0));
expect(
note.height,
lessThanOrEqualTo(tab.height * 0.5 + 1),
reason: 'the guidance note may never take more than half the tab',
);
expect(
canvas.height,
greaterThanOrEqualTo(tab.height * 0.5 - 1),
reason: 'the canvas keeps at least half of the tab slot',
);
expect(canvas.height, lessThan(tab.height));
});
}
testWidgets('an empty definition keeps its message in a short slot', (
tester,
) async {
final detail = PipelineDetail.fromJson(
pipelineDetail(
id: 4,
name: 'Empty definition',
version: 1,
latestVersion: 1,
graph: {'name': 'Empty definition', 'stages': <dynamic>[]},
),
);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Center(
child: SizedBox(
width: 390,
height: 200,
child: PipelineGraphTab(
detail: detail,
selectedStage: null,
onSelected: (_) {},
),
),
),
),
),
);
await tester.pumpAndSettle();
expect(find.text(definitionGraphEmpty), findsOneWidget);
expect(find.byType(GraphStageNode), findsNothing);
expect(tester.takeException(), isNull);
});
testWidgets('selecting a node opens its exact pinned definition', (
tester,
) async {
await _pumpScreen(tester, const Size(1100, 900));
await _openGraphTab(tester, 1);
await _tapNode(tester, 'review');
await tester.pumpAndSettle();
final stagePane = tester.widget<StageDefinitionView>(
find.byType(StageDefinitionView),
);
expect(stagePane.stageKey, 'review');
expect(stagePane.pipelineId, 1);
expect(stagePane.pipelineName, 'Alpha review');
expect(stagePane.version, 2);
expect(stagePane.graph, reviewGraph());
expect(find.text('review definition'), findsOneWidget);
expect(find.text('Alpha review · v2'), findsOneWidget);
await tester.pageBack();
await tester.pumpAndSettle();
expect(find.byType(StageDefinitionView), findsNothing);
expect(tester.widget<GraphStageNode>(_node('review')).selected, isTrue);
// The selection belongs to the panel, so an in-place tab round trip keeps
// the same node marked (the web keeps its graph selection across tabs).
await tester.tap(find.text('Summary'));
await tester.pumpAndSettle();
await tester.tap(find.text('Graph'));
await tester.pump();
await tester.pump();
expect(tester.widget<GraphStageNode>(_node('review')).selected, isTrue);
// Terminals are definition targets too: they open the same pane with the
// pinned identity, not a visit.
await _tapNode(tester, '#success');
await tester.pumpAndSettle();
final terminalPane = tester.widget<StageDefinitionView>(
find.byType(StageDefinitionView),
);
expect(terminalPane.stageKey, '#success');
expect(terminalPane.pipelineId, 1);
expect(terminalPane.version, 2);
expect(find.text('Success definition'), findsOneWidget);
await tester.pageBack();
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
// The selection belongs to the pinned definition: changing version must not
// carry a same-named node's mark into the other version.
await tester.tap(find.text('Summary'));
await tester.pumpAndSettle();
await tester.ensureVisible(find.byKey(const Key('pipeline-version-1')));
await tester.pumpAndSettle();
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('Graph'));
await tester.pump();
await tester.pump();
expect(tester.widget<GraphStageNode>(_node('review')).selected, isFalse);
expect(
tester
.widget<DefinitionGraphView>(find.byType(DefinitionGraphView))
.graph,
reviewGraphV1(),
);
});
testWidgets('a reconnect that replaces the detail clears the old mark', (
tester,
) async {
var latest = 2;
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, latest)!,
),
_ => errorReply('unexpected $type'),
},
);
await _pumpScreen(tester, const Size(1100, 900), gateway: gateway);
await _openGraphTab(tester, 1);
await _tapNode(tester, 'review');
await tester.pumpAndSettle();
await tester.pageBack();
await tester.pumpAndSettle();
expect(tester.widget<GraphStageNode>(_node('review')).selected, isTrue);
// A reconnect reloads the selected detail in place (it is not nulled), so
// this is the path the old tab-state guard existed for. The newer pin must
// not inherit the previous version's mark.
latest = 3;
await _pumpScreen(
tester,
const Size(1100, 900),
gateway: gateway,
syncToken: 1,
);
expect(find.byType(GraphStageNode), findsWidgets);
expect(tester.widget<GraphStageNode>(_node('review')).selected, isFalse);
expect(tester.takeException(), isNull);
});
testWidgets('a missing definition graph is stated, never drawn', (
tester,
) async {
await _pumpScreen(tester, const Size(1100, 900));
await _openGraphTab(tester, 2);
expect(find.text(pipelineGraphMissing), findsOneWidget);
expect(find.byType(DefinitionGraphView), findsNothing);
expect(find.byType(GraphStageNode), findsNothing);
});
}
@@ -2,7 +2,11 @@ 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/graph/widgets/definition_graph_view.dart';
import 'package:pipelines_app/features/pipelines/pipeline_repository.dart';
import 'package:pipelines_app/features/pipelines/pipelines_controller.dart';
import 'package:pipelines_app/features/pipelines/screen.dart';
import 'package:pipelines_app/features/pipelines/widgets/pipeline_detail_panel.dart';
import 'package:pipelines_app/features/pipelines/widgets/pipeline_tabs.dart';
import 'fixtures.dart';
@@ -142,37 +146,45 @@ void main() {
}
});
testWidgets('hosted graph hook receives the selected pipeline and stage', (
testWidgets('3x text in a very short panel keeps the tabs reachable', (
tester,
) async {
final fixture = PipelineFixture();
PipelineStageRef? selected;
tester.view.physicalSize = const Size(390, 300);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final controller = PipelinesController(
PipelinesRepository(gatewayFor(PipelineFixture())),
);
addTearDown(controller.dispose);
await controller.openPipeline(1);
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,
builder: (context, child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: const TextScaler.linear(3)),
child: child!,
),
home: Scaffold(
body: PipelineDetailPanel(controller: controller, showBack: true),
),
),
);
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('pipeline-row-1')));
// The header scrolls instead of squeezing the tab out; the tabs stay
// reachable inside it and the tab keeps a bounded slot.
expect(tester.takeException(), isNull);
await tester.ensureVisible(find.text('Graph'));
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');
await tester.pump();
expect(tester.takeException(), isNull);
expect(find.byType(DefinitionGraphView), findsOneWidget);
expect(
tester.getSize(find.byType(DefinitionGraphView)).height,
greaterThan(0),
);
});
}
@@ -153,14 +153,4 @@ void main() {
await tester.pumpAndSettle();
expect(gateway.callsOf('list_pipelines').length, lists + 1);
});
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);
});
}
+78
View File
@@ -0,0 +1,78 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pipelines_app/features/pipelines/screen.dart';
import 'pipelines_probe_fixture.dart';
/// Browser fixture for the pipeline detail's real Graph tab.
///
/// `style=cupertino` selects the Cupertino host, `dark=1` its dark theme and
/// `scale=2` a real 2x text scale. The screen, its list, detail, Graph tab and
/// definition pane are the same widgets the app registers; only the replies
/// come from the in-memory fixture.
void main() {
final parameters = Uri.base.queryParameters;
runApp(
_PipelineGraphTabProbe(
cupertino: parameters['style'] == 'cupertino',
dark: parameters['dark'] == '1',
scale: double.tryParse(parameters['scale'] ?? '') ?? 1,
),
);
}
class _PipelineGraphTabProbe extends StatelessWidget {
const _PipelineGraphTabProbe({
required this.cupertino,
required this.dark,
required this.scale,
});
final bool cupertino;
final bool dark;
final double scale;
@override
Widget build(BuildContext context) {
Widget scaled(BuildContext context, Widget? child) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(scale)),
child: child ?? const SizedBox.shrink(),
);
final screen = PipelinesScreen(
gateway: PipelinesProbeGateway(),
embedded: true,
);
if (cupertino) {
return CupertinoApp(
title: 'Pipeline graph fixture',
debugShowCheckedModeBanner: false,
theme: CupertinoThemeData(
brightness: dark ? Brightness.dark : Brightness.light,
),
builder: scaled,
// The application shell owns the navigation bar; the probe keeps the
// same embedded screen inside a host-native page instead of adding a
// second bar that would overlay the detail header.
home: CupertinoPageScaffold(child: SafeArea(child: screen)),
);
}
return MaterialApp(
title: 'Pipeline graph fixture',
debugShowCheckedModeBanner: false,
theme: ThemeData(
platform: TargetPlatform.android,
brightness: Brightness.light,
),
darkTheme: ThemeData(
platform: TargetPlatform.android,
brightness: Brightness.dark,
),
themeMode: dark ? ThemeMode.dark : ThemeMode.light,
builder: scaled,
home: Scaffold(body: SafeArea(child: screen)),
);
}
}
+372
View File
@@ -0,0 +1,372 @@
// Browser acceptance for the pipeline detail's landed Graph tab.
//
// Serves the probe build (`flutter build web -t tool/pipeline_graph_tab_probe.dart`)
// on an OS-assigned loopback port and drives the actual PipelinesScreen: open a
// pipeline, switch to Graph, select a stage node, verify the definition pane's
// pinned identity, close it with Back and confirm the Graph tab is still there.
// Captures are written for both hosts, dark at 2x; the file prefix carries the
// viewport so short-window and large-text runs cannot overwrite each other.
//
// PROBE_VARIANT=material|cupertino PROBE_SCHEME=dark|light PROBE_SCALE=1|2 \
// PROBE_WIDTH=1280 PROBE_HEIGHT=900 PROBE_WEB_ROOT=<probe build> \
// OPENCODE_ARTIFACT_DIR=<dir> node tool/pipeline_graph_tab_probe.mjs
import { createServer } from 'node:http';
import { spawn } from 'node:child_process';
import { once } from 'node:events';
import { setTimeout as delay } from 'node:timers/promises';
import { join, extname, resolve, sep } from 'node:path';
import { tmpdir } from 'node:os';
import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
const root = resolve(
process.env.PROBE_WEB_ROOT ??
join(process.cwd(), 'build/pipeline_graph_tab_probe_web'),
);
const variant = process.env.PROBE_VARIANT ?? 'material';
const scheme = process.env.PROBE_SCHEME ?? 'dark';
const scale = process.env.PROBE_SCALE ?? '2';
const width = Number(process.env.PROBE_WIDTH ?? 1280);
const height = Number(process.env.PROBE_HEIGHT ?? 900);
const chromePath = process.env.CHROME_PATH ??
'/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
const artifactDir = process.env.OPENCODE_ARTIFACT_DIR;
if (!artifactDir) throw new Error('Set OPENCODE_ARTIFACT_DIR for the probe captures');
await mkdir(artifactDir, { recursive: true });
const prefix = `pipeline-graph-${variant}-${scheme}-${scale}x-${width}x${height}`;
const mime = {
'.html': 'text/html',
'.js': 'text/javascript',
'.json': 'application/json',
'.wasm': 'application/wasm',
'.png': 'image/png',
'.ico': 'image/x-icon',
'.otf': 'font/otf',
'.ttf': 'font/ttf',
};
const server = createServer(async (req, res) => {
try {
const path = resolve(root, '.' + decodeURIComponent(new URL(req.url, 'http://localhost').pathname));
if (path !== root && !path.startsWith(root + sep)) return res.writeHead(403).end();
const filePath = path === root || path.endsWith('/') ? join(path, 'index.html') : path;
const file = await readFile(filePath);
res.writeHead(200, { 'content-type': mime[extname(filePath)] ?? 'application/octet-stream' }).end(file);
} catch {
res.writeHead(404).end('not found');
}
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const port = server.address().port;
const profile = await mkdtemp(join(tmpdir(), 'pipeline-graph-chrome-'));
const chrome = spawn(chromePath, [
'--headless=new', '--no-first-run', '--no-default-browser-check', '--disable-gpu',
'--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank',
], { stdio: ['ignore', 'ignore', 'pipe'] });
let stderr = '';
chrome.stderr.on('data', (data) => { stderr += data; });
const waitFor = async (fn) => {
for (let i = 0; i < 140; i++) {
const value = await fn();
if (value) return value;
await delay(100);
}
throw new Error('Timed out waiting for Chrome DevTools');
};
let ws;
try {
const endpoint = await waitFor(() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1]);
ws = new WebSocket(endpoint);
await once(ws, 'open');
let id = 0;
const pending = new Map();
ws.addEventListener('message', (event) => {
const message = JSON.parse(event.data);
if (message.method === 'Runtime.exceptionThrown') {
console.error('PAGE EXCEPTION', JSON.stringify(message.params?.exceptionDetails?.exception?.description));
}
if (message.id && pending.has(message.id)) {
pending.get(message.id)(message);
pending.delete(message.id);
}
});
const send = (method, params = {}, sessionId) => new Promise((resolveCall) => {
const callId = ++id;
pending.set(callId, resolveCall);
ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) }));
});
const created = await send('Target.createTarget', { url: 'about:blank' });
const target = created.result.targetId;
const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result.sessionId;
await send('Page.enable', {}, session);
await send('Runtime.enable', {}, session);
await send('Emulation.setEmulatedMedia', {
features: [{ name: 'prefers-color-scheme', value: scheme }],
}, session);
await send('Emulation.setDeviceMetricsOverride', {
width, height, deviceScaleFactor: 1, mobile: false,
}, session);
const query = `?style=${variant}&dark=${scheme === 'dark' ? 1 : 0}&scale=${scale}`;
const navigation = await send('Page.navigate', { url: `http://127.0.0.1:${port}/${query}` }, session);
if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation));
const evaluate = async (expression) => {
const response = await send('Runtime.evaluate', {
expression, returnByValue: true, awaitPromise: true,
}, session);
if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`);
return response.result?.result?.value;
};
await delay(3500);
const loaded = await evaluate('({url:location.href, ready:document.readyState})');
if (!loaded?.url.includes(`127.0.0.1:${port}/${query}`)) {
throw new Error(`Fixture did not load: ${JSON.stringify(loaded)}`);
}
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
await delay(2200);
const semantics = () => evaluate(`[...document.querySelectorAll('flt-semantics')].map(x => {
const r = x.getBoundingClientRect();
return {
label: (x.getAttribute('aria-label') || (x.innerText || '')).trim(),
x: r.x, y: r.y, width: r.width, height: r.height,
visible: r.width > 0 && r.height > 0 && r.bottom > 0 && r.top < innerHeight,
};
})`);
const labels = async () => (await semantics()).map((item) => item.label).filter(Boolean);
const bodyText = async () => [await evaluate('document.body.innerText'), ...(await labels())].join('\n');
const waitForText = async (needle, context) => {
for (let attempt = 0; attempt < 60; attempt++) {
if ((await bodyText()).includes(needle)) return;
await delay(250);
}
throw new Error(`${context}: missing ${JSON.stringify(needle)}\n${await bodyText()}`);
};
const exact = async (label) => {
const items = await semantics();
return items.filter((item) => item.label === label && item.visible)
.sort((a, b) => a.width * a.height - b.width * b.height)[0] ?? null;
};
const clickItem = async (item) => {
const x = item.x + item.width / 2;
const y = item.y + item.height / 2;
await send('Input.dispatchMouseEvent', {
type: 'mousePressed', x, y, button: 'left', clickCount: 1,
}, session);
await send('Input.dispatchMouseEvent', {
type: 'mouseReleased', x, y, button: 'left', clickCount: 1,
}, session);
await delay(1200);
};
const clickExact = async (label) => {
const item = await exact(label);
if (!item) throw new Error(`Missing control ${JSON.stringify(label)}: ${JSON.stringify(await labels())}`);
await clickItem(item);
};
// A list row's merged semantics label starts with the pipeline name and also
// carries its id/version/run text, so match that prefix and use the row box.
const clickNamed = async (name) => {
const items = await semantics();
const item = items.filter((entry) => entry.label.startsWith(name) && entry.visible)
.sort((a, b) => a.width * a.height - b.width * b.height)[0];
if (!item) throw new Error(`Missing row ${JSON.stringify(name)}: ${JSON.stringify(await labels())}`);
await clickItem(item);
};
const capture = async (name) => {
const data = (await send('Page.captureScreenshot', {
format: 'png', captureBeyondViewport: false,
}, session)).result.data;
const file = `${prefix}-${name}.png`;
await writeFile(join(artifactDir, file), Buffer.from(data, 'base64'));
return file;
};
const evidence = { variant, scheme, scale, width, height, checks: [], captures: [] };
const check = (text, value) => evidence.checks.push({ check: text, value });
await waitForText('Release verification', 'pipeline list');
await clickNamed('Release verification');
await waitForText('Content hash', 'pipeline detail');
check('actual pipeline detail opened from the list', true);
await clickExact('Graph');
await waitForText('select a stage for details', 'graph tab guidance');
await waitForText('inspect', 'definition stage node');
const graphSemantics = await semantics();
const note = graphSemantics.find((item) => item.label.startsWith('Scroll or pinch to zoom'));
if (!note?.visible) throw new Error(`Graph note is not visible: ${JSON.stringify(note)}`);
const tab = graphSemantics.find((item) => item.label === 'Graph');
const node = graphSemantics.find((item) => item.label === 'inspect');
if (!node?.visible || node.width <= 0 || node.height <= 0) {
throw new Error(`Measured stage node is not visible: ${JSON.stringify(node)}`);
}
// The graph is bounded: the tabs and note stay on screen above the canvas
// instead of the canvas growing with the routed layout.
if (!tab?.visible) throw new Error(`Graph tab scrolled away: ${JSON.stringify(tab)}`);
if (note.y + note.height > node.y) {
throw new Error(`Canvas overlaps the note: ${JSON.stringify({ note, node })}`);
}
if (note.height < 16) throw new Error(`Guidance note collapsed: ${JSON.stringify(note)}`);
evidence.nodeRect = node;
evidence.noteRect = note;
// A capped note must be a real scroll region with its remainder present, not
// a label clipped at the viewport edge. Flutter's semantics expose that region
// as an overflow-scrolling group with a scroll-overflow marker, so the page
// proves the hidden guidance exists and is reachable.
const noteScroll = await evaluate(`(() => {
const matches = [...document.querySelectorAll('flt-semantics')]
.filter(x => ((x.getAttribute('aria-label') || x.innerText || '').trim()
.startsWith('Scroll or pinch to zoom')));
matches.sort((a, b) =>
a.getBoundingClientRect().height - b.getBoundingClientRect().height);
let element = matches[0];
while (element && element.tagName === 'FLT-SEMANTICS') {
if (getComputedStyle(element).overflowY === 'scroll') {
const marker = element.querySelector('flt-semantics-scroll-overflow');
return {
scrollable: true,
viewport: element.getBoundingClientRect().height,
overflowHeight: marker ? marker.getBoundingClientRect().height : 0,
};
}
element = element.parentElement;
}
return { scrollable: false, viewport: 0, overflowHeight: 0 };
})()`);
evidence.noteScroll = noteScroll;
if (noteScroll.scrollable) {
if (!(noteScroll.overflowHeight > 0)) {
throw new Error(`Capped note has no scrollable remainder: ${JSON.stringify(noteScroll)}`);
}
check(
'capped guidance note is an explicit scroll region, not a clipped label',
`${Math.round(noteScroll.viewport)}px viewport`,
);
} else {
check('the guidance note fits its slot without scrolling', true);
}
check('graph tab draws a measured native stage node inside a bounded viewport', true);
check('guidance note keeps a readable slot above the canvas', `${note.width}x${note.height}`);
evidence.captures.push(await capture('graph'));
await clickExact('inspect');
await waitForText('inspect definition', 'stage definition pane');
await waitForText('Release verification · v3', 'pinned identity');
await waitForText('Inspect the candidate release.', 'stage definition field');
const paneLabels = await labels();
if (paneLabels.includes('Release verification') && !paneLabels.includes('Graph')) {
throw new Error(`Definition pane did not replace the detail: ${JSON.stringify(paneLabels)}`);
}
evidence.checks.push({
check: 'selecting a stage opens the definition pane for the exact pinned identity',
value: 'Release verification · v3',
});
evidence.captures.push(await capture('stage-definition'));
await clickExact('Back');
await waitForText('Scroll or pinch to zoom, drag to pan', 'graph tab after Back');
const afterClose = await bodyText();
if (afterClose.includes('inspect definition')) {
throw new Error(`Definition pane stayed open after Back: ${afterClose}`);
}
check('Back closes the definition pane and returns to the same graph tab', true);
evidence.captures.push(await capture('closed'));
// A capped note is a real scroll region; prove its hidden tail moves under a
// wheel rather than being unreachable clipped text.
if (noteScroll.scrollable) {
const noteScrollTop = () => evaluate(`(() => {
const matches = [...document.querySelectorAll('flt-semantics')]
.filter(x => ((x.getAttribute('aria-label') || x.innerText || '').trim()
.startsWith('Scroll or pinch to zoom')));
matches.sort((a, b) =>
a.getBoundingClientRect().height - b.getBoundingClientRect().height);
let element = matches[0];
while (element && element.tagName === 'FLT-SEMANTICS') {
if (getComputedStyle(element).overflowY === 'scroll') return element.scrollTop;
element = element.parentElement;
}
return -1;
})()`);
await send('Input.dispatchMouseEvent', {
type: 'mouseWheel',
x: Math.round(note.x + note.width / 2),
y: Math.round(note.y + note.height / 2),
deltaX: 0,
deltaY: 120,
button: 'none',
}, session);
await delay(600);
const scrolled = await noteScrollTop();
if (!(scrolled > 0)) {
throw new Error(`Wheel did not scroll the capped note: ${JSON.stringify({ scrolled, note })}`);
}
evidence.noteScrolledPixels = scrolled;
check('wheel reaches the guidance note tail inside its scroll region', `${scrolled}px`);
evidence.captures.push(await capture('note-scrolled'));
}
// The two definition states the widget tests cover also render in the real
// page. They need the list on screen, so they run where list and detail sit
// side by side instead of behind one another.
if (width >= 1200 && height >= 900) {
// At a larger text scale the last rows start below the window; wheel the
// list itself until the row is fully on screen, then click its own box.
const clickListRow = async (name) => {
for (let attempt = 0; attempt < 8; attempt++) {
const item = (await semantics())
.filter((entry) => entry.label.startsWith(name) && entry.visible)
.sort((a, b) => a.width * a.height - b.width * b.height)[0];
if (item && item.y >= 0 && item.y + item.height <= height) {
await clickItem(item);
return;
}
await send('Input.dispatchMouseEvent', {
type: 'mouseWheel',
x: Math.round(width * 0.15),
y: Math.round(height * 0.5),
deltaX: 0,
deltaY: 240,
button: 'none',
}, session);
await delay(600);
}
throw new Error(`Missing list row ${JSON.stringify(name)}: ${JSON.stringify(await labels())}`);
};
const openGraph = async (name) => {
await clickListRow(name);
await clickExact('Graph');
};
const hasStageNode = async () =>
(await semantics()).some((item) => item.label === 'inspect' && item.visible);
await openGraph('Unparsed definition');
await waitForText('did not include the pipeline definition graph', 'missing graph state');
if (await hasStageNode()) {
throw new Error('A reply without a graph still drew a stage node');
}
check('a reply without a definition graph states it and draws nothing', true);
evidence.captures.push(await capture('missing-graph'));
await openGraph('Empty definition');
await waitForText('This pipeline has no stages.', 'empty definition state');
if (await hasStageNode()) {
throw new Error('An empty definition still drew a stage node');
}
check('an empty definition keeps its native empty message', true);
evidence.captures.push(await capture('empty-definition'));
}
console.log(JSON.stringify(evidence, null, 2));
} finally {
if (ws?.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ id: 2147483647, method: 'Browser.close' }));
}
await Promise.race([once(chrome, 'exit'), delay(3000)]);
ws?.close();
if (chrome.exitCode === null) chrome.kill('SIGTERM');
chrome.stderr.destroy();
chrome.unref();
await new Promise((resolveClose) => {
server.close(resolveClose);
server.closeAllConnections();
});
await rm(profile, { recursive: true, force: true });
}
+127
View File
@@ -54,6 +54,28 @@ class PipelinesProbeGateway implements ApiGateway {
'schedule_count': null,
'enabled_schedule_count': null,
},
{
'id': 21,
'name': 'Unparsed definition',
'version': 1,
'stages': 1,
'created_at': '2026-07-19T09:05:00',
'updated_at': '2026-09-30T14:00:00',
'scheduled': false,
'schedule_count': 0,
'enabled_schedule_count': 0,
},
{
'id': 22,
'name': 'Empty definition',
'version': 1,
'stages': 0,
'created_at': '2026-06-02T16:30:00',
'updated_at': '2026-08-22T10:20:00',
'scheduled': false,
'schedule_count': 0,
'enabled_schedule_count': 0,
},
];
static const _runs = <Map<String, dynamic>>[
@@ -107,6 +129,97 @@ class PipelinesProbeGateway implements ApiGateway {
14: [
{'version': 1, 'stages': 1, 'created_at': '2026-08-04T11:45:00'},
],
21: [
{'version': 1, 'stages': 1, 'created_at': '2026-07-19T09:05:00'},
],
22: [
{'version': 1, 'stages': 0, 'created_at': '2026-06-02T16:30:00'},
],
};
/// The pinned definition for each fixture pipeline, in the server's own
/// `graph` shape. Only the definitions are here: no run evidence is present.
static const _graphs = <int, Map<String, dynamic>>{
3: {
'name': 'Release verification',
'stages': [
{
'key': 'inspect',
'type': 'model',
'prompt': 'Inspect the candidate release.',
'output': 'report',
'edges': {'pass': 'verify', 'fail': '#failure'},
},
{
'key': 'verify',
'type': 'model',
'prompt': 'Verify the report against the checklist.',
'output': 'verdict',
'edges': {'pass': 'package', 'fail': '#failure'},
},
{
'key': 'package',
'type': 'human',
'prompt': 'Approve the package.',
'output': 'approval',
'edges': {'approve': 'publish', 'hold': '#success'},
},
{
'key': 'publish',
'type': 'model',
'prompt': 'Publish the release.',
'output': 'release',
'edges': {'done': '#success'},
},
],
},
7: {
'name': 'Nightly documentation',
'stages': [
{
'key': 'collect',
'type': 'model',
'edges': {'done': 'write'},
},
{
'key': 'write',
'type': 'model',
'edges': {'done': '#success'},
},
],
},
11: {
'name': 'Hotfix triage',
'stages': [
{
'key': 'classify',
'type': 'model',
'edges': {'urgent': 'patch', 'normal': 'document'},
},
{
'key': 'patch',
'type': 'model',
'edges': {'done': '#success'},
},
{
'key': 'document',
'type': 'human',
'edges': {'done': '#success'},
},
],
},
14: {
'name': 'Legacy import',
'stages': [
{
'key': 'import',
'type': 'model',
'edges': {'done': '#success'},
},
],
},
// 21 intentionally has no entry: the reply carries no definition graph.
22: {'name': 'Empty definition', 'stages': <dynamic>[]},
};
static const _sources = <int, String>{
@@ -179,6 +292,19 @@ stages:
output: summary
edges:
done: '#success'
''',
21: '''
name: Unparsed definition
stages:
import:
type: model
output: summary
edges:
done: '#success'
''',
22: '''
name: Empty definition
stages: {}
''',
};
@@ -223,6 +349,7 @@ stages:
'version_created_at': _versionCreatedAt(versions, resolved),
'content_hash': 'sha256:fixture-$id-v$resolved',
'source': '${_sources[id]}\n# selected version $resolved\n',
'graph': _graphs[id],
'versions': versions,
},
};