From a309d9d571ff1444c9c51fe7fffaa4550fe00b8a Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 22 Oct 2026 00:52:06 +0100 Subject: [PATCH] feat(app): show the live Needs-you bell over the Runs list rows --- app/PARITY.md | 2 +- .../runtime/attention_controller.dart | 179 +++++++++++++ .../attention/runtime/attention_store.dart | 82 ++++++ .../attention/ui/needs_you_runs_heading.dart | 118 +++++++++ app/lib/features/runs/screen.dart | 16 +- app/lib/features/runs/ui/runs_filters.dart | 138 ++++++++++ app/lib/features/runs/ui/runs_list.dart | 146 +++------- app/notes/attention-wiring.md | 84 ++++++ .../runtime/attention_controller_test.dart | 250 ++++++++++++++++++ .../runtime/attention_runs_layout_test.dart | 72 +++++ .../runtime/attention_runs_test_support.dart | 125 +++++++++ .../runtime/attention_runs_wiring_test.dart | 196 ++++++++++++++ .../runtime/attention_store_test.dart | 36 +++ app/tool/attention_wiring_probe.mjs | 220 +++++++++++++++ app/tool/runs_probe_server.mjs | 20 +- 15 files changed, 1557 insertions(+), 127 deletions(-) create mode 100644 app/lib/features/attention/runtime/attention_controller.dart create mode 100644 app/lib/features/attention/runtime/attention_store.dart create mode 100644 app/lib/features/attention/ui/needs_you_runs_heading.dart create mode 100644 app/lib/features/runs/ui/runs_filters.dart create mode 100644 app/notes/attention-wiring.md create mode 100644 app/test/features/attention/runtime/attention_controller_test.dart create mode 100644 app/test/features/attention/runtime/attention_runs_layout_test.dart create mode 100644 app/test/features/attention/runtime/attention_runs_test_support.dart create mode 100644 app/test/features/attention/runtime/attention_runs_wiring_test.dart create mode 100644 app/test/features/attention/runtime/attention_store_test.dart create mode 100644 app/tool/attention_wiring_probe.mjs diff --git a/app/PARITY.md b/app/PARITY.md index 887dae01..8629d62a 100644 --- a/app/PARITY.md +++ b/app/PARITY.md @@ -52,7 +52,7 @@ or scratch servers only, never real operator sessions/runs/workflows. | Saved schedule list | Source | pipeline entry and route registration, exact timer provenance vocabulary | | Schedule editor | Preview: pipeline Summary section creates/edits/pauses/deletes with the lossless draft and revision guard; conflict keeps the draft and shows the server words | Schedule-this-run seeding, schedules list entry/route | | Search | Preview: shell entry, /search route, focused field, restore on close | result target routing for pipeline/version/field/visit/artifact hits | -| Needs you | Source model + native bell/sheet; wiring90 | in-app count from list rows, dismiss persistence and live transitions | +| Needs you | Preview: runs-list bell/count, native sheet, open/dismiss/clear persistence, live fold and reconnect reseed | notification transitions/permission, authenticated preview smoke | | Notifications | Missing | explicit permission/rationale, secure/unsupported/denied states, transition-only dedupe, background question notices | | Mobile replacement build | Scaffold only | Android build at end; all source portable to iOS, isolated IDs; device/OS behavior clearly separate | diff --git a/app/lib/features/attention/runtime/attention_controller.dart b/app/lib/features/attention/runtime/attention_controller.dart new file mode 100644 index 00000000..d80e3fcc --- /dev/null +++ b/app/lib/features/attention/runtime/attention_controller.dart @@ -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 _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(); + } +} diff --git a/app/lib/features/attention/runtime/attention_store.dart b/app/lib/features/attention/runtime/attention_store.dart new file mode 100644 index 00000000..fe9d4095 --- /dev/null +++ b/app/lib/features/attention/runtime/attention_store.dart @@ -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 read(); + + Future 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 _preferences() async { + try { + return await SharedPreferences.getInstance(); + } catch (_) { + return null; + } + } + + @override + Future read() async { + final preferences = await _preferences(); + if (preferences == null) return null; + try { + return preferences.getString(attentionStorageKey); + } catch (_) { + return null; + } + } + + @override + Future 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 read() async { + if (failReads) throw StateError('attention store unavailable'); + return stored; + } + + @override + Future write(String value) async { + writes++; + if (failWrites) throw StateError('attention store is read-only'); + stored = value; + return true; + } +} diff --git a/app/lib/features/attention/ui/needs_you_runs_heading.dart b/app/lib/features/attention/ui/needs_you_runs_heading.dart new file mode 100644 index 00000000..bf8889f1 --- /dev/null +++ b/app/lib/features/attention/ui/needs_you_runs_heading.dart @@ -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 rows; + + /// The shared gateway's frames; only `run_event` envelopes are folded. + final Stream frames; + + /// Opens an entry's run. A Failed entry is dismissed by the bell first. + final ValueChanged 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 createState() => _NeedsYouRunsHeadingState(); +} + +class _NeedsYouRunsHeadingState extends State { + late final AttentionController _attention = AttentionController( + store: widget.store, + now: widget.now, + ); + StreamSubscription? _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)); + }, + ), + ); + } +} diff --git a/app/lib/features/runs/screen.dart b/app/lib/features/runs/screen.dart index 42126b44..f4f28125 100644 --- a/app/lib/features/runs/screen.dart +++ b/app/lib/features/runs/screen.dart @@ -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? 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 createState() => _RunsScreenState(); } @@ -103,7 +111,13 @@ class _RunsScreenState extends State { 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) diff --git a/app/lib/features/runs/ui/runs_filters.dart b/app/lib/features/runs/ui/runs_filters.dart new file mode 100644 index 00000000..9ff33de0 --- /dev/null +++ b/app/lib/features/runs/ui/runs_filters.dart @@ -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( + 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( + 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 _choose( + BuildContext context, + String title, + List<(String, String)> values, + String selected, + ValueChanged onSelected, + ) async { + final value = await showCupertinoModalPopup( + 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)}'; diff --git a/app/lib/features/runs/ui/runs_list.dart b/app/lib/features/runs/ui/runs_list.dart index 0f974eac..2c5a2ab3 100644 --- a/app/lib/features/runs/ui/runs_list.dart +++ b/app/lib/features/runs/ui/runs_list.dart @@ -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 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( - 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( - 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 _choose( - BuildContext context, - String title, - List<(String, String)> values, - String selected, - ValueChanged onSelected, - ) async { - final value = await showCupertinoModalPopup( - 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)}'; diff --git a/app/notes/attention-wiring.md b/app/notes/attention-wiring.md new file mode 100644 index 00000000..05f0c7a5 --- /dev/null +++ b/app/notes/attention-wiring.md @@ -0,0 +1,84 @@ +# Runs-list Needs-you bell wiring + +The landed attention model and native bell/sheet are now registered in the real +Runs destination. The bell sits in the Runs list heading area and reads the same +`list_runs` rows the screen already loaded; it issues no attention request and +adds no poll. + +## Code + +- `lib/features/attention/runtime/attention_store.dart` — the injectable + `AttentionStore` seam, a `SharedPreferences` implementation under + `pipelines.next.attention.v1` (only that key), and an in-memory implementation + for tests/fixtures. Reads and writes are total: an unavailable plugin or full + store returns null/false instead of throwing. +- `lib/features/attention/runtime/attention_controller.dart` — derives today's + ordered entries from rows plus the persisted dismissal set, loads asynchronously, + and folds pushed `run_event` frames with the runs feature's existing + `foldRunEvent`. The attention transition detector is seeded by authoritative + list reads, reseeded on reconnect, and keeps emitted keys, so a failure/wait + that appears while the screen is open reaches the bell once while a reconnect + never replays it. Dismissals update memory and notify before the store write, so + a slow or failed write cannot block the sheet. Pushed `title`/`name`/`diagnostic` + are retained because the lifecycle fold does not carry the row's attention text. +- `lib/features/attention/ui/needs_you_runs_heading.dart` — owns the controller + and shared-frame subscription for the destination, passes the dismissed list to + the landed `NeedsYouBell`, and opens the existing run through `RunsList`'s + `onSelected` (the existing run route). +- `lib/features/runs/ui/runs_list.dart` — small heading insert plus injectable + store/clock and reconnect token; no other destination is touched. +- `lib/features/runs/screen.dart` — forwards the reconnect token and the test + seam to the list. +- `lib/features/runs/ui/runs_filters.dart` — the existing filter controls moved + out of the list file unchanged for Material, with the Cupertino strip made + horizontally scrollable. At 320 logical px / 2x the old wrapping strip alone + made the Runs `Column` overflow before the attention change; one native row is + the same narrow-toolbar shape the browser uses and keeps every control + reachable. File split keeps `runs_list.dart` at 159 lines. + +The bell keeps the native `NeedsYouBell` semantics (`Notifications` / +`Notifications, N needing attention`), shows no badge when empty, and uses the +already-landed Material bottom sheet / Cupertino popup. Failed rows dismiss before +opening; Decision rows open without dismissing; Clear all uses the snapshot the +sheet captured when it opened. Dismissals survive a screen rebuild through the +same store. + +## Verification + +- `flutter test` — 966 tests passed. +- Focused `flutter test test/features/attention/runtime` — 20 tests passed: + rows -> entries, export waits and yesterday excluded, dismissal persistence + across a rebuilt controller, slow write does not block, failed read/write is + harmless, clear-all snapshot leaves a later arrival, live failed frame adds an + entry, a frame can create a new run summary, reconnect keeps dismissals and + emitted keys, empty state keeps the bell and hides its badge, both hosts at + 320 logical px / 2x with no list/sheet overflow, and the SharedPreferences key + ownership test. +- `flutter analyze` — no issues. +- `flutter build web` — normal `lib/main.dart` built successfully. +- Real browser (`tool/attention_wiring_probe.mjs`, isolated `startFixture`, two + fresh app boots, one shared socket each): four captures in + `public/attention-wiring/` at 320 logical px / 2x: + `attention-runs-cupertino-bell-320x2.png`, + `attention-runs-cupertino-sheet-320x2.png`, + `attention-runs-material-bell-320x2.png`, + `attention-runs-material-sheet-320x2.png`. + The drive asserted the accessible count `Notifications, 2 needing attention`, + both void rows absent, the `Dismiss ...` names and Clear all, and viewed both + PNGs. The fixture list held a running row and an `export_pending_sequence` + wait that did not enter the sheet; the fixture served one connection and no + `get_run`/attention request (`listRuns: 4` across the two boots, the existing + screen loads). Both bell and sheet captures were inspected. + +`tool/runs_probe_server.mjs` now accepts an optional `runs` list so this fixture +can use current-day timestamps without changing the existing runs probe's +default data. No legacy driver was edited. + +## Not done / limits + +- No commit, push, merge, deployment, preview cutover or service restart. +- Notification permission/tray delivery remains separate work; the transition + ledger is exposed for that wiring but no permission is requested here. +- Android/iOS builds and real devices were not run; web only, as required. +- The fixture is isolated (loopback, its own browser profile) and does not touch + operator runs, chats, storage or production credentials. diff --git a/app/test/features/attention/runtime/attention_controller_test.dart b/app/test/features/attention/runtime/attention_controller_test.dart new file mode 100644 index 00000000..adcbd87d --- /dev/null +++ b/app/test/features/attention/runtime/attention_controller_test.dart @@ -0,0 +1,250 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/domain/attention_models.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_controller.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_store.dart'; + +final _now = DateTime(2026, 10, 22, 12); + +String _at(Duration before) => _now.subtract(before).toIso8601String(); + +Map _run( + int id, + String status, { + String name = 'release', + String? title, + Duration age = const Duration(hours: 1), + String diagnostic = '', + Object? exportPending, + Map extra = const {}, +}) => { + 'id': id, + 'name': name, + 'title': title ?? 'Run $id', + 'status': status, + 'diagnostic': diagnostic, + 'created_at': _at(age), + 'finished_at': _at(age - const Duration(minutes: 5)), + 'export_pending_sequence': ?exportPending, + ...extra, +}; + +AttentionController _controller(AttentionStore store) => + AttentionController(store: store, now: () => _now); + +class _SlowStore extends MemoryAttentionStore { + final gate = Completer(); + + @override + Future write(String value) { + writes++; + stored = value; + return gate.future; + } +} + +void main() { + group('entries from the rows the Runs destination already holds', () { + test('only failed and human waiting rows become entries', () async { + final controller = _controller(MemoryAttentionStore()); + addTearDown(controller.dispose); + await controller.load(); + controller.seedRows([ + _run(1, 'running'), + _run(2, 'succeeded'), + _run(3, 'queued'), + _run(4, 'canceled'), + _run(5, 'failed', diagnostic: 'Stage 2 failed'), + _run(6, 'waiting', title: 'Approve the release'), + ]); + + expect(controller.entries.map((entry) => entry.key), [ + '6:Decision', + '5:Failed', + ]); + expect(controller.entries.last.detail, 'Stage 2 failed'); + }); + + test('export handoffs and yesterday do not ask the operator', () async { + final controller = _controller(MemoryAttentionStore()); + addTearDown(controller.dispose); + await controller.load(); + controller.seedRows([ + _run(1, 'waiting', exportPending: 4), + _run(2, 'waiting', exportPending: ' 2 '), + _run(3, 'waiting', exportPending: 0), + _run(4, 'failed', age: const Duration(days: 1, hours: 2)), + _run(5, 'waiting', age: const Duration(days: 1)), + ]); + + expect(controller.entries.map((entry) => entry.runId), [3]); + }); + }); + + group('dismissal persistence', () { + test('a dismissed identity survives a rebuilt controller', () async { + final store = MemoryAttentionStore(); + final first = _controller(store); + await first.load(); + first.seedRows([_run(7, 'failed')]); + final entry = first.entries.single; + + expect(await first.dismiss(entry), isTrue); + expect(first.entries, isEmpty); + expect(store.stored, encodeAttentionDismissals({'7:Failed'})); + first.dispose(); + + final rebuilt = _controller(store); + addTearDown(rebuilt.dispose); + await rebuilt.load(); + rebuilt.seedRows([_run(7, 'failed')]); + expect(rebuilt.dismissed, {'7:Failed'}); + expect(rebuilt.entries, isEmpty); + }); + + test('Clear all applies only the snapshot, leaving later arrivals', () async { + final controller = _controller(MemoryAttentionStore()); + addTearDown(controller.dispose); + await controller.load(); + controller.seedRows([_run(1, 'failed'), _run(2, 'waiting')]); + final snapshot = attentionDismissalSnapshot(controller.entries); + + // A third run arrives while the sheet is open. Clear all must not know it. + controller.seedRows([ + _run(1, 'failed'), + _run(2, 'waiting'), + _run(3, 'failed'), + ]); + expect(await controller.clearAll(snapshot), isTrue); + + expect(controller.dismissed, {'1:Failed', '2:Decision'}); + expect(controller.entries.map((entry) => entry.key), ['3:Failed']); + }); + + test('a slow write never holds the bell or entries back', () async { + final store = _SlowStore(); + final controller = _controller(store); + addTearDown(controller.dispose); + await controller.load(); + controller.seedRows([_run(4, 'failed')]); + final entry = controller.entries.single; + + final pending = controller.dismiss(entry); + expect(controller.entries, isEmpty, reason: 'memory applies first'); + expect(store.stored, encodeAttentionDismissals({'4:Failed'})); + store.gate.complete(true); + expect(await pending, isTrue); + }); + + test('failed reads and writes are total and keep this session', () async { + final store = MemoryAttentionStore() + ..failReads = true + ..failWrites = true; + final controller = _controller(store); + addTearDown(controller.dispose); + + await expectLater(controller.load(), completes); + expect(controller.loaded, isTrue); + expect(controller.dismissed, isEmpty); + + controller.seedRows([_run(8, 'failed')]); + final entry = controller.entries.single; + expect(await controller.dismiss(entry), isFalse); + expect(controller.dismissed, {'8:Failed'}); + expect(controller.entries, isEmpty); + }); + }); + + group('pushed frames and reconnect', () { + test('a live frame that becomes failed appears without a reload', () async { + final controller = _controller(MemoryAttentionStore()); + addTearDown(controller.dispose); + await controller.load(); + controller.seedRows([_run(1, 'running')]); + expect(controller.entries, isEmpty); + + controller.observeFrame({ + 'type': 'run_event', + 'run_id': 1, + 'status': 'failed', + 'diagnostic': 'Stage 4 failed', + 'finished_at': _at(const Duration(minutes: 1)), + }); + + expect(controller.entries.map((entry) => entry.key), ['1:Failed']); + expect(controller.entries.single.detail, 'Stage 4 failed'); + expect(controller.transitions.map((item) => item.key), ['1:Failed']); + + // The same state again is not a new transition. + controller.observeFrame({ + 'type': 'run_event', + 'run_id': 1, + 'status': 'failed', + 'diagnostic': 'Stage 4 failed', + }); + expect(controller.entries, hasLength(1)); + expect(controller.transitions, hasLength(1)); + }); + + test('a live frame for a new run can create its own summary', () async { + final controller = _controller(MemoryAttentionStore()); + addTearDown(controller.dispose); + await controller.load(); + controller.seedRows(const []); + + controller.observeFrame({ + 'type': 'run_event', + 'run_id': 9, + 'pipeline_id': 10, + 'name': 'nightly', + 'title': 'Nightly audit', + 'status': 'waiting', + 'created_at': _at(const Duration(minutes: 3)), + }); + + expect(controller.entries.single.runId, 9); + expect(controller.entries.single.kind, AttentionKind.decision); + }); + + test( + 'a reconnect reseed keeps dismissals and does not re-notify', + () async { + final controller = _controller(MemoryAttentionStore()); + addTearDown(controller.dispose); + await controller.load(); + controller.seedRows([_run(1, 'running'), _run(2, 'failed')]); + final failed = controller.entries.single; + expect(await controller.dismiss(failed), isTrue); + + controller.observeFrame({ + 'type': 'run_event', + 'run_id': 1, + 'status': 'failed', + }); + expect(controller.transitions, hasLength(1)); + + controller.resetForReconnect(); + controller.seedRows([ + _run(1, 'failed'), + _run(2, 'failed'), + ], reconnect: true); + + expect(controller.dismissed, {'2:Failed'}); + expect(controller.entries.map((entry) => entry.key), ['1:Failed']); + expect( + controller.transitions, + hasLength(1), + reason: 'the reconnect baseline is already failed for run 1', + ); + + controller.observeFrame({ + 'type': 'run_event', + 'run_id': 1, + 'status': 'failed', + }); + expect(controller.transitions, hasLength(1)); + }, + ); + }); +} diff --git a/app/test/features/attention/runtime/attention_runs_layout_test.dart b/app/test/features/attention/runtime/attention_runs_layout_test.dart new file mode 100644 index 00000000..16b57207 --- /dev/null +++ b/app/test/features/attention/runtime/attention_runs_layout_test.dart @@ -0,0 +1,72 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_store.dart'; +import 'package:pipelines_app/features/attention/ui/needs_you_keys.dart'; + +import 'attention_runs_test_support.dart'; + +/// The hardest real-app case: a narrow phone at a doubled text scale. Both the +/// Runs list chrome and the native sheet must keep the bell and every action +/// inside the viewport. +void main() { + testWidgets('both hosts fit the bell and sheet at 320 logical px and 2x', ( + tester, + ) async { + tester.view.devicePixelRatio = 2; + tester.view.physicalSize = const Size(640, 1280); + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final gateway = AttentionRunsGateway(); + addTearDown(gateway.framesController.close); + + for (final native in [false, true]) { + await mountAttentionRuns( + tester, + gateway, + cupertino: native, + store: MemoryAttentionStore(), + runs: [ + attentionRun( + 1, + 'waiting', + title: 'Approve a release candidate at 320 px', + ), + attentionRun( + 2, + 'failed', + title: 'A failed run with a label long enough to wrap', + diagnostic: 'Stage 3 stopped because the credential is missing.', + ), + ], + request: native ? 1 : 0, + textScale: 2, + key: ValueKey(native), + ); + expect(find.byKey(attentionBellKey), findsOneWidget); + final listError = tester.takeException(); + expect( + listError, + isNull, + reason: listError is FlutterError + ? '${native ? 'Cupertino' : 'Material'} list: ${listError.toStringDeep()}' + : '${native ? 'Cupertino' : 'Material'} list: $listError', + ); + await openAttentionSheet(tester); + final sheetError = tester.takeException(); + expect( + sheetError, + isNull, + reason: sheetError is FlutterError + ? '${native ? 'Cupertino' : 'Material'} sheet: ${sheetError.toStringDeep()}' + : '${native ? 'Cupertino' : 'Material'} sheet: $sheetError', + ); + final sheet = tester.getRect(find.byKey(attentionSheetKey)); + expect(sheet.left, greaterThanOrEqualTo(0)); + expect(sheet.right, lessThanOrEqualTo(320)); + expect(sheet.top, greaterThanOrEqualTo(0)); + expect(sheet.bottom, lessThanOrEqualTo(640)); + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + } + }); +} diff --git a/app/test/features/attention/runtime/attention_runs_test_support.dart b/app/test/features/attention/runtime/attention_runs_test_support.dart new file mode 100644 index 00000000..0dd459b6 --- /dev/null +++ b/app/test/features/attention/runtime/attention_runs_test_support.dart @@ -0,0 +1,125 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_store.dart'; +import 'package:pipelines_app/features/attention/ui/needs_you_keys.dart'; +import 'package:pipelines_app/features/runs/screen.dart'; + +/// A fixed local noon so the attention local-day window is deterministic. +final attentionTestNow = DateTime(2026, 10, 22, 12); + +Map attentionRun( + int id, + String status, { + required String title, + String name = 'release', + String diagnostic = '', +}) => { + 'id': id, + 'name': name, + 'title': title, + 'status': status, + 'diagnostic': diagnostic, + 'created_at': attentionTestNow + .subtract(const Duration(hours: 1)) + .toIso8601String(), + 'finished_at': attentionTestNow + .subtract(const Duration(minutes: 30)) + .toIso8601String(), +}; + +/// The two requests the Runs destination makes; no attention request exists. +class AttentionRunsGateway implements ApiGateway { + final framesController = StreamController.broadcast(); + final listRequests = >[]; + final detailRequests = >>{}; + + @override + Stream get frames => framesController.stream; + + @override + Future call(String type, [JsonMap fields = const {}]) { + final request = Completer(); + if (type == 'list_runs') { + listRequests.add(request); + } else if (type == 'get_run') { + final id = fields['run_id'] as num; + detailRequests.putIfAbsent(id, () => []).add(request); + } else { + request.completeError(UnsupportedError(type)); + } + return request.future; + } + + void replyList(int index, List runs) => + listRequests[index].complete({'runs': runs}); + + void replyDetail(num id, JsonMap detail) => + detailRequests[id]!.first.complete({'run_detail': detail}); +} + +Widget attentionRunsApp( + AttentionRunsGateway gateway, { + required bool cupertino, + required AttentionStore store, + double textScale = 1, + Key? key, +}) { + Widget scaled(BuildContext context, Widget? child) => MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(textScaler: TextScaler.linear(textScale)), + child: child!, + ); + final screen = RunsScreen( + key: key, + gateway: gateway, + attentionStore: store, + attentionNow: () => attentionTestNow, + ); + if (cupertino) { + return CupertinoApp( + theme: const CupertinoThemeData(brightness: Brightness.dark), + builder: scaled, + home: CupertinoPageScaffold(child: screen), + ); + } + return MaterialApp( + theme: ThemeData(platform: TargetPlatform.android), + builder: scaled, + home: Scaffold(body: screen), + ); +} + +Future mountAttentionRuns( + WidgetTester tester, + AttentionRunsGateway gateway, { + required bool cupertino, + required AttentionStore store, + required List runs, + int request = 0, + double textScale = 1, + Key? key, +}) async { + await tester.pumpWidget( + attentionRunsApp( + gateway, + cupertino: cupertino, + store: store, + textScale: textScale, + key: key, + ), + ); + await tester.pump(); + gateway.replyList(request, runs); + await tester.pump(); + await tester.pump(); +} + +Future openAttentionSheet(WidgetTester tester) async { + await tester.tap(find.byKey(attentionBellKey)); + await tester.pumpAndSettle(); +} diff --git a/app/test/features/attention/runtime/attention_runs_wiring_test.dart b/app/test/features/attention/runtime/attention_runs_wiring_test.dart new file mode 100644 index 00000000..9b13694b --- /dev/null +++ b/app/test/features/attention/runtime/attention_runs_wiring_test.dart @@ -0,0 +1,196 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/domain/attention_models.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_store.dart'; +import 'package:pipelines_app/features/attention/ui/needs_you_keys.dart'; + +import 'attention_runs_test_support.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + late AttentionRunsGateway gateway; + + setUp(() => gateway = AttentionRunsGateway()); + tearDown(() => gateway.framesController.close()); + + for (final native in [false, true]) { + final host = native ? 'Cupertino' : 'Material'; + + testWidgets( + '$host Runs list bell opens the native sheet and dismisses one', + (tester) async { + final semantics = tester.ensureSemantics(); + final store = MemoryAttentionStore(); + await mountAttentionRuns( + tester, + gateway, + cupertino: native, + store: store, + runs: [ + attentionRun(1, 'waiting', title: 'Approve the release'), + attentionRun( + 2, + 'failed', + title: 'Ship the release', + diagnostic: 'Stage 2', + ), + attentionRun(3, 'waiting', title: 'Machine export') + ..['export_pending_sequence'] = 2, + attentionRun(4, 'running', title: 'Still running'), + ], + ); + + expect( + find.bySemanticsLabel('Notifications, 2 needing attention'), + findsOneWidget, + ); + await openAttentionSheet(tester); + expect(find.byKey(attentionSheetKey), findsOneWidget); + expect(find.byKey(attentionRowKey('3:Decision')), findsNothing); + expect(find.byKey(attentionRowKey('4:Failed')), findsNothing); + expect(find.byKey(attentionRowKey('2:Failed')), findsOneWidget); + + await tester.tap(find.byKey(attentionDismissKey('2:Failed'))); + await tester.pumpAndSettle(); + expect(find.byKey(attentionSheetKey), findsOneWidget); + expect(find.byKey(attentionRowKey('2:Failed')), findsNothing); + expect(store.stored, encodeAttentionDismissals({'2:Failed'})); + + // Closing and rebuilding from the same store keeps the dismissal. + await tester.binding.handlePopRoute(); + await tester.pumpAndSettle(); + await tester.pumpWidget(const SizedBox()); + await mountAttentionRuns( + tester, + gateway, + cupertino: native, + store: store, + runs: [ + attentionRun(1, 'waiting', title: 'Approve the release'), + attentionRun( + 2, + 'failed', + title: 'Ship the release', + diagnostic: 'Stage 2', + ), + ], + request: 1, + key: const ValueKey('rebuilt'), + ); + expect( + find.bySemanticsLabel('Notifications, 1 needing attention'), + findsOneWidget, + ); + semantics.dispose(); + }, + ); + + testWidgets('$host rows follow the browser open/dismiss rules', ( + tester, + ) async { + final store = MemoryAttentionStore(); + await mountAttentionRuns( + tester, + gateway, + cupertino: native, + store: store, + runs: [ + attentionRun(1, 'waiting', title: 'Approve the release'), + attentionRun(2, 'failed', title: 'Ship the release'), + ], + ); + + await openAttentionSheet(tester); + await tester.tap(find.byKey(attentionRowKey('1:Decision'))); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + expect(gateway.detailRequests[1], hasLength(1)); + expect( + store.stored, + isNull, + reason: 'a Decision opens without dismissing', + ); + gateway.replyDetail(1, {'id': 1, 'title': 'Approve the release'}); + await tester.pump(); + await tester.pumpAndSettle(); + + await tester.tap(find.text(native ? 'Back' : 'Back to list')); + await tester.pump(); + await openAttentionSheet(tester); + await tester.tap(find.byKey(attentionRowKey('2:Failed'))); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + expect(gateway.detailRequests[2], hasLength(1)); + expect(store.stored, encodeAttentionDismissals({'2:Failed'})); + gateway.replyDetail(2, {'id': 2, 'title': 'Ship the release'}); + await tester.pump(); + }); + + testWidgets('$host live frame and Clear-all snapshot reach the bell', ( + tester, + ) async { + final semantics = tester.ensureSemantics(); + final store = MemoryAttentionStore(); + await mountAttentionRuns( + tester, + gateway, + cupertino: native, + store: store, + runs: [attentionRun(1, 'failed', title: 'First failure')], + ); + expect( + find.bySemanticsLabel('Notifications, 1 needing attention'), + findsOneWidget, + ); + + await openAttentionSheet(tester); + gateway.framesController.add({ + 'type': 'run_event', + 'run_id': 9, + 'pipeline_id': 4, + 'name': 'nightly', + 'title': 'Arrived while open', + 'status': 'waiting', + 'created_at': attentionTestNow + .subtract(const Duration(minutes: 5)) + .toIso8601String(), + }); + await tester.pump(); + await tester.pumpAndSettle(); + expect(find.byKey(attentionRowKey('9:Decision')), findsOneWidget); + + await tester.tap(find.byKey(attentionClearAllKey)); + await tester.pumpAndSettle(); + expect(find.byKey(attentionRowKey('1:Failed')), findsNothing); + expect( + find.byKey(attentionRowKey('9:Decision')), + findsOneWidget, + reason: 'Clear all acts on the snapshot it opened with', + ); + expect(store.stored, encodeAttentionDismissals({'1:Failed'})); + semantics.dispose(); + }); + + testWidgets('$host empty runs hide the badge but keep the bell', ( + tester, + ) async { + final semantics = tester.ensureSemantics(); + await mountAttentionRuns( + tester, + gateway, + cupertino: native, + store: MemoryAttentionStore(), + runs: const [], + ); + + expect(find.byKey(attentionBellKey), findsOneWidget); + expect(find.byKey(attentionBadgeKey), findsNothing); + expect(find.bySemanticsLabel('Notifications'), findsOneWidget); + await openAttentionSheet(tester); + expect(find.text('Nothing needs you right now.'), findsOneWidget); + expect(find.byKey(attentionClearAllKey), findsNothing); + semantics.dispose(); + }); + } +} diff --git a/app/test/features/attention/runtime/attention_store_test.dart b/app/test/features/attention/runtime/attention_store_test.dart new file mode 100644 index 00000000..ee222995 --- /dev/null +++ b/app/test/features/attention/runtime/attention_store_test.dart @@ -0,0 +1,36 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/attention/domain/attention_models.dart'; +import 'package:pipelines_app/features/attention/runtime/attention_store.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test('reads and writes only the attention model key', () async { + SharedPreferences.setMockInitialValues({ + attentionStorageKey: '["7:Failed"]', + 'pipelines.next.workspace.v1': '/srv/keep', + }); + const store = SharedPreferencesAttentionStore(); + + expect(await store.read(), '["7:Failed"]'); + expect(await store.write('["8:Decision"]'), isTrue); + + final preferences = await SharedPreferences.getInstance(); + expect(preferences.getString(attentionStorageKey), '["8:Decision"]'); + expect( + preferences.getString('pipelines.next.workspace.v1'), + '/srv/keep', + reason: 'another owned preference must not be rewritten', + ); + }); + + test('an empty store reads as null and the key stays namespaced', () async { + SharedPreferences.setMockInitialValues({}); + const store = SharedPreferencesAttentionStore(); + + expect(await store.read(), isNull); + expect(attentionStorageKey, 'pipelines.next.attention.v1'); + expect(await store.write('[]'), isTrue); + }); +} diff --git a/app/tool/attention_wiring_probe.mjs b/app/tool/attention_wiring_probe.mjs new file mode 100644 index 00000000..47b22d4f --- /dev/null +++ b/app/tool/attention_wiring_probe.mjs @@ -0,0 +1,220 @@ +// Real-browser acceptance for the Needs-you bell in the Runs destination. +// +// flutter build web +// OPENCODE_ARTIFACT_DIR= node tool/attention_wiring_probe.mjs build/web +// +// The fixture serves the normal app bundle and answers list_runs over the same +// origin, so this is the real Runs screen and the real shared socket. It touches +// no production server, operator run or browser profile. The list carries one +// failed run, one human wait, plus a running and a machine export wait that must +// not reach the bell. Each native host is captured at 320 logical px / 2x. +import { spawn, execFile } from 'node:child_process'; +import { promisify } from 'node:util'; +import { once } from 'node:events'; +import { existsSync } from 'node:fs'; +import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'; +import { join, resolve } from 'node:path'; +import { tmpdir } from 'node:os'; +import { setTimeout as delay } from 'node:timers/promises'; + +import { startFixture } from './runs_probe_server.mjs'; + +const output = process.env.OPENCODE_ARTIFACT_DIR; +if (!output) throw new Error('Set OPENCODE_ARTIFACT_DIR for the probe captures'); +await mkdir(output, { recursive: true }); +const root = resolve(process.argv[2] ?? 'build/web'); + +const now = Date.now(); +const dayStart = new Date(now); +dayStart.setHours(0, 0, 0, 0); +const at = (minutes) => + new Date(Math.max(now - minutes * 60_000, dayStart.getTime() + 30_000)).toISOString(); +const runs = [ + { id: 1, title: 'Running fixture', name: 'running-fixture', status: 'running', + created_at: at(6), pipeline_id: 10 }, + { id: 2, title: 'Approve the release candidate', name: 'release', + status: 'waiting', created_at: at(5), finished_at: '', pipeline_id: 10 }, + { id: 3, title: 'Nightly audit stopped', name: 'nightly-audit', + status: 'failed', diagnostic: 'Stage 3 stopped at the export archive step because the credential is missing.', + created_at: at(4), finished_at: at(1), pipeline_id: 10 }, + { id: 6, title: 'Machine export wait', name: 'export-handoff', + status: 'waiting', export_pending_sequence: 2, created_at: at(3), pipeline_id: 10 }, +]; + +const fixture = await startFixture({ root, runs }); +// Prove the fixture answered before Chrome starts, so a missing build fails with +// a clear message instead of a blank page. +const probe = await fetch(`${fixture.url}/`); +if (probe.status !== 200 || !(probe.headers.get('content-type') ?? '').startsWith('text/html')) { + throw new Error(`Fixture index must be HTML: ${probe.status} ${probe.headers.get('content-type')}`); +} +await probe.text(); + +const chromePath = process.env.CHROME_PATH ?? '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; +if (!existsSync(chromePath)) throw new Error(`Chrome not found at ${chromePath}; set CHROME_PATH`); +const profile = await mkdtemp(join(tmpdir(), 'attention-wiring-chrome-')); +const chrome = spawn(chromePath, [ + '--headless=new', '--no-first-run', '--no-default-browser-check', '--disable-gpu', + '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank', +], { stdio: ['ignore', 'ignore', 'pipe'] }); +let stderr = ''; +chrome.stderr.on('data', (data) => { stderr += data; }); + +const waitFor = async (check, what) => { + for (let i = 0; i < 160; i++) { + const value = await check(); + if (value) return value; + await delay(100); + } + throw new Error(`Timed out waiting for ${what}\n${stderr.slice(-1200)}`); +}; + +let ws; +const captures = []; +try { + const endpoint = await waitFor( + () => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1], + 'Chrome DevTools', + ); + ws = new WebSocket(endpoint); + await once(ws, 'open'); + let id = 0; + const pending = new Map(); + ws.addEventListener('message', (event) => { + const message = JSON.parse(event.data); + if (message.id && pending.has(message.id)) { + pending.get(message.id)(message); + pending.delete(message.id); + } + }); + const send = (method, params = {}, sessionId) => new Promise((resolveCall) => { + const callId = ++id; + pending.set(callId, resolveCall); + ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) })); + }); + const target = (await send('Target.createTarget', { url: 'about:blank' })).result.targetId; + const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result.sessionId; + await send('Page.enable', {}, session); + await send('Runtime.enable', {}, session); + + const evaluate = async (expression) => { + const response = await send('Runtime.evaluate', { + expression, returnByValue: true, awaitPromise: true, + }, session); + if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`); + if (response.result?.exceptionDetails) { + throw new Error(`Page exception: ${JSON.stringify(response.result.exceptionDetails)}`); + } + return response.result?.result?.value; + }; + const path = () => evaluate('location.pathname'); + const semantics = () => evaluate(`[...document.querySelectorAll('flt-semantics')].map((el) => { + const r = el.getBoundingClientRect(); + return { label: (el.getAttribute('aria-label') || el.innerText || '').trim(), + role: el.getAttribute('role'), x: r.x, y: r.y, w: r.width, h: r.height }; + })`); + const labels = async () => (await semantics()).map((item) => item.label).filter(Boolean); + const text = () => evaluate(`(() => { + const chunks = [...document.querySelectorAll('flt-semantics, [aria-label]')] + .map((el) => el.getAttribute('aria-label') || el.innerText || ''); + if (document.body?.innerText) chunks.push(document.body.innerText); + return [...new Set(chunks)].join('\\n'); + })()`); + const requireLabel = async (needle) => { + await waitFor(async () => (await labels()).some((label) => label.includes(needle)), `label ${JSON.stringify(needle)}`); + }; + const requireText = async (needle) => { + await waitFor(async () => (await text()).includes(needle), `text ${JSON.stringify(needle)}`); + }; + const enableSemantics = async () => { + await waitFor( + () => evaluate("Boolean(document.querySelector('flt-semantics-placeholder'))"), + 'semantics placeholder', + ); + await evaluate("document.querySelector('flt-semantics-placeholder')?.click()"); + await delay(600); + }; + const clickLabel = async (needle, exact = false) => { + const clicked = await evaluate(`(() => { + const wanted = ${JSON.stringify(needle)}; + const all = [...document.querySelectorAll('flt-semantics')]; + const match = (el) => { + const label = (el.getAttribute('aria-label') || el.innerText || '').trim(); + return ${exact ? 'label === wanted' : 'label.includes(wanted)'}; + }; + const element = all.find((el) => ['button', 'tab', 'link', 'menuitem'].includes(el.getAttribute('role')) && match(el)) + || all.find(match); + if (!element) return false; + element.click(); + return true; + })()`); + if (!clicked) throw new Error(`Could not click ${JSON.stringify(needle)}. Labels: ${JSON.stringify(await labels())}`); + await delay(400); + }; + const capture = async (name) => { + const data = (await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session)).result.data; + const pathName = join(output, `${name}.png`); + await writeFile(pathName, Buffer.from(data, 'base64')); + captures.push(pathName); + return pathName; + }; + const ocr = async (file) => (await promisify(execFile)('tesseract', [file, 'stdout'])).stdout; + const requireOcr = async (file, needle) => { + const read = await ocr(file); + if (!read.toLowerCase().includes(needle.toLowerCase())) { + throw new Error(`OCR of ${file} lacks ${JSON.stringify(needle)}:\n${read.slice(0, 2000)}`); + } + }; + const setPhone = async () => { + await send('Emulation.setDeviceMetricsOverride', { + width: 320, height: 640, deviceScaleFactor: 2, mobile: true, + }, session); + await delay(500); + }; + + const drive = async (host, userAgent) => { + if (userAgent) { + await send('Emulation.setUserAgentOverride', userAgent, session); + } + await setPhone(); + await send('Page.navigate', { url: `${fixture.url}/` }, session); + await enableSemantics(); + await waitFor(async () => (await path()) === '/pipelines', 'boot route /pipelines'); + await clickLabel('Runs', true); + await waitFor(async () => (await path()) === '/runs', 'runs route'); + await requireLabel('Notifications, 2 needing attention'); + const bell = await capture(`attention-runs-${host}-bell-320x2`); + await requireOcr(bell, 'Nightly audit stopped'); + + await clickLabel('Notifications, 2 needing attention'); + await requireText('Needs you'); + await requireText('Approve the release candidate'); + await requireText('Stage 3 stopped at the export archive step'); + await requireLabel('Dismiss Approve the release candidate'); + await requireLabel('Dismiss Nightly audit stopped'); + await requireLabel('Clear all'); + const sheetLabels = await labels(); + if (sheetLabels.some((label) => label.includes('Machine export wait'))) { + throw new Error('an export wait leaked into the bell sheet'); + } + if (sheetLabels.some((label) => label.includes('Running fixture'))) { + throw new Error('a running run leaked into the bell sheet'); + } + const sheet = await capture(`attention-runs-${host}-sheet-320x2`); + await requireOcr(sheet, 'Needs you'); + return { host, bell, sheet }; + }; + + const cupertino = await drive('cupertino'); + const material = await drive('material', { + userAgent: 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36', + platform: 'Linux x86_64', + }); + const state = await (await fetch(`${fixture.url}/fixture/state`)).json(); + console.log(JSON.stringify({ captures, cupertino, material, fixture: state }, null, 2)); +} finally { + try { ws?.close(); } catch {} + chrome.kill('SIGTERM'); + await rm(profile, { recursive: true, force: true }).catch(() => {}); + await fixture.close(); +} diff --git a/app/tool/runs_probe_server.mjs b/app/tool/runs_probe_server.mjs index 60f38562..267a34a5 100644 --- a/app/tool/runs_probe_server.mjs +++ b/app/tool/runs_probe_server.mjs @@ -57,9 +57,9 @@ const RUNS = [ }, ]; -function humanDetail(accepted) { +function humanDetail(accepted, runs = RUNS) { return { - ...RUNS.find((run) => run.id === 5), + ...runs.find((run) => run.id === 5), status: accepted ? 'succeeded' : 'waiting', current_stage: 'gate', input: { prompt: 'Fixture human decision' }, graph: { stages: [{ key: 'gate', type: 'human', edges: { approve: '#success' } }] }, @@ -79,12 +79,12 @@ const LIVE_EVENT = { finished_at: '2026-10-21T12:05:00Z', }; -function detail(id, live, canceled = false) { +function detail(id, live, canceled = false, runs = RUNS) { const status = canceled ? 'canceled' : id === 1 && live ? 'succeeded' : id === 3 ? 'failed' : 'running'; return { id, - title: RUNS.find((run) => run.id === id)?.title ?? `Run ${id}`, + title: runs.find((run) => run.id === id)?.title ?? `Run ${id}`, name: 'fixture-pipeline', status, executing: status === 'running', @@ -310,7 +310,7 @@ async function staticFile(base, pathname, req, res) { * It serves the built probe bundle and upgrades /connect on the same origin, so * the normal web composition infers this server from Uri.base. */ -export async function startFixture({ root }) { +export async function startFixture({ root, runs = RUNS }) { const base = await realpath(root); const connections = new Set(); const sockets = new Set(); @@ -436,7 +436,7 @@ export async function startFixture({ root }) { } if (request.type === 'list_runs') { listRuns++; - client.send({ id: request.id, type: 'runs', runs: RUNS.map((run) => + client.send({ id: request.id, type: 'runs', runs: runs.map((run) => canceled.has(run.id) ? { ...run, status: 'canceled', executing: false } : run.id === 5 && decisionAccepted ? { ...run, status: 'succeeded' } : run), usage: null }); return; @@ -448,7 +448,7 @@ export async function startFixture({ root }) { // Deliberately slow so the browser sees the pending/Back state; // it must still answer so the serialized request queue continues. setTimeout(() => { - client.send({ id: request.id, type: 'run', run_detail: detail(2, live) }); + client.send({ id: request.id, type: 'run', run_detail: detail(2, live, false, runs) }); }, 2500); return; } @@ -461,13 +461,13 @@ export async function startFixture({ root }) { return; } client.send({ id: request.id, type: 'run', run_detail: id === 5 - ? humanDetail(decisionAccepted) : detail(id, live, canceled.has(id)) }); + ? humanDetail(decisionAccepted, runs) : detail(id, live, canceled.has(id), runs) }); return; } if (request.type === 'cancel_run' && request.run_id === 4) { cancelRequests.push({ run_id: request.run_id }); canceled.add(4); - client.send({ id: request.id, type: 'run', run_detail: detail(4, live, true) }); + client.send({ id: request.id, type: 'run', run_detail: detail(4, live, true, runs) }); return; } if (request.type === 'decide_run' && request.run_id === 5 && @@ -475,7 +475,7 @@ export async function startFixture({ root }) { decisionRequests.push({ run_id: request.run_id, stage: request.stage, option: request.option, ...(request.feedback ? { feedback: request.feedback } : {}) }); decisionAccepted = true; - client.send({ id: request.id, type: 'run', run_detail: humanDetail(true) }); + client.send({ id: request.id, type: 'run', run_detail: humanDetail(true, runs) }); return; } if (request.type === 'search') {