Merge branch 'main' into flutter/s1-list

This commit is contained in:
2026-10-21 17:00:52 +01:00
70 changed files with 7796 additions and 27 deletions
@@ -0,0 +1,152 @@
import 'graph_protocol.dart';
/// The graph definition: nodes and edges declared by a pipeline, never the
/// evidence that a run executed them. Run evidence lives in
/// `run_graph_state.dart`; keeping the two shapes separate means a definition
/// can be drawn without claiming a visit happened.
///
/// Mirrors `stageOutcomes`, `edgeLabel`, `graphEdges` and `nodeDisplayLabel`
/// from `web/src/graph.js` (and `web/src/runDetail.js`). Pure data only.
/// Ordering priority: success first, error last, every other outcome
/// alphabetical in between (the web client's `outcomePriority`).
int _outcomePriority(String outcome) {
if (outcome == 'success') return 0;
if (outcome == 'error') return 2;
return 1;
}
/// A stage's edge outcomes in the app's one stable order.
List<String> stageOutcomes(dynamic stage) {
final edges = stage is Map ? stage['edges'] : null;
if (edges is! Map) return const <String>[];
final outcomes = edges.keys.map((key) => '$key').toList();
outcomes.sort((a, b) {
final priority = _outcomePriority(a) - _outcomePriority(b);
return priority != 0 ? priority : a.compareTo(b);
});
return outcomes;
}
/// The outcome label on an edge: `error*` for an implicit fallback error route.
String edgeLabel(dynamic stage, String outcome) {
final implicitFallback = stage is Map && stage['fallback_error'] == true;
return outcome == 'error' && implicitFallback ? 'error*' : outcome;
}
/// One declared edge, in stable definition order.
class GraphEdge {
const GraphEdge({
required this.id,
required this.source,
required this.outcome,
required this.target,
required this.label,
required this.fallback,
required this.knownTarget,
});
/// The 1-based id assigned in stable definition order (`Graph.edges()`).
final int id;
final String source;
final String outcome;
/// The resolved target: `#` has already become `#success`/`#failure`.
final String target;
final String label;
/// True only for the parser's implicit `error -> #failure` route.
final bool fallback;
/// True when [target] is a terminal or a stage declared in this graph.
///
/// An empty or unknown target is kept exactly as recorded, with this flag
/// false, so callers can show it honestly instead of inventing a node.
final bool knownTarget;
bool get isTerminal => isTerminalTarget(target);
}
/// One graph definition node: a declared stage, or a terminal the definition
/// routes to.
class GraphNode {
const GraphNode({required this.key, required this.terminal, this.stageIndex});
final String key;
final bool terminal;
/// The node's stage declaration index, or null for a terminal.
final int? stageIndex;
String get label => nodeDisplayLabel(key);
String get shortLabel => nodeLabel(key);
}
List<Map<String, dynamic>> _stages(dynamic graph) {
if (graph is! Map) return const <Map<String, dynamic>>[];
final stages = graph['stages'];
if (stages is! List) return const <Map<String, dynamic>>[];
return stages.whereType<Map>().map(Map<String, dynamic>.from).toList();
}
String _stageKey(Map<String, dynamic> stage) => '${stage['key'] ?? ''}';
/// Every definition edge in stable id order.
///
/// Stages keep declaration order and each stage's outcomes use
/// [stageOutcomes]; ids are contiguous in that order. An absent (null) edge
/// value declares no edge and is skipped, while an empty or unknown target is
/// preserved with [GraphEdge.knownTarget] false.
List<GraphEdge> graphEdges(dynamic graph) {
final stages = _stages(graph);
final stageKeys = <String>{
for (final stage in stages)
if (_stageKey(stage).isNotEmpty) _stageKey(stage),
};
final result = <GraphEdge>[];
for (final stage in stages) {
final edges = stage['edges'];
if (edges is! Map) continue;
final source = _stageKey(stage);
for (final outcome in stageOutcomes(stage)) {
final raw = edges[outcome];
if (raw == null) continue;
final target = resolveTarget(outcome, '$raw') ?? '';
result.add(
GraphEdge(
id: result.length + 1,
source: source,
outcome: outcome,
target: target,
label: edgeLabel(stage, outcome),
fallback: outcome == 'error' && stage['fallback_error'] == true,
knownTarget: isTerminalTarget(target) || stageKeys.contains(target),
),
);
}
}
return result;
}
/// The definition's nodes in declaration order.
///
/// A stage key identifies one node even when it is declared twice; self edges
/// and loops therefore never duplicate identity. Terminal nodes are appended
/// failure first, then success, once any declared edge resolves to a terminal
/// (the same `hasTerminal` rule the web layout uses). They are still
/// definition nodes, not evidence that a run reached them.
List<GraphNode> graphNodes(dynamic graph) {
final stages = _stages(graph);
final seen = <String>{};
final nodes = <GraphNode>[];
for (var index = 0; index < stages.length; index += 1) {
final key = _stageKey(stages[index]);
if (key.isEmpty || !seen.add(key)) continue;
nodes.add(GraphNode(key: key, terminal: false, stageIndex: index));
}
if (graphEdges(graph).any((edge) => edge.isTerminal)) {
nodes.add(const GraphNode(key: failureEnd, terminal: true));
nodes.add(const GraphNode(key: successEnd, terminal: true));
}
return nodes;
}
@@ -0,0 +1,43 @@
/// Protocol terminal targets and the labels the graph uses for them.
///
/// Mirrors `web/src/protocol.js` (`SUCCESS_END`, `FAILURE_END`,
/// `isTerminal`, `resolveTarget`) and the label helpers in `web/src/graph.js`.
/// Pure Dart: no Flutter imports and no layout or rendering decisions.
library;
/// The explicit success terminal (`Protocol.SUCCESS_END`).
const String successEnd = '#success';
/// The explicit failure terminal (`Protocol.FAILURE_END`).
const String failureEnd = '#failure';
/// True only for the two explicit terminal targets.
///
/// A bare `#` is not itself terminal; [resolveTarget] turns it into one using
/// the outcome, exactly as the server and the web client do.
bool isTerminalTarget(String? target) =>
target == successEnd || target == failureEnd;
/// Mirrors `Protocol.resolveTarget`: a bare `#` is the outcome's terminal.
///
/// Every other value is preserved verbatim, including an empty or unknown
/// stage key. A missing target stays null rather than becoming a terminal, so
/// a blank edge cannot fabricate a visit or a terminal node.
String? resolveTarget(String? outcome, String? target) {
if (target != '#') return target;
return outcome == 'error' ? failureEnd : successEnd;
}
/// A graph node title: a stage keeps its key, a terminal reads Success/Failure.
String nodeDisplayLabel(String? key) {
if (key == successEnd) return 'Success';
if (key == failureEnd) return 'Failure';
return key ?? '';
}
/// The TUI-mirroring label: terminal targets are all caps.
String nodeLabel(String? key) {
if (key == successEnd) return 'SUCCESS';
if (key == failureEnd) return 'FAILURE';
return key ?? '';
}
@@ -0,0 +1,124 @@
import 'graph_protocol.dart';
/// Which stages and routes a run actually recorded.
///
/// This is executed-route evidence, deliberately distinct from the graph
/// definition's nodes and edges. It mirrors `runGraphState` from
/// `web/src/runDetail.js` (Android `RunGraphState.from`): every recorded step's
/// stage is visited once in first-appearance order, a step with a non-blank
/// outcome and target contributes one deduplicated `source\0outcome\0target`
/// route, and only a resolved terminal is added by its target. A non-terminal
/// target is not visited until a step lands on it.
///
/// The run map is the same detail produced by the runs feature; this helper
/// reads recorded steps and never folds live events a second time.
class RunGraphState {
RunGraphState({
required List<String> visitedStages,
required List<String> takenRoutes,
required this.currentStage,
required this.executing,
required this.currentStageStartedAt,
}) : visitedStages = List.unmodifiable(visitedStages),
takenRoutes = List.unmodifiable(takenRoutes);
/// Visited stage keys in first-appearance order, without duplicates.
final List<String> visitedStages;
/// Taken routes as `source\0outcome\0resolvedTarget`, in recorded order.
final List<String> takenRoutes;
/// The run's current stage, else the last recorded visit's stage, else null.
final String? currentStage;
final bool executing;
/// The running visit's start for [currentStage], only while executing.
final String? currentStageStartedAt;
bool isStageVisited(String key) => visitedStages.contains(key);
/// True when a recorded visit took this definition route. The target is
/// resolved with the same `#` rule the definition edges use.
bool isRouteTaken(String source, String outcome, String target) {
final resolved = resolveTarget(outcome, target);
if (resolved == null || resolved.isEmpty) return false;
return takenRoutes.contains('$source\u0000$outcome\u0000$resolved');
}
/// The active stage for a live run, else null. A finished run has none.
String? get activeStage {
if (!executing || currentStage == null || currentStage!.isEmpty) {
return null;
}
return currentStage;
}
}
List<Map<String, dynamic>> _steps(dynamic run) {
if (run is! Map) return const <Map<String, dynamic>>[];
final steps = run['steps'];
if (steps is! List) return const <Map<String, dynamic>>[];
return steps.whereType<Map>().map(Map<String, dynamic>.from).toList();
}
String _text(dynamic value) => '${value ?? ''}';
/// Derives [RunGraphState] from one run detail map.
///
/// Missing or malformed steps yield no visits and no routes; nothing is
/// fabricated from a missing capture. Repeated visits stay one identity per
/// stage, and self edges or loops never recurse.
RunGraphState runGraphState(dynamic run) {
final steps = _steps(run);
final visitedStages = <String>[];
final seenStages = <String>{};
final takenRoutes = <String>[];
final seenRoutes = <String>{};
void visit(String? key) {
if (key == null || key.isEmpty || !seenStages.add(key)) return;
visitedStages.add(key);
}
for (final step in steps) {
final stage = _text(step['stage']);
if (stage.isNotEmpty) visit(stage);
final outcome = _text(step['outcome']);
final target = _text(step['target']);
if (outcome.trim().isEmpty || target.trim().isEmpty) continue;
final resolved = resolveTarget(outcome, target);
if (resolved == null || resolved.isEmpty) continue;
final route = '$stage\u0000$outcome\u0000$resolved';
if (seenRoutes.add(route)) takenRoutes.add(route);
if (isTerminalTarget(resolved)) visit(resolved);
}
final lastStage = steps.isEmpty ? '' : _text(steps.last['stage']);
final rawCurrent = _text(run is Map ? run['current_stage'] : null);
final currentStage = rawCurrent.trim().isNotEmpty
? rawCurrent
: (lastStage.trim().isNotEmpty ? lastStage : null);
final executing = run is Map && run['executing'] == true;
String? currentStageStartedAt;
if (executing && currentStage != null) {
for (var index = steps.length - 1; index >= 0; index -= 1) {
final step = steps[index];
if (_text(step['stage']) != currentStage) continue;
if (_text(step['status']) != 'running') continue;
final started = _text(step['started_at']);
if (started.trim().isNotEmpty) currentStageStartedAt = started;
break;
}
}
return RunGraphState(
visitedStages: visitedStages,
takenRoutes: takenRoutes,
currentStage: currentStage,
executing: executing,
currentStageStartedAt: currentStageStartedAt,
);
}
@@ -0,0 +1,107 @@
import '../../../core/api_gateway.dart';
/// Recorded stage-visit selection, matching the web client's timeline and
/// stage pane. Visits are ordered by their recorded sequence, never by the
/// order a caller happens to pass them in; repeated visits to one stage stay
/// separate entries. Pure data: no widgets, layout or coordinates.
int _sequenceOf(JsonMap step) {
final sequence = step['sequence'];
return sequence is num ? sequence.toInt() : 0;
}
int _positiveVisit(dynamic control) {
if (control is! Map) return 0;
final visit = control['visit'];
if (visit is num) return visit > 0 ? visit.toInt() : 0;
return int.tryParse('${visit ?? ''}') ?? 0;
}
/// The visit number a timeline row shows: the recorded `control.visit` when it
/// is positive, else the position within the stage's ordered visits.
int displayVisit(JsonMap step, int index) {
final recorded = _positiveVisit(step['control']);
return recorded > 0 ? recorded : index + 1;
}
/// Clamps a visit index into `[0, count)`; an empty list yields 0.
int clampVisitIndex(int index, int count) {
if (count <= 0) return 0;
if (index < 0) return 0;
return index >= count ? count - 1 : index;
}
List<JsonMap> _ordered(List<JsonMap> visits) {
final indexed = <({int position, JsonMap step})>[
for (var index = 0; index < visits.length; index += 1)
(position: index, step: visits[index]),
];
indexed.sort((a, b) {
final bySequence = _sequenceOf(a.step).compareTo(_sequenceOf(b.step));
return bySequence != 0 ? bySequence : a.position.compareTo(b.position);
});
return [for (final entry in indexed) entry.step];
}
/// Every stage's recorded visits, ordered by sequence.
///
/// The map keeps stage first-appearance order. Equal sequences keep their
/// recorded order (the web client's stable sort), and a stage with no recorded
/// visit is simply absent rather than present with a synthetic visit.
Map<String, List<JsonMap>> visitsByStage(List<JsonMap> steps) {
final grouped = <String, List<JsonMap>>{};
for (final step in steps) {
final stage = '${step['stage'] ?? ''}';
grouped.putIfAbsent(stage, () => <JsonMap>[]).add(step);
}
return <String, List<JsonMap>>{
for (final entry in grouped.entries) entry.key: _ordered(entry.value),
};
}
/// One selected stage visit. [step] is null when the stage has no recorded
/// visit, so callers cannot mistake an absent capture for an execution.
class StageVisitSelection {
const StageVisitSelection({
required this.stageKey,
required this.visits,
required this.index,
});
final String stageKey;
/// The stage's visits ordered by sequence.
final List<JsonMap> visits;
/// The clamped index into [visits]; 0 when there are none.
final int index;
bool get hasVisit => visits.isNotEmpty;
JsonMap? get step => hasVisit ? visits[index] : null;
int get visitNumber => step == null ? 0 : displayVisit(step!, index);
/// True when an explicit requested index was clamped, so a caller can
/// correct its route exactly as the web stage route does.
bool correctedRequest(int? requested) =>
requested != null && requested != index;
}
/// Selects a stage's visit exactly as the web stage pane does.
///
/// A null [visitIndex] means the stage's most recent recorded visit; an
/// out-of-range index is clamped to the last visit (negative values to the
/// first). A stage with no recorded visits returns [StageVisitSelection.step]
/// null instead of a fabricated visit.
StageVisitSelection selectStageVisit(
List<JsonMap> steps,
String stageKey, {
int? visitIndex,
}) {
final visits = visitsByStage(steps)[stageKey] ?? const <JsonMap>[];
final wanted = visitIndex ?? (visits.isEmpty ? 0 : visits.length - 1);
return StageVisitSelection(
stageKey: stageKey,
visits: visits,
index: clampVisitIndex(wanted, visits.length),
);
}
@@ -0,0 +1,142 @@
import 'dart:math' as math;
import '../domain/graph_definition.dart';
import 'graph_ranks.dart';
import 'layout_models.dart';
/// Places definition nodes in topological columns.
///
/// Nodes keep definition order inside a rank, each column is as wide as its
/// widest measured node, and columns are top-aligned. A node is centred in its
/// column, so heterogeneous widths and text-expanded heights stay separated by
/// [GraphLayoutConfig.rowGap] inside a rank and [GraphLayoutConfig.columnGap]
/// between ranks. Nothing is clipped to a fixed box: the supplied measured
/// width and height are used verbatim and the returned bounds include them.
///
/// [nodes] and [edges] normally come from `graphNodes`/`graphEdges`. Edges whose
/// source or target is not one of [nodes] are ignored, so an unknown target can
/// never invent a node. A measurement is required for every node; a missing one
/// is an error rather than a made-up size. Extra measurement entries are
/// ignored because they cannot become nodes.
GraphLayout layoutGraphNodes({
required List<GraphNode> nodes,
required List<GraphEdge> edges,
required Map<String, NodeExtent> extents,
required GraphLayoutConfig config,
}) {
_validateNodeKeys(nodes);
final ranks = assignGraphRanks(nodes, edges);
final measured = <String, NodeExtent>{};
final missing = <String>[];
for (final node in nodes) {
final extent = extents[node.key];
if (extent == null) {
missing.add(node.key);
} else {
measured[node.key] = extent;
}
}
if (missing.isNotEmpty) {
throw ArgumentError.value(
missing,
'extents',
'missing measured extents for graph nodes',
);
}
final columns = List<List<GraphNode>>.generate(
ranks.rankCount,
(_) => <GraphNode>[],
);
for (final node in nodes) {
columns[ranks.rankOf[node.key]!].add(node);
}
final columnWidths = <double>[
for (final column in columns)
column.fold<double>(
0,
(width, node) => math.max(width, measured[node.key]!.width),
),
];
final columnHeights = <double>[
for (final column in columns)
_columnHeight(column, measured, config.rowGap),
];
final columnX = <double>[];
var nextX = config.padding;
for (var rank = 0; rank < columns.length; rank += 1) {
columnX.add(nextX);
nextX += columnWidths[rank];
if (rank + 1 < columns.length) nextX += config.columnGap;
}
final boxes = <GraphNodeBox>[];
for (var rank = 0; rank < columns.length; rank += 1) {
var nextY = config.padding;
for (final node in columns[rank]) {
final extent = measured[node.key]!;
boxes.add(
GraphNodeBox(
key: node.key,
terminal: node.terminal,
stageIndex: node.stageIndex,
rank: rank,
x: columnX[rank] + (columnWidths[rank] - extent.width) / 2,
y: nextY,
width: extent.width,
height: extent.height,
),
);
nextY += extent.height + config.rowGap;
}
}
final width =
config.padding * 2 +
columnWidths.fold<double>(0, (sum, column) => sum + column) +
config.columnGap * math.max(0, columns.length - 1);
final height =
config.padding * 2 +
columnHeights.fold<double>(
0,
(tallest, column) => math.max(tallest, column),
);
return GraphLayout(
nodes: boxes,
width: width,
height: height,
rankCount: ranks.rankCount,
ranks: ranks.rankOf,
);
}
void _validateNodeKeys(List<GraphNode> nodes) {
final seen = <String>{};
for (final node in nodes) {
if (node.key.isEmpty) {
throw ArgumentError.value(
node.key,
'nodes',
'node key must not be empty',
);
}
if (!seen.add(node.key)) {
throw ArgumentError.value(node.key, 'nodes', 'duplicate graph node key');
}
}
}
double _columnHeight(
List<GraphNode> column,
Map<String, NodeExtent> measured,
double rowGap,
) {
if (column.isEmpty) return 0;
var height = 0.0;
for (final node in column) {
height += measured[node.key]!.height;
}
return height + rowGap * (column.length - 1);
}
@@ -0,0 +1,191 @@
import 'dart:collection';
import 'dart:math' as math;
import '../domain/graph_definition.dart';
/// Deterministic 0-based ranks for a graph definition's nodes.
///
/// Ranks come from the condensation DAG: every strongly connected component
/// shares one rank, and a component sits one past its deepest predecessor
/// (longest path). Self loops and cycles therefore stay finite, a cycle's
/// members do not drift apart, and disconnected nodes stay at rank 0. Edges
/// whose endpoints are not definition nodes are ignored: an unknown target
/// never invents a node.
class GraphRanks {
GraphRanks({
required Map<String, int> rankOf,
required this.rankCount,
required List<List<String>> components,
}) : rankOf = Map.unmodifiable(rankOf),
components = List.unmodifiable(<List<String>>[
for (final component in components) List.unmodifiable(component),
]);
/// Every definition key's rank, in definition order.
final Map<String, int> rankOf;
/// Number of distinct ranks, 0 for an empty node set.
final int rankCount;
/// Strongly connected components as keys, each sorted by definition order and
/// the list sorted by its first member.
final List<List<String>> components;
}
/// One DFS frame for the iterative Tarjan walk.
class _Frame {
_Frame(this.node);
final int node;
int nextChild = 0;
}
/// Assigns ranks to exactly the supplied [nodes].
///
/// [edges] is read for ordering only; it never adds nodes. Duplicate edges are
/// harmless. The walk is iterative, so a deep chain cannot overflow the call
/// stack, and the work is linear in nodes plus edges.
GraphRanks assignGraphRanks(List<GraphNode> nodes, List<GraphEdge> edges) {
final indexOf = <String, int>{};
for (var index = 0; index < nodes.length; index += 1) {
indexOf[nodes[index].key] = index;
}
final adjacency = List<List<int>>.generate(nodes.length, (_) => <int>[]);
final seenPairs = <int>{};
for (final edge in edges) {
final source = indexOf[edge.source];
final target = indexOf[edge.target];
if (source == null || target == null) continue;
if (!seenPairs.add(source * nodes.length + target)) continue;
adjacency[source].add(target);
}
final components = _components(adjacency);
final componentOf = List<int>.filled(nodes.length, -1);
for (var component = 0; component < components.length; component += 1) {
for (final node in components[component]) {
componentOf[node] = component;
}
}
// Condensation edges and their indegrees.
final successors = List<Set<int>>.generate(components.length, (_) => <int>{});
final indegree = List<int>.filled(components.length, 0);
for (var source = 0; source < adjacency.length; source += 1) {
final from = componentOf[source];
for (final target in adjacency[source]) {
final to = componentOf[target];
if (from == to) continue;
if (successors[from].add(to)) indegree[to] += 1;
}
}
// Longest-path ranks over the condensation. Queue order only has to be a
// topological order; the resulting rank per component is unique.
final ranks = List<int>.filled(components.length, 0);
final ready = ListQueue<int>();
for (var component = 0; component < components.length; component += 1) {
if (indegree[component] == 0) ready.add(component);
}
var settled = 0;
while (ready.isNotEmpty) {
final component = ready.removeFirst();
settled += 1;
for (final next in successors[component]) {
ranks[next] = math.max(ranks[next], ranks[component] + 1);
indegree[next] -= 1;
if (indegree[next] == 0) ready.add(next);
}
}
if (settled != components.length) {
// The condensation cannot contain a cycle by construction; stop rather than
// return a silently truncated layout.
throw StateError('graph condensation was not acyclic');
}
final componentKeys = <List<String>>[
for (final component in components)
<String>[for (final node in component) nodes[node].key],
];
final componentOrder = <int>[
for (var component = 0; component < components.length; component += 1)
component,
]..sort((a, b) => components[a].first.compareTo(components[b].first));
final rankOf = <String, int>{};
var rankCount = 0;
for (var index = 0; index < nodes.length; index += 1) {
final rank = ranks[componentOf[index]];
rankOf[nodes[index].key] = rank;
if (rank + 1 > rankCount) rankCount = rank + 1;
}
return GraphRanks(
rankOf: rankOf,
rankCount: rankCount,
components: <List<String>>[
for (final component in componentOrder) componentKeys[component],
],
);
}
/// Tarjan's strongly connected components, emitted sinks first.
///
/// Iterative rather than recursive so a long chain cannot exhaust the stack.
/// Members are sorted by definition index, which keeps every output stable.
List<List<int>> _components(List<List<int>> adjacency) {
final discovery = List<int>.filled(adjacency.length, -1);
final low = List<int>.filled(adjacency.length, 0);
final onStack = List<bool>.filled(adjacency.length, false);
final stack = <int>[];
final components = <List<int>>[];
var nextDiscovery = 0;
for (var root = 0; root < adjacency.length; root += 1) {
if (discovery[root] != -1) continue;
discovery[root] = low[root] = nextDiscovery;
nextDiscovery += 1;
stack.add(root);
onStack[root] = true;
final callStack = <_Frame>[_Frame(root)];
while (callStack.isNotEmpty) {
final frame = callStack.last;
final node = frame.node;
if (frame.nextChild < adjacency[node].length) {
final child = adjacency[node][frame.nextChild];
frame.nextChild += 1;
if (discovery[child] == -1) {
discovery[child] = low[child] = nextDiscovery;
nextDiscovery += 1;
stack.add(child);
onStack[child] = true;
callStack.add(_Frame(child));
} else if (onStack[child]) {
low[node] = math.min(low[node], discovery[child]);
}
continue;
}
callStack.removeLast();
if (callStack.isNotEmpty) {
final parent = callStack.last.node;
low[parent] = math.min(low[parent], low[node]);
}
if (low[node] == discovery[node]) {
final component = <int>[];
while (stack.isNotEmpty) {
final member = stack.removeLast();
onStack[member] = false;
component.add(member);
if (member == node) break;
}
component.sort();
components.add(component);
}
}
}
return components;
}
@@ -0,0 +1,129 @@
/// Pure geometry for a workflow graph's node layout.
///
/// Every size and gap is supplied by the caller. The native renderer measures
/// each node after text layout (including the platform's text scaling), so this
/// library never assumes a node width, font, palette or device class.
///
/// No Flutter imports: rectangles are plain numbers so the same result can be
/// built into widgets, a canvas or a test fixture.
library;
void _requireFiniteNonNegative(String name, double value) {
if (!value.isFinite || value < 0) {
throw ArgumentError.value(value, name, 'must be finite and non-negative');
}
}
/// One caller-measured node extent, in logical pixels.
///
/// A width or height may be zero for an empty label; the layout still keeps the
/// node separate from its neighbours through the configured gaps.
class NodeExtent {
NodeExtent({required this.width, required this.height}) {
_requireFiniteNonNegative('width', width);
_requireFiniteNonNegative('height', height);
}
final double width;
final double height;
}
/// The gaps a caller reserves around measured nodes.
///
/// [columnGap] separates adjacent ranks, [rowGap] separates nodes sharing a
/// rank, and [padding] is the outer margin included in [GraphLayout] bounds.
class GraphLayoutConfig {
GraphLayoutConfig({
required this.columnGap,
required this.rowGap,
this.padding = 0,
}) {
_requireFiniteNonNegative('columnGap', columnGap);
_requireFiniteNonNegative('rowGap', rowGap);
_requireFiniteNonNegative('padding', padding);
}
final double columnGap;
final double rowGap;
final double padding;
}
/// One placed node.
///
/// [key], [terminal] and [stageIndex] are the definition node's own identity,
/// copied unchanged. [x]/[y] are the measured rectangle's top-left corner in
/// graph space and [rank] is its 0-based topological column.
class GraphNodeBox {
const GraphNodeBox({
required this.key,
required this.terminal,
required this.stageIndex,
required this.rank,
required this.x,
required this.y,
required this.width,
required this.height,
});
final String key;
final bool terminal;
final int? stageIndex;
final int rank;
final double x;
final double y;
final double width;
final double height;
double get right => x + width;
double get bottom => y + height;
@override
bool operator ==(Object other) =>
other is GraphNodeBox &&
other.key == key &&
other.terminal == terminal &&
other.stageIndex == stageIndex &&
other.rank == rank &&
other.x == x &&
other.y == y &&
other.width == width &&
other.height == height;
@override
int get hashCode =>
Object.hash(key, terminal, stageIndex, rank, x, y, width, height);
}
/// An immutable node layout: every placed box plus the total graph bounds.
///
/// [nodes] is ordered by rank first and definition order inside a rank; use
/// [ranks] or [nodeFor] for keyed lookup. [width] and [height] include the
/// caller's padding; every box's [right] and [bottom] stay inside them.
/// [ranks] exposes each definition key's 0-based rank; [rankCount] is the
/// number of columns (0 for an empty node set).
class GraphLayout {
GraphLayout({
required List<GraphNodeBox> nodes,
required this.width,
required this.height,
required this.rankCount,
required Map<String, int> ranks,
}) : nodes = List.unmodifiable(nodes),
ranks = Map.unmodifiable(ranks);
final List<GraphNodeBox> nodes;
final Map<String, int> ranks;
final double width;
final double height;
final int rankCount;
bool get isEmpty => nodes.isEmpty;
/// The placed box for [key], or null when the definition has no such node.
GraphNodeBox? nodeFor(String key) {
for (final node in nodes) {
if (node.key == key) return node;
}
return null;
}
}
@@ -0,0 +1,123 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../data/runs_repository.dart';
import 'action_refusal.dart';
import 'retry_dialog.dart';
import 'retry_eligibility.dart';
import 'retry_intent.dart';
import 'retry_wording.dart';
/// The run detail's deliberate retry entry point.
///
/// Renders one native button only while [run] is a stopped `failed` run. Opening
/// the resume or restart confirmation sends nothing; only the confirm action
/// asks the server to retry. A refusal is returned to the kept-open prompt
/// immediately and the run is re-read separately, so [onRunChanged] still
/// receives server truth without locking the prompt while that read is pending.
class RetryRunAction extends StatefulWidget {
const RetryRunAction({
super.key,
required this.run,
required this.gateway,
required this.onRunChanged,
});
final JsonMap run;
final ApiGateway gateway;
final ValueChanged<JsonMap> onRunChanged;
@override
State<RetryRunAction> createState() => _RetryRunActionState();
}
class _RetryRunActionState extends State<RetryRunAction> {
bool _dialogOpen = false;
Future<bool?>? _resync;
bool _usesCupertino(BuildContext context) {
final material = Localizations.of<MaterialLocalizations>(
context,
MaterialLocalizations,
);
return material == null;
}
Future<void> _open() async {
final id = retryRunId(widget.run);
if (id == null || !canRetryRun(widget.run) || _dialogOpen) return;
_dialogOpen = true;
try {
await showRetryRunPrompt(
context: context,
runId: id,
cupertino: _usesCupertino(context),
onSubmit: (intent) => _submit(id, intent),
);
} finally {
_dialogOpen = false;
if (mounted) setState(() {});
}
}
Future<ActionRefusal?> _submit(num id, RetryIntent intent) async {
final repository = RunsRepository(widget.gateway);
try {
final run = await repository.retryRun(
id,
requestKey: intent.requestKey,
mode: intent.mode.wireMode,
);
if (!mounted) return null;
if (_owns(id)) widget.onRunChanged(run);
return null;
} catch (error) {
return ActionRefusal(
describeRetryError(error),
stillPossible: _resyncRun(id),
);
}
}
bool _owns(num id) => mounted && retryRunId(widget.run) == id;
/// One bounded re-read per refusal. A refusal that arrives while a read is
/// already in flight observes that same read instead of starting another.
Future<bool?> _resyncRun(num id) {
return _resync ??= _readRun(id);
}
Future<bool?> _readRun(num id) async {
try {
final run = await RunsRepository(widget.gateway).getRun(id);
if (!_owns(id)) return null;
widget.onRunChanged(run);
return canRetryRun(run);
} catch (_) {
// Unknown server truth: keep the refusal and leave a deliberate retry.
return null;
} finally {
_resync = null;
}
}
@override
Widget build(BuildContext context) {
if (retryRunId(widget.run) == null || !canRetryRun(widget.run)) {
return const SizedBox.shrink();
}
if (_usesCupertino(context)) {
return CupertinoButton.filled(
key: retryActionKey,
onPressed: _open,
child: const Text(retryActionLabel),
);
}
return FilledButton(
key: retryActionKey,
onPressed: _open,
child: const Text(retryActionLabel),
);
}
}
@@ -0,0 +1,207 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'action_refusal.dart';
import 'retry_intent.dart';
import 'retry_wording.dart';
/// Sends the confirmed retry intent. Returns null once the server has accepted
/// it, or an [ActionRefusal] carrying the server's words verbatim; the prompt
/// then stays open with dismissal available immediately.
typedef RetrySubmit = Future<ActionRefusal?> Function(RetryIntent intent);
/// Opens the native retry confirmation for [runId].
///
/// The first confirmation offers resume (the default) and a secondary
/// `Restart from start` confirmation, exactly like the browser's retry dialog.
/// Nothing is sent until the operator presses a confirm action; `Keep` only
/// closes the prompt.
Future<void> showRetryRunPrompt({
required BuildContext context,
required num runId,
required bool cupertino,
required RetrySubmit onSubmit,
}) {
final prompt = _RetryPrompt(
runId: runId,
cupertino: cupertino,
onSubmit: onSubmit,
);
if (cupertino) {
return showCupertinoDialog<void>(
context: context,
barrierDismissible: false,
builder: (_) => prompt,
);
}
return showDialog<void>(
context: context,
barrierDismissible: false,
builder: (_) => prompt,
);
}
class _RetryPrompt extends StatefulWidget {
const _RetryPrompt({
required this.runId,
required this.cupertino,
required this.onSubmit,
});
final num runId;
final bool cupertino;
final RetrySubmit onSubmit;
@override
State<_RetryPrompt> createState() => _RetryPromptState();
}
class _RetryPromptState extends State<_RetryPrompt> {
RetryMode _mode = RetryMode.resume;
String? _requestKey;
bool _sending = false;
bool _checking = false;
bool _blocked = false;
bool _attempted = false;
String? _error;
void _keep() {
if (!_sending) Navigator.of(context).pop();
}
void _restart() {
if (_sending || _checking || _attempted) return;
setState(() {
_mode = RetryMode.restart;
_error = null;
});
}
Future<void> _confirm() async {
if (_sending || _checking || _blocked) return;
setState(() {
_sending = true;
_attempted = true;
_error = null;
});
final intent = RetryIntent(
mode: _mode,
requestKey: _requestKey ??= newRetryRequestKey(widget.runId),
);
final refusal = await widget.onSubmit(intent);
if (!mounted) return;
if (refusal == null) {
Navigator.of(context).pop();
return;
}
final check = refusal.stillPossible;
setState(() {
_sending = false;
_error = refusal.message;
_checking = check != null;
});
if (check == null) return;
bool? stillPossible;
try {
stillPossible = await check;
} catch (_) {
// The action reports re-read failures as null; never fabricate one here.
}
if (!mounted) return;
setState(() {
_checking = false;
_blocked = stillPossible == false;
});
}
@override
Widget build(BuildContext context) {
final dialog = widget.cupertino ? _cupertino(context) : _material(context);
return PopScope(canPop: !_sending, child: dialog);
}
bool get _confirmDisabled => _sending || _checking || _blocked;
bool get _showRestart => _mode == RetryMode.resume && !_attempted;
Widget _material(BuildContext context) {
final theme = Theme.of(context);
return AlertDialog(
scrollable: true,
title: Text(_dialogTitle),
content: _body(errorStyle: TextStyle(color: theme.colorScheme.error)),
actions: [
if (_showRestart)
TextButton(
key: retryRestartKey,
onPressed: _sending || _checking ? null : _restart,
child: const Text(restartConfirmLabel),
),
TextButton(
key: retryKeepKey,
onPressed: _sending ? null : _keep,
child: const Text(retryKeepLabel),
),
FilledButton(
key: retryConfirmKey,
onPressed: _confirmDisabled ? null : _confirm,
child: Text(_confirmLabel),
),
],
);
}
Widget _cupertino(BuildContext context) {
return CupertinoAlertDialog(
title: Text(_dialogTitle),
content: _body(
errorStyle: TextStyle(
color: CupertinoColors.systemRed.resolveFrom(context),
),
),
actions: [
if (_showRestart)
CupertinoDialogAction(
key: retryRestartKey,
onPressed: _sending || _checking ? null : _restart,
child: const Text(restartConfirmLabel),
),
CupertinoDialogAction(
key: retryKeepKey,
onPressed: _sending ? null : _keep,
child: const Text(retryKeepLabel),
),
CupertinoDialogAction(
key: retryConfirmKey,
isDestructiveAction: _mode == RetryMode.restart,
onPressed: _confirmDisabled ? null : _confirm,
child: Text(_confirmLabel),
),
],
);
}
Widget _body({required TextStyle errorStyle}) {
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(_dialogMessage),
if (_error case final error?)
Padding(
padding: const EdgeInsets.only(top: 8),
child: Text(error, key: retryErrorKey, style: errorStyle),
),
],
);
}
String get _dialogTitle => _mode == RetryMode.restart
? restartDialogTitle(widget.runId)
: retryDialogTitle(widget.runId);
String get _dialogMessage =>
_mode == RetryMode.restart ? restartDialogMessage : retryDialogMessage;
String get _confirmLabel =>
_mode == RetryMode.restart ? restartConfirmLabel : retryConfirmLabel;
}
@@ -0,0 +1,16 @@
import '../../../core/api_gateway.dart';
/// Whether the operator may retry [run], matching `canRetry` in
/// `web/src/actions.js` exactly: a loaded run that is not executing and whose
/// status is `failed`. A stale `failed` status while the run still executes is
/// not retryable.
bool canRetryRun(JsonMap? run) {
if (run == null) return false;
return run['executing'] != true && run['status'] == 'failed';
}
/// The run id used by the retry request, or null for a malformed run.
num? retryRunId(JsonMap run) {
final id = run['id'];
return id is num ? id : null;
}
@@ -0,0 +1,29 @@
import 'dart:math';
/// The two deliberate retry choices. `resume` is the server's default, so its
/// wire field is omitted; `restart` replays the whole pipeline.
enum RetryMode {
resume,
restart;
/// The `retry_mode` value to send, or null to let the server resume.
String? get wireMode => this == RetryMode.restart ? 'restart' : null;
}
/// One confirmed retry intent: the chosen mode plus the idempotency key that
/// belongs to it. Retrying the same uncertain intent reuses [requestKey] so the
/// server can dedupe it; a fresh deliberate intent uses a new key.
class RetryIntent {
const RetryIntent({required this.mode, required this.requestKey});
final RetryMode mode;
final String requestKey;
}
/// A fresh `request_key` for one retry intent. The server requires one and caps
/// it at 128 characters; this stays well inside that bound and unique per call.
String newRetryRequestKey(num runId, {DateTime? now, int? random}) {
final stamp = (now ?? DateTime.now()).microsecondsSinceEpoch;
final entropy = random ?? Random().nextInt(1 << 32);
return 'app-retry-$runId-$stamp-${entropy.toRadixString(36)}';
}
@@ -0,0 +1,33 @@
import 'package:flutter/widgets.dart';
/// The browser client's retry wording, kept verbatim.
const retryActionLabel = 'Retry';
const retryDialogMessage =
'Only failed runs can be retried. The server starts a new run from the '
'same input.';
const retryConfirmLabel = 'Retry';
const restartDialogMessage =
'This replays the whole pipeline from the start instead of resuming the '
'failed stage.';
const restartConfirmLabel = 'Restart from start';
const retryKeepLabel = 'Keep';
/// Stable test/semantics keys shared by the action and its prompt.
const retryActionKey = ValueKey<String>('retry-run-action');
const retryKeepKey = ValueKey<String>('retry-run-keep');
const retryConfirmKey = ValueKey<String>('retry-run-confirm');
const retryRestartKey = ValueKey<String>('retry-run-restart');
const retryErrorKey = ValueKey<String>('retry-run-error');
/// The retry dialog's title: `Retry run {id}?`.
String retryDialogTitle(num runId) => 'Retry run $runId?';
/// The restart dialog's title: `Restart run {id}?`.
String restartDialogTitle(num runId) => 'Restart run $runId?';
/// The server's refusal, verbatim. Only a blank error gets a generic sentence
/// so the prompt never claims a retry that did not happen.
String describeRetryError(Object error) {
final message = '$error'.trim();
return message.isEmpty ? 'The server did not retry the run.' : message;
}
@@ -0,0 +1,28 @@
import '../../../core/api_gateway.dart';
import '../domain/search_models.dart';
/// Search protocol requests over the application's shared gateway.
///
/// The request body is exactly `SearchRequest{query, kind, limit}` with
/// `limit: 0`, so the server applies its own default cap (`SearchDefaultLimit`,
/// 50) instead of the client choosing a larger one.
class SearchRepository {
SearchRepository(this._gateway);
final ApiGateway _gateway;
/// Returns the bounded `search_results` body, or null when an older server
/// answered without it (its default `pong`) so the caller can report the
/// "cannot search" sentence rather than showing a false empty success.
Future<SearchResponse?> search({
required String query,
required SearchKind kind,
}) async {
final reply = await _gateway.call('search', {
'search': {'query': query, 'kind': kind.wire, 'limit': 0},
});
final results = reply['search_results'];
if (results is! Map) return null;
return SearchResponse.fromJson(Map<String, dynamic>.from(results));
}
}
@@ -0,0 +1,236 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import '../data/search_repository.dart';
import 'search_models.dart';
import 'search_query.dart';
import 'search_row.dart';
/// The body the results area shows, in the browser's precedence order: an error
/// takes precedence over retained results, a refresh keeps results on screen,
/// and a first load shows the searching row.
enum SearchBodyKind { idle, searching, results, empty, error }
/// Debounced, stale-safe omni-search state. It owns no widgets and no socket:
/// the screen listens to it and the repository talks to the shared gateway.
class OmniSearchController extends ChangeNotifier {
OmniSearchController({
required this.repository,
this.debounce = const Duration(milliseconds: 250),
});
final SearchRepository repository;
final Duration debounce;
final SearchSequencer _sequencer = SearchSequencer();
Timer? _timer;
bool _disposed = false;
String _query = '';
SearchKind _selectedKind = SearchKind.all;
List<JsonMap> _results = const [];
bool _loading = false;
bool _loaded = false;
bool _truncated = false;
int _scannedSteps = 0;
int _scannedBytes = 0;
int _cap = 0;
int _scanBoundBytes = 0;
String? _error;
String get query => _query;
SearchKind get selectedKind => _selectedKind;
ParsedSearchQuery get parsed => parseSearchQuery(_query, _selectedKind);
List<JsonMap> get results => _results;
bool get loading => _loading;
bool get loaded => _loaded;
bool get truncated => _truncated;
int get scannedSteps => _scannedSteps;
int get scannedBytes => _scannedBytes;
int get cap => _cap;
int get scanBoundBytes => _scanBoundBytes;
String? get error => _error;
/// The results already in hand, re-narrowed to the effective kind so the list
/// always matches the control while a narrowed request loads.
List<JsonMap> get shownResults {
final kind = parsed.kind;
if (kind == SearchKind.all) return _results;
return _results
.where((hit) => hit['kind'] == kind.wire)
.toList(growable: false);
}
SearchBodyKind get bodyKind {
if (_error != null) return SearchBodyKind.error;
if (shownResults.isNotEmpty) return SearchBodyKind.results;
if (_loading && _results.isEmpty) return SearchBodyKind.searching;
if (emptyMessage != null) return SearchBodyKind.empty;
return SearchBodyKind.idle;
}
/// A thin progress report above retained results while a newer query loads.
bool get showProgress => _loading && _results.isNotEmpty;
String? get emptyMessage {
if (_error != null || _loading || shownResults.isNotEmpty) return null;
final effective = parsed;
if (effective.query.trim().isEmpty) {
if (!_loaded || effective.kind == SearchKind.all) return null;
final label = effective.kind.label.toLowerCase();
return _truncated
? "No $label found within the server's scan limit."
: 'No $label yet.';
}
final bounded = _truncated ? " within the server's scan limit" : '';
if (effective.kind == SearchKind.all) {
return 'No matches for "${effective.query}"$bounded.';
}
return 'No ${effective.kind.label.toLowerCase()} match '
'"${effective.query}"$bounded.';
}
/// The server's own result/scan bounds, so a capped answer is not presented as
/// a complete one. A truncated reply keeps its warning even with no rows;
/// before any loaded reply there is nothing to report.
String? get boundsText {
if (!_loaded) return null;
// A new first load has no current result set yet, so do not carry the
// previous reply's warning while the searching state is on screen.
if (_loading && _results.isEmpty) return null;
if (_results.isEmpty && !_truncated) return null;
final count = _results.length;
final parts = <String>[];
if (_truncated) {
parts.add("Results truncated by the server's result or scan limit.");
}
parts.add('$count ${count == 1 ? 'result' : 'results'}');
if (_cap > 0) parts.add('cap $_cap');
parts.add('scanned $_scannedSteps steps');
parts.add('${humanBytes(_scannedBytes)} scanned');
if (_scanBoundBytes > 0) {
parts.add('scan limit ${humanBytes(_scanBoundBytes)}');
}
return parts.join(' · ');
}
/// Record a keystroke. Blank text with no kind clears locally and sends
/// nothing; valid kind-only browsing is sendable like the browser's search.
void updateQuery(String value) {
_query = value;
_error = null;
_cancelTimer();
final effective = parsed;
if (!searchQuerySendable(effective.query, effective.kind)) {
_sequencer.edit('');
_clearResults();
_notify();
return;
}
_loading = true;
final edit = _sequencer.edit(value);
_notify();
_timer = Timer(debounce, () {
_timer = null;
final sent = _sequencer.begin(edit);
if (sent != null) unawaited(_send(sent));
});
}
/// A kind change removes recognised type tokens from the visible text and
/// sends at once, matching the browser's selector behaviour.
void selectKind(SearchKind kind) {
_query = parseSearchQuery(_query, _selectedKind).query;
_selectedKind = kind;
_error = null;
_notify();
unawaited(sendNow());
}
/// Enter: send the current query immediately, skipping the debounce.
Future<void> submit() => sendNow();
/// Retry the current query after a failure.
Future<void> retry() => sendNow();
Future<void> sendNow() async {
_cancelTimer();
final effective = parseSearchQuery(_query, _selectedKind);
if (!searchQuerySendable(effective.query, effective.kind)) {
_sequencer.edit('');
_clearResults();
_notify();
return;
}
final sent = _sequencer.begin(_sequencer.edit(_query));
if (sent == null) return;
await _send(sent);
}
Future<void> _send(SearchEdit sent) async {
final effective = parseSearchQuery(sent.query, _selectedKind);
_loading = true;
_error = null;
_notify();
try {
final response = await repository.search(
query: effective.query.trim(),
kind: effective.kind,
);
if (!_sequencer.accepts(sent.token) || _disposed) return;
if (response == null) {
_loading = false;
_loaded = true;
_error = unsupportedSearchCopy;
_notify();
return;
}
_results = response.results;
_truncated = response.truncated;
_scannedSteps = response.scannedSteps;
_scannedBytes = response.scannedBytes;
_cap = response.cap;
_scanBoundBytes = response.scanBoundBytes;
_loading = false;
_loaded = true;
_error = null;
_notify();
} catch (error) {
if (!_sequencer.accepts(sent.token) || _disposed) return;
_loading = false;
_loaded = true;
_error = searchFailureText(error);
_notify();
}
}
void _clearResults() {
_results = const [];
_truncated = false;
_scannedSteps = 0;
_scannedBytes = 0;
_cap = 0;
_scanBoundBytes = 0;
_loading = false;
_loaded = false;
_error = null;
}
void _cancelTimer() {
_timer?.cancel();
_timer = null;
}
void _notify() {
if (!_disposed) notifyListeners();
}
@override
void dispose() {
_disposed = true;
_cancelTimer();
super.dispose();
}
}
@@ -0,0 +1,43 @@
/// Human bytes with the shared binary units (`2.0 KiB`), matching the browser.
String humanBytes(int size) {
const unit = 1024;
if (size < unit) return '$size B';
var divisor = unit;
var exponent = 0;
var scaled = size ~/ unit;
while (scaled >= unit && exponent < 5) {
divisor *= unit;
exponent++;
scaled ~/= unit;
}
return '${(size / divisor).toStringAsFixed(1)} ${'KMGTPE'[exponent]}iB';
}
const _months = [
'Jan',
'Feb',
'Mar',
'Apr',
'May',
'Jun',
'Jul',
'Aug',
'Sep',
'Oct',
'Nov',
'Dec',
];
/// An RFC3339 timestamp as the app's one human local rendering (`20 Oct 12:00`),
/// or null when blank/unparseable so the caller omits the value rather than
/// printing a blank.
String? formatSearchTimestamp(String value) {
final text = value.trim();
if (text.isEmpty) return null;
final instant = DateTime.tryParse(text);
if (instant == null) return null;
final local = instant.toLocal();
final hour = local.hour.toString().padLeft(2, '0');
final minute = local.minute.toString().padLeft(2, '0');
return '${local.day} ${_months[local.month - 1]} $hour:$minute';
}
@@ -0,0 +1,87 @@
import '../../../core/api_gateway.dart';
/// The server's search narrowing vocabulary (`internal/protocol/search.go`),
/// in the control's display order. The empty [wire] value means every kind.
enum SearchKind {
all('', 'All kinds'),
pipeline('pipeline', 'Pipelines'),
run('run', 'Runs'),
step('step', 'Steps'),
field('field', 'Fields'),
artifact('artifact', 'Artifacts'),
version('version', 'Versions');
const SearchKind(this.wire, this.label);
final String wire;
final String label;
/// A stale or unknown value falls back to [SearchKind.all] rather than
/// inventing an option the server does not accept.
static SearchKind fromWire(String? wire) {
for (final kind in values) {
if (kind.wire == wire) return kind;
}
return SearchKind.all;
}
}
/// A query after `t:`/`type:` tokens have been recognised. [query] is the text
/// the server should match; [kind] is the effective narrowing.
class ParsedSearchQuery {
const ParsedSearchQuery(this.query, this.kind, this.hasType);
final String query;
final SearchKind kind;
final bool hasType;
}
/// The bounded `search_results` body from the server. Every bound the server
/// reports is kept, so the screen can show a truncation/scan indicator instead
/// of pretending a capped reply was complete.
class SearchResponse {
const SearchResponse({
this.query = '',
this.kind = SearchKind.all,
this.results = const [],
this.truncated = false,
this.scannedSteps = 0,
this.scannedBytes = 0,
this.cap = 0,
this.scanBoundBytes = 0,
});
factory SearchResponse.fromJson(JsonMap json) {
final rows = json['results'];
return SearchResponse(
query: '${json['query'] ?? ''}',
kind: SearchKind.fromWire('${json['kind'] ?? ''}'),
results: rows is List
? rows
.whereType<Map>()
.map((row) => Map<String, dynamic>.from(row))
.toList(growable: false)
: const [],
truncated: json['truncated'] == true,
scannedSteps: _integer(json['scanned_steps']),
scannedBytes: _integer(json['scanned_bytes']),
cap: _integer(json['cap']),
scanBoundBytes: _integer(json['scan_bound_bytes']),
);
}
final String query;
final SearchKind kind;
final List<JsonMap> results;
final bool truncated;
final int scannedSteps;
final int scannedBytes;
final int cap;
final int scanBoundBytes;
}
int _integer(Object? value) {
if (value is int) return value;
if (value is num) return value.toInt();
return int.tryParse('$value') ?? 0;
}
@@ -0,0 +1,82 @@
import 'search_models.dart';
/// Wording for a server that cannot answer `search`: an explicit rejection
/// naming an unknown/unsupported command, or a reply without
/// `search_results`. Kept verbatim from the web client's AppViewModel copy.
const unsupportedSearchCopy =
'This server does not support search. Update the Pipelines server, then try again.';
/// Unquoted, whitespace-delimited `t:`/`type:` tokens; the last supported token
/// wins. Unknown tokens and quoted text stay literal, including their whitespace.
/// The selector is a fallback; explicitly changing it removes tokens in the view.
///
/// This is the same token grammar as `web/src/search.js`, so `"t:run"`,
/// `t:unknown`, `prefix"t:run"` and `\t:run` all remain searchable text.
ParsedSearchQuery parseSearchQuery(
String value, [
SearchKind selectedKind = SearchKind.all,
]) {
var kind = selectedKind;
var hasType = false;
final query = value.replaceAllMapped(_tokenPattern, (match) {
final token = match[0] ?? '';
final type = _typePattern.firstMatch(token);
if (type == null) return token;
final candidate = SearchKind.fromWire(type.group(1)!.toLowerCase());
if (candidate == SearchKind.all) return token;
kind = candidate;
hasType = true;
return '';
});
return ParsedSearchQuery(query, kind, hasType);
}
final _tokenPattern = RegExp(
r'''(?:[^\s"'\\]|\\[\s\S]|"(?:[^"\\]|\\[\s\S])*(?:"|$)|'(?:[^'\\]|\\[\s\S])*(?:'|$))+''',
);
final _typePattern = RegExp(r'^(?:t|type):([a-z]+)$', caseSensitive: false);
/// Text searches and valid kind-only browsing are sendable. Empty text with no
/// supported kind clears locally, without an all-kind scan.
bool searchQuerySendable(String query, SearchKind kind) =>
query.trim().isNotEmpty || kind != SearchKind.all;
/// The message for a failed search: the unsupported sentence for a missing
/// payload or an unknown-command rejection, otherwise the server's own text.
String searchFailureText(Object? error) {
if (error == null) return unsupportedSearchCopy;
final message = error.toString().trim();
if (message.isEmpty) return unsupportedSearchCopy;
if (_unsupportedCommand.hasMatch(message)) return unsupportedSearchCopy;
return message;
}
final _unsupportedCommand = RegExp(
r'\b(unknown|unsupported|unrecognised|unrecognized)\b[\s\S]*\bcommand\b',
caseSensitive: false,
);
/// One recorded edit being debounced.
class SearchEdit {
const SearchEdit(this.token, this.query);
final int token;
final String query;
}
/// Query sequencing: a burst of keystrokes collapses into one request, and a
/// reply is accepted only for the newest recorded edit, so a stale reply can
/// never overwrite a newer one. Recording an edit (a keystroke, or an empty
/// edit when the field clears) is enough to invalidate an in-flight reply.
class SearchSequencer {
int _newest = 0;
SearchEdit edit(String query) => SearchEdit(++_newest, query);
SearchEdit? begin(SearchEdit? edit) {
if (edit == null || edit.token != _newest) return null;
return edit;
}
bool accepts(int token) => token == _newest;
}
@@ -0,0 +1,226 @@
import '../../../core/api_gateway.dart';
import 'search_format.dart';
export 'search_format.dart' show humanBytes, formatSearchTimestamp;
/// One run of a field snippet, split so the first case-insensitive occurrence of
/// the query can be emphasised without colour or markup.
class SearchSnippetSpan {
const SearchSnippetSpan(this.text, {required this.matched});
final String text;
final bool matched;
}
/// A render-ready search row. [target] is the server's own stable target token;
/// it is null for an unknown/absent payload or a reply without a target, and
/// such a row is read-only — the client never guesses a route.
class SearchRowView {
const SearchRowView({
required this.title,
required this.secondary,
required this.kindLabel,
required this.snippetSpans,
required this.target,
this.snippet,
this.recency,
});
final String title;
final String secondary;
final String kindLabel;
final String? snippet;
final List<SearchSnippetSpan> snippetSpans;
final String? recency;
final String? target;
bool get openable => target != null;
}
/// One rendered search row, mirroring the browser's per-kind row text. Every
/// server-provided string is only ever compared or rendered as text.
SearchRowView searchRowView(JsonMap hit, String query) {
final pipeline = _map(hit['pipeline']);
final version = _map(hit['version']);
final run = _map(hit['run']);
final step = _map(hit['step']);
final field = _map(hit['field']);
final artifact = _map(hit['artifact']);
final recency = formatSearchTimestamp('${hit['recency'] ?? ''}');
final target = _serverTarget(hit);
if (pipeline != null) {
return SearchRowView(
title: _nonBlank(pipeline['name']) ?? 'pipeline ${_num(pipeline['id'])}',
secondary:
'pipeline ${_num(pipeline['id'])} · v${_num(pipeline['version'])}'
' · ${_stageCount(pipeline['stages'])}',
kindLabel: 'Pipeline',
snippetSpans: const [],
recency: recency,
target: target,
);
}
if (version != null) {
final hash = _nonBlank(version['content_hash']);
return SearchRowView(
title:
'pipeline ${_num(version['pipeline_id'])}'
' · v${_num(version['version'])}',
secondary: _join([
hash == null ? null : 'content $hash',
formatSearchTimestamp('${version['created_at'] ?? ''}'),
]),
kindLabel: 'Pipeline version',
snippetSpans: const [],
recency: recency,
target: target,
);
}
if (run != null) {
final name = _nonBlank(run['pipeline_name']);
return SearchRowView(
title: 'run #${_num(run['id'])}${name == null ? '' : ' · $name'}',
secondary: _join([
_nonBlank(run['status']),
_nonBlank(run['workspace']),
formatSearchTimestamp('${run['created_at'] ?? ''}'),
]),
kindLabel: 'Run',
snippetSpans: const [],
recency: recency,
target: target,
);
}
if (step != null) {
final stage = _nonBlank(step['stage']) ?? 'step';
return SearchRowView(
title:
'run #${_num(step['run_id'])} · $stage'
' visit ${_num(step['visit'])}',
secondary: _stepSecondary(step),
kindLabel: 'Step',
snippetSpans: const [],
recency: recency,
target: target,
);
}
if (field != null) {
final snippet = '${field['snippet'] ?? ''}';
return SearchRowView(
title:
'run #${_num(field['run_id'])} · step ${_num(field['sequence'])}'
' · ${_nonBlank(field['field']) ?? 'field'}',
secondary: snippet,
kindLabel: 'Field',
snippet: snippet,
snippetSpans: snippetSpans(snippet, query),
recency: recency,
target: target,
);
}
if (artifact != null) {
return SearchRowView(
title: _nonBlank(artifact['name']) ?? 'artifact',
secondary: _join([
'run #${_num(artifact['run_id'])}',
'step ${_num(artifact['sequence'])}',
_nonBlank(artifact['content_type']),
humanBytes(_num(artifact['size_bytes'])),
]),
kindLabel: 'Artifact',
snippetSpans: const [],
recency: recency,
target: target,
);
}
final kind = _nonBlank(hit['kind']);
return SearchRowView(
title: _nonBlank(hit['target']) ?? 'Unrecognised result',
secondary: kind == null ? 'read-only' : 'kind "$kind" · read-only',
kindLabel: 'Unrecognised result',
snippetSpans: const [],
recency: recency,
target: target,
);
}
/// Splits [snippet] so the first case-insensitive occurrence of [query] is a
/// distinct matched span. A blank query or absent match leaves the whole
/// snippet unmatched, so no text is ever dropped.
List<SearchSnippetSpan> snippetSpans(String snippet, String query) {
if (snippet.isEmpty) return const [];
final needle = query.trim();
if (needle.isEmpty) {
return [SearchSnippetSpan(snippet, matched: false)];
}
final index = snippet.toLowerCase().indexOf(needle.toLowerCase());
if (index < 0) return [SearchSnippetSpan(snippet, matched: false)];
final end = index + needle.length;
return [
if (index > 0)
SearchSnippetSpan(snippet.substring(0, index), matched: false),
SearchSnippetSpan(snippet.substring(index, end), matched: true),
if (end < snippet.length)
SearchSnippetSpan(snippet.substring(end), matched: false),
];
}
String _stepSecondary(JsonMap step) {
final diagnostic = '${step['diagnostic'] ?? ''}';
String? line;
for (final candidate in diagnostic.split(RegExp(r'\r?\n'))) {
if (candidate.trim().isNotEmpty) {
line = candidate;
break;
}
}
final target = _nonBlank(step['target']);
final joined = _join([
_nonBlank(step['outcome']),
target == null ? null : '→ $target',
line?.trim(),
]);
return joined.isEmpty ? 'step ${_num(step['sequence'])}' : joined;
}
/// The server's own target token, never a target the client invents. A known
/// payload is not enough: an absent token makes the row read-only.
String? _serverTarget(JsonMap hit) {
final target = _nonBlank(hit['target']);
if (target == null) return null;
final known = [
'pipeline',
'version',
'run',
'step',
'field',
'artifact',
].any((key) => _map(hit[key]) != null);
return known ? target : null;
}
String _stageCount(Object? count) {
final n = _num(count);
return '$n ${n == 1 ? 'stage' : 'stages'}';
}
Map<String, dynamic>? _map(Object? value) {
if (value is! Map) return null;
return Map<String, dynamic>.from(value);
}
String? _nonBlank(Object? value) {
final text = '${value ?? ''}';
return text.trim().isEmpty ? null : text;
}
int _num(Object? value) {
if (value is int) return value;
if (value is num) return value.toInt();
return int.tryParse('${value ?? ''}') ?? 0;
}
String _join(List<String?> parts) =>
parts.whereType<String>().where((part) => part.isNotEmpty).join(' · ');
+228
View File
@@ -0,0 +1,228 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../core/api_gateway.dart';
import 'data/search_repository.dart';
import 'domain/search_controller.dart';
import 'domain/search_models.dart';
import 'ui/cupertino_search_body.dart';
import 'ui/material_search_body.dart';
/// Native omni-search over the Pipelines server: a standard search field, an
/// explicit kind selector, and a flat result list whose rows open the server's
/// own target through [onOpen]. The screen never mutates server state and never
/// guesses a route for an unknown or targetless hit.
class SearchScreen extends StatefulWidget {
const SearchScreen({
super.key,
required this.gateway,
required this.onOpen,
this.cupertino,
});
final ApiGateway gateway;
final ValueChanged<JsonMap> onOpen;
/// Lets the shell state the surface it composed. When omitted, iOS/macOS use
/// Cupertino controls and every other platform uses Material.
final bool? cupertino;
@override
State<SearchScreen> createState() => _SearchScreenState();
}
class _SearchScreenState extends State<SearchScreen> {
late final OmniSearchController _controller;
late final TextEditingController _text;
@override
void initState() {
super.initState();
_controller = OmniSearchController(
repository: SearchRepository(widget.gateway),
);
_text = TextEditingController();
_controller.addListener(_onState);
}
void _onState() {
final query = _controller.query;
if (_text.text != query) {
_text.value = TextEditingValue(
text: query,
selection: TextSelection.collapsed(offset: query.length),
);
}
if (mounted) setState(() {});
}
void _clear() {
_text.clear();
_controller.updateQuery('');
}
void _selectKind(SearchKind kind) => _controller.selectKind(kind);
bool get _showHint {
final body = _controller.bodyKind;
return body == SearchBodyKind.idle || body == SearchBodyKind.empty;
}
Future<void> _pickKind(BuildContext context) async {
final selected = await showCupertinoModalPopup<SearchKind>(
context: context,
builder: (context) => CupertinoActionSheet(
title: const Text('Kind'),
actions: [
for (final kind in SearchKind.values)
CupertinoActionSheetAction(
onPressed: () => Navigator.pop(context, kind),
isDefaultAction: kind == _controller.parsed.kind,
child: Text(kind.label),
),
],
cancelButton: CupertinoActionSheetAction(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
),
);
if (selected != null) _selectKind(selected);
}
@override
void dispose() {
_controller.removeListener(_onState);
_controller.dispose();
_text.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final cupertino =
widget.cupertino ??
switch (Theme.of(context).platform) {
TargetPlatform.iOS || TargetPlatform.macOS => true,
_ => false,
};
return cupertino ? _cupertinoScreen() : _materialScreen();
}
Widget _materialScreen() => Scaffold(
appBar: AppBar(title: const Text('Search')),
body: SafeArea(
child: MaterialSearchBody(
controller: _controller,
query: _controller.parsed.query,
onOpen: widget.onOpen,
header: _materialHeader(),
),
),
);
Widget _materialHeader() => Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
spacing: 8,
children: [
SearchBar(
key: const ValueKey('search.field'),
controller: _text,
autoFocus: true,
hintText: 'Search pipelines, runs and artifacts',
leading: const Icon(Icons.search),
trailing: [
if (_text.text.isNotEmpty)
IconButton(
key: const ValueKey('search.clear'),
onPressed: _clear,
tooltip: 'Clear search',
icon: const Icon(Icons.close),
),
],
textInputAction: TextInputAction.search,
onChanged: _controller.updateQuery,
onSubmitted: (_) => _controller.submit(),
),
InputDecorator(
decoration: const InputDecoration(
labelText: 'Kind',
border: OutlineInputBorder(),
),
child: DropdownButtonHideUnderline(
child: DropdownButton<SearchKind>(
key: const ValueKey('search.kind'),
value: _controller.parsed.kind,
isExpanded: true,
onChanged: (kind) {
if (kind != null) _selectKind(kind);
},
items: [
for (final kind in SearchKind.values)
DropdownMenuItem(value: kind, child: Text(kind.label)),
],
),
),
),
if (_showHint) const Text(_tokenHint),
if (_controller.boundsText case final bounds?) Text(bounds),
],
),
);
Widget _cupertinoScreen() => CupertinoPageScaffold(
navigationBar: const CupertinoNavigationBar(middle: Text('Search')),
child: SafeArea(
child: CupertinoSearchBody(
controller: _controller,
query: _controller.parsed.query,
onOpen: widget.onOpen,
header: _cupertinoHeader(context),
),
),
);
Widget _cupertinoHeader(BuildContext context) => Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
spacing: 8,
children: [
CupertinoSearchTextField(
key: const ValueKey('search.field'),
controller: _text,
autofocus: true,
placeholder: 'Search pipelines, runs and artifacts',
onChanged: _controller.updateQuery,
onSubmitted: (_) => _controller.submit(),
onSuffixTap: _clear,
),
Align(
alignment: AlignmentDirectional.centerStart,
child: CupertinoButton(
key: const ValueKey('search.kind'),
padding: EdgeInsets.zero,
onPressed: () => _pickKind(context),
child: Row(
mainAxisSize: MainAxisSize.max,
spacing: 6,
children: [
Expanded(child: Text('Kind: ${_controller.parsed.kind.label}')),
const Icon(CupertinoIcons.chevron_down),
],
),
),
),
if (_showHint) const Text(_tokenHint),
if (_controller.boundsText case final bounds?) Text(bounds),
],
),
);
}
const _tokenHint =
'Filter with t:pipeline or type:artifact (pipeline, run, step, field, '
'artifact, version). Last type wins; choosing Kind replaces it. Quote '
'tokens to search literally.';
@@ -0,0 +1,174 @@
import 'package:flutter/cupertino.dart';
import '../../../core/api_gateway.dart';
import '../domain/search_controller.dart';
import '../domain/search_row.dart';
import 'search_result_view.dart';
/// The Cupertino search view: native search/kind controls and grouped list rows
/// in one scroll view, with standard activity and retry controls.
class CupertinoSearchBody extends StatelessWidget {
const CupertinoSearchBody({
super.key,
required this.controller,
required this.query,
required this.onOpen,
required this.header,
});
final OmniSearchController controller;
final String query;
final ValueChanged<JsonMap> onOpen;
final Widget header;
@override
Widget build(BuildContext context) {
return CustomScrollView(
slivers: [
SliverToBoxAdapter(child: header),
if (controller.showProgress)
const SliverToBoxAdapter(
child: Padding(
padding: EdgeInsets.symmetric(vertical: 8),
child: CupertinoActivityIndicator(),
),
),
..._content(context),
],
);
}
List<Widget> _content(BuildContext context) {
switch (controller.bodyKind) {
case SearchBodyKind.error:
return [
SliverFillRemaining(
hasScrollBody: false,
child: _CupertinoError(
message: controller.error!,
onRetry: controller.retry,
),
),
];
case SearchBodyKind.searching:
return const [
SliverFillRemaining(
hasScrollBody: false,
child: _CupertinoSearching(),
),
];
case SearchBodyKind.results:
return [
SliverToBoxAdapter(
child: CupertinoListSection.insetGrouped(
children: [
for (final hit in controller.shownResults)
_CupertinoResult(hit: hit, query: query, onOpen: onOpen),
],
),
),
];
case SearchBodyKind.empty:
return [
SliverFillRemaining(
hasScrollBody: false,
child: _CupertinoMessage(message: controller.emptyMessage!),
),
];
case SearchBodyKind.idle:
return const [
SliverFillRemaining(
hasScrollBody: false,
child: _CupertinoMessage(
message: 'Search pipelines, runs and artifacts.',
),
),
];
}
}
}
class _CupertinoResult extends StatelessWidget {
const _CupertinoResult({
required this.hit,
required this.query,
required this.onOpen,
});
final JsonMap hit;
final String query;
final ValueChanged<JsonMap> onOpen;
@override
Widget build(BuildContext context) {
final row = searchRowView(hit, query);
return CupertinoListTile(
key: ValueKey('search.result.${hit['target']}'),
leading: Icon(searchCupertinoIcon('${hit['kind'] ?? ''}')),
title: Text(row.title),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
spacing: 2,
children: [searchRowMeta(row), searchRowSnippet(context, row)],
),
onTap: row.openable ? () => onOpen(hit) : null,
);
}
}
class _CupertinoSearching extends StatelessWidget {
const _CupertinoSearching();
@override
Widget build(BuildContext context) => const Center(
child: Padding(
padding: EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
spacing: 12,
children: [CupertinoActivityIndicator(), Text('Searching…')],
),
),
);
}
class _CupertinoMessage extends StatelessWidget {
const _CupertinoMessage({required this.message});
final String message;
@override
Widget build(BuildContext context) => Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Text(message, textAlign: TextAlign.center),
),
);
}
class _CupertinoError extends StatelessWidget {
const _CupertinoError({required this.message, required this.onRetry});
final String message;
final Future<void> Function() onRetry;
@override
Widget build(BuildContext context) => Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
spacing: 12,
children: [
Text(message, textAlign: TextAlign.center),
CupertinoButton.filled(
key: const ValueKey('search.retry'),
onPressed: onRetry,
child: const Text('Retry'),
),
],
),
),
);
}
@@ -0,0 +1,166 @@
import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../domain/search_controller.dart';
import '../domain/search_row.dart';
import 'search_result_view.dart';
/// The Material search view: the controls header and a flat native result list
/// in one scroll view, so text scaling can never clip the controls or a row.
class MaterialSearchBody extends StatelessWidget {
const MaterialSearchBody({
super.key,
required this.controller,
required this.query,
required this.onOpen,
required this.header,
});
final OmniSearchController controller;
final String query;
final ValueChanged<JsonMap> onOpen;
final Widget header;
@override
Widget build(BuildContext context) {
return CustomScrollView(
slivers: [
SliverToBoxAdapter(child: header),
if (controller.showProgress)
const SliverToBoxAdapter(child: LinearProgressIndicator()),
..._content(context),
],
);
}
List<Widget> _content(BuildContext context) {
switch (controller.bodyKind) {
case SearchBodyKind.error:
return [
SliverFillRemaining(
hasScrollBody: false,
child: _SearchError(
message: controller.error!,
onRetry: controller.retry,
),
),
];
case SearchBodyKind.searching:
return const [
SliverFillRemaining(hasScrollBody: false, child: _Searching()),
];
case SearchBodyKind.results:
return [
SliverList.builder(
itemCount: controller.shownResults.length,
itemBuilder: (context, index) {
final hit = controller.shownResults[index];
return _MaterialResult(hit: hit, query: query, onOpen: onOpen);
},
),
];
case SearchBodyKind.empty:
return [
SliverFillRemaining(
hasScrollBody: false,
child: _SearchMessage(message: controller.emptyMessage!),
),
];
case SearchBodyKind.idle:
return const [
SliverFillRemaining(
hasScrollBody: false,
child: _SearchMessage(
message: 'Search pipelines, runs and artifacts.',
),
),
];
}
}
}
class _MaterialResult extends StatelessWidget {
const _MaterialResult({
required this.hit,
required this.query,
required this.onOpen,
});
final JsonMap hit;
final String query;
final ValueChanged<JsonMap> onOpen;
@override
Widget build(BuildContext context) {
final row = searchRowView(hit, query);
return ListTile(
key: ValueKey('search.result.${hit['target']}'),
leading: Icon(searchMaterialIcon('${hit['kind'] ?? ''}')),
title: Text(row.title),
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
spacing: 2,
children: [searchRowMeta(row), searchRowSnippet(context, row)],
),
onTap: row.openable ? () => onOpen(hit) : null,
);
}
}
class _Searching extends StatelessWidget {
const _Searching();
@override
Widget build(BuildContext context) => const Center(
child: Padding(
padding: EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
spacing: 12,
children: [CircularProgressIndicator(), Text('Searching…')],
),
),
);
}
class _SearchMessage extends StatelessWidget {
const _SearchMessage({required this.message});
final String message;
@override
Widget build(BuildContext context) => Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Text(message, textAlign: TextAlign.center),
),
);
}
class _SearchError extends StatelessWidget {
const _SearchError({required this.message, required this.onRetry});
final String message;
final Future<void> Function() onRetry;
@override
Widget build(BuildContext context) => Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
spacing: 12,
children: [
Text(message, textAlign: TextAlign.center),
FilledButton.tonalIcon(
key: const ValueKey('search.retry'),
onPressed: onRetry,
icon: const Icon(Icons.refresh),
label: const Text('Retry'),
),
],
),
),
);
}
@@ -0,0 +1,59 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../domain/search_row.dart';
/// Kind, recency and read-only affordance for one row. Deliberately unstyled
/// beyond weight so Material and Cupertino inherit their own system typography
/// and colours, including dark mode and text scaling.
Widget searchRowMeta(SearchRowView row) {
final parts = [row.kindLabel, if (row.recency != null) row.recency!];
return Text(
parts.join(' · '),
style: const TextStyle(fontWeight: FontWeight.w600),
);
}
/// The snippet with the first query occurrence emphasised by weight, never by
/// parsing server text as markup or by a bespoke colour.
Widget searchRowSnippet(BuildContext context, SearchRowView row) {
final snippet = row.snippet;
if (snippet == null) {
return row.secondary.isEmpty
? const SizedBox.shrink()
: Text(row.secondary);
}
return Text.rich(
TextSpan(
children: [
for (final span in row.snippetSpans)
TextSpan(
text: span.text,
style: span.matched
? const TextStyle(fontWeight: FontWeight.bold)
: null,
),
],
),
);
}
IconData searchMaterialIcon(String kind) => switch (kind) {
'pipeline' => Icons.account_tree_outlined,
'version' => Icons.layers_outlined,
'run' => Icons.play_circle_outline,
'step' => Icons.arrow_forward,
'field' => Icons.notes,
'artifact' => Icons.attach_file,
_ => Icons.help_outline,
};
IconData searchCupertinoIcon(String kind) => switch (kind) {
'pipeline' => CupertinoIcons.arrow_branch,
'version' => CupertinoIcons.square_stack_3d_up,
'run' => CupertinoIcons.play_circle,
'step' => CupertinoIcons.arrow_right,
'field' => CupertinoIcons.doc_text,
'artifact' => CupertinoIcons.paperclip,
_ => CupertinoIcons.question_circle,
};
@@ -0,0 +1,84 @@
import '../../../core/api_gateway.dart';
import '../domain/template_entry.dart';
/// A templates protocol refusal kept separate from transport errors; server
/// error envelopes are propagated unchanged by [ApiGateway].
class TemplateRepositoryException implements Exception {
const TemplateRepositoryException(this.message);
final String message;
@override
String toString() => message;
}
/// Template catalogue, definition validation and create-only submission over
/// the application's shared gateway.
///
/// These are reads plus one explicit submit. No method publishes, runs,
/// overwrites or schedules a pipeline, so merely loading or validating a
/// template can never start work.
class TemplateRepository {
TemplateRepository(this._gateway);
final ApiGateway _gateway;
/// The server's template catalogue, exactly as `list_templates` returns it.
/// A reply without a `templates` field is the older server answering with no
/// catalogue, which is an empty list rather than an error.
Future<List<TemplateEntry>> listTemplates() async {
final reply = await _gateway.call('list_templates');
final templates = reply['templates'];
if (templates == null) return const [];
if (templates is! List) {
throw const TemplateRepositoryException(
'The server returned no template catalogue.',
);
}
return List.unmodifiable(
templates.map((entry) {
if (entry is! Map) {
throw const TemplateRepositoryException(
'The server returned a template that is not an object.',
);
}
return TemplateEntry.fromJson(Map<String, dynamic>.from(entry));
}),
);
}
/// Parses one definition source on the server (`validate`) and returns the
/// graph it produced. The source is sent byte-for-byte: no trimming, casing or
/// whitespace changes. A malformed definition rejects with the server's own
/// error; a reply without a graph is refused rather than reported as valid.
Future<JsonMap> validate(String source) async {
final reply = await _gateway.call('validate', {'source': source});
final graph = reply['graph'];
if (graph is! Map) {
throw const TemplateRepositoryException('The server returned no graph.');
}
return Map<String, dynamic>.from(graph);
}
/// Creates a new draft pipeline from [source] (`submit`), create-only.
///
/// A blank name is refused locally before anything is sent, matching the
/// browser and Android clients; the name that is sent is trimmed. The source
/// is not changed. `create_only` is always true, so an existing pipeline can
/// never be overwritten, and no run is started.
Future<JsonMap> submit(String name, String source) async {
final trimmed = name.trim();
if (trimmed.isEmpty) {
throw const TemplateRepositoryException('Enter a pipeline name.');
}
final reply = await _gateway.call('submit', {
'name': trimmed,
'source': source,
'create_only': true,
});
final detail = reply['detail'];
if (detail is! Map) {
throw const TemplateRepositoryException(
'The server returned no pipeline detail.',
);
}
return Map<String, dynamic>.from(detail);
}
}
@@ -0,0 +1,63 @@
import '../../../core/api_gateway.dart';
/// One template from the server catalogue.
///
/// The server owns this record: [key], [name], [description], [source] and
/// [scheduled] are read from it verbatim and every other field is kept in
/// [raw], so a later view or round-trip never loses fields this client does not
/// understand yet. Loading a template is a read; it never publishes or runs it.
class TemplateEntry {
const TemplateEntry({
required this.key,
required this.name,
required this.description,
required this.source,
required this.scheduled,
required this.raw,
});
factory TemplateEntry.fromJson(JsonMap json) {
final raw = _frozenMap(json);
return TemplateEntry(
key: _text(raw['key']),
name: _text(raw['name']),
description: _text(raw['description']),
source: _text(raw['source']),
scheduled: raw['scheduled'] == true,
raw: raw,
);
}
/// The stable catalogue key the gallery selects on.
final String key;
final String name;
final String description;
/// The template's complete, untrimmed definition source.
final String source;
/// Whether the source declares a schedule (the summary's "Includes a schedule").
final bool scheduled;
/// Every field the server sent, including fields this client does not model.
/// Deeply unmodifiable: nested maps and lists are copied into read-only
/// collections too, so a view cannot mutate the server reply through it.
final JsonMap raw;
static String _text(dynamic value) => value == null ? '' : '$value';
static JsonMap _frozenMap(Map<String, dynamic> json) =>
Map<String, dynamic>.unmodifiable(
json.map((key, value) => MapEntry(key, _frozen(value))),
);
static dynamic _frozen(dynamic value) {
if (value is Map) {
return _frozenMap(Map<String, dynamic>.from(value));
}
if (value is List) {
return List<dynamic>.unmodifiable(value.map(_frozen));
}
return value;
}
}