Merge branch 'main' into flutter/chat-markdown

This commit is contained in:
2026-10-21 23:34:35 +01:00
91 changed files with 12318 additions and 149 deletions
+18 -1
View File
@@ -7,6 +7,10 @@ void main() {
expect(AppRoute.parse('/runs'), AppRoute.runs);
expect(AppRoute.parse('/runs/12'), AppRoute.run(12));
expect(AppRoute.parse('/chat'), AppRoute.chat);
expect(
AppRoute.parse('/chat/abc_DEF-123'),
AppRoute.chatSession('abc_DEF-123'),
);
expect(AppRoute.parse('/settings'), AppRoute.settings);
});
@@ -18,6 +22,14 @@ void main() {
AppRoute.run(7),
);
expect(AppRoute.parse('/runs/7/'), AppRoute.run(7));
expect(
AppRoute.parse('/chat/session/?x=1'),
AppRoute.chatSession('session'),
);
expect(
AppRoute.parse('/chat/probe%2Dchat'),
AppRoute.chatSession('probe-chat'),
);
});
test('a malformed or unknown location is the default Pipelines route', () {
@@ -29,7 +41,9 @@ void main() {
'/runs/-1',
'/runs/1/extra',
'/pipelines/2',
'/chat/session',
'/chat/a/b',
'/chat/%2F',
'/chat/${'x' * 201}',
'/unknown',
'/runs/%E0%A4%A',
]) {
@@ -43,10 +57,13 @@ void main() {
AppRoute.runs,
AppRoute.run(3),
AppRoute.chat,
AppRoute.chatSession('probe_open-1'),
AppRoute.settings,
]) {
expect(AppRoute.parse(route.path), route);
}
expect(AppRoute.run(3).path, '/runs/3');
expect(AppRoute.chatSession('probe_open-1').path, '/chat/probe_open-1');
expect(AppRoute.chatSession('bad id').path, '/chat');
});
}
+31
View File
@@ -0,0 +1,31 @@
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/application/app_route.dart';
import 'package:pipelines_app/application/app_router.dart';
AppRouterDelegate delegate(AppRoute initial, {void Function()? onChat}) =>
AppRouterDelegate(
builder: (context, route) => const SizedBox.shrink(),
onPopToRuns: () {},
onPopToChat: onChat ?? () {},
cupertino: false,
initial: initial,
);
void main() {
test('system Back leaves one chat session for the chat list', () async {
var left = 0;
final router = delegate(AppRoute.chatSession('s1'), onChat: () => left++);
addTearDown(router.dispose);
expect(await router.popRoute(), isTrue);
expect(left, 1);
});
test('system Back on a list destination stays with the platform', () async {
final router = delegate(AppRoute.chat);
addTearDown(router.dispose);
expect(await router.popRoute(), isFalse);
});
}
@@ -0,0 +1,113 @@
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/application/app_session.dart';
import 'package:pipelines_app/application/chat_destination.dart';
import 'package:pipelines_app/core/transport/pipelines_client.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import '../core/transport/pipelines_client_test.dart' show FakeChannel;
import 'chat_registration_test.dart'
show
replyHistory,
replySessions,
replySubscribe,
requestOf,
waitForRequest,
webServer;
Widget host(AppSession session, {String? initialSessionId}) => MaterialApp(
home: Scaffold(
body: ChatDestination(
session: session,
server: webServer(),
initialSessionId: initialSessionId,
),
),
);
void main() {
testWidgets('nothing is requested before the shared socket is ready', (
tester,
) async {
final channel = FakeChannel();
final client = PipelinesClient(channelFactory: (_) => channel);
final server = webServer();
final session = AppSession(endpoint: server.uri, client: client);
addTearDown(session.dispose);
final starting = session.start();
await tester.pumpWidget(host(session, initialSessionId: 's1'));
expect(find.text('Connecting to Pipelines…'), findsOneWidget);
expect(find.byType(ChatThreadView), findsNothing);
expect(channel.outgoing, isEmpty);
channel.readyCompleter.complete();
await starting;
});
testWidgets('a reconnect resyncs the open session without losing it', (
tester,
) async {
final first = FakeChannel()..readyCompleter.complete();
final second = FakeChannel()..readyCompleter.complete();
var sockets = 0;
final client = PipelinesClient(
channelFactory: (_) => sockets++ == 0 ? first : second,
backoffBase: const Duration(milliseconds: 10),
);
final server = webServer();
final session = AppSession(endpoint: server.uri, client: client);
addTearDown(session.dispose);
await session.start();
await tester.pumpWidget(host(session, initialSessionId: 's1'));
await tester.pump();
await replySessions(tester, first);
await replySubscribe(tester, first);
await replyHistory(tester, first);
expect(find.text('The stored reply stays readable.'), findsOneWidget);
first.incoming.addError(StateError('network drop'));
await tester.pump();
expect(find.byType(ChatThreadView), findsOneWidget);
expect(find.text('The stored reply stays readable.'), findsOneWidget);
// The mounted session list re-reads on reconnect: a session created while
// the socket was gone must not stay invisible until Refresh. Requests are
// serialized, so this reply also lets the thread's resync proceed.
final relisted = await waitForRequest(tester, second, 'chat_sessions');
second.incoming.add(
jsonEncode({
'id': relisted['id'],
'type': 'chat_sessions',
'chat_sessions': [
{'id': 's1', 'title': 'Wire chat'},
{'id': 's2', 'title': 'Created while offline'},
],
}),
);
await tester.pump();
final resubscribe = await waitForRequest(tester, second, 'chat_subscribe');
second.incoming.add(
jsonEncode({'id': resubscribe['id'], 'type': 'chat_subscribe'}),
);
await tester.pump();
await replyHistory(tester, second, text: 'Refreshed after reconnect.');
expect(find.byType(ChatThreadView), findsOneWidget);
expect(find.text('Refreshed after reconnect.'), findsOneWidget);
expect(find.text('The stored reply stays readable.'), findsNothing);
expect(requestOf(second, 'chat_messages')!['chat_query'], {
'session_id': 's1',
'limit': 200,
'cursor': '',
});
expect(
find.text('Created while offline', skipOffstage: false),
findsOneWidget,
);
});
}
@@ -0,0 +1,235 @@
import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/application/pipelines_app.dart';
import 'package:pipelines_app/application/server_endpoint.dart';
import 'package:pipelines_app/core/transport/pipelines_client.dart';
import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart';
import 'package:pipelines_app/features/chat/ui/sessions/chat_sessions_screen.dart';
import '../core/transport/pipelines_client_test.dart' show FakeChannel;
ServerEndpoint webServer() => ServerEndpoint.resolve(
base: Uri.parse('http://127.0.0.1:8096/'),
web: true,
);
Map<String, dynamic>? requestOf(
FakeChannel channel,
String type, {
int index = 0,
}) => channel.outgoing
.map((frame) => jsonDecode(frame as String) as Map<String, dynamic>)
.where((frame) => frame['type'] == type)
.skip(index)
.firstOrNull;
Future<Map<String, dynamic>> waitForRequest(
WidgetTester tester,
FakeChannel channel,
String type, {
int index = 0,
}) async {
for (var attempt = 0; attempt < 80; attempt++) {
final request = requestOf(channel, type, index: index);
if (request != null) return request;
await tester.pump(const Duration(milliseconds: 5));
}
fail('Timed out waiting for $type #$index');
}
Future<void> replySessions(
WidgetTester tester,
FakeChannel channel, {
int index = 0,
}) async {
final request = await waitForRequest(
tester,
channel,
'chat_sessions',
index: index,
);
channel.incoming.add(
jsonEncode({
'id': request['id'],
'type': 'chat_sessions',
'chat_sessions': [
{'id': 's1', 'title': 'Wire chat', 'directory': '/workspace/demo'},
],
}),
);
await tester.pump();
}
Future<void> replySubscribe(
WidgetTester tester,
FakeChannel channel, {
int index = 0,
}) async {
final request = await waitForRequest(
tester,
channel,
'chat_subscribe',
index: index,
);
channel.incoming.add(
jsonEncode({'id': request['id'], 'type': 'chat_subscribe'}),
);
await tester.pump();
await tester.pump();
}
Future<void> replyHistory(
WidgetTester tester,
FakeChannel channel, {
int index = 0,
String text = 'The stored reply stays readable.',
}) async {
final request = await waitForRequest(
tester,
channel,
'chat_messages',
index: index,
);
channel.incoming.add(
jsonEncode({
'id': request['id'],
'type': 'chat_history',
'chat_history': {
'messages': [
{
'id': 'u1',
'role': 'user',
'parts': [
{'type': 'text', 'text': 'Open this chat from its route.'},
],
},
{
'id': 'a1',
'role': 'assistant',
'parts': [
{'type': 'text', 'text': text},
{'type': 'reasoning', 'text': 'Kept behind a native disclosure.'},
{'type': 'tool', 'name': 'shell'},
],
},
],
'next_cursor': '',
'has_more': false,
},
}),
);
await tester.pump();
await tester.pump();
}
void main() {
for (final cupertino in [false, true]) {
testWidgets(
'a /chat/s1 deep link renders that thread and Back returns to /chat ($cupertino)',
(tester) async {
tester.view.physicalSize = const Size(900, 900);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
if (cupertino) {
tester.platformDispatcher.platformBrightnessTestValue =
Brightness.dark;
addTearDown(
tester.platformDispatcher.clearPlatformBrightnessTestValue,
);
}
final channel = FakeChannel()..readyCompleter.complete();
final client = PipelinesClient(channelFactory: (_) => channel);
final provider = PlatformRouteInformationProvider(
initialRouteInformation: RouteInformation(uri: Uri.parse('/chat/s1')),
);
addTearDown(provider.dispose);
await tester.pumpWidget(
PipelinesApp(
server: webServer(),
client: client,
cupertino: cupertino,
routeInformationProvider: provider,
),
);
await tester.pump();
await replySessions(tester, channel);
await replySubscribe(tester, channel);
await replyHistory(tester, channel);
expect(provider.value.uri.path, '/chat/s1');
expect(find.byType(ChatThreadView), findsOneWidget);
// The exact route names the session; the request carries the same id.
expect(requestOf(channel, 'chat_subscribe')!['chat_subscribe'], {
'session_id': 's1',
});
expect(requestOf(channel, 'chat_messages')!['chat_query'], {
'session_id': 's1',
'limit': 200,
'cursor': '',
});
expect(find.text('The stored reply stays readable.'), findsOneWidget);
expect(find.text('Reasoning'), findsOneWidget);
expect(find.text('shell'), findsOneWidget);
expect(find.text('Kept behind a native disclosure.'), findsNothing);
// One shell bar only: the embedded list/thread adds no second one.
if (cupertino) {
expect(find.byType(CupertinoNavigationBar), findsOneWidget);
expect(find.byType(AppBar), findsNothing);
} else {
expect(find.byType(AppBar), findsOneWidget);
expect(find.byType(CupertinoNavigationBar), findsNothing);
}
// A live frame updates the held thread.
channel.incoming.add(
jsonEncode({
'type': 'chat_event',
'chat_event': {
'session_id': 's1',
'message_id': 'a1',
'kind': 'text',
'part': {'id': 'p2', 'type': 'text'},
'delta': 'A live line arrived.',
},
}),
);
await tester.pump();
await tester.pump();
expect(find.text('A live line arrived.'), findsOneWidget);
await tester.tap(find.text(cupertino ? 'Back' : 'Back to chats'));
await tester.pump();
expect(provider.value.uri.path, '/chat');
expect(find.byType(ChatThreadView), findsNothing);
expect(find.byType(ChatSessionsScreen), findsOneWidget);
expect(find.text('Wire chat'), findsOneWidget);
// Browser Forward re-opens the same session through its route.
await provider.didPushRouteInformation(
RouteInformation(uri: Uri.parse('/chat/s1')),
);
await tester.pump();
expect(provider.value.uri.path, '/chat/s1');
await replySubscribe(tester, channel, index: 1);
await replyHistory(
tester,
channel,
index: 1,
text: 'Reopened from the route.',
);
expect(find.text('Reopened from the route.'), findsOneWidget);
await tester.pumpWidget(const SizedBox.shrink());
await tester.pump();
},
);
}
}
@@ -91,6 +91,7 @@ void main() {
('video/mp4', 'clip.mp4'),
('text/markdown', 'input.md'),
('text/plain', 'memory.txt'),
('text/plain', 'run.log'),
('', 'output.md'),
]) {
expect(isViewerArtifact(contentType, name), isTrue, reason: name);
@@ -100,7 +101,6 @@ void main() {
('text/csv', 'rows.csv'),
('application/json', 'payload.json'),
('text/x-python', 'main.py'),
('text/plain', 'run.log'),
('application/octet-stream', 'blob.bin'),
('', ''),
]) {
@@ -0,0 +1,99 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_preview.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart';
import 'artifact_fixtures.dart';
const _endpoint = 'ws://127.0.0.1:8081/connect';
ArtifactRecord _record(String name, {String? url, String contentType = ''}) =>
ArtifactRecord.fromJson(artifact(name, url: url, contentType: contentType));
ArtifactPreviewPlan _plan(
ArtifactRecord artifact, {
String endpoint = _endpoint,
}) => planArtifactPreview(artifact: artifact, configuredEndpoint: endpoint);
void main() {
test('an image on the configured origin is fetched locally', () {
final plan = _plan(_record('shot.png', contentType: 'image/png'));
expect(plan.kind, ArtifactPreviewKind.image);
expect(plan.canFetch, isTrue);
expect(plan.resolved?.url, 'http://127.0.0.1:8081/artifacts/1/1/shot.png');
expect(plan.message, isEmpty);
});
test('text/plain and markdown are selectable text plans', () {
expect(
_plan(_record('build.log', contentType: 'text/plain')).kind,
ArtifactPreviewKind.text,
);
expect(
_plan(_record('notes.txt', contentType: 'text/plain')).kind,
ArtifactPreviewKind.text,
);
expect(
_plan(_record('notes.md', contentType: 'text/markdown')).kind,
ArtifactPreviewKind.markdown,
);
expect(
_plan(
_record('notes.markdown', contentType: 'application/octet-stream'),
).kind,
ArtifactPreviewKind.markdown,
);
});
test('an external origin is marked and never fetchable', () {
final plan = _plan(
_record(
'shot.png',
url: 'https://elsewhere.test/shot.png',
contentType: 'image/png',
),
);
expect(plan.kind, ArtifactPreviewKind.unavailable);
expect(plan.canFetch, isFalse);
expect(plan.message, artifactPreviewExternalUrl);
expect(plan.resolved?.url, 'https://elsewhere.test/shot.png');
});
test('unsafe and absent urls are explicit and never fetchable', () {
final unsafe = _plan(
_record(
'shot.png',
url: '//evil.test/shot.png',
contentType: 'image/png',
),
);
expect(unsafe.kind, ArtifactPreviewKind.unavailable);
expect(unsafe.canFetch, isFalse);
expect(unsafe.message, artifactPreviewUnsafeUrl);
final absent = _plan(
ArtifactRecord.fromJson(<String, dynamic>{
'name': 'shot.png',
'url': '',
'content_type': 'image/png',
'size_bytes': 1,
}),
);
expect(absent.kind, ArtifactPreviewKind.unavailable);
expect(absent.canFetch, isFalse);
expect(absent.message, artifactPreviewNoUrl);
});
test('unsupported types are explicit instead of a fake preview', () {
for (final record in <ArtifactRecord>[
_record('result.csv', contentType: 'text/csv'),
_record('clip.mp4', contentType: 'video/mp4'),
_record('bundle.zip', contentType: 'application/zip'),
]) {
final plan = _plan(record);
expect(plan.kind, ArtifactPreviewKind.unsupported);
expect(plan.canFetch, isFalse);
expect(plan.message, 'This file type cannot be previewed here.');
expect(plan.resolved, isNotNull);
}
});
}
@@ -37,6 +37,7 @@ void main() {
expect(pagedArtifacts(groups).map((page) => page.artifact.name), <String>[
'input.md',
'run.log',
'shot.png',
'clip.mp4',
'memory.txt',
@@ -161,7 +162,7 @@ void main() {
artifacts: <Map<String, dynamic>>[
artifact('session.html', contentType: 'text/html'),
artifact('main.py', contentType: 'text/x-python'),
artifact('run.log', contentType: 'text/plain'),
artifact('result.csv', contentType: 'text/csv'),
],
),
]);
@@ -0,0 +1,321 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_groups.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_gallery_page.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_visit_list.dart';
import '../domain/artifact_fixtures.dart';
enum _Platform { material, cupertino }
JsonMap _recorded(
String name, {
String url = '',
String contentType = 'text/csv',
int sizeBytes = 2048,
}) => artifact(
name,
url: url.isEmpty ? null : url,
contentType: contentType,
sizeBytes: sizeBytes,
);
/// Two visits of `review` record the same filename; the second visit also
/// records `notes.md`. `build` records one file.
List<JsonMap> _steps() => <JsonMap>[
step(
stage: 'build',
sequence: 1,
visit: 1,
artifacts: [_recorded('build.log', contentType: 'text/plain')],
),
step(
stage: 'review',
sequence: 2,
visit: 1,
artifacts: [
_recorded('result.csv'),
_recorded('notes.md', contentType: 'text/markdown'),
],
),
step(
stage: 'review',
sequence: 3,
visit: 2,
artifacts: [_recorded('result.csv', url: '/artifacts/1/2/result.csv')],
),
];
Future<void> _pumpGallery(
WidgetTester tester,
_Platform platform,
List<JsonMap> steps, {
String configuredEndpoint = '',
bool executing = false,
Future<bool> Function(Uri)? openExternal,
}) async {
final page = ArtifactGalleryPage(
steps: steps,
executing: executing,
configuredEndpoint: configuredEndpoint,
openExternal: openExternal ?? (_) async => true,
);
await tester.pumpWidget(
platform == _Platform.material
? MaterialApp(home: page)
: CupertinoApp(home: page),
);
await tester.pumpAndSettle();
}
Finder _inDialog(_Platform platform, String text) => find.descendant(
of: find.byType(
platform == _Platform.material ? AlertDialog : CupertinoAlertDialog,
),
matching: find.text(text),
);
void main() {
for (final platform in _Platform.values) {
testWidgets('${platform.name}: lists recorded groups and rows', (
tester,
) async {
await _pumpGallery(tester, platform, _steps());
expect(find.text('Artifacts · 4 recorded'), findsOneWidget);
expect(find.text('build · visit 1'), findsOneWidget);
expect(find.text('review · visit 1'), findsOneWidget);
expect(find.text('review · visit 2'), findsOneWidget);
expect(find.text('result.csv'), findsNWidgets(2));
expect(find.text('notes.md'), findsOneWidget);
expect(find.text('text/markdown · 2.0\u00a0KiB'), findsOneWidget);
});
testWidgets('${platform.name}: duplicate filename stays visit distinct', (
tester,
) async {
final steps = _steps();
await _pumpGallery(tester, platform, steps);
await tester.tap(find.text('result.csv').at(1));
await tester.pumpAndSettle();
final groups = artifactGroups(steps);
final visitTwo = groups.firstWhere(
(group) => group.stageKey == 'review' && group.visit == 2,
);
final list = tester.widget<ArtifactVisitList>(
find.byType(ArtifactVisitList),
);
expect(
list.selectedIdentity,
artifactVisitIdentity(visitTwo, visitTwo.artifacts.single),
);
expect(_inDialog(platform, 'review · visit 2'), findsOneWidget);
expect(_inDialog(platform, 'review · visit 1'), findsNothing);
expect(_inDialog(platform, 'Artifacts · 1 recorded'), findsOneWidget);
});
}
testWidgets('capture notes and partial label come from the visit step', (
tester,
) async {
await _pumpGallery(tester, _Platform.material, [
step(
stage: 'review',
visit: 1,
artifacts: [_recorded('result.csv'), _recorded('notes.md')],
skipped: 2,
truncated: 3,
),
]);
expect(
find.text('Artifacts · 2 recorded · partial capture'),
findsOneWidget,
);
await tester.tap(find.text('result.csv'));
await tester.pumpAndSettle();
expect(
_inDialog(_Platform.material, 'Artifacts · 2 recorded · partial capture'),
findsOneWidget,
);
expect(
_inDialog(_Platform.material, '2 files excluded from artifact capture.'),
findsOneWidget,
);
expect(
_inDialog(
_Platform.material,
'3 files omitted by artifact capture limits.',
),
findsOneWidget,
);
});
testWidgets('an unavailable capture never claims nothing was recorded', (
tester,
) async {
await _pumpGallery(tester, _Platform.material, [
step(stage: 'review', visit: 1, includeArtifacts: false),
]);
expect(find.text('Artifacts · capture unavailable'), findsOneWidget);
expect(find.text('No artifacts recorded for this run.'), findsNothing);
});
testWidgets('a recorded empty capture says nothing was recorded', (
tester,
) async {
await _pumpGallery(tester, _Platform.material, [
step(stage: 'review', visit: 1, artifacts: const []),
]);
expect(find.text('No artifacts recorded for this run.'), findsOneWidget);
expect(find.byType(ArtifactVisitList), findsNothing);
});
testWidgets('a page with no steps says so explicitly', (tester) async {
await _pumpGallery(tester, _Platform.material, const []);
expect(find.text('No steps recorded for this run.'), findsOneWidget);
});
testWidgets('Open uses the resolved recorded url only', (tester) async {
final opened = <Uri>[];
await _pumpGallery(
tester,
_Platform.material,
[
step(
stage: 'review',
visit: 1,
artifacts: [
_recorded('result.csv', url: '/artifacts/1/1/result.csv'),
],
),
],
configuredEndpoint: 'ws://127.0.0.1:8081/connect',
openExternal: (uri) async {
opened.add(uri);
return true;
},
);
await tester.tap(find.text('result.csv'));
await tester.pumpAndSettle();
await tester.tap(_inDialog(_Platform.material, 'Open'));
await tester.pumpAndSettle();
expect(opened, [
Uri.parse('http://127.0.0.1:8081/artifacts/1/1/result.csv'),
]);
expect(find.text('Link opened externally.'), findsOneWidget);
expect(find.byType(AlertDialog), findsNothing);
});
testWidgets('an unsafe recorded url offers no open or copy action', (
tester,
) async {
await _pumpGallery(tester, _Platform.material, [
step(
stage: 'review',
visit: 1,
artifacts: [_recorded('result.csv', url: '//evil.test/result.csv')],
),
], configuredEndpoint: 'ws://127.0.0.1:8081/connect');
await tester.tap(find.text('result.csv'));
await tester.pumpAndSettle();
expect(
_inDialog(
_Platform.material,
'The recorded artifact URL cannot be opened safely.',
),
findsOneWidget,
);
expect(_inDialog(_Platform.material, 'Open'), findsNothing);
expect(_inDialog(_Platform.material, 'Copy link'), findsNothing);
});
testWidgets('a record with no url is explicit and offers no action', (
tester,
) async {
await _pumpGallery(tester, _Platform.material, [
step(
stage: 'review',
visit: 1,
artifacts: [
<String, dynamic>{
'name': 'result.csv',
'url': '',
'content_type': 'text/csv',
'size_bytes': 10,
},
],
),
]);
await tester.tap(find.text('result.csv'));
await tester.pumpAndSettle();
expect(
_inDialog(_Platform.material, 'No artifact URL recorded.'),
findsOneWidget,
);
expect(_inDialog(_Platform.material, 'Open'), findsNothing);
});
testWidgets('Copy link copies the resolved url, separate from Open', (
tester,
) async {
final copied = <String>[];
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
(call) async {
if (call.method == 'Clipboard.setData') {
copied.add((call.arguments as Map)['text'] as String);
}
return null;
},
);
addTearDown(
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
null,
),
);
final opened = <Uri>[];
await _pumpGallery(
tester,
_Platform.material,
[
step(
stage: 'review',
visit: 1,
artifacts: [
_recorded('result.csv', url: '/artifacts/1/1/result.csv'),
],
),
],
configuredEndpoint: 'ws://127.0.0.1:8081/connect',
openExternal: (uri) async {
opened.add(uri);
return true;
},
);
await tester.tap(find.text('result.csv'));
await tester.pumpAndSettle();
await tester.tap(_inDialog(_Platform.material, 'Copy link'));
await tester.pumpAndSettle();
expect(copied, ['http://127.0.0.1:8081/artifacts/1/1/result.csv']);
expect(opened, isEmpty);
expect(find.text('Link copied.'), findsOneWidget);
});
testWidgets('an executing run says capture pending', (tester) async {
await _pumpGallery(tester, _Platform.material, [
step(
stage: 'review',
visit: 1,
includeArtifacts: false,
status: 'running',
),
], executing: true);
expect(find.text('Artifacts · capture pending'), findsOneWidget);
});
}
@@ -0,0 +1,406 @@
import 'dart:async';
import 'dart:convert';
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/domain/artifact_groups.dart';
import 'package:pipelines_app/features/artifacts/domain/artifact_record.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_external_open.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_gallery_page.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_fetch.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_viewer_page.dart';
import 'package:pipelines_app/features/artifacts/ui/artifact_visit_list.dart';
import '../domain/artifact_fixtures.dart';
import 'artifact_visit_list_fixture.dart';
const _endpoint = 'ws://127.0.0.1:8081/connect';
/// A real 1x1 PNG so the image preview decodes instead of only holding bytes.
final Uint8List _png = base64Decode(
'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAE'
'hQGAhKmMIQAAAABJRU5ErkJggg==',
);
ArtifactGroup _group(
List<ArtifactRecord> artifacts, {
String stageKey = 'review',
int visit = 1,
}) => visitGroup(stageKey: stageKey, visit: visit, artifacts: artifacts);
Future<void> _pumpViewer(
WidgetTester tester, {
required List<ArtifactGroup> groups,
required String selected,
bool cupertino = false,
ArtifactFetch? fetch,
Widget Function(String)? markdownBuilder,
ArtifactExternalOpen? openExternal,
}) async {
final page = ArtifactViewerPage(
groups: groups,
selectedIdentity: selected,
configuredEndpoint: _endpoint,
fetch: fetch ?? (_) async => ArtifactFetchResult(status: 200, bytes: _png),
markdownBuilder: markdownBuilder ?? (value) => SelectableText(value),
openExternal: openExternal ?? (_) async => true,
);
await tester.pumpWidget(
cupertino
? CupertinoApp(home: page)
: MaterialApp(home: Scaffold(body: page)),
);
await tester.pumpAndSettle();
}
TextButton _textButton(WidgetTester tester, String label) {
return tester.widget<TextButton>(
find
.ancestor(of: find.text(label), matching: find.byType(TextButton))
.first,
);
}
void main() {
testWidgets('an image is previewed in-app without opening a tab', (
tester,
) async {
final fetched = <Uri>[];
final opened = <Uri>[];
await tester.pumpWidget(
MaterialApp(
home: ArtifactGalleryPage(
steps: <JsonMap>[
step(
stage: 'review',
visit: 1,
artifacts: [
artifact(
'shot.png',
url: '/artifacts/1/1/shot.png',
contentType: 'image/png',
sizeBytes: 1024,
),
],
),
],
configuredEndpoint: _endpoint,
fetch: (uri) async {
fetched.add(uri);
return ArtifactFetchResult(status: 200, bytes: _png);
},
openExternal: (uri) async {
opened.add(uri);
return true;
},
),
),
);
await tester.pumpAndSettle();
await tester.tap(find.text('shot.png'));
await tester.pumpAndSettle();
expect(find.byType(ArtifactViewerPage), findsOneWidget);
expect(fetched, [
Uri.parse('http://127.0.0.1:8081/artifacts/1/1/shot.png'),
]);
expect(find.byType(Image), findsOneWidget);
expect(find.text('1 of 1 · image/png'), findsOneWidget);
expect(find.text('image/png · 1.0\u00a0KiB'), findsOneWidget);
expect(opened, isEmpty);
expect(find.byType(AlertDialog), findsNothing);
});
testWidgets('text/plain is fetched and shown as selectable text', (
tester,
) async {
final text = recordedArtifact(
'build.log',
url: '/artifacts/1/1/build.log',
contentType: 'text/plain; charset=utf-8',
);
await _pumpViewer(
tester,
groups: [
_group([text]),
],
selected: artifactVisitIdentity(_group([text]), text),
fetch: (_) async =>
ArtifactFetchResult(status: 200, bytes: utf8.encode('build ok\n')),
);
expect(find.byType(SelectableText), findsOneWidget);
expect(find.text('build ok\n'), findsOneWidget);
expect(find.text('text/plain · 0\u00a0B'), findsOneWidget);
});
testWidgets('markdown uses the injected builder and defaults to text', (
tester,
) async {
final markdown = recordedArtifact(
'notes.md',
url: '/artifacts/1/1/notes.md',
contentType: 'text/markdown',
);
final group = _group([markdown]);
final identity = artifactVisitIdentity(group, markdown);
await _pumpViewer(
tester,
groups: [group],
selected: identity,
fetch: (_) async =>
ArtifactFetchResult(status: 200, bytes: utf8.encode('# Title')),
markdownBuilder: (value) => Text('MARKDOWN $value'),
);
expect(find.text('MARKDOWN # Title'), findsOneWidget);
await tester.pumpWidget(const SizedBox());
await _pumpViewer(
tester,
groups: [group],
selected: identity,
fetch: (_) async =>
ArtifactFetchResult(status: 200, bytes: utf8.encode('# Raw title')),
);
expect(find.byType(SelectableText), findsOneWidget);
expect(find.text('# Raw title'), findsOneWidget);
});
testWidgets('an external origin is marked and never fetched', (tester) async {
final fetched = <Uri>[];
final opened = <Uri>[];
final image = recordedArtifact(
'shot.png',
url: 'https://elsewhere.test/shot.png',
contentType: 'image/png',
);
final group = _group([image]);
await _pumpViewer(
tester,
groups: [group],
selected: artifactVisitIdentity(group, image),
fetch: (uri) async {
fetched.add(uri);
return ArtifactFetchResult(status: 200, bytes: _png);
},
openExternal: (uri) async {
opened.add(uri);
return true;
},
);
expect(
find.text(
'This artifact is hosted on another origin and is not previewed here.',
),
findsOneWidget,
);
expect(fetched, isEmpty);
expect(find.byType(Image), findsNothing);
await tester.tap(find.text('Open'));
await tester.pumpAndSettle();
expect(opened, [Uri.parse('https://elsewhere.test/shot.png')]);
});
testWidgets('the gallery marks an external viewer artifact without fetching', (
tester,
) async {
final fetched = <Uri>[];
await tester.pumpWidget(
MaterialApp(
home: ArtifactGalleryPage(
steps: <JsonMap>[
step(
stage: 'review',
visit: 1,
artifacts: [
artifact(
'shot.png',
url: 'https://elsewhere.test/shot.png',
contentType: 'image/png',
sizeBytes: 10,
),
],
),
],
configuredEndpoint: _endpoint,
fetch: (uri) async {
fetched.add(uri);
return ArtifactFetchResult(status: 200, bytes: _png);
},
openExternal: (_) async => true,
),
),
);
await tester.pumpAndSettle();
await tester.tap(find.text('shot.png'));
await tester.pumpAndSettle();
expect(find.byType(ArtifactViewerPage), findsOneWidget);
expect(
find.text(
'This artifact is hosted on another origin and is not previewed here.',
),
findsOneWidget,
);
expect(fetched, isEmpty);
expect(find.byType(Image), findsNothing);
});
testWidgets('an unsupported type is explicit, with Open and Copy link', (
tester,
) async {
final video = recordedArtifact(
'clip.mp4',
url: '/artifacts/1/1/clip.mp4',
contentType: 'video/mp4',
);
final group = _group([video]);
var fetches = 0;
await _pumpViewer(
tester,
groups: [group],
selected: artifactVisitIdentity(group, video),
fetch: (_) async {
fetches += 1;
return ArtifactFetchResult(status: 200, bytes: _png);
},
);
expect(
find.text('This file type cannot be previewed here.'),
findsOneWidget,
);
expect(find.text('Open'), findsOneWidget);
expect(find.text('Copy link'), findsOneWidget);
expect(fetches, 0);
expect(find.byType(Image), findsNothing);
});
testWidgets('paging clamps at both ends and keeps the visit facts', (
tester,
) async {
final first = recordedArtifact(
'a.png',
url: '/artifacts/1/1/a.png',
contentType: 'image/png',
);
final second = recordedArtifact(
'b.png',
url: '/artifacts/1/2/b.png',
contentType: 'image/png',
);
final third = recordedArtifact(
'c.png',
url: '/artifacts/1/3/c.png',
contentType: 'image/png',
);
final groups = [
_group([first], visit: 1),
_group([second], visit: 2),
_group([third], visit: 3),
];
await _pumpViewer(
tester,
groups: groups,
selected: artifactVisitIdentity(groups[0], first),
);
expect(find.text('1 of 3 · image/png'), findsOneWidget);
expect(_textButton(tester, 'Previous artifact').onPressed, isNull);
expect(_textButton(tester, 'Next artifact').onPressed, isNotNull);
await tester.tap(find.text('Next artifact'));
await tester.pumpAndSettle();
expect(find.text('2 of 3 · image/png'), findsOneWidget);
expect(find.text('review · visit 2'), findsOneWidget);
expect(_textButton(tester, 'Previous artifact').onPressed, isNotNull);
await tester.tap(find.text('Next artifact'));
await tester.pumpAndSettle();
expect(find.text('3 of 3 · image/png'), findsOneWidget);
expect(_textButton(tester, 'Next artifact').onPressed, isNull);
await tester.tap(find.text('Next artifact'));
await tester.pumpAndSettle();
expect(find.text('3 of 3 · image/png'), findsOneWidget);
await tester.tap(find.text('Previous artifact'));
await tester.pumpAndSettle();
expect(find.text('2 of 3 · image/png'), findsOneWidget);
});
testWidgets('loading and HTTP failure are honest', (tester) async {
final text = recordedArtifact(
'notes.txt',
url: '/artifacts/1/1/notes.txt',
contentType: 'text/plain',
);
final group = _group([text]);
final pending = Completer<ArtifactFetchResult>();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: ArtifactViewerPage(
groups: [group],
selectedIdentity: artifactVisitIdentity(group, text),
configuredEndpoint: _endpoint,
fetch: (_) => pending.future,
openExternal: (_) async => true,
),
),
),
);
await tester.pump();
expect(find.text('Loading preview…'), findsOneWidget);
pending.complete(ArtifactFetchResult(status: 404, bytes: Uint8List(0)));
await tester.pumpAndSettle();
expect(find.text('The server answered 404.'), findsOneWidget);
expect(find.byType(SelectableText), findsNothing);
});
testWidgets('a network failure is reported instead of an empty preview', (
tester,
) async {
final text = recordedArtifact(
'notes.txt',
url: '/artifacts/1/1/notes.txt',
contentType: 'text/plain',
);
final group = _group([text]);
await _pumpViewer(
tester,
groups: [group],
selected: artifactVisitIdentity(group, text),
fetch: (_) async => throw const ArtifactFetchException('network down'),
);
expect(find.textContaining('Could not load preview'), findsOneWidget);
expect(find.textContaining('network down'), findsOneWidget);
});
testWidgets('Cupertino draws the same text preview and controls', (
tester,
) async {
final text = recordedArtifact(
'notes.txt',
url: '/artifacts/1/1/notes.txt',
contentType: 'text/plain',
);
final group = _group([text]);
await _pumpViewer(
tester,
cupertino: true,
groups: [group],
selected: artifactVisitIdentity(group, text),
fetch: (_) async => ArtifactFetchResult(
status: 200,
bytes: utf8.encode('cupertino text'),
),
);
expect(find.text('cupertino text'), findsOneWidget);
expect(find.byType(CupertinoButton), findsWidgets);
});
}
@@ -0,0 +1,114 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/attention/domain/attention_models.dart';
Map<String, dynamic> run([Map<String, dynamic> overrides = const {}]) => {
'id': 1,
'name': 'Plan and land',
'title': null,
'status': 'failed',
'created_at': '2026-10-19T10:00:00Z',
'finished_at': '2026-10-19T10:05:00Z',
'diagnostic': '',
...overrides,
};
void main() {
group('dismissal and clear-all snapshot', () {
test('a dismissed identity is filtered out and never returns', () {
final rows = [
run({'id': 7, 'status': 'waiting', 'title': 'Wait'}),
];
final dismissed = attentionDismiss(const {}, '7:Decision');
expect(attentionEntries(rows, dismissed: dismissed), isEmpty);
expect(attentionEntries(rows, dismissed: dismissed), isEmpty);
});
test('a different kind for the same run is a different identity', () {
final dismissed = attentionDismiss(const {}, '7:Decision');
final failed = run({'id': 7, 'status': 'failed', 'diagnostic': 'later'});
final entries = attentionEntries([failed], dismissed: dismissed);
expect(entries.single.key, '7:Failed');
expect(entries.single.detail, 'later');
});
test('dismiss ignores a blank key and adds once', () {
final one = attentionDismiss(const {}, '1:Failed');
expect(one, {'1:Failed'});
expect(attentionDismiss(one, '1:Failed'), {'1:Failed'});
expect(attentionDismiss(one, ' '), {'1:Failed'});
expect(one, {'1:Failed'}, reason: 'input set is not mutated');
});
test('clear all applies only the identities in the open snapshot', () {
final a = attentionEntryFor(run({'id': 1}))!;
final snapshot = attentionDismissalSnapshot([a]);
final b = attentionEntryFor(run({'id': 2}))!;
final after = attentionDismissAll(const {}, snapshot);
expect(after, {'1:Failed'});
expect(after.contains(b.key), isFalse);
expect(
attentionEntries([
run({'id': 1}),
run({'id': 2}),
], dismissed: after).map((entry) => entry.runId),
[2],
);
});
test('the snapshot is a defensive copy', () {
final a = attentionEntryFor(run({'id': 1}))!;
final b = attentionEntryFor(run({'id': 2}))!;
final live = [a, b];
final snapshot = attentionDismissalSnapshot(live);
live.add(attentionEntryFor(run({'id': 3}))!);
expect(snapshot.map((entry) => entry.runId), [1, 2]);
expect(snapshot, isNot(same(live)));
});
});
group('persistence', () {
test('the key is the documented one', () {
expect(attentionStorageKey, 'pipelines.next.attention.v1');
expect(attentionStorageKey, isNot('pipelines.web.attention.v1'));
});
test('encoding is one sorted JSON array and round-trips', () {
final encoded = encodeAttentionDismissals({
'9:Failed',
'1:Decision',
'4:Failed',
});
expect(encoded, '["1:Decision","4:Failed","9:Failed"]');
expect(decodeAttentionDismissals(encoded), {
'1:Decision',
'4:Failed',
'9:Failed',
});
expect(encodeAttentionDismissals(const {}), '[]');
});
test('blank or unreadable storage decodes to empty and never throws', () {
for (final stored in [
null,
'',
' ',
'not json',
'{',
'"a string"',
'{}',
'42',
]) {
expect(decodeAttentionDismissals(stored), isEmpty);
}
});
test('a JSON array keeps only non-empty strings', () {
expect(
decodeAttentionDismissals(
'["1:Failed", 2, null, {"a":1}, "3:Decision", ""]',
),
{'1:Failed', '3:Decision'},
);
});
});
}
@@ -0,0 +1,334 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/attention/domain/attention_models.dart';
Map<String, dynamic> run([Map<String, dynamic> overrides = const {}]) => {
'id': 1,
'name': 'Plan and land',
'title': null,
'status': 'failed',
'created_at': '2026-10-19T10:00:00Z',
'finished_at': '2026-10-19T10:05:00Z',
'diagnostic': '',
...overrides,
};
void main() {
group('qualification', () {
test('only waiting and failed qualify; every other status asks nobody', () {
expect(attentionKindOf('waiting'), AttentionKind.decision);
expect(attentionKindOf('failed'), AttentionKind.failed);
for (final status in [
'queued',
'running',
'succeeded',
'canceled',
'cancelled',
'interrupted',
'active',
'blocked',
'skipped',
'unknown',
'',
' ',
null,
'FAILED?',
]) {
expect(
attentionKindOf(status),
isNull,
reason: 'status ${status ?? 'null'} must not qualify',
);
}
});
test('trims and lowercases the server words', () {
expect(attentionKindOf(' Waiting '), AttentionKind.decision);
expect(attentionKindOf('Failed\n'), AttentionKind.failed);
expect(attentionKindOf('WAITING'), AttentionKind.decision);
});
test('ranks are Decision 0 then Failed 1', () {
expect(AttentionKind.decision.rank, 0);
expect(AttentionKind.failed.rank, 1);
});
test('waiting excludes audit/export handoffs, not resource waits', () {
expect(
attentionKindForRun(run({'status': 'waiting'})),
AttentionKind.decision,
);
expect(
attentionKindForRun(
run({'status': 'waiting', 'export_pending_sequence': 4}),
),
isNull,
);
expect(
attentionKindForRun(
run({'status': 'waiting', 'export_pending_sequence': ' 2 '}),
),
isNull,
);
expect(
attentionKindForRun(
run({'status': 'waiting', 'export_pending_sequence': 0}),
),
AttentionKind.decision,
);
// web/src/attention.js and Attention.kt never consult resource_wait; the
// server retired it, so a stale value must not hide a real decision.
for (final stale in [
{'resource': 'device-1'},
'device-1',
true,
1,
]) {
expect(
attentionKindForRun(
run({'status': 'waiting', 'resource_wait': stale}),
),
AttentionKind.decision,
reason: 'resource_wait $stale must not suppress a decision',
);
}
// A failed run stays failed even if a stale export field survived.
expect(
attentionKindForRun(
run({'status': 'failed', 'export_pending_sequence': 4}),
),
AttentionKind.failed,
);
});
test(
'nonqualifying runs are dropped entirely, including malformed ids',
() {
final entries = attentionEntries([
run({'id': 1, 'status': 'succeeded'}),
run({'id': 2, 'status': 'running'}),
run({'id': 3, 'status': 'failed'}),
run({'id': 4, 'status': 'queued'}),
run({'id': 'not-a-number', 'status': 'failed'}),
run({'id': 0, 'status': 'failed'}),
]);
expect(entries.map((entry) => entry.runId), [3]);
expect(attentionEntries(null), isEmpty);
},
);
});
group('identity and wording', () {
test('identity is exactly {runId}:{kind}', () {
expect(attentionKey(440, AttentionKind.failed), '440:Failed');
expect(attentionKey(12, AttentionKind.decision), '12:Decision');
});
test('label is the trimmed title else the pipeline name', () {
expect(attentionEntryFor(run({'title': ' My run '}))!.label, 'My run');
expect(attentionEntryFor(run({'title': ' '}))!.label, 'Plan and land');
expect(attentionEntryFor(run({'title': null}))!.label, 'Plan and land');
});
test(
'detail is the decision line or the trimmed diagnostic else Run failed',
() {
expect(
attentionDetail(AttentionKind.decision, run({'status': 'waiting'})),
'Waiting for your decision',
);
expect(
attentionDetail(
AttentionKind.failed,
run({'diagnostic': ' boom '}),
),
'boom',
);
expect(
attentionDetail(AttentionKind.failed, run({'diagnostic': ' '})),
'Run failed',
);
expect(
attentionDetail(AttentionKind.failed, run({'diagnostic': null})),
'Run failed',
);
},
);
test('row description is exactly {pipeline} · {detail}', () {
final entry = attentionEntryFor(
run({'title': 'T', 'diagnostic': 'failed hard'}),
)!;
expect(attentionRowDescription(entry), 'Plan and land · failed hard');
});
test('badge label is bare Notifications when empty, else the count', () {
expect(attentionBadgeLabel(0), 'Notifications');
expect(attentionBadgeLabel(-3), 'Notifications');
expect(attentionBadgeLabel(1), 'Notifications, 1 needing attention');
expect(attentionBadgeLabel(171), 'Notifications, 171 needing attention');
});
test('the entry keeps the whole summary, including unknown fields', () {
final source = run({
'unknown_future_field': {'keep': true},
'id': 7,
});
final entry = attentionEntryFor(source)!;
expect(entry.run['unknown_future_field'], {'keep': true});
expect(entry.run, same(source));
});
});
group('ordering', () {
test('kind rank, then recency descending, then run id descending', () {
final entries = attentionEntries([
run({
'id': 10,
'status': 'failed',
'finished_at': '2026-10-19T10:00:00Z',
}),
run({
'id': 11,
'status': 'waiting',
'finished_at': '2026-10-19T09:00:00Z',
}),
run({
'id': 12,
'status': 'failed',
'finished_at': '2026-10-19T11:00:00Z',
}),
run({
'id': 13,
'status': 'waiting',
'finished_at': '2026-10-19T08:00:00Z',
}),
]);
expect(entries.map((entry) => entry.runId), [11, 13, 12, 10]);
});
test('recency falls back to created_at when finished_at is blank', () {
final entries = attentionEntries([
run({
'id': 1,
'status': 'failed',
'finished_at': '',
'created_at': '2026-10-19T12:00:00Z',
}),
run({
'id': 2,
'status': 'failed',
'finished_at': '2026-10-19T11:00:00Z',
}),
]);
expect(entries.map((entry) => entry.runId), [1, 2]);
});
test('equal kind and recency tie by run id descending and stay stable', () {
final rows = [
run({'id': 3, 'finished_at': '2026-10-19T10:00:00Z'}),
run({'id': 9, 'finished_at': '2026-10-19T10:00:00Z'}),
run({'id': 5, 'finished_at': '2026-10-19T10:00:00Z'}),
];
expect(attentionEntries(rows).map((entry) => entry.runId), [9, 5, 3]);
expect(attentionEntries(rows.reversed).map((entry) => entry.runId), [
9,
5,
3,
]);
});
});
group('local-day window', () {
final since = DateTime.utc(2026, 10, 20);
final rows = [
run({'id': 1, 'finished_at': '2026-10-19T21:33:27Z'}),
run({'id': 2, 'finished_at': '2026-10-20T10:00:00Z'}),
];
test('startOfLocalDay is local midnight, injectable for tests', () {
final now = DateTime(2026, 10, 20, 15, 4, 5, 6);
final start = startOfLocalDay(now: now);
expect(start, DateTime(2026, 10, 20));
expect(start.hour, 0);
expect(start.minute, 0);
expect(start.second, 0);
expect(start.millisecond, 0);
expect(start.isBefore(now), isTrue);
expect(start.toLocal(), start);
});
test('a cutoff drops older work and keeps newer work', () {
expect(attentionEntries(rows, since: since).map((entry) => entry.runId), [
2,
]);
});
test('no cutoff, and an epoch-zero cutoff, show everything', () {
expect(attentionEntries(rows).map((entry) => entry.runId), [2, 1]);
expect(
attentionEntries(
rows,
since: DateTime.fromMillisecondsSinceEpoch(0),
).map((entry) => entry.runId),
[2, 1],
);
});
test('the cutoff applies to waiting decisions as well as failures', () {
expect(
attentionEntries([
run({
'id': 3,
'status': 'waiting',
'finished_at': '2026-10-19T09:00:00Z',
}),
], since: since),
isEmpty,
);
});
test('unparseable or blank recency is kept, as in the browser', () {
for (final recency in ['', ' ', 'not a timestamp']) {
final kept = attentionEntries([
run({'id': 4, 'finished_at': recency, 'created_at': recency}),
], since: since);
expect(
kept.map((entry) => entry.runId),
[4],
reason: 'recency ${recency.isEmpty ? '<blank>' : recency} is kept',
);
}
});
test('finished_at is the recency the cutoff reads, else created_at', () {
expect(
attentionEntries([
run({
'id': 5,
'created_at': '2026-10-18T09:00:00Z',
'finished_at': '2026-10-20T09:00:00Z',
}),
], since: since).map((entry) => entry.runId),
[5],
);
expect(
attentionEntries([
run({
'id': 6,
'created_at': '2026-10-18T09:00:00Z',
'finished_at': '',
}),
], since: since),
isEmpty,
);
});
test('dismissal and the cutoff compose', () {
final dismissed = attentionDismiss(const {}, '2:Failed');
expect(
attentionEntries(rows, dismissed: dismissed, since: since),
isEmpty,
);
});
});
}
@@ -0,0 +1,224 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/attention/domain/attention_models.dart';
import 'package:pipelines_app/features/attention/domain/attention_transitions.dart';
Map<String, dynamic> run([Map<String, dynamic> overrides = const {}]) => {
'id': 1,
'name': 'Plan and land',
'title': null,
'status': 'failed',
'created_at': '2026-10-19T10:00:00Z',
'finished_at': '2026-10-19T10:05:00Z',
'diagnostic': '',
...overrides,
};
void main() {
test('a seeded failed/waiting run raises nothing', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 1, 'status': 'failed'}),
run({'id': 2, 'status': 'waiting'}),
]);
expect(detector.observe(run({'id': 1, 'status': 'failed'})), isNull);
expect(detector.observe(run({'id': 2, 'status': 'waiting'})), isNull);
expect(detector.emittedKeys, isEmpty);
});
test('a first-seen run raises nothing and becomes the baseline', () {
final detector = AttentionTransitionDetector();
expect(detector.observe(run({'id': 5, 'status': 'failed'})), isNull);
expect(detector.statusOf(5), 'failed');
expect(detector.observe(run({'id': 5, 'status': 'failed'})), isNull);
expect(detector.emittedKeys, isEmpty);
});
test('entering failed from a known running run emits exactly once', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 5, 'status': 'running'}),
]);
final first = detector.observe(run({'id': 5, 'status': 'failed'}));
expect(first, isNotNull);
expect(first!.runId, 5);
expect(first.kind, AttentionKind.failed);
expect(first.key, '5:Failed');
expect(first.entry.label, 'Plan and land');
expect(first.entry.detail, 'Run failed');
expect(detector.observe(run({'id': 5, 'status': 'failed'})), isNull);
expect(detector.emittedKeys, {'5:Failed'});
});
test('entering a human waiting state emits a Decision', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 6, 'status': 'running'}),
]);
final transition = detector.observe(
run({'id': 6, 'status': 'waiting', 'title': ' Decide '}),
);
expect(transition, isNotNull);
expect(transition!.kind, AttentionKind.decision);
expect(transition.key, '6:Decision');
expect(transition.entry.label, 'Decide');
expect(transition.entry.detail, 'Waiting for your decision');
});
test('waiting to failed is a new kind and emits once', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 7, 'status': 'waiting'}),
]);
final transition = detector.observe(run({'id': 7, 'status': 'failed'}));
expect(transition!.key, '7:Failed');
expect(detector.emittedKeys, {'7:Failed'});
});
test('a run that leaves the state and returns may emit again', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 8, 'status': 'running'}),
]);
expect(detector.observe(run({'id': 8, 'status': 'failed'})), isNotNull);
expect(detector.observe(run({'id': 8, 'status': 'running'})), isNull);
expect(detector.emittedKeys, isEmpty);
final again = detector.observe(run({'id': 8, 'status': 'failed'}));
expect(again, isNotNull);
expect(detector.observe(run({'id': 8, 'status': 'failed'})), isNull);
});
test('nonqualifying statuses never emit', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 9, 'status': 'queued'}),
]);
for (final status in [
'running',
'succeeded',
'canceled',
'interrupted',
'unknown',
]) {
expect(
detector.observe(run({'id': 9, 'status': status})),
isNull,
reason: 'status $status must not emit',
);
}
expect(detector.emittedKeys, isEmpty);
});
test(
'an export wait never emits a Decision even though status is waiting',
() {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 10, 'status': 'running'}),
]);
expect(
detector.observe(
run({'id': 10, 'status': 'waiting', 'export_pending_sequence': 2}),
),
isNull,
);
expect(detector.emittedKeys, isEmpty);
},
);
test('dismissed identities are marked seen but do not emit', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 11, 'status': 'running'}),
]);
expect(
detector.observe(
run({'id': 11, 'status': 'failed'}),
dismissed: {'11:Failed'},
),
isNull,
);
expect(detector.emittedKeys, {'11:Failed'});
expect(detector.observe(run({'id': 11, 'status': 'failed'})), isNull);
});
test('a reconnect reseed produces no transition and no replay', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 12, 'status': 'failed'}),
]);
detector.resetForReconnect();
detector.reseed([
run({'id': 12, 'status': 'failed'}),
]);
expect(detector.observe(run({'id': 12, 'status': 'failed'})), isNull);
expect(detector.emittedKeys, isEmpty);
});
test('a reseed keeps still-qualifying keys and prunes the rest', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 20, 'status': 'running'}),
run({'id': 21, 'status': 'running'}),
]);
expect(detector.observe(run({'id': 20, 'status': 'failed'})), isNotNull);
expect(detector.observe(run({'id': 21, 'status': 'waiting'})), isNotNull);
expect(detector.emittedKeys, {'20:Failed', '21:Decision'});
detector.reseed([
run({'id': 20, 'status': 'failed'}),
run({'id': 21, 'status': 'succeeded'}),
]);
// 20 still qualifies, so its key survives; 21 no longer asks, so its key is
// pruned and a genuine later transition can be raised once more.
expect(detector.emittedKeys, {'20:Failed'});
expect(detector.observe(run({'id': 20, 'status': 'failed'})), isNull);
expect(detector.observe(run({'id': 21, 'status': 'waiting'})), isNotNull);
expect(detector.observe(run({'id': 21, 'status': 'waiting'})), isNull);
});
test('a reseed keeps the key of a run absent from the read', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 22, 'status': 'running'}),
]);
expect(detector.observe(run({'id': 22, 'status': 'failed'})), isNotNull);
detector.reseed([
run({'id': 23, 'status': 'running'}),
]);
expect(detector.emittedKeys, {'22:Failed'});
// Absence says nothing, so seeing the same state again is not a transition.
expect(detector.observe(run({'id': 22, 'status': 'failed'})), isNull);
});
test('a snapshot bracketed as a seed does not emit or replay', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 13, 'status': 'running'}),
])
..beginSeed();
expect(detector.observe(run({'id': 13, 'status': 'waiting'})), isNull);
detector.endSeed();
expect(detector.observe(run({'id': 13, 'status': 'waiting'})), isNull);
expect(detector.emittedKeys, isEmpty);
});
test('the transition keeps the whole frame, including unknown fields', () {
final detector = AttentionTransitionDetector()
..seed([
run({'id': 14, 'status': 'running'}),
]);
final frame = run({
'id': 14,
'run_id': 14,
'status': 'failed',
'diagnostic': ' boom ',
'unknown_future_field': ['keep'],
});
final transition = detector.observe(frame);
expect(transition!.entry.detail, 'boom');
expect(transition.run, same(frame));
expect(transition.run['unknown_future_field'], ['keep']);
});
}
@@ -0,0 +1,101 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/chat/conversation/chat_row_keys.dart';
import 'package:pipelines_app/features/chat/domain/chat_transcript.dart';
import 'chat_thread_fixtures.dart';
JsonMap _assistant(String id) => chatMessage(
id,
'assistant',
parts: [
{'type': 'reasoning', 'id': 'r-$id', 'text': 'reasoning $id'},
{'type': 'text', 'id': 't-$id', 'text': 'answer $id'},
],
);
JsonMap _user(String id) => chatMessage(
id,
'user',
parts: [
{'type': 'text', 'text': 'question $id'},
],
);
void main() {
test('an older page prepended into a folded turn keeps its key', () {
final keys = ChatRowKeys();
final newest = keys.forRows(
transcriptRows([_assistant('msg_6'), _assistant('msg_4')]),
);
final paged = keys.forRows(
transcriptRows([
_assistant('msg_2'),
_assistant('msg_0'),
_assistant('msg_6'),
_assistant('msg_4'),
]),
);
expect(newest, hasLength(1));
expect(paged, hasLength(1));
expect(paged.single, newest.single);
});
test('a live assistant message appended to a folded turn keeps its key', () {
final keys = ChatRowKeys();
final newest = keys.forRows(transcriptRows([_assistant('msg_6')]));
final streamed = keys.forRows(
transcriptRows([_assistant('msg_6'), _assistant('msg_live')]),
);
expect(streamed.single, newest.single);
});
test('user rows keep their key and folded turns stay distinct', () {
final keys = ChatRowKeys();
final first = keys.forRows(
transcriptRows([
_user('u1'),
_assistant('a1'),
_user('u2'),
_assistant('a2'),
]),
);
final paged = keys.forRows(
transcriptRows([
_user('u0'),
_assistant('a0'),
_user('u1'),
_assistant('a1'),
_user('u2'),
_assistant('a2'),
]),
);
expect(first.toSet(), hasLength(4));
expect(paged.toSet(), hasLength(6));
expect(paged.sublist(2), first);
});
test('an id-less prepended turn never collides with a held key', () {
final keys = ChatRowKeys();
keys.forRows(transcriptRows([_assistant('a1')]));
final paged = keys.forRows(
transcriptRows([
// No id: only a positional fallback is possible.
chatMessage(
'',
'assistant',
parts: [
{'type': 'text', 'text': 'anonymous older answer'},
],
),
_user('u1'),
_assistant('a1'),
]),
);
expect(paged.toSet(), hasLength(paged.length));
});
}
@@ -0,0 +1,368 @@
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_thread_view.dart';
import 'chat_thread_fixtures.dart';
Widget host(Widget child) => MaterialApp(
theme: ThemeData(platform: TargetPlatform.android),
home: Scaffold(body: child),
);
Widget cupertinoHost(Widget child) => CupertinoApp(
theme: const CupertinoThemeData(brightness: Brightness.dark),
home: CupertinoPageScaffold(child: child),
);
void main() {
testWidgets('live-subscription refusal is separate from readable history', (
tester,
) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.subscribe = () async => throw StateError('live watch refused');
gateway.history = (_) async => chatPage([
chatMessage(
'u1',
'user',
parts: [
{'type': 'text', 'text': 'History still renders.'},
],
),
]);
await tester.pumpWidget(
host(ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {})),
);
await tester.pumpAndSettle();
expect(find.text('History still renders.'), findsOneWidget);
expect(find.byKey(const Key('chat-live-error')), findsOneWidget);
expect(find.textContaining('Live updates unavailable'), findsOneWidget);
expect(find.textContaining('live watch refused'), findsOneWidget);
expect(find.byKey(const Key('chat-history-error')), findsNothing);
// A later resync that attaches clears only the live notice.
gateway.subscribe = () async => const {};
gateway.history = (_) async => chatPage([
chatMessage(
'u1',
'user',
parts: [
{'type': 'text', 'text': 'History still renders.'},
],
),
]);
var attempts = 0;
for (
var i = 0;
i < 80 && find.byKey(const Key('chat-live-error')).evaluate().isNotEmpty;
i++
) {
if (attempts == 0) {
await tester.tap(find.text('Retry').last);
attempts++;
}
await tester.pump(const Duration(milliseconds: 5));
}
expect(find.byKey(const Key('chat-live-error')), findsNothing);
});
testWidgets('Load older passes the server cursor back and shows older text', (
tester,
) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
gateway.history = (_) async => chatPage(
[
chatMessage(
'a2',
'assistant',
parts: [
{'type': 'text', 'text': 'Newest reply.'},
],
),
],
cursor: 'opaque/next?x=1',
hasMore: true,
);
await tester.pumpWidget(
host(ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {})),
);
await tester.pumpAndSettle();
expect(find.text('Newest reply.'), findsOneWidget);
expect(find.text('Load older'), findsOneWidget);
final older = Completer<JsonMap>();
gateway.history = (_) => older.future;
await tester.tap(find.text('Load older'));
await tester.pump();
expect(gateway.calls.last.fields['chat_query'], {
'session_id': 's',
'limit': 200,
'cursor': 'opaque/next?x=1',
});
older.complete(
chatPage(
[
chatMessage(
'a1',
'assistant',
parts: [
{'type': 'text', 'text': 'Older stored reply.'},
],
),
],
cursor: '',
hasMore: false,
),
);
await tester.pumpAndSettle();
expect(find.text('Older stored reply.'), findsOneWidget);
expect(find.text('Newest reply.'), findsOneWidget);
expect(find.text('Load older'), findsNothing);
});
// Paging prepends messages, so an unkeyed transcript would reuse the element
// at a message's old index: the operator's open reasoning would move to the
// previous answer, or be dropped when `Load older` disappears.
for (final cupertino in [false, true]) {
testWidgets(
'an open reasoning block stays on its answer while has_more remains '
'($cupertino)',
(tester) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
var reads = 0;
gateway.history = (_) async => ++reads == 1
? pagedChatPage(
'a2',
'NEWEST reasoning body that belongs to the newest answer.',
cursor: 'opaque/older',
hasMore: true,
)
: pagedChatPage(
'a1',
'OLDER reasoning body that must not steal the newest disclosure.',
cursor: 'opaque/older-2',
hasMore: true,
);
await tester.pumpWidget(
(cupertino ? cupertinoHost : host)(
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
);
await tester.pumpAndSettle();
await tester.tap(find.text('Reasoning'));
await tester.pumpAndSettle();
expect(
find.text('NEWEST reasoning body that belongs to the newest answer.'),
findsOneWidget,
);
await tester.tap(find.text('Load older'));
await tester.pumpAndSettle();
// Both answers are present; only the one the operator opened is open.
expect(find.text('Reasoning'), findsNWidgets(2));
expect(find.text('Load older'), findsOneWidget);
expect(
find.text('NEWEST reasoning body that belongs to the newest answer.'),
findsOneWidget,
);
expect(
find.text(
'OLDER reasoning body that must not steal the newest disclosure.',
),
findsNothing,
);
},
);
testWidgets(
'an open reasoning block survives the removal of Load older ($cupertino)',
(tester) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
var reads = 0;
gateway.history = (_) async => ++reads == 1
? pagedChatPage(
'a2',
'NEWEST reasoning body that belongs to the newest answer.',
cursor: 'opaque/older',
hasMore: true,
)
: pagedChatPage(
'a1',
'OLDER reasoning body that must not steal the newest disclosure.',
cursor: '',
hasMore: false,
);
await tester.pumpWidget(
(cupertino ? cupertinoHost : host)(
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
);
await tester.pumpAndSettle();
await tester.tap(find.text('Reasoning'));
await tester.pumpAndSettle();
expect(
find.text('NEWEST reasoning body that belongs to the newest answer.'),
findsOneWidget,
);
await tester.tap(find.text('Load older'));
await tester.pumpAndSettle();
expect(find.text('Reasoning'), findsNWidgets(2));
expect(find.text('Load older'), findsNothing);
expect(
find.text('NEWEST reasoning body that belongs to the newest answer.'),
findsOneWidget,
);
expect(
find.text(
'OLDER reasoning body that must not steal the newest disclosure.',
),
findsNothing,
);
},
);
}
// The repository's own paged-history fixture pages consecutive assistant
// messages, so an older page can prepend into the one folded turn. Its first
// message id changes; the row must still be the same element and keep the
// operator's open disclosure.
for (final cupertino in [false, true]) {
for (final keepsControl in [true, false]) {
testWidgets(
'an open reasoning block in a folded assistant turn survives paging '
'(keeps Load older: $keepsControl, $cupertino)',
(tester) async {
final gateway = FakeChatGateway();
addTearDown(gateway.close);
var reads = 0;
gateway.history = (_) async => ++reads == 1
? assistantFoldPage(
const ['msg_6', 'msg_4'],
const [
'NEWEST folded reasoning body.',
'FOURTH folded reasoning body.',
],
cursor: 'opaque/fold',
hasMore: true,
)
: assistantFoldPage(
const ['msg_2', 'msg_0'],
const [
'SECOND folded reasoning body.',
'OLDEST folded reasoning body.',
],
cursor: keepsControl ? 'opaque/fold-2' : '',
hasMore: keepsControl,
);
await tester.pumpWidget(
(cupertino ? cupertinoHost : host)(
ChatThreadView(gateway: gateway, sessionId: 's', onBack: () {}),
),
);
await tester.pumpAndSettle();
// Before paging the turn holds two messages, so two disclosures.
expect(find.text('Reasoning'), findsNWidgets(2));
await tester.tap(find.text('Reasoning').first);
await tester.pumpAndSettle();
expect(find.text('NEWEST folded reasoning body.'), findsOneWidget);
await tester.tap(find.text('Load older'));
await tester.pumpAndSettle();
// All four assistant messages now fold into the same turn. The
// newest block stays open; no older block may open.
expect(find.text('Reasoning'), findsNWidgets(4));
expect(find.text('NEWEST folded reasoning body.'), findsOneWidget);
expect(find.text('FOURTH folded reasoning body.'), findsNothing);
expect(find.text('SECOND folded reasoning body.'), findsNothing);
expect(find.text('OLDEST folded reasoning body.'), findsNothing);
expect(
find.text('Load older'),
keepsControl ? findsOneWidget : findsNothing,
);
},
);
}
}
}
/// The paged-history fixture shape: a page of consecutive assistant messages,
/// each with its own reasoning and text part.
JsonMap assistantFoldPage(
List<String> ids,
List<String> reasoning, {
required String cursor,
required bool hasMore,
}) => chatPage(
[
for (var index = 0; index < ids.length; index++)
chatMessage(
ids[index],
'assistant',
parts: [
{
'type': 'reasoning',
'id': 'r-${ids[index]}',
'text': reasoning[index],
},
{
'type': 'text',
'id': 't-${ids[index]}',
'text': 'Answer stored as ${ids[index]}.',
},
],
),
],
cursor: cursor,
hasMore: hasMore,
);
/// A newest page with one user prompt and one answer carrying [reasoning].
JsonMap pagedChatPage(
String answerId,
String reasoning, {
required String cursor,
required bool hasMore,
}) => chatPage(
[
chatMessage(
'u-$answerId',
'user',
parts: [
{'type': 'text', 'text': 'A question for $answerId.'},
],
),
chatMessage(
answerId,
'assistant',
parts: [
{'type': 'reasoning', 'text': reasoning},
{'type': 'text', 'text': 'The answer stored as $answerId.'},
],
),
],
cursor: cursor,
hasMore: hasMore,
);
@@ -0,0 +1,159 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/api_gateway.dart';
import 'package:pipelines_app/features/graph/domain/stage_definition.dart';
import 'graph_fixtures.dart';
JsonMap _stage() => <String, dynamic>{
'key': 'build',
'prompt': 'Implement the planned change.',
'output': 'A committed change.',
'edges': <String, String?>{
'success': 'audit',
'approved': '#',
'error': '#failure',
},
'fallback_error': true,
'configs': <String, dynamic>{
'provider': 'openai',
'model': 'gpt-5',
'budget_usd': 12.5,
'retries': 2,
'harness': 'codex',
'timeout': '15m',
'skipped_blank': ' ',
'skipped_null': null,
},
'blocks': <String, dynamic>{'tools': 'shell\nread_file'},
'limits': <String, dynamic>{
'max_visits': 3,
'on': <String>['success', 'error'],
},
'memory': <String, dynamic>{'context': 'latest', 'notes': 'keep'},
'notify': <String, dynamic>{
'on': <String>['failure'],
'destination': 'ops@example.test',
'artifacts': <String>['run.log'],
},
'custom_flag': true,
};
void main() {
group('stage fields', () {
test('follow the web pane order, labels and blank-field rules', () {
final fields = stageDefinitionFields(_stage());
expect(fields.map((field) => field.label), <String>[
'Type',
'Prompt',
'Output',
'Outcomes',
'Budget (USD)',
'Harness',
'Model',
'Provider',
'Retries',
'Timeout',
'Tools',
'Max visits',
'Limit on',
'Memory',
'Notify on',
'Notify destination',
'Notify artifacts',
]);
expect(fields.first.value, 'model');
expect(fields[1].block, isTrue);
expect(fields[2].value, 'A committed change.');
expect(
fields[3].value,
'success → audit\n'
'approved → SUCCESS (terminal)\n'
'error → FAILURE (terminal)',
);
expect(fields[4].value, '12.5');
expect(fields[5].value, 'codex');
expect(fields[10].value, 'shell\nread_file');
expect(fields[11].value, '3');
expect(fields[12].value, 'success, error');
expect(fields[13].value, 'context: latest\nnotes: keep');
expect(fields[14].value, 'failure');
expect(fields[15].value, 'ops@example.test');
expect(fields[16].value, 'run.log');
});
test('a blank or absent type reads model; an authored type is kept', () {
expect(effectiveStageType(null), 'model');
expect(effectiveStageType(' '), 'model');
expect(effectiveStageType('shell'), 'shell');
expect(
stageDefinitionFields(<String, dynamic>{'key': 'a'}).single.value,
'model',
);
});
test('config keys outside the known labels are shown verbatim', () {
final fields = stageDefinitionFields(<String, dynamic>{
'key': 'a',
'configs': <String, dynamic>{'temperature': 0},
});
expect(fields.map((field) => field.label), contains('temperature'));
expect(
fields.firstWhere((field) => field.label == 'temperature').value,
'0',
);
});
test('zero visits and missing limits emit no invented rows', () {
final fields = stageDefinitionFields(<String, dynamic>{
'key': 'a',
'limits': <String, dynamic>{'max_visits': 0, 'on': <String>[]},
});
expect(fields.map((field) => field.label), <String>['Type']);
});
test(
'the stage lookup preserves unknown keys and the last declaration',
() {
final graph = <String, dynamic>{
'stages': <dynamic>[
<String, dynamic>{'key': 'build', 'type': 'old'},
_stage(),
],
};
final stage = stageDefinitionFor(graph, 'build');
expect(stage?['type'], isNull);
expect(effectiveStageType(stage?['type']), 'model');
expect(stage?['custom_flag'], isTrue);
expect(stageDefinitionFor(graph, 'ghost'), isNull);
},
);
});
group('terminal fields', () {
test('list incoming definition routes, including the fallback marker', () {
expect(terminalDefinitionFields(linearGraph(), '#failure'), hasLength(1));
final fields = terminalDefinitionFields(linearGraph(), '#failure');
expect(
fields.single.value,
'plan · error* → FAILURE\nship · error → FAILURE',
);
expect(fields.single.block, isTrue);
expect(
terminalDefinitionFields(linearGraph(), '#success').single.value,
'ship · success → SUCCESS',
);
});
test('a terminal with no routes has no fields to invent', () {
expect(
terminalDefinitionFields(<String, dynamic>{}, '#success'),
isEmpty,
);
});
});
}
@@ -0,0 +1,286 @@
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/domain/stage_definition.dart';
import 'package:pipelines_app/features/graph/widgets/stage_definition_view.dart';
JsonMap _graph() => <String, dynamic>{
'stages': <dynamic>[
<String, dynamic>{
'key': 'plan',
'type': 'model',
'prompt': 'Plan the change.',
'edges': <String, String?>{'success': 'build', 'error': '#'},
'fallback_error': true,
'configs': <String, dynamic>{'provider': 'openai', 'model': 'gpt-5'},
'limits': <String, dynamic>{
'max_visits': 2,
'on': <String>['error'],
},
'future_field': <String, dynamic>{'kept': true},
},
<String, dynamic>{
'key': 'build',
'type': 'shell',
'edges': <String, String?>{'success': '#success', 'error': '#failure'},
},
],
};
Widget _material(Widget child) => MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('plan definition')),
body: child,
),
);
Widget _cupertino(Widget child, {bool dark = false}) => CupertinoApp(
theme: CupertinoThemeData(
brightness: dark ? Brightness.dark : Brightness.light,
),
home: CupertinoPageScaffold(child: child),
);
StageDefinitionView _view({String key = 'plan'}) => StageDefinitionView(
graph: _graph(),
stageKey: key,
pipelineId: 41,
pipelineName: 'Demo pipeline',
version: 7,
);
/// Finds visible text, including SelectableText's editable body.
Finder _text(String value) => find.byWidgetPredicate(
(widget) =>
(widget is Text && widget.data == value) ||
(widget is SelectableText && widget.data == value),
);
void main() {
testWidgets('a declared stage shows pinned identity and web field values', (
tester,
) async {
await tester.pumpWidget(_material(_view()));
expect(_text('Demo pipeline · v7'), findsOneWidget);
expect(_text('model'), findsOneWidget);
expect(_text('Plan the change.'), findsOneWidget);
expect(
_text('success → build\nerror → FAILURE (terminal)'),
findsOneWidget,
);
expect(_text('Provider'), findsOneWidget);
expect(_text('openai'), findsOneWidget);
expect(_text('Model'), findsOneWidget);
expect(_text('gpt-5'), findsOneWidget);
expect(_text('Max visits'), findsOneWidget);
expect(_text('2'), findsOneWidget);
expect(_text('Limit on'), findsOneWidget);
expect(_text('error'), findsOneWidget);
});
testWidgets('the raw section keeps unknown fields exact and selectable', (
tester,
) async {
await tester.pumpWidget(_material(_view()));
expect(_text(rawStageDefinitionTitle), findsOneWidget);
final raw = tester
.widgetList<SelectableText>(find.byType(SelectableText))
.map((widget) => widget.data ?? '')
.join('\n');
expect(raw, contains('"future_field": {'));
expect(raw, contains('"kept": true'));
expect(raw, contains('"fallback_error": true'));
expect(tester.takeException(), isNull);
});
testWidgets('unknown stages get an explicit missing state, never defaults', (
tester,
) async {
await tester.pumpWidget(_material(_view(key: 'ghost')));
expect(_text(unknownStageDefinition), findsOneWidget);
expect(_text('model'), findsNothing);
expect(_text(rawStageDefinitionTitle), findsNothing);
expect(find.byType(SelectableText), findsNothing);
});
testWidgets('terminals explain definition targets and incoming routes', (
tester,
) async {
await tester.pumpWidget(_material(_view(key: '#failure')));
expect(_text(terminalDefinitionNote), findsOneWidget);
expect(_text('Incoming routes'), findsOneWidget);
expect(
_text('plan · error* → FAILURE\nbuild · error → FAILURE'),
findsOneWidget,
);
expect(_text(rawStageDefinitionTitle), findsNothing);
expect(_text('successful'), findsNothing);
});
testWidgets('Cupertino uses its theme roles in dark mode', (tester) async {
late Color secondary;
await tester.pumpWidget(
_cupertino(
Builder(
builder: (context) {
secondary = CupertinoColors.secondaryLabel.resolveFrom(context);
return _view();
},
),
dark: true,
),
);
final identity = tester.widget<Text>(_text('Demo pipeline · v7'));
expect(identity.style?.color, secondary);
expect(_text('Plan the change.'), findsOneWidget);
expect(tester.takeException(), isNull);
});
testWidgets('the Material helper opens one bar and Back closes it', (
tester,
) async {
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) => Scaffold(
body: TextButton(
onPressed: () => openStageDefinition(
context,
graph: _graph(),
stageKey: 'plan',
pipelineId: 41,
pipelineName: 'Demo pipeline',
version: 7,
),
child: const Text('Open definition'),
),
),
),
),
);
await tester.tap(find.text('Open definition'));
await tester.pumpAndSettle();
expect(_text('plan definition'), findsOneWidget);
expect(find.byType(AppBar), findsOneWidget);
expect(find.byType(BackButton), findsOneWidget);
final route = ModalRoute.of(
tester.element(find.byType(StageDefinitionView)),
);
expect(route?.settings.name, 'stage-definition/41/7/plan');
await tester.pageBack();
await tester.pumpAndSettle();
expect(_text('Open definition'), findsOneWidget);
expect(find.byType(StageDefinitionView), findsNothing);
});
testWidgets('the Cupertino helper opens one native bar and Back closes it', (
tester,
) async {
await tester.pumpWidget(
CupertinoApp(
home: Builder(
builder: (context) => CupertinoPageScaffold(
child: CupertinoButton(
onPressed: () => openStageDefinition(
context,
graph: _graph(),
stageKey: '#success',
pipelineId: 41,
pipelineName: 'Demo pipeline',
version: 7,
),
child: const Text('Open terminal'),
),
),
),
),
);
await tester.tap(find.text('Open terminal'));
await tester.pumpAndSettle();
expect(_text('Success definition'), findsOneWidget);
expect(_text('#success definition'), findsNothing);
expect(find.byType(CupertinoNavigationBar), findsOneWidget);
expect(find.byType(CupertinoNavigationBarBackButton), findsOneWidget);
expect(_text('Incoming routes'), findsOneWidget);
await tester.tap(find.byType(CupertinoNavigationBarBackButton));
await tester.pumpAndSettle();
expect(_text('Open terminal'), findsOneWidget);
expect(find.byType(StageDefinitionView), findsNothing);
});
testWidgets('the Material helper titles a terminal with its display label', (
tester,
) async {
await tester.pumpWidget(
MaterialApp(
home: Builder(
builder: (context) => Scaffold(
body: TextButton(
onPressed: () => openStageDefinition(
context,
graph: _graph(),
stageKey: '#failure',
pipelineId: 41,
pipelineName: 'Demo pipeline',
version: 7,
),
child: const Text('Open failure'),
),
),
),
),
);
await tester.tap(find.text('Open failure'));
await tester.pumpAndSettle();
expect(_text('Failure definition'), findsOneWidget);
expect(_text('#failure definition'), findsNothing);
expect(tester.takeException(), isNull);
});
testWidgets('selectable blocks force the host strut for one line rhythm', (
tester,
) async {
await tester.pumpWidget(_cupertino(_view()));
final selectable = tester
.widgetList<SelectableText>(find.byType(SelectableText))
.toList();
expect(selectable.length, greaterThanOrEqualTo(2));
for (final widget in selectable) {
final strut = widget.strutStyle;
expect(strut, isNotNull);
// The host's own metrics, forced: a fallback glyph cannot widen a block.
expect(strut!.forceStrutHeight, isTrue);
expect(strut.fontFamily, widget.style?.fontFamily);
expect(strut.fontSize, widget.style?.fontSize);
}
final outcomes = selectable.firstWhere(
(widget) => (widget.data ?? '').contains('success → build'),
);
final raw = selectable.firstWhere(
(widget) => (widget.data ?? '').startsWith('{'),
);
expect(outcomes.strutStyle, raw.strutStyle);
});
test('field labels are the web words', () {
expect(stageConfigLabel('budget_usd'), 'Budget (USD)');
expect(stageConfigLabel('budget_tokens'), 'Budget (tokens)');
expect(stageConfigLabel('custom'), 'custom');
});
}
@@ -40,6 +40,22 @@ void main() {
);
});
test('the full entropy width still forms a bounded request key', () {
// The web build once rejected every retry because `1 << 32` is 0 there;
// the generator now uses a literal 2^32 bound. This pins the largest
// entropy value it may consume.
final key = newRetryRequestKey(
7,
now: DateTime.utc(2026, 1, 1),
random: 0xFFFFFFFF,
);
expect(
key,
'app-retry-7-${DateTime.utc(2026, 1, 1).microsecondsSinceEpoch}-1z141z3',
);
expect(key.length, lessThanOrEqualTo(128));
});
testWidgets(
'material retry asks first, Keep sends nothing, then omits retry_mode',
(tester) async {
@@ -0,0 +1,25 @@
@TestOn('browser')
library;
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/runs/actions/retry_intent.dart';
void main() {
test('a fresh key uses the full entropy bound under dart2js', () {
// `1 << 32` compiles to 0 on the web, so Random.nextInt threw a RangeError
// and no retry request was ever sent. Generating without an injected
// random value exercises the real bound; a VM test cannot catch this
// class of bug, so this file runs only in a browser:
//
// flutter test --platform chrome \
// test/features/runs/actions/retry_intent_web_test.dart
final keys = <String>{};
for (var index = 0; index < 32; index++) {
final key = newRetryRequestKey(7);
expect(key, startsWith('app-retry-7-'));
expect(key.length, lessThanOrEqualTo(128));
keys.add(key);
}
expect(keys, hasLength(32));
});
}
@@ -0,0 +1,161 @@
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/ui/artifact_gallery_action.dart';
import 'package:pipelines_app/features/runs/data/runs_repository.dart';
import 'package:pipelines_app/features/runs/ui/run_detail_view.dart';
import 'package:pipelines_app/features/runs/ui/runs_controller.dart';
import '../../artifacts/domain/artifact_fixtures.dart';
enum _Platform { material, cupertino }
class _FakeGateway implements ApiGateway {
_FakeGateway(this.detail);
final JsonMap detail;
@override
Stream<JsonMap> get frames => const Stream<JsonMap>.empty();
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
if (type != 'get_run') throw UnsupportedError(type);
return Future.value({'run_detail': detail});
}
}
JsonMap _run({required List<JsonMap> steps}) => <String, dynamic>{
'id': 21,
'title': 'Artifacts wiring run',
'name': 'gallery',
'status': 'succeeded',
'steps': steps,
};
Future<void> _pumpDetail(
WidgetTester tester,
_Platform platform,
RunsController controller,
ApiGateway gateway,
) async {
tester.view.physicalSize = const Size(500, 1200);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final view = RunDetailView(
controller: controller,
gateway: gateway,
onBack: () {},
);
await tester.pumpWidget(
platform == _Platform.material
? MaterialApp(home: Scaffold(body: view))
: CupertinoApp(
builder: (context, app) => Theme(
data: ThemeData(platform: TargetPlatform.iOS),
child: app!,
),
home: CupertinoPageScaffold(child: view),
),
);
await tester.pumpAndSettle();
}
Future<RunsController> _loaded(ApiGateway gateway) async {
final controller = RunsController(RunsRepository(gateway));
await controller.select(21);
return controller;
}
void main() {
for (final platform in _Platform.values) {
testWidgets('${platform.name}: the action opens the recorded groups', (
tester,
) async {
final gateway = _FakeGateway(
_run(
steps: [
step(
stage: 'implementer',
sequence: 1,
artifacts: [
artifact(
'build.log',
contentType: 'text/plain',
sizeBytes: 2337,
),
],
),
step(
stage: 'reviewer',
sequence: 2,
artifacts: [
artifact(
'shot.png',
contentType: 'image/png',
sizeBytes: 80544,
),
],
),
],
),
);
final controller = await _loaded(gateway);
addTearDown(controller.dispose);
await _pumpDetail(tester, platform, controller, gateway);
expect(find.byKey(runArtifactsButtonKey), findsOneWidget);
await tester.tap(find.byKey(runArtifactsButtonKey));
await tester.pumpAndSettle();
expect(find.text('Artifacts · 2 recorded'), findsOneWidget);
expect(find.text('build.log'), findsOneWidget);
expect(find.text('shot.png'), findsOneWidget);
expect(find.text('implementer · visit 1'), findsOneWidget);
expect(find.text('reviewer · visit 1'), findsOneWidget);
});
}
testWidgets('the action is offered only when the detail has steps', (
tester,
) async {
final gateway = _FakeGateway(_run(steps: const []));
final controller = await _loaded(gateway);
addTearDown(controller.dispose);
await _pumpDetail(tester, _Platform.material, controller, gateway);
expect(find.byKey(runArtifactsButtonKey), findsNothing);
});
testWidgets('a recorded empty capture keeps its explicit wording', (
tester,
) async {
final gateway = _FakeGateway(
_run(
steps: [step(stage: 'reviewer', visit: 1, artifacts: const [])],
),
);
final controller = await _loaded(gateway);
addTearDown(controller.dispose);
await _pumpDetail(tester, _Platform.material, controller, gateway);
await tester.tap(find.byKey(runArtifactsButtonKey));
await tester.pumpAndSettle();
expect(find.text('No artifacts recorded for this run.'), findsOneWidget);
});
testWidgets('an unavailable capture is never reported as empty', (
tester,
) async {
final gateway = _FakeGateway(
_run(steps: [step(stage: 'reviewer', visit: 1, includeArtifacts: false)]),
);
final controller = await _loaded(gateway);
addTearDown(controller.dispose);
await _pumpDetail(tester, _Platform.material, controller, gateway);
await tester.tap(find.byKey(runArtifactsButtonKey));
await tester.pumpAndSettle();
expect(find.text('Artifacts · capture unavailable'), findsOneWidget);
expect(find.text('No artifacts recorded for this run.'), findsNothing);
});
}
@@ -0,0 +1,114 @@
import 'package:flutter/widgets.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/core/transport/connection_state.dart';
import 'package:pipelines_app/features/runs/actions/retry_wording.dart';
import 'package:pipelines_app/features/runs/actions/title_wording.dart';
import 'run_retry_wiring_support.dart';
void main() {
testWidgets('a reply without an id never opens a guessed run', (
tester,
) async {
final gateway = RetryWiringGateway();
addTearDown(gateway.framesController.close);
final opened = <int>[];
await mountRetryScreen(
tester,
gateway,
cupertino: false,
onRunSelected: opened.add,
);
await confirmRetry(tester);
gateway.retries.last.complete({
'run_detail': {'title': 'Unknown run', 'status': 'running'},
});
await tester.pumpAndSettle();
expect(opened, isEmpty);
expect(find.text(retryFailedTitle), findsOneWidget);
expect(find.text('Unknown run'), findsNothing);
expect(gateway.calls.where((call) => call.type == 'get_run'), hasLength(1));
});
testWidgets('a refused retry stays on the failed run', (tester) async {
final gateway = RetryWiringGateway();
addTearDown(gateway.framesController.close);
final opened = <int>[];
await mountRetryScreen(
tester,
gateway,
cupertino: false,
onRunSelected: opened.add,
);
await confirmRetry(tester);
gateway.refuseRetry(const ProtocolError('the run is still executing'));
await tester.pumpAndSettle();
expect(find.text('the run is still executing'), findsOneWidget);
expect(opened, isEmpty);
expect(find.text(retryFailedTitle), findsOneWidget);
await tester.tap(find.byKey(retryKeepKey));
await tester.pumpAndSettle();
expect(find.byKey(retryActionKey), findsOneWidget);
});
testWidgets('a retry reply that lands after leaving is ignored', (
tester,
) async {
final gateway = RetryWiringGateway();
addTearDown(gateway.framesController.close);
final opened = <int>[];
await mountRetryScreen(
tester,
gateway,
cupertino: false,
onRunSelected: opened.add,
);
await confirmRetry(tester);
expect(gateway.retryCalls, hasLength(1));
await tester.pumpWidget(const SizedBox.shrink());
gateway.acceptRetry(retryCreatedDetail());
await tester.pump();
expect(tester.takeException(), isNull);
expect(opened, isEmpty);
expect(gateway.calls.where((call) => call.type == 'get_run'), hasLength(1));
});
testWidgets('a reply naming the source run opens nothing', (tester) async {
final gateway = RetryWiringGateway();
addTearDown(gateway.framesController.close);
final opened = <int>[];
await mountRetryScreen(
tester,
gateway,
cupertino: false,
onRunSelected: opened.add,
);
await confirmRetry(tester);
gateway.acceptRetry(retryCreatedDetail(id: 7));
await tester.pumpAndSettle();
// The accepted detail still folds, but its id is the source run, so there
// is no new run to open and no second read.
expect(opened, isEmpty);
expect(find.text(retryCreatedTitle), findsOneWidget);
expect(gateway.calls.where((call) => call.type == 'get_run'), hasLength(1));
});
testWidgets('a failed run that is still executing exposes no retry', (
tester,
) async {
final gateway = RetryWiringGateway(executing: true);
addTearDown(gateway.framesController.close);
await mountRetryScreen(tester, gateway, cupertino: false);
expect(find.byKey(runTitleActionKey), findsOneWidget);
expect(find.byKey(retryActionKey), findsNothing);
});
}
@@ -0,0 +1,151 @@
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/runs/actions/cancel_wording.dart';
import 'package:pipelines_app/features/runs/actions/retry_wording.dart';
import 'package:pipelines_app/features/runs/actions/title_wording.dart';
import 'package:pipelines_app/features/runs/ui/run_detail_actions.dart';
import 'run_retry_wiring_support.dart';
void main() {
testWidgets('a hidden retry adds no extra gap for Rename and Cancel', (
tester,
) async {
final gateway = RetryWiringGateway();
addTearDown(gateway.framesController.close);
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Padding(
padding: const EdgeInsets.all(16),
child: RunDetailActions(
run: retryCreatedDetail(id: 7),
gateway: gateway,
onRunChanged: (_) {},
),
),
),
),
);
await tester.pumpAndSettle();
// Retry is not eligible on the running run and must not consume spacing.
expect(find.byKey(retryActionKey), findsNothing);
final rename = tester.getRect(find.byKey(runTitleActionKey));
final cancel = tester.getRect(find.byKey(cancelActionKey));
expect(cancel.left - rename.right, closeTo(8, 0.5));
});
for (final cupertino in [false, true]) {
testWidgets('adjacent actions keep native spacing at 320 px ($cupertino)', (
tester,
) async {
tester.view.physicalSize = const Size(320, 480);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final gateway = RetryWiringGateway();
addTearDown(gateway.framesController.close);
final row = Padding(
padding: const EdgeInsets.all(16),
child: RunDetailActions(
run: retryFailedDetail(),
gateway: gateway,
onRunChanged: (_) {},
),
);
await tester.pumpWidget(
cupertino
? CupertinoApp(
home: CupertinoPageScaffold(child: SafeArea(child: row)),
)
: MaterialApp(home: Scaffold(body: row)),
);
await tester.pumpAndSettle();
expectNativeActionSpacing(tester);
});
}
for (final cupertino in [false, true]) {
testWidgets('320 px at 2x keeps Rename and Retry reachable ($cupertino)', (
tester,
) async {
tester.view.physicalSize = const Size(320, 480);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final gateway = RetryWiringGateway();
addTearDown(gateway.framesController.close);
Widget scale(BuildContext context, Widget? app) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: const TextScaler.linear(2)),
child: app!,
);
// The action row itself, in the detail's 16 px inset, so the narrow
// accessibility state is measured without unrelated header controls.
final row = Padding(
padding: const EdgeInsets.all(16),
child: RunDetailActions(
run: retryFailedDetail(),
gateway: gateway,
onRunChanged: (_) {},
),
);
await tester.pumpWidget(
cupertino
? CupertinoApp(
builder: scale,
home: CupertinoPageScaffold(child: SafeArea(child: row)),
)
: MaterialApp(
builder: scale,
home: Scaffold(body: row),
),
);
await tester.pumpAndSettle();
expect(find.byKey(runTitleActionKey).hitTestable(), findsOneWidget);
expect(find.byKey(retryActionKey).hitTestable(), findsOneWidget);
final rect = tester.getRect(find.byKey(retryActionKey));
expect(rect.left, greaterThanOrEqualTo(0));
expect(rect.right, lessThanOrEqualTo(320));
expectNativeActionSpacing(tester);
await tester.tap(find.byKey(retryActionKey));
await tester.pumpAndSettle();
expect(find.text(retryDialogTitle(7)), findsOneWidget);
await tester.tap(find.byKey(retryKeepKey));
await tester.pumpAndSettle();
expect(gateway.retryCalls, isEmpty);
});
}
}
/// Asserts the action row uses the detail's native 8 dp / 4 dp spacing.
///
/// The row previously had no `spacing`, leaving the outlined Rename border
/// touching the filled Retry button; browser measurement at 320 px reported a
/// 0.008 px gap. A hidden action must not consume spacing either.
void expectNativeActionSpacing(WidgetTester tester) {
final rename = tester.getRect(find.byKey(runTitleActionKey));
final retry = tester.getRect(find.byKey(retryActionKey));
final sameRow = retry.top < rename.bottom && rename.top < retry.bottom;
if (sameRow) {
expect(
retry.left - rename.right,
greaterThanOrEqualTo(8 - 0.01),
reason: 'side-by-side actions need the 8 dp Wrap spacing',
);
} else {
expect(
retry.top - rename.bottom,
greaterThanOrEqualTo(4 - 0.01),
reason: 'wrapped actions need the 4 dp Wrap run spacing',
);
}
}
@@ -0,0 +1,113 @@
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/runs/actions/retry_wording.dart';
import 'package:pipelines_app/features/runs/screen.dart';
const retryFailedTitle = 'Fixture failed run';
const retryCreatedTitle = 'Retry of fixture';
JsonMap retryFailedDetail({bool executing = false}) => {
'id': 7,
'title': retryFailedTitle,
'name': 'fixture',
'status': 'failed',
'executing': executing,
'input': {'prompt': 'the stored prompt'},
'steps': const <JsonMap>[],
};
JsonMap retryCreatedDetail({num id = 8}) => {
'id': id,
'title': retryCreatedTitle,
'name': 'fixture',
'status': 'running',
'executing': true,
'retry_of': 7,
'input': {'prompt': 'the stored prompt'},
'steps': const <JsonMap>[],
};
JsonMap _summary(JsonMap run) => {
'id': run['id'],
'title': run['title'],
'name': run['name'],
'status': run['status'],
'executing': run['executing'] ?? false,
};
/// Serves the same envelopes as the app server and holds each retry reply until
/// the test releases it, so nothing can be applied optimistically.
class RetryWiringGateway implements ApiGateway {
RetryWiringGateway({bool executing = false}) {
details[7] = retryFailedDetail(executing: executing);
}
final framesController = StreamController<JsonMap>.broadcast();
final calls = <({String type, JsonMap fields})>[];
final retries = <Completer<JsonMap>>[];
final details = <num, JsonMap>{};
@override
Stream<JsonMap> get frames => framesController.stream;
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) {
calls.add((type: type, fields: Map<String, dynamic>.from(fields)));
switch (type) {
case 'list_runs':
return Future.value({
'runs': [for (final run in details.values) _summary(run)],
});
case 'get_run':
final id = fields['run_id'] as num;
return Future.value({'run_detail': details[id] ?? retryFailedDetail()});
case 'retry_run':
final reply = Completer<JsonMap>();
retries.add(reply);
return reply.future;
}
return Future.error(UnsupportedError(type));
}
Iterable<({String type, JsonMap fields})> get retryCalls =>
calls.where((call) => call.type == 'retry_run');
void acceptRetry(JsonMap detail) {
details[detail['id'] as num] = detail;
retries.last.complete({'run_detail': detail});
}
void refuseRetry(Object error) => retries.last.completeError(error);
}
Future<void> mountRetryScreen(
WidgetTester tester,
RetryWiringGateway gateway, {
required bool cupertino,
ValueChanged<int>? onRunSelected,
}) async {
final screen = RunsScreen(
gateway: gateway,
initialRunId: 7,
onRunSelected: onRunSelected,
);
await tester.pumpWidget(
cupertino
? CupertinoApp(
home: CupertinoPageScaffold(child: SafeArea(child: screen)),
)
: MaterialApp(home: Scaffold(body: screen)),
);
await tester.pumpAndSettle();
}
Future<void> confirmRetry(WidgetTester tester) async {
await tester.tap(find.byKey(retryActionKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(retryConfirmKey));
await tester.pump();
}
@@ -0,0 +1,102 @@
import 'package:flutter_test/flutter_test.dart';
import 'package:pipelines_app/features/runs/actions/cancel_wording.dart';
import 'package:pipelines_app/features/runs/actions/retry_wording.dart';
import 'package:pipelines_app/features/runs/actions/title_wording.dart';
import 'run_retry_wiring_support.dart';
void main() {
for (final cupertino in [false, true]) {
testWidgets(
'accepted retry reply opens the server-identified run ($cupertino)',
(tester) async {
final gateway = RetryWiringGateway();
addTearDown(gateway.framesController.close);
final opened = <int>[];
await mountRetryScreen(
tester,
gateway,
cupertino: cupertino,
onRunSelected: opened.add,
);
expect(find.text(retryFailedTitle), findsOneWidget);
expect(find.byKey(runTitleActionKey), findsOneWidget);
expect(find.byKey(retryActionKey), findsOneWidget);
expect(find.byKey(cancelActionKey), findsNothing);
expect(gateway.retryCalls, isEmpty);
await tester.tap(find.byKey(retryActionKey));
await tester.pumpAndSettle();
expect(find.text(retryDialogTitle(7)), findsOneWidget);
expect(find.text(retryDialogMessage), findsOneWidget);
expect(gateway.retryCalls, isEmpty);
await tester.tap(find.byKey(retryKeepKey));
await tester.pumpAndSettle();
expect(gateway.retryCalls, isEmpty);
expect(opened, isEmpty);
expect(find.byKey(retryActionKey), findsOneWidget);
await confirmRetry(tester);
expect(gateway.retryCalls, hasLength(1));
final fields = gateway.retryCalls.single.fields;
expect(fields.keys.toSet(), {'run_id', 'request_key'});
expect(fields['run_id'], 7);
expect(fields['request_key'], startsWith('app-retry-7-'));
expect(
(fields['request_key'] as String).length,
lessThanOrEqualTo(128),
);
// The prompt closes only from server truth; no navigation is guessed.
expect(opened, isEmpty);
expect(find.text(retryFailedTitle), findsOneWidget);
gateway.acceptRetry(retryCreatedDetail());
await tester.pumpAndSettle();
expect(opened, [8]);
expect(find.text(retryCreatedTitle), findsOneWidget);
expect(find.text(retryFailedTitle), findsNothing);
expect(find.byKey(retryActionKey), findsNothing);
expect(
gateway.calls.where((call) => call.type == 'get_run').last.fields,
{'run_id': 8},
);
},
);
}
testWidgets('restart sends its explicit mode through the real detail row', (
tester,
) async {
final gateway = RetryWiringGateway();
addTearDown(gateway.framesController.close);
final opened = <int>[];
await mountRetryScreen(
tester,
gateway,
cupertino: false,
onRunSelected: opened.add,
);
await tester.tap(find.byKey(retryActionKey));
await tester.pumpAndSettle();
await tester.tap(find.byKey(retryRestartKey));
await tester.pumpAndSettle();
expect(find.text(restartDialogTitle(7)), findsOneWidget);
await tester.tap(find.byKey(retryConfirmKey));
await tester.pump();
final fields = gateway.retryCalls.single.fields;
expect(fields.keys.toSet(), {'run_id', 'request_key', 'retry_mode'});
expect(fields['run_id'], 7);
expect(fields['retry_mode'], 'restart');
expect(fields['request_key'], startsWith('app-retry-7-'));
gateway.acceptRetry(retryCreatedDetail());
await tester.pumpAndSettle();
expect(opened, [8]);
expect(find.text(retryCreatedTitle), findsOneWidget);
});
}
@@ -0,0 +1,104 @@
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/templates/screen.dart';
import 'package:pipelines_app/features/templates/ui/template_create_wording.dart';
import '../data/template_test_support.dart' show source;
import 'template_gallery_test_support.dart';
Future<void> openRelease(WidgetTester tester) async {
await tester.tap(find.byKey(templateRowKey('release')));
await tester.pumpAndSettle();
await tester.tap(find.byKey(templateCreateActionKey));
await tester.pumpAndSettle();
}
void main() {
testWidgets(
'Cancel sends nothing; Create validates and submits the verbatim source '
'once through the existing prompt',
(tester) async {
final gateway = GalleryGateway((type, fields) async {
if (type == 'list_templates') return templatesReply(galleryTemplates);
return acceptedCreate(type, fields);
});
final created = <JsonMap>[];
await pumpGallery(tester, gateway, onCreated: created.add);
await openRelease(tester);
expect(find.byType(AlertDialog), findsOneWidget);
expect(find.text('Create from Release workflow'), findsOneWidget);
await tester.enterText(find.byKey(templateCreateNameKey), 'Café');
await tester.pump();
await tester.tap(find.byKey(templateCreateCancelKey));
await tester.pumpAndSettle();
expect(find.byType(AlertDialog), findsNothing);
expect(gateway.callsOf('validate'), isEmpty);
expect(gateway.callsOf('submit'), isEmpty);
expect(created, isEmpty);
await tester.tap(find.byKey(templateCreateActionKey));
await tester.pumpAndSettle();
expect(find.byKey(templateCreateNameKey), findsOneWidget);
await tester.enterText(find.byKey(templateCreateNameKey), ' Café ');
await tester.pump();
await tester.tap(find.byKey(templateCreateConfirmKey));
await tester.pumpAndSettle();
expect(gateway.callsOf('validate').single.fields, {'source': source});
expect(gateway.callsOf('submit').single.fields, {
'name': 'Café',
'source': source,
'create_only': true,
});
expect(gateway.callsOf('submit').single.fields.keys, [
'name',
'source',
'create_only',
]);
expect(created, [
{'id': 7, 'name': 'Created release'},
]);
expect(
find.text('Created "Created release". It is in the Pipelines list.'),
findsOneWidget,
);
expect(find.text('Close'), findsOneWidget);
await tester.tap(find.byKey(templateCreateCancelKey));
await tester.pumpAndSettle();
expect(find.byKey(templateDetailKey), findsOneWidget);
expect(created, hasLength(1));
expect(gateway.callsOf('submit'), hasLength(1));
},
);
testWidgets('the callback is optional and Cupertino uses its native prompt', (
tester,
) async {
final gateway = GalleryGateway((type, fields) async {
if (type == 'list_templates') return templatesReply(galleryTemplates);
return acceptedCreate(type, fields);
});
await pumpGallery(tester, gateway, cupertino: true);
await openRelease(tester);
expect(find.byType(CupertinoAlertDialog), findsOneWidget);
expect(find.byType(AlertDialog), findsNothing);
await tester.enterText(find.byKey(templateCreateNameKey), 'Cupertino');
await tester.pump();
await tester.tap(find.byKey(templateCreateConfirmKey));
await tester.pumpAndSettle();
expect(gateway.callsOf('validate'), hasLength(1));
expect(gateway.callsOf('submit'), hasLength(1));
expect(
find.text('Created "Created release". It is in the Pipelines list.'),
findsOneWidget,
);
expect(find.byKey(templateCreateCancelKey), findsOneWidget);
});
}
@@ -0,0 +1,379 @@
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/templates/screen.dart';
import 'package:pipelines_app/features/templates/ui/template_detail.dart';
import '../data/template_test_support.dart' show source;
import 'template_gallery_test_support.dart';
void main() {
testWidgets('loading shows the exact line, then the server catalogue', (
tester,
) async {
final reply = Completer<JsonMap>();
final gateway = GalleryGateway((type, fields) => reply.future);
await pumpGallery(tester, gateway, settle: false);
await tester.pump();
expect(find.byKey(templatesLoadingKey), findsOneWidget);
expect(find.text('Loading templates…'), findsOneWidget);
expect(gateway.calls.single.type, 'list_templates');
expect(gateway.calls.single.fields, isEmpty);
reply.complete(templatesReply(galleryTemplates));
await tester.pumpAndSettle();
expect(find.byKey(templatesGalleryKey), findsOneWidget);
expect(find.text('Release workflow'), findsOneWidget);
expect(find.text('Ship a version'), findsOneWidget);
expect(find.text('(unnamed template)'), findsOneWidget);
expect(find.byKey(templatesLoadingKey), findsNothing);
});
testWidgets('an empty catalogue states it without inventing rows', (
tester,
) async {
final gateway = GalleryGateway(
(type, fields) async => templatesReply(const []),
);
await pumpGallery(tester, gateway);
expect(find.byKey(templatesEmptyKey), findsOneWidget);
expect(
find.text('No templates are available on this server.'),
findsOneWidget,
);
expect(find.byKey(templatesGalleryKey), findsNothing);
});
testWidgets('a refusal offers Retry; a failed refresh keeps the rows', (
tester,
) async {
var mode = 'refuse';
final gateway = GalleryGateway((type, fields) async {
if (type != 'list_templates') throw StateError('unexpected $type');
if (mode == 'refuse') {
throw Exception('catalogue unavailable');
}
return templatesReply(galleryTemplates);
});
await pumpGallery(tester, gateway);
expect(find.byKey(templatesErrorKey), findsOneWidget);
expect(find.text('catalogue unavailable'), findsOneWidget);
expect(find.byKey(templatesGalleryKey), findsNothing);
mode = 'ok';
await tester.tap(find.byKey(templatesRetryKey));
await tester.pumpAndSettle();
expect(find.byKey(templatesGalleryKey), findsOneWidget);
expect(find.text('Release workflow'), findsOneWidget);
mode = 'refuse';
await tester.tap(find.byKey(templatesRefreshKey));
await tester.pumpAndSettle();
expect(find.byKey(templatesGalleryKey), findsOneWidget);
expect(find.text('Release workflow'), findsOneWidget);
expect(find.text('catalogue unavailable'), findsOneWidget);
expect(find.byKey(templatesErrorBannerKey), findsOneWidget);
expect(find.byKey(templatesErrorKey), findsNothing);
mode = 'ok';
await tester.tap(find.byKey(templatesBannerRetryKey));
await tester.pumpAndSettle();
expect(find.text('catalogue unavailable'), findsNothing);
expect(find.byKey(templatesErrorBannerKey), findsNothing);
expect(find.text('Release workflow'), findsOneWidget);
});
testWidgets('refresh re-reads the catalogue and keeps the selection', (
tester,
) async {
var calls = 0;
final gateway = GalleryGateway((type, fields) async {
calls++;
return templatesReply(
calls == 1
? galleryTemplates
: [
...galleryTemplates,
templateJson(key: 'new', name: 'New template'),
],
);
});
await pumpGallery(tester, gateway);
await tester.tap(find.byKey(templateRowKey('release')));
await tester.pumpAndSettle();
expect(find.byKey(templateDetailKey), findsOneWidget);
await tester.tap(find.byKey(templatesRefreshKey));
await tester.pumpAndSettle();
expect(find.byKey(templateDetailKey), findsOneWidget);
expect(find.text('Release workflow'), findsOneWidget);
expect(gateway.callsOf('list_templates'), hasLength(2));
await tester.tap(find.byKey(templatesBackKey));
await tester.pumpAndSettle();
expect(find.text('New template'), findsOneWidget);
});
testWidgets('selecting a template shows metadata and verbatim source only', (
tester,
) async {
final gateway = GalleryGateway(
(type, fields) async => templatesReply(galleryTemplates),
);
await pumpGallery(tester, gateway);
expect(gateway.callsOf('list_templates'), hasLength(1));
await tester.tap(find.byKey(templateRowKey('release')));
await tester.pumpAndSettle();
expect(find.byKey(templateDetailKey), findsOneWidget);
expect(find.text('Release workflow'), findsOneWidget);
expect(find.text('Ship a version'), findsOneWidget);
expect(find.text('Key'), findsOneWidget);
expect(find.text('Includes a schedule'), findsOneWidget);
expect(find.text(templateSourceLabel), findsOneWidget);
expect(selectableSource(source), findsOneWidget);
expect(selectableSource('release'), findsOneWidget);
expect(find.text(templateCreateActionLabel), findsOneWidget);
expect(gateway.callsOf('validate'), isEmpty);
expect(gateway.callsOf('submit'), isEmpty);
await tester.tap(find.byKey(templatesBackKey));
await tester.pumpAndSettle();
expect(find.byKey(templatesGalleryKey), findsOneWidget);
expect(find.byKey(templateDetailKey), findsNothing);
});
testWidgets('native back returns to the gallery', (tester) async {
final gateway = GalleryGateway(
(type, fields) async => templatesReply(galleryTemplates),
);
await pumpGallery(tester, gateway);
await tester.tap(find.byKey(templateRowKey('blank')));
await tester.pumpAndSettle();
expect(find.byKey(templateDetailKey), findsOneWidget);
expect(selectableSource('blank'), findsOneWidget);
await tester.binding.handlePopRoute();
await tester.pumpAndSettle();
expect(find.byKey(templatesGalleryKey), findsOneWidget);
expect(find.byKey(templateDetailKey), findsNothing);
});
testWidgets('embedded use drops the app bar and keeps native detail back', (
tester,
) async {
final gateway = GalleryGateway(
(type, fields) async => templatesReply(galleryTemplates),
);
await pumpGallery(tester, gateway, embedded: true);
expect(find.byType(AppBar), findsNothing);
expect(find.byKey(templatesRefreshKey), findsOneWidget);
await tester.tap(find.byKey(templateRowKey('release')));
await tester.pumpAndSettle();
expect(find.byKey(templateDetailKey), findsOneWidget);
await tester.tap(find.byKey(templateDetailBackKey));
await tester.pumpAndSettle();
expect(find.byKey(templatesGalleryKey), findsOneWidget);
});
testWidgets('Cupertino host uses its own list, back and detail controls', (
tester,
) async {
final gateway = GalleryGateway(
(type, fields) async => templatesReply(galleryTemplates),
);
await pumpGallery(tester, gateway, cupertino: true);
expect(find.byType(CupertinoListTile), findsNWidgets(2));
expect(find.byType(Scaffold), findsNothing);
await tester.tap(find.byKey(templateRowKey('release')));
await tester.pumpAndSettle();
expect(find.byKey(templateDetailKey), findsOneWidget);
expect(selectableSource(source), findsOneWidget);
expect(
tester
.widget<CupertinoButton>(find.byKey(templateCreateActionKey))
.onPressed,
isNotNull,
);
expect(find.byType(BackButton), findsNothing);
await tester.tap(find.byKey(templatesBackKey));
await tester.pumpAndSettle();
expect(find.byType(CupertinoListTile), findsNWidgets(2));
});
testWidgets(
'a failed refresh with a template open is visible and retryable',
(tester) async {
for (final cupertino in [false, true]) {
var mode = 'ok';
final gateway = GalleryGateway((type, fields) async {
if (type != 'list_templates') throw StateError('unexpected $type');
if (mode == 'refuse') throw Exception('refresh unavailable');
return templatesReply(galleryTemplates);
});
await pumpGallery(tester, gateway, cupertino: cupertino);
await tester.tap(find.byKey(templateRowKey('release')));
await tester.pumpAndSettle();
expect(find.byKey(templateDetailKey), findsOneWidget);
mode = 'refuse';
await tester.tap(find.byKey(templatesRefreshKey));
await tester.pumpAndSettle();
expect(gateway.callsOf('list_templates'), hasLength(2));
expect(find.byKey(templateDetailKey), findsOneWidget);
expect(find.byKey(templatesErrorBannerKey), findsOneWidget);
expect(find.text('refresh unavailable'), findsOneWidget);
expect(find.byKey(templatesBannerRetryKey), findsOneWidget);
expect(find.byKey(templatesErrorKey), findsNothing);
expect(find.text(templateSourceLabel), findsOneWidget);
expect(find.text(templateCreateActionLabel), findsOneWidget);
expect(
tester.widget(find.byKey(templatesBannerRetryKey)),
cupertino ? isA<CupertinoButton>() : isA<TextButton>(),
);
expect(tester.takeException(), isNull);
mode = 'ok';
await tester.tap(find.byKey(templatesBannerRetryKey));
await tester.pumpAndSettle();
expect(find.text('refresh unavailable'), findsNothing);
expect(find.byKey(templatesErrorBannerKey), findsNothing);
expect(find.byKey(templateDetailKey), findsOneWidget);
expect(find.text(templateSourceLabel), findsOneWidget);
expect(gateway.callsOf('list_templates'), hasLength(3));
await tester.tap(find.byKey(templatesBackKey));
await tester.pumpAndSettle();
expect(find.byKey(templatesGalleryKey), findsOneWidget);
expect(find.text('Release workflow'), findsOneWidget);
expect(find.text('(unnamed template)'), findsOneWidget);
}
},
);
testWidgets('an embedded failed refresh is visible above the open template', (
tester,
) async {
var mode = 'ok';
final gateway = GalleryGateway((type, fields) async {
if (type != 'list_templates') throw StateError('unexpected $type');
if (mode == 'refuse') throw Exception('refresh unavailable');
return templatesReply(galleryTemplates);
});
await pumpGallery(tester, gateway, embedded: true);
await tester.tap(find.byKey(templateRowKey('release')));
await tester.pumpAndSettle();
expect(find.byKey(templateDetailBackKey), findsOneWidget);
mode = 'refuse';
await tester.tap(find.byKey(templatesRefreshKey));
await tester.pumpAndSettle();
expect(find.byKey(templatesErrorBannerKey), findsOneWidget);
expect(find.text('refresh unavailable'), findsOneWidget);
expect(find.byKey(templateDetailKey), findsOneWidget);
expect(find.byKey(templateDetailBackKey), findsOneWidget);
mode = 'ok';
await tester.tap(find.byKey(templatesBannerRetryKey));
await tester.pumpAndSettle();
expect(find.byKey(templatesErrorBannerKey), findsNothing);
expect(find.byKey(templateDetailKey), findsOneWidget);
expect(gateway.callsOf('list_templates'), hasLength(3));
});
testWidgets('2x text on a short phone has no overflow and stays reachable', (
tester,
) async {
final gateway = GalleryGateway(
(type, fields) async => templatesReply(galleryTemplates),
);
await pumpGallery(
tester,
gateway,
size: const Size(360, 640),
textScale: 2,
);
expect(tester.takeException(), isNull);
await tester.tap(find.byKey(templateRowKey('release')));
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(find.text(templateCreateActionLabel), findsOneWidget);
expect(selectableSource(source), findsOneWidget);
expect(find.byKey(templatesBackKey), findsOneWidget);
});
testWidgets('only the newest reply wins and a disposed screen ignores one', (
tester,
) async {
final first = Completer<JsonMap>();
final stale = Completer<JsonMap>();
var calls = 0;
final gateway = GalleryGateway((type, fields) {
calls++;
if (calls == 1) return first.future;
if (calls == 2) return stale.future;
return Future.value(
templatesReply([templateJson(key: 'fresh', name: 'Fresh')]),
);
});
await pumpGallery(tester, gateway, settle: false);
first.complete(
templatesReply([templateJson(key: 'old', name: 'Old reply')]),
);
await tester.pumpAndSettle();
expect(find.text('Old reply'), findsOneWidget);
await tester.tap(find.byKey(templatesRefreshKey));
await tester.pump();
final replacement = GalleryGateway(
(type, fields) async =>
templatesReply([templateJson(key: 'other', name: 'Other server')]),
);
await pumpGallery(tester, replacement);
expect(find.text('Other server'), findsOneWidget);
stale.complete(
templatesReply([templateJson(key: 'stale', name: 'Stale reply')]),
);
await tester.pumpAndSettle();
expect(find.text('Stale reply'), findsNothing);
expect(find.text('Other server'), findsOneWidget);
final pending = Completer<JsonMap>();
final disposedGateway = GalleryGateway((type, fields) => pending.future);
await pumpGallery(tester, disposedGateway, settle: false);
await tester.pumpWidget(const SizedBox.shrink());
pending.complete(templatesReply(galleryTemplates));
await tester.pump();
expect(tester.takeException(), isNull);
});
}
@@ -0,0 +1,112 @@
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/templates/screen.dart';
import '../data/template_test_support.dart' show source;
typedef GalleryHandler =
FutureOr<JsonMap> Function(String type, JsonMap fields);
/// A recording gateway whose replies come from [handler].
class GalleryGateway implements ApiGateway {
GalleryGateway(this.handler);
final GalleryHandler handler;
final List<({String type, JsonMap fields})> calls = [];
@override
Future<JsonMap> call(String type, [JsonMap fields = const {}]) async {
final copy = Map<String, dynamic>.from(fields);
calls.add((type: type, fields: copy));
return handler(type, copy);
}
@override
Stream<JsonMap> get frames => const Stream.empty();
List<({String type, JsonMap fields})> callsOf(String type) =>
calls.where((call) => call.type == type).toList(growable: false);
}
JsonMap templateJson({
required String key,
String name = '',
String description = '',
String? definition,
bool scheduled = false,
}) => {
'key': key,
'name': name,
'description': description,
'source': definition ?? source,
'scheduled': scheduled,
};
JsonMap templatesReply(List<JsonMap> templates) => {'templates': templates};
final galleryTemplates = [
templateJson(
key: 'release',
name: 'Release workflow',
description: 'Ship a version',
scheduled: true,
),
templateJson(key: 'blank', description: 'No display name'),
];
Future<JsonMap> acceptedCreate(String type, JsonMap fields) async {
if (type == 'validate') return {'graph': {}};
if (type == 'submit') {
return {
'detail': {'id': 7, 'name': 'Created release'},
};
}
throw StateError('Unexpected request $type');
}
/// Pumps the gallery in a real Material or Cupertino host without fixed sizes.
Future<void> pumpGallery(
WidgetTester tester,
GalleryGateway gateway, {
bool cupertino = false,
bool embedded = false,
ValueChanged<JsonMap>? onCreated,
double textScale = 1,
Size size = const Size(800, 1000),
bool settle = true,
}) async {
tester.view.physicalSize = size;
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
Widget media(BuildContext context, Widget? app) => MediaQuery(
data: MediaQuery.of(
context,
).copyWith(textScaler: TextScaler.linear(textScale)),
child: app!,
);
final screen = TemplatesScreen(
gateway: gateway,
embedded: embedded,
onCreated: onCreated,
);
final home = embedded
? (cupertino
? CupertinoPageScaffold(child: screen)
: Scaffold(body: screen))
: screen;
await tester.pumpWidget(
cupertino
? CupertinoApp(builder: media, home: home)
: MaterialApp(builder: media, home: home),
);
if (settle) await tester.pumpAndSettle();
}
Finder selectableSource(String text) => find.byWidgetPredicate(
(widget) => widget is SelectableText && widget.data == text,
);