From 444bd62996673d95756eaa79827bebf4d7541b50 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:21:30 +0100 Subject: [PATCH 1/2] feat(app): add run foundation repository and models --- app/lib/features/runs/domain/run_events.dart | 24 ++++++++ app/lib/features/runs/domain/run_models.dart | 33 +++++++++++ app/notes/F3.md | 12 ++++ .../features/runs/runs_foundation_test.dart | 59 +++++++++++++++++++ 4 files changed, 128 insertions(+) create mode 100644 app/lib/features/runs/domain/run_events.dart create mode 100644 app/lib/features/runs/domain/run_models.dart create mode 100644 app/notes/F3.md create mode 100644 app/test/features/runs/runs_foundation_test.dart diff --git a/app/lib/features/runs/domain/run_events.dart b/app/lib/features/runs/domain/run_events.dart new file mode 100644 index 00000000..5462d217 --- /dev/null +++ b/app/lib/features/runs/domain/run_events.dart @@ -0,0 +1,24 @@ +import '../../../core/api_gateway.dart'; +const _terminal = {'succeeded','failed','canceled','interrupted'}; +int _rank(dynamic s) => s == 'queued' ? 0 : {'running','waiting'}.contains(s) ? 1 : _terminal.contains(s) ? 2 : -1; +int _stepRank(dynamic s) => {'running','waiting'}.contains(s) ? 1 : {'completed','failed','canceled','interrupted'}.contains(s) ? 2 : -1; +bool _stale(dynamic a, dynamic b, int Function(dynamic) rank) => '${b ?? ''}'.trim().isNotEmpty && rank(a) >= 0 && rank(b) >= 0 && (rank(b) < rank(a) || (rank(a) == 2 && rank(b) == 2 && a != b)); +String _advance(dynamic a, dynamic b, int Function(dynamic) rank) => '${b ?? ''}'.trim().isEmpty || rank(b) < rank(a) || (rank(a) == 2 && rank(b) == 2) ? '${a ?? ''}' : '${b ?? ''}'; +({List runs, bool needsResync}) foldRunEvent(List runs, JsonMap frame) { + final id = frame['run_id']; if (id is! num || id <= 0) return (runs:runs, needsResync:false); + final i = runs.indexWhere((r) => r['id'] == id); + if (i < 0) { final pid=frame['pipeline_id']; final name=frame['name']; if (pid is! num || '${name ?? ''}'.trim().isEmpty) return (runs:runs, needsResync:true); + return (runs:[{'id':id,'pipeline_id':pid,'name':name,'title':frame['title'],'version':frame['version'] ?? 0,'status':frame['status'] ?? '', 'executing':true,'completed_steps':frame['completed_steps'] ?? 0,'created_at':frame['created_at'] ?? '', 'finished_at':frame['finished_at'] ?? '', 'resource_wait':frame['resource_wait']}, ...runs], needsResync:false); } + final current=runs[i]; if (_stale(current['status'],frame['status'],_rank) && frame['resource_wait_set'] != true) return (runs:runs, needsResync:false); + final status=frame['resource_wait_set']==true && frame['status']=='queued' && !_terminal.contains(current['status']) ? 'queued' : _advance(current['status'],frame['status'],_rank); + final updated={...current,'status':status,'executing':status=='queued'||status=='running','completed_steps':(((current['completed_steps'] as num?)??0).toInt()).clamp(((frame['completed_steps'] as num?)??0).toInt(),0x7fffffff),'resource_wait':_terminal.contains(status)?null:frame['resource_wait_set']==true?frame['resource_wait']:current['resource_wait']}; + for(final k in ['outcome','current_stage','finished_at','created_at']) { if ('${frame[k]??''}'.trim().isNotEmpty) updated[k]=frame[k]; } + final next=[...runs]; next[i]=updated; return (runs:next,needsResync:false); +} +bool runDetailNeedsFullSync(JsonMap f) => _terminal.contains(f['status']) || f['status']=='waiting' || f['cancel_requested']==true || f['cleanup_unconfirmed']==true || f['step']?['status']=='waiting' || _stepRank(f['step']?['status'])==2; +JsonMap? foldRunEventDetail(JsonMap? detail, JsonMap frame) { + if(detail==null || detail['id']!=frame['run_id'] || (_stale(detail['status'],frame['status'],_rank)&&frame['resource_wait_set']!=true)) return detail; + final folded=foldRunEvent([detail],frame).runs.single; final delta=frame['step']; + if(delta is Map) { final steps=List.from(detail['steps']??[]); final i=steps.indexWhere((s)=>s['sequence']==delta['sequence']); if(i<0){steps.add(Map.from(delta));steps.sort((a,b)=>((a['sequence'] as num?)??0).compareTo((b['sequence'] as num?)??0));} else if(!_stale(steps[i]['status'],delta['status'],_stepRank)){steps[i]={...steps[i],...Map.from(delta)};} folded['steps']=steps; } + return folded; +} diff --git a/app/lib/features/runs/domain/run_models.dart b/app/lib/features/runs/domain/run_models.dart new file mode 100644 index 00000000..5fe96a56 --- /dev/null +++ b/app/lib/features/runs/domain/run_models.dart @@ -0,0 +1,33 @@ +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 filterRuns(List runs, {Set statuses = const {}, int? pipelineId}) => runs.where((r) => (statuses.isEmpty || statuses.contains(runStateOf(r['status']))) && (pipelineId == null || r['pipeline_id'] == pipelineId)).toList(); +List sortRuns(List runs, {String sort = 'newest_first'}) { + int time(dynamic x) => DateTime.tryParse('${x ?? ''}')?.millisecondsSinceEpoch ?? -0x7fffffffffffffff; + final result = [...runs]; + result.sort((a,b) { + final c = switch (sort) { 'oldest_first' => time(a['created_at']).compareTo(time(b['created_at'])), 'pipeline_name' => '${a['name'] ?? ''}'.toLowerCase().compareTo('${b['name'] ?? ''}'.toLowerCase()), 'status' => '${a['status'] ?? ''}'.compareTo('${b['status'] ?? ''}'), _ => time(b['created_at']).compareTo(time(a['created_at'])) }; + return c == 0 ? ((b['id'] as num?) ?? 0).compareTo((a['id'] as num?) ?? 0) : c; + }); + return result; +} +/// Null usage means unsupported/unavailable, not zero. +class RunListResult { const RunListResult(this.runs, this.usage); final List 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; } +String attentionKey(num runId, String kind) => '$runId:$kind'; +List orderAttention(List runs, {Set dismissed = const {}}) { + final result = runs.where((r) => ['waiting','failed'].contains(r['status']) && !dismissed.contains(attentionKey(r['id'] as num, r['status'] == 'waiting' ? 'Decision' : 'Failed'))).toList(); + int at(JsonMap r) => DateTime.tryParse('${r['finished_at'] ?? r['created_at'] ?? ''}')?.millisecondsSinceEpoch ?? 0; + result.sort((a,b) { final rank = (a['status'] == 'waiting' ? 0 : 1).compareTo(b['status'] == 'waiting' ? 0 : 1); if (rank != 0) return rank; final date = at(b).compareTo(at(a)); return date != 0 ? date : (b['id'] as num).compareTo(a['id'] as num); }); + return result; +} diff --git a/app/notes/F3.md b/app/notes/F3.md new file mode 100644 index 00000000..79954b60 --- /dev/null +++ b/app/notes/F3.md @@ -0,0 +1,12 @@ +# F3 run foundation + +Public API: `run_models.dart` provides run identity/state/filter/sort helpers, +`RunListResult`, decision draft/option values, and attention ordering/identity. +`run_events.dart` provides monotonic list/detail event folds and +`runDetailNeedsFullSync`. `data/runs_repository.dart` provides `RunsRepository` +for list/get/cancel/retry/decide/title/start calls through the shared gateway. + +Focused tests cover stale lifecycle deltas, explicit resource-wait clearing, +unknown usage versus zero, decision refusal, attention identity/order, and exact +retry/start fields. This is a nonvisual foundation; browser UI captures were not +applicable. Mobile targets are unverified. diff --git a/app/test/features/runs/runs_foundation_test.dart b/app/test/features/runs/runs_foundation_test.dart new file mode 100644 index 00000000..9ad8f833 --- /dev/null +++ b/app/test/features/runs/runs_foundation_test.dart @@ -0,0 +1,59 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/data/runs_repository.dart'; +import 'package:pipelines_app/features/runs/domain/run_events.dart'; +import 'package:pipelines_app/features/runs/domain/run_models.dart'; + +class FakeGateway implements ApiGateway { + String? type; + JsonMap fields = {}; + JsonMap reply = {}; + @override + Future call(String type, [JsonMap fields = const {}]) async { + this.type = type; + this.fields = Map.of(fields); + return reply; + } + @override + Stream get frames => const Stream.empty(); +} + +void main() { + test('filter/sort identities and unknown usage remain distinct', () { + expect(runIdentity(' Report ', 'Build').label, 'Report'); + final rows = [{'id': 1, 'pipeline_id': 2, 'status': 'failed', 'created_at': '2024-01-01'}, {'id': 2, 'pipeline_id': 2, 'status': 'running', 'created_at': '2025-01-01'}]; + expect(filterRuns(rows, statuses: {'failed'}).single['id'], 1); + expect(sortRuns(rows).first['id'], 2); + expect(RunListResult(const [], null).usage, isNull); + }); + + test('fold is monotonic and explicit resource wait clearing is honored', () { + final rows = [{'id': 1, 'status': 'running', 'completed_steps': 3, 'resource_wait': {'resource': 'gpu'}}]; + final stale = foldRunEvent(rows, {'run_id': 1, 'status': 'queued', 'completed_steps': 1}); + expect(stale.runs.single['status'], 'running'); + final cleared = foldRunEvent(rows, {'run_id': 1, 'status': 'queued', 'resource_wait_set': true, 'resource_wait': null}); + expect(cleared.runs.single['status'], 'queued'); + expect(cleared.runs.single['resource_wait'], isNull); + expect(cleared.runs.single['completed_steps'], 3); + expect(runDetailNeedsFullSync({'status': 'waiting'}), isTrue); + }); + + test('decision guard and attention dismissal identity', () { + expect(const DecisionDraft().canSubmit, isFalse); + expect(const DecisionDraft(selected: ' continue ').canSubmit, isTrue); + expect(attentionKey(7, 'Decision'), '7:Decision'); + final ordered = orderAttention([{'id': 8, 'status': 'failed'}, {'id': 7, 'status': 'waiting'}]); + expect(ordered.first['id'], 7); + }); + + test('repository emits exact action envelopes and requires idempotency key', () async { + final gateway = FakeGateway()..reply = {'run_detail': {'id': 3}}; + final repo = RunsRepository(gateway); + await repo.retryRun(3, requestKey: 'retry-1'); + expect(gateway.type, 'retry_run'); + expect(gateway.fields, {'run_id': 3, 'request_key': 'retry-1'}); + await repo.startRun(pipelineId: 4, version: 2, prompt: 'hello', workspace: ' /work ', requestKey: 'start-2'); + expect(gateway.fields, {'pipeline_id': 4, 'version': 2, 'request_key': 'start-2', 'workspace': '/work', 'input': {'prompt': 'hello'}}); + await expectLater(repo.decideRun(3, option: ' '), throwsA(isA())); + }); +} From 1515ebee990e1db31cc365a03d24be30ecc0d304 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Wed, 21 Oct 2026 13:34:56 +0100 Subject: [PATCH 2/2] fix flutter runs foundation parity gaps --- .../features/runs/data/runs_repository.dart | 105 ++++++++ .../features/runs/domain/run_decisions.dart | 110 ++++++++ app/lib/features/runs/domain/run_events.dart | 242 ++++++++++++++++-- app/lib/features/runs/domain/run_models.dart | 222 ++++++++++++++-- .../runs/domain/run_step_evidence.dart | 142 ++++++++++ app/notes/F3.md | 26 +- .../features/runs/run_decisions_test.dart | 87 +++++++ .../features/runs/runs_foundation_test.dart | 228 +++++++++++++---- .../features/runs/runs_repository_test.dart | 163 ++++++++++++ 9 files changed, 1229 insertions(+), 96 deletions(-) create mode 100644 app/lib/features/runs/data/runs_repository.dart create mode 100644 app/lib/features/runs/domain/run_decisions.dart create mode 100644 app/lib/features/runs/domain/run_step_evidence.dart create mode 100644 app/test/features/runs/run_decisions_test.dart create mode 100644 app/test/features/runs/runs_repository_test.dart diff --git a/app/lib/features/runs/data/runs_repository.dart b/app/lib/features/runs/data/runs_repository.dart new file mode 100644 index 00000000..5a1ea8c4 --- /dev/null +++ b/app/lib/features/runs/data/runs_repository.dart @@ -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 listRuns() async { + final reply = await _gateway.call('list_runs'); + final runs = reply['runs']; + return RunListResult( + runs is List + ? runs + .whereType() + .map((r) => Map.from(r)) + .toList() + : const [], + reply['usage'] is Map + ? Map.from(reply['usage'] as Map) + : null, + ); + } + + Future getRun(num id) async => + _required(await _gateway.call('get_run', {'run_id': id}), 'run_detail'); + Future cancelRun(num id) async => _required( + await _gateway.call('cancel_run', {'run_id': id}), + 'run_detail', + ); + + Future retryRun( + num id, { + required String requestKey, + String? mode, + }) async { + final fields = {'run_id': id, 'request_key': requestKey}; + if (mode == 'restart') fields['retry_mode'] = mode; + return _required(await _gateway.call('retry_run', fields), 'run_detail'); + } + + Future 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 = {'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 setRunTitle(num id, String title) async => _required( + await _gateway.call('set_run_title', {'run_id': id, 'title': title}), + 'run_detail', + ); + + Future 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 = { + '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.from(value); + } +} diff --git a/app/lib/features/runs/domain/run_decisions.dart b/app/lib/features/runs/domain/run_decisions.dart new file mode 100644 index 00000000..339508e6 --- /dev/null +++ b/app/lib/features/runs/domain/run_decisions.dart @@ -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 options; +} + +JsonMap? lastWaitingStep(List steps) { + for (final value in steps.reversed) { + if (value is Map && value['status'] == 'waiting') { + return Map.from(value); + } + } + return null; +} + +String waitingPrompt(dynamic output) => + output is Map && output['prompt'] is String + ? output['prompt'] as String + : ''; + +List waitingOptions(dynamic output) { + final options = output is Map ? output['options'] : null; + if (options is! List) return const []; + return options + .whereType() + .where((entry) => entry.trim().isNotEmpty) + .toList(); +} + +List 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()) { + if (value['key'] == stage) { + declaration = Map.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'; diff --git a/app/lib/features/runs/domain/run_events.dart b/app/lib/features/runs/domain/run_events.dart index 5462d217..3ce3bc87 100644 --- a/app/lib/features/runs/domain/run_events.dart +++ b/app/lib/features/runs/domain/run_events.dart @@ -1,24 +1,226 @@ import '../../../core/api_gateway.dart'; -const _terminal = {'succeeded','failed','canceled','interrupted'}; -int _rank(dynamic s) => s == 'queued' ? 0 : {'running','waiting'}.contains(s) ? 1 : _terminal.contains(s) ? 2 : -1; -int _stepRank(dynamic s) => {'running','waiting'}.contains(s) ? 1 : {'completed','failed','canceled','interrupted'}.contains(s) ? 2 : -1; -bool _stale(dynamic a, dynamic b, int Function(dynamic) rank) => '${b ?? ''}'.trim().isNotEmpty && rank(a) >= 0 && rank(b) >= 0 && (rank(b) < rank(a) || (rank(a) == 2 && rank(b) == 2 && a != b)); -String _advance(dynamic a, dynamic b, int Function(dynamic) rank) => '${b ?? ''}'.trim().isEmpty || rank(b) < rank(a) || (rank(a) == 2 && rank(b) == 2) ? '${a ?? ''}' : '${b ?? ''}'; -({List runs, bool needsResync}) foldRunEvent(List runs, JsonMap frame) { - final id = frame['run_id']; if (id is! num || id <= 0) return (runs:runs, needsResync:false); - final i = runs.indexWhere((r) => r['id'] == id); - if (i < 0) { final pid=frame['pipeline_id']; final name=frame['name']; if (pid is! num || '${name ?? ''}'.trim().isEmpty) return (runs:runs, needsResync:true); - return (runs:[{'id':id,'pipeline_id':pid,'name':name,'title':frame['title'],'version':frame['version'] ?? 0,'status':frame['status'] ?? '', 'executing':true,'completed_steps':frame['completed_steps'] ?? 0,'created_at':frame['created_at'] ?? '', 'finished_at':frame['finished_at'] ?? '', 'resource_wait':frame['resource_wait']}, ...runs], needsResync:false); } - final current=runs[i]; if (_stale(current['status'],frame['status'],_rank) && frame['resource_wait_set'] != true) return (runs:runs, needsResync:false); - final status=frame['resource_wait_set']==true && frame['status']=='queued' && !_terminal.contains(current['status']) ? 'queued' : _advance(current['status'],frame['status'],_rank); - final updated={...current,'status':status,'executing':status=='queued'||status=='running','completed_steps':(((current['completed_steps'] as num?)??0).toInt()).clamp(((frame['completed_steps'] as num?)??0).toInt(),0x7fffffff),'resource_wait':_terminal.contains(status)?null:frame['resource_wait_set']==true?frame['resource_wait']:current['resource_wait']}; - for(final k in ['outcome','current_stage','finished_at','created_at']) { if ('${frame[k]??''}'.trim().isNotEmpty) updated[k]=frame[k]; } - final next=[...runs]; next[i]=updated; return (runs:next,needsResync:false); +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)); } -bool runDetailNeedsFullSync(JsonMap f) => _terminal.contains(f['status']) || f['status']=='waiting' || f['cancel_requested']==true || f['cleanup_unconfirmed']==true || f['step']?['status']=='waiting' || _stepRank(f['step']?['status'])==2; + +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 = { + ...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 = { + '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 runs, bool needsResync}) foldRunEvent( + List 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'] || (_stale(detail['status'],frame['status'],_rank)&&frame['resource_wait_set']!=true)) return detail; - final folded=foldRunEvent([detail],frame).runs.single; final delta=frame['step']; - if(delta is Map) { final steps=List.from(detail['steps']??[]); final i=steps.indexWhere((s)=>s['sequence']==delta['sequence']); if(i<0){steps.add(Map.from(delta));steps.sort((a,b)=>((a['sequence'] as num?)??0).compareTo((b['sequence'] as num?)??0));} else if(!_stale(steps[i]['status'],delta['status'],_stepRank)){steps[i]={...steps[i],...Map.from(delta)};} folded['steps']=steps; } - return folded; + 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((s) => Map.from(s)) + .toList() + : [], + Map.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(); diff --git a/app/lib/features/runs/domain/run_models.dart b/app/lib/features/runs/domain/run_models.dart index 5fe96a56..0c2ff344 100644 --- a/app/lib/features/runs/domain/run_models.dart +++ b/app/lib/features/runs/domain/run_models.dart @@ -1,33 +1,217 @@ import '../../../core/api_gateway.dart'; -const runStates = ['queued', 'running', 'waiting', 'succeeded', 'failed', 'canceled', 'interrupted']; +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); + 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 filterRuns(List runs, {Set statuses = const {}, int? pipelineId}) => runs.where((r) => (statuses.isEmpty || statuses.contains(runStateOf(r['status']))) && (pipelineId == null || r['pipeline_id'] == pipelineId)).toList(); + +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 filterRuns( + List runs, { + Set 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 sortRuns(List runs, {String sort = 'newest_first'}) { - int time(dynamic x) => DateTime.tryParse('${x ?? ''}')?.millisecondsSinceEpoch ?? -0x7fffffffffffffff; final result = [...runs]; - result.sort((a,b) { - final c = switch (sort) { 'oldest_first' => time(a['created_at']).compareTo(time(b['created_at'])), 'pipeline_name' => '${a['name'] ?? ''}'.toLowerCase().compareTo('${b['name'] ?? ''}'.toLowerCase()), 'status' => '${a['status'] ?? ''}'.compareTo('${b['status'] ?? ''}'), _ => time(b['created_at']).compareTo(time(a['created_at'])) }; - return c == 0 ? ((b['id'] as num?) ?? 0).compareTo((a['id'] as num?) ?? 0) : c; + 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 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 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; } +class RunListResult { + const RunListResult(this.runs, this.usage); + final List 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 orderAttention(List runs, {Set dismissed = const {}}) { - final result = runs.where((r) => ['waiting','failed'].contains(r['status']) && !dismissed.contains(attentionKey(r['id'] as num, r['status'] == 'waiting' ? 'Decision' : 'Failed'))).toList(); - int at(JsonMap r) => DateTime.tryParse('${r['finished_at'] ?? r['created_at'] ?? ''}')?.millisecondsSinceEpoch ?? 0; - result.sort((a,b) { final rank = (a['status'] == 'waiting' ? 0 : 1).compareTo(b['status'] == 'waiting' ? 0 : 1); if (rank != 0) return rank; final date = at(b).compareTo(at(a)); return date != 0 ? date : (b['id'] as num).compareTo(a['id'] as num); }); + +List orderAttention( + List runs, { + Set 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; } diff --git a/app/lib/features/runs/domain/run_step_evidence.dart b/app/lib/features/runs/domain/run_step_evidence.dart new file mode 100644 index 00000000..f4fdb710 --- /dev/null +++ b/app/lib/features/runs/domain/run_step_evidence.dart @@ -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 upsertRunStep(List 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 = []; + final oldVisits = current?['visits']; + if (oldVisits is List) { + visits = oldVisits + .whereType() + .map((v) => Map.from(v)) + .toList(); + } + final additions = []; + 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()) { + final delta = Map.from(item); + visits = upsertRunStep(visits, { + 'sequence': delta['sequence'], + 'stage': delta['stage'], + 'status': delta['status'], + 'outcome': delta['outcome'], + 'target': delta['target'], + }); + } + final latestByStage = {}; + final routeSequence = {}; + 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) => { + 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; diff --git a/app/notes/F3.md b/app/notes/F3.md index 79954b60..687abed2 100644 --- a/app/notes/F3.md +++ b/app/notes/F3.md @@ -1,12 +1,22 @@ # F3 run foundation Public API: `run_models.dart` provides run identity/state/filter/sort helpers, -`RunListResult`, decision draft/option values, and attention ordering/identity. -`run_events.dart` provides monotonic list/detail event folds and -`runDetailNeedsFullSync`. `data/runs_repository.dart` provides `RunsRepository` -for list/get/cancel/retry/decide/title/start calls through the shared gateway. +status wording, `RunListResult`, decision draft/option values, and attention +ordering/identity. `run_decisions.dart` resolves recorded human options and +prompt evidence with graph fallback. `run_events.dart` and +`run_step_evidence.dart` provide monotonic list/detail folds, immutable schedule +origin, graph evidence, and `runDetailNeedsFullSync`. `data/runs_repository.dart` +provides list/get/cancel/retry/decide/title/start calls through the shared gateway. -Focused tests cover stale lifecycle deltas, explicit resource-wait clearing, -unknown usage versus zero, decision refusal, attention identity/order, and exact -retry/start fields. This is a nonvisual foundation; browser UI captures were not -applicable. Mobile targets are unverified. +Focused tests cover stale and terminal lifecycle deltas, resource-wait clearing, +sparse step preservation, sticky cancel/cleanup flags, schedule provenance, +export gating, pending-decision evidence, list/detail agreement, filters/sorts, +exact request fields and server refusals. The repository file is deliberately +tracked despite the repository's `data/` ignore rule. This is a nonvisual +foundation; browser UI captures were not applicable. Mobile targets are +unverified. + +This is not total web parity: date filtering uses Dart local-time conversion +rather than web's explicit IANA-zone/locale helpers; the complete attention +dismissal/persistence surface, retry key generation, and repository methods for +export repair/request-key reconciliation are not included in this foundation. diff --git a/app/test/features/runs/run_decisions_test.dart b/app/test/features/runs/run_decisions_test.dart new file mode 100644 index 00000000..2cb47b1c --- /dev/null +++ b/app/test/features/runs/run_decisions_test.dart @@ -0,0 +1,87 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/domain/run_decisions.dart'; +import 'package:pipelines_app/features/runs/domain/run_events.dart'; +import 'package:pipelines_app/features/runs/domain/run_models.dart'; + +void main() { + test( + 'scheduled origin is immutable and export pending blocks attention/decision', + () { + final rows = [ + { + 'id': 5, + 'status': 'waiting', + 'scheduled': true, + 'schedule_id': 12, + 'schedule_name': 'Nightly', + }, + ]; + final changed = foldRunEvent(rows, { + 'run_id': 5, + 'status': 'waiting', + 'scheduled': false, + 'schedule_id': 99, + 'schedule_name': 'Other', + 'export_pending_sequence': 4, + }); + expect(changed.runs.single['schedule_id'], 12); + expect(changed.runs.single['schedule_name'], 'Nightly'); + expect(changed.runs.single['scheduled'], true); + expect(orderAttention(changed.runs), isEmpty); + expect( + pendingDecision({ + ...changed.runs.single, + 'current_stage': 'human', + 'steps': [], + }), + isNull, + ); + }, + ); + + test( + 'pending decision uses recorded options then graph fallback and target labels', + () { + final run = { + 'id': 7, + 'status': 'waiting', + 'current_stage': 'human', + 'name': 'Build', + 'graph': { + 'stages': [ + { + 'key': 'human', + 'type': 'human', + 'prompt': 'Graph prompt', + 'edges': {'go': '#', 'error': '#', 'skip': 'finish'}, + }, + ], + }, + 'steps': [ + { + 'sequence': 1, + 'status': 'waiting', + 'stage': 'human', + 'output': { + 'prompt': 'Recorded prompt', + 'options': ['go'], + }, + }, + ], + }; + final decision = pendingDecision(run)!; + expect(decision.instructions, 'Recorded prompt'); + expect(decision.options.map((option) => option.key), ['go']); + expect(decision.options.single.target, 'SUCCESS'); + final fallback = pendingDecision({ + ...run, + 'steps': [ + {'status': 'waiting', 'stage': 'human', 'output': {}}, + ], + })!; + expect(fallback.instructions, 'Graph prompt'); + expect(fallback.options.map((option) => option.key), ['go', 'skip']); + }, + ); +} diff --git a/app/test/features/runs/runs_foundation_test.dart b/app/test/features/runs/runs_foundation_test.dart index 9ad8f833..df77eca0 100644 --- a/app/test/features/runs/runs_foundation_test.dart +++ b/app/test/features/runs/runs_foundation_test.dart @@ -1,59 +1,189 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/core/api_gateway.dart'; -import 'package:pipelines_app/features/runs/data/runs_repository.dart'; import 'package:pipelines_app/features/runs/domain/run_events.dart'; -import 'package:pipelines_app/features/runs/domain/run_models.dart'; - -class FakeGateway implements ApiGateway { - String? type; - JsonMap fields = {}; - JsonMap reply = {}; - @override - Future call(String type, [JsonMap fields = const {}]) async { - this.type = type; - this.fields = Map.of(fields); - return reply; - } - @override - Stream get frames => const Stream.empty(); -} void main() { - test('filter/sort identities and unknown usage remain distinct', () { - expect(runIdentity(' Report ', 'Build').label, 'Report'); - final rows = [{'id': 1, 'pipeline_id': 2, 'status': 'failed', 'created_at': '2024-01-01'}, {'id': 2, 'pipeline_id': 2, 'status': 'running', 'created_at': '2025-01-01'}]; - expect(filterRuns(rows, statuses: {'failed'}).single['id'], 1); - expect(sortRuns(rows).first['id'], 2); - expect(RunListResult(const [], null).usage, isNull); - }); + group('event fold', () { + test('terminal status and resource wait reset are monotonic', () { + final initial = [ + { + 'id': 1, + 'status': 'succeeded', + 'executing': false, + 'completed_steps': 4, + }, + ]; + final reset = foldRunEvent(initial, { + 'run_id': 1, + 'status': 'queued', + 'resource_wait_set': true, + 'resource_wait': null, + }); + expect(reset.runs.single['status'], 'succeeded'); + expect(reset.runs.single['executing'], false); + final competing = foldRunEvent(initial, { + 'run_id': 1, + 'status': 'failed', + 'resource_wait_set': true, + }); + expect(competing.runs.single['status'], 'succeeded'); + expect(competing.runs.single['resource_wait'], isNull); + }); - test('fold is monotonic and explicit resource wait clearing is honored', () { - final rows = [{'id': 1, 'status': 'running', 'completed_steps': 3, 'resource_wait': {'resource': 'gpu'}}]; - final stale = foldRunEvent(rows, {'run_id': 1, 'status': 'queued', 'completed_steps': 1}); - expect(stale.runs.single['status'], 'running'); - final cleared = foldRunEvent(rows, {'run_id': 1, 'status': 'queued', 'resource_wait_set': true, 'resource_wait': null}); - expect(cleared.runs.single['status'], 'queued'); - expect(cleared.runs.single['resource_wait'], isNull); - expect(cleared.runs.single['completed_steps'], 3); - expect(runDetailNeedsFullSync({'status': 'waiting'}), isTrue); - }); + test( + 'resource wait reset advances only nonterminal rows, even on stale status', + () { + final rows = [ + { + 'id': 2, + 'status': 'running', + 'executing': true, + 'resource_wait': {'resource': 'gpu'}, + 'completed_steps': 3, + }, + ]; + final result = foldRunEvent(rows, { + 'run_id': 2, + 'status': 'queued', + 'resource_wait_set': true, + 'resource_wait': null, + 'completed_steps': 1, + }); + expect(result.runs.single['status'], 'queued'); + expect(result.runs.single['resource_wait'], isNull); + expect(result.runs.single['completed_steps'], 3); + }, + ); - test('decision guard and attention dismissal identity', () { - expect(const DecisionDraft().canSubmit, isFalse); - expect(const DecisionDraft(selected: ' continue ').canSubmit, isTrue); - expect(attentionKey(7, 'Decision'), '7:Decision'); - final ordered = orderAttention([{'id': 8, 'status': 'failed'}, {'id': 7, 'status': 'waiting'}]); - expect(ordered.first['id'], 7); - }); + test( + 'new waiting and terminal rows are not executing; identity-less frame resyncs', + () { + for (final status in ['waiting', 'succeeded']) { + final result = foldRunEvent([], { + 'run_id': 8, + 'pipeline_id': 4, + 'name': 'Build', + 'status': status, + }); + expect(result.runs.single['executing'], false); + } + expect( + foldRunEvent([], {'run_id': 9, 'status': 'running'}).needsResync, + isTrue, + ); + }, + ); - test('repository emits exact action envelopes and requires idempotency key', () async { - final gateway = FakeGateway()..reply = {'run_detail': {'id': 3}}; - final repo = RunsRepository(gateway); - await repo.retryRun(3, requestKey: 'retry-1'); - expect(gateway.type, 'retry_run'); - expect(gateway.fields, {'run_id': 3, 'request_key': 'retry-1'}); - await repo.startRun(pipelineId: 4, version: 2, prompt: 'hello', workspace: ' /work ', requestKey: 'start-2'); - expect(gateway.fields, {'pipeline_id': 4, 'version': 2, 'request_key': 'start-2', 'workspace': '/work', 'input': {'prompt': 'hello'}}); - await expectLater(repo.decideRun(3, option: ' '), throwsA(isA())); + test( + 'blank sparse step fields preserve graph evidence and terminal visit', + () { + final detail = { + 'id': 1, + 'status': 'running', + 'steps': [ + { + 'sequence': 2, + 'stage': 'review', + 'status': 'completed', + 'outcome': 'approve', + 'target': 'publish', + 'diagnostic': 'kept', + }, + ], + }; + final next = foldRunEventDetail(detail, { + 'run_id': 1, + 'status': 'running', + 'step': { + 'sequence': 2, + 'stage': '', + 'status': 'running', + 'outcome': ' ', + 'target': '', + 'diagnostic': '', + }, + })!; + final step = (next['steps'] as List).single as JsonMap; + expect(step, containsPair('stage', 'review')); + expect(step, containsPair('status', 'completed')); + expect(step, containsPair('outcome', 'approve')); + expect(step, containsPair('target', 'publish')); + expect(step, containsPair('diagnostic', 'kept')); + }, + ); + + test( + 'cancel and cleanup flags stick; resource wait can clear; terminal clears it', + () { + final rows = [ + { + 'id': 3, + 'status': 'running', + 'resource_wait': {'resource': 'gpu'}, + }, + ]; + final first = foldRunEvent(rows, { + 'run_id': 3, + 'status': 'running', + 'cancel_requested': true, + 'cleanup_unconfirmed': true, + }); + final second = foldRunEvent(first.runs, { + 'run_id': 3, + 'status': 'running', + 'cancel_requested': false, + 'cleanup_unconfirmed': false, + 'resource_wait_set': true, + 'resource_wait': null, + }); + expect(second.runs.single['cancel_requested'], true); + expect(second.runs.single['cleanup_unconfirmed'], true); + expect(second.runs.single['resource_wait'], isNull); + final terminal = foldRunEvent(second.runs, { + 'run_id': 3, + 'status': 'failed', + }); + expect(terminal.runs.single['resource_wait'], isNull); + }, + ); + + test( + 'full sync triggers and list/detail folds agree across stale and current frames', + () { + expect(runDetailNeedsFullSync({'status': 'waiting'}), true); + expect( + runDetailNeedsFullSync({ + 'status': 'running', + 'step': {'status': 'completed'}, + }), + true, + ); + final summary = [ + {'id': 1, 'status': 'running', 'completed_steps': 1}, + ]; + final frame = { + 'run_id': 1, + 'status': 'succeeded', + 'completed_steps': 2, + 'outcome': 'done', + }; + final list = foldRunEvent(summary, frame).runs.single; + final detail = foldRunEventDetail({ + 'id': 1, + 'status': 'running', + 'completed_steps': 1, + 'steps': [], + }, frame)!; + expect(list['status'], detail['status']); + expect(list['completed_steps'], detail['completed_steps']); + final old = foldRunEventDetail(detail, { + 'run_id': 1, + 'status': 'running', + 'outcome': '', + })!; + expect(old['status'], 'succeeded'); + expect(old['outcome'], 'done'); + }, + ); }); } diff --git a/app/test/features/runs/runs_repository_test.dart b/app/test/features/runs/runs_repository_test.dart new file mode 100644 index 00000000..e6ee2164 --- /dev/null +++ b/app/test/features/runs/runs_repository_test.dart @@ -0,0 +1,163 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/data/runs_repository.dart'; +import 'package:pipelines_app/features/runs/domain/run_models.dart'; + +class FakeGateway implements ApiGateway { + String? type; + JsonMap fields = {}; + JsonMap reply = {}; + Object? failure; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + this.type = type; + this.fields = Map.of(fields); + if (failure case final error?) throw error; + return reply; + } + + @override + Stream get frames => const Stream.empty(); +} + +void main() { + test( + 'run models match identity, filtering, sorting and null usage behavior', + () { + expect(runIdentity(' Report ', 'Build').label, 'Report'); + final rows = [ + { + 'id': 1, + 'pipeline_id': 2, + 'status': 'failed', + 'created_at': '2024-01-01T00:00:00Z', + 'finished_at': '2024-01-01T00:00:10Z', + }, + { + 'id': 2, + 'pipeline_id': 2, + 'status': 'running', + 'created_at': '2025-01-01T00:00:00Z', + }, + ]; + expect(filterRuns(rows, statuses: {'failed'}).single['id'], 1); + expect(sortRuns(rows).first['id'], 2); + expect(sortRuns(rows, sort: 'shortest_duration').first['id'], 1); + final scheduled = [ + { + 'id': 3, + 'scheduled': true, + 'schedule_id': 9, + 'created_at': '2025-03-10T12:00:00Z', + }, + {'id': 4, 'scheduled': false, 'created_at': '2025-03-10T12:00:00Z'}, + {'id': 5, 'created_at': '2025-03-10T12:00:00Z'}, + ]; + expect( + filterRuns(scheduled, scheduled: 'scheduled').map((run) => run['id']), + [3], + ); + expect( + filterRuns( + scheduled, + scheduled: 'unscheduled', + timeRange: 'today', + today: DateTime(2025, 3, 10), + ).map((run) => run['id']), + [4], + ); + expect( + runStatusLabel({'status': 'waiting', 'export_pending_sequence': 2}), + 'Waiting for session export', + ); + expect(RunListResult(const [], null).usage, isNull); + }, + ); + + test('repository sends exact action and launch requests', () async { + final gateway = FakeGateway() + ..reply = { + 'run_detail': {'id': 3}, + }; + final repo = RunsRepository(gateway); + gateway.reply = { + 'runs': [ + {'id': 1, 'status': 'running'}, + ], + 'usage': {'active': 1}, + }; + final listed = await repo.listRuns(); + expect(gateway.type, 'list_runs'); + expect(gateway.fields, isEmpty); + expect(listed.runs.single['id'], 1); + expect(listed.usage, {'active': 1}); + gateway.reply = { + 'run_detail': {'id': 3}, + }; + await repo.retryRun(3, requestKey: 'retry-1'); + expect(gateway.type, 'retry_run'); + expect(gateway.fields, {'run_id': 3, 'request_key': 'retry-1'}); + await repo.retryRun(3, requestKey: 'retry-2', mode: 'restart'); + expect(gateway.fields, { + 'run_id': 3, + 'request_key': 'retry-2', + 'retry_mode': 'restart', + }); + await repo.decideRun(3, stage: 'human', option: ' go ', feedback: ' yes '); + expect(gateway.fields, { + 'run_id': 3, + 'stage': 'human', + 'option': 'go', + 'feedback': 'yes', + }); + await repo.cancelRun(3); + expect(gateway.type, 'cancel_run'); + expect(gateway.fields, {'run_id': 3}); + await repo.setRunTitle(3, 'New'); + expect(gateway.type, 'set_run_title'); + expect(gateway.fields, {'run_id': 3, 'title': 'New'}); + await repo.startRun( + pipelineId: 4, + version: 2, + prompt: 'hello', + workspace: ' /work ', + requestKey: 'start-2', + title: ' Job ', + notifyMode: 'off', + outputFormat: 'json', + ); + expect(gateway.type, 'run_pipeline'); + expect(gateway.fields, { + 'pipeline_id': 4, + 'version': 2, + 'request_key': 'start-2', + 'workspace': '/work', + 'input': {'prompt': 'hello'}, + 'title': 'Job', + 'notify_mode': 'off', + 'output_format': 'json', + }); + }); + + test( + 'repository propagates server refusals and rejects missing detail', + () async { + final gateway = FakeGateway()..reply = {}; + final repo = RunsRepository(gateway); + await expectLater( + repo.getRun(3), + throwsA(isA()), + ); + await expectLater( + repo.decideRun(3, option: ' '), + throwsA(isA()), + ); + gateway.failure = const RunsRepositoryException('server refused'); + await expectLater( + repo.cancelRun(3), + throwsA(predicate((error) => '$error' == 'server refused')), + ); + }, + ); +}