merge(app): land run-mode graph evidence component

This commit is contained in:
2026-10-21 23:42:49 +01:00
7 changed files with 1916 additions and 0 deletions
@@ -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<EdgeRoute> executedRoutes;
final List<EdgeRoute> 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<EdgeRoute> executedRoutes;
final List<EdgeRoute> 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<GraphNode> nodes;
final GraphLayout layout;
final GraphRouting routing;
final RunGraphState state;
final GraphCanvasStyle style;
final Map<String, String?> recordedStatuses;
final ValueChanged<String> onStageSelected;
final String? selectedStage;
@override
Widget build(BuildContext context) {
final nodesByKey = <String, GraphNode>{
for (final node in nodes) node.key: node,
};
final executed = <EdgeRoute>[];
final untaken = <EdgeRoute>[];
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<String> 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<GraphNode> nodes;
final List<GraphEdge> edges;
final double maxNodeWidth;
final TextStyle labelStyle;
final Map<String, String?> 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),
),
],
),
),
);
}
@@ -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<String> onStageSelected;
final String? selectedStage;
/// Injectable clock for deterministic elapsed labels; defaults to now.
final DateTime Function()? now;
@override
State<RunGraphView> createState() => _RunGraphViewState();
}
class _RunGraphViewState extends State<RunGraphView> {
final Map<String, Size> _nodeSizes = {};
final Map<String, Size> _labelSizes = {};
final Map<String, String?> _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<String, Size> 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<GraphNode> nodes,
List<GraphEdge> edges,
) {
final extents = <String, NodeExtent>{};
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 = <int, LabelExtent>{};
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<String, List<JsonMap>> 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 <GraphNode>[] : graphNodes(graph);
final edges = graph == null ? const <GraphEdge>[] : 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>().map(JsonMap.from).toList()
: const <JsonMap>[];
final visits = visitsByStage(steps);
final statuses = <String, String?>{
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';
}