Merge branch 'main' into flutter/start-pipeline

This commit is contained in:
2026-10-22 02:07:51 +01:00
124 changed files with 15223 additions and 440 deletions
@@ -0,0 +1,403 @@
import 'dart:typed_data';
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/artifacts/actions/artifact_file.dart';
import 'package:pipelines_app/features/artifacts/actions/artifact_file_actions.dart';
import 'package:pipelines_app/features/artifacts/actions/artifact_file_bridge.dart';
import 'package:pipelines_app/features/artifacts/actions/artifact_transfer.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_url.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_gallery_page.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_visit_list.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_fetch.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_page.dart';
import '../domain/artifact_fixtures.dart';
import '../ui/artifact_visit_list_fixture.dart';
const _endpoint = 'ws://127.0.0.1:8081/connect';
final Uint8List _bytes = Uint8List.fromList(<int>[7, 8, 9]);
final ArtifactRecord _record = ArtifactRecord.fromJson(<String, dynamic>{
'name': 'report.csv',
'url': '/artifacts/1/1/report.csv',
'content_type': 'text/csv',
'size_bytes': 3,
});
ArtifactFileBridge _bridge({
List<ArtifactFile>? saved,
List<ArtifactFile>? shared,
bool downloadSupported = true,
bool shareSupported = true,
}) => ArtifactFileBridge(
downloadSupported: downloadSupported,
shareSupported: shareSupported,
downloadUnsupportedMessage: 'No download on this host.',
shareUnsupportedMessage: 'No share on this host.',
download: (file) async {
saved?.add(file);
return ArtifactTransferResult(
ArtifactTransferState.saved,
'Downloaded ${file.name}.',
);
},
share: (file) async {
shared?.add(file);
return const ArtifactTransferResult(
ArtifactTransferState.shared,
'File shared.',
);
},
);
Future<ArtifactFetchResult> _fetch(Uri uri) async =>
ArtifactFetchResult(status: 200, bytes: _bytes);
Widget _row({
required bool cupertino,
ArtifactFileBridge? bridge,
ArtifactRecord? artifact,
ArtifactFetch? fetch,
}) {
final actions = ArtifactFileActions(
artifact: artifact ?? _record,
resolved: resolveArtifactUrl(_endpoint, _record.url)!,
fetch: fetch ?? _fetch,
bridge: bridge ?? _bridge(),
);
return cupertino
? CupertinoApp(
home: CupertinoPageScaffold(
child: SafeArea(
child: Padding(padding: const EdgeInsets.all(8), child: actions),
),
),
)
: MaterialApp(
home: Scaffold(
body: Padding(padding: const EdgeInsets.all(8), child: actions),
),
);
}
TextButton _materialButton(WidgetTester tester, String label) =>
tester.widget<TextButton>(
find
.ancestor(of: find.text(label), matching: find.byType(TextButton))
.first,
);
CupertinoButton _cupertinoButton(WidgetTester tester, String label) =>
tester.widget<CupertinoButton>(
find
.ancestor(
of: find.text(label),
matching: find.byType(CupertinoButton),
)
.first,
);
void main() {
testWidgets('Download saves the exact named bytes and reports it', (
tester,
) async {
final saved = <ArtifactFile>[];
await tester.pumpWidget(
_row(cupertino: false, bridge: _bridge(saved: saved)),
);
await tester.tap(find.text('Download'));
await tester.pumpAndSettle();
expect(saved, hasLength(1));
expect(saved.single.name, 'report.csv');
expect(saved.single.mimeType, 'text/csv');
expect(saved.single.bytes, _bytes);
expect(find.text('Downloaded report.csv.'), findsOneWidget);
});
testWidgets('Share starts one file transfer, not a link', (tester) async {
final shared = <ArtifactFile>[];
await tester.pumpWidget(
_row(cupertino: false, bridge: _bridge(shared: shared)),
);
await tester.tap(find.text('Share'));
await tester.pumpAndSettle();
expect(shared.single.name, 'report.csv');
expect(shared.single.byteLength, 3);
expect(find.text('File shared.'), findsOneWidget);
});
testWidgets('unsupported share is explained but download stays enabled', (
tester,
) async {
final saved = <ArtifactFile>[];
await tester.pumpWidget(
_row(
cupertino: false,
bridge: _bridge(saved: saved, shareSupported: false),
),
);
expect(find.text('No share on this host.'), findsOneWidget);
expect(_materialButton(tester, 'Share').onPressed, isNull);
expect(_materialButton(tester, 'Download').onPressed, isNotNull);
await tester.tap(find.text('Download'));
await tester.pumpAndSettle();
expect(saved, hasLength(1));
});
testWidgets('a slow fetch shows progress and cancel, then reports cancel', (
tester,
) async {
await tester.pumpWidget(
_row(
cupertino: false,
bridge: _bridge(),
fetch: (_) => Future<ArtifactFetchResult>.delayed(
const Duration(seconds: 30),
() => ArtifactFetchResult(status: 200, bytes: _bytes),
),
),
);
await tester.tap(find.text('Download'));
await tester.pump();
expect(find.text('Preparing file…'), findsOneWidget);
expect(find.byType(CircularProgressIndicator), findsOneWidget);
expect(_materialButton(tester, 'Download').onPressed, isNull);
expect(find.text('Cancel'), findsOneWidget);
await tester.tap(find.text('Cancel'));
await tester.pump();
expect(find.text('Download canceled.'), findsOneWidget);
expect(find.text('Cancel'), findsNothing);
await tester.pump(const Duration(seconds: 31));
});
testWidgets('both hosts keep the file actions whole at 320/2x dark', (
tester,
) async {
tester.view.physicalSize = const Size(640, 1200);
tester.view.devicePixelRatio = 2;
tester.platformDispatcher.textScaleFactorTestValue = 2;
tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue);
for (final cupertino in <bool>[false, true]) {
await tester.pumpWidget(_row(cupertino: cupertino));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(find.text('Download'), findsOneWidget);
expect(find.text('Share'), findsOneWidget);
if (cupertino) {
expect(_cupertinoButton(tester, 'Download').onPressed, isNotNull);
expect(find.byType(TextButton), findsNothing);
} else {
expect(_materialButton(tester, 'Download').onPressed, isNotNull);
expect(find.byType(CupertinoButton), findsNothing);
}
}
});
testWidgets('the gallery selection offers both file actions in its dialog', (
tester,
) async {
final saved = <ArtifactFile>[];
await tester.pumpWidget(
MaterialApp(
home: ArtifactGalleryPage(
steps: <JsonMap>[
step(
stage: 'review',
visit: 1,
artifacts: <JsonMap>[
artifact('report.csv', contentType: 'text/csv', sizeBytes: 3),
],
),
],
configuredEndpoint: _endpoint,
fetch: _fetch,
fileBridge: _bridge(saved: saved),
),
),
);
await tester.pumpAndSettle();
await tester.tap(find.text('report.csv'));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsOneWidget);
expect(find.text('Download'), findsOneWidget);
expect(find.text('Share'), findsOneWidget);
expect(find.text('Open'), findsOneWidget);
expect(find.text('Copy link'), findsOneWidget);
await tester.tap(find.text('Download'));
await tester.pumpAndSettle();
expect(saved.single.bytes, _bytes);
expect(find.text('Downloaded report.csv.'), findsOneWidget);
expect(find.byType(AlertDialog), findsOneWidget);
});
testWidgets('a host without file capabilities explains and disables both', (
tester,
) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Padding(
padding: const EdgeInsets.all(8),
child: ArtifactFileActions(
artifact: _record,
resolved: resolveArtifactUrl(_endpoint, _record.url)!,
fetch: _fetch,
),
),
),
),
);
expect(find.text('Download'), findsOneWidget);
expect(find.text('Share'), findsOneWidget);
expect(_materialButton(tester, 'Download').onPressed, isNull);
expect(_materialButton(tester, 'Share').onPressed, isNull);
expect(
find.text('Downloading files is not supported on this platform yet.'),
findsOneWidget,
);
expect(
find.text('File sharing is not supported on this platform yet.'),
findsOneWidget,
);
});
testWidgets('gallery selection keeps both actions at 320/2x dark', (
tester,
) async {
tester.view.physicalSize = const Size(640, 1200);
tester.view.devicePixelRatio = 2;
tester.platformDispatcher.textScaleFactorTestValue = 2;
tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue);
final steps = <JsonMap>[
step(
stage: 'review',
visit: 1,
artifacts: <JsonMap>[
artifact('report.csv', contentType: 'text/csv', sizeBytes: 3),
],
),
];
for (final cupertino in <bool>[false, true]) {
await tester.pumpWidget(
cupertino
? CupertinoApp(
theme: const CupertinoThemeData(brightness: Brightness.dark),
home: ArtifactGalleryPage(
steps: steps,
configuredEndpoint: _endpoint,
fetch: _fetch,
fileBridge: _bridge(),
),
)
: MaterialApp(
theme: ThemeData(brightness: Brightness.dark),
home: ArtifactGalleryPage(
steps: steps,
configuredEndpoint: _endpoint,
fetch: _fetch,
fileBridge: _bridge(),
),
),
);
await tester.pumpAndSettle();
await tester.tap(find.text('report.csv'));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(find.text('Download'), findsOneWidget);
expect(find.text('Share'), findsOneWidget);
expect(
cupertino
? find.byType(CupertinoAlertDialog)
: find.byType(AlertDialog),
findsOneWidget,
);
await tester.tap(find.text('Close'));
await tester.pumpAndSettle();
}
});
testWidgets(
'the viewer offers file actions only for a same-origin artifact',
(tester) async {
final local = recordedArtifact(
'clip.mp4',
url: '/artifacts/1/1/clip.mp4',
contentType: 'video/mp4',
);
final external = recordedArtifact(
'elsewhere.png',
url: 'https://elsewhere.test/elsewhere.png',
contentType: 'image/png',
);
final localGroup = visitGroup(artifacts: <ArtifactRecord>[local]);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ArtifactViewerPage(
key: const ValueKey<String>('local'),
groups: <ArtifactGroup>[localGroup],
selectedIdentity: artifactVisitIdentity(localGroup, local),
configuredEndpoint: _endpoint,
fetch: _fetch,
fileBridge: _bridge(),
openExternal: (_) async => true,
),
),
),
);
await tester.pumpAndSettle();
expect(find.text('Download'), findsOneWidget);
expect(find.text('Share'), findsOneWidget);
final externalGroup = visitGroup(artifacts: <ArtifactRecord>[external]);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ArtifactViewerPage(
key: const ValueKey<String>('external'),
groups: <ArtifactGroup>[externalGroup],
selectedIdentity: artifactVisitIdentity(externalGroup, external),
configuredEndpoint: _endpoint,
fetch: _fetch,
fileBridge: _bridge(),
openExternal: (_) async => true,
),
),
),
);
await tester.pumpAndSettle();
expect(find.text('Download'), findsNothing);
expect(find.text('Share'), findsNothing);
expect(find.text('Open'), findsOneWidget);
},
);
}
@@ -0,0 +1,229 @@
import 'dart:async';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/artifacts/actions/artifact_file.dart';
import 'package:pipelines_app/features/artifacts/actions/artifact_file_bridge.dart';
import 'package:pipelines_app/features/artifacts/actions/artifact_file_controller.dart';
import 'package:pipelines_app/features/artifacts/actions/artifact_transfer.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_url.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_fetch.dart';
const _url = 'http://127.0.0.1:8081/artifacts/1/1/report.csv';
final Uint8List _bytes = Uint8List.fromList(<int>[10, 20, 30, 40]);
final ArtifactRecord _record = ArtifactRecord.fromJson(<String, dynamic>{
'name': 'public/reports/report.csv',
'url': '/artifacts/1/1/report.csv',
'content_type': 'text/csv; charset=utf-8',
'size_bytes': 4,
});
ArtifactFileActionsController _controller({
ArtifactFetch? fetch,
ArtifactFileBridge bridge = const ArtifactFileBridge(),
}) => ArtifactFileActionsController(
artifact: _record,
resolved: resolveArtifactUrl('ws://127.0.0.1:8081/connect', _record.url)!,
fetch: fetch ?? (_) async => ArtifactFetchResult(status: 200, bytes: _bytes),
bridge: bridge,
);
ArtifactFileBridge _bridge({
List<ArtifactFile>? saved,
List<ArtifactFile>? shared,
ArtifactTransferResult shareResult = const ArtifactTransferResult(
ArtifactTransferState.shared,
'File shared.',
),
bool downloadSupported = true,
bool shareSupported = true,
}) => ArtifactFileBridge(
downloadSupported: downloadSupported,
shareSupported: shareSupported,
downloadUnsupportedMessage: 'No download here.',
shareUnsupportedMessage: 'No share here.',
download: (file) async {
saved?.add(file);
return ArtifactTransferResult(
ArtifactTransferState.saved,
'Downloaded ${file.name}.',
);
},
share: (file) async {
shared?.add(file);
return shareResult;
},
);
void main() {
test('download carries the exact named, typed bytes', () async {
final saved = <ArtifactFile>[];
final controller = _controller(bridge: _bridge(saved: saved));
await controller.download();
expect(saved, hasLength(1));
expect(saved.single.name, 'report.csv');
expect(saved.single.mimeType, 'text/csv');
expect(saved.single.bytes, _bytes);
expect(controller.status, 'Downloaded report.csv.');
expect(controller.busy, isFalse);
});
test('share uses a file, not a link, and reports when shared', () async {
final shared = <ArtifactFile>[];
final fetched = <Uri>[];
final controller = _controller(
bridge: _bridge(shared: shared),
fetch: (uri) async {
fetched.add(uri);
return ArtifactFetchResult(status: 200, bytes: _bytes);
},
);
await controller.share();
expect(fetched, [Uri.parse(_url)]);
expect(shared, hasLength(1));
expect(shared.single.name, 'report.csv');
expect(shared.single.mimeType, 'text/csv');
expect(shared.single.bytes, _bytes);
expect(controller.canShare, isTrue);
expect(controller.status, 'File shared.');
});
test('unsupported sharing leaves download working', () async {
final saved = <ArtifactFile>[];
final shared = <ArtifactFile>[];
var fetches = 0;
final controller = _controller(
fetch: (_) async {
fetches += 1;
return ArtifactFetchResult(status: 200, bytes: _bytes);
},
bridge: _bridge(saved: saved, shared: shared, shareSupported: false),
);
await controller.share();
expect(shared, isEmpty);
expect(fetches, 0);
expect(controller.status, 'No share here.');
expect(controller.canDownload, isTrue);
await controller.download();
expect(saved, hasLength(1));
expect(controller.status, 'Downloaded report.csv.');
});
test(
'an HTTP or network fetch failure is reported, never transferred',
() async {
final saved = <ArtifactFile>[];
final bridge = _bridge(saved: saved);
final notFound = _controller(
fetch: (_) async =>
ArtifactFetchResult(status: 404, bytes: Uint8List(0)),
bridge: bridge,
);
await notFound.download();
expect(notFound.status, 'Could not fetch the artifact (HTTP 404).');
expect(saved, isEmpty);
expect(notFound.busy, isFalse);
final offline = _controller(
fetch: (_) async => throw const ArtifactFetchException('network down'),
bridge: bridge,
);
await offline.download();
expect(offline.status, contains('network down'));
expect(saved, isEmpty);
},
);
test(
'cancel during a slow fetch starts no transfer and ignores the result',
() async {
final pending = Completer<ArtifactFetchResult>();
final saved = <ArtifactFile>[];
final controller = _controller(
fetch: (_) => pending.future,
bridge: _bridge(saved: saved),
);
final action = controller.download();
await Future<void>.delayed(Duration.zero);
expect(controller.busy, isTrue);
expect(controller.canCancel, isTrue);
expect(controller.status, 'Preparing file…');
controller.cancel();
expect(controller.busy, isFalse);
expect(controller.status, 'Download canceled.');
pending.complete(ArtifactFetchResult(status: 200, bytes: _bytes));
await action;
expect(saved, isEmpty);
expect(controller.status, 'Download canceled.');
},
);
test('one tap starts one transfer even when called twice', () async {
var fetches = 0;
final pending = Completer<ArtifactFetchResult>();
final saved = <ArtifactFile>[];
final controller = _controller(
fetch: (_) {
fetches += 1;
return pending.future;
},
bridge: _bridge(saved: saved),
);
final first = controller.download();
final second = controller.download();
await Future<void>.delayed(Duration.zero);
expect(fetches, 1);
pending.complete(ArtifactFetchResult(status: 200, bytes: _bytes));
await first;
await second;
expect(saved, hasLength(1));
});
test('a ready share reuses prepared bytes on the fresh tap', () async {
var fetches = 0;
var shares = 0;
final controller = _controller(
fetch: (_) async {
fetches += 1;
return ArtifactFetchResult(status: 200, bytes: _bytes);
},
bridge: ArtifactFileBridge(
shareSupported: true,
share: (file) async {
shares += 1;
return shares == 1
? const ArtifactTransferResult(
ArtifactTransferState.ready,
'File ready. Tap Share again to choose where to send it.',
)
: const ArtifactTransferResult(
ArtifactTransferState.shared,
'File shared.',
);
},
),
);
await controller.share();
expect(controller.status, contains('Tap Share again'));
await controller.share();
expect(fetches, 1);
expect(shares, 2);
expect(controller.status, 'File shared.');
});
}
@@ -0,0 +1,99 @@
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/artifacts/actions/artifact_file.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart';
ArtifactRecord _record(
String name, {
String contentType = '',
String url = '/artifacts/1/1/report.csv',
}) => ArtifactRecord.fromJson(<String, dynamic>{
'name': name,
'url': url,
'content_type': contentType,
'size_bytes': 10,
});
void main() {
test('a recorded name keeps only its basename', () {
final file = artifactFileFor(
artifact: _record('public/reports/result.csv', contentType: 'text/csv'),
url: Uri.parse('http://127.0.0.1:8081/artifacts/1/1/result.csv'),
bytes: Uint8List.fromList(<int>[1, 2, 3]),
);
expect(file.name, 'result.csv');
expect(file.mimeType, 'text/csv');
expect(file.byteLength, 3);
expect(file.bytes, <int>[1, 2, 3]);
});
test(
'a recorded name with backslashes and control characters is repaired',
() {
final name = artifactFileName(
_record('C:\\tmp\\odd\u0001name.csv'),
Uri.parse('http://127.0.0.1/a.csv'),
);
expect(name, 'odd_name.csv');
},
);
test('a missing name falls back to the url basename then artifact', () {
expect(
artifactFileName(
_record(''),
Uri.parse('http://127.0.0.1:8081/artifacts/1/1/from-url.csv'),
),
'from-url.csv',
);
expect(
artifactFileName(_record('public/'), Uri.parse('http://127.0.0.1/')),
'artifact',
);
expect(
artifactFileName(_record('..'), Uri.parse('http://127.0.0.1/')),
'artifact',
);
});
test('the recorded media type loses parameters and is validated', () {
expect(
artifactFileMimeType(
_record('a.txt', contentType: 'Text/Plain; charset=utf-8'),
),
'text/plain',
);
expect(
artifactFileMimeType(_record('a.bin')),
artifactFileFallbackMimeType,
);
expect(
artifactFileMimeType(_record('a.bin', contentType: 'not a mime')),
artifactFileFallbackMimeType,
);
});
test('a missing name or MIME type gets an explicit fallback notice', () {
final url = Uri.parse('http://127.0.0.1/artifacts/1/1/kept.csv');
expect(
artifactFileRecordingNotice(
_record('kept.csv', contentType: 'text/csv'),
url,
),
isNull,
);
expect(
artifactFileRecordingNotice(_record('', contentType: 'text/csv'), url),
'No usable recorded name; the file is saved as kept.csv.',
);
expect(
artifactFileRecordingNotice(_record('kept.csv'), url),
'No usable recorded MIME type; the file is saved as '
'application/octet-stream.',
);
});
}
@@ -266,6 +266,39 @@ void main() {
];
expect(artifactGroups(steps).single.artifacts.length, 1);
});
test('visitArtifactGroup matches the pane group of a later visit', () {
final steps = <Map<String, dynamic>>[
step(
stage: 'a',
sequence: 1,
visit: 1,
artifacts: <Map<String, dynamic>>[
artifact('public/shared.csv'),
artifact('a.csv'),
],
),
step(
stage: 'a',
sequence: 2,
visit: 2,
artifacts: <Map<String, dynamic>>[
artifact('public/shared.csv'),
artifact('b.csv'),
],
),
];
final group = visitArtifactGroup(steps, 1)!;
expect(group.stageKey, 'a');
expect(group.visit, 2);
expect(group.artifacts.map((record) => record.name), <String>['b.csv']);
expect(
visitArtifacts(steps[1], steps).map((record) => record.name),
<String>['b.csv'],
);
expect(visitArtifactGroup(steps, 2), isNull);
expect(visitArtifactGroup(steps, -1), isNull);
});
});
group('unavailable and empty captures', () {
@@ -0,0 +1,181 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/attention/notify/notification_controller.dart';
import 'package:pipelines_app/features/attention/notify/notification_store.dart';
import 'notification_test_support.dart';
void main() {
group('the seed never notifies', () {
test('an already failed and waiting list is silent', () async {
final attention = attentionController();
final bridge = FakeNotificationBridge();
final notify = NotificationController(
store: MemoryNotificationStore(),
bridge: bridge,
);
addTearDown(attention.dispose);
addTearDown(notify.dispose);
await attention.load();
await notify.load();
attention.seedRows([
runSummary(1, 'failed', diagnostic: 'Stage 3 stopped'),
runSummary(2, 'waiting'),
]);
expect(attention.transitions, isEmpty);
expect(publish(notify, attention), 0);
expect(bridge.shown, isEmpty);
});
});
group('a live transition notifies once', () {
test('the frame\'s own words and identity are used', () async {
final attention = attentionController();
final bridge = FakeNotificationBridge(permission: 'granted');
final notify = NotificationController(
store: MemoryNotificationStore(),
bridge: bridge,
);
addTearDown(attention.dispose);
addTearDown(notify.dispose);
await attention.load();
await notify.load();
expect(notify.canNotify, isTrue);
attention.seedRows([runSummary(1, 'running', name: 'nightly')]);
attention.observeFrame(
runFrame(
1,
'failed',
name: 'nightly',
title: 'Nightly audit',
diagnostic: 'Stage 3 stopped',
finishedAt: '2026-10-22T11:00:00Z',
),
);
expect(publish(notify, attention), 1);
final message = bridge.shown.single;
expect(message.title, 'A run failed');
expect(message.body, 'Nightly audit \u00b7 nightly');
expect(message.tag, '1:Failed');
expect(message.runId, 1);
});
test('a duplicate frame and a republished list stay silent', () async {
final attention = attentionController();
final bridge = FakeNotificationBridge(permission: 'granted');
final notify = NotificationController(
store: MemoryNotificationStore(),
bridge: bridge,
);
addTearDown(attention.dispose);
addTearDown(notify.dispose);
await attention.load();
await notify.load();
attention.seedRows([runSummary(1, 'running')]);
attention.observeFrame(runFrame(1, 'failed'));
expect(publish(notify, attention), 1);
attention.observeFrame(runFrame(1, 'failed'));
expect(attention.transitions, hasLength(1));
expect(publish(notify, attention), 0);
expect(bridge.shown, hasLength(1));
});
test('a reconnect reseed cannot replay the notification', () async {
final attention = attentionController();
final bridge = FakeNotificationBridge(permission: 'granted');
final notify = NotificationController(
store: MemoryNotificationStore(),
bridge: bridge,
);
addTearDown(attention.dispose);
addTearDown(notify.dispose);
await attention.load();
await notify.load();
attention.seedRows([runSummary(1, 'running')]);
attention.observeFrame(runFrame(1, 'failed'));
expect(publish(notify, attention), 1);
attention.resetForReconnect();
attention.seedRows([runSummary(1, 'failed')], reconnect: true);
expect(publish(notify, attention), 0);
attention.observeFrame(runFrame(1, 'failed'));
expect(publish(notify, attention), 0);
expect(bridge.shown, hasLength(1));
});
test('a rebuilt controller with the same store stays silent', () async {
final store = MemoryNotificationStore();
final bridge = FakeNotificationBridge(permission: 'granted');
final attention = attentionController();
final notify = NotificationController(store: store, bridge: bridge);
addTearDown(attention.dispose);
addTearDown(notify.dispose);
await attention.load();
await notify.load();
attention.seedRows([runSummary(1, 'running')]);
attention.observeFrame(runFrame(1, 'failed'));
expect(publish(notify, attention), 1);
await settle();
final restarted = NotificationController(store: store, bridge: bridge);
addTearDown(restarted.dispose);
await restarted.load();
expect(restarted.notified, contains('1:Failed'));
expect(publish(restarted, attention), 0);
expect(bridge.shown, hasLength(1));
});
test('a later failure of another run notifies independently', () async {
final attention = attentionController();
final bridge = FakeNotificationBridge(permission: 'granted');
final notify = NotificationController(
store: MemoryNotificationStore(),
bridge: bridge,
);
addTearDown(attention.dispose);
addTearDown(notify.dispose);
await attention.load();
await notify.load();
attention.seedRows([runSummary(1, 'running'), runSummary(2, 'running')]);
attention.observeFrame(runFrame(1, 'failed'));
expect(publish(notify, attention), 1);
attention.observeFrame(runFrame(2, 'failed'));
expect(publish(notify, attention), 1);
expect(bridge.shown, hasLength(2));
expect(bridge.shown.map((m) => m.tag), ['1:Failed', '2:Failed']);
});
test('a transition for a run that left is never re-posted', () async {
final attention = attentionController();
final bridge = FakeNotificationBridge(permission: 'granted');
final notify = NotificationController(
store: MemoryNotificationStore(),
bridge: bridge,
);
addTearDown(attention.dispose);
addTearDown(notify.dispose);
await attention.load();
await notify.load();
attention.seedRows([runSummary(1, 'running')]);
attention.observeFrame(runFrame(1, 'failed'));
expect(publish(notify, attention), 1);
// Publishing the leaving frame forgets the identity; republishing the
// accumulated list afterwards must not resurrect the old alert.
attention.observeFrame(runFrame(1, 'running'));
expect(publish(notify, attention), 0);
expect(publish(notify, attention), 0);
expect(bridge.shown, hasLength(1));
});
});
}
@@ -0,0 +1,238 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/attention/domain/attention_models.dart';
import 'package:pipelines_app/features/attention/notify/notification_bridge.dart';
import 'package:pipelines_app/features/attention/notify/notification_controller.dart';
import 'package:pipelines_app/features/attention/notify/notification_models.dart';
import 'package:pipelines_app/features/attention/notify/notification_store.dart';
import 'notification_test_support.dart';
void main() {
group('a dismissed entry never notifies', () {
test('the detector suppresses it and nothing is posted', () async {
final attention = attentionController();
final bridge = FakeNotificationBridge(permission: 'granted');
final notify = NotificationController(
store: MemoryNotificationStore(),
bridge: bridge,
);
addTearDown(attention.dispose);
addTearDown(notify.dispose);
await attention.load();
await notify.load();
attention.seedRows([runSummary(1, 'running')]);
await attention.dismiss(attentionEntryFor(runSummary(1, 'failed'))!);
attention.observeFrame(runFrame(1, 'failed'));
expect(attention.transitions, isEmpty);
expect(publish(notify, attention), 0);
expect(bridge.shown, isEmpty);
});
test(
'the publish guard records but does not show a dismissed key',
() async {
final bridge = FakeNotificationBridge(permission: 'granted');
final notify = NotificationController(
store: MemoryNotificationStore(),
bridge: bridge,
);
addTearDown(notify.dispose);
await notify.load();
final transition = transitionFor(4);
expect(
notify.publishTransitions(
[transition],
qualifying: {transition.key},
dismissed: {transition.key},
),
0,
);
expect(notify.notified, contains(transition.key));
expect(bridge.shown, isEmpty);
},
);
});
group('batching and the tap seam', () {
test('a burst posts a bounded batch in order, then the rest', () async {
final bridge = FakeNotificationBridge(permission: 'granted');
final notify = NotificationController(
store: MemoryNotificationStore(),
bridge: bridge,
);
addTearDown(notify.dispose);
await notify.load();
final transitions = [for (var id = 1; id <= 7; id++) transitionFor(id)];
final qualifying = {for (final t in transitions) t.key};
expect(notify.publishTransitions(transitions, qualifying: qualifying), 5);
expect(bridge.shown.map((m) => m.runId), [1, 2, 3, 4, 5]);
expect(notify.publishTransitions(transitions, qualifying: qualifying), 2);
expect(bridge.shown.map((m) => m.runId), [1, 2, 3, 4, 5, 6, 7]);
});
test('a tap reports the run and never navigates here', () async {
final bridge = FakeNotificationBridge(permission: 'granted');
final notify = NotificationController(
store: MemoryNotificationStore(),
bridge: bridge,
);
addTearDown(notify.dispose);
await notify.load();
final opened = <int>[];
notify.onOpenRun = opened.add;
expect(
notify.publishTransitions([transitionFor(3)], qualifying: {'3:Failed'}),
1,
);
bridge.taps.single!.call();
expect(opened, [3]);
});
});
group('the ledger cannot be read into by a caller', () {
test('notified is an unmodifiable copy', () async {
final bridge = FakeNotificationBridge(permission: 'granted');
final notify = NotificationController(
store: MemoryNotificationStore(),
bridge: bridge,
);
addTearDown(notify.dispose);
await notify.load();
expect(
notify.publishTransitions([transitionFor(1)], qualifying: {'1:Failed'}),
1,
);
expect(notify.notified, {'1:Failed'});
expect(() => notify.notified.add('9:Failed'), throwsUnsupportedError);
expect(notify.notified, {'1:Failed'});
});
});
group('an unavailable store cannot reach the UI', () {
test('a failed read and write still notify and never throw', () async {
final store = MemoryNotificationStore()
..failReads = true
..failWrites = true;
final bridge = FakeNotificationBridge(permission: 'granted');
final notify = NotificationController(store: store, bridge: bridge);
addTearDown(notify.dispose);
await expectLater(notify.load(), completes);
expect(notify.loaded, isTrue);
expect(notify.notified, isEmpty);
expect(
notify.publishTransitions([transitionFor(1)], qualifying: {'1:Failed'}),
1,
);
await settle();
expect(bridge.shown, hasLength(1));
});
test('a throwing platform post is reported, not propagated', () async {
final bridge = _ThrowingBridge();
final notify = NotificationController(
store: MemoryNotificationStore(),
bridge: bridge,
);
addTearDown(notify.dispose);
await notify.load();
expect(
notify.publishTransitions([transitionFor(1)], qualifying: {'1:Failed'}),
0,
);
expect(notify.notified, contains('1:Failed'));
});
test('ledger writes land in call order, one at a time', () async {
final store = _SlowStore();
final bridge = FakeNotificationBridge(permission: 'granted');
final notify = NotificationController(store: store, bridge: bridge);
addTearDown(notify.dispose);
await notify.load();
notify.publishTransitions([transitionFor(1)], qualifying: {'1:Failed'});
notify.publishTransitions(
[transitionFor(2)],
qualifying: {'1:Failed', '2:Failed'},
);
await Future<void>.delayed(const Duration(milliseconds: 40));
expect(store.maxActive, 1, reason: 'the writes must be serialized');
expect(store.stored, contains('"1:Failed"'));
expect(store.stored, contains('"2:Failed"'));
expect(store.writes.last, store.stored);
});
});
group('the platform seam', () {
test('the non-web bridge reports unsupported honestly', () async {
final bridge = createNotificationBridge();
expect(bridge.environment().supported, isFalse);
final notify = NotificationController(
store: MemoryNotificationStore(),
bridge: bridge,
);
addTearDown(notify.dispose);
await notify.load();
expect(notify.permission, NotificationPermissionState.unsupported);
expect(
bridge.show(
const NotificationMessage(
runId: 1,
title: 'A run failed',
body: 'release',
tag: '1:Failed',
),
),
isFalse,
);
});
});
}
/// A store whose writes take a tick, so a racing implementation would overlap
/// them and the last value to land would be the older snapshot.
class _SlowStore implements NotificationStore {
String? stored;
int active = 0;
int maxActive = 0;
final List<String> writes = [];
@override
Future<String?> read() async => stored;
@override
Future<bool> write(String value) async {
active++;
if (active > maxActive) maxActive = active;
await Future<void>.delayed(const Duration(milliseconds: 2));
stored = value;
writes.add(value);
active--;
return true;
}
}
class _ThrowingBridge implements NotificationBridge {
@override
NotificationEnvironment environment() => const NotificationEnvironment(
supported: true,
secureContext: true,
permission: 'granted',
);
@override
Future<String> requestPermission() async => 'granted';
@override
bool show(NotificationMessage message, {void Function()? onTap}) =>
throw StateError('the browser refused to construct a notification');
}
@@ -0,0 +1,143 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/attention/notify/notification_ledger.dart';
import 'notification_test_support.dart';
void main() {
group('the identity is the run and kind', () {
test('two failures of one run are the same announced state', () {
final first = transitionFor(7, finishedAt: '2026-10-22T09:10:00Z');
final second = transitionFor(7, finishedAt: '2026-10-22T11:30:00Z');
expect(notificationIdentity(first), '7:Failed');
expect(notificationIdentity(second), '7:Failed');
});
test('a waiting run needs no finish time to have an identity', () {
final entry = transitionFor(7, status: 'waiting', finishedAt: '');
expect(notificationIdentity(entry), '7:Decision');
});
test('the kind separates a decision from a failure of one run', () {
expect(
notificationIdentity(transitionFor(7)),
isNot(notificationIdentity(transitionFor(7, status: 'waiting'))),
);
});
});
group('the qualifying set is the attention surface\'s own keys', () {
test('only failed and human-waiting runs qualify', () {
expect(
notificationQualifyingKeys([
runSummary(1, 'failed'),
runSummary(2, 'waiting'),
runSummary(3, 'running'),
runSummary(4, 'succeeded'),
runSummary(5, 'queued'),
runSummary(6, 'waiting', exportPending: 2),
]),
{'1:Failed', '2:Decision'},
);
});
test('a duplicate row and a malformed id add nothing', () {
expect(
notificationQualifyingKeys([
runSummary(1, 'failed'),
runSummary(1, 'failed'),
{'id': 0, 'status': 'failed'},
{'id': 'not a run', 'status': 'failed'},
]),
{'1:Failed'},
);
expect(notificationQualifyingKeys(null), isEmpty);
});
test('the frame key form is read too', () {
expect(notificationQualifyingKeys([runFrame(9, 'failed')]), {'9:Failed'});
});
});
group('the ledger records identities', () {
test('recording is idempotent and never mutates the original', () {
const base = NotificationLedger();
final once = base.recording('7:Failed');
final twice = once.recording('7:Failed');
expect(base.notified, isEmpty);
expect(once.hasNotified('7:Failed'), isTrue);
expect(twice.notified, {'7:Failed'});
});
test('asked is carried without touching the identities', () {
final asked = const NotificationLedger(notified: {'a'}).withAsked(true);
expect(asked.asked, isTrue);
expect(asked.notified, {'a'});
});
});
group('pruning keeps only the current qualifying run', () {
test('a run that left the state is forgotten; asked survives', () {
final ledger = const NotificationLedger(
notified: {'7:Decision', '8:Failed'},
).withAsked(true);
final pruned = ledger.pruning({'8:Failed'});
expect(pruned.notified, {'8:Failed'});
expect(pruned.asked, isTrue);
});
test('nothing to drop returns the same ledger', () {
const ledger = NotificationLedger(notified: {'7:Failed'});
expect(identical(ledger.pruning({'7:Failed'}), ledger), isTrue);
});
test('a timestamped identity from an older build is dropped', () {
final old = decodeNotificationLedger(
'{"asked":false,"notified":["7:Decision@2026-10-22T11:00:00.000"]}',
);
expect(old.notified, hasLength(1));
expect(old.pruning({'7:Decision'}).notified, isEmpty);
});
});
group('persistence is total', () {
test('a round trip keeps the asked flag and the identities', () {
final ledger = const NotificationLedger(
notified: {'b', 'a'},
).withAsked(true);
final decoded = decodeNotificationLedger(
encodeNotificationLedger(ledger),
);
expect(decoded.asked, isTrue);
expect(decoded.notified, {'a', 'b'});
});
test('an unchanged ledger always encodes to the same bytes', () {
final first = encodeNotificationLedger(
const NotificationLedger(notified: {'b', 'a'}),
);
final second = encodeNotificationLedger(
const NotificationLedger(notified: {'a', 'b'}),
);
expect(first, second);
});
test('blank, malformed and wrong-typed values never throw', () {
expect(decodeNotificationLedger(null).notified, isEmpty);
expect(decodeNotificationLedger('').asked, isFalse);
expect(decodeNotificationLedger('not json').notified, isEmpty);
expect(decodeNotificationLedger('[]').notified, isEmpty);
expect(decodeNotificationLedger('"text"').notified, isEmpty);
expect(
decodeNotificationLedger(
'{"asked":"yes","notified":[1,null,"a",""]}',
).notified,
{'a'},
);
expect(
decodeNotificationLedger('{"asked":"yes"}').asked,
isFalse,
reason: 'only a real true counts as asked',
);
});
});
}
@@ -0,0 +1,158 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/attention/domain/attention_models.dart';
import 'package:pipelines_app/features/attention/notify/notification_models.dart';
NotificationEnvironment _env({
bool supported = true,
bool secure = true,
String permission = 'default',
}) => NotificationEnvironment(
supported: supported,
secureContext: secure,
permission: permission,
);
void main() {
group('permission state is the platform\'s own answer', () {
test('an unsupported API and an insecure page win over the word', () {
expect(
notificationStateOf(_env(supported: false, permission: 'granted')),
NotificationPermissionState.unsupported,
);
expect(
notificationStateOf(_env(secure: false, permission: 'granted')),
NotificationPermissionState.needsSecureContext,
);
});
test('granted is never assumed from an unrecognised word', () {
expect(
notificationStateOf(_env(permission: 'prompt')),
NotificationPermissionState.notRequested,
);
expect(
notificationStateOf(_env(permission: '')),
NotificationPermissionState.notRequested,
);
expect(
notificationStateOf(_env(permission: 'granted')),
NotificationPermissionState.granted,
);
expect(
notificationStateOf(_env(permission: 'denied')),
NotificationPermissionState.denied,
);
});
test('each state carries the browser model\'s own wire word', () {
expect(NotificationPermissionState.unsupported.wireName, 'unsupported');
expect(
NotificationPermissionState.needsSecureContext.wireName,
'insecure',
);
expect(NotificationPermissionState.notRequested.wireName, 'default');
expect(NotificationPermissionState.granted.wireName, 'granted');
expect(NotificationPermissionState.denied.wireName, 'denied');
});
});
group('the permission view', () {
test('only a still-undecided page can request', () {
final view = notificationPermissionView(
NotificationPermissionState.notRequested,
);
expect(view.canRequest, isTrue);
expect(view.actionLabel, notificationRequestLabel);
expect(view.body, notificationDefaultCopy);
for (final state in [
NotificationPermissionState.unsupported,
NotificationPermissionState.needsSecureContext,
NotificationPermissionState.granted,
NotificationPermissionState.denied,
]) {
final other = notificationPermissionView(state);
expect(other.canRequest, isFalse, reason: '$state');
expect(other.actionLabel, isNull, reason: '$state');
}
});
test('asked only changes the undecided wording', () {
expect(
notificationPermissionView(
NotificationPermissionState.notRequested,
asked: true,
).body,
notificationDefaultAskedCopy,
);
expect(
notificationPermissionView(
NotificationPermissionState.denied,
asked: true,
).body,
notificationDeniedCopy,
);
});
test('every unavailable state names the in-app channel', () {
for (final state in [
NotificationPermissionState.unsupported,
NotificationPermissionState.needsSecureContext,
NotificationPermissionState.denied,
]) {
expect(
notificationPermissionView(state).body,
contains('in-app Needs you surface'),
reason: '$state',
);
}
});
});
group('notification content is the entry\'s own words', () {
test('the headline is the kind, nothing invented', () {
expect(
notificationAlertTitle(AttentionKind.decision),
'A run needs your decision',
);
expect(notificationAlertTitle(AttentionKind.failed), 'A run failed');
});
test('the body is the run label then its pipeline', () {
final entry = attentionEntryFor({
'id': 7,
'name': 'nightly-audit',
'title': 'Nightly audit',
'status': 'failed',
'diagnostic': 'Stage 3 stopped',
'created_at': '2026-10-22T09:00:00Z',
'finished_at': '2026-10-22T09:10:00Z',
})!;
expect(
notificationAlertBody(entry),
'Nightly audit \u00b7 nightly-audit',
);
});
test('a blank or equal pipeline is never repeated', () {
final untitled = attentionEntryFor({
'id': 7,
'name': 'release',
'status': 'failed',
'created_at': '2026-10-22T09:00:00Z',
'finished_at': '2026-10-22T09:10:00Z',
})!;
expect(notificationAlertBody(untitled), 'release');
final nameless = attentionEntryFor({
'id': 8,
'name': '',
'title': 'A title',
'status': 'failed',
'created_at': '2026-10-22T09:00:00Z',
'finished_at': '2026-10-22T09:10:00Z',
})!;
expect(notificationAlertBody(nameless), 'A title');
});
});
}
@@ -0,0 +1,103 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/attention/notify/notification_controller.dart';
import 'package:pipelines_app/features/attention/notify/notification_models.dart';
import 'package:pipelines_app/features/attention/notify/notification_store.dart';
import 'notification_test_support.dart';
void main() {
group('permission is only ever the platform\'s answer', () {
test('an unsupported platform is never asked and never posts', () async {
final bridge = FakeNotificationBridge(supported: false);
final notify = NotificationController(
store: MemoryNotificationStore(),
bridge: bridge,
);
addTearDown(notify.dispose);
await notify.load();
expect(notify.permission, NotificationPermissionState.unsupported);
expect(
await notify.requestPermission(),
NotificationPermissionState.unsupported,
);
expect(bridge.requests, 0);
expect(
notify.publishTransitions([transitionFor(1)], qualifying: {'1:Failed'}),
0,
);
expect(bridge.shown, isEmpty);
});
test('an insecure page reports needsSecureContext', () async {
final bridge = FakeNotificationBridge(secureContext: false);
final notify = NotificationController(
store: MemoryNotificationStore(),
bridge: bridge,
);
addTearDown(notify.dispose);
await notify.load();
expect(notify.permission, NotificationPermissionState.needsSecureContext);
await notify.requestPermission();
expect(bridge.requests, 0);
});
test('a default page is asked once and follows the real answer', () async {
final store = MemoryNotificationStore();
final bridge = FakeNotificationBridge(answer: 'granted');
final notify = NotificationController(store: store, bridge: bridge);
addTearDown(notify.dispose);
await notify.load();
expect(notify.permission, NotificationPermissionState.notRequested);
expect(notify.canNotify, isFalse);
final state = await notify.requestPermission();
expect(bridge.requests, 1);
expect(state, NotificationPermissionState.granted);
expect(notify.canNotify, isTrue);
expect(notify.asked, isTrue);
await settle();
expect(store.stored, contains('"asked":true'));
});
test('a denied answer is never re-prompted', () async {
final bridge = FakeNotificationBridge(permission: 'denied');
final notify = NotificationController(
store: MemoryNotificationStore(),
bridge: bridge,
);
addTearDown(notify.dispose);
await notify.load();
expect(notify.permission, NotificationPermissionState.denied);
expect(
await notify.requestPermission(),
NotificationPermissionState.denied,
);
expect(bridge.requests, 0);
expect(
notify.publishTransitions([transitionFor(1)], qualifying: {'1:Failed'}),
0,
);
expect(bridge.shown, isEmpty);
});
test(
'a prompt that grants nothing keeps the honest default wording',
() async {
final bridge = FakeNotificationBridge(answer: 'default');
final notify = NotificationController(
store: MemoryNotificationStore(),
bridge: bridge,
);
addTearDown(notify.dispose);
await notify.load();
final state = await notify.requestPermission();
expect(state, NotificationPermissionState.notRequested);
expect(notify.asked, isTrue);
expect(notify.canNotify, isFalse);
},
);
});
}
@@ -0,0 +1,93 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/attention/notify/notification_controller.dart';
import 'package:pipelines_app/features/attention/notify/notification_store.dart';
import 'notification_test_support.dart';
/// A run that leaves a qualifying state and enters it again is a new event.
///
/// A waiting run has no `finished_at`, and its creation time never changes, so
/// both gates of one run carry exactly the same timestamps. These tests pin the
/// behaviour that was silently dropped when the identity included that marker.
void main() {
test('a second decision gate of the same run notifies again', () async {
final attention = attentionController();
final bridge = FakeNotificationBridge(permission: 'granted');
final notify = NotificationController(
store: MemoryNotificationStore(),
bridge: bridge,
);
addTearDown(attention.dispose);
addTearDown(notify.dispose);
await attention.load();
await notify.load();
attention.seedRows([runSummary(7, 'running')]);
attention.observeFrame(runFrame(7, 'waiting', finishedAt: ''));
expect(publish(notify, attention), 1);
expect(bridge.shown.single.tag, '7:Decision');
attention.observeFrame(runFrame(7, 'running'));
expect(publish(notify, attention), 0);
attention.observeFrame(runFrame(7, 'waiting', finishedAt: ''));
expect(attention.transitions, hasLength(2));
expect(publish(notify, attention), 1);
expect(bridge.shown, hasLength(2));
// The browser coalesces by run+kind, so both alerts share one tag.
expect(bridge.shown.map((m) => m.tag).toSet(), {'7:Decision'});
});
test(
'a second decision gate notifies even without the leaving publish',
() async {
final attention = attentionController();
final bridge = FakeNotificationBridge(permission: 'granted');
final notify = NotificationController(
store: MemoryNotificationStore(),
bridge: bridge,
);
addTearDown(attention.dispose);
addTearDown(notify.dispose);
await attention.load();
await notify.load();
attention.seedRows([runSummary(7, 'running')]);
attention.observeFrame(runFrame(7, 'waiting', finishedAt: ''));
expect(publish(notify, attention), 1);
// The caller misses the frame that leaves the state; the detector still
// creates a new instance for the next gate, so it must notify again.
attention.observeFrame(runFrame(7, 'running'));
attention.observeFrame(runFrame(7, 'waiting', finishedAt: ''));
expect(publish(notify, attention), 1);
expect(bridge.shown, hasLength(2));
expect(bridge.shown.map((m) => m.tag).toSet(), {'7:Decision'});
},
);
test('a coalesced backlog of two gates notifies once', () async {
final attention = attentionController();
final bridge = FakeNotificationBridge(permission: 'granted');
final notify = NotificationController(
store: MemoryNotificationStore(),
bridge: bridge,
);
addTearDown(attention.dispose);
addTearDown(notify.dispose);
await attention.load();
await notify.load();
attention.seedRows([runSummary(7, 'running')]);
attention.observeFrame(runFrame(7, 'waiting', finishedAt: ''));
attention.observeFrame(runFrame(7, 'running'));
attention.observeFrame(runFrame(7, 'waiting', finishedAt: ''));
expect(attention.transitions, hasLength(2));
// Both gates were folded before the caller published; the current state is
// what the operator should be told about, once.
expect(publish(notify, attention), 1);
expect(bridge.shown, hasLength(1));
expect(bridge.shown.single.tag, '7:Decision');
});
}
@@ -0,0 +1,136 @@
import 'package:pipelines_app/features/attention/domain/attention_models.dart';
import 'package:pipelines_app/features/attention/domain/attention_transitions.dart';
import 'package:pipelines_app/features/attention/notify/notification_bridge.dart';
import 'package:pipelines_app/features/attention/notify/notification_controller.dart';
import 'package:pipelines_app/features/attention/notify/notification_ledger.dart';
import 'package:pipelines_app/features/attention/notify/notification_models.dart';
import 'package:pipelines_app/features/attention/runtime/attention_controller.dart';
import 'package:pipelines_app/features/attention/runtime/attention_store.dart';
/// The fixed local time the attention tests order and window by.
final attentionNow = DateTime(2026, 10, 22, 12);
String at(Duration before) => attentionNow.subtract(before).toIso8601String();
/// One run summary, built exactly as the runs list holds it.
Map<String, dynamic> runSummary(
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),
// The server leaves finished_at empty for a waiting run (and for one still in
// flight); only a settled run carries a finish time.
'finished_at': status == 'waiting' || status == 'running'
? ''
: at(age - const Duration(minutes: 5)),
'export_pending_sequence': ?exportPending,
...extra,
};
/// One qualifying pushed frame for a run, as `run_event` carries it.
///
/// A waiting or running frame has no `finished_at`, matching the server; pass
/// [finishedAt] only to describe a settled run.
Map<String, dynamic> runFrame(
int id,
String status, {
String name = 'release',
String? title,
String diagnostic = '',
String? finishedAt,
}) => {
'type': 'run_event',
'run_id': id,
'name': name,
'title': title ?? 'Run $id',
'status': status,
'diagnostic': diagnostic,
'created_at': at(const Duration(hours: 1)),
'finished_at':
finishedAt ??
(status == 'waiting' || status == 'running'
? ''
: at(const Duration(minutes: 1))),
};
/// One transition for a run that just entered [status], for batch tests.
AttentionTransition transitionFor(
int id, {
String status = 'failed',
String name = 'release',
String? title,
String? finishedAt,
}) => AttentionTransition(
attentionEntryFor(
runFrame(id, status, name: name, title: title, finishedAt: finishedAt),
)!,
);
/// Let the controller's fire-and-forget ledger write land.
Future<void> settle() => Future<void>.delayed(Duration.zero);
/// Publish exactly the way the manager wires it: the accumulated transitions,
/// the current rows and the dismissed set from the same attention snapshot.
int publish(NotificationController notify, AttentionController attention) =>
notify.publishTransitions(
attention.transitions,
qualifying: notificationQualifyingKeys(attention.rows),
dismissed: attention.dismissed,
);
AttentionController attentionController() =>
AttentionController(store: MemoryAttentionStore(), now: () => attentionNow);
/// A bridge whose answers are set explicitly, so every permission path is
/// exercised without a browser. It records what the controller asked for.
class FakeNotificationBridge implements NotificationBridge {
FakeNotificationBridge({
this.supported = true,
this.secureContext = true,
this.permission = 'default',
this.answer = 'granted',
this.accepts = true,
});
bool supported;
bool secureContext;
String permission;
String answer;
bool accepts;
int requests = 0;
final List<NotificationMessage> shown = [];
final List<void Function()?> taps = [];
@override
NotificationEnvironment environment() => NotificationEnvironment(
supported: supported,
secureContext: secureContext,
permission: permission,
);
@override
Future<String> requestPermission() async {
requests++;
permission = answer;
return answer;
}
@override
bool show(NotificationMessage message, {void Function()? onTap}) {
shown.add(message);
taps.add(onTap);
return accepts;
}
}
@@ -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);
});
}
@@ -0,0 +1,140 @@
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/attention/notify/notification_models.dart';
import 'package:pipelines_app/features/attention/ui/notification_permission_tile.dart';
import 'needs_you_test_support.dart';
/// The tile inside a normal page, so both native hosts can draw it. The page
/// scrolls like the Settings list does, so the tile is never given a fixed
/// height to overflow.
Widget _page({
required NotificationPermissionState state,
bool cupertino = false,
bool asked = false,
VoidCallback? onRequest,
}) => attentionApp(
Scaffold(
body: SingleChildScrollView(
child: NotificationPermissionTile(
state: state,
asked: asked,
onRequest: onRequest,
),
),
),
cupertino: cupertino,
);
void _noop() {}
void main() {
for (final native in [false, true]) {
final host = native ? 'Cupertino' : 'Material';
testWidgets('$host shows the state\'s own honest copy', (tester) async {
final cases = <NotificationPermissionState, String>{
NotificationPermissionState.unsupported: notificationUnsupportedCopy,
NotificationPermissionState.needsSecureContext:
notificationInsecureCopy,
NotificationPermissionState.granted: notificationGrantedCopy,
NotificationPermissionState.denied: notificationDeniedCopy,
NotificationPermissionState.notRequested: notificationDefaultCopy,
};
for (final entry in cases.entries) {
await tester.pumpWidget(
_page(state: entry.key, cupertino: native, onRequest: _noop),
);
expect(find.text(notificationSectionTitle), findsOneWidget);
expect(find.text(notificationRationale), findsOneWidget);
expect(find.text(entry.value), findsOneWidget, reason: '${entry.key}');
expect(
find.byKey(notificationEnableKey),
entry.key == NotificationPermissionState.notRequested
? findsOneWidget
: findsNothing,
reason: '${entry.key}',
);
}
});
testWidgets('$host shows the asked wording without an action', (
tester,
) async {
await tester.pumpWidget(
_page(
state: NotificationPermissionState.notRequested,
asked: true,
cupertino: native,
),
);
expect(find.text(notificationDefaultAskedCopy), findsOneWidget);
expect(find.text(notificationDefaultCopy), findsNothing);
});
testWidgets('$host Enable runs the explicit request', (tester) async {
var requested = 0;
await tester.pumpWidget(
_page(
state: NotificationPermissionState.notRequested,
cupertino: native,
onRequest: () => requested++,
),
);
await tester.tap(find.byKey(notificationEnableKey));
await tester.pump();
expect(requested, 1);
});
testWidgets('$host tile wraps at 320 logical px and 2x in dark', (
tester,
) async {
tester.view.devicePixelRatio = 2;
tester.view.physicalSize = const Size(640, 1280);
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
// The undecided state is the hardest: it carries the Enable action as well
// as the longest copy, so the section title must still have room to read.
await tester.pumpWidget(
attentionApp(
Scaffold(
body: SingleChildScrollView(
child: NotificationPermissionTile(
state: NotificationPermissionState.notRequested,
onRequest: _noop,
),
),
),
cupertino: native,
dark: true,
textScale: 2,
),
);
expect(tester.takeException(), isNull);
final title = tester.renderObject<RenderParagraph>(
find.text(notificationSectionTitle),
);
// Cupertino's list tile deliberately caps its title at one line; the
// defect this guards is the title being squeezed to a single glyph by the
// action sharing the row, so its width is the meaningful check.
expect(
title.size.width,
greaterThan(100),
reason: 'the action must not squeeze the section title to one glyph',
);
final body = tester.renderObject<RenderParagraph>(
find.text(notificationDefaultCopy),
);
expect(body.didExceedMaxLines, isFalse);
expect(find.byKey(notificationEnableKey), findsOneWidget);
final rect = tester.getRect(find.byKey(notificationStateKey));
expect(rect.left, greaterThanOrEqualTo(0));
expect(rect.right, lessThanOrEqualTo(320));
expect(tester.takeException(), isNull);
});
}
}
@@ -0,0 +1,415 @@
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/chat/conversation/chat_permission_card.dart';
import 'package:pipelines_app/features/chat/conversation/chat_permission_card_model.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'chat_thread_fixtures.dart';
Widget materialHost(Widget child) => MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: Scaffold(body: child),
);
Widget scrollHost(Widget child) =>
materialHost(SingleChildScrollView(child: child));
Widget cupertinoHost(Widget child) => CupertinoApp(
theme: const CupertinoThemeData(brightness: Brightness.dark),
home: CupertinoPageScaffold(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: child,
),
),
);
JsonMap permission({
String id = 'req-1',
String action = 'bash',
List<String> resources = const [
'command: rm -rf build',
'cwd: /workspace/demo',
],
String message = 'This deletes the build output.',
bool resolved = false,
String decision = '',
}) => {
'session_id': 's',
'request_id': id,
'action': action,
'resources': resources,
'message': message,
'source': {'type': 'tool'},
'resolved': resolved,
if (decision.isNotEmpty) 'decision': decision,
};
void main() {
test('recorded action, risk and options survive the card model', () {
final card = chatPermissionCard(permission(), '')!;
expect(card.headline, 'Approve bash');
expect(card.statusLine, chatApprovalStatusPending);
expect(card.risk, 'This deletes the build output.');
expect(card.resources, ['command: rm -rf build', 'cwd: /workspace/demo']);
expect(card.alwaysLabel, 'Always allow');
expect(card.actionable, isTrue);
expect(card.showRisk, isTrue);
});
test('resources keep their recorded indentation and order', () {
final card = chatPermissionCard(
permission(
resources: const [
' cd /workspace/demo',
'command: |\n echo hello',
' ',
],
),
'',
)!;
expect(card.resources, [
' cd /workspace/demo',
'command: |\n echo hello',
]);
expect(
card.resourceText,
' cd /workspace/demo\ncommand: |\n echo hello',
);
});
test('risk falls back to the action and resources cap at six lines', () {
final card = chatPermissionCard(
permission(
message: '',
resources: const [
'one',
'two\nthree',
'four',
'five',
'six',
'seven',
'eight',
],
),
'',
)!;
expect(
card.risk,
'The agent is asking to run bash; review the request before allowing.',
);
expect(card.resourceText.split('\n'), hasLength(6));
expect(card.resourceText.endsWith('…'), isTrue);
expect(card.resources, hasLength(7));
});
test('a server resolution outranks a local answer and a blank decision is '
'stale', () {
final resolved = chatPermissionCard(
permission(
resolved: true,
decision: 'always',
message: 'Another client already allowed this.',
),
'once',
)!;
expect(resolved.state, ChatPermissionState.resolved);
expect(resolved.headline, 'Always allowed');
expect(resolved.statusLine, 'Another client already allowed this.');
expect(resolved.actionable, isFalse);
expect(resolved.showRisk, isFalse);
final stale = chatPermissionCard(
permission(resolved: true, message: ''),
'',
)!;
expect(stale.state, ChatPermissionState.stale);
expect(stale.headline, 'Already resolved');
expect(stale.statusLine, chatApprovalStatusResolved);
expect(stale.actionable, isFalse);
});
test('a rejection keeps the risk panel while answered', () {
final rejected = chatPermissionCard(permission(), 'reject')!;
expect(rejected.state, ChatPermissionState.answered);
expect(rejected.headline, 'Rejected');
expect(rejected.statusLine, chatApprovalStatusAnswered);
expect(rejected.showRisk, isTrue);
expect(rejected.actionable, isFalse);
});
test('one stable reply id per confirmed action', () {
expect(
chatPermissionReplyId('req-1', 'once'),
chatPermissionReplyId('req-1', 'once'),
);
expect(
chatPermissionReplyId('req-1', 'once'),
isNot(chatPermissionReplyId('req-1', 'always')),
);
final gate = ChatActionGate();
final id = chatPermissionReplyId('req-1', 'once');
expect(gate.start(id), isTrue);
expect(gate.start(id), isFalse);
gate.release(id);
expect(gate.start(id), isTrue);
});
testWidgets('a pending approval renders native Material controls', (
tester,
) async {
final decisions = <String>[];
final card = chatPermissionCard(permission(), '')!;
await tester.pumpWidget(
scrollHost(
ChatPermissionCard(
card: card,
onDecision: (value) async {
decisions.add(value);
},
),
),
);
expect(find.text('Approve bash'), findsOneWidget);
expect(find.text('Waiting for your response'), findsOneWidget);
expect(find.text('RISK REVIEW'), findsOneWidget);
expect(find.text('This deletes the build output.'), findsOneWidget);
expect(find.text('Allow once'), findsOneWidget);
expect(find.text('Always allow'), findsOneWidget);
expect(find.text('Reject'), findsOneWidget);
expect(find.text('Permission request · tool'), findsNothing);
await tester.tap(find.text('Allow once'));
await tester.pump();
expect(decisions, ['once']);
});
testWidgets('Show full request expands to every recorded resource line', (
tester,
) async {
final card = chatPermissionCard(
permission(
resources: const [
' one',
'two',
'three',
'four',
'five',
'six',
'seven',
],
),
'',
)!;
await tester.pumpWidget(
scrollHost(ChatPermissionCard(card: card, onDecision: (_) async {})),
);
expect(find.text(' one'), findsNothing);
await tester.tap(find.text('Show full request'));
await tester.pumpAndSettle();
expect(find.text(card.resources.join('\n')), findsOneWidget);
});
testWidgets('320px at 2x in dark Cupertino keeps the card native and '
'readable', (tester) async {
tester.view.physicalSize = const Size(640, 1400);
tester.view.devicePixelRatio = 2;
tester.platformDispatcher.textScaleFactorTestValue = 2;
tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue);
final card = chatPermissionCard(
permission(
action: 'a very long tool name that has to wrap at twice the text size',
resources: const [
'a long resource line that wraps instead of clipping any words at all',
],
),
'',
)!;
await tester.pumpWidget(
cupertinoHost(ChatPermissionCard(card: card, onDecision: (_) async {})),
);
expect(tester.takeException(), isNull);
expect(find.text('Allow once'), findsOneWidget);
expect(find.byType(Material), findsNothing);
});
testWidgets('a pushed chat_permission renders, sends the recorded reply, '
'and a second tap sends once', (tester) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage(const []);
final held = Completer<JsonMap>();
gateway.reply = (_) => held.future;
await tester.pumpWidget(
materialHost(
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
);
await tester.pumpAndSettle();
gateway.emitRaw({
'type': 'chat_permission',
'chat_permission': permission(),
});
await tester.pumpAndSettle();
expect(find.text('Approve bash'), findsOneWidget);
await tester.tap(find.text('Allow once'));
await tester.tap(find.text('Allow once'));
await tester.pump();
final replies = gateway.calls.where((call) => call.type == 'chat_reply');
expect(replies, hasLength(1));
expect(replies.single.fields, {
'chat_reply': {
'session_id': 's',
'request_id': 'req-1',
'decision': 'once',
'client': 'Web',
},
});
expect(find.text('Allowed once'), findsOneWidget);
expect(find.text('Waiting for the agent to continue…'), findsOneWidget);
held.complete(const {});
await tester.pumpAndSettle();
});
testWidgets('a refused reply keeps the card pending and shows the server '
'reason', (tester) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage(const []);
gateway.reply = (_) async => throw StateError('request expired');
await tester.pumpWidget(
materialHost(
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
);
await tester.pumpAndSettle();
gateway.emitRaw({
'type': 'chat_permission',
'chat_permission': permission(),
});
await tester.pumpAndSettle();
await tester.tap(find.text('Reject'));
await tester.pumpAndSettle();
expect(find.textContaining('request expired'), findsOneWidget);
expect(find.text('Approve bash'), findsOneWidget);
expect(find.text('Allow once'), findsOneWidget);
expect(find.text('Reject'), findsOneWidget);
});
testWidgets('a server resolution clears the controls and shows the recorded '
'decision', (tester) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage(const []);
await tester.pumpWidget(
materialHost(
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
);
await tester.pumpAndSettle();
gateway.emitRaw({
'type': 'chat_permission',
'chat_permission': permission(),
});
await tester.pumpAndSettle();
expect(find.text('Allow once'), findsOneWidget);
gateway.emitRaw({
'type': 'chat_permission',
'chat_permission': permission(
resolved: true,
decision: 'once',
message: 'Another device allowed once.',
),
});
await tester.pumpAndSettle();
expect(find.text('Allowed once'), findsOneWidget);
expect(find.text('Another device allowed once.'), findsOneWidget);
expect(find.text('Allow once'), findsNothing);
});
testWidgets('a turn waiting on a pending card hides the running indicator '
'but keeps Stop', (tester) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage(const []);
await tester.pumpWidget(
materialHost(
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
);
await tester.pumpAndSettle();
gateway.emitRaw({
'type': 'chat_permission',
'chat_permission': permission(),
});
gateway.emitEvent(chatStepFrame('running'));
await tester.pumpAndSettle();
expect(find.text('Approve bash'), findsOneWidget);
expect(find.text('Assistant is responding…'), findsNothing);
expect(find.text('Stop'), findsOneWidget);
gateway.emitRaw({
'type': 'chat_permission',
'chat_permission': permission(resolved: true, decision: 'once'),
});
await tester.pumpAndSettle();
expect(find.text('Assistant is responding…'), findsOneWidget);
expect(find.text('Stop'), findsOneWidget);
});
testWidgets('consecutive Material cards stay separate surfaces', (
tester,
) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage(const []);
await tester.pumpWidget(
materialHost(
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
);
await tester.pumpAndSettle();
gateway.emitRaw({
'type': 'chat_permission',
'chat_permission': permission(id: 'req-1'),
});
gateway.emitRaw({
'type': 'chat_permission',
'chat_permission': permission(id: 'req-2', action: 'python'),
});
await tester.pumpAndSettle();
final first = tester.getRect(
find
.descendant(of: find.byType(Card).at(0), matching: find.byType(Material))
.first,
);
final second = tester.getRect(
find
.descendant(of: find.byType(Card).at(1), matching: find.byType(Material))
.first,
);
expect(second.top - first.bottom, greaterThanOrEqualTo(12));
});
}
@@ -0,0 +1,159 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/chat/conversation/chat_question_card_model.dart';
import 'package:pipelines_app/features/chat/conversation/chat_question_validation.dart';
void main() {
test('field visibility keeps false and zero as answers', () {
final fields = [
{'key': 'enabled', 'type': 'boolean'},
{
'key': 'count',
'type': 'integer',
'when': [
{'key': 'enabled', 'op': 'eq', 'value': true},
],
},
];
final hidden = {'enabled': false, 'count': 0};
expect(chatFormFieldVisible(fields[1], hidden), isFalse);
expect(chatFormAnswerError(fields, hidden), '');
expect(chatVisibleFormAnswers(fields, hidden), {'enabled': false});
});
test('required free text and numeric bounds use the web wording', () {
final fields = [
{'key': 'note', 'title': 'Notes', 'type': 'string', 'required': true},
{'key': 'count', 'type': 'integer', 'minimum': 1, 'maximum': 5},
];
expect(
chatFormAnswerError(fields, {'count': 2}),
'Answer Notes before sending.',
);
expect(
chatFormAnswerError(fields, {'note': 'ok', 'count': 1.5}),
'count needs a valid integer.',
);
expect(
chatFormAnswerError(fields, {'note': 'ok', 'count': 6}),
'count must be at most 5.',
);
expect(
chatFormAnswerError(fields, {'note': 'ok', 'count': 0}),
'count must be at least 1.',
);
expect(chatFormAnswerError(fields, {'note': 'ok', 'count': 5}), '');
});
test('integer input becomes an int, including decimal and exponent forms', () {
final field = <String, dynamic>{'key': 'count', 'type': 'integer'};
expect(chatFormFieldValue(field, '1.0'), isA<int>());
expect(chatFormFieldValue(field, '1.0'), 1);
expect(chatFormFieldValue(field, '1e3'), 1000);
expect(chatFormFieldValue(field, '1.5'), 1.5);
expect((chatFormFieldValue(field, 'nope')! as num).isNaN, isTrue);
expect(chatFormFieldValue({'type': 'number'}, '1e3'), 1000.0);
final fields = [field];
expect(
chatVisibleFormAnswers(
fields,
{'count': chatFormFieldValue(field, '1.0')},
),
{'count': 1},
);
expect(
chatFormAnswerError(fields, {'count': chatFormFieldValue(field, '1.0')}),
'',
);
});
test('a malformed pattern is reported with the documented wording', () {
final fields = [
{
'key': 'code',
'title': 'Code',
'type': 'string',
'pattern': r'^[a-z]+$',
},
];
expect(chatFormAnswerError(fields, {'code': 'abc'}), '');
expect(
chatFormAnswerError(fields, {'code': 'ABC'}),
'Code does not match the required format.',
);
// An unparseable server pattern constrains nothing, like a browser ignoring
// an invalid `pattern` attribute.
expect(
chatFormAnswerError([
{'key': 'code', 'type': 'string', 'pattern': '('},
], {'code': 'anything'}),
'',
);
});
test('email, URL and date formats are checked like native inputs', () {
final fields = [
{'key': 'mail', 'title': 'Email', 'type': 'string', 'format': 'email'},
{'key': 'site', 'title': 'Site', 'type': 'string', 'format': 'uri'},
{'key': 'day', 'title': 'Day', 'type': 'string', 'format': 'date'},
];
expect(chatFormAnswerError(fields, {'mail': 'a@b.co'}), '');
expect(
chatFormAnswerError(fields, {
'mail': 'not-a-mail',
'site': 'https://example.com',
'day': '2026-10-22',
}),
'Email is not a valid email address.',
);
expect(
chatFormAnswerError(fields, {
'mail': 'a@b.co',
'site': 'exa mple',
'day': '2026-10-22',
}),
'Site is not a valid URL.',
);
expect(
chatFormAnswerError(fields, {
'mail': 'a@b.co',
'site': 'https://example.com',
'day': '2026-02-31',
}),
'Day is not a valid date.',
);
expect(
chatFormAnswerError(fields, {
'mail': 'a@b.co',
'site': 'https://example.com',
'day': '2026-10-22',
}),
'',
);
});
test('options with an empty recorded value are skipped', () {
final field = <String, dynamic>{
'key': 'choice',
'options': [
{'value': '', 'label': 'Blank'},
{'value': 'red', 'label': 'Red'},
{'label': 'Blue'},
],
};
expect(chatQuestionOptions(field).map(chatQuestionOptionValue), [
'red',
'Blue',
]);
expect(chatQuestionFieldOptionValues(field), ['red', 'Blue']);
});
test('external URLs require an absolute HTTP(S) URL with a host', () {
expect(chatExternalUrlIsSafe('https://example.com/form'), isTrue);
expect(chatExternalUrlIsSafe('http://example.com'), isTrue);
expect(chatExternalUrlIsSafe('http://'), isFalse);
expect(chatExternalUrlIsSafe('http://exa mple.com'), isFalse);
expect(chatExternalUrlIsSafe('ftp://example.com'), isFalse);
expect(chatExternalUrlIsSafe('not a url'), isFalse);
});
}
@@ -0,0 +1,545 @@
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/chat/conversation/chat_question_card.dart';
import 'package:pipelines_app/features/chat/conversation/chat_question_card_model.dart';
import 'package:pipelines_app/features/chat/conversation/chat_question_validation.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'chat_thread_fixtures.dart';
Widget materialHost(Widget child) => MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: Scaffold(body: child),
);
Widget scrollHost(Widget child) =>
materialHost(SingleChildScrollView(child: child));
Widget cupertinoHost(Widget child) => CupertinoApp(
theme: const CupertinoThemeData(brightness: Brightness.dark),
home: CupertinoPageScaffold(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: child,
),
),
);
List<JsonMap> fields() => [
{
'key': 'colour',
'title': 'Colour',
'type': 'string',
'required': true,
'options': [
{'value': 'red', 'label': 'Red'},
{'value': 'blue', 'label': 'Blue'},
],
},
{
'key': 'extras',
'title': 'Extras',
'type': 'multiselect',
'options': [
{'value': 'extra-a', 'label': 'Extra A'},
{'value': 'extra-b', 'label': 'Extra B'},
],
},
{
'key': 'note',
'title': 'Notes',
'type': 'string',
'required': true,
'min_length': 3,
},
];
JsonMap question({
bool resolved = false,
bool cancelled = false,
Map<String, dynamic>? answers,
}) => {
'id': 'form-1',
'session_id': 's',
'kind': 'question',
'title': 'A demo question',
'fields': fields(),
'actions': ['accept', 'decline', 'cancel'],
if (resolved) 'resolved': true,
if (cancelled) 'cancelled': true,
'answers': ?answers,
};
void main() {
test('field visibility keeps false and zero as answers', () {
final fields = [
{'key': 'enabled', 'type': 'boolean'},
{
'key': 'count',
'type': 'integer',
'when': [
{'key': 'enabled', 'op': 'eq', 'value': true},
],
},
];
final hidden = {'enabled': false, 'count': 0};
expect(chatFormFieldVisible(fields[1], hidden), isFalse);
expect(chatFormAnswerError(fields, hidden), '');
expect(chatVisibleFormAnswers(fields, hidden), {'enabled': false});
});
test('required free text and numeric bounds use the web wording', () {
final fields = [
{'key': 'note', 'title': 'Notes', 'type': 'string', 'required': true},
{'key': 'count', 'type': 'integer', 'minimum': 1, 'maximum': 5},
];
expect(
chatFormAnswerError(fields, {'count': 2}),
'Answer Notes before sending.',
);
expect(
chatFormAnswerError(fields, {'note': 'ok', 'count': 1.5}),
'count needs a valid integer.',
);
expect(
chatFormAnswerError(fields, {'note': 'ok', 'count': 6}),
'count must be at most 5.',
);
expect(
chatFormAnswerError(fields, {'note': 'ok', 'count': 0}),
'count must be at least 1.',
);
expect(chatFormAnswerError(fields, {'note': 'ok', 'count': 5}), '');
});
testWidgets('a pending question answers single, multi and required free text '
'exactly as recorded', (tester) async {
tester.view.physicalSize = const Size(800, 1200);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
Map<String, dynamic>? sent;
await tester.pumpWidget(
scrollHost(
ChatQuestionCard(
form: question(),
onSubmit: (answers, action) async {
sent = answers;
},
),
),
);
expect(find.text('A demo question'), findsOneWidget);
expect(find.text(chatQuestionWaiting), findsOneWidget);
await tester.tap(find.text('Red'));
await tester.pump();
await tester.tap(find.text('Extra A'));
await tester.pump();
await tester.tap(find.text('Send answer'));
await tester.pump();
expect(find.text('Answer Notes before sending.'), findsOneWidget);
expect(sent, isNull);
await tester.enterText(
find.byKey(const ValueKey<String>('chat-question-input-note')),
' ready ',
);
await tester.pump();
await tester.tap(find.text('Send answer'));
await tester.pumpAndSettle();
expect(sent, {
'colour': 'red',
'extras': ['extra-a'],
'note': ' ready ',
});
});
testWidgets('a single-select option replaces the previous choice and a '
'multi-select toggles', (tester) async {
Map<String, dynamic>? sent;
await tester.pumpWidget(
scrollHost(
ChatQuestionCard(
form: question(),
onSubmit: (answers, action) async {
sent = answers;
},
),
),
);
await tester.tap(find.text('Red'));
await tester.pump();
await tester.tap(find.text('Blue'));
await tester.pump();
await tester.tap(find.text('Extra A'));
await tester.pump();
await tester.tap(find.text('Extra B'));
await tester.pump();
await tester.tap(find.text('Extra A'));
await tester.pump();
await tester.enterText(
find.byKey(const ValueKey<String>('chat-question-input-note')),
'done',
);
await tester.tap(find.text('Send answer'));
await tester.pumpAndSettle();
expect(sent, {
'colour': 'blue',
'extras': ['extra-b'],
'note': 'done',
});
});
testWidgets('answered questions show the recorded answer read-only', (
tester,
) async {
await tester.pumpWidget(
scrollHost(
ChatQuestionCard(
form: question(
resolved: true,
answers: {
'colour': 'red',
'extras': ['extra-b'],
'note': 'Recorded note',
},
),
onSubmit: (_, _) async {},
),
),
);
expect(find.text(chatQuestionAnswered), findsOneWidget);
expect(find.text('Red'), findsOneWidget);
expect(find.text('Extra B'), findsOneWidget);
expect(find.text('Recorded note'), findsOneWidget);
expect(find.text('Send answer'), findsNothing);
});
testWidgets('an expired question keeps recorded answers and offers no '
'controls', (tester) async {
await tester.pumpWidget(
scrollHost(
ChatQuestionCard(
form: question(cancelled: true, answers: {'colour': 'red'}),
onSubmit: (_, _) async {},
),
),
);
expect(find.text(chatQuestionExpired), findsOneWidget);
expect(find.text('Red'), findsOneWidget);
expect(find.text('Send answer'), findsNothing);
});
testWidgets('Cupertino field labels stay subordinate to the card title', (
tester,
) async {
await tester.pumpWidget(
cupertinoHost(
ChatQuestionCard(form: question(), onSubmit: (_, _) async {}),
),
);
final title = tester.widget<Text>(find.text('A demo question'));
final label = tester.widget<Text>(find.text('Colour'));
expect(label.style!.fontSize, lessThan(title.style!.fontSize!));
});
testWidgets('a free-text input carries its visual label in semantics', (
tester,
) async {
final semantics = tester.ensureSemantics();
await tester.pumpWidget(
scrollHost(
ChatQuestionCard(form: question(), onSubmit: (_, _) async {}),
),
);
final node = tester.getSemantics(
find.byKey(const ValueKey<String>('chat-question-input-note')),
);
expect(node.label, contains('Notes'));
semantics.dispose();
});
testWidgets('integer input sends an int, never a decimal double', (
tester,
) async {
Map<String, dynamic>? sent;
await tester.pumpWidget(
scrollHost(
ChatQuestionCard(
form: {
'id': 'form-int',
'title': 'How many?',
'actions': ['accept'],
'fields': [
{'key': 'count', 'title': 'Count', 'type': 'integer'},
],
},
onSubmit: (answers, action) async {
sent = answers;
},
),
),
);
await tester.enterText(
find.byKey(const ValueKey<String>('chat-question-input-count')),
'1.0',
);
await tester.pump();
await tester.tap(find.text('Send answer'));
await tester.pumpAndSettle();
expect(sent, {'count': 1});
expect(sent!['count'], isA<int>());
});
testWidgets('decline and cancel send their recorded actions with no answers', (
tester,
) async {
final actions = <String>[];
final answers = <Map<String, dynamic>>[];
await tester.pumpWidget(
scrollHost(
ChatQuestionCard(
form: question(),
onSubmit: (sent, action) async {
actions.add(action);
answers.add(sent);
},
),
),
);
await tester.tap(find.text('Decline'));
await tester.pumpAndSettle();
await tester.tap(find.text('Cancel question'));
await tester.pumpAndSettle();
expect(actions, ['decline', 'cancel']);
expect(answers, [<String, dynamic>{}, <String, dynamic>{}]);
});
testWidgets('an all-external form confirms completion without field answers', (
tester,
) async {
Map<String, dynamic>? sent;
String? action;
await tester.pumpWidget(
scrollHost(
ChatQuestionCard(
form: {
'id': 'form-external',
'title': 'Open the form',
'actions': ['accept'],
'fields': [
{
'key': 'form',
'title': 'External form',
'type': 'external',
'url': 'https://example.com/complete',
},
],
},
onSubmit: (answers, next) async {
sent = answers;
action = next;
},
),
),
);
expect(find.text('Confirm completion'), findsOneWidget);
expect(find.text('https://example.com/complete'), findsOneWidget);
await tester.tap(find.text('Confirm completion'));
await tester.pumpAndSettle();
expect(sent, isEmpty);
expect(action, 'accept');
});
testWidgets('an unsupported external URL shows the web alert wording', (
tester,
) async {
await tester.pumpWidget(
scrollHost(
ChatQuestionCard(
form: {
'id': 'form-external',
'title': 'Open the form',
'actions': ['accept'],
'fields': [
{'key': 'form', 'type': 'external', 'url': 'http://'},
],
},
onSubmit: (_, _) async {},
),
),
);
expect(
find.text('This form has an unsupported external URL.'),
findsOneWidget,
);
});
testWidgets('a resolved question without answers says none was recorded', (
tester,
) async {
await tester.pumpWidget(
scrollHost(
ChatQuestionCard(
form: question(resolved: true, answers: const {}),
onSubmit: (_, _) async {},
),
),
);
expect(find.text('No answer was recorded.'), findsOneWidget);
});
testWidgets('recorded booleans use Yes/No and blank titles fall back to the '
'key', (tester) async {
await tester.pumpWidget(
scrollHost(
ChatQuestionCard(
form: {
'id': 'form-recorded',
'title': 'Recorded',
'resolved': true,
'answers': {'enabled': true, 'extra': 'kept'},
'fields': [
{'key': 'enabled', 'title': '', 'description': '', 'type': 'boolean'},
],
},
onSubmit: (_, _) async {},
),
),
);
expect(find.text('enabled'), findsOneWidget);
expect(find.text('Yes'), findsOneWidget);
expect(find.text('true'), findsNothing);
expect(find.text('extra'), findsOneWidget);
expect(find.text('kept'), findsOneWidget);
});
testWidgets('320px at 2x in dark Cupertino keeps native controls', (
tester,
) async {
tester.view.physicalSize = const Size(640, 1600);
tester.view.devicePixelRatio = 2;
tester.platformDispatcher.textScaleFactorTestValue = 2;
tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue);
await tester.pumpWidget(
cupertinoHost(
ChatQuestionCard(form: question(), onSubmit: (_, _) async {}),
),
);
expect(tester.takeException(), isNull);
expect(find.text('A demo question'), findsOneWidget);
expect(find.text('Send answer'), findsOneWidget);
expect(find.byType(Material), findsNothing);
});
testWidgets('a pushed form renders and sends one exact chat_answer', (
tester,
) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage(const []);
final held = Completer<JsonMap>();
gateway.answer = (_) => held.future;
await tester.pumpWidget(
materialHost(
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
);
await tester.pumpAndSettle();
gateway.emitEvent({'session_id': 's', 'kind': 'form', 'form': question()});
await tester.pumpAndSettle();
expect(find.text('A demo question'), findsOneWidget);
await tester.tap(find.text('Red'));
await tester.pump();
await tester.enterText(
find.byKey(const ValueKey<String>('chat-question-input-note')),
'sent once',
);
await tester.tap(find.text('Send answer'));
await tester.tap(find.text('Send answer'));
await tester.pump();
final answers = gateway.calls.where((call) => call.type == 'chat_answer');
expect(answers, hasLength(1));
expect(answers.single.fields, {
'chat_answer': {
'session_id': 's',
'form_id': 'form-1',
'answers': {'colour': 'red', 'note': 'sent once'},
'action': 'accept',
},
});
held.complete(const {});
await tester.pumpAndSettle();
expect(find.text(chatQuestionAnswered), findsOneWidget);
});
testWidgets('a refused question keeps the card open with the server reason', (
tester,
) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage(const []);
gateway.answer = (_) async => throw StateError('form already closed');
await tester.pumpWidget(
materialHost(
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
);
await tester.pumpAndSettle();
gateway.emitEvent({'session_id': 's', 'kind': 'form', 'form': question()});
await tester.pumpAndSettle();
await tester.tap(find.text('Red'));
await tester.pump();
await tester.enterText(
find.byKey(const ValueKey<String>('chat-question-input-note')),
'retry me',
);
await tester.tap(find.text('Send answer'));
await tester.pumpAndSettle();
expect(find.textContaining('form already closed'), findsOneWidget);
expect(find.text('Send answer'), findsOneWidget);
expect(find.text(chatQuestionWaiting), findsOneWidget);
});
testWidgets('unknown transcript parts remain available beside cards', (
tester,
) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage([
chatMessage(
'a1',
'assistant',
parts: [
{'type': 'text', 'text': 'Recorded answer with a fallback part.'},
{'type': 'future-content', 'future_value': 'still preserved'},
],
),
]);
await tester.pumpWidget(
materialHost(
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
);
await tester.pumpAndSettle();
expect(find.text('Recorded answer with a fallback part.'), findsOneWidget);
await tester.tap(find.text('Unrecognised part: future-content'));
await tester.pumpAndSettle();
expect(find.textContaining('still preserved'), findsOneWidget);
});
}
@@ -0,0 +1,82 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_controller.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_cards.dart';
import 'chat_thread_fixtures.dart';
JsonMap permission(String id, {bool resolved = false}) => {
'session_id': 's',
'request_id': id,
'action': 'bash',
'resources': const ['command: ls'],
'message': '',
'resolved': resolved,
if (resolved) 'decision': 'once',
};
JsonMap form(String id, {bool resolved = false}) => {
'id': id,
'session_id': 's',
'title': 'Question',
'fields': const [],
'actions': const ['accept'],
'resolved': resolved,
if (resolved) 'answers': const {'note': 'recorded'},
};
void main() {
test('settled approvals are bounded while the pending one is kept', () async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
final controller = ChatThreadController(gateway, 's');
addTearDown(controller.dispose);
for (var index = 0; index < ChatThreadCards.settledLimit + 5; index++) {
gateway.emitRaw({
'type': 'chat_permission',
'chat_permission': permission('req-$index', resolved: true),
});
}
gateway.emitRaw({
'type': 'chat_permission',
'chat_permission': permission('req-pending'),
});
await pumpEventQueue();
expect(controller.permissionFrames, hasLength(ChatThreadCards.settledLimit + 1));
expect(
controller.permissionFrames.first['request_id'],
'req-5',
);
expect(
controller.permissionFrames.last['request_id'],
'req-pending',
);
});
test('settled forms are bounded while the pending one is kept', () async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
final controller = ChatThreadController(gateway, 's');
addTearDown(controller.dispose);
for (var index = 0; index < ChatThreadCards.settledLimit + 5; index++) {
gateway.emitEvent({
'session_id': 's',
'kind': 'form',
'form': form('form-$index', resolved: true),
});
}
gateway.emitEvent({
'session_id': 's',
'kind': 'form',
'form': form('form-pending'),
});
await pumpEventQueue();
expect(controller.questionForms, hasLength(ChatThreadCards.settledLimit + 1));
expect(controller.questionForms.first['id'], 'form-5');
expect(controller.questionForms.last['id'], 'form-pending');
});
}
@@ -9,6 +9,8 @@ class FakeChatGateway implements ApiGateway {
final _frames = StreamController<JsonMap>.broadcast();
Future<JsonMap> Function(JsonMap fields)? history;
Future<JsonMap> Function()? subscribe;
Future<JsonMap> Function(JsonMap fields)? reply;
Future<JsonMap> Function(JsonMap fields)? answer;
void Function()? onSubscribe;
@override
@@ -23,6 +25,12 @@ class FakeChatGateway implements ApiGateway {
historyRequests.add(completer);
if (history != null) return history!(fields);
return completer.future;
case 'chat_reply':
if (reply != null) return reply!(fields);
return <String, dynamic>{};
case 'chat_answer':
if (answer != null) return answer!(fields);
return <String, dynamic>{};
}
return <String, dynamic>{};
}
@@ -0,0 +1,213 @@
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/graph/viewport/graph_expanded_view.dart';
import 'package:pipelines_app/features/graph/viewport/graph_viewport_math.dart';
import 'package:pipelines_app/features/graph/widgets/definition_graph_view.dart';
import 'package:pipelines_app/features/graph/widgets/graph_stage_node.dart';
import '../domain/graph_fixtures.dart';
Widget _materialHost({
required JsonMap graph,
required String? selected,
required ValueChanged<String> onSelected,
}) => MaterialApp(
home: Scaffold(
body: DefinitionGraphView(
graph: graph,
selectedStage: selected,
onSelected: onSelected,
),
),
);
Finder _node(String key) => find.byWidgetPredicate(
(widget) => widget is GraphStageNode && widget.node.key == key,
);
Finder _inExpanded(Finder finder) =>
find.descendant(of: find.byType(GraphExpandedView), matching: finder);
Future<void> _settle(WidgetTester tester) async {
await tester.pump();
await tester.pump();
await tester.pump();
}
TransformationController _inlineTransform(WidgetTester tester) => tester
.widget<InteractiveViewer>(find.byType(InteractiveViewer))
.transformationController!;
void main() {
testWidgets(
'expanded fits the larger canvas and returns to the inline state',
(tester) async {
tester.view.physicalSize = const Size(900, 700);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final picked = <String>[];
await tester.pumpWidget(
_materialHost(
graph: linearGraph(),
selected: 'build',
onSelected: picked.add,
),
);
await _settle(tester);
final inline = _inlineTransform(tester);
final inlineMatrix = Matrix4.copy(inline.value);
final inlineRect = tester.getRect(_node('build'));
await tester.tap(find.byKey(const Key('graph-expand')));
await tester.pumpAndSettle();
expect(find.byType(GraphExpandedView), findsOneWidget);
expect(find.text(definitionGraphExpandedTitle), findsOneWidget);
final expanded = _inExpanded(find.byType(InteractiveViewer));
expect(expanded, findsOneWidget);
final expandedController = tester
.widget<InteractiveViewer>(expanded)
.transformationController!;
final expandedView = tester.widget<GraphExpandedView>(
find.byType(GraphExpandedView),
);
final canvas = tester.getRect(
_inExpanded(find.byKey(const Key('graph-viewport'))),
);
// The web re-fits when its panel expands: the larger canvas fits the
// whole graph instead of keeping the small inline scale.
expect(
expandedController.value.getMaxScaleOnAxis(),
closeTo(graphFitScale(canvas.size, expandedView.contentSize), 1e-9),
);
expect(
canvas.contains(tester.getCenter(_inExpanded(_node('build')))),
isTrue,
);
expect(
tester.widget<GraphStageNode>(_inExpanded(_node('build'))).selected,
isTrue,
);
// A tap in the larger canvas follows the same transform and updates the
// presentation's own selection.
await tester.tap(_inExpanded(_node('plan')));
await tester.pump();
expect(picked, ['plan']);
expect(
tester.widget<GraphStageNode>(_inExpanded(_node('plan'))).selected,
isTrue,
);
await tester.tap(find.byKey(const Key('graph-expanded-close')));
await tester.pumpAndSettle();
expect(find.byType(GraphExpandedView), findsNothing);
// The inline canvas was never changed: same selection, same place.
expect(tester.widget<GraphStageNode>(_node('build')).selected, isTrue);
expect(tester.getRect(_node('build')), inlineRect);
expect(inline.value.storage, orderedEquals(inlineMatrix.storage));
},
);
testWidgets('a rotation re-clamps the expanded transform into the new box', (
tester,
) async {
tester.view.physicalSize = const Size(900, 700);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
await tester.pumpWidget(
_materialHost(
graph: linearGraph(),
selected: 'build',
onSelected: (_) {},
),
);
await _settle(tester);
await tester.tap(find.byKey(const Key('graph-expand')));
await tester.pumpAndSettle();
final expanded = _inExpanded(find.byType(InteractiveViewer));
final controller = tester
.widget<InteractiveViewer>(expanded)
.transformationController!;
final canvas = find.descendant(
of: find.byType(GraphExpandedView),
matching: find.byKey(const Key('graph-viewport')),
);
// Pan far enough that the wide canvas' clamp is the only limit.
await tester.drag(canvas, const Offset(500, 0));
await tester.pumpAndSettle();
final wide = tester.getRect(canvas);
final panned = controller.value.getTranslation().x;
expect(panned, lessThanOrEqualTo(wide.width - graphMinVisible + 0.5));
// Rotating to a narrow box must keep the graph inside it, not leave the
// reader's old place hanging outside until Fit is pressed.
tester.view.physicalSize = const Size(320, 700);
await tester.pumpAndSettle();
await _settle(tester);
final narrow = tester.getRect(canvas);
expect(narrow.width, lessThan(wide.width));
final clamped = controller.value.getTranslation().x;
expect(
clamped,
lessThanOrEqualTo(narrow.width - graphMinVisible + 0.5),
reason: 'a resize must re-clamp the existing transform',
);
expect(clamped, lessThan(panned));
});
testWidgets('320px at 2x opens and closes on the dark Cupertino host', (
tester,
) async {
tester.view.physicalSize = const Size(320, 700);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final picked = <String>[];
await tester.pumpWidget(
CupertinoApp(
theme: const CupertinoThemeData(brightness: Brightness.dark),
home: CupertinoPageScaffold(
child: Builder(
builder: (context) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: const TextScaler.linear(2)),
child: DefinitionGraphView(
graph: linearGraph(),
selectedStage: 'build',
onSelected: picked.add,
),
),
),
),
),
);
await _settle(tester);
final inline = _inlineTransform(tester);
final inlineMatrix = Matrix4.copy(inline.value);
await tester.tap(find.byKey(const Key('graph-expand')));
await tester.pumpAndSettle();
expect(find.byType(GraphExpandedView), findsOneWidget);
expect(_inExpanded(find.text(graphExpandedClose)), findsOneWidget);
expect(
tester.widget<GraphStageNode>(_inExpanded(_node('build'))).selected,
isTrue,
);
expect(tester.takeException(), isNull);
await tester.tap(find.byKey(const Key('graph-expanded-close')));
await tester.pumpAndSettle();
expect(find.byType(GraphExpandedView), findsNothing);
expect(tester.widget<GraphStageNode>(_node('build')).selected, isTrue);
expect(inline.value.storage, orderedEquals(inlineMatrix.storage));
expect(picked, isEmpty);
expect(tester.takeException(), isNull);
});
}
@@ -0,0 +1,99 @@
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/viewport/graph_viewport_controller.dart';
import 'graph_viewport_fixtures.dart';
void main() {
testWidgets('Fit and Expand stay labelled, activatable buttons on both hosts', (
tester,
) async {
for (final cupertino in [false, true]) {
final host = cupertino ? 'cupertino' : 'material';
final controller = GraphViewportController();
addTearDown(controller.dispose);
var expands = 0;
await tester.pumpWidget(
viewportHost(
controller: controller,
child: viewportTargets([]),
cupertino: cupertino,
onExpand: () => expands += 1,
),
);
await settleViewport(tester);
final fitted = controller.snapshot;
for (final control in viewportControls().entries) {
final node = tester.getSemantics(find.byKey(control.key));
final data = node.getSemanticsData();
expect(
data.label,
control.value,
reason: '$host ${control.key} must have the web name',
);
expect(
data.flagsCollection.isButton,
isTrue,
reason: '$host ${control.key} must be announced as a button',
);
// A labelled button with no action is unusable with VoiceOver/TalkBack;
// this is the regression the excluded-button wrapper introduced.
expect(
data.hasAction(SemanticsAction.tap),
isTrue,
reason: '$host ${control.key} must expose a tap action',
);
}
// The exposed action must run the real callback, not just be announced.
await pinchViewport(tester, const Offset(200, 150), 2);
await tester.pumpAndSettle();
expect(controller.snapshot, isNot(fitted));
performViewportTap(tester, find.byKey(const Key('graph-fit')));
await tester.pump();
expect(controller.scale, closeTo(fitted.scale, 1e-9));
performViewportTap(tester, find.byKey(const Key('graph-expand')));
await tester.pump();
expect(expands, 1, reason: '$host Expand must activate');
}
});
testWidgets('320px at 2x keeps native controls and gestures on both hosts', (
tester,
) async {
for (final cupertino in [false, true]) {
final controller = GraphViewportController();
addTearDown(controller.dispose);
await tester.pumpWidget(
viewportHost(
controller: controller,
child: viewportTargets([]),
cupertino: cupertino,
dark: cupertino,
textScale: 2,
viewport: const Size(320, 300),
onExpand: () {},
),
);
await settleViewport(tester);
expect(find.byKey(const Key('graph-fit')), findsOneWidget);
expect(find.byKey(const Key('graph-expand')), findsOneWidget);
expect(tester.takeException(), isNull);
final before = controller.offset;
await dragViewport(
tester,
find.byKey(const Key('graph-viewport')),
const Offset(-30, -10),
);
expect(controller.offset, isNot(before));
await pinchViewport(tester, const Offset(160, 150), 2);
await tester.pumpAndSettle();
expect(controller.scale, greaterThan(0.3));
expect(tester.takeException(), isNull);
}
});
}
@@ -0,0 +1,167 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/viewport/graph_viewport.dart';
import 'package:pipelines_app/features/graph/viewport/graph_viewport_controller.dart';
/// Shared fixture for the graph viewport widget tests.
///
/// One 1200x900 graph in a 400x300 box unless a test asks for another size.
const Size viewportContent = Size(1200, 900);
const Size defaultViewportSize = Size(400, 300);
/// Two native tap targets at known graph coordinates; a tap reports its key so
/// hit-testing can be checked against the visible transform.
Widget viewportTargets(List<String> picked) => Stack(
clipBehavior: Clip.none,
children: [
Positioned(
left: 60,
top: 60,
width: 120,
height: 60,
child: GestureDetector(
key: const Key('target-a'),
behavior: HitTestBehavior.opaque,
onTap: () => picked.add('a'),
child: const ColoredBox(color: Color(0xFF3366CC)),
),
),
Positioned(
left: 900,
top: 700,
width: 160,
height: 80,
child: GestureDetector(
key: const Key('target-b'),
behavior: HitTestBehavior.opaque,
onTap: () => picked.add('b'),
child: const ColoredBox(color: Color(0xFFCC6633)),
),
),
],
);
Widget viewportHost({
required GraphViewportController controller,
required Widget child,
VoidCallback? onExpand,
bool cupertino = false,
bool dark = false,
double textScale = 1,
Size viewport = defaultViewportSize,
}) {
final graph = MediaQuery(
data: MediaQueryData(textScaler: TextScaler.linear(textScale)),
child: SizedBox.fromSize(
size: viewport,
child: GraphViewport(
controller: controller,
contentSize: viewportContent,
onExpand: onExpand,
child: child,
),
),
);
if (cupertino) {
return CupertinoApp(
theme: CupertinoThemeData(
brightness: dark ? Brightness.dark : Brightness.light,
),
home: CupertinoPageScaffold(child: Center(child: graph)),
);
}
return MaterialApp(
theme: dark ? ThemeData.dark() : ThemeData.light(),
home: Scaffold(body: Center(child: graph)),
);
}
Future<void> settleViewport(WidgetTester tester) async {
await tester.pump();
await tester.pump();
await tester.pump();
}
/// Two-pointer pinch around [center]; [factor] > 1 zooms in.
Future<void> pinchViewport(
WidgetTester tester,
Offset center,
double factor, {
double half = 20,
}) async {
final origin = viewportGlobal(tester, center);
final left = await tester.startGesture(origin - Offset(half, 0));
final right = await tester.startGesture(origin + Offset(half, 0));
await tester.pump();
const steps = 8;
final end = half * factor;
for (var step = 1; step <= steps; step += 1) {
final spread = half + (end - half) * step / steps;
await left.moveTo(origin - Offset(spread, 0));
await right.moveTo(origin + Offset(spread, 0));
await tester.pump();
}
await left.up();
await right.up();
await tester.pump();
}
Offset viewportScreenOf(
GraphViewportController controller,
Offset graphPoint,
) => MatrixUtils.transformPoint(controller.transformation.value, graphPoint);
/// Viewport-local coordinates to the test screen, where gestures are dispatched.
Offset viewportGlobal(WidgetTester tester, Offset local) =>
tester.getTopLeft(find.byKey(const Key('graph-viewport'))) + local;
/// Starts a drag and moves past the pan slop, so the canvas owns the gesture.
///
/// The viewer only pans movement after it accepts the gesture, so tests record
/// their reference offset after this warm-up rather than at pointer down.
Future<TestGesture> startViewportDrag(
WidgetTester tester,
Finder finder, {
Offset warmUp = const Offset(-10, -10),
}) async {
final gesture = await tester.startGesture(tester.getCenter(finder));
for (var step = 0; step < 4; step += 1) {
await gesture.moveBy(warmUp);
await tester.pump();
}
return gesture;
}
Future<void> dragViewport(
WidgetTester tester,
Finder finder,
Offset delta, {
Offset warmUp = const Offset(-10, -10),
}) async {
final gesture = await startViewportDrag(tester, finder, warmUp: warmUp);
for (var step = 0; step < 4; step += 1) {
await gesture.moveBy(delta / 4);
await tester.pump();
}
await gesture.up();
await tester.pumpAndSettle();
}
/// Activates a control the way a screen reader does: through its semantics
/// action, not pointer input.
void performViewportTap(WidgetTester tester, Finder finder) {
final node = tester.getSemantics(finder);
tester.binding.renderViews.first.owner!.semanticsOwner!.performAction(
node.id,
SemanticsAction.tap,
);
}
/// The controls' accessible names, in the order they are shown.
Map<Key, String> viewportControls() => <Key, String>{
const Key('graph-fit'): graphFitLabel,
const Key('graph-expand'): graphExpandLabel,
};
@@ -0,0 +1,134 @@
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/viewport/graph_viewport_controller.dart';
import 'package:pipelines_app/features/graph/viewport/graph_viewport_math.dart';
void main() {
test('fit keeps the padding and never upscales a small graph', () {
final scale = graphFitScale(
const Size(400, 300),
const Size(1000, 800),
padding: 20,
);
// 360/1000 and 260/800 both fit; the smaller axis wins.
expect(scale, closeTo(0.325, 1e-9));
expect(graphFitScale(const Size(400, 300), const Size(100, 80)), 1);
});
test('fit clamps to the graph scale bounds', () {
expect(
graphFitScale(const Size(400, 300), const Size(10000, 10000)),
graphMinScale,
);
expect(
graphFitScale(const Size(400, 300), const Size(1000, 800), minScale: 0.9),
0.9,
);
});
test('degenerate sizes never divide by zero', () {
expect(graphFitScale(Size.zero, const Size(100, 100)), 1);
expect(graphFitScale(const Size(400, 300), Size.zero), 1);
expect(
graphFitScale(const Size(400, 300), const Size(100, 100), padding: 200),
1,
);
});
test('pan clamp keeps part of the scaled graph visible', () {
const viewport = Size(400, 300);
const scaled = Size(800, 600);
expect(
graphClampOffset(const Offset(5000, 5000), scaled, viewport),
const Offset(400 - graphMinVisible, 300 - graphMinVisible),
);
expect(
graphClampOffset(const Offset(-5000, -5000), scaled, viewport),
Offset(graphMinVisible - 800, graphMinVisible - 600),
);
// Inside the bounds the offset is untouched.
expect(
graphClampOffset(const Offset(-100, -50), scaled, viewport),
const Offset(-100, -50),
);
});
test('clamp leaves degenerate content and empty ranges alone', () {
expect(
graphClampOffset(const Offset(12, 34), Size.zero, const Size(400, 300)),
const Offset(12, 34),
);
// The viewport is narrower than twice the minimum visible part: the range
// is empty, so the input survives rather than being pinned to a bad value.
expect(
graphClampOffset(
const Offset(500, 500),
const Size(1, 1),
const Size(40, 40),
),
const Offset(500, 500),
);
});
test('the transform draws graph points at offset + point * scale', () {
final matrix = graphViewportMatrix(const Offset(30, 20), 0.5);
expect(
MatrixUtils.transformPoint(matrix, const Offset(100, 80)),
const Offset(80, 60),
);
expect(matrix.getMaxScaleOnAxis(), 0.5);
});
test('controller fits, centers and round-trips a snapshot', () {
final controller = GraphViewportController();
addTearDown(controller.dispose);
controller.attach(
viewport: const Size(400, 300),
content: const Size(1000, 800),
);
final fitted = controller.snapshot;
expect(fitted.scale, closeTo(0.315, 1e-9));
expect(fitted.offset.dx, greaterThan(0));
expect(fitted.offset.dy, greaterThan(0));
expect(
fitted.offset,
graphCenteredOffset(
Size(1000 * fitted.scale, 800 * fitted.scale),
const Size(400, 300),
),
);
controller.applySnapshot(
const GraphViewportSnapshot(scale: 2, offset: Offset(-100, -80)),
);
expect(
controller.snapshot,
const GraphViewportSnapshot(scale: 2, offset: Offset(-100, -80)),
);
// A resize after the reader adjusted keeps their scale, only clamping the
// offset into the new bounds.
controller.attach(
viewport: const Size(200, 200),
content: const Size(1000, 800),
);
expect(controller.scale, 2);
});
test('controller fit clamps a graph that cannot fit at the minimum', () {
final controller = GraphViewportController();
addTearDown(controller.dispose);
controller.attach(
viewport: const Size(400, 300),
content: const Size(10000, 10000),
);
expect(controller.scale, graphMinScale);
final scaled = 10000 * graphMinScale;
expect(
controller.offset.dx,
greaterThanOrEqualTo(graphMinVisible - scaled),
);
expect(controller.offset.dx, lessThanOrEqualTo(400 - graphMinVisible));
});
}
@@ -0,0 +1,238 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/graph/viewport/graph_viewport.dart';
import 'package:pipelines_app/features/graph/viewport/graph_viewport_controller.dart';
import 'package:pipelines_app/features/graph/viewport/graph_viewport_math.dart';
import 'graph_viewport_fixtures.dart';
void main() {
testWidgets('drag pans the canvas and the pan stays bounded', (tester) async {
final controller = GraphViewportController();
addTearDown(controller.dispose);
await tester.pumpWidget(
viewportHost(controller: controller, child: viewportTargets([])),
);
await settleViewport(tester);
expect(controller.scale, lessThan(1));
final finder = find.byKey(const Key('graph-viewport'));
final gesture = await startViewportDrag(tester, finder);
final before = controller.offset;
for (var step = 0; step < 4; step += 1) {
await gesture.moveBy(const Offset(-10, -5));
await tester.pump();
}
await gesture.up();
await tester.pumpAndSettle();
expect(controller.offset.dx, closeTo(before.dx - 40, 1));
expect(controller.offset.dy, closeTo(before.dy - 20, 1));
// A huge drag can never leave an empty canvas: at least the minimum part
// of the scaled graph stays inside the viewport.
final out = await startViewportDrag(tester, finder);
await out.moveBy(const Offset(5000, 5000));
await tester.pump();
await out.up();
await tester.pumpAndSettle();
expect(
controller.offset.dx,
lessThanOrEqualTo(defaultViewportSize.width - graphMinVisible + 0.01),
);
expect(
controller.offset.dy,
lessThanOrEqualTo(defaultViewportSize.height - graphMinVisible + 0.01),
);
final back = await startViewportDrag(tester, finder);
await back.moveBy(const Offset(-10000, -10000));
await tester.pump();
await back.up();
await tester.pumpAndSettle();
expect(
controller.offset.dx,
greaterThanOrEqualTo(
graphMinVisible - viewportContent.width * controller.scale - 0.01,
),
);
});
testWidgets('pinch zoom clamps at the graph scale bounds', (tester) async {
final controller = GraphViewportController();
addTearDown(controller.dispose);
await tester.pumpWidget(
viewportHost(controller: controller, child: viewportTargets([])),
);
await settleViewport(tester);
expect(controller.scale, lessThan(1));
await pinchViewport(tester, const Offset(200, 150), 10);
await tester.pumpAndSettle();
expect(controller.scale, graphMaxScale);
await pinchViewport(tester, const Offset(200, 150), 0.01);
await tester.pumpAndSettle();
expect(controller.scale, graphMinScale);
});
testWidgets('zoom keeps the graph point under the moving focal point', (
tester,
) async {
final controller = GraphViewportController();
addTearDown(controller.dispose);
await tester.pumpWidget(
viewportHost(controller: controller, child: viewportTargets([])),
);
await settleViewport(tester);
const focal = Offset(150, 120);
final before = controller.transformation.toScene(focal);
await pinchViewport(tester, focal, 1.6);
await tester.pumpAndSettle();
final after = controller.transformation.toScene(focal);
// A gesture is not pixel-exact: the focal point keeps its graph point
// within a few graph pixels while the transform scales.
expect(after.dx, closeTo(before.dx, 4));
expect(after.dy, closeTo(before.dy, 4));
expect(controller.scale, greaterThan(0.3));
});
testWidgets('the first painted frame is already fitted', (tester) async {
final controller = GraphViewportController();
addTearDown(controller.dispose);
// No extra pump: the fit must land during the first layout, not one frame
// later over an identity transform.
await tester.pumpWidget(
viewportHost(controller: controller, child: viewportTargets([])),
);
expect(
controller.scale,
closeTo(graphFitScale(defaultViewportSize, viewportContent), 1e-9),
);
expect(tester.takeException(), isNull);
});
testWidgets('the fit control restores the fitted scale and offset', (
tester,
) async {
final controller = GraphViewportController();
addTearDown(controller.dispose);
await tester.pumpWidget(
viewportHost(controller: controller, child: viewportTargets([])),
);
await settleViewport(tester);
final fitted = controller.snapshot;
await pinchViewport(tester, const Offset(200, 150), 2);
await dragViewport(
tester,
find.byKey(const Key('graph-viewport')),
const Offset(-30, -10),
);
expect(controller.snapshot, isNot(fitted));
await tester.tap(find.byKey(const Key('graph-fit')));
await tester.pump();
expect(controller.scale, closeTo(fitted.scale, 1e-9));
expect(controller.offset.dx, closeTo(fitted.offset.dx, 1e-9));
expect(controller.offset.dy, closeTo(fitted.offset.dy, 1e-9));
});
testWidgets('a tap selects the node visually under the pointer', (
tester,
) async {
final picked = <String>[];
final controller = GraphViewportController();
addTearDown(controller.dispose);
await tester.pumpWidget(
viewportHost(controller: controller, child: viewportTargets(picked)),
);
await settleViewport(tester);
// Bring target b to the middle, then zoom in around it. Its graph point
// stays under the focal point while the transform scales.
const targetCenter = Offset(980, 740);
final finder = find.byKey(const Key('graph-viewport'));
final gesture = await startViewportDrag(tester, finder);
final start = viewportScreenOf(controller, targetCenter);
final delta = const Offset(200, 150) - start;
for (var step = 0; step < 4; step += 1) {
await gesture.moveBy(delta / 4);
await tester.pump();
}
await gesture.up();
await tester.pumpAndSettle();
await pinchViewport(tester, const Offset(200, 150), 2.4);
await tester.pumpAndSettle();
final underPointer = viewportScreenOf(controller, targetCenter);
final viewportRect = tester.getRect(
find.byKey(const Key('graph-viewport')),
);
expect(viewportRect.contains(underPointer), isTrue);
expect(controller.scale, greaterThan(0.3));
await tester.tapAt(viewportGlobal(tester, underPointer));
await tester.pump();
expect(picked, ['b']);
});
testWidgets('an ancestor scroll view keeps scrolling outside the canvas', (
tester,
) async {
final controller = GraphViewportController();
final scroll = ScrollController();
addTearDown(controller.dispose);
addTearDown(scroll.dispose);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ListView(
controller: scroll,
children: [
Container(key: const Key('scroll-header'), height: 400),
SizedBox(
height: 300,
child: GraphViewport(
controller: controller,
contentSize: viewportContent,
child: viewportTargets([]),
),
),
Container(height: 800),
],
),
),
),
);
await settleViewport(tester);
// A drag outside the canvas scrolls the ancestor and never pans the graph.
await tester.dragFrom(const Offset(400, 60), const Offset(0, -120));
await tester.pumpAndSettle();
expect(scroll.offset, greaterThan(0));
final scrolled = scroll.offset;
final graphBefore = controller.offset;
expect(controller.offset, graphBefore);
// Inside its own box the canvas consumes the drag: the graph pans and the
// list keeps its position.
await dragViewport(
tester,
find.byKey(const Key('graph-viewport')),
const Offset(-40, 0),
warmUp: const Offset(-10, 0),
);
expect(scroll.offset, scrolled);
expect(controller.offset.dx, lessThan(graphBefore.dx));
// Scrolling outside still works afterwards and leaves the graph place alone.
final panned = controller.offset;
await tester.dragFrom(const Offset(400, 60), const Offset(0, -80));
await tester.pumpAndSettle();
expect(scroll.offset, greaterThan(scrolled));
expect(controller.offset, panned);
});
}
@@ -82,6 +82,22 @@ Finder _node(String key) => find.byWidgetPredicate(
(widget) => widget is GraphStageNode && widget.node.key == key,
);
/// The graph-space extent of a placed node.
///
/// The viewport fits the measured graph into the available box, so an onstage
/// node's rectangle is its measured extent times the current scale. Dividing
/// the rectangle by that scale keeps these assertions about measurement rather
/// than about the viewport transform.
Size _measuredNodeSize(WidgetTester tester, String key) {
final scale = tester
.widget<InteractiveViewer>(find.byType(InteractiveViewer))
.transformationController!
.value
.getMaxScaleOnAxis();
final rect = _nodeRect(tester, key);
return Size(rect.width / scale, rect.height / scale);
}
Rect _nodeRect(WidgetTester tester, String key) => tester.getRect(_node(key));
Future<void> _tapNode(WidgetTester tester, String key) async {
@@ -123,11 +139,11 @@ void main() {
addTearDown(tester.view.reset);
await tester.pumpWidget(_materialHost(_longKeyGraph()));
await _settle(tester);
final wide = _nodeRect(tester, _longKey);
final wide = _measuredNodeSize(tester, _longKey);
tester.view.physicalSize = const Size(320, 700);
await tester.pump();
await _settle(tester);
final narrow = _nodeRect(tester, _longKey);
final narrow = _measuredNodeSize(tester, _longKey);
expect(narrow.width, lessThan(wide.width));
expect(narrow.width, lessThanOrEqualTo(320));
expect(narrow.height, greaterThan(wide.height));
@@ -156,6 +172,42 @@ void main() {
expect(picked, ['plan', '#success']);
});
testWidgets('a tap after zoom selects the node under the pointer', (
tester,
) async {
final picked = <String>[];
await tester.pumpWidget(
_materialHost(linearGraph(), onSelected: picked.add),
);
await _settle(tester);
final controller = tester
.widget<InteractiveViewer>(find.byType(InteractiveViewer))
.transformationController!;
final fitted = controller.value.getMaxScaleOnAxis();
// Scale about the node's own on-screen point, as a pinch there would.
final viewportRect = tester.getRect(find.byType(InteractiveViewer));
final anchor = _nodeRect(tester, 'build').center - viewportRect.topLeft;
final zoom = Matrix4.identity()
..translateByDouble(anchor.dx, anchor.dy, 0, 1)
..scaleByDouble(1.6, 1.6, 1.6, 1)
..translateByDouble(-anchor.dx, -anchor.dy, 0, 1);
controller.value = zoom * controller.value;
await tester.pump();
expect(controller.value.getMaxScaleOnAxis(), greaterThan(fitted));
// The node's on-screen rectangle already carries the transform, so this
// tap lands where the node is drawn rather than at its graph coordinate.
final build = _nodeRect(tester, 'build');
expect(
tester.getRect(find.byType(InteractiveViewer)).contains(build.center),
isTrue,
);
await tester.tapAt(build.center);
await tester.pump();
expect(picked, ['build']);
});
testWidgets('nodes use measured native sizes and never overlap', (
tester,
) async {
@@ -194,13 +246,13 @@ void main() {
final graph = linearGraph();
await tester.pumpWidget(_materialHost(graph));
await _settle(tester);
final oneX = _nodeRect(tester, 'plan');
final oneX = _measuredNodeSize(tester, 'plan');
final oneXLabel = tester.getRect(find.text('error*'));
await tester.pumpWidget(_materialHost(graph, scale: 2));
await _settle(tester);
final twoX = _nodeRect(tester, 'plan');
final twoX = _measuredNodeSize(tester, 'plan');
expect(twoX.height, greaterThan(oneX.height));
expect(twoX.width, greaterThan(oneX.width));
expect(
@@ -248,7 +300,13 @@ void main() {
);
await _settle(tester);
expect(find.byType(CupertinoButton), findsNWidgets(5));
expect(
find.descendant(
of: find.byType(GraphStageNode),
matching: find.byType(CupertinoButton),
),
findsNWidgets(5),
);
expect(find.byType(Card), findsNothing);
_expectNoOverlaps(tester);
@@ -5,6 +5,7 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/graph/domain/graph_protocol.dart';
import 'package:pipelines_app/features/graph/viewport/graph_expanded_view.dart';
import 'package:pipelines_app/features/graph/widgets/graph_stage_node.dart';
import 'package:pipelines_app/features/graph/widgets/run_graph_canvas.dart';
import 'package:pipelines_app/features/graph/widgets/run_graph_view.dart';
@@ -203,6 +204,24 @@ void main() {
expect(tester.takeException(), isNull);
});
testWidgets('the expanded run graph keeps the route legend', (tester) async {
await tester.pumpWidget(_materialHost(linearGraph(), _runningRun()));
await _settle(tester);
await tester.tap(find.byKey(const Key('graph-expand')));
await tester.pumpAndSettle();
final expanded = find.byType(GraphExpandedView);
expect(expanded, findsOneWidget);
for (final label in [runGraphExecuted, runGraphNotExecuted]) {
expect(
find.descendant(of: expanded, matching: find.text(label)),
findsOneWidget,
reason: 'the full-screen canvas must explain its routes: $label',
);
}
expect(tester.takeException(), isNull);
});
testWidgets('only routes the run took are executed and labelled', (
tester,
) async {
@@ -439,7 +458,13 @@ void main() {
await _settle(tester);
expect(find.byType(Card), findsNothing);
expect(find.byType(CupertinoButton), findsNWidgets(5));
expect(
find.descendant(
of: find.byType(GraphStageNode),
matching: find.byType(CupertinoButton),
),
findsNWidgets(5),
);
expect(find.text(runGraphExecuted), findsOneWidget);
expect(find.text(runGraphNotExecuted), findsOneWidget);
expect(
@@ -81,6 +81,7 @@ Future<RunsController> pumpRunDetail(
JsonMap? run,
Size size = const Size(900, 1000),
double scale = 1,
Brightness brightness = Brightness.light,
}) async {
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1;
@@ -100,10 +101,20 @@ Future<RunsController> pumpRunDetail(
).copyWith(textScaler: TextScaler.linear(scale)),
child: view,
);
// A caller that pumps a second run in one test must not inherit the previous
// detail's open tab or pane, so start from an empty tree.
await tester.pumpWidget(const SizedBox.shrink());
await tester.pumpWidget(
platform == RunDetailTestPlatform.material
? MaterialApp(home: Scaffold(body: page))
? MaterialApp(
theme: ThemeData(
brightness: brightness,
platform: TargetPlatform.android,
),
home: Scaffold(body: page),
)
: CupertinoApp(
theme: CupertinoThemeData(brightness: brightness),
home: CupertinoPageScaffold(child: SafeArea(child: page)),
),
);
@@ -4,7 +4,6 @@ import 'package:pipelines_app/features/graph/widgets/graph_stage_node.dart';
import 'package:pipelines_app/features/graph/widgets/run_graph_canvas.dart';
import 'package:pipelines_app/features/graph/widgets/run_graph_view.dart';
import 'package:pipelines_app/features/runs/ui/run_detail_tab.dart';
import 'package:pipelines_app/features/runs/ui/run_detail_timeline.dart';
import 'run_detail_graph_support.dart';
@@ -41,32 +40,25 @@ void main() {
expect(tester.takeException(), isNull);
});
testWidgets('${platform.name} stage click highlights its recorded visit', (
testWidgets('${platform.name} stage click opens its recorded visit pane', (
tester,
) async {
await pumpRunDetail(tester, platform);
await openRunDetailTab(tester, RunDetailTab.graph);
await tapGraphNode(tester, 'plan');
await tester.pumpAndSettle();
// The Graph reports the stage and the detail moves to Timeline, where the
// exact recorded visit is selected.
// exact recorded visit is open.
expect(find.byType(RunGraphView), findsNothing);
expect(
find.byKey(const Key('run-detail-tab-body-timeline')),
findsOneWidget,
);
final selected = tester.widget<RunTimelineRow>(
find.byKey(const ValueKey('run-timeline-visit-1')),
);
expect(selected.selected, isTrue);
expect(
tester
.widget<RunTimelineRow>(
find.byKey(const ValueKey('run-timeline-visit-2')),
)
.selected,
isFalse,
);
expect(find.byKey(const Key('run-visit-pane')), findsOneWidget);
expect(find.byKey(const Key('run-visit-title')), findsOneWidget);
expect(find.text('plan · visit 1'), findsOneWidget);
expect(find.textContaining('Status:'), findsOneWidget);
expect(find.textContaining('audit · visit'), findsNothing);
});
@@ -0,0 +1,187 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_gallery_page.dart';
import 'package:pipelines_app/features/graph/widgets/stage_definition_view.dart';
import 'package:pipelines_app/features/runs/ui/run_detail_visit_facts.dart';
import 'package:pipelines_app/features/runs/ui/run_detail_visit_sections.dart';
import 'package:pipelines_app/features/runs/ui/run_detail_visit_session_state.dart';
import 'run_detail_graph_support.dart';
import 'run_detail_visit_support.dart';
void main() {
for (final platform in RunDetailTestPlatform.values) {
testWidgets('${platform.name} tabs show recorded values and exact empty '
'wording', (tester) async {
await openVisit(tester, platform);
expect(find.textContaining('"prompt": "Ship it."'), findsOneWidget);
await openVisitTab(tester, RunVisitSection.output);
expect(find.textContaining('"result": "ok"'), findsOneWidget);
await openVisitTab(tester, RunVisitSection.artifacts);
expect(find.text('plan.csv'), findsOneWidget);
await tester.tap(find.text('plan.csv'));
await tester.pumpAndSettle();
expect(find.byType(ArtifactGalleryPage), findsOneWidget);
// The opened page lists exactly the pane's stage files: the session
// evidence file is not stage output and stays out of both.
expect(find.text('plan · visit 1'), findsOneWidget);
expect(find.text('plan.csv'), findsOneWidget);
expect(find.text('session.html'), findsNothing);
expect(find.text('Artifacts · 1 recorded'), findsOneWidget);
await tester.pageBack();
await tester.pumpAndSettle();
await openVisitTab(tester, RunVisitSection.session);
expect(find.text('Session'), findsWidgets);
expect(find.text('sess-1'), findsOneWidget);
expect(find.text('Open session.html'), findsOneWidget);
await openVisitTab(tester, RunVisitSection.definition);
expect(find.byType(StageDefinitionView), findsOneWidget);
expect(find.text('Draft the plan.'), findsOneWidget);
});
testWidgets('${platform.name} artifacts tab reports the capture state', (
tester,
) async {
final absent = visitRunFixture();
firstVisitStep(absent).remove('artifacts');
await openVisit(tester, platform, run: absent);
await openVisitTab(tester, RunVisitSection.artifacts);
expect(find.text('Artifacts · capture unavailable'), findsOneWidget);
final empty = visitRunFixture();
firstVisitStep(empty)['artifacts'] = <dynamic>[];
await openVisit(tester, platform, run: empty);
await openVisitTab(tester, RunVisitSection.artifacts);
expect(
find.text('Artifacts · not recorded for this visit'),
findsOneWidget,
);
final running = visitRunFixture();
final runningStep = firstVisitStep(running);
runningStep['status'] = 'running';
runningStep['artifacts'] = <dynamic>[];
await openVisit(tester, platform, run: running);
await openVisitTab(tester, RunVisitSection.artifacts);
expect(find.text('Artifacts · capture pending'), findsOneWidget);
});
testWidgets('${platform.name} empty sections use the exact wording', (
tester,
) async {
final run = visitRunFixture();
final step = firstVisitStep(run);
step.remove('input');
step.remove('output');
step['artifacts'] = <dynamic>[];
step.remove('session_id');
step.remove('session_export');
await openVisit(tester, platform, run: run);
expect(find.text(visitEmptyInput), findsOneWidget);
await openVisitTab(tester, RunVisitSection.output);
expect(find.text(visitEmptyOutput), findsOneWidget);
await openVisitTab(tester, RunVisitSection.artifacts);
expect(
find.text('Artifacts · not recorded for this visit'),
findsOneWidget,
);
await openVisitTab(tester, RunVisitSection.session);
// A completed model visit with no identity is a runtime error, not a
// generic "no session" claim.
expect(find.text(visitSessionNoIdentity), findsOneWidget);
});
testWidgets('${platform.name} later visit pane and opened gallery agree on '
'attributed files', (tester) async {
final run = visitRunFixture();
final steps = run['steps'] as List;
firstVisitStep(run)['artifacts'] = <dynamic>[
<String, dynamic>{
'name': 'public/shared.csv',
'url': 'https://example.test/artifacts/1/public/shared.csv',
'content_type': 'text/csv',
'size_bytes': 10,
},
<String, dynamic>{
'name': 'plan.csv',
'url': 'https://example.test/artifacts/1/plan.csv',
'content_type': 'text/csv',
'size_bytes': 42,
},
];
steps.add(<String, dynamic>{
'stage': 'plan',
'sequence': 2,
'status': 'completed',
'outcome': 'success',
'artifacts': <dynamic>[
<String, dynamic>{
'name': 'public/shared.csv',
'url': 'https://example.test/artifacts/2/public/shared.csv',
'content_type': 'text/csv',
'size_bytes': 10,
},
<String, dynamic>{
'name': 'plan-2.csv',
'url': 'https://example.test/artifacts/2/plan-2.csv',
'content_type': 'text/csv',
'size_bytes': 7,
},
],
});
await openVisit(tester, platform, run: run, sequence: 2);
expect(find.text('plan · visit 2'), findsOneWidget);
await openVisitTab(tester, RunVisitSection.artifacts);
expect(find.text('plan-2.csv'), findsOneWidget);
expect(find.text('public/shared.csv'), findsNothing);
await tester.tap(find.text('plan-2.csv'));
await tester.pumpAndSettle();
expect(find.byType(ArtifactGalleryPage), findsOneWidget);
expect(find.text('plan · visit 2'), findsOneWidget);
expect(find.text('plan-2.csv'), findsOneWidget);
expect(find.text('public/shared.csv'), findsNothing);
expect(find.text('Artifacts · 1 recorded'), findsOneWidget);
});
testWidgets('${platform.name} missing definition uses exact wording', (
tester,
) async {
await openVisit(
tester,
platform,
run: visitRunFixture(declareStage: false),
);
await openVisitTab(tester, RunVisitSection.definition);
expect(find.byType(StageDefinitionView), findsNothing);
expect(find.text(unknownStageDefinition), findsOneWidget);
expect(find.text('Draft the plan.'), findsNothing);
});
testWidgets('${platform.name} visit sections at 320 with 2x dark text', (
tester,
) async {
await openVisit(
tester,
platform,
size: const Size(320, 568),
scale: 2,
brightness: Brightness.dark,
);
expect(find.byKey(const Key('run-visit-pane')), findsOneWidget);
expect(tester.takeException(), isNull);
for (final section in RunVisitSection.values) {
await openVisitTab(tester, section);
expect(tester.takeException(), isNull, reason: section.label);
}
});
}
}
@@ -0,0 +1,147 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/runs/ui/run_detail_visit_sections.dart';
import 'package:pipelines_app/features/runs/ui/run_detail_visit_session.dart';
import 'package:pipelines_app/features/runs/ui/run_detail_visit_session_state.dart';
import 'run_detail_graph_support.dart';
import 'run_detail_visit_support.dart';
void main() {
for (final platform in RunDetailTestPlatform.values) {
testWidgets('${platform.name} legacy session.html stays openable', (
tester,
) async {
final run = visitRunFixture();
firstVisitStep(run).remove('session_export');
await openVisit(tester, platform, run: run);
await openVisitTab(tester, RunVisitSection.session);
expect(find.text('sess-1'), findsOneWidget);
expect(find.text('Open session.html'), findsOneWidget);
expect(
find.textContaining('not available in the artifact inventory'),
findsNothing,
);
});
testWidgets('${platform.name} running and failed model visits report '
'their session state', (tester) async {
final running = visitRunFixture();
final runningStep = firstVisitStep(running);
runningStep['status'] = 'running';
runningStep.remove('session_id');
runningStep.remove('session_export');
runningStep.remove('artifacts');
await openVisit(tester, platform, run: running);
await openVisitTab(tester, RunVisitSection.session);
expect(find.text(visitSessionStarting), findsOneWidget);
final failed = visitRunFixture();
final failedStep = firstVisitStep(failed);
failedStep['status'] = 'failed';
failedStep.remove('session_id');
failedStep.remove('session_export');
failedStep.remove('artifacts');
failedStep['diagnostic'] = 'Provider refused.';
await openVisit(tester, platform, run: failed);
await openVisitTab(tester, RunVisitSection.session);
expect(
find.text('$visitSessionFailed Provider refused.'),
findsOneWidget,
);
});
}
testWidgets('a recorded session without any export file reports its state', (
tester,
) async {
final step = firstVisitStep(visitRunFixture());
step.remove('session_export');
step['artifacts'] = <dynamic>[
<String, dynamic>{
'name': 'plan.csv',
'url': 'https://example.test/artifacts/plan.csv',
'content_type': 'text/csv',
'size_bytes': 42,
},
];
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: RunVisitSession(step: step, configuredEndpoint: ''),
),
),
);
expect(
find.text('Session sess-1 is recorded. Its export is not yet available.'),
findsOneWidget,
);
expect(find.textContaining('Open '), findsNothing);
step['session_export'] = <String, dynamic>{
'html': 'session.html',
'status': 'failed',
'diagnostic': 'Repair failed.',
};
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: RunVisitSession(step: step, configuredEndpoint: ''),
),
),
);
expect(
find.text(
'Session sess-1 is recorded. Its export is failed. Repair failed.',
),
findsOneWidget,
);
});
testWidgets('session entry opens the resolved export externally', (
tester,
) async {
Uri? opened;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: RunVisitSession(
step: firstVisitStep(visitRunFixture()),
configuredEndpoint: 'ws://example.test/connect',
openExternal: (uri) async {
opened = uri;
return true;
},
),
),
),
);
await tester.tap(find.text('Open session.html'));
await tester.pumpAndSettle();
expect(opened, Uri.parse('https://example.test/artifacts/session.html'));
expect(find.text('Link opened externally.'), findsOneWidget);
});
testWidgets('session open refusal is reported', (tester) async {
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: RunVisitSession(
step: firstVisitStep(visitRunFixture()),
configuredEndpoint: 'ws://example.test/connect',
openExternal: (uri) async => false,
),
),
),
);
await tester.tap(find.text('Open session.html'));
await tester.pumpAndSettle();
expect(find.text('Could not open the link.'), findsOneWidget);
});
}
@@ -0,0 +1,116 @@
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/runs/ui/run_detail_tab.dart';
import 'package:pipelines_app/features/runs/ui/run_detail_visit_sections.dart';
import 'run_detail_graph_support.dart';
/// plan -> build, with one rich recorded plan visit.
JsonMap visitRunFixture({
bool bothTimestamps = true,
bool providerModel = true,
bool declareStage = true,
}) => <String, dynamic>{
'id': 77,
'title': 'Visit run',
'name': 'release',
'pipeline_id': 7,
'version': 3,
'status': 'succeeded',
'graph': <String, dynamic>{
'stages': <dynamic>[
if (declareStage)
<String, dynamic>{
'key': 'plan',
'type': 'model',
'prompt': 'Draft the plan.',
'edges': <String, String?>{'success': 'build', 'error': '#'},
},
<String, dynamic>{
'key': 'build',
'type': 'model',
'edges': <String, String?>{'success': '#success'},
},
],
},
'steps': <dynamic>[
<String, dynamic>{
'stage': 'plan',
'sequence': 1,
'status': 'completed',
'outcome': 'success',
'target': 'build',
if (providerModel) 'provider': 'anthropic',
if (providerModel) 'model': 'claude-x',
if (bothTimestamps) 'started_at': '2026-10-22T00:00:00Z',
if (bothTimestamps) 'finished_at': '2026-10-22T00:02:05Z',
'diagnostic': 'Plan checked.',
'verdict': <String, dynamic>{
'option': 'approve',
'reason': 'Looks good.',
},
'input': <String, dynamic>{'prompt': 'Ship it.'},
'output': <String, dynamic>{'result': 'ok'},
'session_id': 'sess-1',
'session_export': <String, dynamic>{
'html': 'session.html',
'status': 'complete',
'messages': 3,
'html_bytes': 1234,
},
'artifacts': <dynamic>[
<String, dynamic>{
'name': 'plan.csv',
'url': 'https://example.test/artifacts/plan.csv',
'content_type': 'text/csv',
'size_bytes': 42,
},
<String, dynamic>{
'name': 'session.html',
'url': 'https://example.test/artifacts/session.html',
'content_type': 'text/html',
'size_bytes': 100,
},
],
},
],
};
/// The first recorded step of a detail fixture, for tests that change one
/// visit's recorded fields.
JsonMap firstVisitStep(JsonMap run) =>
(run['steps'] as List).first as Map<String, dynamic>;
Future<void> openVisit(
WidgetTester tester,
RunDetailTestPlatform platform, {
JsonMap? run,
int sequence = 1,
Size size = const Size(900, 1000),
double scale = 1,
Brightness brightness = Brightness.light,
}) async {
await pumpRunDetail(
tester,
platform,
run: run ?? visitRunFixture(),
size: size,
scale: scale,
brightness: brightness,
);
await openRunDetailTab(tester, RunDetailTab.timeline);
final row = find.byKey(ValueKey('run-timeline-visit-$sequence'));
await tester.ensureVisible(row);
await tester.pumpAndSettle();
await tester.tap(row);
await tester.pumpAndSettle();
}
Future<void> openVisitTab(WidgetTester tester, RunVisitSection section) async {
final tab = find.byKey(ValueKey('run-visit-tab-${section.name}'));
await tester.ensureVisible(tab);
await tester.pumpAndSettle();
await tester.tap(tab);
await tester.pumpAndSettle();
}
@@ -0,0 +1,106 @@
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/runs/ui/run_detail_timeline.dart';
import 'package:pipelines_app/features/runs/ui/run_detail_visit_session.dart';
import 'package:pipelines_app/features/runs/ui/run_detail_visit_session_state.dart';
import 'run_detail_graph_support.dart';
import 'run_detail_visit_support.dart';
void main() {
for (final platform in RunDetailTestPlatform.values) {
testWidgets('${platform.name} visit shows only its recorded facts', (
tester,
) async {
await openVisit(tester, platform);
expect(find.byKey(const Key('run-visit-pane')), findsOneWidget);
expect(find.text('plan · visit 1'), findsOneWidget);
for (final value in [
'Status: completed',
'Outcome: success',
'Duration: 2m 5s',
'Provider/model: anthropic / claude-x',
'Target: build',
]) {
expect(find.textContaining(value), findsOneWidget, reason: value);
}
for (final value in ['approve', 'Looks good.', 'Plan checked.']) {
expect(find.text(value), findsOneWidget, reason: value);
}
expect(find.text('Verdict'), findsOneWidget);
expect(find.text('Diagnostic'), findsOneWidget);
});
testWidgets('${platform.name} duration hides without both timestamps', (
tester,
) async {
await openVisit(
tester,
platform,
run: visitRunFixture(bothTimestamps: false),
);
expect(find.textContaining('Duration'), findsNothing);
expect(find.textContaining('0s'), findsNothing);
expect(find.textContaining('Status: completed'), findsOneWidget);
});
testWidgets('${platform.name} absent provider/model is not invented', (
tester,
) async {
await openVisit(
tester,
platform,
run: visitRunFixture(providerModel: false),
);
expect(find.textContaining('Provider/model'), findsNothing);
expect(find.textContaining('anthropic / claude-x'), findsNothing);
});
testWidgets('${platform.name} Back closes the visit pane', (tester) async {
await openVisit(tester, platform);
await tester.tap(find.byKey(const Key('run-visit-back')));
await tester.pumpAndSettle();
expect(find.byKey(const Key('run-visit-pane')), findsNothing);
expect(find.byType(RunTimelineList), findsOneWidget);
expect(find.text('plan · visit 1'), findsOneWidget);
});
testWidgets('${platform.name} visit pane at 320 with 2x dark text', (
tester,
) async {
await openVisit(
tester,
platform,
size: const Size(320, 568),
scale: 2,
brightness: Brightness.dark,
);
expect(find.byKey(const Key('run-visit-pane')), findsOneWidget);
expect(tester.takeException(), isNull);
});
}
testWidgets('session export with no configured endpoint states the hint', (
tester,
) async {
final step = (visitRunFixture()['steps'] as List).first as JsonMap;
final artifacts = step['artifacts'] as List;
(artifacts[1] as JsonMap)['url'] = '/artifacts/session.html';
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: RunVisitSession(step: step, configuredEndpoint: ''),
),
),
);
expect(find.text('Open session.html'), findsNothing);
expect(find.text(visitSessionEndpointMissing), findsOneWidget);
});
}