Merge branch 'main' into flutter/x1-search
This commit is contained in:
@@ -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,18 @@
|
||||
/// A refused operator action and, when one was started, the bounded re-read of
|
||||
/// server truth that follows it.
|
||||
///
|
||||
/// The prompt shows [message] and allows dismissal immediately; it must never
|
||||
/// wait for [stillPossible]. That future is only observed so a retry can be
|
||||
/// ruled out once server truth arrives: `true` means the re-read found the run
|
||||
/// still allows the action, `false` means it plainly does not, and `null` means
|
||||
/// the re-read failed or was overtaken, leaving a deliberate retry possible.
|
||||
class ActionRefusal {
|
||||
const ActionRefusal(this.message, {this.stillPossible});
|
||||
|
||||
final String message;
|
||||
final Future<bool?>? stillPossible;
|
||||
}
|
||||
|
||||
/// Local guards, distinct from a server refusal; they never claim success.
|
||||
const actionOptionRequired = 'Choose an option before continuing.';
|
||||
const actionAlreadySending = 'That action is still being sent.';
|
||||
@@ -0,0 +1,165 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'action_refusal.dart';
|
||||
import 'cancel_wording.dart';
|
||||
|
||||
/// Sends the confirmed cancellation. 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 CancelSubmit = Future<ActionRefusal?> Function();
|
||||
|
||||
/// Opens the native cancel confirmation for [runId].
|
||||
///
|
||||
/// Nothing is sent until the operator presses the confirm action, and the
|
||||
/// dismiss action (`Keep`) only closes the prompt.
|
||||
Future<void> showCancelRunPrompt({
|
||||
required BuildContext context,
|
||||
required num runId,
|
||||
required bool cupertino,
|
||||
required CancelSubmit onSubmit,
|
||||
}) {
|
||||
final prompt = _CancelPrompt(
|
||||
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 _CancelPrompt extends StatefulWidget {
|
||||
const _CancelPrompt({
|
||||
required this.runId,
|
||||
required this.cupertino,
|
||||
required this.onSubmit,
|
||||
});
|
||||
|
||||
final num runId;
|
||||
final bool cupertino;
|
||||
final CancelSubmit onSubmit;
|
||||
|
||||
@override
|
||||
State<_CancelPrompt> createState() => _CancelPromptState();
|
||||
}
|
||||
|
||||
class _CancelPromptState extends State<_CancelPrompt> {
|
||||
bool _sending = false;
|
||||
bool _checking = false;
|
||||
bool _blocked = false;
|
||||
String? _error;
|
||||
|
||||
void _keep() {
|
||||
if (!_sending) Navigator.of(context).pop();
|
||||
}
|
||||
|
||||
Future<void> _confirm() async {
|
||||
if (_sending || _checking || _blocked) return;
|
||||
setState(() {
|
||||
_sending = true;
|
||||
_error = null;
|
||||
});
|
||||
final refusal = await widget.onSubmit();
|
||||
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;
|
||||
|
||||
Widget _material(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return AlertDialog(
|
||||
scrollable: true,
|
||||
title: Text(cancelDialogTitle(widget.runId)),
|
||||
content: _body(errorStyle: TextStyle(color: theme.colorScheme.error)),
|
||||
actions: [
|
||||
TextButton(
|
||||
key: cancelKeepKey,
|
||||
onPressed: _sending ? null : _keep,
|
||||
child: const Text(cancelKeepLabel),
|
||||
),
|
||||
FilledButton(
|
||||
key: cancelConfirmKey,
|
||||
onPressed: _confirmDisabled ? null : _confirm,
|
||||
child: const Text(cancelConfirmLabel),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _cupertino(BuildContext context) {
|
||||
return CupertinoAlertDialog(
|
||||
title: Text(cancelDialogTitle(widget.runId)),
|
||||
content: _body(
|
||||
errorStyle: TextStyle(
|
||||
color: CupertinoColors.systemRed.resolveFrom(context),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
CupertinoDialogAction(
|
||||
key: cancelKeepKey,
|
||||
onPressed: _sending ? null : _keep,
|
||||
child: const Text(cancelKeepLabel),
|
||||
),
|
||||
CupertinoDialogAction(
|
||||
key: cancelConfirmKey,
|
||||
isDestructiveAction: true,
|
||||
onPressed: _confirmDisabled ? null : _confirm,
|
||||
child: const Text(cancelConfirmLabel),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _body({required TextStyle errorStyle}) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const Text(cancelDialogMessage),
|
||||
if (_error case final error?)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Text(error, key: cancelErrorKey, style: errorStyle),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
/// Whether the operator may cancel [run], matching `canCancel` in
|
||||
/// `web/src/actions.js` exactly:
|
||||
///
|
||||
/// `(executing || (status == "waiting" && export_pending_sequence > 0)) &&
|
||||
/// !cancel_requested && !cleanup_unconfirmed`
|
||||
///
|
||||
/// The status word alone is not enough: a stale `running` status without
|
||||
/// `executing` is not cancellable, while a run waiting on a pending session
|
||||
/// export is.
|
||||
bool canCancelRun(JsonMap? run) {
|
||||
if (run == null) return false;
|
||||
final exportPending = _number(run['export_pending_sequence']);
|
||||
return (run['executing'] == true ||
|
||||
(run['status'] == 'waiting' && exportPending > 0)) &&
|
||||
run['cancel_requested'] != true &&
|
||||
run['cleanup_unconfirmed'] != true;
|
||||
}
|
||||
|
||||
/// The run id used by the cancel request, or null for a malformed run.
|
||||
num? cancelRunId(JsonMap run) {
|
||||
final id = run['id'];
|
||||
return id is num ? id : null;
|
||||
}
|
||||
|
||||
/// `Number(value) > 0`, tolerating numeric strings as the browser does.
|
||||
double _number(dynamic value) {
|
||||
if (value is num) return value.toDouble();
|
||||
return double.tryParse('${value ?? ''}'.trim()) ?? 0;
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
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 'cancel_dialog.dart';
|
||||
import 'cancel_eligibility.dart';
|
||||
import 'cancel_wording.dart';
|
||||
|
||||
/// The run detail's deliberate cancel entry point.
|
||||
///
|
||||
/// Renders one native button only while [run] is cancellable under the browser
|
||||
/// client's rule. Opening the prompt or choosing [cancelKeepLabel] sends
|
||||
/// nothing; only the confirm action asks the server to stop the run. 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 CancelRunAction extends StatefulWidget {
|
||||
const CancelRunAction({
|
||||
super.key,
|
||||
required this.run,
|
||||
required this.gateway,
|
||||
required this.onRunChanged,
|
||||
});
|
||||
|
||||
final JsonMap run;
|
||||
final ApiGateway gateway;
|
||||
final ValueChanged<JsonMap> onRunChanged;
|
||||
|
||||
@override
|
||||
State<CancelRunAction> createState() => _CancelRunActionState();
|
||||
}
|
||||
|
||||
class _CancelRunActionState extends State<CancelRunAction> {
|
||||
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 = cancelRunId(widget.run);
|
||||
if (id == null || !canCancelRun(widget.run) || _dialogOpen) return;
|
||||
_dialogOpen = true;
|
||||
try {
|
||||
await showCancelRunPrompt(
|
||||
context: context,
|
||||
runId: id,
|
||||
cupertino: _usesCupertino(context),
|
||||
onSubmit: () => _submit(id),
|
||||
);
|
||||
} finally {
|
||||
_dialogOpen = false;
|
||||
if (mounted) setState(() {});
|
||||
}
|
||||
}
|
||||
|
||||
Future<ActionRefusal?> _submit(num id) async {
|
||||
final repository = RunsRepository(widget.gateway);
|
||||
try {
|
||||
final run = await repository.cancelRun(id);
|
||||
if (!mounted) return null;
|
||||
if (_owns(id)) widget.onRunChanged(run);
|
||||
return null;
|
||||
} catch (error) {
|
||||
return ActionRefusal(
|
||||
describeCancelError(error),
|
||||
stillPossible: _resyncRun(id),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
bool _owns(num id) => mounted && cancelRunId(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 canCancelRun(run);
|
||||
} catch (_) {
|
||||
// Unknown server truth: keep the refusal and leave a deliberate retry.
|
||||
return null;
|
||||
} finally {
|
||||
_resync = null;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (cancelRunId(widget.run) == null || !canCancelRun(widget.run)) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
if (_usesCupertino(context)) {
|
||||
return CupertinoButton.filled(
|
||||
key: cancelActionKey,
|
||||
onPressed: _open,
|
||||
child: const Text(cancelActionLabel),
|
||||
);
|
||||
}
|
||||
return FilledButton(
|
||||
key: cancelActionKey,
|
||||
onPressed: _open,
|
||||
child: const Text(cancelActionLabel),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
/// The browser client's cancel wording, kept verbatim.
|
||||
const cancelActionLabel = 'Cancel run';
|
||||
const cancelDialogMessage = 'This asks the server to stop the active run.';
|
||||
const cancelConfirmLabel = 'Cancel run';
|
||||
const cancelKeepLabel = 'Keep';
|
||||
|
||||
/// Stable test/semantics keys shared by the action and its prompt.
|
||||
const cancelActionKey = ValueKey<String>('cancel-run-action');
|
||||
const cancelKeepKey = ValueKey<String>('cancel-run-keep');
|
||||
const cancelConfirmKey = ValueKey<String>('cancel-run-confirm');
|
||||
const cancelErrorKey = ValueKey<String>('cancel-run-error');
|
||||
|
||||
/// The cancel dialog's title: `Cancel run {id}?`.
|
||||
String cancelDialogTitle(num runId) => 'Cancel run $runId?';
|
||||
|
||||
/// The server's refusal, verbatim. Only a blank error gets a generic sentence
|
||||
/// so the prompt never claims a cancellation that did not happen.
|
||||
String describeCancelError(Object error) {
|
||||
final message = '$error'.trim();
|
||||
return message.isEmpty ? 'The server did not cancel the run.' : message;
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../data/runs_repository.dart';
|
||||
import '../domain/run_decisions.dart';
|
||||
import '../domain/run_models.dart';
|
||||
import 'action_refusal.dart';
|
||||
import 'decision_dialog.dart';
|
||||
import 'decision_wording.dart';
|
||||
|
||||
/// The run detail's deliberate human-decision entry point.
|
||||
///
|
||||
/// Renders one native button only while [run] is genuinely waiting on a person.
|
||||
/// Nothing is sent until the operator opens the prompt, chooses an option and
|
||||
/// presses Confirm; cancel, selection and optional feedback stay local. A
|
||||
/// server refusal is shown verbatim in the prompt immediately, the draft is
|
||||
/// preserved and the run is re-read separately so [onRunChanged] still receives
|
||||
/// server truth without locking the prompt while that read is pending.
|
||||
class HumanDecisionAction extends StatefulWidget {
|
||||
const HumanDecisionAction({
|
||||
super.key,
|
||||
required this.run,
|
||||
required this.gateway,
|
||||
required this.onRunChanged,
|
||||
this.cupertino,
|
||||
});
|
||||
|
||||
final JsonMap run;
|
||||
final ApiGateway gateway;
|
||||
final ValueChanged<JsonMap> onRunChanged;
|
||||
|
||||
/// Overrides the platform style; by default it follows the enclosing app.
|
||||
final bool? cupertino;
|
||||
|
||||
@override
|
||||
State<HumanDecisionAction> createState() => _HumanDecisionActionState();
|
||||
}
|
||||
|
||||
class _HumanDecisionActionState extends State<HumanDecisionAction> {
|
||||
PendingDecision? _pending;
|
||||
bool _dialogOpen = false;
|
||||
bool _sending = false;
|
||||
Future<bool?>? _resync;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_pending = pendingDecision(widget.run);
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant HumanDecisionAction oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
_pending = pendingDecision(widget.run);
|
||||
}
|
||||
|
||||
bool _usesCupertino(BuildContext context) {
|
||||
if (widget.cupertino != null) return widget.cupertino!;
|
||||
final material = Localizations.of<MaterialLocalizations>(
|
||||
context,
|
||||
MaterialLocalizations,
|
||||
);
|
||||
return material == null;
|
||||
}
|
||||
|
||||
Future<void> _open() async {
|
||||
final decision = _pending;
|
||||
if (decision == null || _dialogOpen) return;
|
||||
_dialogOpen = true;
|
||||
try {
|
||||
await showHumanDecisionPrompt(
|
||||
context: context,
|
||||
decision: decision,
|
||||
cupertino: _usesCupertino(context),
|
||||
onSubmit: (draft) => _submit(decision, draft),
|
||||
);
|
||||
} finally {
|
||||
_dialogOpen = false;
|
||||
if (mounted) setState(() {});
|
||||
}
|
||||
}
|
||||
|
||||
Future<ActionRefusal?> _submit(
|
||||
PendingDecision decision,
|
||||
DecisionDraft draft,
|
||||
) async {
|
||||
final option = draft.selected?.trim() ?? '';
|
||||
if (option.isEmpty) return const ActionRefusal(actionOptionRequired);
|
||||
if (_sending) return const ActionRefusal(actionAlreadySending);
|
||||
_sending = true;
|
||||
final repository = RunsRepository(widget.gateway);
|
||||
try {
|
||||
final JsonMap run;
|
||||
try {
|
||||
run = await repository.decideRun(
|
||||
decision.runId,
|
||||
stage: decision.stageKey,
|
||||
option: option,
|
||||
feedback: draft.feedback,
|
||||
);
|
||||
} catch (error) {
|
||||
return ActionRefusal(
|
||||
_describe(error),
|
||||
stillPossible: _resyncRun(decision),
|
||||
);
|
||||
}
|
||||
if (!mounted) return null;
|
||||
if (_owns(decision.runId)) {
|
||||
setState(() => _pending = pendingDecision(run));
|
||||
widget.onRunChanged(run);
|
||||
}
|
||||
return null;
|
||||
} finally {
|
||||
_sending = false;
|
||||
}
|
||||
}
|
||||
|
||||
bool _owns(num id) => mounted && widget.run['id'] == 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(PendingDecision decision) {
|
||||
return _resync ??= _readRun(decision);
|
||||
}
|
||||
|
||||
Future<bool?> _readRun(PendingDecision expected) async {
|
||||
try {
|
||||
final run = await RunsRepository(widget.gateway).getRun(expected.runId);
|
||||
if (!_owns(expected.runId)) return null;
|
||||
final next = pendingDecision(run);
|
||||
setState(() => _pending = next);
|
||||
widget.onRunChanged(run);
|
||||
return _stillDecidable(next, expected);
|
||||
} catch (_) {
|
||||
// Unknown server truth: keep the refusal and leave a deliberate retry.
|
||||
return null;
|
||||
} finally {
|
||||
_resync = null;
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the refreshed run offers the same decision the prompt is showing.
|
||||
bool _stillDecidable(PendingDecision? next, PendingDecision expected) {
|
||||
if (next == null ||
|
||||
next.runId != expected.runId ||
|
||||
next.stageKey != expected.stageKey) {
|
||||
return false;
|
||||
}
|
||||
final keys = next.options.map((option) => option.key).toSet();
|
||||
return expected.options.every((option) => keys.contains(option.key));
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final decision = _pending;
|
||||
if (decision == null) return const SizedBox.shrink();
|
||||
if (_usesCupertino(context)) {
|
||||
return CupertinoButton.filled(
|
||||
key: decisionActionKey,
|
||||
onPressed: _open,
|
||||
child: const Text(decisionActionLabel),
|
||||
);
|
||||
}
|
||||
return FilledButton(
|
||||
key: decisionActionKey,
|
||||
onPressed: _open,
|
||||
child: const Text(decisionActionLabel),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _describe(Object error) {
|
||||
final message = '$error';
|
||||
return message.trim().isEmpty ? 'The server refused the decision.' : message;
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../domain/run_decisions.dart';
|
||||
import '../domain/run_models.dart';
|
||||
import 'action_refusal.dart';
|
||||
import 'decision_wording.dart';
|
||||
|
||||
/// Sends the draft to the server. Returns null on success, or an
|
||||
/// [ActionRefusal] with the server's words verbatim; the prompt stays open
|
||||
/// with the draft intact and dismissal available immediately.
|
||||
typedef DecisionSubmit = Future<ActionRefusal?> Function(DecisionDraft draft);
|
||||
|
||||
/// Opens the native decision prompt for [decision].
|
||||
Future<void> showHumanDecisionPrompt({
|
||||
required BuildContext context,
|
||||
required PendingDecision decision,
|
||||
required bool cupertino,
|
||||
required DecisionSubmit onSubmit,
|
||||
}) {
|
||||
final prompt = _DecisionPrompt(
|
||||
decision: decision,
|
||||
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 _DecisionPrompt extends StatefulWidget {
|
||||
const _DecisionPrompt({
|
||||
required this.decision,
|
||||
required this.cupertino,
|
||||
required this.onSubmit,
|
||||
});
|
||||
|
||||
final PendingDecision decision;
|
||||
final bool cupertino;
|
||||
final DecisionSubmit onSubmit;
|
||||
|
||||
@override
|
||||
State<_DecisionPrompt> createState() => _DecisionPromptState();
|
||||
}
|
||||
|
||||
class _DecisionPromptState extends State<_DecisionPrompt> {
|
||||
DecisionDraft _draft = const DecisionDraft();
|
||||
late final TextEditingController _feedback = TextEditingController();
|
||||
bool _sending = false;
|
||||
bool _checking = false;
|
||||
bool _blocked = false;
|
||||
String? _error;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_feedback.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _select(String option) {
|
||||
if (_sending) return;
|
||||
setState(() => _draft = _draft.select(option));
|
||||
}
|
||||
|
||||
void _feedbackChanged(String value) => _draft = _draft.withFeedback(value);
|
||||
|
||||
void _cancel() {
|
||||
if (!_sending) Navigator.of(context).pop();
|
||||
}
|
||||
|
||||
Future<void> _confirm() async {
|
||||
if (_sending || _checking || _blocked || !_draft.canSubmit) return;
|
||||
setState(() {
|
||||
_sending = true;
|
||||
_error = null;
|
||||
});
|
||||
final refusal = await widget.onSubmit(_draft);
|
||||
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;
|
||||
|
||||
Widget _material(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return AlertDialog(
|
||||
scrollable: true,
|
||||
title: const Text(decisionWaitingTitle),
|
||||
content: _body(
|
||||
errorStyle: TextStyle(color: theme.colorScheme.error),
|
||||
options: RadioGroup<String>(
|
||||
groupValue: _draft.selected,
|
||||
onChanged: (value) {
|
||||
if (value != null) _select(value);
|
||||
},
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
for (final option in widget.decision.options)
|
||||
RadioListTile<String>(
|
||||
value: option.key,
|
||||
enabled: !_sending,
|
||||
title: Text(option.key),
|
||||
subtitle: _target(option),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
feedback: TextField(
|
||||
key: decisionFeedbackKey,
|
||||
controller: _feedback,
|
||||
enabled: !_sending,
|
||||
decoration: const InputDecoration(labelText: decisionFeedbackLabel),
|
||||
textInputAction: TextInputAction.done,
|
||||
onChanged: _feedbackChanged,
|
||||
onSubmitted: (_) => _confirm(),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: _sending ? null : _cancel,
|
||||
child: const Text(decisionCancelLabel),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: _confirmDisabled || !_draft.canSubmit ? null : _confirm,
|
||||
child: Text(_sending ? decisionSendingLabel : decisionConfirmLabel),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _cupertino(BuildContext context) {
|
||||
return CupertinoAlertDialog(
|
||||
title: const Text(decisionWaitingTitle),
|
||||
content: _body(
|
||||
errorStyle: TextStyle(
|
||||
color: CupertinoColors.systemRed.resolveFrom(context),
|
||||
),
|
||||
options: RadioGroup<String>(
|
||||
groupValue: _draft.selected,
|
||||
onChanged: (value) {
|
||||
if (value != null) _select(value);
|
||||
},
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
for (final option in widget.decision.options)
|
||||
CupertinoButton(
|
||||
onPressed: _sending ? null : () => _select(option.key),
|
||||
child: Row(
|
||||
children: [
|
||||
CupertinoRadio<String>(
|
||||
value: option.key,
|
||||
useCheckmarkStyle: true,
|
||||
enabled: !_sending,
|
||||
),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(option.key),
|
||||
if (_targetText(option) case final target?)
|
||||
Text(target),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
feedback: CupertinoTextField(
|
||||
key: decisionFeedbackKey,
|
||||
controller: _feedback,
|
||||
enabled: !_sending,
|
||||
placeholder: decisionFeedbackLabel,
|
||||
textInputAction: TextInputAction.done,
|
||||
onChanged: _feedbackChanged,
|
||||
onSubmitted: (_) => _confirm(),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
CupertinoDialogAction(
|
||||
onPressed: _sending ? null : _cancel,
|
||||
child: const Text(decisionCancelLabel),
|
||||
),
|
||||
CupertinoDialogAction(
|
||||
isDefaultAction: true,
|
||||
onPressed: _confirmDisabled || !_draft.canSubmit ? null : _confirm,
|
||||
child: Text(_sending ? decisionSendingLabel : decisionConfirmLabel),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _body({
|
||||
required TextStyle errorStyle,
|
||||
required Widget options,
|
||||
required Widget feedback,
|
||||
}) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(decisionMeta(widget.decision)),
|
||||
if (widget.decision.instructions.trim().isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Text(widget.decision.instructions),
|
||||
),
|
||||
Padding(padding: const EdgeInsets.only(top: 8), child: options),
|
||||
Padding(padding: const EdgeInsets.only(top: 8), child: feedback),
|
||||
if (_error case final error?)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Text(error, key: decisionErrorKey, style: errorStyle),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget? _target(DecisionOption option) {
|
||||
final text = _targetText(option);
|
||||
return text == null ? null : Text(text);
|
||||
}
|
||||
|
||||
String? _targetText(DecisionOption option) {
|
||||
final text = decisionTargetText(option.target);
|
||||
return text.isEmpty ? null : text;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
import '../domain/run_decisions.dart';
|
||||
|
||||
/// The browser client's decision wording, kept verbatim.
|
||||
const decisionWaitingTitle = 'Waiting for your decision';
|
||||
const decisionActionLabel = 'Decide';
|
||||
const decisionFeedbackLabel = 'Feedback (optional)';
|
||||
const decisionCancelLabel = 'Cancel';
|
||||
const decisionConfirmLabel = 'Confirm decision';
|
||||
const decisionSendingLabel = 'Sending…';
|
||||
|
||||
/// Stable test/semantics keys shared by the action and its prompt.
|
||||
const decisionActionKey = ValueKey<String>('human-decision-action');
|
||||
const decisionFeedbackKey = ValueKey<String>('human-decision-feedback');
|
||||
const decisionErrorKey = ValueKey<String>('human-decision-error');
|
||||
|
||||
/// `{stage} · run {id} · {label}`, as the web decision card shows it.
|
||||
String decisionMeta(PendingDecision decision) =>
|
||||
'${decision.stageKey} · run ${decision.runId} · ${decision.runLabel}';
|
||||
|
||||
/// The option's target line, `→ {target}`, or "" when no target was declared.
|
||||
String decisionTargetText(String target) =>
|
||||
target.trim().isEmpty ? '' : '→ $target';
|
||||
@@ -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,109 @@
|
||||
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 'title_dialog.dart';
|
||||
import 'title_wording.dart';
|
||||
|
||||
/// The run detail's rename entry point, mirroring the browser's rename row.
|
||||
///
|
||||
/// The prompt starts with [run]'s stored title exactly as the server sent it
|
||||
/// (never a prompt or output fallback). Typing and Cancel send nothing; only
|
||||
/// Save sends `set_run_title` with the exact run id and title text. A refusal is
|
||||
/// returned verbatim to the kept-open prompt, and only the server's returned
|
||||
/// `run_detail` is delivered through [onRunChanged], once.
|
||||
class RunTitleAction extends StatefulWidget {
|
||||
const RunTitleAction({
|
||||
super.key,
|
||||
required this.run,
|
||||
required this.gateway,
|
||||
required this.onRunChanged,
|
||||
});
|
||||
|
||||
final JsonMap run;
|
||||
final ApiGateway gateway;
|
||||
final ValueChanged<JsonMap> onRunChanged;
|
||||
|
||||
@override
|
||||
State<RunTitleAction> createState() => _RunTitleActionState();
|
||||
}
|
||||
|
||||
class _RunTitleActionState extends State<RunTitleAction> {
|
||||
bool _dialogOpen = false;
|
||||
bool _saving = false;
|
||||
|
||||
bool _usesCupertino(BuildContext context) {
|
||||
final material = Localizations.of<MaterialLocalizations>(
|
||||
context,
|
||||
MaterialLocalizations,
|
||||
);
|
||||
return material == null;
|
||||
}
|
||||
|
||||
Future<void> _open() async {
|
||||
final id = runTitleId(widget.run);
|
||||
if (id == null || _dialogOpen) return;
|
||||
_dialogOpen = true;
|
||||
try {
|
||||
await showRunTitlePrompt(
|
||||
context: context,
|
||||
runId: id,
|
||||
initialTitle: storedRunTitle(widget.run),
|
||||
cupertino: _usesCupertino(context),
|
||||
onSubmit: (title) => _submit(id, title),
|
||||
);
|
||||
} finally {
|
||||
_dialogOpen = false;
|
||||
if (mounted) setState(() {});
|
||||
}
|
||||
}
|
||||
|
||||
Future<ActionRefusal?> _submit(num id, String title) async {
|
||||
if (_saving) return const ActionRefusal(actionAlreadySending);
|
||||
_saving = true;
|
||||
try {
|
||||
final run = await RunsRepository(widget.gateway).setRunTitle(id, title);
|
||||
if (!mounted) return null;
|
||||
if (_owns(id)) widget.onRunChanged(run);
|
||||
return null;
|
||||
} catch (error) {
|
||||
return ActionRefusal(describeTitleError(error));
|
||||
} finally {
|
||||
_saving = false;
|
||||
}
|
||||
}
|
||||
|
||||
bool _owns(num id) => mounted && runTitleId(widget.run) == id;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (runTitleId(widget.run) == null) return const SizedBox.shrink();
|
||||
if (_usesCupertino(context)) {
|
||||
return CupertinoButton(
|
||||
key: runTitleActionKey,
|
||||
onPressed: _open,
|
||||
child: const Text(runTitleActionLabel),
|
||||
);
|
||||
}
|
||||
return OutlinedButton(
|
||||
key: runTitleActionKey,
|
||||
onPressed: _open,
|
||||
child: const Text(runTitleActionLabel),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// The run id used by the rename request, or null for a malformed run.
|
||||
num? runTitleId(JsonMap run) {
|
||||
final id = run['id'];
|
||||
return id is num ? id : null;
|
||||
}
|
||||
|
||||
/// The run's stored title exactly as the browser reads it
|
||||
/// (`String(d.title ?? "")`); never inferred from the prompt or output.
|
||||
String storedRunTitle(JsonMap run) {
|
||||
final title = run['title'];
|
||||
return title == null ? '' : '$title';
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
import 'package:flutter/cupertino.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import 'action_refusal.dart';
|
||||
import 'title_wording.dart';
|
||||
|
||||
/// Sends the typed title. Returns null once the server has accepted it, or an
|
||||
/// [ActionRefusal] carrying the server's words verbatim; the prompt then stays
|
||||
/// open with the typed title intact.
|
||||
typedef TitleSubmit = Future<ActionRefusal?> Function(String title);
|
||||
|
||||
/// Opens the native rename prompt for [runId], seeded with the run's stored
|
||||
/// [initialTitle].
|
||||
///
|
||||
/// Typing and the dismiss action send nothing; only Save sends the title. The
|
||||
/// title is passed through exactly as typed, including surrounding whitespace,
|
||||
/// matching `setRunTitle` in `web/src/repository.js`; the server decides whether
|
||||
/// a blank title is acceptable.
|
||||
Future<void> showRunTitlePrompt({
|
||||
required BuildContext context,
|
||||
required num runId,
|
||||
required String initialTitle,
|
||||
required bool cupertino,
|
||||
required TitleSubmit onSubmit,
|
||||
}) {
|
||||
final prompt = _TitlePrompt(
|
||||
runId: runId,
|
||||
initialTitle: initialTitle,
|
||||
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 _TitlePrompt extends StatefulWidget {
|
||||
const _TitlePrompt({
|
||||
required this.runId,
|
||||
required this.initialTitle,
|
||||
required this.cupertino,
|
||||
required this.onSubmit,
|
||||
});
|
||||
|
||||
final num runId;
|
||||
final String initialTitle;
|
||||
final bool cupertino;
|
||||
final TitleSubmit onSubmit;
|
||||
|
||||
@override
|
||||
State<_TitlePrompt> createState() => _TitlePromptState();
|
||||
}
|
||||
|
||||
class _TitlePromptState extends State<_TitlePrompt> {
|
||||
late final TextEditingController _title = TextEditingController(
|
||||
text: widget.initialTitle,
|
||||
);
|
||||
bool _sending = false;
|
||||
String? _error;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_title.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _cancel() {
|
||||
if (!_sending) Navigator.of(context).pop();
|
||||
}
|
||||
|
||||
Future<void> _save() async {
|
||||
if (_sending) return;
|
||||
setState(() {
|
||||
_sending = true;
|
||||
_error = null;
|
||||
});
|
||||
final refusal = await widget.onSubmit(_title.text);
|
||||
if (!mounted) return;
|
||||
if (refusal == null) {
|
||||
Navigator.of(context).pop();
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_sending = false;
|
||||
_error = refusal.message;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final dialog = widget.cupertino ? _cupertino(context) : _material(context);
|
||||
return PopScope(canPop: !_sending, child: dialog);
|
||||
}
|
||||
|
||||
Widget _material(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
return AlertDialog(
|
||||
scrollable: true,
|
||||
title: const Text(runTitleDialogTitle),
|
||||
content: _body(
|
||||
field: TextField(
|
||||
key: runTitleFieldKey,
|
||||
controller: _title,
|
||||
enabled: !_sending,
|
||||
autofocus: true,
|
||||
decoration: const InputDecoration(labelText: runTitleFieldLabel),
|
||||
textInputAction: TextInputAction.done,
|
||||
onSubmitted: (_) => _save(),
|
||||
),
|
||||
errorStyle: TextStyle(color: theme.colorScheme.error),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
key: runTitleCancelKey,
|
||||
onPressed: _sending ? null : _cancel,
|
||||
child: const Text(runTitleCancelLabel),
|
||||
),
|
||||
FilledButton(
|
||||
key: runTitleSaveKey,
|
||||
onPressed: _sending ? null : _save,
|
||||
child: const Text(runTitleSaveLabel),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _cupertino(BuildContext context) {
|
||||
return CupertinoAlertDialog(
|
||||
title: const Text(runTitleDialogTitle),
|
||||
content: _body(
|
||||
field: CupertinoTextField(
|
||||
key: runTitleFieldKey,
|
||||
controller: _title,
|
||||
enabled: !_sending,
|
||||
autofocus: true,
|
||||
placeholder: runTitleFieldLabel,
|
||||
textInputAction: TextInputAction.done,
|
||||
onSubmitted: (_) => _save(),
|
||||
),
|
||||
errorStyle: TextStyle(
|
||||
color: CupertinoColors.systemRed.resolveFrom(context),
|
||||
),
|
||||
),
|
||||
actions: [
|
||||
CupertinoDialogAction(
|
||||
key: runTitleCancelKey,
|
||||
onPressed: _sending ? null : _cancel,
|
||||
child: const Text(runTitleCancelLabel),
|
||||
),
|
||||
CupertinoDialogAction(
|
||||
key: runTitleSaveKey,
|
||||
isDefaultAction: true,
|
||||
onPressed: _sending ? null : _save,
|
||||
child: const Text(runTitleSaveLabel),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _body({required Widget field, required TextStyle errorStyle}) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
field,
|
||||
if (_error case final error?)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 8),
|
||||
child: Text(error, key: runTitleErrorKey, style: errorStyle),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import 'package:flutter/widgets.dart';
|
||||
|
||||
/// The browser client's rename wording, kept verbatim.
|
||||
const runTitleActionLabel = 'Rename';
|
||||
const runTitleDialogTitle = 'Rename';
|
||||
const runTitleFieldLabel = 'Run title';
|
||||
const runTitleSaveLabel = 'Save';
|
||||
const runTitleCancelLabel = 'Cancel';
|
||||
|
||||
/// Stable test/semantics keys shared by the action and its prompt.
|
||||
const runTitleActionKey = ValueKey<String>('rename-run-action');
|
||||
const runTitleFieldKey = ValueKey<String>('rename-run-field');
|
||||
const runTitleSaveKey = ValueKey<String>('rename-run-save');
|
||||
const runTitleCancelKey = ValueKey<String>('rename-run-cancel');
|
||||
const runTitleErrorKey = ValueKey<String>('rename-run-error');
|
||||
|
||||
/// The server's refusal, verbatim. Only a blank error gets a generic sentence
|
||||
/// so the prompt never claims a rename that did not happen.
|
||||
String describeTitleError(Object error) {
|
||||
final message = '$error';
|
||||
return message.trim().isEmpty
|
||||
? 'The server did not rename the run.'
|
||||
: message;
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../domain/saved_schedule.dart';
|
||||
import '../domain/schedule_json.dart';
|
||||
|
||||
/// Client-side protocol failure. Server refusals and transport errors are not
|
||||
/// wrapped: [ApiGateway] already surfaces their exact text.
|
||||
class SchedulesRepositoryException implements Exception {
|
||||
const SchedulesRepositoryException(this.message);
|
||||
final String message;
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
/// The saved-schedule commands of the current web client.
|
||||
///
|
||||
/// These are run configurations, not pipeline definitions: this repository
|
||||
/// never submits, validates or publishes a workflow, and it never starts or
|
||||
/// polls a run. Timer execution belongs to the server.
|
||||
class SchedulesRepository {
|
||||
SchedulesRepository(this._gateway);
|
||||
|
||||
final ApiGateway _gateway;
|
||||
|
||||
/// Lists saved schedules, optionally for one pipeline.
|
||||
///
|
||||
/// An explicit empty reply is a valid empty list. A reply without the
|
||||
/// `schedules` type is not: that is an older/unsupported server and must be
|
||||
/// reported rather than shown as "no schedules".
|
||||
Future<List<SavedSchedule>> listSchedules({int? pipelineId}) async {
|
||||
final fields = <String, dynamic>{};
|
||||
if (pipelineId != null) {
|
||||
if (!_isPositiveId(pipelineId)) {
|
||||
throw const SchedulesRepositoryException(
|
||||
'A positive pipeline ID is required.',
|
||||
);
|
||||
}
|
||||
fields['pipeline_id'] = pipelineId;
|
||||
}
|
||||
final reply = await _gateway.call('list_schedules', fields);
|
||||
final schedules = reply['schedules'];
|
||||
if (reply['type'] != 'schedules' ||
|
||||
(schedules != null && schedules is! List)) {
|
||||
throw const SchedulesRepositoryException(
|
||||
'The server returned no schedules response.',
|
||||
);
|
||||
}
|
||||
if (schedules == null) return const [];
|
||||
return [
|
||||
for (final item in schedules as List)
|
||||
if (item is Map)
|
||||
SavedSchedule(Map<String, dynamic>.from(item))
|
||||
else
|
||||
throw const SchedulesRepositoryException(
|
||||
'The server returned an invalid schedule record.',
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
/// Creates or updates one saved schedule.
|
||||
///
|
||||
/// Creation sends the web client's sentinel record (`id` 0, no revision) and
|
||||
/// may carry a stable request key so a lost reply is retried instead of
|
||||
/// creating a duplicate. Updating sends the record read from the server,
|
||||
/// whose `revision` is the compare-and-swap token; the key is omitted, as in
|
||||
/// the web client. A stale revision is refused by the server and propagated
|
||||
/// unchanged, never overwritten locally.
|
||||
Future<SavedSchedule> saveSchedule(
|
||||
JsonMap schedule, {
|
||||
String? requestKey,
|
||||
}) async {
|
||||
if (requestKey != null && requestKey.length > 128) {
|
||||
throw const SchedulesRepositoryException(
|
||||
'Schedule request keys must be strings of at most 128 characters.',
|
||||
);
|
||||
}
|
||||
final fields = <String, dynamic>{'schedule': cloneJsonMap(schedule)};
|
||||
if (requestKey != null && requestKey.isNotEmpty) {
|
||||
fields['request_key'] = requestKey;
|
||||
}
|
||||
final reply = await _gateway.call('save_schedule', fields);
|
||||
final saved = reply['schedule'];
|
||||
if (saved is! Map) {
|
||||
throw const SchedulesRepositoryException(
|
||||
'The server returned no saved schedule.',
|
||||
);
|
||||
}
|
||||
return SavedSchedule(Map<String, dynamic>.from(saved));
|
||||
}
|
||||
|
||||
/// Deletes exactly the revision the caller read.
|
||||
///
|
||||
/// Both identity and revision are required before any request is sent; a
|
||||
/// confirmation for a different schedule is treated as a failed delete.
|
||||
Future<void> deleteSchedule(int id, int revision) async {
|
||||
if (!_isPositiveId(id) || !_isPositiveId(revision)) {
|
||||
throw const SchedulesRepositoryException(
|
||||
'An exact schedule ID and revision are required.',
|
||||
);
|
||||
}
|
||||
final reply = await _gateway.call('delete_schedule', {
|
||||
'schedule_id': id,
|
||||
'expected_revision': revision,
|
||||
});
|
||||
if (reply['type'] != 'schedule_deleted' || reply['schedule_id'] != id) {
|
||||
throw const SchedulesRepositoryException(
|
||||
'The server did not confirm deletion of this schedule.',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// JSON/JavaScript integers are safe up to 2^53-1; the web client checks
|
||||
/// `Number.isSafeInteger` before sending an identity.
|
||||
const _maxSafeInteger = 9007199254740991;
|
||||
|
||||
bool _isPositiveId(int value) => value > 0 && value <= _maxSafeInteger;
|
||||
@@ -0,0 +1,87 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'schedule_json.dart';
|
||||
import 'schedule_rule.dart';
|
||||
|
||||
/// One saved run configuration from `list_schedules` or `save_schedule`.
|
||||
///
|
||||
/// A saved schedule is a complete run request pinned to one pipeline version.
|
||||
/// It is deliberately not a pipeline definition: nothing here is published,
|
||||
/// validated as a graph or treated as the pipeline's current version.
|
||||
///
|
||||
/// [raw] keeps the exact server record, including fields this client does not
|
||||
/// know yet. Typed getters are views; they never rewrite [raw].
|
||||
class SavedSchedule {
|
||||
SavedSchedule(JsonMap raw) : raw = cloneJsonMap(raw);
|
||||
|
||||
final JsonMap raw;
|
||||
|
||||
/// Server identity; null when an older reply omits it. Never defaulted to 0,
|
||||
/// because 0 is the create sentinel rather than a saved identity.
|
||||
int? get id => _integer(raw['id']);
|
||||
|
||||
/// Compare-and-swap token. Updates reuse it and deletes send it as
|
||||
/// `expected_revision`; this client never invents or increments it.
|
||||
int? get revision => _integer(raw['revision']);
|
||||
|
||||
int? get pipelineId => _integer(raw['pipeline_id']);
|
||||
int? get version => _integer(raw['version']);
|
||||
String get name => _text(raw['name']);
|
||||
bool get enabled => raw['enabled'] == true;
|
||||
|
||||
JsonMap get input => _map(raw['input']);
|
||||
String get prompt => _text(input['prompt']);
|
||||
String get workspace => _text(raw['workspace']);
|
||||
ScheduleRule get rule => ScheduleRule(_map(raw['rule']));
|
||||
|
||||
List<String> get writePaths => _texts(raw['write_paths']);
|
||||
bool get allowTools => raw['allow_tools'] == true;
|
||||
String get model => _text(raw['model']);
|
||||
Map<String, String> get stageModels => {
|
||||
for (final entry in _map(raw['stage_models']).entries)
|
||||
if (entry.value is String) entry.key: entry.value as String,
|
||||
};
|
||||
String get notifyMode => _text(raw['notify_mode']);
|
||||
String get title => _text(raw['title']);
|
||||
String get outputFormat => _text(raw['output_format']);
|
||||
|
||||
String get nextDue => _text(raw['next_due']);
|
||||
String get createdAt => _text(raw['created_at']);
|
||||
String get updatedAt => _text(raw['updated_at']);
|
||||
|
||||
/// The record to pass to `save_schedule`, deep-copied so callers cannot
|
||||
/// mutate this snapshot by aliasing.
|
||||
JsonMap toJson() => cloneJsonMap(raw);
|
||||
|
||||
/// Pause/enable copy. Identity, revision and every unknown field are kept so
|
||||
/// the update still targets the revision this record was read at.
|
||||
SavedSchedule withEnabled(bool value) {
|
||||
final copy = toJson();
|
||||
copy['enabled'] = value;
|
||||
return SavedSchedule(copy);
|
||||
}
|
||||
}
|
||||
|
||||
int? _integer(dynamic value) {
|
||||
if (value is int) return value;
|
||||
if (value is num && value.isFinite && value == value.truncateToDouble()) {
|
||||
return value.toInt();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
String _text(dynamic value) => value is String ? value : '';
|
||||
|
||||
JsonMap _map(dynamic value) {
|
||||
if (value is! Map) return <String, dynamic>{};
|
||||
return <String, dynamic>{
|
||||
for (final entry in value.entries)
|
||||
'${entry.key}': cloneJsonValue(entry.value),
|
||||
};
|
||||
}
|
||||
|
||||
List<String> _texts(dynamic value) => value is List
|
||||
? [
|
||||
for (final item in value)
|
||||
if (item is String) item,
|
||||
]
|
||||
: const [];
|
||||
@@ -0,0 +1,22 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
/// Deep copy of a decoded JSON value.
|
||||
///
|
||||
/// Saved schedules travel back to the server unchanged, so unknown fields (and
|
||||
/// unknown nested values) must survive every round trip without sharing state
|
||||
/// with the reply map that produced them.
|
||||
dynamic cloneJsonValue(dynamic value) {
|
||||
if (value is Map) {
|
||||
return <String, dynamic>{
|
||||
for (final entry in value.entries)
|
||||
'${entry.key}': cloneJsonValue(entry.value),
|
||||
};
|
||||
}
|
||||
if (value is List) {
|
||||
return [for (final item in value) cloneJsonValue(item)];
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
JsonMap cloneJsonMap(JsonMap value) =>
|
||||
Map<String, dynamic>.from(cloneJsonValue(value) as Map);
|
||||
@@ -0,0 +1,41 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'schedule_json.dart';
|
||||
|
||||
/// Weekday keys the server accepts for an interval rule.
|
||||
const scheduleDays = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
|
||||
|
||||
/// The timer part of a saved schedule (`rule` on the wire).
|
||||
///
|
||||
/// This is a view over the decoded server record, not a timer implementation:
|
||||
/// it never calculates due times, converts timezones or starts runs. Unknown
|
||||
/// rule fields stay in [raw] and are returned by [toJson].
|
||||
class ScheduleRule {
|
||||
ScheduleRule([JsonMap? raw]) : raw = cloneJsonMap(raw ?? const {});
|
||||
|
||||
final JsonMap raw;
|
||||
|
||||
/// Go-style duration such as `24h` or `1h30m`; empty for a clock rule.
|
||||
String get every => _text(raw['every']);
|
||||
|
||||
/// Distinct 24-hour times such as `09:00`; empty for an interval rule.
|
||||
List<String> get times => _texts(raw['times']);
|
||||
|
||||
/// Empty means every day (written as absent on the wire).
|
||||
List<String> get days => _texts(raw['days']);
|
||||
|
||||
/// Empty or `Local` means the server's timezone.
|
||||
String get timezone => _text(raw['timezone']);
|
||||
|
||||
bool get isClock => times.isNotEmpty;
|
||||
|
||||
JsonMap toJson() => cloneJsonMap(raw);
|
||||
}
|
||||
|
||||
String _text(dynamic value) => value is String ? value : '';
|
||||
|
||||
List<String> _texts(dynamic value) => value is List
|
||||
? [
|
||||
for (final item in value)
|
||||
if (item is String) item,
|
||||
]
|
||||
: const [];
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user