import 'dart:async'; import 'package:flutter/foundation.dart'; import '../../../core/api_gateway.dart'; import '../data/runs_repository.dart'; import '../domain/run_events.dart'; import '../domain/run_models.dart'; class RunsController extends ChangeNotifier { RunsController(this.repository); final RunsRepository repository; StreamSubscription? _subscription; List runs = []; JsonMap? detail, usage; String? error; bool loading = false, detailLoading = false; String query = '', sort = 'newest_first', scheduled = 'any', timeRange = 'any_time'; final Set statuses = {}; int? pipelineId; // List and detail requests advance independent generations so neither can // make the other's in-flight reply stale. int _listGeneration = 0, _detailGeneration = 0; num? _selectedId; Timer? _detailRefresh; bool _listResyncing = false, _listAgain = false; bool _detailRefreshing = false, _detailAgain = false; bool _disposed = false; num? get selectedRunId => _selectedId; /// The number of narrowing facets, one per status set, pipeline, time range /// and trigger choice. Mirrors the browser's `runFiltersActiveCount`. int get activeFilterCount => (statuses.isNotEmpty ? 1 : 0) + (pipelineId != null ? 1 : 0) + (timeRange != 'any_time' && timeRange.isNotEmpty ? 1 : 0) + (scheduled == 'scheduled' || scheduled == 'unscheduled' ? 1 : 0); void listen(Stream frames) { _subscription?.cancel(); _subscription = frames .where((f) => f['type'] == 'run_event') .listen(_event); } Future load([int? initialId]) async { final token = ++_listGeneration; _listAgain = false; loading = true; error = null; notifyListeners(); try { final result = await repository.listRuns(); if (!_listOwned(token)) return; runs = result.runs; usage = result.usage; } catch (e) { if (!_listOwned(token)) return; error = '$e'; } if (!_listOwned(token)) return; loading = false; notifyListeners(); // A run event may have arrived while the list request was in flight; one // resync after it keeps the pushed state without dropping the event. _resyncAgainIfNeeded(); if (initialId != null) await select(initialId); } /// Re-reads the list and the open detail after the socket was replaced. /// /// The selection is kept, so a reconnect refreshes in place instead of /// discarding the detail the operator had open. Future resync() async { final selected = _selectedId; await load(); if (selected != null && _selectedId == selected) await select(selected); } Future select(num id) async { final token = ++_detailGeneration; _cancelDetailRefresh(); // Keep a same-run detail while it refreshes, but never present the previous // run as if it were the newly selected one. if (_selectedId != id) detail = null; _selectedId = id; detailLoading = true; error = null; notifyListeners(); try { final value = await repository.getRun(id); if (!_detailOwned(id, token)) return; detail = value; } catch (e) { if (!_detailOwned(id, token)) return; error = '$e'; } if (!_detailOwned(id, token)) return; detailLoading = false; notifyListeners(); } void back() { ++_detailGeneration; _cancelDetailRefresh(); _selectedId = null; detail = null; detailLoading = false; error = null; notifyListeners(); } /// Folds the server's accepted run detail into the open detail and the /// matching list row, mirroring the web's `applyRunTitle`. /// /// A reply for a run that is no longer selected never replaces the open /// detail; no title or other field is invented locally. void acceptRunDetail(JsonMap run) { final id = run['id']; if (id == null) return; var changed = false; if (detail?['id'] == id) { ++_detailGeneration; _cancelDetailRefresh(); detail = run; detailLoading = false; error = null; changed = true; } final index = runs.indexWhere((row) => row['id'] == id); if (index >= 0) { // A cancel/decision reply changes lifecycle fields as well as title. // Keep sparse/unknown summary fields, without copying bulky detail-only // payloads into the held list or inventing missing values. const detailOnly = { 'steps', 'input', 'output', 'graph', 'usage', 'notifications', }; runs = [...runs] ..[index] = { ...runs[index], for (final entry in run.entries) if (!detailOnly.contains(entry.key)) entry.key: entry.value, }; changed = true; } if (changed) notifyListeners(); } void setQuery(String value) { query = value; 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 setTimeRange(String value) { timeRange = value; notifyListeners(); } void setSort(String value) { sort = value; notifyListeners(); } /// Returns every filter to its default, like the browser's `Clear filters`. void clearFilters() { statuses.clear(); pipelineId = null; timeRange = 'any_time'; scheduled = 'any'; notifyListeners(); } void _event(JsonMap frame) { final folded = foldRunEvent(runs, frame); runs = folded.runs; if (detail?['id'] == frame['run_id']) { detail = foldRunEventDetail(detail, frame); } if (frame['run_id'] == null || folded.needsResync) { _scheduleListRefresh(); } final selected = _selectedId; if (selected != null && frame['run_id'] == selected && (folded.needsResync || runDetailNeedsFullSync(frame))) { _scheduleDetailRefresh(selected); } notifyListeners(); } void _scheduleListRefresh() { if (_disposed) return; if (_listResyncing || loading) { _listAgain = true; return; } _listResyncing = true; loading = true; notifyListeners(); unawaited(_reloadList()); } Future _reloadList() async { final token = ++_listGeneration; _listAgain = false; try { final result = await repository.listRuns(); if (!_listOwned(token)) return; runs = result.runs; usage = result.usage; error = null; } catch (e) { if (_listOwned(token)) error = '$e'; } finally { _listResyncing = false; if (_listOwned(token)) { loading = false; notifyListeners(); } // A followup may have been requested while this (possibly superseded) // request was still the one marked in flight. _resyncAgainIfNeeded(); } } void _resyncAgainIfNeeded() { if (_disposed || !_listAgain) return; _listAgain = false; _scheduleListRefresh(); } void _scheduleDetailRefresh(num id) { if (_disposed || _selectedId != id) return; if (_detailRefreshing) { _detailAgain = true; return; } _detailRefresh?.cancel(); _detailRefresh = Timer( const Duration(milliseconds: 150), () => _refreshDetail(id, _detailGeneration), ); } Future _refreshDetail(num id, int token) async { _detailRefresh = null; if (!_detailOwned(id, token)) return; _detailRefreshing = true; try { final value = await repository.getRun(id); if (_detailOwned(id, token)) { detail = value; notifyListeners(); } } catch (e) { if (_detailOwned(id, token)) { error = '$e'; notifyListeners(); } } finally { if (_detailOwned(id, token)) { _detailRefreshing = false; if (_detailAgain) { _detailAgain = false; unawaited(_refreshDetail(id, token)); } } } } void _cancelDetailRefresh() { _detailRefresh?.cancel(); _detailRefresh = null; _detailAgain = false; _detailRefreshing = false; } bool _listOwned(int token) => !_disposed && token == _listGeneration; bool _detailOwned(num id, int token) => !_disposed && token == _detailGeneration && _selectedId == id; List get visibleRuns => sortRuns( filterRuns( runs, statuses: statuses, pipelineId: pipelineId, scheduled: scheduled, timeRange: timeRange, ) .where( (r) => '${r['title'] ?? r['name'] ?? ''}'.toLowerCase().contains( query.toLowerCase(), ), ) .toList(), sort: sort, ); @override void dispose() { _disposed = true; _subscription?.cancel(); _detailRefresh?.cancel(); super.dispose(); } }