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

217 lines
8.0 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_ack_sync.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.
///
/// With a [sync], dismissals are shared with every device: Dismiss and Clear
/// all are also acknowledged to the server, and identities dismissed elsewhere
/// (the server's set and pushed deltas) are folded in and cached locally, so
/// the local store doubles as the offline copy.
class AttentionController extends ChangeNotifier {
AttentionController({
required this.store,
this.sync,
DateTime Function()? now,
}) : _now = now ?? DateTime.now {
sync?.addListener(_syncChanged);
}
final AttentionStore store;
final AttentionAckSync? sync;
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();
_syncChanged();
}
/// Folds identities acknowledged on any device into this set. A change is
/// cached in the local store; nothing is sent back to the server.
void _syncChanged() {
final shared = sync?.acks.dismissed;
if (_disposed || !_loaded || shared == null) return;
if (_dismissed.containsAll(shared)) return;
unawaited(_commit({..._dismissed, ...shared}));
}
/// 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;
frame = runEventPayload(frame);
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) {
_share([entry.key]);
return _commit(attentionDismiss(_dismissed, entry.key));
}
/// Applies only the identities captured when the sheet opened.
Future<bool> clearAll(Iterable<AttentionEntry> snapshot) {
final entries = snapshot.toList();
_share([for (final entry in entries) entry.key]);
return _commit(attentionDismissAll(_dismissed, entries));
}
/// Acknowledges [keys] to every device. The sync queues them while offline,
/// and sending never blocks or fails the local dismissal.
void _share(List<String> keys) {
final shared = sync;
if (_disposed || shared == null || keys.isEmpty) return;
unawaited(shared.acknowledge(dismissed: keys));
}
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;
sync?.removeListener(_syncChanged);
super.dispose();
}
}