Run card mini-map and stage strip; graph edge hover highlight

The show_run card carries the run's graph and per-stage progress (bounded by
the graph, not the run length) and draws a still mini-map with the run graph
plus a stage strip with status, visits and time. Hovering or tapping an edge
in the pipeline and run graphs highlights it, its label and endpoints, with a
tooltip naming from -> to, the outcome and, for runs, how often it was taken.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-12-03 12:56:51 +00:00
parent c4de1de27b
commit 7872e57d40
17 changed files with 1709 additions and 51 deletions
@@ -1,6 +1,9 @@
import '../../../core/api_gateway.dart';
import '../../pipelines/pipeline_format.dart' show formatDuration;
import '../../runs/domain/run_events.dart' show isTerminalRunStatus;
import 'chat_shown_run_map.dart';
export 'chat_shown_run_map.dart';
/// A `show_run` item's run, as the server records it
/// (`internal/protocol/chat_shown.go` ChatShownRunBody). The server pushes the
@@ -15,6 +18,7 @@ class ChatShownRun {
required this.currentStage,
required this.startedAt,
required this.finishedAt,
this.map,
});
/// The run of a `run` item, or null for any other item or a malformed one.
@@ -32,6 +36,7 @@ class ChatShownRun {
currentStage: _text(body['current_stage']),
startedAt: _millis(body['started_at']),
finishedAt: _millis(body['finished_at']),
map: ChatShownRunMap.of(body['map']),
);
}
@@ -44,6 +49,9 @@ class ChatShownRun {
final int? startedAt;
final int? finishedAt;
/// The graph and stage progress for the card's mini-map, when sent.
final ChatShownRunMap? map;
/// Whether the run has ended (succeeded, failed, canceled, interrupted).
bool get finished => isTerminalRunStatus(status);
@@ -0,0 +1,119 @@
import '../../../core/api_gateway.dart';
import '../../pipelines/pipeline_format.dart' show formatDuration;
/// One declared stage of a `show_run` card's map with its progress in the run
/// (`internal/protocol/chat_shown.go` ChatShownRunStage).
class ChatShownRunStage {
const ChatShownRunStage({
required this.key,
required this.type,
required this.visits,
required this.status,
required this.seconds,
required this.runningSince,
});
final String key;
final String type;
/// How many times the run entered the stage; 0 when it never did.
final int visits;
/// The latest visit's recorded status, empty when never visited.
final String status;
/// Seconds spent in the stage's finished visits.
final int seconds;
/// The running visit's start (epoch milliseconds), or null.
final int? runningSince;
bool get visited => visits > 0;
/// Total time in the stage at [now] (epoch milliseconds), counting a running
/// visit; null for a stage that never ran.
String? duration(int now) {
if (!visited) return null;
final since = runningSince;
final live = since == null || now < since ? 0 : (now - since) ~/ 1000;
return formatDuration(seconds + live);
}
}
/// A `show_run` card's map: the run's graph as the graph feature reads it and
/// the compact route evidence as run-detail steps, plus the stage list.
///
/// The server bounds it by the graph's size (ChatShownRunMapStages), not by
/// the run's length.
class ChatShownRunMap {
const ChatShownRunMap({
required this.graph,
required this.steps,
required this.stages,
});
/// The map of a run body, or null when the server sent none.
static ChatShownRunMap? of(Object? raw) {
if (raw is! Map) return null;
final rawStages = raw['stages'];
if (rawStages is! List) return null;
final stages = <ChatShownRunStage>[];
final definitions = <JsonMap>[];
for (final stage in rawStages.whereType<Map>()) {
final key = '${stage['key'] ?? ''}'.trim();
if (key.isEmpty) continue;
final edges = stage['edges'];
definitions.add({
'key': key,
'type': stage['type'],
'edges': edges is Map ? JsonMap.from(edges) : const <String, dynamic>{},
'fallback_error': stage['fallback_error'] == true,
});
stages.add(
ChatShownRunStage(
key: key,
type: '${stage['type'] ?? ''}',
visits: _int(stage['visits']) ?? 0,
status: '${stage['status'] ?? ''}'.trim(),
seconds: _int(stage['seconds']) ?? 0,
runningSince: _positive(stage['running_since']),
),
);
}
if (stages.isEmpty) return null;
final rawVisits = raw['visits'];
final steps = <JsonMap>[
if (rawVisits is List)
for (final visit in rawVisits.whereType<Map>())
{
'sequence': visit['sequence'],
'stage': '${visit['stage'] ?? ''}',
'status': '${visit['status'] ?? ''}',
'outcome': '${visit['outcome'] ?? ''}',
'target': '${visit['target'] ?? ''}',
},
];
return ChatShownRunMap(
graph: {'stages': definitions},
steps: steps,
stages: stages,
);
}
/// The graph definition shape (`stages` with `key`, `edges`).
final JsonMap graph;
/// The route evidence in the run-detail step shape, in sequence order.
final List<JsonMap> steps;
final List<ChatShownRunStage> stages;
/// The run-detail map the graph feature reads its evidence from.
JsonMap runDetail({required String currentStage, required bool executing}) =>
{'steps': steps, 'current_stage': currentStage, 'executing': executing};
}
int? _int(Object? value) => value is num ? value.toInt() : null;
int? _positive(Object? value) =>
value is num && value > 0 ? value.toInt() : null;
@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';
import '../../../../../core/api_gateway.dart';
import '../../../chat_run_opener.dart';
import '../../../domain/chat_shown_run.dart';
import 'chat_shown_run_map_view.dart';
import 'chat_shown_surface.dart';
/// The glyph of a run status.
@@ -134,6 +135,10 @@ class _ChatShownRunCardState extends State<ChatShownRunCard> {
),
],
),
if (run.map case final map?) ...[
const SizedBox(height: 10),
ChatShownRunMapView(run: run, map: map, now: _now),
],
],
),
);
@@ -0,0 +1,175 @@
import 'package:flutter/material.dart';
import '../../../../graph/widgets/run_graph_view.dart';
import '../../../domain/chat_shown_run.dart';
/// The mini-map's height: enough for one row of stages and the ends below it
/// at a glance, small enough to keep the card compact.
const double chatShownRunMapHeight = 136;
/// A `show_run` card's graph: a still mini-map of the run's pipeline drawn by
/// the run graph itself (visited stages with their status, the live stage's
/// halo, the taken path solid and untaken routes dashed), then a strip of every
/// stage with its status, visits and time.
class ChatShownRunMapView extends StatelessWidget {
const ChatShownRunMapView({
super.key,
required this.run,
required this.map,
required this.now,
});
final ChatShownRun run;
final ChatShownRunMap map;
/// The current time in epoch milliseconds, for running stages' durations.
final int now;
@override
Widget build(BuildContext context) {
final colors = Theme.of(context).colorScheme;
final current = run.finished ? '' : run.currentStage;
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
mainAxisSize: MainAxisSize.min,
children: [
DecoratedBox(
decoration: BoxDecoration(
color: colors.surfaceContainerLow,
border: Border.all(color: colors.outlineVariant),
borderRadius: BorderRadius.circular(8),
),
child: ClipRRect(
borderRadius: BorderRadius.circular(8),
child: SizedBox(
key: const Key('chat-shown-run-map'),
height: chatShownRunMapHeight,
child: Padding(
padding: const EdgeInsets.all(6),
child: RunGraphView(
graph: map.graph,
run: map.runDetail(
currentStage: run.currentStage,
executing: !run.finished,
),
onStageSelected: (_) {},
showHeader: false,
expandable: false,
still: true,
),
),
),
),
),
const SizedBox(height: 8),
Wrap(
key: const Key('chat-shown-run-stages'),
spacing: 6,
runSpacing: 6,
children: [
for (final stage in map.stages)
_StageEntry(
stage: stage,
current: stage.key == current,
duration: stage.duration(now),
),
],
),
],
);
}
}
/// The glyph of a recorded stage status; a stage never entered is a hollow
/// circle.
IconData chatShownStageIcon(String status, {required bool visited}) {
if (!visited) return Icons.radio_button_unchecked;
return switch (status) {
'completed' || 'succeeded' => Icons.check_circle,
'failed' => Icons.error,
'running' => Icons.play_circle,
'waiting' => Icons.front_hand,
'interrupted' => Icons.pause_circle,
'canceled' => Icons.cancel,
_ => Icons.circle,
};
}
Color _stageColor(ColorScheme colors, ChatShownRunStage stage) {
if (!stage.visited) return colors.outline;
return switch (stage.status) {
'completed' || 'succeeded' => colors.primary,
'failed' || 'interrupted' => colors.error,
'running' || 'waiting' => colors.tertiary,
_ => colors.onSurfaceVariant,
};
}
/// One stage of the strip: status glyph, name, `×visits` when it looped and
/// the time spent. The run's current stage is filled and bold.
class _StageEntry extends StatelessWidget {
const _StageEntry({
required this.stage,
required this.current,
required this.duration,
});
final ChatShownRunStage stage;
final bool current;
final String? duration;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final colors = theme.colorScheme;
final base = theme.textTheme.labelMedium ?? const TextStyle();
final name = base.copyWith(
color: stage.visited ? colors.onSurface : colors.onSurfaceVariant,
fontWeight: current ? FontWeight.w700 : null,
);
final meta = base.copyWith(color: colors.onSurfaceVariant);
final status = stage.visited ? stage.status : 'not run';
final facts = [if (stage.visits > 1) '×${stage.visits}', ?duration];
return Semantics(
container: true,
label: [
stage.key,
status,
if (stage.visits > 1) '${stage.visits} visits',
?duration,
if (current) 'current stage',
].join(', '),
child: ExcludeSemantics(
child: DecoratedBox(
key: ValueKey('chat-shown-run-stage:${stage.key}'),
decoration: BoxDecoration(
color: current ? colors.secondaryContainer : null,
border: Border.all(
color: current ? colors.secondary : colors.outlineVariant,
),
borderRadius: BorderRadius.circular(8),
),
child: Padding(
padding: const EdgeInsetsDirectional.fromSTEB(6, 3, 8, 3),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
chatShownStageIcon(stage.status, visited: stage.visited),
size: MediaQuery.textScalerOf(context).scale(14),
color: _stageColor(colors, stage),
),
const SizedBox(width: 4),
Text(stage.key, style: name),
if (facts.isNotEmpty) ...[
const SizedBox(width: 6),
Text(facts.join(' · '), style: meta),
],
],
),
),
),
),
);
}
}
@@ -0,0 +1,91 @@
import 'package:flutter/material.dart';
import '../layout/layout_models.dart';
import '../routing/route_models.dart';
import 'graph_edge_layer.dart';
/// Paints one highlighted edge over the other routes and behind the nodes: a
/// soft glow under the two endpoint stages, then the route in [color] at a
/// heavier stroke with its arrow, on a translucent halo.
///
/// Passive like the other edge layers: it never takes a hit.
class EdgeHighlightPainter extends CustomPainter {
EdgeHighlightPainter({
required this.route,
required this.endpoints,
required this.color,
required this.strokeWidth,
});
final EdgeRoute route;
/// The source and target node boxes (one for a self loop).
final List<GraphNodeBox> endpoints;
final Color color;
/// The highlighted stroke; the halo is wider.
final double strokeWidth;
@override
void paint(Canvas canvas, Size size) {
final glow = Paint()..color = color.withValues(alpha: 0.18);
for (final box in endpoints) {
final rect = Rect.fromLTWH(box.x, box.y, box.width, box.height);
canvas.drawRRect(
RRect.fromRectAndRadius(rect.inflate(5), const Radius.circular(14)),
glow,
);
}
if (route.points.length < 2) return;
final geometry = GraphEdgePainter(
routes: [route],
color: color,
strokeWidth: strokeWidth,
);
final line = geometry.linePath(route);
canvas.drawPath(
line,
Paint()
..color = color.withValues(alpha: 0.22)
..strokeWidth = strokeWidth * 3
..style = PaintingStyle.stroke
..strokeJoin = StrokeJoin.round
..strokeCap = StrokeCap.round,
);
canvas.drawPath(
line,
Paint()
..color = color
..strokeWidth = strokeWidth
..style = PaintingStyle.stroke
..strokeJoin = StrokeJoin.round,
);
canvas.drawPath(
GraphEdgePainter(
routes: [route],
color: color,
// The arrow scales with the stroke; keep it near the plain arrow.
strokeWidth: strokeWidth / 1.5,
).arrowPath(route),
Paint()..color = color,
);
}
@override
bool hitTest(Offset position) => false;
@override
bool shouldRepaint(EdgeHighlightPainter oldDelegate) =>
oldDelegate.route != route ||
oldDelegate.color != color ||
oldDelegate.strokeWidth != strokeWidth ||
oldDelegate.endpoints.length != endpoints.length ||
!_sameBoxes(oldDelegate.endpoints, endpoints);
static bool _sameBoxes(List<GraphNodeBox> a, List<GraphNodeBox> b) {
for (var index = 0; index < a.length; index += 1) {
if (a[index] != b[index]) return false;
}
return true;
}
}
@@ -0,0 +1,68 @@
import 'dart:math' as math;
import 'dart:ui' show Offset, Rect;
import '../layout/layout_models.dart';
import '../routing/route_models.dart';
/// Which routed edge a pointer at [point] (graph space) is on, or null.
///
/// A point inside a node box belongs to the node, never to an edge. A point on
/// an edge's label box is that edge. Otherwise the nearest route polyline
/// within [tolerance] wins, so overlapping corridors pick the closest lane and
/// self loops and back edges are hit along every bend they take.
int? hitTestEdge({
required List<EdgeRoute> routes,
required List<EdgeLabelBox> labels,
required List<GraphNodeBox> nodes,
required Offset point,
required double tolerance,
}) {
for (final node in nodes) {
if (Rect.fromLTWH(
node.x,
node.y,
node.width,
node.height,
).contains(point)) {
return null;
}
}
for (final label in labels) {
final box = Rect.fromLTWH(label.x, label.y, label.width, label.height);
if (box.inflate(2).contains(point)) return label.edgeId;
}
int? best;
var bestDistance = tolerance;
for (final route in routes) {
final distance = distanceToRoute(route, point);
if (distance <= bestDistance) {
best = route.id;
bestDistance = distance;
}
}
return best;
}
/// The shortest distance from [point] to [route]'s polyline.
double distanceToRoute(EdgeRoute route, Offset point) {
final points = route.points;
if (points.isEmpty) return double.infinity;
var best = double.infinity;
for (var index = 0; index < points.length; index += 1) {
final a = Offset(points[index].x, points[index].y);
final b = index + 1 < points.length
? Offset(points[index + 1].x, points[index + 1].y)
: a;
best = math.min(best, _distanceToSegment(point, a, b));
}
return best;
}
double _distanceToSegment(Offset p, Offset a, Offset b) {
final ab = b - a;
final lengthSquared = ab.distanceSquared;
if (lengthSquared == 0) return (p - a).distance;
final t = (((p.dx - a.dx) * ab.dx + (p.dy - a.dy) * ab.dy) / lengthSquared)
.clamp(0.0, 1.0);
return (p - (a + ab * t)).distance;
}
@@ -1,10 +1,11 @@
import 'package:flutter/widgets.dart';
import 'package:flutter/material.dart';
import '../domain/graph_definition.dart';
import '../layout/layout_models.dart';
import '../painting/graph_edge_layer.dart';
import '../routing/route_models.dart';
import 'graph_canvas_style.dart';
import 'graph_edge_hover.dart';
import 'graph_stage_node.dart';
/// The measured definition canvas at any viewport size and selection.
@@ -36,6 +37,22 @@ 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),
);
}
Widget _canvas(
BuildContext context,
Map<String, GraphNode> nodesByKey,
Size size,
int? highlighted,
ValueChanged<int> select,
) {
return Stack(
clipBehavior: Clip.none,
children: [
@@ -49,6 +66,15 @@ class DefinitionGraphCanvas extends StatelessWidget {
strokeWidth: style.edgeWidth,
),
),
Positioned.fill(
child: graphEdgeHighlight(
context: context,
layout: layout,
routing: routing,
highlighted: highlighted,
edgeWidth: style.edgeWidth,
),
),
for (final box in layout.nodes)
Positioned(
left: box.x,
@@ -65,9 +91,19 @@ class DefinitionGraphCanvas extends StatelessWidget {
Positioned(
left: label.x,
top: label.y,
child: Text(
routing.routeFor(label.edgeId)!.label,
style: style.labelStyle,
child: graphEdgeLabel(
context: context,
highlighted: label.edgeId == highlighted,
description: describeGraphEdge(routing.routeFor(label.edgeId)!),
onSelect: () => select(label.edgeId),
child: Text(
routing.routeFor(label.edgeId)!.label,
style: graphEdgeLabelStyle(
context,
style.labelStyle,
highlighted: label.edgeId == highlighted,
),
),
),
),
],
@@ -0,0 +1,282 @@
import 'package:flutter/gestures.dart' show PointerDeviceKind;
import 'package:flutter/material.dart';
import '../domain/graph_protocol.dart';
import '../layout/layout_models.dart';
import '../painting/edge_highlight_layer.dart';
import '../painting/edge_hit_test.dart';
import '../routing/route_models.dart';
/// Builds a graph canvas with [highlighted] (an edge id, or null) emphasized.
/// [select] highlights an edge without a pointer, e.g. from semantics.
typedef GraphEdgeHoverBuilder =
Widget Function(
BuildContext context,
int? highlighted,
ValueChanged<int> select,
);
/// How far from a route, in screen pixels, a pointer still counts as on it.
const double graphEdgeHitTolerance = 8;
/// Highlights the edge under the pointer of a graph canvas, and shows what it
/// is in a tooltip: hovering with a mouse, or tapping with touch (tap again
/// elsewhere to clear).
///
/// Wraps the canvas in graph space, inside any pan/zoom transform, so hits are
/// tested against the routed polylines and label boxes with a tolerance that
/// stays [graphEdgeHitTolerance] screen pixels at every zoom. Nodes keep their
/// own taps; a point over a node is never an edge.
class GraphEdgeHover extends StatefulWidget {
const GraphEdgeHover({
super.key,
required this.layout,
required this.routing,
required this.describe,
required this.builder,
});
final GraphLayout layout;
final GraphRouting routing;
/// The tooltip text for one edge.
final String Function(EdgeRoute route) describe;
final GraphEdgeHoverBuilder builder;
@override
State<GraphEdgeHover> createState() => _GraphEdgeHoverState();
}
class _GraphEdgeHoverState extends State<GraphEdgeHover> {
final OverlayPortalController _tooltip = OverlayPortalController();
int? _hovered;
int? _pinned;
Offset? _pointer;
int? get _highlighted => _hovered ?? _pinned;
/// Graph-space pixels per screen pixel under the current transform.
double _tolerance() {
final box = context.findRenderObject();
if (box is! RenderBox || !box.attached) return graphEdgeHitTolerance;
final scale =
(box.localToGlobal(const Offset(1, 0)) - box.localToGlobal(Offset.zero))
.distance;
return scale <= 0 ? graphEdgeHitTolerance : graphEdgeHitTolerance / scale;
}
int? _hit(Offset local) => hitTestEdge(
routes: widget.routing.routes,
labels: widget.routing.labels,
nodes: widget.layout.nodes,
point: local,
tolerance: _tolerance(),
);
void _update({int? hovered, int? pinned, Offset? pointer, bool pin = false}) {
final nextPinned = pin ? pinned : _pinned;
if (hovered == _hovered && nextPinned == _pinned && pointer == _pointer) {
return;
}
setState(() {
_hovered = hovered;
_pinned = nextPinned;
_pointer = pointer;
});
_syncTooltip();
}
void _syncTooltip() {
if (_highlighted != null && _pointer != null) {
_tooltip.show();
} else {
_tooltip.hide();
}
}
@override
void didUpdateWidget(covariant GraphEdgeHover oldWidget) {
super.didUpdateWidget(oldWidget);
// A re-laid graph may have dropped the highlighted edge.
bool known(int? id) => id != null && widget.routing.routeFor(id) != null;
if (!known(_hovered)) _hovered = null;
if (!known(_pinned)) _pinned = null;
if (_highlighted == null) _pointer = null;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) _syncTooltip();
});
}
@override
Widget build(BuildContext context) {
final canvas = MouseRegion(
onHover: (event) {
final id = _hit(event.localPosition);
_update(hovered: id, pointer: id == null ? null : event.position);
},
onExit: (_) =>
_update(hovered: null, pointer: _pinned == null ? null : _pointer),
child: GestureDetector(
behavior: HitTestBehavior.translucent,
// A tap pins the edge under it (touch has no hover); tapping it again
// or anywhere off an edge clears it.
onTapUp: (details) {
final id = _hit(details.localPosition);
final hovered = details.kind == PointerDeviceKind.mouse
? _hovered
: null;
final pinned = id == _pinned ? null : id;
_update(
hovered: hovered,
pinned: pinned,
pin: true,
pointer: (hovered ?? pinned) == null
? null
: details.globalPosition,
);
},
child: widget.builder(context, _highlighted, (id) {
_update(hovered: _hovered, pinned: id, pin: true, pointer: _pointer);
}),
),
);
if (Overlay.maybeOf(context) == null) return canvas;
return OverlayPortal(
controller: _tooltip,
overlayChildBuilder: _buildTooltip,
child: canvas,
);
}
Widget _buildTooltip(BuildContext context) {
final id = _highlighted;
final pointer = _pointer;
final route = id == null ? null : widget.routing.routeFor(id);
final overlay = Overlay.of(context).context.findRenderObject();
if (route == null || pointer == null || overlay is! RenderBox) {
return const SizedBox.shrink();
}
final local = overlay.globalToLocal(pointer);
final size = overlay.size;
final theme = Theme.of(context);
final colors = theme.colorScheme;
const gap = 14.0;
final flipX = local.dx > size.width * 0.6;
final flipY = local.dy > size.height * 0.75;
return Positioned(
left: flipX ? null : local.dx + gap,
right: flipX ? size.width - local.dx + gap : null,
top: flipY ? null : local.dy + gap,
bottom: flipY ? size.height - local.dy + gap : null,
child: IgnorePointer(
child: ConstrainedBox(
constraints: BoxConstraints(maxWidth: size.width * 0.6),
child: Material(
key: const Key('graph-edge-tooltip'),
color: colors.inverseSurface,
elevation: 2,
borderRadius: BorderRadius.circular(6),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
child: Text(
widget.describe(route),
style: theme.textTheme.bodySmall?.copyWith(
color: colors.onInverseSurface,
),
),
),
),
),
),
);
}
}
/// The highlight layer a canvas places above its edges and below its nodes,
/// or nothing when no edge is highlighted.
Widget graphEdgeHighlight({
required BuildContext context,
required GraphLayout layout,
required GraphRouting routing,
required int? highlighted,
required double edgeWidth,
}) {
final route = highlighted == null ? null : routing.routeFor(highlighted);
if (route == null) return const SizedBox.shrink();
final endpoints = [
?layout.nodeFor(route.source),
if (route.target != route.source) ?layout.nodeFor(route.target),
];
return IgnorePointer(
child: CustomPaint(
key: ValueKey('graph-edge-highlight:${route.id}'),
size: Size(routing.width, routing.height),
painter: EdgeHighlightPainter(
route: route,
endpoints: endpoints,
color: Theme.of(context).colorScheme.primary,
strokeWidth: edgeWidth * 2.5,
),
),
);
}
/// What an edge is, for its tooltip and screen readers: `from → to`, the
/// outcome, and for a run how many times it was taken ([taken] null for a
/// definition).
String describeGraphEdge(EdgeRoute route, {int? taken}) {
final lines = [
'${nodeDisplayLabel(route.source)} → ${nodeDisplayLabel(route.target)}',
'Outcome: ${route.label}',
if (taken != null)
switch (taken) {
0 => 'Not taken',
1 => 'Taken once',
_ => 'Taken $taken times',
},
];
return lines.join('\n');
}
/// The label style of a highlighted edge: [base] on the emphasis container.
TextStyle graphEdgeLabelStyle(
BuildContext context,
TextStyle base, {
required bool highlighted,
}) => highlighted
? base.copyWith(color: Theme.of(context).colorScheme.onPrimaryContainer)
: base;
/// An outcome label drawn emphasized while its edge is highlighted. The
/// emphasis is a backdrop only, so the measured label box does not change.
/// [description] names the edge for screen readers; activating it highlights
/// the edge through [onSelect].
Widget graphEdgeLabel({
required BuildContext context,
required Widget child,
required bool highlighted,
required String description,
required VoidCallback onSelect,
}) {
final colors = Theme.of(context).colorScheme;
return Semantics(
container: true,
label: description,
selected: highlighted,
onTap: onSelect,
child: ExcludeSemantics(
child: !highlighted
? child
: DecoratedBox(
decoration: BoxDecoration(
color: colors.primaryContainer,
borderRadius: BorderRadius.circular(4),
boxShadow: [
BoxShadow(color: colors.primaryContainer, spreadRadius: 2),
],
),
child: child,
),
),
);
}
@@ -7,6 +7,7 @@ import '../layout/layout_models.dart';
import '../painting/graph_edge_layer.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';
@@ -199,56 +200,115 @@ class RunGraphCanvas extends StatelessWidget {
final size = Size(routing.width, routing.height);
final activeStage = state.activeStage;
final executedColor = Theme.of(context).colorScheme.primary;
return Stack(
clipBehavior: Clip.none,
children: [
Positioned.fill(
child: RunGraphEdgeLayer(
executedRoutes: executed,
untakenRoutes: untaken,
canvasSize: size,
executedColor: executedColor,
untakenColor: style.edgeColor,
strokeWidth: style.edgeWidth,
),
),
for (final box in layout.nodes)
Positioned(
left: box.x,
top: box.y,
width: box.width,
height: box.height,
child: RunGraphNode(
node: nodesByKey[box.key]!,
recordedStatus: recordedStatuses[box.key],
selected: box.key == selectedStage,
active: box.key == activeStage,
opensVisit:
!nodesByKey[box.key]!.terminal &&
state.isStageVisited(box.key),
onSelected: onStageSelected,
String describe(EdgeRoute route) => describeGraphEdge(
route,
taken: state.routeOrder(route.source, route.outcome, route.target).length,
);
return GraphEdgeHover(
layout: layout,
routing: routing,
describe: describe,
builder: (context, highlighted, select) => Stack(
clipBehavior: Clip.none,
children: [
Positioned.fill(
child: RunGraphEdgeLayer(
executedRoutes: executed,
untakenRoutes: untaken,
canvasSize: size,
executedColor: executedColor,
untakenColor: style.edgeColor,
strokeWidth: style.edgeWidth,
),
),
// A run labels only the routes that actually happened.
for (final label in routing.labels)
if (executedIds.contains(label.edgeId))
Positioned(
left: label.x,
top: label.y,
child: _takenLabel(
routing.routeFor(label.edgeId)!,
executedColor,
),
Positioned.fill(
child: graphEdgeHighlight(
context: context,
layout: layout,
routing: routing,
highlighted: highlighted,
edgeWidth: style.edgeWidth,
),
],
),
..._placed(
context,
nodesByKey,
executedIds,
executedColor,
activeStage,
highlighted,
select,
describe,
),
],
),
);
}
Widget _takenLabel(EdgeRoute route, Color color) => RunRouteLabel(
List<Widget> _placed(
BuildContext context,
Map<String, GraphNode> nodesByKey,
Set<int> executedIds,
Color executedColor,
String? activeStage,
int? highlighted,
ValueChanged<int> select,
String Function(EdgeRoute) describe,
) {
return [
for (final box in layout.nodes)
Positioned(
left: box.x,
top: box.y,
width: box.width,
height: box.height,
child: RunGraphNode(
node: nodesByKey[box.key]!,
recordedStatus: recordedStatuses[box.key],
selected: box.key == selectedStage,
active: box.key == activeStage,
opensVisit:
!nodesByKey[box.key]!.terminal && state.isStageVisited(box.key),
onSelected: onStageSelected,
),
),
// A run labels only the routes that actually happened, and the route
// being highlighted so its outcome reads where it is drawn.
for (final label in routing.labels)
if (executedIds.contains(label.edgeId) || label.edgeId == highlighted)
Positioned(
left: label.x,
top: label.y,
child: graphEdgeLabel(
context: context,
highlighted: label.edgeId == highlighted,
description: describe(routing.routeFor(label.edgeId)!),
onSelect: () => select(label.edgeId),
child: _takenLabel(
context,
routing.routeFor(label.edgeId)!,
executedColor,
highlighted: label.edgeId == highlighted,
),
),
),
];
}
Widget _takenLabel(
BuildContext context,
EdgeRoute route,
Color color, {
required bool highlighted,
}) => RunRouteLabel(
edgeId: route.id,
label: route.label,
order: state.routeOrder(route.source, route.outcome, route.target),
style: style.labelStyle,
style: graphEdgeLabelStyle(
context,
style.labelStyle,
highlighted: highlighted,
),
color: color,
);
}
@@ -48,8 +48,13 @@ class RunGraphView extends StatefulWidget {
this.now,
this.showHeader = true,
this.expandable = true,
this.still = false,
});
/// True for a mini-map: the whole graph scaled to fit the box, with no
/// pan/zoom viewport, controls, input or semantics of its own.
final bool still;
/// False when this graph is already the full-screen view: no maximise.
final bool expandable;
@@ -207,7 +212,9 @@ class _RunGraphViewState extends State<RunGraphView> {
child: Stack(
fit: StackFit.expand,
children: [
if (geometry != null)
if (geometry != null && widget.still)
_stillCanvas(nodes, geometry, state, style, statuses)
else if (geometry != null)
GraphViewport(
controller: _viewport,
contentSize: Size(geometry.$2.width, geometry.$2.height),
@@ -273,6 +280,40 @@ class _RunGraphViewState extends State<RunGraphView> {
),
);
/// The whole measured canvas scaled down (never up) to fit the box: a
/// picture with no input or semantics, for a mini-map.
Widget _stillCanvas(
List<GraphNode> nodes,
(GraphLayout, GraphRouting) geometry,
RunGraphState state,
GraphCanvasStyle style,
Map<String, String?> statuses,
) {
final routing = geometry.$2;
return ExcludeSemantics(
child: IgnorePointer(
child: FittedBox(
key: const Key('run-graph-still'),
fit: BoxFit.scaleDown,
child: SizedBox(
width: routing.width,
height: routing.height,
child: _runCanvas(
nodes: nodes,
layout: geometry.$1,
routing: routing,
state: state,
style: style,
statuses: statuses,
selectedStage: widget.selectedStage,
onStageSelected: widget.onStageSelected,
),
),
),
),
);
}
/// The same measured run canvas at any viewport size and selection, used by
/// the inline viewport and the expanded presentation.
Widget _runCanvas({
@@ -0,0 +1,273 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/chat_run_opener.dart';
import 'package:pipelines_app/features/chat/domain/chat_shown_run.dart';
import 'package:pipelines_app/features/chat/ui/transcript/shown/chat_shown_run_card.dart';
import 'package:pipelines_app/features/chat/ui/transcript/shown/chat_shown_run_map_view.dart';
import 'package:pipelines_app/features/graph/widgets/graph_stage_node.dart';
import 'package:pipelines_app/features/graph/widgets/run_graph_canvas.dart';
final _start = DateTime.utc(2026, 12, 1, 9);
int _at(int seconds) =>
_start.add(Duration(seconds: seconds)).millisecondsSinceEpoch;
/// plan → implement ⇄ review → #success, as the server sends a card's map.
JsonMap _map({
required String review,
int reviewVisits = 1,
int? reviewRunningSince,
List<JsonMap> extraVisits = const [],
}) => {
'stages': [
{
'key': 'plan',
'edges': {'success': 'implement'},
'visits': 1,
'status': 'completed',
'seconds': 65,
},
{
'key': 'implement',
'edges': {'success': 'review'},
'visits': 2,
'status': 'completed',
'seconds': 600,
},
{
'key': 'review',
'edges': {'success': '#', 'changes': 'implement'},
'fallback_error': true,
'visits': reviewVisits,
'status': review,
'seconds': 30,
'running_since': ?reviewRunningSince,
},
],
'visits': [
{
'sequence': 1,
'stage': 'plan',
'status': 'completed',
'outcome': 'success',
'target': 'implement',
},
{
'sequence': 3,
'stage': 'review',
'status': 'completed',
'outcome': 'changes',
'target': 'implement',
},
{
'sequence': 4,
'stage': 'implement',
'status': 'completed',
'outcome': 'success',
'target': 'review',
},
...extraVisits,
],
};
JsonMap _item(String status, JsonMap map, {int? finishedAt}) => {
'id': 'r',
'kind': 'run',
'run': {
'id': 42,
'pipeline': 'Feature',
'title': 'Add the mini-map',
'status': status,
'current_stage': 'review',
'started_at': _start.millisecondsSinceEpoch,
'finished_at': ?finishedAt,
'map': map,
},
};
Finder _stage(String key) => find.byKey(ValueKey('chat-shown-run-stage:$key'));
void main() {
final opened = <int>[];
Future<void> pump(WidgetTester tester, JsonMap item, {int now = 0}) async {
await tester.binding.setSurfaceSize(const Size(480, 900));
addTearDown(() => tester.binding.setSurfaceSize(null));
await tester.pumpWidget(
ChatRunOpener(
openRun: opened.add,
child: MaterialApp(
home: Scaffold(
body: SingleChildScrollView(
child: ChatShownRunCard(
key: const ValueKey('card'),
item: item,
now: () => DateTime.fromMillisecondsSinceEpoch(now),
),
),
),
),
),
);
for (var i = 0; i < 3; i += 1) {
await tester.pump();
}
}
test('the map reads stages, progress and route evidence', () {
final map = ChatShownRunMap.of(
_map(review: 'running', reviewRunningSince: _at(0)),
)!;
expect(map.stages.map((s) => s.key), ['plan', 'implement', 'review']);
expect(map.stages[1].visits, 2);
expect(map.stages[2].duration(_at(15)), '45s');
expect(map.graph['stages'], hasLength(3));
expect(map.steps.map((s) => s['sequence']), [1, 3, 4]);
expect(ChatShownRunMap.of(null), isNull);
expect(ChatShownRunMap.of({'stages': []}), isNull);
});
testWidgets('a running run draws its graph and stage strip, live', (
tester,
) async {
final item = _item(
'running',
_map(
review: 'running',
reviewVisits: 2,
reviewRunningSince: _at(100),
extraVisits: [
{'sequence': 5, 'stage': 'review', 'status': 'running'},
],
),
);
await pump(tester, item, now: _at(110));
expect(find.byKey(const Key('chat-shown-run-map')), findsOneWidget);
expect(find.byKey(const Key('run-graph-still')), findsOneWidget);
// The still graph is the run graph: review is the live stage.
final review = tester.widget<RunGraphNode>(
find.byWidgetPredicate(
(w) => w is RunGraphNode && w.node.key == 'review',
),
);
expect(review.active, isTrue);
expect(review.recordedStatus, 'running');
// The taken loop is drawn solid, the untaken success route dashed.
final edges = tester.widget<RunGraphEdgeLayer>(
find.byType(RunGraphEdgeLayer),
);
expect(
edges.executedRoutes.map((r) => '${r.source}>${r.outcome}'),
containsAll(['plan>success', 'implement>success', 'review>changes']),
);
expect(
edges.untakenRoutes.map((r) => '${r.source}>${r.outcome}'),
contains('review>success'),
);
// The stage strip: visits, durations, the current stage emphasized.
expect(find.text('1m 5s'), findsOneWidget);
expect(find.text('×2 · 10m 0s'), findsOneWidget);
expect(find.text('×2 · 40s'), findsOneWidget);
expect(
find.descendant(
of: _stage('review'),
matching: find.byIcon(Icons.play_circle),
),
findsOneWidget,
);
final name = tester.widget<Text>(
find.descendant(of: _stage('review'), matching: find.text('review')),
);
expect(name.style?.fontWeight, FontWeight.w700);
// The mini-map is a picture: the card still opens the run.
await tester.tap(
find.byKey(const Key('chat-shown-run-map')),
warnIfMissed: false,
);
expect(opened, [42]);
});
testWidgets('a failed run marks the failed stage and has no live stage', (
tester,
) async {
await pump(
tester,
_item(
'failed',
_map(
review: 'failed',
extraVisits: [
{
'sequence': 5,
'stage': 'review',
'status': 'failed',
'outcome': 'error',
'target': '#',
},
],
),
finishedAt: _at(700),
),
now: _at(900),
);
expect(
find.descendant(of: _stage('review'), matching: find.byIcon(Icons.error)),
findsOneWidget,
);
final review = tester.widget<RunGraphNode>(
find.byWidgetPredicate(
(w) => w is RunGraphNode && w.node.key == 'review',
),
);
expect(review.active, isFalse);
expect(review.recordedStatus, 'failed');
final failure = find.byWidgetPredicate(
(w) => w is GraphStageNode && w.node.key == '#failure',
);
expect(failure, findsOneWidget);
final name = tester.widget<Text>(
find.descendant(of: _stage('review'), matching: find.text('review')),
);
expect(name.style?.fontWeight, isNot(FontWeight.w700));
});
testWidgets('a succeeded run checks every stage; no map, no strip', (
tester,
) async {
await pump(
tester,
_item('succeeded', _map(review: 'completed'), finishedAt: _at(700)),
now: _at(900),
);
for (final key in ['plan', 'implement', 'review']) {
expect(
find.descendant(
of: _stage(key),
matching: find.byIcon(Icons.check_circle),
),
findsOneWidget,
);
}
final item = _item('running', _map(review: 'running'));
(item['run'] as Map).remove('map');
await pump(tester, item, now: _at(10));
expect(find.byKey(const Key('chat-shown-run-map')), findsNothing);
expect(find.byType(ChatShownRunMapView), findsNothing);
});
testWidgets('a stage that never ran reads as not run', (tester) async {
final map = _map(review: '');
((map['stages'] as List)[2] as Map)
..['visits'] = 0
..remove('seconds');
await pump(tester, _item('running', map), now: _at(10));
expect(
find.descendant(
of: _stage('review'),
matching: find.byIcon(Icons.radio_button_unchecked),
),
findsOneWidget,
);
expect(find.bySemanticsLabel(RegExp('^review, not run')), findsOneWidget);
});
}
@@ -0,0 +1,202 @@
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/painting/edge_hit_test.dart';
import 'package:pipelines_app/features/graph/routing/route_models.dart';
import 'package:pipelines_app/features/graph/widgets/definition_graph_view.dart';
import 'package:pipelines_app/features/graph/widgets/graph_edge_hover.dart';
import 'package:pipelines_app/features/graph/widgets/run_graph_view.dart';
import '../domain/graph_fixtures.dart';
Widget _host(Widget graph) => MaterialApp(
home: Scaffold(
body: Align(
alignment: Alignment.topLeft,
child: SizedBox(width: 900, height: 600, child: graph),
),
),
);
Future<void> _settle(WidgetTester tester) async {
await tester.pump();
await tester.pump();
await tester.pump();
}
GraphEdgeHover _hover(WidgetTester tester) =>
tester.widget<GraphEdgeHover>(find.byType(GraphEdgeHover).first);
EdgeRoute _route(WidgetTester tester, String source, String outcome) =>
_hover(tester).routing.routes.firstWhere(
(route) => route.source == source && route.outcome == outcome,
);
/// A global point on [route] that hits only it: sampled along its segments,
/// clear of nodes, labels and other routes.
Offset _onRoute(WidgetTester tester, EdgeRoute route) {
final hover = _hover(tester);
final box = tester.renderObject<RenderBox>(find.byType(GraphEdgeHover).first);
for (var index = 0; index + 1 < route.points.length; index += 1) {
final a = Offset(route.points[index].x, route.points[index].y);
final b = Offset(route.points[index + 1].x, route.points[index + 1].y);
for (final t in const [0.5, 0.3, 0.7, 0.2, 0.8]) {
final point = Offset.lerp(a, b, t)!;
final others = hover.routing.routes.where((r) => r.id != route.id);
final clear = others.every((r) => distanceToRoute(r, point) > 10);
final hit = hitTestEdge(
routes: hover.routing.routes,
labels: const [],
nodes: hover.layout.nodes,
point: point,
tolerance: 1,
);
final inLabel = hover.routing.labels.any(
(l) =>
l.edgeId != route.id &&
Rect.fromLTWH(
l.x,
l.y,
l.width,
l.height,
).inflate(4).contains(point),
);
if (clear && !inLabel && hit == route.id) return box.localToGlobal(point);
}
}
throw StateError('no clear point on route ${route.id}');
}
Finder _highlight(int id) => find.byKey(ValueKey('graph-edge-highlight:$id'));
void main() {
test('hit testing follows bends, prefers nodes and labels', () {
final loop = EdgeRoute(
id: 1,
source: 'a',
outcome: 'retry',
target: 'a',
label: 'retry',
fallback: false,
kind: RouteKind.values.first,
straight: false,
sourcePort: const RoutePort(
side: RoutePortSide.top,
point: RoutePoint(10, 0),
),
targetPort: const RoutePort(
side: RoutePortSide.top,
point: RoutePoint(40, 0),
),
points: const [
RoutePoint(10, 0),
RoutePoint(10, -30),
RoutePoint(40, -30),
RoutePoint(40, 0),
],
);
int? hit(Offset point, {double tolerance = 4}) => hitTestEdge(
routes: [loop],
labels: const [
EdgeLabelBox(edgeId: 1, x: 100, y: 100, width: 30, height: 12),
],
nodes: const [],
point: point,
tolerance: tolerance,
);
expect(distanceToRoute(loop, const Offset(25, -27)), 3);
expect(hit(const Offset(25, -27)), 1, reason: 'the loop top is hit');
expect(hit(const Offset(13, -15)), 1, reason: 'the loop side is hit');
expect(hit(const Offset(25, -15)), isNull, reason: 'inside the loop');
expect(hit(const Offset(110, 105)), 1, reason: 'the label is the edge');
});
testWidgets('hovering a definition edge highlights it with a tooltip', (
tester,
) async {
await tester.pumpWidget(
_host(DefinitionGraphView(graph: linearGraph(), onSelected: (_) {})),
);
await _settle(tester);
final route = _route(tester, 'plan', 'success');
final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse);
await mouse.addPointer(location: Offset.zero);
addTearDown(mouse.removePointer);
await mouse.moveTo(_onRoute(tester, route));
await tester.pump();
expect(_highlight(route.id), findsOneWidget);
expect(find.byKey(const Key('graph-edge-tooltip')), findsOneWidget);
expect(find.text('plan → build\nOutcome: success'), findsOneWidget);
// Over a node the edge is let go: nodes keep their own pointer.
final node = _hover(tester).layout.nodeFor('build')!;
final box = tester.renderObject<RenderBox>(find.byType(GraphEdgeHover));
await mouse.moveTo(
box.localToGlobal(
Offset(node.x + node.width / 2, node.y + node.height / 2),
),
);
await tester.pump();
expect(_highlight(route.id), findsNothing);
expect(find.byKey(const Key('graph-edge-tooltip')), findsNothing);
});
testWidgets('tapping a run edge pins it and counts how often it was taken', (
tester,
) async {
final run = <String, dynamic>{
'steps': [
step(sequence: 1, stage: 'a', outcome: 'retry', target: 'a'),
step(sequence: 2, stage: 'a', outcome: 'retry', target: 'a'),
step(sequence: 3, stage: 'a', outcome: 'success', target: 'b'),
step(sequence: 4, stage: 'b', status: 'running'),
],
'current_stage': 'b',
'executing': true,
};
await tester.pumpWidget(
_host(
RunGraphView(
graph: selfLoopGraph(),
run: run,
onStageSelected: (_) {},
showHeader: false,
),
),
);
await _settle(tester);
final loop = _route(tester, 'a', 'retry');
await tester.tapAt(_onRoute(tester, loop));
await tester.pump();
expect(_highlight(loop.id), findsOneWidget);
expect(find.text('a → a\nOutcome: retry\nTaken 2 times'), findsOneWidget);
final untaken = _route(tester, 'b', 'error');
await tester.tapAt(_onRoute(tester, untaken));
await tester.pump();
expect(_highlight(loop.id), findsNothing);
expect(_highlight(untaken.id), findsOneWidget);
expect(find.text('b → Failure\nOutcome: error\nNot taken'), findsOneWidget);
// Tapping it again lets it go.
await tester.tapAt(_onRoute(tester, untaken));
await tester.pump();
expect(_highlight(untaken.id), findsNothing);
expect(find.byKey(const Key('graph-edge-tooltip')), findsNothing);
});
testWidgets('edge labels name their edge for screen readers', (tester) async {
final handle = tester.ensureSemantics();
await tester.pumpWidget(
_host(DefinitionGraphView(graph: linearGraph(), onSelected: (_) {})),
);
await _settle(tester);
expect(
find.bySemanticsLabel('build → ship\nOutcome: success'),
findsOneWidget,
);
handle.dispose();
});
}
+97
View File
@@ -0,0 +1,97 @@
package pipeline
import (
"context"
"encoding/json"
"sort"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// RunShownMap returns the graph and per-stage progress a chat's run card
// draws (protocol.ChatShownRunMap). It is nil, without an error, when the
// graph has more than protocol.ChatShownRunMapStages stages. Only routing and
// lifecycle facts are read: no step inputs, outputs or transcripts.
func (s *Store) RunShownMap(ctx context.Context, id int64) (*protocol.ChatShownRunMap, error) {
tx, err := s.db.BeginTx(ctx, nil)
if err != nil {
return nil, err
}
defer tx.Rollback()
var graphJSON string
if err := tx.QueryRowContext(ctx, `SELECT v.graph_json FROM pipeline_runs r
JOIN pipeline_versions v ON v.pipeline_id=r.pipeline_id AND v.version=r.version WHERE r.id=?`, id).Scan(&graphJSON); err != nil {
return nil, err
}
var graph protocol.Graph
if err := json.Unmarshal([]byte(graphJSON), &graph); err != nil {
return nil, err
}
if len(graph.Stages) > protocol.ChatShownRunMapStages {
return nil, nil
}
rows, err := tx.QueryContext(ctx, `SELECT sequence,stage_key,status,outcome,target,
COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ',started_at),''),COALESCE(strftime('%Y-%m-%dT%H:%M:%SZ',finished_at),'')
FROM run_steps WHERE run_id=? ORDER BY sequence`, id)
if err != nil {
return nil, err
}
defer rows.Close()
result := &protocol.ChatShownRunMap{Stages: []protocol.ChatShownRunStage{}, Visits: []protocol.RunGraphVisit{}}
index := map[string]int{}
for _, stage := range graph.Stages {
if _, seen := index[stage.Key]; seen || stage.Key == "" {
continue
}
index[stage.Key] = len(result.Stages)
result.Stages = append(result.Stages, protocol.ChatShownRunStage{
Key: stage.Key, Type: stage.Type, Edges: stage.Edges, FallbackError: stage.FallbackError,
})
}
latestStage := map[string]protocol.RunGraphVisit{}
latestRoute := map[[3]string]protocol.RunGraphVisit{}
for rows.Next() {
var visit protocol.RunGraphVisit
var started, finished string
if err := rows.Scan(&visit.Sequence, &visit.Stage, &visit.Status, &visit.Outcome, &visit.Target, &started, &finished); err != nil {
return nil, err
}
latestStage[visit.Stage] = visit
if visit.Outcome != "" && visit.Target != "" {
latestRoute[[3]string{visit.Stage, visit.Outcome, visit.Target}] = visit
}
i, declared := index[visit.Stage]
if !declared {
continue
}
stage := &result.Stages[i]
stage.Visits++
stage.Status = visit.Status
stage.RunningSince = 0
start, startErr := time.Parse(time.RFC3339, started)
end, endErr := time.Parse(time.RFC3339, finished)
switch {
case startErr == nil && endErr == nil && !end.Before(start):
stage.Seconds += int64(end.Sub(start) / time.Second)
case startErr == nil && finished == "" && visit.Status == "running":
stage.RunningSince = start.UnixMilli()
}
}
if err := rows.Err(); err != nil {
return nil, err
}
seen := map[int]bool{}
for _, visit := range latestStage {
seen[visit.Sequence] = true
result.Visits = append(result.Visits, visit)
}
for _, visit := range latestRoute {
if !seen[visit.Sequence] {
seen[visit.Sequence] = true
result.Visits = append(result.Visits, visit)
}
}
sort.Slice(result.Visits, func(a, b int) bool { return result.Visits[a].Sequence < result.Visits[b].Sequence })
return result, nil
}
@@ -0,0 +1,80 @@
package pipeline
import (
"context"
"path/filepath"
"strings"
"testing"
)
func TestRunShownMapCompactsVisitsAndTotalsStages(t *testing.T) {
ctx := context.Background()
store, err := Open(filepath.Join(t.TempDir(), "map.db"))
if err != nil {
t.Fatal(err)
}
defer store.Close()
if _, err := store.Submit(ctx, "graph", Template([]string{"a", "b", "c"}, true)); err != nil {
t.Fatal(err)
}
pipelines, _ := store.List(ctx)
definition, _ := store.Get(ctx, pipelines[0].ID, 1)
id, _, err := store.CreateRun(ctx, definition, "map", "workspace", false, nil, nil)
if err != nil {
t.Fatal(err)
}
// a → b loops back to a 20 times, then b → c, and c is still running.
type step struct{ stage, status, outcome, target, started, finished string }
var steps []step
for i := 0; i < 20; i++ {
steps = append(steps,
step{"a", "completed", "success", "b", "2026-12-01 10:00:00", "2026-12-01 10:00:10"},
step{"b", "completed", "retry", "a", "2026-12-01 10:00:10", "2026-12-01 10:00:15"})
}
steps = append(steps,
step{"a", "completed", "success", "b", "2026-12-01 10:00:00", "2026-12-01 10:00:10"},
step{"b", "completed", "success", "c", "2026-12-01 10:00:10", "2026-12-01 10:00:15"},
step{"c", "running", "", "", "2026-12-01 10:05:00", ""})
tx, err := store.db.BeginTx(ctx, nil)
if err != nil {
t.Fatal(err)
}
for i, s := range steps {
var finished any
if s.finished != "" {
finished = s.finished
}
if _, err := tx.ExecContext(ctx, `INSERT INTO run_steps(run_id,sequence,stage_key,status,outcome,target,input_json,output_json,diagnostic,transcript,started_at,finished_at)
VALUES(?,?,?,?,?,?,'{}','{}','PRIVATE','PRIVATE',?,?)`, id, i+1, s.stage, s.status, s.outcome, s.target, s.started, finished); err != nil {
t.Fatal(err)
}
}
if err := tx.Commit(); err != nil {
t.Fatal(err)
}
got, err := store.RunShownMap(ctx, id)
if err != nil || got == nil {
t.Fatalf("map = %+v, %v", got, err)
}
if len(got.Stages) != 3 || got.Stages[0].Key != "a" || got.Stages[0].Edges["success"] != "b" {
t.Fatalf("stages = %+v", got.Stages)
}
a, b, c := got.Stages[0], got.Stages[1], got.Stages[2]
if a.Visits != 21 || a.Seconds != 210 || a.Status != "completed" || a.RunningSince != 0 {
t.Fatalf("stage a = %+v", a)
}
if b.Visits != 21 || b.Seconds != 105 {
t.Fatalf("stage b = %+v", b)
}
if c.Visits != 1 || c.Status != "running" || c.Seconds != 0 || c.RunningSince == 0 {
t.Fatalf("stage c = %+v", c)
}
// Bounded by the graph: the latest visit of each stage and of each route.
var routes []string
for _, visit := range got.Visits {
routes = append(routes, visit.Stage+">"+visit.Outcome+">"+visit.Target)
}
if want := "b>retry>a a>success>b b>success>c c>>"; strings.Join(routes, " ") != want {
t.Fatalf("visits = %q, want %q", strings.Join(routes, " "), want)
}
}
+31
View File
@@ -97,6 +97,37 @@ type ChatShownRunBody struct {
Workspace string `json:"workspace,omitempty"`
StartedAt int64 `json:"started_at,omitempty"`
FinishedAt int64 `json:"finished_at,omitempty"`
// Map is the run's graph and per-stage progress for the card's mini-map
// and stage strip; nil when the server could not read it or the graph has
// more than ChatShownRunMapStages stages.
Map *ChatShownRunMap `json:"map,omitempty"`
}
// ChatShownRunMapStages bounds the graph a run card carries.
const ChatShownRunMapStages = 48
// ChatShownRunMap is a run's graph reduced to what a card draws: each
// declared stage's routes and progress, and the compact route evidence (the
// latest visit of every stage and of every taken route, in sequence order,
// as RunGraphEvidence). Its size is bounded by the graph, not by the run's
// length, so a long loop does not grow it.
type ChatShownRunMap struct {
Stages []ChatShownRunStage `json:"stages"`
Visits []RunGraphVisit `json:"visits"`
}
// ChatShownRunStage is one declared stage with its progress in the run.
// Seconds totals its finished visits; RunningSince (epoch milliseconds) is the
// start of a visit still running, so a client can add the live part.
type ChatShownRunStage struct {
Key string `json:"key"`
Type string `json:"type,omitempty"`
Edges map[string]string `json:"edges,omitempty"`
FallbackError bool `json:"fallback_error,omitempty"`
Visits int `json:"visits,omitempty"`
Status string `json:"status,omitempty"`
Seconds int64 `json:"seconds,omitempty"`
RunningSince int64 `json:"running_since,omitempty"`
}
// ChatShownDiffBody is one Git comparison a chat's model showed: the work tree
@@ -0,0 +1,75 @@
package server
import (
"context"
"sync"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// mappedShownRuns is a run store that also reads the card's graph map.
type mappedShownRuns struct {
mu sync.Mutex
runs fakeShownRuns
maps map[int64]*protocol.ChatShownRunMap
}
func (m *mappedShownRuns) RunSummaryByID(ctx context.Context, id int64) (protocol.RunSummary, bool, error) {
m.mu.Lock()
defer m.mu.Unlock()
return m.runs.RunSummaryByID(ctx, id)
}
func (m *mappedShownRuns) RunShownMap(_ context.Context, id int64) (*protocol.ChatShownRunMap, error) {
m.mu.Lock()
defer m.mu.Unlock()
return m.maps[id], nil
}
func TestShowRunCarriesTheGraphMapAndRefreshesItsProgress(t *testing.T) {
previous := shownRunRefreshDelay
shownRunRefreshDelay = 10 * time.Millisecond
t.Cleanup(func() { shownRunRefreshDelay = previous })
f := newChatToolFixture(t)
stages := func(implement string) []protocol.ChatShownRunStage {
return []protocol.ChatShownRunStage{
{Key: "plan", Edges: map[string]string{"success": "implement"}, Visits: 1, Status: "completed", Seconds: 30},
{Key: "implement", Edges: map[string]string{"success": "#"}, Visits: 1, Status: implement},
}
}
store := &mappedShownRuns{
runs: fakeShownRuns{7: {ID: 7, Name: "feature", Status: "running", CurrentStage: "implement", CreatedAt: "2026-12-01T10:00:00Z"}},
maps: map[int64]*protocol.ChatShownRunMap{7: {Stages: stages("running"), Visits: []protocol.RunGraphVisit{
{Sequence: 1, Stage: "plan", Status: "completed", Outcome: "success", Target: "implement"},
{Sequence: 2, Stage: "implement", Status: "running"},
}}},
}
f.service.runs = store
token := f.token(t, chatToolSessionScope+"ses_m")
if r := f.call(token, "show_run", `{"run_id":7}`); r.IsError {
t.Fatalf("show_run: %v", r)
}
item := f.items(t, "ses_m")[0]
if item.Run.Map == nil || len(item.Run.Map.Stages) != 2 || item.Run.Map.Stages[1].Status != "running" {
t.Fatalf("run map = %+v", item.Run.Map)
}
// Only the stage progress changes: the summary is the same, the card is not.
store.mu.Lock()
store.maps[7] = &protocol.ChatShownRunMap{Stages: stages("completed"), Visits: store.maps[7].Visits}
store.mu.Unlock()
f.service.observeRun(protocol.RunEventFrame{RunID: 7, Status: "running"})
deadline := time.Now().Add(5 * time.Second)
for {
item = f.items(t, "ses_m")[0]
if item.Run.Map != nil && item.Run.Map.Stages[1].Status == "completed" {
break
}
if time.Now().After(deadline) {
t.Fatalf("the run map was not refreshed: %+v", item.Run.Map)
}
time.Sleep(10 * time.Millisecond)
}
}
+20 -5
View File
@@ -4,6 +4,7 @@ import (
"context"
"fmt"
"log"
"reflect"
"sync"
"time"
@@ -44,7 +45,7 @@ func (s *chatToolService) runShowRun(ctx context.Context, runID int64, title str
if !found {
return fail(fmt.Sprintf("there is no run %d.", runID))
}
body := shownRunBody(summary)
body := s.shownRunBody(ctx, summary)
item := protocol.ChatShownItem{Kind: protocol.ChatShownRun, Title: title, Run: &body}
text := fmt.Sprintf("Shown in the operator's Pipelines chat: run %d of %s, %s", runID, body.Pipeline, body.Status)
if body.CurrentStage != "" && !shownRunTerminal(body.Status) {
@@ -53,12 +54,26 @@ func (s *chatToolService) runShowRun(ctx context.Context, runID int64, title str
return &item, chattools.Result{Text: text + "; the card follows the run live."}
}
func shownRunBody(summary protocol.RunSummary) protocol.ChatShownRunBody {
return protocol.ChatShownRunBody{
// chatShownRunMapStore reads the graph and stage progress a run card draws
// (pipeline.Store). It is optional: without it a card has no mini-map.
type chatShownRunMapStore interface {
RunShownMap(ctx context.Context, id int64) (*protocol.ChatShownRunMap, error)
}
func (s *chatToolService) shownRunBody(ctx context.Context, summary protocol.RunSummary) protocol.ChatShownRunBody {
body := protocol.ChatShownRunBody{
ID: summary.ID, Pipeline: summary.Name, Title: summary.Title, Status: summary.Status, Outcome: summary.Outcome,
CurrentStage: summary.CurrentStage, Workspace: summary.Workspace,
StartedAt: shownRunTime(summary.CreatedAt), FinishedAt: shownRunTime(summary.FinishedAt),
}
if maps, ok := s.runs.(chatShownRunMapStore); ok {
runMap, err := maps.RunShownMap(ctx, summary.ID)
if err != nil {
log.Printf("chat tools: run %d card map: %v", summary.ID, err)
}
body.Map = runMap
}
return body
}
func shownRunTime(value string) int64 {
@@ -152,13 +167,13 @@ func (s *chatToolService) refreshRunItem(ctx context.Context, sessionID string,
if err != nil || !found {
return item
}
body := shownRunBody(summary)
body := s.shownRunBody(ctx, summary)
if shownRunTerminal(body.Status) {
s.unwatchRun(body.ID, item.ID)
} else {
s.watchRun(body.ID, sessionID, item.ID)
}
if body == *item.Run {
if reflect.DeepEqual(body, *item.Run) {
return item
}
item.Run = &body