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 _transitions = []; List _rows = const []; Set _dismissed = {}; bool _loaded = false; bool _dirty = false; bool _disposed = false; /// The summaries the surface currently draws from. List get rows => _rows; /// The identities the operator has dismissed in this session or storage. Set 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 get transitions => List.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 get entries => entriesSince(startOfLocalDay(now: _now())); /// The ordered rows within an explicit [since] window. List entriesSince(DateTime? since) => attentionEntries(_rows, dismissed: _dismissed, since: since); /// Reads the persisted dismissals once. Unreadable storage means "none". Future load() async { Set stored; try { stored = decodeAttentionDismissals(await store.read()); } catch (_) { stored = {}; } 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 rows, {bool reconnect = false}) { if (_disposed) return; _rows = List.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.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 _withAttentionText(List 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 = {...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 dismiss(AttentionEntry entry) => _commit(attentionDismiss(_dismissed, entry.key)); /// Applies only the identities captured when the sheet opened. Future clearAll(Iterable snapshot) => _commit(attentionDismissAll(_dismissed, snapshot)); Future _commit(Set 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(); } }