Files
pipelines/app/lib/features/attention/runtime/attention_controller.dart
T

180 lines
6.7 KiB
Dart

import 'dart:async';
import 'package:flutter/foundation.dart';
import '../../../core/api_gateway.dart';
import '../../runs/domain/run_events.dart';
import '../domain/attention_models.dart';
import '../domain/attention_transitions.dart';
import 'attention_store.dart';
/// The live `Needs you` state behind the Runs-list bell.
///
/// Entries are derived from the same `list_runs` rows the Runs destination
/// already holds: no poll and no extra request is made here. Pushed
/// `run_event` frames are folded with the runs feature's own [foldRunEvent], so
/// a run that becomes failed or waiting while the screen is open appears without
/// a reload, exactly as the browser's attention surface does.
///
/// Dismissals are kept in memory for immediate feedback and written through
/// [AttentionStore] without blocking the caller. A failed read or write leaves
/// the in-memory set in force for this session; neither direction can throw into
/// the UI.
class AttentionController extends ChangeNotifier {
AttentionController({required this.store, DateTime Function()? now})
: _now = now ?? DateTime.now;
final AttentionStore store;
final DateTime Function() _now;
final AttentionTransitionDetector _detector = AttentionTransitionDetector();
final List<AttentionTransition> _transitions = [];
List<JsonMap> _rows = const [];
Set<String> _dismissed = <String>{};
bool _loaded = false;
bool _dirty = false;
bool _disposed = false;
/// The summaries the surface currently draws from.
List<JsonMap> get rows => _rows;
/// The identities the operator has dismissed in this session or storage.
Set<String> get dismissed => {..._dismissed};
/// True once the persisted set has been read (successfully or not).
bool get loaded => _loaded;
/// Transition facts raised by pushed frames, kept for notification wiring.
List<AttentionTransition> get transitions =>
List<AttentionTransition>.unmodifiable(_transitions);
/// Today's ordered rows, minus explicitly dismissed identities.
///
/// The local-day cutoff is the model's [startOfLocalDay]: yesterday's failures
/// are history, not a badge that follows every device for ever. A caller that
/// needs a different window should use [entriesSince] rather than a second
/// ordering implementation.
List<AttentionEntry> get entries =>
entriesSince(startOfLocalDay(now: _now()));
/// The ordered rows within an explicit [since] window.
List<AttentionEntry> entriesSince(DateTime? since) =>
attentionEntries(_rows, dismissed: _dismissed, since: since);
/// Reads the persisted dismissals once. Unreadable storage means "none".
Future<void> load() async {
Set<String> stored;
try {
stored = decodeAttentionDismissals(await store.read());
} catch (_) {
stored = <String>{};
}
if (_disposed) return;
_loaded = true;
// A dismissal made while the read was in flight must not be reverted by the
// older stored value; the in-memory set is the operator's latest intent.
if (!_dirty) _dismissed = stored;
notifyListeners();
}
/// Replaces the drawn rows with an authoritative read.
///
/// The transition detector is seeded rather than observed, so the initial list
/// and a reconnect cannot announce work that was already there. With
/// [reconnect] the status baseline is dropped first, while emitted keys are
/// retained by the model so the gap cannot re-notify.
void seedRows(Iterable<JsonMap> rows, {bool reconnect = false}) {
if (_disposed) return;
_rows = List<JsonMap>.unmodifiable(rows);
if (reconnect) {
_detector.reseed(_rows);
} else {
_detector.seed(_rows);
}
notifyListeners();
}
/// Called when the shared socket drops, before the next [seedRows].
void resetForReconnect() {
if (_disposed) return;
_detector.resetForReconnect();
}
/// Folds one pushed run summary into the drawn entries.
///
/// A frame that cannot build a complete summary asks the Runs controller for
/// its usual resync; this surface never issues a request of its own. The
/// transition (if any) is recorded for the notification wiring but a dismissed
/// identity never emits.
void observeFrame(JsonMap frame) {
if (_disposed) return;
final transition = _detector.observe(frame, dismissed: _dismissed);
if (transition != null) _transitions.add(transition);
final folded = foldRunEvent(_rows, frame);
final changed = !folded.needsResync && !identical(folded.runs, _rows);
if (changed) {
_rows = List<JsonMap>.unmodifiable(
_withAttentionText(folded.runs, frame),
);
}
if (changed || transition != null) notifyListeners();
}
/// The runs fold deliberately carries only lifecycle fields, but the attention
/// row's wording comes from `title`/`name`/`diagnostic`. Keep those summary
/// fields from the same push so a failure announces its real reason without
/// waiting for the next list read. Only non-blank pushed values win; the source
/// or other unknown fields are left untouched.
List<JsonMap> _withAttentionText(List<JsonMap> rows, JsonMap frame) {
final id = frame['run_id'];
final index = rows.indexWhere((row) => row['id'] == id);
if (index < 0) return rows;
final current = rows[index];
final merged = <String, dynamic>{...current};
var changed = false;
for (final key in const ['title', 'name', 'diagnostic']) {
final value = frame[key];
if ('${value ?? ''}'.trim().isEmpty || value == current[key]) continue;
merged[key] = value;
changed = true;
}
if (!changed) return rows;
final next = [...rows];
next[index] = merged;
return next;
}
/// Dismisses exactly one identity and persists the new set.
///
/// The in-memory set and the bell update before the store is touched, so a
/// slow or failed write never blocks the sheet. The returned future reports
/// whether the write succeeded; callers that do not need it may ignore it.
Future<bool> dismiss(AttentionEntry entry) =>
_commit(attentionDismiss(_dismissed, entry.key));
/// Applies only the identities captured when the sheet opened.
Future<bool> clearAll(Iterable<AttentionEntry> snapshot) =>
_commit(attentionDismissAll(_dismissed, snapshot));
Future<bool> _commit(Set<String> next) async {
final unchanged =
next.length == _dismissed.length && next.containsAll(_dismissed);
if (unchanged) return true;
_dismissed = next;
_dirty = true;
notifyListeners();
if (_disposed) return false;
try {
return await store.write(encodeAttentionDismissals(_dismissed));
} catch (_) {
return false;
}
}
@override
void dispose() {
_disposed = true;
super.dispose();
}
}