From bf378c94ca7e4e7bb7837e003b95fdd08616c960 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 21:06:57 +0100 Subject: [PATCH] feat(app): finish measured native graph canvas and clear labels from wires --- .../graph/routing/edge_label_placement.dart | 31 ++- .../graph/routing/graph_edge_routing.dart | 1 + .../graph/widgets/definition_graph_view.dart | 231 ++++++++++++++++ .../graph/widgets/graph_canvas_style.dart | 86 ++++++ .../graph/widgets/graph_measurements.dart | 64 +++++ .../graph/widgets/measured_child.dart | 47 ++++ app/notes/P2-canvas.md | 39 +++ .../graph/routing/graph_label_wire_test.dart | 46 ++++ .../widgets/definition_graph_view_test.dart | 258 ++++++++++++++++++ app/tool/graph_canvas_probe.dart | 120 ++++++++ app/tool/graph_canvas_probe.mjs | 202 ++++++++++++++ 11 files changed, 1123 insertions(+), 2 deletions(-) create mode 100644 app/lib/features/graph/widgets/definition_graph_view.dart create mode 100644 app/lib/features/graph/widgets/graph_canvas_style.dart create mode 100644 app/lib/features/graph/widgets/graph_measurements.dart create mode 100644 app/lib/features/graph/widgets/measured_child.dart create mode 100644 app/notes/P2-canvas.md create mode 100644 app/test/features/graph/routing/graph_label_wire_test.dart create mode 100644 app/test/features/graph/widgets/definition_graph_view_test.dart create mode 100644 app/tool/graph_canvas_probe.dart create mode 100644 app/tool/graph_canvas_probe.mjs diff --git a/app/lib/features/graph/routing/edge_label_placement.dart b/app/lib/features/graph/routing/edge_label_placement.dart index 75264135..e04d5524 100644 --- a/app/lib/features/graph/routing/edge_label_placement.dart +++ b/app/lib/features/graph/routing/edge_label_placement.dart @@ -16,6 +16,7 @@ EdgeLabelBox placeEdgeLabel({ required LabelExtent extent, required List nodes, required List placed, + required List routes, required RoutingConfig config, required double floorY, }) { @@ -29,7 +30,7 @@ EdgeLabelBox placeEdgeLabel({ width: width, height: height, ); - if (_fits(box, nodes, placed, config)) return box; + if (_fits(box, nodes, placed, routes, config)) return box; } // The fallback shelf is below every route and every existing label, so it @@ -50,7 +51,7 @@ EdgeLabelBox placeEdgeLabel({ width: width, height: height, ); - if (_fits(box, nodes, placed, config)) return box; + if (_fits(box, nodes, placed, routes, config)) return box; top += step; } // A zero-sized label cannot collide; this is unreachable for real extents. @@ -67,9 +68,35 @@ bool _fits( EdgeLabelBox box, List nodes, List placed, + List routes, RoutingConfig config, ) { if (box.x < 0 || box.y < 0) return false; + // A label clear of nodes can still sit across its self-loop's vertical leg + // or another edge. Keep its measured text rectangle clear of every wire. + final left = box.x - config.labelGap; + final right = box.right + config.labelGap; + final top = box.y - config.labelGap; + final bottom = box.bottom + config.labelGap; + for (final route in routes) { + for (var index = 1; index < route.points.length; index++) { + final a = route.points[index - 1], b = route.points[index]; + if (a.x == b.x && + a.x > left && + a.x < right && + math.max(a.y, b.y) > top && + math.min(a.y, b.y) < bottom) { + return false; + } + if (a.y == b.y && + a.y > top && + a.y < bottom && + math.max(a.x, b.x) > left && + math.min(a.x, b.x) < right) { + return false; + } + } + } for (final node in nodes) { if (boxIntersectsNode( x: box.x, diff --git a/app/lib/features/graph/routing/graph_edge_routing.dart b/app/lib/features/graph/routing/graph_edge_routing.dart index 33ad9a9a..b43fa126 100644 --- a/app/lib/features/graph/routing/graph_edge_routing.dart +++ b/app/lib/features/graph/routing/graph_edge_routing.dart @@ -106,6 +106,7 @@ GraphRouting routeGraphEdges({ extent: labelExtents[routes[index].id]!, nodes: layout.nodes, placed: labels, + routes: routes, config: config, floorY: floorY, ), diff --git a/app/lib/features/graph/widgets/definition_graph_view.dart b/app/lib/features/graph/widgets/definition_graph_view.dart new file mode 100644 index 00000000..6c96e208 --- /dev/null +++ b/app/lib/features/graph/widgets/definition_graph_view.dart @@ -0,0 +1,231 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../domain/graph_definition.dart'; +import '../layout/graph_node_layout.dart'; +import '../layout/layout_models.dart'; +import '../painting/graph_edge_layer.dart'; +import '../routing/graph_edge_routing.dart'; +import '../routing/route_models.dart'; +import 'graph_canvas_style.dart'; +import 'graph_stage_node.dart'; +import 'graph_measurements.dart'; + +/// The definition's own empty-state wording (web `PIPELINE_GRAPH_EMPTY`). +const String definitionGraphEmpty = 'This pipeline has no stages.'; + +/// One pipeline definition as a readable native graph: measured stage nodes, +/// routed passive edges behind them and native outcome labels on their boxes. +/// +/// [selectedStage] is a node key (including `#success`/`#failure`) and +/// [onSelected] reports the exact key activated. Nothing reads run evidence: +/// nodes show no status and terminals stay plain, so no visit is implied. The +/// view fills bounded caller constraints with a stock [InteractiveViewer]. +class DefinitionGraphView extends StatefulWidget { + const DefinitionGraphView({ + super.key, + required this.graph, + required this.onSelected, + this.selectedStage, + }); + + final JsonMap graph; + final String? selectedStage; + final ValueChanged onSelected; + + @override + State createState() => _DefinitionGraphViewState(); +} + +class _DefinitionGraphViewState extends State { + final Map _nodeSizes = {}; + final Map _labelSizes = {}; + TextScaler? _scaler; + bool _rebuildScheduled = false; + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + // A different text scale changes every measured extent; drop the old + // extents so a stale 1x layout is never rendered around 2x text. + final scaler = MediaQuery.textScalerOf(context); + if (scaler != _scaler) { + _scaler = scaler; + _nodeSizes.clear(); + _labelSizes.clear(); + } + } + + /// Records one measured extent and schedules the frame that uses it. + void _record(Map sizes, String key, Size size) { + if (sizes[key] == size) return; + sizes[key] = size; + if (_rebuildScheduled) return; + _rebuildScheduled = true; + WidgetsBinding.instance.addPostFrameCallback((_) { + _rebuildScheduled = false; + if (mounted) setState(() {}); + }); + } + + /// The landed layout and routing for the measured extents, or null until + /// every node and every edge label has a real measurement. + (GraphLayout, GraphRouting)? _geometry( + List nodes, + List edges, + ) { + final extents = {}; + for (final node in nodes) { + final size = _nodeSizes[node.key]; + if (size == null) return null; + extents[node.key] = NodeExtent(width: size.width, height: size.height); + } + final labelExtents = {}; + for (final edge in edges) { + final size = _labelSizes[edge.label]; + if (size == null) return null; + labelExtents[edge.id] = LabelExtent( + width: size.width, + height: size.height, + ); + } + final layout = layoutGraphNodes( + nodes: nodes, + edges: edges, + extents: extents, + config: graphCanvasLayoutConfig(labelExtents.values), + ); + final routing = routeGraphEdges( + layout: layout, + edges: edges, + labelExtents: labelExtents, + config: graphCanvasRoutingConfig(), + ); + return (layout, routing); + } + + @override + Widget build(BuildContext context) { + final nodes = graphNodes(widget.graph); + final edges = graphEdges(widget.graph); + final style = GraphCanvasStyle.of(context); + return LayoutBuilder( + builder: (context, constraints) { + assert( + constraints.hasBoundedWidth && constraints.hasBoundedHeight, + 'DefinitionGraphView needs a bounded viewport; constrain it, for ' + 'example with a SizedBox or an Expanded slot.', + ); + final geometry = nodes.isEmpty ? null : _geometry(nodes, edges); + return Stack( + fit: StackFit.expand, + children: [ + if (nodes.isEmpty) + _message(definitionGraphEmpty, style) + else if (geometry != null) + _canvas(nodes, geometry.$1, geometry.$2, style) + else + const SizedBox.shrink(), + if (nodes.isNotEmpty) + GraphMeasurements( + nodes: nodes, + edges: edges, + maxNodeWidth: constraints.maxWidth, + labelStyle: style.labelStyle, + selectedStage: widget.selectedStage, + onNodeSize: (key, size) => _record(_nodeSizes, key, size), + onLabelSize: (key, size) => _record(_labelSizes, key, size), + ), + ], + ); + }, + ); + } + + Widget _message(String message, GraphCanvasStyle style) { + return Padding( + padding: const EdgeInsets.all(24), + child: Align( + alignment: AlignmentDirectional.topStart, + child: Text(message, style: style.messageStyle), + ), + ); + } + + Widget _canvas( + List nodes, + GraphLayout layout, + GraphRouting routing, + GraphCanvasStyle style, + ) { + final nodesByKey = { + for (final node in nodes) node.key: node, + }; + final size = Size(routing.width, routing.height); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded( + child: InteractiveViewer( + constrained: false, + minScale: 0.3, + maxScale: 3, + child: SizedBox.fromSize( + size: size, + child: Stack( + clipBehavior: Clip.none, + children: [ + // The passive layer comes first so every edge paints behind + // the native nodes and labels without taking their input. + Positioned.fill( + child: GraphEdgeLayer( + routes: routing.routes, + canvasSize: size, + color: style.edgeColor, + strokeWidth: style.edgeWidth, + ), + ), + for (final box in layout.nodes) + Positioned( + left: box.x, + top: box.y, + width: box.width, + height: box.height, + child: GraphStageNode( + node: nodesByKey[box.key]!, + selected: box.key == widget.selectedStage, + onSelected: widget.onSelected, + ), + ), + for (final label in routing.labels) + Positioned( + left: label.x, + top: label.y, + child: Text( + routing.routeFor(label.edgeId)!.label, + style: style.labelStyle, + ), + ), + ], + ), + ), + ), + ), + if (routing.skipped.isNotEmpty) + Flexible( + child: SingleChildScrollView( + child: _message( + [ + for (final diagnostic in routing.skipped) + '${diagnostic.source} → ${diagnostic.outcome}: ' + '${diagnostic.message}', + ].join('\n'), + style, + ), + ), + ), + ], + ); + } +} diff --git a/app/lib/features/graph/widgets/graph_canvas_style.dart b/app/lib/features/graph/widgets/graph_canvas_style.dart new file mode 100644 index 00000000..b4c97ef6 --- /dev/null +++ b/app/lib/features/graph/widgets/graph_canvas_style.dart @@ -0,0 +1,86 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; +import '../layout/layout_models.dart'; +import '../routing/route_models.dart'; + +/// Centralized graph spacing, not component dimensions. Rank separation follows +/// actual native label measurements at any text scale. +GraphLayoutConfig graphCanvasLayoutConfig(Iterable labels) { + final widest = labels.fold( + 0, + (width, label) => label.width > width ? label.width : width, + ); + final routing = graphCanvasRoutingConfig(); + return GraphLayoutConfig( + columnGap: widest + 2 * (routing.nodeClearance + routing.labelGap) + 24, + rowGap: 24, + padding: 24, + ); +} + +RoutingConfig graphCanvasRoutingConfig() => RoutingConfig( + nodeClearance: 12, + laneSpacing: 28, + corridorSpacing: 20, + portSpacing: 12, + labelGap: 6, + boundsPadding: 12, +); + +/// The native theme roles one definition graph canvas needs. +/// +/// No palette, font family or size is defined here: every value comes from the +/// ambient Material or Cupertino theme, so light/dark and text scaling follow +/// the host exactly. Edge labels and diagnostics are metadata, so they use the +/// host's secondary-label role rather than the node's own label style. +class GraphCanvasStyle { + const GraphCanvasStyle({ + required this.labelStyle, + required this.messageStyle, + required this.edgeColor, + required this.edgeWidth, + }); + + factory GraphCanvasStyle.of(BuildContext context) { + if (usesCupertinoHost(context)) { + final theme = CupertinoTheme.of(context); + final secondary = CupertinoColors.secondaryLabel.resolveFrom(context); + return GraphCanvasStyle( + labelStyle: theme.textTheme.tabLabelTextStyle.copyWith( + color: secondary, + ), + messageStyle: theme.textTheme.textStyle.copyWith(color: secondary), + edgeColor: CupertinoColors.separator.resolveFrom(context), + // Cupertino has no divider-thickness token; its separators are one + // logical pixel hairlines, so the stroke keeps that native default. + edgeWidth: 1, + ); + } + final theme = Theme.of(context); + final secondary = theme.colorScheme.onSurfaceVariant; + return GraphCanvasStyle( + labelStyle: (theme.textTheme.labelMedium ?? const TextStyle()).copyWith( + color: secondary, + ), + messageStyle: (theme.textTheme.bodySmall ?? const TextStyle()).copyWith( + color: secondary, + ), + edgeColor: theme.colorScheme.outline, + edgeWidth: theme.dividerTheme.thickness ?? 1, + ); + } + + /// Style of one routed outcome label. + final TextStyle labelStyle; + + /// Style of the empty-state and skipped-edge messages. + final TextStyle messageStyle; + + /// Native outline/separator color for the routed edges. + final Color edgeColor; + + /// Native hairline thickness for the routed edges and their arrows. + final double edgeWidth; +} diff --git a/app/lib/features/graph/widgets/graph_measurements.dart b/app/lib/features/graph/widgets/graph_measurements.dart new file mode 100644 index 00000000..ae0b4582 --- /dev/null +++ b/app/lib/features/graph/widgets/graph_measurements.dart @@ -0,0 +1,64 @@ +import 'package:flutter/widgets.dart'; + +import '../domain/graph_definition.dart'; +import 'graph_stage_node.dart'; +import 'measured_child.dart'; + +/// Measures the same native controls that the graph places, at a bound derived +/// from its actual viewport rather than a fixed node dimension. +class GraphMeasurements extends StatelessWidget { + const GraphMeasurements({ + super.key, + required this.nodes, + required this.edges, + required this.maxNodeWidth, + required this.labelStyle, + required this.onNodeSize, + required this.onLabelSize, + this.selectedStage, + }); + + final List nodes; + final List edges; + final double maxNodeWidth; + final TextStyle labelStyle; + final String? selectedStage; + final void Function(String, Size) onNodeSize; + final void Function(String, Size) onLabelSize; + + @override + Widget build(BuildContext context) => Offstage( + child: OverflowBox( + alignment: Alignment.topLeft, + minWidth: 0, + maxWidth: double.infinity, + minHeight: 0, + maxHeight: double.infinity, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (final node in nodes) + MeasuredChild( + key: ValueKey('node:${node.key}'), + onSize: (size) => onNodeSize(node.key, size), + child: ConstrainedBox( + constraints: BoxConstraints(maxWidth: maxNodeWidth), + child: GraphStageNode( + node: node, + selected: node.key == selectedStage, + onSelected: (_) {}, + ), + ), + ), + for (final edge in edges) + MeasuredChild( + key: ValueKey('label:${edge.id}'), + onSize: (size) => onLabelSize(edge.label, size), + child: Text(edge.label, style: labelStyle), + ), + ], + ), + ), + ); +} diff --git a/app/lib/features/graph/widgets/measured_child.dart b/app/lib/features/graph/widgets/measured_child.dart new file mode 100644 index 00000000..03f8c1ce --- /dev/null +++ b/app/lib/features/graph/widgets/measured_child.dart @@ -0,0 +1,47 @@ +import 'package:flutter/rendering.dart'; +import 'package:flutter/widgets.dart'; + +/// Reports the laid-out size of its real child. +/// +/// The definition graph measures the very node and label widgets it renders +/// instead of assuming a height, so a wrapped key, a larger text scale or a +/// platform host all produce the honest extent. The child is laid out with the +/// constraints its caller gives, and [onSize] runs during layout. +/// +/// Because it runs inside layout, a caller must not rebuild synchronously: +/// record the size and schedule the rebuild for after the frame. The size is +/// reported again only when it actually changes, so a caller that keeps its +/// reported sizes stable does not loop. +class MeasuredChild extends SingleChildRenderObjectWidget { + const MeasuredChild({super.key, required this.onSize, required super.child}); + + /// Receives the child's size, in logical pixels, after every size change. + final ValueChanged onSize; + + @override + MeasuredBox createRenderObject(BuildContext context) => + MeasuredBox(onSize: onSize); + + @override + void updateRenderObject(BuildContext context, MeasuredBox renderObject) { + renderObject.onSize = onSize; + } +} + +/// The proxy render object behind [MeasuredChild]. +class MeasuredBox extends RenderProxyBox { + MeasuredBox({required this.onSize}); + + ValueChanged onSize; + + Size? _reported; + + @override + void performLayout() { + super.performLayout(); + final measured = size; + if (measured == _reported) return; + _reported = measured; + onSize(measured); + } +} diff --git a/app/notes/P2-canvas.md b/app/notes/P2-canvas.md new file mode 100644 index 00000000..b9582413 --- /dev/null +++ b/app/notes/P2-canvas.md @@ -0,0 +1,39 @@ +# Measured native definition graph canvas + +Retained run71 hit its Code deadline while collecting browser evidence. Manager +completed the existing work directly; no replacement workflow or lost edits. + +DefinitionGraphView composes the landed native node, layout, route and passive +edge components. Nodes/labels are measured from their rendered native widgets, +then placed in a stock InteractiveViewer. Selection reports the exact stage or +terminal key; no run status, visit or session is invented. Unknown targets produce +bounded scrollable diagnostics. No node height/width is assumed. + +## Corrections from actual checks + +- Removed the fixed220px node bound: wrapping follows the caller's viewport. +- Rank gaps follow measured outcome labels, not an assumed2x text width. +- Split offstage native measurement into its own cohesive widget; source files + remain below250lines rather than making an oversized renderer. +- Two original selection tests tapped offscreen terminals. They now pan the real + InteractiveViewer first; a new resize test checks viewport-dependent remeasure. +- Browser inspection found the retry label crossed its own loop wire. Added + three failing pure regressions, then fixed label candidate collision checks to + include ALL route segments. No masking background or routing rewrite. +- Browser fixture now pans to reveal offscreen nodes, instead of assuming the + whole content-sized graph fits one screen. Selected terminal identity and real + pan movement are asserted. Explicit owned Chrome pipe/server cleanup prevents + successful probes leaving the Node process waiting on fixture resources. + +## Verification + +Graph tests (composition + existing geometry) pass; analyzer clean. Fresh real +Chrome cases cover Material light1x/2x, Cupertino light1x/dark2x, five captures +each (desktop/phone/selection/terminal/pan), under approved temp/ +graph-canvas-manager-browser. Each case's probe assertions passed; the cleanup +fix was checked with clean process exit. Material2x label/wire view inspected. +Fixtures bind loopback and touch no production server, session or device. + +This is a definition-only component, NOT run-graph parity. Pipeline hook, authored +stage pane, run evidence/recorded-visit integration and keyboard/fit toolbar are +still separate acceptance work. Mobile remains unverified. diff --git a/app/test/features/graph/routing/graph_label_wire_test.dart b/app/test/features/graph/routing/graph_label_wire_test.dart new file mode 100644 index 00000000..3946cada --- /dev/null +++ b/app/test/features/graph/routing/graph_label_wire_test.dart @@ -0,0 +1,46 @@ +import 'dart:math' as math; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/graph/domain/graph_definition.dart'; + +import '../domain/graph_fixtures.dart'; +import 'routing_fixtures.dart'; + +void main() { + for (final width in [52.0, 100.0, 160.0]) { + test( + 'measured self-loop labels do not sit across route wires ($width)', + () { + final graph = selfLoopGraph(); + final result = routeFor( + graph, + labels: fixedLabels(graphEdges(graph), width: width, height: 32), + ); + for (final label in result.labels) { + for (final route in result.routes) { + for (var i = 1; i < route.points.length; i++) { + final a = route.points[i - 1], b = route.points[i]; + final vertical = + a.x == b.x && + a.x > label.x && + a.x < label.right && + math.max(a.y, b.y) > label.y && + math.min(a.y, b.y) < label.bottom; + final horizontal = + a.y == b.y && + a.y > label.y && + a.y < label.bottom && + math.max(a.x, b.x) > label.x && + math.min(a.x, b.x) < label.right; + expect( + vertical || horizontal, + isFalse, + reason: 'edge ${route.id} crosses label ${label.edgeId}', + ); + } + } + } + }, + ); + } +} diff --git a/app/test/features/graph/widgets/definition_graph_view_test.dart b/app/test/features/graph/widgets/definition_graph_view_test.dart new file mode 100644 index 00000000..ed448257 --- /dev/null +++ b/app/test/features/graph/widgets/definition_graph_view_test.dart @@ -0,0 +1,258 @@ +import 'package:flutter/cupertino.dart'; +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/graph/painting/graph_edge_layer.dart'; +import 'package:pipelines_app/features/graph/widgets/definition_graph_view.dart'; +import 'package:pipelines_app/features/graph/widgets/graph_stage_node.dart'; + +import '../domain/graph_fixtures.dart'; + +const String _longKey = 'implementer-with-an-unusually-long-stage-label'; + +JsonMap _longKeyGraph() => { + 'stages': [ + stage( + 'plan', + edges: {'success': _longKey, 'error': '#'}, + fallbackError: true, + ), + stage( + _longKey, + edges: {'success': '#success', 'error': '#failure'}, + ), + ], +}; + +JsonMap _emptyGraph() => {'stages': []}; + +/// One bounded viewport, with an optional real text scale applied below the +/// app so the graph measures text exactly as a device would. +Widget _materialHost( + JsonMap graph, { + String? selected, + ValueChanged? onSelected, + double scale = 1, +}) { + return MaterialApp( + home: Scaffold( + body: Builder( + builder: (context) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(scale)), + child: SizedBox( + width: 900, + height: 700, + child: DefinitionGraphView( + graph: graph, + selectedStage: selected, + onSelected: onSelected ?? (_) {}, + ), + ), + ), + ), + ), + ); +} + +Widget _cupertinoHost(JsonMap graph, {ValueChanged? onSelected}) { + return CupertinoApp( + home: CupertinoPageScaffold( + child: SizedBox( + width: 900, + height: 700, + child: DefinitionGraphView( + graph: graph, + onSelected: onSelected ?? (_) {}, + ), + ), + ), + ); +} + +/// Settles the two-frame measure-then-place contract. +Future _settle(WidgetTester tester) async { + await tester.pump(); + await tester.pump(); +} + +Finder _node(String key) => find.byWidgetPredicate( + (widget) => widget is GraphStageNode && widget.node.key == key, +); + +Rect _nodeRect(WidgetTester tester, String key) => tester.getRect(_node(key)); + +Future _tapNode(WidgetTester tester, String key) async { + final viewport = tester.getRect(find.byType(InteractiveViewer)); + final node = _nodeRect(tester, 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(); +} + +void _expectNoOverlaps(WidgetTester tester) { + final rects = [ + for (final element in find.byType(GraphStageNode).evaluate()) + tester.getRect(find.byWidget(element.widget)), + ]; + for (var a = 0; a < rects.length; a += 1) { + for (var b = a + 1; b < rects.length; b += 1) { + expect( + rects[a].overlaps(rects[b]), + isFalse, + reason: 'nodes $a and $b overlap: ${rects[a]} and ${rects[b]}', + ); + } + } +} + +void main() { + testWidgets( + 'viewport changes remeasure node width instead of imposing a fixed cap', + (tester) async { + tester.view.physicalSize = const Size(900, 700); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget(_materialHost(_longKeyGraph())); + await _settle(tester); + final wide = _nodeRect(tester, _longKey); + tester.view.physicalSize = const Size(320, 700); + await tester.pump(); + await _settle(tester); + final narrow = _nodeRect(tester, _longKey); + expect(narrow.width, lessThan(wide.width)); + expect(narrow.width, lessThanOrEqualTo(320)); + expect(narrow.height, greaterThan(wide.height)); + _expectNoOverlaps(tester); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets('selection reports the exact definition key', (tester) async { + final picked = []; + await tester.pumpWidget( + _materialHost(linearGraph(), selected: 'build', onSelected: picked.add), + ); + await _settle(tester); + + expect(find.byType(GraphStageNode), findsNWidgets(5)); + expect(find.byType(InteractiveViewer), findsOneWidget); + expect(tester.widget(_node('build')).selected, isTrue); + expect(tester.widget(_node('plan')).selected, isFalse); + + await tester.tap(_node('plan')); + await tester.pump(); + expect(picked, ['plan']); + + await _tapNode(tester, '#success'); + expect(picked, ['plan', '#success']); + }); + + testWidgets('nodes use measured native sizes and never overlap', ( + tester, + ) async { + tester.view.physicalSize = const Size(320, 700); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget(_materialHost(_longKeyGraph())); + await _settle(tester); + + expect(find.byType(GraphStageNode), findsNWidgets(4)); + _expectNoOverlaps(tester); + + final plan = _nodeRect(tester, 'plan'); + final long = _nodeRect(tester, _longKey); + // The wrapped key is bounded by the graph's measurement bound and is both + // wider and taller than the single-line node: a fixed node size could not + // produce either difference. + expect(long.width, lessThanOrEqualTo(320)); + expect(long.width, greaterThan(plan.width)); + expect(long.height, greaterThan(plan.height * 1.5)); + + final layer = tester.widget(find.byType(GraphEdgeLayer)); + expect(layer.routes, isNotEmpty); + expect(layer.canvasSize.width, greaterThan(0)); + // Every routed edge gets its native outcome label; `error*` is the + // fallback marker carried verbatim from the definition. + expect(find.text('error*'), findsOneWidget); + expect(find.text('success'), findsNWidgets(2)); + expect(find.textContaining('no placed node'), findsNothing); + expect(tester.takeException(), isNull); + }); + + testWidgets('2x text scale re-measures instead of reusing 1x extents', ( + tester, + ) async { + final graph = linearGraph(); + await tester.pumpWidget(_materialHost(graph)); + await _settle(tester); + final oneX = _nodeRect(tester, 'plan'); + final oneXLabel = tester.getRect(find.text('error*')); + + await tester.pumpWidget(_materialHost(graph, scale: 2)); + await _settle(tester); + + final twoX = _nodeRect(tester, 'plan'); + expect(twoX.height, greaterThan(oneX.height)); + expect(twoX.width, greaterThan(oneX.width)); + expect( + tester.getRect(find.text('error*')).height, + greaterThan(oneXLabel.height), + ); + _expectNoOverlaps(tester); + }); + + testWidgets('unknown endpoints stay honest and invent no node', ( + tester, + ) async { + await tester.pumpWidget(_materialHost(incompleteGraph())); + await _settle(tester); + + expect(find.byType(GraphStageNode), findsNWidgets(4)); + expect(_node('ghost'), findsNothing); + // Two routes are drawn; the empty and unknown targets are reported, not + // guessed into nodes. + expect( + tester.widget(find.byType(GraphEdgeLayer)).routes, + hasLength(2), + ); + expect(find.textContaining('ghost'), findsOneWidget); + expect(find.textContaining('edge target is empty'), findsOneWidget); + _expectNoOverlaps(tester); + expect(tester.takeException(), isNull); + }); + + testWidgets('an empty definition states its empty message', (tester) async { + await tester.pumpWidget(_materialHost(_emptyGraph())); + await tester.pump(); + + expect(find.text(definitionGraphEmpty), findsOneWidget); + expect(find.byType(GraphStageNode), findsNothing); + expect(find.byType(InteractiveViewer), findsNothing); + }); + + testWidgets('cupertino host composes native buttons and keeps identity', ( + tester, + ) async { + final picked = []; + await tester.pumpWidget( + _cupertinoHost(linearGraph(), onSelected: picked.add), + ); + await _settle(tester); + + expect(find.byType(CupertinoButton), findsNWidgets(5)); + expect(find.byType(Card), findsNothing); + _expectNoOverlaps(tester); + + await _tapNode(tester, '#failure'); + expect(picked, ['#failure']); + }); +} diff --git a/app/tool/graph_canvas_probe.dart b/app/tool/graph_canvas_probe.dart new file mode 100644 index 00000000..19a6a4cd --- /dev/null +++ b/app/tool/graph_canvas_probe.dart @@ -0,0 +1,120 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/graph/widgets/definition_graph_view.dart'; + +const String _longKey = 'implementer-with-an-unusually-long-stage-label'; + +/// A definition with forward, fallback, self-loop and terminal edges so one +/// canvas shows measured wrapping nodes, native outcome labels and arrows. +JsonMap _definition() => { + 'stages': [ + { + 'key': 'plan', + 'type': 'model', + 'edges': {'success': 'build', 'error': '#'}, + 'fallback_error': true, + }, + { + 'key': 'build', + 'type': 'model', + 'edges': {'success': _longKey, 'retry': 'build'}, + }, + { + 'key': _longKey, + 'type': 'model', + 'edges': {'success': 'audit', 'blocked': '#failure'}, + }, + { + 'key': 'audit', + 'type': 'model', + 'edges': {'success': '#success', 'error': '#failure'}, + }, + ], +}; + +/// Isolated browser fixture for `DefinitionGraphView` only. +/// +/// Not wired into the app or shell. `style=cupertino` selects the native +/// Cupertino host, `scale=2` applies a real 2x text scale to the graph viewport, +/// and a click reports the exact stage key in the status line. +void main() { + final parameters = Uri.base.queryParameters; + final cupertino = parameters['style'] == 'cupertino'; + final scale = double.tryParse(parameters['scale'] ?? '') ?? 1; + runApp(_ProbeApp(cupertino: cupertino, scale: scale)); +} + +class _ProbeApp extends StatelessWidget { + const _ProbeApp({required this.cupertino, required this.scale}); + + final bool cupertino; + final double scale; + + @override + Widget build(BuildContext context) { + final page = _ProbePage(scale: scale); + if (cupertino) { + return CupertinoApp( + home: CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar( + middle: Text('Definition graph'), + ), + child: SafeArea(child: page), + ), + ); + } + return MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + darkTheme: ThemeData( + platform: TargetPlatform.android, + brightness: Brightness.dark, + ), + themeMode: ThemeMode.system, + home: Scaffold( + appBar: AppBar(title: const Text('Definition graph')), + body: SafeArea(child: page), + ), + ); + } +} + +class _ProbePage extends StatefulWidget { + const _ProbePage({required this.scale}); + + final double scale; + + @override + State<_ProbePage> createState() => _ProbePageState(); +} + +class _ProbePageState extends State<_ProbePage> { + String? _selected = 'build'; + + @override + Widget build(BuildContext context) { + return Padding( + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text('Selected: ${_selected ?? 'none'}'), + const SizedBox(height: 8), + Expanded( + child: MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(widget.scale)), + child: DefinitionGraphView( + graph: _definition(), + selectedStage: _selected, + onSelected: (key) => setState(() => _selected = key), + ), + ), + ), + ], + ), + ); + } +} diff --git a/app/tool/graph_canvas_probe.mjs b/app/tool/graph_canvas_probe.mjs new file mode 100644 index 00000000..e23137ed --- /dev/null +++ b/app/tool/graph_canvas_probe.mjs @@ -0,0 +1,202 @@ +// Browser acceptance for the isolated DefinitionGraphView fixture. +// +// Serves the probe build (`flutter build web -t tool/graph_canvas_probe.dart`) +// on an OS-assigned loopback port, drives a real headless Chrome, asserts the +// native node/label semantics, selection identity, measured node rectangles and +// that a real drag pans the stock InteractiveViewer, then writes captures. +// +// PROBE_VARIANT=material|cupertino PROBE_SCHEME=dark|light PROBE_SCALE=1|2 \ +// PROBE_WEB_ROOT= OPENCODE_ARTIFACT_DIR= \ +// node tool/graph_canvas_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/graph_canvas_probe')); +const variant = process.env.PROBE_VARIANT ?? 'material'; +const scheme = process.env.PROBE_SCHEME ?? 'dark'; +const scale = process.env.PROBE_SCALE ?? '1'; +const artifactDir = process.env.OPENCODE_ARTIFACT_DIR ?? join(tmpdir(), 'graph-canvas-capture'); +const prefix = scheme === 'light' ? 'light-' : ''; +const longKey = 'implementer-with-an-unusually-long-stage-label'; +const nodes = ['plan', 'build', longKey, 'audit', 'Success', 'Failure']; +const edgeLabels = ['success', 'error*', 'retry', 'blocked']; +await mkdir(artifactDir, { recursive: true }); +const mime = { '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.wasm': 'application/wasm', '.png': 'image/png', '.ico': 'image/x-icon' }; +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(), 'graph-canvas-chrome-')); +const chrome = spawn('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', [ + '--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 < 100; 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 msg = JSON.parse(event.data); + if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); } + }); + const send = (method, params = {}, sessionId) => new Promise(resolve => { + const callId = ++id; pending.set(callId, resolve); + 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); + const url = `http://127.0.0.1:${port}/?style=${variant}&scale=${scale}`; + const navigation = await send('Page.navigate', { url }, session); + if (navigation.error || navigation.result?.errorText) throw new Error(JSON.stringify(navigation)); + await send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 800, deviceScaleFactor: 1, mobile: false }, session); + const evaluate = async expression => { + const response = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, session); + if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`); + return response.result?.result?.value; + }; + await delay(3500); + const loaded = await evaluate('({url:location.href, ready:document.readyState})'); + if (!loaded?.url.includes(`127.0.0.1:${port}/?style=${variant}&scale=${scale}`)) throw new Error(`Fixture did not load: ${JSON.stringify(loaded)}`); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(2500); + const semantics = () => evaluate("[...document.querySelectorAll('flt-semantics')].map(x=>({label:(x.getAttribute('aria-label')||x.innerText||'').trim(), selected:x.getAttribute('aria-current')}))"); + const nodeAt = label => `[...document.querySelectorAll('flt-semantics')].find(x => (x.getAttribute('aria-label')||x.innerText||'').trim() === ${JSON.stringify(label)})`; + const body = await evaluate('document.body.innerText'); + if (!body.includes('Selected: build')) throw new Error(`Initial selection missing: ${body}`); + const initial = await semantics(); + // Flutter web maps Semantics(selected:) to aria-current, not aria-selected. + const current = initial.find(x => x.selected === 'true'); + if (!current?.label.startsWith('build')) throw new Error(`Selected node is not announced: ${JSON.stringify(initial)}`); + const nodeRect = async label => evaluate(`(() => { const e=${nodeAt(label)}; if (!e) return null; const r=e.getBoundingClientRect(); return {x:r.x,y:r.y,width:r.width,height:r.height}; })()`); + const rects = {}; + for (const label of nodes) { + const rect = await nodeRect(label); + if (rect?.width > 0 && rect?.height > 0) rects[label] = rect; + } + // Measured native nodes occupy separate rectangles: no fixed-size overlap. + const visibleNodes = Object.keys(rects); + for (let a = 0; a < visibleNodes.length; a++) { + for (let b = a + 1; b < visibleNodes.length; b++) { + const one = rects[visibleNodes[a]], two = rects[visibleNodes[b]]; + const overlap = one.x < two.x + two.width && two.x < one.x + one.width && + one.y < two.y + two.height && two.y < one.y + one.height; + if (overlap) throw new Error(`Nodes overlap: ${visibleNodes[a]} ${JSON.stringify(one)} vs ${visibleNodes[b]} ${JSON.stringify(two)}`); + } + } + if (!(rects[longKey].height > rects.plan.height || rects[longKey].width > rects.plan.width)) { + throw new Error(`Long key did not determine its own native extent: ${JSON.stringify(rects)}`); + } + const clickLabel = async label => { + const point = await evaluate(`(() => { const e=${nodeAt(label)}; if (!e) return null; const r=e.getBoundingClientRect(); return {x:r.x+r.width/2,y:r.y+r.height/2}; })()`); + if (!point) return false; + await send('Input.dispatchMouseEvent', { type: 'mousePressed', x: point.x, y: point.y, button: 'left', clickCount: 1 }, session); + await send('Input.dispatchMouseEvent', { type: 'mouseReleased', x: point.x, y: point.y, button: 'left', clickCount: 1 }, session); + return true; + }; + const capture = async (name, width, height) => { + await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 }, session); + await delay(2500); + const data = (await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session)).result.data; + const file = `${prefix}${variant}-graph-${scale}x-${name}.png`; + await writeFile(`${artifactDir}/${file}`, Buffer.from(data, 'base64')); + return file; + }; + const captures = []; + captures.push(await capture('desktop', 1280, 800)); + captures.push(await capture('phone', 390, 844)); + if (!await clickLabel('plan')) throw new Error('Could not click plan node'); + await delay(800); + const afterPlan = await evaluate('document.body.innerText'); + if (!afterPlan.includes('Selected: plan')) throw new Error(`plan callback did not carry its key: ${afterPlan}`); + const planCurrent = (await semantics()).find(x => x.selected === 'true'); + if (planCurrent?.label !== 'plan') throw new Error(`plan is not announced selected: ${JSON.stringify(planCurrent)}`); + captures.push(await capture('selected-plan', 1280, 800)); + const seen = new Set(); + const drag = async (start, dx, dy = 0) => { + await send('Input.dispatchMouseEvent', {type:'mousePressed', ...start, button:'left', buttons:1, clickCount:1}, session); + for (let step=1; step<=5; step++) { + await send('Input.dispatchMouseEvent', {type:'mouseMoved', x:start.x+dx*step/5, y:start.y+dy*step/5, button:'left', buttons:1}, session); + await delay(40); + } + await send('Input.dispatchMouseEvent', {type:'mouseReleased', x:start.x+dx, y:start.y+dy, button:'left', clickCount:1}, session); + await delay(800); + }; + // Native content-sized graphs need not fit on one screen. Verify offscreen + // nodes through actual pan gestures rather than assuming fixed node boxes. + for (let pass=0; pass<10; pass++) { + const labels = (await semantics()).map(item => item.label); + for (const needle of [...nodes, ...edgeLabels]) { + if (labels.some(label => label.includes(needle))) seen.add(needle); + } + if ([...nodes, ...edgeLabels].every(label => seen.has(label)) && + (await nodeRect('Success'))?.width > 0) break; + await drag({x:900,y:300}, -500); + } + for (const label of [...nodes, ...edgeLabels]) { + if (!seen.has(label)) throw new Error(`Graph pan never revealed ${label}`); + } + if (!await clickLabel('Success')) throw new Error('Could not click Success terminal'); + await delay(800); + const afterTerminal = await evaluate('document.body.innerText'); + if (!afterTerminal.includes('Selected: #success')) throw new Error(`terminal callback did not carry its key: ${afterTerminal}`); + captures.push(await capture('selected-terminal',1280,800)); + await send('Page.reload', {}, session); + await delay(2500); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(1500); + // A real drag on a phone viewport, where the measured graph is wider than + // the viewport, must pan the stock InteractiveViewer: the node moves. + await send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true }, session); + await delay(1500); + const before = await nodeRect('plan'); + const start = { x: before.x + before.width / 2, y: before.y + before.height / 2 }; + await drag(start, -40, -10); + const after = await nodeRect('plan'); + if (!after || (Math.abs(after.x - before.x) < 20 && Math.abs(after.y - before.y) < 20)) { + throw new Error(`Drag did not pan the graph: ${JSON.stringify({ before, after })}`); + } + captures.push(await capture('panned-phone', 390, 844)); + console.log(JSON.stringify({ variant, scheme, scale, rects, captures }, 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(resolve => { + server.close(resolve); + server.closeAllConnections(); + }); + await rm(profile, { recursive: true, force: true }); +}