merge(app): land corrected run-state foundation
This commit is contained in:
@@ -0,0 +1,105 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import '../domain/run_models.dart';
|
||||
|
||||
/// Protocol failure kept separate from transport errors; server error envelopes
|
||||
/// are otherwise propagated unchanged by [ApiGateway].
|
||||
class RunsRepositoryException implements Exception {
|
||||
const RunsRepositoryException(this.message);
|
||||
final String message;
|
||||
@override
|
||||
String toString() => message;
|
||||
}
|
||||
|
||||
/// Run protocol requests over the application's shared gateway.
|
||||
class RunsRepository {
|
||||
RunsRepository(this._gateway);
|
||||
final ApiGateway _gateway;
|
||||
|
||||
Future<RunListResult> listRuns() async {
|
||||
final reply = await _gateway.call('list_runs');
|
||||
final runs = reply['runs'];
|
||||
return RunListResult(
|
||||
runs is List
|
||||
? runs
|
||||
.whereType<Map>()
|
||||
.map((r) => Map<String, dynamic>.from(r))
|
||||
.toList()
|
||||
: const [],
|
||||
reply['usage'] is Map
|
||||
? Map<String, dynamic>.from(reply['usage'] as Map)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
Future<JsonMap> getRun(num id) async =>
|
||||
_required(await _gateway.call('get_run', {'run_id': id}), 'run_detail');
|
||||
Future<JsonMap> cancelRun(num id) async => _required(
|
||||
await _gateway.call('cancel_run', {'run_id': id}),
|
||||
'run_detail',
|
||||
);
|
||||
|
||||
Future<JsonMap> retryRun(
|
||||
num id, {
|
||||
required String requestKey,
|
||||
String? mode,
|
||||
}) async {
|
||||
final fields = <String, dynamic>{'run_id': id, 'request_key': requestKey};
|
||||
if (mode == 'restart') fields['retry_mode'] = mode;
|
||||
return _required(await _gateway.call('retry_run', fields), 'run_detail');
|
||||
}
|
||||
|
||||
Future<JsonMap> decideRun(
|
||||
num id, {
|
||||
String? stage,
|
||||
required String option,
|
||||
String feedback = '',
|
||||
}) async {
|
||||
final selected = option.trim();
|
||||
if (selected.isEmpty) {
|
||||
throw const RunsRepositoryException(
|
||||
'Choose an option before continuing.',
|
||||
);
|
||||
}
|
||||
final fields = <String, dynamic>{'run_id': id, 'option': selected};
|
||||
if (stage != null && stage.trim().isNotEmpty) fields['stage'] = stage;
|
||||
if (feedback.trim().isNotEmpty) fields['feedback'] = feedback.trim();
|
||||
return _required(await _gateway.call('decide_run', fields), 'run_detail');
|
||||
}
|
||||
|
||||
Future<JsonMap> setRunTitle(num id, String title) async => _required(
|
||||
await _gateway.call('set_run_title', {'run_id': id, 'title': title}),
|
||||
'run_detail',
|
||||
);
|
||||
|
||||
Future<JsonMap> startRun({
|
||||
required num pipelineId,
|
||||
required num version,
|
||||
required String prompt,
|
||||
required String workspace,
|
||||
required String requestKey,
|
||||
String title = '',
|
||||
String outputFormat = '',
|
||||
String notifyMode = 'auto',
|
||||
}) async {
|
||||
final fields = <String, dynamic>{
|
||||
'pipeline_id': pipelineId,
|
||||
'version': version,
|
||||
'request_key': requestKey,
|
||||
'workspace': workspace.trim(),
|
||||
'input': {'prompt': prompt},
|
||||
};
|
||||
if (title.trim().isNotEmpty) fields['title'] = title.trim();
|
||||
if (outputFormat.isNotEmpty) fields['output_format'] = outputFormat;
|
||||
final mode = notifyMode.trim().toLowerCase();
|
||||
if (mode == 'on' || mode == 'off') fields['notify_mode'] = mode;
|
||||
return _required(await _gateway.call('run_pipeline', fields), 'run_detail');
|
||||
}
|
||||
|
||||
JsonMap _required(JsonMap reply, String key) {
|
||||
final value = reply[key];
|
||||
if (value is! Map) {
|
||||
throw RunsRepositoryException('The server returned no $key.');
|
||||
}
|
||||
return Map<String, dynamic>.from(value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'run_models.dart';
|
||||
|
||||
class PendingDecision {
|
||||
const PendingDecision({
|
||||
required this.runId,
|
||||
required this.runLabel,
|
||||
required this.stageKey,
|
||||
required this.instructions,
|
||||
required this.options,
|
||||
});
|
||||
final num runId;
|
||||
final String runLabel;
|
||||
final String stageKey;
|
||||
final String instructions;
|
||||
final List<DecisionOption> options;
|
||||
}
|
||||
|
||||
JsonMap? lastWaitingStep(List<dynamic> steps) {
|
||||
for (final value in steps.reversed) {
|
||||
if (value is Map && value['status'] == 'waiting') {
|
||||
return Map<String, dynamic>.from(value);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
String waitingPrompt(dynamic output) =>
|
||||
output is Map && output['prompt'] is String
|
||||
? output['prompt'] as String
|
||||
: '';
|
||||
|
||||
List<String> waitingOptions(dynamic output) {
|
||||
final options = output is Map ? output['options'] : null;
|
||||
if (options is! List) return const [];
|
||||
return options
|
||||
.whereType<String>()
|
||||
.where((entry) => entry.trim().isNotEmpty)
|
||||
.toList();
|
||||
}
|
||||
|
||||
List<String> humanOptions(dynamic edges) {
|
||||
if (edges is! Map) return const [];
|
||||
return edges.keys.map((key) => '$key').where((key) => key != 'error').toList()
|
||||
..sort();
|
||||
}
|
||||
|
||||
PendingDecision? pendingDecision(JsonMap? run) {
|
||||
if (run == null ||
|
||||
run['status'] != 'waiting' ||
|
||||
_positive(run['export_pending_sequence'])) {
|
||||
return null;
|
||||
}
|
||||
final steps = run['steps'] is List ? run['steps'] as List : const [];
|
||||
final step = lastWaitingStep(steps);
|
||||
final stage = _string(step?['stage']).trim().isNotEmpty
|
||||
? _string(step?['stage'])
|
||||
: _string(run['current_stage']);
|
||||
if (stage.trim().isEmpty) return null;
|
||||
JsonMap? declaration;
|
||||
final graph = run['graph'];
|
||||
final graphStages = graph is Map ? graph['stages'] : null;
|
||||
if (graphStages is List) {
|
||||
for (final value in graphStages.whereType<Map>()) {
|
||||
if (value['key'] == stage) {
|
||||
declaration = Map<String, dynamic>.from(value);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (declaration?['type'] != null && declaration!['type'] != 'human') {
|
||||
return null;
|
||||
}
|
||||
final edges = declaration?['edges'];
|
||||
final options = waitingOptions(step?['output']);
|
||||
final keys = options.isNotEmpty ? options : humanOptions(edges);
|
||||
if (keys.isEmpty) return null;
|
||||
final instructions = waitingPrompt(step?['output']).trim().isNotEmpty
|
||||
? waitingPrompt(step?['output'])
|
||||
: _string(declaration?['prompt']);
|
||||
return PendingDecision(
|
||||
runId: run['id'] is num ? run['id'] as num : 0,
|
||||
runLabel: runIdentity(run['title'], run['name']).label,
|
||||
stageKey: stage,
|
||||
instructions: instructions,
|
||||
options: keys
|
||||
.map(
|
||||
(key) => DecisionOption(
|
||||
key,
|
||||
target: _targetLabel(key, edges is Map ? edges[key] : null),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
String _targetLabel(String option, dynamic target) {
|
||||
if (target == null || '$target'.trim().isEmpty) return '';
|
||||
final resolved = target == '#'
|
||||
? (option == 'error' ? '#failure' : '#success')
|
||||
: '$target';
|
||||
return switch (resolved) {
|
||||
'#success' => 'SUCCESS',
|
||||
'#failure' => 'FAILURE',
|
||||
_ => resolved,
|
||||
};
|
||||
}
|
||||
|
||||
bool _positive(dynamic value) => value is num && value > 0;
|
||||
String _string(dynamic value) => value == null ? '' : '$value';
|
||||
@@ -0,0 +1,226 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
import 'run_step_evidence.dart';
|
||||
|
||||
const terminalRunStatuses = {'succeeded', 'failed', 'canceled', 'interrupted'};
|
||||
|
||||
bool isTerminalRunStatus(dynamic status) =>
|
||||
terminalRunStatuses.contains(_word(status));
|
||||
bool isWaitingRunStatus(dynamic status) => _word(status) == 'waiting';
|
||||
|
||||
int runLifecycleRank(dynamic status) => switch (_word(status)) {
|
||||
'queued' => 0,
|
||||
'running' || 'waiting' => 1,
|
||||
'succeeded' || 'failed' || 'canceled' || 'interrupted' => 2,
|
||||
_ => -1,
|
||||
};
|
||||
|
||||
int stepLifecycleRank(dynamic status) => switch (_word(status)) {
|
||||
'running' || 'waiting' => 1,
|
||||
'completed' || 'failed' || 'canceled' || 'interrupted' => 2,
|
||||
_ => -1,
|
||||
};
|
||||
|
||||
bool _stale(dynamic current, dynamic incoming, int Function(dynamic) rank) {
|
||||
if (_word(incoming).isEmpty) return false;
|
||||
final oldRank = rank(current);
|
||||
final newRank = rank(incoming);
|
||||
return oldRank >= 0 &&
|
||||
newRank >= 0 &&
|
||||
(newRank < oldRank ||
|
||||
(oldRank == 2 && newRank == 2 && incoming != current));
|
||||
}
|
||||
|
||||
String _advance(dynamic current, dynamic incoming, int Function(dynamic) rank) {
|
||||
if (_word(incoming).isEmpty || incoming == current) return '${current ?? ''}';
|
||||
final oldRank = rank(current);
|
||||
final newRank = rank(incoming);
|
||||
if (oldRank < 0) return '$incoming';
|
||||
if (newRank < 0 || (oldRank == 2 && newRank == 2) || newRank < oldRank) {
|
||||
return '${current ?? ''}';
|
||||
}
|
||||
return '$incoming';
|
||||
}
|
||||
|
||||
bool executingFor(dynamic status, bool current) => switch (_word(status)) {
|
||||
'queued' || 'running' => true,
|
||||
'waiting' || 'succeeded' || 'failed' || 'canceled' || 'interrupted' => false,
|
||||
_ => current,
|
||||
};
|
||||
|
||||
bool _blank(dynamic value) => '${value ?? ''}'.trim().isEmpty;
|
||||
|
||||
JsonMap _scheduleOrigin(JsonMap current, JsonMap frame) {
|
||||
final oldId = _positiveInt(current['schedule_id']);
|
||||
final newId = _positiveInt(frame['schedule_id']);
|
||||
final known =
|
||||
current.containsKey('scheduled') ||
|
||||
frame.containsKey('scheduled') ||
|
||||
oldId > 0 ||
|
||||
newId > 0;
|
||||
if (!known) return {};
|
||||
final id = oldId > 0 ? oldId : newId;
|
||||
final nameConflict = oldId > 0 && newId > 0 && oldId != newId;
|
||||
final name =
|
||||
'${current['schedule_name'] ?? (nameConflict ? '' : frame['schedule_name'] ?? '')}';
|
||||
return {
|
||||
'scheduled':
|
||||
current['scheduled'] == true || frame['scheduled'] == true || id > 0,
|
||||
if (id > 0) 'schedule_id': id,
|
||||
if (name.isNotEmpty) 'schedule_name': name,
|
||||
};
|
||||
}
|
||||
|
||||
int _positiveInt(dynamic value) =>
|
||||
value is num && value > 0 ? value.toInt() : 0;
|
||||
|
||||
JsonMap _mergeRunFields(JsonMap current, JsonMap frame) {
|
||||
if (_stale(current['status'], frame['status'], runLifecycleRank) &&
|
||||
frame['resource_wait_set'] != true) {
|
||||
return current;
|
||||
}
|
||||
final beforeStatus = '${current['status'] ?? ''}';
|
||||
final status =
|
||||
frame['resource_wait_set'] == true &&
|
||||
frame['status'] == 'queued' &&
|
||||
!isTerminalRunStatus(beforeStatus)
|
||||
? 'queued'
|
||||
: _advance(beforeStatus, frame['status'], runLifecycleRank);
|
||||
final merged = <String, dynamic>{
|
||||
...current,
|
||||
..._scheduleOrigin(current, frame),
|
||||
'status': status,
|
||||
'executing': executingFor(status, current['executing'] == true),
|
||||
'completed_steps': _maxInt(
|
||||
current['completed_steps'],
|
||||
frame['completed_steps'],
|
||||
),
|
||||
'resource_wait': isTerminalRunStatus(status)
|
||||
? null
|
||||
: frame['resource_wait_set'] == true
|
||||
? frame['resource_wait']
|
||||
: current['resource_wait'],
|
||||
'notify_mode': _blank(frame['notify_mode'])
|
||||
? current['notify_mode'] ?? 'auto'
|
||||
: frame['notify_mode'],
|
||||
'cancel_requested':
|
||||
current['cancel_requested'] == true ||
|
||||
frame['cancel_requested'] == true,
|
||||
'cleanup_unconfirmed':
|
||||
current['cleanup_unconfirmed'] == true ||
|
||||
frame['cleanup_unconfirmed'] == true,
|
||||
};
|
||||
for (final key in ['outcome', 'current_stage', 'created_at', 'finished_at']) {
|
||||
if (!_blank(frame[key])) merged[key] = frame[key];
|
||||
}
|
||||
final oldExport = _positiveInt(current['export_pending_sequence']);
|
||||
if (oldExport > 0 || frame.containsKey('export_pending_sequence')) {
|
||||
merged['export_pending_sequence'] = _blank(frame['status'])
|
||||
? oldExport
|
||||
: status == 'waiting'
|
||||
? _positiveInt(frame['export_pending_sequence'])
|
||||
: 0;
|
||||
}
|
||||
if (current['steps'] is! List) {
|
||||
final evidence = mergeGraphEvidence(
|
||||
current['graph_evidence'] as JsonMap?,
|
||||
frame,
|
||||
);
|
||||
if (evidence != null) merged['graph_evidence'] = evidence;
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
int _maxInt(dynamic a, dynamic b) =>
|
||||
(a is num ? a.toInt() : 0).clamp(b is num ? b.toInt() : 0, 0x7fffffff);
|
||||
|
||||
/// A summary row can be built from a sufficiently identified push; otherwise
|
||||
/// the caller must resync from the server's authoritative list.
|
||||
JsonMap? newRunSummaryFromFrame(JsonMap frame) {
|
||||
final id = frame['run_id'];
|
||||
final pipelineId = frame['pipeline_id'];
|
||||
if (id is! num ||
|
||||
id <= 0 ||
|
||||
pipelineId is! num ||
|
||||
pipelineId <= 0 ||
|
||||
_blank(frame['name'])) {
|
||||
return null;
|
||||
}
|
||||
final row = <String, dynamic>{
|
||||
'id': id,
|
||||
'pipeline_id': pipelineId,
|
||||
'name': frame['name'],
|
||||
'title': _blank(frame['title']) ? null : frame['title'],
|
||||
'version': frame['version'] ?? 0,
|
||||
'notify_mode': frame['notify_mode'] ?? 'auto',
|
||||
'status': frame['status'] ?? '',
|
||||
'executing': executingFor(frame['status'], true),
|
||||
'completed_steps': _maxInt(0, frame['completed_steps']),
|
||||
'created_at': frame['created_at'] ?? '',
|
||||
'finished_at': frame['finished_at'] ?? '',
|
||||
'outcome': frame['outcome'] ?? '',
|
||||
'current_stage': frame['current_stage'] ?? '',
|
||||
'resource_wait': frame['resource_wait'],
|
||||
'cancel_requested': frame['cancel_requested'] == true,
|
||||
'cleanup_unconfirmed': frame['cleanup_unconfirmed'] == true,
|
||||
};
|
||||
row.addAll(_scheduleOrigin({}, frame));
|
||||
final sequence = _positiveInt(frame['export_pending_sequence']);
|
||||
if (sequence > 0) row['export_pending_sequence'] = sequence;
|
||||
final evidence = mergeGraphEvidence(null, frame);
|
||||
if (evidence != null) row['graph_evidence'] = evidence;
|
||||
return row;
|
||||
}
|
||||
|
||||
({List<JsonMap> runs, bool needsResync}) foldRunEvent(
|
||||
List<JsonMap> runs,
|
||||
JsonMap frame,
|
||||
) {
|
||||
final id = frame['run_id'];
|
||||
if (id is! num || id <= 0) return (runs: runs, needsResync: false);
|
||||
final index = runs.indexWhere((run) => run['id'] == id);
|
||||
if (index < 0) {
|
||||
final row = newRunSummaryFromFrame(frame);
|
||||
return row == null
|
||||
? (runs: runs, needsResync: true)
|
||||
: (runs: [row, ...runs], needsResync: false);
|
||||
}
|
||||
final updated = _mergeRunFields(runs[index], frame);
|
||||
if (identical(updated, runs[index])) return (runs: runs, needsResync: false);
|
||||
final next = [...runs];
|
||||
next[index] = updated;
|
||||
return (runs: next, needsResync: false);
|
||||
}
|
||||
|
||||
JsonMap? foldRunEventDetail(JsonMap? detail, JsonMap frame) {
|
||||
if (detail == null || detail['id'] != frame['run_id']) return detail;
|
||||
if (_stale(detail['status'], frame['status'], runLifecycleRank) &&
|
||||
frame['resource_wait_set'] != true) {
|
||||
return detail;
|
||||
}
|
||||
final merged = _mergeRunFields(detail, frame);
|
||||
final steps = frame['step'] is Map
|
||||
? upsertRunStep(
|
||||
detail['steps'] is List
|
||||
? (detail['steps'] as List)
|
||||
.whereType<Map>()
|
||||
.map((s) => Map<String, dynamic>.from(s))
|
||||
.toList()
|
||||
: [],
|
||||
Map<String, dynamic>.from(frame['step'] as Map),
|
||||
)
|
||||
: detail['steps'] ?? [];
|
||||
return {...merged, 'steps': steps};
|
||||
}
|
||||
|
||||
bool runDetailNeedsFullSync(JsonMap frame) {
|
||||
final step = frame['step'];
|
||||
final stepStatus = step is Map ? step['status'] : null;
|
||||
return isTerminalRunStatus(frame['status']) ||
|
||||
isWaitingRunStatus(frame['status']) ||
|
||||
frame['cancel_requested'] == true ||
|
||||
frame['cleanup_unconfirmed'] == true ||
|
||||
isWaitingRunStatus(stepStatus) ||
|
||||
stepLifecycleRank(stepStatus) == 2;
|
||||
}
|
||||
|
||||
String _word(dynamic value) => '${value ?? ''}'.trim().toLowerCase();
|
||||
@@ -0,0 +1,217 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
const runStates = [
|
||||
'queued',
|
||||
'running',
|
||||
'waiting',
|
||||
'succeeded',
|
||||
'failed',
|
||||
'canceled',
|
||||
'interrupted',
|
||||
];
|
||||
|
||||
({String label, String? pipeline}) runIdentity(dynamic title, dynamic name) {
|
||||
final stored = '${title ?? ''}'.trim();
|
||||
return (
|
||||
label: stored.isNotEmpty ? stored : '${name ?? ''}',
|
||||
pipeline: stored.isNotEmpty ? '${name ?? ''}' : null,
|
||||
);
|
||||
}
|
||||
|
||||
String runStateOf(dynamic status) =>
|
||||
switch ('${status ?? ''}'.trim().toLowerCase()) {
|
||||
'queued' ||
|
||||
'running' ||
|
||||
'waiting' ||
|
||||
'active' ||
|
||||
'blocked' ||
|
||||
'skipped' => '${status ?? ''}'.trim().toLowerCase(),
|
||||
'succeeded' || 'success' || 'completed' || 'done' => 'succeeded',
|
||||
'failed' || 'error' => 'failed',
|
||||
'canceled' || 'cancelled' => 'canceled',
|
||||
'interrupted' => 'interrupted',
|
||||
_ => 'unknown',
|
||||
};
|
||||
|
||||
List<JsonMap> filterRuns(
|
||||
List<JsonMap> runs, {
|
||||
Set<String> statuses = const {},
|
||||
int? pipelineId,
|
||||
String timeRange = 'any_time',
|
||||
String scheduled = 'any',
|
||||
DateTime? today,
|
||||
}) => runs.where((run) {
|
||||
if (statuses.isNotEmpty && !statuses.contains(runStateOf(run['status']))) {
|
||||
return false;
|
||||
}
|
||||
if (pipelineId != null && run['pipeline_id'] != pipelineId) {
|
||||
return false;
|
||||
}
|
||||
if (scheduled == 'scheduled' && !_isScheduled(run)) {
|
||||
return false;
|
||||
}
|
||||
if (scheduled == 'unscheduled' &&
|
||||
(run['scheduled'] != false || _isScheduled(run))) {
|
||||
return false;
|
||||
}
|
||||
if (timeRange == 'any_time' || timeRange.isEmpty) {
|
||||
return true;
|
||||
}
|
||||
final created = DateTime.tryParse('${run['created_at'] ?? ''}')?.toLocal();
|
||||
if (created == null) {
|
||||
return false;
|
||||
}
|
||||
final now = today ?? DateTime.now();
|
||||
final start = DateTime(now.year, now.month, now.day);
|
||||
final date = DateTime(created.year, created.month, created.day);
|
||||
if (date.isAfter(start)) {
|
||||
return false;
|
||||
}
|
||||
final days = switch (timeRange) {
|
||||
'today' => 0,
|
||||
'last_7_days' => 6,
|
||||
'last_30_days' => 29,
|
||||
_ => null,
|
||||
};
|
||||
return days == null || !date.isBefore(start.subtract(Duration(days: days)));
|
||||
}).toList();
|
||||
|
||||
bool _isScheduled(JsonMap run) =>
|
||||
run['scheduled'] == true ||
|
||||
(run['schedule_id'] is num && (run['schedule_id'] as num) > 0);
|
||||
|
||||
String runStatusLabel(JsonMap run) {
|
||||
final status = '${run['status'] ?? ''}';
|
||||
if (!{'queued', 'running', 'waiting'}.contains(status)) {
|
||||
return status.isEmpty ? 'unknown' : status;
|
||||
}
|
||||
if (run['cleanup_unconfirmed'] == true) {
|
||||
return 'Cleanup unconfirmed — workspace reserved';
|
||||
}
|
||||
if (run['cancel_requested'] == true) {
|
||||
return 'Stopping — waiting for execution to stop';
|
||||
}
|
||||
if (status == 'waiting' &&
|
||||
(run['export_pending_sequence'] as num? ?? 0) > 0) {
|
||||
return 'Waiting for session export';
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
List<JsonMap> sortRuns(List<JsonMap> runs, {String sort = 'newest_first'}) {
|
||||
final result = [...runs];
|
||||
int? instant(dynamic value) =>
|
||||
DateTime.tryParse('${value ?? ''}')?.millisecondsSinceEpoch;
|
||||
int? duration(JsonMap run) {
|
||||
final from = instant(run['created_at']);
|
||||
final to = instant(run['finished_at']);
|
||||
if (from == null || to == null || to < from) return null;
|
||||
return (to - from) ~/ 1000;
|
||||
}
|
||||
|
||||
int cmp<T extends Comparable<Object>>(T a, T b) => a.compareTo(b);
|
||||
result.sort((a, b) {
|
||||
final at = instant(a['created_at']);
|
||||
final bt = instant(b['created_at']);
|
||||
int primary;
|
||||
switch (sort) {
|
||||
case 'oldest_first':
|
||||
primary = cmp(at ?? 0x7fffffffffffffff, bt ?? 0x7fffffffffffffff);
|
||||
break;
|
||||
case 'longest_duration':
|
||||
primary = cmp(duration(a) == null ? 1 : 0, duration(b) == null ? 1 : 0);
|
||||
if (primary == 0) primary = cmp(duration(b) ?? -1, duration(a) ?? -1);
|
||||
if (primary == 0) {
|
||||
primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff);
|
||||
}
|
||||
break;
|
||||
case 'shortest_duration':
|
||||
primary = cmp(duration(a) == null ? 1 : 0, duration(b) == null ? 1 : 0);
|
||||
if (primary == 0) {
|
||||
primary = cmp(
|
||||
duration(a) ?? 0x7fffffffffffffff,
|
||||
duration(b) ?? 0x7fffffffffffffff,
|
||||
);
|
||||
}
|
||||
if (primary == 0) {
|
||||
primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff);
|
||||
}
|
||||
break;
|
||||
case 'pipeline_name':
|
||||
primary = '${a['name'] ?? ''}'.toLowerCase().compareTo(
|
||||
'${b['name'] ?? ''}'.toLowerCase(),
|
||||
);
|
||||
if (primary == 0) {
|
||||
primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff);
|
||||
}
|
||||
break;
|
||||
case 'status':
|
||||
primary = '${a['status'] ?? ''}'.toLowerCase().compareTo(
|
||||
'${b['status'] ?? ''}'.toLowerCase(),
|
||||
);
|
||||
if (primary == 0) {
|
||||
primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
primary = cmp(bt ?? -0x7fffffffffffffff, at ?? -0x7fffffffffffffff);
|
||||
}
|
||||
return primary == 0
|
||||
? ((b['id'] as num?) ?? 0).compareTo((a['id'] as num?) ?? 0)
|
||||
: primary;
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Null usage means unsupported/unavailable, not zero.
|
||||
class RunListResult {
|
||||
const RunListResult(this.runs, this.usage);
|
||||
final List<JsonMap> runs;
|
||||
final JsonMap? usage;
|
||||
}
|
||||
|
||||
class DecisionOption {
|
||||
const DecisionOption(this.key, {this.target = ''});
|
||||
final String key;
|
||||
final String target;
|
||||
}
|
||||
|
||||
class DecisionDraft {
|
||||
const DecisionDraft({this.selected, this.feedback = ''});
|
||||
final String? selected;
|
||||
final String feedback;
|
||||
bool get canSubmit => selected != null && selected!.trim().isNotEmpty;
|
||||
DecisionDraft select(String option) =>
|
||||
DecisionDraft(selected: option, feedback: feedback);
|
||||
DecisionDraft withFeedback(String value) =>
|
||||
DecisionDraft(selected: selected, feedback: value);
|
||||
}
|
||||
|
||||
String attentionKey(num runId, String kind) => '$runId:$kind';
|
||||
|
||||
List<JsonMap> orderAttention(
|
||||
List<JsonMap> runs, {
|
||||
Set<String> dismissed = const {},
|
||||
}) {
|
||||
final result = runs.where((run) {
|
||||
final waiting = run['status'] == 'waiting';
|
||||
if (waiting && (run['export_pending_sequence'] as num? ?? 0) > 0) {
|
||||
return false;
|
||||
}
|
||||
final kind = waiting ? 'Decision' : 'Failed';
|
||||
return (waiting || run['status'] == 'failed') &&
|
||||
!dismissed.contains(attentionKey(run['id'] as num, kind));
|
||||
}).toList();
|
||||
String recency(JsonMap run) => '${run['finished_at'] ?? ''}'.trim().isNotEmpty
|
||||
? '${run['finished_at']}'
|
||||
: '${run['created_at'] ?? ''}';
|
||||
result.sort((a, b) {
|
||||
final rank = (a['status'] == 'waiting' ? 0 : 1).compareTo(
|
||||
b['status'] == 'waiting' ? 0 : 1,
|
||||
);
|
||||
if (rank != 0) return rank;
|
||||
final date = recency(b).compareTo(recency(a));
|
||||
return date != 0 ? date : (b['id'] as num).compareTo(a['id'] as num);
|
||||
});
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
import '../../../core/api_gateway.dart';
|
||||
|
||||
/// Merge a visit by sequence without allowing stale status or blank sparse
|
||||
/// deltas to erase evidence already held by the detail cache.
|
||||
List<JsonMap> upsertRunStep(List<JsonMap> steps, JsonMap delta) {
|
||||
final sequence = delta['sequence'] is num
|
||||
? (delta['sequence'] as num).toInt()
|
||||
: 0;
|
||||
final index = steps.indexWhere((step) => step['sequence'] == sequence);
|
||||
if (index < 0) {
|
||||
final result = [...steps, _stepFields({}, delta, sequence)];
|
||||
result.sort(
|
||||
(a, b) => ((a['sequence'] as num?) ?? 0).compareTo(
|
||||
(b['sequence'] as num?) ?? 0,
|
||||
),
|
||||
);
|
||||
return result;
|
||||
}
|
||||
final old = steps[index];
|
||||
final incomingStatus = '${delta['status'] ?? ''}';
|
||||
final oldStatus = '${old['status'] ?? ''}';
|
||||
if (_stale(oldStatus, incomingStatus)) return steps;
|
||||
final merged = _stepFields(old, delta, sequence);
|
||||
if (_same(old, merged)) return steps;
|
||||
final result = [...steps];
|
||||
result[index] = merged;
|
||||
return result;
|
||||
}
|
||||
|
||||
JsonMap _stepFields(JsonMap old, JsonMap delta, int sequence) {
|
||||
final oldStatus = '${old['status'] ?? ''}';
|
||||
final incoming = '${delta['status'] ?? ''}';
|
||||
return {
|
||||
...old,
|
||||
'sequence': sequence,
|
||||
for (final key in ['stage', 'outcome', 'target', 'diagnostic'])
|
||||
key: _blank(delta[key]) ? old[key] ?? '' : delta[key],
|
||||
'status': _advance(oldStatus, incoming),
|
||||
};
|
||||
}
|
||||
|
||||
bool _stale(String old, String incoming) {
|
||||
if (_blank(incoming)) return false;
|
||||
final before = _rank(old);
|
||||
final after = _rank(incoming);
|
||||
return before >= 0 &&
|
||||
after >= 0 &&
|
||||
(after < before || (before == 2 && after == 2 && old != incoming));
|
||||
}
|
||||
|
||||
String _advance(String old, String incoming) {
|
||||
if (_blank(incoming)) return old;
|
||||
final before = _rank(old);
|
||||
final after = _rank(incoming);
|
||||
if (before < 0 || (after >= 0 && after > before && before < 2)) {
|
||||
return incoming;
|
||||
}
|
||||
if (before < 2 && after == before) return incoming;
|
||||
return old;
|
||||
}
|
||||
|
||||
int _rank(String status) => switch (status.trim().toLowerCase()) {
|
||||
'running' || 'waiting' => 1,
|
||||
'completed' || 'failed' || 'canceled' || 'interrupted' => 2,
|
||||
_ => -1,
|
||||
};
|
||||
|
||||
bool _same(JsonMap a, JsonMap b) =>
|
||||
a.length == b.length && a.entries.every((e) => b[e.key] == e.value);
|
||||
|
||||
/// Compact graph evidence is intentionally allowlisted. It retains latest
|
||||
/// visit-by-stage and distinct outcome routes, not arbitrary frame diagnostics.
|
||||
JsonMap? mergeGraphEvidence(JsonMap? current, JsonMap frame) {
|
||||
final incomingEvidence = frame['graph_evidence'];
|
||||
final graphVisits = frame['graph_visits'];
|
||||
final step = frame['step'];
|
||||
if (incomingEvidence is! Map && graphVisits is! List && step is! Map) {
|
||||
return current;
|
||||
}
|
||||
var visits = <JsonMap>[];
|
||||
final oldVisits = current?['visits'];
|
||||
if (oldVisits is List) {
|
||||
visits = oldVisits
|
||||
.whereType<Map>()
|
||||
.map((v) => Map<String, dynamic>.from(v))
|
||||
.toList();
|
||||
}
|
||||
final additions = <dynamic>[];
|
||||
if (incomingEvidence is Map && incomingEvidence['visits'] is List) {
|
||||
additions.addAll(incomingEvidence['visits'] as List);
|
||||
}
|
||||
if (graphVisits is List) additions.addAll(graphVisits);
|
||||
if (step is Map) additions.add(step);
|
||||
for (final item in additions.whereType<Map>()) {
|
||||
final delta = Map<String, dynamic>.from(item);
|
||||
visits = upsertRunStep(visits, {
|
||||
'sequence': delta['sequence'],
|
||||
'stage': delta['stage'],
|
||||
'status': delta['status'],
|
||||
'outcome': delta['outcome'],
|
||||
'target': delta['target'],
|
||||
});
|
||||
}
|
||||
final latestByStage = <String, int>{};
|
||||
final routeSequence = <String, int>{};
|
||||
for (final visit in visits) {
|
||||
final sequence = (visit['sequence'] as num?)?.toInt() ?? 0;
|
||||
final stage = '${visit['stage'] ?? ''}';
|
||||
latestByStage[stage] = sequence;
|
||||
if (!_blank(visit['outcome']) && !_blank(visit['target'])) {
|
||||
routeSequence['$stage\u0000${visit['outcome']}\u0000${visit['target']}'] =
|
||||
sequence;
|
||||
}
|
||||
}
|
||||
visits = visits
|
||||
.where((visit) {
|
||||
final sequence = (visit['sequence'] as num?)?.toInt() ?? 0;
|
||||
final stage = '${visit['stage'] ?? ''}';
|
||||
final route = '$stage\u0000${visit['outcome']}\u0000${visit['target']}';
|
||||
return latestByStage[stage] == sequence ||
|
||||
routeSequence[route] == sequence;
|
||||
})
|
||||
.map(
|
||||
(visit) => <String, dynamic>{
|
||||
for (final key in [
|
||||
'sequence',
|
||||
'stage',
|
||||
'status',
|
||||
'outcome',
|
||||
'target',
|
||||
])
|
||||
key: visit[key],
|
||||
},
|
||||
)
|
||||
.toList();
|
||||
final complete =
|
||||
current?['complete'] == true ||
|
||||
(incomingEvidence is Map && incomingEvidence['complete'] == true);
|
||||
return {'complete': complete, 'visits': visits};
|
||||
}
|
||||
|
||||
bool _blank(dynamic value) => '${value ?? ''}'.trim().isEmpty;
|
||||
Reference in New Issue
Block a user