Merge branch 'graph-stage-popover'

This commit is contained in:
2026-12-03 23:41:55 +00:00
28 changed files with 3024 additions and 380 deletions
@@ -0,0 +1,115 @@
import '../../../core/api_gateway.dart';
import '../../pipelines/pipeline_format.dart';
import '../../runs/domain/run_tokens.dart';
import 'stage_visits.dart';
/// What one run recorded for one stage, for the graph's stage popover.
///
/// Read from the run detail's own steps only: a stage the run never visited
/// has [visits] 0 and nothing else, and nothing is estimated.
class StageRunFacts {
const StageRunFacts({
required this.visits,
this.status,
this.duration,
this.usage,
this.verdict,
this.handoff,
this.failure,
});
/// How many recorded visits the stage has.
final int visits;
/// The latest visit's recorded status word.
final String? status;
/// The latest visit's duration, when both timestamps were recorded.
final String? duration;
/// Reported tokens and cost summed over every visit (`12.4k tok · $0.31`).
final String? usage;
/// The latest visit's recorded verdict: `option: reason`.
final String? verdict;
/// The first non-blank line of the latest visit's handoff output.
final String? handoff;
/// The latest visit's recorded diagnostic when it failed.
final String? failure;
}
/// The facts [run] recorded for [stageKey].
StageRunFacts stageRunFacts(JsonMap run, String stageKey) {
final steps = run['steps'];
final list = steps is List
? steps.whereType<Map>().map(JsonMap.from).toList()
: const <JsonMap>[];
final visits = visitsByStage(list)[stageKey] ?? const <JsonMap>[];
if (visits.isEmpty) return const StageRunFacts(visits: 0);
final latest = visits.last;
final status = _text(latest['status']);
final seconds = durationSeconds(
_text(latest['started_at']),
_text(latest['finished_at']),
);
var tokens = 0;
var tokensKnown = false;
var cost = 0.0;
var costKnown = false;
for (final visit in visits) {
final usage = stageTokenUsage(visit);
if (usage == null) continue;
tokens += usage.total;
tokensKnown = true;
final visitCost = usage.cost;
if (visitCost != null) {
cost += visitCost;
costKnown = true;
}
}
final verdict = latest['verdict'];
String? verdictText;
if (verdict is Map) {
final option = _text(verdict['option']);
final reason = _firstLine(verdict['reason']);
verdictText = [?option, ?reason].join(': ');
if (verdictText.isEmpty) verdictText = null;
}
final failed = status != null && _failed(status);
return StageRunFacts(
visits: visits.length,
status: status,
duration: seconds == null ? null : formatDuration(seconds),
usage: tokensKnown || costKnown
? [
if (tokensKnown) '${formatTokenCount(tokens)} tok',
if (costKnown) '\$${cost.toStringAsFixed(2)}',
].join(' · ')
: null,
verdict: verdictText,
handoff: _firstLine(latest['output']),
failure: failed ? _firstLine(latest['diagnostic']) : null,
);
}
bool _failed(String status) {
final word = status.trim().toLowerCase();
return word == 'failed' || word == 'error' || word == 'blocked';
}
String? _text(dynamic value) {
final text = '${value ?? ''}'.trim();
return text.isEmpty ? null : text;
}
String? _firstLine(dynamic value) {
final text = _text(value);
if (text == null) return null;
for (final line in text.split('\n')) {
final trimmed = line.trim().replaceFirst(RegExp(r'^#+\s*'), '');
if (trimmed.isNotEmpty) return trimmed;
}
return null;
}
@@ -0,0 +1,246 @@
import 'dart:convert';
import 'check_stage.dart';
import 'graph_definition.dart';
import 'graph_protocol.dart';
import 'stage_definition.dart';
/// The kind of stage a popover names in its type chip.
enum StageKind { model, check, deliveryGate, findings, human, other, terminal }
/// The tool set a model stage runs with when it declares no `tools` block: the
/// server's legacy bundle (`legacyTools` in `internal/stage/tools.go`).
const List<String> defaultStageTools = [
'read',
'glob',
'grep',
'edit',
'shell',
];
/// One declared outgoing route: `outcome → target`.
typedef StageRoute = ({String outcome, String target});
/// A compact, read-only digest of one stage declaration for the graph's stage
/// popover. Pure data: built from the stage JSON the definition graph carries;
/// a field the declaration omits stays empty rather than guessed.
class StageSummary {
const StageSummary({
required this.key,
required this.kind,
required this.typeLabel,
this.meta = const [],
this.tools = const [],
this.toolsDefault = false,
this.permissions = const [],
this.skills = const [],
this.prompt,
this.commands = const [],
this.gate = const [],
this.limits = const [],
this.routes = const [],
});
final String key;
final StageKind kind;
/// The type chip's word: `Model`, `Check`, `Findings gate`, ...
final String typeLabel;
/// Short configuration chips in reading order: harness, model, effort,
/// timeout, retries, budget.
final List<String> meta;
/// The model stage's tools, in declared order.
final List<String> tools;
/// True when [tools] is the server default because no block was declared.
final bool toolsDefault;
/// Permission allow-lists as `edit: path, path` lines.
final List<String> permissions;
final List<String> skills;
/// A model stage's prompt or a human stage's operator instructions.
final String? prompt;
/// A check stage's commands, one per line.
final List<String> commands;
/// A findings gate's severity and origin facts.
final List<String> gate;
/// Limit facts: `max 3 visits`, `on fail`, `exhausted: decide`.
final List<String> limits;
/// Declared routes, for a terminal the routes into it.
final List<StageRoute> routes;
}
/// The digest of [key] in [graph], or null when the version does not declare
/// it (a terminal is summarised by its incoming routes instead).
StageSummary? stageSummaryFor(dynamic graph, String key) {
if (isTerminalTarget(key)) {
return StageSummary(
key: key,
kind: StageKind.terminal,
typeLabel: 'End',
routes: [
for (final edge in graphEdges(graph))
if (edge.target == key)
(outcome: edge.label, target: nodeDisplayLabel(edge.source)),
],
);
}
final stage = stageDefinitionFor(graph, key);
if (stage == null) return null;
final type = effectiveStageType(stage['type']).trim();
final kind = switch (type) {
'model' => StageKind.model,
'check' => isDeliveryGate(stage) ? StageKind.deliveryGate : StageKind.check,
'findings' => StageKind.findings,
'human' => StageKind.human,
_ => StageKind.other,
};
final configs = _strings(stage['configs']);
final blocks = _strings(stage['blocks']);
final declaredTools = blocks['tools'];
final tools = kind != StageKind.model
? const <String>[]
: declaredTools == null
? defaultStageTools
: _lines(declaredTools);
final prompt = (blocks['prompt'] ?? _text(stage['prompt'])).trim();
return StageSummary(
key: key,
kind: kind,
typeLabel: stageKindLabel(kind, type),
meta: _meta(kind, configs),
tools: tools,
toolsDefault: kind == StageKind.model && declaredTools == null,
permissions: _permissions(blocks['permissions']),
skills: _lines(blocks['skills'] ?? ''),
prompt:
(kind == StageKind.model ||
kind == StageKind.human ||
kind == StageKind.other) &&
prompt.isNotEmpty
? prompt
: null,
commands: kind == StageKind.check || kind == StageKind.deliveryGate
? checkCommands(stage)
: const [],
gate: kind == StageKind.findings
? [
'min severity ${configs['severity'] ?? 'important'}',
'origin ${configs['origin'] ?? 'introduced'}',
]
: const [],
limits: _limits(stage['limits']),
routes: [
for (final edge in graphEdges({
'stages': [stage],
}))
(outcome: edge.label, target: nodeDisplayLabel(edge.target)),
],
);
}
/// The type chip's word for [kind]; an unknown type keeps its own name.
String stageKindLabel(StageKind kind, [String type = '']) => switch (kind) {
StageKind.model => 'Model',
StageKind.check => 'Check',
StageKind.deliveryGate => 'Delivery gate',
StageKind.findings => 'Findings gate',
StageKind.human => 'Human',
StageKind.terminal => 'End',
StageKind.other =>
type.isEmpty ? 'Stage' : '${type[0].toUpperCase()}${type.substring(1)}',
};
/// A model id without its vendor prefix and date stamp:
/// `anthropic/claude-sonnet-4-5-20250929` reads `claude-sonnet-4-5`.
String shortModelName(String model) {
var name = model.trim();
final slash = name.lastIndexOf('/');
if (slash >= 0) name = name.substring(slash + 1);
return name.replaceFirst(RegExp(r'-\d{8}$'), '');
}
List<String> _meta(StageKind kind, Map<String, String> configs) {
String? config(String key) {
final value = configs[key]?.trim();
return value == null || value.isEmpty ? null : value;
}
final harness = config('harness');
final provider = config('provider');
final model = config('model');
final effort = config('reasoning_effort');
final timeout = config('timeout') ?? config('command_timeout');
final retries = config('retries');
final budget = config('budget_usd');
final tokens = config('budget_tokens');
return [
?harness,
if (model != null)
shortModelName(model)
else if (provider != null && harness == null)
provider,
if (effort != null) '$effort effort',
if (timeout != null) '$timeout timeout',
if (retries != null) retries == '1' ? '1 retry' : '$retries retries',
if (budget != null) '\$$budget budget',
if (tokens != null) '$tokens tokens max',
if (config('keep_going') == 'true') 'keep going',
];
}
List<String> _permissions(String? text) {
if (text == null || text.trim().isEmpty) return const [];
try {
final decoded = jsonDecode(text);
if (decoded is! Map) return [text.trim()];
return [
for (final entry in decoded.entries)
'${entry.key}: ${entry.value is List && (entry.value as List).isEmpty
? 'denied'
: entry.value is List
? (entry.value as List).join(', ')
: _text(entry.value)}',
];
} on FormatException {
return [text.trim()];
}
}
List<String> _limits(dynamic limits) {
if (limits is! Map) return const [];
final maxVisits = int.tryParse(_text(limits['max_visits']));
final on = limits['on'];
final exhausted = _text(limits['on_exhausted']).trim();
return [
if (maxVisits != null && maxVisits > 0)
maxVisits == 1 ? 'max 1 visit' : 'max $maxVisits visits',
if (on is List && on.isNotEmpty) 'on ${on.map(_text).join(', ')}',
if (exhausted.isNotEmpty) 'when exhausted: $exhausted',
];
}
Map<String, String> _strings(dynamic value) => value is Map
? {for (final entry in value.entries) _text(entry.key): _text(entry.value)}
: const {};
List<String> _lines(String text) => [
for (final line in text.split('\n'))
if (line.trim().isNotEmpty) line.trim(),
];
String _text(dynamic value) {
if (value == null) return '';
if (value is num && value == value.roundToDouble()) {
return value.toInt().toString();
}
return '$value';
}
@@ -0,0 +1,145 @@
import 'package:flutter/foundation.dart' show listEquals;
import 'package:flutter/material.dart';
import '../routing/route_models.dart';
import 'graph_edge_layer.dart';
/// The run graph's route painting: the landed `GraphEdgePainter` geometry
/// (paths and arrowheads) with the two route classes run evidence needs on one
/// passive layer. 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);
}
@@ -0,0 +1,89 @@
import 'package:flutter/material.dart';
import '../routing/route_models.dart';
import 'graph_edge_layer.dart';
/// Softly emphasises every route into or out of one stage (the stage whose
/// popover is open): a translucent wider stroke under the plain edges' own
/// lines. Quieter than a hovered edge, which still paints above it.
class StageEdgesHighlightPainter extends CustomPainter {
StageEdgesHighlightPainter({
required this.routes,
required this.color,
required this.strokeWidth,
});
final List<EdgeRoute> routes;
final Color color;
final double strokeWidth;
@override
void paint(Canvas canvas, Size size) {
if (routes.isEmpty) return;
final geometry = GraphEdgePainter(
routes: routes,
color: color,
strokeWidth: strokeWidth,
);
final halo = Paint()
..color = color.withValues(alpha: 0.16)
..strokeWidth = strokeWidth * 5
..style = PaintingStyle.stroke
..strokeJoin = StrokeJoin.round
..strokeCap = StrokeCap.round;
final line = Paint()
..color = color.withValues(alpha: 0.7)
..strokeWidth = strokeWidth * 1.5
..style = PaintingStyle.stroke
..strokeJoin = StrokeJoin.round;
for (final route in routes) {
if (route.points.length < 2) continue;
final path = geometry.linePath(route);
canvas.drawPath(path, halo);
canvas.drawPath(path, line);
}
}
@override
bool hitTest(Offset position) => false;
@override
bool shouldRepaint(StageEdgesHighlightPainter oldDelegate) =>
oldDelegate.color != color ||
oldDelegate.strokeWidth != strokeWidth ||
oldDelegate.routes.length != routes.length ||
!_same(oldDelegate.routes, routes);
static bool _same(List<EdgeRoute> a, List<EdgeRoute> b) {
for (var i = 0; i < a.length; i++) {
if (a[i] != b[i]) return false;
}
return true;
}
}
/// The soft highlight for [stage]'s routes, or nothing when none is open.
Widget graphStageEdgesHighlight({
required BuildContext context,
required GraphRouting routing,
required String? stage,
required double edgeWidth,
}) {
if (stage == null) return const SizedBox.shrink();
final routes = [
for (final route in routing.routes)
if (route.source == stage || route.target == stage) route,
];
if (routes.isEmpty) return const SizedBox.shrink();
return IgnorePointer(
child: CustomPaint(
key: ValueKey('graph-stage-edges:$stage'),
size: Size(routing.width, routing.height),
painter: StageEdgesHighlightPainter(
routes: routes,
color: Theme.of(context).colorScheme.primary,
strokeWidth: edgeWidth,
),
),
);
}
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import '../../../ui/adaptive/glass_pill.dart';
import 'graph_viewport_controller.dart';
import 'graph_viewport_scope.dart';
/// The fit control's web wording (`Fit graph to view`).
const String graphFitLabel = 'Fit graph to view';
@@ -46,6 +47,7 @@ class GraphViewport extends StatefulWidget {
}
class _GraphViewportState extends State<GraphViewport> {
final GlobalKey _viewportKey = GlobalKey(debugLabel: 'graph-viewport-box');
Size? _scheduledViewport;
Size? _scheduledContent;
@@ -97,20 +99,26 @@ class _GraphViewportState extends State<GraphViewport> {
fit: StackFit.expand,
children: [
Positioned.fill(
child: InteractiveViewer(
key: const Key('graph-viewport'),
transformationController: widget.controller.transformation,
constrained: false,
// The graph owns its own bounds (fit and the visible-pan clamp),
// so the viewer must not impose a second, cover-the-viewport
// boundary that would fight the fit scale.
boundaryMargin: const EdgeInsets.all(double.infinity),
minScale: widget.controller.minScale,
maxScale: widget.controller.maxScale,
clipBehavior: Clip.hardEdge,
child: SizedBox.fromSize(
size: widget.contentSize,
child: widget.child,
key: _viewportKey,
child: GraphViewportScope(
transform: widget.controller.transformation,
viewportKey: _viewportKey,
viewportSize: viewport,
child: InteractiveViewer(
key: const Key('graph-viewport'),
transformationController: widget.controller.transformation,
constrained: false,
// The graph owns its own bounds (fit and the visible-pan clamp),
// so the viewer must not impose a second, cover-the-viewport
// boundary that would fight the fit scale.
boundaryMargin: const EdgeInsets.all(double.infinity),
minScale: widget.controller.minScale,
maxScale: widget.controller.maxScale,
clipBehavior: Clip.hardEdge,
child: SizedBox.fromSize(
size: widget.contentSize,
child: widget.child,
),
),
),
),
@@ -0,0 +1,34 @@
import 'package:flutter/widgets.dart';
/// What a graph canvas can learn about the pan/zoom viewport around it: the
/// transform it follows and the visible box it must stay inside.
///
/// [GraphViewport] provides it; a canvas drawn without one (a still preview,
/// a test) has no scope and uses its overlay's bounds instead.
class GraphViewportScope extends InheritedWidget {
const GraphViewportScope({
super.key,
required this.transform,
required this.viewportKey,
required this.viewportSize,
required super.child,
});
/// Notifies on every pan, zoom and fit.
final Listenable transform;
/// The key of the visible viewport box, for its on-screen origin.
final GlobalKey viewportKey;
/// The visible viewport's extent.
final Size viewportSize;
static GraphViewportScope? maybeOf(BuildContext context) =>
context.dependOnInheritedWidgetOfExactType<GraphViewportScope>();
@override
bool updateShouldNotify(GraphViewportScope oldWidget) =>
oldWidget.transform != transform ||
oldWidget.viewportKey != viewportKey ||
oldWidget.viewportSize != viewportSize;
}
@@ -1,21 +1,28 @@
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../domain/graph_definition.dart';
import '../domain/stage_summary.dart';
import '../layout/layout_models.dart';
import '../painting/graph_edge_layer.dart';
import '../painting/stage_edges_highlight.dart';
import '../routing/route_models.dart';
import 'graph_canvas_style.dart';
import 'graph_edge_hover.dart';
import 'graph_stage_node.dart';
import 'graph_stage_popover.dart';
import 'stage_popover_card.dart';
/// The measured definition canvas at any viewport size and selection.
///
/// Used by both the inline [GraphViewport] and the expanded presentation: the
/// passive edge layer paints behind the native nodes and outcome labels, and
/// every node reports selection through [onSelected].
/// passive edge layer paints behind the native nodes and outcome labels.
/// Tapping a node opens its stage popover (the declaration at a glance); the
/// popover's "Open definition" reports the node through [onSelected].
class DefinitionGraphCanvas extends StatelessWidget {
const DefinitionGraphCanvas({
super.key,
required this.graph,
required this.nodes,
required this.layout,
required this.routing,
@@ -24,6 +31,8 @@ class DefinitionGraphCanvas extends StatelessWidget {
required this.onSelected,
});
/// The definition the nodes came from, for each stage's declaration.
final JsonMap graph;
final List<GraphNode> nodes;
final GraphLayout layout;
final GraphRouting routing;
@@ -37,12 +46,34 @@ class DefinitionGraphCanvas extends StatelessWidget {
for (final node in nodes) node.key: node,
};
final size = Size(routing.width, routing.height);
return GraphEdgeHover(
layout: layout,
routing: routing,
describe: describeGraphEdge,
builder: (context, highlighted, select) =>
_canvas(context, nodesByKey, size, highlighted, select),
return GraphStagePopover(
nodeRects: {
for (final box in layout.nodes)
box.key: Rect.fromLTWH(box.x, box.y, box.width, box.height),
},
cardBuilder: (context, stage, close) => StagePopoverCard(
label: nodesByKey[stage]?.label ?? stage,
summary: stageSummaryFor(graph, stage),
onClose: close,
onOpenDefinition: () {
close();
onSelected(stage);
},
),
builder: (context, open, toggle) => GraphEdgeHover(
layout: layout,
routing: routing,
describe: describeGraphEdge,
builder: (context, highlighted, select) => _canvas(
context,
nodesByKey,
size,
highlighted,
select,
open,
toggle,
),
),
);
}
@@ -52,6 +83,8 @@ class DefinitionGraphCanvas extends StatelessWidget {
Size size,
int? highlighted,
ValueChanged<int> select,
String? open,
ValueChanged<String> toggle,
) {
return Stack(
clipBehavior: Clip.none,
@@ -66,6 +99,14 @@ class DefinitionGraphCanvas extends StatelessWidget {
strokeWidth: style.edgeWidth,
),
),
Positioned.fill(
child: graphStageEdgesHighlight(
context: context,
routing: routing,
stage: open,
edgeWidth: style.edgeWidth,
),
),
Positioned.fill(
child: graphEdgeHighlight(
context: context,
@@ -83,8 +124,8 @@ class DefinitionGraphCanvas extends StatelessWidget {
height: box.height,
child: GraphStageNode(
node: nodesByKey[box.key]!,
selected: box.key == selectedStage,
onSelected: onSelected,
selected: box.key == selectedStage || box.key == open,
onSelected: toggle,
),
),
for (final label in routing.labels)
@@ -176,6 +176,7 @@ class _DefinitionGraphViewState extends State<DefinitionGraphView> {
contentSize: size,
onExpand: () => _openExpanded(nodes, layout, routing, size),
child: DefinitionGraphCanvas(
graph: widget.graph,
nodes: nodes,
layout: layout,
routing: routing,
@@ -216,6 +217,7 @@ class _DefinitionGraphViewState extends State<DefinitionGraphView> {
selectedStage: widget.selectedStage,
onSelected: widget.onSelected,
canvasBuilder: (context, selected, onSelected) => DefinitionGraphCanvas(
graph: widget.graph,
nodes: nodes,
layout: layout,
routing: routing,
@@ -0,0 +1,271 @@
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../../../ui/theme/app_design_tokens.dart';
import '../viewport/graph_viewport_scope.dart';
import 'stage_popover_position.dart';
/// Builds the canvas with [openStage] (or null) and the node tap handler.
typedef GraphStagePopoverCanvasBuilder =
Widget Function(
BuildContext context,
String? openStage,
ValueChanged<String> toggle,
);
/// Builds one stage's popover content; [close] dismisses it.
typedef GraphStagePopoverCardBuilder =
Widget Function(BuildContext context, String stage, VoidCallback close);
/// Below this viewport width (or height) the card cannot sit beside a node
/// with room to read, so the stage opens in a bottom sheet instead.
const double graphStagePopoverMinWidth = 440;
const double graphStagePopoverMinHeight = 300;
/// A stage popover over a graph canvas: tapping (or pressing Enter on) a node
/// opens a small card anchored to it, with a nub pointing at the node.
///
/// The card is built only while open, in the overlay, and lays out against
/// the live pan/zoom transform so it follows its node; it stays inside the
/// viewport. A tap outside it (a tap, not a pan: a drag still pans the graph
/// under it), Escape, or tapping the same node again closes it. On a narrow
/// or short viewport the same content opens in a bottom sheet instead.
class GraphStagePopover extends StatefulWidget {
const GraphStagePopover({
super.key,
required this.nodeRects,
required this.cardBuilder,
required this.builder,
});
/// Every openable node's box in canvas (graph) space.
final Map<String, Rect> nodeRects;
final GraphStagePopoverCardBuilder cardBuilder;
final GraphStagePopoverCanvasBuilder builder;
@override
State<GraphStagePopover> createState() => _GraphStagePopoverState();
}
class _GraphStagePopoverState extends State<GraphStagePopover> {
final OverlayPortalController _portal = OverlayPortalController();
final GlobalKey _canvasKey = GlobalKey(debugLabel: 'graph-popover-canvas');
final GlobalKey _cardKey = GlobalKey(debugLabel: 'graph-popover-card');
final FocusNode _cardFocus = FocusNode(debugLabel: 'graph-stage-popover');
FocusNode? _returnFocus;
String? _open;
bool _routed = false;
final Map<int, Offset> _downs = {};
@override
void didUpdateWidget(GraphStagePopover oldWidget) {
super.didUpdateWidget(oldWidget);
final open = _open;
if (open != null && !widget.nodeRects.containsKey(open)) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _close();
});
}
}
@override
void dispose() {
_unroute();
_cardFocus.dispose();
super.dispose();
}
bool _useSheet() {
final scope = GraphViewportScope.maybeOf(context);
final size = scope?.viewportSize ?? MediaQuery.sizeOf(context);
return size.width < graphStagePopoverMinWidth ||
size.height < graphStagePopoverMinHeight;
}
void _toggle(String stage) {
if (_open == stage) {
_close();
return;
}
if (!widget.nodeRects.containsKey(stage)) return;
if (Overlay.maybeOf(context) == null || _useSheet()) {
_openSheet(stage);
return;
}
_returnFocus ??= FocusManager.instance.primaryFocus;
setState(() => _open = stage);
_portal.show();
_route();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted && _open != null) _cardFocus.requestFocus();
});
}
void _close() {
if (_open == null) return;
final hadFocus = _cardFocus.hasFocus;
setState(() => _open = null);
_portal.hide();
_unroute();
final back = _returnFocus;
_returnFocus = null;
if (hadFocus && back != null && back.context != null) back.requestFocus();
}
Future<void> _openSheet(String stage) {
return showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
showDragHandle: true,
useSafeArea: true,
constraints: BoxConstraints(
maxHeight: MediaQuery.sizeOf(context).height * 0.85,
),
builder: (sheet) => Padding(
key: const Key('graph-stage-sheet'),
padding: const EdgeInsets.only(bottom: 8),
child: widget.cardBuilder(
sheet,
stage,
// Synchronous, so an action that pops or pushes next (Open visit
// from a full-screen graph page) acts on the page under the sheet.
() => Navigator.of(sheet).pop(),
),
),
);
}
// A global route sees every pointer while the card is open: a tap (down and
// up within touch slop) outside the card and outside its own node closes
// it; a drag never does, so panning keeps the card on its node.
void _route() {
if (_routed) return;
GestureBinding.instance.pointerRouter.addGlobalRoute(_onPointer);
_routed = true;
}
void _unroute() {
if (!_routed) return;
GestureBinding.instance.pointerRouter.removeGlobalRoute(_onPointer);
_routed = false;
_downs.clear();
}
void _onPointer(PointerEvent event) {
if (event is PointerDownEvent) {
_downs[event.pointer] = event.position;
} else if (event is PointerCancelEvent) {
_downs.remove(event.pointer);
} else if (event is PointerUpEvent) {
final down = _downs.remove(event.pointer);
if (down == null) return;
if ((event.position - down).distance > kTouchSlop) return;
if (_contains(_cardKey, event.position) || _onOpenNode(event.position)) {
return;
}
_close();
}
}
bool _contains(GlobalKey key, Offset global) {
final box = key.currentContext?.findRenderObject();
if (box is! RenderBox || !box.attached || !box.hasSize) return false;
return (Offset.zero & box.size).contains(box.globalToLocal(global));
}
bool _onOpenNode(Offset global) {
final rect = widget.nodeRects[_open];
final box = _canvasKey.currentContext?.findRenderObject();
if (rect == null || box is! RenderBox || !box.attached) return false;
return rect.contains(box.globalToLocal(global));
}
RenderBox? _box(GlobalKey key) {
final box = key.currentContext?.findRenderObject();
return box is RenderBox ? box : null;
}
@override
Widget build(BuildContext context) {
final canvas = KeyedSubtree(
key: _canvasKey,
child: widget.builder(context, _open, _toggle),
);
if (Overlay.maybeOf(context) == null) return canvas;
return OverlayPortal(
controller: _portal,
overlayChildBuilder: _overlay,
child: canvas,
);
}
Widget _overlay(BuildContext context) {
final stage = _open;
final rect = stage == null ? null : widget.nodeRects[stage];
if (stage == null || rect == null) return const SizedBox.shrink();
final scope = GraphViewportScope.maybeOf(context);
final surface = stagePopoverSurface(context);
return StagePopoverPosition(
key: const Key('graph-stage-popover'),
anchorBox: () => _box(_canvasKey),
anchorRect: rect,
boundsBox: () => scope == null ? null : _box(scope.viewportKey),
boundsSize: scope?.viewportSize,
safeArea: MediaQuery.paddingOf(this.context),
relayout: scope?.transform,
fill: surface.fill,
border: surface.border,
radius: surface.radius,
elevation: surface.elevation,
shadowColor: surface.shadow,
child: Focus(
focusNode: _cardFocus,
onKeyEvent: (node, event) {
if (event is KeyDownEvent &&
event.logicalKey == LogicalKeyboardKey.escape) {
_close();
return KeyEventResult.handled;
}
return KeyEventResult.ignored;
},
child: FocusTraversalGroup(
child: Material(
key: _cardKey,
color: surface.fill,
elevation: surface.elevation,
shadowColor: surface.shadow,
shape: RoundedRectangleBorder(
side: surface.border,
borderRadius: BorderRadius.circular(surface.radius),
),
clipBehavior: Clip.antiAlias,
child: widget.cardBuilder(context, stage, _close),
),
),
),
);
}
}
/// The popover's surface in the current design: Classic floats a raised card
/// with a hairline; a flat design (Terminal, Paper, Compact) draws its own
/// panel fill and frame with no shadow, at the design's corner radius.
({Color fill, BorderSide border, double radius, double elevation, Color shadow})
stagePopoverSurface(BuildContext context) {
final theme = Theme.of(context);
final colors = theme.colorScheme;
final tokens = AppDesignTokens.of(context);
final flat = tokens.flat;
return (
fill: flat
? tokens.panelFill(colors, colors.surfaceContainer)
: colors.surfaceContainerHigh,
border:
tokens.frameSide ??
BorderSide(color: colors.outlineVariant.withValues(alpha: 0.7)),
radius: tokens.radius ?? 14,
elevation: flat ? 0 : (theme.popupMenuTheme.elevation ?? 3).toDouble() + 3,
shadow: theme.popupMenuTheme.shadowColor ?? colors.shadow,
);
}
@@ -1,158 +1,22 @@
import 'package:flutter/foundation.dart' show listEquals;
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../domain/graph_definition.dart';
import '../domain/run_graph_state.dart';
import '../domain/stage_run_facts.dart';
import '../domain/stage_summary.dart';
import '../layout/layout_models.dart';
import '../painting/graph_edge_layer.dart';
import '../painting/run_graph_edge_layer.dart';
import '../painting/stage_edges_highlight.dart';
import '../routing/route_models.dart';
import 'graph_canvas_style.dart';
import 'graph_edge_hover.dart';
import 'graph_stage_node.dart';
import 'measured_child.dart';
import 'graph_stage_popover.dart';
import 'run_graph_parts.dart';
import 'stage_popover_card.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);
}
export '../painting/run_graph_edge_layer.dart';
export 'run_graph_parts.dart';
/// The run canvas: split route classes behind status-bearing native nodes, with
/// outcome labels only for routes the run actually took.
@@ -160,9 +24,16 @@ class RunGraphEdgePainter extends CustomPainter {
/// [layout] and [routing] are the caller's measured geometry. The canvas never
/// changes them and never assumes a node size; the caller supplies the pan/zoom
/// viewport around this content.
///
/// Tapping a stage opens its popover: the declaration with what the run
/// recorded for it. "Open visit" reports a visited stage through
/// [onStageSelected]; "Open definition" reports it through [onOpenDefinition].
class RunGraphCanvas extends StatelessWidget {
const RunGraphCanvas({
super.key,
required this.graph,
required this.run,
required this.onOpenDefinition,
required this.nodes,
required this.layout,
required this.routing,
@@ -173,6 +44,10 @@ class RunGraphCanvas extends StatelessWidget {
this.selectedStage,
});
/// The run's pinned definition and the run detail, for the popover.
final JsonMap graph;
final JsonMap run;
final ValueChanged<String> onOpenDefinition;
final List<GraphNode> nodes;
final GraphLayout layout;
final GraphRouting routing;
@@ -204,6 +79,63 @@ class RunGraphCanvas extends StatelessWidget {
route,
taken: state.routeOrder(route.source, route.outcome, route.target).length,
);
return GraphStagePopover(
nodeRects: {
for (final box in layout.nodes)
if (!(nodesByKey[box.key]?.terminal ?? true))
box.key: Rect.fromLTWH(box.x, box.y, box.width, box.height),
},
cardBuilder: (context, stage, close) =>
_card(nodesByKey[stage]?.label ?? stage, stage, close),
builder: (context, open, toggle) => _hover(
context,
nodesByKey,
executed,
untaken,
executedIds,
size,
activeStage,
executedColor,
describe,
open,
toggle,
),
);
}
Widget _card(String label, String stage, VoidCallback close) {
final visited = state.isStageVisited(stage);
return StagePopoverCard(
label: label,
summary: stageSummaryFor(graph, stage),
facts: stageRunFacts(run, stage),
onClose: close,
onOpenDefinition: () {
close();
onOpenDefinition(stage);
},
onOpenVisit: !visited
? null
: () {
close();
onStageSelected(stage);
},
);
}
Widget _hover(
BuildContext context,
Map<String, GraphNode> nodesByKey,
List<EdgeRoute> executed,
List<EdgeRoute> untaken,
Set<int> executedIds,
Size size,
String? activeStage,
Color executedColor,
String Function(EdgeRoute) describe,
String? open,
ValueChanged<String> toggle,
) {
return GraphEdgeHover(
layout: layout,
routing: routing,
@@ -221,6 +153,14 @@ class RunGraphCanvas extends StatelessWidget {
strokeWidth: style.edgeWidth,
),
),
Positioned.fill(
child: graphStageEdgesHighlight(
context: context,
routing: routing,
stage: open,
edgeWidth: style.edgeWidth,
),
),
Positioned.fill(
child: graphEdgeHighlight(
context: context,
@@ -239,6 +179,8 @@ class RunGraphCanvas extends StatelessWidget {
highlighted,
select,
describe,
open,
toggle,
),
],
),
@@ -254,6 +196,8 @@ class RunGraphCanvas extends StatelessWidget {
int? highlighted,
ValueChanged<int> select,
String Function(EdgeRoute) describe,
String? open,
ValueChanged<String> toggle,
) {
return [
for (final box in layout.nodes)
@@ -265,11 +209,10 @@ class RunGraphCanvas extends StatelessWidget {
child: RunGraphNode(
node: nodesByKey[box.key]!,
recordedStatus: recordedStatuses[box.key],
selected: box.key == selectedStage,
selected: box.key == selectedStage || box.key == open,
active: box.key == activeStage,
opensVisit:
!nodesByKey[box.key]!.terminal && state.isStageVisited(box.key),
onSelected: onStageSelected,
interactive: !nodesByKey[box.key]!.terminal,
onSelected: toggle,
),
),
// A run labels only the routes that actually happened, and the route
@@ -312,184 +255,3 @@ class RunGraphCanvas extends StatelessWidget {
color: color,
);
}
/// A taken route's label led by its place in the run (`2`, or `2, 5` for a
/// loop), so the path reads in order.
///
/// The canvas places this widget and [RunGraphMeasurements] measures the same
/// one, so the routed label box covers the order badge as well as the text.
class RunRouteLabel extends StatelessWidget {
const RunRouteLabel({
super.key,
required this.edgeId,
required this.label,
required this.order,
required this.style,
required this.color,
});
final int edgeId;
final String label;
final List<int> order;
final TextStyle style;
final Color color;
@override
Widget build(BuildContext context) {
final text = Text(label, style: style);
if (order.isEmpty) return text;
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
key: ValueKey('run-route-order:$edgeId'),
padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1),
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(8),
),
child: Text(
order.join(', '),
style: const TextStyle(
color: Color(0xFFFFFFFF),
fontSize: 10,
fontWeight: FontWeight.w700,
),
),
),
const SizedBox(width: 4),
text,
],
);
}
}
/// 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. [active]
/// marks the run's recorded current stage while it executes; it only adds the
/// live halo, never a visit or a control.
class RunGraphNode extends StatelessWidget {
const RunGraphNode({
super.key,
required this.node,
required this.recordedStatus,
required this.opensVisit,
required this.onSelected,
this.selected = false,
this.active = false,
});
final GraphNode node;
final String? recordedStatus;
final bool opensVisit;
final bool selected;
final bool active;
final ValueChanged<String> onSelected;
@override
Widget build(BuildContext context) {
final status = recordedStatus;
if (opensVisit) {
return GraphStageNode(
node: node,
recordedStatus: status,
selected: selected,
active: active,
onSelected: onSelected,
);
}
return Semantics(
container: true,
label: graphNodeSemanticsLabel(node, status),
child: ExcludeSemantics(
child: IgnorePointer(
child: GraphStageNode(
node: node,
recordedStatus: status,
active: active,
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.state,
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;
/// The run whose route order badges lead the taken labels.
final RunGraphState state;
final void Function(String, Size) onNodeSize;
/// Receives each edge's label size keyed by its edge id, because two edges
/// with the same outcome can carry different order badges.
final void Function(int, 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.id, size),
child: RunRouteLabel(
edgeId: edge.id,
label: edge.label,
order: state.routeOrder(edge.source, edge.outcome, edge.target),
style: labelStyle,
color: const Color(0x00000000),
),
),
],
),
),
);
}
@@ -0,0 +1,190 @@
import 'package:flutter/material.dart';
import '../domain/graph_definition.dart';
import '../domain/run_graph_state.dart';
import 'graph_stage_node.dart';
import 'measured_child.dart';
/// The run canvas's placed pieces: taken-route labels, run nodes and the
/// offstage measurement of exactly those widgets.
/// A taken route's label led by its place in the run (`2`, or `2, 5` for a
/// loop), so the path reads in order.
///
/// The canvas places this widget and [RunGraphMeasurements] measures the same
/// one, so the routed label box covers the order badge as well as the text.
class RunRouteLabel extends StatelessWidget {
const RunRouteLabel({
super.key,
required this.edgeId,
required this.label,
required this.order,
required this.style,
required this.color,
});
final int edgeId;
final String label;
final List<int> order;
final TextStyle style;
final Color color;
@override
Widget build(BuildContext context) {
final text = Text(label, style: style);
if (order.isEmpty) return text;
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
key: ValueKey('run-route-order:$edgeId'),
padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1),
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(8),
),
child: Text(
order.join(', '),
style: const TextStyle(
color: Color(0xFFFFFFFF),
fontSize: 10,
fontWeight: FontWeight.w700,
),
),
),
const SizedBox(width: 4),
text,
],
);
}
}
/// One placed run node. A stage is the native control with its recorded status
/// (none when unvisited) and opens its popover; a terminal is a label with no
/// tap target or button semantics, because it has no declaration. [active]
/// marks the run's recorded current stage while it executes; it only adds the
/// live halo, never a visit or a control.
class RunGraphNode extends StatelessWidget {
const RunGraphNode({
super.key,
required this.node,
required this.recordedStatus,
required this.interactive,
required this.onSelected,
this.selected = false,
this.active = false,
});
final GraphNode node;
final String? recordedStatus;
final bool interactive;
final bool selected;
final bool active;
final ValueChanged<String> onSelected;
@override
Widget build(BuildContext context) {
final status = recordedStatus;
if (interactive) {
return GraphStageNode(
node: node,
recordedStatus: status,
selected: selected,
active: active,
onSelected: onSelected,
);
}
return Semantics(
container: true,
label: graphNodeSemanticsLabel(node, status),
child: ExcludeSemantics(
child: IgnorePointer(
child: GraphStageNode(
node: node,
recordedStatus: status,
active: active,
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.state,
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;
/// The run whose route order badges lead the taken labels.
final RunGraphState state;
final void Function(String, Size) onNodeSize;
/// Receives each edge's label size keyed by its edge id, because two edges
/// with the same outcome can carry different order badges.
final void Function(int, 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.id, size),
child: RunRouteLabel(
edgeId: edge.id,
label: edge.label,
order: state.routeOrder(edge.source, edge.outcome, edge.target),
style: labelStyle,
color: const Color(0x00000000),
),
),
],
),
),
);
}
@@ -13,6 +13,7 @@ import '../viewport/graph_viewport_controller.dart';
import 'graph_canvas_style.dart';
import 'run_graph_canvas.dart';
import 'run_graph_header.dart';
import 'stage_definition_view.dart';
export 'run_graph_header.dart' show runGraphExecuted, runGraphNotExecuted;
@@ -327,6 +328,9 @@ class _RunGraphViewState extends State<RunGraphView> {
required String? selectedStage,
required ValueChanged<String> onStageSelected,
}) => RunGraphCanvas(
graph: widget.graph ?? const {},
run: widget.run,
onOpenDefinition: _openDefinition,
nodes: nodes,
layout: layout,
routing: routing,
@@ -337,6 +341,23 @@ class _RunGraphViewState extends State<RunGraphView> {
onStageSelected: onStageSelected,
);
/// The full definition page for [stage], pinned to this run's version.
void _openDefinition(String stage) {
final graph = widget.graph;
if (graph == null) return;
final id = widget.run['pipeline_id'];
final version = widget.run['version'];
final name = '${widget.run['name'] ?? ''}'.trim();
openStageDefinition(
context,
graph: graph,
stageKey: stage,
pipelineId: id is num ? id.toInt() : 0,
pipelineName: name,
version: version is num ? version.toInt() : 0,
);
}
void _openExpanded(
List<GraphNode> nodes,
GraphLayout layout,
@@ -0,0 +1,290 @@
import 'package:flutter/material.dart';
import '../../../ui/status/run_status_icon.dart';
import '../domain/stage_run_facts.dart';
import '../domain/stage_summary.dart';
import 'graph_stage_node.dart';
import 'stage_popover_parts.dart';
/// The undeclared-stage line, when this version has no declaration for a node.
const String stagePopoverUndeclared =
'This stage is not declared in this pipeline version.';
/// The compact content of one stage's popover: a header with the stage's name,
/// type and (for a run) its recorded status, then the declaration's facts, the
/// prompt or its type's equivalent, limits and routes, and the actions.
///
/// Built only while the popover is open. Nothing here is fetched: [summary] is
/// the pinned declaration and [facts] what the run recorded, if anything.
class StagePopoverCard extends StatelessWidget {
const StagePopoverCard({
super.key,
required this.label,
required this.summary,
required this.onClose,
required this.onOpenDefinition,
this.facts,
this.onOpenVisit,
});
final String label;
final StageSummary? summary;
final StageRunFacts? facts;
final VoidCallback onClose;
final VoidCallback onOpenDefinition;
/// Opens the stage's latest recorded visit; null when it has none.
final VoidCallback? onOpenVisit;
@override
Widget build(BuildContext context) {
final summary = this.summary;
final facts = this.facts;
final sections = <Widget>[
if (facts != null && facts.visits > 0) ..._runSections(context, facts),
if (summary == null)
Text(stagePopoverUndeclared, style: popoverMuted(context))
else
..._definitionSections(context, summary),
];
return Semantics(
container: true,
explicitChildNodes: true,
label: '$label details',
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_header(context, summary, facts),
if (sections.isNotEmpty)
Flexible(
child: SingleChildScrollView(
key: const Key('stage-popover-body'),
padding: const EdgeInsets.fromLTRB(16, 4, 16, 12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (var i = 0; i < sections.length; i++) ...[
if (i > 0) const SizedBox(height: 12),
sections[i],
],
],
),
),
),
_actions(context),
],
),
);
}
Widget _header(
BuildContext context,
StageSummary? summary,
StageRunFacts? facts,
) {
final theme = Theme.of(context);
final status = facts?.status;
final chips = <Widget>[
if (summary != null)
PopoverChip(
key: const Key('stage-popover-type'),
label: summary.typeLabel,
icon: stageKindIcon(summary.kind),
tone: PopoverChipTone.accent,
),
if (status != null)
PopoverChip(
key: const Key('stage-popover-status'),
label: status,
dot: runStatusColorOf(context, graphStatusState(status)),
),
if (facts != null && facts.visits > 0)
PopoverChip(
key: const Key('stage-popover-visits'),
label: '×${facts.visits}',
tooltip: facts.visits == 1 ? '1 visit' : '${facts.visits} visits',
),
if (facts?.duration case final duration?)
PopoverChip(label: duration, icon: Icons.schedule),
if (facts?.usage case final usage?) PopoverChip(label: usage),
];
return Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 4, 8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Padding(
padding: const EdgeInsets.only(top: 6),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
key: const Key('stage-popover-title'),
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600,
),
),
if (chips.isNotEmpty) ...[
const SizedBox(height: 6),
Wrap(spacing: 6, runSpacing: 6, children: chips),
],
],
),
),
),
IconButton(
key: const Key('stage-popover-close'),
tooltip: 'Close',
visualDensity: VisualDensity.compact,
iconSize: 18,
onPressed: onClose,
icon: const Icon(Icons.close),
),
],
),
);
}
List<Widget> _runSections(BuildContext context, StageRunFacts facts) {
final colors = Theme.of(context).colorScheme;
return [
if (facts.failure case final failure?)
PopoverNote(
key: const Key('stage-popover-failure'),
icon: Icons.error_outline,
color: colors.error,
text: failure,
),
if (facts.verdict case final verdict?)
PopoverSection(
label: 'Verdict',
child: Text(verdict, key: const Key('stage-popover-verdict')),
),
if (facts.handoff case final handoff?)
PopoverSection(
label: 'Handoff',
child: Text(
handoff,
key: const Key('stage-popover-handoff'),
maxLines: 3,
overflow: TextOverflow.ellipsis,
),
),
];
}
List<Widget> _definitionSections(BuildContext context, StageSummary s) {
return [
if (s.meta.isNotEmpty)
Wrap(
key: const Key('stage-popover-meta'),
spacing: 6,
runSpacing: 6,
children: [for (final item in s.meta) PopoverChip(label: item)],
),
if (s.tools.isNotEmpty)
PopoverSection(
label: s.toolsDefault ? 'Tools · default' : 'Tools',
child: Wrap(
key: const Key('stage-popover-tools'),
spacing: 6,
runSpacing: 6,
children: [
for (final tool in s.tools)
PopoverChip(label: tool, icon: toolIcon(tool), mono: true),
],
),
),
if (s.permissions.isNotEmpty) PopoverPermissions(lines: s.permissions),
if (s.skills.isNotEmpty)
PopoverSection(
label: 'Skills',
child: Wrap(
spacing: 6,
runSpacing: 6,
children: [for (final skill in s.skills) PopoverChip(label: skill)],
),
),
if (s.prompt case final prompt?)
PopoverSection(
label: s.kind == StageKind.human ? 'Operator instructions' : 'Prompt',
child: PopoverPrompt(text: prompt),
),
if (s.commands.isNotEmpty)
PopoverSection(
label: 'Commands',
child: PopoverCommands(commands: s.commands),
),
if (s.gate.isNotEmpty)
PopoverSection(
label: 'Gate',
child: Wrap(
key: const Key('stage-popover-gate'),
spacing: 6,
runSpacing: 6,
children: [for (final item in s.gate) PopoverChip(label: item)],
),
),
if (s.limits.isNotEmpty)
PopoverSection(
label: 'Limits',
child: Wrap(
key: const Key('stage-popover-limits'),
spacing: 6,
runSpacing: 6,
children: [for (final item in s.limits) PopoverChip(label: item)],
),
),
if (s.routes.isNotEmpty)
PopoverSection(
label: s.kind == StageKind.terminal ? 'Routes in' : 'Routes',
child: Wrap(
key: const Key('stage-popover-routes'),
spacing: 6,
runSpacing: 6,
children: [
for (final route in s.routes)
s.kind == StageKind.terminal
? PopoverRouteChip(from: route.target, to: route.outcome)
: PopoverRouteChip(from: route.outcome, to: route.target),
],
),
),
];
}
Widget _actions(BuildContext context) {
final colors = Theme.of(context).colorScheme;
return DecoratedBox(
decoration: BoxDecoration(
border: Border(top: BorderSide(color: colors.outlineVariant)),
),
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 8, 12, 8),
child: Wrap(
alignment: WrapAlignment.end,
spacing: 8,
runSpacing: 4,
children: [
if (onOpenVisit != null)
TextButton.icon(
key: const Key('stage-popover-open-visit'),
onPressed: onOpenVisit,
icon: const Icon(Icons.history, size: 18),
label: const Text('Open visit'),
),
FilledButton.tonalIcon(
key: const Key('stage-popover-open-definition'),
onPressed: onOpenDefinition,
icon: const Icon(Icons.description_outlined, size: 18),
label: const Text('Open definition'),
),
],
),
),
);
}
}
@@ -0,0 +1,170 @@
import 'package:flutter/material.dart';
import '../../../ui/text/monospace.dart';
import '../../../ui/theme/app_design_tokens.dart';
import '../domain/stage_summary.dart';
import 'graph_stage_node.dart';
/// The stage popover's compact facts: chips for configs, tools and routes,
/// and the icons and corners they share.
TextStyle? popoverMuted(BuildContext context) {
final theme = Theme.of(context);
return theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
);
}
/// The corners of the popover's inner pieces (chips, blocks): the design's
/// own radius, else a soft 8 (chips 6).
BorderRadius popoverCorners(BuildContext context, double designed) =>
AppDesignTokens.of(context).corners(BorderRadius.circular(designed));
/// The icon of a stage's type chip.
IconData stageKindIcon(StageKind kind) => switch (kind) {
StageKind.model => Icons.auto_awesome_outlined,
StageKind.check => checkStageIcon(delivery: false),
StageKind.deliveryGate => checkStageIcon(delivery: true),
StageKind.findings => Icons.filter_alt_outlined,
StageKind.human => Icons.person_outline,
StageKind.terminal => Icons.flag_outlined,
StageKind.other => Icons.widgets_outlined,
};
/// A tool chip's icon.
IconData toolIcon(String tool) => switch (tool) {
'read' => Icons.visibility_outlined,
'glob' => Icons.folder_open_outlined,
'grep' => Icons.search,
'edit' => Icons.edit_outlined,
'shell' => Icons.terminal,
'websearch' => Icons.travel_explore,
'webfetch' => Icons.public,
_ when tool.startsWith('mcp:') => Icons.extension_outlined,
_ => Icons.build_outlined,
};
enum PopoverChipTone { neutral, accent }
/// One compact fact: a tinted label, optionally led by an icon or a status dot.
class PopoverChip extends StatelessWidget {
const PopoverChip({
super.key,
required this.label,
this.icon,
this.dot,
this.tone = PopoverChipTone.neutral,
this.mono = false,
this.tooltip,
});
final String label;
final IconData? icon;
final Color? dot;
final PopoverChipTone tone;
final bool mono;
final String? tooltip;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colors = theme.colorScheme;
final accent = tone == PopoverChipTone.accent;
final foreground = accent
? colors.onSecondaryContainer
: colors.onSurfaceVariant;
final base = theme.textTheme.labelMedium ?? const TextStyle();
final style = base.copyWith(
color: foreground,
fontFamily: mono ? appMonospaceFamily : null,
height: 1.2,
);
final size = (style.fontSize ?? 12) * 1.15;
Widget chip = DecoratedBox(
decoration: BoxDecoration(
color: accent
? colors.secondaryContainer
: colors.surfaceContainerHighest,
borderRadius: popoverCorners(context, 6),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
if (dot != null) ...[
Container(
width: 7,
height: 7,
decoration: BoxDecoration(color: dot, shape: BoxShape.circle),
),
const SizedBox(width: 5),
] else if (icon != null) ...[
Icon(icon, size: size, color: foreground),
const SizedBox(width: 4),
],
Flexible(child: Text(label, style: style)),
],
),
),
);
final tip = tooltip;
if (tip != null) chip = Tooltip(message: tip, child: chip);
return chip;
}
}
/// One route as `from → to`. The arrow is an icon, not a glyph: a design's
/// interface face may not carry U+2192.
class PopoverRouteChip extends StatelessWidget {
const PopoverRouteChip({super.key, required this.from, required this.to});
final String from;
final String to;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colors = theme.colorScheme;
final style = (theme.textTheme.labelMedium ?? const TextStyle()).copyWith(
color: colors.onSurfaceVariant,
height: 1.2,
);
return Semantics(
label: '$from to $to',
excludeSemantics: true,
child: DecoratedBox(
decoration: BoxDecoration(
color: colors.surfaceContainerHighest,
borderRadius: popoverCorners(context, 6),
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Flexible(child: Text(from, style: style)),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 4),
child: Icon(
Icons.arrow_forward,
size: (style.fontSize ?? 12) * 1.1,
color: colors.outline,
),
),
Flexible(
child: Text(
to,
style: style.copyWith(
color: colors.onSurface,
fontWeight: FontWeight.w600,
),
),
),
],
),
),
),
);
}
}
@@ -0,0 +1,308 @@
import 'package:flutter/material.dart';
import '../../../ui/text/monospace.dart';
import '../../chat/ui/transcript/chat_markdown_view.dart';
import 'stage_popover_chips.dart';
export 'stage_popover_chips.dart';
/// The stage popover's larger pieces: labelled sections, the clamped prompt
/// block, the command list and the collapsed permissions line.
/// A small muted label over its content.
class PopoverSection extends StatelessWidget {
const PopoverSection({super.key, required this.label, required this.child});
final String label;
final Widget child;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
label,
style: theme.textTheme.labelSmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
fontWeight: FontWeight.w600,
letterSpacing: 0.4,
),
),
const SizedBox(height: 6),
DefaultTextStyle.merge(style: theme.textTheme.bodyMedium, child: child),
],
);
}
}
/// A one-line notice with an icon, e.g. the recorded failure reason.
class PopoverNote extends StatelessWidget {
const PopoverNote({
super.key,
required this.icon,
required this.color,
required this.text,
});
final IconData icon;
final Color color;
final String text;
@override
Widget build(BuildContext context) {
final style = Theme.of(
context,
).textTheme.bodyMedium?.copyWith(color: color);
return DecoratedBox(
decoration: BoxDecoration(
color: color.withValues(alpha: 0.08),
borderRadius: popoverCorners(context, 8),
),
child: Padding(
padding: const EdgeInsets.fromLTRB(10, 8, 10, 8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon, size: 18, color: color),
const SizedBox(width: 8),
Expanded(child: Text(text, style: style)),
],
),
),
);
}
}
/// The inset block a prompt or command list sits in.
class PopoverBlock extends StatelessWidget {
const PopoverBlock({super.key, required this.child});
final Widget child;
@override
Widget build(BuildContext context) {
final colors = Theme.of(context).colorScheme;
return DecoratedBox(
decoration: BoxDecoration(
color: colors.surface,
border: Border.all(color: colors.outlineVariant.withValues(alpha: 0.6)),
borderRadius: popoverCorners(context, 8),
),
child: Padding(padding: const EdgeInsets.all(12), child: child),
);
}
}
/// A prompt as typeset markdown, held to about ten lines with a fade until
/// "Show all" expands it in place.
class PopoverPrompt extends StatefulWidget {
const PopoverPrompt({super.key, required this.text});
final String text;
/// Collapsed height in lines of the body face.
static const int collapsedLines = 10;
@override
State<PopoverPrompt> createState() => _PopoverPromptState();
}
class _PopoverPromptState extends State<PopoverPrompt> {
bool _expanded = false;
bool _overflows = false;
bool _onMetrics(ScrollMetricsNotification notification) {
final overflows = notification.metrics.maxScrollExtent > 0.5;
if (overflows != _overflows) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) setState(() => _overflows = overflows);
});
}
return true;
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final body = theme.textTheme.bodyMedium ?? const TextStyle();
final scaler = MediaQuery.textScalerOf(context);
final line = scaler.scale(body.fontSize ?? 14) * (body.height ?? 1.43);
// Headings a step down from the transcript's: in a compact card a
// prompt's `## Goal` is a label, not a page title.
final text = theme.textTheme;
final heading = text.titleSmall?.copyWith(fontWeight: FontWeight.w700);
final markdown = Theme(
data: theme.copyWith(
textTheme: text.copyWith(
headlineSmall: text.titleMedium?.copyWith(
fontWeight: FontWeight.w700,
),
titleLarge: heading,
titleMedium: heading,
),
),
child: DefaultTextStyle.merge(
style: body,
child: ChatMarkdownView(text: widget.text),
),
);
final Widget content = _expanded
? markdown
: NotificationListener<ScrollMetricsNotification>(
onNotification: _onMetrics,
child: ConstrainedBox(
constraints: BoxConstraints(
maxHeight: line * PopoverPrompt.collapsedLines,
),
child: _fade(
SingleChildScrollView(
physics: const NeverScrollableScrollPhysics(),
primary: false,
child: markdown,
),
),
),
);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
PopoverBlock(
child: KeyedSubtree(
key: const Key('stage-popover-prompt'),
child: content,
),
),
if (_overflows || _expanded)
Align(
alignment: AlignmentDirectional.centerStart,
child: TextButton(
key: const Key('stage-popover-show-all'),
style: TextButton.styleFrom(
visualDensity: VisualDensity.compact,
padding: const EdgeInsets.symmetric(horizontal: 4),
),
onPressed: () => setState(() => _expanded = !_expanded),
child: Text(_expanded ? 'Show less' : 'Show all'),
),
),
],
);
}
Widget _fade(Widget child) {
if (!_overflows) return child;
return ShaderMask(
blendMode: BlendMode.dstIn,
shaderCallback: (bounds) => LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: const [Color(0xFFFFFFFF), Color(0x00FFFFFF)],
stops: [
bounds.height <= 0 ? 0 : (1 - 36 / bounds.height).clamp(0.0, 1.0),
1,
],
).createShader(bounds),
child: child,
);
}
}
/// A check stage's commands, one per line in the monospace face.
class PopoverCommands extends StatelessWidget {
const PopoverCommands({super.key, required this.commands});
final List<String> commands;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final style = theme.textTheme.bodySmall?.copyWith(
fontFamily: appMonospaceFamily,
height: 1.5,
);
final prompt = theme.colorScheme.onSurfaceVariant;
return PopoverBlock(
child: SelectableText.rich(
key: const Key('stage-popover-commands'),
TextSpan(
style: style,
children: [
for (var i = 0; i < commands.length; i++) ...[
if (i > 0) const TextSpan(text: '\n'),
TextSpan(
text: r'$ ',
style: TextStyle(color: prompt),
),
TextSpan(text: commands[i]),
],
],
),
),
);
}
}
/// The permission allow-lists behind one collapsed "Permissions" line.
class PopoverPermissions extends StatefulWidget {
const PopoverPermissions({super.key, required this.lines});
final List<String> lines;
@override
State<PopoverPermissions> createState() => _PopoverPermissionsState();
}
class _PopoverPermissionsState extends State<PopoverPermissions> {
bool _open = false;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final muted = theme.colorScheme.onSurfaceVariant;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
InkWell(
key: const Key('stage-popover-permissions'),
borderRadius: popoverCorners(context, 6),
onTap: () => setState(() => _open = !_open),
child: Padding(
padding: const EdgeInsets.symmetric(vertical: 2),
child: Row(
children: [
Icon(
_open ? Icons.expand_more : Icons.chevron_right,
size: 18,
color: muted,
),
const SizedBox(width: 2),
Text(
'Permissions',
style: theme.textTheme.labelSmall?.copyWith(
color: muted,
fontWeight: FontWeight.w600,
letterSpacing: 0.4,
),
),
],
),
),
),
if (_open)
Padding(
padding: const EdgeInsetsDirectional.only(start: 20, top: 4),
child: Text(
widget.lines.join('\n'),
key: const Key('stage-popover-permission-lines'),
style: theme.textTheme.bodySmall?.copyWith(
fontFamily: appMonospaceFamily,
height: 1.5,
),
),
),
],
);
}
}
@@ -0,0 +1,368 @@
import 'dart:math' as math;
import 'package:flutter/rendering.dart';
import 'package:flutter/widgets.dart';
/// Where a stage popover sits relative to its node.
enum StagePopoverSide { above, below, right, left, over }
/// Places one popover card beside an anchor node, inside a bounding box, and
/// paints the nub that points at the node.
///
/// It fills its overlay but hit-tests only the card, so the graph under it
/// keeps every gesture. The anchor is a rectangle in [anchorBox]'s own space
/// (the graph canvas, inside the pan/zoom transform); it is mapped through the
/// live transform at layout, and [relayout] (the viewport transform) lays the
/// card out again on every pan or zoom, so it follows the node.
class StagePopoverPosition extends SingleChildRenderObjectWidget {
const StagePopoverPosition({
super.key,
required this.anchorBox,
required this.anchorRect,
required this.boundsBox,
required this.boundsSize,
this.safeArea = EdgeInsets.zero,
required this.relayout,
required this.fill,
required this.border,
required this.radius,
required this.elevation,
required this.shadowColor,
super.child,
});
final RenderBox? Function() anchorBox;
final Rect anchorRect;
/// The visible box the card must stay inside, and its extent; a null box
/// uses the overlay itself.
final RenderBox? Function() boundsBox;
final Size? boundsSize;
/// Insets of the screen the card must also keep clear of (floating bars
/// drawn over the viewport's edges).
final EdgeInsets safeArea;
final Listenable? relayout;
final Color fill;
final BorderSide border;
final double radius;
final double elevation;
final Color shadowColor;
@override
RenderStagePopoverPosition createRenderObject(BuildContext context) =>
RenderStagePopoverPosition(
anchorBox: anchorBox,
anchorRect: anchorRect,
boundsBox: boundsBox,
boundsSize: boundsSize,
safeArea: safeArea,
relayout: relayout,
fill: fill,
border: border,
radius: radius,
elevation: elevation,
shadowColor: shadowColor,
);
@override
void updateRenderObject(
BuildContext context,
RenderStagePopoverPosition renderObject,
) {
renderObject
..anchorBox = anchorBox
..anchorRect = anchorRect
..boundsBox = boundsBox
..boundsSize = boundsSize
..safeArea = safeArea
..relayout = relayout
..fill = fill
..border = border
..radius = radius
..elevation = elevation
..shadowColor = shadowColor;
}
}
class RenderStagePopoverPosition extends RenderShiftedBox {
RenderStagePopoverPosition({
required this.anchorBox,
required this._anchorRect,
required this.boundsBox,
required this._boundsSize,
required this._safeArea,
required this._relayout,
required this.fill,
required this.border,
required this.radius,
required this.elevation,
required this.shadowColor,
}) : super(null);
/// The card's widest extent.
static const double maxCardWidth = 400;
/// The card's tallest extent; a longer card scrolls its body.
static const double maxCardHeight = 560;
/// The space kept between the card and the viewport's edges.
static const double margin = 8;
/// The nub's depth; its base is twice as wide.
static const double nub = 7;
/// The gap between the node and the nub's tip.
static const double gap = 3;
RenderBox? Function() anchorBox;
RenderBox? Function() boundsBox;
Color fill;
BorderSide border;
double radius;
double elevation;
Color shadowColor;
Rect _anchorRect;
set anchorRect(Rect value) {
if (value == _anchorRect) return;
_anchorRect = value;
markNeedsLayout();
}
EdgeInsets _safeArea;
set safeArea(EdgeInsets value) {
if (value == _safeArea) return;
_safeArea = value;
markNeedsLayout();
}
Size? _boundsSize;
set boundsSize(Size? value) {
if (value == _boundsSize) return;
_boundsSize = value;
markNeedsLayout();
}
Listenable? _relayout;
set relayout(Listenable? value) {
if (value == _relayout) return;
if (attached) _relayout?.removeListener(markNeedsLayout);
_relayout = value;
if (attached) _relayout?.addListener(markNeedsLayout);
markNeedsLayout();
}
/// Where the card went in the last layout, for tests and the nub.
StagePopoverSide side = StagePopoverSide.above;
bool _visible = false;
Offset _tip = Offset.zero;
@override
void attach(PipelineOwner owner) {
super.attach(owner);
_relayout?.addListener(markNeedsLayout);
}
@override
void detach() {
_relayout?.removeListener(markNeedsLayout);
super.detach();
}
Rect _bounds() {
final whole = _safeArea.deflateRect(Offset.zero & size);
final box = boundsBox();
final extent = _boundsSize;
if (box == null || !box.attached || extent == null) {
return whole.deflate(margin);
}
final origin = MatrixUtils.transformPoint(
box.getTransformTo(this),
Offset.zero,
);
return (origin & extent).intersect(whole).deflate(margin);
}
Rect? _anchor() {
final box = anchorBox();
if (box == null || !box.attached) return null;
return MatrixUtils.transformRect(box.getTransformTo(this), _anchorRect);
}
@override
void performLayout() {
size = constraints.biggest;
final card = child;
// Mapping through the ancestors' paint transforms reads their sizes (a
// page transition's translation does); a layout callback is the sanctioned
// scope for that, as it is for a LayoutBuilder.
var mapped = (bounds: Rect.zero, anchor: null as Rect?);
invokeLayoutCallback<BoxConstraints>((_) {
mapped = (bounds: _bounds(), anchor: _anchor());
});
final bounds = mapped.bounds;
final anchor = mapped.anchor;
_visible =
card != null &&
anchor != null &&
bounds.width > 0 &&
bounds.height > 0 &&
anchor.overlaps(bounds);
if (!_visible || card == null || anchor == null) {
card?.layout(const BoxConstraints.tightFor(width: 0, height: 0));
return;
}
final width = math.min(maxCardWidth, bounds.width);
var cardSize = _layoutCard(
card,
width,
math.min(maxCardHeight, bounds.height),
);
final reach = gap + nub;
final above = anchor.top - reach - bounds.top;
final below = bounds.bottom - anchor.bottom - reach;
final right = bounds.right - anchor.right - reach;
final left = anchor.left - reach - bounds.left;
if (cardSize.height <= above) {
side = StagePopoverSide.above;
} else if (cardSize.height <= below) {
side = StagePopoverSide.below;
} else if (cardSize.width <= right) {
side = StagePopoverSide.right;
} else if (cardSize.width <= left) {
side = StagePopoverSide.left;
} else if (math.max(above, below) >= 160) {
// Too tall for either side whole: take the roomier one and scroll.
side = above >= below ? StagePopoverSide.above : StagePopoverSide.below;
cardSize = _layoutCard(
card,
width,
math.min(maxCardHeight, math.max(above, below)),
);
} else {
side = StagePopoverSide.over;
}
final parentData = card.parentData! as BoxParentData;
double clampX(double x) => x.clamp(
bounds.left,
math.max(bounds.left, bounds.right - cardSize.width),
);
double clampY(double y) => y.clamp(
bounds.top,
math.max(bounds.top, bounds.bottom - cardSize.height),
);
final center = anchor.center;
final inset = radius + nub + 2;
switch (side) {
case StagePopoverSide.above:
case StagePopoverSide.below:
final x = clampX(center.dx - cardSize.width / 2);
final y = side == StagePopoverSide.above
? anchor.top - reach - cardSize.height
: anchor.bottom + reach;
parentData.offset = Offset(x, y);
final tipX = center.dx
.clamp(x + inset, math.max(x + inset, x + cardSize.width - inset))
.toDouble();
_tip = Offset(
tipX,
side == StagePopoverSide.above
? anchor.top - gap
: anchor.bottom + gap,
);
case StagePopoverSide.right:
case StagePopoverSide.left:
final y = clampY(center.dy - cardSize.height / 2);
final x = side == StagePopoverSide.right
? anchor.right + reach
: anchor.left - reach - cardSize.width;
parentData.offset = Offset(x, y);
final tipY = center.dy
.clamp(y + inset, math.max(y + inset, y + cardSize.height - inset))
.toDouble();
_tip = Offset(
side == StagePopoverSide.right
? anchor.right + gap
: anchor.left - gap,
tipY,
);
case StagePopoverSide.over:
parentData.offset = Offset(
clampX(center.dx - cardSize.width / 2),
clampY(center.dy - cardSize.height / 2),
);
}
}
Size _layoutCard(RenderBox card, double width, double height) {
card.layout(
BoxConstraints(maxWidth: width, maxHeight: math.max(0, height)),
parentUsesSize: true,
);
return card.size;
}
/// The nub as a triangle whose base overlaps the card's edge by the
/// border, so the card's own frame line does not cross it.
Path _nubPath() {
final t = _tip;
final b = border.width;
return switch (side) {
StagePopoverSide.above =>
Path()
..moveTo(t.dx - nub, t.dy - nub - b)
..lineTo(t.dx, t.dy)
..lineTo(t.dx + nub, t.dy - nub - b),
StagePopoverSide.below =>
Path()
..moveTo(t.dx - nub, t.dy + nub + b)
..lineTo(t.dx, t.dy)
..lineTo(t.dx + nub, t.dy + nub + b),
StagePopoverSide.right =>
Path()
..moveTo(t.dx + nub + b, t.dy - nub)
..lineTo(t.dx, t.dy)
..lineTo(t.dx + nub + b, t.dy + nub),
StagePopoverSide.left =>
Path()
..moveTo(t.dx - nub - b, t.dy - nub)
..lineTo(t.dx, t.dy)
..lineTo(t.dx - nub - b, t.dy + nub),
StagePopoverSide.over => Path(),
};
}
@override
void paint(PaintingContext context, Offset offset) {
final card = child;
if (!_visible || card == null) return;
final hasNub = side != StagePopoverSide.over;
final nubPath = _nubPath().shift(offset);
if (hasNub && elevation > 0) {
context.canvas.drawShadow(
Path.from(nubPath)..close(),
shadowColor,
elevation,
false,
);
}
super.paint(context, offset);
if (!hasNub) return;
context.canvas.drawPath(Path.from(nubPath)..close(), Paint()..color = fill);
if (border.width > 0 && border.style != BorderStyle.none) {
context.canvas.drawPath(
nubPath,
Paint()
..color = border.color
..style = PaintingStyle.stroke
..strokeWidth = border.width
..strokeJoin = StrokeJoin.miter,
);
}
}
@override
bool hitTestChildren(BoxHitTestResult result, {required Offset position}) =>
_visible && super.hitTestChildren(result, position: position);
}
+54
View File
@@ -0,0 +1,54 @@
# Graph stage popover
## Change
- Tapping (or pressing Enter on) a stage in the pipeline graph or the run graph,
inline or full screen, opens a small card anchored to the node with a nub
pointing at it. It no longer navigates straight to the definition page.
- The card shows: the name, a type chip (Model, Check, Delivery gate, Findings
gate, Human, End), config chips (harness, short model name, effort, timeout,
retries, budget), tools as chips (the server's default set is labelled
`Tools · default` when no block is declared), permission allow-lists behind a
collapsed `Permissions` line, skills, then the prompt as markdown clamped to
ten lines with a fade and `Show all`. A check stage lists its commands, a
findings gate its severity and origin, a human stage its operator
instructions. Limits and outgoing routes close it.
- In a run it also shows the latest status, `×N` visits, the latest visit's
duration, reported tokens/cost over all visits, the latest verdict, the first
line of the handoff and the failure diagnostic when the latest visit failed.
- Actions: `Open definition` (the old tap target) and, for a visited run stage,
`Open visit` (the old run-graph tap target). An unvisited run stage now opens
its declaration too; it simply has no `Open visit`.
- The open stage is marked selected and its routes get a soft highlight; edge
hover and the edge tooltip work as before.
## Decisions
- Follows the node on pan and zoom instead of closing: the card lays out in
the overlay against the live viewport transform, so a drag, wheel or pinch
keeps it on its node. Only a tap (down and up within touch slop) outside the
card and its node, Escape, the close button or tapping the node again closes
it; tapping another node replaces it.
- Placement: above, else below, else right, else left, else the roomier of
above/below with the body scrolling. The card stays inside the viewport and
clear of floating bars (the canvas's MediaQuery padding); 400 px wide and at
most 560 px tall.
- Below a 440 px wide (or 300 px tall) viewport the same content opens in a
modal bottom sheet.
- Surface follows the design tokens: Classic is a raised card with a hairline
and 14 px corners; flat designs (Terminal, Paper, Compact) use their panel
fill, frame and radius with no shadow. No blur. Route arrows are icons since
the Terminal face has no U+2192.
- Built lazily: nothing is built while closed, and the global pointer route
and transform listener exist only while a card is open.
Changed paths (under `app/`): `lib/features/graph/{domain/stage_summary.dart,
domain/stage_run_facts.dart, painting/stage_edges_highlight.dart,
painting/run_graph_edge_layer.dart, viewport/graph_viewport_scope.dart,
viewport/graph_viewport.dart, widgets/graph_stage_popover.dart,
widgets/stage_popover_position.dart, widgets/stage_popover_card.dart,
widgets/stage_popover_parts.dart, widgets/stage_popover_chips.dart,
widgets/run_graph_parts.dart, widgets/run_graph_canvas.dart,
widgets/run_graph_view.dart, widgets/definition_graph_canvas.dart,
widgets/definition_graph_view.dart}`, `tool/perf/perf_fixture.dart` (the
`graph=1` fixture now has a prompt, configs, tools and a check stage).
@@ -0,0 +1,84 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/domain/stage_run_facts.dart';
import 'package:pipelines_app/features/graph/domain/stage_summary.dart';
void main() {
test('a model stage with no tools block runs the default tools', () {
final summary = stageSummaryFor({
'stages': [
{'key': 'a', 'prompt': 'Do it', 'edges': {}},
],
}, 'a')!;
expect(summary.kind, StageKind.model);
expect(summary.tools, defaultStageTools);
expect(summary.toolsDefault, isTrue);
expect(summary.prompt, 'Do it');
});
test('a delivery check reads as the delivery gate with its commands', () {
final summary = stageSummaryFor({
'stages': [
{
'key': 'land',
'type': 'check',
'configs': {'delivery': 'true', 'command_timeout': '10m'},
'blocks': {'commands': 'make test\n\nmake lint'},
'edges': {'pass': '#success'},
},
],
}, 'land')!;
expect(summary.typeLabel, 'Delivery gate');
expect(summary.commands, ['make test', 'make lint']);
expect(summary.tools, isEmpty);
expect(summary.prompt, isNull);
expect(summary.meta, ['10m timeout']);
expect(summary.routes.single, (outcome: 'pass', target: 'Success'));
});
test('an undeclared stage has no summary; a terminal lists routes in', () {
final graph = {
'stages': [
{
'key': 'a',
'edges': {'success': '#success'},
},
],
};
expect(stageSummaryFor(graph, 'missing'), isNull);
final end = stageSummaryFor(graph, '#success')!;
expect(end.kind, StageKind.terminal);
expect(end.routes.single, (outcome: 'success', target: 'a'));
});
test('short model names drop the vendor and date', () {
expect(
shortModelName('anthropic/claude-opus-4-1-20250805'),
'claude-opus-4-1',
);
expect(shortModelName('gpt-5'), 'gpt-5');
});
test('an unvisited stage has no run facts', () {
final facts = stageRunFacts({'steps': []}, 'a');
expect(facts.visits, 0);
expect(facts.status, isNull);
});
test('a failure reason is read only from a failed latest visit', () {
final facts = stageRunFacts({
'steps': [
{'sequence': 1, 'stage': 'a', 'status': 'failed', 'diagnostic': 'boom'},
{
'sequence': 2,
'stage': 'a',
'status': 'completed',
'diagnostic': 'old',
},
],
}, 'a');
expect(facts.visits, 2);
expect(facts.status, 'completed');
expect(facts.failure, isNull);
});
}
@@ -96,8 +96,13 @@ void main() {
// A tap in the larger canvas follows the same transform and updates the
// presentation's own selection.
// The tap opens the stage's popover; its "Open definition" reports it.
await tester.tap(_inExpanded(_node('plan')));
await tester.pump();
expect(picked, isEmpty);
expect(find.byKey(const Key('graph-stage-popover')), findsOneWidget);
await tester.tap(find.byKey(const Key('stage-popover-open-definition')));
await tester.pump();
expect(picked, ['plan']);
expect(
tester.widget<GraphStageNode>(_inExpanded(_node('plan'))).selected,
@@ -98,6 +98,14 @@ Future<void> _tapNode(WidgetTester tester, String key) async {
await tester.pump();
}
/// Taps a node, then its popover's "Open definition", which reports the key.
Future<void> _openDefinition(WidgetTester tester, String key) async {
await _tapNode(tester, key);
expect(find.byKey(const Key('graph-stage-popover')), findsOneWidget);
await tester.tap(find.byKey(const Key('stage-popover-open-definition')));
await tester.pump();
}
void _expectNoOverlaps(WidgetTester tester) {
final rects = <Rect>[
for (final element in find.byType(GraphStageNode).evaluate())
@@ -148,11 +156,10 @@ void main() {
expect(tester.widget<GraphStageNode>(_node('build')).selected, isTrue);
expect(tester.widget<GraphStageNode>(_node('plan')).selected, isFalse);
await tester.tap(_node('plan'));
await tester.pump();
await _openDefinition(tester, 'plan');
expect(picked, ['plan']);
await _tapNode(tester, '#success');
await _openDefinition(tester, '#success');
expect(picked, ['plan', '#success']);
});
@@ -189,7 +196,10 @@ void main() {
);
await tester.tapAt(build.center);
await tester.pump();
expect(picked, ['build']);
expect(
tester.widget<Text>(find.byKey(const Key('stage-popover-title'))).data,
'build',
);
});
testWidgets('nodes use measured native sizes and never overlap', (
@@ -0,0 +1,369 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/graph/widgets/definition_graph_view.dart';
import 'package:pipelines_app/features/graph/widgets/graph_stage_node.dart';
import 'package:pipelines_app/features/graph/widgets/run_graph_view.dart';
import 'package:pipelines_app/features/graph/widgets/stage_popover_position.dart';
/// One stage of every type, with the fields the popover shows.
JsonMap _graph() => <String, dynamic>{
'stages': <dynamic>[
<String, dynamic>{
'key': 'implement',
'type': 'model',
'prompt': 'Implement the feature.\n\nKeep the change small.',
'configs': <String, dynamic>{
'harness': 'claude',
'model': 'anthropic/claude-sonnet-4-5-20250929',
'reasoning_effort': 'high',
'timeout': '30m',
'retries': '2',
'budget_usd': '5',
},
'blocks': <String, dynamic>{
'tools': 'read\nglob\nedit\nshell\nmcp:pipelines',
'permissions': '{"edit": ["app/**"], "shell": ["flutter test"]}',
},
'limits': <String, dynamic>{
'max_visits': 3,
'on': ['fail'],
'on_exhausted': 'decide',
},
'edges': <String, dynamic>{'success': 'verify', 'error': '#failure'},
},
<String, dynamic>{
'key': 'verify',
'type': 'check',
'blocks': <String, dynamic>{'commands': 'flutter analyze\nflutter test'},
'edges': <String, dynamic>{
'pass': 'triage',
'fail': 'implement',
'error': '#failure',
},
},
<String, dynamic>{
'key': 'triage',
'type': 'findings',
'configs': <String, dynamic>{'severity': 'critical', 'origin': 'any'},
'edges': <String, dynamic>{'open': 'approve', 'clear': '#success'},
},
<String, dynamic>{
'key': 'approve',
'type': 'human',
'prompt': 'Check the screenshots before landing.',
'edges': <String, dynamic>{'accept': '#success', 'reject': 'implement'},
},
],
};
JsonMap _run() => <String, dynamic>{
'id': 7,
'pipeline_id': 3,
'name': 'feature',
'version': 4,
'steps': <dynamic>[
<String, dynamic>{
'sequence': 1,
'stage': 'implement',
'status': 'completed',
'outcome': 'success',
'target': 'verify',
'started_at': '2026-10-21T10:00:00Z',
'finished_at': '2026-10-21T10:01:00Z',
},
<String, dynamic>{
'sequence': 2,
'stage': 'verify',
'status': 'failed',
'outcome': 'fail',
'target': 'implement',
'diagnostic': 'flutter test: 2 failures',
},
<String, dynamic>{
'sequence': 3,
'stage': 'implement',
'status': 'completed',
'outcome': 'success',
'target': 'verify',
'started_at': '2026-10-21T10:02:00Z',
'finished_at': '2026-10-21T10:04:05Z',
'output': '# Fixed the two failing tests\nmore detail',
'verdict': <String, dynamic>{'option': 'success', 'reason': 'All green'},
},
],
'current_stage': '',
'executing': false,
};
Widget _host(Widget child, {Size size = const Size(1000, 760)}) => MaterialApp(
home: Scaffold(
body: Align(
alignment: Alignment.topLeft,
child: SizedBox(width: size.width, height: size.height, child: child),
),
),
);
Future<void> _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,
);
final Finder _popover = find.byKey(const Key('graph-stage-popover'));
String _title(WidgetTester tester) =>
tester.widget<Text>(find.byKey(const Key('stage-popover-title'))).data!;
Future<void> _view(
WidgetTester tester, {
ValueChanged<String>? onSelected,
Size size = const Size(1000, 760),
}) async {
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(
_host(
DefinitionGraphView(graph: _graph(), onSelected: onSelected ?? (_) {}),
size: size,
),
);
await _settle(tester);
}
void main() {
testWidgets('a model stage shows its type, configs, tools and prompt', (
tester,
) async {
await _view(tester);
expect(_popover, findsNothing);
await tester.tap(_node('implement'));
await tester.pump();
expect(_popover, findsOneWidget);
expect(_title(tester), 'implement');
expect(find.text('Model'), findsOneWidget);
for (final chip in [
'claude',
'claude-sonnet-4-5',
'high effort',
'30m timeout',
'2 retries',
r'$5 budget',
'mcp:pipelines',
'max 3 visits',
'on fail',
'when exhausted: decide',
]) {
expect(find.text(chip), findsOneWidget, reason: chip);
}
for (final route in ['success to verify', 'error to Failure']) {
expect(find.bySemanticsLabel(route), findsOneWidget, reason: route);
}
expect(find.textContaining('Implement the feature.'), findsOneWidget);
// The permission allow-lists stay behind a collapsed line.
expect(
find.byKey(const Key('stage-popover-permission-lines')),
findsNothing,
);
await tester.tap(find.byKey(const Key('stage-popover-permissions')));
await tester.pump();
expect(
tester
.widget<Text>(find.byKey(const Key('stage-popover-permission-lines')))
.data,
'edit: app/**\nshell: flutter test',
);
// The node is the open selection while its popover shows.
expect(tester.widget<GraphStageNode>(_node('implement')).selected, isTrue);
});
testWidgets('a check stage lists its commands instead of a prompt', (
tester,
) async {
await _view(tester);
await tester.tap(_node('verify'));
await tester.pump();
expect(find.text('Check'), findsWidgets);
expect(find.byKey(const Key('stage-popover-commands')), findsOneWidget);
expect(find.byKey(const Key('stage-popover-prompt')), findsNothing);
final commands = tester.widget<SelectableText>(
find.byKey(const Key('stage-popover-commands')),
);
expect(commands.textSpan!.toPlainText(), contains('flutter analyze'));
expect(find.bySemanticsLabel('fail to implement'), findsOneWidget);
});
testWidgets('a findings gate shows severity and origin', (tester) async {
await _view(tester);
await tester.tap(_node('triage'));
await tester.pump();
expect(find.text('Findings gate'), findsOneWidget);
expect(find.text('min severity critical'), findsOneWidget);
expect(find.text('origin any'), findsOneWidget);
});
testWidgets('a human stage shows the operator instructions', (tester) async {
await _view(tester);
await tester.tap(_node('approve'));
await tester.pump();
expect(find.text('Human'), findsOneWidget);
expect(find.text('Operator instructions'), findsOneWidget);
expect(
find.textContaining('Check the screenshots before landing.'),
findsOneWidget,
);
});
testWidgets('the card sits inside the viewport with its nub on the node', (
tester,
) async {
await _view(tester);
await tester.tap(_node('verify'));
await tester.pump();
final card = tester.getRect(find.byKey(const Key('stage-popover-body')));
final viewport = tester.getRect(find.byType(InteractiveViewer));
expect(viewport.inflate(1).contains(card.topLeft), isTrue);
expect(viewport.inflate(1).contains(card.bottomRight), isTrue);
final position = tester.renderObject<RenderStagePopoverPosition>(_popover);
expect(position.side, isNot(StagePopoverSide.over));
});
testWidgets('an outside tap, Escape and the same node close it', (
tester,
) async {
await _view(tester);
await tester.tap(_node('implement'));
await tester.pump();
expect(_popover, findsOneWidget);
// Tapping inside the card keeps it open.
await tester.tap(find.byKey(const Key('stage-popover-title')));
await tester.pump();
expect(_popover, findsOneWidget);
// An outside tap on the empty canvas closes it.
final viewport = tester.getRect(find.byType(InteractiveViewer));
await tester.tapAt(viewport.bottomRight - const Offset(10, 10));
await tester.pump();
expect(_popover, findsNothing);
// A drag pans the graph but keeps the card on its node.
await tester.tap(_node('implement'));
await tester.pump();
await tester.dragFrom(
viewport.bottomRight - const Offset(40, 40),
const Offset(-60, -20),
);
await tester.pump();
expect(_popover, findsOneWidget);
// Escape closes it.
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
expect(_popover, findsNothing);
// Tapping the same node again toggles it shut.
await tester.tap(_node('implement'));
await tester.pump();
expect(_popover, findsOneWidget);
await tester.tap(_node('implement'));
await tester.pump();
expect(_popover, findsNothing);
// Another node replaces it.
await tester.tap(_node('triage'));
await tester.pump();
expect(_title(tester), 'triage');
await tester.tap(_node('implement'));
await tester.pump();
expect(_title(tester), 'implement');
});
testWidgets('Open definition reports the stage and closes the card', (
tester,
) async {
final opened = <String>[];
await _view(tester, onSelected: opened.add);
await tester.tap(_node('approve'));
await tester.pump();
await tester.tap(find.byKey(const Key('stage-popover-open-definition')));
await tester.pump();
expect(opened, ['approve']);
expect(_popover, findsNothing);
});
testWidgets('a focused node opens with Enter', (tester) async {
await _view(tester);
// The node's own focus: the nearest focus above its label.
final label = find
.descendant(of: _node('triage'), matching: find.byType(Text))
.first;
Focus.of(tester.element(label)).requestFocus();
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(_popover, findsOneWidget);
expect(_title(tester), 'triage');
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
expect(_popover, findsNothing);
});
testWidgets('a phone-width graph opens the stage in a bottom sheet', (
tester,
) async {
await _view(tester, size: const Size(390, 760));
await tester.tap(_node('implement'));
await tester.pumpAndSettle();
expect(_popover, findsNothing);
expect(find.byKey(const Key('graph-stage-sheet')), findsOneWidget);
expect(_title(tester), 'implement');
expect(find.text('claude-sonnet-4-5'), findsOneWidget);
});
testWidgets('the run variant shows status, visits, verdict and failure', (
tester,
) async {
tester.view.physicalSize = const Size(1000, 760);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final visits = <String>[];
await tester.pumpWidget(
_host(
RunGraphView(graph: _graph(), run: _run(), onStageSelected: visits.add),
),
);
await _settle(tester);
await tester.tap(_node('implement'));
await tester.pump();
expect(find.text('completed'), findsWidgets);
expect(find.text('×2'), findsOneWidget);
expect(find.text('2m 5s'), findsOneWidget);
expect(find.text('success: All green'), findsOneWidget);
expect(find.text('Fixed the two failing tests'), findsOneWidget);
await tester.tap(find.byKey(const Key('stage-popover-open-visit')));
await tester.pump();
expect(visits, ['implement']);
await tester.tap(_node('verify'));
await tester.pump();
expect(find.text('×1'), findsOneWidget);
expect(find.text('flutter test: 2 failures'), findsOneWidget);
// Open definition pushes the pinned stage definition page.
await tester.tap(find.byKey(const Key('stage-popover-open-definition')));
await tester.pumpAndSettle();
expect(find.text('verify definition'), findsOneWidget);
});
}
@@ -260,7 +260,7 @@ void main() {
});
testWidgets(
'a visited stage reports its key and an unvisited node does not',
'a visited stage opens its visit from the popover; an unvisited one has none',
(tester) async {
final picked = <String>[];
await tester.pumpWidget(
@@ -278,28 +278,26 @@ void main() {
final visited = tester.getSemantics(_node('plan')).getSemanticsData();
expect(visited.flagsCollection.isButton, isTrue);
expect(visited.hasAction(SemanticsAction.tap), isTrue);
// An unvisited stage still opens its declaration, with no status.
final unvisited = tester.getSemantics(_node('build')).getSemanticsData();
expect(unvisited.flagsCollection.isButton, isFalse);
expect(unvisited.hasAction(SemanticsAction.tap), isFalse);
expect(unvisited.flagsCollection.isButton, isTrue);
expect(unvisited.label, 'build');
await tester.tap(_node('plan'));
await tester.pump();
expect(picked, isEmpty);
await tester.tap(find.byKey(const Key('stage-popover-open-visit')));
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);
// `build` was never recorded in this run: its popover offers no visit,
// so nothing is ever fabricated.
await tester.tap(_node('build'));
await tester.pump();
expect(find.byKey(const Key('graph-stage-popover')), findsOneWidget);
expect(find.byKey(const Key('stage-popover-open-visit')), findsNothing);
expect(find.byKey(const Key('stage-popover-status')), findsNothing);
expect(picked, ['plan']);
expect(
find.ancestor(
of: _node('build'),
matching: find.byWidgetPredicate(
(widget) => widget is IgnorePointer && widget.ignoring,
),
),
findsOneWidget,
);
handle.dispose();
},
);
@@ -30,6 +30,10 @@ Future<void> _tapNode(WidgetTester tester, Finder node) async {
await tester.pumpAndSettle();
}
await tester.tap(node);
await tester.pump(); // A tap opens the stage's popover (or sheet); "Open definition" opens the
// pinned definition page, as a tap did before the popover.
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('stage-popover-open-definition')));
await tester.pump();
}
@@ -25,6 +25,10 @@ Future<void> _tapNode(WidgetTester tester, String key) async {
await tester.pumpAndSettle();
}
await tester.tap(_node(key));
await tester.pump(); // A tap opens the stage's popover (or sheet); "Open definition" opens the
// pinned definition page, as a tap did before the popover.
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('stage-popover-open-definition')));
await tester.pump();
}
@@ -182,7 +182,7 @@ void main() {
) async {
await pumpDeepLink(tester, RunDetailTestPlatform.material);
await openRunDetailTab(tester, RunDetailTab.graph);
await tapGraphNode(tester, 'plan');
await openGraphVisit(tester, 'plan');
await tester.pumpAndSettle();
// The web client's graph click takes the last visit in sequence order, not
@@ -156,3 +156,11 @@ Future<void> tapGraphNode(WidgetTester tester, String key) async {
await tester.pump();
await tester.pump();
}
/// Opens [key]'s stage popover (or sheet), then its "Open visit".
Future<void> openGraphVisit(WidgetTester tester, String key) async {
await tapGraphNode(tester, key);
await tester.pumpAndSettle();
await tester.tap(find.byKey(const Key('stage-popover-open-visit')));
await tester.pump();
}
@@ -46,7 +46,7 @@ void main() {
) async {
await pumpRunDetail(tester, platform);
await openRunDetailTab(tester, RunDetailTab.graph);
await tapGraphNode(tester, 'plan');
await openGraphVisit(tester, 'plan');
await tester.pumpAndSettle();
// The Graph reports the stage; the exact recorded visit opens as its
@@ -76,9 +76,11 @@ void main() {
) async {
await pumpRunDetail(tester, platform);
await openRunDetailTab(tester, RunDetailTab.graph);
// `audit` was never recorded: its node is not a control and a click must
// leave the detail on the Graph tab.
// `audit` was never recorded: its popover shows the declaration but
// offers no visit, and the detail stays on the Graph tab.
await tapGraphNode(tester, 'audit');
await tester.pumpAndSettle();
expect(find.byKey(const Key('stage-popover-open-visit')), findsNothing);
expect(find.byType(RunGraphView), findsOneWidget);
expect(
find.byKey(const Key('run-detail-tab-body-timeline')),
@@ -96,7 +98,7 @@ void main() {
scale: 2,
);
await openRunDetailTab(tester, RunDetailTab.graph);
await tapGraphNode(tester, 'plan');
await openGraphVisit(tester, 'plan');
await tester.pumpAndSettle();
// Leaving the visit page lands on Timeline. At 320/2x the strip
+47 -1
View File
@@ -256,16 +256,62 @@ JsonMap perfRunGraphFixture() => {
{
'key': 'plan',
'type': 'model',
'prompt': _planPrompt,
'configs': {
'harness': 'claude',
'model': 'anthropic/claude-sonnet-4-5-20250929',
'reasoning_effort': 'high',
'timeout': '20m',
'retries': '1',
'budget_usd': '4',
},
'blocks': {
'tools': 'read\nglob\ngrep\nedit\nmcp:pipelines',
'permissions': '{"edit": ["docs/**", "notes/**"]}',
},
'limits': {
'max_visits': 3,
'on': ['success'],
'on_exhausted': 'decide',
},
'edges': {'success': 'build', 'error': '#'},
},
{
'key': 'build',
'type': 'model',
'edges': {'success': 'plan', 'error': '#failure'},
'prompt': 'Build the release artifacts and report what changed.',
'configs': {'harness': 'codex', 'model': 'gpt-5-codex'},
'edges': {'success': 'plan', 'review': 'verify', 'error': '#failure'},
},
{
'key': 'verify',
'type': 'check',
'configs': {'command_timeout': '15m'},
'blocks': {
'commands':
'flutter analyze\ntool/memwatch/full.sh test\n'
'go test ./...',
},
'edges': {'pass': '#success', 'fail': 'build', 'error': '#failure'},
},
],
};
const String _planPrompt = '''## Goal
Plan the release train for this week.
1. Read the open changes since the last tag and group them by area.
2. Write `docs/release-plan.md` with the scope, the risks and the rollout order.
3. Call out anything that needs a migration or a feature flag.
## Constraints
- Keep the plan short: one screen per area.
- Do not edit source files; this stage only plans.
- Link each item to its change.
## Handoff
Finish with `# success` and a one-line summary of the plan.''';
/// Filler run hits for a query that `release` text matches.
List<JsonMap> perfSearchHits(String query, String kind) {
if (_hits == 0 || (kind.isNotEmpty && kind != 'run')) return const [];