import 'package:flutter/foundation.dart'; import 'pipeline_models.dart'; import 'pipeline_query.dart'; import 'pipeline_repository.dart'; import 'run_pipeline_intent.dart'; import 'pending_run_store.dart'; /// The user-facing message for a request failure, keeping server refusals /// verbatim and removing only the generic `Exception:` prefix. String pipelineErrorMessage(Object error) { if (error is PipelineRequestException) return error.message; final text = error.toString(); return text.startsWith('Exception: ') ? text.substring(11) : text; } /// Owns the pipeline list/detail state. The screen only renders this object; /// every request is sequenced here so a late reply can never replace a newer /// selection. class PipelinesController extends ChangeNotifier { PipelinesController(this._repository, {PendingRunStore? pendingRunStore}) : _pendingRunStore = pendingRunStore ?? const SharedPreferencesPendingRunStore(''); final PipelinesRepository _repository; final PendingRunStore _pendingRunStore; final Set _loadedPendingRuns = {}; final Map _pendingRunGenerations = {}; List _pipelines = const []; List _runs = const []; PipelineFilters _filters = emptyPipelineFilters; PipelineSort _sort = PipelineSort.serverOrder; int? _selectedId; int _selectedVersion = 0; PipelineDetail? _detail; bool _listLoading = false; bool _pipelinesLoaded = false; bool _runsLoaded = false; String? _listError; String? _runsError; bool _detailLoading = false; String? _detailError; int _listSequence = 0; int _runsSequence = 0; int _detailSequence = 0; bool _disposed = false; List? _latestSource; Map? _latestCache; /// Launch intents whose reply never arrived, keyed by pinned identity. /// /// Kept per pipeline/version like the browser's sessionStorage intent, so a /// dialog reopened in this session still offers check/retry with the same /// request key instead of minting a possible duplicate. final Map _pendingRuns = {}; List get pipelines => _pipelines; PipelineFilters get filters => _filters; PipelineSort get sort => _sort; bool get listLoading => _listLoading; bool get pipelinesLoaded => _pipelinesLoaded; bool get runsLoaded => _runsLoaded; String? get listError => _listError; String? get runsError => _runsError; bool get detailLoading => _detailLoading; String? get detailError => _detailError; PipelineDetail? get detail => _detail; int? get selectedId => _selectedId; int get selectedVersion => _selectedVersion; bool get hasSelection => _selectedId != null; bool get initialListLoading => _listLoading && !_pipelinesLoaded; Map get latestRuns { final cache = _latestCache; if (cache != null && identical(_latestSource, _runs)) return cache; _latestSource = _runs; return _latestCache = latestRunByPipeline(_runs); } /// The rows after sorting and filtering, using the same pure rules as web. List get visiblePipelines { final runs = latestRuns; final sorted = sortPipelines(_pipelines, _sort, runs); return filterPipelines(sorted, _filters, runs, _runsLoaded); } PipelineEmptyState? get emptyState => pipelineListEmptyState(_pipelines, visiblePipelines, _filters); /// Reloads the list and runs and re-reads the current detail. The selection /// (pipeline id and requested version) is deliberately preserved. Future load() async { final listToken = ++_listSequence; final runsToken = ++_runsSequence; _listLoading = true; _listError = null; _runsError = null; _notify(); await Future.wait([_readList(listToken), _readRuns(runsToken)]); if (_selectedId != null) await _reloadDetail(); } Future _readList(int token) async { try { final rows = await _repository.listPipelines(); if (!_current(_listSequence, token)) return; _pipelines = rows; _pipelinesLoaded = true; _listError = null; } catch (error) { if (!_current(_listSequence, token)) return; _listError = pipelineErrorMessage(error); } finally { if (_current(_listSequence, token)) { _listLoading = false; _notify(); } } } Future _readRuns(int token) async { try { final runs = await _repository.listRuns(); if (!_current(_runsSequence, token)) return; _runs = runs; _runsLoaded = true; _runsError = null; } catch (error) { if (!_current(_runsSequence, token)) return; // Retain any previously successful run history: a failed refresh must // not silently change the meaning of an active last-run filter. _runsError = pipelineErrorMessage(error); } if (_current(_runsSequence, token)) _notify(); } /// Opens [id] at [version] (0 asks for latest), discarding the previous /// detail immediately so no unrelated entity sits under the new selection. Future openPipeline(int id, {int version = 0}) async { final requestedVersion = version > 0 ? version : 0; _selectedId = id; _selectedVersion = requestedVersion; _detail = null; _detailError = null; await _requestDetail(id, requestedVersion); } /// Selects a recorded version by its version number; 0 returns to latest. Future selectVersion(int version) async { final id = _selectedId; if (id == null) return; await openPipeline(id, version: version); } Future retryDetail() async { final id = _selectedId; if (id == null) return; await _requestDetail(id, _selectedVersion); } Future _reloadDetail() async { final id = _selectedId; if (id == null) return; await _requestDetail(id, _selectedVersion); } Future _requestDetail(int id, int version) async { final token = ++_detailSequence; _detailLoading = true; _detailError = null; _notify(); try { final detail = await _repository.getPipeline(id, version); if (!_currentDetail(token, id, version)) return; _detail = detail; _detailError = null; } catch (error) { if (!_currentDetail(token, id, version)) return; _detail = null; _detailError = pipelineErrorMessage(error); } finally { if (_currentDetail(token, id, version)) { _detailLoading = false; _notify(); } } } /// Clears the selection for narrow-layout Back and for an explicit close. void clearSelection() { _detailSequence++; _selectedId = null; _selectedVersion = 0; _detail = null; _detailError = null; _detailLoading = false; _notify(); } void setFilters(PipelineFilters filters) { _filters = filters; _notify(); } void clearFilters() { _filters = emptyPipelineFilters; _notify(); } void setSort(PipelineSort sort) { _sort = sort; _notify(); } /// The unresolved launch for one pinned definition, read from the device /// store first, so the Run dialog opened right after a reload offers the /// same request key instead of minting a new one. Future loadPendingRun(int pipelineId, int version) async { final key = '$pipelineId@$version'; if (_loadedPendingRuns.add(key)) { final generation = _pendingRunGenerations[key] ?? 0; final intent = await _pendingRunStore.read(pipelineId, version); if (!_disposed && (_pendingRunGenerations[key] ?? 0) == generation && intent != null) { _pendingRuns[key] = intent; } } return _pendingRuns[key]; } /// The unresolved launch for one pinned definition, if any. RunPipelineIntent? pendingRunFor(int pipelineId, int version) { final key = '$pipelineId@$version'; if (!_loadedPendingRuns.contains(key)) { _loadedPendingRuns.add(key); final generation = _pendingRunGenerations[key] ?? 0; _pendingRunStore.read(pipelineId, version).then((intent) { if (_disposed || (_pendingRunGenerations[key] ?? 0) != generation) { return; } if (intent != null) _pendingRuns[key] = intent; _notify(); }); } return _pendingRuns[key]; } /// Remembers an intent whose admission is unknown, or clears it once the /// server's truth is known. void rememberPendingRun(RunPipelineIntent intent) { final key = '${intent.pipelineId}@${intent.version}'; _pendingRunGenerations.update( key, (generation) => generation + 1, ifAbsent: () => 1, ); _pendingRuns[key] = intent; _pendingRunStore.write(intent); } void clearPendingRun(int pipelineId, int version) { final key = '$pipelineId@$version'; _pendingRunGenerations.update( key, (generation) => generation + 1, ifAbsent: () => 1, ); _pendingRuns.remove(key); _pendingRunStore.remove(pipelineId, version); } bool _current(int sequence, int token) => !_disposed && sequence == token; bool _currentDetail(int token, int id, int version) => !_disposed && token == _detailSequence && id == _selectedId && version == _selectedVersion; void _notify() { if (!_disposed) notifyListeners(); } @override void dispose() { _disposed = true; super.dispose(); } }