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,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<String, dynamic> _run(
int id,
String status, {
String name = 'release',
String? title,
Duration age = const Duration(hours: 1),
String diagnostic = '',
Object? exportPending,
Map<String, dynamic> 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<bool>();
@override
Future<bool> 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));
},
);
});
}
@@ -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();
}
});
}
@@ -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<String, dynamic> 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<JsonMap>.broadcast();
final listRequests = <Completer<JsonMap>>[];
final detailRequests = <num, List<Completer<JsonMap>>>{};
@override
Stream<JsonMap> get frames => framesController.stream;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
final request = Completer<JsonMap>();
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<JsonMap> 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<void> mountAttentionRuns(
WidgetTester tester,
AttentionRunsGateway gateway, {
required bool cupertino,
required AttentionStore store,
required List<JsonMap> 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<void> openAttentionSheet(WidgetTester tester) async {
await tester.tap(find.byKey(attentionBellKey));
await tester.pumpAndSettle();
}
@@ -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();
});
}
}
@@ -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(<String, Object>{
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(<String, Object>{});
const store = SharedPreferencesAttentionStore();
expect(await store.read(), isNull);
expect(attentionStorageKey, 'pipelines.next.attention.v1');
expect(await store.write('[]'), isTrue);
});
}