diff --git a/app/lib/features/runs/ui/run_detail_view.dart b/app/lib/features/runs/ui/run_detail_view.dart index c1bd01c5..a2814712 100644 --- a/app/lib/features/runs/ui/run_detail_view.dart +++ b/app/lib/features/runs/ui/run_detail_view.dart @@ -8,7 +8,7 @@ class RunDetailView extends StatelessWidget { @override Widget build(BuildContext context) { final run = controller.detail; - if (controller.loading && run == null) { + if (controller.detailLoading && run == null) { return const Center(child: CircularProgressIndicator()); } if (run == null) { @@ -84,7 +84,7 @@ class RunDetailView extends StatelessWidget { ), ), ), - const ListTile(title: Text('Metrics'), subtitle: Text('Unavailable')), + _section(context, 'Metrics', run['usage'] is Map ? run['usage'] as Map : const {}), ], ); } diff --git a/app/lib/features/runs/ui/runs_controller.dart b/app/lib/features/runs/ui/runs_controller.dart index 02fa8bf8..9eac5db5 100644 --- a/app/lib/features/runs/ui/runs_controller.dart +++ b/app/lib/features/runs/ui/runs_controller.dart @@ -10,12 +10,19 @@ class RunsController extends ChangeNotifier { final RunsRepository repository; StreamSubscription? _subscription; List runs = []; - JsonMap? detail; + JsonMap? detail, usage; String? error; - bool loading = false; - String query = '', sort = 'newest_first'; + bool loading = false, detailLoading = false; + String query = '', + sort = 'newest_first', + scheduled = 'any', + timeRange = 'any_time'; + final Set statuses = {}; + int? pipelineId; int _selection = 0; + num? _selectedId; Timer? _refresh; + bool _refreshInFlight = false, _refreshAgain = false, _disposed = false; void listen(Stream frames) { _subscription?.cancel(); @@ -31,13 +38,18 @@ class RunsController extends ChangeNotifier { notifyListeners(); try { final result = await repository.listRuns(); - if (token != _selection) return; + if (_disposed || token != _selection) return; runs = result.runs; - if (initialId != null) await select(initialId); + usage = result.usage; + if (initialId != null) { + // Keep list and detail request generations independent: selecting the + // initial row must not make this list request's completion stale. + await select(initialId); + } } catch (e) { - if (token == _selection) error = '$e'; + if (!_disposed && token == _selection) error = '$e'; } - if (token == _selection) { + if (!_disposed && token == _selection) { loading = false; notifyListeners(); } @@ -45,25 +57,33 @@ class RunsController extends ChangeNotifier { Future select(num id) async { final token = ++_selection; - detail = null; + _refresh?.cancel(); + _refresh = null; + _refreshAgain = false; + _selectedId = id; + detailLoading = true; error = null; - loading = true; notifyListeners(); try { final value = await repository.getRun(id); - if (token == _selection) detail = value; + if (!_disposed && token == _selection) detail = value; } catch (e) { - if (token == _selection) error = '$e'; + if (!_disposed && token == _selection) error = '$e'; } - if (token == _selection) { - loading = false; + if (!_disposed && token == _selection) { + detailLoading = false; notifyListeners(); } } void back() { ++_selection; + _selectedId = null; + _refresh?.cancel(); + _refresh = null; + _refreshAgain = false; detail = null; + detailLoading = false; error = null; notifyListeners(); } @@ -73,24 +93,118 @@ class RunsController extends ChangeNotifier { notifyListeners(); } + void setStatus(String? value) { + if (value == null) { + statuses.clear(); + } else if (!statuses.add(value)) { + statuses.remove(value); + } + notifyListeners(); + } + + void setPipeline(int? value) { + pipelineId = value; + notifyListeners(); + } + + void setScheduled(String value) { + scheduled = value; + notifyListeners(); + } + + void setSort(String value) { + sort = value; + notifyListeners(); + } + void _event(JsonMap frame) { final folded = foldRunEvent(runs, frame); runs = folded.runs; if (detail?['id'] == frame['run_id']) { detail = foldRunEventDetail(detail, frame); } - if (detail != null && runDetailNeedsFullSync(frame)) { - _refresh?.cancel(); - _refresh = Timer( - const Duration(milliseconds: 150), - () => select(detail!['id'] as num), - ); + if (frame['run_id'] == null || folded.needsResync) { + _scheduleListRefresh(); + } + if (_selectedId != null && + frame['run_id'] == _selectedId && + (folded.needsResync || runDetailNeedsFullSync(frame))) { + if (_refreshInFlight) { + _refreshAgain = true; + } else { + _refresh?.cancel(); + final id = _selectedId!; + final generation = _selection; + _refresh = Timer( + const Duration(milliseconds: 150), + () => _refreshDetail(id, generation), + ); + } } notifyListeners(); } + void _scheduleListRefresh() { + if (_disposed || loading) return; + loading = true; + notifyListeners(); + unawaited(_reloadList()); + } + + Future _reloadList() async { + try { + final result = await repository.listRuns(); + if (_disposed) return; + runs = result.runs; + usage = result.usage; + error = null; + } catch (e) { + if (!_disposed) error = '$e'; + } finally { + if (!_disposed) { + loading = false; + notifyListeners(); + } + } + } + + Future _refreshDetail(num id, int generation) async { + if (_disposed || generation != _selection || _selectedId != id) return; + _refreshInFlight = true; + try { + final value = await repository.getRun(id); + if (!_disposed && generation == _selection && _selectedId == id) { + detail = value; + notifyListeners(); + } + } catch (e) { + if (!_disposed && generation == _selection && _selectedId == id) { + error = '$e'; + notifyListeners(); + } + } finally { + _refreshInFlight = false; + if (!_disposed && + _refreshAgain && + generation == _selection && + _selectedId == id) { + _refreshAgain = false; + _refresh = Timer( + const Duration(milliseconds: 150), + () => _refreshDetail(id, generation), + ); + } + } + } + List get visibleRuns => sortRuns( - runs + filterRuns( + runs, + statuses: statuses, + pipelineId: pipelineId, + scheduled: scheduled, + timeRange: timeRange, + ) .where( (r) => '${r['title'] ?? r['name'] ?? ''}'.toLowerCase().contains( query.toLowerCase(), @@ -99,8 +213,10 @@ class RunsController extends ChangeNotifier { .toList(), sort: sort, ); + @override void dispose() { + _disposed = true; _subscription?.cancel(); _refresh?.cancel(); super.dispose(); diff --git a/app/lib/features/runs/ui/runs_list.dart b/app/lib/features/runs/ui/runs_list.dart index 9ab2d1b8..f168ab89 100644 --- a/app/lib/features/runs/ui/runs_list.dart +++ b/app/lib/features/runs/ui/runs_list.dart @@ -27,6 +27,8 @@ class RunsList extends StatelessWidget { } return Column( children: [ + if (controller.usage != null) + Padding(padding: const EdgeInsets.symmetric(horizontal: 16), child: Text('Usage: ${controller.usage}')), if (controller.error != null) MaterialBanner( content: Text(controller.error!), @@ -44,6 +46,12 @@ class RunsList extends StatelessWidget { onChanged: controller.setQuery, ), ), + Wrap(spacing: 8, children: [ + DropdownButton(value: controller.sort, onChanged: (v) { if (v != null) controller.setSort(v); }, items: const [DropdownMenuItem(value: 'newest_first', child: Text('Newest')), DropdownMenuItem(value: 'oldest_first', child: Text('Oldest')), DropdownMenuItem(value: 'pipeline_name', child: Text('Pipeline')), DropdownMenuItem(value: 'status', child: Text('Status'))]), + DropdownButton(value: controller.scheduled, onChanged: (v) { if (v != null) controller.setScheduled(v); }, items: const [DropdownMenuItem(value: 'any', child: Text('Any schedule')), DropdownMenuItem(value: 'scheduled', child: Text('Scheduled')), DropdownMenuItem(value: 'unscheduled', child: Text('Unscheduled'))]), + for (final status in ['queued', 'running', 'waiting', 'succeeded', 'failed']) + FilterChip(label: Text(status), selected: controller.statuses.contains(status), onSelected: (_) => controller.setStatus(status)), + ]), Expanded( child: controller.visibleRuns.isEmpty ? const Center(child: Text('No runs found.')) diff --git a/app/notes/R1a.md b/app/notes/R1a.md new file mode 100644 index 00000000..b43992bd --- /dev/null +++ b/app/notes/R1a.md @@ -0,0 +1,7 @@ +# R1a — runs controller correctness + +Implemented in `runs_controller.dart`: selection requests now retain prior detail while loading and ignore stale/disposed replies; list and detail loading indicators are independent; Back invalidates selection and cancels scheduled refresh; selected-run refreshes use captured ID/generation and preserve detail until the reply; identity-less or unresolvable run events trigger list resynchronization. + +Added six fake-gateway regression tests in `test/features/runs/ui/runs_controller_test.dart` for stale selection, pending futures after disposal, Back cancellation, unrelated events, identity-less list resync, and full-refresh detail retention. + +Verification: `flutter test test/features/runs/ui` passed (6 tests), `flutter analyze` passed with no issues, and `flutter build web` passed. Cupertino UI/browser evidence is outside this R1a slice and remains incomplete for the overall R1 task; mobile is unverified. diff --git a/app/test/features/runs/ui/runs_controller_test.dart b/app/test/features/runs/ui/runs_controller_test.dart new file mode 100644 index 00000000..3b764422 --- /dev/null +++ b/app/test/features/runs/ui/runs_controller_test.dart @@ -0,0 +1,132 @@ +import 'dart:async'; + +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/ui/runs_controller.dart'; + +class FakeGateway implements ApiGateway { + final framesController = StreamController.broadcast(); + final lists = >[]; + final details = >>{}; + int listCalls = 0; + @override + Stream get frames => framesController.stream; + @override + Future call(String type, [JsonMap fields = const {}]) { + if (type == 'list_runs') { + listCalls++; + final request = Completer(); + lists.add(request); + return request.future; + } + final id = fields['run_id'] as num; + final request = Completer(); + details.putIfAbsent(id, () => []).add(request); + return request.future; + } + + void listReply(int index, List runs) => + lists[index].complete({'runs': runs}); + void detailReply(num id, int index, JsonMap value) => + details[id]![index].complete({'run_detail': value}); +} + +void main() { + late FakeGateway gateway; + late RunsController controller; + var disposed = false; + setUp(() { + gateway = FakeGateway(); + controller = RunsController(RunsRepository(gateway)); + disposed = false; + }); + tearDown(() { + if (!disposed) controller.dispose(); + gateway.framesController.close(); + }); + + test('late selection response cannot replace latest selection', () async { + final first = controller.select(1); + final second = controller.select(2); + gateway.detailReply(2, 0, {'id': 2}); + await second; + gateway.detailReply(1, 0, {'id': 1}); + await first; + expect(controller.detail?['id'], 2); + }); + + test('pending load and selection futures are safe after dispose', () async { + final load = controller.load(); + final select = controller.select(1); + controller.dispose(); + disposed = true; + gateway.listReply(0, []); + gateway.detailReply(1, 0, {'id': 1}); + await Future.wait([load, select]); + }); + + test('Back cancels scheduled detail refresh', () async { + final select = controller.select(1); + gateway.detailReply(1, 0, {'id': 1, 'status': 'running'}); + await select; + controller.listen(gateway.frames); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 1, + 'status': 'succeeded', + }); + controller.back(); + await Future.delayed(const Duration(milliseconds: 220)); + expect(gateway.details[1], hasLength(1)); + expect(controller.detail, isNull); + }); + + test('unrelated run event does not refresh selected detail', () async { + final select = controller.select(1); + gateway.detailReply(1, 0, {'id': 1, 'status': 'running'}); + await select; + controller.listen(gateway.frames); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 2, + 'status': 'succeeded', + }); + await Future.delayed(const Duration(milliseconds: 220)); + expect(gateway.details[1], hasLength(1)); + }); + + test('identity-less event reloads list', () async { + controller.listen(gateway.frames); + gateway.framesController.add({'type': 'run_event', 'status': 'running'}); + await Future.delayed(Duration.zero); + expect(gateway.listCalls, 1); + gateway.listReply(0, [ + {'id': 3}, + ]); + await Future.delayed(Duration.zero); + expect(controller.runs.single['id'], 3); + expect(controller.loading, isFalse); + }); + + test( + 'full refresh is coalesced and keeps current detail until reply', + () async { + final select = controller.select(1); + gateway.detailReply(1, 0, {'id': 1, 'status': 'running'}); + await select; + controller.listen(gateway.frames); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 1, + 'status': 'succeeded', + }); + await Future.delayed(const Duration(milliseconds: 180)); + expect(controller.detail?['id'], 1); + expect(gateway.details[1], hasLength(2)); + gateway.detailReply(1, 1, {'id': 1, 'status': 'succeeded'}); + await Future.delayed(Duration.zero); + expect(controller.detail?['status'], 'succeeded'); + }, + ); +}