feat(app): show the live Needs-you bell over the Runs list rows

This commit is contained in:
2026-10-22 00:52:06 +01:00
parent 1835bc8832
commit a309d9d571
15 changed files with 1557 additions and 127 deletions
@@ -0,0 +1,179 @@
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();
}
}
@@ -0,0 +1,82 @@
import 'package:shared_preferences/shared_preferences.dart';
import '../domain/attention_models.dart';
/// The persistence seam for the `Needs you` dismissal identities.
///
/// The controller only ever hands over the exact string produced by
/// [encodeAttentionDismissals], so a store cannot invent a different identity
/// format. Both directions are allowed to fail: a caller treats a null read as
/// "nothing dismissed yet" and a false write as "this session only".
abstract interface class AttentionStore {
Future<String?> read();
Future<bool> write(String value);
}
/// `shared_preferences` storage under the attention model's own key.
///
/// Reads and writes are total: an unavailable plugin, a disabled store or a full
/// disk returns null/false instead of throwing into the caller's frame. Only the
/// documented [attentionStorageKey] is touched, never the legacy web key.
class SharedPreferencesAttentionStore implements AttentionStore {
const SharedPreferencesAttentionStore();
Future<SharedPreferences?> _preferences() async {
try {
return await SharedPreferences.getInstance();
} catch (_) {
return null;
}
}
@override
Future<String?> read() async {
final preferences = await _preferences();
if (preferences == null) return null;
try {
return preferences.getString(attentionStorageKey);
} catch (_) {
return null;
}
}
@override
Future<bool> write(String value) async {
final preferences = await _preferences();
if (preferences == null) return false;
try {
return await preferences.setString(attentionStorageKey, value);
} catch (_) {
return false;
}
}
}
/// An in-memory store for tests and isolated fixtures.
///
/// It never touches the platform store, so a probe or widget test cannot mutate
/// a real operator's persisted dismissals. [failReads] and [failWrites] reproduce
/// an unavailable store without throwing.
class MemoryAttentionStore implements AttentionStore {
MemoryAttentionStore({this.stored});
String? stored;
bool failReads = false;
bool failWrites = false;
int writes = 0;
@override
Future<String?> read() async {
if (failReads) throw StateError('attention store unavailable');
return stored;
}
@override
Future<bool> write(String value) async {
writes++;
if (failWrites) throw StateError('attention store is read-only');
stored = value;
return true;
}
}
@@ -0,0 +1,118 @@
import 'dart:async';
import 'package:flutter/widgets.dart';
import '../../../core/api_gateway.dart';
import '../domain/attention_models.dart';
import '../runtime/attention_controller.dart';
import '../runtime/attention_store.dart';
import 'needs_you_bell.dart';
/// The `Needs you` bell as it appears in the Runs list heading.
///
/// It owns the live attention state for this destination: [rows] are the
/// already-loaded `list_runs` summaries and [frames] is the shared gateway's
/// unsolicited stream, so it never polls or issues an attention request. The
/// bell has no built-in host choice; the ambient app host (or [cupertino] in a
/// fixture) selects the native Material or Cupertino action and sheet.
class NeedsYouRunsHeading extends StatefulWidget {
const NeedsYouRunsHeading({
super.key,
required this.rows,
required this.frames,
required this.onOpen,
this.syncToken = 0,
this.store = const SharedPreferencesAttentionStore(),
this.now,
this.cupertino,
});
/// The run summaries the Runs destination already holds.
final List<JsonMap> rows;
/// The shared gateway's frames; only `run_event` envelopes are folded.
final Stream<JsonMap> frames;
/// Opens an entry's run. A Failed entry is dismissed by the bell first.
final ValueChanged<AttentionEntry> onOpen;
/// Advances when the shared socket is replaced. The detector rebaselines
/// without replaying a transition that happened during the gap.
final int syncToken;
final AttentionStore store;
/// Injected clock for deterministic local-day windows.
final DateTime Function()? now;
/// Forces the native host in tests and fixtures.
final bool? cupertino;
@override
State<NeedsYouRunsHeading> createState() => _NeedsYouRunsHeadingState();
}
class _NeedsYouRunsHeadingState extends State<NeedsYouRunsHeading> {
late final AttentionController _attention = AttentionController(
store: widget.store,
now: widget.now,
);
StreamSubscription<JsonMap>? _frames;
@override
void initState() {
super.initState();
_attention.seedRows(widget.rows);
unawaited(_attention.load());
_listen();
}
void _listen() {
_frames = widget.frames
.where((frame) => frame['type'] == 'run_event')
.listen(_attention.observeFrame);
}
@override
void didUpdateWidget(covariant NeedsYouRunsHeading oldWidget) {
super.didUpdateWidget(oldWidget);
if (!identical(oldWidget.frames, widget.frames)) {
unawaited(_frames?.cancel());
_frames = null;
_listen();
}
if (oldWidget.syncToken != widget.syncToken) {
_attention.resetForReconnect();
_attention.seedRows(widget.rows, reconnect: true);
return;
}
if (!identical(oldWidget.rows, widget.rows)) {
_attention.seedRows(widget.rows);
}
}
@override
void dispose() {
unawaited(_frames?.cancel());
_attention.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _attention,
builder: (context, _) => NeedsYouBell(
entries: _attention.entries,
cupertino: widget.cupertino,
onOpen: widget.onOpen,
onDismiss: (entry) {
unawaited(_attention.dismiss(entry));
},
onClearAll: (snapshot) {
unawaited(_attention.clearAll(snapshot));
},
),
);
}
}
+15 -1
View File
@@ -1,6 +1,7 @@
import 'package:flutter/widgets.dart';
import '../../core/api_gateway.dart';
import '../attention/runtime/attention_store.dart';
import 'data/runs_repository.dart';
import 'ui/run_detail_view.dart';
import 'ui/runs_controller.dart';
@@ -20,6 +21,8 @@ class RunsScreen extends StatefulWidget {
this.syncToken = 0,
this.onRunSelected,
this.onBack,
this.attentionStore = const SharedPreferencesAttentionStore(),
this.attentionNow,
});
final ApiGateway gateway;
@@ -34,6 +37,11 @@ class RunsScreen extends StatefulWidget {
final ValueChanged<int>? onRunSelected;
final VoidCallback? onBack;
/// Persisted attention dismissals and the clock for its local-day window.
/// The app uses SharedPreferences; tests and fixtures inject a memory store.
final AttentionStore attentionStore;
final DateTime Function()? attentionNow;
@override
State<RunsScreen> createState() => _RunsScreenState();
}
@@ -103,7 +111,13 @@ class _RunsScreenState extends State<RunsScreen> {
animation: controller,
builder: (context, _) => Offstage(
offstage: selected,
child: RunsList(controller: controller, onSelected: _select),
child: RunsList(
controller: controller,
onSelected: _select,
syncToken: widget.syncToken,
attentionStore: widget.attentionStore,
attentionNow: widget.attentionNow,
),
),
),
if (selected)
+138
View File
@@ -0,0 +1,138 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../../../ui/adaptive/host.dart';
import 'runs_controller.dart';
/// The runs list's native sort/schedule/status controls.
///
/// On Cupertino the controls stay in one horizontally scrollable strip: a phone
/// at a doubled text scale cannot stack seven buttons above the list without
/// crushing it, and the browser's narrow toolbar is likewise one row. Material
/// keeps its native dropdowns and filter chips.
class RunsFilters extends StatelessWidget {
const RunsFilters({super.key, required this.controller});
final RunsController controller;
@override
Widget build(BuildContext context) =>
usesCupertinoHost(context) ? _cupertino(context) : _material(context);
Widget _cupertino(BuildContext context) => SingleChildScrollView(
scrollDirection: Axis.horizontal,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
child: Row(
children: [
CupertinoButton(
onPressed: () => _choose(
context,
'Sort runs',
_sorts,
controller.sort,
controller.setSort,
),
child: Text('Sort: ${_sortLabel(controller.sort)}'),
),
const SizedBox(width: 8),
CupertinoButton(
onPressed: () => _choose(
context,
'Schedule',
_schedules,
controller.scheduled,
controller.setScheduled,
),
child: Text('Schedule: ${_scheduleLabel(controller.scheduled)}'),
),
for (final status in _statuses) ...[
const SizedBox(width: 8),
CupertinoButton(
onPressed: () => controller.setStatus(status),
child: Text(
'${controller.statuses.contains(status) ? '✓ ' : ''}${_title(status)}',
),
),
],
],
),
);
Widget _material(BuildContext context) => Wrap(
spacing: 8,
children: [
DropdownButton<String>(
value: controller.sort,
isExpanded: true,
onChanged: (v) {
if (v != null) controller.setSort(v);
},
items: _sorts
.map((e) => DropdownMenuItem(value: e.$1, child: Text(e.$2)))
.toList(),
),
DropdownButton<String>(
value: controller.scheduled,
isExpanded: true,
onChanged: (v) {
if (v != null) controller.setScheduled(v);
},
items: _schedules
.map((e) => DropdownMenuItem(value: e.$1, child: Text(e.$2)))
.toList(),
),
for (final status in _statuses)
FilterChip(
label: Text(_title(status)),
selected: controller.statuses.contains(status),
onSelected: (_) => controller.setStatus(status),
),
],
);
Future<void> _choose(
BuildContext context,
String title,
List<(String, String)> values,
String selected,
ValueChanged<String> onSelected,
) async {
final value = await showCupertinoModalPopup<String>(
context: context,
builder: (context) => CupertinoActionSheet(
title: Text(title),
actions: [
for (final option in values)
CupertinoActionSheetAction(
onPressed: () => Navigator.pop(context, option.$1),
child: Text(option.$2),
),
],
cancelButton: CupertinoActionSheetAction(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
),
);
if (value != null && value != selected) onSelected(value);
}
}
const _sorts = [
('newest_first', 'Newest'),
('oldest_first', 'Oldest'),
('pipeline_name', 'Pipeline'),
('status', 'Status'),
];
const _schedules = [
('any', 'Any schedule'),
('scheduled', 'Scheduled'),
('unscheduled', 'Unscheduled'),
];
const _statuses = ['queued', 'running', 'waiting', 'succeeded', 'failed'];
String _sortLabel(String value) =>
_sorts.firstWhere((e) => e.$1 == value, orElse: () => _sorts.first).$2;
String _scheduleLabel(String value) => _schedules
.firstWhere((e) => e.$1 == value, orElse: () => _schedules.first)
.$2;
String _title(String value) => '${value[0].toUpperCase()}${value.substring(1)}';
+31 -115
View File
@@ -3,19 +3,35 @@ import 'package:flutter/material.dart';
import '../../../core/api_gateway.dart';
import '../../../ui/adaptive/host.dart';
import '../../attention/runtime/attention_store.dart';
import '../../attention/ui/needs_you_runs_heading.dart';
import '../domain/run_models.dart';
import 'runs_controller.dart';
import 'runs_filters.dart';
class RunsList extends StatelessWidget {
const RunsList({
super.key,
required this.controller,
required this.onSelected,
this.syncToken = 0,
this.attentionStore = const SharedPreferencesAttentionStore(),
this.attentionNow,
});
final RunsController controller;
final ValueChanged<num> onSelected;
/// Advances when the shared socket is replaced, so the attention detector
/// rebaselines instead of replaying a transition from before the gap.
final int syncToken;
/// Test and fixture seam for the persisted attention dismissals.
final AttentionStore attentionStore;
/// Deterministic local-day clock for the attention window.
final DateTime Function()? attentionNow;
@override
Widget build(BuildContext context) {
if (controller.loading && controller.runs.isEmpty) {
@@ -31,6 +47,20 @@ class RunsList extends StatelessWidget {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Padding(
padding: const EdgeInsetsDirectional.fromSTEB(16, 8, 16, 0),
child: Align(
alignment: AlignmentDirectional.centerEnd,
child: NeedsYouRunsHeading(
rows: controller.runs,
frames: controller.repository.gateway.frames,
onOpen: (entry) => onSelected(entry.runId),
syncToken: syncToken,
store: attentionStore,
now: attentionNow,
),
),
),
if (controller.usage != null)
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
@@ -52,7 +82,7 @@ class RunsList extends StatelessWidget {
onChanged: controller.setQuery,
),
),
_selectors(context),
RunsFilters(controller: controller),
Expanded(
child: controller.visibleRuns.isEmpty
? const Center(child: Text('No runs found.'))
@@ -101,101 +131,6 @@ class RunsList extends StatelessWidget {
),
);
Widget _selectors(BuildContext context) {
if (usesCupertinoHost(context)) {
return Wrap(
spacing: 8,
children: [
CupertinoButton(
onPressed: () => _choose(
context,
'Sort runs',
_sorts,
controller.sort,
controller.setSort,
),
child: Text('Sort: ${_sortLabel(controller.sort)}'),
),
CupertinoButton(
onPressed: () => _choose(
context,
'Schedule',
_schedules,
controller.scheduled,
controller.setScheduled,
),
child: Text('Schedule: ${_scheduleLabel(controller.scheduled)}'),
),
for (final status in _statuses)
CupertinoButton(
onPressed: () => controller.setStatus(status),
child: Text(
'${controller.statuses.contains(status) ? '✓ ' : ''}${_title(status)}',
),
),
],
);
}
return Wrap(
spacing: 8,
children: [
DropdownButton<String>(
value: controller.sort,
isExpanded: true,
onChanged: (v) {
if (v != null) controller.setSort(v);
},
items: _sorts
.map((e) => DropdownMenuItem(value: e.$1, child: Text(e.$2)))
.toList(),
),
DropdownButton<String>(
value: controller.scheduled,
isExpanded: true,
onChanged: (v) {
if (v != null) controller.setScheduled(v);
},
items: _schedules
.map((e) => DropdownMenuItem(value: e.$1, child: Text(e.$2)))
.toList(),
),
for (final status in _statuses)
FilterChip(
label: Text(_title(status)),
selected: controller.statuses.contains(status),
onSelected: (_) => controller.setStatus(status),
),
],
);
}
Future<void> _choose(
BuildContext context,
String title,
List<(String, String)> values,
String selected,
ValueChanged<String> onSelected,
) async {
final value = await showCupertinoModalPopup<String>(
context: context,
builder: (context) => CupertinoActionSheet(
title: Text(title),
actions: [
for (final option in values)
CupertinoActionSheetAction(
onPressed: () => Navigator.pop(context, option.$1),
child: Text(option.$2),
),
],
cancelButton: CupertinoActionSheetAction(
onPressed: () => Navigator.pop(context),
child: const Text('Cancel'),
),
),
);
if (value != null && value != selected) onSelected(value);
}
Widget _runTile(BuildContext context, JsonMap run) {
final identity = runIdentity(run['title'], run['name']);
final id = run['id'];
@@ -222,22 +157,3 @@ class RunsList extends StatelessWidget {
);
}
}
const _sorts = [
('newest_first', 'Newest'),
('oldest_first', 'Oldest'),
('pipeline_name', 'Pipeline'),
('status', 'Status'),
];
const _schedules = [
('any', 'Any schedule'),
('scheduled', 'Scheduled'),
('unscheduled', 'Unscheduled'),
];
const _statuses = ['queued', 'running', 'waiting', 'succeeded', 'failed'];
String _sortLabel(String value) =>
_sorts.firstWhere((e) => e.$1 == value, orElse: () => _sorts.first).$2;
String _scheduleLabel(String value) => _schedules
.firstWhere((e) => e.$1 == value, orElse: () => _schedules.first)
.$2;
String _title(String value) => '${value[0].toUpperCase()}${value.substring(1)}';