Files
pipelines/app/lib/features/runs/ui/runs_controller.dart
T
alan 3b996bdbc7 Share one minute clock across time labels and narrow shell and runs rebuilds
Relative-time labels follow one wall-minute RelativeTimeClock instead of a
timer per row, skip ticks while their tab is offstage and rebuild only when
their text changes. The shell rebuilds its top bar only for the focused
destination's published bar and its tab bar only for badge changes. Run
events that repeat a row's state no longer notify, and the runs list filters
and sorts once per build. Adds a rebuild/timer benchmark.
2026-11-01 23:29:39 +00:00

416 lines
12 KiB
Dart

import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import '../data/runs_repository.dart';
import '../data/runs_sort_store.dart';
import '../domain/run_deletion.dart';
import '../domain/run_events.dart';
import '../domain/run_models.dart';
import 'runs_filter_options.dart';
import 'runs_selection.dart';
class RunsController extends ChangeNotifier {
RunsController(this.repository, {this.sortStore}) {
selection.addListener(notifyListeners);
unawaited(_restoreSort());
}
final RunsRepository repository;
/// Where the sort choice persists; null keeps it for this controller only.
final RunsSortStore? sortStore;
/// Multi-select for deletion and the last deletion report.
final RunsSelection selection = RunsSelection();
/// Called when the open run was deleted (here or by another client) and its
/// detail closed, so the host can return its route to the list.
VoidCallback? onOpenRunRemoved;
/// Deleted run ids never return: a list read already in flight when the
/// deletion landed must not bring a row back.
final Set<int> _removed = {};
bool _sortChosen = false;
StreamSubscription<JsonMap>? _subscription;
List<JsonMap> runs = [];
JsonMap? detail, usage;
String? error;
bool loading = false, detailLoading = false;
String query = '',
sort = 'newest_first',
scheduled = 'any',
timeRange = 'any_time';
final Set<String> 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<JsonMap> frames) {
_subscription?.cancel();
_subscription = frames.listen((frame) {
switch (frame['type']) {
case 'run_event':
_event(frame);
case 'runs_removed':
// Another client deleted these runs.
removeRuns(removedRunIds(frame));
}
});
}
Future<void> load([int? initialId]) async {
final token = ++_listGeneration;
_listAgain = false;
loading = true;
error = null;
notifyListeners();
try {
final result = await repository.listRuns();
if (!_listOwned(token)) return;
_setRuns(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<void> resync() async {
final selected = _selectedId;
await load();
if (selected != null && _selectedId == selected) await select(selected);
}
Future<void> 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) {
_sortChosen = true;
sort = value;
notifyListeners();
unawaited(sortStore?.write(value));
}
/// Applies the saved sort unless the operator already chose one.
Future<void> _restoreSort() async {
final saved = await sortStore?.read();
if (_disposed || _sortChosen || saved == null || saved == sort) return;
if (!runSorts.any((option) => option.$1 == saved)) return;
sort = saved;
notifyListeners();
}
void _setRuns(List<JsonMap> value) {
runs = _removed.isEmpty
? value
: value.where((run) => !_removed.contains(run['id'])).toList();
selection.retain(runs);
}
/// Drops deleted runs from the list and the selection, and closes the open
/// detail when it showed one of them.
void removeRuns(Iterable<int> ids) {
final gone = ids.toSet();
if (gone.isEmpty) return;
_removed.addAll(gone);
final before = runs.length;
runs = runs.where((run) => !gone.contains(run['id'])).toList();
var changed = runs.length != before;
selection.retain(runs);
final open = _selectedId;
if (open != null && gone.contains(open)) {
back();
onOpenRunRemoved?.call();
changed = false; // back() already notified.
}
if (changed) notifyListeners();
}
/// Applies the server's `runs_deleted` reply: removes what it deleted and
/// records the report (including refusals) for the list.
void applyDeletion(RunsDeletion deletion) {
removeRuns(deletion.deleted);
selection.applied(deletion);
}
/// 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) {
if (_removed.contains(frame['run_id'])) return;
final folded = foldRunEvent(runs, frame);
final before = (runs: runs, detail: detail);
runs = folded.runs;
selection.retain(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);
}
// A frame that changed neither the list nor the open detail shows
// nothing new; the refreshes above notify for themselves.
if (identical(before.runs, runs) && identical(before.detail, detail)) {
return;
}
notifyListeners();
}
void _scheduleListRefresh() {
if (_disposed) return;
if (_listResyncing || loading) {
_listAgain = true;
return;
}
_listResyncing = true;
loading = true;
notifyListeners();
unawaited(_reloadList());
}
Future<void> _reloadList() async {
final token = ++_listGeneration;
_listAgain = false;
try {
final result = await repository.listRuns();
if (!_listOwned(token)) return;
_setRuns(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<void> _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<JsonMap> 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;
selection.removeListener(notifyListeners);
selection.dispose();
_subscription?.cancel();
_detailRefresh?.cancel();
super.dispose();
}
}