From 5b833e721ea1418c83e7a9ebf5accd18d0b15a65 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 23:42:46 +0100 Subject: [PATCH] feat(app): add run-mode graph with recorded-visit evidence --- .../graph/widgets/run_graph_canvas.dart | 367 ++++++++++++++ .../graph/widgets/run_graph_view.dart | 331 +++++++++++++ app/notes/P2-run-graph.md | 146 ++++++ .../widgets/run_graph_edge_layer_test.dart | 147 ++++++ .../graph/widgets/run_graph_view_test.dart | 460 ++++++++++++++++++ app/tool/run_graph_probe.dart | 200 ++++++++ app/tool/run_graph_probe.mjs | 265 ++++++++++ 7 files changed, 1916 insertions(+) create mode 100644 app/lib/features/graph/widgets/run_graph_canvas.dart create mode 100644 app/lib/features/graph/widgets/run_graph_view.dart create mode 100644 app/notes/P2-run-graph.md create mode 100644 app/test/features/graph/widgets/run_graph_edge_layer_test.dart create mode 100644 app/test/features/graph/widgets/run_graph_view_test.dart create mode 100644 app/tool/run_graph_probe.dart create mode 100644 app/tool/run_graph_probe.mjs diff --git a/app/lib/features/graph/widgets/run_graph_canvas.dart b/app/lib/features/graph/widgets/run_graph_canvas.dart new file mode 100644 index 00000000..22be89cf --- /dev/null +++ b/app/lib/features/graph/widgets/run_graph_canvas.dart @@ -0,0 +1,367 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/foundation.dart' show listEquals; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; +import '../domain/graph_definition.dart'; +import '../domain/run_graph_state.dart'; +import '../layout/layout_models.dart'; +import '../painting/graph_edge_layer.dart'; +import '../routing/route_models.dart'; +import 'graph_canvas_style.dart'; +import 'graph_stage_node.dart'; +import 'measured_child.dart'; + +/// The run graph's canvas primitives: split route painting and measurement of +/// the exact status-bearing nodes the run renderer places. +/// +/// This keeps the landed `GraphEdgePainter` geometry (paths and arrowheads) and +/// adds only what run evidence needs: two route classes on one passive layer. +/// No node is invented, no route is re-routed and no style is assumed here. + +/// A passive canvas that draws taken routes as solid, arrowed strokes and +/// untaken routes as dashed, arrowless strokes behind them. +/// +/// The caller supplies the already-routed [executedRoutes] and +/// [untakenRoutes], the graph-space [canvasSize] and its native theme colours. +/// The layer never takes pointer input, so nodes and labels keep their gestures. +class RunGraphEdgeLayer extends StatelessWidget { + const RunGraphEdgeLayer({ + super.key, + required this.executedRoutes, + required this.untakenRoutes, + required this.canvasSize, + required this.executedColor, + required this.untakenColor, + required this.strokeWidth, + }); + + final List executedRoutes; + final List untakenRoutes; + final Size canvasSize; + final Color executedColor; + final Color untakenColor; + final double strokeWidth; + + @override + Widget build(BuildContext context) => CustomPaint( + size: canvasSize, + painter: RunGraphEdgePainter( + executedRoutes: executedRoutes, + untakenRoutes: untakenRoutes, + executedColor: executedColor, + untakenColor: untakenColor, + strokeWidth: strokeWidth, + ), + ); +} + +/// Paints a [RunGraphEdgeLayer]. +/// +/// Executed routes reuse the landed [GraphEdgePainter] path and arrow geometry; +/// untaken routes are the same polyline broken into native-sized dashes and +/// never receive an arrowhead. Public so the compositor and its tests share one +/// decision about which class of route gets an arrow. +class RunGraphEdgePainter extends CustomPainter { + RunGraphEdgePainter({ + required this.executedRoutes, + required this.untakenRoutes, + required this.executedColor, + required this.untakenColor, + required this.strokeWidth, + }) : assert(strokeWidth > 0), + _executed = GraphEdgePainter( + routes: executedRoutes, + color: executedColor, + strokeWidth: strokeWidth, + ), + _executedLine = Paint() + ..color = executedColor + ..strokeWidth = strokeWidth + ..style = PaintingStyle.stroke + ..strokeJoin = StrokeJoin.round, + _untakenLine = Paint() + ..color = untakenColor + ..strokeWidth = strokeWidth + ..style = PaintingStyle.stroke + ..strokeJoin = StrokeJoin.round, + _arrow = Paint() + ..color = executedColor + ..style = PaintingStyle.fill; + + final List executedRoutes; + final List untakenRoutes; + final Color executedColor; + final Color untakenColor; + final double strokeWidth; + + final GraphEdgePainter _executed; + final Paint _executedLine; + final Paint _untakenLine; + final Paint _arrow; + + /// Dash and gap lengths in graph space; a dash never becomes a route style. + static const double dashLength = 12; + static const double dashGap = 8; + + @override + void paint(Canvas canvas, Size size) { + if (executedRoutes.isEmpty && untakenRoutes.isEmpty) return; + canvas.save(); + canvas.clipRect(Offset.zero & size); + for (final route in untakenRoutes) { + if (route.points.length < 2) continue; + canvas.drawPath(dashedPath(route), _untakenLine); + } + for (final route in executedRoutes) { + if (route.points.length < 2) continue; + canvas.drawPath(_executed.linePath(route), _executedLine); + } + for (final route in executedRoutes) { + if (route.points.length < 2) continue; + canvas.drawPath(_executed.arrowPath(route), _arrow); + } + canvas.restore(); + } + + /// The route's polyline split into [dashLength] segments separated by + /// [dashGap], following every orthogonal bend without smoothing. + Path dashedPath(EdgeRoute route) { + final source = _executed.linePath(route); + final dashed = Path(); + for (final metric in source.computeMetrics()) { + var start = 0.0; + while (start < metric.length) { + final end = start + dashLength < metric.length + ? start + dashLength + : metric.length; + dashed.addPath(metric.extractPath(start, end), Offset.zero); + start = end + dashGap; + } + } + return dashed; + } + + /// Passive like the landed edge layer: every point misses. + @override + bool hitTest(Offset position) => false; + + @override + bool shouldRepaint(RunGraphEdgePainter oldDelegate) => + oldDelegate.executedColor != executedColor || + oldDelegate.untakenColor != untakenColor || + oldDelegate.strokeWidth != strokeWidth || + !listEquals(oldDelegate.executedRoutes, executedRoutes) || + !listEquals(oldDelegate.untakenRoutes, untakenRoutes); +} + +/// The run canvas: split route classes behind status-bearing native nodes, with +/// outcome labels only for routes the run actually took. +/// +/// [layout] and [routing] are the caller's measured geometry. The canvas never +/// changes them and never assumes a node size. +class RunGraphCanvas extends StatelessWidget { + const RunGraphCanvas({ + super.key, + required this.nodes, + required this.layout, + required this.routing, + required this.state, + required this.style, + required this.recordedStatuses, + required this.onStageSelected, + this.selectedStage, + }); + + final List nodes; + final GraphLayout layout; + final GraphRouting routing; + final RunGraphState state; + final GraphCanvasStyle style; + final Map recordedStatuses; + final ValueChanged onStageSelected; + final String? selectedStage; + + @override + Widget build(BuildContext context) { + final nodesByKey = { + for (final node in nodes) node.key: node, + }; + final executed = []; + final untaken = []; + for (final route in routing.routes) { + if (state.isRouteTaken(route.source, route.outcome, route.target)) { + executed.add(route); + } else { + untaken.add(route); + } + } + final executedIds = {for (final route in executed) route.id}; + final size = Size(routing.width, routing.height); + final cupertino = usesCupertinoHost(context); + final executedColor = cupertino + ? CupertinoTheme.of(context).primaryColor + : Theme.of(context).colorScheme.primary; + return InteractiveViewer( + constrained: false, + minScale: 0.3, + maxScale: 3, + child: SizedBox.fromSize( + size: size, + child: Stack( + clipBehavior: Clip.none, + children: [ + Positioned.fill( + child: RunGraphEdgeLayer( + executedRoutes: executed, + untakenRoutes: untaken, + canvasSize: size, + executedColor: executedColor, + untakenColor: 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: RunGraphNode( + node: nodesByKey[box.key]!, + recordedStatus: recordedStatuses[box.key], + selected: box.key == selectedStage, + opensVisit: + !nodesByKey[box.key]!.terminal && + state.isStageVisited(box.key), + onSelected: onStageSelected, + ), + ), + // A run labels only the routes that actually happened. + for (final label in routing.labels) + if (executedIds.contains(label.edgeId)) + Positioned( + left: label.x, + top: label.y, + child: Text( + routing.routeFor(label.edgeId)!.label, + style: style.labelStyle, + ), + ), + ], + ), + ), + ); + } +} + +/// One placed run node. A visited stage is the native control with its recorded +/// status; an unvisited node and a terminal are labels with no tap target or +/// button semantics, because neither owns a recorded visit to open. +class RunGraphNode extends StatelessWidget { + const RunGraphNode({ + super.key, + required this.node, + required this.recordedStatus, + required this.opensVisit, + required this.onSelected, + this.selected = false, + }); + + final GraphNode node; + final String? recordedStatus; + final bool opensVisit; + final bool selected; + final ValueChanged onSelected; + + @override + Widget build(BuildContext context) { + final status = recordedStatus; + if (opensVisit) { + return GraphStageNode( + node: node, + recordedStatus: status, + selected: selected, + onSelected: onSelected, + ); + } + return Semantics( + container: true, + label: status == null ? node.label : '${node.label}\n$status', + child: ExcludeSemantics( + child: IgnorePointer( + child: GraphStageNode( + node: node, + recordedStatus: status, + onSelected: (_) {}, + ), + ), + ), + ); + } +} + +/// Measures the status-bearing run nodes and every route label offstage. +/// +/// A visited node is taller than the same node without its recorded status, so +/// the measurement must use the exact widget the canvas places. Sizes are +/// reported after layout and callers schedule the placement frame. +class RunGraphMeasurements extends StatelessWidget { + const RunGraphMeasurements({ + super.key, + required this.nodes, + required this.edges, + required this.maxNodeWidth, + required this.labelStyle, + required this.recordedStatuses, + required this.onNodeSize, + required this.onLabelSize, + }); + + final List nodes; + final List edges; + final double maxNodeWidth; + final TextStyle labelStyle; + final Map recordedStatuses; + 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( + 'run-node:${node.key}:${node.label}:' + '${recordedStatuses[node.key] ?? ''}', + ), + onSize: (size) => onNodeSize(node.key, size), + child: ConstrainedBox( + constraints: BoxConstraints(maxWidth: maxNodeWidth), + child: GraphStageNode( + node: node, + recordedStatus: recordedStatuses[node.key], + onSelected: (_) {}, + ), + ), + ), + for (final edge in edges) + MeasuredChild( + key: ValueKey('run-label:${edge.id}'), + onSize: (size) => onLabelSize(edge.label, size), + child: Text(edge.label, style: labelStyle), + ), + ], + ), + ), + ); +} diff --git a/app/lib/features/graph/widgets/run_graph_view.dart b/app/lib/features/graph/widgets/run_graph_view.dart new file mode 100644 index 00000000..1868d488 --- /dev/null +++ b/app/lib/features/graph/widgets/run_graph_view.dart @@ -0,0 +1,331 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../ui/adaptive/host.dart'; +import '../domain/graph_definition.dart'; +import '../domain/run_graph_state.dart'; +import '../domain/stage_visits.dart'; +import '../layout/graph_node_layout.dart'; +import '../layout/layout_models.dart'; +import '../routing/graph_edge_routing.dart'; +import '../routing/route_models.dart'; +import 'graph_canvas_style.dart'; +import 'run_graph_canvas.dart'; + +/// The run tab's exact missing-graph wording (web `RUN_GRAPH_MISSING`). +const String runGraphMissing = 'This server did not include the run graph.'; + +/// The run legend's route-class words (web graph legend). +const String runGraphExecuted = 'Executed'; +const String runGraphNotExecuted = 'Not executed'; + +/// One run's definition drawn as evidence: visited stages carry their recorded +/// status, only taken routes are solid and arrowed, and every other route stays +/// dashed and muted. +/// +/// [run] is the run detail map whose recorded steps are the only source of +/// visits, statuses and routes. A node with no recorded visit is not a control: +/// tapping it does nothing, and no visit, session or status is manufactured for +/// it. A visited stage reports its exact key through [onStageSelected] so the +/// caller can open that stage's latest recorded visit. Visited terminals are +/// shown with the outcome that resolved there but have no recorded visit to +/// open, so they stay non-interactive. +/// +/// The view fills its bounded constraints with a stock [InteractiveViewer] for +/// pan and zoom; the elapsed line appears only while the run is executing and +/// is static (no invented progress or timer). +class RunGraphView extends StatefulWidget { + const RunGraphView({ + super.key, + required this.graph, + required this.run, + required this.onStageSelected, + this.selectedStage, + this.now, + }); + + /// The run's definition graph, or null when the server omitted it. + final JsonMap? graph; + + /// The run detail whose recorded steps supply all execution evidence. + final JsonMap run; + + /// Reports one visited stage's exact key; never called for an unvisited node. + final ValueChanged onStageSelected; + + final String? selectedStage; + + /// Injectable clock for deterministic elapsed labels; defaults to now. + final DateTime Function()? now; + + @override + State createState() => _RunGraphViewState(); +} + +class _RunGraphViewState extends State { + final Map _nodeSizes = {}; + final Map _labelSizes = {}; + final Map _measuredStatuses = {}; + TextScaler? _scaler; + bool _rebuildScheduled = false; + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + final scaler = MediaQuery.textScalerOf(context); + if (scaler != _scaler) { + _scaler = scaler; + _nodeSizes.clear(); + _labelSizes.clear(); + } + } + + 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(() {}); + }); + } + + (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); + } + + /// Executed evidence shown by the native node's recorded-status affordance. + /// + /// A stage shows its latest recorded status (sequence order) verbatim. A + /// terminal has no step; it shows the recorded route outcome that resolved + /// there. Null means no recorded execution, so an unvisited node cannot be + /// mistaken for a visit. + String? _recordedStatus( + GraphNode node, + RunGraphState state, + Map> visits, + ) { + if (!state.isStageVisited(node.key)) return null; + if (!node.terminal) { + final stageVisits = visits[node.key]; + if (stageVisits == null || stageVisits.isEmpty) return null; + final status = '${stageVisits.last['status'] ?? ''}'.trim(); + return status.isEmpty ? null : status; + } + for (final route in state.takenRoutes) { + final parts = route.split('\u0000'); + if (parts.length == 3 && parts[2] == node.key) return parts[1]; + } + return null; + } + + @override + Widget build(BuildContext context) { + final graph = widget.graph; + final nodes = graph == null ? const [] : graphNodes(graph); + final edges = graph == null ? const [] : graphEdges(graph); + final style = GraphCanvasStyle.of(context); + final state = runGraphState(widget.run); + final rawSteps = widget.run['steps']; + final steps = rawSteps is List + ? rawSteps.whereType().map(JsonMap.from).toList() + : const []; + final visits = visitsByStage(steps); + final statuses = { + for (final node in nodes) node.key: _recordedStatus(node, state, visits), + }; + // A status line changes the node's measured height. Drop only the stale + // extents so this frame never places a taller node in its old box; the + // offstage measurement reports the new extent and schedules the placement. + for (final entry in statuses.entries) { + if (_measuredStatuses[entry.key] != entry.value) { + _nodeSizes.remove(entry.key); + _measuredStatuses[entry.key] = entry.value; + } + } + _measuredStatuses.removeWhere((key, _) => !statuses.containsKey(key)); + return LayoutBuilder( + builder: (context, constraints) { + assert( + constraints.hasBoundedWidth && constraints.hasBoundedHeight, + 'RunGraphView needs a bounded viewport; constrain it, for example ' + 'with a SizedBox or an Expanded slot.', + ); + if (nodes.isEmpty) return _message(runGraphMissing, style); + final geometry = _geometry(nodes, edges); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + _header(state, style), + Expanded( + child: Stack( + fit: StackFit.expand, + children: [ + if (geometry != null) + RunGraphCanvas( + nodes: nodes, + layout: geometry.$1, + routing: geometry.$2, + state: state, + style: style, + recordedStatuses: statuses, + selectedStage: widget.selectedStage, + onStageSelected: widget.onStageSelected, + ) + else + const SizedBox.shrink(), + RunGraphMeasurements( + nodes: nodes, + edges: edges, + maxNodeWidth: constraints.maxWidth, + labelStyle: style.labelStyle, + recordedStatuses: statuses, + onNodeSize: (key, size) => _record(_nodeSizes, key, size), + onLabelSize: (key, size) => _record(_labelSizes, key, size), + ), + ], + ), + ), + if (geometry != null && geometry.$2.skipped.isNotEmpty) + Flexible( + child: SingleChildScrollView( + child: _message( + [ + for (final diagnostic in geometry.$2.skipped) + '${diagnostic.source} → ${diagnostic.outcome}: ' + '${diagnostic.message}', + ].join('\n'), + style, + ), + ), + ), + ], + ); + }, + ); + } + + Widget _message(String message, GraphCanvasStyle style) => Padding( + padding: const EdgeInsets.all(24), + child: Align( + alignment: AlignmentDirectional.topStart, + child: Text(message, style: style.messageStyle), + ), + ); + + Widget _header(RunGraphState state, GraphCanvasStyle style) { + final cupertino = usesCupertinoHost(context); + final executedColor = cupertino + ? CupertinoTheme.of(context).primaryColor + : Theme.of(context).colorScheme.primary; + final mutedColor = style.edgeColor; + final active = state.activeStage; + return Padding( + padding: const EdgeInsetsDirectional.fromSTEB(12, 8, 12, 0), + child: Wrap( + spacing: 16, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Semantics( + container: true, + label: 'Route kinds', + child: Wrap( + spacing: 12, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + _LegendEntry( + icon: cupertino + ? CupertinoIcons.arrow_right + : Icons.arrow_forward, + label: runGraphExecuted, + color: executedColor, + ), + _LegendEntry( + icon: cupertino ? CupertinoIcons.minus : Icons.remove, + label: runGraphNotExecuted, + color: mutedColor, + ), + ], + ), + ), + if (active != null) _elapsed(active, state.currentStageStartedAt), + ], + ), + ); + } + + Widget _elapsed(String active, String? startedAt) { + final started = startedAt == null ? null : DateTime.tryParse(startedAt); + final duration = started == null + ? null + : _formatElapsed((widget.now ?? DateTime.now)().difference(started)); + final text = duration == null + ? 'Current stage $active' + : 'Current stage $active · elapsed $duration'; + return Text(text, style: GraphCanvasStyle.of(context).labelStyle); + } +} + +class _LegendEntry extends StatelessWidget { + const _LegendEntry({ + required this.icon, + required this.label, + required this.color, + }); + + final IconData icon; + final String label; + final Color color; + + @override + Widget build(BuildContext context) => Wrap( + spacing: 4, + runSpacing: 2, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + ExcludeSemantics(child: Icon(icon, color: color)), + Text(label), + ], + ); +} + +String _formatElapsed(Duration duration) { + final seconds = duration.inSeconds < 0 ? 0 : duration.inSeconds; + if (seconds < 60) return '${seconds}s'; + if (seconds < 3600) return '${seconds ~/ 60}m ${seconds % 60}s'; + return '${seconds ~/ 3600}h ${(seconds % 3600) ~/ 60}m'; +} diff --git a/app/notes/P2-run-graph.md b/app/notes/P2-run-graph.md new file mode 100644 index 00000000..6d08d7dc --- /dev/null +++ b/app/notes/P2-run-graph.md @@ -0,0 +1,146 @@ +# P2-run-graph — executed vs unexecuted run evidence + +## Scope + +App-only, new files. No existing source, `main.dart`, shell, pubspec, server, web +client, platform directory or other feature lane was edited. The slice renders a +run definition with recorded execution evidence and reports a visited stage key +to its caller; it does not open the visit pane itself and is not wired into the +run tab (that integration belongs to the runs lane). + +| File | Lines | Responsibility | +| --- | --- | --- | +| `lib/features/graph/widgets/run_graph_view.dart` | 331 | bounded widget, geometry, recorded evidence, legend/elapsed header | +| `lib/features/graph/widgets/run_graph_canvas.dart` | 367 | split edge layer/painter, canvas composition, native node wrapper, measurement | +| `test/features/graph/widgets/run_graph_view_test.dart` | 460 | evidence, route classes, terminal truth, click/semantics, empty state, order, 320/2x, dark Cupertino, status remeasure | +| `test/features/graph/widgets/run_graph_edge_layer_test.dart` | 147 | solid/arrowed taken strokes, dashed untaken strokes, passive hit test, repaint | +| `tool/run_graph_probe.dart` | 200 | isolated browser fixture (not app/shell registration) | +| `tool/run_graph_probe.mjs` | 265 | real-Chrome assertions and captures | + +Both source files are cohesive units and slightly over the 250-line aim because +the view owns evidence/geometry while the helper owns painting/measurement and +the native node wrapper. Splitting further would either duplicate measurement or +create arbitrary fragments. + +## Public API + +```dart +RunGraphView( + graph: JsonMap?, // omitted run graph -> exact missing wording + run: JsonMap, // recorded steps are the only evidence + onStageSelected: ValueChanged, + selectedStage: String?, // caller-owned graph selection + now: DateTime Function()?, // deterministic elapsed tests +) +``` + +`runGraphMissing` is the exact web sentence: `This server did not include the +run graph.` `runGraphExecuted` / `runGraphNotExecuted` are `Executed` and +`Not executed`. + +## Behavior + +- **Visited stages only:** `RunGraphState` decides visits and routes. A visited + stage's native node receives its latest recorded step status (sequence order, + via `visitsByStage`). An unvisited stage gets no status, no tap target and no + button semantics; it is a plain graph label. No visit, session, status or + elapsed value is fabricated. +- **Terminals:** only `RunGraphState.visitedStages` terminals (a recorded route + resolved there) show evidence, using the recorded route outcome + (`success`/`error`). An untaken terminal stays plain. Terminals own no recorded + step, so they are never presented as an openable visit. +- **Routes:** taken definition routes are solid and arrowed using the landed + `GraphEdgePainter` geometry; untaken routes are dashed, arrowless and use the + host's outline/separator role. Only taken routes get outcome labels, as in the + web run tab. Untaken routes keep their definition order and identifiers. +- **Order:** routing preserves `graphEdges` order, so a stage's outcomes are + success first, other alphabetical, error last. The run filter does not reorder + them. +- **Legend:** a native `Wrap` of two stock-icon entries, `Executed` and + `Not executed`, labelled `Route kinds` for assistive technology. No bespoke + palette or swatch painting. +- **Elapsed:** a static `Current stage · elapsed ` line appears + only while `RunGraphState.activeStage` exists (run executing). It is computed + once per build from `currentStageStartedAt`; there is no timer, pulse or + invented progress. With no parseable start it says only `Current stage `. +- **Node styling:** Material uses the landed `Card`/`Card.filled` node and + Cupertino its tinted/filled buttons; the recorded-status line is the execution + affordance. Status changes drop only that node's stale measured extent, and the + measurement key includes the status so even a same-size status change reports + a fresh extent; a taller node is never placed in the old box. +- **Viewport:** the caller must supply bounded constraints; the view fills them + with stock `InteractiveViewer` pan/zoom (`minScale: 0.3`, `maxScale: 3`). + Node and label extents are measured from the exact widgets placed. At 320px + and 2x text the graph pans instead of shrinking or clipping content. +- **Empty:** null/absent graph or a graph with no stages shows the exact + `This server did not include the run graph.` sentence and no viewer. + +## Checks actually run + +``` +dart format lib/features/graph/widgets test/features/graph/widgets tool/run_graph_probe.dart +flutter test test/features/graph/widgets/run_graph_view_test.dart \ + test/features/graph/widgets/run_graph_edge_layer_test.dart # 13 passed +flutter test test/features/graph # 153 passed +flutter test # 844 passed +flutter analyze # No issues found! +flutter build web # ✓ Built build/web +flutter build web -t tool/run_graph_probe.dart -o build/run_graph_probe +``` + +The full-app `flutter analyze`, `flutter test` and `flutter build web` also pass; +integrated run-tab registration was not performed because the shell/runs wiring +belongs to another lane. + +## Rendered evidence + +Fresh real Chrome (headless, throwaway profile, loopback server on an +OS-assigned port). The fixture records a running `plan -> build` path and a +finished `plan -> build -> audit -> Success` path. Captures are in shared +`public/run-graph-captures/`: + +| File | Shows | +| --- | --- | +| `run-graph-material-light-1x-running-initial.png` | visited plan/build with `completed`/`running`, solid arrowed taken route, dashed untaken routes, legend, live elapsed line | +| `run-graph-material-light-1x-running-final.png` | plan selected after a real node click; selection reported by key | +| `run-graph-material-light-1x-running-phone.png` | 320px material viewport | +| `run-graph-material-light-1x-finished-initial.png` | finished run: executed path through `Success success`, no live line, untaken failure route dashed | +| `run-graph-material-light-1x-finished-final.png` / `-phone.png` | final/phone variants after pan and terminal safety check | +| `run-graph-cupertino-dark-2x-running-initial.png` | dark Cupertino host at 320px/2x, wrapped native legend, visited statuses | +| `run-graph-cupertino-dark-2x-running-final.png` | real pan exposes the running build node | +| `run-graph-cupertino-dark-2x-finished-initial.png` / `-final.png` | dark Cupertino finished path and terminal evidence | + +The probe asserts legend wording, visible recorded statuses, the live line only +for the running fixture, click-by-key selection, unvisited `audit` leaving +selection unchanged, a finished terminal click not creating a visit, and real +drag panning at 320/2x. Earlier `*-desktop.png` captures from the first probe +run were removed as superseded by the `initial`/`final` set. + +## Honest limits + +- **Not wired.** No run-tab, shell or application edit; the caller must supply + the graph/run maps and open the reported stage's latest recorded visit. +- **Terminal clicks do nothing.** Terminals have no recorded step, so the view + refuses to invent a visit for them; they remain evidence-only. +- **No live ticking.** The elapsed line is intentionally static per build; a + live ticking badge/timer remains for the integrating lane. +- **No browser keyboard/fit toolbar.** Standard node focus semantics come from + the native controls, but a fit/expand toolbar was not added (not in this + slice). +- **Mobile unverified.** Only Chrome/Flutter web was built and driven. Android + and iOS were not built, installed or tested. +- **Not committed.** The stage instruction forbids commit/push/deploy, so the + candidate remains uncommitted working-tree files; no main merge or push. The + task input's "commit the candidate" is superseded by the stage policy. + +## Manager completion after an infrastructure failure + +The run ended with the server's `UNIQUE constraint failed: +step_file_changes.run_id, step_file_changes.sequence (1555)` persistence bug, not +an app fault; the parallel search slice failed the same way. The retained work is +complete: the manager ran the graph widget suite (43 tests pass) and inspected the +run-mode canvas, then merged it. No retry of this slice was started. The server +defect is tracked in WORK.md and fixed separately with a regression. + +This slice is the run-mode COMPONENT only: it is not yet the run detail's Graph +tab and does not open visit panes. Those remain wiring work. diff --git a/app/test/features/graph/widgets/run_graph_edge_layer_test.dart b/app/test/features/graph/widgets/run_graph_edge_layer_test.dart new file mode 100644 index 00000000..f792d010 --- /dev/null +++ b/app/test/features/graph/widgets/run_graph_edge_layer_test.dart @@ -0,0 +1,147 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:pipelines_app/features/graph/routing/route_models.dart'; +import 'package:pipelines_app/features/graph/widgets/run_graph_canvas.dart'; + +import '../painting/edge_layer_fixtures.dart'; + +void main() { + const executedColor = Colors.blue; + const untakenColor = Colors.grey; + final executed = edgeRoute( + points: const [RoutePoint(10, 20), RoutePoint(90, 20)], + ); + final untaken = edgeRoute( + points: const [ + RoutePoint(10, 40), + RoutePoint(40, 40), + RoutePoint(40, 70), + RoutePoint(90, 70), + ], + ); + + test( + 'draws solid arrowed taken routes and dashed arrowless untaken routes', + () { + final canvas = TestRecordingCanvas(); + RunGraphEdgePainter( + executedRoutes: [executed], + untakenRoutes: [untaken], + executedColor: executedColor, + untakenColor: untakenColor, + strokeWidth: 1, + ).paint(canvas, const Size(120, 90)); + + final draws = canvas.invocations + .where((call) => call.invocation.memberName == #drawPath) + .toList(); + final paints = [ + for (final call in draws) + call.invocation.positionalArguments.last as Paint, + ]; + // One dashed path behind, then one solid line and one filled arrow. + expect(draws, hasLength(3)); + expect(paints[0].style, PaintingStyle.stroke); + expect(paints[0].color.toARGB32(), untakenColor.toARGB32()); + expect(paints[1].style, PaintingStyle.stroke); + expect(paints[1].color.toARGB32(), executedColor.toARGB32()); + expect(paints[2].style, PaintingStyle.fill); + expect(paints[2].color.toARGB32(), executedColor.toARGB32()); + + final clip = canvas.invocations.singleWhere( + (call) => call.invocation.memberName == #clipRect, + ); + expect( + clip.invocation.positionalArguments.first, + const Rect.fromLTWH(0, 0, 120, 90), + ); + }, + ); + + test('an untaken route is broken into dashes and never an arrow', () { + final canvas = TestRecordingCanvas(); + final painter = RunGraphEdgePainter( + executedRoutes: const [], + untakenRoutes: [untaken], + executedColor: executedColor, + untakenColor: untakenColor, + strokeWidth: 1, + ); + painter.paint(canvas, const Size(120, 90)); + + final paints = canvas.invocations + .where((call) => call.invocation.memberName == #drawPath) + .map((call) => call.invocation.positionalArguments.last as Paint); + expect(paints, hasLength(1)); + expect(paints.single.style, PaintingStyle.stroke); + expect(painter.dashedPath(untaken).computeMetrics().length, greaterThan(1)); + }); + + test('is passive and repaints only for a real change', () { + final painter = RunGraphEdgePainter( + executedRoutes: [executed], + untakenRoutes: [untaken], + executedColor: executedColor, + untakenColor: untakenColor, + strokeWidth: 1, + ); + expect(painter.hitTest(const Offset(50, 20)), isFalse); + expect(painter.hitTest(const Offset(500, 500)), isFalse); + expect( + painter.shouldRepaint( + RunGraphEdgePainter( + executedRoutes: [executed], + untakenRoutes: [untaken], + executedColor: executedColor, + untakenColor: untakenColor, + strokeWidth: 1, + ), + ), + isFalse, + ); + expect( + painter.shouldRepaint( + RunGraphEdgePainter( + executedRoutes: [executed], + untakenRoutes: const [], + executedColor: executedColor, + untakenColor: untakenColor, + strokeWidth: 1, + ), + ), + isTrue, + ); + expect( + painter.shouldRepaint( + RunGraphEdgePainter( + executedRoutes: [executed], + untakenRoutes: [untaken], + executedColor: Colors.green, + untakenColor: untakenColor, + strokeWidth: 1, + ), + ), + isTrue, + ); + }); + + testWidgets('sizes itself from the supplied graph canvas', (tester) async { + await tester.pumpWidget( + MaterialApp( + home: Center( + child: RunGraphEdgeLayer( + executedRoutes: [executed], + untakenRoutes: [untaken], + canvasSize: const Size(120, 90), + executedColor: executedColor, + untakenColor: untakenColor, + strokeWidth: 1, + ), + ), + ), + ); + expect(tester.getSize(find.byType(RunGraphEdgeLayer)), const Size(120, 90)); + expect(tester.takeException(), isNull); + }); +} diff --git a/app/test/features/graph/widgets/run_graph_view_test.dart b/app/test/features/graph/widgets/run_graph_view_test.dart new file mode 100644 index 00000000..5b4f7512 --- /dev/null +++ b/app/test/features/graph/widgets/run_graph_view_test.dart @@ -0,0 +1,460 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/semantics.dart'; +import 'package:flutter_test/flutter_test.dart'; + +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/graph/domain/graph_protocol.dart'; +import 'package:pipelines_app/features/graph/widgets/graph_stage_node.dart'; +import 'package:pipelines_app/features/graph/widgets/run_graph_canvas.dart'; +import 'package:pipelines_app/features/graph/widgets/run_graph_view.dart'; + +import '../domain/graph_fixtures.dart'; + +JsonMap _runningRun() => { + 'id': 42, + 'steps': [ + step( + sequence: 1, + stage: 'plan', + status: 'completed', + outcome: 'success', + target: 'build', + ), + step( + sequence: 2, + stage: 'build', + status: 'running', + startedAt: '2026-10-21T10:00:00Z', + ), + ], + 'current_stage': 'build', + 'executing': true, +}; + +JsonMap _finishedRun({String outcome = 'success', String target = '#'}) => + { + 'id': 43, + 'steps': [ + step( + sequence: 1, + stage: 'plan', + status: 'completed', + outcome: outcome, + target: target, + ), + ], + 'current_stage': '', + 'executing': false, + }; + +/// plan -> build -> ship, with the last recorded outcome resolving a terminal. +JsonMap _completedPath({bool failure = false}) => { + 'id': 45, + 'steps': [ + step( + sequence: 1, + stage: 'plan', + status: 'completed', + outcome: 'success', + target: 'build', + ), + step( + sequence: 2, + stage: 'build', + status: 'completed', + outcome: 'success', + target: 'ship', + ), + step( + sequence: 3, + stage: 'ship', + status: 'completed', + outcome: failure ? 'error' : 'success', + target: '#', + ), + ], + 'current_stage': '', + 'executing': false, +}; + +Widget _materialHost( + JsonMap? graph, + JsonMap run, { + ValueChanged? onSelected, + String? selected, + double scale = 1, + Size size = const Size(900, 700), + DateTime Function()? now, +}) { + return MaterialApp( + home: Scaffold( + body: Builder( + builder: (context) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(scale)), + child: SizedBox( + width: size.width, + height: size.height, + child: RunGraphView( + graph: graph, + run: run, + selectedStage: selected, + onStageSelected: onSelected ?? (_) {}, + now: now, + ), + ), + ), + ), + ), + ); +} + +Widget _cupertinoHost( + JsonMap graph, + JsonMap run, { + ValueChanged? onSelected, + double scale = 1, +}) { + return CupertinoApp( + theme: const CupertinoThemeData(brightness: Brightness.dark), + home: CupertinoPageScaffold( + child: Builder( + builder: (context) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(scale)), + child: SizedBox( + width: 320, + height: 700, + child: RunGraphView( + graph: graph, + run: run, + onStageSelected: onSelected ?? (_) {}, + ), + ), + ), + ), + ), + ); +} + +Future _settle(WidgetTester tester) async { + await tester.pump(); + await tester.pump(); + await tester.pump(); +} + +Finder _node(String key) => find.byWidgetPredicate( + (widget) => widget is GraphStageNode && widget.node.key == key, +); + +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('visited stages show recorded status and the legend', ( + tester, + ) async { + await tester.pumpWidget( + _materialHost( + linearGraph(), + _runningRun(), + now: () => DateTime.utc(2026, 10, 21, 10, 2, 5), + ), + ); + await _settle(tester); + + expect(find.text(runGraphExecuted), findsOneWidget); + expect(find.text(runGraphNotExecuted), findsOneWidget); + expect( + tester.widget(_node('plan')).recordedStatus, + 'completed', + ); + expect( + tester.widget(_node('build')).recordedStatus, + 'running', + ); + expect(tester.widget(_node('ship')).recordedStatus, isNull); + expect( + tester.widget(_node(failureEnd)).recordedStatus, + isNull, + ); + expect( + tester.widget(_node(successEnd)).recordedStatus, + isNull, + ); + // The elapsed line exists only because this run is still executing. + expect(find.text('Current stage build · elapsed 2m 5s'), findsOneWidget); + expect(tester.takeException(), isNull); + }); + + testWidgets('only routes the run took are executed and labelled', ( + tester, + ) async { + await tester.pumpWidget( + _materialHost( + linearGraph(), + _runningRun(), + now: () => DateTime.utc(2026, 10, 21, 10, 2, 5), + ), + ); + await _settle(tester); + + final layer = tester.widget( + find.byType(RunGraphEdgeLayer), + ); + expect( + layer.executedRoutes.map((route) => '${route.source}/${route.target}'), + ['plan/build'], + ); + expect(layer.untakenRoutes, isNotEmpty); + expect( + layer.executedRoutes.every( + (route) => route.source == 'plan' && route.target == 'build', + ), + isTrue, + ); + // A run labels only what happened: the untaken success/error routes on + // build/ship carry no chips, including the implicit fallback `error*`. + expect(find.text('success'), findsOneWidget); + expect(find.text('error*'), findsNothing); + expect(find.text('error'), findsNothing); + }); + + testWidgets('a terminal is executed only when a visit resolved there', ( + tester, + ) async { + await tester.pumpWidget(_materialHost(linearGraph(), _completedPath())); + await _settle(tester); + + expect( + tester.widget(_node(successEnd)).recordedStatus, + 'success', + ); + expect( + tester.widget(_node(failureEnd)).recordedStatus, + isNull, + ); + // A finished run has no active-stage line even with a current_stage value. + expect(find.textContaining('Current stage'), findsNothing); + + await tester.pumpWidget( + _materialHost(linearGraph(), _completedPath(failure: true)), + ); + await _settle(tester); + expect( + tester.widget(_node(failureEnd)).recordedStatus, + 'error', + ); + expect( + tester.widget(_node(successEnd)).recordedStatus, + isNull, + ); + }); + + testWidgets( + 'a visited stage reports its key and an unvisited node does not', + (tester) async { + final picked = []; + await tester.pumpWidget( + _materialHost( + linearGraph(), + _finishedRun(), + onSelected: picked.add, + selected: 'plan', + ), + ); + await _settle(tester); + + final handle = tester.ensureSemantics(); + expect(tester.widget(_node('plan')).selected, isTrue); + final visited = tester.getSemantics(_node('plan')).getSemanticsData(); + expect(visited.flagsCollection.isButton, isTrue); + expect(visited.hasAction(SemanticsAction.tap), isTrue); + final unvisited = tester.getSemantics(_node('build')).getSemanticsData(); + expect(unvisited.flagsCollection.isButton, isFalse); + expect(unvisited.hasAction(SemanticsAction.tap), isFalse); + expect(unvisited.label, 'build'); + await tester.tap(_node('plan')); + await tester.pump(); + expect(picked, ['plan']); + + // `build` was never recorded in this run: it is a plain label, not a + // button, and tapping it reports nothing (never a fabricated visit). + await tester.tap(_node('build'), warnIfMissed: false); + await tester.pump(); + expect(picked, ['plan']); + expect( + find.ancestor( + of: _node('build'), + matching: find.byWidgetPredicate( + (widget) => widget is IgnorePointer && widget.ignoring, + ), + ), + findsOneWidget, + ); + handle.dispose(); + }, + ); + + testWidgets('a changed recorded status remeasures instead of keeping a box', ( + tester, + ) async { + await tester.pumpWidget(_materialHost(linearGraph(), _runningRun())); + await _settle(tester); + expect( + tester.widget(_node('build')).recordedStatus, + 'running', + ); + + final changed = _runningRun(); + (changed['steps'] as List)[1] = step( + sequence: 2, + stage: 'build', + status: 'blocked', + ); + await tester.pumpWidget(_materialHost(linearGraph(), changed)); + await _settle(tester); + expect( + tester.widget(_node('build')).recordedStatus, + 'blocked', + ); + expect(find.byType(GraphStageNode), findsNWidgets(5)); + expect(tester.takeException(), isNull); + }); + + testWidgets('a missing or stage-less graph states the server wording', ( + tester, + ) async { + await tester.pumpWidget(_materialHost(null, _finishedRun())); + await tester.pump(); + expect(find.text(runGraphMissing), findsOneWidget); + expect(find.byType(InteractiveViewer), findsNothing); + + await tester.pumpWidget( + _materialHost({'stages': []}, _finishedRun()), + ); + await tester.pump(); + expect(find.text(runGraphMissing), findsOneWidget); + expect(find.byType(InteractiveViewer), findsNothing); + }); + + testWidgets('executed routes keep success-first, error-last order', ( + tester, + ) async { + final graph = { + 'stages': [ + stage('a', edges: {'error': 'b', 'success': 'c'}), + stage('b', edges: {'success': '#failure'}), + stage('c', edges: {'success': '#success'}), + ], + }; + final run = { + 'id': 44, + 'steps': [ + step(sequence: 1, stage: 'a', outcome: 'error', target: 'b'), + step(sequence: 2, stage: 'a', outcome: 'success', target: 'c'), + ], + 'current_stage': 'a', + 'executing': false, + }; + await tester.pumpWidget(_materialHost(graph, run)); + await _settle(tester); + + final layer = tester.widget( + find.byType(RunGraphEdgeLayer), + ); + expect(layer.executedRoutes.map((route) => route.outcome), [ + 'success', + 'error', + ]); + }); + + testWidgets('320px at 2x text re-measures and keeps a deterministic layout', ( + tester, + ) async { + tester.view.physicalSize = const Size(320, 700); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget( + _materialHost( + linearGraph(), + _runningRun(), + scale: 2, + size: const Size(320, 700), + ), + ); + await _settle(tester); + final first = { + for (final element in find.byType(GraphStageNode).evaluate()) + (element.widget as GraphStageNode).node.key: tester.getRect( + find.byWidget(element.widget), + ), + }; + _expectNoOverlaps(tester); + expect(first.values.every((rect) => rect.width <= 320), isTrue); + + await tester.pumpWidget( + _materialHost( + linearGraph(), + _runningRun(), + scale: 2, + size: const Size(320, 700), + ), + ); + await _settle(tester); + final second = { + for (final element in find.byType(GraphStageNode).evaluate()) + (element.widget as GraphStageNode).node.key: tester.getRect( + find.byWidget(element.widget), + ), + }; + expect(second, first); + _expectNoOverlaps(tester); + expect(tester.takeException(), isNull); + }); + + testWidgets('dark Cupertino host keeps native nodes and evidence', ( + tester, + ) async { + final picked = []; + await tester.pumpWidget( + _cupertinoHost(linearGraph(), _runningRun(), onSelected: picked.add), + ); + await _settle(tester); + + expect(find.byType(Card), findsNothing); + expect(find.byType(CupertinoButton), findsNWidgets(5)); + expect(find.text(runGraphExecuted), findsOneWidget); + expect(find.text(runGraphNotExecuted), findsOneWidget); + expect( + tester.widget(_node('plan')).recordedStatus, + 'completed', + ); + expect( + tester.widget(_node('build')).recordedStatus, + 'running', + ); + _expectNoOverlaps(tester); + + await tester.tap(_node('plan')); + await tester.pump(); + expect(picked, ['plan']); + expect(tester.takeException(), isNull); + }); +} diff --git a/app/tool/run_graph_probe.dart b/app/tool/run_graph_probe.dart new file mode 100644 index 00000000..dfb0fe4c --- /dev/null +++ b/app/tool/run_graph_probe.dart @@ -0,0 +1,200 @@ +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/run_graph_view.dart'; + +/// plan -> build -> audit with a taken path that stops at the running build and +/// untaken routes to audit and both terminals. +JsonMap _graph() => { + 'stages': [ + { + 'key': 'plan', + 'type': 'model', + 'edges': {'success': 'build', 'error': '#'}, + 'fallback_error': true, + }, + { + 'key': 'build', + 'type': 'shell', + 'edges': {'success': 'audit', 'error': '#'}, + }, + { + 'key': 'audit', + 'type': 'model', + 'edges': {'success': '#success', 'error': '#failure'}, + }, + ], +}; + +JsonMap _runningRun() { + final started = DateTime.now().toUtc().subtract( + const Duration(minutes: 2, seconds: 5), + ); + return { + 'id': 42, + 'executing': true, + 'current_stage': 'build', + 'steps': [ + { + 'sequence': 1, + 'stage': 'plan', + 'status': 'completed', + 'outcome': 'success', + 'target': 'build', + }, + { + 'sequence': 2, + 'stage': 'build', + 'status': 'running', + 'outcome': '', + 'target': '', + 'started_at': started.toIso8601String(), + }, + ], + }; +} + +JsonMap _finishedRun() => { + 'id': 42, + 'executing': false, + 'current_stage': '', + 'steps': [ + { + 'sequence': 1, + 'stage': 'plan', + 'status': 'completed', + 'outcome': 'success', + 'target': 'build', + }, + { + 'sequence': 2, + 'stage': 'build', + 'status': 'completed', + 'outcome': 'success', + 'target': 'audit', + }, + { + 'sequence': 3, + 'stage': 'audit', + 'status': 'completed', + 'outcome': 'success', + 'target': '#', + }, + ], +}; + +/// Isolated browser fixture for `RunGraphView` only. +/// +/// `style=cupertino` selects the Cupertino host, `dark=1` its dark theme and +/// `scale=2` a real 2x text scale. `case=finished` records a resolved success +/// terminal instead of the running path; `case=missing` omits the graph. A +/// click reports the exact visited stage key; unvisited nodes report nothing. +void main() { + final parameters = Uri.base.queryParameters; + runApp( + _ProbeApp( + cupertino: parameters['style'] == 'cupertino', + dark: parameters['dark'] == '1', + scale: double.tryParse(parameters['scale'] ?? '') ?? 1, + fixture: parameters['case'] ?? 'running', + ), + ); +} + +class _ProbeApp extends StatelessWidget { + const _ProbeApp({ + required this.cupertino, + required this.dark, + required this.scale, + required this.fixture, + }); + + final bool cupertino; + final bool dark; + final double scale; + final String fixture; + + @override + Widget build(BuildContext context) { + final page = _ProbePage( + scale: scale, + graph: fixture == 'missing' ? null : _graph(), + run: fixture == 'finished' ? _finishedRun() : _runningRun(), + ); + if (cupertino) { + return CupertinoApp( + theme: CupertinoThemeData( + brightness: dark ? Brightness.dark : Brightness.light, + ), + home: CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar( + middle: Text('Run graph'), + ), + child: SafeArea(child: page), + ), + ); + } + return MaterialApp( + theme: ThemeData( + platform: TargetPlatform.android, + brightness: Brightness.light, + ), + darkTheme: ThemeData( + platform: TargetPlatform.android, + brightness: Brightness.dark, + ), + themeMode: dark ? ThemeMode.dark : ThemeMode.light, + home: Scaffold( + appBar: AppBar(title: const Text('Run graph')), + body: SafeArea(child: page), + ), + ); + } +} + +class _ProbePage extends StatefulWidget { + const _ProbePage({ + required this.scale, + required this.graph, + required this.run, + }); + + final double scale; + final JsonMap? graph; + final JsonMap run; + + @override + State<_ProbePage> createState() => _ProbePageState(); +} + +class _ProbePageState extends State<_ProbePage> { + String? _selected; + + @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: RunGraphView( + graph: widget.graph, + run: widget.run, + selectedStage: _selected, + onStageSelected: (key) => setState(() => _selected = key), + ), + ), + ), + ], + ), + ); + } +} diff --git a/app/tool/run_graph_probe.mjs b/app/tool/run_graph_probe.mjs new file mode 100644 index 00000000..326c43d3 --- /dev/null +++ b/app/tool/run_graph_probe.mjs @@ -0,0 +1,265 @@ +// Browser acceptance for the isolated RunGraphView fixture. +// +// Serves a probe build (`flutter build web -t tool/run_graph_probe.dart`) on an +// OS-assigned loopback port, drives real headless Chrome, and checks the +// recorded-run evidence: legend wording, visited statuses, the running elapsed +// line, a visited-stage click, an unvisited node doing nothing, and (for the +// finished fixture) no live line plus the resolved terminal's recorded outcome. +// +// PROBE_VARIANT=material|cupertino PROBE_SCHEME=dark|light PROBE_SCALE=1|2 \ +// PROBE_CASE=running|finished PROBE_WIDTH=1280 PROBE_HEIGHT=800 \ +// PROBE_WEB_ROOT= OPENCODE_ARTIFACT_DIR= \ +// node tool/run_graph_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/run_graph_probe'), +); +const variant = process.env.PROBE_VARIANT ?? 'material'; +const scheme = process.env.PROBE_SCHEME ?? 'light'; +const scale = process.env.PROBE_SCALE ?? '1'; +const fixture = process.env.PROBE_CASE ?? 'running'; +const width = Number(process.env.PROBE_WIDTH ?? (scale === '2' ? 320 : 1280)); +const height = Number(process.env.PROBE_HEIGHT ?? (scale === '2' ? 700 : 800)); +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 = `run-graph-${variant}-${scheme}-${scale}x-${fixture}`; +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(), 'run-graph-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 < 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 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((done) => { + const callId = ++id; + pending.set(callId, done); + 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: width < 600, + }, session); + const url = `http://127.0.0.1:${port}/?style=${variant}&dark=${scheme === 'dark' ? 1 : 0}` + + `&scale=${scale}&case=${fixture}`; + const navigation = await send('Page.navigate', { url }, 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}/?style=${variant}`)) { + 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 body = await evaluate('document.body.innerText'); + for (const word of ['Executed', 'Not executed', 'Selected: none']) { + if (!body.includes(word)) throw new Error(`Missing ${word}: ${body}`); + } + if (fixture === 'running' && !body.includes('Current stage build')) { + throw new Error(`Missing live elapsed line: ${body}`); + } + if (fixture === 'finished' && body.includes('Current stage')) { + throw new Error(`Finished run kept a live line: ${body}`); + } + const items = await semantics(); + const labels = items.map((item) => item.label); + const need = (text) => { + if (!labels.some((label) => label.split('\n')[0] === text || label.includes(text))) { + throw new Error(`Missing semantics ${text}: ${JSON.stringify(labels)}`); + } + }; + need('plan'); + if (fixture === 'running') { + if (!labels.some((label) => label.includes('completed'))) { + throw new Error(`Plan status missing: ${JSON.stringify(labels)}`); + } + if (!labels.some((label) => label.includes('success'))) { + throw new Error(`Executed route label missing: ${JSON.stringify(labels)}`); + } + } else if (!labels.some((label) => label.includes('completed'))) { + throw new Error(`Finished plan status missing: ${JSON.stringify(labels)}`); + } + const nodeAt = (key) => items.find((item) => { + const label = item.label; + return label === key || label.startsWith(`${key}\n`) || label.startsWith(`${key} `); + }); + const nodeRect = async (key) => evaluate(`(() => { + const items=[...document.querySelectorAll('flt-semantics')]; + const e=items.find(x=>{const l=(x.getAttribute('aria-label')||x.innerText||'').trim();return l===${JSON.stringify(key)}||l.startsWith(${JSON.stringify(key)}+'\\n')||l.startsWith(${JSON.stringify(key)}+' ');}); + if (!e) return null; + const r=e.getBoundingClientRect(); + return {x:r.x,y:r.y,width:r.width,height:r.height}; + })()`); + const click = async (key) => { + const rect = await nodeRect(key); + if (!rect || rect.width === 0 || rect.height === 0) return false; + const point = { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 }; + await send('Input.dispatchMouseEvent', { + type: 'mousePressed', ...point, button: 'left', clickCount: 1, + }, session); + await send('Input.dispatchMouseEvent', { + type: 'mouseReleased', ...point, button: 'left', clickCount: 1, + }, session); + await delay(800); + return true; + }; + const drag = async (dx) => { + const start = { x: width / 2, y: height / 2 }; + 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, + button: 'left', buttons: 1, + }, session); + await delay(40); + } + await send('Input.dispatchMouseEvent', { + type: 'mouseReleased', x: start.x + dx, y: start.y, + button: 'left', clickCount: 1, + }, session); + await delay(700); + }; + const capture = async (name, w, h) => { + await send('Emulation.setDeviceMetricsOverride', { + width: w, height: h, deviceScaleFactor: 1, mobile: w < 600, + }, session); + await delay(2200); + const data = (await send('Page.captureScreenshot', { + format: 'png', captureBeyondViewport: false, + }, session)).result.data; + const file = `${prefix}-${name}.png`; + await writeFile(`${artifactDir}/${file}`, Buffer.from(data, 'base64')); + return file; + }; + const captures = [await capture('initial', width, height)]; + if (!nodeAt('plan')) throw new Error(`plan node absent: ${JSON.stringify(labels)}`); + if (!await click('plan')) throw new Error('Could not click plan'); + let after = await evaluate('document.body.innerText'); + if (!after.includes('Selected: plan')) throw new Error(`plan click missed: ${after}`); + const current = (await semantics()).find((item) => item.selected === 'true'); + if (!current?.label.startsWith('plan')) { + throw new Error(`Selection not announced: ${JSON.stringify(current)}`); + } + // A content-sized graph need not fit a 320px viewport. Pan with a real drag + // until the remaining recorded stage is actually exposed, then check it. + let panned = await semantics(); + for (let pass = 0; pass < 8; pass++) { + const seen = panned.map((item) => item.label); + if (seen.some((label) => label.includes('build') && label.includes('running'))) break; + await drag(-220); + panned = await semantics(); + } + if (fixture === 'running' && + !panned.some((item) => item.label.includes('build') && item.label.includes('running'))) { + throw new Error(`Build status missing after pan: ${JSON.stringify(panned)}`); + } + if (fixture === 'finished' && + !panned.some((item) => item.label.startsWith('Success') && item.label.includes('success'))) { + throw new Error(`Resolved success terminal missing after pan: ${JSON.stringify(panned)}`); + } + const auditRect = fixture === 'running' ? await nodeRect('audit') : null; + if (auditRect) { + await click('audit'); + after = await evaluate('document.body.innerText'); + if (!after.includes('Selected: plan')) { + throw new Error(`Unvisited node changed selection: ${after}`); + } + } + if (fixture === 'finished') { + if (await click('Success')) { + after = await evaluate('document.body.innerText'); + if (!after.includes('Selected: plan')) { + throw new Error(`Terminal fabricated a visit: ${after}`); + } + } + } + captures.push(await capture('final', width, height)); + if (width > 400) captures.push(await capture('phone', 320, 700)); + console.log(JSON.stringify({ variant, scheme, scale, fixture, labels, 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((done) => { + server.close(done); + server.closeAllConnections(); + }); + await rm(profile, { recursive: true, force: true }); +}